025306: Visualization, TKOpenGl - support texturing within RayTracing
[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_GlCore15.hxx>
17
18 #include <InterfaceGraphic.hxx>
19
20 #include <OpenGl_AspectLine.hxx>
21 #include <OpenGl_AspectFace.hxx>
22 #include <OpenGl_AspectMarker.hxx>
23 #include <OpenGl_AspectText.hxx>
24 #include <OpenGl_Context.hxx>
25 #include <OpenGl_Element.hxx>
26 #include <OpenGl_FrameBuffer.hxx>
27 #include <OpenGl_Structure.hxx>
28 #include <OpenGl_Sampler.hxx>
29 #include <OpenGl_Texture.hxx>
30 #include <OpenGl_View.hxx>
31 #include <OpenGl_Workspace.hxx>
32
33 #include <Graphic3d_TextureParams.hxx>
34
35 #if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
36   #include <OpenGl_AVIWriter.hxx>
37 #endif
38
39 IMPLEMENT_STANDARD_HANDLE(OpenGl_Workspace,OpenGl_Window)
40 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Workspace,OpenGl_Window)
41
42 namespace
43 {
44   static const TEL_COLOUR  THE_WHITE_COLOR = { { 1.0f, 1.0f, 1.0f, 1.0f } };
45   static const OpenGl_Vec4 THE_BLACK_COLOR      (0.0f, 0.0f, 0.0f, 1.0f);
46
47   static const OpenGl_AspectLine myDefaultAspectLine;
48   static const OpenGl_AspectFace myDefaultAspectFace;
49   static const OpenGl_AspectMarker myDefaultAspectMarker;
50   static const OpenGl_AspectText myDefaultAspectText;
51
52   static const OpenGl_TextParam myDefaultTextParam =
53   {
54     16, Graphic3d_HTA_LEFT, Graphic3d_VTA_BOTTOM
55   };
56
57   static const OpenGl_Matrix myDefaultMatrix =
58   {
59     {{ 1.0F, 0.0F, 0.0F, 0.0F },
60      { 0.0F, 1.0F, 0.0F, 0.0F },
61      { 0.0F, 0.0F, 1.0F, 0.0F },
62      { 0.0F, 0.0F, 0.0F, 1.0F }}
63   };
64
65 };
66
67 // =======================================================================
68 // function : Init
69 // purpose  :
70 // =======================================================================
71 void OpenGl_Material::Init (const OPENGL_SURF_PROP& theProp)
72 {
73   // ambient component
74   if (theProp.color_mask & OPENGL_AMBIENT_MASK)
75   {
76     const float* aSrcAmb = theProp.isphysic ? theProp.ambcol.rgb : theProp.matcol.rgb;
77     Ambient = OpenGl_Vec4 (aSrcAmb[0] * theProp.amb,
78                            aSrcAmb[1] * theProp.amb,
79                            aSrcAmb[2] * theProp.amb,
80                            1.0f);
81   }
82   else
83   {
84     Ambient = THE_BLACK_COLOR;
85   }
86
87   // diffusion component
88   if (theProp.color_mask & OPENGL_DIFFUSE_MASK)
89   {
90     const float* aSrcDif = theProp.isphysic ? theProp.difcol.rgb : theProp.matcol.rgb;
91     Diffuse = OpenGl_Vec4 (aSrcDif[0] * theProp.diff,
92                            aSrcDif[1] * theProp.diff,
93                            aSrcDif[2] * theProp.diff,
94                            1.0f);
95   }
96   else
97   {
98     Diffuse = THE_BLACK_COLOR;
99   }
100
101   // specular component
102   if (theProp.color_mask & OPENGL_SPECULAR_MASK)
103   {
104     const float* aSrcSpe = theProp.isphysic ? theProp.speccol.rgb : THE_WHITE_COLOR.rgb;
105     Specular = OpenGl_Vec4 (aSrcSpe[0] * theProp.spec,
106                             aSrcSpe[1] * theProp.spec,
107                             aSrcSpe[2] * theProp.spec,
108                             1.0f);
109   }
110   else
111   {
112     Specular = THE_BLACK_COLOR;
113   }
114
115   // emission component
116   if (theProp.color_mask & OPENGL_EMISSIVE_MASK)
117   {
118     const float* aSrcEms = theProp.isphysic ? theProp.emscol.rgb : theProp.matcol.rgb;
119     Emission = OpenGl_Vec4 (aSrcEms[0] * theProp.emsv,
120                             aSrcEms[1] * theProp.emsv,
121                             aSrcEms[2] * theProp.emsv,
122                             1.0f);
123   }
124   else
125   {
126     Emission = THE_BLACK_COLOR;
127   }
128
129   ChangeShine()        = theProp.shine;
130   ChangeTransparency() = theProp.trans;
131 }
132
133 // =======================================================================
134 // function : OpenGl_Workspace
135 // purpose  :
136 // =======================================================================
137 OpenGl_Workspace::OpenGl_Workspace (const Handle(OpenGl_GraphicDriver)& theDriver,
138                                     const CALL_DEF_WINDOW&        theCWindow,
139                                     Aspect_RenderingContext       theGContext,
140                                     const Handle(OpenGl_Caps)&    theCaps,
141                                     const Handle(OpenGl_Context)& theShareCtx)
142 : OpenGl_Window (theDriver, theCWindow, theGContext, theCaps, theShareCtx),
143   NamedStatus (0),
144   HighlightColor (&THE_WHITE_COLOR),
145   //
146   myComputeInitStatus (OpenGl_RT_NONE),
147   myIsRaytraceDataValid (Standard_False),
148   myIsRaytraceWarnTextures (Standard_False),
149   myViewModificationStatus (0),
150   myLayersModificationStatus (0),
151   //
152   myRaytraceFilter       (new OpenGl_RaytraceFilter()),
153   myToRedrawGL           (Standard_True),
154   myAntiAliasingMode     (3),
155   myTransientDrawToFront (Standard_True),
156   myBackBufferRestored   (Standard_False),
157   myIsImmediateDrawn     (Standard_False),
158   myUseTransparency (Standard_False),
159   myUseZBuffer (Standard_False),
160   myUseDepthTest (Standard_True),
161   myUseGLLight (Standard_True),
162   myIsCullingEnabled (Standard_False),
163   myFrameCounter (0),
164   //
165   AspectLine_set (&myDefaultAspectLine),
166   AspectLine_applied (NULL),
167   AspectFace_set (&myDefaultAspectFace),
168   AspectFace_applied (NULL),
169   AspectMarker_set (&myDefaultAspectMarker),
170   AspectMarker_applied (NULL),
171   AspectText_set (&myDefaultAspectText),
172   AspectText_applied (NULL),
173   TextParam_set (&myDefaultTextParam),
174   TextParam_applied (NULL),
175   ViewMatrix_applied (&myDefaultMatrix),
176   StructureMatrix_applied (&myDefaultMatrix),
177   myCullingMode (TelCullUndefined),
178   myModelViewMatrix (myDefaultMatrix),
179   PolygonOffset_applied (THE_DEFAULT_POFFSET)
180 {
181   myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
182
183   if (!myGlContext->GetResource ("OpenGl_LineAttributes", myLineAttribs))
184   {
185     // share and register for release once the resource is no longer used
186     myLineAttribs = new OpenGl_LineAttributes();
187     myGlContext->ShareResource ("OpenGl_LineAttributes", myLineAttribs);
188     myLineAttribs->Init (myGlContext);
189   }
190
191   // General initialization of the context
192
193 #if !defined(GL_ES_VERSION_2_0)
194   // Eviter d'avoir les faces mal orientees en noir.
195   // Pourrait etre utiliser pour detecter les problemes d'orientation
196   glLightModeli ((GLenum )GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
197
198   // Optimisation pour le Fog et l'antialiasing
199   glHint (GL_FOG_HINT,            GL_FASTEST);
200   glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
201   glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
202   glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
203 #endif
204
205   // AA mode
206   const char* anAaEnv = ::getenv ("CALL_OPENGL_ANTIALIASING_MODE");
207   if (anAaEnv != NULL)
208   {
209     int v;
210     if (sscanf (anAaEnv, "%d", &v) > 0) myAntiAliasingMode = v;
211   }
212 }
213
214 // =======================================================================
215 // function : SetImmediateModeDrawToFront
216 // purpose  :
217 // =======================================================================
218 Standard_Boolean OpenGl_Workspace::SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer)
219 {
220   const Standard_Boolean aPrevMode = myTransientDrawToFront;
221   myTransientDrawToFront = theDrawToFrontBuffer;
222   return aPrevMode;
223 }
224
225 // =======================================================================
226 // function : ~OpenGl_Workspace
227 // purpose  :
228 // =======================================================================
229 OpenGl_Workspace::~OpenGl_Workspace()
230 {
231   if (!myLineAttribs.IsNull())
232   {
233     myLineAttribs.Nullify();
234     myGlContext->ReleaseResource ("OpenGl_LineAttributes", Standard_True);
235   }
236
237   ReleaseRaytraceResources();
238 }
239
240 // =======================================================================
241 // function : Activate
242 // purpose  :
243 // =======================================================================
244 Standard_Boolean OpenGl_Workspace::Activate()
245 {
246   if (!OpenGl_Window::Activate())
247     return Standard_False;
248
249   ViewMatrix_applied      = &myDefaultMatrix;
250   StructureMatrix_applied = &myDefaultMatrix;
251
252   ResetAppliedAspect();
253
254   return Standard_True;
255 }
256
257 // =======================================================================
258 // function : UseTransparency
259 // purpose  : call_togl_transparency
260 // =======================================================================
261 void OpenGl_Workspace::UseTransparency (const Standard_Boolean theFlag)
262 {
263   myUseTransparency = theFlag;
264 }
265
266 //=======================================================================
267 //function : ResetAppliedAspect
268 //purpose  : Sets default values of GL parameters in accordance with default aspects
269 //=======================================================================
270 void OpenGl_Workspace::ResetAppliedAspect()
271 {
272   NamedStatus           = !myTextureBound.IsNull() ? OPENGL_NS_TEXTURE : 0;
273   HighlightColor        = &THE_WHITE_COLOR;
274   AspectLine_set        = &myDefaultAspectLine;
275   AspectLine_applied    = NULL;
276   AspectFace_set        = &myDefaultAspectFace;
277   AspectFace_applied    = NULL;
278   AspectMarker_set      = &myDefaultAspectMarker;
279   AspectMarker_applied  = NULL;
280   AspectText_set        = &myDefaultAspectText;
281   AspectText_applied    = NULL;
282   TextParam_set         = &myDefaultTextParam;
283   TextParam_applied     = NULL;
284   PolygonOffset_applied = THE_DEFAULT_POFFSET;
285   myCullingMode         = TelCullUndefined;
286
287   AspectLine(Standard_True);
288   AspectFace(Standard_True);
289   AspectMarker(Standard_True);
290   AspectText(Standard_True);
291 }
292
293 // =======================================================================
294 // function : DisableTexture
295 // purpose  :
296 // =======================================================================
297 Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
298 {
299   if (myTextureBound.IsNull())
300   {
301     return myTextureBound;
302   }
303
304 #if !defined(GL_ES_VERSION_2_0)
305   // reset texture matrix because some code may expect it is identity
306   GLint aMatrixMode = GL_TEXTURE;
307   glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
308   glMatrixMode (GL_TEXTURE);
309   glLoadIdentity();
310   glMatrixMode (aMatrixMode);
311 #endif
312
313   myTextureBound->Unbind (myGlContext);
314   switch (myTextureBound->GetTarget())
315   {
316   #if !defined(GL_ES_VERSION_2_0)
317     case GL_TEXTURE_1D:
318     {
319
320       if (myTextureBound->GetParams()->GenMode() != GL_NONE)
321       {
322         glDisable (GL_TEXTURE_GEN_S);
323       }
324       glDisable (GL_TEXTURE_1D);
325       break;
326     }
327   #endif
328     case GL_TEXTURE_2D:
329     {
330     #if !defined(GL_ES_VERSION_2_0)
331       if (myTextureBound->GetParams()->GenMode() != GL_NONE)
332       {
333         glDisable (GL_TEXTURE_GEN_S);
334         glDisable (GL_TEXTURE_GEN_T);
335         if (myTextureBound->GetParams()->GenMode() == Graphic3d_TOTM_SPRITE)
336         {
337           glDisable (GL_POINT_SPRITE);
338         }
339       }
340     #endif
341       glDisable (GL_TEXTURE_2D);
342       break;
343     }
344     default: break;
345   }
346
347   Handle(OpenGl_Texture) aPrevTexture = myTextureBound;
348   myTextureBound.Nullify();
349   return aPrevTexture;
350 }
351
352 // =======================================================================
353 // function : setTextureParams
354 // purpose  :
355 // =======================================================================
356 void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&                theTexture,
357                                          const Handle(Graphic3d_TextureParams)& theParams)
358 {
359   const Handle(Graphic3d_TextureParams)& aParams = theParams.IsNull() ? theTexture->GetParams() : theParams;
360   if (aParams.IsNull())
361   {
362     return;
363   }
364
365 #if !defined(GL_ES_VERSION_2_0)
366   GLint aMatrixMode = GL_TEXTURE;
367   glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
368
369   // setup texture matrix
370   glMatrixMode (GL_TEXTURE);
371   glLoadIdentity();
372   const Graphic3d_Vec2& aScale = aParams->Scale();
373   const Graphic3d_Vec2& aTrans = aParams->Translation();
374   glScalef     ( aScale.x(),  aScale.y(), 1.0f);
375   glTranslatef (-aTrans.x(), -aTrans.y(), 0.0f);
376   glRotatef (-aParams->Rotation(), 0.0f, 0.0f, 1.0f);
377
378   // setup generation of texture coordinates
379   switch (aParams->GenMode())
380   {
381     case Graphic3d_TOTM_OBJECT:
382     {
383       glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
384       glTexGenfv (GL_S, GL_OBJECT_PLANE,     aParams->GenPlaneS().GetData());
385       if (theTexture->GetTarget() != GL_TEXTURE_1D)
386       {
387         glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
388         glTexGenfv (GL_T, GL_OBJECT_PLANE,     aParams->GenPlaneT().GetData());
389       }
390       break;
391     }
392     case Graphic3d_TOTM_SPHERE:
393     {
394       glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
395       if (theTexture->GetTarget() != GL_TEXTURE_1D)
396       {
397         glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
398       }
399       break;
400     }
401     case Graphic3d_TOTM_EYE:
402     {
403       glMatrixMode (GL_MODELVIEW);
404       glPushMatrix();
405       glLoadIdentity();
406
407       glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
408       glTexGenfv (GL_S, GL_EYE_PLANE,        aParams->GenPlaneS().GetData());
409
410       if (theTexture->GetTarget() != GL_TEXTURE_1D)
411       {
412         glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
413         glTexGenfv (GL_T, GL_EYE_PLANE,        aParams->GenPlaneT().GetData());
414       }
415       glPopMatrix();
416       break;
417     }
418     case Graphic3d_TOTM_SPRITE:
419     {
420       if (GetGlContext()->core20 != NULL)
421       {
422         glEnable  (GL_POINT_SPRITE);
423         glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
424         glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
425         GetGlContext()->core15->glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);
426       }
427       break;
428     }
429     case Graphic3d_TOTM_MANUAL:
430     default: break;
431   }
432
433   // setup lighting
434   if (aParams->GenMode() != Graphic3d_TOTM_SPRITE)
435   {
436     glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, aParams->IsModulate() ? GL_MODULATE : GL_DECAL);
437   }
438 #endif
439
440   // get active sampler object to override default texture parameters
441   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
442
443   // setup texture filtering and wrapping
444   //if (theTexture->GetParams() != theParams)
445   const GLenum aFilter   = (aParams->Filter() == Graphic3d_TOTF_NEAREST) ? GL_NEAREST : GL_LINEAR;
446   const GLenum aWrapMode = aParams->IsRepeat() ? GL_REPEAT : myGlContext->TextureWrapClamp();
447   switch (theTexture->GetTarget())
448   {
449   #if !defined(GL_ES_VERSION_2_0)
450     case GL_TEXTURE_1D:
451     {
452       if (aSampler.IsNull() || !aSampler->IsValid())
453       {
454         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, aFilter);
455         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, aFilter);
456         glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_WRAP_S,     aWrapMode);
457       }
458       else
459       {
460         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAG_FILTER, aFilter);
461         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MIN_FILTER, aFilter);
462         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_S,     aWrapMode);
463       }
464
465       break;
466     }
467   #endif
468     case GL_TEXTURE_2D:
469     {
470       GLenum aFilterMin = aFilter;
471       if (theTexture->HasMipmaps())
472       {
473         aFilterMin = GL_NEAREST_MIPMAP_NEAREST;
474         if (aParams->Filter() == Graphic3d_TOTF_BILINEAR)
475         {
476           aFilterMin = GL_LINEAR_MIPMAP_NEAREST;
477         }
478         else if (aParams->Filter() == Graphic3d_TOTF_TRILINEAR)
479         {
480           aFilterMin = GL_LINEAR_MIPMAP_LINEAR;
481         }
482
483         if (myGlContext->extAnis)
484         {
485           // setup degree of anisotropy filter
486           const GLint aMaxDegree = myGlContext->MaxDegreeOfAnisotropy();
487           GLint aDegree;
488           switch (aParams->AnisoFilter())
489           {
490             case Graphic3d_LOTA_QUALITY:
491             {
492               aDegree = aMaxDegree;
493               break;
494             }
495             case Graphic3d_LOTA_MIDDLE:
496             {
497               aDegree = (aMaxDegree <= 4) ? 2 : (aMaxDegree / 2);
498               break;
499             }
500             case Graphic3d_LOTA_FAST:
501             {
502               aDegree = 2;
503               break;
504             }
505             case Graphic3d_LOTA_OFF:
506             default:
507             {
508               aDegree = 1;
509               break;
510             }
511           }
512
513           if (aSampler.IsNull() || !aSampler->IsValid())
514           {
515             glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aDegree);
516           }
517           else
518           {
519             aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAX_ANISOTROPY_EXT, aDegree);
520           }
521         }
522       }
523
524       if (aSampler.IsNull() || !aSampler->IsValid())
525       {
526         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterMin);
527         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilter);
528         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,     aWrapMode);
529         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,     aWrapMode);
530       }
531       else
532       {
533         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MIN_FILTER, aFilterMin);
534         aSampler->SetParameter (*myGlContext, GL_TEXTURE_MAG_FILTER, aFilter);
535         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_S,     aWrapMode);
536         aSampler->SetParameter (*myGlContext, GL_TEXTURE_WRAP_T,     aWrapMode);
537       }
538
539       break;
540     }
541     default: break;
542   }
543
544   switch (theTexture->GetTarget())
545   {
546   #if !defined(GL_ES_VERSION_2_0)
547     case GL_TEXTURE_1D:
548     {
549       if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
550       {
551         glEnable (GL_TEXTURE_GEN_S);
552       }
553       glEnable (GL_TEXTURE_1D);
554       break;
555     }
556   #endif
557     case GL_TEXTURE_2D:
558     {
559     #if !defined(GL_ES_VERSION_2_0)
560       if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
561       {
562         glEnable (GL_TEXTURE_GEN_S);
563         glEnable (GL_TEXTURE_GEN_T);
564       }
565     #endif
566       glEnable (GL_TEXTURE_2D);
567       break;
568     }
569     default: break;
570   }
571
572 #if !defined(GL_ES_VERSION_2_0)
573   glMatrixMode (aMatrixMode); // turn back active matrix
574 #endif
575   theTexture->SetParams (aParams);
576 }
577
578 // =======================================================================
579 // function : EnableTexture
580 // purpose  :
581 // =======================================================================
582 Handle(OpenGl_Texture) OpenGl_Workspace::EnableTexture (const Handle(OpenGl_Texture)&          theTexture,
583                                                         const Handle(Graphic3d_TextureParams)& theParams)
584 {
585   if (theTexture.IsNull() || !theTexture->IsValid())
586   {
587     return DisableTexture();
588   }
589
590   if (myTextureBound == theTexture
591    && (theParams.IsNull() || theParams == theTexture->GetParams()))
592   {
593     // already bound
594     return myTextureBound;
595   }
596
597   Handle(OpenGl_Texture) aPrevTexture = DisableTexture();
598   myTextureBound = theTexture;
599   myTextureBound->Bind (myGlContext);
600   setTextureParams (myTextureBound, theParams);
601
602   // If custom sampler object is available it will be
603   // used for overriding default texture parameters
604   const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
605
606   if (!aSampler.IsNull() && aSampler->IsValid())
607   {
608     aSampler->Bind (*myGlContext);
609   }
610
611   return aPrevTexture;
612 }
613
614 // =======================================================================
615 // function : Redraw
616 // purpose  :
617 // =======================================================================
618 void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
619                                const Aspect_CLayer2d& theCUnderLayer,
620                                const Aspect_CLayer2d& theCOverLayer)
621 {
622   if (!Activate())
623   {
624     return;
625   }
626
627   ++myFrameCounter;
628   myIsCullingEnabled = theCView.IsCullingEnabled;
629
630   // release pending GL resources
631   Handle(OpenGl_Context) aGlCtx = GetGlContext();
632   aGlCtx->ReleaseDelayed();
633
634   // fetch OpenGl context state
635   aGlCtx->FetchState();
636
637   Tint toSwap = (aGlCtx->IsRender() && !aGlCtx->caps->buffersNoSwap) ? 1 : 0; // swap buffers
638   GLint aViewPortBack[4];
639   OpenGl_FrameBuffer* aFrameBuffer = (OpenGl_FrameBuffer* )theCView.ptrFBO;
640   if (aFrameBuffer != NULL)
641   {
642     glGetIntegerv (GL_VIEWPORT, aViewPortBack);
643     aFrameBuffer->SetupViewport (aGlCtx);
644     toSwap = 0; // no need to swap buffers
645   }
646
647   myToRedrawGL = Standard_True;
648   if (theCView.RenderParams.Method == Graphic3d_RM_RAYTRACING
649    && myComputeInitStatus != OpenGl_RT_FAIL)
650   {
651     if (UpdateRaytraceGeometry (OpenGl_GUM_CHECK) && myIsRaytraceDataValid)
652     {
653       myToRedrawGL = Standard_False;
654
655       // Only non-raytracable structures should be rendered in OpenGL mode.
656       Handle(OpenGl_RenderFilter) aRenderFilter = GetRenderFilter();
657       myRaytraceFilter->SetPrevRenderFilter (aRenderFilter);
658       SetRenderFilter (myRaytraceFilter);
659
660       Standard_Integer aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWidth;
661       Standard_Integer aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myHeight;
662
663       if (myOpenGlFBO.IsNull())
664       {
665         myOpenGlFBO = new OpenGl_FrameBuffer();
666       }
667       if (myOpenGlFBO->GetVPSizeX() != aSizeX
668        || myOpenGlFBO->GetVPSizeY() != aSizeY)
669       {
670         myOpenGlFBO->Init (aGlCtx, aSizeX, aSizeY);
671       }
672
673       // OverLayer and UnderLayer shouldn't be drawn by OpenGL.
674       // They will be drawn during ray-tracing.
675       Aspect_CLayer2d anEmptyCLayer;
676       anEmptyCLayer.ptrLayer = NULL;
677
678       myOpenGlFBO->BindBuffer (aGlCtx);
679       redraw1 (theCView, anEmptyCLayer, anEmptyCLayer, 0);
680       myOpenGlFBO->UnbindBuffer (aGlCtx);
681
682       const Standard_Boolean isImmediate = !myView->ImmediateStructures().IsEmpty();
683       Raytrace (theCView, aSizeX, aSizeY, isImmediate ? 0 : toSwap,
684                 theCOverLayer, theCUnderLayer, aFrameBuffer);
685
686       if (isImmediate)
687       {
688         RedrawImmediate (theCView, theCUnderLayer, theCOverLayer, Standard_True);
689       }
690
691       SetRenderFilter (aRenderFilter);
692
693       theCView.WasRedrawnGL = Standard_False;
694     }
695   }
696
697   if (myToRedrawGL)
698   {
699     // draw entire frame using normal OpenGL pipeline
700     if (aFrameBuffer != NULL)
701     {
702       aFrameBuffer->BindBuffer (aGlCtx);
703     }
704
705     const Standard_Boolean isImmediate = !myView->ImmediateStructures().IsEmpty();
706     redraw1 (theCView, theCUnderLayer, theCOverLayer, isImmediate ? 0 : toSwap);
707     if (isImmediate)
708     {
709       RedrawImmediate (theCView, theCUnderLayer, theCOverLayer, Standard_True);
710     }
711
712     theCView.WasRedrawnGL = Standard_True;
713   }
714
715   if (aFrameBuffer != NULL)
716   {
717     aFrameBuffer->UnbindBuffer (aGlCtx);
718     // move back original viewport
719     glViewport (aViewPortBack[0], aViewPortBack[1], aViewPortBack[2], aViewPortBack[3]);
720   }
721
722 #if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
723   if (OpenGl_AVIWriter_AllowWriting (theCView.DefWindow.XWindow))
724   {
725     GLint params[4];
726     glGetIntegerv (GL_VIEWPORT, params);
727     int nWidth  = params[2] & ~0x7;
728     int nHeight = params[3] & ~0x7;
729
730     const int nBitsPerPixel = 24;
731     GLubyte* aDumpData = new GLubyte[nWidth * nHeight * nBitsPerPixel / 8];
732
733     glPixelStorei (GL_PACK_ALIGNMENT, 1);
734     glReadPixels (0, 0, nWidth, nHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, aDumpData);
735     OpenGl_AVIWriter_AVIWriter (aDumpData, nWidth, nHeight, nBitsPerPixel);
736     delete[] aDumpData;
737   }
738 #endif
739
740   // reset render mode state
741   aGlCtx->FetchState();
742 }
743
744 // =======================================================================
745 // function : redraw1
746 // purpose  :
747 // =======================================================================
748 void OpenGl_Workspace::redraw1 (const Graphic3d_CView& theCView,
749                                 const Aspect_CLayer2d& theCUnderLayer,
750                                 const Aspect_CLayer2d& theCOverLayer,
751                                 const int              theToSwap)
752 {
753   if (myView.IsNull())
754   {
755     return;
756   }
757
758   // request reset of material
759   NamedStatus |= OPENGL_NS_RESMAT;
760
761   GLbitfield toClear = GL_COLOR_BUFFER_BIT;
762   if (myUseZBuffer)
763   {
764     glDepthFunc (GL_LEQUAL);
765     glDepthMask (GL_TRUE);
766     if (myUseDepthTest)
767     {
768       glEnable (GL_DEPTH_TEST);
769     }
770     else
771     {
772       glDisable (GL_DEPTH_TEST);
773     }
774
775   #if !defined(GL_ES_VERSION_2_0)
776     glClearDepth (1.0);
777   #else
778     glClearDepthf (1.0f);
779   #endif
780     toClear |= GL_DEPTH_BUFFER_BIT;
781   }
782   else
783   {
784     glDisable (GL_DEPTH_TEST);
785   }
786
787   if (!ToRedrawGL())
788   {
789     // set background to black
790     glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
791     toClear |= GL_DEPTH_BUFFER_BIT; //
792   }
793   else
794   {
795     if (NamedStatus & OPENGL_NS_WHITEBACK)
796     {
797         // set background to white
798       glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
799       toClear |= GL_DEPTH_BUFFER_BIT;
800     }
801     else
802     {
803       glClearColor (myBgColor.rgb[0], myBgColor.rgb[1], myBgColor.rgb[2], 0.0f);
804     }
805   }
806   glClear (toClear);
807
808   Handle(OpenGl_Workspace) aWS (this);
809   myView->Render (myPrintContext, aWS, theCView, theCUnderLayer, theCOverLayer);
810
811   // swap the buffers
812   if (theToSwap)
813   {
814     GetGlContext()->SwapBuffers();
815     myBackBufferRestored = Standard_False;
816     myIsImmediateDrawn   = Standard_False;
817   }
818   else
819   {
820     glFlush(); //
821     myBackBufferRestored = Standard_True;//
822     myIsImmediateDrawn   = Standard_False;//
823   }
824 }
825
826 // =======================================================================
827 // function : copyBackToFront
828 // purpose  :
829 // =======================================================================
830 void OpenGl_Workspace::copyBackToFront()
831 {
832 #if !defined(GL_ES_VERSION_2_0)
833   glMatrixMode (GL_PROJECTION);
834   glPushMatrix();
835   glLoadIdentity();
836   gluOrtho2D (0.0, (GLdouble )myWidth, 0.0, (GLdouble )myHeight);
837
838   glMatrixMode (GL_MODELVIEW);
839   glPushMatrix();
840   glLoadIdentity();
841
842   DisableFeatures();
843
844   glDrawBuffer (GL_FRONT);
845   glReadBuffer (GL_BACK);
846
847   glRasterPos2i (0, 0);
848   glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_COLOR);
849
850   EnableFeatures();
851
852   glMatrixMode (GL_PROJECTION);
853   glPopMatrix();
854   glMatrixMode (GL_MODELVIEW);
855   glPopMatrix();
856
857   glDrawBuffer (GL_BACK);
858
859 #endif
860   myIsImmediateDrawn = Standard_False;
861 }
862
863 // =======================================================================
864 // function : DisplayCallback
865 // purpose  :
866 // =======================================================================
867 void OpenGl_Workspace::DisplayCallback (const Graphic3d_CView& theCView,
868                                         Standard_Integer       theReason)
869 {
870   if (theCView.GDisplayCB == NULL)
871   {
872     return;
873   }
874
875   Aspect_GraphicCallbackStruct aCallData;
876   aCallData.reason    = theReason;
877   aCallData.glContext = GetGlContext();
878   aCallData.wsID      = theCView.WsId;
879   aCallData.viewID    = theCView.ViewId;
880   theCView.GDisplayCB (theCView.DefWindow.XWindow, theCView.GClientData, &aCallData);
881 }
882
883 // =======================================================================
884 // function : RedrawImmediate
885 // purpose  :
886 // =======================================================================
887 void OpenGl_Workspace::RedrawImmediate (const Graphic3d_CView& theCView,
888                                         const Aspect_CLayer2d& theCUnderLayer,
889                                         const Aspect_CLayer2d& theCOverLayer,
890                                         const Standard_Boolean theToForce)
891 {
892   if (!Activate())
893   {
894     return;
895   }
896
897   GLboolean isDoubleBuffer = GL_FALSE;
898 #if !defined(GL_ES_VERSION_2_0)
899   glGetBooleanv (GL_DOUBLEBUFFER, &isDoubleBuffer);
900 #endif
901   if (myView->ImmediateStructures().IsEmpty())
902   {
903     if (theToForce
904      || !myIsImmediateDrawn)
905     {
906       myIsImmediateDrawn = Standard_False;
907       return;
908     }
909
910     if (myBackBufferRestored
911      && isDoubleBuffer)
912     {
913       copyBackToFront();
914       glFlush();
915     }
916     else
917     {
918       Redraw (theCView, theCUnderLayer, theCOverLayer);
919     }
920     return;
921   }
922
923   if (isDoubleBuffer && myTransientDrawToFront)
924   {
925     if (!myBackBufferRestored)
926     {
927       Redraw (theCView, theCUnderLayer, theCOverLayer);
928       return;
929     }
930     copyBackToFront();
931     MakeFrontBufCurrent();
932   }
933   else
934   {
935     myBackBufferRestored = Standard_False;
936   }
937   myIsImmediateDrawn = Standard_True;
938
939   NamedStatus |= OPENGL_NS_IMMEDIATE;
940   ///glDisable (GL_LIGHTING);
941   glDisable (GL_DEPTH_TEST);
942
943   Handle(OpenGl_Workspace) aWS (this);
944   for (OpenGl_SequenceOfStructure::Iterator anIter (myView->ImmediateStructures());
945        anIter.More(); anIter.Next())
946   {
947     const OpenGl_Structure* aStructure = anIter.Value();
948     aStructure->Render (aWS);
949   }
950
951   NamedStatus &= ~OPENGL_NS_IMMEDIATE;
952
953   if (isDoubleBuffer && myTransientDrawToFront)
954   {
955     glFlush();
956     MakeBackBufCurrent();
957   }
958 }