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