1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2014 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
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.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #ifndef _OpenGl_View_Header
17 #define _OpenGl_View_Header
19 #include <Standard_Transient.hxx>
20 #include <Standard_Type.hxx>
22 #include <TColStd_Array2OfReal.hxx>
23 #include <NCollection_List.hxx>
24 #include <math_BullardGenerator.hxx>
26 #include <Quantity_NameOfColor.hxx>
27 #include <Aspect_FillMethod.hxx>
28 #include <Aspect_GradientFillMethod.hxx>
30 #include <Graphic3d_CView.hxx>
31 #include <Graphic3d_CullingTool.hxx>
32 #include <Graphic3d_GraduatedTrihedron.hxx>
33 #include <Graphic3d_SequenceOfHClipPlane.hxx>
34 #include <Graphic3d_ToneMappingMethod.hxx>
35 #include <Graphic3d_TypeOfShadingModel.hxx>
36 #include <Graphic3d_WorldViewProjState.hxx>
37 #include <Graphic3d_ZLayerSettings.hxx>
39 #include <OpenGl_Aspects.hxx>
40 #include <OpenGl_BackgroundArray.hxx>
41 #include <OpenGl_Context.hxx>
42 #include <OpenGl_FrameBuffer.hxx>
43 #include <OpenGl_FrameStatsPrs.hxx>
44 #include <OpenGl_GraduatedTrihedron.hxx>
45 #include <OpenGl_LayerList.hxx>
46 #include <OpenGl_LineAttributes.hxx>
47 #include <OpenGl_SceneGeometry.hxx>
48 #include <OpenGl_Structure.hxx>
49 #include <OpenGl_Window.hxx>
50 #include <OpenGl_Workspace.hxx>
51 #include <OpenGl_TileSampler.hxx>
58 class Graphic3d_StructureManager;
59 class OpenGl_GraphicDriver;
60 class OpenGl_StateCounter;
61 class OpenGl_RaytraceMaterial;
62 class OpenGl_TriangleSet;
63 class OpenGl_Workspace;
65 DEFINE_STANDARD_HANDLE(OpenGl_View,Graphic3d_CView)
67 //! Implementation of OpenGl view.
68 class OpenGl_View : public Graphic3d_CView
74 Standard_EXPORT OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr,
75 const Handle(OpenGl_GraphicDriver)& theDriver,
76 const Handle(OpenGl_Caps)& theCaps,
77 OpenGl_StateCounter* theCounter);
79 //! Default destructor.
80 Standard_EXPORT virtual ~OpenGl_View();
82 Standard_EXPORT void ReleaseGlResources (const Handle(OpenGl_Context)& theCtx);
84 //! Deletes and erases the view.
85 Standard_EXPORT virtual void Remove() Standard_OVERRIDE;
87 //! @param theDrawToFrontBuffer Advanced option to modify rendering mode:
88 //! 1. TRUE. Drawing immediate mode structures directly to the front buffer over the scene image.
89 //! Fast, so preferred for interactive work (used by default).
90 //! However these extra drawings will be missed in image dump since it is performed from back buffer.
91 //! Notice that since no pre-buffering used the V-Sync will be ignored and rendering could be seen
92 //! in run-time (in case of slow hardware) and/or tearing may appear.
93 //! So this is strongly recommended to draw only simple (fast) structures.
94 //! 2. FALSE. Drawing immediate mode structures to the back buffer.
95 //! The complete scene is redrawn first, so this mode is slower if scene contains complex data and/or V-Sync
96 //! is turned on. But it works in any case and is especially useful for view dump because the dump image is read
97 //! from the back buffer.
98 //! @return previous mode.
99 Standard_EXPORT Standard_Boolean SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer) Standard_OVERRIDE;
101 //! Creates and maps rendering window to the view.
102 //! @param theWindow [in] the window.
103 //! @param theContext [in] the rendering context. If NULL the context will be created internally.
104 Standard_EXPORT virtual void SetWindow (const Handle(Aspect_Window)& theWindow,
105 const Aspect_RenderingContext theContext) Standard_OVERRIDE;
107 //! Returns window associated with the view.
108 virtual Handle(Aspect_Window) Window() const Standard_OVERRIDE
109 { return myWindow->PlatformWindow(); }
111 //! Returns True if the window associated to the view is defined.
112 virtual Standard_Boolean IsDefined() const Standard_OVERRIDE
113 { return !myWindow.IsNull(); }
115 //! Handle changing size of the rendering window.
116 Standard_EXPORT virtual void Resized() Standard_OVERRIDE;
118 //! Redraw content of the view.
119 Standard_EXPORT virtual void Redraw() Standard_OVERRIDE;
121 //! Redraw immediate content of the view.
122 Standard_EXPORT virtual void RedrawImmediate() Standard_OVERRIDE;
124 //! Marks BVH tree for given priority list as dirty and marks primitive set for rebuild.
125 Standard_EXPORT virtual void Invalidate() Standard_OVERRIDE;
127 //! Return true if view content cache has been invalidated.
128 virtual Standard_Boolean IsInvalidated() Standard_OVERRIDE { return !myBackBufferRestored; }
130 //! Dump active rendering buffer into specified memory buffer.
131 //! In Ray-Tracing allow to get a raw HDR buffer using Graphic3d_BT_RGB_RayTraceHdrLeft buffer type,
132 //! only Left view will be dumped ignoring stereoscopic parameter.
133 Standard_EXPORT virtual Standard_Boolean BufferDump (Image_PixMap& theImage,
134 const Graphic3d_BufferType& theBufferType) Standard_OVERRIDE;
136 //! Marks BVH tree and the set of BVH primitives of correspondent priority list with id theLayerId as outdated.
137 Standard_EXPORT virtual void InvalidateBVHData (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
139 //! Add a layer to the view.
140 //! @param theNewLayerId [in] id of new layer, should be > 0 (negative values are reserved for default layers).
141 //! @param theSettings [in] new layer settings
142 //! @param theLayerAfter [in] id of layer to append new layer before
143 Standard_EXPORT virtual void InsertLayerBefore (const Graphic3d_ZLayerId theLayerId,
144 const Graphic3d_ZLayerSettings& theSettings,
145 const Graphic3d_ZLayerId theLayerAfter) Standard_OVERRIDE;
147 //! Add a layer to the view.
148 //! @param theNewLayerId [in] id of new layer, should be > 0 (negative values are reserved for default layers).
149 //! @param theSettings [in] new layer settings
150 //! @param theLayerBefore [in] id of layer to append new layer after
151 Standard_EXPORT virtual void InsertLayerAfter (const Graphic3d_ZLayerId theNewLayerId,
152 const Graphic3d_ZLayerSettings& theSettings,
153 const Graphic3d_ZLayerId theLayerBefore) Standard_OVERRIDE;
155 //! Remove a z layer with the given ID.
156 Standard_EXPORT virtual void RemoveZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
158 //! Sets the settings for a single Z layer of specified view.
159 Standard_EXPORT virtual void SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
160 const Graphic3d_ZLayerSettings& theSettings) Standard_OVERRIDE;
162 //! Returns the maximum Z layer ID.
163 //! First layer ID is Graphic3d_ZLayerId_Default, last ID is ZLayerMax().
164 Standard_EXPORT virtual Standard_Integer ZLayerMax() const Standard_OVERRIDE;
166 //! Returns the list of layers.
167 Standard_EXPORT virtual const NCollection_List<Handle(Graphic3d_Layer)>& Layers() const Standard_OVERRIDE;
169 //! Returns layer with given ID or NULL if undefined.
170 Standard_EXPORT virtual Handle(Graphic3d_Layer) Layer (const Graphic3d_ZLayerId theLayerId) const Standard_OVERRIDE;
172 //! Returns the bounding box of all structures displayed in the view.
173 //! If theToIncludeAuxiliary is TRUE, then the boundary box also includes minimum and maximum limits
174 //! of graphical elements forming parts of infinite and other auxiliary structures.
175 //! @param theToIncludeAuxiliary consider also auxiliary presentations (with infinite flag or with trihedron transformation persistence)
176 //! @return computed bounding box
177 Standard_EXPORT virtual Bnd_Box MinMaxValues (const Standard_Boolean theToIncludeAuxiliary) const Standard_OVERRIDE;
179 //! Returns pointer to an assigned framebuffer object.
180 Standard_EXPORT virtual Handle(Standard_Transient) FBO() const Standard_OVERRIDE;
182 //! Sets framebuffer object for offscreen rendering.
183 Standard_EXPORT virtual void SetFBO (const Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
185 //! Generate offscreen FBO in the graphic library.
186 //! If not supported on hardware returns NULL.
187 Standard_EXPORT virtual Handle(Standard_Transient) FBOCreate (const Standard_Integer theWidth,
188 const Standard_Integer theHeight) Standard_OVERRIDE;
190 //! Remove offscreen FBO from the graphic library
191 Standard_EXPORT virtual void FBORelease (Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
193 //! Read offscreen FBO configuration.
194 Standard_EXPORT virtual void FBOGetDimensions (const Handle(Standard_Transient)& theFbo,
195 Standard_Integer& theWidth,
196 Standard_Integer& theHeight,
197 Standard_Integer& theWidthMax,
198 Standard_Integer& theHeightMax) Standard_OVERRIDE;
200 //! Change offscreen FBO viewport.
201 Standard_EXPORT virtual void FBOChangeViewport (const Handle(Standard_Transient)& theFbo,
202 const Standard_Integer theWidth,
203 const Standard_Integer theHeight) Standard_OVERRIDE;
207 //! Returns gradient background fill colors.
208 Standard_EXPORT virtual Aspect_GradientBackground GradientBackground() const Standard_OVERRIDE;
210 //! Sets gradient background fill colors.
211 Standard_EXPORT virtual void SetGradientBackground (const Aspect_GradientBackground& theBackground) Standard_OVERRIDE;
213 //! Returns background image texture file path.
214 virtual TCollection_AsciiString BackgroundImage() Standard_OVERRIDE { return myBackgroundImagePath; }
216 //! Sets background image texture file path.
217 Standard_EXPORT virtual void SetBackgroundImage (const TCollection_AsciiString& theFilePath) Standard_OVERRIDE;
219 //! Returns background image fill style.
220 Standard_EXPORT virtual Aspect_FillMethod BackgroundImageStyle() const Standard_OVERRIDE;
222 //! Sets background image fill style.
223 Standard_EXPORT virtual void SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle) Standard_OVERRIDE;
225 //! Returns environment texture set for the view.
226 virtual Handle(Graphic3d_TextureEnv) TextureEnv() const Standard_OVERRIDE { return myTextureEnvData; }
228 //! Sets environment texture for the view.
229 Standard_EXPORT virtual void SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv) Standard_OVERRIDE;
231 //! Return backfacing model used for the view.
232 virtual Graphic3d_TypeOfBackfacingModel BackfacingModel() const Standard_OVERRIDE { return myBackfacing; }
234 //! Sets backfacing model for the view.
235 virtual void SetBackfacingModel (const Graphic3d_TypeOfBackfacingModel theModel) Standard_OVERRIDE { myBackfacing = theModel; }
237 //! Returns local camera origin currently set for rendering, might be modified during rendering.
238 const gp_XYZ& LocalOrigin() const { return myLocalOrigin; }
240 //! Setup local camera origin currently set for rendering.
241 Standard_EXPORT void SetLocalOrigin (const gp_XYZ& theOrigin);
243 //! Returns list of lights of the view.
244 virtual const Handle(Graphic3d_LightSet)& Lights() const Standard_OVERRIDE { return myLights; }
246 //! Sets list of lights for the view.
247 virtual void SetLights (const Handle(Graphic3d_LightSet)& theLights) Standard_OVERRIDE
249 myLights = theLights;
250 myCurrLightSourceState = myStateCounter->Increment();
253 //! Returns list of clip planes set for the view.
254 virtual const Handle(Graphic3d_SequenceOfHClipPlane)& ClipPlanes() const Standard_OVERRIDE { return myClipPlanes; }
256 //! Sets list of clip planes for the view.
257 virtual void SetClipPlanes (const Handle(Graphic3d_SequenceOfHClipPlane)& thePlanes) Standard_OVERRIDE { myClipPlanes = thePlanes; }
259 //! Fill in the dictionary with diagnostic info.
260 //! Should be called within rendering thread.
262 //! This API should be used only for user output or for creating automated reports.
263 //! The format of returned information (e.g. key-value layout)
264 //! is NOT part of this API and can be changed at any time.
265 //! Thus application should not parse returned information to weed out specific parameters.
266 Standard_EXPORT virtual void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
267 Graphic3d_DiagnosticInfo theFlags) const Standard_OVERRIDE;
269 //! Returns string with statistic performance info.
270 Standard_EXPORT virtual TCollection_AsciiString StatisticInformation() const Standard_OVERRIDE;
272 //! Fills in the dictionary with statistic performance info.
273 Standard_EXPORT virtual void StatisticInformation (TColStd_IndexedDataMapOfStringString& theDict) const Standard_OVERRIDE;
277 //! Returns background color.
278 const Quantity_ColorRGBA& BackgroundColor() const { return myBgColor; }
280 //! Change graduated trihedron.
281 OpenGl_GraduatedTrihedron& ChangeGraduatedTrihedron() { return myGraduatedTrihedron; }
283 void SetTextureEnv (const Handle(OpenGl_Context)& theCtx,
284 const Handle(Graphic3d_TextureEnv)& theTexture);
286 void SetBackgroundTextureStyle (const Aspect_FillMethod FillStyle);
288 void SetBackgroundGradient (const Quantity_Color& AColor1, const Quantity_Color& AColor2, const Aspect_GradientFillMethod AType);
290 void SetBackgroundGradientType (const Aspect_GradientFillMethod AType);
292 //! Returns list of OpenGL Z-layers.
293 const OpenGl_LayerList& LayerList() const { return myZLayers; }
295 //! Returns OpenGL window implementation.
296 const Handle(OpenGl_Window)& GlWindow() const { return myWindow; }
298 //! Returns OpenGL environment map.
299 const Handle(OpenGl_TextureSet)& GlTextureEnv() const { return myTextureEnv; }
301 //! Returns selector for BVH tree, providing a possibility to store information
302 //! about current view volume and to detect which objects are overlapping it.
303 const Graphic3d_CullingTool& BVHTreeSelector() const { return myBVHSelector; }
305 //! Returns true if there are immediate structures to display
306 bool HasImmediateStructures() const
308 return myZLayers.NbImmediateStructures() != 0;
311 public: //! @name obsolete Graduated Trihedron functionality
313 //! Displays Graduated Trihedron.
314 Standard_EXPORT virtual void GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData) Standard_OVERRIDE;
316 //! Erases Graduated Trihedron.
317 Standard_EXPORT virtual void GraduatedTrihedronErase() Standard_OVERRIDE;
319 //! Sets minimum and maximum points of scene bounding box for Graduated Trihedron stored in graphic view object.
320 //! @param theMin [in] the minimum point of scene.
321 //! @param theMax [in] the maximum point of scene.
322 Standard_EXPORT virtual void GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax) Standard_OVERRIDE;
324 protected: //! @name Internal methods for managing GL resources
326 //! Initializes OpenGl resource for environment texture.
327 void initTextureEnv (const Handle(OpenGl_Context)& theContext);
329 protected: //! @name low-level redrawing sub-routines
331 //! Redraws view for the given monographic camera projection, or left/right eye.
332 Standard_EXPORT virtual void redraw (const Graphic3d_Camera::Projection theProjection,
333 OpenGl_FrameBuffer* theReadDrawFbo,
334 OpenGl_FrameBuffer* theOitAccumFbo);
336 //! Redraws view for the given monographic camera projection, or left/right eye.
338 //! Method will blit snapshot containing main scene (myMainSceneFbos or BackBuffer)
339 //! into presentation buffer (myMainSceneFbos -> offscreen FBO or
340 //! myMainSceneFbos -> BackBuffer or BackBuffer -> FrontBuffer),
341 //! and redraw immediate structures on top.
343 //! When scene caching is disabled (myTransientDrawToFront, no double buffer in window, etc.),
344 //! the first step (blitting) will be skipped.
346 //! @return false if immediate structures has been rendered directly into FrontBuffer
347 //! and Buffer Swap should not be called.
348 Standard_EXPORT virtual bool redrawImmediate (const Graphic3d_Camera::Projection theProjection,
349 OpenGl_FrameBuffer* theReadFbo,
350 OpenGl_FrameBuffer* theDrawFbo,
351 OpenGl_FrameBuffer* theOitAccumFbo,
352 const Standard_Boolean theIsPartialUpdate = Standard_False);
354 //! Blit image from/to specified buffers.
355 Standard_EXPORT bool blitBuffers (OpenGl_FrameBuffer* theReadFbo,
356 OpenGl_FrameBuffer* theDrawFbo,
357 const Standard_Boolean theToFlip = Standard_False);
359 //! Setup default FBO.
360 Standard_EXPORT void bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo = NULL);
362 protected: //! @name Rendering of GL graphics (with prepared drawing buffer).
364 //! Renders the graphical contents of the view into the preprepared window or framebuffer.
365 //! @param theProjection [in] the projection that should be used for rendering.
366 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
367 //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process.
368 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
369 Standard_EXPORT virtual void render (Graphic3d_Camera::Projection theProjection,
370 OpenGl_FrameBuffer* theReadDrawFbo,
371 OpenGl_FrameBuffer* theOitAccumFbo,
372 const Standard_Boolean theToDrawImmediate);
374 //! Renders the graphical scene.
375 //! @param theProjection [in] the projection that is used for rendering.
376 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
377 //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process.
378 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
379 Standard_EXPORT virtual void renderScene (Graphic3d_Camera::Projection theProjection,
380 OpenGl_FrameBuffer* theReadDrawFbo,
381 OpenGl_FrameBuffer* theOitAccumFbo,
382 const Standard_Boolean theToDrawImmediate);
384 //! Draw background (gradient / image)
385 Standard_EXPORT virtual void drawBackground (const Handle(OpenGl_Workspace)& theWorkspace);
387 //! Render set of structures presented in the view.
388 //! @param theProjection [in] the projection that is used for rendering.
389 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
390 //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process.
391 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
392 Standard_EXPORT virtual void renderStructs (Graphic3d_Camera::Projection theProjection,
393 OpenGl_FrameBuffer* theReadDrawFbo,
394 OpenGl_FrameBuffer* theOitAccumFbo,
395 const Standard_Boolean theToDrawImmediate);
397 //! Renders trihedron.
398 void renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace);
400 //! Renders frame statistics.
401 void renderFrameStats();
405 //! Adds the structure to display lists of the view.
406 Standard_EXPORT virtual void displayStructure (const Handle(Graphic3d_CStructure)& theStructure,
407 const Standard_Integer thePriority) Standard_OVERRIDE;
409 //! Erases the structure from display lists of the view.
410 Standard_EXPORT virtual void eraseStructure (const Handle(Graphic3d_CStructure)& theStructure) Standard_OVERRIDE;
412 //! Change Z layer of a structure already presented in view.
413 Standard_EXPORT virtual void changeZLayer (const Handle(Graphic3d_CStructure)& theCStructure,
414 const Graphic3d_ZLayerId theNewLayerId) Standard_OVERRIDE;
416 //! Changes the priority of a structure within its Z layer in the specified view.
417 Standard_EXPORT virtual void changePriority (const Handle(Graphic3d_CStructure)& theCStructure,
418 const Standard_Integer theNewPriority) Standard_OVERRIDE;
422 //! Copy content of Back buffer to the Front buffer.
423 bool copyBackToFront();
425 //! Initialize blit quad.
426 OpenGl_VertexBuffer* initBlitQuad (const Standard_Boolean theToFlip);
428 //! Blend together views pair into stereo image.
429 void drawStereoPair (OpenGl_FrameBuffer* theDrawFbo);
431 //! Check and update OIT compatibility with current OpenGL context's state.
432 bool checkOitCompatibility (const Handle(OpenGl_Context)& theGlContext,
433 const Standard_Boolean theMSAA);
435 //! Chooses compatible internal color format for OIT frame buffer.
436 bool chooseOitColorConfiguration (const Handle(OpenGl_Context)& theGlContext,
437 const Standard_Integer theConfigIndex,
438 OpenGl_ColorFormats& theFormats);
442 OpenGl_GraphicDriver* myDriver;
443 Handle(OpenGl_Window) myWindow;
444 Handle(OpenGl_Workspace) myWorkspace;
445 Handle(OpenGl_Caps) myCaps;
446 Standard_Boolean myWasRedrawnGL;
448 Graphic3d_TypeOfBackfacingModel myBackfacing;
449 Handle(Graphic3d_SequenceOfHClipPlane) myClipPlanes;
450 gp_XYZ myLocalOrigin;
451 Handle(OpenGl_FrameBuffer) myFBO;
452 Standard_Boolean myToShowGradTrihedron;
453 TCollection_AsciiString myBackgroundImagePath;
454 Handle(Graphic3d_TextureEnv) myTextureEnvData;
455 Graphic3d_GraduatedTrihedron myGTrihedronData;
457 Handle(Graphic3d_LightSet) myNoShadingLight;
458 Handle(Graphic3d_LightSet) myLights;
459 OpenGl_LayerList myZLayers; //!< main list of displayed structure, sorted by layers
461 Graphic3d_WorldViewProjState myWorldViewProjState; //!< camera modification state
462 OpenGl_StateCounter* myStateCounter;
463 Standard_Size myCurrLightSourceState;
464 Standard_Size myLightsRevision;
466 typedef std::pair<Standard_Size, Standard_Size> StateInfo;
468 StateInfo myLastOrientationState;
469 StateInfo myLastViewMappingState;
470 StateInfo myLastLightSourceState;
472 //! Is needed for selection of overlapping objects and storage of the current view volume
473 Graphic3d_CullingTool myBVHSelector;
475 OpenGl_GraduatedTrihedron myGraduatedTrihedron;
476 OpenGl_FrameStatsPrs myFrameStatsPrs;
478 Handle(OpenGl_TextureSet) myTextureEnv;
480 //! Framebuffers for OpenGL output.
481 Handle(OpenGl_FrameBuffer) myOpenGlFBO;
482 Handle(OpenGl_FrameBuffer) myOpenGlFBO2;
484 protected: //! @name Rendering properties
486 //! Two framebuffers (left and right views) store cached main presentation
487 //! of the view (without presentation of immediate layers).
488 GLint myFboColorFormat; //!< sized format for color attachments
489 GLint myFboDepthFormat; //!< sized format for depth-stencil attachments
490 OpenGl_ColorFormats myFboOitColorConfig; //!< selected color format configuration for OIT color attachments
491 Handle(OpenGl_FrameBuffer) myMainSceneFbos[2];
492 Handle(OpenGl_FrameBuffer) myMainSceneFbosOit[2]; //!< Additional buffers for transparent draw of main layer.
493 Handle(OpenGl_FrameBuffer) myImmediateSceneFbos[2]; //!< Additional buffers for immediate layer in stereo mode.
494 Handle(OpenGl_FrameBuffer) myImmediateSceneFbosOit[2]; //!< Additional buffers for transparency draw of immediate layer.
495 OpenGl_VertexBuffer myFullScreenQuad; //!< Vertices for full-screen quad rendering.
496 OpenGl_VertexBuffer myFullScreenQuadFlip;
497 Standard_Boolean myToFlipOutput; //!< Flag to draw result image upside-down
498 unsigned int myFrameCounter; //!< redraw counter, for debugging
499 Standard_Boolean myHasFboBlit; //!< disable FBOs on failure
500 Standard_Boolean myToDisableOIT; //!< disable OIT on failure
501 Standard_Boolean myToDisableOITMSAA; //!< disable OIT with MSAA on failure
502 Standard_Boolean myToDisableMSAA; //!< disable MSAA after failure
503 Standard_Boolean myTransientDrawToFront; //!< optimization flag for immediate mode (to render directly to the front buffer)
504 Standard_Boolean myBackBufferRestored;
505 Standard_Boolean myIsImmediateDrawn; //!< flag indicates that immediate mode buffer contains some data
507 protected: //! @name Background parameters
509 OpenGl_Aspects* myTextureParams; //!< Stores texture and its parameters for textured background
510 OpenGl_BackgroundArray* myBgGradientArray; //!< Primitive array for gradient background
511 OpenGl_BackgroundArray* myBgTextureArray; //!< Primitive array for texture background
513 protected: //! @name data types related to ray-tracing
515 //! Result of OpenGL shaders initialization.
516 enum RaytraceInitStatus
523 //! Describes update mode (state).
524 enum RaytraceUpdateMode
526 OpenGl_GUM_CHECK, //!< check geometry state
527 OpenGl_GUM_PREPARE, //!< collect unchanged objects
528 OpenGl_GUM_REBUILD //!< rebuild changed and new objects
531 //! Defines frequently used shader variables.
532 enum ShaderVariableIndex
545 OpenGl_RT_uViewPrMat,
546 OpenGl_RT_uUnviewMat,
551 OpenGl_RT_uLightAmbnt,
552 OpenGl_RT_uLightCount,
555 OpenGl_RT_uBackColorTop,
556 OpenGl_RT_uBackColorBot,
558 // ray-tracing params
559 OpenGl_RT_uShadowsEnabled,
560 OpenGl_RT_uReflectEnabled,
561 OpenGl_RT_uSphereMapEnabled,
562 OpenGl_RT_uSphereMapForBack,
563 OpenGl_RT_uTexSamplersArray,
564 OpenGl_RT_uBlockedRngEnabled,
566 // size of render window
570 // sampled frame params
571 OpenGl_RT_uAccumSamples,
572 OpenGl_RT_uFrameRndSeed,
574 // adaptive FSAA params
579 // images used by ISS mode
580 OpenGl_RT_uRenderImage,
581 OpenGl_RT_uTilesImage,
582 OpenGl_RT_uOffsetImage,
584 OpenGl_RT_uVarianceScaleFactor,
586 // maximum radiance value
587 OpenGl_RT_uMaxRadiance,
589 OpenGl_RT_NbVariables // special field
592 //! Defines OpenGL image samplers.
593 enum ShaderImageNames
595 OpenGl_RT_OutputImage = 0,
596 OpenGl_RT_VisualErrorImage = 1,
597 OpenGl_RT_TileOffsetsImage = 2,
598 OpenGl_RT_TileSamplesImage = 3
601 //! Tool class for management of shader sources.
606 //! Default shader prefix - empty string.
607 static const TCollection_AsciiString EMPTY_PREFIX;
609 //! Creates new uninitialized shader source.
617 //! Returns error description in case of load fail.
618 const TCollection_AsciiString& ErrorDescription() const
623 //! Returns prefix to insert before the source.
624 const TCollection_AsciiString& Prefix() const
629 //! Sets prefix to insert before the source.
630 void SetPrefix (const TCollection_AsciiString& thePrefix)
632 myPrefix = thePrefix;
635 //! Returns shader source combined with prefix.
636 TCollection_AsciiString Source() const;
638 //! Loads shader source from specified files.
639 Standard_Boolean LoadFromFiles (const TCollection_AsciiString* theFileNames, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
641 //! Loads shader source from specified strings.
642 Standard_Boolean LoadFromStrings (const TCollection_AsciiString* theStrings, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
646 TCollection_AsciiString mySource; //!< Source string of the shader object
647 TCollection_AsciiString myPrefix; //!< Prefix to insert before the source
648 TCollection_AsciiString myError; //!< error state
652 //! Default ray-tracing depth.
653 static const Standard_Integer THE_DEFAULT_NB_BOUNCES = 3;
655 //! Default size of traversal stack.
656 static const Standard_Integer THE_DEFAULT_STACK_SIZE = 10;
658 //! Compile-time ray-tracing parameters.
659 struct RaytracingParams
661 //! Actual size of traversal stack in shader program.
662 Standard_Integer StackSize;
664 //! Actual ray-tracing depth (number of ray bounces).
665 Standard_Integer NbBounces;
667 //! Enables/disables light propagation through transparent media.
668 Standard_Boolean TransparentShadows;
670 //! Enables/disables global illumination (GI) effects.
671 Standard_Boolean GlobalIllumination;
673 //! Enables/disables the use of OpenGL bindless textures.
674 Standard_Boolean UseBindlessTextures;
676 //! Enables/disables two-sided BSDF models instead of one-sided.
677 Standard_Boolean TwoSidedBsdfModels;
679 //! Enables/disables adaptive screen sampling for path tracing.
680 Standard_Boolean AdaptiveScreenSampling;
682 //! Enables/disables 1-pass atomic mode for AdaptiveScreenSampling.
683 Standard_Boolean AdaptiveScreenSamplingAtomic;
685 //! Enables/disables environment map for background.
686 Standard_Boolean UseEnvMapForBackground;
688 //! Maximum radiance value used for clamping radiance estimation.
689 Standard_ShortReal RadianceClampingValue;
691 //! Enables/disables depth-of-field effect (path tracing, perspective camera).
692 Standard_Boolean DepthOfField;
694 //! Tone mapping method for path tracing.
695 Graphic3d_ToneMappingMethod ToneMappingMethod;
697 //! Creates default compile-time ray-tracing parameters.
699 : StackSize (THE_DEFAULT_STACK_SIZE),
700 NbBounces (THE_DEFAULT_NB_BOUNCES),
701 TransparentShadows (Standard_False),
702 GlobalIllumination (Standard_False),
703 UseBindlessTextures (Standard_False),
704 TwoSidedBsdfModels (Standard_False),
705 AdaptiveScreenSampling (Standard_False),
706 AdaptiveScreenSamplingAtomic (Standard_False),
707 UseEnvMapForBackground (Standard_False),
708 RadianceClampingValue (30.0),
709 DepthOfField (Standard_False),
710 ToneMappingMethod (Graphic3d_ToneMappingMethod_Disabled) { }
713 //! Describes state of OpenGL structure.
716 Standard_Size StructureState;
717 Standard_Size InstancedState;
719 //! Creates new structure state.
720 StructState (const Standard_Size theStructureState = 0,
721 const Standard_Size theInstancedState = 0)
722 : StructureState (theStructureState),
723 InstancedState (theInstancedState)
728 //! Creates new structure state.
729 StructState (const OpenGl_Structure* theStructure)
731 StructureState = theStructure->ModificationState();
733 InstancedState = theStructure->InstancedStructure() != NULL ?
734 theStructure->InstancedStructure()->ModificationState() : 0;
738 protected: //! @name methods related to ray-tracing
740 //! Updates 3D scene geometry for ray-tracing.
741 Standard_Boolean updateRaytraceGeometry (const RaytraceUpdateMode theMode,
742 const Standard_Integer theViewId,
743 const Handle(OpenGl_Context)& theGlContext);
745 //! Updates 3D scene light sources for ray-tracing.
746 Standard_Boolean updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext);
748 //! Checks to see if the OpenGL structure is modified.
749 Standard_Boolean toUpdateStructure (const OpenGl_Structure* theStructure);
751 //! Adds OpenGL structure to ray-traced scene geometry.
752 Standard_Boolean addRaytraceStructure (const OpenGl_Structure* theStructure,
753 const Handle(OpenGl_Context)& theGlContext);
755 //! Adds OpenGL groups to ray-traced scene geometry.
756 Standard_Boolean addRaytraceGroups (const OpenGl_Structure* theStructure,
757 const OpenGl_RaytraceMaterial& theStructMat,
758 const Handle(Geom_Transformation)& theTrsf,
759 const Handle(OpenGl_Context)& theGlContext);
761 //! Creates ray-tracing material properties.
762 OpenGl_RaytraceMaterial convertMaterial (const OpenGl_Aspects* theAspect,
763 const Handle(OpenGl_Context)& theGlContext);
765 //! Adds OpenGL primitive array to ray-traced scene geometry.
766 Handle(OpenGl_TriangleSet) addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
767 const Standard_Integer theMatID,
768 const OpenGl_Mat4* theTrans);
770 //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry.
771 Standard_Boolean addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
772 const Standard_Integer theMatID,
773 const Standard_Integer theCount,
774 const Standard_Integer theOffset,
775 const OpenGl_PrimitiveArray& theArray);
777 //! Adds OpenGL triangle array to ray-traced scene geometry.
778 Standard_Boolean addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
779 const Standard_Integer theMatID,
780 const Standard_Integer theCount,
781 const Standard_Integer theOffset,
782 const Handle(Graphic3d_IndexBuffer)& theIndices);
784 //! Adds OpenGL triangle fan array to ray-traced scene geometry.
785 Standard_Boolean addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
786 const Standard_Integer theMatID,
787 const Standard_Integer theCount,
788 const Standard_Integer theOffset,
789 const Handle(Graphic3d_IndexBuffer)& theIndices);
791 //! Adds OpenGL triangle strip array to ray-traced scene geometry.
792 Standard_Boolean addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
793 const Standard_Integer theMatID,
794 const Standard_Integer theCount,
795 const Standard_Integer theOffset,
796 const Handle(Graphic3d_IndexBuffer)& theIndices);
798 //! Adds OpenGL quadrangle array to ray-traced scene geometry.
799 Standard_Boolean addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
800 const Standard_Integer theMatID,
801 const Standard_Integer theCount,
802 const Standard_Integer theOffset,
803 const Handle(Graphic3d_IndexBuffer)& theIndices);
805 //! Adds OpenGL quadrangle strip array to ray-traced scene geometry.
806 Standard_Boolean addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
807 const Standard_Integer theMatID,
808 const Standard_Integer theCount,
809 const Standard_Integer theOffset,
810 const Handle(Graphic3d_IndexBuffer)& theIndices);
812 //! Adds OpenGL polygon array to ray-traced scene geometry.
813 Standard_Boolean addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
814 const Standard_Integer theMatID,
815 const Standard_Integer theCount,
816 const Standard_Integer theOffset,
817 const Handle(Graphic3d_IndexBuffer)& theIndices);
819 //! Uploads ray-trace data to the GPU.
820 Standard_Boolean uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext);
822 //! Generates shader prefix based on current ray-tracing options.
823 TCollection_AsciiString generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const;
825 //! Performs safe exit when shaders initialization fails.
826 Standard_Boolean safeFailBack (const TCollection_ExtendedString& theMessage,
827 const Handle(OpenGl_Context)& theGlContext);
829 //! Loads and compiles shader object from specified source.
830 Handle(OpenGl_ShaderObject) initShader (const GLenum theType,
831 const ShaderSource& theSource,
832 const Handle(OpenGl_Context)& theGlContext);
834 //! Creates shader program from the given vertex and fragment shaders.
835 Handle(OpenGl_ShaderProgram) initProgram (const Handle(OpenGl_Context)& theGlContext,
836 const Handle(OpenGl_ShaderObject)& theVertShader,
837 const Handle(OpenGl_ShaderObject)& theFragShader,
838 const TCollection_AsciiString& theName);
840 //! Initializes OpenGL/GLSL shader programs.
841 Standard_Boolean initRaytraceResources (const Standard_Integer theSizeX,
842 const Standard_Integer theSizeY,
843 const Handle(OpenGl_Context)& theGlContext);
845 //! Releases OpenGL/GLSL shader programs.
846 void releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext,
847 const Standard_Boolean theToRebuild = Standard_False);
849 //! Updates auxiliary OpenGL frame buffers.
850 Standard_Boolean updateRaytraceBuffers (const Standard_Integer theSizeX,
851 const Standard_Integer theSizeY,
852 const Handle(OpenGl_Context)& theGlContext);
854 //! Generates viewing rays for corners of screen quad.
855 //! (ray tracing; path tracing for orthographic camera)
856 void updateCamera (const OpenGl_Mat4& theOrientation,
857 const OpenGl_Mat4& theViewMapping,
858 OpenGl_Vec3* theOrigins,
859 OpenGl_Vec3* theDirects,
860 OpenGl_Mat4& theView,
861 OpenGl_Mat4& theUnView);
863 //! Generate viewing rays (path tracing, perspective camera).
864 void updatePerspCameraPT(const OpenGl_Mat4& theOrientation,
865 const OpenGl_Mat4& theViewMapping,
866 Graphic3d_Camera::Projection theProjection,
867 OpenGl_Mat4& theViewPr,
868 OpenGl_Mat4& theUnview,
869 const int theWinSizeX,
870 const int theWinSizeY);
872 //! Binds ray-trace textures to corresponding texture units.
873 void bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
876 //! Unbinds ray-trace textures from corresponding texture unit.
877 void unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
879 //! Sets uniform state for the given ray-tracing shader program.
880 Standard_Boolean setUniformState (const Standard_Integer theProgramId,
881 const Standard_Integer theSizeX,
882 const Standard_Integer theSizeY,
883 Graphic3d_Camera::Projection theProjection,
884 const Handle(OpenGl_Context)& theGlContext);
886 //! Runs ray-tracing shader programs.
887 Standard_Boolean runRaytraceShaders (const Standard_Integer theSizeX,
888 const Standard_Integer theSizeY,
889 Graphic3d_Camera::Projection theProjection,
890 OpenGl_FrameBuffer* theReadDrawFbo,
891 const Handle(OpenGl_Context)& theGlContext);
893 //! Runs classical (Whitted-style) ray-tracing kernel.
894 Standard_Boolean runRaytrace (const Standard_Integer theSizeX,
895 const Standard_Integer theSizeY,
896 Graphic3d_Camera::Projection theProjection,
897 OpenGl_FrameBuffer* theReadDrawFbo,
898 const Handle(OpenGl_Context)& theGlContext);
900 //! Runs path tracing (global illumination) kernel.
901 Standard_Boolean runPathtrace (const Standard_Integer theSizeX,
902 const Standard_Integer theSizeY,
903 Graphic3d_Camera::Projection theProjection,
904 const Handle(OpenGl_Context)& theGlContext);
906 //! Runs path tracing (global illumination) kernel.
907 Standard_Boolean runPathtraceOut (Graphic3d_Camera::Projection theProjection,
908 OpenGl_FrameBuffer* theReadDrawFbo,
909 const Handle(OpenGl_Context)& theGlContext);
911 //! Redraws the window using OpenGL/GLSL ray-tracing or path tracing.
912 Standard_Boolean raytrace (const Standard_Integer theSizeX,
913 const Standard_Integer theSizeY,
914 Graphic3d_Camera::Projection theProjection,
915 OpenGl_FrameBuffer* theReadDrawFbo,
916 const Handle(OpenGl_Context)& theGlContext);
918 protected: //! @name fields related to ray-tracing
920 //! Result of RT/PT shaders initialization.
921 RaytraceInitStatus myRaytraceInitStatus;
923 //! Is ray-tracing geometry data valid?
924 Standard_Boolean myIsRaytraceDataValid;
926 //! True if warning about missing extension GL_ARB_bindless_texture has been displayed.
927 Standard_Boolean myIsRaytraceWarnTextures;
929 //! 3D scene geometry data for ray-tracing.
930 OpenGl_RaytraceGeometry myRaytraceGeometry;
932 //! Builder for triangle set.
933 opencascade::handle<BVH_Builder<Standard_ShortReal, 3> > myRaytraceBVHBuilder;
935 //! Compile-time ray-tracing parameters.
936 RaytracingParams myRaytraceParameters;
938 //! Radius of bounding sphere of the scene.
939 Standard_ShortReal myRaytraceSceneRadius;
940 //! Scene epsilon to prevent self-intersections.
941 Standard_ShortReal myRaytraceSceneEpsilon;
943 //! OpenGL/GLSL source of ray-tracing fragment shader.
944 ShaderSource myRaytraceShaderSource;
945 //! OpenGL/GLSL source of adaptive-AA fragment shader.
946 ShaderSource myPostFSAAShaderSource;
947 //! OpenGL/GLSL source of RT/PT display fragment shader.
948 ShaderSource myOutImageShaderSource;
950 //! OpenGL/GLSL ray-tracing fragment shader.
951 Handle(OpenGl_ShaderObject) myRaytraceShader;
952 //! OpenGL/GLSL adaptive-AA fragment shader.
953 Handle(OpenGl_ShaderObject) myPostFSAAShader;
954 //! OpenGL/GLSL ray-tracing display fragment shader.
955 Handle(OpenGl_ShaderObject) myOutImageShader;
957 //! OpenGL/GLSL ray-tracing shader program.
958 Handle(OpenGl_ShaderProgram) myRaytraceProgram;
959 //! OpenGL/GLSL adaptive-AA shader program.
960 Handle(OpenGl_ShaderProgram) myPostFSAAProgram;
961 //! OpenGL/GLSL program for displaying texture.
962 Handle(OpenGl_ShaderProgram) myOutImageProgram;
964 //! Texture buffer of data records of bottom-level BVH nodes.
965 Handle(OpenGl_TextureBufferArb) mySceneNodeInfoTexture;
966 //! Texture buffer of minimum points of bottom-level BVH nodes.
967 Handle(OpenGl_TextureBufferArb) mySceneMinPointTexture;
968 //! Texture buffer of maximum points of bottom-level BVH nodes.
969 Handle(OpenGl_TextureBufferArb) mySceneMaxPointTexture;
970 //! Texture buffer of transformations of high-level BVH nodes.
971 Handle(OpenGl_TextureBufferArb) mySceneTransformTexture;
973 //! Texture buffer of vertex coords.
974 Handle(OpenGl_TextureBufferArb) myGeometryVertexTexture;
975 //! Texture buffer of vertex normals.
976 Handle(OpenGl_TextureBufferArb) myGeometryNormalTexture;
977 //! Texture buffer of vertex UV coords.
978 Handle(OpenGl_TextureBufferArb) myGeometryTexCrdTexture;
979 //! Texture buffer of triangle indices.
980 Handle(OpenGl_TextureBufferArb) myGeometryTriangTexture;
982 //! Texture buffer of material properties.
983 Handle(OpenGl_TextureBufferArb) myRaytraceMaterialTexture;
984 //! Texture buffer of light source properties.
985 Handle(OpenGl_TextureBufferArb) myRaytraceLightSrcTexture;
987 //! 1st framebuffer (FBO) to perform adaptive FSAA.
988 //! Used in compatibility mode (no adaptive sampling).
989 Handle(OpenGl_FrameBuffer) myRaytraceFBO1[2];
990 //! 2nd framebuffer (FBO) to perform adaptive FSAA.
991 //! Used in compatibility mode (no adaptive sampling).
992 Handle(OpenGl_FrameBuffer) myRaytraceFBO2[2];
994 //! Output textures (2 textures are used in stereo mode).
995 //! Used if adaptive screen sampling is activated.
996 Handle(OpenGl_Texture) myRaytraceOutputTexture[2];
998 //! Texture containing per-tile visual error estimation (2 textures are used in stereo mode).
999 //! Used if adaptive screen sampling is activated.
1000 Handle(OpenGl_Texture) myRaytraceVisualErrorTexture[2];
1001 //! Texture containing offsets of sampled screen tiles (2 textures are used in stereo mode).
1002 //! Used if adaptive screen sampling is activated.
1003 Handle(OpenGl_Texture) myRaytraceTileOffsetsTexture[2];
1004 //! Texture containing amount of extra per-tile samples (2 textures are used in stereo mode).
1005 //! Used if adaptive screen sampling is activated.
1006 Handle(OpenGl_Texture) myRaytraceTileSamplesTexture[2];
1008 //! Vertex buffer (VBO) for drawing dummy quad.
1009 OpenGl_VertexBuffer myRaytraceScreenQuad;
1011 //! Cached locations of frequently used uniform variables.
1012 Standard_Integer myUniformLocations[2][OpenGl_RT_NbVariables];
1014 //! State of OpenGL structures reflected to ray-tracing.
1015 std::map<const OpenGl_Structure*, StructState> myStructureStates;
1017 //! PrimitiveArray to TriangleSet map for scene partial update.
1018 std::map<Standard_Size, OpenGl_TriangleSet*> myArrayToTrianglesMap;
1020 //! Set of IDs of non-raytracable elements (to detect updates).
1021 std::set<Standard_Integer> myNonRaytraceStructureIDs;
1023 //! Marks if environment map should be updated.
1024 Standard_Boolean myToUpdateEnvironmentMap;
1026 //! State of OpenGL layer list.
1027 Standard_Size myRaytraceLayerListState;
1029 //! Number of accumulated frames (for progressive rendering).
1030 Standard_Integer myAccumFrames;
1032 //! Stored ray origins used for detection of camera movements.
1033 OpenGl_Vec3 myPreviousOrigins[3];
1035 //! Bullard RNG to produce random sequence.
1036 math_BullardGenerator myRNG;
1038 //! Tool object for sampling screen tiles in PT mode.
1039 OpenGl_TileSampler myTileSampler;
1041 //! Camera position used for projective mode
1042 OpenGl_Vec3 myEyeOrig;
1044 //! Camera view direction used for projective mode
1045 OpenGl_Vec3 myEyeView;
1047 //! Camera's screen vertical direction used for projective mode
1048 OpenGl_Vec3 myEyeVert;
1050 //! Camera's screen horizontal direction used for projective mode
1051 OpenGl_Vec3 myEyeSide;
1053 //! Camera's screen size used for projective mode
1054 OpenGl_Vec2 myEyeSize;
1056 //! Aperture radius of camera on previous frame used for depth-of-field (path tracing)
1057 float myPrevCameraApertureRadius;
1059 //! Focal distance of camera on previous frame used for depth-of-field (path tracing)
1060 float myPrevCameraFocalPlaneDist;
1064 DEFINE_STANDARD_ALLOC
1065 DEFINE_STANDARD_RTTIEXT(OpenGl_View,Graphic3d_CView) // Type definition
1067 friend class OpenGl_GraphicDriver;
1068 friend class OpenGl_Workspace;
1069 friend class OpenGl_LayerList;
1070 friend class OpenGl_FrameStats;
1073 #endif // _OpenGl_View_Header