SceneGraph.cpp 8.8 KB

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