0027817: Visualization, StdSelect_BRepOwner - copy transformation persistence flag
[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
31 #include <Graphic3d_CView.hxx>
32 #include <Graphic3d_GraduatedTrihedron.hxx>
33 #include <Graphic3d_SequenceOfHClipPlane.hxx>
34 #include <Graphic3d_TypeOfShadingModel.hxx>
35 #include <Graphic3d_WorldViewProjState.hxx>
36 #include <Graphic3d_ZLayerSettings.hxx>
37
38 #include <OpenGl_AspectFace.hxx>
39 #include <OpenGl_BackgroundArray.hxx>
40 #include <OpenGl_BVHTreeSelector.hxx>
41 #include <OpenGl_Context.hxx>
42 #include <OpenGl_FrameBuffer.hxx>
43 #include <OpenGl_GraduatedTrihedron.hxx>
44 #include <OpenGl_LayerList.hxx>
45 #include <OpenGl_Light.hxx>
46 #include <OpenGl_LineAttributes.hxx>
47 #include <OpenGl_SceneGeometry.hxx>
48 #include <OpenGl_Structure.hxx>
49 #include <OpenGl_Trihedron.hxx>
50 #include <OpenGl_Window.hxx>
51 #include <OpenGl_Workspace.hxx>
52
53 #include <map>
54 #include <set>
55
56 struct OpenGl_Matrix;
57
58 class Graphic3d_StructureManager;
59 class OpenGl_GraphicDriver;
60 class OpenGl_StateCounter;
61 class OpenGl_RaytraceMaterial;
62 class OpenGl_TriangleSet;
63 class OpenGl_Workspace;
64 class OpenGl_View;
65 DEFINE_STANDARD_HANDLE(OpenGl_View,Graphic3d_CView)
66
67 //! Implementation of OpenGl view.
68 class OpenGl_View : public Graphic3d_CView
69 {
70
71 public:
72
73   //! Constructor.
74   Standard_EXPORT OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr,
75                                const Handle(OpenGl_GraphicDriver)& theDriver,
76                                const Handle(OpenGl_Caps)& theCaps,
77                                Standard_Boolean& theDeviceLostFlag,
78                                OpenGl_StateCounter* theCounter);
79
80   //! Default destructor.
81   Standard_EXPORT virtual ~OpenGl_View();
82
83   Standard_EXPORT void ReleaseGlResources (const Handle(OpenGl_Context)& theCtx);
84
85   //! Deletes and erases the view.
86   Standard_EXPORT virtual void Remove() Standard_OVERRIDE;
87
88   //! @param theDrawToFrontBuffer Advanced option to modify rendering mode:
89   //! 1. TRUE.  Drawing immediate mode structures directly to the front buffer over the scene image.
90   //! Fast, so preferred for interactive work (used by default).
91   //! However these extra drawings will be missed in image dump since it is performed from back buffer.
92   //! Notice that since no pre-buffering used the V-Sync will be ignored and rendering could be seen
93   //! in run-time (in case of slow hardware) and/or tearing may appear.
94   //! So this is strongly recommended to draw only simple (fast) structures.
95   //! 2. FALSE. Drawing immediate mode structures to the back buffer.
96   //! The complete scene is redrawn first, so this mode is slower if scene contains complex data and/or V-Sync
97   //! is turned on. But it works in any case and is especially useful for view dump because the dump image is read
98   //! from the back buffer.
99   //! @return previous mode.
100   Standard_EXPORT Standard_Boolean SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer) Standard_OVERRIDE;
101
102   //! Creates and maps rendering window to the view.
103   //! @param theWindow [in] the window.
104   //! @param theContext [in] the rendering context. If NULL the context will be created internally.
105   Standard_EXPORT virtual void SetWindow (const Handle(Aspect_Window)&  theWindow,
106                                           const Aspect_RenderingContext theContext) Standard_OVERRIDE;
107
108   //! Returns window associated with the view.
109   virtual Handle(Aspect_Window) Window() const Standard_OVERRIDE
110   { return myWindow->PlatformWindow(); }
111
112   //! Returns True if the window associated to the view is defined.
113   virtual Standard_Boolean IsDefined() const Standard_OVERRIDE
114   { return !myWindow.IsNull(); }
115
116   //! Handle changing size of the rendering window.
117   Standard_EXPORT virtual void Resized() Standard_OVERRIDE;
118
119   //! Redraw content of the view.
120   Standard_EXPORT virtual void Redraw() Standard_OVERRIDE;
121
122   //! Redraw immediate content of the view.
123   Standard_EXPORT virtual void RedrawImmediate() Standard_OVERRIDE;
124
125   //! Marks BVH tree for given priority list as dirty and marks primitive set for rebuild.
126   Standard_EXPORT virtual void Invalidate() Standard_OVERRIDE;
127
128   //! Return true if view content cache has been invalidated.
129   virtual Standard_Boolean IsInvalidated() Standard_OVERRIDE { return !myBackBufferRestored; }
130
131   //! Displays z-buffer trihedron.
132   Standard_EXPORT virtual void TriedronDisplay (const Aspect_TypeOfTriedronPosition thePosition = Aspect_TOTP_CENTER,
133                                                 const Quantity_NameOfColor theColor = Quantity_NOC_WHITE,
134                                                 const Standard_Real theScale = 0.02,
135                                                 const Standard_Boolean theAsWireframe = Standard_True) Standard_OVERRIDE;
136
137   //! Erases z-buffer trihedron.
138   Standard_EXPORT virtual void TriedronErase() Standard_OVERRIDE;
139
140   //! Setup parameters of z-buffer trihedron.
141   Standard_EXPORT virtual void ZBufferTriedronSetup (const Quantity_NameOfColor theXColor = Quantity_NOC_RED,
142                                                      const Quantity_NameOfColor theYColor = Quantity_NOC_GREEN,
143                                                      const Quantity_NameOfColor theZColor = Quantity_NOC_BLUE1,
144                                                      const Standard_Real theSizeRatio = 0.8,
145                                                      const Standard_Real theAxisDiametr = 0.05,
146                                                      const Standard_Integer theNbFacettes = 12) Standard_OVERRIDE;
147
148   //! Displays trihedron echo.
149   Standard_EXPORT virtual void TriedronEcho (const Aspect_TypeOfTriedronEcho theType = Aspect_TOTE_NONE) Standard_OVERRIDE;
150
151   //! Returns data of a graduated trihedron
152   const Graphic3d_GraduatedTrihedron& GetGraduatedTrihedron() Standard_OVERRIDE
153   { return myGTrihedronData; }
154
155   //! Displays Graduated Trihedron.
156   Standard_EXPORT virtual void GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData) Standard_OVERRIDE;
157
158   //! Erases Graduated Trihedron.
159   Standard_EXPORT virtual void GraduatedTrihedronErase() Standard_OVERRIDE;
160
161   //! Sets minimum and maximum points of scene bounding box for Graduated Trihedron stored in graphic view object.
162   //! @param theMin [in] the minimum point of scene.
163   //! @param theMax [in] the maximum point of scene.
164   Standard_EXPORT virtual void GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax) Standard_OVERRIDE;
165
166   //! Dump active rendering buffer into specified memory buffer.
167   Standard_EXPORT virtual Standard_Boolean BufferDump (Image_PixMap& theImage,
168                                                        const Graphic3d_BufferType& theBufferType) Standard_OVERRIDE;
169
170   //! Export scene into the one of the Vector graphics formats (SVG, PS, PDF...).
171   //! In contrast to Bitmaps, Vector graphics is scalable (so you may got quality benefits
172   //! on printing to laser printer). Notice however that results may differ a lot and
173   //! do not contain some elements.
174   Standard_EXPORT virtual Standard_Boolean Export (const Standard_CString theFileName,
175                                                    const Graphic3d_ExportFormat theFormat,
176                                                    const Graphic3d_SortType theSortType = Graphic3d_ST_BSP_Tree) Standard_OVERRIDE;
177
178   //! Marks BVH tree and the set of BVH primitives of correspondent priority list with id theLayerId as outdated.
179   Standard_EXPORT virtual void InvalidateBVHData (const Standard_Integer theLayerId) Standard_OVERRIDE;
180
181   //! Insert a new top-level z layer with the given ID.
182   Standard_EXPORT virtual void AddZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
183
184   //! Remove a z layer with the given ID.
185   Standard_EXPORT virtual void RemoveZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
186
187   //! Sets the settings for a single Z layer of specified view.
188   Standard_EXPORT virtual void SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
189                                                   const Graphic3d_ZLayerSettings& theSettings) Standard_OVERRIDE;
190
191   //! Returns the maximum Z layer ID.
192   //! First layer ID is Graphic3d_ZLayerId_Default, last ID is ZLayerMax().
193   Standard_EXPORT virtual Standard_Integer ZLayerMax() const Standard_OVERRIDE;
194
195   //! Returns the bounding box of all structures displayed in the Z layer.
196   //! Never fails. If Z layer does not exist nothing happens.
197   Standard_EXPORT virtual void InvalidateZLayerBoundingBox (const Graphic3d_ZLayerId theLayerId) const Standard_OVERRIDE;
198
199   //! Returns the bounding box of all structures displayed in the Z layer.
200   //! If Z layer does not exist the empty box is returned.
201   //! @param theLayerId            layer identifier
202   //! @param theCamera             camera definition
203   //! @param theWindowWidth        viewport width  (for applying transformation-persistence)
204   //! @param theWindowHeight       viewport height (for applying transformation-persistence)
205   //! @param theToIncludeAuxiliary consider also auxiliary presentations (with infinite flag or with trihedron transformation persistence)
206   //! @return computed bounding box
207   Standard_EXPORT virtual Graphic3d_BndBox4f ZLayerBoundingBox (const Graphic3d_ZLayerId        theLayerId,
208                                                                 const Handle(Graphic3d_Camera)& theCamera,
209                                                                 const Standard_Integer          theWindowWidth,
210                                                                 const Standard_Integer          theWindowHeight,
211                                                                 const Standard_Boolean          theToIncludeAuxiliary) const Standard_OVERRIDE;
212
213   //! Returns pointer to an assigned framebuffer object.
214   Standard_EXPORT virtual Handle(Standard_Transient) FBO() const Standard_OVERRIDE;
215
216   //! Sets framebuffer object for offscreen rendering.
217   Standard_EXPORT virtual void SetFBO (const Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
218
219   //! Generate offscreen FBO in the graphic library.
220   //! If not supported on hardware returns NULL.
221   Standard_EXPORT virtual Handle(Standard_Transient) FBOCreate (const Standard_Integer theWidth,
222                                                                 const Standard_Integer theHeight) Standard_OVERRIDE;
223
224   //! Remove offscreen FBO from the graphic library
225   Standard_EXPORT virtual void FBORelease (Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
226
227   //! Read offscreen FBO configuration.
228   Standard_EXPORT virtual void FBOGetDimensions (const Handle(Standard_Transient)& theFbo,
229                                                  Standard_Integer& theWidth,
230                                                  Standard_Integer& theHeight,
231                                                  Standard_Integer& theWidthMax,
232                                                  Standard_Integer& theHeightMax) Standard_OVERRIDE;
233
234   //! Change offscreen FBO viewport.
235   Standard_EXPORT virtual void FBOChangeViewport (const Handle(Standard_Transient)& theFbo,
236                                                   const Standard_Integer theWidth,
237                                                   const Standard_Integer theHeight) Standard_OVERRIDE;
238
239 public:
240
241   //! Returns background  fill color.
242   Standard_EXPORT virtual Aspect_Background Background() const Standard_OVERRIDE;
243
244   //! Sets background fill color.
245   Standard_EXPORT virtual void SetBackground (const Aspect_Background& theBackground) Standard_OVERRIDE;
246
247   //! Returns gradient background fill colors.
248   Standard_EXPORT virtual Aspect_GradientBackground GradientBackground() const Standard_OVERRIDE;
249
250   //! Sets gradient background fill colors.
251   Standard_EXPORT virtual void SetGradientBackground (const Aspect_GradientBackground& theBackground) Standard_OVERRIDE;
252
253   //! Returns background image texture file path.
254   Standard_EXPORT virtual TCollection_AsciiString BackgroundImage() Standard_OVERRIDE { return myBackgroundImagePath; }
255
256   //! Sets background image texture file path.
257   Standard_EXPORT virtual void SetBackgroundImage (const TCollection_AsciiString& theFilePath) Standard_OVERRIDE;
258
259   //! Returns background image fill style.
260   Standard_EXPORT virtual Aspect_FillMethod BackgroundImageStyle() const Standard_OVERRIDE;
261
262   //! Sets background image fill style.
263   Standard_EXPORT virtual void SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle) Standard_OVERRIDE;
264
265   //! Returns environment texture set for the view.
266   Standard_EXPORT virtual Handle(Graphic3d_TextureEnv) TextureEnv() const Standard_OVERRIDE { return myTextureEnvData; }
267
268   //! Sets environment texture for the view.
269   Standard_EXPORT virtual void SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv) Standard_OVERRIDE;
270
271   //! Returns the state of frustum culling optimization.
272   virtual Standard_Boolean IsCullingEnabled() const Standard_OVERRIDE { return myCulling; }
273
274   //! Enables or disables frustum culling optimization.
275   virtual void SetCullingEnabled (const Standard_Boolean theIsEnabled) Standard_OVERRIDE { myCulling = theIsEnabled; }
276
277   //! Returns shading model of the view.
278   virtual Graphic3d_TypeOfShadingModel ShadingModel() const Standard_OVERRIDE { return myShadingModel; }
279
280   //! Sets shading model of the view.
281   virtual void SetShadingModel (const Graphic3d_TypeOfShadingModel theModel) Standard_OVERRIDE { myShadingModel = theModel; }
282
283   //! Return backfacing model used for the view.
284   virtual Graphic3d_TypeOfBackfacingModel BackfacingModel() const Standard_OVERRIDE { return myBackfacing; }
285
286   //! Sets backfacing model for the view.
287   virtual void SetBackfacingModel (const Graphic3d_TypeOfBackfacingModel theModel) Standard_OVERRIDE { myBackfacing = theModel; }
288
289   //! Returns camera object of the view.
290   virtual const Handle(Graphic3d_Camera)& Camera() const Standard_OVERRIDE { return myCamera; }
291
292   //! Sets camera used by the view.
293   virtual void SetCamera (const Handle(Graphic3d_Camera)& theCamera) Standard_OVERRIDE { myCamera = theCamera; }
294
295   //! Returns true if GL lighting is enabled.
296   virtual Standard_Boolean IsGLLightEnabled() const Standard_OVERRIDE { return myUseGLLight; }
297
298   //! Sets GL lighting enabled or disable state.
299   virtual void SetGLLightEnabled (const Standard_Boolean theIsEnabled) Standard_OVERRIDE { myUseGLLight = theIsEnabled; }
300
301   //! Returns list of lights of the view.
302   virtual const Graphic3d_ListOfCLight& Lights() const Standard_OVERRIDE { return myLights; }
303
304   //! Sets list of lights for the view.
305   virtual void SetLights (const Graphic3d_ListOfCLight& theLights) Standard_OVERRIDE
306   {
307     myLights = theLights;
308     myCurrLightSourceState = myStateCounter->Increment();
309   }
310
311   //! Returns list of clip planes set for the view.
312   virtual const Graphic3d_SequenceOfHClipPlane& ClipPlanes() const Standard_OVERRIDE { return myClipPlanes; }
313
314   //! Sets list of clip planes for the view.
315   virtual void SetClipPlanes (const Graphic3d_SequenceOfHClipPlane& thePlanes) Standard_OVERRIDE { myClipPlanes = thePlanes; }
316
317 public:
318
319   //! Returns background color.
320   const Quantity_ColorRGBA& BackgroundColor() const { return myBgColor; }
321
322   //! Change trihedron.
323   OpenGl_Trihedron& ChangeTrihedron() { return myTrihedron; }
324
325   //! Change graduated trihedron.
326   OpenGl_GraduatedTrihedron& ChangeGraduatedTrihedron() { return myGraduatedTrihedron; }
327
328   void SetTextureEnv (const Handle(OpenGl_Context)&       theCtx,
329                       const Handle(Graphic3d_TextureEnv)& theTexture);
330
331   void SetBackgroundTextureStyle (const Aspect_FillMethod FillStyle);
332
333   void SetBackgroundGradient (const Quantity_Color& AColor1, const Quantity_Color& AColor2, const Aspect_GradientFillMethod AType);
334
335   void SetBackgroundGradientType (const Aspect_GradientFillMethod AType);
336
337   //! Returns list of OpenGL Z-layers.
338   const OpenGl_LayerList& LayerList() const { return myZLayers; }
339
340   //! Returns list of openGL light sources.
341   const OpenGl_ListOfLight& LightList() const { return myLights; }
342
343   //! Returns OpenGL window implementation.
344   const Handle(OpenGl_Window) GlWindow() const { return myWindow; }
345
346   //! Returns OpenGL environment map.
347   const Handle(OpenGl_Texture)& GlTextureEnv() const { return myTextureEnv; }
348
349   //! Returns selector for BVH tree, providing a possibility to store information
350   //! about current view volume and to detect which objects are overlapping it.
351   OpenGl_BVHTreeSelector& BVHTreeSelector() { return myBVHSelector; }
352
353   //! Returns true if there are immediate structures to display
354   bool HasImmediateStructures() const
355   {
356     return myZLayers.NbImmediateStructures() != 0;
357   }
358
359 protected: //! @name Internal methods for managing GL resources
360
361   //! Initializes OpenGl resource for environment texture.
362   void initTextureEnv (const Handle(OpenGl_Context)& theContext);
363
364 protected: //! @name low-level redrawing sub-routines
365
366   //! Redraws view for the given monographic camera projection, or left/right eye.
367   Standard_EXPORT virtual void redraw (const Graphic3d_Camera::Projection theProjection,
368                                        OpenGl_FrameBuffer*                theReadDrawFbo);
369
370   //! Redraws view for the given monographic camera projection, or left/right eye.
371   //!
372   //! Method will blit snapshot containing main scene (myMainSceneFbos or BackBuffer)
373   //! into presentation buffer (myMainSceneFbos -> offscreen FBO or
374   //! myMainSceneFbos -> BackBuffer or BackBuffer -> FrontBuffer),
375   //! and redraw immediate structures on top.
376   //!
377   //! When scene caching is disabled (myTransientDrawToFront, no double buffer in window, etc.),
378   //! the first step (blitting) will be skipped.
379   //!
380   //! @return false if immediate structures has been rendered directly into FrontBuffer
381   //! and Buffer Swap should not be called.
382   Standard_EXPORT virtual bool redrawImmediate (const Graphic3d_Camera::Projection theProjection,
383                                                 OpenGl_FrameBuffer* theReadFbo,
384                                                 OpenGl_FrameBuffer* theDrawFbo,
385                                                 const Standard_Boolean theIsPartialUpdate = Standard_False);
386
387   //! Blit image from/to specified buffers.
388   Standard_EXPORT bool blitBuffers (OpenGl_FrameBuffer*    theReadFbo,
389                                     OpenGl_FrameBuffer*    theDrawFbo,
390                                     const Standard_Boolean theToFlip = Standard_False);
391
392   //! Setup default FBO.
393   Standard_EXPORT void bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo = NULL);
394
395 protected: //! @name Rendering of GL graphics (with prepared drawing buffer).
396
397   //! Renders the graphical contents of the view into the preprepared window or framebuffer.
398   //! @param theProjection [in] the projection that should be used for rendering.
399   //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
400   //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
401   Standard_EXPORT virtual void render (Graphic3d_Camera::Projection theProjection,
402                                        OpenGl_FrameBuffer*          theReadDrawFbo,
403                                        const Standard_Boolean       theToDrawImmediate);
404
405   //! Renders the graphical scene.
406   //! @param theProjection [in] the projection that is used for rendering.
407   //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
408   //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
409   Standard_EXPORT virtual void renderScene (Graphic3d_Camera::Projection theProjection,
410                                             OpenGl_FrameBuffer*    theReadDrawFbo,
411                                             const Standard_Boolean theToDrawImmediate);
412
413   //! Draw background (gradient / image)
414   Standard_EXPORT virtual void drawBackground (const Handle(OpenGl_Workspace)& theWorkspace);
415
416   //! Render set of structures presented in the view.
417   //! @param theProjection [in] the projection that is used for rendering.
418   //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
419   //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
420   Standard_EXPORT virtual void renderStructs (Graphic3d_Camera::Projection theProjection,
421                                               OpenGl_FrameBuffer*    theReadDrawFbo,
422                                               const Standard_Boolean theToDrawImmediate);
423
424   //! Renders trihedron.
425   void renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace);
426
427 private:
428
429   //! Adds the structure to display lists of the view.
430   Standard_EXPORT virtual void displayStructure (const Handle(Graphic3d_CStructure)& theStructure,
431                                                  const Standard_Integer thePriority) Standard_OVERRIDE;
432
433   //! Erases the structure from display lists of the view.
434   Standard_EXPORT virtual void eraseStructure (const Handle(Graphic3d_CStructure)& theStructure) Standard_OVERRIDE;
435
436   //! Change Z layer of a structure already presented in view.
437   Standard_EXPORT virtual void changeZLayer (const Handle(Graphic3d_CStructure)& theCStructure,
438                                              const Graphic3d_ZLayerId theNewLayerId) Standard_OVERRIDE;
439
440   //! Changes the priority of a structure within its Z layer in the specified view.
441   Standard_EXPORT virtual void changePriority (const Handle(Graphic3d_CStructure)& theCStructure,
442                                                const Standard_Integer theNewPriority) Standard_OVERRIDE;
443
444   //! Returns zoom-scale factor.
445   Standard_EXPORT virtual Standard_Real considerZoomPersistenceObjects (const Graphic3d_ZLayerId        theLayerId,
446                                                                         const Handle(Graphic3d_Camera)& theCamera,
447                                                                         const Standard_Integer          theWindowWidth,
448                                                                         const Standard_Integer          theWindowHeight) const Standard_OVERRIDE;
449
450 private:
451
452   //! Copy content of Back buffer to the Front buffer.
453   void copyBackToFront();
454
455   //! Initialize blit quad.
456   OpenGl_VertexBuffer* initBlitQuad (const Standard_Boolean theToFlip);
457
458   //! Blend together views pair into stereo image.
459   void drawStereoPair (OpenGl_FrameBuffer* theDrawFbo);
460
461 protected:
462
463   OpenGl_GraphicDriver*    myDriver;
464   Handle(OpenGl_Window)    myWindow;
465   Handle(OpenGl_Workspace) myWorkspace;
466   Handle(OpenGl_Caps)      myCaps;
467   Standard_Boolean&        myDeviceLostFlag;
468   Standard_Boolean         myWasRedrawnGL;
469
470   Standard_Boolean                myCulling;
471   Graphic3d_TypeOfShadingModel    myShadingModel;
472   Graphic3d_TypeOfBackfacingModel myBackfacing;
473   Quantity_ColorRGBA              myBgColor;
474   Graphic3d_SequenceOfHClipPlane  myClipPlanes;
475   Handle(Graphic3d_Camera)        myCamera;
476   Handle(OpenGl_FrameBuffer)      myFBO;
477   Standard_Boolean                myUseGLLight;
478   Standard_Boolean                myToShowTrihedron;
479   Standard_Boolean                myToShowGradTrihedron;
480   TCollection_AsciiString         myBackgroundImagePath;
481   Handle(Graphic3d_TextureEnv)    myTextureEnvData;
482   Graphic3d_GraduatedTrihedron    myGTrihedronData;
483
484   OpenGl_ListOfLight              myNoShadingLight;
485   OpenGl_ListOfLight              myLights;
486   OpenGl_LayerList                myZLayers; //!< main list of displayed structure, sorted by layers
487
488   Graphic3d_WorldViewProjState    myWorldViewProjState; //!< camera modification state
489   OpenGl_StateCounter*            myStateCounter;
490   Standard_Size                   myCurrLightSourceState;
491
492   typedef std::pair<Standard_Size, Standard_Size> StateInfo;
493
494   StateInfo myLastOrientationState;
495   StateInfo myLastViewMappingState;
496   StateInfo myLastLightSourceState;
497
498   //! Is needed for selection of overlapping objects and storage of the current view volume
499   OpenGl_BVHTreeSelector myBVHSelector;
500
501   OpenGl_Trihedron          myTrihedron;
502   OpenGl_GraduatedTrihedron myGraduatedTrihedron;
503
504   Handle(OpenGl_Texture) myTextureEnv;
505
506 protected: //! @name Rendering properties
507
508   //! Two framebuffers (left and right views) store cached main presentation
509   //! of the view (without presentation of immediate layers).
510   GLint                      myFboColorFormat;        //!< sized format for color attachments
511   GLint                      myFboDepthFormat;        //!< sized format for depth-stencil attachments
512   Handle(OpenGl_FrameBuffer) myMainSceneFbos[2];
513   Handle(OpenGl_FrameBuffer) myImmediateSceneFbos[2]; //!< Additional buffers for immediate layer in stereo mode.
514   OpenGl_VertexBuffer        myFullScreenQuad;        //!< Vertices for full-screen quad rendering.
515   OpenGl_VertexBuffer        myFullScreenQuadFlip;
516   Standard_Boolean           myToFlipOutput;          //!< Flag to draw result image upside-down
517   unsigned int               myFrameCounter;          //!< redraw counter, for debugging
518   Standard_Boolean           myHasFboBlit;            //!< disable FBOs on failure
519   Standard_Boolean           myToDisableMSAA;         //!< disable MSAA after failure
520   Standard_Boolean           myTransientDrawToFront; //!< optimization flag for immediate mode (to render directly to the front buffer)
521   Standard_Boolean           myBackBufferRestored;
522   Standard_Boolean           myIsImmediateDrawn;     //!< flag indicates that immediate mode buffer contains some data
523
524 protected: //! @name Background parameters
525
526   OpenGl_AspectFace*      myTextureParams;   //!< Stores texture and its parameters for textured background
527   OpenGl_BackgroundArray* myBgGradientArray; //!< Primitive array for gradient background
528   OpenGl_BackgroundArray* myBgTextureArray;  //!< Primitive array for texture  background
529
530 protected: //! @name data types related to ray-tracing
531
532   //! Result of OpenGL shaders initialization.
533   enum RaytraceInitStatus
534   {
535     OpenGl_RT_NONE,
536     OpenGl_RT_INIT,
537     OpenGl_RT_FAIL
538   };
539
540   //! Describes update mode (state).
541   enum RaytraceUpdateMode
542   {
543     OpenGl_GUM_CHECK,   //!< check geometry state
544     OpenGl_GUM_PREPARE, //!< collect unchanged objects
545     OpenGl_GUM_REBUILD  //!< rebuild changed and new objects
546   };
547
548   //! Defines frequently used shader variables.
549   enum ShaderVariableIndex
550   {
551     OpenGl_RT_aPosition,
552
553     // camera position
554     OpenGl_RT_uOriginLT,
555     OpenGl_RT_uOriginLB,
556     OpenGl_RT_uOriginRT,
557     OpenGl_RT_uOriginRB,
558     OpenGl_RT_uDirectLT,
559     OpenGl_RT_uDirectLB,
560     OpenGl_RT_uDirectRT,
561     OpenGl_RT_uDirectRB,
562     OpenGl_RT_uViewMat,
563     OpenGl_RT_uUnviewMat,
564
565     // 3D scene params
566     OpenGl_RT_uSceneRad,
567     OpenGl_RT_uSceneEps,
568     OpenGl_RT_uLightAmbnt,
569     OpenGl_RT_uLightCount,
570
571     // background params
572     OpenGl_RT_uBackColorTop,
573     OpenGl_RT_uBackColorBot,
574
575     // ray-tracing params
576     OpenGl_RT_uShadowsEnabled,
577     OpenGl_RT_uReflectEnabled,
578     OpenGl_RT_uSphereMapEnabled,
579     OpenGl_RT_uSphereMapForBack,
580     OpenGl_RT_uTexSamplersArray,
581     OpenGl_RT_uBlockedRngEnabled,
582
583     // sampled frame params
584     OpenGl_RT_uSampleWeight,
585     OpenGl_RT_uFrameRndSeed,
586
587     // adaptive FSAA params
588     OpenGl_RT_uOffsetX,
589     OpenGl_RT_uOffsetY,
590     OpenGl_RT_uSamples,
591
592     OpenGl_RT_NbVariables // special field
593   };
594
595   //! Defines texture samplers.
596   enum ShaderSamplerNames
597   {
598     OpenGl_RT_SceneNodeInfoTexture  = 0,
599     OpenGl_RT_SceneMinPointTexture  = 1,
600     OpenGl_RT_SceneMaxPointTexture  = 2,
601     OpenGl_RT_SceneTransformTexture = 3,
602
603     OpenGl_RT_GeometryVertexTexture = 4,
604     OpenGl_RT_GeometryNormalTexture = 5,
605     OpenGl_RT_GeometryTexCrdTexture = 6,
606     OpenGl_RT_GeometryTriangTexture = 7,
607
608     OpenGl_RT_EnvironmentMapTexture = 8,
609
610     OpenGl_RT_RaytraceMaterialTexture = 9,
611     OpenGl_RT_RaytraceLightSrcTexture = 10,
612
613     OpenGl_RT_FsaaInputTexture = 11,
614     OpenGl_RT_PrevAccumTexture = 12,
615     OpenGl_RT_DepthTexture = 13,
616
617     OpenGl_RT_OpenGlColorTexture = 14,
618     OpenGl_RT_OpenGlDepthTexture = 15
619   };
620
621   //! Tool class for management of shader sources.
622   class ShaderSource
623   {
624   public:
625
626     //! Default shader prefix - empty string.
627     static const TCollection_AsciiString EMPTY_PREFIX;
628
629     //! Creates new uninitialized shader source.
630     ShaderSource()
631     {
632       //
633     }
634
635   public:
636
637     //! Returns error description in case of load fail.
638     const TCollection_AsciiString& ErrorDescription() const
639     {
640       return myError;
641     }
642
643     //! Returns prefix to insert before the source.
644     const TCollection_AsciiString& Prefix() const
645     {
646       return myPrefix;
647     }
648
649     //! Sets prefix to insert before the source.
650     void SetPrefix (const TCollection_AsciiString& thePrefix)
651     {
652       myPrefix = thePrefix;
653     }
654
655     //! Returns shader source combined with prefix.
656     TCollection_AsciiString Source() const;
657
658     //! Loads shader source from specified files.
659     Standard_Boolean Load (const TCollection_AsciiString* theFileNames, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
660
661   private:
662
663     TCollection_AsciiString mySource; //!< Source string of the shader object
664     TCollection_AsciiString myPrefix; //!< Prefix to insert before the source
665     TCollection_AsciiString myError;  //!< error state
666
667   };
668
669   //! Default ray-tracing depth.
670   static const Standard_Integer THE_DEFAULT_NB_BOUNCES = 3;
671
672   //! Default size of traversal stack.
673   static const Standard_Integer THE_DEFAULT_STACK_SIZE = 10;
674
675   //! Compile-time ray-tracing parameters.
676   struct RaytracingParams
677   {
678     //! Actual size of traversal stack in shader program.
679     Standard_Integer StackSize;
680
681     //! Actual ray-tracing depth (number of ray bounces).
682     Standard_Integer NbBounces;
683
684     //! Enables/disables light propagation through transparent media.
685     Standard_Boolean TransparentShadows;
686
687     //! Enables/disables global illumination (GI) effects.
688     Standard_Boolean GlobalIllumination;
689
690     //! Enables/disables the use of OpenGL bindless textures.
691     Standard_Boolean UseBindlessTextures;
692
693     //! Creates default compile-time ray-tracing parameters.
694     RaytracingParams()
695     : StackSize (THE_DEFAULT_STACK_SIZE),
696       NbBounces (THE_DEFAULT_NB_BOUNCES),
697       TransparentShadows (Standard_False),
698       GlobalIllumination  (Standard_False),
699       UseBindlessTextures (Standard_False)
700     {
701       //
702     }
703   };
704
705   //! Describes state of OpenGL structure.
706   struct StructState
707   {
708     Standard_Size StructureState;
709     Standard_Size InstancedState;
710
711     //! Creates new structure state.
712     StructState (const Standard_Size theStructureState = 0,
713                  const Standard_Size theInstancedState = 0)
714     : StructureState (theStructureState),
715       InstancedState (theInstancedState)
716     {
717       //
718     }
719
720     //! Creates new structure state.
721     StructState (const OpenGl_Structure* theStructure)
722     {
723       StructureState = theStructure->ModificationState();
724
725       InstancedState = theStructure->InstancedStructure() != NULL ?
726         theStructure->InstancedStructure()->ModificationState() : 0;
727     }
728   };
729
730 protected: //! @name methods related to ray-tracing
731
732   //! Updates 3D scene geometry for ray-tracing.
733   Standard_Boolean updateRaytraceGeometry (const RaytraceUpdateMode      theMode,
734                                            const Standard_Integer        theViewId,
735                                            const Handle(OpenGl_Context)& theGlContext);
736
737   //! Updates 3D scene light sources for ray-tracing.
738   Standard_Boolean updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext);
739
740   //! Updates environment map for ray-tracing.
741   Standard_Boolean updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext);
742
743   //! Checks to see if the OpenGL structure is modified.
744   Standard_Boolean toUpdateStructure (const OpenGl_Structure* theStructure);
745
746   //! Adds OpenGL structure to ray-traced scene geometry.
747   Standard_Boolean addRaytraceStructure (const OpenGl_Structure*       theStructure,
748                                          const Handle(OpenGl_Context)& theGlContext);
749
750   //! Adds OpenGL groups to ray-traced scene geometry.
751   Standard_Boolean addRaytraceGroups (const OpenGl_Structure*        theStructure,
752                                       const OpenGl_RaytraceMaterial& theStructMat,
753                                       const Graphic3d_Mat4*          theTransform,
754                                       const Handle(OpenGl_Context)&  theGlContext);
755
756   //! Creates ray-tracing material properties.
757   OpenGl_RaytraceMaterial convertMaterial (const OpenGl_AspectFace*      theAspect,
758                                            const Handle(OpenGl_Context)& theGlContext);
759
760   //! Adds OpenGL primitive array to ray-traced scene geometry.
761   OpenGl_TriangleSet* addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
762                                                  const Standard_Integer       theMatID,
763                                                  const OpenGl_Mat4*           theTrans);
764
765   //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry.
766   Standard_Boolean addRaytraceVertexIndices (OpenGl_TriangleSet&                  theSet,
767                                              const Standard_Integer               theMatID,
768                                              const Standard_Integer               theCount,
769                                              const Standard_Integer               theOffset,
770                                              const OpenGl_PrimitiveArray&         theArray);
771
772   //! Adds OpenGL triangle array to ray-traced scene geometry.
773   Standard_Boolean addRaytraceTriangleArray (OpenGl_TriangleSet&                  theSet,
774                                              const Standard_Integer               theMatID,
775                                              const Standard_Integer               theCount,
776                                              const Standard_Integer               theOffset,
777                                              const Handle(Graphic3d_IndexBuffer)& theIndices);
778
779   //! Adds OpenGL triangle fan array to ray-traced scene geometry.
780   Standard_Boolean addRaytraceTriangleFanArray (OpenGl_TriangleSet&                  theSet,
781                                                 const Standard_Integer               theMatID,
782                                                 const Standard_Integer               theCount,
783                                                 const Standard_Integer               theOffset,
784                                                 const Handle(Graphic3d_IndexBuffer)& theIndices);
785
786   //! Adds OpenGL triangle strip array to ray-traced scene geometry.
787   Standard_Boolean addRaytraceTriangleStripArray (OpenGl_TriangleSet&                  theSet,
788                                                   const Standard_Integer               theMatID,
789                                                   const Standard_Integer               theCount,
790                                                   const Standard_Integer               theOffset,
791                                                   const Handle(Graphic3d_IndexBuffer)& theIndices);
792
793   //! Adds OpenGL quadrangle array to ray-traced scene geometry.
794   Standard_Boolean addRaytraceQuadrangleArray (OpenGl_TriangleSet&                  theSet,
795                                                const Standard_Integer               theMatID,
796                                                const Standard_Integer               theCount,
797                                                const Standard_Integer               theOffset,
798                                                const Handle(Graphic3d_IndexBuffer)& theIndices);
799
800   //! Adds OpenGL quadrangle strip array to ray-traced scene geometry.
801   Standard_Boolean addRaytraceQuadrangleStripArray (OpenGl_TriangleSet&                  theSet,
802                                                     const Standard_Integer               theMatID,
803                                                     const Standard_Integer               theCount,
804                                                     const Standard_Integer               theOffset,
805                                                     const Handle(Graphic3d_IndexBuffer)& theIndices);
806
807   //! Adds OpenGL polygon array to ray-traced scene geometry.
808   Standard_Boolean addRaytracePolygonArray (OpenGl_TriangleSet&                  theSet,
809                                             const Standard_Integer               theMatID,
810                                             const Standard_Integer               theCount,
811                                             const Standard_Integer               theOffset,
812                                             const Handle(Graphic3d_IndexBuffer)& theIndices);
813
814   //! Uploads ray-trace data to the GPU.
815   Standard_Boolean uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext);
816
817   //! Generates shader prefix based on current ray-tracing options.
818   TCollection_AsciiString generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const;
819
820   //! Performs safe exit when shaders initialization fails.
821   Standard_Boolean safeFailBack (const TCollection_ExtendedString& theMessage,
822                                  const Handle(OpenGl_Context)&     theGlContext);
823
824   //! Loads and compiles shader object from specified source.
825   Handle(OpenGl_ShaderObject) initShader (const GLenum                  theType,
826                                           const ShaderSource&           theSource,
827                                           const Handle(OpenGl_Context)& theGlContext);
828
829   //! Creates shader program from the given vertex and fragment shaders.
830   Handle(OpenGl_ShaderProgram) initProgram (const Handle(OpenGl_Context)&      theGlContext,
831                                             const Handle(OpenGl_ShaderObject)& theVertShader,
832                                             const Handle(OpenGl_ShaderObject)& theFragShader);
833
834   //! Initializes OpenGL/GLSL shader programs.
835   Standard_Boolean initRaytraceResources (const Handle(OpenGl_Context)& theGlContext);
836
837   //! Releases OpenGL/GLSL shader programs.
838   void releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext);
839
840   //! Updates auxiliary OpenGL frame buffers.
841   Standard_Boolean updateRaytraceBuffers (const Standard_Integer        theSizeX,
842                                           const Standard_Integer        theSizeY,
843                                           const Handle(OpenGl_Context)& theGlContext);
844
845   //! Generates viewing rays for corners of screen quad.
846   void updateCamera (const OpenGl_Mat4& theOrientation,
847                      const OpenGl_Mat4& theViewMapping,
848                      OpenGl_Vec3*       theOrigins,
849                      OpenGl_Vec3*       theDirects,
850                      OpenGl_Mat4&       theView,
851                      OpenGl_Mat4&       theUnView);
852
853   //! Binds ray-trace textures to corresponding texture units.
854   void bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
855
856   //! Unbinds ray-trace textures from corresponding texture unit.
857   void unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
858
859   //! Sets uniform state for the given ray-tracing shader program.
860   Standard_Boolean setUniformState (const OpenGl_Vec3*            theOrigins,
861                                     const OpenGl_Vec3*            theDirects,
862                                     const OpenGl_Mat4&            theViewMat,
863                                     const OpenGl_Mat4&            theUnviewMat,
864                                     const Standard_Integer        theProgramId,
865                                     const Handle(OpenGl_Context)& theGlContext);
866
867   //! Runs ray-tracing shader programs.
868   Standard_Boolean runRaytraceShaders (const Standard_Integer        theSizeX,
869                                        const Standard_Integer        theSizeY,
870                                        const OpenGl_Vec3*            theOrigins,
871                                        const OpenGl_Vec3*            theDirects,
872                                        const OpenGl_Mat4&            theViewMat,
873                                        const OpenGl_Mat4&            theUnviewMat,
874                                        Graphic3d_Camera::Projection  theProjection,
875                                        OpenGl_FrameBuffer*           theReadDrawFbo,
876                                        const Handle(OpenGl_Context)& theGlContext);
877
878   //! Redraws the window using OpenGL/GLSL ray-tracing.
879   Standard_Boolean raytrace (const Standard_Integer        theSizeX,
880                              const Standard_Integer        theSizeY,
881                              Graphic3d_Camera::Projection  theProjection,
882                              OpenGl_FrameBuffer*           theReadDrawFbo,
883                              const Handle(OpenGl_Context)& theGlContext);
884
885 protected: //! @name fields related to ray-tracing
886
887   //! Result of shaders initialization.
888   RaytraceInitStatus myRaytraceInitStatus;
889
890   //! Is geometry data valid?
891   Standard_Boolean myIsRaytraceDataValid;
892
893   //! Warning about missing extension GL_ARB_bindless_texture has been displayed?
894   Standard_Boolean myIsRaytraceWarnTextures;
895
896   //! 3D scene geometry data for ray-tracing.
897   OpenGl_RaytraceGeometry myRaytraceGeometry;
898
899   //! Compile-time ray-tracing parameters.
900   RaytracingParams myRaytraceParameters;
901
902   //! Radius of bounding sphere of the scene.
903   Standard_ShortReal myRaytraceSceneRadius;
904   //! Scene epsilon to prevent self-intersections.
905   Standard_ShortReal myRaytraceSceneEpsilon;
906
907   //! OpenGL/GLSL source of ray-tracing fragment shader.
908   ShaderSource myRaytraceShaderSource;
909   //! OpenGL/GLSL source of adaptive-AA fragment shader.
910   ShaderSource myPostFSAAShaderSource;
911
912   //! OpenGL/GLSL ray-tracing fragment shader.
913   Handle(OpenGl_ShaderObject) myRaytraceShader;
914   //! OpenGL/GLSL adaptive-AA fragment shader.
915   Handle(OpenGl_ShaderObject) myPostFSAAShader;
916
917   //! OpenGL/GLSL ray-tracing shader program.
918   Handle(OpenGl_ShaderProgram) myRaytraceProgram;
919   //! OpenGL/GLSL adaptive-AA shader program.
920   Handle(OpenGl_ShaderProgram) myPostFSAAProgram;
921   //! OpenGL/GLSL program for displaying texture.
922   Handle(OpenGl_ShaderProgram) myOutImageProgram;
923
924   //! Texture buffer of data records of bottom-level BVH nodes.
925   Handle(OpenGl_TextureBufferArb) mySceneNodeInfoTexture;
926   //! Texture buffer of minimum points of bottom-level BVH nodes.
927   Handle(OpenGl_TextureBufferArb) mySceneMinPointTexture;
928   //! Texture buffer of maximum points of bottom-level BVH nodes.
929   Handle(OpenGl_TextureBufferArb) mySceneMaxPointTexture;
930   //! Texture buffer of transformations of high-level BVH nodes.
931   Handle(OpenGl_TextureBufferArb) mySceneTransformTexture;
932
933   //! Texture buffer of vertex coords.
934   Handle(OpenGl_TextureBufferArb) myGeometryVertexTexture;
935   //! Texture buffer of vertex normals.
936   Handle(OpenGl_TextureBufferArb) myGeometryNormalTexture;
937   //! Texture buffer of vertex UV coords.
938   Handle(OpenGl_TextureBufferArb) myGeometryTexCrdTexture;
939   //! Texture buffer of triangle indices.
940   Handle(OpenGl_TextureBufferArb) myGeometryTriangTexture;
941
942   //! Texture buffer of material properties.
943   Handle(OpenGl_TextureBufferArb) myRaytraceMaterialTexture;
944   //! Texture buffer of light source properties.
945   Handle(OpenGl_TextureBufferArb) myRaytraceLightSrcTexture;
946
947   //! 1st framebuffer (FBO) to perform adaptive FSAA.
948   Handle(OpenGl_FrameBuffer) myRaytraceFBO1[2];
949   //! 2nd framebuffer (FBO) to perform adaptive FSAA.
950   Handle(OpenGl_FrameBuffer) myRaytraceFBO2[2];
951   //! Framebuffer (FBO) for preliminary OpenGL output.
952   Handle(OpenGl_FrameBuffer) myOpenGlFBO;
953   Handle(OpenGl_FrameBuffer) myOpenGlFBO2;
954
955   //! Vertex buffer (VBO) for drawing dummy quad.
956   OpenGl_VertexBuffer myRaytraceScreenQuad;
957
958   //! Cached locations of frequently used uniform variables.
959   Standard_Integer myUniformLocations[2][OpenGl_RT_NbVariables];
960
961   //! State of OpenGL structures reflected to ray-tracing.
962   std::map<const OpenGl_Structure*, StructState> myStructureStates;
963
964   //! PrimitiveArray to TriangleSet map for scene partial update.
965   std::map<Standard_Size, OpenGl_TriangleSet*> myArrayToTrianglesMap;
966
967   //! Set of IDs of non-raytracable elements (to detect updates).
968   std::set<Standard_Integer> myNonRaytraceStructureIDs;
969
970   //! Render filter to filter out all raytracable structures.
971   Handle(OpenGl_RaytraceFilter) myRaytraceFilter;
972
973   //! Marks if environment map should be updated.
974   Standard_Boolean myToUpdateEnvironmentMap;
975
976   //! State of OpenGL layer list.
977   Standard_Size myLayerListState;
978
979   //! Number of accumulated frames (for progressive rendering).
980   Standard_Integer myAccumFrames;
981
982   //! Stored ray origins used for detection of camera movements.
983   OpenGl_Vec3 myPreviousOrigins[3];
984
985   //! Bullard RNG to produce random sequence.
986   math_BullardGenerator myRNG;
987
988 public:
989
990   DEFINE_STANDARD_ALLOC
991   DEFINE_STANDARD_RTTIEXT(OpenGl_View,Graphic3d_CView) // Type definition
992
993   friend class OpenGl_GraphicDriver;
994   friend class OpenGl_Workspace;
995 };
996
997 #endif // _OpenGl_View_Header