SceneGraph.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. // Copyright (C) 2009-2023, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Scene/SceneGraph.h>
  6. #include <AnKi/Scene/Octree.h>
  7. #include <AnKi/Scene/RenderStateBucket.h>
  8. #include <AnKi/Scene/Components/CameraComponent.h>
  9. #include <AnKi/Physics/PhysicsWorld.h>
  10. #include <AnKi/Resource/ResourceManager.h>
  11. #include <AnKi/Renderer/MainRenderer.h>
  12. #include <AnKi/Core/CVarSet.h>
  13. #include <AnKi/Core/StatsSet.h>
  14. #include <AnKi/Util/ThreadHive.h>
  15. #include <AnKi/Util/Tracer.h>
  16. #include <AnKi/Util/HighRezTimer.h>
  17. namespace anki {
  18. static StatCounter g_sceneUpdateTime(StatCategory::kTime, "All scene update", StatFlag::kMilisecond | StatFlag::kShowAverage);
  19. static StatCounter g_sceneVisibilityTime(StatCategory::kTime, "Scene visibility", StatFlag::kMilisecond | StatFlag::kShowAverage);
  20. static StatCounter g_scenePhysicsTime(StatCategory::kTime, "Physics", StatFlag::kMilisecond | StatFlag::kShowAverage);
  21. static NumericCVar<U32> g_octreeMaxDepthCVar(CVarSubsystem::kScene, "OctreeMaxDepth", 5, 2, 10, "The max depth of the octree");
  22. NumericCVar<F32> g_probeEffectiveDistanceCVar(CVarSubsystem::kScene, "ProbeEffectiveDistance", 256.0f, 1.0f, kMaxF32,
  23. "How far various probes can render");
  24. NumericCVar<F32> g_probeShadowEffectiveDistanceCVar(CVarSubsystem::kScene, "ProbeShadowEffectiveDistance", 32.0f, 1.0f, kMaxF32,
  25. "How far to render shadows for the various probes");
  26. // Gpu scene arrays
  27. static NumericCVar<U32> g_minGpuSceneTransformsCVar(CVarSubsystem::kScene, "MinGpuSceneTransforms", 2 * 10 * 1024, 8, 100 * 1024,
  28. "The min number of transforms stored in the GPU scene");
  29. static NumericCVar<U32> g_minGpuSceneMeshesCVar(CVarSubsystem::kScene, "MinGpuSceneMeshes", 8 * 1024, 8, 100 * 1024,
  30. "The min number of meshes stored in the GPU scene");
  31. static NumericCVar<U32> g_minGpuSceneParticleEmittersCVar(CVarSubsystem::kScene, "MinGpuSceneParticleEmitters", 1 * 1024, 8, 100 * 1024,
  32. "The min number of particle emitters stored in the GPU scene");
  33. static NumericCVar<U32> g_minGpuSceneLightsCVar(CVarSubsystem::kScene, "MinGpuSceneLights", 2 * 1024, 8, 100 * 1024,
  34. "The min number of lights stored in the GPU scene");
  35. static NumericCVar<U32> g_minGpuSceneReflectionProbesCVar(CVarSubsystem::kScene, "MinGpuSceneReflectionProbes", 128, 8, 100 * 1024,
  36. "The min number of reflection probes stored in the GPU scene");
  37. static NumericCVar<U32> g_minGpuSceneGlobalIlluminationProbesCVar(CVarSubsystem::kScene, "MinGpuSceneGlobalIlluminationProbes", 128, 8, 100 * 1024,
  38. "The min number of GI probes stored in the GPU scene");
  39. static NumericCVar<U32> g_minGpuSceneDecalsCVar(CVarSubsystem::kScene, "MinGpuSceneDecals", 2 * 1024, 8, 100 * 1024,
  40. "The min number of decals stored in the GPU scene");
  41. static NumericCVar<U32> g_minGpuSceneFogDensityVolumesCVar(CVarSubsystem::kScene, "MinGpuSceneFogDensityVolumes", 512, 8, 100 * 1024,
  42. "The min number fog density volumes stored in the GPU scene");
  43. static NumericCVar<U32> g_minGpuSceneRenderablesCVar(CVarSubsystem::kScene, "MinGpuSceneRenderables", 10 * 1024, 8, 100 * 1024,
  44. "The min number of renderables stored in the GPU scene");
  45. constexpr U32 kUpdateNodeBatchSize = 10;
  46. class SceneGraph::UpdateSceneNodesCtx
  47. {
  48. public:
  49. SceneGraph* m_scene = nullptr;
  50. IntrusiveList<SceneNode>::Iterator m_crntNode;
  51. SpinLock m_crntNodeLock;
  52. Second m_prevUpdateTime;
  53. Second m_crntTime;
  54. };
  55. SceneGraph::SceneGraph()
  56. {
  57. }
  58. SceneGraph::~SceneGraph()
  59. {
  60. [[maybe_unused]] const Error err = iterateSceneNodes([&](SceneNode& s) -> Error {
  61. s.setMarkedForDeletion();
  62. return Error::kNone;
  63. });
  64. deleteNodesMarkedForDeletion();
  65. if(m_octree)
  66. {
  67. deleteInstance(SceneMemoryPool::getSingleton(), m_octree);
  68. }
  69. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::freeSingleton();
  70. #include <AnKi/Scene/GpuSceneArrays.def.h>
  71. RenderStateBucketContainer::freeSingleton();
  72. }
  73. Error SceneGraph::init(AllocAlignedCallback allocCallback, void* allocCallbackData)
  74. {
  75. SceneMemoryPool::allocateSingleton(allocCallback, allocCallbackData);
  76. m_framePool.init(allocCallback, allocCallbackData, 1_MB, 2.0, 0, true, ANKI_SAFE_ALIGNMENT, "SceneGraphFramePool");
  77. m_octree = newInstance<Octree>(SceneMemoryPool::getSingleton());
  78. m_octree->init(m_sceneMin, m_sceneMax, g_octreeMaxDepthCVar.get());
  79. // Init the default main camera
  80. ANKI_CHECK(newSceneNode<SceneNode>("mainCamera", m_defaultMainCam));
  81. CameraComponent* camc = m_defaultMainCam->newComponent<CameraComponent>();
  82. camc->setPerspective(0.1f, 1000.0f, toRad(60.0f), (1080.0f / 1920.0f) * toRad(60.0f));
  83. m_mainCam = m_defaultMainCam;
  84. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::allocateSingleton(cvarName.get());
  85. #include <AnKi/Scene/GpuSceneArrays.def.h>
  86. RenderStateBucketContainer::allocateSingleton();
  87. return Error::kNone;
  88. }
  89. Error SceneGraph::registerNode(SceneNode* node)
  90. {
  91. ANKI_ASSERT(node);
  92. // Add to dict if it has a name
  93. if(node->getName())
  94. {
  95. if(tryFindSceneNode(node->getName()))
  96. {
  97. ANKI_SCENE_LOGE("Node with the same name already exists");
  98. return Error::kUserData;
  99. }
  100. m_nodesDict.emplace(node->getName(), node);
  101. }
  102. // Add to vector
  103. m_nodes.pushBack(node);
  104. ++m_nodesCount;
  105. return Error::kNone;
  106. }
  107. void SceneGraph::unregisterNode(SceneNode* node)
  108. {
  109. // Remove from the graph
  110. m_nodes.erase(node);
  111. --m_nodesCount;
  112. if(m_mainCam != m_defaultMainCam && m_mainCam == node)
  113. {
  114. m_mainCam = m_defaultMainCam;
  115. }
  116. // Remove from dict
  117. if(node->getName())
  118. {
  119. auto it = m_nodesDict.find(node->getName());
  120. ANKI_ASSERT(it != m_nodesDict.getEnd());
  121. m_nodesDict.erase(it);
  122. }
  123. }
  124. SceneNode& SceneGraph::findSceneNode(const CString& name)
  125. {
  126. SceneNode* node = tryFindSceneNode(name);
  127. ANKI_ASSERT(node);
  128. return *node;
  129. }
  130. SceneNode* SceneGraph::tryFindSceneNode(const CString& name)
  131. {
  132. auto it = m_nodesDict.find(name);
  133. return (it == m_nodesDict.getEnd()) ? nullptr : (*it);
  134. }
  135. void SceneGraph::deleteNodesMarkedForDeletion()
  136. {
  137. /// Delete all nodes pending deletion. At this point all scene threads
  138. /// should have finished their tasks
  139. while(m_objectsMarkedForDeletionCount.load() > 0)
  140. {
  141. [[maybe_unused]] Bool found = false;
  142. auto it = m_nodes.begin();
  143. auto end = m_nodes.end();
  144. for(; it != end; ++it)
  145. {
  146. SceneNode& node = *it;
  147. if(node.getMarkedForDeletion())
  148. {
  149. // Delete node
  150. unregisterNode(&node);
  151. deleteInstance(SceneMemoryPool::getSingleton(), &node);
  152. m_objectsMarkedForDeletionCount.fetchSub(1);
  153. found = true;
  154. break;
  155. }
  156. }
  157. ANKI_ASSERT(found && "Something is wrong with marked for deletion");
  158. }
  159. }
  160. Error SceneGraph::update(Second prevUpdateTime, Second crntTime)
  161. {
  162. ANKI_ASSERT(m_mainCam);
  163. ANKI_TRACE_SCOPED_EVENT(SceneUpdate);
  164. const Second startUpdateTime = HighRezTimer::getCurrentTime();
  165. // Reset the framepool
  166. m_framePool.reset();
  167. // Delete stuff
  168. {
  169. ANKI_TRACE_SCOPED_EVENT(SceneRemoveMarkedForDeletion);
  170. const Bool fullCleanup = m_objectsMarkedForDeletionCount.load() != 0;
  171. m_events.deleteEventsMarkedForDeletion(fullCleanup);
  172. deleteNodesMarkedForDeletion();
  173. }
  174. // Update
  175. {
  176. ANKI_TRACE_SCOPED_EVENT(ScenePhysics);
  177. const Second physicsUpdate = HighRezTimer::getCurrentTime();
  178. PhysicsWorld::getSingleton().update(crntTime - prevUpdateTime);
  179. g_scenePhysicsTime.set((HighRezTimer::getCurrentTime() - physicsUpdate) * 1000.0);
  180. }
  181. {
  182. ANKI_TRACE_SCOPED_EVENT(SceneNodesUpdate);
  183. ANKI_CHECK(m_events.updateAllEvents(prevUpdateTime, crntTime));
  184. // Then the rest
  185. Array<ThreadHiveTask, ThreadHive::kMaxThreads> tasks;
  186. UpdateSceneNodesCtx updateCtx;
  187. updateCtx.m_scene = this;
  188. updateCtx.m_crntNode = m_nodes.getBegin();
  189. updateCtx.m_prevUpdateTime = prevUpdateTime;
  190. updateCtx.m_crntTime = crntTime;
  191. for(U i = 0; i < CoreThreadHive::getSingleton().getThreadCount(); i++)
  192. {
  193. tasks[i] = ANKI_THREAD_HIVE_TASK(
  194. {
  195. if(self->m_scene->updateNodes(*self))
  196. {
  197. ANKI_SCENE_LOGF("Will not recover");
  198. }
  199. },
  200. &updateCtx, nullptr, nullptr);
  201. }
  202. CoreThreadHive::getSingleton().submitTasks(&tasks[0], CoreThreadHive::getSingleton().getThreadCount());
  203. CoreThreadHive::getSingleton().waitAllTasks();
  204. }
  205. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::getSingleton().flush();
  206. #include <AnKi/Scene/GpuSceneArrays.def.h>
  207. g_sceneUpdateTime.set((HighRezTimer::getCurrentTime() - startUpdateTime) * 1000.0);
  208. return Error::kNone;
  209. }
  210. void SceneGraph::doVisibilityTests(RenderQueue& rqueue)
  211. {
  212. const Second startTime = HighRezTimer::getCurrentTime();
  213. doVisibilityTests(*m_mainCam, *this, rqueue);
  214. g_sceneVisibilityTime.set((HighRezTimer::getCurrentTime() - startTime) * 1000.0);
  215. }
  216. Error SceneGraph::updateNode(Second prevTime, Second crntTime, SceneNode& node)
  217. {
  218. ANKI_TRACE_INC_COUNTER(SceneNodeUpdated, 1);
  219. Error err = Error::kNone;
  220. // Components update
  221. SceneComponentUpdateInfo componentUpdateInfo(prevTime, crntTime);
  222. componentUpdateInfo.m_framePool = &m_framePool;
  223. Bool atLeastOneComponentUpdated = false;
  224. node.iterateComponents([&](SceneComponent& comp) {
  225. if(err)
  226. {
  227. return;
  228. }
  229. componentUpdateInfo.m_node = &node;
  230. Bool updated = false;
  231. err = comp.updateReal(componentUpdateInfo, updated);
  232. if(updated)
  233. {
  234. ANKI_TRACE_INC_COUNTER(SceneComponentUpdated, 1);
  235. comp.setTimestamp(GlobalFrameIndex::getSingleton().m_value);
  236. atLeastOneComponentUpdated = true;
  237. }
  238. });
  239. // Update children
  240. if(!err)
  241. {
  242. err = node.visitChildrenMaxDepth(0, [&](SceneNode& child) -> Error {
  243. return updateNode(prevTime, crntTime, child);
  244. });
  245. }
  246. // Frame update
  247. if(!err)
  248. {
  249. if(atLeastOneComponentUpdated)
  250. {
  251. node.setComponentMaxTimestamp(GlobalFrameIndex::getSingleton().m_value);
  252. }
  253. else
  254. {
  255. // No components or nothing updated, don't change the timestamp
  256. }
  257. err = node.frameUpdate(prevTime, crntTime);
  258. }
  259. return err;
  260. }
  261. Error SceneGraph::updateNodes(UpdateSceneNodesCtx& ctx)
  262. {
  263. ANKI_TRACE_SCOPED_EVENT(SceneNodeUpdate);
  264. IntrusiveList<SceneNode>::ConstIterator end = m_nodes.getEnd();
  265. Bool quit = false;
  266. Error err = Error::kNone;
  267. while(!quit && !err)
  268. {
  269. // Fetch a batch of scene nodes that don't have parent
  270. Array<SceneNode*, kUpdateNodeBatchSize> batch;
  271. U batchSize = 0;
  272. {
  273. LockGuard<SpinLock> lock(ctx.m_crntNodeLock);
  274. while(1)
  275. {
  276. if(batchSize == batch.getSize())
  277. {
  278. break;
  279. }
  280. if(ctx.m_crntNode == end)
  281. {
  282. quit = true;
  283. break;
  284. }
  285. SceneNode& node = *ctx.m_crntNode;
  286. if(node.getParent() == nullptr)
  287. {
  288. batch[batchSize++] = &node;
  289. }
  290. ++ctx.m_crntNode;
  291. }
  292. }
  293. // Process nodes
  294. for(U i = 0; i < batchSize && !err; ++i)
  295. {
  296. err = updateNode(ctx.m_prevUpdateTime, ctx.m_crntTime, *batch[i]);
  297. }
  298. }
  299. return err;
  300. }
  301. } // end namespace anki