SceneGraph.cpp 12 KB

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