SceneGraph.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. // Copyright (C) 2009-2022, 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/CameraNode.h>
  7. #include <AnKi/Scene/PhysicsDebugNode.h>
  8. #include <AnKi/Scene/ModelNode.h>
  9. #include <AnKi/Scene/Octree.h>
  10. #include <AnKi/Scene/Components/FrustumComponent.h>
  11. #include <AnKi/Physics/PhysicsWorld.h>
  12. #include <AnKi/Resource/ResourceManager.h>
  13. #include <AnKi/Renderer/MainRenderer.h>
  14. #include <AnKi/Core/ConfigSet.h>
  15. #include <AnKi/Util/ThreadHive.h>
  16. #include <AnKi/Util/Tracer.h>
  17. #include <AnKi/Util/HighRezTimer.h>
  18. namespace anki {
  19. const U NODE_UPDATE_BATCH = 10;
  20. class SceneGraph::UpdateSceneNodesCtx
  21. {
  22. public:
  23. SceneGraph* m_scene = nullptr;
  24. IntrusiveList<SceneNode>::Iterator m_crntNode;
  25. SpinLock m_crntNodeLock;
  26. Second m_prevUpdateTime;
  27. Second m_crntTime;
  28. };
  29. SceneGraph::SceneGraph()
  30. {
  31. }
  32. SceneGraph::~SceneGraph()
  33. {
  34. [[maybe_unused]] const Error err = iterateSceneNodes([&](SceneNode& s) -> Error {
  35. s.setMarkedForDeletion();
  36. return Error::kNone;
  37. });
  38. deleteNodesMarkedForDeletion();
  39. if(m_octree)
  40. {
  41. m_alloc.deleteInstance(m_octree);
  42. }
  43. }
  44. Error SceneGraph::init(AllocAlignedCallback allocCb, void* allocCbData, ThreadHive* threadHive,
  45. ResourceManager* resources, Input* input, ScriptManager* scriptManager, UiManager* uiManager,
  46. ConfigSet* config, const Timestamp* globalTimestamp)
  47. {
  48. m_globalTimestamp = globalTimestamp;
  49. m_threadHive = threadHive;
  50. m_resources = resources;
  51. m_gr = &m_resources->getGrManager();
  52. m_physics = &m_resources->getPhysicsWorld();
  53. m_input = input;
  54. m_scriptManager = scriptManager;
  55. m_uiManager = uiManager;
  56. m_config = config;
  57. m_alloc = SceneAllocator<U8>(allocCb, allocCbData);
  58. m_frameAlloc = SceneFrameAllocator<U8>(allocCb, allocCbData, 1 * 1024 * 1024);
  59. ANKI_CHECK(m_events.init(this));
  60. m_octree = m_alloc.newInstance<Octree>(m_alloc);
  61. m_octree->init(m_sceneMin, m_sceneMax, m_config->getSceneOctreeMaxDepth());
  62. // Init the default main camera
  63. ANKI_CHECK(newSceneNode<PerspectiveCameraNode>("mainCamera", m_defaultMainCam));
  64. m_defaultMainCam->getFirstComponentOfType<FrustumComponent>().setPerspective(0.1f, 1000.0f, toRad(60.0f),
  65. (1080.0f / 1920.0f) * toRad(60.0f));
  66. m_mainCam = m_defaultMainCam;
  67. // Create a special node for debugging the physics world
  68. PhysicsDebugNode* pnode;
  69. ANKI_CHECK(newSceneNode<PhysicsDebugNode>("_physicsDebugNode", pnode));
  70. // Other
  71. ANKI_CHECK(m_debugDrawer.init(&getResourceManager()));
  72. return Error::kNone;
  73. }
  74. Error SceneGraph::registerNode(SceneNode* node)
  75. {
  76. ANKI_ASSERT(node);
  77. // Add to dict if it has a name
  78. if(node->getName())
  79. {
  80. if(tryFindSceneNode(node->getName()))
  81. {
  82. ANKI_SCENE_LOGE("Node with the same name already exists");
  83. return Error::kUserData;
  84. }
  85. m_nodesDict.emplace(m_alloc, node->getName(), node);
  86. }
  87. // Add to vector
  88. m_nodes.pushBack(node);
  89. ++m_nodesCount;
  90. return Error::kNone;
  91. }
  92. void SceneGraph::unregisterNode(SceneNode* node)
  93. {
  94. // Remove from the graph
  95. m_nodes.erase(node);
  96. --m_nodesCount;
  97. if(m_mainCam != m_defaultMainCam && m_mainCam == node)
  98. {
  99. m_mainCam = m_defaultMainCam;
  100. }
  101. // Remove from dict
  102. if(node->getName())
  103. {
  104. auto it = m_nodesDict.find(node->getName());
  105. ANKI_ASSERT(it != m_nodesDict.getEnd());
  106. m_nodesDict.erase(m_alloc, it);
  107. }
  108. }
  109. SceneNode& SceneGraph::findSceneNode(const CString& name)
  110. {
  111. SceneNode* node = tryFindSceneNode(name);
  112. ANKI_ASSERT(node);
  113. return *node;
  114. }
  115. SceneNode* SceneGraph::tryFindSceneNode(const CString& name)
  116. {
  117. auto it = m_nodesDict.find(name);
  118. return (it == m_nodesDict.getEnd()) ? nullptr : (*it);
  119. }
  120. void SceneGraph::deleteNodesMarkedForDeletion()
  121. {
  122. /// Delete all nodes pending deletion. At this point all scene threads
  123. /// should have finished their tasks
  124. while(m_objectsMarkedForDeletionCount.load() > 0)
  125. {
  126. [[maybe_unused]] Bool found = false;
  127. auto it = m_nodes.begin();
  128. auto end = m_nodes.end();
  129. for(; it != end; ++it)
  130. {
  131. SceneNode& node = *it;
  132. if(node.getMarkedForDeletion())
  133. {
  134. // Delete node
  135. unregisterNode(&node);
  136. m_alloc.deleteInstance(&node);
  137. m_objectsMarkedForDeletionCount.fetchSub(1);
  138. found = true;
  139. break;
  140. }
  141. }
  142. ANKI_ASSERT(found && "Something is wrong with marked for deletion");
  143. }
  144. }
  145. Error SceneGraph::update(Second prevUpdateTime, Second crntTime)
  146. {
  147. ANKI_ASSERT(m_mainCam);
  148. ANKI_TRACE_SCOPED_EVENT(SCENE_UPDATE);
  149. m_stats.m_updateTime = HighRezTimer::getCurrentTime();
  150. m_timestamp = *m_globalTimestamp;
  151. ANKI_ASSERT(m_timestamp > 0);
  152. // Reset the framepool
  153. m_frameAlloc.getMemoryPool().reset();
  154. // Delete stuff
  155. {
  156. ANKI_TRACE_SCOPED_EVENT(SCENE_MARKED_FOR_DELETION);
  157. const Bool fullCleanup = m_objectsMarkedForDeletionCount.load() != 0;
  158. m_events.deleteEventsMarkedForDeletion(fullCleanup);
  159. deleteNodesMarkedForDeletion();
  160. }
  161. // Update
  162. {
  163. ANKI_TRACE_SCOPED_EVENT(SCENE_PHYSICS_UPDATE);
  164. m_stats.m_physicsUpdate = HighRezTimer::getCurrentTime();
  165. m_physics->update(crntTime - prevUpdateTime);
  166. m_stats.m_physicsUpdate = HighRezTimer::getCurrentTime() - m_stats.m_physicsUpdate;
  167. }
  168. {
  169. ANKI_TRACE_SCOPED_EVENT(SCENE_NODES_UPDATE);
  170. ANKI_CHECK(m_events.updateAllEvents(prevUpdateTime, crntTime));
  171. // Then the rest
  172. Array<ThreadHiveTask, ThreadHive::kMaxThreads> tasks;
  173. UpdateSceneNodesCtx updateCtx;
  174. updateCtx.m_scene = this;
  175. updateCtx.m_crntNode = m_nodes.getBegin();
  176. updateCtx.m_prevUpdateTime = prevUpdateTime;
  177. updateCtx.m_crntTime = crntTime;
  178. for(U i = 0; i < m_threadHive->getThreadCount(); i++)
  179. {
  180. tasks[i] = ANKI_THREAD_HIVE_TASK(
  181. {
  182. if(self->m_scene->updateNodes(*self))
  183. {
  184. ANKI_SCENE_LOGF("Will not recover");
  185. }
  186. },
  187. &updateCtx, nullptr, nullptr);
  188. }
  189. m_threadHive->submitTasks(&tasks[0], m_threadHive->getThreadCount());
  190. m_threadHive->waitAllTasks();
  191. }
  192. m_stats.m_updateTime = HighRezTimer::getCurrentTime() - m_stats.m_updateTime;
  193. return Error::kNone;
  194. }
  195. void SceneGraph::doVisibilityTests(RenderQueue& rqueue)
  196. {
  197. m_stats.m_visibilityTestsTime = HighRezTimer::getCurrentTime();
  198. doVisibilityTests(*m_mainCam, *this, rqueue);
  199. m_stats.m_visibilityTestsTime = HighRezTimer::getCurrentTime() - m_stats.m_visibilityTestsTime;
  200. }
  201. Error SceneGraph::updateNode(Second prevTime, Second crntTime, SceneNode& node)
  202. {
  203. ANKI_TRACE_INC_COUNTER(SCENE_NODES_UPDATED, 1);
  204. Error err = Error::kNone;
  205. // Components update
  206. SceneComponentUpdateInfo componentUpdateInfo(prevTime, crntTime);
  207. Timestamp componentTimestamp = 0;
  208. Bool atLeastOneComponentUpdated = false;
  209. node.iterateComponents([&](SceneComponent& comp, Bool isFeedbackComponent) {
  210. if(err)
  211. {
  212. return;
  213. }
  214. Bool updated = false;
  215. if(!atLeastOneComponentUpdated && isFeedbackComponent)
  216. {
  217. // Skip feedback component if prior components didn't got updated
  218. }
  219. else
  220. {
  221. componentUpdateInfo.m_node = &node;
  222. err = comp.update(componentUpdateInfo, updated);
  223. }
  224. if(updated)
  225. {
  226. ANKI_TRACE_INC_COUNTER(SCENE_COMPONENTS_UPDATED, 1);
  227. comp.setTimestamp(node.getSceneGraph().m_timestamp);
  228. componentTimestamp = max(componentTimestamp, node.getSceneGraph().m_timestamp);
  229. ANKI_ASSERT(componentTimestamp > 0);
  230. atLeastOneComponentUpdated = true;
  231. }
  232. });
  233. // Update children
  234. if(!err)
  235. {
  236. err = node.visitChildrenMaxDepth(0, [&](SceneNode& child) -> Error {
  237. return updateNode(prevTime, crntTime, child);
  238. });
  239. }
  240. // Frame update
  241. if(!err)
  242. {
  243. if(componentTimestamp != 0)
  244. {
  245. node.setComponentMaxTimestamp(componentTimestamp);
  246. }
  247. else
  248. {
  249. // No components or nothing updated, don't change the timestamp
  250. }
  251. err = node.frameUpdate(prevTime, crntTime);
  252. }
  253. return err;
  254. }
  255. Error SceneGraph::updateNodes(UpdateSceneNodesCtx& ctx) const
  256. {
  257. ANKI_TRACE_SCOPED_EVENT(SCENE_NODES_UPDATE);
  258. IntrusiveList<SceneNode>::ConstIterator end = m_nodes.getEnd();
  259. Bool quit = false;
  260. Error err = Error::kNone;
  261. while(!quit && !err)
  262. {
  263. // Fetch a batch of scene nodes that don't have parent
  264. Array<SceneNode*, NODE_UPDATE_BATCH> batch;
  265. U batchSize = 0;
  266. {
  267. LockGuard<SpinLock> lock(ctx.m_crntNodeLock);
  268. while(1)
  269. {
  270. if(batchSize == batch.getSize())
  271. {
  272. break;
  273. }
  274. if(ctx.m_crntNode == end)
  275. {
  276. quit = true;
  277. break;
  278. }
  279. SceneNode& node = *ctx.m_crntNode;
  280. if(node.getParent() == nullptr)
  281. {
  282. batch[batchSize++] = &node;
  283. }
  284. ++ctx.m_crntNode;
  285. }
  286. }
  287. // Process nodes
  288. for(U i = 0; i < batchSize && !err; ++i)
  289. {
  290. err = updateNode(ctx.m_prevUpdateTime, ctx.m_crntTime, *batch[i]);
  291. }
  292. }
  293. return err;
  294. }
  295. } // end namespace anki