Big patches:
[blender.git] / source / gameengine / BlenderRoutines / KX_BlenderRenderTools.cpp
1 /**
2  * $Id$
3  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version. The Blender
9  * Foundation also sells licenses for use in proprietary software under
10  * the Blender License.  See http://www.blender.org/BL/ for information
11  * about this.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL/BL DUAL LICENSE BLOCK *****
30  */
31
32 #include "KX_BlenderRenderTools.h"
33
34 #ifdef WIN32
35 // OpenGL gl.h needs 'windows.h' on windows platforms 
36 #include <windows.h>
37 #endif //WIN32
38 #ifdef __APPLE__
39 #include <OpenGL/gl.h>
40 #else
41 #include <GL/gl.h>
42 #endif
43
44 #include "RAS_IRenderTools.h"
45 #include "RAS_IRasterizer.h"
46 #include "RAS_LightObject.h"
47 #include "RAS_ICanvas.h"
48 #include "RAS_GLExtensionManager.h"
49
50 // next two includes/dependencies come from the shadow feature
51 // it needs the gameobject and the sumo physics scene for a raycast
52 #include "KX_GameObject.h"
53
54 #include "KX_BlenderPolyMaterial.h"
55 #include "KX_PolygonMaterial.h"
56 #include "Value.h"
57
58 #include "KX_BlenderGL.h" // for text printing
59 #include "STR_String.h"
60 #include "RAS_BucketManager.h" // for polymaterial (needed for textprinting)
61
62 #include "KX_RayCast.h"
63 #include "KX_IPhysicsController.h"
64 #include "PHY_IPhysicsEnvironment.h"
65 #include "KX_Scene.h"
66
67 KX_BlenderRenderTools::KX_BlenderRenderTools()
68 {
69         glGetIntegerv(GL_MAX_LIGHTS, (GLint*) &m_numgllights);
70         if (m_numgllights < 8)
71                 m_numgllights = 8;
72 }
73
74 /**
75 ProcessLighting performs lighting on objects. the layer is a bitfield that contains layer information.
76 There are 20 'official' layers in blender.
77 A light is applied on an object only when they are in the same layer.
78 OpenGL has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in a scene.
79 */
80
81 int     KX_BlenderRenderTools::ProcessLighting(int layer) 
82 {
83         
84         int result = false;
85
86         if (layer < 0)
87         {
88                 DisableOpenGLLights();
89                 result = false;
90         } else
91         {
92                 if (m_clientobject)
93                 {
94
95                         
96                         if (applyLights(layer))
97                         {
98                                 EnableOpenGLLights();
99                                 result = true;
100                         } else
101                         {
102                                 DisableOpenGLLights();
103                                 result = false;
104                         }
105
106                         
107                 }
108         }
109         return result;
110         
111         
112 }
113
114
115 void KX_BlenderRenderTools::BeginFrame(RAS_IRasterizer* rasty)
116 {
117         m_clientobject = NULL;
118         m_lastblenderobject = NULL;
119         m_lastblenderlights = false;
120         m_lastlayer = -1;
121         m_lastlighting = false;
122         m_modified = true;
123         DisableOpenGLLights();
124
125
126 }
127
128 bool KX_BlenderRenderTools::RayHit(KX_ClientObjectInfo* client, MT_Point3& hit_point, MT_Vector3& hit_normal, void * const data)
129 {
130         double* const oglmatrix = (double* const) data;
131         MT_Point3 resultpoint(hit_point);
132         MT_Vector3 resultnormal(hit_normal);
133         MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
134         MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
135         left = (dir.cross(resultnormal)).safe_normalized();
136         // for the up vector, we take the 'resultnormal' returned by the physics
137         
138         double maat[16]={
139                         left[0],        left[1],        left[2], 0,
140                                 dir[0],         dir[1],         dir[2], 0,
141                 resultnormal[0],resultnormal[1],resultnormal[2], 0,
142                                 0,              0,              0, 1};
143         glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
144         //glMultMatrixd(oglmatrix);
145         glMultMatrixd(maat);
146         return true;
147 }
148
149 void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode )
150 {
151         /* FIXME:
152         blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const
153         MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed. 
154         
155         Program received signal SIGABRT, Aborted. 
156         [Switching to Thread 16384 (LWP 1519)] 
157         0x40477571 in kill () from /lib/libc.so.6 
158         (gdb) bt 
159         #7  0x08334368 in MT_Vector3::normalized() const () 
160         #8  0x0833e6ec in KX_BlenderRenderTools::applyTransform(RAS_IRasterizer*, double*, int) () 
161         */
162
163         if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
164                 objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
165         {
166                 // rotate the billboard/halo
167                 //page 360/361 3D Game Engine Design, David Eberly for a discussion
168                 // on screen aligned and axis aligned billboards
169                 // assumed is that the preprocessor transformed all billboard polygons
170                 // so that their normal points into the positive x direction (1.0 , 0.0 , 0.0)
171                 // when new parenting for objects is done, this rotation
172                 // will be moved into the object
173                 
174                 MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
175                 MT_Point3 campos = rasty->GetCameraPosition();
176                 MT_Vector3 dir = (campos - objpos).safe_normalized();
177                 MT_Vector3 up(0,0,1.0);
178
179                 KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject;
180                 // get scaling of halo object
181                 MT_Vector3  size = gameobj->GetSGNode()->GetLocalScale();
182                 
183                 bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
184                 if (screenaligned)
185                 {
186                         up = (up - up.dot(dir) * dir).safe_normalized();
187                 } else
188                 {
189                         dir = (dir - up.dot(dir)*up).safe_normalized();
190                 }
191
192                 MT_Vector3 left = dir.normalized();
193                 dir = (left.cross(up)).normalized();
194
195                 // we have calculated the row vectors, now we keep
196                 // local scaling into account:
197
198                 left *= size[0];
199                 dir  *= size[1];
200                 up   *= size[2];
201                 double maat[16]={
202                         left[0], left[1],left[2], 0,
203                                 dir[0], dir[1],dir[2],0,
204                                 up[0],up[1],up[2],0,
205                                 0,0,0,1};
206                         glTranslated(objpos[0],objpos[1],objpos[2]);
207                         glMultMatrixd(maat);
208                         
209         } else
210         {
211                 if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
212                 {
213                         // shadow must be cast to the ground, physics system needed here!
214                         MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
215                         KX_GameObject *gameobj = (KX_GameObject*) this->m_clientobject;
216                         MT_Vector3 direction = MT_Vector3(0,0,-1);
217
218                         direction.normalize();
219                         direction *= 100000;
220
221                         MT_Point3 topoint = frompoint + direction;
222
223                         KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
224                         PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
225                         KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
226                         
227                         KX_GameObject *parent = gameobj->GetParent();
228                         if (!physics_controller && parent)
229                                 physics_controller = parent->GetPhysicsController();
230                         if (parent)
231                                 parent->Release();
232                                 
233                         MT_Point3 resultpoint;
234                         MT_Vector3 resultnormal;
235                         if (!KX_RayCast::RayTest(physics_controller, physics_environment, frompoint, topoint, resultpoint, resultnormal, KX_RayCast::Callback<KX_BlenderRenderTools>(this, oglmatrix)))
236                         {
237                                 // couldn't find something to cast the shadow on...
238                                 glMultMatrixd(oglmatrix);
239                         }
240                 } else
241                 {
242
243                         // 'normal' object
244                         glMultMatrixd(oglmatrix);
245                 }
246         }
247 }
248
249
250 /**
251 Render Text renders text into a (series of) polygon, using a texture font,
252 Each character consists of one polygon (one quad or two triangles)
253 */
254 void    KX_BlenderRenderTools::RenderText(int mode,RAS_IPolyMaterial* polymat,float v1[3],float v2[3],float v3[3],float v4[3])
255 {
256                 
257         STR_String mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
258         
259         KX_PolygonMaterial* blenderpoly = static_cast<KX_PolygonMaterial*>(polymat);
260         struct TFace* tface = blenderpoly->GetTFace();
261         
262         BL_RenderText( mode,mytext,mytext.Length(),tface,v1,v2,v3,v4);
263         
264 }
265
266
267
268 KX_BlenderRenderTools::~KX_BlenderRenderTools()
269 {
270 };
271         
272         
273 void    KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty)
274 {
275 }
276         
277
278         
279 void KX_BlenderRenderTools::DisableOpenGLLights()
280 {
281         glDisable(GL_LIGHTING);
282         glDisable(GL_COLOR_MATERIAL);
283 }
284
285         
286 void KX_BlenderRenderTools::EnableOpenGLLights()
287 {
288         glEnable(GL_LIGHTING);
289         
290         glEnable(GL_COLOR_MATERIAL);
291         glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE);
292         glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, false);
293         if (bgl::QueryExtension(bgl::_GL_EXT_separate_specular_color) || bgl::QueryVersion(1, 2))
294                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
295
296 }
297         
298
299 /**
300  * Rendering text using 2D bitmap functionality.  
301  */
302 void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
303                                                                                  const char* text,
304                                                                                  int xco,
305                                                                                  int yco,                                                                        
306                                                                                  int width,
307                                                                                  int height)
308 {
309         switch (mode) {
310         case RAS_IRenderTools::RAS_TEXT_PADDED: {
311                 STR_String tmpstr(text);
312                 BL_print_gamedebug_line_padded(tmpstr.Ptr(),xco,yco,width,height);
313                 break;
314         }
315         default: {
316                 STR_String tmpstr(text);
317                 BL_print_gamedebug_line(tmpstr.Ptr(),xco,yco,width,height);
318         }
319         }
320 }
321
322         
323
324 void KX_BlenderRenderTools::PushMatrix()
325 {
326         glPushMatrix();
327 }
328
329 void KX_BlenderRenderTools::PopMatrix()
330 {
331         glPopMatrix();
332 }
333
334
335
336 int     KX_BlenderRenderTools::applyLights(int objectlayer)
337 {
338 // taken from blender source, incompatibility between Blender Object / GameObject       
339         
340         unsigned int count;
341         float vec[4];
342                 
343         vec[3]= 1.0;
344         
345         for(count=0; count<m_numgllights; count++)
346                 glDisable((GLenum)(GL_LIGHT0+count));
347         
348         //std::vector<struct    RAS_LightObject*> m_lights;
349         std::vector<struct      RAS_LightObject*>::iterator lit = m_lights.begin();
350         
351         glPushMatrix();
352         glLoadMatrixf(m_viewmat);
353         for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
354         {
355                 RAS_LightObject* lightdata = (*lit);
356                 if (lightdata->m_layer & objectlayer)
357                 {
358                         vec[0] = (*(lightdata->m_worldmatrix))(0,3);
359                         vec[1] = (*(lightdata->m_worldmatrix))(1,3);
360                         vec[2] = (*(lightdata->m_worldmatrix))(2,3);
361                         vec[3] = 1;
362
363                         if(lightdata->m_type==RAS_LightObject::LIGHT_SUN) {
364                                 
365                                 vec[0] = (*(lightdata->m_worldmatrix))(0,2);
366                                 vec[1] = (*(lightdata->m_worldmatrix))(1,2);
367                                 vec[2] = (*(lightdata->m_worldmatrix))(2,2);
368                                 //vec[0]= base->object->obmat[2][0];
369                                 //vec[1]= base->object->obmat[2][1];
370                                 //vec[2]= base->object->obmat[2][2];
371                                 vec[3]= 0.0;
372                                 glLightfv((GLenum)(GL_LIGHT0+count), GL_POSITION, vec); 
373                         }
374                         else {
375                                 //vec[3]= 1.0;
376                                 glLightfv((GLenum)(GL_LIGHT0+count), GL_POSITION, vec); 
377                                 glLightf((GLenum)(GL_LIGHT0+count), GL_CONSTANT_ATTENUATION, 1.0);
378                                 glLightf((GLenum)(GL_LIGHT0+count), GL_LINEAR_ATTENUATION, lightdata->m_att1/lightdata->m_distance);
379                                 // without this next line it looks backward compatible.
380                                 //attennuation still is acceptable 
381                                 glLightf((GLenum)(GL_LIGHT0+count), GL_QUADRATIC_ATTENUATION, lightdata->m_att2/(lightdata->m_distance*lightdata->m_distance)); 
382                                 
383                                 if(lightdata->m_type==RAS_LightObject::LIGHT_SPOT) {
384                                         vec[0] = -(*(lightdata->m_worldmatrix))(0,2);
385                                         vec[1] = -(*(lightdata->m_worldmatrix))(1,2);
386                                         vec[2] = -(*(lightdata->m_worldmatrix))(2,2);
387                                         //vec[0]= -base->object->obmat[2][0];
388                                         //vec[1]= -base->object->obmat[2][1];
389                                         //vec[2]= -base->object->obmat[2][2];
390                                         glLightfv((GLenum)(GL_LIGHT0+count), GL_SPOT_DIRECTION, vec);
391                                         glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_CUTOFF, lightdata->m_spotsize/2.0);
392                                         glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_EXPONENT, 128.0*lightdata->m_spotblend);
393                                 }
394                                 else glLightf((GLenum)(GL_LIGHT0+count), GL_SPOT_CUTOFF, 180.0);
395                         }
396                         
397                         if (lightdata->m_nodiffuse)
398                         {
399                                 vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
400                         } else {
401                                 vec[0]= lightdata->m_energy*lightdata->m_red;
402                                 vec[1]= lightdata->m_energy*lightdata->m_green;
403                                 vec[2]= lightdata->m_energy*lightdata->m_blue;
404                                 vec[3]= 1.0;
405                         }
406                         glLightfv((GLenum)(GL_LIGHT0+count), GL_DIFFUSE, vec);
407                         if (lightdata->m_nospecular)
408                         {
409                                 vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
410                         } else if (lightdata->m_nodiffuse) {
411                                 vec[0]= lightdata->m_energy*lightdata->m_red;
412                                 vec[1]= lightdata->m_energy*lightdata->m_green;
413                                 vec[2]= lightdata->m_energy*lightdata->m_blue;
414                                 vec[3]= 1.0;
415                         }
416                         glLightfv((GLenum)(GL_LIGHT0+count), GL_SPECULAR, vec);
417                         glEnable((GLenum)(GL_LIGHT0+count));
418
419                         count++;
420                         
421                 }
422         }
423         glPopMatrix();
424
425         return count;
426
427 }
428
429
430
431 RAS_IPolyMaterial* KX_BlenderRenderTools::CreateBlenderPolyMaterial(
432                 const STR_String &texname,
433                 bool ba,const STR_String& matname,int tile,int tilexrep,int tileyrep,int mode,bool transparant,bool zsort, int lightlayer
434                 ,bool bIsTriangle,void* clientobject,void* tface)
435 {
436         assert(!"Deprecated");
437 /*      return new KX_BlenderPolyMaterial(
438
439                 texname,
440                 ba,matname,tile,tilexrep,tileyrep,mode,transparant,zsort, lightlayer
441                 ,bIsTriangle,clientobject,(struct TFace*)tface);*/
442         return NULL;
443 }
444
445 unsigned int KX_BlenderRenderTools::m_numgllights;