Fix for bug #18900: game engine lights in non-glsl mode did move
[blender.git] / source / gameengine / GamePlayer / common / GPC_RenderTools.cpp
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include "GL/glew.h"
31
32 #include "BMF_Api.h"
33
34 #include "RAS_IRenderTools.h"
35 #include "RAS_IRasterizer.h"
36 #include "RAS_LightObject.h"
37 #include "RAS_ICanvas.h"
38 #include "RAS_GLExtensionManager.h"
39
40 #include "KX_GameObject.h"
41 #include "KX_PolygonMaterial.h"
42 #include "KX_BlenderMaterial.h"
43 #include "KX_RayCast.h"
44 #include "KX_IPhysicsController.h"
45 #include "KX_Light.h"
46
47 #include "PHY_IPhysicsEnvironment.h"
48
49 #include "STR_String.h"
50
51 #include "GPU_draw.h"
52
53 #include "BKE_bmfont.h" // for text printing
54 #include "BKE_bmfont_types.h"
55
56 #include "GPC_RenderTools.h"
57
58
59 unsigned int GPC_RenderTools::m_numgllights;
60
61 GPC_RenderTools::GPC_RenderTools()
62 {
63         m_font = BMF_GetFont(BMF_kHelvetica10);
64
65         glGetIntegerv(GL_MAX_LIGHTS, (GLint*) &m_numgllights);
66         if (m_numgllights < 8)
67                 m_numgllights = 8;
68 }
69
70 GPC_RenderTools::~GPC_RenderTools()
71 {
72 }
73
74 void GPC_RenderTools::BeginFrame(RAS_IRasterizer* rasty)
75 {
76         m_clientobject = NULL;
77         m_lastlightlayer = -1;
78         m_lastauxinfo = NULL;
79         m_lastlighting = true; /* force disable in DisableOpenGLLights() */
80         DisableOpenGLLights();
81 }
82
83 void GPC_RenderTools::EndFrame(RAS_IRasterizer* rasty)
84 {
85 }
86
87 /* ProcessLighting performs lighting on objects. the layer is a bitfield that
88  * contains layer information. There are 20 'official' layers in blender. A
89  * light is applied on an object only when they are in the same layer. OpenGL
90  * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in
91  * a scene. */
92
93 void GPC_RenderTools::ProcessLighting(RAS_IRasterizer *rasty, bool uselights, const MT_Transform& viewmat)
94 {
95         bool enable = false;
96         int layer= -1;
97
98         /* find the layer */
99         if(uselights) {
100                 if(m_clientobject)
101                         layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
102         }
103
104         /* avoid state switching */
105         if(m_lastlightlayer == layer && m_lastauxinfo == m_auxilaryClientInfo)
106                 return;
107
108         m_lastlightlayer = layer;
109         m_lastauxinfo = m_auxilaryClientInfo;
110
111         /* enable/disable lights as needed */
112         if(layer >= 0)
113                 enable = applyLights(layer, viewmat);
114
115         if(enable)
116                 EnableOpenGLLights(rasty);
117         else
118                 DisableOpenGLLights();
119 }
120
121 void GPC_RenderTools::EnableOpenGLLights(RAS_IRasterizer *rasty)
122 {
123         if(m_lastlighting == true)
124                 return;
125
126         glEnable(GL_LIGHTING);
127         glEnable(GL_COLOR_MATERIAL);
128
129         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
130         glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
131         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, (rasty->GetCameraOrtho())? GL_FALSE: GL_TRUE);
132         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
133                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
134         
135         m_lastlighting = true;
136 }
137
138 void GPC_RenderTools::DisableOpenGLLights()
139 {
140         if(m_lastlighting == false)
141                 return;
142
143         glDisable(GL_LIGHTING);
144         glDisable(GL_COLOR_MATERIAL);
145
146         m_lastlighting = false;
147 }
148
149
150 void GPC_RenderTools::SetClientObject(RAS_IRasterizer *rasty, void* obj)
151 {
152         if (m_clientobject != obj)
153         {
154                 bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
155                 rasty->SetFrontFace(ccw);
156
157                 m_clientobject = obj;
158         }
159 }
160
161 bool GPC_RenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
162 {
163         double* const oglmatrix = (double* const) data;
164         MT_Point3 resultpoint(result->m_hitPoint);
165         MT_Vector3 resultnormal(result->m_hitNormal);
166         MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
167         MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
168         left = (dir.cross(resultnormal)).safe_normalized();
169         // for the up vector, we take the 'resultnormal' returned by the physics
170         
171         double maat[16]={
172                         left[0],        left[1],        left[2], 0,
173                                 dir[0],         dir[1],         dir[2], 0,
174                 resultnormal[0],resultnormal[1],resultnormal[2], 0,
175                                 0,              0,              0, 1};
176         glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
177         //glMultMatrixd(oglmatrix);
178         glMultMatrixd(maat);
179         return true;
180 }
181
182 void GPC_RenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode )
183 {
184         /* FIXME:
185         blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const
186         MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed. 
187         
188         Program received signal SIGABRT, Aborted. 
189         [Switching to Thread 16384 (LWP 1519)] 
190         0x40477571 in kill () from /lib/libc.so.6 
191         (gdb) bt 
192         #7  0x08334368 in MT_Vector3::normalized() const () 
193         #8  0x0833e6ec in GPC_RenderTools::applyTransform(RAS_IRasterizer*, double*, int) () 
194         */
195
196         if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
197                 objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
198         {
199                 // rotate the billboard/halo
200                 //page 360/361 3D Game Engine Design, David Eberly for a discussion
201                 // on screen aligned and axis aligned billboards
202                 // assumed is that the preprocessor transformed all billboard polygons
203                 // so that their normal points into the positive x direction (1.0 , 0.0 , 0.0)
204                 // when new parenting for objects is done, this rotation
205                 // will be moved into the object
206                 
207                 MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
208                 MT_Point3 campos = rasty->GetCameraPosition();
209                 MT_Vector3 dir = (campos - objpos).safe_normalized();
210                 MT_Vector3 up(0,0,1.0);
211
212                 KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject;
213                 // get scaling of halo object
214                 MT_Vector3  size = gameobj->GetSGNode()->GetLocalScale();
215                 
216                 bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
217                 if (screenaligned)
218                 {
219                         up = (up - up.dot(dir) * dir).safe_normalized();
220                 } else
221                 {
222                         dir = (dir - up.dot(dir)*up).safe_normalized();
223                 }
224
225                 MT_Vector3 left = dir.normalized();
226                 dir = (left.cross(up)).normalized();
227
228                 // we have calculated the row vectors, now we keep
229                 // local scaling into account:
230
231                 left *= size[0];
232                 dir  *= size[1];
233                 up   *= size[2];
234                 double maat[16]={
235                         left[0], left[1],left[2], 0,
236                                 dir[0], dir[1],dir[2],0,
237                                 up[0],up[1],up[2],0,
238                                 0,0,0,1};
239                         glTranslated(objpos[0],objpos[1],objpos[2]);
240                         glMultMatrixd(maat);
241                         
242         } else
243         {
244                 if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
245                 {
246                         // shadow must be cast to the ground, physics system needed here!
247                         MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
248                         KX_GameObject *gameobj = (KX_GameObject*) this->m_clientobject;
249                         MT_Vector3 direction = MT_Vector3(0,0,-1);
250
251                         direction.normalize();
252                         direction *= 100000;
253
254                         MT_Point3 topoint = frompoint + direction;
255
256                         KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
257                         PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
258                         KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
259                         
260                         KX_GameObject *parent = gameobj->GetParent();
261                         if (!physics_controller && parent)
262                                 physics_controller = parent->GetPhysicsController();
263                         if (parent)
264                                 parent->Release();
265                                 
266                         KX_RayCast::Callback<GPC_RenderTools> callback(this, physics_controller, oglmatrix);
267                         if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
268                         {
269                                 // couldn't find something to cast the shadow on...
270                                 glMultMatrixd(oglmatrix);
271                         }
272                 } else
273                 {
274
275                         // 'normal' object
276                         glMultMatrixd(oglmatrix);
277                 }
278         }
279 }
280
281
282 void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
283                                                                                  const char* text,
284                                                                                  int xco,
285                                                                                  int yco,                                                                        
286                                                                                  int width,
287                                                                                  int height)
288 {
289         STR_String tmpstr(text);
290         char* s = tmpstr.Ptr();
291
292         // Save and change OpenGL settings
293         int texture2D;
294         glGetIntegerv(GL_TEXTURE_2D, (GLint*)&texture2D);
295         glDisable(GL_TEXTURE_2D);
296         int fog;
297         glGetIntegerv(GL_FOG, (GLint*)&fog);
298         glDisable(GL_FOG);
299         
300         int light;
301         glGetIntegerv(GL_LIGHTING, (GLint*)&light);
302         glDisable(GL_LIGHTING);
303
304         
305         // Set up viewing settings
306         glMatrixMode(GL_PROJECTION);
307         glPushMatrix();
308         glLoadIdentity();
309         glOrtho(0, width, 0, height, -1, 1);
310         glMatrixMode(GL_MODELVIEW);
311         glPushMatrix();
312         glLoadIdentity();
313
314         // Actual drawing (draw black first if padded)
315         if (mode == RAS_IRenderTools::RAS_TEXT_PADDED)
316         {
317                 glColor3ub(0, 0, 0);
318                 glRasterPos2s(xco+1, height-yco-1);
319                 BMF_DrawString(m_font, s);
320         }
321
322         glColor3ub(255, 255, 255);
323         glRasterPos2s(xco, height-yco);
324         BMF_DrawString(m_font, s);
325
326         // Restore view settings
327         glMatrixMode(GL_PROJECTION);
328         glPopMatrix();
329         glMatrixMode(GL_MODELVIEW);
330         glPopMatrix();
331
332         // Restore OpenGL Settings
333         if (fog)
334                 glEnable(GL_FOG);
335         else
336                 glDisable(GL_FOG);
337         
338         if (texture2D)
339                 glEnable(GL_TEXTURE_2D);
340         else
341                 glDisable(GL_TEXTURE_2D);
342         if (light)
343                 glEnable(GL_LIGHTING);
344         else
345                 glDisable(GL_LIGHTING);
346 }
347
348 /* Render Text renders text into a (series of) polygon, using a texture font,
349  * Each character consists of one polygon (one quad or two triangles) */
350
351 void GPC_RenderTools::RenderText(
352         int mode,
353         RAS_IPolyMaterial* polymat,
354         float v1[3], float v2[3], float v3[3], float v4[3], int glattrib)
355 {
356         STR_String mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
357         
358         const unsigned int flag = polymat->GetFlag();
359         struct MTFace* tface = 0;
360         unsigned int *col = 0;
361
362         if(flag & RAS_BLENDERMAT) {
363                 KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(polymat);
364                 tface = bl_mat->GetMTFace();
365                 col = bl_mat->GetMCol();
366         } else {
367                 KX_PolygonMaterial* blenderpoly = static_cast<KX_PolygonMaterial*>(polymat);
368                 tface = blenderpoly->GetMTFace();
369                 col = blenderpoly->GetMCol();
370         }
371         
372         GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib);
373 }
374
375
376 void GPC_RenderTools::PushMatrix()
377 {
378         glPushMatrix();
379 }
380
381 void GPC_RenderTools::PopMatrix()
382 {
383         glPopMatrix();
384 }
385
386
387 int GPC_RenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
388 {
389         // taken from blender source, incompatibility between Blender Object / GameObject       
390         KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo;
391         float glviewmat[16];
392         unsigned int count;
393         std::vector<struct      RAS_LightObject*>::iterator lit = m_lights.begin();
394
395         for(count=0; count<m_numgllights; count++)
396                 glDisable((GLenum)(GL_LIGHT0+count));
397
398         viewmat.getValue(glviewmat);
399         
400         glPushMatrix();
401         glLoadMatrixf(glviewmat);
402         for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
403         {
404                 RAS_LightObject* lightdata = (*lit);
405                 KX_LightObject *kxlight = (KX_LightObject*)lightdata->m_light;
406
407                 if(kxlight->ApplyLight(kxscene, objectlayer, count))
408                         count++;
409         }
410         glPopMatrix();
411
412         return count;
413 }
414
415 void GPC_RenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
416 {
417         int state = rasterizer->GetMotionBlurState();
418         float motionblurvalue;
419         if(state)
420         {
421                 motionblurvalue = rasterizer->GetMotionBlurValue();
422                 if(state==1)
423                 {
424                         //bugfix:load color buffer into accum buffer for the first time(state=1)
425                         glAccum(GL_LOAD, 1.0);
426                         rasterizer->SetMotionBlurState(2);
427                 }
428                 else if(motionblurvalue>=0.0 && motionblurvalue<=1.0)
429                 {
430                         glAccum(GL_MULT, motionblurvalue);
431                         glAccum(GL_ACCUM, 1-motionblurvalue);
432                         glAccum(GL_RETURN, 1.0);
433                         glFlush();
434                 }
435         }
436 }
437
438 void GPC_RenderTools::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
439 {
440         m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
441 }
442
443 void GPC_RenderTools::Render2DFilters(RAS_ICanvas* canvas)
444 {
445         m_filtermanager.RenderFilters(canvas);
446 }
447