SceneGraph.cpp 11 KB

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