0028811: Visualization - merge texturing support into AIS_Shape class and get rid...
[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_ShaderManager.hxx>
31 #include <OpenGl_Texture.hxx>
32 #include <OpenGl_View.hxx>
33 #include <OpenGl_Window.hxx>
34
35 #include <Graphic3d_TextureParams.hxx>
36 #include <Graphic3d_TransformUtils.hxx>
37 #include <NCollection_AlignedAllocator.hxx>
38
39 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Workspace,Standard_Transient)
40 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter,OpenGl_RenderFilter)
41
42 #ifdef HAVE_GL2PS
43   #include <gl2ps.h>
44   /* OCC22216 NOTE: linker dependency can be switched off by undefining macro.
45      Pragma comment for gl2ps.lib is defined only here. */
46   #ifdef _MSC_VER
47   #pragma comment( lib, "gl2ps.lib" )
48   #endif
49 #endif
50
51 namespace
52 {
53   static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
54   static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
55
56   static const OpenGl_AspectLine myDefaultAspectLine;
57   static const OpenGl_AspectFace myDefaultAspectFace;
58   static const OpenGl_AspectMarker myDefaultAspectMarker;
59   static const OpenGl_AspectText myDefaultAspectText;
60
61   static const OpenGl_Matrix myDefaultMatrix =
62   {
63     {{ 1.0F, 0.0F, 0.0F, 0.0F },
64      { 0.0F, 1.0F, 0.0F, 0.0F },
65      { 0.0F, 0.0F, 1.0F, 0.0F },
66      { 0.0F, 0.0F, 0.0F, 1.0F }}
67   };
68
69 }
70
71 // =======================================================================
72 // function : Init
73 // purpose  :
74 // =======================================================================
75 void OpenGl_Material::Init (const Graphic3d_MaterialAspect& theMat,
76                             const Quantity_Color&           theInteriorColor)
77 {
78   const bool isPhysic = theMat.MaterialType (Graphic3d_MATERIAL_PHYSIC);
79   ChangeShine()        = 128.0f * theMat.Shininess();
80   ChangeTransparency() = theMat.Alpha();
81
82   // ambient component
83   if (theMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
84   {
85     const OpenGl_Vec3& aSrcAmb = isPhysic ? theMat.AmbientColor() : theInteriorColor;
86     Ambient = OpenGl_Vec4 (aSrcAmb * theMat.Ambient(), 1.0f);
87   }
88   else
89   {
90     Ambient = THE_BLACK_COLOR;
91   }
92
93   // diffusion component
94   if (theMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
95   {
96     const OpenGl_Vec3& aSrcDif = isPhysic ? theMat.DiffuseColor() : theInteriorColor;
97     Diffuse = OpenGl_Vec4 (aSrcDif * theMat.Diffuse(), 1.0f);
98   }
99   else
100   {
101     Diffuse = THE_BLACK_COLOR;
102   }
103
104   // specular component
105   if (theMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
106   {
107     const OpenGl_Vec3& aSrcSpe = isPhysic ? (const OpenGl_Vec3& )theMat.SpecularColor() : THE_WHITE_COLOR.rgb();
108     Specular = OpenGl_Vec4 (aSrcSpe * theMat.Specular(), 1.0f);
109   }
110   else
111   {
112     Specular = THE_BLACK_COLOR;
113   }
114
115   // emission component
116   if (theMat.ReflectionMode (Graphic3d_TOR_EMISSION))
117   {
118     const OpenGl_Vec3& aSrcEms = isPhysic ? theMat.EmissiveColor() : theInteriorColor;
119     Emission = OpenGl_Vec4 (aSrcEms * theMat.Emissive(), 1.0f);
120   }
121   else
122   {
123     Emission = THE_BLACK_COLOR;
124   }
125 }
126
127 // =======================================================================
128 // function : OpenGl_Workspace
129 // purpose  :
130 // =======================================================================
131 OpenGl_Workspace::OpenGl_Workspace (OpenGl_View* theView, const Handle(OpenGl_Window)& theWindow)
132 : myView (theView),
133   myWindow (theWindow),
134   myGlContext (!theWindow.IsNull() ? theWindow->GetGlContext() : NULL),
135   myUseZBuffer    (Standard_True),
136   myUseDepthWrite (Standard_True),
137   //
138   myAspectLineSet (&myDefaultAspectLine),
139   myAspectFaceSet (&myDefaultAspectFace),
140   myAspectMarkerSet (&myDefaultAspectMarker),
141   myAspectTextSet (&myDefaultAspectText),
142   //
143   ViewMatrix_applied (&myDefaultMatrix),
144   StructureMatrix_applied (&myDefaultMatrix),
145   myToAllowFaceCulling (false),
146   myModelViewMatrix (myDefaultMatrix)
147 {
148   if (!myGlContext.IsNull() && myGlContext->MakeCurrent())
149   {
150     myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
151
152     // General initialization of the context
153   #if !defined(GL_ES_VERSION_2_0)
154     if (myGlContext->core11 != NULL)
155     {
156       // Eviter d'avoir les faces mal orientees en noir.
157       // Pourrait etre utiliser pour detecter les problemes d'orientation
158       glLightModeli ((GLenum )GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
159
160       // Optimisation pour le Fog et l'antialiasing
161       glHint (GL_FOG_HINT,            GL_FASTEST);
162       glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
163     }
164
165     glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
166     glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
167   #endif
168   }
169
170   myDefaultCappingAlgoFilter = new OpenGl_CappingAlgoFilter();
171
172   myNoneCulling .Aspect()->SetSuppressBackFaces (false);
173   myNoneCulling .Aspect()->SetDrawEdges (false);
174   myFrontCulling.Aspect()->SetSuppressBackFaces (true);
175   myFrontCulling.Aspect()->SetDrawEdges (false);
176 }
177
178 // =======================================================================
179 // function : Activate
180 // purpose  :
181 // =======================================================================
182 Standard_Boolean OpenGl_Workspace::Activate()
183 {
184   if (myWindow.IsNull() || !myWindow->Activate())
185   {
186     return Standard_False;
187   }
188
189   ViewMatrix_applied      = &myDefaultMatrix;
190   StructureMatrix_applied = &myDefaultMatrix;
191
192   ResetAppliedAspect();
193
194   // reset state for safety
195   myGlContext->BindProgram (Handle(OpenGl_ShaderProgram)());
196   if (myGlContext->core20fwd != NULL)
197   {
198     myGlContext->core20fwd->glUseProgram (OpenGl_ShaderProgram::NO_PROGRAM);
199   }
200   myGlContext->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
201   return Standard_True;
202 }
203
204 //=======================================================================
205 //function : ResetAppliedAspect
206 //purpose  : Sets default values of GL parameters in accordance with default aspects
207 //=======================================================================
208 void OpenGl_Workspace::ResetAppliedAspect()
209 {
210   myGlContext->BindDefaultVao();
211
212   myHighlightStyle.Nullify();
213   myToAllowFaceCulling  = false;
214   myAspectLineSet       = &myDefaultAspectLine;
215   myAspectFaceSet       = &myDefaultAspectFace;
216   myAspectFaceApplied.Nullify();
217   myAspectMarkerSet     = &myDefaultAspectMarker;
218   myAspectMarkerApplied.Nullify();
219   myAspectTextSet       = &myDefaultAspectText;
220   myPolygonOffsetApplied= Graphic3d_PolygonOffset();
221
222   ApplyAspectLine();
223   ApplyAspectFace();
224   ApplyAspectMarker();
225   ApplyAspectText();
226
227   myGlContext->SetTypeOfLine (myDefaultAspectLine.Aspect()->Type());
228   myGlContext->SetLineWidth  (myDefaultAspectLine.Aspect()->Width());
229 }
230
231 // =======================================================================
232 // function : DisableTexture
233 // purpose  :
234 // =======================================================================
235 Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
236 {
237   if (myTextureBound.IsNull())
238   {
239     return myTextureBound;
240   }
241
242   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
243   if (!aSampler.IsNull())
244   {
245     aSampler->Unbind (*myGlContext);
246   }
247
248 #if !defined(GL_ES_VERSION_2_0)
249   // reset texture matrix because some code may expect it is identity
250   if (myGlContext->core11 != NULL)
251   {
252     GLint aMatrixMode = GL_TEXTURE;
253     glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
254     glMatrixMode (GL_TEXTURE);
255     glLoadIdentity();
256     glMatrixMode (aMatrixMode);
257   }
258 #endif
259
260   myTextureBound->Unbind (myGlContext);
261   switch (myTextureBound->GetTarget())
262   {
263   #if !defined(GL_ES_VERSION_2_0)
264     case GL_TEXTURE_1D:
265     {
266       if (myGlContext->core11 != NULL)
267       {
268         if (myTextureBound->GetParams()->GenMode() != GL_NONE)
269         {
270           glDisable (GL_TEXTURE_GEN_S);
271         }
272         glDisable (GL_TEXTURE_1D);
273       }
274       break;
275     }
276   #endif
277     case GL_TEXTURE_2D:
278     {
279     #if !defined(GL_ES_VERSION_2_0)
280       if (myGlContext->core11 != NULL)
281       {
282         if (myTextureBound->GetParams()->GenMode() != GL_NONE)
283         {
284           glDisable (GL_TEXTURE_GEN_S);
285           glDisable (GL_TEXTURE_GEN_T);
286           if (myTextureBound->GetParams()->GenMode() == Graphic3d_TOTM_SPRITE)
287           {
288             glDisable (GL_POINT_SPRITE);
289           }
290         }
291         glDisable (GL_TEXTURE_2D);
292       }
293     #endif
294       break;
295     }
296     default: break;
297   }
298
299   Handle(OpenGl_Texture) aPrevTexture = myTextureBound;
300   myTextureBound.Nullify();
301   return aPrevTexture;
302 }
303
304 // =======================================================================
305 // function : setTextureParams
306 // purpose  :
307 // =======================================================================
308 void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&                theTexture,
309                                          const Handle(Graphic3d_TextureParams)& theParams)
310 {
311   const Handle(Graphic3d_TextureParams)& aParams = theParams.IsNull() ? theTexture->GetParams() : theParams;
312   if (aParams.IsNull())
313   {
314     return;
315   }
316
317 #if !defined(GL_ES_VERSION_2_0)
318   if (myGlContext->core11 != NULL)
319   {
320     GLint anEnvMode = GL_MODULATE; // lighting mode
321     if (!aParams->IsModulate())
322     {
323       anEnvMode = GL_DECAL;
324       if (theTexture->GetFormat() == GL_ALPHA
325        || theTexture->GetFormat() == GL_LUMINANCE)
326       {
327         anEnvMode = GL_REPLACE;
328       }
329     }
330
331     // setup generation of texture coordinates
332     switch (aParams->GenMode())
333     {
334       case Graphic3d_TOTM_OBJECT:
335       {
336         glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
337         glTexGenfv (GL_S, GL_OBJECT_PLANE,     aParams->GenPlaneS().GetData());
338         if (theTexture->GetTarget() != GL_TEXTURE_1D)
339         {
340           glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
341           glTexGenfv (GL_T, GL_OBJECT_PLANE,     aParams->GenPlaneT().GetData());
342         }
343         break;
344       }
345       case Graphic3d_TOTM_SPHERE:
346       {
347         glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
348         if (theTexture->GetTarget() != GL_TEXTURE_1D)
349         {
350           glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
351         }
352         break;
353       }
354       case Graphic3d_TOTM_EYE:
355       {
356         myGlContext->WorldViewState.Push();
357
358         myGlContext->WorldViewState.SetIdentity();
359         myGlContext->ApplyWorldViewMatrix();
360
361         glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
362         glTexGenfv (GL_S, GL_EYE_PLANE,        aParams->GenPlaneS().GetData());
363
364         if (theTexture->GetTarget() != GL_TEXTURE_1D)
365         {
366           glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
367           glTexGenfv (GL_T, GL_EYE_PLANE,        aParams->GenPlaneT().GetData());
368         }
369
370         myGlContext->WorldViewState.Pop();
371
372         break;
373       }
374       case Graphic3d_TOTM_SPRITE:
375       {
376         if (myGlContext->core20fwd != NULL)
377         {
378           glEnable  (GL_POINT_SPRITE);
379           glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
380           anEnvMode = GL_REPLACE;
381         }
382         break;
383       }
384       case Graphic3d_TOTM_MANUAL:
385       default: break;
386     }
387
388     // setup lighting
389     glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, anEnvMode);
390   }
391 #endif
392
393   // get active sampler object to override default texture parameters
394   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
395
396   // setup texture filtering and wrapping
397   //if (theTexture->GetParams() != theParams)
398   const GLenum aFilter   = (aParams->Filter() == Graphic3d_TOTF_NEAREST) ? GL_NEAREST : GL_LINEAR;
399   const GLenum aWrapMode = aParams->IsRepeat() ? GL_REPEAT : myGlContext->TextureWrapClamp();
400   switch (theTexture->GetTarget())
401   {
402   #if !defined(GL_ES_VERSION_2_0)
403     case GL_TEXTURE_1D:
404     {
405       if (aSampler.IsNull() || !aSampler->IsValid())
406       {
407         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, aFilter);
408         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, aFilter);
409         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_WRAP_S,     aWrapMode);
410       }
411       else
412       {
413         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAG_FILTER, aFilter);
414         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MIN_FILTER, aFilter);
415         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_S,     aWrapMode);
416       }
417
418       break;
419     }
420   #endif
421     case GL_TEXTURE_2D:
422     {
423       GLenum aFilterMin = aFilter;
424       if (theTexture->HasMipmaps())
425       {
426         aFilterMin = GL_NEAREST_MIPMAP_NEAREST;
427         if (aParams->Filter() == Graphic3d_TOTF_BILINEAR)
428         {
429           aFilterMin = GL_LINEAR_MIPMAP_NEAREST;
430         }
431         else if (aParams->Filter() == Graphic3d_TOTF_TRILINEAR)
432         {
433           aFilterMin = GL_LINEAR_MIPMAP_LINEAR;
434         }
435
436         if (myGlContext->extAnis)
437         {
438           // setup degree of anisotropy filter
439           const GLint aMaxDegree = myGlContext->MaxDegreeOfAnisotropy();
440           GLint aDegree;
441           switch (aParams->AnisoFilter())
442           {
443             case Graphic3d_LOTA_QUALITY:
444             {
445               aDegree = aMaxDegree;
446               break;
447             }
448             case Graphic3d_LOTA_MIDDLE:
449             {
450               aDegree = (aMaxDegree <= 4) ? 2 : (aMaxDegree / 2);
451               break;
452             }
453             case Graphic3d_LOTA_FAST:
454             {
455               aDegree = 2;
456               break;
457             }
458             case Graphic3d_LOTA_OFF:
459             default:
460             {
461               aDegree = 1;
462               break;
463             }
464           }
465
466           if (aSampler.IsNull() || !aSampler->IsValid())
467           {
468             glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aDegree);
469           }
470           else
471           {
472             aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAX_ANISOTROPY_EXT, aDegree);
473           }
474         }
475       }
476
477       if (aSampler.IsNull() || !aSampler->IsValid())
478       {
479         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterMin);
480         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilter);
481         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,     aWrapMode);
482         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,     aWrapMode);
483       }
484       else
485       {
486         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MIN_FILTER, aFilterMin);
487         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAG_FILTER, aFilter);
488         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_S,     aWrapMode);
489         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_T,     aWrapMode);
490       }
491
492       break;
493     }
494     default: break;
495   }
496
497   switch (theTexture->GetTarget())
498   {
499   #if !defined(GL_ES_VERSION_2_0)
500     case GL_TEXTURE_1D:
501     {
502       if (myGlContext->core11 != NULL)
503       {
504         if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
505         {
506           glEnable (GL_TEXTURE_GEN_S);
507         }
508         glEnable (GL_TEXTURE_1D);
509       }
510       break;
511     }
512   #endif
513     case GL_TEXTURE_2D:
514     {
515     #if !defined(GL_ES_VERSION_2_0)
516       if (myGlContext->core11 != NULL)
517       {
518         if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
519         {
520           glEnable (GL_TEXTURE_GEN_S);
521           glEnable (GL_TEXTURE_GEN_T);
522         }
523         glEnable (GL_TEXTURE_2D);
524       }
525     #endif
526       break;
527     }
528     default: break;
529   }
530
531   theTexture->SetParams (aParams);
532 }
533
534 // =======================================================================
535 // function : EnableTexture
536 // purpose  :
537 // =======================================================================
538 Handle(OpenGl_Texture) OpenGl_Workspace::EnableTexture (const Handle(OpenGl_Texture)&          theTexture,
539                                                         const Handle(Graphic3d_TextureParams)& theParams)
540 {
541   if (theTexture.IsNull() || !theTexture->IsValid())
542   {
543     return DisableTexture();
544   }
545
546   if (myTextureBound == theTexture
547    && (theParams.IsNull() || theParams == theTexture->GetParams()))
548   {
549     // already bound
550     return myTextureBound;
551   }
552
553   Handle(OpenGl_Texture) aPrevTexture = DisableTexture();
554   myTextureBound = theTexture;
555   myTextureBound->Bind (myGlContext);
556   setTextureParams (myTextureBound, theParams);
557
558   // If custom sampler object is available it will be
559   // used for overriding default texture parameters
560   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
561
562   if (!aSampler.IsNull() && aSampler->IsValid())
563   {
564     aSampler->Bind (*myGlContext);
565   }
566
567   return aPrevTexture;
568 }
569
570 // =======================================================================
571 // function : SetAspectLine
572 // purpose  :
573 // =======================================================================
574 const OpenGl_AspectLine* OpenGl_Workspace::SetAspectLine (const OpenGl_AspectLine* theAspect)
575 {
576   const OpenGl_AspectLine* aPrevAspectLine = myAspectLineSet;
577   myAspectLineSet = theAspect;
578   return aPrevAspectLine;
579 }
580
581 // =======================================================================
582 // function : SetAspectFace
583 // purpose  :
584 // =======================================================================
585 const OpenGl_AspectFace * OpenGl_Workspace::SetAspectFace (const OpenGl_AspectFace* theAspect)
586 {
587   const OpenGl_AspectFace* aPrevAspectFace = myAspectFaceSet;
588   myAspectFaceSet = theAspect;
589   return aPrevAspectFace;
590 }
591
592 // =======================================================================
593 // function : SetAspectMarker
594 // purpose  :
595 // =======================================================================
596 const OpenGl_AspectMarker* OpenGl_Workspace::SetAspectMarker (const OpenGl_AspectMarker* theAspect)
597 {
598   const OpenGl_AspectMarker* aPrevAspectMarker = myAspectMarkerSet;
599   myAspectMarkerSet = theAspect;
600   return aPrevAspectMarker;
601 }
602
603 // =======================================================================
604 // function : SetAspectText
605 // purpose  :
606 // =======================================================================
607 const OpenGl_AspectText * OpenGl_Workspace::SetAspectText (const OpenGl_AspectText* theAspect)
608 {
609   const OpenGl_AspectText* aPrevAspectText = myAspectTextSet;
610   myAspectTextSet = theAspect;
611   return aPrevAspectText;
612 }
613
614 // =======================================================================
615 // function : ApplyAspectFace
616 // purpose  :
617 // =======================================================================
618 const OpenGl_AspectFace* OpenGl_Workspace::ApplyAspectFace()
619 {
620   if (myView->BackfacingModel() == Graphic3d_TOBM_AUTOMATIC)
621   {
622     // manage back face culling mode, disable culling when clipping is enabled
623     bool toSuppressBackFaces = myToAllowFaceCulling
624                             && myAspectFaceSet->Aspect()->ToSuppressBackFaces();
625     if (toSuppressBackFaces)
626     {
627       if (myGlContext->Clipping().IsClippingOrCappingOn()
628        || myAspectFaceSet->Aspect()->InteriorStyle() == Aspect_IS_HATCH)
629       {
630         toSuppressBackFaces = false;
631       }
632     }
633     if (toSuppressBackFaces)
634     {
635       if ((float )myAspectFaceSet->Aspect()->FrontMaterial().Transparency() != 0.0f)
636       {
637         // disable culling in case of translucent shading aspect
638         toSuppressBackFaces = false;
639       }
640     }
641     myGlContext->SetCullBackFaces (toSuppressBackFaces);
642   }
643
644   if (myAspectFaceSet->Aspect() == myAspectFaceApplied
645    && myHighlightStyle == myAspectFaceAppliedWithHL)
646   {
647     return myAspectFaceSet;
648   }
649   myAspectFaceAppliedWithHL = myHighlightStyle;
650
651 #if !defined(GL_ES_VERSION_2_0)
652   const Aspect_InteriorStyle anIntstyle = myAspectFaceSet->Aspect()->InteriorStyle();
653   if (myAspectFaceApplied.IsNull()
654    || myAspectFaceApplied->InteriorStyle() != anIntstyle)
655   {
656     switch (anIntstyle)
657     {
658       case Aspect_IS_EMPTY:
659       case Aspect_IS_HOLLOW:
660       {
661         myGlContext->SetPolygonMode (GL_LINE);
662         break;
663       }
664       case Aspect_IS_HATCH:
665       {
666         myGlContext->SetPolygonMode (GL_FILL);
667         myGlContext->SetPolygonHatchEnabled (true);
668         break;
669       }
670       case Aspect_IS_SOLID:
671       case Aspect_IS_HIDDENLINE:
672       {
673         myGlContext->SetPolygonMode (GL_FILL);
674         myGlContext->SetPolygonHatchEnabled (false);
675         break;
676       }
677       case Aspect_IS_POINT:
678       {
679         myGlContext->SetPolygonMode (GL_POINT);
680         break;
681       }
682     }
683   }
684
685   if (anIntstyle == Aspect_IS_HATCH)
686   {
687     myGlContext->SetPolygonHatchStyle (myAspectFaceSet->Aspect()->HatchStyle());
688   }
689 #endif
690
691   // Aspect_POM_None means: do not change current settings
692   if ((myAspectFaceSet->Aspect()->PolygonOffset().Mode & Aspect_POM_None) != Aspect_POM_None)
693   {
694     if (myPolygonOffsetApplied.Mode   != myAspectFaceSet->Aspect()->PolygonOffset().Mode
695      || myPolygonOffsetApplied.Factor != myAspectFaceSet->Aspect()->PolygonOffset().Factor
696      || myPolygonOffsetApplied.Units  != myAspectFaceSet->Aspect()->PolygonOffset().Units)
697     {
698       SetPolygonOffset (myAspectFaceSet->Aspect()->PolygonOffset());
699     }
700   }
701
702   // Case of hidden line
703   if (myAspectFaceSet->Aspect()->InteriorStyle() == Aspect_IS_HIDDENLINE)
704   {
705     // copy all values including line edge aspect
706     *myAspectFaceHl.Aspect().operator->() = *myAspectFaceSet->Aspect();
707     myAspectFaceHl.SetAspectEdge (myAspectFaceSet->AspectEdge());
708     myAspectFaceHl.Aspect()->SetInteriorColor (myView->BackgroundColor().GetRGB());
709     myAspectFaceHl.SetNoLighting (true);
710     myAspectFaceSet = &myAspectFaceHl;
711   }
712   else
713   {
714     myGlContext->SetShadingMaterial (myAspectFaceSet, myHighlightStyle);
715   }
716
717   if (myAspectFaceSet->Aspect()->ToMapTexture())
718   {
719     EnableTexture (myAspectFaceSet->TextureRes (myGlContext),
720                    myAspectFaceSet->TextureParams());
721   }
722   else
723   {
724     if (!myEnvironmentTexture.IsNull())
725     {
726       EnableTexture (myEnvironmentTexture,
727                      myEnvironmentTexture->GetParams());
728     }
729     else
730     {
731       DisableTexture();
732     }
733   }
734
735   myAspectFaceApplied = myAspectFaceSet->Aspect();
736   return myAspectFaceSet;
737 }
738
739 //=======================================================================
740 //function : SetPolygonOffset
741 //purpose  :
742 //=======================================================================
743 void OpenGl_Workspace::SetPolygonOffset (const Graphic3d_PolygonOffset& theParams)
744 {
745   myPolygonOffsetApplied = theParams;
746
747   if ((theParams.Mode & Aspect_POM_Fill) == Aspect_POM_Fill)
748   {
749     glEnable (GL_POLYGON_OFFSET_FILL);
750   }
751   else
752   {
753     glDisable (GL_POLYGON_OFFSET_FILL);
754   }
755
756 #if !defined(GL_ES_VERSION_2_0)
757   if ((theParams.Mode & Aspect_POM_Line) == Aspect_POM_Line)
758   {
759     glEnable (GL_POLYGON_OFFSET_LINE);
760   }
761   else
762   {
763     glDisable (GL_POLYGON_OFFSET_LINE);
764   }
765
766   if ((theParams.Mode & Aspect_POM_Point) == Aspect_POM_Point)
767   {
768     glEnable (GL_POLYGON_OFFSET_POINT);
769   }
770   else
771   {
772     glDisable (GL_POLYGON_OFFSET_POINT);
773   }
774 #endif
775   glPolygonOffset (theParams.Factor, theParams.Units);
776 }
777
778 // =======================================================================
779 // function : ApplyAspectMarker
780 // purpose  :
781 // =======================================================================
782 const OpenGl_AspectMarker* OpenGl_Workspace::ApplyAspectMarker()
783 {
784   if (myAspectMarkerSet->Aspect() != myAspectMarkerApplied)
785   {
786     if (myAspectMarkerApplied.IsNull()
787     || (myAspectMarkerSet->Aspect()->Scale() != myAspectMarkerApplied->Scale()))
788     {
789     #if !defined(GL_ES_VERSION_2_0)
790       glPointSize (myAspectMarkerSet->Aspect()->Scale());
791     #ifdef HAVE_GL2PS
792       gl2psPointSize (myAspectMarkerSet->Aspect()->Scale());
793     #endif
794     #endif
795     }
796     myAspectMarkerApplied = myAspectMarkerSet->Aspect();
797   }
798   return myAspectMarkerSet;
799 }
800
801 // =======================================================================
802 // function : Width
803 // purpose  :
804 // =======================================================================
805 Standard_Integer OpenGl_Workspace::Width()  const
806 {
807   return !myView->GlWindow().IsNull() ? myView->GlWindow()->Width() : 0;
808 }
809
810 // =======================================================================
811 // function : Height
812 // purpose  :
813 // =======================================================================
814 Standard_Integer OpenGl_Workspace::Height() const
815 {
816   return !myView->GlWindow().IsNull() ? myView->GlWindow()->Height() : 0;
817 }
818
819 // =======================================================================
820 // function : IsCullingEnabled
821 // purpose  :
822 // =======================================================================
823 Standard_Boolean OpenGl_Workspace::IsCullingEnabled() const
824 {
825   return myView->IsCullingEnabled();
826 }
827
828 // =======================================================================
829 // function : FBOCreate
830 // purpose  :
831 // =======================================================================
832 Handle(OpenGl_FrameBuffer) OpenGl_Workspace::FBOCreate (const Standard_Integer theWidth,
833                                                         const Standard_Integer theHeight)
834 {
835   // activate OpenGL context
836   if (!Activate())
837     return Handle(OpenGl_FrameBuffer)();
838
839   DisableTexture();
840
841   // create the FBO
842   const Handle(OpenGl_Context)& aCtx = GetGlContext();
843   Handle(OpenGl_FrameBuffer) aFrameBuffer = new OpenGl_FrameBuffer();
844   if (!aFrameBuffer->Init (aCtx, theWidth, theHeight, GL_RGBA8, GL_DEPTH24_STENCIL8, 0))
845   {
846     aFrameBuffer->Release (aCtx.operator->());
847     return Handle(OpenGl_FrameBuffer)();
848   }
849   return aFrameBuffer;
850 }
851
852 // =======================================================================
853 // function : FBORelease
854 // purpose  :
855 // =======================================================================
856 void OpenGl_Workspace::FBORelease (Handle(OpenGl_FrameBuffer)& theFbo)
857 {
858   // activate OpenGL context
859   if (!Activate()
860    || theFbo.IsNull())
861   {
862     return;
863   }
864
865   theFbo->Release (GetGlContext().operator->());
866   theFbo.Nullify();
867 }
868
869 // =======================================================================
870 // function : getAligned
871 // purpose  :
872 // =======================================================================
873 inline Standard_Size getAligned (const Standard_Size theNumber,
874                                  const Standard_Size theAlignment)
875 {
876   return theNumber + theAlignment - 1 - (theNumber - 1) % theAlignment;
877 }
878
879 template<typename T>
880 inline void convertRowFromRgba (T* theRgbRow,
881                                 const Image_ColorRGBA* theRgbaRow,
882                                 const Standard_Size theWidth)
883 {
884   for (Standard_Size aCol = 0; aCol < theWidth; ++aCol)
885   {
886     const Image_ColorRGBA& anRgba = theRgbaRow[aCol];
887     T& anRgb = theRgbRow[aCol];
888     anRgb.r() = anRgba.r();
889     anRgb.g() = anRgba.g();
890     anRgb.b() = anRgba.b();
891   }
892 }
893
894 // =======================================================================
895 // function : BufferDump
896 // purpose  :
897 // =======================================================================
898 Standard_Boolean OpenGl_Workspace::BufferDump (const Handle(OpenGl_FrameBuffer)& theFbo,
899                                                Image_PixMap&                     theImage,
900                                                const Graphic3d_BufferType&       theBufferType)
901 {
902   if (theImage.IsEmpty()
903   || !Activate())
904   {
905     return Standard_False;
906   }
907
908   GLenum aFormat = 0;
909   GLenum aType   = 0;
910   bool toSwapRgbaBgra = false;
911   bool toConvRgba2Rgb = false;
912   switch (theImage.Format())
913   {
914   #if !defined(GL_ES_VERSION_2_0)
915     case Image_Format_Gray:
916       aFormat = GL_DEPTH_COMPONENT;
917       aType   = GL_UNSIGNED_BYTE;
918       break;
919     case Image_Format_GrayF:
920       aFormat = GL_DEPTH_COMPONENT;
921       aType   = GL_FLOAT;
922       break;
923     case Image_Format_RGB:
924       aFormat = GL_RGB;
925       aType   = GL_UNSIGNED_BYTE;
926       break;
927     case Image_Format_BGR:
928       aFormat = GL_BGR;
929       aType   = GL_UNSIGNED_BYTE;
930       break;
931     case Image_Format_BGRA:
932     case Image_Format_BGR32:
933       aFormat = GL_BGRA;
934       aType   = GL_UNSIGNED_BYTE;
935       break;
936     case Image_Format_BGRF:
937       aFormat = GL_BGR;
938       aType   = GL_FLOAT;
939       break;
940     case Image_Format_BGRAF:
941       aFormat = GL_BGRA;
942       aType   = GL_FLOAT;
943       break;
944   #else
945     case Image_Format_Gray:
946     case Image_Format_GrayF:
947     case Image_Format_BGRF:
948     case Image_Format_BGRAF:
949       return Standard_False;
950     case Image_Format_BGRA:
951     case Image_Format_BGR32:
952       aFormat = GL_RGBA;
953       aType   = GL_UNSIGNED_BYTE;
954       toSwapRgbaBgra = true;
955       break;
956     case Image_Format_BGR:
957     case Image_Format_RGB:
958       aFormat = GL_RGBA;
959       aType   = GL_UNSIGNED_BYTE;
960       toConvRgba2Rgb = true;
961       break;
962   #endif
963     case Image_Format_RGBA:
964     case Image_Format_RGB32:
965       aFormat = GL_RGBA;
966       aType   = GL_UNSIGNED_BYTE;
967       break;
968     case Image_Format_RGBF:
969       aFormat = GL_RGB;
970       aType   = GL_FLOAT;
971       break;
972     case Image_Format_RGBAF:
973       aFormat = GL_RGBA;
974       aType   = GL_FLOAT;
975       break;
976     case Image_Format_Alpha:
977     case Image_Format_AlphaF:
978       return Standard_False; // GL_ALPHA is no more supported in core context
979     case Image_Format_UNKNOWN:
980       return Standard_False;
981   }
982
983   if (aFormat == 0)
984   {
985     return Standard_False;
986   }
987
988 #if !defined(GL_ES_VERSION_2_0)
989   GLint aReadBufferPrev = GL_BACK;
990   if (theBufferType == Graphic3d_BT_Depth
991    && aFormat != GL_DEPTH_COMPONENT)
992   {
993     return Standard_False;
994   }
995 #else
996   (void )theBufferType;
997 #endif
998
999   // bind FBO if used
1000   if (!theFbo.IsNull() && theFbo->IsValid())
1001   {
1002     theFbo->BindBuffer (GetGlContext());
1003   }
1004   else
1005   {
1006   #if !defined(GL_ES_VERSION_2_0)
1007     glGetIntegerv (GL_READ_BUFFER, &aReadBufferPrev);
1008     GLint aDrawBufferPrev = GL_BACK;
1009     glGetIntegerv (GL_DRAW_BUFFER, &aDrawBufferPrev);
1010     glReadBuffer (aDrawBufferPrev);
1011   #endif
1012   }
1013
1014   // setup alignment
1015   const GLint anAligment   = Min (GLint(theImage.MaxRowAligmentBytes()), 8); // limit to 8 bytes for OpenGL
1016   glPixelStorei (GL_PACK_ALIGNMENT, anAligment);
1017   bool isBatchCopy = !theImage.IsTopDown();
1018
1019   const GLint   anExtraBytes       = GLint(theImage.RowExtraBytes());
1020   GLint         aPixelsWidth       = GLint(theImage.SizeRowBytes() / theImage.SizePixelBytes());
1021   Standard_Size aSizeRowBytesEstim = getAligned (theImage.SizePixelBytes() * aPixelsWidth, anAligment);
1022   if (anExtraBytes < anAligment)
1023   {
1024     aPixelsWidth = 0;
1025   }
1026   else if (aSizeRowBytesEstim != theImage.SizeRowBytes())
1027   {
1028     aPixelsWidth = 0;
1029     isBatchCopy  = false;
1030   }
1031 #if !defined(GL_ES_VERSION_2_0)
1032   glPixelStorei (GL_PACK_ROW_LENGTH, aPixelsWidth);
1033 #else
1034   if (aPixelsWidth != 0)
1035   {
1036     isBatchCopy = false;
1037   }
1038 #endif
1039   if (toConvRgba2Rgb)
1040   {
1041     Handle(NCollection_BaseAllocator) anAlloc = new NCollection_AlignedAllocator (16);
1042     const Standard_Size aRowSize = theImage.SizeX() * 4;
1043     NCollection_Buffer aRowBuffer (anAlloc);
1044     if (!aRowBuffer.Allocate (aRowSize))
1045     {
1046       return Standard_False;
1047     }
1048
1049     for (Standard_Size aRow = 0; aRow < theImage.SizeY(); ++aRow)
1050     {
1051       // Image_PixMap rows indexation always starts from the upper corner
1052       // while order in memory depends on the flag and processed by ChangeRow() method
1053       glReadPixels (0, GLint(theImage.SizeY() - aRow - 1), GLsizei (theImage.SizeX()), 1, aFormat, aType, aRowBuffer.ChangeData());
1054       const Image_ColorRGBA* aRowDataRgba = (const Image_ColorRGBA* )aRowBuffer.Data();
1055       if (theImage.Format() == Image_Format_BGR)
1056       {
1057         convertRowFromRgba ((Image_ColorBGR* )theImage.ChangeRow (aRow), aRowDataRgba, theImage.SizeX());
1058       }
1059       else
1060       {
1061         convertRowFromRgba ((Image_ColorRGB* )theImage.ChangeRow (aRow), aRowDataRgba, theImage.SizeX());
1062       }
1063     }
1064   }
1065   else if (!isBatchCopy)
1066   {
1067     // copy row by row
1068     for (Standard_Size aRow = 0; aRow < theImage.SizeY(); ++aRow)
1069     {
1070       // Image_PixMap rows indexation always starts from the upper corner
1071       // while order in memory depends on the flag and processed by ChangeRow() method
1072       glReadPixels (0, GLint(theImage.SizeY() - aRow - 1), GLsizei (theImage.SizeX()), 1, aFormat, aType, theImage.ChangeRow (aRow));
1073     }
1074   }
1075   else
1076   {
1077     glReadPixels (0, 0, GLsizei (theImage.SizeX()), GLsizei (theImage.SizeY()), aFormat, aType, theImage.ChangeData());
1078   }
1079   const bool hasErrors = myGlContext->ResetErrors (true);
1080
1081   glPixelStorei (GL_PACK_ALIGNMENT,  1);
1082 #if !defined(GL_ES_VERSION_2_0)
1083   glPixelStorei (GL_PACK_ROW_LENGTH, 0);
1084 #endif
1085
1086   if (!theFbo.IsNull() && theFbo->IsValid())
1087   {
1088     theFbo->UnbindBuffer (GetGlContext());
1089   }
1090   else
1091   {
1092   #if !defined(GL_ES_VERSION_2_0)
1093     glReadBuffer (aReadBufferPrev);
1094   #endif
1095   }
1096
1097   if (toSwapRgbaBgra)
1098   {
1099     Image_PixMap::SwapRgbaBgra (theImage);
1100   }
1101
1102   return !hasErrors;
1103 }
1104
1105 // =======================================================================
1106 // function : ShouldRender
1107 // purpose  :
1108 // =======================================================================
1109 Standard_Boolean OpenGl_RaytraceFilter::ShouldRender (const Handle(OpenGl_Workspace)& theWorkspace,
1110                                                       const OpenGl_Element*           theElement)
1111 {
1112   Standard_Boolean aPrevFilterResult = Standard_True;
1113   if (!myPrevRenderFilter.IsNull())
1114   {
1115     aPrevFilterResult = myPrevRenderFilter->ShouldRender (theWorkspace, theElement);
1116   }
1117   return aPrevFilterResult &&
1118     !OpenGl_Raytrace::IsRaytracedElement (theElement);
1119 }