| 1 | // Created on: 2015-02-20 |
| 2 | // Created by: Denis BOGOLEPOV |
| 3 | // Copyright (c) 2015 OPEN CASCADE SAS |
| 4 | // |
| 5 | // This file is part of Open CASCADE Technology software library. |
| 6 | // |
| 7 | // This library is free software; you can redistribute it and/or modify it under |
| 8 | // the terms of the GNU Lesser General Public License version 2.1 as published |
| 9 | // by the Free Software Foundation, with special exception defined in the file |
| 10 | // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT |
| 11 | // distribution for complete text of the license and disclaimer of any warranty. |
| 12 | // |
| 13 | // Alternatively, this file may be used under the terms of Open CASCADE |
| 14 | // commercial license or contractual agreement. |
| 15 | |
| 16 | #include <OpenGl_View.hxx> |
| 17 | |
| 18 | #include <Graphic3d_TextureParams.hxx> |
| 19 | #include <OpenGl_PrimitiveArray.hxx> |
| 20 | #include <OpenGl_VertexBuffer.hxx> |
| 21 | #include <OpenGl_GlCore44.hxx> |
| 22 | #include <OSD_Protection.hxx> |
| 23 | #include <OSD_File.hxx> |
| 24 | |
| 25 | using namespace OpenGl_Raytrace; |
| 26 | |
| 27 | //! Use this macro to output ray-tracing debug info |
| 28 | // #define RAY_TRACE_PRINT_INFO |
| 29 | |
| 30 | #ifdef RAY_TRACE_PRINT_INFO |
| 31 | #include <OSD_Timer.hxx> |
| 32 | #endif |
| 33 | |
| 34 | namespace |
| 35 | { |
| 36 | static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f); |
| 37 | static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f); |
| 38 | } |
| 39 | |
| 40 | // ======================================================================= |
| 41 | // function : updateRaytraceGeometry |
| 42 | // purpose : Updates 3D scene geometry for ray-tracing |
| 43 | // ======================================================================= |
| 44 | Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode, |
| 45 | const Standard_Integer theViewId, |
| 46 | const Handle(OpenGl_Context)& theGlContext) |
| 47 | { |
| 48 | // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for |
| 49 | // modifications. This is light-weight procedure performed on each frame |
| 50 | if (theMode == OpenGl_GUM_CHECK) |
| 51 | { |
| 52 | if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable()) |
| 53 | { |
| 54 | return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext); |
| 55 | } |
| 56 | } |
| 57 | else if (theMode == OpenGl_GUM_PREPARE) |
| 58 | { |
| 59 | myRaytraceGeometry.ClearMaterials(); |
| 60 | |
| 61 | myArrayToTrianglesMap.clear(); |
| 62 | |
| 63 | myIsRaytraceDataValid = Standard_False; |
| 64 | } |
| 65 | |
| 66 | // The set of processed structures (reflected to ray-tracing) |
| 67 | // This set is used to remove out-of-date records from the |
| 68 | // hash map of structures |
| 69 | std::set<const OpenGl_Structure*> anElements; |
| 70 | |
| 71 | // Set to store all currently visible OpenGL primitive arrays |
| 72 | // applicable for ray-tracing |
| 73 | std::set<Standard_Size> anArrayIDs; |
| 74 | |
| 75 | // Set to store all non-raytracable elements allowing tracking |
| 76 | // of changes in OpenGL scene (only for path tracing) |
| 77 | std::set<Standard_Integer> aNonRaytraceIDs; |
| 78 | |
| 79 | const OpenGl_Layer& aLayer = myZLayers.Layer (Graphic3d_ZLayerId_Default); |
| 80 | |
| 81 | if (aLayer.NbStructures() != 0) |
| 82 | { |
| 83 | const OpenGl_ArrayOfIndexedMapOfStructure& aStructArray = aLayer.ArrayOfStructures(); |
| 84 | |
| 85 | for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex) |
| 86 | { |
| 87 | for (OpenGl_IndexedMapOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next()) |
| 88 | { |
| 89 | const OpenGl_Structure* aStructure = aStructIt.Value(); |
| 90 | |
| 91 | if (theMode == OpenGl_GUM_CHECK) |
| 92 | { |
| 93 | if (toUpdateStructure (aStructure)) |
| 94 | { |
| 95 | return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext); |
| 96 | } |
| 97 | else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination) |
| 98 | { |
| 99 | aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id); |
| 100 | } |
| 101 | } |
| 102 | else if (theMode == OpenGl_GUM_PREPARE) |
| 103 | { |
| 104 | if (!aStructure->IsRaytracable() || !aStructure->IsVisible()) |
| 105 | { |
| 106 | continue; |
| 107 | } |
| 108 | else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId)) |
| 109 | { |
| 110 | continue; |
| 111 | } |
| 112 | |
| 113 | for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next()) |
| 114 | { |
| 115 | // Extract OpenGL elements from the group (primitives arrays) |
| 116 | for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next) |
| 117 | { |
| 118 | OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem); |
| 119 | |
| 120 | if (aPrimArray != NULL) |
| 121 | { |
| 122 | anArrayIDs.insert (aPrimArray->GetUID()); |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | else if (theMode == OpenGl_GUM_REBUILD) |
| 128 | { |
| 129 | if (!aStructure->IsRaytracable()) |
| 130 | { |
| 131 | continue; |
| 132 | } |
| 133 | else if (addRaytraceStructure (aStructure, theGlContext)) |
| 134 | { |
| 135 | anElements.insert (aStructure); // structure was processed |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | if (theMode == OpenGl_GUM_PREPARE) |
| 143 | { |
| 144 | BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects; |
| 145 | |
| 146 | // Filter out unchanged objects so only their transformations and materials |
| 147 | // will be updated (and newly added objects will be processed from scratch) |
| 148 | for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx) |
| 149 | { |
| 150 | OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> ( |
| 151 | myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->()); |
| 152 | |
| 153 | if (aTriangleSet == NULL) |
| 154 | { |
| 155 | continue; |
| 156 | } |
| 157 | |
| 158 | if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end()) |
| 159 | { |
| 160 | anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx)); |
| 161 | |
| 162 | myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet; |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | myRaytraceGeometry.Objects() = anUnchangedObjects; |
| 167 | |
| 168 | return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext); |
| 169 | } |
| 170 | else if (theMode == OpenGl_GUM_REBUILD) |
| 171 | { |
| 172 | // Actualize the hash map of structures - remove out-of-date records |
| 173 | std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin(); |
| 174 | |
| 175 | while (anIter != myStructureStates.end()) |
| 176 | { |
| 177 | if (anElements.find (anIter->first) == anElements.end()) |
| 178 | { |
| 179 | myStructureStates.erase (anIter++); |
| 180 | } |
| 181 | else |
| 182 | { |
| 183 | ++anIter; |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | // Actualize OpenGL layer list state |
| 188 | myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable(); |
| 189 | |
| 190 | // Rebuild two-level acceleration structure |
| 191 | myRaytraceGeometry.ProcessAcceleration(); |
| 192 | |
| 193 | myRaytraceSceneRadius = 2.f /* scale factor */ * std::max ( |
| 194 | myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(), |
| 195 | myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp()); |
| 196 | |
| 197 | const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size(); |
| 198 | |
| 199 | myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus()); |
| 200 | |
| 201 | return uploadRaytraceData (theGlContext); |
| 202 | } |
| 203 | |
| 204 | if (myRaytraceParameters.GlobalIllumination) |
| 205 | { |
| 206 | Standard_Boolean toRestart = |
| 207 | aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size(); |
| 208 | |
| 209 | for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID) |
| 210 | { |
| 211 | if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end()) |
| 212 | { |
| 213 | toRestart = Standard_True; |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | if (toRestart) |
| 218 | { |
| 219 | myAccumFrames = 0; |
| 220 | } |
| 221 | |
| 222 | myNonRaytraceStructureIDs = aNonRaytraceIDs; |
| 223 | } |
| 224 | |
| 225 | return Standard_True; |
| 226 | } |
| 227 | |
| 228 | // ======================================================================= |
| 229 | // function : toUpdateStructure |
| 230 | // purpose : Checks to see if the structure is modified |
| 231 | // ======================================================================= |
| 232 | Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure) |
| 233 | { |
| 234 | if (!theStructure->IsRaytracable()) |
| 235 | { |
| 236 | if (theStructure->ModificationState() > 0) |
| 237 | { |
| 238 | theStructure->ResetModificationState(); |
| 239 | |
| 240 | return Standard_True; // ray-trace element was removed - need to rebuild |
| 241 | } |
| 242 | |
| 243 | return Standard_False; // did not contain ray-trace elements |
| 244 | } |
| 245 | |
| 246 | std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure); |
| 247 | |
| 248 | if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState()) |
| 249 | { |
| 250 | return Standard_True; |
| 251 | } |
| 252 | else if (theStructure->InstancedStructure() != NULL) |
| 253 | { |
| 254 | return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState(); |
| 255 | } |
| 256 | |
| 257 | return Standard_False; |
| 258 | } |
| 259 | |
| 260 | // ======================================================================= |
| 261 | // function : buildTextureTransform |
| 262 | // purpose : Constructs texture transformation matrix |
| 263 | // ======================================================================= |
| 264 | void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix) |
| 265 | { |
| 266 | theMatrix.InitIdentity(); |
| 267 | |
| 268 | // Apply scaling |
| 269 | const Graphic3d_Vec2& aScale = theParams->Scale(); |
| 270 | |
| 271 | theMatrix.ChangeValue (0, 0) *= aScale.x(); |
| 272 | theMatrix.ChangeValue (1, 0) *= aScale.x(); |
| 273 | theMatrix.ChangeValue (2, 0) *= aScale.x(); |
| 274 | theMatrix.ChangeValue (3, 0) *= aScale.x(); |
| 275 | |
| 276 | theMatrix.ChangeValue (0, 1) *= aScale.y(); |
| 277 | theMatrix.ChangeValue (1, 1) *= aScale.y(); |
| 278 | theMatrix.ChangeValue (2, 1) *= aScale.y(); |
| 279 | theMatrix.ChangeValue (3, 1) *= aScale.y(); |
| 280 | |
| 281 | // Apply translation |
| 282 | const Graphic3d_Vec2 aTrans = -theParams->Translation(); |
| 283 | |
| 284 | theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() + |
| 285 | theMatrix.GetValue (0, 1) * aTrans.y(); |
| 286 | |
| 287 | theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() + |
| 288 | theMatrix.GetValue (1, 1) * aTrans.y(); |
| 289 | |
| 290 | theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() + |
| 291 | theMatrix.GetValue (2, 1) * aTrans.y(); |
| 292 | |
| 293 | // Apply rotation |
| 294 | const Standard_ShortReal aSin = std::sin ( |
| 295 | -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0)); |
| 296 | const Standard_ShortReal aCos = std::cos ( |
| 297 | -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0)); |
| 298 | |
| 299 | BVH_Mat4f aRotationMat; |
| 300 | aRotationMat.SetValue (0, 0, aCos); |
| 301 | aRotationMat.SetValue (1, 1, aCos); |
| 302 | aRotationMat.SetValue (0, 1, -aSin); |
| 303 | aRotationMat.SetValue (1, 0, aSin); |
| 304 | |
| 305 | theMatrix = theMatrix * aRotationMat; |
| 306 | } |
| 307 | |
| 308 | // ======================================================================= |
| 309 | // function : convertMaterial |
| 310 | // purpose : Creates ray-tracing material properties |
| 311 | // ======================================================================= |
| 312 | OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace* theAspect, |
| 313 | const Handle(OpenGl_Context)& theGlContext) |
| 314 | { |
| 315 | OpenGl_RaytraceMaterial theMaterial; |
| 316 | |
| 317 | const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial(); |
| 318 | const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor(); |
| 319 | const float aShine = 128.0f * float(aSrcMat.Shininess()); |
| 320 | const bool isPhysic = aSrcMat.MaterialType (Graphic3d_MATERIAL_PHYSIC) == Standard_True; |
| 321 | |
| 322 | // ambient component |
| 323 | if (aSrcMat.ReflectionMode (Graphic3d_TOR_AMBIENT)) |
| 324 | { |
| 325 | const OpenGl_Vec3& aSrcAmb = isPhysic ? aSrcMat.AmbientColor() : aMatCol; |
| 326 | theMaterial.Ambient = BVH_Vec4f (aSrcAmb * (float )aSrcMat.Ambient(), 1.0f); |
| 327 | } |
| 328 | else |
| 329 | { |
| 330 | theMaterial.Ambient = THE_BLACK_COLOR; |
| 331 | } |
| 332 | |
| 333 | // diffusion component |
| 334 | if (aSrcMat.ReflectionMode (Graphic3d_TOR_DIFFUSE)) |
| 335 | { |
| 336 | const OpenGl_Vec3& aSrcDif = isPhysic ? aSrcMat.DiffuseColor() : aMatCol; |
| 337 | theMaterial.Diffuse = BVH_Vec4f (aSrcDif * (float )aSrcMat.Diffuse(), -1.0f); // -1 is no texture |
| 338 | } |
| 339 | else |
| 340 | { |
| 341 | theMaterial.Diffuse = BVH_Vec4f (THE_BLACK_COLOR.rgb(), -1.0f); |
| 342 | } |
| 343 | |
| 344 | // specular component |
| 345 | if (aSrcMat.ReflectionMode (Graphic3d_TOR_SPECULAR)) |
| 346 | { |
| 347 | const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor(); |
| 348 | const OpenGl_Vec3& aSrcSpe2 = isPhysic ? aSrcSpe : THE_WHITE_COLOR.rgb(); |
| 349 | theMaterial.Specular = BVH_Vec4f (aSrcSpe2 * (float )aSrcMat.Specular(), aShine); |
| 350 | |
| 351 | const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(), |
| 352 | Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(), |
| 353 | theMaterial.Diffuse.z() + theMaterial.Specular.z())); |
| 354 | |
| 355 | const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl; |
| 356 | |
| 357 | // ignore isPhysic here |
| 358 | theMaterial.Reflection = BVH_Vec4f (aSrcSpe * (float )aSrcMat.Specular() * aReflectionScale, 0.0f); |
| 359 | } |
| 360 | else |
| 361 | { |
| 362 | theMaterial.Specular = BVH_Vec4f (THE_BLACK_COLOR.rgb(), aShine); |
| 363 | } |
| 364 | |
| 365 | // emission component |
| 366 | if (aSrcMat.ReflectionMode (Graphic3d_TOR_EMISSION)) |
| 367 | { |
| 368 | const OpenGl_Vec3& aSrcEms = isPhysic ? aSrcMat.EmissiveColor() : aMatCol; |
| 369 | theMaterial.Emission = BVH_Vec4f (aSrcEms * (float )aSrcMat.Emissive(), 1.0f); |
| 370 | } |
| 371 | else |
| 372 | { |
| 373 | theMaterial.Emission = THE_BLACK_COLOR; |
| 374 | } |
| 375 | |
| 376 | const float anIndex = (float )aSrcMat.RefractionIndex(); |
| 377 | theMaterial.Transparency = BVH_Vec4f (1.0f - (float )aSrcMat.Transparency(), |
| 378 | (float )aSrcMat.Transparency(), |
| 379 | anIndex == 0 ? 1.0f : anIndex, |
| 380 | anIndex == 0 ? 1.0f : 1.0f / anIndex); |
| 381 | |
| 382 | // Serialize physically-based material properties |
| 383 | const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF(); |
| 384 | |
| 385 | theMaterial.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f); |
| 386 | theMaterial.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f /* no tex */); |
| 387 | theMaterial.BSDF.Kr = BVH_Vec4f (aBSDF.Kr, 0.f); |
| 388 | theMaterial.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f); |
| 389 | theMaterial.BSDF.Ks = BVH_Vec4f (aBSDF.Ks, aBSDF.Roughness); |
| 390 | |
| 391 | theMaterial.BSDF.Fresnel = aBSDF.Fresnel.Serialize(); |
| 392 | |
| 393 | theMaterial.BSDF.Absorption = BVH_Vec4f (aBSDF.AbsorptionColor, |
| 394 | aBSDF.AbsorptionCoeff); |
| 395 | |
| 396 | // Handle material textures |
| 397 | if (theAspect->Aspect()->ToMapTexture()) |
| 398 | { |
| 399 | if (theGlContext->HasRayTracingTextures()) |
| 400 | { |
| 401 | buildTextureTransform (theAspect->TextureParams(), theMaterial.TextureTransform); |
| 402 | |
| 403 | // write texture ID to diffuse w-component |
| 404 | theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() = |
| 405 | static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (theAspect->TextureRes (theGlContext))); |
| 406 | } |
| 407 | else if (!myIsRaytraceWarnTextures) |
| 408 | { |
| 409 | const TCollection_ExtendedString aWarnMessage = |
| 410 | "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. " |
| 411 | "Please try to update graphics card driver. At the moment textures will be ignored."; |
| 412 | |
| 413 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, |
| 414 | GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage); |
| 415 | |
| 416 | myIsRaytraceWarnTextures = Standard_True; |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | return theMaterial; |
| 421 | } |
| 422 | |
| 423 | // ======================================================================= |
| 424 | // function : addRaytraceStructure |
| 425 | // purpose : Adds OpenGL structure to ray-traced scene geometry |
| 426 | // ======================================================================= |
| 427 | Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure, |
| 428 | const Handle(OpenGl_Context)& theGlContext) |
| 429 | { |
| 430 | if (!theStructure->IsVisible()) |
| 431 | { |
| 432 | myStructureStates[theStructure] = StructState (theStructure); |
| 433 | |
| 434 | return Standard_True; |
| 435 | } |
| 436 | |
| 437 | // Get structure material |
| 438 | OpenGl_RaytraceMaterial aDefaultMaterial; |
| 439 | Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext); |
| 440 | |
| 441 | // Process all connected OpenGL structures |
| 442 | const OpenGl_Structure* anInstanced = theStructure->InstancedStructure(); |
| 443 | |
| 444 | if (anInstanced != NULL && anInstanced->IsRaytracable()) |
| 445 | { |
| 446 | aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext); |
| 447 | } |
| 448 | |
| 449 | myStructureStates[theStructure] = StructState (theStructure); |
| 450 | |
| 451 | return aResult; |
| 452 | } |
| 453 | |
| 454 | // ======================================================================= |
| 455 | // function : addRaytraceGroups |
| 456 | // purpose : Adds OpenGL groups to ray-traced scene geometry |
| 457 | // ======================================================================= |
| 458 | Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure, |
| 459 | const OpenGl_RaytraceMaterial& theStructMat, |
| 460 | const Handle(Geom_Transformation)& theTrsf, |
| 461 | const Handle(OpenGl_Context)& theGlContext) |
| 462 | { |
| 463 | OpenGl_Mat4 aMat4; |
| 464 | for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next()) |
| 465 | { |
| 466 | // Get group material |
| 467 | OpenGl_RaytraceMaterial aGroupMaterial; |
| 468 | if (aGroupIter.Value()->AspectFace() != NULL) |
| 469 | { |
| 470 | aGroupMaterial = convertMaterial ( |
| 471 | aGroupIter.Value()->AspectFace(), theGlContext); |
| 472 | } |
| 473 | |
| 474 | Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size()); |
| 475 | |
| 476 | // Use group material if available, otherwise use structure material |
| 477 | myRaytraceGeometry.Materials.push_back ( |
| 478 | aGroupIter.Value()->AspectFace() != NULL ? aGroupMaterial : theStructMat); |
| 479 | |
| 480 | // Add OpenGL elements from group (extract primitives arrays and aspects) |
| 481 | for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next) |
| 482 | { |
| 483 | OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem); |
| 484 | |
| 485 | if (anAspect != NULL) |
| 486 | { |
| 487 | aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size()); |
| 488 | |
| 489 | OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext); |
| 490 | |
| 491 | myRaytraceGeometry.Materials.push_back (aMaterial); |
| 492 | } |
| 493 | else |
| 494 | { |
| 495 | OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem); |
| 496 | |
| 497 | if (aPrimArray != NULL) |
| 498 | { |
| 499 | std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID()); |
| 500 | |
| 501 | if (aSetIter != myArrayToTrianglesMap.end()) |
| 502 | { |
| 503 | OpenGl_TriangleSet* aSet = aSetIter->second; |
| 504 | |
| 505 | BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>(); |
| 506 | |
| 507 | if (!theTrsf.IsNull()) |
| 508 | { |
| 509 | theTrsf->Trsf().GetMat4 (aMat4); |
| 510 | aTransform->SetTransform (aMat4); |
| 511 | } |
| 512 | |
| 513 | aSet->SetProperties (aTransform); |
| 514 | |
| 515 | if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID) |
| 516 | { |
| 517 | aSet->SetMaterialIndex (aMatID); |
| 518 | } |
| 519 | } |
| 520 | else |
| 521 | { |
| 522 | NCollection_Handle<BVH_Object<Standard_ShortReal, 3> > aSet = |
| 523 | addRaytracePrimitiveArray (aPrimArray, aMatID, 0); |
| 524 | |
| 525 | if (!aSet.IsNull()) |
| 526 | { |
| 527 | BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>; |
| 528 | |
| 529 | if (!theTrsf.IsNull()) |
| 530 | { |
| 531 | theTrsf->Trsf().GetMat4 (aMat4); |
| 532 | aTransform->SetTransform (aMat4); |
| 533 | } |
| 534 | |
| 535 | aSet->SetProperties (aTransform); |
| 536 | |
| 537 | myRaytraceGeometry.Objects().Append (aSet); |
| 538 | } |
| 539 | } |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | return Standard_True; |
| 546 | } |
| 547 | |
| 548 | // ======================================================================= |
| 549 | // function : addRaytracePrimitiveArray |
| 550 | // purpose : Adds OpenGL primitive array to ray-traced scene geometry |
| 551 | // ======================================================================= |
| 552 | OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray, |
| 553 | const Standard_Integer theMaterial, |
| 554 | const OpenGl_Mat4* theTransform) |
| 555 | { |
| 556 | const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds(); |
| 557 | const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices(); |
| 558 | const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes(); |
| 559 | |
| 560 | if (theArray->DrawMode() < GL_TRIANGLES |
| 561 | #ifndef GL_ES_VERSION_2_0 |
| 562 | || theArray->DrawMode() > GL_POLYGON |
| 563 | #else |
| 564 | || theArray->DrawMode() > GL_TRIANGLE_FAN |
| 565 | #endif |
| 566 | || anAttribs.IsNull()) |
| 567 | { |
| 568 | return NULL; |
| 569 | } |
| 570 | |
| 571 | OpenGl_Mat4 aNormalMatrix; |
| 572 | |
| 573 | if (theTransform != NULL) |
| 574 | { |
| 575 | Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix), |
| 576 | "Error: Failed to compute normal transformation matrix", NULL); |
| 577 | |
| 578 | aNormalMatrix.Transpose(); |
| 579 | } |
| 580 | |
| 581 | OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID()); |
| 582 | { |
| 583 | aSet->Vertices.reserve (anAttribs->NbElements); |
| 584 | aSet->Normals.reserve (anAttribs->NbElements); |
| 585 | aSet->TexCrds.reserve (anAttribs->NbElements); |
| 586 | |
| 587 | const size_t aVertFrom = aSet->Vertices.size(); |
| 588 | |
| 589 | for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter) |
| 590 | { |
| 591 | const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter); |
| 592 | const size_t anOffset = anAttribs->AttributeOffset (anAttribIter); |
| 593 | if (anAttrib.Id == Graphic3d_TOA_POS) |
| 594 | { |
| 595 | if (anAttrib.DataType == Graphic3d_TOD_VEC3 |
| 596 | || anAttrib.DataType == Graphic3d_TOD_VEC4) |
| 597 | { |
| 598 | for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter) |
| 599 | { |
| 600 | aSet->Vertices.push_back ( |
| 601 | *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset)); |
| 602 | } |
| 603 | } |
| 604 | else if (anAttrib.DataType == Graphic3d_TOD_VEC2) |
| 605 | { |
| 606 | for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter) |
| 607 | { |
| 608 | const Standard_ShortReal* aCoords = |
| 609 | reinterpret_cast<const Standard_ShortReal*> (anAttribs->value (aVertIter) + anOffset); |
| 610 | |
| 611 | aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], 0.0f)); |
| 612 | } |
| 613 | } |
| 614 | } |
| 615 | else if (anAttrib.Id == Graphic3d_TOA_NORM) |
| 616 | { |
| 617 | if (anAttrib.DataType == Graphic3d_TOD_VEC3 |
| 618 | || anAttrib.DataType == Graphic3d_TOD_VEC4) |
| 619 | { |
| 620 | for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter) |
| 621 | { |
| 622 | aSet->Normals.push_back ( |
| 623 | *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset)); |
| 624 | } |
| 625 | } |
| 626 | } |
| 627 | else if (anAttrib.Id == Graphic3d_TOA_UV) |
| 628 | { |
| 629 | if (anAttrib.DataType == Graphic3d_TOD_VEC2) |
| 630 | { |
| 631 | for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter) |
| 632 | { |
| 633 | aSet->TexCrds.push_back ( |
| 634 | *reinterpret_cast<const Graphic3d_Vec2*> (anAttribs->value (aVertIter) + anOffset)); |
| 635 | } |
| 636 | } |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | if (aSet->Normals.size() != aSet->Vertices.size()) |
| 641 | { |
| 642 | for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter) |
| 643 | { |
| 644 | aSet->Normals.push_back (BVH_Vec3f()); |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | if (aSet->TexCrds.size() != aSet->Vertices.size()) |
| 649 | { |
| 650 | for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter) |
| 651 | { |
| 652 | aSet->TexCrds.push_back (BVH_Vec2f()); |
| 653 | } |
| 654 | } |
| 655 | |
| 656 | if (theTransform != NULL) |
| 657 | { |
| 658 | for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter) |
| 659 | { |
| 660 | BVH_Vec3f& aVertex = aSet->Vertices[aVertIter]; |
| 661 | |
| 662 | BVH_Vec4f aTransVertex = *theTransform * |
| 663 | BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f); |
| 664 | |
| 665 | aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z()); |
| 666 | } |
| 667 | for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter) |
| 668 | { |
| 669 | BVH_Vec3f& aNormal = aSet->Normals[aVertIter]; |
| 670 | |
| 671 | BVH_Vec4f aTransNormal = aNormalMatrix * |
| 672 | BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f); |
| 673 | |
| 674 | aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z()); |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | if (!aBounds.IsNull()) |
| 679 | { |
| 680 | for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound) |
| 681 | { |
| 682 | const Standard_Integer aVertNum = aBounds->Bounds[aBound]; |
| 683 | |
| 684 | if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray)) |
| 685 | { |
| 686 | delete aSet; |
| 687 | return NULL; |
| 688 | } |
| 689 | |
| 690 | aBoundStart += aVertNum; |
| 691 | } |
| 692 | } |
| 693 | else |
| 694 | { |
| 695 | const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements; |
| 696 | |
| 697 | if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray)) |
| 698 | { |
| 699 | delete aSet; |
| 700 | return NULL; |
| 701 | } |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | if (aSet->Size() != 0) |
| 706 | { |
| 707 | aSet->MarkDirty(); |
| 708 | } |
| 709 | |
| 710 | return aSet; |
| 711 | } |
| 712 | |
| 713 | // ======================================================================= |
| 714 | // function : addRaytraceVertexIndices |
| 715 | // purpose : Adds vertex indices to ray-traced scene geometry |
| 716 | // ======================================================================= |
| 717 | Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet, |
| 718 | const Standard_Integer theMatID, |
| 719 | const Standard_Integer theCount, |
| 720 | const Standard_Integer theOffset, |
| 721 | const OpenGl_PrimitiveArray& theArray) |
| 722 | { |
| 723 | switch (theArray.DrawMode()) |
| 724 | { |
| 725 | case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices()); |
| 726 | case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices()); |
| 727 | case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices()); |
| 728 | #if !defined(GL_ES_VERSION_2_0) |
| 729 | case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices()); |
| 730 | case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices()); |
| 731 | case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices()); |
| 732 | #endif |
| 733 | } |
| 734 | |
| 735 | return Standard_False; |
| 736 | } |
| 737 | |
| 738 | // ======================================================================= |
| 739 | // function : addRaytraceTriangleArray |
| 740 | // purpose : Adds OpenGL triangle array to ray-traced scene geometry |
| 741 | // ======================================================================= |
| 742 | Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet, |
| 743 | const Standard_Integer theMatID, |
| 744 | const Standard_Integer theCount, |
| 745 | const Standard_Integer theOffset, |
| 746 | const Handle(Graphic3d_IndexBuffer)& theIndices) |
| 747 | { |
| 748 | if (theCount < 3) |
| 749 | { |
| 750 | return Standard_True; |
| 751 | } |
| 752 | |
| 753 | theSet.Elements.reserve (theSet.Elements.size() + theCount / 3); |
| 754 | |
| 755 | if (!theIndices.IsNull()) |
| 756 | { |
| 757 | for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3) |
| 758 | { |
| 759 | theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0), |
| 760 | theIndices->Index (aVert + 1), |
| 761 | theIndices->Index (aVert + 2), |
| 762 | theMatID)); |
| 763 | } |
| 764 | } |
| 765 | else |
| 766 | { |
| 767 | for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3) |
| 768 | { |
| 769 | theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID)); |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | return Standard_True; |
| 774 | } |
| 775 | |
| 776 | // ======================================================================= |
| 777 | // function : addRaytraceTriangleFanArray |
| 778 | // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry |
| 779 | // ======================================================================= |
| 780 | Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet, |
| 781 | const Standard_Integer theMatID, |
| 782 | const Standard_Integer theCount, |
| 783 | const Standard_Integer theOffset, |
| 784 | const Handle(Graphic3d_IndexBuffer)& theIndices) |
| 785 | { |
| 786 | if (theCount < 3) |
| 787 | { |
| 788 | return Standard_True; |
| 789 | } |
| 790 | |
| 791 | theSet.Elements.reserve (theSet.Elements.size() + theCount - 2); |
| 792 | |
| 793 | if (!theIndices.IsNull()) |
| 794 | { |
| 795 | for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert) |
| 796 | { |
| 797 | theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset), |
| 798 | theIndices->Index (aVert + 1), |
| 799 | theIndices->Index (aVert + 2), |
| 800 | theMatID)); |
| 801 | } |
| 802 | } |
| 803 | else |
| 804 | { |
| 805 | for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert) |
| 806 | { |
| 807 | theSet.Elements.push_back (BVH_Vec4i (theOffset, |
| 808 | aVert + 1, |
| 809 | aVert + 2, |
| 810 | theMatID)); |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | return Standard_True; |
| 815 | } |
| 816 | |
| 817 | // ======================================================================= |
| 818 | // function : addRaytraceTriangleStripArray |
| 819 | // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry |
| 820 | // ======================================================================= |
| 821 | Standard_Boolean OpenGl_View::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) |
| 826 | { |
| 827 | if (theCount < 3) |
| 828 | { |
| 829 | return Standard_True; |
| 830 | } |
| 831 | |
| 832 | theSet.Elements.reserve (theSet.Elements.size() + theCount - 2); |
| 833 | |
| 834 | if (!theIndices.IsNull()) |
| 835 | { |
| 836 | for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2) |
| 837 | { |
| 838 | theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)), |
| 839 | theIndices->Index (aVert + (aCW ? 0 : 1)), |
| 840 | theIndices->Index (aVert + 2), |
| 841 | theMatID)); |
| 842 | } |
| 843 | } |
| 844 | else |
| 845 | { |
| 846 | for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2) |
| 847 | { |
| 848 | theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0), |
| 849 | aVert + (aCW ? 0 : 1), |
| 850 | aVert + 2, |
| 851 | theMatID)); |
| 852 | } |
| 853 | } |
| 854 | |
| 855 | return Standard_True; |
| 856 | } |
| 857 | |
| 858 | // ======================================================================= |
| 859 | // function : addRaytraceQuadrangleArray |
| 860 | // purpose : Adds OpenGL quad array to ray-traced scene geometry |
| 861 | // ======================================================================= |
| 862 | Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet, |
| 863 | const Standard_Integer theMatID, |
| 864 | const Standard_Integer theCount, |
| 865 | const Standard_Integer theOffset, |
| 866 | const Handle(Graphic3d_IndexBuffer)& theIndices) |
| 867 | { |
| 868 | if (theCount < 4) |
| 869 | { |
| 870 | return Standard_True; |
| 871 | } |
| 872 | |
| 873 | theSet.Elements.reserve (theSet.Elements.size() + theCount / 2); |
| 874 | |
| 875 | if (!theIndices.IsNull()) |
| 876 | { |
| 877 | for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4) |
| 878 | { |
| 879 | theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0), |
| 880 | theIndices->Index (aVert + 1), |
| 881 | theIndices->Index (aVert + 2), |
| 882 | theMatID)); |
| 883 | theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0), |
| 884 | theIndices->Index (aVert + 2), |
| 885 | theIndices->Index (aVert + 3), |
| 886 | theMatID)); |
| 887 | } |
| 888 | } |
| 889 | else |
| 890 | { |
| 891 | for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4) |
| 892 | { |
| 893 | theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, |
| 894 | theMatID)); |
| 895 | theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3, |
| 896 | theMatID)); |
| 897 | } |
| 898 | } |
| 899 | |
| 900 | return Standard_True; |
| 901 | } |
| 902 | |
| 903 | // ======================================================================= |
| 904 | // function : addRaytraceQuadrangleStripArray |
| 905 | // purpose : Adds OpenGL quad strip array to ray-traced scene geometry |
| 906 | // ======================================================================= |
| 907 | Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet, |
| 908 | const Standard_Integer theMatID, |
| 909 | const Standard_Integer theCount, |
| 910 | const Standard_Integer theOffset, |
| 911 | const Handle(Graphic3d_IndexBuffer)& theIndices) |
| 912 | { |
| 913 | if (theCount < 4) |
| 914 | { |
| 915 | return Standard_True; |
| 916 | } |
| 917 | |
| 918 | theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6); |
| 919 | |
| 920 | if (!theIndices.IsNull()) |
| 921 | { |
| 922 | for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2) |
| 923 | { |
| 924 | theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0), |
| 925 | theIndices->Index (aVert + 1), |
| 926 | theIndices->Index (aVert + 2), |
| 927 | theMatID)); |
| 928 | |
| 929 | theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1), |
| 930 | theIndices->Index (aVert + 3), |
| 931 | theIndices->Index (aVert + 2), |
| 932 | theMatID)); |
| 933 | } |
| 934 | } |
| 935 | else |
| 936 | { |
| 937 | for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2) |
| 938 | { |
| 939 | theSet.Elements.push_back (BVH_Vec4i (aVert + 0, |
| 940 | aVert + 1, |
| 941 | aVert + 2, |
| 942 | theMatID)); |
| 943 | |
| 944 | theSet.Elements.push_back (BVH_Vec4i (aVert + 1, |
| 945 | aVert + 3, |
| 946 | aVert + 2, |
| 947 | theMatID)); |
| 948 | } |
| 949 | } |
| 950 | |
| 951 | return Standard_True; |
| 952 | } |
| 953 | |
| 954 | // ======================================================================= |
| 955 | // function : addRaytracePolygonArray |
| 956 | // purpose : Adds OpenGL polygon array to ray-traced scene geometry |
| 957 | // ======================================================================= |
| 958 | Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet, |
| 959 | const Standard_Integer theMatID, |
| 960 | const Standard_Integer theCount, |
| 961 | const Standard_Integer theOffset, |
| 962 | const Handle(Graphic3d_IndexBuffer)& theIndices) |
| 963 | { |
| 964 | if (theCount < 3) |
| 965 | { |
| 966 | return Standard_True; |
| 967 | } |
| 968 | |
| 969 | theSet.Elements.reserve (theSet.Elements.size() + theCount - 2); |
| 970 | |
| 971 | if (!theIndices.IsNull()) |
| 972 | { |
| 973 | for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert) |
| 974 | { |
| 975 | theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset), |
| 976 | theIndices->Index (aVert + 1), |
| 977 | theIndices->Index (aVert + 2), |
| 978 | theMatID)); |
| 979 | } |
| 980 | } |
| 981 | else |
| 982 | { |
| 983 | for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert) |
| 984 | { |
| 985 | theSet.Elements.push_back (BVH_Vec4i (theOffset, |
| 986 | aVert + 1, |
| 987 | aVert + 2, |
| 988 | theMatID)); |
| 989 | } |
| 990 | } |
| 991 | |
| 992 | return Standard_True; |
| 993 | } |
| 994 | |
| 995 | const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX; |
| 996 | |
| 997 | // ======================================================================= |
| 998 | // function : Source |
| 999 | // purpose : Returns shader source combined with prefix |
| 1000 | // ======================================================================= |
| 1001 | TCollection_AsciiString OpenGl_View::ShaderSource::Source() const |
| 1002 | { |
| 1003 | const TCollection_AsciiString aVersion = "#version 140"; |
| 1004 | |
| 1005 | if (myPrefix.IsEmpty()) |
| 1006 | { |
| 1007 | return aVersion + "\n" + mySource; |
| 1008 | } |
| 1009 | |
| 1010 | return aVersion + "\n" + myPrefix + "\n" + mySource; |
| 1011 | } |
| 1012 | |
| 1013 | // ======================================================================= |
| 1014 | // function : Load |
| 1015 | // purpose : Loads shader source from specified files |
| 1016 | // ======================================================================= |
| 1017 | Standard_Boolean OpenGl_View::ShaderSource::Load (const TCollection_AsciiString* theFileNames, |
| 1018 | const TCollection_AsciiString& thePrefix) |
| 1019 | { |
| 1020 | myError.Clear(); |
| 1021 | mySource.Clear(); |
| 1022 | TCollection_AsciiString aMissingFiles; |
| 1023 | for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex) |
| 1024 | { |
| 1025 | OSD_File aFile (theFileNames[anIndex]); |
| 1026 | if (aFile.Exists()) |
| 1027 | { |
| 1028 | aFile.Open (OSD_ReadOnly, OSD_Protection()); |
| 1029 | } |
| 1030 | if (!aFile.IsOpen()) |
| 1031 | { |
| 1032 | if (!aMissingFiles.IsEmpty()) |
| 1033 | { |
| 1034 | aMissingFiles += ", "; |
| 1035 | } |
| 1036 | aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'"; |
| 1037 | continue; |
| 1038 | } |
| 1039 | else if (!aMissingFiles.IsEmpty()) |
| 1040 | { |
| 1041 | aFile.Close(); |
| 1042 | continue; |
| 1043 | } |
| 1044 | |
| 1045 | TCollection_AsciiString aSource; |
| 1046 | aFile.Read (aSource, (Standard_Integer) aFile.Size()); |
| 1047 | if (!aSource.IsEmpty()) |
| 1048 | { |
| 1049 | mySource += TCollection_AsciiString ("\n") + aSource; |
| 1050 | } |
| 1051 | aFile.Close(); |
| 1052 | } |
| 1053 | |
| 1054 | myPrefix = thePrefix; |
| 1055 | if (!aMissingFiles.IsEmpty()) |
| 1056 | { |
| 1057 | myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible"; |
| 1058 | return Standard_False; |
| 1059 | } |
| 1060 | return Standard_True; |
| 1061 | } |
| 1062 | |
| 1063 | // ======================================================================= |
| 1064 | // function : generateShaderPrefix |
| 1065 | // purpose : Generates shader prefix based on current ray-tracing options |
| 1066 | // ======================================================================= |
| 1067 | TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const |
| 1068 | { |
| 1069 | TCollection_AsciiString aPrefixString = |
| 1070 | TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" + |
| 1071 | TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces); |
| 1072 | |
| 1073 | if (myRaytraceParameters.TransparentShadows) |
| 1074 | { |
| 1075 | aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS"); |
| 1076 | } |
| 1077 | |
| 1078 | // If OpenGL driver supports bindless textures and texturing |
| 1079 | // is actually used, activate texturing in ray-tracing mode |
| 1080 | if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL) |
| 1081 | { |
| 1082 | aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") + |
| 1083 | TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER); |
| 1084 | } |
| 1085 | |
| 1086 | if (myRaytraceParameters.GlobalIllumination) // path tracing activated |
| 1087 | { |
| 1088 | aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING"); |
| 1089 | |
| 1090 | if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested |
| 1091 | { |
| 1092 | // to activate the feature we need OpenGL 4.4 and GL_NV_shader_atomic_float extension |
| 1093 | if (theGlContext->IsGlGreaterEqual (4, 4) && theGlContext->CheckExtension ("GL_NV_shader_atomic_float")) |
| 1094 | { |
| 1095 | aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING") + |
| 1096 | TCollection_AsciiString ("\n#define BLOCK_SIZE ") + TCollection_AsciiString (OpenGl_TileSampler::TileSize()); |
| 1097 | } |
| 1098 | } |
| 1099 | } |
| 1100 | |
| 1101 | return aPrefixString; |
| 1102 | } |
| 1103 | |
| 1104 | // ======================================================================= |
| 1105 | // function : safeFailBack |
| 1106 | // purpose : Performs safe exit when shaders initialization fails |
| 1107 | // ======================================================================= |
| 1108 | Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage, |
| 1109 | const Handle(OpenGl_Context)& theGlContext) |
| 1110 | { |
| 1111 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, |
| 1112 | GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage); |
| 1113 | |
| 1114 | myRaytraceInitStatus = OpenGl_RT_FAIL; |
| 1115 | |
| 1116 | releaseRaytraceResources (theGlContext); |
| 1117 | |
| 1118 | return Standard_False; |
| 1119 | } |
| 1120 | |
| 1121 | // ======================================================================= |
| 1122 | // function : initShader |
| 1123 | // purpose : Creates new shader object with specified source |
| 1124 | // ======================================================================= |
| 1125 | Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType, |
| 1126 | const ShaderSource& theSource, |
| 1127 | const Handle(OpenGl_Context)& theGlContext) |
| 1128 | { |
| 1129 | Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType); |
| 1130 | |
| 1131 | if (!aShader->Create (theGlContext)) |
| 1132 | { |
| 1133 | const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") + |
| 1134 | (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object"; |
| 1135 | |
| 1136 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, |
| 1137 | GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage); |
| 1138 | |
| 1139 | aShader->Release (theGlContext.operator->()); |
| 1140 | |
| 1141 | return Handle(OpenGl_ShaderObject)(); |
| 1142 | } |
| 1143 | |
| 1144 | if (!aShader->LoadSource (theGlContext, theSource.Source())) |
| 1145 | { |
| 1146 | const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") + |
| 1147 | (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source"; |
| 1148 | |
| 1149 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, |
| 1150 | GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage); |
| 1151 | |
| 1152 | aShader->Release (theGlContext.operator->()); |
| 1153 | |
| 1154 | return Handle(OpenGl_ShaderObject)(); |
| 1155 | } |
| 1156 | |
| 1157 | TCollection_AsciiString aBuildLog; |
| 1158 | |
| 1159 | if (!aShader->Compile (theGlContext)) |
| 1160 | { |
| 1161 | aShader->FetchInfoLog (theGlContext, aBuildLog); |
| 1162 | |
| 1163 | const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") + |
| 1164 | (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog; |
| 1165 | |
| 1166 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, |
| 1167 | GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage); |
| 1168 | |
| 1169 | aShader->Release (theGlContext.operator->()); |
| 1170 | |
| 1171 | #ifdef RAY_TRACE_PRINT_INFO |
| 1172 | std::cout << "Shader build log:\n" << aBuildLog << "\n"; |
| 1173 | #endif |
| 1174 | |
| 1175 | return Handle(OpenGl_ShaderObject)(); |
| 1176 | } |
| 1177 | else if (theGlContext->caps->glslWarnings) |
| 1178 | { |
| 1179 | aShader->FetchInfoLog (theGlContext, aBuildLog); |
| 1180 | |
| 1181 | if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n")) |
| 1182 | { |
| 1183 | const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ? |
| 1184 | "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog; |
| 1185 | |
| 1186 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, |
| 1187 | GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage); |
| 1188 | } |
| 1189 | |
| 1190 | #ifdef RAY_TRACE_PRINT_INFO |
| 1191 | std::cout << "Shader build log:\n" << aBuildLog << "\n"; |
| 1192 | #endif |
| 1193 | } |
| 1194 | |
| 1195 | return aShader; |
| 1196 | } |
| 1197 | |
| 1198 | // ======================================================================= |
| 1199 | // function : initProgram |
| 1200 | // purpose : Creates GLSL program from the given shader objects |
| 1201 | // ======================================================================= |
| 1202 | Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext, |
| 1203 | const Handle(OpenGl_ShaderObject)& theVertShader, |
| 1204 | const Handle(OpenGl_ShaderObject)& theFragShader) |
| 1205 | { |
| 1206 | Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram; |
| 1207 | |
| 1208 | if (!aProgram->Create (theGlContext)) |
| 1209 | { |
| 1210 | theVertShader->Release (theGlContext.operator->()); |
| 1211 | |
| 1212 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, |
| 1213 | GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program"); |
| 1214 | |
| 1215 | return Handle(OpenGl_ShaderProgram)(); |
| 1216 | } |
| 1217 | |
| 1218 | if (!aProgram->AttachShader (theGlContext, theVertShader) |
| 1219 | || !aProgram->AttachShader (theGlContext, theFragShader)) |
| 1220 | { |
| 1221 | theVertShader->Release (theGlContext.operator->()); |
| 1222 | |
| 1223 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, |
| 1224 | GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects"); |
| 1225 | |
| 1226 | return Handle(OpenGl_ShaderProgram)(); |
| 1227 | } |
| 1228 | |
| 1229 | aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex"); |
| 1230 | |
| 1231 | TCollection_AsciiString aLinkLog; |
| 1232 | |
| 1233 | if (!aProgram->Link (theGlContext)) |
| 1234 | { |
| 1235 | aProgram->FetchInfoLog (theGlContext, aLinkLog); |
| 1236 | |
| 1237 | const TCollection_ExtendedString aMessage = TCollection_ExtendedString ( |
| 1238 | "Failed to link shader program:\n") + aLinkLog; |
| 1239 | |
| 1240 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, |
| 1241 | GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage); |
| 1242 | |
| 1243 | return Handle(OpenGl_ShaderProgram)(); |
| 1244 | } |
| 1245 | else if (theGlContext->caps->glslWarnings) |
| 1246 | { |
| 1247 | aProgram->FetchInfoLog (theGlContext, aLinkLog); |
| 1248 | if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n")) |
| 1249 | { |
| 1250 | const TCollection_ExtendedString aMessage = TCollection_ExtendedString ( |
| 1251 | "Shader program was linked with following warnings:\n") + aLinkLog; |
| 1252 | |
| 1253 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, |
| 1254 | GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage); |
| 1255 | } |
| 1256 | } |
| 1257 | |
| 1258 | return aProgram; |
| 1259 | } |
| 1260 | |
| 1261 | // ======================================================================= |
| 1262 | // function : initRaytraceResources |
| 1263 | // purpose : Initializes OpenGL/GLSL shader programs |
| 1264 | // ======================================================================= |
| 1265 | Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context)& theGlContext) |
| 1266 | { |
| 1267 | if (myRaytraceInitStatus == OpenGl_RT_FAIL) |
| 1268 | { |
| 1269 | return Standard_False; |
| 1270 | } |
| 1271 | |
| 1272 | Standard_Boolean aToRebuildShaders = Standard_False; |
| 1273 | |
| 1274 | if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization |
| 1275 | { |
| 1276 | myRaytraceInitStatus = OpenGl_RT_NONE; |
| 1277 | releaseRaytraceResources (theGlContext, Standard_True); |
| 1278 | myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag |
| 1279 | } |
| 1280 | |
| 1281 | if (myRaytraceInitStatus == OpenGl_RT_INIT) |
| 1282 | { |
| 1283 | if (!myIsRaytraceDataValid) |
| 1284 | { |
| 1285 | return Standard_True; |
| 1286 | } |
| 1287 | |
| 1288 | const Standard_Integer aRequiredStackSize = |
| 1289 | myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth(); |
| 1290 | |
| 1291 | if (myRaytraceParameters.StackSize < aRequiredStackSize) |
| 1292 | { |
| 1293 | myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE); |
| 1294 | |
| 1295 | aToRebuildShaders = Standard_True; |
| 1296 | } |
| 1297 | else |
| 1298 | { |
| 1299 | if (aRequiredStackSize < myRaytraceParameters.StackSize) |
| 1300 | { |
| 1301 | if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE) |
| 1302 | { |
| 1303 | myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE); |
| 1304 | aToRebuildShaders = Standard_True; |
| 1305 | } |
| 1306 | } |
| 1307 | } |
| 1308 | |
| 1309 | if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces) |
| 1310 | { |
| 1311 | myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth; |
| 1312 | aToRebuildShaders = Standard_True; |
| 1313 | } |
| 1314 | |
| 1315 | if (myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures) |
| 1316 | { |
| 1317 | myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures(); |
| 1318 | aToRebuildShaders = Standard_True; |
| 1319 | } |
| 1320 | |
| 1321 | if (myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows) |
| 1322 | { |
| 1323 | myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled; |
| 1324 | aToRebuildShaders = Standard_True; |
| 1325 | } |
| 1326 | |
| 1327 | if (myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination) |
| 1328 | { |
| 1329 | myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled; |
| 1330 | aToRebuildShaders = Standard_True; |
| 1331 | } |
| 1332 | |
| 1333 | if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling) |
| 1334 | { |
| 1335 | myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling; |
| 1336 | if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested |
| 1337 | { |
| 1338 | if (!theGlContext->HasRayTracingAdaptiveSampling()) |
| 1339 | { |
| 1340 | // disable the feature if it is not supported |
| 1341 | myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False; |
| 1342 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, |
| 1343 | "Adaptive sampling not supported (OpenGL 4.4 or GL_NV_shader_atomic_float is missing)"); |
| 1344 | } |
| 1345 | } |
| 1346 | |
| 1347 | aToRebuildShaders = Standard_True; |
| 1348 | } |
| 1349 | |
| 1350 | if (aToRebuildShaders) |
| 1351 | { |
| 1352 | // Reject accumulated frames |
| 1353 | myAccumFrames = 0; |
| 1354 | |
| 1355 | // Environment map should be updated |
| 1356 | myToUpdateEnvironmentMap = Standard_True; |
| 1357 | |
| 1358 | const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext); |
| 1359 | |
| 1360 | #ifdef RAY_TRACE_PRINT_INFO |
| 1361 | std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl; |
| 1362 | #endif |
| 1363 | |
| 1364 | myRaytraceShaderSource.SetPrefix (aPrefixString); |
| 1365 | myPostFSAAShaderSource.SetPrefix (aPrefixString); |
| 1366 | myOutImageShaderSource.SetPrefix (aPrefixString); |
| 1367 | |
| 1368 | if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source()) |
| 1369 | || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source()) |
| 1370 | || !myOutImageShader->LoadSource (theGlContext, myOutImageShaderSource.Source())) |
| 1371 | { |
| 1372 | return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext); |
| 1373 | } |
| 1374 | |
| 1375 | if (!myRaytraceShader->Compile (theGlContext) |
| 1376 | || !myPostFSAAShader->Compile (theGlContext) |
| 1377 | || !myOutImageShader->Compile (theGlContext)) |
| 1378 | { |
| 1379 | return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext); |
| 1380 | } |
| 1381 | |
| 1382 | myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex"); |
| 1383 | myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex"); |
| 1384 | myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex"); |
| 1385 | |
| 1386 | if (!myRaytraceProgram->Link (theGlContext) |
| 1387 | || !myPostFSAAProgram->Link (theGlContext) |
| 1388 | || !myOutImageProgram->Link (theGlContext)) |
| 1389 | { |
| 1390 | return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext); |
| 1391 | } |
| 1392 | } |
| 1393 | } |
| 1394 | |
| 1395 | if (myRaytraceInitStatus == OpenGl_RT_NONE) |
| 1396 | { |
| 1397 | myAccumFrames = 0; // reject accumulated frames |
| 1398 | |
| 1399 | if (!theGlContext->IsGlGreaterEqual (3, 1)) |
| 1400 | { |
| 1401 | return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext); |
| 1402 | } |
| 1403 | else if (!theGlContext->arbTboRGB32) |
| 1404 | { |
| 1405 | return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext); |
| 1406 | } |
| 1407 | else if (!theGlContext->arbFBOBlit) |
| 1408 | { |
| 1409 | return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext); |
| 1410 | } |
| 1411 | |
| 1412 | myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth; |
| 1413 | |
| 1414 | const TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder(); |
| 1415 | |
| 1416 | if (aFolder.IsEmpty()) |
| 1417 | { |
| 1418 | return safeFailBack ("Failed to locate shaders directory", theGlContext); |
| 1419 | } |
| 1420 | |
| 1421 | if (myIsRaytraceDataValid) |
| 1422 | { |
| 1423 | myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE, |
| 1424 | myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth()); |
| 1425 | } |
| 1426 | |
| 1427 | const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext); |
| 1428 | |
| 1429 | #ifdef RAY_TRACE_PRINT_INFO |
| 1430 | std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl; |
| 1431 | #endif |
| 1432 | |
| 1433 | ShaderSource aBasicVertShaderSrc; |
| 1434 | { |
| 1435 | TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.vs", "" }; |
| 1436 | if (!aBasicVertShaderSrc.Load (aFiles)) |
| 1437 | { |
| 1438 | return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext); |
| 1439 | } |
| 1440 | } |
| 1441 | |
| 1442 | { |
| 1443 | TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", |
| 1444 | aFolder + "/PathtraceBase.fs", |
| 1445 | aFolder + "/RaytraceRender.fs", |
| 1446 | "" }; |
| 1447 | if (!myRaytraceShaderSource.Load (aFiles, aPrefixString)) |
| 1448 | { |
| 1449 | return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext); |
| 1450 | } |
| 1451 | |
| 1452 | Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext); |
| 1453 | if (aBasicVertShader.IsNull()) |
| 1454 | { |
| 1455 | return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext); |
| 1456 | } |
| 1457 | |
| 1458 | myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext); |
| 1459 | if (myRaytraceShader.IsNull()) |
| 1460 | { |
| 1461 | aBasicVertShader->Release (theGlContext.operator->()); |
| 1462 | return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext); |
| 1463 | } |
| 1464 | |
| 1465 | myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader); |
| 1466 | if (myRaytraceProgram.IsNull()) |
| 1467 | { |
| 1468 | return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext); |
| 1469 | } |
| 1470 | } |
| 1471 | |
| 1472 | { |
| 1473 | TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", |
| 1474 | aFolder + "/RaytraceSmooth.fs", |
| 1475 | "" }; |
| 1476 | if (!myPostFSAAShaderSource.Load (aFiles, aPrefixString)) |
| 1477 | { |
| 1478 | return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext); |
| 1479 | } |
| 1480 | |
| 1481 | Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext); |
| 1482 | if (aBasicVertShader.IsNull()) |
| 1483 | { |
| 1484 | return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext); |
| 1485 | } |
| 1486 | |
| 1487 | myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext); |
| 1488 | if (myPostFSAAShader.IsNull()) |
| 1489 | { |
| 1490 | aBasicVertShader->Release (theGlContext.operator->()); |
| 1491 | return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext); |
| 1492 | } |
| 1493 | |
| 1494 | myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader); |
| 1495 | if (myPostFSAAProgram.IsNull()) |
| 1496 | { |
| 1497 | return safeFailBack ("Failed to initialize FSAA shader program", theGlContext); |
| 1498 | } |
| 1499 | } |
| 1500 | |
| 1501 | { |
| 1502 | TCollection_AsciiString aFiles[] = { aFolder + "/Display.fs", "" }; |
| 1503 | if (!myOutImageShaderSource.Load (aFiles, aPrefixString)) |
| 1504 | { |
| 1505 | return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext); |
| 1506 | } |
| 1507 | |
| 1508 | Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext); |
| 1509 | if (aBasicVertShader.IsNull()) |
| 1510 | { |
| 1511 | return safeFailBack ("Failed to set vertex shader source", theGlContext); |
| 1512 | } |
| 1513 | |
| 1514 | myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext); |
| 1515 | if (myOutImageShader.IsNull()) |
| 1516 | { |
| 1517 | aBasicVertShader->Release (theGlContext.operator->()); |
| 1518 | return safeFailBack ("Failed to set display fragment shader source", theGlContext); |
| 1519 | } |
| 1520 | |
| 1521 | myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader); |
| 1522 | if (myOutImageProgram.IsNull()) |
| 1523 | { |
| 1524 | return safeFailBack ("Failed to initialize display shader program", theGlContext); |
| 1525 | } |
| 1526 | } |
| 1527 | } |
| 1528 | |
| 1529 | if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders) |
| 1530 | { |
| 1531 | for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex) |
| 1532 | { |
| 1533 | Handle(OpenGl_ShaderProgram)& aShaderProgram = |
| 1534 | (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram; |
| 1535 | |
| 1536 | theGlContext->BindProgram (aShaderProgram); |
| 1537 | |
| 1538 | aShaderProgram->SetSampler (theGlContext, |
| 1539 | "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture); |
| 1540 | aShaderProgram->SetSampler (theGlContext, |
| 1541 | "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture); |
| 1542 | aShaderProgram->SetSampler (theGlContext, |
| 1543 | "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture); |
| 1544 | aShaderProgram->SetSampler (theGlContext, |
| 1545 | "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture); |
| 1546 | aShaderProgram->SetSampler (theGlContext, |
| 1547 | "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture); |
| 1548 | aShaderProgram->SetSampler (theGlContext, |
| 1549 | "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture); |
| 1550 | aShaderProgram->SetSampler (theGlContext, |
| 1551 | "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture); |
| 1552 | aShaderProgram->SetSampler (theGlContext, |
| 1553 | "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture); |
| 1554 | aShaderProgram->SetSampler (theGlContext, |
| 1555 | "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture); |
| 1556 | aShaderProgram->SetSampler (theGlContext, |
| 1557 | "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture); |
| 1558 | aShaderProgram->SetSampler (theGlContext, |
| 1559 | "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture); |
| 1560 | |
| 1561 | if (anIndex == 1) |
| 1562 | { |
| 1563 | aShaderProgram->SetSampler (theGlContext, |
| 1564 | "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture); |
| 1565 | } |
| 1566 | else |
| 1567 | { |
| 1568 | aShaderProgram->SetSampler (theGlContext, |
| 1569 | "uAccumTexture", OpenGl_RT_PrevAccumTexture); |
| 1570 | } |
| 1571 | |
| 1572 | myUniformLocations[anIndex][OpenGl_RT_aPosition] = |
| 1573 | aShaderProgram->GetAttributeLocation (theGlContext, "occVertex"); |
| 1574 | |
| 1575 | myUniformLocations[anIndex][OpenGl_RT_uOriginLB] = |
| 1576 | aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB"); |
| 1577 | myUniformLocations[anIndex][OpenGl_RT_uOriginRB] = |
| 1578 | aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB"); |
| 1579 | myUniformLocations[anIndex][OpenGl_RT_uOriginLT] = |
| 1580 | aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT"); |
| 1581 | myUniformLocations[anIndex][OpenGl_RT_uOriginRT] = |
| 1582 | aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT"); |
| 1583 | myUniformLocations[anIndex][OpenGl_RT_uDirectLB] = |
| 1584 | aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB"); |
| 1585 | myUniformLocations[anIndex][OpenGl_RT_uDirectRB] = |
| 1586 | aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB"); |
| 1587 | myUniformLocations[anIndex][OpenGl_RT_uDirectLT] = |
| 1588 | aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT"); |
| 1589 | myUniformLocations[anIndex][OpenGl_RT_uDirectRT] = |
| 1590 | aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT"); |
| 1591 | myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] = |
| 1592 | aShaderProgram->GetUniformLocation (theGlContext, "uViewMat"); |
| 1593 | myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] = |
| 1594 | aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat"); |
| 1595 | |
| 1596 | myUniformLocations[anIndex][OpenGl_RT_uSceneRad] = |
| 1597 | aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius"); |
| 1598 | myUniformLocations[anIndex][OpenGl_RT_uSceneEps] = |
| 1599 | aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon"); |
| 1600 | myUniformLocations[anIndex][OpenGl_RT_uLightCount] = |
| 1601 | aShaderProgram->GetUniformLocation (theGlContext, "uLightCount"); |
| 1602 | myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] = |
| 1603 | aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient"); |
| 1604 | |
| 1605 | myUniformLocations[anIndex][OpenGl_RT_uOffsetX] = |
| 1606 | aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX"); |
| 1607 | myUniformLocations[anIndex][OpenGl_RT_uOffsetY] = |
| 1608 | aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY"); |
| 1609 | myUniformLocations[anIndex][OpenGl_RT_uSamples] = |
| 1610 | aShaderProgram->GetUniformLocation (theGlContext, "uSamples"); |
| 1611 | |
| 1612 | myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] = |
| 1613 | aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers"); |
| 1614 | |
| 1615 | myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] = |
| 1616 | aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled"); |
| 1617 | myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] = |
| 1618 | aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled"); |
| 1619 | myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] = |
| 1620 | aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled"); |
| 1621 | myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] = |
| 1622 | aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack"); |
| 1623 | myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] = |
| 1624 | aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled"); |
| 1625 | |
| 1626 | myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] = |
| 1627 | aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX"); |
| 1628 | myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] = |
| 1629 | aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY"); |
| 1630 | |
| 1631 | myUniformLocations[anIndex][OpenGl_RT_uSampleWeight] = |
| 1632 | aShaderProgram->GetUniformLocation (theGlContext, "uSampleWeight"); |
| 1633 | myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] = |
| 1634 | aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed"); |
| 1635 | |
| 1636 | myUniformLocations[anIndex][OpenGl_RT_uRenderImage] = |
| 1637 | aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage"); |
| 1638 | myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] = |
| 1639 | aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage"); |
| 1640 | |
| 1641 | myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] = |
| 1642 | aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop"); |
| 1643 | myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] = |
| 1644 | aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot"); |
| 1645 | } |
| 1646 | |
| 1647 | theGlContext->BindProgram (myOutImageProgram); |
| 1648 | |
| 1649 | myOutImageProgram->SetSampler (theGlContext, |
| 1650 | "uInputTexture", OpenGl_RT_PrevAccumTexture); |
| 1651 | |
| 1652 | myOutImageProgram->SetSampler (theGlContext, |
| 1653 | "uDepthTexture", OpenGl_RT_RaytraceDepthTexture); |
| 1654 | |
| 1655 | theGlContext->BindProgram (NULL); |
| 1656 | } |
| 1657 | |
| 1658 | if (myRaytraceInitStatus != OpenGl_RT_NONE) |
| 1659 | { |
| 1660 | return myRaytraceInitStatus == OpenGl_RT_INIT; |
| 1661 | } |
| 1662 | |
| 1663 | const GLfloat aVertices[] = { -1.f, -1.f, 0.f, |
| 1664 | -1.f, 1.f, 0.f, |
| 1665 | 1.f, 1.f, 0.f, |
| 1666 | 1.f, 1.f, 0.f, |
| 1667 | 1.f, -1.f, 0.f, |
| 1668 | -1.f, -1.f, 0.f }; |
| 1669 | |
| 1670 | myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices); |
| 1671 | |
| 1672 | myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way |
| 1673 | |
| 1674 | return Standard_True; |
| 1675 | } |
| 1676 | |
| 1677 | // ======================================================================= |
| 1678 | // function : nullifyResource |
| 1679 | // purpose : Releases OpenGL resource |
| 1680 | // ======================================================================= |
| 1681 | template <class T> |
| 1682 | inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource) |
| 1683 | { |
| 1684 | if (!theResource.IsNull()) |
| 1685 | { |
| 1686 | theResource->Release (theGlContext.operator->()); |
| 1687 | theResource.Nullify(); |
| 1688 | } |
| 1689 | } |
| 1690 | |
| 1691 | // ======================================================================= |
| 1692 | // function : releaseRaytraceResources |
| 1693 | // purpose : Releases OpenGL/GLSL shader programs |
| 1694 | // ======================================================================= |
| 1695 | void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild) |
| 1696 | { |
| 1697 | // release shader resources |
| 1698 | nullifyResource (theGlContext, myRaytraceShader); |
| 1699 | nullifyResource (theGlContext, myPostFSAAShader); |
| 1700 | |
| 1701 | nullifyResource (theGlContext, myRaytraceProgram); |
| 1702 | nullifyResource (theGlContext, myPostFSAAProgram); |
| 1703 | nullifyResource (theGlContext, myOutImageProgram); |
| 1704 | |
| 1705 | if (!theToRebuild) // complete release |
| 1706 | { |
| 1707 | myRaytraceFBO1[0]->Release (theGlContext.operator->()); |
| 1708 | myRaytraceFBO1[1]->Release (theGlContext.operator->()); |
| 1709 | myRaytraceFBO2[0]->Release (theGlContext.operator->()); |
| 1710 | myRaytraceFBO2[1]->Release (theGlContext.operator->()); |
| 1711 | |
| 1712 | nullifyResource (theGlContext, myRaytraceOutputTexture[0]); |
| 1713 | nullifyResource (theGlContext, myRaytraceOutputTexture[1]); |
| 1714 | |
| 1715 | nullifyResource (theGlContext, myRaytraceTileOffsetsTexture); |
| 1716 | nullifyResource (theGlContext, myRaytraceVisualErrorTexture); |
| 1717 | |
| 1718 | nullifyResource (theGlContext, mySceneNodeInfoTexture); |
| 1719 | nullifyResource (theGlContext, mySceneMinPointTexture); |
| 1720 | nullifyResource (theGlContext, mySceneMaxPointTexture); |
| 1721 | |
| 1722 | nullifyResource (theGlContext, myGeometryVertexTexture); |
| 1723 | nullifyResource (theGlContext, myGeometryNormalTexture); |
| 1724 | nullifyResource (theGlContext, myGeometryTexCrdTexture); |
| 1725 | nullifyResource (theGlContext, myGeometryTriangTexture); |
| 1726 | nullifyResource (theGlContext, mySceneTransformTexture); |
| 1727 | |
| 1728 | nullifyResource (theGlContext, myRaytraceLightSrcTexture); |
| 1729 | nullifyResource (theGlContext, myRaytraceMaterialTexture); |
| 1730 | |
| 1731 | myRaytraceGeometry.ReleaseResources (theGlContext); |
| 1732 | |
| 1733 | if (myRaytraceScreenQuad.IsValid ()) |
| 1734 | { |
| 1735 | myRaytraceScreenQuad.Release (theGlContext.operator->()); |
| 1736 | } |
| 1737 | } |
| 1738 | } |
| 1739 | |
| 1740 | // ======================================================================= |
| 1741 | // function : updateRaytraceBuffers |
| 1742 | // purpose : Updates auxiliary OpenGL frame buffers. |
| 1743 | // ======================================================================= |
| 1744 | Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX, |
| 1745 | const Standard_Integer theSizeY, |
| 1746 | const Handle(OpenGl_Context)& theGlContext) |
| 1747 | { |
| 1748 | // Auxiliary buffers are not used. |
| 1749 | if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled) |
| 1750 | { |
| 1751 | myRaytraceFBO1[0]->Release (theGlContext.operator->()); |
| 1752 | myRaytraceFBO2[0]->Release (theGlContext.operator->()); |
| 1753 | myRaytraceFBO1[1]->Release (theGlContext.operator->()); |
| 1754 | myRaytraceFBO2[1]->Release (theGlContext.operator->()); |
| 1755 | |
| 1756 | return Standard_True; |
| 1757 | } |
| 1758 | |
| 1759 | myRaytraceFBO1[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat); |
| 1760 | myRaytraceFBO2[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat); |
| 1761 | |
| 1762 | // Init second set of buffers for stereographic rendering. |
| 1763 | if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo) |
| 1764 | { |
| 1765 | myRaytraceFBO1[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat); |
| 1766 | myRaytraceFBO2[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat); |
| 1767 | } |
| 1768 | else |
| 1769 | { |
| 1770 | myRaytraceFBO1[1]->Release (theGlContext.operator->()); |
| 1771 | myRaytraceFBO2[1]->Release (theGlContext.operator->()); |
| 1772 | } |
| 1773 | |
| 1774 | myTileSampler.SetSize (theSizeX, theSizeY); |
| 1775 | |
| 1776 | if (myRaytraceTileOffsetsTexture.IsNull()) |
| 1777 | { |
| 1778 | myRaytraceOutputTexture[0] = new OpenGl_Texture(); |
| 1779 | myRaytraceOutputTexture[1] = new OpenGl_Texture(); |
| 1780 | |
| 1781 | myRaytraceTileOffsetsTexture = new OpenGl_Texture(); |
| 1782 | myRaytraceVisualErrorTexture = new OpenGl_Texture(); |
| 1783 | } |
| 1784 | |
| 1785 | if (myRaytraceOutputTexture[0]->SizeX() / 3 != theSizeX |
| 1786 | || myRaytraceOutputTexture[0]->SizeY() / 2 != theSizeY) |
| 1787 | { |
| 1788 | // Due to limitations of OpenGL image load-store extension |
| 1789 | // atomic operations are supported only for single-channel |
| 1790 | // images, so we define GL_R32F image. It is used as array |
| 1791 | // of 6D floating point vectors: |
| 1792 | // 0 - R color channel |
| 1793 | // 1 - G color channel |
| 1794 | // 2 - B color channel |
| 1795 | // 3 - hit time transformed into OpenGL NDC space |
| 1796 | // 4 - luminance accumulated for odd samples only |
| 1797 | myRaytraceOutputTexture[0]->InitRectangle (theGlContext, |
| 1798 | theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>()); |
| 1799 | |
| 1800 | myRaytraceVisualErrorTexture->Init (theGlContext, |
| 1801 | GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D); |
| 1802 | |
| 1803 | myRaytraceTileOffsetsTexture->Init (theGlContext, |
| 1804 | GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D); |
| 1805 | } |
| 1806 | |
| 1807 | if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo) |
| 1808 | { |
| 1809 | if (myRaytraceOutputTexture[1]->SizeX() / 3 != theSizeX |
| 1810 | || myRaytraceOutputTexture[1]->SizeY() / 2 != theSizeY) |
| 1811 | { |
| 1812 | myRaytraceOutputTexture[1]->InitRectangle (theGlContext, |
| 1813 | theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>()); |
| 1814 | } |
| 1815 | } |
| 1816 | else |
| 1817 | { |
| 1818 | myRaytraceOutputTexture[1]->Release (theGlContext.operator->()); |
| 1819 | } |
| 1820 | |
| 1821 | return Standard_True; |
| 1822 | } |
| 1823 | |
| 1824 | // ======================================================================= |
| 1825 | // function : updateCamera |
| 1826 | // purpose : Generates viewing rays for corners of screen quad |
| 1827 | // ======================================================================= |
| 1828 | void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation, |
| 1829 | const OpenGl_Mat4& theViewMapping, |
| 1830 | OpenGl_Vec3* theOrigins, |
| 1831 | OpenGl_Vec3* theDirects, |
| 1832 | OpenGl_Mat4& theViewPr, |
| 1833 | OpenGl_Mat4& theUnview) |
| 1834 | { |
| 1835 | // compute view-projection matrix |
| 1836 | theViewPr = theViewMapping * theOrientation; |
| 1837 | |
| 1838 | // compute inverse view-projection matrix |
| 1839 | theViewPr.Inverted (theUnview); |
| 1840 | |
| 1841 | Standard_Integer aOriginIndex = 0; |
| 1842 | Standard_Integer aDirectIndex = 0; |
| 1843 | |
| 1844 | for (Standard_Integer aY = -1; aY <= 1; aY += 2) |
| 1845 | { |
| 1846 | for (Standard_Integer aX = -1; aX <= 1; aX += 2) |
| 1847 | { |
| 1848 | OpenGl_Vec4 aOrigin (GLfloat(aX), |
| 1849 | GLfloat(aY), |
| 1850 | -1.0f, |
| 1851 | 1.0f); |
| 1852 | |
| 1853 | aOrigin = theUnview * aOrigin; |
| 1854 | |
| 1855 | aOrigin.x() = aOrigin.x() / aOrigin.w(); |
| 1856 | aOrigin.y() = aOrigin.y() / aOrigin.w(); |
| 1857 | aOrigin.z() = aOrigin.z() / aOrigin.w(); |
| 1858 | |
| 1859 | OpenGl_Vec4 aDirect (GLfloat(aX), |
| 1860 | GLfloat(aY), |
| 1861 | 1.0f, |
| 1862 | 1.0f); |
| 1863 | |
| 1864 | aDirect = theUnview * aDirect; |
| 1865 | |
| 1866 | aDirect.x() = aDirect.x() / aDirect.w(); |
| 1867 | aDirect.y() = aDirect.y() / aDirect.w(); |
| 1868 | aDirect.z() = aDirect.z() / aDirect.w(); |
| 1869 | |
| 1870 | aDirect = aDirect - aOrigin; |
| 1871 | |
| 1872 | theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()), |
| 1873 | static_cast<GLfloat> (aOrigin.y()), |
| 1874 | static_cast<GLfloat> (aOrigin.z())); |
| 1875 | |
| 1876 | theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()), |
| 1877 | static_cast<GLfloat> (aDirect.y()), |
| 1878 | static_cast<GLfloat> (aDirect.z())); |
| 1879 | } |
| 1880 | } |
| 1881 | } |
| 1882 | |
| 1883 | // ======================================================================= |
| 1884 | // function : uploadRaytraceData |
| 1885 | // purpose : Uploads ray-trace data to the GPU |
| 1886 | // ======================================================================= |
| 1887 | Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext) |
| 1888 | { |
| 1889 | if (!theGlContext->IsGlGreaterEqual (3, 1)) |
| 1890 | { |
| 1891 | #ifdef RAY_TRACE_PRINT_INFO |
| 1892 | std::cout << "Error: OpenGL version is less than 3.1" << std::endl; |
| 1893 | #endif |
| 1894 | return Standard_False; |
| 1895 | } |
| 1896 | |
| 1897 | myAccumFrames = 0; // accumulation should be restarted |
| 1898 | |
| 1899 | ///////////////////////////////////////////////////////////////////////////// |
| 1900 | // Prepare OpenGL textures |
| 1901 | |
| 1902 | if (theGlContext->arbTexBindless != NULL) |
| 1903 | { |
| 1904 | // If OpenGL driver supports bindless textures we need |
| 1905 | // to get unique 64- bit handles for using on the GPU |
| 1906 | if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext)) |
| 1907 | { |
| 1908 | #ifdef RAY_TRACE_PRINT_INFO |
| 1909 | std::cout << "Error: Failed to get OpenGL texture handles" << std::endl; |
| 1910 | #endif |
| 1911 | return Standard_False; |
| 1912 | } |
| 1913 | } |
| 1914 | |
| 1915 | ///////////////////////////////////////////////////////////////////////////// |
| 1916 | // Create OpenGL BVH buffers |
| 1917 | |
| 1918 | if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers |
| 1919 | { |
| 1920 | mySceneNodeInfoTexture = new OpenGl_TextureBufferArb; |
| 1921 | mySceneMinPointTexture = new OpenGl_TextureBufferArb; |
| 1922 | mySceneMaxPointTexture = new OpenGl_TextureBufferArb; |
| 1923 | mySceneTransformTexture = new OpenGl_TextureBufferArb; |
| 1924 | |
| 1925 | if (!mySceneNodeInfoTexture->Create (theGlContext) |
| 1926 | || !mySceneMinPointTexture->Create (theGlContext) |
| 1927 | || !mySceneMaxPointTexture->Create (theGlContext) |
| 1928 | || !mySceneTransformTexture->Create (theGlContext)) |
| 1929 | { |
| 1930 | #ifdef RAY_TRACE_PRINT_INFO |
| 1931 | std::cout << "Error: Failed to create scene BVH buffers" << std::endl; |
| 1932 | #endif |
| 1933 | return Standard_False; |
| 1934 | } |
| 1935 | } |
| 1936 | |
| 1937 | if (myGeometryVertexTexture.IsNull()) // create geometry buffers |
| 1938 | { |
| 1939 | myGeometryVertexTexture = new OpenGl_TextureBufferArb; |
| 1940 | myGeometryNormalTexture = new OpenGl_TextureBufferArb; |
| 1941 | myGeometryTexCrdTexture = new OpenGl_TextureBufferArb; |
| 1942 | myGeometryTriangTexture = new OpenGl_TextureBufferArb; |
| 1943 | |
| 1944 | if (!myGeometryVertexTexture->Create (theGlContext) |
| 1945 | || !myGeometryNormalTexture->Create (theGlContext) |
| 1946 | || !myGeometryTexCrdTexture->Create (theGlContext) |
| 1947 | || !myGeometryTriangTexture->Create (theGlContext)) |
| 1948 | { |
| 1949 | #ifdef RAY_TRACE_PRINT_INFO |
| 1950 | std::cout << "Error: Failed to create buffers for triangulation data" << std::endl; |
| 1951 | #endif |
| 1952 | return Standard_False; |
| 1953 | } |
| 1954 | } |
| 1955 | |
| 1956 | if (myRaytraceMaterialTexture.IsNull()) // create material buffer |
| 1957 | { |
| 1958 | myRaytraceMaterialTexture = new OpenGl_TextureBufferArb; |
| 1959 | |
| 1960 | if (!myRaytraceMaterialTexture->Create (theGlContext)) |
| 1961 | { |
| 1962 | #ifdef RAY_TRACE_PRINT_INFO |
| 1963 | std::cout << "Error: Failed to create buffers for material data" << std::endl; |
| 1964 | #endif |
| 1965 | return Standard_False; |
| 1966 | } |
| 1967 | } |
| 1968 | |
| 1969 | ///////////////////////////////////////////////////////////////////////////// |
| 1970 | // Write transform buffer |
| 1971 | |
| 1972 | BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()]; |
| 1973 | |
| 1974 | bool aResult = true; |
| 1975 | |
| 1976 | for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex) |
| 1977 | { |
| 1978 | OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> ( |
| 1979 | myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->()); |
| 1980 | |
| 1981 | const BVH_Transform<Standard_ShortReal, 4>* aTransform = |
| 1982 | dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->()); |
| 1983 | |
| 1984 | Standard_ASSERT_RETURN (aTransform != NULL, |
| 1985 | "OpenGl_TriangleSet does not contain transform", Standard_False); |
| 1986 | |
| 1987 | aNodeTransforms[anElemIndex] = aTransform->Inversed(); |
| 1988 | } |
| 1989 | |
| 1990 | aResult &= mySceneTransformTexture->Init (theGlContext, 4, |
| 1991 | myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms)); |
| 1992 | |
| 1993 | delete [] aNodeTransforms; |
| 1994 | |
| 1995 | ///////////////////////////////////////////////////////////////////////////// |
| 1996 | // Write geometry and bottom-level BVH buffers |
| 1997 | |
| 1998 | Standard_Size aTotalVerticesNb = 0; |
| 1999 | Standard_Size aTotalElementsNb = 0; |
| 2000 | Standard_Size aTotalBVHNodesNb = 0; |
| 2001 | |
| 2002 | for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex) |
| 2003 | { |
| 2004 | OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> ( |
| 2005 | myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->()); |
| 2006 | |
| 2007 | Standard_ASSERT_RETURN (aTriangleSet != NULL, |
| 2008 | "Error: Failed to get triangulation of OpenGL element", Standard_False); |
| 2009 | |
| 2010 | aTotalVerticesNb += aTriangleSet->Vertices.size(); |
| 2011 | aTotalElementsNb += aTriangleSet->Elements.size(); |
| 2012 | |
| 2013 | Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(), |
| 2014 | "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False); |
| 2015 | |
| 2016 | aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size(); |
| 2017 | } |
| 2018 | |
| 2019 | aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size(); |
| 2020 | |
| 2021 | if (aTotalBVHNodesNb != 0) |
| 2022 | { |
| 2023 | aResult &= mySceneNodeInfoTexture->Init ( |
| 2024 | theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL)); |
| 2025 | aResult &= mySceneMinPointTexture->Init ( |
| 2026 | theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL)); |
| 2027 | aResult &= mySceneMaxPointTexture->Init ( |
| 2028 | theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL)); |
| 2029 | } |
| 2030 | |
| 2031 | if (!aResult) |
| 2032 | { |
| 2033 | #ifdef RAY_TRACE_PRINT_INFO |
| 2034 | std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl; |
| 2035 | #endif |
| 2036 | return Standard_False; |
| 2037 | } |
| 2038 | |
| 2039 | if (aTotalElementsNb != 0) |
| 2040 | { |
| 2041 | aResult &= myGeometryTriangTexture->Init ( |
| 2042 | theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL)); |
| 2043 | } |
| 2044 | |
| 2045 | if (aTotalVerticesNb != 0) |
| 2046 | { |
| 2047 | aResult &= myGeometryVertexTexture->Init ( |
| 2048 | theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL)); |
| 2049 | aResult &= myGeometryNormalTexture->Init ( |
| 2050 | theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL)); |
| 2051 | aResult &= myGeometryTexCrdTexture->Init ( |
| 2052 | theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL)); |
| 2053 | } |
| 2054 | |
| 2055 | if (!aResult) |
| 2056 | { |
| 2057 | #ifdef RAY_TRACE_PRINT_INFO |
| 2058 | std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl; |
| 2059 | #endif |
| 2060 | return Standard_False; |
| 2061 | } |
| 2062 | |
| 2063 | const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH(); |
| 2064 | |
| 2065 | if (aBVH->Length() > 0) |
| 2066 | { |
| 2067 | aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(), |
| 2068 | reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front())); |
| 2069 | aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(), |
| 2070 | reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front())); |
| 2071 | aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(), |
| 2072 | reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front())); |
| 2073 | } |
| 2074 | |
| 2075 | for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx) |
| 2076 | { |
| 2077 | if (!aBVH->IsOuter (aNodeIdx)) |
| 2078 | continue; |
| 2079 | |
| 2080 | OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx); |
| 2081 | |
| 2082 | Standard_ASSERT_RETURN (aTriangleSet != NULL, |
| 2083 | "Error: Failed to get triangulation of OpenGL element", Standard_False); |
| 2084 | |
| 2085 | Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx); |
| 2086 | |
| 2087 | Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET, |
| 2088 | "Error: Failed to get offset for bottom-level BVH", Standard_False); |
| 2089 | |
| 2090 | const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length(); |
| 2091 | |
| 2092 | if (aBvhBuffersSize != 0) |
| 2093 | { |
| 2094 | aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize, |
| 2095 | reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front())); |
| 2096 | aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize, |
| 2097 | reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front())); |
| 2098 | aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize, |
| 2099 | reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front())); |
| 2100 | |
| 2101 | if (!aResult) |
| 2102 | { |
| 2103 | #ifdef RAY_TRACE_PRINT_INFO |
| 2104 | std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl; |
| 2105 | #endif |
| 2106 | return Standard_False; |
| 2107 | } |
| 2108 | } |
| 2109 | |
| 2110 | const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx); |
| 2111 | |
| 2112 | Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET, |
| 2113 | "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False); |
| 2114 | |
| 2115 | if (!aTriangleSet->Vertices.empty()) |
| 2116 | { |
| 2117 | aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset, |
| 2118 | GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front())); |
| 2119 | aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset, |
| 2120 | GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front())); |
| 2121 | aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset, |
| 2122 | GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front())); |
| 2123 | } |
| 2124 | |
| 2125 | const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx); |
| 2126 | |
| 2127 | Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET, |
| 2128 | "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False); |
| 2129 | |
| 2130 | if (!aTriangleSet->Elements.empty()) |
| 2131 | { |
| 2132 | aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()), |
| 2133 | reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front())); |
| 2134 | } |
| 2135 | |
| 2136 | if (!aResult) |
| 2137 | { |
| 2138 | #ifdef RAY_TRACE_PRINT_INFO |
| 2139 | std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl; |
| 2140 | #endif |
| 2141 | return Standard_False; |
| 2142 | } |
| 2143 | } |
| 2144 | |
| 2145 | ///////////////////////////////////////////////////////////////////////////// |
| 2146 | // Write material buffer |
| 2147 | |
| 2148 | if (myRaytraceGeometry.Materials.size() != 0) |
| 2149 | { |
| 2150 | aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4, |
| 2151 | GLsizei (myRaytraceGeometry.Materials.size() * 18), myRaytraceGeometry.Materials.front().Packed()); |
| 2152 | |
| 2153 | if (!aResult) |
| 2154 | { |
| 2155 | #ifdef RAY_TRACE_PRINT_INFO |
| 2156 | std::cout << "Error: Failed to upload material buffer" << std::endl; |
| 2157 | #endif |
| 2158 | return Standard_False; |
| 2159 | } |
| 2160 | } |
| 2161 | |
| 2162 | myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0; |
| 2163 | |
| 2164 | #ifdef RAY_TRACE_PRINT_INFO |
| 2165 | |
| 2166 | Standard_ShortReal aMemTrgUsed = 0.f; |
| 2167 | Standard_ShortReal aMemBvhUsed = 0.f; |
| 2168 | |
| 2169 | for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx) |
| 2170 | { |
| 2171 | OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get()); |
| 2172 | |
| 2173 | aMemTrgUsed += static_cast<Standard_ShortReal> ( |
| 2174 | aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f)); |
| 2175 | aMemTrgUsed += static_cast<Standard_ShortReal> ( |
| 2176 | aTriangleSet->Normals.size() * sizeof (BVH_Vec3f)); |
| 2177 | aMemTrgUsed += static_cast<Standard_ShortReal> ( |
| 2178 | aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f)); |
| 2179 | aMemTrgUsed += static_cast<Standard_ShortReal> ( |
| 2180 | aTriangleSet->Elements.size() * sizeof (BVH_Vec4i)); |
| 2181 | |
| 2182 | aMemBvhUsed += static_cast<Standard_ShortReal> ( |
| 2183 | aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i)); |
| 2184 | aMemBvhUsed += static_cast<Standard_ShortReal> ( |
| 2185 | aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f)); |
| 2186 | aMemBvhUsed += static_cast<Standard_ShortReal> ( |
| 2187 | aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f)); |
| 2188 | } |
| 2189 | |
| 2190 | aMemBvhUsed += static_cast<Standard_ShortReal> ( |
| 2191 | myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i)); |
| 2192 | aMemBvhUsed += static_cast<Standard_ShortReal> ( |
| 2193 | myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f)); |
| 2194 | aMemBvhUsed += static_cast<Standard_ShortReal> ( |
| 2195 | myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f)); |
| 2196 | |
| 2197 | std::cout << "GPU Memory Used (Mb):\n" |
| 2198 | << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n" |
| 2199 | << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n"; |
| 2200 | |
| 2201 | #endif |
| 2202 | |
| 2203 | return aResult; |
| 2204 | } |
| 2205 | |
| 2206 | // ======================================================================= |
| 2207 | // function : updateRaytraceLightSources |
| 2208 | // purpose : Updates 3D scene light sources for ray-tracing |
| 2209 | // ======================================================================= |
| 2210 | Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext) |
| 2211 | { |
| 2212 | myRaytraceGeometry.Sources.clear(); |
| 2213 | |
| 2214 | myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f); |
| 2215 | |
| 2216 | OpenGl_ListOfLight::Iterator aLightIter (myShadingModel == Graphic3d_TOSM_NONE ? myNoShadingLight : myLights); |
| 2217 | for (; aLightIter.More(); aLightIter.Next()) |
| 2218 | { |
| 2219 | const OpenGl_Light& aLight = aLightIter.Value(); |
| 2220 | |
| 2221 | if (aLight.Type == Graphic3d_TOLS_AMBIENT) |
| 2222 | { |
| 2223 | myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r() * aLight.Intensity, |
| 2224 | aLight.Color.g() * aLight.Intensity, |
| 2225 | aLight.Color.b() * aLight.Intensity, |
| 2226 | 0.0f); |
| 2227 | continue; |
| 2228 | } |
| 2229 | |
| 2230 | BVH_Vec4f aDiffuse (aLight.Color.r() * aLight.Intensity, |
| 2231 | aLight.Color.g() * aLight.Intensity, |
| 2232 | aLight.Color.b() * aLight.Intensity, |
| 2233 | 1.0f); |
| 2234 | |
| 2235 | BVH_Vec4f aPosition (-aLight.Direction.x(), |
| 2236 | -aLight.Direction.y(), |
| 2237 | -aLight.Direction.z(), |
| 2238 | 0.0f); |
| 2239 | |
| 2240 | if (aLight.Type != Graphic3d_TOLS_DIRECTIONAL) |
| 2241 | { |
| 2242 | aPosition = BVH_Vec4f (static_cast<float>(aLight.Position.x()), |
| 2243 | static_cast<float>(aLight.Position.y()), |
| 2244 | static_cast<float>(aLight.Position.z()), |
| 2245 | 1.0f); |
| 2246 | |
| 2247 | // store smoothing radius in w-component |
| 2248 | aDiffuse.w() = Max (aLight.Smoothness, 0.f); |
| 2249 | } |
| 2250 | else |
| 2251 | { |
| 2252 | // store cosine of smoothing angle in w-component |
| 2253 | aDiffuse.w() = cosf (Min (Max (aLight.Smoothness, 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0))); |
| 2254 | } |
| 2255 | |
| 2256 | if (aLight.IsHeadlight) |
| 2257 | { |
| 2258 | aPosition = theInvModelView * aPosition; |
| 2259 | } |
| 2260 | |
| 2261 | myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition)); |
| 2262 | } |
| 2263 | |
| 2264 | if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer |
| 2265 | { |
| 2266 | myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb; |
| 2267 | |
| 2268 | if (!myRaytraceLightSrcTexture->Create (theGlContext)) |
| 2269 | { |
| 2270 | #ifdef RAY_TRACE_PRINT_INFO |
| 2271 | std::cout << "Error: Failed to create light source buffer" << std::endl; |
| 2272 | #endif |
| 2273 | return Standard_False; |
| 2274 | } |
| 2275 | } |
| 2276 | |
| 2277 | if (myRaytraceGeometry.Sources.size() != 0) |
| 2278 | { |
| 2279 | const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed(); |
| 2280 | if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr)) |
| 2281 | { |
| 2282 | #ifdef RAY_TRACE_PRINT_INFO |
| 2283 | std::cout << "Error: Failed to upload light source buffer" << std::endl; |
| 2284 | #endif |
| 2285 | return Standard_False; |
| 2286 | } |
| 2287 | } |
| 2288 | |
| 2289 | return Standard_True; |
| 2290 | } |
| 2291 | |
| 2292 | // ======================================================================= |
| 2293 | // function : updateRaytraceEnvironmentMap |
| 2294 | // purpose : Updates environment map for ray-tracing |
| 2295 | // ======================================================================= |
| 2296 | Standard_Boolean OpenGl_View::updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext) |
| 2297 | { |
| 2298 | Standard_Boolean aResult = Standard_True; |
| 2299 | |
| 2300 | if (!myToUpdateEnvironmentMap) |
| 2301 | { |
| 2302 | return aResult; |
| 2303 | } |
| 2304 | |
| 2305 | Handle(OpenGl_ShaderProgram) aPrograms[] = { myRaytraceProgram, |
| 2306 | myPostFSAAProgram }; |
| 2307 | |
| 2308 | for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx) |
| 2309 | { |
| 2310 | if (!aPrograms[anIdx].IsNull()) |
| 2311 | { |
| 2312 | aResult &= theGlContext->BindProgram (aPrograms[anIdx]); |
| 2313 | |
| 2314 | if (!myTextureEnv.IsNull()) |
| 2315 | { |
| 2316 | myTextureEnv->Bind (theGlContext, |
| 2317 | GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture); |
| 2318 | |
| 2319 | aResult &= aPrograms[anIdx]->SetUniform (theGlContext, |
| 2320 | myUniformLocations[anIdx][OpenGl_RT_uSphereMapEnabled], 1); |
| 2321 | } |
| 2322 | else |
| 2323 | { |
| 2324 | aResult &= aPrograms[anIdx]->SetUniform (theGlContext, |
| 2325 | myUniformLocations[anIdx][OpenGl_RT_uSphereMapEnabled], 0); |
| 2326 | } |
| 2327 | } |
| 2328 | } |
| 2329 | |
| 2330 | myToUpdateEnvironmentMap = Standard_False; |
| 2331 | |
| 2332 | theGlContext->BindProgram (NULL); |
| 2333 | |
| 2334 | return aResult; |
| 2335 | } |
| 2336 | |
| 2337 | // ======================================================================= |
| 2338 | // function : setUniformState |
| 2339 | // purpose : Sets uniform state for the given ray-tracing shader program |
| 2340 | // ======================================================================= |
| 2341 | Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId, |
| 2342 | const Standard_Integer theWinSizeX, |
| 2343 | const Standard_Integer theWinSizeY, |
| 2344 | const Handle(OpenGl_Context)& theGlContext) |
| 2345 | { |
| 2346 | // Get projection state |
| 2347 | OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState; |
| 2348 | |
| 2349 | OpenGl_Mat4 aViewPrjMat; |
| 2350 | OpenGl_Mat4 anUnviewMat; |
| 2351 | OpenGl_Vec3 aOrigins[4]; |
| 2352 | OpenGl_Vec3 aDirects[4]; |
| 2353 | |
| 2354 | updateCamera (myCamera->OrientationMatrixF(), |
| 2355 | aCntxProjectionState.Current(), |
| 2356 | aOrigins, |
| 2357 | aDirects, |
| 2358 | aViewPrjMat, |
| 2359 | anUnviewMat); |
| 2360 | |
| 2361 | Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0 |
| 2362 | ? myRaytraceProgram |
| 2363 | : myPostFSAAProgram; |
| 2364 | |
| 2365 | if (theProgram.IsNull()) |
| 2366 | { |
| 2367 | return Standard_False; |
| 2368 | } |
| 2369 | |
| 2370 | // Set camera state |
| 2371 | theProgram->SetUniform (theGlContext, |
| 2372 | myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]); |
| 2373 | theProgram->SetUniform (theGlContext, |
| 2374 | myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]); |
| 2375 | theProgram->SetUniform (theGlContext, |
| 2376 | myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]); |
| 2377 | theProgram->SetUniform (theGlContext, |
| 2378 | myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]); |
| 2379 | theProgram->SetUniform (theGlContext, |
| 2380 | myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]); |
| 2381 | theProgram->SetUniform (theGlContext, |
| 2382 | myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]); |
| 2383 | theProgram->SetUniform (theGlContext, |
| 2384 | myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]); |
| 2385 | theProgram->SetUniform (theGlContext, |
| 2386 | myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]); |
| 2387 | theProgram->SetUniform (theGlContext, |
| 2388 | myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat); |
| 2389 | theProgram->SetUniform (theGlContext, |
| 2390 | myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat); |
| 2391 | |
| 2392 | // Set ray-tracing intersection parameters |
| 2393 | theProgram->SetUniform (theGlContext, |
| 2394 | myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius); |
| 2395 | theProgram->SetUniform (theGlContext, |
| 2396 | myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon); |
| 2397 | |
| 2398 | const Standard_Integer aLightSourceBufferSize = |
| 2399 | static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size()); |
| 2400 | |
| 2401 | // Set ray-tracing light source parameters |
| 2402 | theProgram->SetUniform (theGlContext, |
| 2403 | myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize); |
| 2404 | theProgram->SetUniform (theGlContext, |
| 2405 | myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient); |
| 2406 | |
| 2407 | // Enable/disable run time rendering effects |
| 2408 | theProgram->SetUniform (theGlContext, |
| 2409 | myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0); |
| 2410 | theProgram->SetUniform (theGlContext, |
| 2411 | myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0); |
| 2412 | |
| 2413 | // Set screen dimensions |
| 2414 | myRaytraceProgram->SetUniform (theGlContext, |
| 2415 | myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX); |
| 2416 | myRaytraceProgram->SetUniform (theGlContext, |
| 2417 | myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY); |
| 2418 | |
| 2419 | if (myRenderParams.IsGlobalIlluminationEnabled) // if Monte-Carlo sampling enabled |
| 2420 | { |
| 2421 | theProgram->SetUniform (theGlContext, |
| 2422 | myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0); |
| 2423 | } |
| 2424 | |
| 2425 | // Set array of 64-bit texture handles |
| 2426 | if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures()) |
| 2427 | { |
| 2428 | const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles(); |
| 2429 | |
| 2430 | theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray], |
| 2431 | static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front())); |
| 2432 | } |
| 2433 | |
| 2434 | // Set background colors (only gradient background supported) |
| 2435 | if (myBgGradientArray != NULL && myBgGradientArray->IsDefined()) |
| 2436 | { |
| 2437 | theProgram->SetUniform (theGlContext, |
| 2438 | myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0)); |
| 2439 | theProgram->SetUniform (theGlContext, |
| 2440 | myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1)); |
| 2441 | } |
| 2442 | else |
| 2443 | { |
| 2444 | const OpenGl_Vec4& aBackColor = myBgColor; |
| 2445 | |
| 2446 | theProgram->SetUniform (theGlContext, |
| 2447 | myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor); |
| 2448 | theProgram->SetUniform (theGlContext, |
| 2449 | myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor); |
| 2450 | } |
| 2451 | |
| 2452 | theProgram->SetUniform (theGlContext, |
| 2453 | myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0); |
| 2454 | |
| 2455 | return Standard_True; |
| 2456 | } |
| 2457 | |
| 2458 | // ======================================================================= |
| 2459 | // function : bindRaytraceTextures |
| 2460 | // purpose : Binds ray-trace textures to corresponding texture units |
| 2461 | // ======================================================================= |
| 2462 | void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext) |
| 2463 | { |
| 2464 | if (myRaytraceParameters.AdaptiveScreenSampling) |
| 2465 | { |
| 2466 | #if !defined(GL_ES_VERSION_2_0) |
| 2467 | theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageLft, |
| 2468 | myRaytraceOutputTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F); |
| 2469 | theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageRgh, |
| 2470 | myRaytraceOutputTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F); |
| 2471 | |
| 2472 | theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage, |
| 2473 | myRaytraceVisualErrorTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I); |
| 2474 | theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage, |
| 2475 | myRaytraceTileOffsetsTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I); |
| 2476 | #endif |
| 2477 | } |
| 2478 | |
| 2479 | mySceneMinPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture); |
| 2480 | mySceneMaxPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture); |
| 2481 | mySceneNodeInfoTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture); |
| 2482 | myGeometryVertexTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture); |
| 2483 | myGeometryNormalTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture); |
| 2484 | myGeometryTexCrdTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture); |
| 2485 | myGeometryTriangTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture); |
| 2486 | mySceneTransformTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture); |
| 2487 | myRaytraceMaterialTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture); |
| 2488 | myRaytraceLightSrcTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture); |
| 2489 | } |
| 2490 | |
| 2491 | // ======================================================================= |
| 2492 | // function : unbindRaytraceTextures |
| 2493 | // purpose : Unbinds ray-trace textures from corresponding texture units |
| 2494 | // ======================================================================= |
| 2495 | void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext) |
| 2496 | { |
| 2497 | mySceneMinPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture); |
| 2498 | mySceneMaxPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture); |
| 2499 | mySceneNodeInfoTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture); |
| 2500 | myGeometryVertexTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture); |
| 2501 | myGeometryNormalTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture); |
| 2502 | myGeometryTexCrdTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture); |
| 2503 | myGeometryTriangTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture); |
| 2504 | mySceneTransformTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture); |
| 2505 | myRaytraceMaterialTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture); |
| 2506 | myRaytraceLightSrcTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture); |
| 2507 | |
| 2508 | theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0); |
| 2509 | } |
| 2510 | |
| 2511 | // ======================================================================= |
| 2512 | // function : runRaytraceShaders |
| 2513 | // purpose : Runs ray-tracing shader programs |
| 2514 | // ======================================================================= |
| 2515 | Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX, |
| 2516 | const Standard_Integer theSizeY, |
| 2517 | Graphic3d_Camera::Projection theProjection, |
| 2518 | OpenGl_FrameBuffer* theReadDrawFbo, |
| 2519 | const Handle(OpenGl_Context)& theGlContext) |
| 2520 | { |
| 2521 | Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram); |
| 2522 | |
| 2523 | aResult &= setUniformState (0, |
| 2524 | theSizeX, |
| 2525 | theSizeY, |
| 2526 | theGlContext); |
| 2527 | |
| 2528 | if (myRaytraceParameters.GlobalIllumination) // path tracing |
| 2529 | { |
| 2530 | aResult &= runPathtrace (theProjection, theReadDrawFbo, theGlContext); |
| 2531 | } |
| 2532 | else // Whitted-style ray-tracing |
| 2533 | { |
| 2534 | aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext); |
| 2535 | } |
| 2536 | |
| 2537 | return aResult; |
| 2538 | } |
| 2539 | |
| 2540 | // ======================================================================= |
| 2541 | // function : runRaytrace |
| 2542 | // purpose : Runs Whitted-style ray-tracing |
| 2543 | // ======================================================================= |
| 2544 | Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX, |
| 2545 | const Standard_Integer theSizeY, |
| 2546 | Graphic3d_Camera::Projection theProjection, |
| 2547 | OpenGl_FrameBuffer* theReadDrawFbo, |
| 2548 | const Handle(OpenGl_Context)& theGlContext) |
| 2549 | { |
| 2550 | Standard_Boolean aResult = Standard_True; |
| 2551 | |
| 2552 | bindRaytraceTextures (theGlContext); |
| 2553 | |
| 2554 | Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer; |
| 2555 | Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer; |
| 2556 | |
| 2557 | // Choose proper set of frame buffers for stereo rendering |
| 2558 | const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye); |
| 2559 | |
| 2560 | if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used |
| 2561 | { |
| 2562 | myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext); |
| 2563 | |
| 2564 | glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth |
| 2565 | } |
| 2566 | |
| 2567 | theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6); |
| 2568 | |
| 2569 | if (myRenderParams.IsAntialiasingEnabled) |
| 2570 | { |
| 2571 | glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer |
| 2572 | |
| 2573 | // bind ray-tracing output image as input |
| 2574 | myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture); |
| 2575 | |
| 2576 | aResult &= theGlContext->BindProgram (myPostFSAAProgram); |
| 2577 | |
| 2578 | aResult &= setUniformState (1 /* FSAA ID */, |
| 2579 | theSizeX, |
| 2580 | theSizeY, |
| 2581 | theGlContext); |
| 2582 | |
| 2583 | // Perform multi-pass adaptive FSAA using ping-pong technique. |
| 2584 | // We use 'FLIPTRI' sampling pattern changing for every pixel |
| 2585 | // (3 additional samples per pixel, the 1st sample is already |
| 2586 | // available from initial ray-traced image). |
| 2587 | for (Standard_Integer anIt = 1; anIt < 4; ++anIt) |
| 2588 | { |
| 2589 | GLfloat aOffsetX = 1.f / theSizeX; |
| 2590 | GLfloat aOffsetY = 1.f / theSizeY; |
| 2591 | |
| 2592 | if (anIt == 1) |
| 2593 | { |
| 2594 | aOffsetX *= -0.55f; |
| 2595 | aOffsetY *= 0.55f; |
| 2596 | } |
| 2597 | else if (anIt == 2) |
| 2598 | { |
| 2599 | aOffsetX *= 0.00f; |
| 2600 | aOffsetY *= -0.55f; |
| 2601 | } |
| 2602 | else if (anIt == 3) |
| 2603 | { |
| 2604 | aOffsetX *= 0.55f; |
| 2605 | aOffsetY *= 0.00f; |
| 2606 | } |
| 2607 | |
| 2608 | aResult &= myPostFSAAProgram->SetUniform (theGlContext, |
| 2609 | myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1); |
| 2610 | aResult &= myPostFSAAProgram->SetUniform (theGlContext, |
| 2611 | myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX); |
| 2612 | aResult &= myPostFSAAProgram->SetUniform (theGlContext, |
| 2613 | myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY); |
| 2614 | |
| 2615 | Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 |
| 2616 | ? myRaytraceFBO2[aFBOIdx] |
| 2617 | : myRaytraceFBO1[aFBOIdx]; |
| 2618 | |
| 2619 | aFramebuffer->BindBuffer (theGlContext); |
| 2620 | |
| 2621 | // perform adaptive FSAA pass |
| 2622 | theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6); |
| 2623 | |
| 2624 | aFramebuffer->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture); |
| 2625 | } |
| 2626 | |
| 2627 | aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx]; |
| 2628 | aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx]; |
| 2629 | |
| 2630 | glEnable (GL_DEPTH_TEST); |
| 2631 | |
| 2632 | // Display filtered image |
| 2633 | theGlContext->BindProgram (myOutImageProgram); |
| 2634 | |
| 2635 | if (theReadDrawFbo != NULL) |
| 2636 | { |
| 2637 | theReadDrawFbo->BindBuffer (theGlContext); |
| 2638 | } |
| 2639 | else |
| 2640 | { |
| 2641 | aRenderImageFramebuffer->UnbindBuffer (theGlContext); |
| 2642 | } |
| 2643 | |
| 2644 | aRenderImageFramebuffer->ColorTexture()->Bind ( |
| 2645 | theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture); |
| 2646 | |
| 2647 | aDepthSourceFramebuffer->DepthStencilTexture()->Bind ( |
| 2648 | theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture); |
| 2649 | |
| 2650 | // copy the output image with depth values |
| 2651 | theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6); |
| 2652 | |
| 2653 | aDepthSourceFramebuffer->DepthStencilTexture()->Unbind ( |
| 2654 | theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture); |
| 2655 | |
| 2656 | aRenderImageFramebuffer->ColorTexture()->Unbind ( |
| 2657 | theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture); |
| 2658 | } |
| 2659 | |
| 2660 | unbindRaytraceTextures (theGlContext); |
| 2661 | |
| 2662 | theGlContext->BindProgram (NULL); |
| 2663 | |
| 2664 | return aResult; |
| 2665 | } |
| 2666 | |
| 2667 | // ======================================================================= |
| 2668 | // function : runPathtrace |
| 2669 | // purpose : Runs path tracing shader |
| 2670 | // ======================================================================= |
| 2671 | Standard_Boolean OpenGl_View::runPathtrace (const Graphic3d_Camera::Projection theProjection, |
| 2672 | OpenGl_FrameBuffer* theReadDrawFbo, |
| 2673 | const Handle(OpenGl_Context)& theGlContext) |
| 2674 | { |
| 2675 | Standard_Boolean aResult = Standard_True; |
| 2676 | |
| 2677 | if (myRaytraceParameters.AdaptiveScreenSampling) |
| 2678 | { |
| 2679 | if (myAccumFrames == 0) |
| 2680 | { |
| 2681 | myTileSampler.Reset(); // reset tile sampler to its initial state |
| 2682 | } |
| 2683 | |
| 2684 | // We upload tile offset texture each 4 frames in order |
| 2685 | // to minimize overhead of additional memory bandwidth. |
| 2686 | // Adaptive sampling is starting after first 10 frames. |
| 2687 | if (myAccumFrames % 4 == 0) |
| 2688 | { |
| 2689 | myTileSampler.Upload (theGlContext, myRaytraceTileOffsetsTexture, myAccumFrames > 10); |
| 2690 | } |
| 2691 | } |
| 2692 | |
| 2693 | bindRaytraceTextures (theGlContext); |
| 2694 | |
| 2695 | Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer; |
| 2696 | Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer; |
| 2697 | Handle(OpenGl_FrameBuffer) anAccumImageFramebuffer; |
| 2698 | |
| 2699 | // Choose proper set of frame buffers for stereo rendering |
| 2700 | const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye); |
| 2701 | |
| 2702 | const Standard_Integer anImageId = (aFBOIdx != 0) |
| 2703 | ? OpenGl_RT_OutputImageRgh |
| 2704 | : OpenGl_RT_OutputImageLft; |
| 2705 | |
| 2706 | aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx]; |
| 2707 | anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx]; |
| 2708 | |
| 2709 | aDepthSourceFramebuffer = aRenderImageFramebuffer; |
| 2710 | |
| 2711 | anAccumImageFramebuffer->ColorTexture()->Bind ( |
| 2712 | theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture); |
| 2713 | |
| 2714 | aRenderImageFramebuffer->BindBuffer (theGlContext); |
| 2715 | |
| 2716 | if (myAccumFrames == 0) |
| 2717 | { |
| 2718 | myRNG.SetSeed(); // start RNG from beginning |
| 2719 | } |
| 2720 | |
| 2721 | // Clear adaptive screen sampling images |
| 2722 | if (myRaytraceParameters.AdaptiveScreenSampling) |
| 2723 | { |
| 2724 | #if !defined(GL_ES_VERSION_2_0) |
| 2725 | if (myAccumFrames == 0) |
| 2726 | { |
| 2727 | theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL); |
| 2728 | } |
| 2729 | |
| 2730 | theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL); |
| 2731 | #endif |
| 2732 | } |
| 2733 | |
| 2734 | // Set frame accumulation weight |
| 2735 | myRaytraceProgram->SetUniform (theGlContext, |
| 2736 | myUniformLocations[0][OpenGl_RT_uSampleWeight], 1.f / (myAccumFrames + 1)); |
| 2737 | |
| 2738 | // Set random number generator seed |
| 2739 | myRaytraceProgram->SetUniform (theGlContext, |
| 2740 | myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2)); |
| 2741 | |
| 2742 | // Set image uniforms for render program |
| 2743 | myRaytraceProgram->SetUniform (theGlContext, |
| 2744 | myUniformLocations[0][OpenGl_RT_uRenderImage], anImageId); |
| 2745 | myRaytraceProgram->SetUniform (theGlContext, |
| 2746 | myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage); |
| 2747 | |
| 2748 | glDisable (GL_DEPTH_TEST); |
| 2749 | |
| 2750 | // Generate for the given RNG seed |
| 2751 | theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6); |
| 2752 | |
| 2753 | // Output accumulated path traced image |
| 2754 | theGlContext->BindProgram (myOutImageProgram); |
| 2755 | |
| 2756 | if (myRaytraceParameters.AdaptiveScreenSampling) |
| 2757 | { |
| 2758 | // Set uniforms for display program |
| 2759 | myOutImageProgram->SetUniform (theGlContext, "uRenderImage", anImageId); |
| 2760 | myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames); |
| 2761 | myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage); |
| 2762 | myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0); |
| 2763 | } |
| 2764 | |
| 2765 | if (theReadDrawFbo != NULL) |
| 2766 | { |
| 2767 | theReadDrawFbo->BindBuffer (theGlContext); |
| 2768 | } |
| 2769 | else |
| 2770 | { |
| 2771 | aRenderImageFramebuffer->UnbindBuffer (theGlContext); |
| 2772 | } |
| 2773 | |
| 2774 | aRenderImageFramebuffer->ColorTexture()->Bind ( |
| 2775 | theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture); |
| 2776 | |
| 2777 | glEnable (GL_DEPTH_TEST); |
| 2778 | |
| 2779 | // Copy accumulated image with correct depth values |
| 2780 | theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6); |
| 2781 | |
| 2782 | aRenderImageFramebuffer->ColorTexture()->Unbind ( |
| 2783 | theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture); |
| 2784 | |
| 2785 | if (myRaytraceParameters.AdaptiveScreenSampling) |
| 2786 | { |
| 2787 | myRaytraceVisualErrorTexture->Bind (theGlContext); |
| 2788 | |
| 2789 | // Download visual error map from the GPU and build |
| 2790 | // adjusted tile offsets for optimal image sampling |
| 2791 | myTileSampler.GrabVarianceMap (theGlContext); |
| 2792 | } |
| 2793 | |
| 2794 | unbindRaytraceTextures (theGlContext); |
| 2795 | |
| 2796 | theGlContext->BindProgram (NULL); |
| 2797 | |
| 2798 | return aResult; |
| 2799 | } |
| 2800 | |
| 2801 | // ======================================================================= |
| 2802 | // function : raytrace |
| 2803 | // purpose : Redraws the window using OpenGL/GLSL ray-tracing |
| 2804 | // ======================================================================= |
| 2805 | Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX, |
| 2806 | const Standard_Integer theSizeY, |
| 2807 | Graphic3d_Camera::Projection theProjection, |
| 2808 | OpenGl_FrameBuffer* theReadDrawFbo, |
| 2809 | const Handle(OpenGl_Context)& theGlContext) |
| 2810 | { |
| 2811 | if (!initRaytraceResources (theGlContext)) |
| 2812 | { |
| 2813 | return Standard_False; |
| 2814 | } |
| 2815 | |
| 2816 | if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext)) |
| 2817 | { |
| 2818 | return Standard_False; |
| 2819 | } |
| 2820 | |
| 2821 | if (!updateRaytraceEnvironmentMap (theGlContext)) |
| 2822 | { |
| 2823 | return Standard_False; |
| 2824 | } |
| 2825 | |
| 2826 | OpenGl_Mat4 aLightSourceMatrix; |
| 2827 | |
| 2828 | // Get inversed model-view matrix for transforming lights |
| 2829 | myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix); |
| 2830 | |
| 2831 | if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext)) |
| 2832 | { |
| 2833 | return Standard_False; |
| 2834 | } |
| 2835 | |
| 2836 | // Generate image using Whitted-style ray-tracing or path tracing |
| 2837 | if (myIsRaytraceDataValid) |
| 2838 | { |
| 2839 | myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS); |
| 2840 | |
| 2841 | if (!myRaytraceGeometry.AcquireTextures (theGlContext)) |
| 2842 | { |
| 2843 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, |
| 2844 | 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures"); |
| 2845 | } |
| 2846 | |
| 2847 | glDisable (GL_BLEND); |
| 2848 | |
| 2849 | const Standard_Boolean aResult = runRaytraceShaders (theSizeX, |
| 2850 | theSizeY, |
| 2851 | theProjection, |
| 2852 | theReadDrawFbo, |
| 2853 | theGlContext); |
| 2854 | |
| 2855 | if (!aResult) |
| 2856 | { |
| 2857 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, |
| 2858 | 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders"); |
| 2859 | } |
| 2860 | |
| 2861 | if (!myRaytraceGeometry.ReleaseTextures (theGlContext)) |
| 2862 | { |
| 2863 | theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, |
| 2864 | 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures"); |
| 2865 | } |
| 2866 | |
| 2867 | myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS); |
| 2868 | } |
| 2869 | |
| 2870 | return Standard_True; |
| 2871 | } |