SceneGraph.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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/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. DynamicArray<SceneNode*, MemoryPoolPtrWrapper<StackMemoryPool>> m_nodesForDeletion;
  46. UpdateSceneNodesCtx()
  47. : m_nodesForDeletion(&SceneGraph::getSingleton().m_framePool)
  48. {
  49. }
  50. };
  51. SceneGraph::SceneGraph()
  52. {
  53. }
  54. SceneGraph::~SceneGraph()
  55. {
  56. while(!m_nodesForRegistration.isEmpty())
  57. {
  58. deleteInstance(SceneMemoryPool::getSingleton(), m_nodesForRegistration.popBack());
  59. }
  60. while(!m_nodes.isEmpty())
  61. {
  62. deleteInstance(SceneMemoryPool::getSingleton(), m_nodes.popBack());
  63. }
  64. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::freeSingleton();
  65. #include <AnKi/Scene/GpuSceneArrays.def.h>
  66. RenderStateBucketContainer::freeSingleton();
  67. }
  68. Error SceneGraph::init(AllocAlignedCallback allocCallback, void* allocCallbackData)
  69. {
  70. SceneMemoryPool::allocateSingleton(allocCallback, allocCallbackData);
  71. m_framePool.init(allocCallback, allocCallbackData, 1_MB, 2.0, 0, true, "SceneGraphFramePool");
  72. // Init the default main camera
  73. m_defaultMainCam = newSceneNode<SceneNode>("mainCamera");
  74. CameraComponent* camc = m_defaultMainCam->newComponent<CameraComponent>();
  75. camc->setPerspective(0.1f, 1000.0f, toRad(60.0f), (1080.0f / 1920.0f) * toRad(60.0f));
  76. m_mainCam = m_defaultMainCam;
  77. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::allocateSingleton(U32(cvarName));
  78. #include <AnKi/Scene/GpuSceneArrays.def.h>
  79. RenderStateBucketContainer::allocateSingleton();
  80. // Construct a few common nodex
  81. if(g_displayStatsCVar > 0)
  82. {
  83. StatsUiNode* statsNode = newSceneNode<StatsUiNode>("_StatsUi");
  84. statsNode->setFpsOnly(g_displayStatsCVar == 1);
  85. }
  86. newSceneNode<DeveloperConsoleUiNode>("_DevConsole");
  87. return Error::kNone;
  88. }
  89. SceneNode& SceneGraph::findSceneNode(const CString& name)
  90. {
  91. SceneNode* node = tryFindSceneNode(name);
  92. ANKI_ASSERT(node);
  93. return *node;
  94. }
  95. SceneNode* SceneGraph::tryFindSceneNode(const CString& name)
  96. {
  97. // Search registered nodes
  98. auto it = m_nodesDict.find(name);
  99. if(it != m_nodesDict.getEnd())
  100. {
  101. return *it;
  102. }
  103. // Didn't found it, search those up for registration
  104. LockGuard lock(m_nodesForRegistrationMtx);
  105. for(SceneNode& node : m_nodesForRegistration)
  106. {
  107. if(node.getName() == name)
  108. {
  109. return &node;
  110. }
  111. }
  112. return nullptr;
  113. }
  114. void SceneGraph::update(Second prevUpdateTime, Second crntTime)
  115. {
  116. ANKI_ASSERT(m_mainCam);
  117. ANKI_TRACE_SCOPED_EVENT(SceneUpdate);
  118. const Second startUpdateTime = HighRezTimer::getCurrentTime();
  119. // Reset the framepool
  120. m_framePool.reset();
  121. // Register new nodes
  122. while(!m_nodesForRegistration.isEmpty())
  123. {
  124. SceneNode* node = m_nodesForRegistration.popFront();
  125. // Add to dict if it has a name
  126. if(node->getName())
  127. {
  128. if(tryFindSceneNode(node->getName()))
  129. {
  130. ANKI_SCENE_LOGE("Node with the same name already exists. New node will not be searchable: %s", node->getName().cstr());
  131. }
  132. else
  133. {
  134. m_nodesDict.emplace(node->getName(), node);
  135. }
  136. }
  137. // Add to list
  138. m_nodes.pushBack(node);
  139. ++m_nodesCount;
  140. }
  141. // Update physics
  142. PhysicsWorld::getSingleton().update(crntTime - prevUpdateTime);
  143. // Before the update wake some threads with dummy work
  144. for(U i = 0; i < 2; i++)
  145. {
  146. CoreThreadJobManager::getSingleton().dispatchTask([]([[maybe_unused]] U32 tid) {});
  147. }
  148. // Update events and scene nodes
  149. UpdateSceneNodesCtx updateCtx;
  150. {
  151. ANKI_TRACE_SCOPED_EVENT(SceneNodesUpdate);
  152. m_events.updateAllEvents(prevUpdateTime, crntTime);
  153. updateCtx.m_crntNode = m_nodes.getBegin();
  154. updateCtx.m_prevUpdateTime = prevUpdateTime;
  155. updateCtx.m_crntTime = crntTime;
  156. for(U i = 0; i < CoreThreadJobManager::getSingleton().getThreadCount(); i++)
  157. {
  158. CoreThreadJobManager::getSingleton().dispatchTask([this, &updateCtx]([[maybe_unused]] U32 tid) {
  159. updateNodes(updateCtx);
  160. });
  161. }
  162. CoreThreadJobManager::getSingleton().waitForAllTasksToFinish();
  163. }
  164. // Cleanup
  165. for(SceneNode* node : updateCtx.m_nodesForDeletion)
  166. {
  167. // Remove from the graph
  168. m_nodes.erase(node);
  169. ANKI_ASSERT(m_nodesCount > 0);
  170. --m_nodesCount;
  171. if(m_mainCam != m_defaultMainCam && m_mainCam == node)
  172. {
  173. m_mainCam = m_defaultMainCam;
  174. }
  175. // Remove from dict
  176. if(node->getName())
  177. {
  178. auto it = m_nodesDict.find(node->getName());
  179. ANKI_ASSERT(it != m_nodesDict.getEnd());
  180. if(*it == node)
  181. {
  182. m_nodesDict.erase(it);
  183. }
  184. }
  185. deleteInstance(SceneMemoryPool::getSingleton(), node);
  186. }
  187. updateCtx.m_nodesForDeletion.destroy();
  188. #define ANKI_CAT_TYPE(arrayName, gpuSceneType, id, cvarName) GpuSceneArrays::arrayName::getSingleton().flush();
  189. #include <AnKi/Scene/GpuSceneArrays.def.h>
  190. g_sceneUpdateTimeStatVar.set((HighRezTimer::getCurrentTime() - startUpdateTime) * 1000.0);
  191. }
  192. void SceneGraph::updateNode(Second prevTime, Second crntTime, SceneNode& node)
  193. {
  194. ANKI_TRACE_INC_COUNTER(SceneNodeUpdated, 1);
  195. // Components update
  196. SceneComponentUpdateInfo componentUpdateInfo(prevTime, crntTime);
  197. componentUpdateInfo.m_framePool = &m_framePool;
  198. Bool atLeastOneComponentUpdated = false;
  199. node.iterateComponents([&](SceneComponent& comp) {
  200. componentUpdateInfo.m_node = &node;
  201. Bool updated = false;
  202. comp.update(componentUpdateInfo, updated);
  203. if(updated)
  204. {
  205. ANKI_TRACE_INC_COUNTER(SceneComponentUpdated, 1);
  206. comp.setTimestamp(GlobalFrameIndex::getSingleton().m_value);
  207. atLeastOneComponentUpdated = true;
  208. }
  209. });
  210. // Update children
  211. node.visitChildrenMaxDepth(0, [&](SceneNode& child) {
  212. updateNode(prevTime, crntTime, child);
  213. return true;
  214. });
  215. // Frame update
  216. {
  217. if(atLeastOneComponentUpdated)
  218. {
  219. node.setComponentMaxTimestamp(GlobalFrameIndex::getSingleton().m_value);
  220. }
  221. else
  222. {
  223. // No components or nothing updated, don't change the timestamp
  224. }
  225. node.frameUpdate(prevTime, crntTime);
  226. }
  227. }
  228. void SceneGraph::updateNodes(UpdateSceneNodesCtx& ctx)
  229. {
  230. ANKI_TRACE_SCOPED_EVENT(SceneNodeUpdate);
  231. IntrusiveList<SceneNode>::ConstIterator end = m_nodes.getEnd();
  232. Bool quit = false;
  233. while(!quit)
  234. {
  235. // Fetch a batch of scene nodes that don't have parent
  236. Array<SceneNode*, kUpdateNodeBatchSize> batch;
  237. U batchSize = 0;
  238. {
  239. LockGuard<SpinLock> lock(ctx.m_crntNodeLock);
  240. while(1)
  241. {
  242. if(batchSize == batch.getSize())
  243. {
  244. break;
  245. }
  246. if(ctx.m_crntNode == end)
  247. {
  248. quit = true;
  249. break;
  250. }
  251. SceneNode& node = *ctx.m_crntNode;
  252. if(node.isMarkedForDeletion())
  253. {
  254. ctx.m_nodesForDeletion.emplaceBack(&node);
  255. }
  256. else if(node.getParent() == nullptr)
  257. {
  258. batch[batchSize++] = &node;
  259. }
  260. else
  261. {
  262. // Ignore
  263. }
  264. ++ctx.m_crntNode;
  265. }
  266. }
  267. // Process nodes
  268. for(U i = 0; i < batchSize; ++i)
  269. {
  270. updateNode(ctx.m_prevUpdateTime, ctx.m_crntTime, *batch[i]);
  271. }
  272. }
  273. }
  274. LightComponent* SceneGraph::getDirectionalLight() const
  275. {
  276. LightComponent* out = (m_dirLights.getSize()) ? m_dirLights[0] : nullptr;
  277. if(out)
  278. {
  279. ANKI_ASSERT(out->getLightComponentType() == LightComponentType::kDirectional);
  280. }
  281. return out;
  282. }
  283. } // end namespace anki