0026344: Visualization - provide a support of zoom persistent selection
[occt.git] / src / OpenGl / OpenGl_View.hxx
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 #ifndef _OpenGl_View_Header
17 #define _OpenGl_View_Header
18
19 #include <MMgt_TShared.hxx>
20 #include <Standard_Type.hxx>
21
22 #include <TColStd_Array2OfReal.hxx>
23 #include <NCollection_List.hxx>
24 #include <math_BullardGenerator.hxx>
25
26 #include <Quantity_NameOfColor.hxx>
27 #include <Aspect_FillMethod.hxx>
28 #include <Aspect_GradientFillMethod.hxx>
29 #include <Aspect_TypeOfTriedronPosition.hxx>
30 #include <Aspect_CLayer2d.hxx>
31
32 #include <InterfaceGraphic_Graphic3d.hxx>
33 #include <InterfaceGraphic_Visual3d.hxx>
34
35 #include <Graphic3d_CView.hxx>
36 #include <Graphic3d_GraduatedTrihedron.hxx>
37 #include <Graphic3d_SequenceOfHClipPlane.hxx>
38 #include <Graphic3d_WorldViewProjState.hxx>
39 #include <Graphic3d_ZLayerSettings.hxx>
40 #include <Visual3d_TypeOfSurfaceDetail.hxx>
41 #include <Visual3d_TypeOfModel.hxx>
42
43 #include <OpenGl_AspectFace.hxx>
44 #include <OpenGl_BackgroundArray.hxx>
45 #include <OpenGl_BVHTreeSelector.hxx>
46 #include <OpenGl_LayerList.hxx>
47 #include <OpenGl_Light.hxx>
48 #include <OpenGl_LineAttributes.hxx>
49 #include <OpenGl_Trihedron.hxx>
50 #include <OpenGl_GraduatedTrihedron.hxx>
51
52
53 struct OPENGL_ZCLIP
54 {
55   struct {
56     Standard_Boolean   IsOn;
57     Standard_ShortReal Limit; /* in the range [0., 1.] */
58   } Back;
59   struct {
60     Standard_Boolean   IsOn;
61     Standard_ShortReal Limit; /* in the range [0., 1.] */
62   } Front;
63 };
64
65 struct OPENGL_FOG
66 {
67   Standard_Boolean   IsOn;
68   Standard_ShortReal Front; /* in the range [0., 1.] */
69   Standard_ShortReal Back; /* in the range [0., 1.] */
70   TEL_COLOUR         Color;
71 };
72
73 struct OpenGl_Matrix;
74 class OpenGl_Structure;
75 class OpenGl_StateCounter;
76
77 class OpenGl_View;
78 DEFINE_STANDARD_HANDLE(OpenGl_View,MMgt_TShared)
79
80 class OpenGl_View : public MMgt_TShared
81 {
82  public:
83   Standard_EXPORT OpenGl_View (const CALL_DEF_VIEWCONTEXT &AContext, OpenGl_StateCounter* theCounter);
84   Standard_EXPORT virtual ~OpenGl_View ();
85
86   Standard_EXPORT void ReleaseGlResources (const Handle(OpenGl_Context)& theCtx);
87
88   void SetTextureEnv (const Handle(OpenGl_Context)&       theCtx,
89                       const Handle(Graphic3d_TextureEnv)& theTexture);
90   void SetSurfaceDetail (const Visual3d_TypeOfSurfaceDetail AMode);
91   void SetBackfacing (const Standard_Integer AMode);
92   void SetLights (const CALL_DEF_VIEWCONTEXT &AContext);
93   void SetAntiAliasing (const Standard_Boolean AMode) { myAntiAliasing = AMode; }
94   void SetClipPlanes (const Graphic3d_SequenceOfHClipPlane &thePlanes) { myClipPlanes = thePlanes; }
95   void SetVisualisation (const CALL_DEF_VIEWCONTEXT &AContext);
96
97   const Handle(Graphic3d_Camera)& Camera() { return myCamera; }
98   void SetCamera (const Handle(Graphic3d_Camera)& theCamera) { myCamera = theCamera; }
99
100   void SetClipLimit (const Graphic3d_CView& theCView);
101
102   void SetFog (const Graphic3d_CView& theCView, const Standard_Boolean theFlag);
103
104   OpenGl_Trihedron& ChangeTrihedron() { return myTrihedron; }
105   void TriedronDisplay (const Aspect_TypeOfTriedronPosition thePosition,
106                         const Quantity_NameOfColor          theColor,
107                         const Standard_Real                 theScale,
108                         const Standard_Boolean              theAsWireframe);
109   void TriedronErase (const Handle(OpenGl_Context)& theCtx);
110
111   OpenGl_GraduatedTrihedron& ChangeGraduatedTrihedron() { return myGraduatedTrihedron; }
112   void GraduatedTrihedronDisplay (const Handle(OpenGl_Context)&        theCtx,
113                                   const Graphic3d_GraduatedTrihedron& theCubic);
114   void GraduatedTrihedronErase (const Handle(OpenGl_Context)& theCtx);
115
116   Standard_Real Height () const { return myCamera->ViewDimensions().X(); }
117   Standard_Real Width () const { return myCamera->ViewDimensions().Y(); }
118
119   Standard_Integer Backfacing () const { return myBackfacing; }
120
121   //! Add structure to display list with specified priority.
122   //! The structure will be added to associated with it z layer.
123   //! If the z layer is not presented in the view, the structure will
124   //! be displayed in default bottom-level z layer.
125   void DisplayStructure (const Handle(Graphic3d_Structure)& theStructure,
126                          const Standard_Integer             thePriority);
127
128   //! Erase structure from display list.
129   void EraseStructure (const Handle(Graphic3d_Structure)& theStructure);
130
131   //! Add structure to the list of immediate structures.
132   void DisplayImmediateStructure (const Handle(Graphic3d_Structure)& theStructure);
133
134   //! Erase structure from display list.
135   void EraseImmediateStructure (const OpenGl_Structure* theStructure);
136
137   //! Insert a new top-level z layer with ID <theLayerId>
138   void AddZLayer (const Graphic3d_ZLayerId theLayerId);
139
140   //! Remove a z layer with ID <theLayerId>
141   void RemoveZLayer (const Graphic3d_ZLayerId theLayerId);
142
143   //! Display structure in z layer with ID <theNewLayerId>
144   //! If the layer with ID <theNewLayerId> is not presented in the view,
145   //! the structure will be displayed in default bottom-level layer.
146   void ChangeZLayer (const OpenGl_Structure*  theStructure,
147                      const Graphic3d_ZLayerId theNewLayerId);
148
149   //! Sets the settings for a single Z layer of specified view.
150   void SetZLayerSettings (const Graphic3d_ZLayerId        theLayerId,
151                           const Graphic3d_ZLayerSettings& theSettings);
152
153   //! Changes the priority of a structure within its ZLayer
154   void ChangePriority (const OpenGl_Structure* theStructure,
155                        const Standard_Integer  theNewPriority);
156
157   void CreateBackgroundTexture (const Standard_CString AFileName,
158                                 const Aspect_FillMethod AFillStyle);
159
160   void SetBackgroundTextureStyle (const Aspect_FillMethod FillStyle);
161   void SetBackgroundGradient (const Quantity_Color& AColor1, const Quantity_Color& AColor2, const Aspect_GradientFillMethod AType);
162   void SetBackgroundGradientType (const Aspect_GradientFillMethod AType);
163
164   void Render (const Handle(OpenGl_PrinterContext)& thePrintContext,
165                const Handle(OpenGl_Workspace)&      theWorkspace,
166                OpenGl_FrameBuffer*                  theReadDrawFbo,
167                Graphic3d_Camera::Projection         theProjection,
168                const Graphic3d_CView&               theCView,
169                const Aspect_CLayer2d&               theCUnderLayer,
170                const Aspect_CLayer2d&               theCOverLayer,
171                const Standard_Boolean               theToDrawImmediate);
172
173
174   void DrawBackground (const Handle(OpenGl_Workspace)& theWorkspace);
175
176   //! Returns list of OpenGL Z-layers.
177   const OpenGl_LayerList& LayerList() const { return myZLayers; }
178
179   //! Returns list of openGL light sources.
180   const OpenGl_ListOfLight& LightList() const { return myLights; }
181
182   //! Returns OpenGL environment map.
183   const Handle(OpenGl_Texture)& TextureEnv() const { return myTextureEnv; }
184
185   //! Returns visualization mode for objects in the view.
186   Visual3d_TypeOfSurfaceDetail SurfaceDetail() const { return mySurfaceDetail; }
187
188   //! Returns selector for BVH tree, providing a possibility to store information
189   //! about current view volume and to detect which objects are overlapping it.
190   OpenGl_BVHTreeSelector& BVHTreeSelector() { return myBVHSelector; }
191
192   //! Marks BVH tree for given priority list as dirty and
193   //! marks primitive set for rebuild.
194   void InvalidateBVHData (const Standard_Integer theLayerId);
195
196   //! Returns list of immediate structures rendered on top of main presentation
197   const OpenGl_IndexedMapOfStructure& ImmediateStructures() const
198   {
199     return myImmediateList;
200   }
201
202   //! Returns true if there are immediate structures to display
203   bool HasImmediateStructures() const
204   {
205     return !myImmediateList.IsEmpty()
206          || myZLayers.NbImmediateStructures() != 0;
207   }
208
209 protected:
210
211   void RenderStructs (const Handle(OpenGl_Workspace)& theWorkspace,
212                       OpenGl_FrameBuffer*             theReadDrawFbo,
213                       const Graphic3d_CView&          theCView,
214                       const Standard_Boolean          theToDrawImmediate);
215
216   void RedrawLayer2d (const Handle(OpenGl_PrinterContext)& thePrintContext,
217                       const Handle(OpenGl_Workspace)&      theWorkspace,
218                       const Graphic3d_CView&               theCView,
219                       const Aspect_CLayer2d&               theCLayer);
220
221   void RedrawTrihedron (const Handle(OpenGl_Workspace) &theWorkspace);
222
223   //! Redraw contents of model scene: clipping planes,
224   //! lights, structures. The peculiar properties of "scene" is that
225   //! it requires empty Z-Buffer and uses projection and orientation
226   //! matrices supplied by 3d view.
227   void RedrawScene (const Handle(OpenGl_PrinterContext)& thePrintContext,
228                     const Handle(OpenGl_Workspace)&      theWorkspace,
229                     OpenGl_FrameBuffer*                  theReadDrawFbo,
230                     const Graphic3d_CView&               theCView,
231                     const Standard_Boolean               theToDrawImmediate);
232
233   Handle(OpenGl_LineAttributes) myLineAttribs;
234   Handle(OpenGl_Texture)        myTextureEnv;
235   Visual3d_TypeOfSurfaceDetail  mySurfaceDetail;
236   Standard_Integer              myBackfacing;
237
238   OPENGL_ZCLIP   myZClip;
239
240   Graphic3d_SequenceOfHClipPlane myClipPlanes;
241   
242   Handle(Graphic3d_Camera) myCamera;
243
244   OPENGL_FOG myFog;
245   OpenGl_Trihedron           myTrihedron;
246   OpenGl_GraduatedTrihedron  myGraduatedTrihedron;
247   bool                       myToShowTrihedron;
248   bool                       myToShowGradTrihedron;
249
250   //View_LABViewContext
251   int myVisualization;
252   Visual3d_TypeOfModel       myShadingModel;  //!< lighting shading model
253
254   //View_LABLight
255   OpenGl_ListOfLight myLights;
256
257   //View_LABPlane
258   //View_LABAliasing
259   Standard_Boolean myAntiAliasing;
260
261   //View_LABDepthCueing - fixed index used
262
263   OpenGl_LayerList             myZLayers;       //!< main list of displayed structure, sorted by layers
264   OpenGl_IndexedMapOfStructure myImmediateList; //!< list of immediate structures rendered on top of main presentation
265
266   //! Modification state
267   Graphic3d_WorldViewProjState myWorldViewProjState;
268   OpenGl_StateCounter* myStateCounter;
269
270   Standard_Size myCurrLightSourceState;
271
272   typedef std::pair<Standard_Size, Standard_Size> StateInfo;
273
274   StateInfo myLastOrientationState;
275   StateInfo myLastViewMappingState;
276   StateInfo myLastLightSourceState;
277
278   //! Is needed for selection of overlapping objects and storage of the current view volume
279   OpenGl_BVHTreeSelector myBVHSelector;
280
281 protected: //! @name Background parameters
282
283   OpenGl_AspectFace*      myTextureParams;   //!< Stores texture and its parameters for textured background
284   OpenGl_BackgroundArray* myBgGradientArray; //!< Primitive array for gradient background
285   OpenGl_BackgroundArray* myBgTextureArray;  //!< Primitive array for texture  background
286
287 protected: //! @name data types related to ray-tracing
288
289   //! Result of OpenGL shaders initialization.
290   enum RaytraceInitStatus
291   {
292     OpenGl_RT_NONE,
293     OpenGl_RT_INIT,
294     OpenGl_RT_FAIL
295   };
296
297   //! Describes update mode (state).
298   enum RaytraceUpdateMode
299   {
300     OpenGl_GUM_CHECK,   //!< check geometry state
301     OpenGl_GUM_PREPARE, //!< collect unchanged objects
302     OpenGl_GUM_REBUILD  //!< rebuild changed and new objects
303   };
304
305   //! Defines frequently used shader variables.
306   enum ShaderVariableIndex
307   {
308     OpenGl_RT_aPosition,
309
310     // camera position
311     OpenGl_RT_uOriginLT,
312     OpenGl_RT_uOriginLB,
313     OpenGl_RT_uOriginRT,
314     OpenGl_RT_uOriginRB,
315     OpenGl_RT_uDirectLT,
316     OpenGl_RT_uDirectLB,
317     OpenGl_RT_uDirectRT,
318     OpenGl_RT_uDirectRB,
319     OpenGl_RT_uUnviewMat,
320
321     // 3D scene params
322     OpenGl_RT_uSceneRad,
323     OpenGl_RT_uSceneEps,
324     OpenGl_RT_uLightAmbnt,
325     OpenGl_RT_uLightCount,
326
327     // background params
328     OpenGl_RT_uBackColorTop,
329     OpenGl_RT_uBackColorBot,
330
331     // ray-tracing params
332     OpenGl_RT_uShadowsEnabled,
333     OpenGl_RT_uReflectEnabled,
334     OpenGl_RT_uSphereMapEnabled,
335     OpenGl_RT_uSphereMapForBack,
336     OpenGl_RT_uTexSamplersArray,
337
338     // sampled frame params
339     OpenGl_RT_uSampleWeight,
340     OpenGl_RT_uFrameRndSeed,
341
342     // adaptive FSAA params
343     OpenGl_RT_uOffsetX,
344     OpenGl_RT_uOffsetY,
345     OpenGl_RT_uSamples,
346
347     OpenGl_RT_NbVariables // special field
348   };
349
350   //! Defines texture samplers.
351   enum ShaderSamplerNames
352   {
353     OpenGl_RT_SceneNodeInfoTexture  = 0,
354     OpenGl_RT_SceneMinPointTexture  = 1,
355     OpenGl_RT_SceneMaxPointTexture  = 2,
356     OpenGl_RT_SceneTransformTexture = 3,
357
358     OpenGl_RT_GeometryVertexTexture = 4,
359     OpenGl_RT_GeometryNormalTexture = 5,
360     OpenGl_RT_GeometryTexCrdTexture = 6,
361     OpenGl_RT_GeometryTriangTexture = 7,
362
363     OpenGl_RT_EnvironmentMapTexture = 8,
364
365     OpenGl_RT_RaytraceMaterialTexture = 9,
366     OpenGl_RT_RaytraceLightSrcTexture = 10,
367
368     OpenGl_RT_FsaaInputTexture = 11,
369     OpenGl_RT_PrevAccumTexture = 12,
370
371     OpenGl_RT_OpenGlColorTexture = 13,
372     OpenGl_RT_OpenGlDepthTexture = 14
373   };
374
375   //! Tool class for management of shader sources.
376   class ShaderSource
377   {
378   public:
379
380     //! Default shader prefix - empty string.
381     static const TCollection_AsciiString EMPTY_PREFIX;
382
383     //! Creates new uninitialized shader source.
384     ShaderSource()
385     {
386       //
387     }
388
389   public:
390
391     //! Returns error description in case of load fail.
392     const TCollection_AsciiString& ErrorDescription() const
393     {
394       return myError;
395     }
396
397     //! Returns prefix to insert before the source.
398     const TCollection_AsciiString& Prefix() const
399     {
400       return myPrefix;
401     }
402
403     //! Sets prefix to insert before the source.
404     void SetPrefix (const TCollection_AsciiString& thePrefix)
405     {
406       myPrefix = thePrefix;
407     }
408
409     //! Returns shader source combined with prefix.
410     TCollection_AsciiString Source() const;
411
412     //! Loads shader source from specified files.
413     Standard_Boolean Load (const TCollection_AsciiString* theFileNames, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
414
415   private:
416
417     TCollection_AsciiString mySource; //!< Source string of the shader object
418     TCollection_AsciiString myPrefix; //!< Prefix to insert before the source
419     TCollection_AsciiString myError;  //!< error state
420
421   };
422
423   //! Default ray-tracing depth.
424   static const Standard_Integer THE_DEFAULT_NB_BOUNCES = 3;
425
426   //! Default size of traversal stack.
427   static const Standard_Integer THE_DEFAULT_STACK_SIZE = 24;
428
429   //! Compile-time ray-tracing parameters.
430   struct RaytracingParams
431   {
432     //! Actual size of traversal stack in shader program.
433     Standard_Integer StackSize;
434
435     //! Actual ray-tracing depth (number of ray bounces).
436     Standard_Integer NbBounces;
437
438     //! Enables/disables light propagation through transparent media.
439     Standard_Boolean TransparentShadows;
440
441     //! Enables/disables global illumination (GI) effects.
442     Standard_Boolean GlobalIllumination;
443
444     //! Enables/disables the use of OpenGL bindless textures.
445     Standard_Boolean UseBindlessTextures;
446
447     //! Creates default compile-time ray-tracing parameters.
448     RaytracingParams()
449     : StackSize (THE_DEFAULT_STACK_SIZE),
450       NbBounces (THE_DEFAULT_NB_BOUNCES),
451       TransparentShadows (Standard_False),
452       GlobalIllumination  (Standard_False),
453       UseBindlessTextures (Standard_False)
454     {
455       //
456     }
457   };
458
459   //! Describes state of OpenGL structure.
460   struct StructState
461   {
462     Standard_Size StructureState;
463     Standard_Size InstancedState;
464
465     //! Creates new structure state.
466     StructState (const Standard_Size theStructureState = 0,
467                  const Standard_Size theInstancedState = 0)
468     : StructureState (theStructureState),
469       InstancedState (theInstancedState)
470     {
471       //
472     }
473
474     //! Creates new structure state.
475     StructState (const OpenGl_Structure* theStructure)
476     {
477       StructureState = theStructure->ModificationState();
478
479       InstancedState = theStructure->InstancedStructure() != NULL ?
480         theStructure->InstancedStructure()->ModificationState() : 0;
481     }
482   };
483
484 protected: //! @name methods related to ray-tracing
485
486   //! Updates 3D scene geometry for ray-tracing.
487   Standard_Boolean updateRaytraceGeometry (const RaytraceUpdateMode      theMode,
488                                            const Standard_Integer        theViewId,
489                                            const Handle(OpenGl_Context)& theGlContext);
490
491   //! Updates 3D scene light sources for ray-tracing.
492   Standard_Boolean updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext);
493
494   //! Updates environment map for ray-tracing.
495   Standard_Boolean updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext);
496
497   //! Checks to see if the OpenGL structure is modified.
498   Standard_Boolean toUpdateStructure (const OpenGl_Structure* theStructure);
499
500   //! Adds OpenGL structure to ray-traced scene geometry.
501   Standard_Boolean addRaytraceStructure (const OpenGl_Structure*       theStructure,
502                                          const Handle(OpenGl_Context)& theGlContext);
503
504   //! Adds OpenGL groups to ray-traced scene geometry.
505   Standard_Boolean addRaytraceGroups (const OpenGl_Structure*       theStructure,
506                                       const Standard_Integer        theStructMat,
507                                       const Standard_ShortReal*     theTransform,
508                                       const Handle(OpenGl_Context)& theGlContext);
509
510   //! Creates ray-tracing material properties.
511   OpenGl_RaytraceMaterial convertMaterial (const OpenGl_AspectFace*      theAspect,
512                                            const Handle(OpenGl_Context)& theGlContext);
513
514   //! Adds OpenGL primitive array to ray-traced scene geometry.
515   OpenGl_TriangleSet* addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
516                                                  const Standard_Integer       theMatID,
517                                                  const OpenGl_Mat4*           theTrans);
518
519   //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry.
520   Standard_Boolean addRaytraceVertexIndices (OpenGl_TriangleSet&                  theSet,
521                                              const Standard_Integer               theMatID,
522                                              const Standard_Integer               theCount,
523                                              const Standard_Integer               theOffset,
524                                              const OpenGl_PrimitiveArray&         theArray);
525
526   //! Adds OpenGL triangle array to ray-traced scene geometry.
527   Standard_Boolean addRaytraceTriangleArray (OpenGl_TriangleSet&                  theSet,
528                                              const Standard_Integer               theMatID,
529                                              const Standard_Integer               theCount,
530                                              const Standard_Integer               theOffset,
531                                              const Handle(Graphic3d_IndexBuffer)& theIndices);
532
533   //! Adds OpenGL triangle fan array to ray-traced scene geometry.
534   Standard_Boolean addRaytraceTriangleFanArray (OpenGl_TriangleSet&                  theSet,
535                                                 const Standard_Integer               theMatID,
536                                                 const Standard_Integer               theCount,
537                                                 const Standard_Integer               theOffset,
538                                                 const Handle(Graphic3d_IndexBuffer)& theIndices);
539
540   //! Adds OpenGL triangle strip array to ray-traced scene geometry.
541   Standard_Boolean addRaytraceTriangleStripArray (OpenGl_TriangleSet&                  theSet,
542                                                   const Standard_Integer               theMatID,
543                                                   const Standard_Integer               theCount,
544                                                   const Standard_Integer               theOffset,
545                                                   const Handle(Graphic3d_IndexBuffer)& theIndices);
546
547   //! Adds OpenGL quadrangle array to ray-traced scene geometry.
548   Standard_Boolean addRaytraceQuadrangleArray (OpenGl_TriangleSet&                  theSet,
549                                                const Standard_Integer               theMatID,
550                                                const Standard_Integer               theCount,
551                                                const Standard_Integer               theOffset,
552                                                const Handle(Graphic3d_IndexBuffer)& theIndices);
553
554   //! Adds OpenGL quadrangle strip array to ray-traced scene geometry.
555   Standard_Boolean addRaytraceQuadrangleStripArray (OpenGl_TriangleSet&                  theSet,
556                                                     const Standard_Integer               theMatID,
557                                                     const Standard_Integer               theCount,
558                                                     const Standard_Integer               theOffset,
559                                                     const Handle(Graphic3d_IndexBuffer)& theIndices);
560
561   //! Adds OpenGL polygon array to ray-traced scene geometry.
562   Standard_Boolean addRaytracePolygonArray (OpenGl_TriangleSet&                  theSet,
563                                             const Standard_Integer               theMatID,
564                                             const Standard_Integer               theCount,
565                                             const Standard_Integer               theOffset,
566                                             const Handle(Graphic3d_IndexBuffer)& theIndices);
567
568   //! Uploads ray-trace data to the GPU.
569   Standard_Boolean uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext);
570
571   //! Generates shader prefix based on current ray-tracing options.
572   TCollection_AsciiString generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const;
573
574   //! Performs safe exit when shaders initialization fails.
575   Standard_Boolean safeFailBack (const TCollection_ExtendedString& theMessage,
576                                  const Handle(OpenGl_Context)&     theGlContext);
577
578   //! Loads and compiles shader object from specified source.
579   Handle(OpenGl_ShaderObject) initShader (const GLenum                  theType,
580                                           const ShaderSource&           theSource,
581                                           const Handle(OpenGl_Context)& theGlContext);
582
583   //! Creates shader program from the given vertex and fragment shaders.
584   Handle(OpenGl_ShaderProgram) initProgram (const Handle(OpenGl_Context)&      theGlContext,
585                                             const Handle(OpenGl_ShaderObject)& theVertShader,
586                                             const Handle(OpenGl_ShaderObject)& theFragShader);
587
588   //! Initializes OpenGL/GLSL shader programs.
589   Standard_Boolean initRaytraceResources (const Graphic3d_CView&        theCView,
590                                           const Handle(OpenGl_Context)& theGlContext);
591
592   //! Releases OpenGL/GLSL shader programs.
593   void releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext);
594
595   //! Resizes OpenGL frame buffers.
596   Standard_Boolean resizeRaytraceBuffers (const Standard_Integer        theSizeX,
597                                           const Standard_Integer        theSizeY,
598                                           const Handle(OpenGl_Context)& theGlContext);
599
600   //! Generates viewing rays for corners of screen quad.
601   void updateCamera (const OpenGl_Mat4& theOrientation,
602                      const OpenGl_Mat4& theViewMapping,
603                      OpenGl_Vec3*       theOrigins,
604                      OpenGl_Vec3*       theDirects,
605                      OpenGl_Mat4&       theUnView);
606
607   //! Binds ray-trace textures to corresponding texture units.
608   void bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
609
610   //! Unbinds ray-trace textures from corresponding texture unit.
611   void unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
612
613   //! Sets uniform state for the given ray-tracing shader program.
614   Standard_Boolean setUniformState (const Graphic3d_CView&        theCView,
615                                     const OpenGl_Vec3*            theOrigins,
616                                     const OpenGl_Vec3*            theDirects,
617                                     const OpenGl_Mat4&            theUnviewMat,
618                                     const Standard_Integer        theProgramId,
619                                     const Handle(OpenGl_Context)& theGlContext);
620
621   //! Runs ray-tracing shader programs.
622   Standard_Boolean runRaytraceShaders (const Graphic3d_CView&        theCView,
623                                        const Standard_Integer        theSizeX,
624                                        const Standard_Integer        theSizeY,
625                                        const OpenGl_Vec3*            theOrigins,
626                                        const OpenGl_Vec3*            theDirects,
627                                        const OpenGl_Mat4&            theUnviewMat,
628                                        OpenGl_FrameBuffer*           theReadDrawFbo,
629                                        const Handle(OpenGl_Context)& theGlContext);
630
631   //! Redraws the window using OpenGL/GLSL ray-tracing.
632   Standard_Boolean raytrace (const Graphic3d_CView&        theCView,
633                              const Standard_Integer        theSizeX,
634                              const Standard_Integer        theSizeY,
635                              OpenGl_FrameBuffer*           theReadDrawFbo,
636                              const Handle(OpenGl_Context)& theGlContext);
637
638 protected: //! @name fields related to ray-tracing
639
640   //! Result of shaders initialization.
641   RaytraceInitStatus myRaytraceInitStatus;
642
643   //! Is geometry data valid?
644   Standard_Boolean myIsRaytraceDataValid;
645
646   //! Warning about missing extension GL_ARB_bindless_texture has been displayed?
647   Standard_Boolean myIsRaytraceWarnTextures;
648
649   //! 3D scene geometry data for ray-tracing.
650   OpenGl_RaytraceGeometry myRaytraceGeometry;
651
652   //! Compile-time ray-tracing parameters.
653   RaytracingParams myRaytraceParameters;
654
655   //! Radius of bounding sphere of the scene.
656   Standard_ShortReal myRaytraceSceneRadius;
657   //! Scene epsilon to prevent self-intersections.
658   Standard_ShortReal myRaytraceSceneEpsilon;
659
660   //! OpenGL/GLSL source of ray-tracing fragment shader.
661   ShaderSource myRaytraceShaderSource;
662   //! OpenGL/GLSL source of adaptive-AA fragment shader.
663   ShaderSource myPostFSAAShaderSource;
664
665   //! OpenGL/GLSL ray-tracing fragment shader.
666   Handle(OpenGl_ShaderObject) myRaytraceShader;
667   //! OpenGL/GLSL adaptive-AA fragment shader.
668   Handle(OpenGl_ShaderObject) myPostFSAAShader;
669
670   //! OpenGL/GLSL ray-tracing shader program.
671   Handle(OpenGl_ShaderProgram) myRaytraceProgram;
672   //! OpenGL/GLSL adaptive-AA shader program.
673   Handle(OpenGl_ShaderProgram) myPostFSAAProgram;
674   //! OpenGL/GLSL program for displaying texture.
675   Handle(OpenGl_ShaderProgram) myOutImageProgram;
676
677   //! Texture buffer of data records of bottom-level BVH nodes.
678   Handle(OpenGl_TextureBufferArb) mySceneNodeInfoTexture;
679   //! Texture buffer of minimum points of bottom-level BVH nodes.
680   Handle(OpenGl_TextureBufferArb) mySceneMinPointTexture;
681   //! Texture buffer of maximum points of bottom-level BVH nodes.
682   Handle(OpenGl_TextureBufferArb) mySceneMaxPointTexture;
683   //! Texture buffer of transformations of high-level BVH nodes.
684   Handle(OpenGl_TextureBufferArb) mySceneTransformTexture;
685
686   //! Texture buffer of vertex coords.
687   Handle(OpenGl_TextureBufferArb) myGeometryVertexTexture;
688   //! Texture buffer of vertex normals.
689   Handle(OpenGl_TextureBufferArb) myGeometryNormalTexture;
690   //! Texture buffer of vertex UV coords.
691   Handle(OpenGl_TextureBufferArb) myGeometryTexCrdTexture;
692   //! Texture buffer of triangle indices.
693   Handle(OpenGl_TextureBufferArb) myGeometryTriangTexture;
694
695   //! Texture buffer of material properties.
696   Handle(OpenGl_TextureBufferArb) myRaytraceMaterialTexture;
697   //! Texture buffer of light source properties.
698   Handle(OpenGl_TextureBufferArb) myRaytraceLightSrcTexture;
699
700   //! 1st framebuffer (FBO) to perform adaptive FSAA.
701   Handle(OpenGl_FrameBuffer) myRaytraceFBO1;
702   //! 2nd framebuffer (FBO) to perform adaptive FSAA.
703   Handle(OpenGl_FrameBuffer) myRaytraceFBO2;
704   //! Framebuffer (FBO) for preliminary OpenGL output.
705   Handle(OpenGl_FrameBuffer) myOpenGlFBO;
706
707   //! Vertex buffer (VBO) for drawing dummy quad.
708   OpenGl_VertexBuffer myRaytraceScreenQuad;
709
710   //! Cached locations of frequently used uniform variables.
711   Standard_Integer myUniformLocations[2][OpenGl_RT_NbVariables];
712
713   //! State of OpenGL structures reflected to ray-tracing.
714   std::map<const OpenGl_Structure*, StructState> myStructureStates;
715
716   //! PrimitiveArray to TriangleSet map for scene partial update.
717   std::map<Standard_Size, OpenGl_TriangleSet*> myArrayToTrianglesMap;
718
719   //! Set of IDs of non-raytracable elements (to detect updates).
720   std::set<Standard_Integer> myNonRaytraceStructureIDs;
721
722   //! Render filter to filter out all raytracable structures.
723   Handle(OpenGl_RaytraceFilter) myRaytraceFilter;
724
725   //! Marks if environment map should be updated.
726   Standard_Boolean myToUpdateEnvironmentMap;
727
728   //! State of OpenGL layer list.
729   Standard_Size myLayerListState;
730
731   //! Number of accumulated frames (for progressive rendering).
732   Standard_Integer myAccumFrames;
733
734   //! Stored ray origins used for detection of camera movements.
735   OpenGl_Vec3 myPreviousOrigins[3];
736
737   //! Bullard RNG to produce random sequence.
738   math_BullardGenerator myRNG;
739
740 public:
741
742   DEFINE_STANDARD_ALLOC
743   DEFINE_STANDARD_RTTI(OpenGl_View, MMgt_TShared) // Type definition
744
745   friend class OpenGl_Workspace;
746
747 };
748
749 #endif // _OpenGl_View_Header