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