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 <MMgt_TShared.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_GraduatedTrihedron.hxx>
32 #include <Graphic3d_SequenceOfHClipPlane.hxx>
33 #include <Graphic3d_TypeOfShadingModel.hxx>
34 #include <Graphic3d_WorldViewProjState.hxx>
35 #include <Graphic3d_ZLayerSettings.hxx>
37 #include <OpenGl_AspectFace.hxx>
38 #include <OpenGl_BackgroundArray.hxx>
39 #include <OpenGl_BVHTreeSelector.hxx>
40 #include <OpenGl_Context.hxx>
41 #include <OpenGl_FrameBuffer.hxx>
42 #include <OpenGl_GraduatedTrihedron.hxx>
43 #include <OpenGl_LayerList.hxx>
44 #include <OpenGl_Light.hxx>
45 #include <OpenGl_LineAttributes.hxx>
46 #include <OpenGl_SceneGeometry.hxx>
47 #include <OpenGl_Structure.hxx>
48 #include <OpenGl_Window.hxx>
49 #include <OpenGl_Workspace.hxx>
50 #include <OpenGl_TileSampler.hxx>
57 class Graphic3d_StructureManager;
58 class OpenGl_GraphicDriver;
59 class OpenGl_StateCounter;
60 class OpenGl_RaytraceMaterial;
61 class OpenGl_TriangleSet;
62 class OpenGl_Workspace;
64 DEFINE_STANDARD_HANDLE(OpenGl_View,Graphic3d_CView)
66 //! Implementation of OpenGl view.
67 class OpenGl_View : public Graphic3d_CView
73 Standard_EXPORT OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr,
74 const Handle(OpenGl_GraphicDriver)& theDriver,
75 const Handle(OpenGl_Caps)& theCaps,
76 Standard_Boolean& theDeviceLostFlag,
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 //! Returns data of a graduated trihedron
131 const Graphic3d_GraduatedTrihedron& GetGraduatedTrihedron() Standard_OVERRIDE
132 { return myGTrihedronData; }
134 //! Displays Graduated Trihedron.
135 Standard_EXPORT virtual void GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData) Standard_OVERRIDE;
137 //! Erases Graduated Trihedron.
138 Standard_EXPORT virtual void GraduatedTrihedronErase() Standard_OVERRIDE;
140 //! Sets minimum and maximum points of scene bounding box for Graduated Trihedron stored in graphic view object.
141 //! @param theMin [in] the minimum point of scene.
142 //! @param theMax [in] the maximum point of scene.
143 Standard_EXPORT virtual void GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax) Standard_OVERRIDE;
145 //! Dump active rendering buffer into specified memory buffer.
146 Standard_EXPORT virtual Standard_Boolean BufferDump (Image_PixMap& theImage,
147 const Graphic3d_BufferType& theBufferType) Standard_OVERRIDE;
149 //! Export scene into the one of the Vector graphics formats (SVG, PS, PDF...).
150 //! In contrast to Bitmaps, Vector graphics is scalable (so you may got quality benefits
151 //! on printing to laser printer). Notice however that results may differ a lot and
152 //! do not contain some elements.
153 Standard_EXPORT virtual Standard_Boolean Export (const Standard_CString theFileName,
154 const Graphic3d_ExportFormat theFormat,
155 const Graphic3d_SortType theSortType = Graphic3d_ST_BSP_Tree) Standard_OVERRIDE;
157 //! Marks BVH tree and the set of BVH primitives of correspondent priority list with id theLayerId as outdated.
158 Standard_EXPORT virtual void InvalidateBVHData (const Standard_Integer theLayerId) Standard_OVERRIDE;
160 //! Insert a new top-level z layer with the given ID.
161 Standard_EXPORT virtual void AddZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
163 //! Remove a z layer with the given ID.
164 Standard_EXPORT virtual void RemoveZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
166 //! Sets the settings for a single Z layer of specified view.
167 Standard_EXPORT virtual void SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
168 const Graphic3d_ZLayerSettings& theSettings) Standard_OVERRIDE;
170 //! Returns the maximum Z layer ID.
171 //! First layer ID is Graphic3d_ZLayerId_Default, last ID is ZLayerMax().
172 Standard_EXPORT virtual Standard_Integer ZLayerMax() const Standard_OVERRIDE;
174 //! Returns the bounding box of all structures displayed in the Z layer.
175 //! Never fails. If Z layer does not exist nothing happens.
176 Standard_EXPORT virtual void InvalidateZLayerBoundingBox (const Graphic3d_ZLayerId theLayerId) const Standard_OVERRIDE;
178 //! Returns the bounding box of all structures displayed in the Z layer.
179 //! If Z layer does not exist the empty box is returned.
180 //! @param theLayerId layer identifier
181 //! @param theCamera camera definition
182 //! @param theWindowWidth viewport width (for applying transformation-persistence)
183 //! @param theWindowHeight viewport height (for applying transformation-persistence)
184 //! @param theToIncludeAuxiliary consider also auxiliary presentations (with infinite flag or with trihedron transformation persistence)
185 //! @return computed bounding box
186 Standard_EXPORT virtual Bnd_Box ZLayerBoundingBox (const Graphic3d_ZLayerId theLayerId,
187 const Handle(Graphic3d_Camera)& theCamera,
188 const Standard_Integer theWindowWidth,
189 const Standard_Integer theWindowHeight,
190 const Standard_Boolean theToIncludeAuxiliary) const Standard_OVERRIDE;
192 //! Returns pointer to an assigned framebuffer object.
193 Standard_EXPORT virtual Handle(Standard_Transient) FBO() const Standard_OVERRIDE;
195 //! Sets framebuffer object for offscreen rendering.
196 Standard_EXPORT virtual void SetFBO (const Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
198 //! Generate offscreen FBO in the graphic library.
199 //! If not supported on hardware returns NULL.
200 Standard_EXPORT virtual Handle(Standard_Transient) FBOCreate (const Standard_Integer theWidth,
201 const Standard_Integer theHeight) Standard_OVERRIDE;
203 //! Remove offscreen FBO from the graphic library
204 Standard_EXPORT virtual void FBORelease (Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
206 //! Read offscreen FBO configuration.
207 Standard_EXPORT virtual void FBOGetDimensions (const Handle(Standard_Transient)& theFbo,
208 Standard_Integer& theWidth,
209 Standard_Integer& theHeight,
210 Standard_Integer& theWidthMax,
211 Standard_Integer& theHeightMax) Standard_OVERRIDE;
213 //! Change offscreen FBO viewport.
214 Standard_EXPORT virtual void FBOChangeViewport (const Handle(Standard_Transient)& theFbo,
215 const Standard_Integer theWidth,
216 const Standard_Integer theHeight) Standard_OVERRIDE;
220 //! Returns background fill color.
221 Standard_EXPORT virtual Aspect_Background Background() const Standard_OVERRIDE;
223 //! Sets background fill color.
224 Standard_EXPORT virtual void SetBackground (const Aspect_Background& theBackground) Standard_OVERRIDE;
226 //! Returns gradient background fill colors.
227 Standard_EXPORT virtual Aspect_GradientBackground GradientBackground() const Standard_OVERRIDE;
229 //! Sets gradient background fill colors.
230 Standard_EXPORT virtual void SetGradientBackground (const Aspect_GradientBackground& theBackground) Standard_OVERRIDE;
232 //! Returns background image texture file path.
233 Standard_EXPORT virtual TCollection_AsciiString BackgroundImage() Standard_OVERRIDE { return myBackgroundImagePath; }
235 //! Sets background image texture file path.
236 Standard_EXPORT virtual void SetBackgroundImage (const TCollection_AsciiString& theFilePath) Standard_OVERRIDE;
238 //! Returns background image fill style.
239 Standard_EXPORT virtual Aspect_FillMethod BackgroundImageStyle() const Standard_OVERRIDE;
241 //! Sets background image fill style.
242 Standard_EXPORT virtual void SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle) Standard_OVERRIDE;
244 //! Returns environment texture set for the view.
245 Standard_EXPORT virtual Handle(Graphic3d_TextureEnv) TextureEnv() const Standard_OVERRIDE { return myTextureEnvData; }
247 //! Sets environment texture for the view.
248 Standard_EXPORT virtual void SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv) Standard_OVERRIDE;
250 //! Returns the state of frustum culling optimization.
251 virtual Standard_Boolean IsCullingEnabled() const Standard_OVERRIDE { return myCulling; }
253 //! Enables or disables frustum culling optimization.
254 virtual void SetCullingEnabled (const Standard_Boolean theIsEnabled) Standard_OVERRIDE { myCulling = theIsEnabled; }
256 //! Returns shading model of the view.
257 virtual Graphic3d_TypeOfShadingModel ShadingModel() const Standard_OVERRIDE { return myShadingModel; }
259 //! Sets shading model of the view.
260 virtual void SetShadingModel (const Graphic3d_TypeOfShadingModel theModel) Standard_OVERRIDE { myShadingModel = theModel; }
262 //! Return backfacing model used for the view.
263 virtual Graphic3d_TypeOfBackfacingModel BackfacingModel() const Standard_OVERRIDE { return myBackfacing; }
265 //! Sets backfacing model for the view.
266 virtual void SetBackfacingModel (const Graphic3d_TypeOfBackfacingModel theModel) Standard_OVERRIDE { myBackfacing = theModel; }
268 //! Returns camera object of the view.
269 virtual const Handle(Graphic3d_Camera)& Camera() const Standard_OVERRIDE { return myCamera; }
271 //! Returns local camera origin currently set for rendering, might be modified during rendering.
272 const gp_XYZ& LocalOrigin() const { return myLocalOrigin; }
274 //! Setup local camera origin currently set for rendering.
275 Standard_EXPORT void SetLocalOrigin (const gp_XYZ& theOrigin);
277 //! Sets camera used by the view.
278 Standard_EXPORT virtual void SetCamera (const Handle(Graphic3d_Camera)& theCamera) Standard_OVERRIDE;
280 //! Returns list of lights of the view.
281 virtual const Graphic3d_ListOfCLight& Lights() const Standard_OVERRIDE { return myLights; }
283 //! Sets list of lights for the view.
284 virtual void SetLights (const Graphic3d_ListOfCLight& theLights) Standard_OVERRIDE
286 myLights = theLights;
287 myCurrLightSourceState = myStateCounter->Increment();
290 //! Returns list of clip planes set for the view.
291 virtual const Handle(Graphic3d_SequenceOfHClipPlane)& ClipPlanes() const Standard_OVERRIDE { return myClipPlanes; }
293 //! Sets list of clip planes for the view.
294 virtual void SetClipPlanes (const Handle(Graphic3d_SequenceOfHClipPlane)& thePlanes) Standard_OVERRIDE { myClipPlanes = thePlanes; }
296 //! Fill in the dictionary with diagnostic info.
297 //! Should be called within rendering thread.
299 //! This API should be used only for user output or for creating automated reports.
300 //! The format of returned information (e.g. key-value layout)
301 //! is NOT part of this API and can be changed at any time.
302 //! Thus application should not parse returned information to weed out specific parameters.
303 Standard_EXPORT virtual void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
304 Graphic3d_DiagnosticInfo theFlags) const Standard_OVERRIDE;
308 //! Returns background color.
309 const Quantity_ColorRGBA& BackgroundColor() const { return myBgColor; }
311 //! Change graduated trihedron.
312 OpenGl_GraduatedTrihedron& ChangeGraduatedTrihedron() { return myGraduatedTrihedron; }
314 void SetTextureEnv (const Handle(OpenGl_Context)& theCtx,
315 const Handle(Graphic3d_TextureEnv)& theTexture);
317 void SetBackgroundTextureStyle (const Aspect_FillMethod FillStyle);
319 void SetBackgroundGradient (const Quantity_Color& AColor1, const Quantity_Color& AColor2, const Aspect_GradientFillMethod AType);
321 void SetBackgroundGradientType (const Aspect_GradientFillMethod AType);
323 //! Returns list of OpenGL Z-layers.
324 const OpenGl_LayerList& LayerList() const { return myZLayers; }
326 //! Returns list of openGL light sources.
327 const OpenGl_ListOfLight& LightList() const { return myLights; }
329 //! Returns OpenGL window implementation.
330 const Handle(OpenGl_Window) GlWindow() const { return myWindow; }
332 //! Returns OpenGL environment map.
333 const Handle(OpenGl_Texture)& GlTextureEnv() const { return myTextureEnv; }
335 //! Returns selector for BVH tree, providing a possibility to store information
336 //! about current view volume and to detect which objects are overlapping it.
337 OpenGl_BVHTreeSelector& BVHTreeSelector() { return myBVHSelector; }
339 //! Returns true if there are immediate structures to display
340 bool HasImmediateStructures() const
342 return myZLayers.NbImmediateStructures() != 0;
345 protected: //! @name Internal methods for managing GL resources
347 //! Initializes OpenGl resource for environment texture.
348 void initTextureEnv (const Handle(OpenGl_Context)& theContext);
350 protected: //! @name low-level redrawing sub-routines
352 //! Redraws view for the given monographic camera projection, or left/right eye.
353 Standard_EXPORT virtual void redraw (const Graphic3d_Camera::Projection theProjection,
354 OpenGl_FrameBuffer* theReadDrawFbo,
355 OpenGl_FrameBuffer* theOitAccumFbo);
357 //! Redraws view for the given monographic camera projection, or left/right eye.
359 //! Method will blit snapshot containing main scene (myMainSceneFbos or BackBuffer)
360 //! into presentation buffer (myMainSceneFbos -> offscreen FBO or
361 //! myMainSceneFbos -> BackBuffer or BackBuffer -> FrontBuffer),
362 //! and redraw immediate structures on top.
364 //! When scene caching is disabled (myTransientDrawToFront, no double buffer in window, etc.),
365 //! the first step (blitting) will be skipped.
367 //! @return false if immediate structures has been rendered directly into FrontBuffer
368 //! and Buffer Swap should not be called.
369 Standard_EXPORT virtual bool redrawImmediate (const Graphic3d_Camera::Projection theProjection,
370 OpenGl_FrameBuffer* theReadFbo,
371 OpenGl_FrameBuffer* theDrawFbo,
372 OpenGl_FrameBuffer* theOitAccumFbo,
373 const Standard_Boolean theIsPartialUpdate = Standard_False);
375 //! Blit image from/to specified buffers.
376 Standard_EXPORT bool blitBuffers (OpenGl_FrameBuffer* theReadFbo,
377 OpenGl_FrameBuffer* theDrawFbo,
378 const Standard_Boolean theToFlip = Standard_False);
380 //! Setup default FBO.
381 Standard_EXPORT void bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo = NULL);
383 protected: //! @name Rendering of GL graphics (with prepared drawing buffer).
385 //! Renders the graphical contents of the view into the preprepared window or framebuffer.
386 //! @param theProjection [in] the projection that should be used for rendering.
387 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
388 //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process.
389 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
390 Standard_EXPORT virtual void render (Graphic3d_Camera::Projection theProjection,
391 OpenGl_FrameBuffer* theReadDrawFbo,
392 OpenGl_FrameBuffer* theOitAccumFbo,
393 const Standard_Boolean theToDrawImmediate);
395 //! Renders the graphical scene.
396 //! @param theProjection [in] the projection that is used for rendering.
397 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
398 //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process.
399 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
400 Standard_EXPORT virtual void renderScene (Graphic3d_Camera::Projection theProjection,
401 OpenGl_FrameBuffer* theReadDrawFbo,
402 OpenGl_FrameBuffer* theOitAccumFbo,
403 const Standard_Boolean theToDrawImmediate);
405 //! Draw background (gradient / image)
406 Standard_EXPORT virtual void drawBackground (const Handle(OpenGl_Workspace)& theWorkspace);
408 //! Render set of structures presented in the view.
409 //! @param theProjection [in] the projection that is used for rendering.
410 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
411 //! @param theOitAccumFbo [in] the framebuffer for accumulating color and coverage for OIT process.
412 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
413 Standard_EXPORT virtual void renderStructs (Graphic3d_Camera::Projection theProjection,
414 OpenGl_FrameBuffer* theReadDrawFbo,
415 OpenGl_FrameBuffer* theOitAccumFbo,
416 const Standard_Boolean theToDrawImmediate);
418 //! Renders trihedron.
419 void renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace);
423 //! Adds the structure to display lists of the view.
424 Standard_EXPORT virtual void displayStructure (const Handle(Graphic3d_CStructure)& theStructure,
425 const Standard_Integer thePriority) Standard_OVERRIDE;
427 //! Erases the structure from display lists of the view.
428 Standard_EXPORT virtual void eraseStructure (const Handle(Graphic3d_CStructure)& theStructure) Standard_OVERRIDE;
430 //! Change Z layer of a structure already presented in view.
431 Standard_EXPORT virtual void changeZLayer (const Handle(Graphic3d_CStructure)& theCStructure,
432 const Graphic3d_ZLayerId theNewLayerId) Standard_OVERRIDE;
434 //! Changes the priority of a structure within its Z layer in the specified view.
435 Standard_EXPORT virtual void changePriority (const Handle(Graphic3d_CStructure)& theCStructure,
436 const Standard_Integer theNewPriority) Standard_OVERRIDE;
438 //! Returns zoom-scale factor.
439 Standard_EXPORT virtual Standard_Real considerZoomPersistenceObjects (const Graphic3d_ZLayerId theLayerId,
440 const Handle(Graphic3d_Camera)& theCamera,
441 const Standard_Integer theWindowWidth,
442 const Standard_Integer theWindowHeight) const Standard_OVERRIDE;
446 //! Copy content of Back buffer to the Front buffer.
447 void copyBackToFront();
449 //! Initialize blit quad.
450 OpenGl_VertexBuffer* initBlitQuad (const Standard_Boolean theToFlip);
452 //! Blend together views pair into stereo image.
453 void drawStereoPair (OpenGl_FrameBuffer* theDrawFbo);
455 //! Check and update OIT compatibility with current OpenGL context's state.
456 bool checkOitCompatibility (const Handle(OpenGl_Context)& theGlContext,
457 const Standard_Boolean theMSAA);
459 //! Chooses compatible internal color format for OIT frame buffer.
460 bool chooseOitColorConfiguration (const Handle(OpenGl_Context)& theGlContext,
461 const Standard_Integer theConfigIndex,
462 OpenGl_ColorFormats& theFormats);
466 OpenGl_GraphicDriver* myDriver;
467 Handle(OpenGl_Window) myWindow;
468 Handle(OpenGl_Workspace) myWorkspace;
469 Handle(OpenGl_Caps) myCaps;
470 Standard_Boolean& myDeviceLostFlag;
471 Standard_Boolean myWasRedrawnGL;
473 Standard_Boolean myCulling;
474 Graphic3d_TypeOfShadingModel myShadingModel;
475 Graphic3d_TypeOfBackfacingModel myBackfacing;
476 Quantity_ColorRGBA myBgColor;
477 Handle(Graphic3d_SequenceOfHClipPlane) myClipPlanes;
478 Handle(Graphic3d_Camera) myCamera;
479 gp_XYZ myLocalOrigin;
480 Handle(OpenGl_FrameBuffer) myFBO;
481 Standard_Boolean myToShowGradTrihedron;
482 TCollection_AsciiString myBackgroundImagePath;
483 Handle(Graphic3d_TextureEnv) myTextureEnvData;
484 Graphic3d_GraduatedTrihedron myGTrihedronData;
486 OpenGl_ListOfLight myNoShadingLight;
487 OpenGl_ListOfLight myLights;
488 OpenGl_LayerList myZLayers; //!< main list of displayed structure, sorted by layers
490 Graphic3d_WorldViewProjState myWorldViewProjState; //!< camera modification state
491 OpenGl_StateCounter* myStateCounter;
492 Standard_Size myCurrLightSourceState;
494 typedef std::pair<Standard_Size, Standard_Size> StateInfo;
496 StateInfo myLastOrientationState;
497 StateInfo myLastViewMappingState;
498 StateInfo myLastLightSourceState;
500 //! Is needed for selection of overlapping objects and storage of the current view volume
501 OpenGl_BVHTreeSelector myBVHSelector;
503 OpenGl_GraduatedTrihedron myGraduatedTrihedron;
505 Handle(OpenGl_Texture) myTextureEnv;
507 //! Framebuffers for OpenGL output.
508 Handle(OpenGl_FrameBuffer) myOpenGlFBO;
509 Handle(OpenGl_FrameBuffer) myOpenGlFBO2;
511 protected: //! @name Rendering properties
513 //! Two framebuffers (left and right views) store cached main presentation
514 //! of the view (without presentation of immediate layers).
515 GLint myFboColorFormat; //!< sized format for color attachments
516 GLint myFboDepthFormat; //!< sized format for depth-stencil attachments
517 OpenGl_ColorFormats myFboOitColorConfig; //!< selected color format configuration for OIT color attachments
518 Handle(OpenGl_FrameBuffer) myMainSceneFbos[2];
519 Handle(OpenGl_FrameBuffer) myMainSceneFbosOit[2]; //!< Additional buffers for transparent draw of main layer.
520 Handle(OpenGl_FrameBuffer) myImmediateSceneFbos[2]; //!< Additional buffers for immediate layer in stereo mode.
521 Handle(OpenGl_FrameBuffer) myImmediateSceneFbosOit[2]; //!< Additional buffers for transparency draw of immediate layer.
522 OpenGl_VertexBuffer myFullScreenQuad; //!< Vertices for full-screen quad rendering.
523 OpenGl_VertexBuffer myFullScreenQuadFlip;
524 Standard_Boolean myToFlipOutput; //!< Flag to draw result image upside-down
525 unsigned int myFrameCounter; //!< redraw counter, for debugging
526 Standard_Boolean myHasFboBlit; //!< disable FBOs on failure
527 Standard_Boolean myToDisableOIT; //!< disable OIT on failure
528 Standard_Boolean myToDisableOITMSAA; //!< disable OIT with MSAA on failure
529 Standard_Boolean myToDisableMSAA; //!< disable MSAA after failure
530 Standard_Boolean myTransientDrawToFront; //!< optimization flag for immediate mode (to render directly to the front buffer)
531 Standard_Boolean myBackBufferRestored;
532 Standard_Boolean myIsImmediateDrawn; //!< flag indicates that immediate mode buffer contains some data
534 protected: //! @name Background parameters
536 OpenGl_AspectFace* myTextureParams; //!< Stores texture and its parameters for textured background
537 OpenGl_BackgroundArray* myBgGradientArray; //!< Primitive array for gradient background
538 OpenGl_BackgroundArray* myBgTextureArray; //!< Primitive array for texture background
540 protected: //! @name data types related to ray-tracing
542 //! Result of OpenGL shaders initialization.
543 enum RaytraceInitStatus
550 //! Describes update mode (state).
551 enum RaytraceUpdateMode
553 OpenGl_GUM_CHECK, //!< check geometry state
554 OpenGl_GUM_PREPARE, //!< collect unchanged objects
555 OpenGl_GUM_REBUILD //!< rebuild changed and new objects
558 //! Defines frequently used shader variables.
559 enum ShaderVariableIndex
572 OpenGl_RT_uViewPrMat,
573 OpenGl_RT_uUnviewMat,
578 OpenGl_RT_uLightAmbnt,
579 OpenGl_RT_uLightCount,
582 OpenGl_RT_uBackColorTop,
583 OpenGl_RT_uBackColorBot,
585 // ray-tracing params
586 OpenGl_RT_uShadowsEnabled,
587 OpenGl_RT_uReflectEnabled,
588 OpenGl_RT_uSphereMapEnabled,
589 OpenGl_RT_uSphereMapForBack,
590 OpenGl_RT_uTexSamplersArray,
591 OpenGl_RT_uBlockedRngEnabled,
593 // size of render window
597 // sampled frame params
598 OpenGl_RT_uAccumSamples,
599 OpenGl_RT_uFrameRndSeed,
601 // adaptive FSAA params
606 // images used by ISS mode
607 OpenGl_RT_uRenderImage,
608 OpenGl_RT_uOffsetImage,
610 // maximum radiance value
611 OpenGl_RT_uMaxRadiance,
613 OpenGl_RT_NbVariables // special field
616 //! Defines OpenGL texture samplers.
617 enum ShaderSamplerNames
619 OpenGl_RT_EnvironmentMapTexture = 0,
621 OpenGl_RT_SceneNodeInfoTexture = 1,
622 OpenGl_RT_SceneMinPointTexture = 2,
623 OpenGl_RT_SceneMaxPointTexture = 3,
624 OpenGl_RT_SceneTransformTexture = 4,
626 OpenGl_RT_GeometryVertexTexture = 5,
627 OpenGl_RT_GeometryNormalTexture = 6,
628 OpenGl_RT_GeometryTexCrdTexture = 7,
629 OpenGl_RT_GeometryTriangTexture = 8,
631 OpenGl_RT_RaytraceMaterialTexture = 9,
632 OpenGl_RT_RaytraceLightSrcTexture = 10,
634 OpenGl_RT_FsaaInputTexture = 11,
635 OpenGl_RT_PrevAccumTexture = 12,
637 OpenGl_RT_RaytraceDepthTexture = 13
640 //! Defines OpenGL image samplers.
641 enum ShaderImageNames
643 OpenGl_RT_OutputImageLft = 0,
644 OpenGl_RT_OutputImageRgh = 1,
645 OpenGl_RT_VisualErrorImage = 2,
646 OpenGl_RT_TileOffsetsImage = 3
649 //! Tool class for management of shader sources.
654 //! Default shader prefix - empty string.
655 static const TCollection_AsciiString EMPTY_PREFIX;
657 //! Creates new uninitialized shader source.
665 //! Returns error description in case of load fail.
666 const TCollection_AsciiString& ErrorDescription() const
671 //! Returns prefix to insert before the source.
672 const TCollection_AsciiString& Prefix() const
677 //! Sets prefix to insert before the source.
678 void SetPrefix (const TCollection_AsciiString& thePrefix)
680 myPrefix = thePrefix;
683 //! Returns shader source combined with prefix.
684 TCollection_AsciiString Source() const;
686 //! Loads shader source from specified files.
687 Standard_Boolean LoadFromFiles (const TCollection_AsciiString* theFileNames, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
689 //! Loads shader source from specified strings.
690 Standard_Boolean LoadFromStrings (const TCollection_AsciiString* theStrings, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
694 TCollection_AsciiString mySource; //!< Source string of the shader object
695 TCollection_AsciiString myPrefix; //!< Prefix to insert before the source
696 TCollection_AsciiString myError; //!< error state
700 //! Default ray-tracing depth.
701 static const Standard_Integer THE_DEFAULT_NB_BOUNCES = 3;
703 //! Default size of traversal stack.
704 static const Standard_Integer THE_DEFAULT_STACK_SIZE = 10;
706 //! Compile-time ray-tracing parameters.
707 struct RaytracingParams
709 //! Actual size of traversal stack in shader program.
710 Standard_Integer StackSize;
712 //! Actual ray-tracing depth (number of ray bounces).
713 Standard_Integer NbBounces;
715 //! Enables/disables light propagation through transparent media.
716 Standard_Boolean TransparentShadows;
718 //! Enables/disables global illumination (GI) effects.
719 Standard_Boolean GlobalIllumination;
721 //! Enables/disables the use of OpenGL bindless textures.
722 Standard_Boolean UseBindlessTextures;
724 //! Enables/disables two-sided BSDF models instead of one-sided.
725 Standard_Boolean TwoSidedBsdfModels;
727 //! Enables/disables adaptive screen sampling for path tracing.
728 Standard_Boolean AdaptiveScreenSampling;
730 //! Enables/disables environment map for background.
731 Standard_Boolean UseEnvMapForBackground;
733 //! Maximum radiance value used for clamping radiance estimation.
734 Standard_ShortReal RadianceClampingValue;
736 //! Number of tiles in X dimension (in adaptive sampling mode).
737 Standard_Integer NbTilesX;
739 //! Number of tiles in Y dimension (in adaptive sampling mode).
740 Standard_Integer NbTilesY;
742 //! Creates default compile-time ray-tracing parameters.
744 : StackSize (THE_DEFAULT_STACK_SIZE),
745 NbBounces (THE_DEFAULT_NB_BOUNCES),
746 TransparentShadows (Standard_False),
747 GlobalIllumination (Standard_False),
748 UseBindlessTextures (Standard_False),
749 TwoSidedBsdfModels (Standard_False),
750 AdaptiveScreenSampling (Standard_False),
751 UseEnvMapForBackground (Standard_False),
752 RadianceClampingValue (30.0),
757 //! Describes state of OpenGL structure.
760 Standard_Size StructureState;
761 Standard_Size InstancedState;
763 //! Creates new structure state.
764 StructState (const Standard_Size theStructureState = 0,
765 const Standard_Size theInstancedState = 0)
766 : StructureState (theStructureState),
767 InstancedState (theInstancedState)
772 //! Creates new structure state.
773 StructState (const OpenGl_Structure* theStructure)
775 StructureState = theStructure->ModificationState();
777 InstancedState = theStructure->InstancedStructure() != NULL ?
778 theStructure->InstancedStructure()->ModificationState() : 0;
782 protected: //! @name methods related to ray-tracing
784 //! Updates 3D scene geometry for ray-tracing.
785 Standard_Boolean updateRaytraceGeometry (const RaytraceUpdateMode theMode,
786 const Standard_Integer theViewId,
787 const Handle(OpenGl_Context)& theGlContext);
789 //! Updates 3D scene light sources for ray-tracing.
790 Standard_Boolean updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext);
792 //! Checks to see if the OpenGL structure is modified.
793 Standard_Boolean toUpdateStructure (const OpenGl_Structure* theStructure);
795 //! Adds OpenGL structure to ray-traced scene geometry.
796 Standard_Boolean addRaytraceStructure (const OpenGl_Structure* theStructure,
797 const Handle(OpenGl_Context)& theGlContext);
799 //! Adds OpenGL groups to ray-traced scene geometry.
800 Standard_Boolean addRaytraceGroups (const OpenGl_Structure* theStructure,
801 const OpenGl_RaytraceMaterial& theStructMat,
802 const Handle(Geom_Transformation)& theTrsf,
803 const Handle(OpenGl_Context)& theGlContext);
805 //! Creates ray-tracing material properties.
806 OpenGl_RaytraceMaterial convertMaterial (const OpenGl_AspectFace* theAspect,
807 const Handle(OpenGl_Context)& theGlContext);
809 //! Adds OpenGL primitive array to ray-traced scene geometry.
810 OpenGl_TriangleSet* addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
811 const Standard_Integer theMatID,
812 const OpenGl_Mat4* theTrans);
814 //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry.
815 Standard_Boolean addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
816 const Standard_Integer theMatID,
817 const Standard_Integer theCount,
818 const Standard_Integer theOffset,
819 const OpenGl_PrimitiveArray& theArray);
821 //! Adds OpenGL triangle array to ray-traced scene geometry.
822 Standard_Boolean addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
823 const Standard_Integer theMatID,
824 const Standard_Integer theCount,
825 const Standard_Integer theOffset,
826 const Handle(Graphic3d_IndexBuffer)& theIndices);
828 //! Adds OpenGL triangle fan array to ray-traced scene geometry.
829 Standard_Boolean addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
830 const Standard_Integer theMatID,
831 const Standard_Integer theCount,
832 const Standard_Integer theOffset,
833 const Handle(Graphic3d_IndexBuffer)& theIndices);
835 //! Adds OpenGL triangle strip array to ray-traced scene geometry.
836 Standard_Boolean addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
837 const Standard_Integer theMatID,
838 const Standard_Integer theCount,
839 const Standard_Integer theOffset,
840 const Handle(Graphic3d_IndexBuffer)& theIndices);
842 //! Adds OpenGL quadrangle array to ray-traced scene geometry.
843 Standard_Boolean addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
844 const Standard_Integer theMatID,
845 const Standard_Integer theCount,
846 const Standard_Integer theOffset,
847 const Handle(Graphic3d_IndexBuffer)& theIndices);
849 //! Adds OpenGL quadrangle strip array to ray-traced scene geometry.
850 Standard_Boolean addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
851 const Standard_Integer theMatID,
852 const Standard_Integer theCount,
853 const Standard_Integer theOffset,
854 const Handle(Graphic3d_IndexBuffer)& theIndices);
856 //! Adds OpenGL polygon array to ray-traced scene geometry.
857 Standard_Boolean addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
858 const Standard_Integer theMatID,
859 const Standard_Integer theCount,
860 const Standard_Integer theOffset,
861 const Handle(Graphic3d_IndexBuffer)& theIndices);
863 //! Uploads ray-trace data to the GPU.
864 Standard_Boolean uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext);
866 //! Generates shader prefix based on current ray-tracing options.
867 TCollection_AsciiString generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const;
869 //! Performs safe exit when shaders initialization fails.
870 Standard_Boolean safeFailBack (const TCollection_ExtendedString& theMessage,
871 const Handle(OpenGl_Context)& theGlContext);
873 //! Loads and compiles shader object from specified source.
874 Handle(OpenGl_ShaderObject) initShader (const GLenum theType,
875 const ShaderSource& theSource,
876 const Handle(OpenGl_Context)& theGlContext);
878 //! Creates shader program from the given vertex and fragment shaders.
879 Handle(OpenGl_ShaderProgram) initProgram (const Handle(OpenGl_Context)& theGlContext,
880 const Handle(OpenGl_ShaderObject)& theVertShader,
881 const Handle(OpenGl_ShaderObject)& theFragShader);
883 //! Initializes OpenGL/GLSL shader programs.
884 Standard_Boolean initRaytraceResources (const Handle(OpenGl_Context)& theGlContext);
886 //! Releases OpenGL/GLSL shader programs.
887 void releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext,
888 const Standard_Boolean theToRebuild = Standard_False);
890 //! Updates auxiliary OpenGL frame buffers.
891 Standard_Boolean updateRaytraceBuffers (const Standard_Integer theSizeX,
892 const Standard_Integer theSizeY,
893 const Handle(OpenGl_Context)& theGlContext);
895 //! Generates viewing rays for corners of screen quad.
896 void updateCamera (const OpenGl_Mat4& theOrientation,
897 const OpenGl_Mat4& theViewMapping,
898 OpenGl_Vec3* theOrigins,
899 OpenGl_Vec3* theDirects,
900 OpenGl_Mat4& theView,
901 OpenGl_Mat4& theUnView);
903 //! Binds ray-trace textures to corresponding texture units.
904 void bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
906 //! Unbinds ray-trace textures from corresponding texture unit.
907 void unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
909 //! Sets uniform state for the given ray-tracing shader program.
910 Standard_Boolean setUniformState (const Standard_Integer theProgramId,
911 const Standard_Integer theSizeX,
912 const Standard_Integer theSizeY,
913 const Handle(OpenGl_Context)& theGlContext);
915 //! Runs ray-tracing shader programs.
916 Standard_Boolean runRaytraceShaders (const Standard_Integer theSizeX,
917 const Standard_Integer theSizeY,
918 Graphic3d_Camera::Projection theProjection,
919 OpenGl_FrameBuffer* theReadDrawFbo,
920 const Handle(OpenGl_Context)& theGlContext);
922 //! Runs classical (Whitted-style) ray-tracing kernel.
923 Standard_Boolean runRaytrace (const Standard_Integer theSizeX,
924 const Standard_Integer theSizeY,
925 Graphic3d_Camera::Projection theProjection,
926 OpenGl_FrameBuffer* theReadDrawFbo,
927 const Handle(OpenGl_Context)& theGlContext);
929 //! Runs path tracing (global illumination) kernel.
930 Standard_Boolean runPathtrace (const Standard_Integer theSizeX,
931 const Standard_Integer theSizeY,
932 Graphic3d_Camera::Projection theProjection,
933 OpenGl_FrameBuffer* theReadDrawFbo,
934 const Handle(OpenGl_Context)& theGlContext);
936 //! Redraws the window using OpenGL/GLSL ray-tracing or path tracing.
937 Standard_Boolean raytrace (const Standard_Integer theSizeX,
938 const Standard_Integer theSizeY,
939 Graphic3d_Camera::Projection theProjection,
940 OpenGl_FrameBuffer* theReadDrawFbo,
941 const Handle(OpenGl_Context)& theGlContext);
943 protected: //! @name fields related to ray-tracing
945 //! Result of RT/PT shaders initialization.
946 RaytraceInitStatus myRaytraceInitStatus;
948 //! Is ray-tracing geometry data valid?
949 Standard_Boolean myIsRaytraceDataValid;
951 //! True if warning about missing extension GL_ARB_bindless_texture has been displayed.
952 Standard_Boolean myIsRaytraceWarnTextures;
954 //! 3D scene geometry data for ray-tracing.
955 OpenGl_RaytraceGeometry myRaytraceGeometry;
957 //! Compile-time ray-tracing parameters.
958 RaytracingParams myRaytraceParameters;
960 //! Radius of bounding sphere of the scene.
961 Standard_ShortReal myRaytraceSceneRadius;
962 //! Scene epsilon to prevent self-intersections.
963 Standard_ShortReal myRaytraceSceneEpsilon;
965 //! OpenGL/GLSL source of ray-tracing fragment shader.
966 ShaderSource myRaytraceShaderSource;
967 //! OpenGL/GLSL source of adaptive-AA fragment shader.
968 ShaderSource myPostFSAAShaderSource;
969 //! OpenGL/GLSL source of RT/PT display fragment shader.
970 ShaderSource myOutImageShaderSource;
972 //! OpenGL/GLSL ray-tracing fragment shader.
973 Handle(OpenGl_ShaderObject) myRaytraceShader;
974 //! OpenGL/GLSL adaptive-AA fragment shader.
975 Handle(OpenGl_ShaderObject) myPostFSAAShader;
976 //! OpenGL/GLSL ray-tracing display fragment shader.
977 Handle(OpenGl_ShaderObject) myOutImageShader;
979 //! OpenGL/GLSL ray-tracing shader program.
980 Handle(OpenGl_ShaderProgram) myRaytraceProgram;
981 //! OpenGL/GLSL adaptive-AA shader program.
982 Handle(OpenGl_ShaderProgram) myPostFSAAProgram;
983 //! OpenGL/GLSL program for displaying texture.
984 Handle(OpenGl_ShaderProgram) myOutImageProgram;
986 //! Texture buffer of data records of bottom-level BVH nodes.
987 Handle(OpenGl_TextureBufferArb) mySceneNodeInfoTexture;
988 //! Texture buffer of minimum points of bottom-level BVH nodes.
989 Handle(OpenGl_TextureBufferArb) mySceneMinPointTexture;
990 //! Texture buffer of maximum points of bottom-level BVH nodes.
991 Handle(OpenGl_TextureBufferArb) mySceneMaxPointTexture;
992 //! Texture buffer of transformations of high-level BVH nodes.
993 Handle(OpenGl_TextureBufferArb) mySceneTransformTexture;
995 //! Texture buffer of vertex coords.
996 Handle(OpenGl_TextureBufferArb) myGeometryVertexTexture;
997 //! Texture buffer of vertex normals.
998 Handle(OpenGl_TextureBufferArb) myGeometryNormalTexture;
999 //! Texture buffer of vertex UV coords.
1000 Handle(OpenGl_TextureBufferArb) myGeometryTexCrdTexture;
1001 //! Texture buffer of triangle indices.
1002 Handle(OpenGl_TextureBufferArb) myGeometryTriangTexture;
1004 //! Texture buffer of material properties.
1005 Handle(OpenGl_TextureBufferArb) myRaytraceMaterialTexture;
1006 //! Texture buffer of light source properties.
1007 Handle(OpenGl_TextureBufferArb) myRaytraceLightSrcTexture;
1009 //! 1st framebuffer (FBO) to perform adaptive FSAA.
1010 //! Used in compatibility mode (no adaptive sampling).
1011 Handle(OpenGl_FrameBuffer) myRaytraceFBO1[2];
1012 //! 2nd framebuffer (FBO) to perform adaptive FSAA.
1013 //! Used in compatibility mode (no adaptive sampling).
1014 Handle(OpenGl_FrameBuffer) myRaytraceFBO2[2];
1016 //! Output textures (2 textures are used in stereo mode).
1017 //! Used if adaptive screen sampling is activated.
1018 Handle(OpenGl_Texture) myRaytraceOutputTexture[2];
1020 //! Texture containing per-tile visual error estimation.
1021 //! Used if adaptive screen sampling is activated.
1022 Handle(OpenGl_Texture) myRaytraceVisualErrorTexture;
1023 //! Texture containing offsets of sampled screen tiles.
1024 //! Used if adaptive screen sampling is activated.
1025 Handle(OpenGl_Texture) myRaytraceTileOffsetsTexture;
1027 //! Vertex buffer (VBO) for drawing dummy quad.
1028 OpenGl_VertexBuffer myRaytraceScreenQuad;
1030 //! Cached locations of frequently used uniform variables.
1031 Standard_Integer myUniformLocations[2][OpenGl_RT_NbVariables];
1033 //! State of OpenGL structures reflected to ray-tracing.
1034 std::map<const OpenGl_Structure*, StructState> myStructureStates;
1036 //! PrimitiveArray to TriangleSet map for scene partial update.
1037 std::map<Standard_Size, OpenGl_TriangleSet*> myArrayToTrianglesMap;
1039 //! Set of IDs of non-raytracable elements (to detect updates).
1040 std::set<Standard_Integer> myNonRaytraceStructureIDs;
1042 //! Render filter to filter out all raytracable structures.
1043 Handle(OpenGl_RaytraceFilter) myRaytraceFilter;
1045 //! Marks if environment map should be updated.
1046 Standard_Boolean myToUpdateEnvironmentMap;
1048 //! State of OpenGL layer list.
1049 Standard_Size myRaytraceLayerListState;
1051 //! Number of accumulated frames (for progressive rendering).
1052 Standard_Integer myAccumFrames;
1054 //! Stored ray origins used for detection of camera movements.
1055 OpenGl_Vec3 myPreviousOrigins[3];
1057 //! Bullard RNG to produce random sequence.
1058 math_BullardGenerator myRNG;
1060 //! Tool object for sampling screen tiles in PT mode.
1061 OpenGl_TileSampler myTileSampler;
1065 DEFINE_STANDARD_ALLOC
1066 DEFINE_STANDARD_RTTIEXT(OpenGl_View,Graphic3d_CView) // Type definition
1068 friend class OpenGl_GraphicDriver;
1069 friend class OpenGl_Workspace;
1070 friend class OpenGl_LayerList;
1073 #endif // _OpenGl_View_Header