0027360: Visualization - remove obsolete anti-aliasing API
[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       glBlendFunc (GL_ONE, GL_ZERO);
659       glDisable   (GL_BLEND);
660       if (myUseDepthWrite)
661       {
662         glDepthMask (GL_TRUE);
663       }
664     }
665   }
666
667   // do not update material properties in case of zero reflection mode,
668   // because GL lighting will be disabled by OpenGl_PrimitiveArray::DrawArray() anyway.
669   if (myAspectFaceSet->IsNoLighting())
670   {
671     return;
672   }
673
674   // reset material
675   if (NamedStatus & OPENGL_NS_RESMAT)
676   {
677   #if !defined(GL_ES_VERSION_2_0)
678     if (myGlContext->core11 != NULL)
679     {
680       myGlContext->core11->glMaterialfv (aFace, GL_AMBIENT,   myMatTmp.Ambient.GetData());
681       myGlContext->core11->glMaterialfv (aFace, GL_DIFFUSE,   myMatTmp.Diffuse.GetData());
682       myGlContext->core11->glMaterialfv (aFace, GL_SPECULAR,  myMatTmp.Specular.GetData());
683       myGlContext->core11->glMaterialfv (aFace, GL_EMISSION,  myMatTmp.Emission.GetData());
684       myGlContext->core11->glMaterialf  (aFace, GL_SHININESS, myMatTmp.Shine());
685     }
686   #endif
687
688     if (theFlag == TEL_FRONT_MATERIAL)
689     {
690       myMatFront = myMatTmp;
691       myMatBack  = myMatTmp;
692     }
693     else
694     {
695       myMatBack = myMatTmp;
696     }
697
698     NamedStatus &= ~OPENGL_NS_RESMAT;
699     return;
700   }
701
702   // reduce updates
703   OpenGl_Material& anOld = (theFlag == TEL_FRONT_MATERIAL)
704                          ? myMatFront
705                          : myMatBack;
706 #if !defined(GL_ES_VERSION_2_0)
707   if (myGlContext->core11 != NULL)
708   {
709     if (myMatTmp.Ambient.r() != anOld.Ambient.r()
710      || myMatTmp.Ambient.g() != anOld.Ambient.g()
711      || myMatTmp.Ambient.b() != anOld.Ambient.b())
712     {
713       myGlContext->core11->glMaterialfv (aFace, GL_AMBIENT, myMatTmp.Ambient.GetData());
714     }
715     if (myMatTmp.Diffuse.r() != anOld.Diffuse.r()
716      || myMatTmp.Diffuse.g() != anOld.Diffuse.g()
717      || myMatTmp.Diffuse.b() != anOld.Diffuse.b()
718      || fabs (myMatTmp.Diffuse.a() - anOld.Diffuse.a()) > 0.01f)
719     {
720       myGlContext->core11->glMaterialfv (aFace, GL_DIFFUSE, myMatTmp.Diffuse.GetData());
721     }
722     if (myMatTmp.Specular.r() != anOld.Specular.r()
723      || myMatTmp.Specular.g() != anOld.Specular.g()
724      || myMatTmp.Specular.b() != anOld.Specular.b())
725     {
726       myGlContext->core11->glMaterialfv (aFace, GL_SPECULAR, myMatTmp.Specular.GetData());
727     }
728     if (myMatTmp.Emission.r() != anOld.Emission.r()
729      || myMatTmp.Emission.g() != anOld.Emission.g()
730      || myMatTmp.Emission.b() != anOld.Emission.b())
731     {
732       myGlContext->core11->glMaterialfv (aFace, GL_EMISSION, myMatTmp.Emission.GetData());
733     }
734     if (myMatTmp.Shine() != anOld.Shine())
735     {
736       myGlContext->core11->glMaterialf (aFace, GL_SHININESS, myMatTmp.Shine());
737     }
738   }
739 #endif
740   anOld = myMatTmp;
741   if (aFace == GL_FRONT_AND_BACK)
742   {
743     myMatBack = myMatTmp;
744   }
745 }
746
747 // =======================================================================
748 // function : SetAspectLine
749 // purpose  :
750 // =======================================================================
751 const OpenGl_AspectLine* OpenGl_Workspace::SetAspectLine (const OpenGl_AspectLine* theAspect)
752 {
753   const OpenGl_AspectLine* aPrevAspectLine = myAspectLineSet;
754   myAspectLineSet = theAspect;
755   return aPrevAspectLine;
756 }
757
758 // =======================================================================
759 // function : SetAspectFace
760 // purpose  :
761 // =======================================================================
762 const OpenGl_AspectFace * OpenGl_Workspace::SetAspectFace (const OpenGl_AspectFace* theAspect)
763 {
764   const OpenGl_AspectFace* aPrevAspectFace = myAspectFaceSet;
765   myAspectFaceSet = theAspect;
766   return aPrevAspectFace;
767 }
768
769 // =======================================================================
770 // function : SetAspectMarker
771 // purpose  :
772 // =======================================================================
773 const OpenGl_AspectMarker* OpenGl_Workspace::SetAspectMarker (const OpenGl_AspectMarker* theAspect)
774 {
775   const OpenGl_AspectMarker* aPrevAspectMarker = myAspectMarkerSet;
776   myAspectMarkerSet = theAspect;
777   return aPrevAspectMarker;
778 }
779
780 // =======================================================================
781 // function : SetAspectText
782 // purpose  :
783 // =======================================================================
784 const OpenGl_AspectText * OpenGl_Workspace::SetAspectText (const OpenGl_AspectText* theAspect)
785 {
786   const OpenGl_AspectText* aPrevAspectText = myAspectTextSet;
787   myAspectTextSet = theAspect;
788   return aPrevAspectText;
789 }
790
791 // =======================================================================
792 // function : ApplyAspectFace
793 // purpose  :
794 // =======================================================================
795 const OpenGl_AspectFace* OpenGl_Workspace::ApplyAspectFace()
796 {
797   if (myView->BackfacingModel() == Graphic3d_TOBM_AUTOMATIC)
798   {
799     // manage back face culling mode, disable culling when clipping is enabled
800     bool toSuppressBackFaces = myToAllowFaceCulling
801                             && myAspectFaceSet->Aspect()->ToSuppressBackFaces();
802     if (toSuppressBackFaces)
803     {
804       if (myGlContext->Clipping().IsClippingOrCappingOn()
805        || myAspectFaceSet->Aspect()->InteriorStyle() == Aspect_IS_HATCH)
806       {
807         toSuppressBackFaces = false;
808       }
809     }
810     if (toSuppressBackFaces)
811     {
812       if (!(NamedStatus & OPENGL_NS_2NDPASSDO)
813        && (float )myAspectFaceSet->Aspect()->FrontMaterial().Transparency() != 0.0f)
814       {
815         // disable culling in case of translucent shading aspect
816         toSuppressBackFaces = false;
817       }
818     }
819     myGlContext->SetCullBackFaces (toSuppressBackFaces);
820   }
821
822   if (myAspectFaceSet->Aspect() == myAspectFaceApplied
823    && myToHighlight == myAspectFaceAppliedWithHL)
824   {
825     return myAspectFaceSet;
826   }
827   myAspectFaceAppliedWithHL = myToHighlight;
828
829 #if !defined(GL_ES_VERSION_2_0)
830   const Aspect_InteriorStyle anIntstyle = myAspectFaceSet->Aspect()->InteriorStyle();
831   if (myAspectFaceApplied.IsNull()
832    || myAspectFaceApplied->InteriorStyle() != anIntstyle)
833   {
834     switch (anIntstyle)
835     {
836       case Aspect_IS_EMPTY:
837       case Aspect_IS_HOLLOW:
838       {
839         glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
840         break;
841       }
842       case Aspect_IS_HATCH:
843       {
844         glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
845         myLineAttribs->SetTypeOfHatch (!myAspectFaceApplied.IsNull() ? myAspectFaceApplied->HatchStyle() : Aspect_HS_SOLID);
846         break;
847       }
848       case Aspect_IS_SOLID:
849       case Aspect_IS_HIDDENLINE:
850       {
851         glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
852         if (myGlContext->core11 != NULL)
853         {
854           glDisable (GL_POLYGON_STIPPLE);
855         }
856         break;
857       }
858       case Aspect_IS_POINT:
859       {
860         glPolygonMode (GL_FRONT_AND_BACK, GL_POINT);
861         break;
862       }
863     }
864   }
865
866   if (anIntstyle == Aspect_IS_HATCH)
867   {
868     const Aspect_HatchStyle hatchstyle = myAspectFaceSet->Aspect()->HatchStyle();
869     if (myAspectFaceApplied.IsNull()
870      || myAspectFaceApplied->HatchStyle() != hatchstyle)
871     {
872       myLineAttribs->SetTypeOfHatch (hatchstyle);
873     }
874   }
875 #endif
876
877   // Aspect_POM_None means: do not change current settings
878   if ((myAspectFaceSet->Aspect()->PolygonOffset().Mode & Aspect_POM_None) != Aspect_POM_None)
879   {
880     if (myPolygonOffsetApplied.Mode   != myAspectFaceSet->Aspect()->PolygonOffset().Mode
881      || myPolygonOffsetApplied.Factor != myAspectFaceSet->Aspect()->PolygonOffset().Factor
882      || myPolygonOffsetApplied.Units  != myAspectFaceSet->Aspect()->PolygonOffset().Units)
883     {
884       SetPolygonOffset (myAspectFaceSet->Aspect()->PolygonOffset());
885     }
886   }
887
888   updateMaterial (TEL_FRONT_MATERIAL);
889   if (myAspectFaceSet->Aspect()->Distinguish())
890   {
891     updateMaterial (TEL_BACK_MATERIAL);
892   }
893
894   if (myAspectFaceSet->Aspect()->ToMapTexture())
895   {
896     EnableTexture (myAspectFaceSet->TextureRes (myGlContext),
897                    myAspectFaceSet->TextureParams());
898   }
899   else
900   {
901     if (!myEnvironmentTexture.IsNull())
902     {
903       EnableTexture (myEnvironmentTexture,
904                      myEnvironmentTexture->GetParams());
905     }
906     else
907     {
908       DisableTexture();
909     }
910   }
911
912   myAspectFaceApplied = myAspectFaceSet->Aspect();
913   return myAspectFaceSet;
914 }
915
916 //=======================================================================
917 //function : SetPolygonOffset
918 //purpose  :
919 //=======================================================================
920 void OpenGl_Workspace::SetPolygonOffset (const Graphic3d_PolygonOffset& theParams)
921 {
922   myPolygonOffsetApplied = theParams;
923
924   if ((theParams.Mode & Aspect_POM_Fill) == Aspect_POM_Fill)
925   {
926     glEnable (GL_POLYGON_OFFSET_FILL);
927   }
928   else
929   {
930     glDisable (GL_POLYGON_OFFSET_FILL);
931   }
932
933 #if !defined(GL_ES_VERSION_2_0)
934   if ((theParams.Mode & Aspect_POM_Line) == Aspect_POM_Line)
935   {
936     glEnable (GL_POLYGON_OFFSET_LINE);
937   }
938   else
939   {
940     glDisable (GL_POLYGON_OFFSET_LINE);
941   }
942
943   if ((theParams.Mode & Aspect_POM_Point) == Aspect_POM_Point)
944   {
945     glEnable (GL_POLYGON_OFFSET_POINT);
946   }
947   else
948   {
949     glDisable (GL_POLYGON_OFFSET_POINT);
950   }
951 #endif
952   glPolygonOffset (theParams.Factor, theParams.Units);
953 }
954
955 // =======================================================================
956 // function : ApplyAspectMarker
957 // purpose  :
958 // =======================================================================
959 const OpenGl_AspectMarker* OpenGl_Workspace::ApplyAspectMarker()
960 {
961   if (myAspectMarkerSet->Aspect() != myAspectMarkerApplied)
962   {
963     if (myAspectMarkerApplied.IsNull()
964     || (myAspectMarkerSet->Aspect()->Scale() != myAspectMarkerApplied->Scale()))
965     {
966     #if !defined(GL_ES_VERSION_2_0)
967       glPointSize (myAspectMarkerSet->Aspect()->Scale());
968     #ifdef HAVE_GL2PS
969       gl2psPointSize (myAspectMarkerSet->Aspect()->Scale());
970     #endif
971     #endif
972     }
973     myAspectMarkerApplied = myAspectMarkerSet->Aspect();
974   }
975   return myAspectMarkerSet;
976 }
977
978 // =======================================================================
979 // function : Width
980 // purpose  :
981 // =======================================================================
982 Standard_Integer OpenGl_Workspace::Width()  const
983 {
984   return !myView->GlWindow().IsNull() ? myView->GlWindow()->Width() : 0;
985 }
986
987 // =======================================================================
988 // function : Height
989 // purpose  :
990 // =======================================================================
991 Standard_Integer OpenGl_Workspace::Height() const
992 {
993   return !myView->GlWindow().IsNull() ? myView->GlWindow()->Height() : 0;
994 }
995
996 // =======================================================================
997 // function : UseGLLight
998 // purpose  :
999 // =======================================================================
1000 Standard_Boolean OpenGl_Workspace::UseGLLight() const
1001 {
1002   return myView->IsGLLightEnabled();
1003 }
1004
1005 // =======================================================================
1006 // function : IsCullingEnabled
1007 // purpose  :
1008 // =======================================================================
1009 Standard_Boolean OpenGl_Workspace::IsCullingEnabled() const
1010 {
1011   return myView->IsCullingEnabled();
1012 }
1013
1014 // =======================================================================
1015 // function : FBOCreate
1016 // purpose  :
1017 // =======================================================================
1018 Handle(OpenGl_FrameBuffer) OpenGl_Workspace::FBOCreate (const Standard_Integer theWidth,
1019                                                         const Standard_Integer theHeight)
1020 {
1021   // activate OpenGL context
1022   if (!Activate())
1023     return Handle(OpenGl_FrameBuffer)();
1024
1025   DisableTexture();
1026
1027   // create the FBO
1028   const Handle(OpenGl_Context)& aCtx = GetGlContext();
1029   Handle(OpenGl_FrameBuffer) aFrameBuffer = new OpenGl_FrameBuffer();
1030   if (!aFrameBuffer->Init (aCtx, theWidth, theHeight, GL_RGBA8, GL_DEPTH24_STENCIL8, 0))
1031   {
1032     aFrameBuffer->Release (aCtx.operator->());
1033     return Handle(OpenGl_FrameBuffer)();
1034   }
1035   return aFrameBuffer;
1036 }
1037
1038 // =======================================================================
1039 // function : FBORelease
1040 // purpose  :
1041 // =======================================================================
1042 void OpenGl_Workspace::FBORelease (Handle(OpenGl_FrameBuffer)& theFbo)
1043 {
1044   // activate OpenGL context
1045   if (!Activate()
1046    || theFbo.IsNull())
1047   {
1048     return;
1049   }
1050
1051   theFbo->Release (GetGlContext().operator->());
1052   theFbo.Nullify();
1053 }
1054
1055 inline bool getDataFormat (const Image_PixMap& theData,
1056                            GLenum&             thePixelFormat,
1057                            GLenum&             theDataType)
1058 {
1059   thePixelFormat = GL_RGB;
1060   theDataType    = GL_UNSIGNED_BYTE;
1061   switch (theData.Format())
1062   {
1063   #if !defined(GL_ES_VERSION_2_0)
1064     case Image_PixMap::ImgGray:
1065       thePixelFormat = GL_DEPTH_COMPONENT;
1066       theDataType    = GL_UNSIGNED_BYTE;
1067       return true;
1068     case Image_PixMap::ImgGrayF:
1069       thePixelFormat = GL_DEPTH_COMPONENT;
1070       theDataType    = GL_FLOAT;
1071       return true;
1072     case Image_PixMap::ImgBGR:
1073       thePixelFormat = GL_BGR;
1074       theDataType    = GL_UNSIGNED_BYTE;
1075       return true;
1076     case Image_PixMap::ImgBGRA:
1077     case Image_PixMap::ImgBGR32:
1078       thePixelFormat = GL_BGRA;
1079       theDataType    = GL_UNSIGNED_BYTE;
1080       return true;
1081     case Image_PixMap::ImgBGRF:
1082       thePixelFormat = GL_BGR;
1083       theDataType    = GL_FLOAT;
1084       return true;
1085     case Image_PixMap::ImgBGRAF:
1086       thePixelFormat = GL_BGRA;
1087       theDataType    = GL_FLOAT;
1088       return true;
1089   #else
1090     case Image_PixMap::ImgGray:
1091     case Image_PixMap::ImgGrayF:
1092     case Image_PixMap::ImgBGR:
1093     case Image_PixMap::ImgBGRA:
1094     case Image_PixMap::ImgBGR32:
1095     case Image_PixMap::ImgBGRF:
1096     case Image_PixMap::ImgBGRAF:
1097       return false;
1098   #endif
1099     case Image_PixMap::ImgRGB:
1100       thePixelFormat = GL_RGB;
1101       theDataType    = GL_UNSIGNED_BYTE;
1102       return true;
1103     case Image_PixMap::ImgRGBA:
1104     case Image_PixMap::ImgRGB32:
1105       thePixelFormat = GL_RGBA;
1106       theDataType    = GL_UNSIGNED_BYTE;
1107       return true;
1108     case Image_PixMap::ImgRGBF:
1109       thePixelFormat = GL_RGB;
1110       theDataType    = GL_FLOAT;
1111       return true;
1112     case Image_PixMap::ImgRGBAF:
1113       thePixelFormat = GL_RGBA;
1114       theDataType    = GL_FLOAT;
1115       return true;
1116     case Image_PixMap::ImgAlpha:
1117     case Image_PixMap::ImgAlphaF:
1118       return false; // GL_ALPHA is no more supported in core context
1119     case Image_PixMap::ImgUNKNOWN:
1120       return false;
1121   }
1122   return false;
1123 }
1124
1125 // =======================================================================
1126 // function : getAligned
1127 // purpose  :
1128 // =======================================================================
1129 inline Standard_Size getAligned (const Standard_Size theNumber,
1130                                  const Standard_Size theAlignment)
1131 {
1132   return theNumber + theAlignment - 1 - (theNumber - 1) % theAlignment;
1133 }
1134
1135 // =======================================================================
1136 // function : BufferDump
1137 // purpose  :
1138 // =======================================================================
1139 Standard_Boolean OpenGl_Workspace::BufferDump (const Handle(OpenGl_FrameBuffer)& theFbo,
1140                                                Image_PixMap&                     theImage,
1141                                                const Graphic3d_BufferType&       theBufferType)
1142 {
1143   GLenum aFormat, aType;
1144   if (theImage.IsEmpty()
1145    || !getDataFormat (theImage, aFormat, aType)
1146    || !Activate())
1147   {
1148     return Standard_False;
1149   }
1150 #if !defined(GL_ES_VERSION_2_0)
1151   GLint aReadBufferPrev = GL_BACK;
1152   if (theBufferType == Graphic3d_BT_Depth
1153    && aFormat != GL_DEPTH_COMPONENT)
1154   {
1155     return Standard_False;
1156   }
1157 #else
1158   (void )theBufferType;
1159 #endif
1160
1161   // bind FBO if used
1162   if (!theFbo.IsNull() && theFbo->IsValid())
1163   {
1164     theFbo->BindBuffer (GetGlContext());
1165   }
1166   else
1167   {
1168   #if !defined(GL_ES_VERSION_2_0)
1169     glGetIntegerv (GL_READ_BUFFER, &aReadBufferPrev);
1170     GLint aDrawBufferPrev = GL_BACK;
1171     glGetIntegerv (GL_DRAW_BUFFER, &aDrawBufferPrev);
1172     glReadBuffer (aDrawBufferPrev);
1173   #endif
1174   }
1175
1176   // setup alignment
1177   const GLint anAligment   = Min (GLint(theImage.MaxRowAligmentBytes()), 8); // limit to 8 bytes for OpenGL
1178   glPixelStorei (GL_PACK_ALIGNMENT, anAligment);
1179   bool isBatchCopy = !theImage.IsTopDown();
1180
1181   const GLint   anExtraBytes       = GLint(theImage.RowExtraBytes());
1182   GLint         aPixelsWidth       = GLint(theImage.SizeRowBytes() / theImage.SizePixelBytes());
1183   Standard_Size aSizeRowBytesEstim = getAligned (theImage.SizePixelBytes() * aPixelsWidth, anAligment);
1184   if (anExtraBytes < anAligment)
1185   {
1186     aPixelsWidth = 0;
1187   }
1188   else if (aSizeRowBytesEstim != theImage.SizeRowBytes())
1189   {
1190     aPixelsWidth = 0;
1191     isBatchCopy  = false;
1192   }
1193 #if !defined(GL_ES_VERSION_2_0)
1194   glPixelStorei (GL_PACK_ROW_LENGTH, aPixelsWidth);
1195 #else
1196   if (aPixelsWidth != 0)
1197   {
1198     isBatchCopy = false;
1199   }
1200 #endif
1201
1202   if (!isBatchCopy)
1203   {
1204     // copy row by row
1205     for (Standard_Size aRow = 0; aRow < theImage.SizeY(); ++aRow)
1206     {
1207       // Image_PixMap rows indexation always starts from the upper corner
1208       // while order in memory depends on the flag and processed by ChangeRow() method
1209       glReadPixels (0, GLint(theImage.SizeY() - aRow - 1), GLsizei (theImage.SizeX()), 1, aFormat, aType, theImage.ChangeRow (aRow));
1210     }
1211   }
1212   else
1213   {
1214     glReadPixels (0, 0, GLsizei (theImage.SizeX()), GLsizei (theImage.SizeY()), aFormat, aType, theImage.ChangeData());
1215   }
1216
1217   glPixelStorei (GL_PACK_ALIGNMENT,  1);
1218 #if !defined(GL_ES_VERSION_2_0)
1219   glPixelStorei (GL_PACK_ROW_LENGTH, 0);
1220 #endif
1221
1222   if (!theFbo.IsNull() && theFbo->IsValid())
1223   {
1224     theFbo->UnbindBuffer (GetGlContext());
1225   }
1226   else
1227   {
1228   #if !defined(GL_ES_VERSION_2_0)
1229     glReadBuffer (aReadBufferPrev);
1230   #endif
1231   }
1232   return Standard_True;
1233 }
1234
1235 // =======================================================================
1236 // function : CanRender
1237 // purpose  :
1238 // =======================================================================
1239 Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
1240 {
1241   Standard_Boolean aPrevFilterResult = Standard_True;
1242   if (!myPrevRenderFilter.IsNull())
1243   {
1244     aPrevFilterResult = myPrevRenderFilter->CanRender (theElement);
1245   }
1246   return aPrevFilterResult &&
1247     !OpenGl_Raytrace::IsRaytracedElement (theElement);
1248 }