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