0029138: Visualization - D3DHost_FrameBuffer should provide software fallback when...
[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 : SetAspectLine
233 // purpose  :
234 // =======================================================================
235 const OpenGl_AspectLine* OpenGl_Workspace::SetAspectLine (const OpenGl_AspectLine* theAspect)
236 {
237   const OpenGl_AspectLine* aPrevAspectLine = myAspectLineSet;
238   myAspectLineSet = theAspect;
239   return aPrevAspectLine;
240 }
241
242 // =======================================================================
243 // function : SetAspectFace
244 // purpose  :
245 // =======================================================================
246 const OpenGl_AspectFace * OpenGl_Workspace::SetAspectFace (const OpenGl_AspectFace* theAspect)
247 {
248   const OpenGl_AspectFace* aPrevAspectFace = myAspectFaceSet;
249   myAspectFaceSet = theAspect;
250   return aPrevAspectFace;
251 }
252
253 // =======================================================================
254 // function : SetAspectMarker
255 // purpose  :
256 // =======================================================================
257 const OpenGl_AspectMarker* OpenGl_Workspace::SetAspectMarker (const OpenGl_AspectMarker* theAspect)
258 {
259   const OpenGl_AspectMarker* aPrevAspectMarker = myAspectMarkerSet;
260   myAspectMarkerSet = theAspect;
261   return aPrevAspectMarker;
262 }
263
264 // =======================================================================
265 // function : SetAspectText
266 // purpose  :
267 // =======================================================================
268 const OpenGl_AspectText * OpenGl_Workspace::SetAspectText (const OpenGl_AspectText* theAspect)
269 {
270   const OpenGl_AspectText* aPrevAspectText = myAspectTextSet;
271   myAspectTextSet = theAspect;
272   return aPrevAspectText;
273 }
274
275 // =======================================================================
276 // function : ApplyAspectFace
277 // purpose  :
278 // =======================================================================
279 const OpenGl_AspectFace* OpenGl_Workspace::ApplyAspectFace()
280 {
281   if (myView->BackfacingModel() == Graphic3d_TOBM_AUTOMATIC)
282   {
283     // manage back face culling mode, disable culling when clipping is enabled
284     bool toSuppressBackFaces = myToAllowFaceCulling
285                             && myAspectFaceSet->Aspect()->ToSuppressBackFaces();
286     if (toSuppressBackFaces)
287     {
288       if (myGlContext->Clipping().IsClippingOrCappingOn()
289        || myAspectFaceSet->Aspect()->InteriorStyle() == Aspect_IS_HATCH)
290       {
291         toSuppressBackFaces = false;
292       }
293     }
294     if (toSuppressBackFaces)
295     {
296       if ((float )myAspectFaceSet->Aspect()->FrontMaterial().Transparency() != 0.0f)
297       {
298         // disable culling in case of translucent shading aspect
299         toSuppressBackFaces = false;
300       }
301     }
302     myGlContext->SetCullBackFaces (toSuppressBackFaces);
303   }
304
305   if (myAspectFaceSet->Aspect() == myAspectFaceApplied
306    && myHighlightStyle == myAspectFaceAppliedWithHL)
307   {
308     return myAspectFaceSet;
309   }
310   myAspectFaceAppliedWithHL = myHighlightStyle;
311
312 #if !defined(GL_ES_VERSION_2_0)
313   const Aspect_InteriorStyle anIntstyle = myAspectFaceSet->Aspect()->InteriorStyle();
314   if (myAspectFaceApplied.IsNull()
315    || myAspectFaceApplied->InteriorStyle() != anIntstyle)
316   {
317     switch (anIntstyle)
318     {
319       case Aspect_IS_EMPTY:
320       case Aspect_IS_HOLLOW:
321       {
322         myGlContext->SetPolygonMode (GL_LINE);
323         break;
324       }
325       case Aspect_IS_HATCH:
326       {
327         myGlContext->SetPolygonMode (GL_FILL);
328         myGlContext->SetPolygonHatchEnabled (true);
329         break;
330       }
331       case Aspect_IS_SOLID:
332       case Aspect_IS_HIDDENLINE:
333       {
334         myGlContext->SetPolygonMode (GL_FILL);
335         myGlContext->SetPolygonHatchEnabled (false);
336         break;
337       }
338       case Aspect_IS_POINT:
339       {
340         myGlContext->SetPolygonMode (GL_POINT);
341         break;
342       }
343     }
344   }
345
346   if (anIntstyle == Aspect_IS_HATCH)
347   {
348     myGlContext->SetPolygonHatchStyle (myAspectFaceSet->Aspect()->HatchStyle());
349   }
350 #endif
351
352   // Aspect_POM_None means: do not change current settings
353   if ((myAspectFaceSet->Aspect()->PolygonOffset().Mode & Aspect_POM_None) != Aspect_POM_None)
354   {
355     if (myPolygonOffsetApplied.Mode   != myAspectFaceSet->Aspect()->PolygonOffset().Mode
356      || myPolygonOffsetApplied.Factor != myAspectFaceSet->Aspect()->PolygonOffset().Factor
357      || myPolygonOffsetApplied.Units  != myAspectFaceSet->Aspect()->PolygonOffset().Units)
358     {
359       SetPolygonOffset (myAspectFaceSet->Aspect()->PolygonOffset());
360     }
361   }
362
363   // Case of hidden line
364   if (myAspectFaceSet->Aspect()->InteriorStyle() == Aspect_IS_HIDDENLINE)
365   {
366     // copy all values including line edge aspect
367     *myAspectFaceHl.Aspect().operator->() = *myAspectFaceSet->Aspect();
368     myAspectFaceHl.SetAspectEdge (myAspectFaceSet->AspectEdge());
369     myAspectFaceHl.Aspect()->SetInteriorColor (myView->BackgroundColor().GetRGB());
370     myAspectFaceHl.SetNoLighting (true);
371     myAspectFaceSet = &myAspectFaceHl;
372   }
373   else
374   {
375     myGlContext->SetShadingMaterial (myAspectFaceSet, myHighlightStyle);
376   }
377
378   if (myAspectFaceSet->Aspect()->ToMapTexture())
379   {
380     myGlContext->BindTextures (myAspectFaceSet->TextureSet (myGlContext));
381   }
382   else
383   {
384     myGlContext->BindTextures (myEnvironmentTexture);
385   }
386
387   myAspectFaceApplied = myAspectFaceSet->Aspect();
388   return myAspectFaceSet;
389 }
390
391 //=======================================================================
392 //function : SetPolygonOffset
393 //purpose  :
394 //=======================================================================
395 void OpenGl_Workspace::SetPolygonOffset (const Graphic3d_PolygonOffset& theParams)
396 {
397   myPolygonOffsetApplied = theParams;
398
399   if ((theParams.Mode & Aspect_POM_Fill) == Aspect_POM_Fill)
400   {
401     glEnable (GL_POLYGON_OFFSET_FILL);
402   }
403   else
404   {
405     glDisable (GL_POLYGON_OFFSET_FILL);
406   }
407
408 #if !defined(GL_ES_VERSION_2_0)
409   if ((theParams.Mode & Aspect_POM_Line) == Aspect_POM_Line)
410   {
411     glEnable (GL_POLYGON_OFFSET_LINE);
412   }
413   else
414   {
415     glDisable (GL_POLYGON_OFFSET_LINE);
416   }
417
418   if ((theParams.Mode & Aspect_POM_Point) == Aspect_POM_Point)
419   {
420     glEnable (GL_POLYGON_OFFSET_POINT);
421   }
422   else
423   {
424     glDisable (GL_POLYGON_OFFSET_POINT);
425   }
426 #endif
427   glPolygonOffset (theParams.Factor, theParams.Units);
428 }
429
430 // =======================================================================
431 // function : ApplyAspectMarker
432 // purpose  :
433 // =======================================================================
434 const OpenGl_AspectMarker* OpenGl_Workspace::ApplyAspectMarker()
435 {
436   if (myAspectMarkerSet->Aspect() != myAspectMarkerApplied)
437   {
438     if (myAspectMarkerApplied.IsNull()
439     || (myAspectMarkerSet->Aspect()->Scale() != myAspectMarkerApplied->Scale()))
440     {
441     #if !defined(GL_ES_VERSION_2_0)
442       glPointSize (myAspectMarkerSet->Aspect()->Scale());
443     #ifdef HAVE_GL2PS
444       gl2psPointSize (myAspectMarkerSet->Aspect()->Scale());
445     #endif
446     #endif
447     }
448     myAspectMarkerApplied = myAspectMarkerSet->Aspect();
449   }
450   return myAspectMarkerSet;
451 }
452
453 // =======================================================================
454 // function : Width
455 // purpose  :
456 // =======================================================================
457 Standard_Integer OpenGl_Workspace::Width()  const
458 {
459   return !myView->GlWindow().IsNull() ? myView->GlWindow()->Width() : 0;
460 }
461
462 // =======================================================================
463 // function : Height
464 // purpose  :
465 // =======================================================================
466 Standard_Integer OpenGl_Workspace::Height() const
467 {
468   return !myView->GlWindow().IsNull() ? myView->GlWindow()->Height() : 0;
469 }
470
471 // =======================================================================
472 // function : IsCullingEnabled
473 // purpose  :
474 // =======================================================================
475 Standard_Boolean OpenGl_Workspace::IsCullingEnabled() const
476 {
477   return myView->IsCullingEnabled();
478 }
479
480 // =======================================================================
481 // function : FBOCreate
482 // purpose  :
483 // =======================================================================
484 Handle(OpenGl_FrameBuffer) OpenGl_Workspace::FBOCreate (const Standard_Integer theWidth,
485                                                         const Standard_Integer theHeight)
486 {
487   // activate OpenGL context
488   if (!Activate())
489     return Handle(OpenGl_FrameBuffer)();
490
491   // create the FBO
492   const Handle(OpenGl_Context)& aCtx = GetGlContext();
493   aCtx->BindTextures (Handle(OpenGl_TextureSet)());
494   Handle(OpenGl_FrameBuffer) aFrameBuffer = new OpenGl_FrameBuffer();
495   if (!aFrameBuffer->Init (aCtx, theWidth, theHeight, GL_RGBA8, GL_DEPTH24_STENCIL8, 0))
496   {
497     aFrameBuffer->Release (aCtx.operator->());
498     return Handle(OpenGl_FrameBuffer)();
499   }
500   return aFrameBuffer;
501 }
502
503 // =======================================================================
504 // function : FBORelease
505 // purpose  :
506 // =======================================================================
507 void OpenGl_Workspace::FBORelease (Handle(OpenGl_FrameBuffer)& theFbo)
508 {
509   // activate OpenGL context
510   if (!Activate()
511    || theFbo.IsNull())
512   {
513     return;
514   }
515
516   theFbo->Release (GetGlContext().operator->());
517   theFbo.Nullify();
518 }
519
520 // =======================================================================
521 // function : BufferDump
522 // purpose  :
523 // =======================================================================
524 Standard_Boolean OpenGl_Workspace::BufferDump (const Handle(OpenGl_FrameBuffer)& theFbo,
525                                                Image_PixMap&                     theImage,
526                                                const Graphic3d_BufferType&       theBufferType)
527 {
528   return !theImage.IsEmpty()
529       && Activate()
530       && OpenGl_FrameBuffer::BufferDump (GetGlContext(), theFbo, theImage, theBufferType);
531 }
532
533 // =======================================================================
534 // function : ShouldRender
535 // purpose  :
536 // =======================================================================
537 Standard_Boolean OpenGl_RaytraceFilter::ShouldRender (const Handle(OpenGl_Workspace)& theWorkspace,
538                                                       const OpenGl_Element*           theElement)
539 {
540   Standard_Boolean aPrevFilterResult = Standard_True;
541   if (!myPrevRenderFilter.IsNull())
542   {
543     aPrevFilterResult = myPrevRenderFilter->ShouldRender (theWorkspace, theElement);
544   }
545   return aPrevFilterResult &&
546     !OpenGl_Raytrace::IsRaytracedElement (theElement);
547 }