Fix for memory leak caused by re-making mipmaps
[blender-staging.git] / source / gameengine / Rasterizer / RAS_OpenGLRasterizer / RAS_OpenGLRasterizer.cpp
1 /*
2  * $Id$
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp
30  *  \ingroup bgerastogl
31  */
32
33  
34 #include <math.h>
35 #include <stdlib.h>
36  
37 #include "RAS_OpenGLRasterizer.h"
38
39 #include "GL/glew.h"
40
41 #include "RAS_Rect.h"
42 #include "RAS_TexVert.h"
43 #include "RAS_MeshObject.h"
44 #include "MT_CmMatrix4x4.h"
45 #include "RAS_IRenderTools.h" // rendering text
46
47 #include "GPU_draw.h"
48 #include "GPU_material.h"
49 #include "GPU_extensions.h"
50
51 #include "DNA_image_types.h"
52 #include "DNA_meshdata_types.h"
53 #include "DNA_material_types.h"
54 #include "DNA_scene_types.h"
55
56 #include "BKE_DerivedMesh.h"
57
58 /**
59  *  32x32 bit masks for vinterlace stereo mode
60  */
61 static GLuint left_eye_vinterlace_mask[32];
62 static GLuint right_eye_vinterlace_mask[32];
63
64 /**
65  *  32x32 bit masks for hinterlace stereo mode.
66  *  Left eye = &hinterlace_mask[0]
67  *  Right eye = &hinterlace_mask[1]
68  */
69 static GLuint hinterlace_mask[33];
70
71 RAS_OpenGLRasterizer::RAS_OpenGLRasterizer(RAS_ICanvas* canvas)
72         :RAS_IRasterizer(canvas),
73         m_2DCanvas(canvas),
74         m_fogenabled(false),
75         m_time(0.0),
76         m_campos(0.0f, 0.0f, 0.0f),
77         m_camortho(false),
78         m_stereomode(RAS_STEREO_NOSTEREO),
79         m_curreye(RAS_STEREO_LEFTEYE),
80         m_eyeseparation(0.0),
81         m_focallength(0.0),
82         m_setfocallength(false),
83         m_noOfScanlines(32),
84         m_motionblur(0),
85         m_motionblurvalue(-1.0),
86         m_texco_num(0),
87         m_attrib_num(0),
88         //m_last_blendmode(GPU_BLEND_SOLID),
89         m_last_frontface(true),
90         m_materialCachingInfo(0)
91 {
92         m_viewmatrix.setIdentity();
93         m_viewinvmatrix.setIdentity();
94         
95         for (int i = 0; i < 32; i++)
96         {
97                 left_eye_vinterlace_mask[i] = 0x55555555;
98                 right_eye_vinterlace_mask[i] = 0xAAAAAAAA;
99                 hinterlace_mask[i] = (i&1)*0xFFFFFFFF;
100         }
101         hinterlace_mask[32] = 0;
102 }
103
104
105
106 RAS_OpenGLRasterizer::~RAS_OpenGLRasterizer()
107 {
108 }
109
110 bool RAS_OpenGLRasterizer::Init()
111 {
112         GPU_state_init();
113
114
115         m_ambr = 0.0f;
116         m_ambg = 0.0f;
117         m_ambb = 0.0f;
118
119         glDisable(GL_BLEND);
120         glDisable(GL_ALPHA_TEST);
121         //m_last_blendmode = GPU_BLEND_SOLID;
122         GPU_set_material_blend_mode(GPU_BLEND_SOLID);
123
124         glFrontFace(GL_CCW);
125         m_last_frontface = true;
126
127         m_redback = 0.4375;
128         m_greenback = 0.4375;
129         m_blueback = 0.4375;
130         m_alphaback = 0.0;
131
132         glClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
133         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
134         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
135
136
137         glShadeModel(GL_SMOOTH);
138
139         return true;
140 }
141
142
143 void RAS_OpenGLRasterizer::SetAmbientColor(float red, float green, float blue)
144 {
145         m_ambr = red;
146         m_ambg = green;
147         m_ambb = blue;
148 }
149
150
151 void RAS_OpenGLRasterizer::SetAmbient(float factor)
152 {
153         float ambient[] = { m_ambr*factor, m_ambg*factor, m_ambb*factor, 1.0f };
154         glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
155 }
156
157
158 void RAS_OpenGLRasterizer::SetBackColor(float red,
159                                                                                 float green,
160                                                                                 float blue,
161                                                                                 float alpha)
162 {
163         m_redback = red;
164         m_greenback = green;
165         m_blueback = blue;
166         m_alphaback = alpha;
167 }
168
169
170
171 void RAS_OpenGLRasterizer::SetFogColor(float r,
172                                                                            float g,
173                                                                            float b)
174 {
175         m_fogr = r;
176         m_fogg = g;
177         m_fogb = b;
178         m_fogenabled = true;
179 }
180
181
182
183 void RAS_OpenGLRasterizer::SetFogStart(float start)
184 {
185         m_fogstart = start;
186         m_fogenabled = true;
187 }
188
189
190
191 void RAS_OpenGLRasterizer::SetFogEnd(float fogend)
192 {
193         m_fogdist = fogend;
194         m_fogenabled = true;
195 }
196
197
198
199 void RAS_OpenGLRasterizer::SetFog(float start,
200                                                                   float dist,
201                                                                   float r,
202                                                                   float g,
203                                                                   float b)
204 {
205         m_fogstart = start;
206         m_fogdist = dist;
207         m_fogr = r;
208         m_fogg = g;
209         m_fogb = b;
210         m_fogenabled = true;
211 }
212
213
214
215 void RAS_OpenGLRasterizer::DisableFog()
216 {
217         m_fogenabled = false;
218 }
219
220 bool RAS_OpenGLRasterizer::IsFogEnabled()
221 {
222         return m_fogenabled;
223 }
224
225
226 void RAS_OpenGLRasterizer::DisplayFog()
227 {
228         if ((m_drawingmode >= KX_SOLID) && m_fogenabled)
229         {
230                 float params[5];
231                 glFogi(GL_FOG_MODE, GL_LINEAR);
232                 glFogf(GL_FOG_DENSITY, 0.1f);
233                 glFogf(GL_FOG_START, m_fogstart);
234                 glFogf(GL_FOG_END, m_fogstart + m_fogdist);
235                 params[0]= m_fogr;
236                 params[1]= m_fogg;
237                 params[2]= m_fogb;
238                 params[3]= 0.0;
239                 glFogfv(GL_FOG_COLOR, params); 
240                 glEnable(GL_FOG);
241         } 
242         else
243         {
244                 glDisable(GL_FOG);
245         }
246 }
247
248
249
250 bool RAS_OpenGLRasterizer::SetMaterial(const RAS_IPolyMaterial& mat)
251 {
252         return mat.Activate(this, m_materialCachingInfo);
253 }
254
255
256
257 void RAS_OpenGLRasterizer::Exit()
258 {
259
260         glEnable(GL_CULL_FACE);
261         glEnable(GL_DEPTH_TEST);
262         glClearDepth(1.0); 
263         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
264         glClearColor(m_redback, m_greenback, m_blueback, m_alphaback);
265         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
266         glDepthMask (GL_TRUE);
267         glDepthFunc(GL_LEQUAL);
268         glBlendFunc(GL_ONE, GL_ZERO);
269         
270         glDisable(GL_POLYGON_STIPPLE);
271         
272         glDisable(GL_LIGHTING);
273         if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2)
274                 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
275         
276         EndFrame();
277 }
278
279 bool RAS_OpenGLRasterizer::BeginFrame(int drawingmode, double time)
280 {
281         m_time = time;
282         m_drawingmode = drawingmode;
283
284         // Blender camera routine destroys the settings
285         if (m_drawingmode < KX_SOLID)
286         {
287                 glDisable (GL_CULL_FACE);
288                 glDisable (GL_DEPTH_TEST);
289         }
290         else
291         {
292                 glEnable(GL_DEPTH_TEST);
293                 glEnable (GL_CULL_FACE);
294         }
295
296         glDisable(GL_BLEND);
297         glDisable(GL_ALPHA_TEST);
298         //m_last_blendmode = GPU_BLEND_SOLID;
299         GPU_set_material_blend_mode(GPU_BLEND_SOLID);
300
301         glFrontFace(GL_CCW);
302         m_last_frontface = true;
303
304         glShadeModel(GL_SMOOTH);
305
306         glEnable(GL_MULTISAMPLE_ARB);
307
308         m_2DCanvas->BeginFrame();
309         
310         return true;
311 }
312
313
314
315 void RAS_OpenGLRasterizer::SetDrawingMode(int drawingmode)
316 {
317         m_drawingmode = drawingmode;
318
319         if(m_drawingmode == KX_WIREFRAME)
320                 glDisable(GL_CULL_FACE);
321 }
322
323 int RAS_OpenGLRasterizer::GetDrawingMode()
324 {
325         return m_drawingmode;
326 }
327
328
329 void RAS_OpenGLRasterizer::SetDepthMask(DepthMask depthmask)
330 {
331         glDepthMask(depthmask == KX_DEPTHMASK_DISABLED ? GL_FALSE : GL_TRUE);
332 }
333
334
335 void RAS_OpenGLRasterizer::ClearColorBuffer()
336 {
337         m_2DCanvas->ClearColor(m_redback,m_greenback,m_blueback,m_alphaback);
338         m_2DCanvas->ClearBuffer(RAS_ICanvas::COLOR_BUFFER);
339 }
340
341
342 void RAS_OpenGLRasterizer::ClearDepthBuffer()
343 {
344         m_2DCanvas->ClearBuffer(RAS_ICanvas::DEPTH_BUFFER);
345 }
346
347
348 void RAS_OpenGLRasterizer::ClearCachingInfo(void)
349 {
350         m_materialCachingInfo = 0;
351 }
352
353 void RAS_OpenGLRasterizer::FlushDebugLines()
354 {
355         if(!m_debugLines.size())
356                 return;
357
358         // DrawDebugLines
359         GLboolean light, tex;
360
361         light= glIsEnabled(GL_LIGHTING);
362         tex= glIsEnabled(GL_TEXTURE_2D);
363
364         if(light) glDisable(GL_LIGHTING);
365         if(tex) glDisable(GL_TEXTURE_2D);
366
367         glBegin(GL_LINES);
368         for (unsigned int i=0;i<m_debugLines.size();i++)
369         {
370                 glColor4f(m_debugLines[i].m_color[0],m_debugLines[i].m_color[1],m_debugLines[i].m_color[2],1.f);
371                 const MT_Scalar* fromPtr = &m_debugLines[i].m_from.x();
372                 const MT_Scalar* toPtr= &m_debugLines[i].m_to.x();
373
374                 glVertex3dv(fromPtr);
375                 glVertex3dv(toPtr);
376         }
377         glEnd();
378
379         if(light) glEnable(GL_LIGHTING);
380         if(tex) glEnable(GL_TEXTURE_2D);
381
382         m_debugLines.clear();
383 }
384
385 void RAS_OpenGLRasterizer::EndFrame()
386 {
387         
388
389         FlushDebugLines();
390
391         glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
392
393         glDisable(GL_MULTISAMPLE_ARB);
394
395         m_2DCanvas->EndFrame();
396 }       
397
398 void RAS_OpenGLRasterizer::SetRenderArea()
399 {
400         RAS_Rect area;
401         // only above/below stereo method needs viewport adjustment
402         switch (m_stereomode)
403         {
404                 case RAS_STEREO_ABOVEBELOW:
405                         switch(m_curreye)
406                         {
407                                 case RAS_STEREO_LEFTEYE:
408                                         // upper half of window
409                                         area.SetLeft(0);
410                                         area.SetBottom(m_2DCanvas->GetHeight() -
411                                                 int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2);
412         
413                                         area.SetRight(int(m_2DCanvas->GetWidth()));
414                                         area.SetTop(int(m_2DCanvas->GetHeight()));
415                                         m_2DCanvas->SetDisplayArea(&area);
416                                         break;
417                                 case RAS_STEREO_RIGHTEYE:
418                                         // lower half of window
419                                         area.SetLeft(0);
420                                         area.SetBottom(0);
421                                         area.SetRight(int(m_2DCanvas->GetWidth()));
422                                         area.SetTop(int(m_2DCanvas->GetHeight() - m_noOfScanlines) / 2);
423                                         m_2DCanvas->SetDisplayArea(&area);
424                                         break;
425                         }
426                         break;
427                 case RAS_STEREO_SIDEBYSIDE:
428                         switch (m_curreye)
429                         {
430                                 case RAS_STEREO_LEFTEYE:
431                                         // Left half of window
432                                         area.SetLeft(0);
433                                         area.SetBottom(0);
434                                         area.SetRight(m_2DCanvas->GetWidth()/2);
435                                         area.SetTop(m_2DCanvas->GetHeight());
436                                         m_2DCanvas->SetDisplayArea(&area);
437                                         break;
438                                 case RAS_STEREO_RIGHTEYE:
439                                         // Right half of window
440                                         area.SetLeft(m_2DCanvas->GetWidth()/2);
441                                         area.SetBottom(0);
442                                         area.SetRight(m_2DCanvas->GetWidth());
443                                         area.SetTop(m_2DCanvas->GetHeight());
444                                         m_2DCanvas->SetDisplayArea(&area);
445                                         break;
446                         }
447                         break;
448                 default:
449                         // every available pixel
450                         area.SetLeft(0);
451                         area.SetBottom(0);
452                         area.SetRight(int(m_2DCanvas->GetWidth()));
453                         area.SetTop(int(m_2DCanvas->GetHeight()));
454                         m_2DCanvas->SetDisplayArea(&area);
455                         break;
456         }
457 }
458         
459 void RAS_OpenGLRasterizer::SetStereoMode(const StereoMode stereomode)
460 {
461         m_stereomode = stereomode;
462 }
463
464 RAS_IRasterizer::StereoMode RAS_OpenGLRasterizer::GetStereoMode()
465 {
466         return m_stereomode;
467 }
468
469 bool RAS_OpenGLRasterizer::Stereo()
470 {
471         if(m_stereomode > RAS_STEREO_NOSTEREO) // > 0
472                 return true;
473         else
474                 return false;
475 }
476
477 bool RAS_OpenGLRasterizer::InterlacedStereo()
478 {
479         return m_stereomode == RAS_STEREO_VINTERLACE || m_stereomode == RAS_STEREO_INTERLACED;
480 }
481
482 void RAS_OpenGLRasterizer::SetEye(const StereoEye eye)
483 {
484         m_curreye = eye;
485         switch (m_stereomode)
486         {
487                 case RAS_STEREO_QUADBUFFERED:
488                         glDrawBuffer(m_curreye == RAS_STEREO_LEFTEYE ? GL_BACK_LEFT : GL_BACK_RIGHT);
489                         break;
490                 case RAS_STEREO_ANAGLYPH:
491                         if (m_curreye == RAS_STEREO_LEFTEYE)
492                         {
493                                 glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_FALSE);
494                         } else {
495                                 //glAccum(GL_LOAD, 1.0);
496                                 glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE);
497                                 ClearDepthBuffer();
498                         }
499                         break;
500                 case RAS_STEREO_VINTERLACE:
501                 {
502                         glEnable(GL_POLYGON_STIPPLE);
503                         glPolygonStipple((const GLubyte*) ((m_curreye == RAS_STEREO_LEFTEYE) ? left_eye_vinterlace_mask : right_eye_vinterlace_mask));
504                         if (m_curreye == RAS_STEREO_RIGHTEYE)
505                                 ClearDepthBuffer();
506                         break;
507                 }
508                 case RAS_STEREO_INTERLACED:
509                 {
510                         glEnable(GL_POLYGON_STIPPLE);
511                         glPolygonStipple((const GLubyte*) &hinterlace_mask[m_curreye == RAS_STEREO_LEFTEYE?0:1]);
512                         if (m_curreye == RAS_STEREO_RIGHTEYE)
513                                 ClearDepthBuffer();
514                         break;
515                 }
516                 default:
517                         break;
518         }
519 }
520
521 RAS_IRasterizer::StereoEye RAS_OpenGLRasterizer::GetEye()
522 {
523         return m_curreye;
524 }
525
526
527 void RAS_OpenGLRasterizer::SetEyeSeparation(const float eyeseparation)
528 {
529         m_eyeseparation = eyeseparation;
530 }
531
532 float RAS_OpenGLRasterizer::GetEyeSeparation()
533 {
534         return m_eyeseparation;
535 }
536
537 void RAS_OpenGLRasterizer::SetFocalLength(const float focallength)
538 {
539         m_focallength = focallength;
540         m_setfocallength = true;
541 }
542
543 float RAS_OpenGLRasterizer::GetFocalLength()
544 {
545         return m_focallength;
546 }
547
548
549 void RAS_OpenGLRasterizer::SwapBuffers()
550 {
551         m_2DCanvas->SwapBuffers();
552 }
553
554
555
556 const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewMatrix() const
557 {
558         return m_viewmatrix;
559 }
560
561 const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewInvMatrix() const
562 {
563         return m_viewinvmatrix;
564 }
565
566 void RAS_OpenGLRasterizer::IndexPrimitives_3DText(RAS_MeshSlot& ms,
567                                                                         class RAS_IPolyMaterial* polymat,
568                                                                         class RAS_IRenderTools* rendertools)
569
570         bool obcolor = ms.m_bObjectColor;
571         MT_Vector4& rgba = ms.m_RGBAcolor;
572         RAS_MeshSlot::iterator it;
573
574         // handle object color
575         if (obcolor) {
576                 glDisableClientState(GL_COLOR_ARRAY);
577                 glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
578         }
579         else
580                 glEnableClientState(GL_COLOR_ARRAY);
581
582         for(ms.begin(it); !ms.end(it); ms.next(it)) {
583                 RAS_TexVert *vertex;
584                 size_t i, j, numvert;
585                 
586                 numvert = it.array->m_type;
587
588                 if(it.array->m_type == RAS_DisplayArray::LINE) {
589                         // line drawing, no text
590                         glBegin(GL_LINES);
591
592                         for(i=0; i<it.totindex; i+=2)
593                         {
594                                 vertex = &it.vertex[it.index[i]];
595                                 glVertex3fv(vertex->getXYZ());
596
597                                 vertex = &it.vertex[it.index[i+1]];
598                                 glVertex3fv(vertex->getXYZ());
599                         }
600
601                         glEnd();
602                 }
603                 else {
604                         // triangle and quad text drawing
605                         for(i=0; i<it.totindex; i+=numvert)
606                         {
607                                 float v[4][3];
608                                 int glattrib, unit;
609
610                                 for(j=0; j<numvert; j++) {
611                                         vertex = &it.vertex[it.index[i+j]];
612
613                                         v[j][0] = vertex->getXYZ()[0];
614                                         v[j][1] = vertex->getXYZ()[1];
615                                         v[j][2] = vertex->getXYZ()[2];
616                                 }
617
618                                 // find the right opengl attribute
619                                 glattrib = -1;
620                                 if(GLEW_ARB_vertex_program)
621                                         for(unit=0; unit<m_attrib_num; unit++)
622                                                 if(m_attrib[unit] == RAS_TEXCO_UV1)
623                                                         glattrib = unit;
624                                 
625                                 rendertools->RenderText(polymat->GetDrawingMode(), polymat,
626                                         v[0], v[1], v[2], (numvert == 4)? v[3]: NULL, glattrib);
627
628                                 ClearCachingInfo();
629                         }
630                 }
631         }
632
633         glDisableClientState(GL_COLOR_ARRAY);
634 }
635
636 void RAS_OpenGLRasterizer::SetTexCoordNum(int num)
637 {
638         m_texco_num = num;
639         if(m_texco_num > RAS_MAX_TEXCO)
640                 m_texco_num = RAS_MAX_TEXCO;
641 }
642
643 void RAS_OpenGLRasterizer::SetAttribNum(int num)
644 {
645         m_attrib_num = num;
646         if(m_attrib_num > RAS_MAX_ATTRIB)
647                 m_attrib_num = RAS_MAX_ATTRIB;
648 }
649
650 void RAS_OpenGLRasterizer::SetTexCoord(TexCoGen coords, int unit)
651 {
652         // this changes from material to material
653         if(unit < RAS_MAX_TEXCO)
654                 m_texco[unit] = coords;
655 }
656
657 void RAS_OpenGLRasterizer::SetAttrib(TexCoGen coords, int unit)
658 {
659         // this changes from material to material
660         if(unit < RAS_MAX_ATTRIB)
661                 m_attrib[unit] = coords;
662 }
663
664 void RAS_OpenGLRasterizer::TexCoord(const RAS_TexVert &tv)
665 {
666         int unit;
667
668         if(GLEW_ARB_multitexture) {
669                 for(unit=0; unit<m_texco_num; unit++) {
670                         if(tv.getFlag() & RAS_TexVert::SECOND_UV && (int)tv.getUnit() == unit) {
671                                 glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
672                                 continue;
673                         }
674                         switch(m_texco[unit]) {
675                         case RAS_TEXCO_ORCO:
676                         case RAS_TEXCO_GLOB:
677                                 glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getXYZ());
678                                 break;
679                         case RAS_TEXCO_UV1:
680                                 glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV1());
681                                 break;
682                         case RAS_TEXCO_NORM:
683                                 glMultiTexCoord3fvARB(GL_TEXTURE0_ARB+unit, tv.getNormal());
684                                 break;
685                         case RAS_TEXTANGENT:
686                                 glMultiTexCoord4fvARB(GL_TEXTURE0_ARB+unit, tv.getTangent());
687                                 break;
688                         case RAS_TEXCO_UV2:
689                                 glMultiTexCoord2fvARB(GL_TEXTURE0_ARB+unit, tv.getUV2());
690                                 break;
691                         default:
692                                 break;
693                         }
694                 }
695         }
696
697         if(GLEW_ARB_vertex_program) {
698                 for(unit=0; unit<m_attrib_num; unit++) {
699                         switch(m_attrib[unit]) {
700                         case RAS_TEXCO_ORCO:
701                         case RAS_TEXCO_GLOB:
702                                 glVertexAttrib3fvARB(unit, tv.getXYZ());
703                                 break;
704                         case RAS_TEXCO_UV1:
705                                 glVertexAttrib2fvARB(unit, tv.getUV1());
706                                 break;
707                         case RAS_TEXCO_NORM:
708                                 glVertexAttrib3fvARB(unit, tv.getNormal());
709                                 break;
710                         case RAS_TEXTANGENT:
711                                 glVertexAttrib4fvARB(unit, tv.getTangent());
712                                 break;
713                         case RAS_TEXCO_UV2:
714                                 glVertexAttrib2fvARB(unit, tv.getUV2());
715                                 break;
716                         case RAS_TEXCO_VCOL:
717                                 glVertexAttrib4ubvARB(unit, tv.getRGBA());
718                                 break;
719                         default:
720                                 break;
721                         }
722                 }
723         }
724
725 }
726
727 void RAS_OpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms)
728 {
729         IndexPrimitivesInternal(ms, false);
730 }
731
732 void RAS_OpenGLRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms)
733 {
734         IndexPrimitivesInternal(ms, true);
735 }
736
737 static bool current_wireframe;
738 static RAS_MaterialBucket *current_bucket;
739 static RAS_IPolyMaterial *current_polymat;
740 static RAS_MeshSlot *current_ms;
741 static RAS_MeshObject *current_mesh;
742 static int current_blmat_nr;
743 static GPUVertexAttribs current_gpu_attribs;
744 static Image *current_image;
745 static int CheckMaterialDM(int matnr, void *attribs)
746 {
747         // only draw the current material
748         if (matnr != current_blmat_nr)
749                 return 0;
750         GPUVertexAttribs *gattribs = (GPUVertexAttribs *)attribs;
751         if (gattribs)
752                 memcpy(gattribs, &current_gpu_attribs, sizeof(GPUVertexAttribs));
753         return 1;
754 }
755
756 /*
757 static int CheckTexfaceDM(void *mcol, int index)
758 {
759
760         // index is the original face index, retrieve the polygon
761         RAS_Polygon* polygon = (index >= 0 && index < current_mesh->NumPolygons()) ?
762                 current_mesh->GetPolygon(index) : NULL;
763         if (polygon && polygon->GetMaterial() == current_bucket) {
764                 // must handle color.
765                 if (current_wireframe)
766                         return 2;
767                 if (current_ms->m_bObjectColor) {
768                         MT_Vector4& rgba = current_ms->m_RGBAcolor;
769                         glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
770                         // don't use mcol
771                         return 2;
772                 }
773                 if (!mcol) {
774                         // we have to set the color from the material
775                         unsigned char rgba[4];
776                         current_polymat->GetMaterialRGBAColor(rgba);
777                         glColor4ubv((const GLubyte *)rgba);
778                         return 2;
779                 }
780                 return 1;
781         }
782         return 0;
783 }
784 */
785
786 static int CheckTexDM(MTFace *tface, MCol *mcol, int matnr)
787 {
788
789         // index is the original face index, retrieve the polygon
790         if (matnr == current_blmat_nr &&
791                 (tface == NULL || tface->tpage == current_image)) {
792                 // must handle color.
793                 if (current_wireframe)
794                         return 2;
795                 if (current_ms->m_bObjectColor) {
796                         MT_Vector4& rgba = current_ms->m_RGBAcolor;
797                         glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
798                         // don't use mcol
799                         return 2;
800                 }
801                 if (!mcol) {
802                         // we have to set the color from the material
803                         unsigned char rgba[4];
804                         current_polymat->GetMaterialRGBAColor(rgba);
805                         glColor4ubv((const GLubyte *)rgba);
806                         return 2;
807                 }
808                 return 1;
809         }
810         return 0;
811 }
812
813 void RAS_OpenGLRasterizer::IndexPrimitivesInternal(RAS_MeshSlot& ms, bool multi)
814
815         bool obcolor = ms.m_bObjectColor;
816         bool wireframe = m_drawingmode <= KX_WIREFRAME;
817         MT_Vector4& rgba = ms.m_RGBAcolor;
818         RAS_MeshSlot::iterator it;
819
820         if (ms.m_pDerivedMesh) {
821                 // mesh data is in derived mesh, 
822                 current_bucket = ms.m_bucket;
823                 current_polymat = current_bucket->GetPolyMaterial();
824                 current_ms = &ms;
825                 current_mesh = ms.m_mesh;
826                 current_wireframe = wireframe;
827                 // MCol *mcol = (MCol*)ms.m_pDerivedMesh->getFaceDataArray(ms.m_pDerivedMesh, CD_MCOL); /* UNUSED */
828
829                 // handle two-side
830                 if (current_polymat->GetDrawingMode() & RAS_IRasterizer::KX_TWOSIDE)
831                         this->SetCullFace(false);
832                 else
833                         this->SetCullFace(true);
834
835                 if (current_polymat->GetFlag() & RAS_BLENDERGLSL) {
836                         // GetMaterialIndex return the original mface material index, 
837                         // increment by 1 to match what derived mesh is doing
838                         current_blmat_nr = current_polymat->GetMaterialIndex()+1;
839                         // For GLSL we need to retrieve the GPU material attribute
840                         Material* blmat = current_polymat->GetBlenderMaterial();
841                         Scene* blscene = current_polymat->GetBlenderScene();
842                         if (!wireframe && blscene && blmat)
843                                 GPU_material_vertex_attributes(GPU_material_from_blender(blscene, blmat), &current_gpu_attribs);
844                         else
845                                 memset(&current_gpu_attribs, 0, sizeof(current_gpu_attribs));
846                         // DM draw can mess up blending mode, restore at the end
847                         int current_blend_mode = GPU_get_material_blend_mode();
848                         ms.m_pDerivedMesh->drawFacesGLSL(ms.m_pDerivedMesh, CheckMaterialDM);
849                         GPU_set_material_blend_mode(current_blend_mode);
850                 } else {
851                         //ms.m_pDerivedMesh->drawMappedFacesTex(ms.m_pDerivedMesh, CheckTexfaceDM, mcol);
852                         current_blmat_nr = current_polymat->GetMaterialIndex();
853                         current_image = current_polymat->GetBlenderImage();
854                         ms.m_pDerivedMesh->drawFacesTex(ms.m_pDerivedMesh, CheckTexDM);
855                 }
856                 return;
857         }
858         // iterate over display arrays, each containing an index + vertex array
859         for(ms.begin(it); !ms.end(it); ms.next(it)) {
860                 RAS_TexVert *vertex;
861                 size_t i, j, numvert;
862                 
863                 numvert = it.array->m_type;
864
865                 if(it.array->m_type == RAS_DisplayArray::LINE) {
866                         // line drawing
867                         glBegin(GL_LINES);
868
869                         for(i=0; i<it.totindex; i+=2)
870                         {
871                                 vertex = &it.vertex[it.index[i]];
872                                 glVertex3fv(vertex->getXYZ());
873
874                                 vertex = &it.vertex[it.index[i+1]];
875                                 glVertex3fv(vertex->getXYZ());
876                         }
877
878                         glEnd();
879                 }
880                 else {
881                         // triangle and quad drawing
882                         if(it.array->m_type == RAS_DisplayArray::TRIANGLE)
883                                 glBegin(GL_TRIANGLES);
884                         else
885                                 glBegin(GL_QUADS);
886
887                         for(i=0; i<it.totindex; i+=numvert)
888                         {
889                                 if(obcolor)
890                                         glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]);
891
892                                 for(j=0; j<numvert; j++) {
893                                         vertex = &it.vertex[it.index[i+j]];
894
895                                         if(!wireframe) {
896                                                 if(!obcolor)
897                                                         glColor4ubv((const GLubyte *)(vertex->getRGBA()));
898
899                                                 glNormal3fv(vertex->getNormal());
900
901                                                 if(multi)
902                                                         TexCoord(*vertex);
903                                                 else
904                                                         glTexCoord2fv(vertex->getUV1());
905                                         }
906
907                                         glVertex3fv(vertex->getXYZ());
908                                 }
909                         }
910
911                         glEnd();
912                 }
913         }
914 }
915
916 void RAS_OpenGLRasterizer::SetProjectionMatrix(MT_CmMatrix4x4 &mat)
917 {
918         glMatrixMode(GL_PROJECTION);
919         double* matrix = &mat(0,0);
920         glLoadMatrixd(matrix);
921
922         m_camortho= (mat(3, 3) != 0.0f);
923 }
924
925 void RAS_OpenGLRasterizer::SetProjectionMatrix(const MT_Matrix4x4 & mat)
926 {
927         glMatrixMode(GL_PROJECTION);
928         double matrix[16];
929         /* Get into argument. Looks a bit dodgy, but it's ok. */
930         mat.getValue(matrix);
931         /* Internally, MT_Matrix4x4 uses doubles (MT_Scalar). */
932         glLoadMatrixd(matrix);  
933
934         m_camortho= (mat[3][3] != 0.0f);
935 }
936
937 MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix(
938         float left,
939         float right,
940         float bottom,
941         float top,
942         float frustnear,
943         float frustfar,
944         float focallength,
945         bool 
946 ){
947         MT_Matrix4x4 result;
948         double mat[16];
949
950         // correction for stereo
951         if(Stereo())
952         {
953                         float near_div_focallength;
954                         float offset;
955
956                         // if Rasterizer.setFocalLength is not called we use the camera focallength
957                         if (!m_setfocallength)
958                                 // if focallength is null we use a value known to be reasonable
959                                 m_focallength = (focallength == 0.f) ? m_eyeseparation * 30.0
960                                         : focallength;
961
962                         near_div_focallength = frustnear / m_focallength;
963                         offset = 0.5 * m_eyeseparation * near_div_focallength;
964                         switch(m_curreye)
965                         {
966                                 case RAS_STEREO_LEFTEYE:
967                                                 left += offset;
968                                                 right += offset;
969                                                 break;
970                                 case RAS_STEREO_RIGHTEYE:
971                                                 left -= offset;
972                                                 right -= offset;
973                                                 break;
974                         }
975                         // leave bottom and top untouched
976         }
977         
978         glMatrixMode(GL_PROJECTION);
979         glLoadIdentity();
980         glFrustum(left, right, bottom, top, frustnear, frustfar);
981                 
982         glGetDoublev(GL_PROJECTION_MATRIX, mat);
983         result.setValue(mat);
984
985         return result;
986 }
987
988 MT_Matrix4x4 RAS_OpenGLRasterizer::GetOrthoMatrix(
989         float left,
990         float right,
991         float bottom,
992         float top,
993         float frustnear,
994         float frustfar
995 ){
996         MT_Matrix4x4 result;
997         double mat[16];
998
999         // stereo is meaning less for orthographic, disable it
1000         glMatrixMode(GL_PROJECTION);
1001         glLoadIdentity();
1002         glOrtho(left, right, bottom, top, frustnear, frustfar);
1003                 
1004         glGetDoublev(GL_PROJECTION_MATRIX, mat);
1005         result.setValue(mat);
1006
1007         return result;
1008 }
1009
1010
1011 // next arguments probably contain redundant info, for later...
1012 void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, 
1013                                                                                  const MT_Matrix3x3 & camOrientMat3x3,
1014                                                                                  const MT_Point3 & pos,
1015                                                                                  bool perspective)
1016 {
1017         m_viewmatrix = mat;
1018
1019         // correction for stereo
1020         if(Stereo() && perspective)
1021         {
1022                 MT_Vector3 unitViewDir(0.0, -1.0, 0.0);  // minus y direction, Blender convention
1023                 MT_Vector3 unitViewupVec(0.0, 0.0, 1.0);
1024                 MT_Vector3 viewDir, viewupVec;
1025                 MT_Vector3 eyeline;
1026
1027                 // actual viewDir
1028                 viewDir = camOrientMat3x3 * unitViewDir;  // this is the moto convention, vector on right hand side
1029                 // actual viewup vec
1030                 viewupVec = camOrientMat3x3 * unitViewupVec;
1031
1032                 // vector between eyes
1033                 eyeline = viewDir.cross(viewupVec);
1034
1035                 switch(m_curreye)
1036                 {
1037                         case RAS_STEREO_LEFTEYE:
1038                                 {
1039                                 // translate to left by half the eye distance
1040                                 MT_Transform transform;
1041                                 transform.setIdentity();
1042                                 transform.translate(-(eyeline * m_eyeseparation / 2.0));
1043                                 m_viewmatrix *= transform;
1044                                 }
1045                                 break;
1046                         case RAS_STEREO_RIGHTEYE:
1047                                 {
1048                                 // translate to right by half the eye distance
1049                                 MT_Transform transform;
1050                                 transform.setIdentity();
1051                                 transform.translate(eyeline * m_eyeseparation / 2.0);
1052                                 m_viewmatrix *= transform;
1053                                 }
1054                                 break;
1055                 }
1056         }
1057
1058         m_viewinvmatrix = m_viewmatrix;
1059         m_viewinvmatrix.invert();
1060
1061         // note: getValue gives back column major as needed by OpenGL
1062         MT_Scalar glviewmat[16];
1063         m_viewmatrix.getValue(glviewmat);
1064
1065         glMatrixMode(GL_MODELVIEW);
1066         glLoadMatrixd(glviewmat);
1067         m_campos = pos;
1068 }
1069
1070
1071 const MT_Point3& RAS_OpenGLRasterizer::GetCameraPosition()
1072 {
1073         return m_campos;
1074 }
1075
1076 bool RAS_OpenGLRasterizer::GetCameraOrtho()
1077 {
1078         return m_camortho;
1079 }
1080
1081 void RAS_OpenGLRasterizer::SetCullFace(bool enable)
1082 {
1083         if (enable)
1084                 glEnable(GL_CULL_FACE);
1085         else
1086                 glDisable(GL_CULL_FACE);
1087 }
1088
1089 void RAS_OpenGLRasterizer::SetLines(bool enable)
1090 {
1091         if (enable)
1092                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
1093         else
1094                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
1095 }
1096
1097 void RAS_OpenGLRasterizer::SetSpecularity(float specX,
1098                                                                                   float specY,
1099                                                                                   float specZ,
1100                                                                                   float specval)
1101 {
1102         GLfloat mat_specular[] = {specX, specY, specZ, specval};
1103         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
1104 }
1105
1106
1107
1108 void RAS_OpenGLRasterizer::SetShinyness(float shiny)
1109 {
1110         GLfloat mat_shininess[] = {     shiny };
1111         glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
1112 }
1113
1114
1115
1116 void RAS_OpenGLRasterizer::SetDiffuse(float difX,float difY,float difZ,float diffuse)
1117 {
1118         GLfloat mat_diffuse [] = {difX, difY,difZ, diffuse};
1119         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);
1120 }
1121
1122 void RAS_OpenGLRasterizer::SetEmissive(float eX, float eY, float eZ, float e)
1123 {
1124         GLfloat mat_emit [] = {eX,eY,eZ,e};
1125         glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, mat_emit);
1126 }
1127
1128
1129 double RAS_OpenGLRasterizer::GetTime()
1130 {
1131         return m_time;
1132 }
1133
1134 void RAS_OpenGLRasterizer::SetPolygonOffset(float mult, float add)
1135 {
1136         glPolygonOffset(mult, add);
1137         GLint mode = GL_POLYGON_OFFSET_FILL;
1138         if (m_drawingmode < KX_SHADED)
1139                 mode = GL_POLYGON_OFFSET_LINE;
1140         if (mult != 0.0f || add != 0.0f)
1141                 glEnable(mode);
1142         else
1143                 glDisable(mode);
1144 }
1145
1146 void RAS_OpenGLRasterizer::EnableMotionBlur(float motionblurvalue)
1147 {
1148         /* don't just set m_motionblur to 1, but check if it is 0 so
1149          * we don't reset a motion blur that is already enabled */
1150         if(m_motionblur == 0)
1151                 m_motionblur = 1;
1152         m_motionblurvalue = motionblurvalue;
1153 }
1154
1155 void RAS_OpenGLRasterizer::DisableMotionBlur()
1156 {
1157         m_motionblur = 0;
1158         m_motionblurvalue = -1.0;
1159 }
1160
1161 void RAS_OpenGLRasterizer::SetBlendingMode(int blendmode)
1162 {
1163         GPU_set_material_blend_mode(blendmode);
1164 /*
1165         if(blendmode == m_last_blendmode)
1166                 return;
1167
1168         if(blendmode == GPU_BLEND_SOLID) {
1169                 glDisable(GL_BLEND);
1170                 glDisable(GL_ALPHA_TEST);
1171                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1172         }
1173         else if(blendmode == GPU_BLEND_ADD) {
1174                 glBlendFunc(GL_ONE, GL_ONE);
1175                 glEnable(GL_BLEND);
1176                 glDisable(GL_ALPHA_TEST);
1177         }
1178         else if(blendmode == GPU_BLEND_ALPHA) {
1179                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1180                 glEnable(GL_BLEND);
1181                 glEnable(GL_ALPHA_TEST);
1182                 glAlphaFunc(GL_GREATER, 0.0f);
1183         }
1184         else if(blendmode == GPU_BLEND_CLIP) {
1185                 glDisable(GL_BLEND); 
1186                 glEnable(GL_ALPHA_TEST);
1187                 glAlphaFunc(GL_GREATER, 0.5f);
1188         }
1189
1190         m_last_blendmode = blendmode;
1191 */
1192 }
1193
1194 void RAS_OpenGLRasterizer::SetFrontFace(bool ccw)
1195 {
1196         if(m_last_frontface == ccw)
1197                 return;
1198
1199         if(ccw)
1200                 glFrontFace(GL_CCW);
1201         else
1202                 glFrontFace(GL_CW);
1203         
1204         m_last_frontface = ccw;
1205 }
1206