0027684: Coding rules - drop unused declarations from Graphic3d
[occt.git] / src / OpenGl / OpenGl_Workspace.cxx
1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #include <OpenGl_Workspace.hxx>
17
18 #include <OpenGl_ArbFBO.hxx>
19 #include <OpenGl_AspectLine.hxx>
20 #include <OpenGl_AspectFace.hxx>
21 #include <OpenGl_AspectMarker.hxx>
22 #include <OpenGl_AspectText.hxx>
23 #include <OpenGl_Context.hxx>
24 #include <OpenGl_Element.hxx>
25 #include <OpenGl_FrameBuffer.hxx>
26 #include <OpenGl_GlCore15.hxx>
27 #include <OpenGl_SceneGeometry.hxx>
28 #include <OpenGl_Structure.hxx>
29 #include <OpenGl_Sampler.hxx>
30 #include <OpenGl_Texture.hxx>
31 #include <OpenGl_View.hxx>
32 #include <OpenGl_Window.hxx>
33
34 #include <Graphic3d_TextureParams.hxx>
35 #include <Graphic3d_TransformUtils.hxx>
36
37 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Workspace,Standard_Transient)
38 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter,OpenGl_RenderFilter)
39
40 #ifdef HAVE_GL2PS
41   #include <gl2ps.h>
42   /* OCC22216 NOTE: linker dependency can be switched off by undefining macro.
43      Pragma comment for gl2ps.lib is defined only here. */
44   #ifdef _MSC_VER
45   #pragma comment( lib, "gl2ps.lib" )
46   #endif
47 #endif
48
49 namespace
50 {
51   static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
52   static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
53
54   static const OpenGl_AspectLine myDefaultAspectLine;
55   static const OpenGl_AspectFace myDefaultAspectFace;
56   static const OpenGl_AspectMarker myDefaultAspectMarker;
57   static const OpenGl_AspectText myDefaultAspectText;
58
59   static const OpenGl_Matrix myDefaultMatrix =
60   {
61     {{ 1.0F, 0.0F, 0.0F, 0.0F },
62      { 0.0F, 1.0F, 0.0F, 0.0F },
63      { 0.0F, 0.0F, 1.0F, 0.0F },
64      { 0.0F, 0.0F, 0.0F, 1.0F }}
65   };
66
67 }
68
69 // =======================================================================
70 // function : Init
71 // purpose  :
72 // =======================================================================
73 void OpenGl_Material::Init (const Graphic3d_MaterialAspect& theMat,
74                             const Quantity_Color&           theInteriorColor)
75 {
76   const bool isPhysic = theMat.MaterialType (Graphic3d_MATERIAL_PHYSIC) == Standard_True;
77
78   // ambient component
79   if (theMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
80   {
81     const OpenGl_Vec3& aSrcAmb = isPhysic ? theMat.AmbientColor() : theInteriorColor;
82     Ambient = OpenGl_Vec4 (aSrcAmb * (float )theMat.Ambient(), 1.0f);
83   }
84   else
85   {
86     Ambient = THE_BLACK_COLOR;
87   }
88
89   // diffusion component
90   if (theMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
91   {
92     const OpenGl_Vec3& aSrcDif = isPhysic ? theMat.DiffuseColor() : theInteriorColor;
93     Diffuse = OpenGl_Vec4 (aSrcDif * (float )theMat.Diffuse(), 1.0f);
94   }
95   else
96   {
97     Diffuse = THE_BLACK_COLOR;
98   }
99
100   // specular component
101   if (theMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
102   {
103     const OpenGl_Vec3& aSrcSpe = isPhysic ? (const OpenGl_Vec3& )theMat.SpecularColor() : THE_WHITE_COLOR.rgb();
104     Specular = OpenGl_Vec4 (aSrcSpe * (float )theMat.Specular(), 1.0f);
105   }
106   else
107   {
108     Specular = THE_BLACK_COLOR;
109   }
110
111   // emission component
112   if (theMat.ReflectionMode (Graphic3d_TOR_EMISSION))
113   {
114     const OpenGl_Vec3& aSrcEms = isPhysic ? theMat.EmissiveColor() : theInteriorColor;
115     Emission = OpenGl_Vec4 (aSrcEms * (float )theMat.Emissive(), 1.0f);
116   }
117   else
118   {
119     Emission = THE_BLACK_COLOR;
120   }
121
122   ChangeShine()        = 128.0f * float(theMat.Shininess());
123   ChangeTransparency() = 1.0f - (float )theMat.Transparency();
124 }
125
126 // =======================================================================
127 // function : OpenGl_Workspace
128 // purpose  :
129 // =======================================================================
130 OpenGl_Workspace::OpenGl_Workspace (OpenGl_View* theView, const Handle(OpenGl_Window)& theWindow)
131 : NamedStatus (0),
132   HighlightColor (&THE_WHITE_COLOR),
133   myView (theView),
134   myWindow (theWindow),
135   myGlContext (!theWindow.IsNull() ? theWindow->GetGlContext() : NULL),
136   myUseZBuffer    (Standard_True),
137   myUseDepthWrite (Standard_True),
138   myUseGLLight (Standard_True),
139   //
140   myAspectLineSet (&myDefaultAspectLine),
141   myAspectFaceSet (&myDefaultAspectFace),
142   myAspectMarkerSet (&myDefaultAspectMarker),
143   myAspectTextSet (&myDefaultAspectText),
144   myAspectFaceAppliedWithHL (false),
145   //
146   ViewMatrix_applied (&myDefaultMatrix),
147   StructureMatrix_applied (&myDefaultMatrix),
148   myToAllowFaceCulling (false),
149   myToHighlight (false),
150   myModelViewMatrix (myDefaultMatrix)
151 {
152   if (!myGlContext.IsNull() && myGlContext->MakeCurrent())
153   {
154     myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
155
156     if (!myGlContext->GetResource ("OpenGl_LineAttributes", myLineAttribs))
157     {
158       // share and register for release once the resource is no longer used
159       myLineAttribs = new OpenGl_LineAttributes();
160       myGlContext->ShareResource ("OpenGl_LineAttributes", myLineAttribs);
161       myLineAttribs->Init (myGlContext);
162     }
163
164     // General initialization of the context
165
166   #if !defined(GL_ES_VERSION_2_0)
167     if (myGlContext->core11 != NULL)
168     {
169       // Eviter d'avoir les faces mal orientees en noir.
170       // Pourrait etre utiliser pour detecter les problemes d'orientation
171       glLightModeli ((GLenum )GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
172
173       // Optimisation pour le Fog et l'antialiasing
174       glHint (GL_FOG_HINT,            GL_FASTEST);
175       glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
176     }
177
178     glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
179     glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
180   #endif
181   }
182
183   myDefaultCappingAlgoFilter = new OpenGl_CappingAlgoFilter();
184
185   myNoneCulling .Aspect()->SetSuppressBackFaces (false);
186   myNoneCulling .Aspect()->SetDrawEdges (false);
187   myFrontCulling.Aspect()->SetSuppressBackFaces (true);
188   myFrontCulling.Aspect()->SetDrawEdges (false);
189 }
190
191 // =======================================================================
192 // function : ~OpenGl_Workspace
193 // purpose  :
194 // =======================================================================
195 OpenGl_Workspace::~OpenGl_Workspace()
196 {
197   if (!myLineAttribs.IsNull())
198   {
199     myLineAttribs.Nullify();
200     myGlContext->ReleaseResource ("OpenGl_LineAttributes", Standard_True);
201   }
202 }
203
204 // =======================================================================
205 // function : Activate
206 // purpose  :
207 // =======================================================================
208 Standard_Boolean OpenGl_Workspace::Activate()
209 {
210   if (myWindow.IsNull() || !myWindow->Activate())
211   {
212     return Standard_False;
213   }
214
215   ViewMatrix_applied      = &myDefaultMatrix;
216   StructureMatrix_applied = &myDefaultMatrix;
217
218   ResetAppliedAspect();
219
220   return Standard_True;
221 }
222
223 //=======================================================================
224 //function : ResetAppliedAspect
225 //purpose  : Sets default values of GL parameters in accordance with default aspects
226 //=======================================================================
227 void OpenGl_Workspace::ResetAppliedAspect()
228 {
229   myGlContext->BindDefaultVao();
230
231   NamedStatus           = !myTextureBound.IsNull() ? OPENGL_NS_TEXTURE : 0;
232   HighlightColor        = &THE_WHITE_COLOR;
233   myToAllowFaceCulling  = false;
234   myAspectLineSet       = &myDefaultAspectLine;
235   myAspectFaceSet       = &myDefaultAspectFace;
236   myAspectFaceApplied.Nullify();
237   myAspectMarkerSet     = &myDefaultAspectMarker;
238   myAspectMarkerApplied.Nullify();
239   myAspectTextSet       = &myDefaultAspectText;
240   myPolygonOffsetApplied= Graphic3d_PolygonOffset();
241
242   ApplyAspectLine();
243   ApplyAspectFace();
244   ApplyAspectMarker();
245   ApplyAspectText();
246
247   myGlContext->SetTypeOfLine (myDefaultAspectLine.Aspect()->Type());
248   myGlContext->SetLineWidth  (myDefaultAspectLine.Aspect()->Width());
249 }
250
251 // =======================================================================
252 // function : DisableTexture
253 // purpose  :
254 // =======================================================================
255 Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
256 {
257   if (myTextureBound.IsNull())
258   {
259     return myTextureBound;
260   }
261
262   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
263   if (!aSampler.IsNull())
264   {
265     aSampler->Unbind (*myGlContext);
266   }
267
268 #if !defined(GL_ES_VERSION_2_0)
269   // reset texture matrix because some code may expect it is identity
270   if (myGlContext->core11 != NULL)
271   {
272     GLint aMatrixMode = GL_TEXTURE;
273     glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
274     glMatrixMode (GL_TEXTURE);
275     glLoadIdentity();
276     glMatrixMode (aMatrixMode);
277   }
278 #endif
279
280   myTextureBound->Unbind (myGlContext);
281   switch (myTextureBound->GetTarget())
282   {
283   #if !defined(GL_ES_VERSION_2_0)
284     case GL_TEXTURE_1D:
285     {
286       if (myGlContext->core11 != NULL)
287       {
288         if (myTextureBound->GetParams()->GenMode() != GL_NONE)
289         {
290           glDisable (GL_TEXTURE_GEN_S);
291         }
292         glDisable (GL_TEXTURE_1D);
293       }
294       break;
295     }
296   #endif
297     case GL_TEXTURE_2D:
298     {
299     #if !defined(GL_ES_VERSION_2_0)
300       if (myGlContext->core11 != NULL)
301       {
302         if (myTextureBound->GetParams()->GenMode() != GL_NONE)
303         {
304           glDisable (GL_TEXTURE_GEN_S);
305           glDisable (GL_TEXTURE_GEN_T);
306           if (myTextureBound->GetParams()->GenMode() == Graphic3d_TOTM_SPRITE)
307           {
308             glDisable (GL_POINT_SPRITE);
309           }
310         }
311         glDisable (GL_TEXTURE_2D);
312       }
313     #endif
314       break;
315     }
316     default: break;
317   }
318
319   Handle(OpenGl_Texture) aPrevTexture = myTextureBound;
320   myTextureBound.Nullify();
321   return aPrevTexture;
322 }
323
324 // =======================================================================
325 // function : setTextureParams
326 // purpose  :
327 // =======================================================================
328 void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&                theTexture,
329                                          const Handle(Graphic3d_TextureParams)& theParams)
330 {
331   const Handle(Graphic3d_TextureParams)& aParams = theParams.IsNull() ? theTexture->GetParams() : theParams;
332   if (aParams.IsNull())
333   {
334     return;
335   }
336
337 #if !defined(GL_ES_VERSION_2_0)
338   if (myGlContext->core11 != NULL)
339   {
340     GLint anEnvMode = GL_MODULATE; // lighting mode
341     if (!aParams->IsModulate())
342     {
343       anEnvMode = GL_DECAL;
344       if (theTexture->GetFormat() == GL_ALPHA
345        || theTexture->GetFormat() == GL_LUMINANCE)
346       {
347         anEnvMode = GL_REPLACE;
348       }
349     }
350
351     // setup generation of texture coordinates
352     switch (aParams->GenMode())
353     {
354       case Graphic3d_TOTM_OBJECT:
355       {
356         glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
357         glTexGenfv (GL_S, GL_OBJECT_PLANE,     aParams->GenPlaneS().GetData());
358         if (theTexture->GetTarget() != GL_TEXTURE_1D)
359         {
360           glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
361           glTexGenfv (GL_T, GL_OBJECT_PLANE,     aParams->GenPlaneT().GetData());
362         }
363         break;
364       }
365       case Graphic3d_TOTM_SPHERE:
366       {
367         glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
368         if (theTexture->GetTarget() != GL_TEXTURE_1D)
369         {
370           glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
371         }
372         break;
373       }
374       case Graphic3d_TOTM_EYE:
375       {
376         myGlContext->WorldViewState.Push();
377
378         myGlContext->WorldViewState.SetIdentity();
379         myGlContext->ApplyWorldViewMatrix();
380
381         glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
382         glTexGenfv (GL_S, GL_EYE_PLANE,        aParams->GenPlaneS().GetData());
383
384         if (theTexture->GetTarget() != GL_TEXTURE_1D)
385         {
386           glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
387           glTexGenfv (GL_T, GL_EYE_PLANE,        aParams->GenPlaneT().GetData());
388         }
389
390         myGlContext->WorldViewState.Pop();
391
392         break;
393       }
394       case Graphic3d_TOTM_SPRITE:
395       {
396         if (myGlContext->core20fwd != NULL)
397         {
398           glEnable  (GL_POINT_SPRITE);
399           glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
400           anEnvMode = GL_REPLACE;
401         }
402         break;
403       }
404       case Graphic3d_TOTM_MANUAL:
405       default: break;
406     }
407
408     // setup lighting
409     glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, anEnvMode);
410   }
411 #endif
412
413   // get active sampler object to override default texture parameters
414   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
415
416   // setup texture filtering and wrapping
417   //if (theTexture->GetParams() != theParams)
418   const GLenum aFilter   = (aParams->Filter() == Graphic3d_TOTF_NEAREST) ? GL_NEAREST : GL_LINEAR;
419   const GLenum aWrapMode = aParams->IsRepeat() ? GL_REPEAT : myGlContext->TextureWrapClamp();
420   switch (theTexture->GetTarget())
421   {
422   #if !defined(GL_ES_VERSION_2_0)
423     case GL_TEXTURE_1D:
424     {
425       if (aSampler.IsNull() || !aSampler->IsValid())
426       {
427         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, aFilter);
428         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, aFilter);
429         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_WRAP_S,     aWrapMode);
430       }
431       else
432       {
433         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAG_FILTER, aFilter);
434         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MIN_FILTER, aFilter);
435         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_S,     aWrapMode);
436       }
437
438       break;
439     }
440   #endif
441     case GL_TEXTURE_2D:
442     {
443       GLenum aFilterMin = aFilter;
444       if (theTexture->HasMipmaps())
445       {
446         aFilterMin = GL_NEAREST_MIPMAP_NEAREST;
447         if (aParams->Filter() == Graphic3d_TOTF_BILINEAR)
448         {
449           aFilterMin = GL_LINEAR_MIPMAP_NEAREST;
450         }
451         else if (aParams->Filter() == Graphic3d_TOTF_TRILINEAR)
452         {
453           aFilterMin = GL_LINEAR_MIPMAP_LINEAR;
454         }
455
456         if (myGlContext->extAnis)
457         {
458           // setup degree of anisotropy filter
459           const GLint aMaxDegree = myGlContext->MaxDegreeOfAnisotropy();
460           GLint aDegree;
461           switch (aParams->AnisoFilter())
462           {
463             case Graphic3d_LOTA_QUALITY:
464             {
465               aDegree = aMaxDegree;
466               break;
467             }
468             case Graphic3d_LOTA_MIDDLE:
469             {
470               aDegree = (aMaxDegree <= 4) ? 2 : (aMaxDegree / 2);
471               break;
472             }
473             case Graphic3d_LOTA_FAST:
474             {
475               aDegree = 2;
476               break;
477             }
478             case Graphic3d_LOTA_OFF:
479             default:
480             {
481               aDegree = 1;
482               break;
483             }
484           }
485
486           if (aSampler.IsNull() || !aSampler->IsValid())
487           {
488             glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aDegree);
489           }
490           else
491           {
492             aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAX_ANISOTROPY_EXT, aDegree);
493           }
494         }
495       }
496
497       if (aSampler.IsNull() || !aSampler->IsValid())
498       {
499         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterMin);
500         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilter);
501         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,     aWrapMode);
502         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,     aWrapMode);
503       }
504       else
505       {
506         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MIN_FILTER, aFilterMin);
507         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAG_FILTER, aFilter);
508         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_S,     aWrapMode);
509         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_T,     aWrapMode);
510       }
511
512       break;
513     }
514     default: break;
515   }
516
517   switch (theTexture->GetTarget())
518   {
519   #if !defined(GL_ES_VERSION_2_0)
520     case GL_TEXTURE_1D:
521     {
522       if (myGlContext->core11 != NULL)
523       {
524         if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
525         {
526           glEnable (GL_TEXTURE_GEN_S);
527         }
528         glEnable (GL_TEXTURE_1D);
529       }
530       break;
531     }
532   #endif
533     case GL_TEXTURE_2D:
534     {
535     #if !defined(GL_ES_VERSION_2_0)
536       if (myGlContext->core11 != NULL)
537       {
538         if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
539         {
540           glEnable (GL_TEXTURE_GEN_S);
541           glEnable (GL_TEXTURE_GEN_T);
542         }
543         glEnable (GL_TEXTURE_2D);
544       }
545     #endif
546       break;
547     }
548     default: break;
549   }
550
551   theTexture->SetParams (aParams);
552 }
553
554 // =======================================================================
555 // function : EnableTexture
556 // purpose  :
557 // =======================================================================
558 Handle(OpenGl_Texture) OpenGl_Workspace::EnableTexture (const Handle(OpenGl_Texture)&          theTexture,
559                                                         const Handle(Graphic3d_TextureParams)& theParams)
560 {
561   if (theTexture.IsNull() || !theTexture->IsValid())
562   {
563     return DisableTexture();
564   }
565
566   if (myTextureBound == theTexture
567    && (theParams.IsNull() || theParams == theTexture->GetParams()))
568   {
569     // already bound
570     return myTextureBound;
571   }
572
573   Handle(OpenGl_Texture) aPrevTexture = DisableTexture();
574   myTextureBound = theTexture;
575   myTextureBound->Bind (myGlContext);
576   setTextureParams (myTextureBound, theParams);
577
578   // If custom sampler object is available it will be
579   // used for overriding default texture parameters
580   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
581
582   if (!aSampler.IsNull() && aSampler->IsValid())
583   {
584     aSampler->Bind (*myGlContext);
585   }
586
587   return aPrevTexture;
588 }
589
590 // =======================================================================
591 // function : updateMaterial
592 // purpose  :
593 // =======================================================================
594 void OpenGl_Workspace::updateMaterial (const int theFlag)
595 {
596   // Case of hidden line
597   if (myAspectFaceSet->Aspect()->InteriorStyle() == Aspect_IS_HIDDENLINE)
598   {
599     // copy all values including line edge aspect
600     *myAspectFaceHl.Aspect().operator->() = *myAspectFaceSet->Aspect();
601     myAspectFaceHl.SetAspectEdge (myAspectFaceSet->AspectEdge());
602     myAspectFaceHl.Aspect()->SetInteriorColor (myView->BackgroundColor().GetRGB());
603     myAspectFaceHl.SetNoLighting (true);
604     myAspectFaceSet = &myAspectFaceHl;
605     return;
606   }
607
608   const Graphic3d_MaterialAspect* aSrcMat      = &myAspectFaceSet->Aspect()->FrontMaterial();
609   const Quantity_Color*           aSrcIntColor = &myAspectFaceSet->Aspect()->InteriorColor();
610   GLenum aFace = GL_FRONT_AND_BACK;
611   if (theFlag == TEL_BACK_MATERIAL)
612   {
613     aFace        = GL_BACK;
614     aSrcMat      = &myAspectFaceSet->Aspect()->BackMaterial();
615     aSrcIntColor = &myAspectFaceSet->Aspect()->BackInteriorColor();
616   }
617   else if (myAspectFaceSet->Aspect()->Distinguish()
618         && !(NamedStatus & OPENGL_NS_RESMAT))
619   {
620     aFace = GL_FRONT;
621   }
622
623   myMatTmp.Init (*aSrcMat, *aSrcIntColor);
624   if (myToHighlight)
625   {
626     myMatTmp.SetColor (*HighlightColor);
627   }
628
629   // handling transparency
630   if (NamedStatus & OPENGL_NS_2NDPASSDO)
631   {
632     // second pass
633     myMatTmp.Diffuse.a() = aSrcMat->EnvReflexion();
634   }
635   else
636   {
637     if (aSrcMat->EnvReflexion() != 0.0f)
638     {
639       // if the material reflects the environment scene, the second pass is needed
640       NamedStatus |= OPENGL_NS_2NDPASSNEED;
641     }
642
643     const float aTransp = (float )aSrcMat->Transparency();
644     if (aTransp != 0.0f)
645     {
646       // render transparent
647       myMatTmp.Diffuse.a() = 1.0f - aTransp;
648       glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
649       glEnable    (GL_BLEND);
650       if (myUseDepthWrite)
651       {
652         glDepthMask (GL_FALSE);
653       }
654     }
655     else
656     {
657       // render opaque
658       if ((NamedStatus & OPENGL_NS_ANTIALIASING) == 0)
659       {
660         glBlendFunc (GL_ONE, GL_ZERO);
661         glDisable   (GL_BLEND);
662       }
663       if (myUseDepthWrite)
664       {
665         glDepthMask (GL_TRUE);
666       }
667     }
668   }
669
670   // do not update material properties in case of zero reflection mode,
671   // because GL lighting will be disabled by OpenGl_PrimitiveArray::DrawArray() anyway.
672   if (myAspectFaceSet->IsNoLighting())
673   {
674     return;
675   }
676
677   // reset material
678   if (NamedStatus & OPENGL_NS_RESMAT)
679   {
680   #if !defined(GL_ES_VERSION_2_0)
681     if (myGlContext->core11 != NULL)
682     {
683       myGlContext->core11->glMaterialfv (aFace, GL_AMBIENT,   myMatTmp.Ambient.GetData());
684       myGlContext->core11->glMaterialfv (aFace, GL_DIFFUSE,   myMatTmp.Diffuse.GetData());
685       myGlContext->core11->glMaterialfv (aFace, GL_SPECULAR,  myMatTmp.Specular.GetData());
686       myGlContext->core11->glMaterialfv (aFace, GL_EMISSION,  myMatTmp.Emission.GetData());
687       myGlContext->core11->glMaterialf  (aFace, GL_SHININESS, myMatTmp.Shine());
688     }
689   #endif
690
691     if (theFlag == TEL_FRONT_MATERIAL)
692     {
693       myMatFront = myMatTmp;
694       myMatBack  = myMatTmp;
695     }
696     else
697     {
698       myMatBack = myMatTmp;
699     }
700
701     NamedStatus &= ~OPENGL_NS_RESMAT;
702     return;
703   }
704
705   // reduce updates
706   OpenGl_Material& anOld = (theFlag == TEL_FRONT_MATERIAL)
707                          ? myMatFront
708                          : myMatBack;
709 #if !defined(GL_ES_VERSION_2_0)
710   if (myGlContext->core11 != NULL)
711   {
712     if (myMatTmp.Ambient.r() != anOld.Ambient.r()
713      || myMatTmp.Ambient.g() != anOld.Ambient.g()
714      || myMatTmp.Ambient.b() != anOld.Ambient.b())
715     {
716       myGlContext->core11->glMaterialfv (aFace, GL_AMBIENT, myMatTmp.Ambient.GetData());
717     }
718     if (myMatTmp.Diffuse.r() != anOld.Diffuse.r()
719      || myMatTmp.Diffuse.g() != anOld.Diffuse.g()
720      || myMatTmp.Diffuse.b() != anOld.Diffuse.b()
721      || fabs (myMatTmp.Diffuse.a() - anOld.Diffuse.a()) > 0.01f)
722     {
723       myGlContext->core11->glMaterialfv (aFace, GL_DIFFUSE, myMatTmp.Diffuse.GetData());
724     }
725     if (myMatTmp.Specular.r() != anOld.Specular.r()
726      || myMatTmp.Specular.g() != anOld.Specular.g()
727      || myMatTmp.Specular.b() != anOld.Specular.b())
728     {
729       myGlContext->core11->glMaterialfv (aFace, GL_SPECULAR, myMatTmp.Specular.GetData());
730     }
731     if (myMatTmp.Emission.r() != anOld.Emission.r()
732      || myMatTmp.Emission.g() != anOld.Emission.g()
733      || myMatTmp.Emission.b() != anOld.Emission.b())
734     {
735       myGlContext->core11->glMaterialfv (aFace, GL_EMISSION, myMatTmp.Emission.GetData());
736     }
737     if (myMatTmp.Shine() != anOld.Shine())
738     {
739       myGlContext->core11->glMaterialf (aFace, GL_SHININESS, myMatTmp.Shine());
740     }
741   }
742 #endif
743   anOld = myMatTmp;
744   if (aFace == GL_FRONT_AND_BACK)
745   {
746     myMatBack = myMatTmp;
747   }
748 }
749
750 // =======================================================================
751 // function : SetAspectLine
752 // purpose  :
753 // =======================================================================
754 const OpenGl_AspectLine* OpenGl_Workspace::SetAspectLine (const OpenGl_AspectLine* theAspect)
755 {
756   const OpenGl_AspectLine* aPrevAspectLine = myAspectLineSet;
757   myAspectLineSet = theAspect;
758   return aPrevAspectLine;
759 }
760
761 // =======================================================================
762 // function : SetAspectFace
763 // purpose  :
764 // =======================================================================
765 const OpenGl_AspectFace * OpenGl_Workspace::SetAspectFace (const OpenGl_AspectFace* theAspect)
766 {
767   const OpenGl_AspectFace* aPrevAspectFace = myAspectFaceSet;
768   myAspectFaceSet = theAspect;
769   return aPrevAspectFace;
770 }
771
772 // =======================================================================
773 // function : SetAspectMarker
774 // purpose  :
775 // =======================================================================
776 const OpenGl_AspectMarker* OpenGl_Workspace::SetAspectMarker (const OpenGl_AspectMarker* theAspect)
777 {
778   const OpenGl_AspectMarker* aPrevAspectMarker = myAspectMarkerSet;
779   myAspectMarkerSet = theAspect;
780   return aPrevAspectMarker;
781 }
782
783 // =======================================================================
784 // function : SetAspectText
785 // purpose  :
786 // =======================================================================
787 const OpenGl_AspectText * OpenGl_Workspace::SetAspectText (const OpenGl_AspectText* theAspect)
788 {
789   const OpenGl_AspectText* aPrevAspectText = myAspectTextSet;
790   myAspectTextSet = theAspect;
791   return aPrevAspectText;
792 }
793
794 // =======================================================================
795 // function : ApplyAspectFace
796 // purpose  :
797 // =======================================================================
798 const OpenGl_AspectFace* OpenGl_Workspace::ApplyAspectFace()
799 {
800   if (myView->BackfacingModel() == Graphic3d_TOBM_AUTOMATIC)
801   {
802     // manage back face culling mode, disable culling when clipping is enabled
803     bool toSuppressBackFaces = myToAllowFaceCulling
804                             && myAspectFaceSet->Aspect()->ToSuppressBackFaces();
805     if (toSuppressBackFaces)
806     {
807       if (myGlContext->Clipping().IsClippingOrCappingOn()
808        || myAspectFaceSet->Aspect()->InteriorStyle() == Aspect_IS_HATCH)
809       {
810         toSuppressBackFaces = false;
811       }
812     }
813     if (toSuppressBackFaces)
814     {
815       if (!(NamedStatus & OPENGL_NS_2NDPASSDO)
816        && (float )myAspectFaceSet->Aspect()->FrontMaterial().Transparency() != 0.0f)
817       {
818         // disable culling in case of translucent shading aspect
819         toSuppressBackFaces = false;
820       }
821     }
822     myGlContext->SetCullBackFaces (toSuppressBackFaces);
823   }
824
825   if (myAspectFaceSet->Aspect() == myAspectFaceApplied
826    && myToHighlight == myAspectFaceAppliedWithHL)
827   {
828     return myAspectFaceSet;
829   }
830   myAspectFaceAppliedWithHL = myToHighlight;
831
832 #if !defined(GL_ES_VERSION_2_0)
833   const Aspect_InteriorStyle anIntstyle = myAspectFaceSet->Aspect()->InteriorStyle();
834   if (myAspectFaceApplied.IsNull()
835    || myAspectFaceApplied->InteriorStyle() != anIntstyle)
836   {
837     switch (anIntstyle)
838     {
839       case Aspect_IS_EMPTY:
840       case Aspect_IS_HOLLOW:
841       {
842         glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
843         break;
844       }
845       case Aspect_IS_HATCH:
846       {
847         glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
848         myLineAttribs->SetTypeOfHatch (!myAspectFaceApplied.IsNull() ? myAspectFaceApplied->HatchStyle() : Aspect_HS_SOLID);
849         break;
850       }
851       case Aspect_IS_SOLID:
852       case Aspect_IS_HIDDENLINE:
853       {
854         glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
855         if (myGlContext->core11 != NULL)
856         {
857           glDisable (GL_POLYGON_STIPPLE);
858         }
859         break;
860       }
861       case Aspect_IS_POINT:
862       {
863         glPolygonMode (GL_FRONT_AND_BACK, GL_POINT);
864         break;
865       }
866     }
867   }
868
869   if (anIntstyle == Aspect_IS_HATCH)
870   {
871     const Aspect_HatchStyle hatchstyle = myAspectFaceSet->Aspect()->HatchStyle();
872     if (myAspectFaceApplied.IsNull()
873      || myAspectFaceApplied->HatchStyle() != hatchstyle)
874     {
875       myLineAttribs->SetTypeOfHatch (hatchstyle);
876     }
877   }
878 #endif
879
880   // Aspect_POM_None means: do not change current settings
881   if ((myAspectFaceSet->Aspect()->PolygonOffset().Mode & Aspect_POM_None) != Aspect_POM_None)
882   {
883     if (myPolygonOffsetApplied.Mode   != myAspectFaceSet->Aspect()->PolygonOffset().Mode
884      || myPolygonOffsetApplied.Factor != myAspectFaceSet->Aspect()->PolygonOffset().Factor
885      || myPolygonOffsetApplied.Units  != myAspectFaceSet->Aspect()->PolygonOffset().Units)
886     {
887       SetPolygonOffset (myAspectFaceSet->Aspect()->PolygonOffset());
888     }
889   }
890
891   updateMaterial (TEL_FRONT_MATERIAL);
892   if (myAspectFaceSet->Aspect()->Distinguish())
893   {
894     updateMaterial (TEL_BACK_MATERIAL);
895   }
896
897   if (myAspectFaceSet->Aspect()->ToMapTexture())
898   {
899     EnableTexture (myAspectFaceSet->TextureRes (myGlContext),
900                    myAspectFaceSet->TextureParams());
901   }
902   else
903   {
904     if (!myEnvironmentTexture.IsNull())
905     {
906       EnableTexture (myEnvironmentTexture,
907                      myEnvironmentTexture->GetParams());
908     }
909     else
910     {
911       DisableTexture();
912     }
913   }
914
915   myAspectFaceApplied = myAspectFaceSet->Aspect();
916   return myAspectFaceSet;
917 }
918
919 //=======================================================================
920 //function : SetPolygonOffset
921 //purpose  :
922 //=======================================================================
923 void OpenGl_Workspace::SetPolygonOffset (const Graphic3d_PolygonOffset& theParams)
924 {
925   myPolygonOffsetApplied = theParams;
926
927   if ((theParams.Mode & Aspect_POM_Fill) == Aspect_POM_Fill)
928   {
929     glEnable (GL_POLYGON_OFFSET_FILL);
930   }
931   else
932   {
933     glDisable (GL_POLYGON_OFFSET_FILL);
934   }
935
936 #if !defined(GL_ES_VERSION_2_0)
937   if ((theParams.Mode & Aspect_POM_Line) == Aspect_POM_Line)
938   {
939     glEnable (GL_POLYGON_OFFSET_LINE);
940   }
941   else
942   {
943     glDisable (GL_POLYGON_OFFSET_LINE);
944   }
945
946   if ((theParams.Mode & Aspect_POM_Point) == Aspect_POM_Point)
947   {
948     glEnable (GL_POLYGON_OFFSET_POINT);
949   }
950   else
951   {
952     glDisable (GL_POLYGON_OFFSET_POINT);
953   }
954 #endif
955   glPolygonOffset (theParams.Factor, theParams.Units);
956 }
957
958 // =======================================================================
959 // function : ApplyAspectMarker
960 // purpose  :
961 // =======================================================================
962 const OpenGl_AspectMarker* OpenGl_Workspace::ApplyAspectMarker()
963 {
964   if (myAspectMarkerSet->Aspect() != myAspectMarkerApplied)
965   {
966     if (myAspectMarkerApplied.IsNull()
967     || (myAspectMarkerSet->Aspect()->Scale() != myAspectMarkerApplied->Scale()))
968     {
969     #if !defined(GL_ES_VERSION_2_0)
970       glPointSize (myAspectMarkerSet->Aspect()->Scale());
971     #ifdef HAVE_GL2PS
972       gl2psPointSize (myAspectMarkerSet->Aspect()->Scale());
973     #endif
974     #endif
975     }
976     myAspectMarkerApplied = myAspectMarkerSet->Aspect();
977   }
978   return myAspectMarkerSet;
979 }
980
981 // =======================================================================
982 // function : Width
983 // purpose  :
984 // =======================================================================
985 Standard_Integer OpenGl_Workspace::Width()  const
986 {
987   return !myView->GlWindow().IsNull() ? myView->GlWindow()->Width() : 0;
988 }
989
990 // =======================================================================
991 // function : Height
992 // purpose  :
993 // =======================================================================
994 Standard_Integer OpenGl_Workspace::Height() const
995 {
996   return !myView->GlWindow().IsNull() ? myView->GlWindow()->Height() : 0;
997 }
998
999 // =======================================================================
1000 // function : UseGLLight
1001 // purpose  :
1002 // =======================================================================
1003 Standard_Boolean OpenGl_Workspace::UseGLLight() const
1004 {
1005   return myView->IsGLLightEnabled();
1006 }
1007
1008 // =======================================================================
1009 // function : AntiAliasingMode
1010 // purpose  :
1011 // =======================================================================
1012 Standard_Integer OpenGl_Workspace::AntiAliasingMode() const
1013 {
1014   return myView->IsAntialiasingEnabled();
1015 }
1016
1017 // =======================================================================
1018 // function : IsCullingEnabled
1019 // purpose  :
1020 // =======================================================================
1021 Standard_Boolean OpenGl_Workspace::IsCullingEnabled() const
1022 {
1023   return myView->IsCullingEnabled();
1024 }
1025
1026 // =======================================================================
1027 // function : FBOCreate
1028 // purpose  :
1029 // =======================================================================
1030 Handle(OpenGl_FrameBuffer) OpenGl_Workspace::FBOCreate (const Standard_Integer theWidth,
1031                                                         const Standard_Integer theHeight)
1032 {
1033   // activate OpenGL context
1034   if (!Activate())
1035     return Handle(OpenGl_FrameBuffer)();
1036
1037   DisableTexture();
1038
1039   // create the FBO
1040   const Handle(OpenGl_Context)& aCtx = GetGlContext();
1041   Handle(OpenGl_FrameBuffer) aFrameBuffer = new OpenGl_FrameBuffer();
1042   if (!aFrameBuffer->Init (aCtx, theWidth, theHeight, GL_RGBA8, GL_DEPTH24_STENCIL8, 0))
1043   {
1044     aFrameBuffer->Release (aCtx.operator->());
1045     return Handle(OpenGl_FrameBuffer)();
1046   }
1047   return aFrameBuffer;
1048 }
1049
1050 // =======================================================================
1051 // function : FBORelease
1052 // purpose  :
1053 // =======================================================================
1054 void OpenGl_Workspace::FBORelease (Handle(OpenGl_FrameBuffer)& theFbo)
1055 {
1056   // activate OpenGL context
1057   if (!Activate()
1058    || theFbo.IsNull())
1059   {
1060     return;
1061   }
1062
1063   theFbo->Release (GetGlContext().operator->());
1064   theFbo.Nullify();
1065 }
1066
1067 inline bool getDataFormat (const Image_PixMap& theData,
1068                            GLenum&             thePixelFormat,
1069                            GLenum&             theDataType)
1070 {
1071   thePixelFormat = GL_RGB;
1072   theDataType    = GL_UNSIGNED_BYTE;
1073   switch (theData.Format())
1074   {
1075   #if !defined(GL_ES_VERSION_2_0)
1076     case Image_PixMap::ImgGray:
1077       thePixelFormat = GL_DEPTH_COMPONENT;
1078       theDataType    = GL_UNSIGNED_BYTE;
1079       return true;
1080     case Image_PixMap::ImgGrayF:
1081       thePixelFormat = GL_DEPTH_COMPONENT;
1082       theDataType    = GL_FLOAT;
1083       return true;
1084     case Image_PixMap::ImgBGR:
1085       thePixelFormat = GL_BGR;
1086       theDataType    = GL_UNSIGNED_BYTE;
1087       return true;
1088     case Image_PixMap::ImgBGRA:
1089     case Image_PixMap::ImgBGR32:
1090       thePixelFormat = GL_BGRA;
1091       theDataType    = GL_UNSIGNED_BYTE;
1092       return true;
1093     case Image_PixMap::ImgBGRF:
1094       thePixelFormat = GL_BGR;
1095       theDataType    = GL_FLOAT;
1096       return true;
1097     case Image_PixMap::ImgBGRAF:
1098       thePixelFormat = GL_BGRA;
1099       theDataType    = GL_FLOAT;
1100       return true;
1101   #else
1102     case Image_PixMap::ImgGray:
1103     case Image_PixMap::ImgGrayF:
1104     case Image_PixMap::ImgBGR:
1105     case Image_PixMap::ImgBGRA:
1106     case Image_PixMap::ImgBGR32:
1107     case Image_PixMap::ImgBGRF:
1108     case Image_PixMap::ImgBGRAF:
1109       return false;
1110   #endif
1111     case Image_PixMap::ImgRGB:
1112       thePixelFormat = GL_RGB;
1113       theDataType    = GL_UNSIGNED_BYTE;
1114       return true;
1115     case Image_PixMap::ImgRGBA:
1116     case Image_PixMap::ImgRGB32:
1117       thePixelFormat = GL_RGBA;
1118       theDataType    = GL_UNSIGNED_BYTE;
1119       return true;
1120     case Image_PixMap::ImgRGBF:
1121       thePixelFormat = GL_RGB;
1122       theDataType    = GL_FLOAT;
1123       return true;
1124     case Image_PixMap::ImgRGBAF:
1125       thePixelFormat = GL_RGBA;
1126       theDataType    = GL_FLOAT;
1127       return true;
1128     case Image_PixMap::ImgAlpha:
1129     case Image_PixMap::ImgAlphaF:
1130       return false; // GL_ALPHA is no more supported in core context
1131     case Image_PixMap::ImgUNKNOWN:
1132       return false;
1133   }
1134   return false;
1135 }
1136
1137 // =======================================================================
1138 // function : getAligned
1139 // purpose  :
1140 // =======================================================================
1141 inline Standard_Size getAligned (const Standard_Size theNumber,
1142                                  const Standard_Size theAlignment)
1143 {
1144   return theNumber + theAlignment - 1 - (theNumber - 1) % theAlignment;
1145 }
1146
1147 // =======================================================================
1148 // function : BufferDump
1149 // purpose  :
1150 // =======================================================================
1151 Standard_Boolean OpenGl_Workspace::BufferDump (const Handle(OpenGl_FrameBuffer)& theFbo,
1152                                                Image_PixMap&                     theImage,
1153                                                const Graphic3d_BufferType&       theBufferType)
1154 {
1155   GLenum aFormat, aType;
1156   if (theImage.IsEmpty()
1157    || !getDataFormat (theImage, aFormat, aType)
1158    || !Activate())
1159   {
1160     return Standard_False;
1161   }
1162 #if !defined(GL_ES_VERSION_2_0)
1163   GLint aReadBufferPrev = GL_BACK;
1164   if (theBufferType == Graphic3d_BT_Depth
1165    && aFormat != GL_DEPTH_COMPONENT)
1166   {
1167     return Standard_False;
1168   }
1169 #else
1170   (void )theBufferType;
1171 #endif
1172
1173   // bind FBO if used
1174   if (!theFbo.IsNull() && theFbo->IsValid())
1175   {
1176     theFbo->BindBuffer (GetGlContext());
1177   }
1178   else
1179   {
1180   #if !defined(GL_ES_VERSION_2_0)
1181     glGetIntegerv (GL_READ_BUFFER, &aReadBufferPrev);
1182     GLint aDrawBufferPrev = GL_BACK;
1183     glGetIntegerv (GL_DRAW_BUFFER, &aDrawBufferPrev);
1184     glReadBuffer (aDrawBufferPrev);
1185   #endif
1186   }
1187
1188   // setup alignment
1189   const GLint anAligment   = Min (GLint(theImage.MaxRowAligmentBytes()), 8); // limit to 8 bytes for OpenGL
1190   glPixelStorei (GL_PACK_ALIGNMENT, anAligment);
1191   bool isBatchCopy = !theImage.IsTopDown();
1192
1193   const GLint   anExtraBytes       = GLint(theImage.RowExtraBytes());
1194   GLint         aPixelsWidth       = GLint(theImage.SizeRowBytes() / theImage.SizePixelBytes());
1195   Standard_Size aSizeRowBytesEstim = getAligned (theImage.SizePixelBytes() * aPixelsWidth, anAligment);
1196   if (anExtraBytes < anAligment)
1197   {
1198     aPixelsWidth = 0;
1199   }
1200   else if (aSizeRowBytesEstim != theImage.SizeRowBytes())
1201   {
1202     aPixelsWidth = 0;
1203     isBatchCopy  = false;
1204   }
1205 #if !defined(GL_ES_VERSION_2_0)
1206   glPixelStorei (GL_PACK_ROW_LENGTH, aPixelsWidth);
1207 #else
1208   if (aPixelsWidth != 0)
1209   {
1210     isBatchCopy = false;
1211   }
1212 #endif
1213
1214   if (!isBatchCopy)
1215   {
1216     // copy row by row
1217     for (Standard_Size aRow = 0; aRow < theImage.SizeY(); ++aRow)
1218     {
1219       // Image_PixMap rows indexation always starts from the upper corner
1220       // while order in memory depends on the flag and processed by ChangeRow() method
1221       glReadPixels (0, GLint(theImage.SizeY() - aRow - 1), GLsizei (theImage.SizeX()), 1, aFormat, aType, theImage.ChangeRow (aRow));
1222     }
1223   }
1224   else
1225   {
1226     glReadPixels (0, 0, GLsizei (theImage.SizeX()), GLsizei (theImage.SizeY()), aFormat, aType, theImage.ChangeData());
1227   }
1228
1229   glPixelStorei (GL_PACK_ALIGNMENT,  1);
1230 #if !defined(GL_ES_VERSION_2_0)
1231   glPixelStorei (GL_PACK_ROW_LENGTH, 0);
1232 #endif
1233
1234   if (!theFbo.IsNull() && theFbo->IsValid())
1235   {
1236     theFbo->UnbindBuffer (GetGlContext());
1237   }
1238   else
1239   {
1240   #if !defined(GL_ES_VERSION_2_0)
1241     glReadBuffer (aReadBufferPrev);
1242   #endif
1243   }
1244   return Standard_True;
1245 }
1246
1247 // =======================================================================
1248 // function : CanRender
1249 // purpose  :
1250 // =======================================================================
1251 Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
1252 {
1253   Standard_Boolean aPrevFilterResult = Standard_True;
1254   if (!myPrevRenderFilter.IsNull())
1255   {
1256     aPrevFilterResult = myPrevRenderFilter->CanRender (theElement);
1257   }
1258   return aPrevFilterResult &&
1259     !OpenGl_Raytrace::IsRaytracedElement (theElement);
1260 }