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