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.
19 #include <OpenGl_GlCore11.hxx>
21 #include <Graphic3d_GraphicDriver.hxx>
22 #include <Graphic3d_StructureManager.hxx>
23 #include <Graphic3d_TextureParams.hxx>
24 #include <Graphic3d_Texture2Dmanual.hxx>
25 #include <Graphic3d_TransformUtils.hxx>
26 #include <Image_AlienPixMap.hxx>
28 #include <NCollection_Mat4.hxx>
30 #include <OpenGl_AspectLine.hxx>
31 #include <OpenGl_Context.hxx>
32 #include <OpenGl_FrameStats.hxx>
33 #include <OpenGl_Matrix.hxx>
34 #include <OpenGl_Workspace.hxx>
35 #include <OpenGl_View.hxx>
36 #include <OpenGl_GraduatedTrihedron.hxx>
37 #include <OpenGl_PrimitiveArray.hxx>
38 #include <OpenGl_ShaderManager.hxx>
39 #include <OpenGl_ShaderProgram.hxx>
40 #include <OpenGl_Structure.hxx>
41 #include <OpenGl_ArbFBO.hxx>
45 //! Format Frame Buffer format for logging messages.
46 static TCollection_AsciiString printFboFormat (const Handle(OpenGl_FrameBuffer)& theFbo)
48 return TCollection_AsciiString() + theFbo->GetInitVPSizeX() + "x" + theFbo->GetInitVPSizeY() + "@" + theFbo->NbSamples();
51 //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
52 static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
53 Standard_Integer theSizeX,
54 Standard_Integer theSizeY,
55 Standard_Integer theNbSamples)
57 return !theFboToCheck->IsValid()
58 && theFboToCheck->GetInitVPSizeX() == theSizeX
59 && theFboToCheck->GetInitVPSizeY() == theSizeY
60 && theFboToCheck->NbSamples() == theNbSamples;
63 //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
64 static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
65 const Handle(OpenGl_FrameBuffer)& theFboRef)
67 return checkWasFailedFbo (theFboToCheck, theFboRef->GetVPSizeX(), theFboRef->GetVPSizeY(), theFboRef->NbSamples());
71 //=======================================================================
72 //function : drawBackground
74 //=======================================================================
75 void OpenGl_View::drawBackground (const Handle(OpenGl_Workspace)& theWorkspace)
77 const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
79 if (!myBgTextureArray->IsDefined() // no texture
80 && !myBgGradientArray->IsDefined()) // no gradient
85 const Standard_Boolean wasUsedZBuffer = theWorkspace->SetUseZBuffer (Standard_False);
88 aCtx->core11fwd->glDisable (GL_DEPTH_TEST);
91 // Drawing background gradient if:
92 // - gradient fill type is not Aspect_GFM_NONE and
93 // - either background texture is no specified or it is drawn in Aspect_FM_CENTERED mode
94 if (myBgGradientArray->IsDefined()
95 && (!myTextureParams->Aspect()->ToMapTexture()
96 || myBgTextureArray->TextureFillMethod() == Aspect_FM_CENTERED
97 || myBgTextureArray->TextureFillMethod() == Aspect_FM_NONE))
99 #if !defined(GL_ES_VERSION_2_0)
100 GLint aShadingModelOld = GL_SMOOTH;
101 if (aCtx->core11 != NULL
102 && aCtx->caps->ffpEnable)
104 aCtx->core11fwd->glDisable (GL_LIGHTING);
105 aCtx->core11fwd->glGetIntegerv (GL_SHADE_MODEL, &aShadingModelOld);
106 aCtx->core11->glShadeModel (GL_SMOOTH);
110 myBgGradientArray->Render (theWorkspace);
112 #if !defined(GL_ES_VERSION_2_0)
113 if (aCtx->core11 != NULL
114 && aCtx->caps->ffpEnable)
116 aCtx->core11->glShadeModel (aShadingModelOld);
121 // Drawing background image if it is defined
122 // (texture is defined and fill type is not Aspect_FM_NONE)
123 if (myBgTextureArray->IsDefined()
124 && myTextureParams->Aspect()->ToMapTexture())
126 aCtx->core11fwd->glDisable (GL_BLEND);
128 const OpenGl_AspectFace* anOldAspectFace = theWorkspace->SetAspectFace (myTextureParams);
129 myBgTextureArray->Render (theWorkspace);
130 theWorkspace->SetAspectFace (anOldAspectFace);
135 theWorkspace->SetUseZBuffer (Standard_True);
136 aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
140 //=======================================================================
143 //=======================================================================
144 void OpenGl_View::Redraw()
146 const Standard_Boolean wasDisabledMSAA = myToDisableMSAA;
147 const Standard_Boolean hadFboBlit = myHasFboBlit;
148 if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
149 && !myCaps->vboDisable
150 && !myCaps->keepArrayData)
152 // caps are shared across all views, thus we need to invalidate all of them
153 // if (myWasRedrawnGL) { myStructureManager->SetDeviceLost(); }
154 myDriver->setDeviceLost();
155 myCaps->keepArrayData = Standard_True;
158 if (!myWorkspace->Activate())
163 myWindow->SetSwapInterval();
166 const Graphic3d_StereoMode aStereoMode = myRenderParams.StereoMode;
167 Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
168 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
169 aCtx->FrameStats()->FrameStart (myWorkspace->View(), false);
171 // release pending GL resources
172 aCtx->ReleaseDelayed();
174 // fetch OpenGl context state
177 OpenGl_FrameBuffer* aFrameBuffer = myFBO.operator->();
178 bool toSwap = aCtx->IsRender()
179 && !aCtx->caps->buffersNoSwap
180 && aFrameBuffer == NULL;
182 Standard_Integer aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWindow->Width();
183 Standard_Integer aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myWindow->Height();
184 Standard_Integer aRendSizeX = Standard_Integer(myRenderParams.RenderResolutionScale * aSizeX + 0.5f);
185 Standard_Integer aRendSizeY = Standard_Integer(myRenderParams.RenderResolutionScale * aSizeY + 0.5f);
187 // determine multisampling parameters
188 Standard_Integer aNbSamples = !myToDisableMSAA && aSizeX == aRendSizeX
189 ? Max (Min (myRenderParams.NbMsaaSamples, aCtx->MaxMsaaSamples()), 0)
193 aNbSamples = OpenGl_Context::GetPowerOfTwo (aNbSamples, aCtx->MaxMsaaSamples());
196 bool toUseOit = myRenderParams.TransparencyMethod == Graphic3d_RTM_BLEND_OIT
197 && checkOitCompatibility (aCtx, aNbSamples > 0);
199 const bool toInitImmediateFbo = myTransientDrawToFront
200 && (!aCtx->caps->useSystemBuffer || (toUseOit && HasImmediateStructures()));
202 if ( aFrameBuffer == NULL
203 && !aCtx->DefaultFrameBuffer().IsNull()
204 && aCtx->DefaultFrameBuffer()->IsValid())
206 aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
210 && (myTransientDrawToFront
211 || aProjectType == Graphic3d_Camera::Projection_Stereo
214 || aSizeX != aRendSizeX))
216 if (myMainSceneFbos[0]->GetVPSizeX() != aRendSizeX
217 || myMainSceneFbos[0]->GetVPSizeY() != aRendSizeY
218 || myMainSceneFbos[0]->NbSamples() != aNbSamples)
220 if (!myTransientDrawToFront)
222 myImmediateSceneFbos[0]->Release (aCtx.operator->());
223 myImmediateSceneFbos[1]->Release (aCtx.operator->());
224 myImmediateSceneFbos[0]->ChangeViewport (0, 0);
225 myImmediateSceneFbos[1]->ChangeViewport (0, 0);
228 // prepare FBOs containing main scene
229 // for further blitting and rendering immediate presentations on top
230 if (aCtx->core20fwd != NULL)
232 const bool wasFailedMain0 = checkWasFailedFbo (myMainSceneFbos[0], aRendSizeX, aRendSizeY, aNbSamples);
233 if (!myMainSceneFbos[0]->Init (aCtx, aRendSizeX, aRendSizeY, myFboColorFormat, myFboDepthFormat, aNbSamples)
236 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO "
237 + printFboFormat (myMainSceneFbos[0]) + " initialization has failed";
238 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
242 if (myMainSceneFbos[0]->IsValid() && (toInitImmediateFbo || myImmediateSceneFbos[0]->IsValid()))
244 const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
245 if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
248 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO "
249 + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
250 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
256 myMainSceneFbos [0]->Release (aCtx.operator->());
257 myMainSceneFbos [1]->Release (aCtx.operator->());
258 myImmediateSceneFbos[0]->Release (aCtx.operator->());
259 myImmediateSceneFbos[1]->Release (aCtx.operator->());
260 myMainSceneFbos [0]->ChangeViewport (0, 0);
261 myMainSceneFbos [1]->ChangeViewport (0, 0);
262 myImmediateSceneFbos[0]->ChangeViewport (0, 0);
263 myImmediateSceneFbos[1]->ChangeViewport (0, 0);
266 if (aProjectType == Graphic3d_Camera::Projection_Stereo
267 && myMainSceneFbos[0]->IsValid())
269 const bool wasFailedMain1 = checkWasFailedFbo (myMainSceneFbos[1], myMainSceneFbos[0]);
270 if (!myMainSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
273 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO (second) "
274 + printFboFormat (myMainSceneFbos[1]) + " initialization has failed";
275 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
277 if (!myMainSceneFbos[1]->IsValid())
280 aProjectType = Graphic3d_Camera::Projection_Perspective;
282 else if (!myTransientDrawToFront)
286 else if (!aCtx->HasStereoBuffers() || aStereoMode != Graphic3d_StereoMode_QuadBuffer)
288 const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
289 const bool wasFailedImm1 = checkWasFailedFbo (myImmediateSceneFbos[1], myMainSceneFbos[0]);
290 if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
293 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
294 + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
295 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
297 if (!myImmediateSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
300 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
301 + printFboFormat (myImmediateSceneFbos[1]) + " initialization has failed";
302 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
304 if (!myImmediateSceneFbos[0]->IsValid()
305 || !myImmediateSceneFbos[1]->IsValid())
307 aProjectType = Graphic3d_Camera::Projection_Perspective;
312 // create color and coverage accumulation buffers required for OIT algorithm
315 Standard_Integer anFboIt = 0;
316 for (; anFboIt < 2; ++anFboIt)
318 Handle(OpenGl_FrameBuffer)& aMainSceneFbo = myMainSceneFbos [anFboIt];
319 Handle(OpenGl_FrameBuffer)& aMainSceneFboOit = myMainSceneFbosOit [anFboIt];
320 Handle(OpenGl_FrameBuffer)& anImmediateSceneFbo = myImmediateSceneFbos [anFboIt];
321 Handle(OpenGl_FrameBuffer)& anImmediateSceneFboOit = myImmediateSceneFbosOit[anFboIt];
322 if (aMainSceneFbo->IsValid()
323 && (aMainSceneFboOit->GetVPSizeX() != aRendSizeX
324 || aMainSceneFboOit->GetVPSizeY() != aRendSizeY
325 || aMainSceneFboOit->NbSamples() != aNbSamples))
327 Standard_Integer aColorConfig = 0;
328 for (;;) // seemly responding to driver limitation (GL_FRAMEBUFFER_UNSUPPORTED)
330 if (myFboOitColorConfig.IsEmpty())
332 if (!chooseOitColorConfiguration (aCtx, aColorConfig++, myFboOitColorConfig))
337 if (aMainSceneFboOit->Init (aCtx, aRendSizeX, aRendSizeY, myFboOitColorConfig, aMainSceneFbo->DepthStencilTexture(), aNbSamples))
341 myFboOitColorConfig.Clear();
343 if (!aMainSceneFboOit->IsValid())
348 else if (!aMainSceneFbo->IsValid())
350 aMainSceneFboOit->Release (aCtx.operator->());
351 aMainSceneFboOit->ChangeViewport (0, 0);
354 if (anImmediateSceneFbo->IsValid()
355 && (anImmediateSceneFboOit->GetVPSizeX() != aRendSizeX
356 || anImmediateSceneFboOit->GetVPSizeY() != aRendSizeY
357 || anImmediateSceneFboOit->NbSamples() != aNbSamples))
359 if (!anImmediateSceneFboOit->Init (aCtx, aRendSizeX, aRendSizeY, myFboOitColorConfig,
360 anImmediateSceneFbo->DepthStencilTexture(), aNbSamples))
365 else if (!anImmediateSceneFbo->IsValid())
367 anImmediateSceneFboOit->Release (aCtx.operator->());
368 anImmediateSceneFboOit->ChangeViewport (0, 0);
371 if (anFboIt == 0) // only the first OIT framebuffer is mandatory
373 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
374 "Initialization of float texture framebuffer for use with\n"
375 " blended order-independent transparency rendering algorithm has failed.\n"
376 " Blended order-independent transparency will not be available.\n");
379 myToDisableOITMSAA = Standard_True;
383 myToDisableOIT = Standard_True;
388 if (!toUseOit && myMainSceneFbosOit[0]->IsValid())
390 myMainSceneFbosOit [0]->Release (aCtx.operator->());
391 myMainSceneFbosOit [1]->Release (aCtx.operator->());
392 myImmediateSceneFbosOit[0]->Release (aCtx.operator->());
393 myImmediateSceneFbosOit[1]->Release (aCtx.operator->());
394 myMainSceneFbosOit [0]->ChangeViewport (0, 0);
395 myMainSceneFbosOit [1]->ChangeViewport (0, 0);
396 myImmediateSceneFbosOit[0]->ChangeViewport (0, 0);
397 myImmediateSceneFbosOit[1]->ChangeViewport (0, 0);
400 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
402 OpenGl_FrameBuffer* aMainFbos[2] =
404 myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
405 myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
407 OpenGl_FrameBuffer* aMainFbosOit[2] =
409 myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL,
410 myMainSceneFbosOit[1]->IsValid() ? myMainSceneFbosOit[1].operator->() :
411 myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL
414 OpenGl_FrameBuffer* anImmFbos[2] =
416 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
417 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
419 OpenGl_FrameBuffer* anImmFbosOit[2] =
421 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
422 myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
423 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
426 if (!myTransientDrawToFront)
428 anImmFbos [0] = aMainFbos [0];
429 anImmFbos [1] = aMainFbos [1];
430 anImmFbosOit[0] = aMainFbosOit[0];
431 anImmFbosOit[1] = aMainFbosOit[1];
433 else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
434 || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
436 anImmFbos [0] = NULL;
437 anImmFbos [1] = NULL;
438 anImmFbosOit[0] = NULL;
439 anImmFbosOit[1] = NULL;
442 #if !defined(GL_ES_VERSION_2_0)
443 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
445 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
446 aMainFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
448 redraw (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], aMainFbosOit[0]);
449 myBackBufferRestored = Standard_True;
450 myIsImmediateDrawn = Standard_False;
451 #if !defined(GL_ES_VERSION_2_0)
452 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
454 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
455 anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
456 if (!redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], anImmFbos[0], anImmFbosOit[0]))
460 else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip && toSwap)
465 #if !defined(GL_ES_VERSION_2_0)
466 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
468 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
469 aMainFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
471 redraw (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], aMainFbosOit[1]);
472 myBackBufferRestored = Standard_True;
473 myIsImmediateDrawn = Standard_False;
474 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
475 anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
476 if (!redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], anImmFbos[1], anImmFbosOit[1]))
481 if (anImmFbos[0] != NULL)
483 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(), 1.0f);
484 drawStereoPair (aFrameBuffer);
489 OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : aFrameBuffer;
490 OpenGl_FrameBuffer* aMainFboOit = myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL;
491 OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
492 OpenGl_FrameBuffer* anImmFboOit = NULL;
493 if (!myTransientDrawToFront)
496 anImmFboOit = aMainFboOit;
498 else if (myImmediateSceneFbos[0]->IsValid())
500 anImmFbo = myImmediateSceneFbos[0].operator->();
501 anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
504 #if !defined(GL_ES_VERSION_2_0)
505 if (aMainFbo == NULL)
507 aCtx->SetReadDrawBuffer (GL_BACK);
510 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
511 aMainFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
513 redraw (aProjectType, aMainFbo, aMainFboOit);
514 myBackBufferRestored = Standard_True;
515 myIsImmediateDrawn = Standard_False;
516 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
517 anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
518 if (!redrawImmediate (aProjectType, aMainFbo, anImmFbo, anImmFboOit))
524 && anImmFbo != aFrameBuffer)
526 blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
530 if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
531 && myRenderParams.IsGlobalIlluminationEnabled)
539 if (wasDisabledMSAA != myToDisableMSAA
540 || hadFboBlit != myHasFboBlit)
546 // reset state for safety
547 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
548 if (aCtx->caps->ffpEnable)
550 aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
557 if (!myMainSceneFbos[0]->IsValid())
559 myBackBufferRestored = Standard_False;
564 aCtx->core11fwd->glFlush();
567 // reset render mode state
569 aCtx->FrameStats()->FrameEnd (myWorkspace->View(), false);
571 myWasRedrawnGL = Standard_True;
574 // =======================================================================
575 // function : RedrawImmediate
577 // =======================================================================
578 void OpenGl_View::RedrawImmediate()
580 if (!myWorkspace->Activate())
583 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
584 if (!myTransientDrawToFront
585 || !myBackBufferRestored
586 || (aCtx->caps->buffersNoSwap && !myMainSceneFbos[0]->IsValid()))
592 const Graphic3d_StereoMode aStereoMode = myRenderParams.StereoMode;
593 Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
594 OpenGl_FrameBuffer* aFrameBuffer = myFBO.operator->();
595 aCtx->FrameStats()->FrameStart (myWorkspace->View(), true);
597 if ( aFrameBuffer == NULL
598 && !aCtx->DefaultFrameBuffer().IsNull()
599 && aCtx->DefaultFrameBuffer()->IsValid())
601 aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
604 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
606 if (myMainSceneFbos[0]->IsValid()
607 && !myMainSceneFbos[1]->IsValid())
609 aProjectType = Graphic3d_Camera::Projection_Perspective;
614 if (aProjectType == Graphic3d_Camera::Projection_Stereo)
616 OpenGl_FrameBuffer* aMainFbos[2] =
618 myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
619 myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
621 OpenGl_FrameBuffer* anImmFbos[2] =
623 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
624 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
626 OpenGl_FrameBuffer* anImmFbosOit[2] =
628 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
629 myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
630 myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
632 if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
633 || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
637 anImmFbosOit[0] = NULL;
638 anImmFbosOit[1] = NULL;
641 if (aCtx->arbFBO != NULL)
643 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
645 #if !defined(GL_ES_VERSION_2_0)
646 if (anImmFbos[0] == NULL)
648 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
652 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
653 anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
654 toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye,
658 Standard_True) || toSwap;
659 if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
661 && !aCtx->caps->buffersNoSwap)
666 if (aCtx->arbFBO != NULL)
668 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
670 #if !defined(GL_ES_VERSION_2_0)
671 if (anImmFbos[1] == NULL)
673 aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
676 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
677 anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
678 toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye,
682 Standard_True) || toSwap;
683 if (anImmFbos[0] != NULL)
685 drawStereoPair (aFrameBuffer);
690 OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
691 OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
692 OpenGl_FrameBuffer* anImmFboOit = NULL;
693 if (myImmediateSceneFbos[0]->IsValid())
695 anImmFbo = myImmediateSceneFbos[0].operator->();
696 anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
698 #if !defined(GL_ES_VERSION_2_0)
699 if (aMainFbo == NULL)
701 aCtx->SetReadDrawBuffer (GL_BACK);
704 aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
705 anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
706 toSwap = redrawImmediate (aProjectType,
710 Standard_True) || toSwap;
712 && anImmFbo != aFrameBuffer)
714 blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
721 // reset state for safety
722 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
723 if (aCtx->caps->ffpEnable)
725 aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
728 if (toSwap && !aCtx->caps->buffersNoSwap)
734 aCtx->core11fwd->glFlush();
736 aCtx->FrameStats()->FrameEnd (myWorkspace->View(), true);
738 myWasRedrawnGL = Standard_True;
741 // =======================================================================
744 // =======================================================================
745 void OpenGl_View::redraw (const Graphic3d_Camera::Projection theProjection,
746 OpenGl_FrameBuffer* theReadDrawFbo,
747 OpenGl_FrameBuffer* theOitAccumFbo)
749 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
750 if (theReadDrawFbo != NULL)
752 theReadDrawFbo->BindBuffer (aCtx);
753 theReadDrawFbo->SetupViewport (aCtx);
757 const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
758 aCtx->ResizeViewport (aViewport);
761 // request reset of material
762 aCtx->ShaderManager()->UpdateMaterialState();
764 myWorkspace->UseZBuffer() = Standard_True;
765 myWorkspace->UseDepthWrite() = Standard_True;
766 GLbitfield toClear = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT;
767 glDepthFunc (GL_LEQUAL);
768 glDepthMask (GL_TRUE);
769 glEnable (GL_DEPTH_TEST);
771 #if !defined(GL_ES_VERSION_2_0)
774 glClearDepthf (1.0f);
777 const OpenGl_Vec4& aBgColor = myBgColor;
778 glClearColor (aBgColor.r(), aBgColor.g(), aBgColor.b(), 0.0f);
782 render (theProjection, theReadDrawFbo, theOitAccumFbo, Standard_False);
785 // =======================================================================
786 // function : redrawMonoImmediate
788 // =======================================================================
789 bool OpenGl_View::redrawImmediate (const Graphic3d_Camera::Projection theProjection,
790 OpenGl_FrameBuffer* theReadFbo,
791 OpenGl_FrameBuffer* theDrawFbo,
792 OpenGl_FrameBuffer* theOitAccumFbo,
793 const Standard_Boolean theIsPartialUpdate)
795 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
796 GLboolean toCopyBackToFront = GL_FALSE;
797 if (theDrawFbo == theReadFbo
798 && theDrawFbo != NULL)
800 myBackBufferRestored = Standard_False;
802 else if (theReadFbo != NULL
803 && theReadFbo->IsValid()
806 if (!blitBuffers (theReadFbo, theDrawFbo))
811 else if (theDrawFbo == NULL)
813 #if !defined(GL_ES_VERSION_2_0)
814 aCtx->core11fwd->glGetBooleanv (GL_DOUBLEBUFFER, &toCopyBackToFront);
816 if (toCopyBackToFront
817 && myTransientDrawToFront)
819 if (!HasImmediateStructures()
820 && !theIsPartialUpdate)
822 // prefer Swap Buffers within Redraw in compatibility mode (without FBO)
825 if (!copyBackToFront())
827 toCopyBackToFront = GL_FALSE;
828 myBackBufferRestored = Standard_False;
833 myBackBufferRestored = Standard_False;
838 myBackBufferRestored = Standard_False;
840 myIsImmediateDrawn = Standard_True;
842 myWorkspace->UseZBuffer() = Standard_True;
843 myWorkspace->UseDepthWrite() = Standard_True;
844 glDepthFunc (GL_LEQUAL);
845 glDepthMask (GL_TRUE);
846 glEnable (GL_DEPTH_TEST);
847 #if !defined(GL_ES_VERSION_2_0)
850 glClearDepthf (1.0f);
853 render (theProjection, theDrawFbo, theOitAccumFbo, Standard_True);
855 return !toCopyBackToFront;
858 //=======================================================================
861 //=======================================================================
862 void OpenGl_View::render (Graphic3d_Camera::Projection theProjection,
863 OpenGl_FrameBuffer* theOutputFBO,
864 OpenGl_FrameBuffer* theOitAccumFbo,
865 const Standard_Boolean theToDrawImmediate)
867 // ==================================
868 // Step 1: Prepare for render
869 // ==================================
871 const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
872 aContext->SetSampleAlphaToCoverage (myRenderParams.ToEnableAlphaToCoverage);
874 #if !defined(GL_ES_VERSION_2_0)
875 // Disable current clipping planes
876 if (aContext->core11 != NULL)
878 const Standard_Integer aMaxPlanes = aContext->MaxClipPlanes();
879 for (Standard_Integer aClipPlaneId = GL_CLIP_PLANE0; aClipPlaneId < GL_CLIP_PLANE0 + aMaxPlanes; ++aClipPlaneId)
881 aContext->core11fwd->glDisable (aClipPlaneId);
886 // update states of OpenGl_BVHTreeSelector (frustum culling algorithm);
887 // note that we pass here window dimensions ignoring Graphic3d_RenderingParams::RenderResolutionScale
888 myBVHSelector.SetViewVolume (myCamera);
889 myBVHSelector.SetViewportSize (myWindow->Width(), myWindow->Height(), myRenderParams.ResolutionRatio());
890 myBVHSelector.CacheClipPtsProjections();
892 const Handle(OpenGl_ShaderManager)& aManager = aContext->ShaderManager();
893 const Handle(Graphic3d_LightSet)& aLights = myShadingModel == Graphic3d_TOSM_UNLIT ? myNoShadingLight : myLights;
894 Standard_Size aLightsRevision = 0;
895 if (!aLights.IsNull())
897 aLightsRevision = aLights->UpdateRevision();
899 if (StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index()) != myLastLightSourceState
900 || aLightsRevision != myLightsRevision)
902 myLightsRevision = aLightsRevision;
903 aManager->UpdateLightSourceStateTo (aLights);
904 myLastLightSourceState = StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index());
907 // Update matrices if camera has changed.
908 Graphic3d_WorldViewProjState aWVPState = myCamera->WorldViewProjState();
909 if (myWorldViewProjState != aWVPState)
912 myWorldViewProjState = aWVPState;
915 myLocalOrigin.SetCoord (0.0, 0.0, 0.0);
916 aContext->ProjectionState.SetCurrent (myCamera->ProjectionMatrixF());
917 aContext->WorldViewState .SetCurrent (myCamera->OrientationMatrixF());
918 aContext->ApplyProjectionMatrix();
919 aContext->ApplyWorldViewMatrix();
920 if (aManager->ModelWorldState().Index() == 0)
922 aContext->ShaderManager()->UpdateModelWorldStateTo (OpenGl_Mat4());
925 // ====================================
926 // Step 2: Redraw background
927 // ====================================
930 if (!theToDrawImmediate)
932 drawBackground (myWorkspace);
935 #if !defined(GL_ES_VERSION_2_0)
936 // Switch off lighting by default
937 if (aContext->core11 != NULL
938 && aContext->caps->ffpEnable)
940 glDisable(GL_LIGHTING);
944 // =================================
945 // Step 3: Redraw main plane
946 // =================================
948 // Setup face culling
949 GLboolean isCullFace = GL_FALSE;
950 if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
952 isCullFace = glIsEnabled (GL_CULL_FACE);
953 if (myBackfacing == Graphic3d_TOBM_DISABLE)
955 glEnable (GL_CULL_FACE);
956 glCullFace (GL_BACK);
959 glDisable (GL_CULL_FACE);
962 #if !defined(GL_ES_VERSION_2_0)
963 // if the view is scaled normal vectors are scaled to unit
964 // length for correct displaying of shaded objects
965 const gp_Pnt anAxialScale = myCamera->AxialScale();
966 if (anAxialScale.X() != 1.F ||
967 anAxialScale.Y() != 1.F ||
968 anAxialScale.Z() != 1.F)
970 aContext->SetGlNormalizeEnabled (Standard_True);
974 aContext->SetGlNormalizeEnabled (Standard_False);
977 // Apply InteriorShadingMethod
978 if (aContext->core11 != NULL)
980 aContext->core11->glShadeModel (myShadingModel == Graphic3d_TOSM_FACET
981 || myShadingModel == Graphic3d_TOSM_UNLIT ? GL_FLAT : GL_SMOOTH);
985 aManager->SetShadingModel (myShadingModel);
988 if (theProjection == Graphic3d_Camera::Projection_MonoLeftEye)
990 aContext->ProjectionState.SetCurrent (myCamera->ProjectionStereoLeftF());
991 aContext->ApplyProjectionMatrix();
993 else if (theProjection == Graphic3d_Camera::Projection_MonoRightEye)
995 aContext->ProjectionState.SetCurrent (myCamera->ProjectionStereoRightF());
996 aContext->ApplyProjectionMatrix();
999 myWorkspace->SetEnvironmentTexture (myTextureEnv);
1001 renderScene (theProjection, theOutputFBO, theOitAccumFbo, theToDrawImmediate);
1003 myWorkspace->SetEnvironmentTexture (Handle(OpenGl_TextureSet)());
1005 // ===============================
1006 // Step 4: Trihedron
1007 // ===============================
1009 // Resetting GL parameters according to the default aspects
1010 // in order to synchronize GL state with the graphic driver state
1011 // before drawing auxiliary stuff (trihedrons, overlayer)
1012 myWorkspace->ResetAppliedAspect();
1015 if (!theToDrawImmediate)
1017 renderTrihedron (myWorkspace);
1019 // Restore face culling
1020 if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
1024 glEnable (GL_CULL_FACE);
1025 glCullFace (GL_BACK);
1028 glDisable (GL_CULL_FACE);
1036 myWorkspace->ResetAppliedAspect();
1037 aContext->SetSampleAlphaToCoverage (false);
1039 // reset FFP state for safety
1040 aContext->BindProgram (Handle(OpenGl_ShaderProgram)());
1041 if (aContext->caps->ffpEnable)
1043 aContext->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1046 // ==============================================================
1047 // Step 6: Keep shader manager informed about last View
1048 // ==============================================================
1050 if (!aManager.IsNull())
1052 aManager->SetLastView (this);
1056 // =======================================================================
1057 // function : InvalidateBVHData
1059 // =======================================================================
1060 void OpenGl_View::InvalidateBVHData (const Graphic3d_ZLayerId theLayerId)
1062 myZLayers.InvalidateBVHData (theLayerId);
1065 //=======================================================================
1066 //function : renderStructs
1068 //=======================================================================
1069 void OpenGl_View::renderStructs (Graphic3d_Camera::Projection theProjection,
1070 OpenGl_FrameBuffer* theReadDrawFbo,
1071 OpenGl_FrameBuffer* theOitAccumFbo,
1072 const Standard_Boolean theToDrawImmediate)
1074 myZLayers.UpdateCulling (myWorkspace, theToDrawImmediate);
1075 if ( myZLayers.NbStructures() <= 0 )
1078 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1079 Standard_Boolean toRenderGL = theToDrawImmediate ||
1080 myRenderParams.Method != Graphic3d_RM_RAYTRACING ||
1081 myRaytraceInitStatus == OpenGl_RT_FAIL ||
1086 toRenderGL = !initRaytraceResources (aCtx) ||
1087 !updateRaytraceGeometry (OpenGl_GUM_CHECK, myId, aCtx);
1089 toRenderGL |= !myIsRaytraceDataValid; // if no ray-trace data use OpenGL
1093 const Standard_Integer aSizeX = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeX() : myWindow->Width();
1094 const Standard_Integer aSizeY = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeY() : myWindow->Height();
1095 myOpenGlFBO ->InitLazy (aCtx, aSizeX, aSizeY, myFboColorFormat, myFboDepthFormat, 0);
1097 if (theReadDrawFbo != NULL)
1098 theReadDrawFbo->UnbindBuffer (aCtx);
1100 // Prepare preliminary OpenGL output
1101 if (aCtx->arbFBOBlit != NULL)
1103 // Render bottom OSD layer
1104 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Bottom, theReadDrawFbo, theOitAccumFbo);
1106 const Standard_Integer aPrevFilter = myWorkspace->RenderFilter() & ~(Standard_Integer )(OpenGl_RenderFilter_NonRaytraceableOnly);
1107 myWorkspace->SetRenderFilter (aPrevFilter | OpenGl_RenderFilter_NonRaytraceableOnly);
1109 if (theReadDrawFbo != NULL)
1111 theReadDrawFbo->BindDrawBuffer (aCtx);
1115 aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, 0);
1118 // Render non-polygonal elements in default layer
1119 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Default, theReadDrawFbo, theOitAccumFbo);
1121 myWorkspace->SetRenderFilter (aPrevFilter);
1124 if (theReadDrawFbo != NULL)
1126 theReadDrawFbo->BindBuffer (aCtx);
1130 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, 0);
1133 // Reset OpenGl aspects state to default to avoid enabling of
1134 // backface culling which is not supported in ray-tracing.
1135 myWorkspace->ResetAppliedAspect();
1137 // Ray-tracing polygonal primitive arrays
1138 raytrace (aSizeX, aSizeY, theProjection, theReadDrawFbo, aCtx);
1140 // Render upper (top and topmost) OpenGL layers
1141 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Upper, theReadDrawFbo, theOitAccumFbo);
1145 // Redraw 3D scene using OpenGL in standard
1146 // mode or in case of ray-tracing failure
1149 myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_All, theReadDrawFbo, theOitAccumFbo);
1151 // Set flag that scene was redrawn by standard pipeline
1152 myWasRedrawnGL = Standard_True;
1156 //=======================================================================
1157 //function : renderTrihedron
1159 //=======================================================================
1160 void OpenGl_View::renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace)
1162 if (myToShowGradTrihedron)
1164 myGraduatedTrihedron.Render (theWorkspace);
1168 //=======================================================================
1169 //function : renderFrameStats
1171 //=======================================================================
1172 void OpenGl_View::renderFrameStats()
1174 if (myRenderParams.ToShowStats
1175 && myRenderParams.CollectedStats != Graphic3d_RenderingParams::PerfCounters_NONE)
1177 myFrameStatsPrs.Update (myWorkspace);
1178 myFrameStatsPrs.Render (myWorkspace);
1182 // =======================================================================
1183 // function : Invalidate
1185 // =======================================================================
1186 void OpenGl_View::Invalidate()
1188 myBackBufferRestored = Standard_False;
1191 //=======================================================================
1192 //function : renderScene
1194 //=======================================================================
1195 void OpenGl_View::renderScene (Graphic3d_Camera::Projection theProjection,
1196 OpenGl_FrameBuffer* theReadDrawFbo,
1197 OpenGl_FrameBuffer* theOitAccumFbo,
1198 const Standard_Boolean theToDrawImmediate)
1200 const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
1202 // Specify clipping planes in view transformation space
1203 aContext->ChangeClipping().Reset (myClipPlanes);
1204 if (!myClipPlanes.IsNull()
1205 && !myClipPlanes->IsEmpty())
1207 aContext->ShaderManager()->UpdateClippingState();
1210 renderStructs (theProjection, theReadDrawFbo, theOitAccumFbo, theToDrawImmediate);
1211 aContext->BindTextures (Handle(OpenGl_TextureSet)());
1213 // Apply restored view matrix.
1214 aContext->ApplyWorldViewMatrix();
1216 aContext->ChangeClipping().Reset (Handle(Graphic3d_SequenceOfHClipPlane)());
1217 if (!myClipPlanes.IsNull()
1218 && !myClipPlanes->IsEmpty())
1220 aContext->ShaderManager()->RevertClippingState();
1224 // =======================================================================
1225 // function : bindDefaultFbo
1227 // =======================================================================
1228 void OpenGl_View::bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo)
1230 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1231 OpenGl_FrameBuffer* anFbo = (theCustomFbo != NULL && theCustomFbo->IsValid())
1233 : (!aCtx->DefaultFrameBuffer().IsNull()
1234 && aCtx->DefaultFrameBuffer()->IsValid()
1235 ? aCtx->DefaultFrameBuffer().operator->()
1239 anFbo->BindBuffer (aCtx);
1240 anFbo->SetupViewport (aCtx);
1244 #if !defined(GL_ES_VERSION_2_0)
1245 aCtx->SetReadDrawBuffer (GL_BACK);
1247 if (aCtx->arbFBO != NULL)
1249 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1252 const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
1253 aCtx->ResizeViewport (aViewport);
1257 // =======================================================================
1258 // function : initBlitQuad
1260 // =======================================================================
1261 OpenGl_VertexBuffer* OpenGl_View::initBlitQuad (const Standard_Boolean theToFlip)
1263 OpenGl_VertexBuffer* aVerts = NULL;
1266 aVerts = &myFullScreenQuad;
1267 if (!aVerts->IsValid())
1269 OpenGl_Vec4 aQuad[4] =
1271 OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
1272 OpenGl_Vec4( 1.0f, 1.0f, 1.0f, 1.0f),
1273 OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
1274 OpenGl_Vec4(-1.0f, 1.0f, 0.0f, 1.0f)
1276 aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1281 aVerts = &myFullScreenQuadFlip;
1282 if (!aVerts->IsValid())
1284 OpenGl_Vec4 aQuad[4] =
1286 OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 1.0f),
1287 OpenGl_Vec4( 1.0f, 1.0f, 1.0f, 0.0f),
1288 OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 1.0f),
1289 OpenGl_Vec4(-1.0f, 1.0f, 0.0f, 0.0f)
1291 aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1297 // =======================================================================
1298 // function : blitBuffers
1300 // =======================================================================
1301 bool OpenGl_View::blitBuffers (OpenGl_FrameBuffer* theReadFbo,
1302 OpenGl_FrameBuffer* theDrawFbo,
1303 const Standard_Boolean theToFlip)
1305 Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1306 const Standard_Integer aReadSizeX = theReadFbo != NULL ? theReadFbo->GetVPSizeX() : myWindow->Width();
1307 const Standard_Integer aReadSizeY = theReadFbo != NULL ? theReadFbo->GetVPSizeY() : myWindow->Height();
1308 const Standard_Integer aDrawSizeX = theDrawFbo != NULL ? theDrawFbo->GetVPSizeX() : myWindow->Width();
1309 const Standard_Integer aDrawSizeY = theDrawFbo != NULL ? theDrawFbo->GetVPSizeY() : myWindow->Height();
1310 if (theReadFbo == NULL || aCtx->IsFeedback())
1314 else if (theReadFbo == theDrawFbo)
1319 // clear destination before blitting
1320 if (theDrawFbo != NULL
1321 && theDrawFbo->IsValid())
1323 theDrawFbo->BindBuffer (aCtx);
1327 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1329 const Standard_Integer aViewport[4] = { 0, 0, aDrawSizeX, aDrawSizeY };
1330 aCtx->ResizeViewport (aViewport);
1332 #if !defined(GL_ES_VERSION_2_0)
1333 aCtx->core20fwd->glClearDepth (1.0);
1335 aCtx->core20fwd->glClearDepthf (1.0f);
1337 aCtx->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1339 if (aCtx->arbFBOBlit != NULL
1340 && theReadFbo->NbSamples() != 0)
1342 GLbitfield aCopyMask = 0;
1343 theReadFbo->BindReadBuffer (aCtx);
1344 if (theDrawFbo != NULL
1345 && theDrawFbo->IsValid())
1347 theDrawFbo->BindDrawBuffer (aCtx);
1348 if (theDrawFbo->HasColor()
1349 && theReadFbo->HasColor())
1351 aCopyMask |= GL_COLOR_BUFFER_BIT;
1353 if (theDrawFbo->HasDepth()
1354 && theReadFbo->HasDepth())
1356 aCopyMask |= GL_DEPTH_BUFFER_BIT;
1361 if (theReadFbo->HasColor())
1363 aCopyMask |= GL_COLOR_BUFFER_BIT;
1365 if (theReadFbo->HasDepth())
1367 aCopyMask |= GL_DEPTH_BUFFER_BIT;
1369 aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1372 // we don't copy stencil buffer here... does it matter for performance?
1373 aCtx->arbFBOBlit->glBlitFramebuffer (0, 0, aReadSizeX, aReadSizeY,
1374 0, 0, aDrawSizeX, aDrawSizeY,
1375 aCopyMask, GL_NEAREST);
1376 const int anErr = ::glGetError();
1377 if (anErr != GL_NO_ERROR)
1379 // glBlitFramebuffer() might fail in several cases:
1380 // - Both FBOs have MSAA and they are samples number does not match.
1381 // OCCT checks that this does not happen,
1382 // however some graphics drivers provide an option for overriding MSAA.
1383 // In this case window MSAA might be non-zero (and application can not check it)
1384 // and might not match MSAA of our offscreen FBOs.
1385 // - Pixel formats of FBOs do not match.
1386 // This also might happen with window has pixel format,
1387 // e.g. Mesa fails blitting RGBA8 -> RGB8 while other drivers support this conversion.
1388 TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "FBO blitting has failed [Error #" + anErr + "]\n"
1389 + " Please check your graphics driver settings or try updating driver.";
1390 if (theReadFbo->NbSamples() != 0)
1392 myToDisableMSAA = true;
1393 aMsg += "\n MSAA settings should not be overridden by driver!";
1395 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1396 GL_DEBUG_TYPE_ERROR,
1398 GL_DEBUG_SEVERITY_HIGH,
1402 if (theDrawFbo != NULL
1403 && theDrawFbo->IsValid())
1405 theDrawFbo->BindBuffer (aCtx);
1409 aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1414 aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1415 aCtx->core20fwd->glDepthMask (GL_TRUE);
1416 aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1417 #if defined(GL_ES_VERSION_2_0)
1418 if (!aCtx->IsGlGreaterEqual (3, 0)
1419 && !aCtx->extFragDepth)
1421 aCtx->core20fwd->glDisable (GL_DEPTH_TEST);
1425 aCtx->BindTextures (Handle(OpenGl_TextureSet)());
1427 const Graphic3d_TypeOfTextureFilter aFilter = (aDrawSizeX == aReadSizeX && aDrawSizeY == aReadSizeY) ? Graphic3d_TOTF_NEAREST : Graphic3d_TOTF_BILINEAR;
1428 const GLint aFilterGl = aFilter == Graphic3d_TOTF_NEAREST ? GL_NEAREST : GL_LINEAR;
1430 OpenGl_VertexBuffer* aVerts = initBlitQuad (theToFlip);
1431 const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1432 if (aVerts->IsValid()
1433 && aManager->BindFboBlitProgram())
1435 theReadFbo->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_0);
1436 if (theReadFbo->ColorTexture()->Sampler()->Parameters()->Filter() != aFilter)
1438 theReadFbo->ColorTexture()->Sampler()->Parameters()->SetFilter (aFilter);
1439 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
1440 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
1443 theReadFbo->DepthStencilTexture()->Bind (aCtx, Graphic3d_TextureUnit_1);
1444 if (theReadFbo->DepthStencilTexture()->Sampler()->Parameters()->Filter() != aFilter)
1446 theReadFbo->DepthStencilTexture()->Sampler()->Parameters()->SetFilter (aFilter);
1447 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
1448 aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
1451 aVerts->BindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1453 aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1455 aVerts->UnbindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1456 theReadFbo->DepthStencilTexture()->Unbind (aCtx, Graphic3d_TextureUnit_1);
1457 theReadFbo->ColorTexture() ->Unbind (aCtx, Graphic3d_TextureUnit_0);
1458 aCtx->BindProgram (NULL);
1462 TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1463 + "Error! FBO blitting has failed";
1464 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1465 GL_DEBUG_TYPE_ERROR,
1467 GL_DEBUG_SEVERITY_HIGH,
1469 myHasFboBlit = Standard_False;
1470 theReadFbo->Release (aCtx.operator->());
1477 // =======================================================================
1478 // function : drawStereoPair
1480 // =======================================================================
1481 void OpenGl_View::drawStereoPair (OpenGl_FrameBuffer* theDrawFbo)
1483 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1484 bindDefaultFbo (theDrawFbo);
1485 OpenGl_FrameBuffer* aPair[2] =
1487 myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
1488 myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
1490 if (aPair[0] == NULL
1492 || !myTransientDrawToFront)
1494 aPair[0] = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
1495 aPair[1] = myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL;
1498 if (aPair[0] == NULL
1499 || aPair[1] == NULL)
1504 if (aPair[0]->NbSamples() != 0)
1506 // resolve MSAA buffers before drawing
1507 if (!myOpenGlFBO ->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, myFboDepthFormat, 0)
1508 || !myOpenGlFBO2->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, 0, 0))
1510 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1511 GL_DEBUG_TYPE_ERROR,
1513 GL_DEBUG_SEVERITY_HIGH,
1514 "Error! Unable to allocate FBO for blitting stereo pair");
1515 bindDefaultFbo (theDrawFbo);
1519 if (!blitBuffers (aPair[0], myOpenGlFBO .operator->(), Standard_False)
1520 || !blitBuffers (aPair[1], myOpenGlFBO2.operator->(), Standard_False))
1522 bindDefaultFbo (theDrawFbo);
1526 aPair[0] = myOpenGlFBO .operator->();
1527 aPair[1] = myOpenGlFBO2.operator->();
1528 bindDefaultFbo (theDrawFbo);
1533 Standard_Integer left;
1534 Standard_Integer top;
1535 Standard_Integer right;
1536 Standard_Integer bottom;
1537 Standard_Integer dx() { return right - left; }
1538 Standard_Integer dy() { return bottom - top; }
1541 myWindow->PlatformWindow()->Position (aGeom.left, aGeom.top, aGeom.right, aGeom.bottom);
1543 Standard_Boolean toReverse = myRenderParams.ToReverseStereo;
1544 const Standard_Boolean isOddY = (aGeom.top + aGeom.dy()) % 2 == 1;
1545 const Standard_Boolean isOddX = aGeom.left % 2 == 1;
1547 && (myRenderParams.StereoMode == Graphic3d_StereoMode_RowInterlaced
1548 || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1550 toReverse = !toReverse;
1553 && (myRenderParams.StereoMode == Graphic3d_StereoMode_ColumnInterlaced
1554 || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1556 toReverse = !toReverse;
1561 std::swap (aPair[0], aPair[1]);
1564 aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1565 aCtx->core20fwd->glDepthMask (GL_TRUE);
1566 aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1568 aCtx->BindTextures (Handle(OpenGl_TextureSet)());
1569 OpenGl_VertexBuffer* aVerts = initBlitQuad (myToFlipOutput);
1571 const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1572 if (aVerts->IsValid()
1573 && aManager->BindStereoProgram (myRenderParams.StereoMode))
1575 if (myRenderParams.StereoMode == Graphic3d_StereoMode_Anaglyph)
1577 OpenGl_Mat4 aFilterL, aFilterR;
1578 aFilterL.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1579 aFilterR.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1580 switch (myRenderParams.AnaglyphFilter)
1582 case Graphic3d_RenderingParams::Anaglyph_RedCyan_Simple:
1584 aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1585 aFilterR.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1586 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1589 case Graphic3d_RenderingParams::Anaglyph_RedCyan_Optimized:
1591 aFilterL.SetRow (0, Graphic3d_Vec4 ( 0.4154f, 0.4710f, 0.16666667f, 0.0f));
1592 aFilterL.SetRow (1, Graphic3d_Vec4 (-0.0458f, -0.0484f, -0.0257f, 0.0f));
1593 aFilterL.SetRow (2, Graphic3d_Vec4 (-0.0547f, -0.0615f, 0.0128f, 0.0f));
1594 aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1595 aFilterR.SetRow (0, Graphic3d_Vec4 (-0.01090909f, -0.03636364f, -0.00606061f, 0.0f));
1596 aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.37560000f, 0.73333333f, 0.01111111f, 0.0f));
1597 aFilterR.SetRow (2, Graphic3d_Vec4 (-0.06510000f, -0.12870000f, 1.29710000f, 0.0f));
1598 aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1601 case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Simple:
1603 aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1604 aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1605 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1608 case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Optimized:
1610 aFilterL.SetRow (0, Graphic3d_Vec4 ( 1.062f, -0.205f, 0.299f, 0.0f));
1611 aFilterL.SetRow (1, Graphic3d_Vec4 (-0.026f, 0.908f, 0.068f, 0.0f));
1612 aFilterL.SetRow (2, Graphic3d_Vec4 (-0.038f, -0.173f, 0.022f, 0.0f));
1613 aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1614 aFilterR.SetRow (0, Graphic3d_Vec4 (-0.016f, -0.123f, -0.017f, 0.0f));
1615 aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.006f, 0.062f, -0.017f, 0.0f));
1616 aFilterR.SetRow (2, Graphic3d_Vec4 ( 0.094f, 0.185f, 0.911f, 0.0f));
1617 aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f, 0.0f, 0.0f, 0.0f));
1620 case Graphic3d_RenderingParams::Anaglyph_GreenMagenta_Simple:
1622 aFilterR.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1623 aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1624 aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1627 case Graphic3d_RenderingParams::Anaglyph_UserDefined:
1629 aFilterL = myRenderParams.AnaglyphLeft;
1630 aFilterR = myRenderParams.AnaglyphRight;
1634 aCtx->ActiveProgram()->SetUniform (aCtx, "uMultL", aFilterL);
1635 aCtx->ActiveProgram()->SetUniform (aCtx, "uMultR", aFilterR);
1638 aPair[0]->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_0);
1639 aPair[1]->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_1);
1640 aVerts->BindVertexAttrib (aCtx, 0);
1642 aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1644 aVerts->UnbindVertexAttrib (aCtx, 0);
1645 aPair[1]->ColorTexture()->Unbind (aCtx, Graphic3d_TextureUnit_1);
1646 aPair[0]->ColorTexture()->Unbind (aCtx, Graphic3d_TextureUnit_0);
1650 TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1651 + "Error! Anaglyph has failed";
1652 aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1653 GL_DEBUG_TYPE_ERROR,
1655 GL_DEBUG_SEVERITY_HIGH,
1660 // =======================================================================
1661 // function : copyBackToFront
1663 // =======================================================================
1664 bool OpenGl_View::copyBackToFront()
1666 myIsImmediateDrawn = Standard_False;
1667 #if !defined(GL_ES_VERSION_2_0)
1668 const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1669 if (aCtx->core11 == NULL)
1674 OpenGl_Mat4 aProjectMat;
1675 Graphic3d_TransformUtils::Ortho2D (aProjectMat,
1676 0.0f, static_cast<GLfloat> (myWindow->Width()),
1677 0.0f, static_cast<GLfloat> (myWindow->Height()));
1679 aCtx->WorldViewState.Push();
1680 aCtx->ProjectionState.Push();
1682 aCtx->WorldViewState.SetIdentity();
1683 aCtx->ProjectionState.SetCurrent (aProjectMat);
1685 aCtx->ApplyProjectionMatrix();
1686 aCtx->ApplyWorldViewMatrix();
1688 // synchronize FFP state before copying pixels
1689 aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
1690 aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1691 aCtx->DisableFeatures();
1693 switch (aCtx->DrawBuffer())
1697 aCtx->SetReadBuffer (GL_BACK_LEFT);
1698 aCtx->SetDrawBuffer (GL_FRONT_LEFT);
1703 aCtx->SetReadBuffer (GL_BACK_RIGHT);
1704 aCtx->SetDrawBuffer (GL_FRONT_RIGHT);
1709 aCtx->SetReadBuffer (GL_BACK);
1710 aCtx->SetDrawBuffer (GL_FRONT);
1715 aCtx->core11->glRasterPos2i (0, 0);
1716 aCtx->core11->glCopyPixels (0, 0, myWindow->Width() + 1, myWindow->Height() + 1, GL_COLOR);
1717 //aCtx->core11->glCopyPixels (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
1719 aCtx->EnableFeatures();
1721 aCtx->WorldViewState.Pop();
1722 aCtx->ProjectionState.Pop();
1723 aCtx->ApplyProjectionMatrix();
1725 // read/write from front buffer now
1726 aCtx->SetReadBuffer (aCtx->DrawBuffer());
1733 // =======================================================================
1734 // function : checkOitCompatibility
1736 // =======================================================================
1737 Standard_Boolean OpenGl_View::checkOitCompatibility (const Handle(OpenGl_Context)& theGlContext,
1738 const Standard_Boolean theMSAA)
1740 // determine if OIT is supported by current OpenGl context
1741 Standard_Boolean& aToDisableOIT = theMSAA ? myToDisableMSAA : myToDisableOIT;
1744 return Standard_False;
1747 TCollection_ExtendedString aCompatibilityMsg;
1748 if (theGlContext->hasFloatBuffer == OpenGl_FeatureNotAvailable
1749 && theGlContext->hasHalfFloatBuffer == OpenGl_FeatureNotAvailable)
1751 aCompatibilityMsg += "OpenGL context does not support floating-point RGBA color buffer format.\n";
1753 if (theMSAA && theGlContext->hasSampleVariables == OpenGl_FeatureNotAvailable)
1755 aCompatibilityMsg += "Current version of GLSL does not support built-in sample variables.\n";
1757 if (theGlContext->hasDrawBuffers == OpenGl_FeatureNotAvailable)
1759 aCompatibilityMsg += "OpenGL context does not support multiple draw buffers.\n";
1761 if (aCompatibilityMsg.IsEmpty())
1763 return Standard_True;
1766 aCompatibilityMsg += " Blended order-independent transparency will not be available.\n";
1767 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1768 GL_DEBUG_TYPE_ERROR,
1770 GL_DEBUG_SEVERITY_HIGH,
1773 aToDisableOIT = Standard_True;
1774 return Standard_False;
1777 // =======================================================================
1778 // function : chooseOitColorConfiguration
1780 // =======================================================================
1781 bool OpenGl_View::chooseOitColorConfiguration (const Handle(OpenGl_Context)& theGlContext,
1782 const Standard_Integer theConfigIndex,
1783 OpenGl_ColorFormats& theFormats)
1786 switch (theConfigIndex)
1788 case 0: // choose best applicable color format combination
1790 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1791 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_R16F : GL_R32F);
1794 case 1: // choose non-optimal applicable color format combination
1796 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1797 theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1801 return false; // color combination does not exist