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