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>
29 #include <Aspect_TypeOfTriedronPosition.hxx>
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>
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 #include <OpenGl_TileSampler.hxx>
59 class Graphic3d_StructureManager;
60 class OpenGl_GraphicDriver;
61 class OpenGl_StateCounter;
62 class OpenGl_RaytraceMaterial;
63 class OpenGl_TriangleSet;
64 class OpenGl_Workspace;
66 DEFINE_STANDARD_HANDLE(OpenGl_View,Graphic3d_CView)
68 //! Implementation of OpenGl view.
69 class OpenGl_View : public Graphic3d_CView
75 Standard_EXPORT OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr,
76 const Handle(OpenGl_GraphicDriver)& theDriver,
77 const Handle(OpenGl_Caps)& theCaps,
78 Standard_Boolean& theDeviceLostFlag,
79 OpenGl_StateCounter* theCounter);
81 //! Default destructor.
82 Standard_EXPORT virtual ~OpenGl_View();
84 Standard_EXPORT void ReleaseGlResources (const Handle(OpenGl_Context)& theCtx);
86 //! Deletes and erases the view.
87 Standard_EXPORT virtual void Remove() Standard_OVERRIDE;
89 //! @param theDrawToFrontBuffer Advanced option to modify rendering mode:
90 //! 1. TRUE. Drawing immediate mode structures directly to the front buffer over the scene image.
91 //! Fast, so preferred for interactive work (used by default).
92 //! However these extra drawings will be missed in image dump since it is performed from back buffer.
93 //! Notice that since no pre-buffering used the V-Sync will be ignored and rendering could be seen
94 //! in run-time (in case of slow hardware) and/or tearing may appear.
95 //! So this is strongly recommended to draw only simple (fast) structures.
96 //! 2. FALSE. Drawing immediate mode structures to the back buffer.
97 //! The complete scene is redrawn first, so this mode is slower if scene contains complex data and/or V-Sync
98 //! is turned on. But it works in any case and is especially useful for view dump because the dump image is read
99 //! from the back buffer.
100 //! @return previous mode.
101 Standard_EXPORT Standard_Boolean SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer) Standard_OVERRIDE;
103 //! Creates and maps rendering window to the view.
104 //! @param theWindow [in] the window.
105 //! @param theContext [in] the rendering context. If NULL the context will be created internally.
106 Standard_EXPORT virtual void SetWindow (const Handle(Aspect_Window)& theWindow,
107 const Aspect_RenderingContext theContext) Standard_OVERRIDE;
109 //! Returns window associated with the view.
110 virtual Handle(Aspect_Window) Window() const Standard_OVERRIDE
111 { return myWindow->PlatformWindow(); }
113 //! Returns True if the window associated to the view is defined.
114 virtual Standard_Boolean IsDefined() const Standard_OVERRIDE
115 { return !myWindow.IsNull(); }
117 //! Handle changing size of the rendering window.
118 Standard_EXPORT virtual void Resized() Standard_OVERRIDE;
120 //! Redraw content of the view.
121 Standard_EXPORT virtual void Redraw() Standard_OVERRIDE;
123 //! Redraw immediate content of the view.
124 Standard_EXPORT virtual void RedrawImmediate() Standard_OVERRIDE;
126 //! Marks BVH tree for given priority list as dirty and marks primitive set for rebuild.
127 Standard_EXPORT virtual void Invalidate() Standard_OVERRIDE;
129 //! Return true if view content cache has been invalidated.
130 virtual Standard_Boolean IsInvalidated() Standard_OVERRIDE { return !myBackBufferRestored; }
132 //! Displays z-buffer trihedron.
133 Standard_EXPORT virtual void TriedronDisplay (const Aspect_TypeOfTriedronPosition thePosition = Aspect_TOTP_CENTER,
134 const Quantity_NameOfColor theColor = Quantity_NOC_WHITE,
135 const Standard_Real theScale = 0.02,
136 const Standard_Boolean theAsWireframe = Standard_True) Standard_OVERRIDE;
138 //! Erases z-buffer trihedron.
139 Standard_EXPORT virtual void TriedronErase() Standard_OVERRIDE;
141 //! Setup parameters of z-buffer trihedron.
142 Standard_EXPORT virtual void ZBufferTriedronSetup (const Quantity_NameOfColor theXColor = Quantity_NOC_RED,
143 const Quantity_NameOfColor theYColor = Quantity_NOC_GREEN,
144 const Quantity_NameOfColor theZColor = Quantity_NOC_BLUE1,
145 const Standard_Real theSizeRatio = 0.8,
146 const Standard_Real theAxisDiametr = 0.05,
147 const Standard_Integer theNbFacettes = 12) Standard_OVERRIDE;
149 //! Displays trihedron echo.
150 Standard_EXPORT virtual void TriedronEcho (const Aspect_TypeOfTriedronEcho theType = Aspect_TOTE_NONE) Standard_OVERRIDE;
152 //! Returns data of a graduated trihedron
153 const Graphic3d_GraduatedTrihedron& GetGraduatedTrihedron() Standard_OVERRIDE
154 { return myGTrihedronData; }
156 //! Displays Graduated Trihedron.
157 Standard_EXPORT virtual void GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData) Standard_OVERRIDE;
159 //! Erases Graduated Trihedron.
160 Standard_EXPORT virtual void GraduatedTrihedronErase() Standard_OVERRIDE;
162 //! Sets minimum and maximum points of scene bounding box for Graduated Trihedron stored in graphic view object.
163 //! @param theMin [in] the minimum point of scene.
164 //! @param theMax [in] the maximum point of scene.
165 Standard_EXPORT virtual void GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax) Standard_OVERRIDE;
167 //! Dump active rendering buffer into specified memory buffer.
168 Standard_EXPORT virtual Standard_Boolean BufferDump (Image_PixMap& theImage,
169 const Graphic3d_BufferType& theBufferType) Standard_OVERRIDE;
171 //! Export scene into the one of the Vector graphics formats (SVG, PS, PDF...).
172 //! In contrast to Bitmaps, Vector graphics is scalable (so you may got quality benefits
173 //! on printing to laser printer). Notice however that results may differ a lot and
174 //! do not contain some elements.
175 Standard_EXPORT virtual Standard_Boolean Export (const Standard_CString theFileName,
176 const Graphic3d_ExportFormat theFormat,
177 const Graphic3d_SortType theSortType = Graphic3d_ST_BSP_Tree) Standard_OVERRIDE;
179 //! Marks BVH tree and the set of BVH primitives of correspondent priority list with id theLayerId as outdated.
180 Standard_EXPORT virtual void InvalidateBVHData (const Standard_Integer theLayerId) Standard_OVERRIDE;
182 //! Insert a new top-level z layer with the given ID.
183 Standard_EXPORT virtual void AddZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
185 //! Remove a z layer with the given ID.
186 Standard_EXPORT virtual void RemoveZLayer (const Graphic3d_ZLayerId theLayerId) Standard_OVERRIDE;
188 //! Sets the settings for a single Z layer of specified view.
189 Standard_EXPORT virtual void SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
190 const Graphic3d_ZLayerSettings& theSettings) Standard_OVERRIDE;
192 //! Returns the maximum Z layer ID.
193 //! First layer ID is Graphic3d_ZLayerId_Default, last ID is ZLayerMax().
194 Standard_EXPORT virtual Standard_Integer ZLayerMax() const Standard_OVERRIDE;
196 //! Returns the bounding box of all structures displayed in the Z layer.
197 //! Never fails. If Z layer does not exist nothing happens.
198 Standard_EXPORT virtual void InvalidateZLayerBoundingBox (const Graphic3d_ZLayerId theLayerId) const Standard_OVERRIDE;
200 //! Returns the bounding box of all structures displayed in the Z layer.
201 //! If Z layer does not exist the empty box is returned.
202 //! @param theLayerId layer identifier
203 //! @param theCamera camera definition
204 //! @param theWindowWidth viewport width (for applying transformation-persistence)
205 //! @param theWindowHeight viewport height (for applying transformation-persistence)
206 //! @param theToIncludeAuxiliary consider also auxiliary presentations (with infinite flag or with trihedron transformation persistence)
207 //! @return computed bounding box
208 Standard_EXPORT virtual Graphic3d_BndBox4f ZLayerBoundingBox (const Graphic3d_ZLayerId theLayerId,
209 const Handle(Graphic3d_Camera)& theCamera,
210 const Standard_Integer theWindowWidth,
211 const Standard_Integer theWindowHeight,
212 const Standard_Boolean theToIncludeAuxiliary) const Standard_OVERRIDE;
214 //! Returns pointer to an assigned framebuffer object.
215 Standard_EXPORT virtual Handle(Standard_Transient) FBO() const Standard_OVERRIDE;
217 //! Sets framebuffer object for offscreen rendering.
218 Standard_EXPORT virtual void SetFBO (const Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
220 //! Generate offscreen FBO in the graphic library.
221 //! If not supported on hardware returns NULL.
222 Standard_EXPORT virtual Handle(Standard_Transient) FBOCreate (const Standard_Integer theWidth,
223 const Standard_Integer theHeight) Standard_OVERRIDE;
225 //! Remove offscreen FBO from the graphic library
226 Standard_EXPORT virtual void FBORelease (Handle(Standard_Transient)& theFbo) Standard_OVERRIDE;
228 //! Read offscreen FBO configuration.
229 Standard_EXPORT virtual void FBOGetDimensions (const Handle(Standard_Transient)& theFbo,
230 Standard_Integer& theWidth,
231 Standard_Integer& theHeight,
232 Standard_Integer& theWidthMax,
233 Standard_Integer& theHeightMax) Standard_OVERRIDE;
235 //! Change offscreen FBO viewport.
236 Standard_EXPORT virtual void FBOChangeViewport (const Handle(Standard_Transient)& theFbo,
237 const Standard_Integer theWidth,
238 const Standard_Integer theHeight) Standard_OVERRIDE;
242 //! Returns background fill color.
243 Standard_EXPORT virtual Aspect_Background Background() const Standard_OVERRIDE;
245 //! Sets background fill color.
246 Standard_EXPORT virtual void SetBackground (const Aspect_Background& theBackground) Standard_OVERRIDE;
248 //! Returns gradient background fill colors.
249 Standard_EXPORT virtual Aspect_GradientBackground GradientBackground() const Standard_OVERRIDE;
251 //! Sets gradient background fill colors.
252 Standard_EXPORT virtual void SetGradientBackground (const Aspect_GradientBackground& theBackground) Standard_OVERRIDE;
254 //! Returns background image texture file path.
255 Standard_EXPORT virtual TCollection_AsciiString BackgroundImage() Standard_OVERRIDE { return myBackgroundImagePath; }
257 //! Sets background image texture file path.
258 Standard_EXPORT virtual void SetBackgroundImage (const TCollection_AsciiString& theFilePath) Standard_OVERRIDE;
260 //! Returns background image fill style.
261 Standard_EXPORT virtual Aspect_FillMethod BackgroundImageStyle() const Standard_OVERRIDE;
263 //! Sets background image fill style.
264 Standard_EXPORT virtual void SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle) Standard_OVERRIDE;
266 //! Returns environment texture set for the view.
267 Standard_EXPORT virtual Handle(Graphic3d_TextureEnv) TextureEnv() const Standard_OVERRIDE { return myTextureEnvData; }
269 //! Sets environment texture for the view.
270 Standard_EXPORT virtual void SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv) Standard_OVERRIDE;
272 //! Returns the state of frustum culling optimization.
273 virtual Standard_Boolean IsCullingEnabled() const Standard_OVERRIDE { return myCulling; }
275 //! Enables or disables frustum culling optimization.
276 virtual void SetCullingEnabled (const Standard_Boolean theIsEnabled) Standard_OVERRIDE { myCulling = theIsEnabled; }
278 //! Returns shading model of the view.
279 virtual Graphic3d_TypeOfShadingModel ShadingModel() const Standard_OVERRIDE { return myShadingModel; }
281 //! Sets shading model of the view.
282 virtual void SetShadingModel (const Graphic3d_TypeOfShadingModel theModel) Standard_OVERRIDE { myShadingModel = theModel; }
284 //! Return backfacing model used for the view.
285 virtual Graphic3d_TypeOfBackfacingModel BackfacingModel() const Standard_OVERRIDE { return myBackfacing; }
287 //! Sets backfacing model for the view.
288 virtual void SetBackfacingModel (const Graphic3d_TypeOfBackfacingModel theModel) Standard_OVERRIDE { myBackfacing = theModel; }
290 //! Returns camera object of the view.
291 virtual const Handle(Graphic3d_Camera)& Camera() const Standard_OVERRIDE { return myCamera; }
293 //! Sets camera used by the view.
294 virtual void SetCamera (const Handle(Graphic3d_Camera)& theCamera) Standard_OVERRIDE { myCamera = theCamera; }
296 //! Returns true if GL lighting is enabled.
297 virtual Standard_Boolean IsGLLightEnabled() const Standard_OVERRIDE { return myUseGLLight; }
299 //! Sets GL lighting enabled or disable state.
300 virtual void SetGLLightEnabled (const Standard_Boolean theIsEnabled) Standard_OVERRIDE { myUseGLLight = theIsEnabled; }
302 //! Returns list of lights of the view.
303 virtual const Graphic3d_ListOfCLight& Lights() const Standard_OVERRIDE { return myLights; }
305 //! Sets list of lights for the view.
306 virtual void SetLights (const Graphic3d_ListOfCLight& theLights) Standard_OVERRIDE
308 myLights = theLights;
309 myCurrLightSourceState = myStateCounter->Increment();
312 //! Returns list of clip planes set for the view.
313 virtual const Handle(Graphic3d_SequenceOfHClipPlane)& ClipPlanes() const Standard_OVERRIDE { return myClipPlanes; }
315 //! Sets list of clip planes for the view.
316 virtual void SetClipPlanes (const Handle(Graphic3d_SequenceOfHClipPlane)& thePlanes) Standard_OVERRIDE { myClipPlanes = thePlanes; }
318 //! Fill in the dictionary with diagnostic info.
319 //! Should be called within rendering thread.
321 //! This API should be used only for user output or for creating automated reports.
322 //! The format of returned information (e.g. key-value layout)
323 //! is NOT part of this API and can be changed at any time.
324 //! Thus application should not parse returned information to weed out specific parameters.
325 Standard_EXPORT virtual void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
326 Graphic3d_DiagnosticInfo theFlags) const Standard_OVERRIDE;
330 //! Returns background color.
331 const Quantity_ColorRGBA& BackgroundColor() const { return myBgColor; }
333 //! Change trihedron.
334 OpenGl_Trihedron& ChangeTrihedron() { return myTrihedron; }
336 //! Change graduated trihedron.
337 OpenGl_GraduatedTrihedron& ChangeGraduatedTrihedron() { return myGraduatedTrihedron; }
339 void SetTextureEnv (const Handle(OpenGl_Context)& theCtx,
340 const Handle(Graphic3d_TextureEnv)& theTexture);
342 void SetBackgroundTextureStyle (const Aspect_FillMethod FillStyle);
344 void SetBackgroundGradient (const Quantity_Color& AColor1, const Quantity_Color& AColor2, const Aspect_GradientFillMethod AType);
346 void SetBackgroundGradientType (const Aspect_GradientFillMethod AType);
348 //! Returns list of OpenGL Z-layers.
349 const OpenGl_LayerList& LayerList() const { return myZLayers; }
351 //! Returns list of openGL light sources.
352 const OpenGl_ListOfLight& LightList() const { return myLights; }
354 //! Returns OpenGL window implementation.
355 const Handle(OpenGl_Window) GlWindow() const { return myWindow; }
357 //! Returns OpenGL environment map.
358 const Handle(OpenGl_Texture)& GlTextureEnv() const { return myTextureEnv; }
360 //! Returns selector for BVH tree, providing a possibility to store information
361 //! about current view volume and to detect which objects are overlapping it.
362 OpenGl_BVHTreeSelector& BVHTreeSelector() { return myBVHSelector; }
364 //! Returns true if there are immediate structures to display
365 bool HasImmediateStructures() const
367 return myZLayers.NbImmediateStructures() != 0;
370 protected: //! @name Internal methods for managing GL resources
372 //! Initializes OpenGl resource for environment texture.
373 void initTextureEnv (const Handle(OpenGl_Context)& theContext);
375 protected: //! @name low-level redrawing sub-routines
377 //! Redraws view for the given monographic camera projection, or left/right eye.
378 Standard_EXPORT virtual void redraw (const Graphic3d_Camera::Projection theProjection,
379 OpenGl_FrameBuffer* theReadDrawFbo);
381 //! Redraws view for the given monographic camera projection, or left/right eye.
383 //! Method will blit snapshot containing main scene (myMainSceneFbos or BackBuffer)
384 //! into presentation buffer (myMainSceneFbos -> offscreen FBO or
385 //! myMainSceneFbos -> BackBuffer or BackBuffer -> FrontBuffer),
386 //! and redraw immediate structures on top.
388 //! When scene caching is disabled (myTransientDrawToFront, no double buffer in window, etc.),
389 //! the first step (blitting) will be skipped.
391 //! @return false if immediate structures has been rendered directly into FrontBuffer
392 //! and Buffer Swap should not be called.
393 Standard_EXPORT virtual bool redrawImmediate (const Graphic3d_Camera::Projection theProjection,
394 OpenGl_FrameBuffer* theReadFbo,
395 OpenGl_FrameBuffer* theDrawFbo,
396 const Standard_Boolean theIsPartialUpdate = Standard_False);
398 //! Blit image from/to specified buffers.
399 Standard_EXPORT bool blitBuffers (OpenGl_FrameBuffer* theReadFbo,
400 OpenGl_FrameBuffer* theDrawFbo,
401 const Standard_Boolean theToFlip = Standard_False);
403 //! Setup default FBO.
404 Standard_EXPORT void bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo = NULL);
406 protected: //! @name Rendering of GL graphics (with prepared drawing buffer).
408 //! Renders the graphical contents of the view into the preprepared window or framebuffer.
409 //! @param theProjection [in] the projection that should be used for rendering.
410 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
411 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
412 Standard_EXPORT virtual void render (Graphic3d_Camera::Projection theProjection,
413 OpenGl_FrameBuffer* theReadDrawFbo,
414 const Standard_Boolean theToDrawImmediate);
416 //! Renders the graphical scene.
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 renderScene (Graphic3d_Camera::Projection theProjection,
421 OpenGl_FrameBuffer* theReadDrawFbo,
422 const Standard_Boolean theToDrawImmediate);
424 //! Draw background (gradient / image)
425 Standard_EXPORT virtual void drawBackground (const Handle(OpenGl_Workspace)& theWorkspace);
427 //! Render set of structures presented in the view.
428 //! @param theProjection [in] the projection that is used for rendering.
429 //! @param theReadDrawFbo [in] the framebuffer for rendering graphics.
430 //! @param theToDrawImmediate [in] the flag indicates whether the rendering performs in immediate mode.
431 Standard_EXPORT virtual void renderStructs (Graphic3d_Camera::Projection theProjection,
432 OpenGl_FrameBuffer* theReadDrawFbo,
433 const Standard_Boolean theToDrawImmediate);
435 //! Renders trihedron.
436 void renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace);
440 //! Adds the structure to display lists of the view.
441 Standard_EXPORT virtual void displayStructure (const Handle(Graphic3d_CStructure)& theStructure,
442 const Standard_Integer thePriority) Standard_OVERRIDE;
444 //! Erases the structure from display lists of the view.
445 Standard_EXPORT virtual void eraseStructure (const Handle(Graphic3d_CStructure)& theStructure) Standard_OVERRIDE;
447 //! Change Z layer of a structure already presented in view.
448 Standard_EXPORT virtual void changeZLayer (const Handle(Graphic3d_CStructure)& theCStructure,
449 const Graphic3d_ZLayerId theNewLayerId) Standard_OVERRIDE;
451 //! Changes the priority of a structure within its Z layer in the specified view.
452 Standard_EXPORT virtual void changePriority (const Handle(Graphic3d_CStructure)& theCStructure,
453 const Standard_Integer theNewPriority) Standard_OVERRIDE;
455 //! Returns zoom-scale factor.
456 Standard_EXPORT virtual Standard_Real considerZoomPersistenceObjects (const Graphic3d_ZLayerId theLayerId,
457 const Handle(Graphic3d_Camera)& theCamera,
458 const Standard_Integer theWindowWidth,
459 const Standard_Integer theWindowHeight) const Standard_OVERRIDE;
463 //! Copy content of Back buffer to the Front buffer.
464 void copyBackToFront();
466 //! Initialize blit quad.
467 OpenGl_VertexBuffer* initBlitQuad (const Standard_Boolean theToFlip);
469 //! Blend together views pair into stereo image.
470 void drawStereoPair (OpenGl_FrameBuffer* theDrawFbo);
474 OpenGl_GraphicDriver* myDriver;
475 Handle(OpenGl_Window) myWindow;
476 Handle(OpenGl_Workspace) myWorkspace;
477 Handle(OpenGl_Caps) myCaps;
478 Standard_Boolean& myDeviceLostFlag;
479 Standard_Boolean myWasRedrawnGL;
481 Standard_Boolean myCulling;
482 Graphic3d_TypeOfShadingModel myShadingModel;
483 Graphic3d_TypeOfBackfacingModel myBackfacing;
484 Quantity_ColorRGBA myBgColor;
485 Handle(Graphic3d_SequenceOfHClipPlane) myClipPlanes;
486 Handle(Graphic3d_Camera) myCamera;
487 Handle(OpenGl_FrameBuffer) myFBO;
488 Standard_Boolean myUseGLLight;
489 Standard_Boolean myToShowTrihedron;
490 Standard_Boolean myToShowGradTrihedron;
491 TCollection_AsciiString myBackgroundImagePath;
492 Handle(Graphic3d_TextureEnv) myTextureEnvData;
493 Graphic3d_GraduatedTrihedron myGTrihedronData;
495 OpenGl_ListOfLight myNoShadingLight;
496 OpenGl_ListOfLight myLights;
497 OpenGl_LayerList myZLayers; //!< main list of displayed structure, sorted by layers
499 Graphic3d_WorldViewProjState myWorldViewProjState; //!< camera modification state
500 OpenGl_StateCounter* myStateCounter;
501 Standard_Size myCurrLightSourceState;
503 typedef std::pair<Standard_Size, Standard_Size> StateInfo;
505 StateInfo myLastOrientationState;
506 StateInfo myLastViewMappingState;
507 StateInfo myLastLightSourceState;
509 //! Is needed for selection of overlapping objects and storage of the current view volume
510 OpenGl_BVHTreeSelector myBVHSelector;
512 OpenGl_Trihedron myTrihedron;
513 OpenGl_GraduatedTrihedron myGraduatedTrihedron;
515 Handle(OpenGl_Texture) myTextureEnv;
517 //! Framebuffers for OpenGL output.
518 Handle(OpenGl_FrameBuffer) myOpenGlFBO;
519 Handle(OpenGl_FrameBuffer) myOpenGlFBO2;
521 protected: //! @name Rendering properties
523 //! Two framebuffers (left and right views) store cached main presentation
524 //! of the view (without presentation of immediate layers).
525 GLint myFboColorFormat; //!< sized format for color attachments
526 GLint myFboDepthFormat; //!< sized format for depth-stencil attachments
527 Handle(OpenGl_FrameBuffer) myMainSceneFbos[2];
528 Handle(OpenGl_FrameBuffer) myImmediateSceneFbos[2]; //!< Additional buffers for immediate layer in stereo mode.
529 OpenGl_VertexBuffer myFullScreenQuad; //!< Vertices for full-screen quad rendering.
530 OpenGl_VertexBuffer myFullScreenQuadFlip;
531 Standard_Boolean myToFlipOutput; //!< Flag to draw result image upside-down
532 unsigned int myFrameCounter; //!< redraw counter, for debugging
533 Standard_Boolean myHasFboBlit; //!< disable FBOs on failure
534 Standard_Boolean myToDisableMSAA; //!< disable MSAA after failure
535 Standard_Boolean myTransientDrawToFront; //!< optimization flag for immediate mode (to render directly to the front buffer)
536 Standard_Boolean myBackBufferRestored;
537 Standard_Boolean myIsImmediateDrawn; //!< flag indicates that immediate mode buffer contains some data
539 protected: //! @name Background parameters
541 OpenGl_AspectFace* myTextureParams; //!< Stores texture and its parameters for textured background
542 OpenGl_BackgroundArray* myBgGradientArray; //!< Primitive array for gradient background
543 OpenGl_BackgroundArray* myBgTextureArray; //!< Primitive array for texture background
545 protected: //! @name data types related to ray-tracing
547 //! Result of OpenGL shaders initialization.
548 enum RaytraceInitStatus
555 //! Describes update mode (state).
556 enum RaytraceUpdateMode
558 OpenGl_GUM_CHECK, //!< check geometry state
559 OpenGl_GUM_PREPARE, //!< collect unchanged objects
560 OpenGl_GUM_REBUILD //!< rebuild changed and new objects
563 //! Defines frequently used shader variables.
564 enum ShaderVariableIndex
577 OpenGl_RT_uViewPrMat,
578 OpenGl_RT_uUnviewMat,
583 OpenGl_RT_uLightAmbnt,
584 OpenGl_RT_uLightCount,
587 OpenGl_RT_uBackColorTop,
588 OpenGl_RT_uBackColorBot,
590 // ray-tracing params
591 OpenGl_RT_uShadowsEnabled,
592 OpenGl_RT_uReflectEnabled,
593 OpenGl_RT_uSphereMapEnabled,
594 OpenGl_RT_uSphereMapForBack,
595 OpenGl_RT_uTexSamplersArray,
596 OpenGl_RT_uBlockedRngEnabled,
598 // size of render window
602 // sampled frame params
603 OpenGl_RT_uSampleWeight,
604 OpenGl_RT_uFrameRndSeed,
606 // adaptive FSAA params
611 // adaptive path tracing images
612 OpenGl_RT_uRenderImage,
613 OpenGl_RT_uOffsetImage,
615 OpenGl_RT_NbVariables // special field
618 //! Defines OpenGL texture samplers.
619 enum ShaderSamplerNames
621 OpenGl_RT_SceneNodeInfoTexture = 0,
622 OpenGl_RT_SceneMinPointTexture = 1,
623 OpenGl_RT_SceneMaxPointTexture = 2,
624 OpenGl_RT_SceneTransformTexture = 3,
626 OpenGl_RT_GeometryVertexTexture = 4,
627 OpenGl_RT_GeometryNormalTexture = 5,
628 OpenGl_RT_GeometryTexCrdTexture = 6,
629 OpenGl_RT_GeometryTriangTexture = 7,
631 OpenGl_RT_EnvironmentMapTexture = 8,
633 OpenGl_RT_RaytraceMaterialTexture = 9,
634 OpenGl_RT_RaytraceLightSrcTexture = 10,
636 OpenGl_RT_FsaaInputTexture = 11,
637 OpenGl_RT_PrevAccumTexture = 12,
639 OpenGl_RT_RaytraceDepthTexture = 13
642 //! Defines OpenGL image samplers.
643 enum ShaderImageNames
645 OpenGl_RT_OutputImageLft = 0,
646 OpenGl_RT_OutputImageRgh = 1,
647 OpenGl_RT_VisualErrorImage = 2,
648 OpenGl_RT_TileOffsetsImage = 3
651 //! Tool class for management of shader sources.
656 //! Default shader prefix - empty string.
657 static const TCollection_AsciiString EMPTY_PREFIX;
659 //! Creates new uninitialized shader source.
667 //! Returns error description in case of load fail.
668 const TCollection_AsciiString& ErrorDescription() const
673 //! Returns prefix to insert before the source.
674 const TCollection_AsciiString& Prefix() const
679 //! Sets prefix to insert before the source.
680 void SetPrefix (const TCollection_AsciiString& thePrefix)
682 myPrefix = thePrefix;
685 //! Returns shader source combined with prefix.
686 TCollection_AsciiString Source() const;
688 //! Loads shader source from specified files.
689 Standard_Boolean Load (const TCollection_AsciiString* theFileNames, const TCollection_AsciiString& thePrefix = EMPTY_PREFIX);
693 TCollection_AsciiString mySource; //!< Source string of the shader object
694 TCollection_AsciiString myPrefix; //!< Prefix to insert before the source
695 TCollection_AsciiString myError; //!< error state
699 //! Default ray-tracing depth.
700 static const Standard_Integer THE_DEFAULT_NB_BOUNCES = 3;
702 //! Default size of traversal stack.
703 static const Standard_Integer THE_DEFAULT_STACK_SIZE = 10;
705 //! Compile-time ray-tracing parameters.
706 struct RaytracingParams
708 //! Actual size of traversal stack in shader program.
709 Standard_Integer StackSize;
711 //! Actual ray-tracing depth (number of ray bounces).
712 Standard_Integer NbBounces;
714 //! Enables/disables light propagation through transparent media.
715 Standard_Boolean TransparentShadows;
717 //! Enables/disables global illumination (GI) effects.
718 Standard_Boolean GlobalIllumination;
720 //! Enables/disables the use of OpenGL bindless textures.
721 Standard_Boolean UseBindlessTextures;
723 //! Enables/disables adaptive screen sampling for path tracing.
724 Standard_Boolean AdaptiveScreenSampling;
726 //! Creates default compile-time ray-tracing parameters.
728 : StackSize (THE_DEFAULT_STACK_SIZE),
729 NbBounces (THE_DEFAULT_NB_BOUNCES),
730 TransparentShadows (Standard_False),
731 GlobalIllumination (Standard_False),
732 UseBindlessTextures (Standard_False),
733 AdaptiveScreenSampling (Standard_False)
739 //! Describes state of OpenGL structure.
742 Standard_Size StructureState;
743 Standard_Size InstancedState;
745 //! Creates new structure state.
746 StructState (const Standard_Size theStructureState = 0,
747 const Standard_Size theInstancedState = 0)
748 : StructureState (theStructureState),
749 InstancedState (theInstancedState)
754 //! Creates new structure state.
755 StructState (const OpenGl_Structure* theStructure)
757 StructureState = theStructure->ModificationState();
759 InstancedState = theStructure->InstancedStructure() != NULL ?
760 theStructure->InstancedStructure()->ModificationState() : 0;
764 protected: //! @name methods related to ray-tracing
766 //! Updates 3D scene geometry for ray-tracing.
767 Standard_Boolean updateRaytraceGeometry (const RaytraceUpdateMode theMode,
768 const Standard_Integer theViewId,
769 const Handle(OpenGl_Context)& theGlContext);
771 //! Updates 3D scene light sources for ray-tracing.
772 Standard_Boolean updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext);
774 //! Updates environment map for ray-tracing.
775 Standard_Boolean updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext);
777 //! Checks to see if the OpenGL structure is modified.
778 Standard_Boolean toUpdateStructure (const OpenGl_Structure* theStructure);
780 //! Adds OpenGL structure to ray-traced scene geometry.
781 Standard_Boolean addRaytraceStructure (const OpenGl_Structure* theStructure,
782 const Handle(OpenGl_Context)& theGlContext);
784 //! Adds OpenGL groups to ray-traced scene geometry.
785 Standard_Boolean addRaytraceGroups (const OpenGl_Structure* theStructure,
786 const OpenGl_RaytraceMaterial& theStructMat,
787 const Handle(Geom_Transformation)& theTrsf,
788 const Handle(OpenGl_Context)& theGlContext);
790 //! Creates ray-tracing material properties.
791 OpenGl_RaytraceMaterial convertMaterial (const OpenGl_AspectFace* theAspect,
792 const Handle(OpenGl_Context)& theGlContext);
794 //! Adds OpenGL primitive array to ray-traced scene geometry.
795 OpenGl_TriangleSet* addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
796 const Standard_Integer theMatID,
797 const OpenGl_Mat4* theTrans);
799 //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry.
800 Standard_Boolean addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
801 const Standard_Integer theMatID,
802 const Standard_Integer theCount,
803 const Standard_Integer theOffset,
804 const OpenGl_PrimitiveArray& theArray);
806 //! Adds OpenGL triangle array to ray-traced scene geometry.
807 Standard_Boolean addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
808 const Standard_Integer theMatID,
809 const Standard_Integer theCount,
810 const Standard_Integer theOffset,
811 const Handle(Graphic3d_IndexBuffer)& theIndices);
813 //! Adds OpenGL triangle fan array to ray-traced scene geometry.
814 Standard_Boolean addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
815 const Standard_Integer theMatID,
816 const Standard_Integer theCount,
817 const Standard_Integer theOffset,
818 const Handle(Graphic3d_IndexBuffer)& theIndices);
820 //! Adds OpenGL triangle strip array to ray-traced scene geometry.
821 Standard_Boolean addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
822 const Standard_Integer theMatID,
823 const Standard_Integer theCount,
824 const Standard_Integer theOffset,
825 const Handle(Graphic3d_IndexBuffer)& theIndices);
827 //! Adds OpenGL quadrangle array to ray-traced scene geometry.
828 Standard_Boolean addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
829 const Standard_Integer theMatID,
830 const Standard_Integer theCount,
831 const Standard_Integer theOffset,
832 const Handle(Graphic3d_IndexBuffer)& theIndices);
834 //! Adds OpenGL quadrangle strip array to ray-traced scene geometry.
835 Standard_Boolean addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
836 const Standard_Integer theMatID,
837 const Standard_Integer theCount,
838 const Standard_Integer theOffset,
839 const Handle(Graphic3d_IndexBuffer)& theIndices);
841 //! Adds OpenGL polygon array to ray-traced scene geometry.
842 Standard_Boolean addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
843 const Standard_Integer theMatID,
844 const Standard_Integer theCount,
845 const Standard_Integer theOffset,
846 const Handle(Graphic3d_IndexBuffer)& theIndices);
848 //! Uploads ray-trace data to the GPU.
849 Standard_Boolean uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext);
851 //! Generates shader prefix based on current ray-tracing options.
852 TCollection_AsciiString generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const;
854 //! Performs safe exit when shaders initialization fails.
855 Standard_Boolean safeFailBack (const TCollection_ExtendedString& theMessage,
856 const Handle(OpenGl_Context)& theGlContext);
858 //! Loads and compiles shader object from specified source.
859 Handle(OpenGl_ShaderObject) initShader (const GLenum theType,
860 const ShaderSource& theSource,
861 const Handle(OpenGl_Context)& theGlContext);
863 //! Creates shader program from the given vertex and fragment shaders.
864 Handle(OpenGl_ShaderProgram) initProgram (const Handle(OpenGl_Context)& theGlContext,
865 const Handle(OpenGl_ShaderObject)& theVertShader,
866 const Handle(OpenGl_ShaderObject)& theFragShader);
868 //! Initializes OpenGL/GLSL shader programs.
869 Standard_Boolean initRaytraceResources (const Handle(OpenGl_Context)& theGlContext);
871 //! Releases OpenGL/GLSL shader programs.
872 void releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext,
873 const Standard_Boolean theToRebuild = Standard_False);
875 //! Updates auxiliary OpenGL frame buffers.
876 Standard_Boolean updateRaytraceBuffers (const Standard_Integer theSizeX,
877 const Standard_Integer theSizeY,
878 const Handle(OpenGl_Context)& theGlContext);
880 //! Generates viewing rays for corners of screen quad.
881 void updateCamera (const OpenGl_Mat4& theOrientation,
882 const OpenGl_Mat4& theViewMapping,
883 OpenGl_Vec3* theOrigins,
884 OpenGl_Vec3* theDirects,
885 OpenGl_Mat4& theView,
886 OpenGl_Mat4& theUnView);
888 //! Binds ray-trace textures to corresponding texture units.
889 void bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
891 //! Unbinds ray-trace textures from corresponding texture unit.
892 void unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext);
894 //! Sets uniform state for the given ray-tracing shader program.
895 Standard_Boolean setUniformState (const Standard_Integer theProgramId,
896 const Standard_Integer theSizeX,
897 const Standard_Integer theSizeY,
898 const Handle(OpenGl_Context)& theGlContext);
900 //! Runs ray-tracing shader programs.
901 Standard_Boolean runRaytraceShaders (const Standard_Integer theSizeX,
902 const Standard_Integer theSizeY,
903 Graphic3d_Camera::Projection theProjection,
904 OpenGl_FrameBuffer* theReadDrawFbo,
905 const Handle(OpenGl_Context)& theGlContext);
907 //! Runs classical (Whitted-style) ray-tracing kernel.
908 Standard_Boolean runRaytrace (const Standard_Integer theSizeX,
909 const Standard_Integer theSizeY,
910 Graphic3d_Camera::Projection theProjection,
911 OpenGl_FrameBuffer* theReadDrawFbo,
912 const Handle(OpenGl_Context)& theGlContext);
914 //! Runs path tracing (global illumination) kernel.
915 Standard_Boolean runPathtrace (const Graphic3d_Camera::Projection theProjection,
916 OpenGl_FrameBuffer* theReadDrawFbo,
917 const Handle(OpenGl_Context)& theGlContext);
919 //! Redraws the window using OpenGL/GLSL ray-tracing or path tracing.
920 Standard_Boolean raytrace (const Standard_Integer theSizeX,
921 const Standard_Integer theSizeY,
922 Graphic3d_Camera::Projection theProjection,
923 OpenGl_FrameBuffer* theReadDrawFbo,
924 const Handle(OpenGl_Context)& theGlContext);
926 protected: //! @name fields related to ray-tracing
928 //! Result of RT/PT shaders initialization.
929 RaytraceInitStatus myRaytraceInitStatus;
931 //! Is ray-tracing geometry data valid?
932 Standard_Boolean myIsRaytraceDataValid;
934 //! True if warning about missing extension GL_ARB_bindless_texture has been displayed.
935 Standard_Boolean myIsRaytraceWarnTextures;
937 //! 3D scene geometry data for ray-tracing.
938 OpenGl_RaytraceGeometry myRaytraceGeometry;
940 //! Compile-time ray-tracing parameters.
941 RaytracingParams myRaytraceParameters;
943 //! Radius of bounding sphere of the scene.
944 Standard_ShortReal myRaytraceSceneRadius;
945 //! Scene epsilon to prevent self-intersections.
946 Standard_ShortReal myRaytraceSceneEpsilon;
948 //! OpenGL/GLSL source of ray-tracing fragment shader.
949 ShaderSource myRaytraceShaderSource;
950 //! OpenGL/GLSL source of adaptive-AA fragment shader.
951 ShaderSource myPostFSAAShaderSource;
952 //! OpenGL/GLSL source of RT/PT display fragment shader.
953 ShaderSource myOutImageShaderSource;
955 //! OpenGL/GLSL ray-tracing fragment shader.
956 Handle(OpenGl_ShaderObject) myRaytraceShader;
957 //! OpenGL/GLSL adaptive-AA fragment shader.
958 Handle(OpenGl_ShaderObject) myPostFSAAShader;
959 //! OpenGL/GLSL ray-tracing display fragment shader.
960 Handle(OpenGl_ShaderObject) myOutImageShader;
962 //! OpenGL/GLSL ray-tracing shader program.
963 Handle(OpenGl_ShaderProgram) myRaytraceProgram;
964 //! OpenGL/GLSL adaptive-AA shader program.
965 Handle(OpenGl_ShaderProgram) myPostFSAAProgram;
966 //! OpenGL/GLSL program for displaying texture.
967 Handle(OpenGl_ShaderProgram) myOutImageProgram;
969 //! Texture buffer of data records of bottom-level BVH nodes.
970 Handle(OpenGl_TextureBufferArb) mySceneNodeInfoTexture;
971 //! Texture buffer of minimum points of bottom-level BVH nodes.
972 Handle(OpenGl_TextureBufferArb) mySceneMinPointTexture;
973 //! Texture buffer of maximum points of bottom-level BVH nodes.
974 Handle(OpenGl_TextureBufferArb) mySceneMaxPointTexture;
975 //! Texture buffer of transformations of high-level BVH nodes.
976 Handle(OpenGl_TextureBufferArb) mySceneTransformTexture;
978 //! Texture buffer of vertex coords.
979 Handle(OpenGl_TextureBufferArb) myGeometryVertexTexture;
980 //! Texture buffer of vertex normals.
981 Handle(OpenGl_TextureBufferArb) myGeometryNormalTexture;
982 //! Texture buffer of vertex UV coords.
983 Handle(OpenGl_TextureBufferArb) myGeometryTexCrdTexture;
984 //! Texture buffer of triangle indices.
985 Handle(OpenGl_TextureBufferArb) myGeometryTriangTexture;
987 //! Texture buffer of material properties.
988 Handle(OpenGl_TextureBufferArb) myRaytraceMaterialTexture;
989 //! Texture buffer of light source properties.
990 Handle(OpenGl_TextureBufferArb) myRaytraceLightSrcTexture;
992 //! 1st framebuffer (FBO) to perform adaptive FSAA.
993 //! Used in compatibility mode (no adaptive sampling).
994 Handle(OpenGl_FrameBuffer) myRaytraceFBO1[2];
995 //! 2nd framebuffer (FBO) to perform adaptive FSAA.
996 //! Used in compatibility mode (no adaptive sampling).
997 Handle(OpenGl_FrameBuffer) myRaytraceFBO2[2];
999 //! Output textures (2 textures are used in stereo mode).
1000 //! Used if adaptive screen sampling is activated.
1001 Handle(OpenGl_Texture) myRaytraceOutputTexture[2];
1003 //! Texture containing per-tile visual error estimation.
1004 //! Used if adaptive screen sampling is activated.
1005 Handle(OpenGl_Texture) myRaytraceVisualErrorTexture;
1006 //! Texture containing offsets of sampled screen tiles.
1007 //! Used if adaptive screen sampling is activated.
1008 Handle(OpenGl_Texture) myRaytraceTileOffsetsTexture;
1010 //! Vertex buffer (VBO) for drawing dummy quad.
1011 OpenGl_VertexBuffer myRaytraceScreenQuad;
1013 //! Cached locations of frequently used uniform variables.
1014 Standard_Integer myUniformLocations[2][OpenGl_RT_NbVariables];
1016 //! State of OpenGL structures reflected to ray-tracing.
1017 std::map<const OpenGl_Structure*, StructState> myStructureStates;
1019 //! PrimitiveArray to TriangleSet map for scene partial update.
1020 std::map<Standard_Size, OpenGl_TriangleSet*> myArrayToTrianglesMap;
1022 //! Set of IDs of non-raytracable elements (to detect updates).
1023 std::set<Standard_Integer> myNonRaytraceStructureIDs;
1025 //! Render filter to filter out all raytracable structures.
1026 Handle(OpenGl_RaytraceFilter) myRaytraceFilter;
1028 //! Marks if environment map should be updated.
1029 Standard_Boolean myToUpdateEnvironmentMap;
1031 //! State of OpenGL layer list.
1032 Standard_Size myRaytraceLayerListState;
1034 //! Number of accumulated frames (for progressive rendering).
1035 Standard_Integer myAccumFrames;
1037 //! Stored ray origins used for detection of camera movements.
1038 OpenGl_Vec3 myPreviousOrigins[3];
1040 //! Bullard RNG to produce random sequence.
1041 math_BullardGenerator myRNG;
1043 //! Tool object for sampling screen tiles in PT mode.
1044 OpenGl_TileSampler myTileSampler;
1048 DEFINE_STANDARD_ALLOC
1049 DEFINE_STANDARD_RTTIEXT(OpenGl_View,Graphic3d_CView) // Type definition
1051 friend class OpenGl_GraphicDriver;
1052 friend class OpenGl_Workspace;
1055 #endif // _OpenGl_View_Header