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