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