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