fa24395a74e78c6a00372d3151063a56fd4318b3
[blender.git] / source / gameengine / Rasterizer / RAS_OpenGLRasterizer / RAS_OpenGLRasterizer.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/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
29  *  \ingroup bgerastogl
30  */
31
32
33 #include <math.h>
34 #include <stdlib.h>
35
36 #include "RAS_OpenGLRasterizer.h"
37
38 #include "GPU_glew.h"
39
40 #include "RAS_ICanvas.h"
41 #include "RAS_Rect.h"
42 #include "RAS_TexVert.h"
43 #include "RAS_MeshObject.h"
44 #include "RAS_Polygon.h"
45 #include "RAS_ILightObject.h"
46 #include "MT_CmMatrix4x4.h"
47
48 #include "RAS_OpenGLLight.h"
49 #include "RAS_OpenGLOffScreen.h"
50 #include "RAS_OpenGLSync.h"
51
52 #include "RAS_StorageVA.h"
53 #include "RAS_StorageVBO.h"
54
55 #include "GPU_draw.h"
56 #include "GPU_extensions.h"
57 #include "GPU_material.h"
58 #include "GPU_shader.h"
59
60 extern "C"{
61         #include "BLF_api.h"
62         #include "BKE_DerivedMesh.h"
63 }
64
65
66 // XXX Clean these up <<<
67 #include "EXP_Value.h"
68 #include "KX_Scene.h"
69 #include "KX_RayCast.h"
70 #include "KX_GameObject.h"
71 // >>>
72
73 #ifndef M_PI
74 #define M_PI            3.14159265358979323846
75 #endif
76
77 /**
78  *  32x32 bit masks for vinterlace stereo mode
79  */
80 static GLuint left_eye_vinterlace_mask[32];
81 static GLuint right_eye_vinterlace_mask[32];
82
83 /**
84  *  32x32 bit masks for hinterlace stereo mode.
85  *  Left eye = &hinterlace_mask[0]
86  *  Right eye = &hinterlace_mask[1]
87  */
88 static GLuint hinterlace_mask[33];
89
90 RAS_OpenGLRasterizer::RAS_OpenGLRasterizer(RAS_ICanvas* canvas, RAS_STORAGE_TYPE storage)
91         :RAS_IRasterizer(canvas),
92         m_2DCanvas(canvas),
93         m_fogenabled(false),
94         m_time(0.0f),
95         m_campos(0.0f, 0.0f, 0.0f),
96         m_camortho(false),
97         m_camnegscale(false),
98         m_stereomode(RAS_STEREO_NOSTEREO),
99         m_curreye(RAS_STEREO_LEFTEYE),
100         m_eyeseparation(0.0f),
101         m_focallength(0.0f),
102         m_setfocallength(false),
103         m_noOfScanlines(32),
104         m_motionblur(0),
105         m_motionblurvalue(-1.0f),
106         m_usingoverrideshader(false),
107         m_clientobject(NULL),
108         m_auxilaryClientInfo(NULL),
109         m_drawingmode(KX_TEXTURED),
110         m_texco_num(0),
111         m_attrib_num(0),
112         //m_last_alphablend(GPU_BLEND_SOLID),
113         m_last_frontface(true),
114         m_materialCachingInfo(0),
115         m_storage_type(storage)
116 {
117         m_viewmatrix.setIdentity();
118         m_viewinvmatrix.setIdentity();
119
120         for (int i = 0; i < 32; i++)
121         {
122                 left_eye_vinterlace_mask[i] = 0x55555555;
123                 right_eye_vinterlace_mask[i] = 0xAAAAAAAA;
124                 hinterlace_mask[i] = (i&1)*0xFFFFFFFF;
125         }
126         hinterlace_mask[32] = 0;
127
128         m_prevafvalue = GPU_get_anisotropic();
129
130         if (m_storage_type == RAS_VBO /*|| m_storage_type == RAS_AUTO_STORAGE && GLEW_ARB_vertex_buffer_object*/) {
131                 m_storage = new RAS_StorageVBO(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer);
132         }
133         else if ((m_storage_type == RAS_VA) || (m_storage_type == RAS_AUTO_STORAGE)) {
134                 m_storage = new RAS_StorageVA(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer);
135         }
136         else {
137                 printf("Unknown rasterizer storage type, falling back to vertex arrays\n");
138                 m_storage = new RAS_StorageVA(&m_texco_num, m_texco, &m_attrib_num, m_attrib, m_attrib_layer);
139         }
140
141         glGetIntegerv(GL_MAX_LIGHTS, (GLint *) &m_numgllights);
142         if (m_numgllights < 8)
143                 m_numgllights = 8;
144 }
145
146
147
148 RAS_OpenGLRasterizer::~RAS_OpenGLRasterizer()
149 {
150         // Restore the previous AF value
151         GPU_set_anisotropic(m_prevafvalue);
152
153         if (m_storage)
154                 delete m_storage;
155 }
156
157 bool RAS_OpenGLRasterizer::Init()
158 {
159         bool storage_init;
160         GPU_state_init();
161
162
163         m_ambr = 0.0f;
164         m_ambg = 0.0f;
165         m_ambb = 0.0f;
166
167         glDisable(GL_BLEND);
168         glDisable(GL_ALPHA_TEST);
169         //m_last_alphablend = GPU_BLEND_SOLID;
170         GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
171
172         glFrontFace(GL_CCW);
173         m_last_frontface = true;
174
175         m_redback = 0.4375f;
176         m_greenback = 0.4375f;
177         m_blueback = 0.4375f;
178         m_alphaback = 0.0f;
179
180         glClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
181         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
182         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
183
184
185         glShadeModel(GL_SMOOTH);
186
187         storage_init = m_storage->Init();
188
189         return true && storage_init;
190 }
191
192
193 void RAS_OpenGLRasterizer::SetAmbientColor(float color[3])
194 {
195         m_ambr = color[0];
196         m_ambg = color[1];
197         m_ambb = color[2];
198 }
199
200 void RAS_OpenGLRasterizer::SetAmbient(float factor)
201 {
202         float ambient[] = {m_ambr * factor, m_ambg * factor, m_ambb * factor, 1.0f};
203         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
204 }
205
206 void RAS_OpenGLRasterizer::SetBackColor(float color[3])
207 {
208         m_redback = color[0];
209         m_greenback = color[1];
210         m_blueback = color[2];
211         m_alphaback = 0.0f;
212 }
213
214 void RAS_OpenGLRasterizer::SetFog(short type, float start, float dist, float intensity, float color[3])
215 {
216         float params[4] = {color[0], color[1], color[2], 1.0f};
217         glFogi(GL_FOG_MODE, GL_LINEAR);
218         glFogf(GL_FOG_DENSITY, intensity / 10.0f);
219         glFogf(GL_FOG_START, start);
220         glFogf(GL_FOG_END, start + dist);
221         glFogfv(GL_FOG_COLOR, params);
222 }
223
224 void RAS_OpenGLRasterizer::EnableFog(bool enable)
225 {
226         m_fogenabled = enable;
227 }
228
229 void RAS_OpenGLRasterizer::DisplayFog()
230 {
231         if ((m_drawingmode >= KX_SOLID) && m_fogenabled) {
232                 glEnable(GL_FOG);
233         }
234         else {
235                 glDisable(GL_FOG);
236         }
237 }
238
239 bool RAS_OpenGLRasterizer::SetMaterial(const RAS_IPolyMaterial& mat)
240 {
241         return mat.Activate(this, m_materialCachingInfo);
242 }
243
244
245
246 void RAS_OpenGLRasterizer::Exit()
247 {
248         m_storage->Exit();
249
250         glEnable(GL_CULL_FACE);
251         glEnable(GL_DEPTH_TEST);
252         glClearDepth(1.0f);
253         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
254         glClearColor(m_redback, m_greenback, m_blueback, m_alphaback);
255         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
256         glDepthMask (GL_TRUE);
257         glDepthFunc(GL_LEQUAL);
258         glBlendFunc(GL_ONE, GL_ZERO);
259
260         glDisable(GL_POLYGON_STIPPLE);
261
262         glDisable(GL_LIGHTING);
263         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
264                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
265
266         EndFrame();
267 }
268
269 bool RAS_OpenGLRasterizer::BeginFrame(double time)
270 {
271         m_time = time;
272
273         // Blender camera routine destroys the settings
274         if (m_drawingmode < KX_SOLID)
275         {
276                 glDisable(GL_CULL_FACE);
277                 glDisable(GL_DEPTH_TEST);
278         }
279         else
280         {
281                 glEnable(GL_DEPTH_TEST);
282                 glEnable(GL_CULL_FACE);
283         }
284
285         glDisable(GL_BLEND);
286         glDisable(GL_ALPHA_TEST);
287         //m_last_alphablend = GPU_BLEND_SOLID;
288         GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
289
290         glFrontFace(GL_CCW);
291         m_last_frontface = true;
292
293         glShadeModel(GL_SMOOTH);
294
295         glEnable(GL_MULTISAMPLE_ARB);
296
297         m_2DCanvas->BeginFrame();
298
299         // Render Tools
300         m_clientobject = NULL;
301         m_lastlightlayer = -1;
302         m_lastauxinfo = NULL;
303         m_lastlighting = true; /* force disable in DisableOpenGLLights() */
304         DisableOpenGLLights();
305
306         return true;
307 }
308
309
310
311 void RAS_OpenGLRasterizer::SetDrawingMode(int drawingmode)
312 {
313         m_drawingmode = drawingmode;
314
315         if (m_drawingmode == KX_WIREFRAME)
316                 glDisable(GL_CULL_FACE);
317
318         m_storage->SetDrawingMode(drawingmode);
319 }
320
321 int RAS_OpenGLRasterizer::GetDrawingMode()
322 {
323         return m_drawingmode;
324 }
325
326
327 void RAS_OpenGLRasterizer::SetDepthMask(DepthMask depthmask)
328 {
329         glDepthMask(depthmask == KX_DEPTHMASK_DISABLED ? GL_FALSE : GL_TRUE);
330 }
331
332
333 void RAS_OpenGLRasterizer::ClearColorBuffer()
334 {
335         m_2DCanvas->ClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
336         m_2DCanvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER);
337 }
338
339
340 void RAS_OpenGLRasterizer::ClearDepthBuffer()
341 {
342         m_2DCanvas->ClearBuffer(RAS_ICanvas::DEPTH_BUFFER);
343 }
344
345
346 void RAS_OpenGLRasterizer::ClearCachingInfo(void)
347 {
348         m_materialCachingInfo = 0;
349 }
350
351 void RAS_OpenGLRasterizer::FlushDebugShapes(SCA_IScene *scene)
352 {
353         std::vector<OglDebugShape> &debugShapes = m_debugShapes[scene];
354         if (debugShapes.empty())
355                 return;
356
357         // DrawDebugLines
358         GLboolean light, tex;
359
360         light= glIsEnabled(GL_LIGHTING);
361         tex= glIsEnabled(GL_TEXTURE_2D);
362
363         if (light) glDisable(GL_LIGHTING);
364         if (tex) glDisable(GL_TEXTURE_2D);
365
366         // draw lines
367         glBegin(GL_LINES);
368         for (unsigned int i = 0; i < debugShapes.size(); i++) {
369                 if (debugShapes[i].m_type != OglDebugShape::LINE)
370                         continue;
371                 glColor4f(debugShapes[i].m_color[0], debugShapes[i].m_color[1], debugShapes[i].m_color[2], 1.0f);
372                 const MT_Scalar *fromPtr = &debugShapes[i].m_pos.x();
373                 const MT_Scalar *toPtr= &debugShapes[i].m_param.x();
374                 glVertex3fv(fromPtr);
375                 glVertex3fv(toPtr);
376         }
377         glEnd();
378
379         // draw circles
380         for (unsigned int i = 0; i < debugShapes.size(); i++) {
381                 if (debugShapes[i].m_type != OglDebugShape::CIRCLE)
382                         continue;
383                 glBegin(GL_LINE_LOOP);
384                 glColor4f(debugShapes[i].m_color[0], debugShapes[i].m_color[1], debugShapes[i].m_color[2], 1.0f);
385
386                 static const MT_Vector3 worldUp(0.0f, 0.0f, 1.0f);
387                 MT_Vector3 norm = debugShapes[i].m_param;
388                 MT_Matrix3x3 tr;
389                 if (norm.fuzzyZero() || norm == worldUp)
390                 {
391                         tr.setIdentity();
392                 }
393                 else
394                 {
395                         MT_Vector3 xaxis, yaxis;
396                         xaxis = MT_cross(norm, worldUp);
397                         yaxis = MT_cross(xaxis, norm);
398                         tr.setValue(xaxis.x(), xaxis.y(), xaxis.z(),
399                                 yaxis.x(), yaxis.y(), yaxis.z(),
400                                 norm.x(), norm.y(), norm.z());
401                 }
402                 MT_Scalar rad = debugShapes[i].m_param2.x();
403                 int n = (int)debugShapes[i].m_param2.y();
404                 for (int j = 0; j<n; j++)
405                 {
406                         MT_Scalar theta = j*(float)M_PI*2/n;
407                         MT_Vector3 pos(cosf(theta) * rad, sinf(theta) * rad, 0.0f);
408                         pos = pos*tr;
409                         pos += debugShapes[i].m_pos;
410                         const MT_Scalar* posPtr = &pos.x();
411                         glVertex3fv(posPtr);
412                 }
413                 glEnd();
414         }
415
416         if (light) glEnable(GL_LIGHTING);
417         if (tex) glEnable(GL_TEXTURE_2D);
418
419         debugShapes.clear();
420 }
421
422 void RAS_OpenGLRasterizer::EndFrame()
423 {
424         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
425
426         glDisable(GL_MULTISAMPLE_ARB);
427
428         m_2DCanvas->EndFrame();
429 }
430
431 void RAS_OpenGLRasterizer::SetRenderArea()
432 {
433         RAS_Rect area;
434         // only above/below stereo method needs viewport adjustment
435         switch (m_stereomode)
436         {
437                 case RAS_STEREO_ABOVEBELOW:
438                         switch (m_curreye) {
439                                 case RAS_STEREO_LEFTEYE:
440                                         // upper half of window
441                                         area.SetLeft(0);
442                                         area.SetBottom(m_2DCanvas->GetHeight() -
443                                                 int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2);
444
445                                         area.SetRight(int(m_2DCanvas->GetWidth()));
446                                         area.SetTop(int(m_2DCanvas->GetHeight()));
447                                         m_2DCanvas->SetDisplayArea(&area);
448                                         break;
449                                 case RAS_STEREO_RIGHTEYE:
450                                         // lower half of window
451                                         area.SetLeft(0);
452                                         area.SetBottom(0);
453                                         area.SetRight(int(m_2DCanvas->GetWidth()));
454                                         area.SetTop(int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2);
455                                         m_2DCanvas->SetDisplayArea(&area);
456                                         break;
457                         }
458                         break;
459                 case RAS_STEREO_3DTVTOPBOTTOM:
460                         switch (m_curreye) {
461                                 case RAS_STEREO_LEFTEYE:
462                                         // upper half of window
463                                         area.SetLeft(0);
464                                         area.SetBottom(m_2DCanvas->GetHeight() -
465                                                 m_2DCanvas->GetHeight() / 2);
466
467                                         area.SetRight(m_2DCanvas->GetWidth());
468                                         area.SetTop(m_2DCanvas->GetHeight());
469                                         m_2DCanvas->SetDisplayArea(&area);
470                                         break;
471                                 case RAS_STEREO_RIGHTEYE:
472                                         // lower half of window
473                                         area.SetLeft(0);
474                                         area.SetBottom(0);
475                                         area.SetRight(m_2DCanvas->GetWidth());
476                                         area.SetTop(m_2DCanvas->GetHeight() / 2);
477                                         m_2DCanvas->SetDisplayArea(&area);
478                                         break;
479                         }
480                         break;
481                 case RAS_STEREO_SIDEBYSIDE:
482                         switch (m_curreye)
483                         {
484                                 case RAS_STEREO_LEFTEYE:
485                                         // Left half of window
486                                         area.SetLeft(0);
487                                         area.SetBottom(0);
488                                         area.SetRight(m_2DCanvas->GetWidth()/2);
489                                         area.SetTop(m_2DCanvas->GetHeight());
490                                         m_2DCanvas->SetDisplayArea(&area);
491                                         break;
492                                 case RAS_STEREO_RIGHTEYE:
493                                         // Right half of window
494                                         area.SetLeft(m_2DCanvas->GetWidth()/2);
495                                         area.SetBottom(0);
496                                         area.SetRight(m_2DCanvas->GetWidth());
497                                         area.SetTop(m_2DCanvas->GetHeight());
498                                         m_2DCanvas->SetDisplayArea(&area);
499                                         break;
500                         }
501                         break;
502                 default:
503                         // every available pixel
504                         area.SetLeft(0);
505                         area.SetBottom(0);
506                         area.SetRight(int(m_2DCanvas->GetWidth()));
507                         area.SetTop(int(m_2DCanvas->GetHeight()));
508                         m_2DCanvas->SetDisplayArea(&area);
509                         break;
510         }
511 }
512
513 void RAS_OpenGLRasterizer::SetStereoMode(const StereoMode stereomode)
514 {
515         m_stereomode = stereomode;
516 }
517
518 RAS_IRasterizer::StereoMode RAS_OpenGLRasterizer::GetStereoMode()
519 {
520         return m_stereomode;
521 }
522
523 bool RAS_OpenGLRasterizer::Stereo()
524 {
525         if (m_stereomode > RAS_STEREO_NOSTEREO) // > 0
526                 return true;
527         else
528                 return false;
529 }
530
531 bool RAS_OpenGLRasterizer::InterlacedStereo()
532 {
533         return m_stereomode == RAS_STEREO_VINTERLACE || m_stereomode == RAS_STEREO_INTERLACED;
534 }
535
536 void RAS_OpenGLRasterizer::SetEye(const StereoEye eye)
537 {
538         m_curreye = eye;
539         switch (m_stereomode)
540         {
541                 case RAS_STEREO_QUADBUFFERED:
542                         glDrawBuffer(m_curreye == RAS_STEREO_LEFTEYE ? GL_BACK_LEFT : GL_BACK_RIGHT);
543                         break;
544                 case RAS_STEREO_ANAGLYPH:
545                         if (m_curreye == RAS_STEREO_LEFTEYE) {
546                                 glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
547                         }
548                         else {
549                                 //glAccum(GL_LOAD, 1.0f);
550                                 glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_FALSE);
551                                 ClearDepthBuffer();
552                         }
553                         break;
554                 case RAS_STEREO_VINTERLACE:
555                 {
556                         // OpenGL stippling is deprecated, it is no longer possible to affect all shaders
557                         // this way, offscreen rendering and then compositing may be the better solution
558                         glEnable(GL_POLYGON_STIPPLE);
559                         glPolygonStipple((const GLubyte*) ((m_curreye == RAS_STEREO_LEFTEYE) ? left_eye_vinterlace_mask : right_eye_vinterlace_mask));
560                         if (m_curreye == RAS_STEREO_RIGHTEYE)
561                                 ClearDepthBuffer();
562                         break;
563                 }
564                 case RAS_STEREO_INTERLACED:
565                 {
566                         glEnable(GL_POLYGON_STIPPLE);
567                         glPolygonStipple((const GLubyte*) &hinterlace_mask[m_curreye == RAS_STEREO_LEFTEYE?0:1]);
568                         if (m_curreye == RAS_STEREO_RIGHTEYE)
569                                 ClearDepthBuffer();
570                         break;
571                 }
572                 default:
573                         break;
574         }
575 }
576
577 RAS_IRasterizer::StereoEye RAS_OpenGLRasterizer::GetEye()
578 {
579         return m_curreye;
580 }
581
582
583 void RAS_OpenGLRasterizer::SetEyeSeparation(const float eyeseparation)
584 {
585         m_eyeseparation = eyeseparation;
586 }
587
588 float RAS_OpenGLRasterizer::GetEyeSeparation()
589 {
590         return m_eyeseparation;
591 }
592
593 void RAS_OpenGLRasterizer::SetFocalLength(const float focallength)
594 {
595         m_focallength = focallength;
596         m_setfocallength = true;
597 }
598
599 float RAS_OpenGLRasterizer::GetFocalLength()
600 {
601         return m_focallength;
602 }
603
604 RAS_IOffScreen *RAS_OpenGLRasterizer::CreateOffScreen(int width, int height, int samples, int target)
605 {
606         RAS_IOffScreen *ofs;
607
608         ofs = new RAS_OpenGLOffScreen(m_2DCanvas);
609
610         if (!ofs->Create(width, height, samples, (RAS_IOffScreen::RAS_OFS_RENDER_TARGET)target)) {
611                 delete ofs;
612                 return NULL;
613         }
614         return ofs;
615 }
616
617 RAS_ISync *RAS_OpenGLRasterizer::CreateSync(int type)
618 {
619         RAS_ISync *sync;
620
621         sync = new RAS_OpenGLSync();
622
623         if (!sync->Create((RAS_ISync::RAS_SYNC_TYPE)type)) {
624                 delete sync;
625                 return NULL;
626         }
627         return sync;
628 }
629
630 void RAS_OpenGLRasterizer::SwapBuffers()
631 {
632         m_2DCanvas->SwapBuffers();
633 }
634
635
636
637 const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewMatrix() const
638 {
639         return m_viewmatrix;
640 }
641
642 const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewInvMatrix() const
643 {
644         return m_viewinvmatrix;
645 }
646
647 void RAS_OpenGLRasterizer::IndexPrimitives_3DText(RAS_MeshSlot& ms,
648                                                                         class RAS_IPolyMaterial* polymat)
649 {
650         bool obcolor = ms.m_bObjectColor;
651         MT_Vector4& rgba = ms.m_RGBAcolor;
652         RAS_MeshSlot::iterator it;
653
654         const STR_String& mytext = ((CValue*)m_clientobject)->GetPropertyText("Text");
655
656         // handle object color
657         if (obcolor) {
658                 glDisableClientState(GL_COLOR_ARRAY);
659                 glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
660         }
661         else
662                 glEnableClientState(GL_COLOR_ARRAY);
663
664         for (ms.begin(it); !ms.end(it); ms.next(it)) {
665                 RAS_TexVert *vertex;
666                 size_t i, j, numvert;
667
668                 numvert = it.array->m_type;
669
670                 if (it.array->m_type == RAS_DisplayArray::LINE) {
671                         // line drawing, no text
672                         glBegin(GL_LINES);
673
674                         for (i=0; i<it.totindex; i+=2)
675                         {
676                                 vertex = &it.vertex[it.index[i]];
677                                 glVertex3fv(vertex->getXYZ());
678
679                                 vertex = &it.vertex[it.index[i+1]];
680                                 glVertex3fv(vertex->getXYZ());
681                         }
682
683                         glEnd();
684                 }
685                 else {
686                         // triangle and quad text drawing
687                         for (i=0; i<it.totindex; i+=numvert)
688                         {
689                                 float  v[4][3];
690                                 const float  *v_ptr[4] = {NULL};
691                                 const float *uv_ptr[4] = {NULL};
692                                 int glattrib, unit;
693
694                                 for (j=0; j<numvert; j++) {
695                                         vertex = &it.vertex[it.index[i+j]];
696
697                                         v[j][0] = vertex->getXYZ()[0];
698                                         v[j][1] = vertex->getXYZ()[1];
699                                         v[j][2] = vertex->getXYZ()[2];
700                                         v_ptr[j] = v[j];
701
702                                         uv_ptr[j] = vertex->getUV(0);
703                                 }
704
705                                 // find the right opengl attribute
706                                 glattrib = -1;
707                                 if (GLEW_ARB_vertex_program)
708                                         for (unit=0; unit<m_attrib_num; unit++)
709                                                 if (m_attrib[unit] == RAS_TEXCO_UV)
710                                                         glattrib = unit;
711
712                                 GPU_render_text(
713                                         polymat->GetMTexPoly(), polymat->GetDrawingMode(), mytext, mytext.Length(), polymat->GetMCol(),
714                                         v_ptr, uv_ptr, glattrib);
715
716                                 ClearCachingInfo();
717                         }
718                 }
719         }
720
721         glDisableClientState(GL_COLOR_ARRAY);
722 }
723
724 void RAS_OpenGLRasterizer::SetTexCoordNum(int num)
725 {
726         m_texco_num = num;
727         if (m_texco_num > RAS_MAX_TEXCO)
728                 m_texco_num = RAS_MAX_TEXCO;
729 }
730
731 void RAS_OpenGLRasterizer::SetAttribNum(int num)
732 {
733         m_attrib_num = num;
734         if (m_attrib_num > RAS_MAX_ATTRIB)
735                 m_attrib_num = RAS_MAX_ATTRIB;
736 }
737
738 void RAS_OpenGLRasterizer::SetTexCoord(TexCoGen coords, int unit)
739 {
740         // this changes from material to material
741         if (unit < RAS_MAX_TEXCO)
742                 m_texco[unit] = coords;
743 }
744
745 void RAS_OpenGLRasterizer::SetAttrib(TexCoGen coords, int unit, int layer)
746 {
747         // this changes from material to material
748         if (unit < RAS_MAX_ATTRIB) {
749                 m_attrib[unit] = coords;
750                 m_attrib_layer[unit] = layer;
751         }
752 }
753
754 void RAS_OpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
755 {
756         if (ms.m_pDerivedMesh)
757                 DrawDerivedMesh(ms);
758         else
759                 m_storage->IndexPrimitives(ms);
760 }
761
762 // Code for hooking into Blender's mesh drawing for derived meshes.
763 // If/when we use more of Blender's drawing code, we may be able to
764 // clean this up
765 static bool current_wireframe;
766 static RAS_MaterialBucket *current_bucket;
767 static RAS_IPolyMaterial *current_polymat;
768 static RAS_MeshSlot *current_ms;
769 static RAS_MeshObject *current_mesh;
770 static int current_blmat_nr;
771 static GPUVertexAttribs current_gpu_attribs;
772 static Image *current_image;
773 static int CheckMaterialDM(int matnr, void *attribs)
774 {
775         // only draw the current material
776         if (matnr != current_blmat_nr)
777                 return 0;
778         GPUVertexAttribs *gattribs = (GPUVertexAttribs *)attribs;
779         if (gattribs)
780                 memcpy(gattribs, &current_gpu_attribs, sizeof(GPUVertexAttribs));
781         return 1;
782 }
783
784 static DMDrawOption CheckTexDM(MTexPoly *mtexpoly, const bool has_mcol, int matnr)
785 {
786
787         // index is the original face index, retrieve the polygon
788         if (matnr == current_blmat_nr &&
789                 (mtexpoly == NULL || mtexpoly->tpage == current_image)) {
790                 // must handle color.
791                 if (current_wireframe)
792                         return DM_DRAW_OPTION_NO_MCOL;
793                 if (current_ms->m_bObjectColor) {
794                         MT_Vector4& rgba = current_ms->m_RGBAcolor;
795                         glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
796                         // don't use mcol
797                         return DM_DRAW_OPTION_NO_MCOL;
798                 }
799                 if (!has_mcol) {
800                         // we have to set the color from the material
801                         unsigned char rgba[4];
802                         current_polymat->GetMaterialRGBAColor(rgba);
803                         glColor4ubv((const GLubyte *)rgba);
804                         return DM_DRAW_OPTION_NORMAL;
805                 }
806                 return DM_DRAW_OPTION_NORMAL;
807         }
808         return DM_DRAW_OPTION_SKIP;
809 }
810
811 void RAS_OpenGLRasterizer::DrawDerivedMesh(class RAS_MeshSlot &ms)
812 {
813         // mesh data is in derived mesh
814         current_bucket = ms.m_bucket;
815         current_polymat = current_bucket->GetPolyMaterial();
816         current_ms = &ms;
817         current_mesh = ms.m_mesh;
818         current_wireframe = m_drawingmode <= RAS_IRasterizer::KX_WIREFRAME;
819         // MCol *mcol = (MCol*)ms.m_pDerivedMesh->getFaceDataArray(ms.m_pDerivedMesh, CD_MCOL); /* UNUSED */
820
821         // handle two-side
822         if (current_polymat->GetDrawingMode() & RAS_IRasterizer::KX_BACKCULL)
823                 this->SetCullFace(true);
824         else
825                 this->SetCullFace(false);
826
827         if (current_polymat->GetFlag() & RAS_BLENDERGLSL) {
828                 // GetMaterialIndex return the original mface material index,
829                 // increment by 1 to match what derived mesh is doing
830                 current_blmat_nr = current_polymat->GetMaterialIndex()+1;
831                 // For GLSL we need to retrieve the GPU material attribute
832                 Material* blmat = current_polymat->GetBlenderMaterial();
833                 Scene* blscene = current_polymat->GetBlenderScene();
834                 if (!current_wireframe && blscene && blmat)
835                         GPU_material_vertex_attributes(GPU_material_from_blender(blscene, blmat, false), &current_gpu_attribs);
836                 else
837                         memset(&current_gpu_attribs, 0, sizeof(current_gpu_attribs));
838                 // DM draw can mess up blending mode, restore at the end
839                 int current_blend_mode = GPU_get_material_alpha_blend();
840                 ms.m_pDerivedMesh->drawFacesGLSL(ms.m_pDerivedMesh, CheckMaterialDM);
841                 GPU_set_material_alpha_blend(current_blend_mode);
842         } else {
843                 //ms.m_pDerivedMesh->drawMappedFacesTex(ms.m_pDerivedMesh, CheckTexfaceDM, mcol);
844                 current_blmat_nr = current_polymat->GetMaterialIndex();
845                 current_image = current_polymat->GetBlenderImage();
846                 ms.m_pDerivedMesh->drawFacesTex(ms.m_pDerivedMesh, CheckTexDM, NULL, NULL, DM_DRAW_USE_ACTIVE_UV);
847         }
848 }
849
850 void RAS_OpenGLRasterizer::SetProjectionMatrix(MT_CmMatrix4x4 &mat)
851 {
852         glMatrixMode(GL_PROJECTION);
853         float* matrix = &mat(0, 0);
854         glLoadMatrixf(matrix);
855
856         m_camortho = (mat(3, 3) != 0.0f);
857 }
858
859 void RAS_OpenGLRasterizer::SetProjectionMatrix(const MT_Matrix4x4 & mat)
860 {
861         glMatrixMode(GL_PROJECTION);
862         float matrix[16];
863         /* Get into argument. Looks a bit dodgy, but it's ok. */
864         mat.getValue(matrix);
865         glLoadMatrixf(matrix);
866
867         m_camortho = (mat[3][3] != 0.0f);
868 }
869
870 MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
871         float left,
872         float right,
873         float bottom,
874         float top,
875         float frustnear,
876         float frustfar,
877         float focallength,
878         bool
879 ) {
880         MT_Matrix4x4 result;
881         float mat[16];
882
883         // correction for stereo
884         if (Stereo())
885         {
886                         float near_div_focallength;
887                         float offset;
888
889                         // if Rasterizer.setFocalLength is not called we use the camera focallength
890                         if (!m_setfocallength)
891                                 // if focallength is null we use a value known to be reasonable
892                                 m_focallength = (focallength == 0.f) ? m_eyeseparation * 30.0f
893                                         : focallength;
894
895                         near_div_focallength = frustnear / m_focallength;
896                         offset = 0.5f * m_eyeseparation * near_div_focallength;
897                         switch (m_curreye) {
898                                 case RAS_STEREO_LEFTEYE:
899                                                 left += offset;
900                                                 right += offset;
901                                                 break;
902                                 case RAS_STEREO_RIGHTEYE:
903                                                 left -= offset;
904                                                 right -= offset;
905                                                 break;
906                         }
907                         // leave bottom and top untouched
908                         if (m_stereomode == RAS_STEREO_3DTVTOPBOTTOM) {
909                                 // restore the vertical frustum because the 3DTV will
910                                 // expand the top and bottom part to the full size of the screen
911                                 bottom *= 2.0f;
912                                 top *= 2.0f;
913                         }
914         }
915
916         glMatrixMode(GL_PROJECTION);
917         glLoadIdentity();
918         glFrustum(left, right, bottom, top, frustnear, frustfar);
919
920         glGetFloatv(GL_PROJECTION_MATRIX, mat);
921         result.setValue(mat);
922
923         return result;
924 }
925
926 MT_Matrix4x4 RAS_OpenGLRasterizer::GetOrthoMatrix(
927         float left,
928         float right,
929         float bottom,
930         float top,
931         float frustnear,
932         float frustfar
933 ) {
934         MT_Matrix4x4 result;
935         float mat[16];
936
937         // stereo is meaningless for orthographic, disable it
938         glMatrixMode(GL_PROJECTION);
939         glLoadIdentity();
940         glOrtho(left, right, bottom, top, frustnear, frustfar);
941
942         glGetFloatv(GL_PROJECTION_MATRIX, mat);
943         result.setValue(mat);
944
945         return result;
946 }
947
948
949 // next arguments probably contain redundant info, for later...
950 void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat,
951                                                                                  const MT_Matrix3x3 & camOrientMat3x3,
952                                                                                  const MT_Point3 & pos,
953                                                                                  const MT_Vector3 &scale,
954                                                                                  bool perspective)
955 {
956         m_viewmatrix = mat;
957
958         // correction for stereo
959         if (Stereo() && perspective)
960         {
961                 MT_Vector3 unitViewDir(0.0f, -1.0f, 0.0f);  // minus y direction, Blender convention
962                 MT_Vector3 unitViewupVec(0.0f, 0.0f, 1.0f);
963                 MT_Vector3 viewDir, viewupVec;
964                 MT_Vector3 eyeline;
965
966                 // actual viewDir
967                 viewDir = camOrientMat3x3 * unitViewDir;  // this is the moto convention, vector on right hand side
968                 // actual viewup vec
969                 viewupVec = camOrientMat3x3 * unitViewupVec;
970
971                 // vector between eyes
972                 eyeline = viewDir.cross(viewupVec);
973
974                 switch (m_curreye) {
975                         case RAS_STEREO_LEFTEYE:
976                                 {
977                                 // translate to left by half the eye distance
978                                 MT_Transform transform;
979                                 transform.setIdentity();
980                                 transform.translate(-(eyeline * m_eyeseparation / 2.0f));
981                                 m_viewmatrix *= transform;
982                                 }
983                                 break;
984                         case RAS_STEREO_RIGHTEYE:
985                                 {
986                                 // translate to right by half the eye distance
987                                 MT_Transform transform;
988                                 transform.setIdentity();
989                                 transform.translate(eyeline * m_eyeseparation / 2.0f);
990                                 m_viewmatrix *= transform;
991                                 }
992                                 break;
993                 }
994         }
995
996         bool negX = (scale[0] < 0.0f);
997         bool negY = (scale[1] < 0.0f);
998         bool negZ = (scale[2] < 0.0f);
999         if (negX || negY || negZ) {
1000                 m_viewmatrix.tscale((negX)?-1.0f:1.0f, (negY)?-1.0f:1.0f, (negZ)?-1.0f:1.0f, 1.0);
1001         }
1002         m_viewinvmatrix = m_viewmatrix;
1003         m_viewinvmatrix.invert();
1004
1005         // note: getValue gives back column major as needed by OpenGL
1006         MT_Scalar glviewmat[16];
1007         m_viewmatrix.getValue(glviewmat);
1008
1009         glMatrixMode(GL_MODELVIEW);
1010         glLoadMatrixf(glviewmat);
1011         m_campos = pos;
1012         m_camnegscale = negX ^ negY ^ negZ;
1013 }
1014
1015
1016 const MT_Point3& RAS_OpenGLRasterizer::GetCameraPosition()
1017 {
1018         return m_campos;
1019 }
1020
1021 bool RAS_OpenGLRasterizer::GetCameraOrtho()
1022 {
1023         return m_camortho;
1024 }
1025
1026 void RAS_OpenGLRasterizer::SetCullFace(bool enable)
1027 {
1028         if (enable)
1029                 glEnable(GL_CULL_FACE);
1030         else
1031                 glDisable(GL_CULL_FACE);
1032 }
1033
1034 void RAS_OpenGLRasterizer::SetLines(bool enable)
1035 {
1036         if (enable)
1037                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
1038         else
1039                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1040 }
1041
1042 void RAS_OpenGLRasterizer::SetSpecularity(float specX,
1043                                                                                   float specY,
1044                                                                                   float specZ,
1045                                                                                   float specval)
1046 {
1047         GLfloat mat_specular[] = {specX, specY, specZ, specval};
1048         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
1049 }
1050
1051
1052
1053 void RAS_OpenGLRasterizer::SetShinyness(float shiny)
1054 {
1055         GLfloat mat_shininess[] = {     shiny };
1056         glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
1057 }
1058
1059
1060
1061 void RAS_OpenGLRasterizer::SetDiffuse(float difX,float difY,float difZ,float diffuse)
1062 {
1063         GLfloat mat_diffuse [] = {difX, difY,difZ, diffuse};
1064         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);
1065 }
1066
1067 void RAS_OpenGLRasterizer::SetEmissive(float eX, float eY, float eZ, float e)
1068 {
1069         GLfloat mat_emit [] = {eX,eY,eZ,e};
1070         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mat_emit);
1071 }
1072
1073
1074 double RAS_OpenGLRasterizer::GetTime()
1075 {
1076         return m_time;
1077 }
1078
1079 void RAS_OpenGLRasterizer::SetPolygonOffset(float mult, float add)
1080 {
1081         glPolygonOffset(mult, add);
1082         GLint mode = GL_POLYGON_OFFSET_FILL;
1083         if (m_drawingmode < KX_SHADED)
1084                 mode = GL_POLYGON_OFFSET_LINE;
1085         if (mult != 0.0f || add != 0.0f)
1086                 glEnable(mode);
1087         else
1088                 glDisable(mode);
1089 }
1090
1091 void RAS_OpenGLRasterizer::EnableMotionBlur(float motionblurvalue)
1092 {
1093         /* don't just set m_motionblur to 1, but check if it is 0 so
1094          * we don't reset a motion blur that is already enabled */
1095         if (m_motionblur == 0)
1096                 m_motionblur = 1;
1097         m_motionblurvalue = motionblurvalue;
1098 }
1099
1100 void RAS_OpenGLRasterizer::DisableMotionBlur()
1101 {
1102         m_motionblur = 0;
1103         m_motionblurvalue = -1.0f;
1104 }
1105
1106 void RAS_OpenGLRasterizer::SetAlphaBlend(int alphablend)
1107 {
1108         /* Variance shadow maps don't handle alpha well, best to not allow it for now  */
1109         if (m_drawingmode == KX_SHADOW && m_usingoverrideshader)
1110                 GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
1111         else
1112                 GPU_set_material_alpha_blend(alphablend);
1113 /*
1114         if (alphablend == m_last_alphablend)
1115                 return;
1116
1117         if (alphablend == GPU_BLEND_SOLID) {
1118                 glDisable(GL_BLEND);
1119                 glDisable(GL_ALPHA_TEST);
1120                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1121         }
1122         else if (alphablend == GPU_BLEND_ADD) {
1123                 glBlendFunc(GL_ONE, GL_ONE);
1124                 glEnable(GL_BLEND);
1125                 glDisable(GL_ALPHA_TEST);
1126         }
1127         else if (alphablend == GPU_BLEND_ALPHA) {
1128                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1129                 glEnable(GL_BLEND);
1130                 glEnable(GL_ALPHA_TEST);
1131                 glAlphaFunc(GL_GREATER, 0.0f);
1132         }
1133         else if (alphablend == GPU_BLEND_CLIP) {
1134                 glDisable(GL_BLEND);
1135                 glEnable(GL_ALPHA_TEST);
1136                 glAlphaFunc(GL_GREATER, 0.5f);
1137         }
1138
1139         m_last_alphablend = alphablend;
1140 */
1141 }
1142
1143 void RAS_OpenGLRasterizer::SetFrontFace(bool ccw)
1144 {
1145         if (m_camnegscale)
1146                 ccw = !ccw;
1147
1148         if (m_last_frontface == ccw)
1149                 return;
1150
1151         if (ccw)
1152                 glFrontFace(GL_CCW);
1153         else
1154                 glFrontFace(GL_CW);
1155
1156         m_last_frontface = ccw;
1157 }
1158
1159 void RAS_OpenGLRasterizer::SetAnisotropicFiltering(short level)
1160 {
1161         GPU_set_anisotropic((float)level);
1162 }
1163
1164 short RAS_OpenGLRasterizer::GetAnisotropicFiltering()
1165 {
1166         return (short)GPU_get_anisotropic();
1167 }
1168
1169 void RAS_OpenGLRasterizer::SetMipmapping(MipmapOption val)
1170 {
1171         if (val == RAS_IRasterizer::RAS_MIPMAP_LINEAR)
1172         {
1173                 GPU_set_linear_mipmap(1);
1174                 GPU_set_mipmap(1);
1175         }
1176         else if (val == RAS_IRasterizer::RAS_MIPMAP_NEAREST)
1177         {
1178                 GPU_set_linear_mipmap(0);
1179                 GPU_set_mipmap(1);
1180         }
1181         else
1182         {
1183                 GPU_set_linear_mipmap(0);
1184                 GPU_set_mipmap(0);
1185         }
1186 }
1187
1188 RAS_IRasterizer::MipmapOption RAS_OpenGLRasterizer::GetMipmapping()
1189 {
1190         if (GPU_get_mipmap()) {
1191                 if (GPU_get_linear_mipmap()) {
1192                         return RAS_IRasterizer::RAS_MIPMAP_LINEAR;
1193                 }
1194                 else {
1195                         return RAS_IRasterizer::RAS_MIPMAP_NEAREST;
1196                 }
1197         }
1198         else {
1199                 return RAS_IRasterizer::RAS_MIPMAP_NONE;
1200         }
1201 }
1202
1203 void RAS_OpenGLRasterizer::SetUsingOverrideShader(bool val)
1204 {
1205         m_usingoverrideshader = val;
1206 }
1207
1208 bool RAS_OpenGLRasterizer::GetUsingOverrideShader()
1209 {
1210         return m_usingoverrideshader;
1211 }
1212
1213 /**
1214  * Render Tools
1215  */
1216
1217 /* ProcessLighting performs lighting on objects. the layer is a bitfield that
1218  * contains layer information. There are 20 'official' layers in blender. A
1219  * light is applied on an object only when they are in the same layer. OpenGL
1220  * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in
1221  * a scene. */
1222
1223 void RAS_OpenGLRasterizer::ProcessLighting(bool uselights, const MT_Transform& viewmat)
1224 {
1225         bool enable = false;
1226         int layer= -1;
1227
1228         /* find the layer */
1229         if (uselights) {
1230                 if (m_clientobject)
1231                         layer = static_cast<KX_GameObject*>(m_clientobject)->GetLayer();
1232         }
1233
1234         /* avoid state switching */
1235         if (m_lastlightlayer == layer && m_lastauxinfo == m_auxilaryClientInfo)
1236                 return;
1237
1238         m_lastlightlayer = layer;
1239         m_lastauxinfo = m_auxilaryClientInfo;
1240
1241         /* enable/disable lights as needed */
1242         if (layer >= 0) {
1243                 //enable = ApplyLights(layer, viewmat);
1244                 // taken from blender source, incompatibility between Blender Object / GameObject
1245                 KX_Scene* kxscene = (KX_Scene*)m_auxilaryClientInfo;
1246                 float glviewmat[16];
1247                 unsigned int count;
1248                 std::vector<RAS_OpenGLLight*>::iterator lit = m_lights.begin();
1249
1250                 for (count=0; count<m_numgllights; count++)
1251                         glDisable((GLenum)(GL_LIGHT0+count));
1252
1253                 viewmat.getValue(glviewmat);
1254
1255                 glPushMatrix();
1256                 glLoadMatrixf(glviewmat);
1257                 for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit)
1258                 {
1259                         RAS_OpenGLLight* light = (*lit);
1260
1261                         if (light->ApplyFixedFunctionLighting(kxscene, layer, count))
1262                                 count++;
1263                 }
1264                 glPopMatrix();
1265
1266                 enable = count > 0;
1267         }
1268
1269         if (enable)
1270                 EnableOpenGLLights();
1271         else
1272                 DisableOpenGLLights();
1273 }
1274
1275 void RAS_OpenGLRasterizer::EnableOpenGLLights()
1276 {
1277         if (m_lastlighting == true)
1278                 return;
1279
1280         glEnable(GL_LIGHTING);
1281         glEnable(GL_COLOR_MATERIAL);
1282
1283         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
1284         glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1285         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, (GetCameraOrtho())? GL_FALSE: GL_TRUE);
1286         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
1287                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1288
1289         m_lastlighting = true;
1290 }
1291
1292 void RAS_OpenGLRasterizer::DisableOpenGLLights()
1293 {
1294         if (m_lastlighting == false)
1295                 return;
1296
1297         glDisable(GL_LIGHTING);
1298         glDisable(GL_COLOR_MATERIAL);
1299
1300         m_lastlighting = false;
1301 }
1302
1303 RAS_ILightObject *RAS_OpenGLRasterizer::CreateLight()
1304 {
1305         return new RAS_OpenGLLight(this);
1306 }
1307
1308 void RAS_OpenGLRasterizer::AddLight(RAS_ILightObject* lightobject)
1309 {
1310         RAS_OpenGLLight* gllight = dynamic_cast<RAS_OpenGLLight*>(lightobject);
1311         assert(gllight);
1312         m_lights.push_back(gllight);
1313 }
1314
1315 void RAS_OpenGLRasterizer::RemoveLight(RAS_ILightObject* lightobject)
1316 {
1317         RAS_OpenGLLight* gllight = dynamic_cast<RAS_OpenGLLight*>(lightobject);
1318         assert(gllight);
1319
1320         std::vector<RAS_OpenGLLight*>::iterator lit =
1321                 std::find(m_lights.begin(),m_lights.end(),gllight);
1322
1323         if (!(lit==m_lights.end()))
1324                 m_lights.erase(lit);
1325 }
1326
1327 bool RAS_OpenGLRasterizer::RayHit(struct KX_ClientObjectInfo *client, KX_RayCast *result, float *oglmatrix)
1328 {
1329         if (result->m_hitMesh) {
1330
1331                 RAS_Polygon* poly = result->m_hitMesh->GetPolygon(result->m_hitPolygon);
1332                 if (!poly->IsVisible())
1333                         return false;
1334
1335                 MT_Vector3 resultnormal(result->m_hitNormal);
1336                 MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]);
1337                 MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized();
1338                 left = (dir.cross(resultnormal)).safe_normalized();
1339                 // for the up vector, we take the 'resultnormal' returned by the physics
1340
1341                 float maat[16] = {left[0],         left[1],         left[2],         0,
1342                                        dir[0],          dir[1],          dir[2],          0,
1343                                   resultnormal[0], resultnormal[1], resultnormal[2], 0,
1344                                   0,               0,               0,               1};
1345
1346                 glTranslatef(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
1347                 //glMultMatrixd(oglmatrix);
1348                 glMultMatrixf(maat);
1349                 return true;
1350         }
1351         else {
1352                 return false;
1353         }
1354 }
1355
1356 void RAS_OpenGLRasterizer::applyTransform(float* oglmatrix,int objectdrawmode )
1357 {
1358         /* FIXME:
1359         blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const
1360         MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed.
1361
1362         Program received signal SIGABRT, Aborted.
1363         [Switching to Thread 16384 (LWP 1519)]
1364         0x40477571 in kill () from /lib/libc.so.6
1365         (gdb) bt
1366         #7  0x08334368 in MT_Vector3::normalized() const ()
1367         #8  0x0833e6ec in RAS_OpenGLRasterizer::applyTransform(RAS_IRasterizer*, double*, int) ()
1368         */
1369
1370         if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED ||
1371                 objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED)
1372         {
1373                 // rotate the billboard/halo
1374                 //page 360/361 3D Game Engine Design, David Eberly for a discussion
1375                 // on screen aligned and axis aligned billboards
1376                 // assumed is that the preprocessor transformed all billboard polygons
1377                 // so that their normal points into the positive x direction (1.0f, 0.0f, 0.0f)
1378                 // when new parenting for objects is done, this rotation
1379                 // will be moved into the object
1380
1381                 MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]);
1382                 MT_Point3 campos = GetCameraPosition();
1383                 MT_Vector3 dir = (campos - objpos).safe_normalized();
1384                 MT_Vector3 up(0,0,1.0f);
1385
1386                 KX_GameObject* gameobj = (KX_GameObject*)m_clientobject;
1387                 // get scaling of halo object
1388                 MT_Vector3  size = gameobj->GetSGNode()->GetWorldScaling();
1389
1390                 bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned
1391                 if (screenaligned)
1392                 {
1393                         up = (up - up.dot(dir) * dir).safe_normalized();
1394                 } else
1395                 {
1396                         dir = (dir - up.dot(dir)*up).safe_normalized();
1397                 }
1398
1399                 MT_Vector3 left = dir.normalized();
1400                 dir = (up.cross(left)).normalized();
1401
1402                 // we have calculated the row vectors, now we keep
1403                 // local scaling into account:
1404
1405                 left *= size[0];
1406                 dir  *= size[1];
1407                 up   *= size[2];
1408
1409                 float maat[16] = {left[0], left[1], left[2], 0,
1410                                    dir[0],  dir[1],  dir[2],  0,
1411                                    up[0],   up[1],   up[2],   0,
1412                                    0,       0,       0,       1};
1413
1414                 glTranslatef(objpos[0],objpos[1],objpos[2]);
1415                 glMultMatrixf(maat);
1416
1417         }
1418         else {
1419                 if (objectdrawmode & RAS_IPolyMaterial::SHADOW)
1420                 {
1421                         // shadow must be cast to the ground, physics system needed here!
1422                         MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]);
1423                         KX_GameObject *gameobj = (KX_GameObject*)m_clientobject;
1424                         MT_Vector3 direction = MT_Vector3(0,0,-1);
1425
1426                         direction.normalize();
1427                         direction *= 100000;
1428
1429                         MT_Point3 topoint = frompoint + direction;
1430
1431                         KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo;
1432                         PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment();
1433                         PHY_IPhysicsController* physics_controller = gameobj->GetPhysicsController();
1434
1435                         KX_GameObject *parent = gameobj->GetParent();
1436                         if (!physics_controller && parent)
1437                                 physics_controller = parent->GetPhysicsController();
1438
1439                         KX_RayCast::Callback<RAS_OpenGLRasterizer, float> callback(this, physics_controller, oglmatrix);
1440                         if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback))
1441                         {
1442                                 // couldn't find something to cast the shadow on...
1443                                 glMultMatrixf(oglmatrix);
1444                         }
1445                         else
1446                         { // we found the "ground", but the cast matrix doesn't take
1447                           // scaling in consideration, so we must apply the object scale
1448                                 MT_Vector3  size = gameobj->GetSGNode()->GetLocalScale();
1449                                 glScalef(size[0], size[1], size[2]);
1450                         }
1451                 } else
1452                 {
1453
1454                         // 'normal' object
1455                         glMultMatrixf(oglmatrix);
1456                 }
1457         }
1458 }
1459
1460 static void DisableForText()
1461 {
1462         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); /* needed for texture fonts otherwise they render as wireframe */
1463
1464         glDisable(GL_BLEND);
1465         glDisable(GL_ALPHA_TEST);
1466
1467         glDisable(GL_LIGHTING);
1468         glDisable(GL_COLOR_MATERIAL);
1469
1470         if (GLEW_ARB_multitexture) {
1471                 for (int i=0; i<RAS_MAX_TEXCO; i++) {
1472                         glActiveTextureARB(GL_TEXTURE0_ARB+i);
1473
1474                         if (GLEW_ARB_texture_cube_map) {
1475                                 glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1476                                 glDisable(GL_TEXTURE_GEN_S);
1477                                 glDisable(GL_TEXTURE_GEN_T);
1478                                 glDisable(GL_TEXTURE_GEN_Q);
1479                                 glDisable(GL_TEXTURE_GEN_R);
1480                         }
1481                         glDisable(GL_TEXTURE_2D);
1482                 }
1483
1484                 glActiveTextureARB(GL_TEXTURE0_ARB);
1485         }
1486         else {
1487                 if (GLEW_ARB_texture_cube_map)
1488                         glDisable(GL_TEXTURE_CUBE_MAP_ARB);
1489
1490                 glDisable(GL_TEXTURE_2D);
1491         }
1492 }
1493
1494 void RAS_OpenGLRasterizer::RenderBox2D(int xco,
1495                         int yco,
1496                         int width,
1497                         int height,
1498                         float percentage)
1499 {
1500         /* This is a rather important line :( The gl-mode hasn't been left
1501          * behind quite as neatly as we'd have wanted to. I don't know
1502          * what cause it, though :/ .*/
1503         glDisable(GL_DEPTH_TEST);
1504
1505         glMatrixMode(GL_PROJECTION);
1506         glPushMatrix();
1507         glLoadIdentity();
1508
1509         glOrtho(0, width, 0, height, -100, 100);
1510
1511         glMatrixMode(GL_MODELVIEW);
1512         glPushMatrix();
1513         glLoadIdentity();
1514
1515         yco = height - yco;
1516         int barsize = 50;
1517
1518         /* draw in black first */
1519         glColor3ub(0, 0, 0);
1520         glBegin(GL_QUADS);
1521         glVertex2f(xco + 1 + 1 + barsize * percentage, yco - 1 + 10);
1522         glVertex2f(xco + 1, yco - 1 + 10);
1523         glVertex2f(xco + 1, yco - 1);
1524         glVertex2f(xco + 1 + 1 + barsize * percentage, yco - 1);
1525         glEnd();
1526
1527         glColor3ub(255, 255, 255);
1528         glBegin(GL_QUADS);
1529         glVertex2f(xco + 1 + barsize * percentage, yco + 10);
1530         glVertex2f(xco, yco + 10);
1531         glVertex2f(xco, yco);
1532         glVertex2f(xco + 1 + barsize * percentage, yco);
1533         glEnd();
1534
1535         glMatrixMode(GL_PROJECTION);
1536         glPopMatrix();
1537         glMatrixMode(GL_MODELVIEW);
1538         glPopMatrix();
1539         glEnable(GL_DEPTH_TEST);
1540 }
1541
1542 void RAS_OpenGLRasterizer::RenderText3D(
1543         int fontid, const char *text, int size, int dpi,
1544         const float color[4], const float mat[16], float aspect)
1545 {
1546         /* gl prepping */
1547         DisableForText();
1548
1549         /* the actual drawing */
1550         glColor4fv(color);
1551
1552         /* multiply the text matrix by the object matrix */
1553         BLF_enable(fontid, BLF_MATRIX|BLF_ASPECT);
1554         BLF_matrix(fontid, mat);
1555
1556         /* aspect is the inverse scale that allows you to increase
1557          * your resolution without sizing the final text size
1558          * the bigger the size, the smaller the aspect */
1559         BLF_aspect(fontid, aspect, aspect, aspect);
1560
1561         BLF_size(fontid, size, dpi);
1562         BLF_position(fontid, 0, 0, 0);
1563         BLF_draw(fontid, text, 65535);
1564
1565         BLF_disable(fontid, BLF_MATRIX|BLF_ASPECT);
1566 }
1567
1568 void RAS_OpenGLRasterizer::RenderText2D(
1569         RAS_TEXT_RENDER_MODE mode,
1570         const char* text,
1571         int xco, int yco,
1572         int width, int height)
1573 {
1574         /* This is a rather important line :( The gl-mode hasn't been left
1575          * behind quite as neatly as we'd have wanted to. I don't know
1576          * what cause it, though :/ .*/
1577         DisableForText();
1578         glDisable(GL_DEPTH_TEST);
1579
1580         glMatrixMode(GL_PROJECTION);
1581         glPushMatrix();
1582         glLoadIdentity();
1583
1584         glOrtho(0, width, 0, height, -100, 100);
1585
1586         glMatrixMode(GL_MODELVIEW);
1587         glPushMatrix();
1588         glLoadIdentity();
1589
1590         if (mode == RAS_TEXT_PADDED) {
1591                 /* draw in black first */
1592                 glColor3ub(0, 0, 0);
1593                 BLF_size(blf_mono_font, 11, 72);
1594                 BLF_position(blf_mono_font, (float)xco+1, (float)(height-yco-1), 0.0f);
1595                 BLF_draw(blf_mono_font, text, 65535); /* XXX, use real len */
1596         }
1597
1598         /* the actual drawing */
1599         glColor3ub(255, 255, 255);
1600         BLF_size(blf_mono_font, 11, 72);
1601         BLF_position(blf_mono_font, (float)xco, (float)(height-yco), 0.0f);
1602         BLF_draw(blf_mono_font, text, 65535); /* XXX, use real len */
1603
1604         glMatrixMode(GL_PROJECTION);
1605         glPopMatrix();
1606         glMatrixMode(GL_MODELVIEW);
1607         glPopMatrix();
1608         glEnable(GL_DEPTH_TEST);
1609 }
1610
1611 void RAS_OpenGLRasterizer::PushMatrix()
1612 {
1613         glPushMatrix();
1614 }
1615
1616 void RAS_OpenGLRasterizer::PopMatrix()
1617 {
1618         glPopMatrix();
1619 }
1620
1621 void RAS_OpenGLRasterizer::MotionBlur()
1622 {
1623         int state = GetMotionBlurState();
1624         float motionblurvalue;
1625         if (state)
1626         {
1627                 motionblurvalue = GetMotionBlurValue();
1628                 if (state==1)
1629                 {
1630                         // bugfix:load color buffer into accum buffer for the first time(state=1)
1631                         glAccum(GL_LOAD, 1.0f);
1632                         SetMotionBlurState(2);
1633                 }
1634                 else if (motionblurvalue >= 0.0f && motionblurvalue <= 1.0f) {
1635                         glAccum(GL_MULT, motionblurvalue);
1636                         glAccum(GL_ACCUM, 1-motionblurvalue);
1637                         glAccum(GL_RETURN, 1.0f);
1638                         glFlush();
1639                 }
1640         }
1641 }
1642
1643 void RAS_OpenGLRasterizer::SetClientObject(void* obj)
1644 {
1645         if (m_clientobject != obj)
1646         {
1647                 bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling());
1648                 SetFrontFace(ccw);
1649
1650                 m_clientobject = obj;
1651         }
1652 }
1653
1654 void RAS_OpenGLRasterizer::SetAuxilaryClientInfo(void* inf)
1655 {
1656         m_auxilaryClientInfo = inf;
1657 }
1658
1659 void RAS_OpenGLRasterizer::PrintHardwareInfo()
1660 {
1661         #define pprint(x) std::cout << x << std::endl;
1662
1663         pprint("GL_VENDOR: " << glGetString(GL_VENDOR));
1664         pprint("GL_RENDERER: " << glGetString(GL_RENDERER));
1665         pprint("GL_VERSION:  " << glGetString(GL_VERSION));
1666         bool support=0;
1667         pprint("Supported Extensions...");
1668         pprint(" GL_ARB_shader_objects supported?       "<< (GLEW_ARB_shader_objects?"yes.":"no."));
1669
1670         support= GLEW_ARB_vertex_shader;
1671         pprint(" GL_ARB_vertex_shader supported?        "<< (support?"yes.":"no."));
1672         if (support) {
1673                 pprint(" ----------Details----------");
1674                 int max=0;
1675                 glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
1676                 pprint("  Max uniform components." << max);
1677
1678                 glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max);
1679                 pprint("  Max varying floats." << max);
1680
1681                 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
1682                 pprint("  Max vertex texture units." << max);
1683
1684                 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
1685                 pprint("  Max combined texture units." << max);
1686                 pprint("");
1687         }
1688
1689         support=GLEW_ARB_fragment_shader;
1690         pprint(" GL_ARB_fragment_shader supported?      "<< (support?"yes.":"no."));
1691         if (support) {
1692                 pprint(" ----------Details----------");
1693                 int max=0;
1694                 glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
1695                 pprint("  Max uniform components." << max);
1696                 pprint("");
1697         }
1698
1699         support = GLEW_ARB_texture_cube_map;
1700         pprint(" GL_ARB_texture_cube_map supported?     "<< (support?"yes.":"no."));
1701         if (support) {
1702                 pprint(" ----------Details----------");
1703                 int size=0;
1704                 glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size);
1705                 pprint("  Max cubemap size." << size);
1706                 pprint("");
1707         }
1708
1709         support = GLEW_ARB_multitexture;
1710         pprint(" GL_ARB_multitexture supported?         "<< (support?"yes.":"no."));
1711         if (support) {
1712                 pprint(" ----------Details----------");
1713                 int units=0;
1714                 glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units);
1715                 pprint("  Max texture units available.  " << units);
1716                 pprint("");
1717         }
1718
1719         pprint(" GL_ARB_texture_env_combine supported?  "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
1720
1721         pprint(" GL_ARB_texture_non_power_of_two supported  " << (GPU_full_non_power_of_two_support()?"yes.":"no."));
1722 }
1723