SceneGraph.cpp 9.0 KB

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