* First commit merging 2.4-based sim_physics in to volume25 branch.
[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 "GL/glew.h"
30
31 #include "RAS_IRenderTools.h"
32 #include "RAS_IRasterizer.h"
33 #include "RAS_LightObject.h"
34 #include "RAS_ICanvas.h"
35 #include "RAS_GLExtensionManager.h"
36
37 #include "KX_GameObject.h"
38 #include "KX_PolygonMaterial.h"
39 #include "KX_BlenderMaterial.h"
40 #include "KX_RayCast.h"
41 #include "KX_IPhysicsController.h"
42 #include "KX_Light.h"
43
44 #include "PHY_IPhysicsEnvironment.h"
45
46 #include "STR_String.h"
47
48 #include "GPU_draw.h"
49
50 #include "KX_BlenderGL.h" // for text printing
51 #include "KX_BlenderRenderTools.h"
52
53 unsigned int KX_BlenderRenderTools::m_numgllights;
54
55 KX_BlenderRenderTools::KX_BlenderRenderTools()
56 {
57         glGetIntegerv(GL_MAX_LIGHTS, (GLint*) &m_numgllights);
58         if (m_numgllights < 8)
59                 m_numgllights = 8;
60 }
61
62 KX_BlenderRenderTools::~KX_BlenderRenderTools()
63 {
64 }
65
66 void KX_BlenderRenderTools::BeginFrame(RAS_IRasterizer* rasty)
67 {
68         m_clientobject = NULL;
69         m_lastlightlayer = -1;
70         m_lastauxinfo = NULL;
71         m_lastlighting = true; /* force disable in DisableOpenGLLights() */
72         DisableOpenGLLights();
73 }
74
75 void KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty)
76 {
77 }
78
79 /* ProcessLighting performs lighting on objects. the layer is a bitfield that
80  * contains layer information. There are 20 'official' layers in blender. A
81  * light is applied on an object only when they are in the same layer. OpenGL
82  * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in
83  * a scene. */
84
85 void KX_BlenderRenderTools::ProcessLighting(RAS_IRasterizer *rasty, bool uselights, const MT_Transform& viewmat)
86 {
87         bool enable = false;
88         int layer= -1;
89
90         /* find the layer */
91         if(uselights) {
92                 if(m_clientobject)
93                         layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
94         }
95
96         /* avoid state switching */
97         if(m_lastlightlayer == layer && m_lastauxinfo == m_auxilaryClientInfo)
98                 return;
99
100         m_lastlightlayer = layer;
101         m_lastauxinfo = m_auxilaryClientInfo;
102
103         /* enable/disable lights as needed */
104         if(layer >= 0)
105                 enable = applyLights(layer, viewmat);
106
107         if(enable)
108                 EnableOpenGLLights(rasty);
109         else
110                 DisableOpenGLLights();
111 }
112
113 void KX_BlenderRenderTools::EnableOpenGLLights(RAS_IRasterizer *rasty)
114 {
115         if(m_lastlighting == true)
116                 return;
117
118         glEnable(GL_LIGHTING);
119         glEnable(GL_COLOR_MATERIAL);
120
121         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
122         glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
123         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, (rasty->GetCameraOrtho())? GL_FALSE: GL_TRUE);
124         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
125                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
126         
127         m_lastlighting = true;
128 }
129
130 void KX_BlenderRenderTools::DisableOpenGLLights()
131 {
132         if(m_lastlighting == false)
133                 return;
134
135         glDisable(GL_LIGHTING);
136         glDisable(GL_COLOR_MATERIAL);
137
138         m_lastlighting = false;
139 }
140
141
142 void KX_BlenderRenderTools::SetClientObject(RAS_IRasterizer *rasty, void* obj)
143 {
144         if (m_clientobject != obj)
145         {
146                 bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
147                 rasty->SetFrontFace(ccw);
148
149                 m_clientobject = obj;
150         }
151 }
152
153 bool KX_BlenderRenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data)
154 {
155         double* const oglmatrix = (double* const) data;
156         MT_Point3 resultpoint(result->m_hitPoint);
157         MT_Vector3 resultnormal(result->m_hitNormal);
158         MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
159         MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
160         left = (dir.cross(resultnormal)).safe_normalized();
161         // for the up vector, we take the 'resultnormal' returned by the physics
162         
163         double maat[16]={
164                         left[0],        left[1],        left[2], 0,
165                                 dir[0],         dir[1],         dir[2], 0,
166                 resultnormal[0],resultnormal[1],resultnormal[2], 0,
167                                 0,              0,              0, 1};
168         glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]);
169         //glMultMatrixd(oglmatrix);
170         glMultMatrixd(maat);
171         return true;
172 }
173
174 void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode )
175 {
176         /* FIXME:
177         blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const
178         MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed. 
179         
180         Program received signal SIGABRT, Aborted. 
181         [Switching to Thread 16384 (LWP 1519)] 
182         0x40477571 in kill () from /lib/libc.so.6 
183         (gdb) bt 
184         #7  0x08334368 in MT_Vector3::normalized() const () 
185         #8  0x0833e6ec in KX_BlenderRenderTools::applyTransform(RAS_IRasterizer*, double*, int) () 
186         */
187
188         if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
189                 objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
190         {
191                 // rotate the billboard/halo
192                 //page 360/361 3D Game Engine Design, David Eberly for a discussion
193                 // on screen aligned and axis aligned billboards
194                 // assumed is that the preprocessor transformed all billboard polygons
195                 // so that their normal points into the positive x direction (1.0 , 0.0 , 0.0)
196                 // when new parenting for objects is done, this rotation
197                 // will be moved into the object
198                 
199                 MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
200                 MT_Point3 campos = rasty->GetCameraPosition();
201                 MT_Vector3 dir = (campos - objpos).safe_normalized();
202                 MT_Vector3 up(0,0,1.0);
203
204                 KX_GameObject* gameobj = (KX_GameObject*)m_clientobject;
205                 // get scaling of halo object
206                 MT_Vector3  size = gameobj->GetSGNode()->GetLocalScale();
207                 
208                 bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
209                 if (screenaligned)
210                 {
211                         up = (up - up.dot(dir) * dir).safe_normalized();
212                 } else
213                 {
214                         dir = (dir - up.dot(dir)*up).safe_normalized();
215                 }
216
217                 MT_Vector3 left = dir.normalized();
218                 dir = (left.cross(up)).normalized();
219
220                 // we have calculated the row vectors, now we keep
221                 // local scaling into account:
222
223                 left *= size[0];
224                 dir  *= size[1];
225                 up   *= size[2];
226                 double maat[16]={
227                         left[0], left[1],left[2], 0,
228                                 dir[0], dir[1],dir[2],0,
229                                 up[0],up[1],up[2],0,
230                                 0,0,0,1};
231                         glTranslated(objpos[0],objpos[1],objpos[2]);
232                         glMultMatrixd(maat);
233                         
234         } else
235         {
236                 if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
237                 {
238                         // shadow must be cast to the ground, physics system needed here!
239                         MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
240                         KX_GameObject *gameobj = (KX_GameObject*)m_clientobject;
241                         MT_Vector3 direction = MT_Vector3(0,0,-1);
242
243                         direction.normalize();
244                         direction *= 100000;
245
246                         MT_Point3 topoint = frompoint + direction;
247
248                         KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
249                         PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
250                         KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
251                         
252                         KX_GameObject *parent = gameobj->GetParent();
253                         if (!physics_controller && parent)
254                                 physics_controller = parent->GetPhysicsController();
255                         if (parent)
256                                 parent->Release();
257                                 
258                         KX_RayCast::Callback<KX_BlenderRenderTools> callback(this, physics_controller, oglmatrix);
259                         if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
260                         {
261                                 // couldn't find something to cast the shadow on...
262                                 glMultMatrixd(oglmatrix);
263                         }
264                         else
265                         { // we found the "ground", but the cast matrix doesn't take
266                           // scaling in consideration, so we must apply the object scale
267                                 MT_Vector3  size = gameobj->GetSGNode()->GetLocalScale();
268                                 glScalef(size[0], size[1], size[2]);
269                         }
270                 } else
271                 {
272
273                         // 'normal' object
274                         glMultMatrixd(oglmatrix);
275                 }
276         }
277 }
278
279
280 void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode,
281                                                                                  const char* text,
282                                                                                  int xco,
283                                                                                  int yco,                                                                        
284                                                                                  int width,
285                                                                                  int height)
286 {
287         STR_String tmpstr(text);
288
289         if(mode == RAS_IRenderTools::RAS_TEXT_PADDED)
290                 BL_print_gamedebug_line_padded(tmpstr.Ptr(), xco, yco, width, height);
291         else
292                 BL_print_gamedebug_line(tmpstr.Ptr(), xco, yco, width, height);
293 }
294
295 /* Render Text renders text into a (series of) polygon, using a texture font,
296  * Each character consists of one polygon (one quad or two triangles) */
297
298 void KX_BlenderRenderTools::RenderText(
299         int mode,
300         RAS_IPolyMaterial* polymat,
301         float v1[3], float v2[3], float v3[3], float v4[3], int glattrib)
302 {
303         const STR_String& mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
304         
305         const unsigned int flag = polymat->GetFlag();
306         struct MTFace* tface = 0;
307         unsigned int *col = 0;
308
309         if(flag & RAS_BLENDERMAT) {
310                 KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(polymat);
311                 tface = bl_mat->GetMTFace();
312                 col = bl_mat->GetMCol();
313         } else {
314                 KX_PolygonMaterial* blenderpoly = static_cast<KX_PolygonMaterial*>(polymat);
315                 tface = blenderpoly->GetMTFace();
316                 col = blenderpoly->GetMCol();
317         }
318         
319         GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib);
320 }
321
322
323 void KX_BlenderRenderTools::PushMatrix()
324 {
325         glPushMatrix();
326 }
327
328 void KX_BlenderRenderTools::PopMatrix()
329 {
330         glPopMatrix();
331 }
332
333
334 int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& viewmat)
335 {
336         // taken from blender source, incompatibility between Blender Object / GameObject       
337         KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo;
338         float glviewmat[16];
339         unsigned int count;
340         std::vector<struct      RAS_LightObject*>::iterator lit = m_lights.begin();
341
342         for(count=0; count<m_numgllights; count++)
343                 glDisable((GLenum)(GL_LIGHT0+count));
344
345         viewmat.getValue(glviewmat);
346         
347         glPushMatrix();
348         glLoadMatrixf(glviewmat);
349         for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
350         {
351                 RAS_LightObject* lightdata = (*lit);
352                 KX_LightObject *kxlight = (KX_LightObject*)lightdata->m_light;
353
354                 if(kxlight->ApplyLight(kxscene, objectlayer, count))
355                         count++;
356         }
357         glPopMatrix();
358
359         return count;
360 }
361
362 void KX_BlenderRenderTools::MotionBlur(RAS_IRasterizer* rasterizer)
363 {
364         int state = rasterizer->GetMotionBlurState();
365         float motionblurvalue;
366         if(state)
367         {
368                 motionblurvalue = rasterizer->GetMotionBlurValue();
369                 if(state==1)
370                 {
371                         //bugfix:load color buffer into accum buffer for the first time(state=1)
372                         glAccum(GL_LOAD, 1.0);
373                         rasterizer->SetMotionBlurState(2);
374                 }
375                 else if(motionblurvalue>=0.0 && motionblurvalue<=1.0)
376                 {
377                         glAccum(GL_MULT, motionblurvalue);
378                         glAccum(GL_ACCUM, 1-motionblurvalue);
379                         glAccum(GL_RETURN, 1.0);
380                         glFlush();
381                 }
382         }
383 }
384
385 void KX_BlenderRenderTools::Update2DFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFilterManager::RAS_2DFILTER_MODE filtermode, int pass, STR_String& text)
386 {
387         m_filtermanager.EnableFilter(propNames, gameObj, filtermode, pass, text);
388 }
389
390 void KX_BlenderRenderTools::Render2DFilters(RAS_ICanvas* canvas)
391 {
392         m_filtermanager.RenderFilters(canvas);
393 }