Octree.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Core/Thread.h"
  27. #include "../Core/WorkQueue.h"
  28. #include "../Graphics/DebugRenderer.h"
  29. #include "../Graphics/Graphics.h"
  30. #include "../Graphics/Octree.h"
  31. #include "../IO/Log.h"
  32. #include "../Scene/Scene.h"
  33. #include "../Scene/SceneEvents.h"
  34. #include "../DebugNew.h"
  35. #ifdef _MSC_VER
  36. #pragma warning(disable:4355)
  37. #endif
  38. namespace Atomic
  39. {
  40. static const float DEFAULT_OCTREE_SIZE = 1000.0f;
  41. static const int DEFAULT_OCTREE_LEVELS = 8;
  42. extern const char* SUBSYSTEM_CATEGORY;
  43. void UpdateDrawablesWork(const WorkItem* item, unsigned threadIndex)
  44. {
  45. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  46. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  47. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  48. while (start != end)
  49. {
  50. Drawable* drawable = *start;
  51. if (drawable)
  52. drawable->Update(frame);
  53. ++start;
  54. }
  55. }
  56. inline bool CompareRayQueryResults(const RayQueryResult& lhs, const RayQueryResult& rhs)
  57. {
  58. return lhs.distance_ < rhs.distance_;
  59. }
  60. Octant::Octant(const BoundingBox& box, unsigned level, Octant* parent, Octree* root, unsigned index) :
  61. level_(level),
  62. numDrawables_(0),
  63. parent_(parent),
  64. root_(root),
  65. index_(index)
  66. {
  67. Initialize(box);
  68. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  69. children_[i] = 0;
  70. }
  71. Octant::~Octant()
  72. {
  73. if (root_)
  74. {
  75. // Remove the drawables (if any) from this octant to the root octant
  76. for (PODVector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  77. {
  78. (*i)->SetOctant(root_);
  79. root_->drawables_.Push(*i);
  80. root_->QueueUpdate(*i);
  81. }
  82. drawables_.Clear();
  83. numDrawables_ = 0;
  84. }
  85. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  86. DeleteChild(i);
  87. }
  88. Octant* Octant::GetOrCreateChild(unsigned index)
  89. {
  90. if (children_[index])
  91. return children_[index];
  92. Vector3 newMin = worldBoundingBox_.min_;
  93. Vector3 newMax = worldBoundingBox_.max_;
  94. Vector3 oldCenter = worldBoundingBox_.Center();
  95. if (index & 1)
  96. newMin.x_ = oldCenter.x_;
  97. else
  98. newMax.x_ = oldCenter.x_;
  99. if (index & 2)
  100. newMin.y_ = oldCenter.y_;
  101. else
  102. newMax.y_ = oldCenter.y_;
  103. if (index & 4)
  104. newMin.z_ = oldCenter.z_;
  105. else
  106. newMax.z_ = oldCenter.z_;
  107. children_[index] = new Octant(BoundingBox(newMin, newMax), level_ + 1, this, root_, index);
  108. return children_[index];
  109. }
  110. void Octant::DeleteChild(unsigned index)
  111. {
  112. assert(index < NUM_OCTANTS);
  113. delete children_[index];
  114. children_[index] = 0;
  115. }
  116. void Octant::InsertDrawable(Drawable* drawable)
  117. {
  118. const BoundingBox& box = drawable->GetWorldBoundingBox();
  119. // If root octant, insert all non-occludees here, so that octant occlusion does not hide the drawable.
  120. // Also if drawable is outside the root octant bounds, insert to root
  121. bool insertHere;
  122. if (this == root_)
  123. insertHere = !drawable->IsOccludee() || cullingBox_.IsInside(box) != INSIDE || CheckDrawableFit(box);
  124. else
  125. insertHere = CheckDrawableFit(box);
  126. if (insertHere)
  127. {
  128. Octant* oldOctant = drawable->octant_;
  129. if (oldOctant != this)
  130. {
  131. // Add first, then remove, because drawable count going to zero deletes the octree branch in question
  132. AddDrawable(drawable);
  133. if (oldOctant)
  134. oldOctant->RemoveDrawable(drawable, false);
  135. }
  136. }
  137. else
  138. {
  139. Vector3 boxCenter = box.Center();
  140. unsigned x = boxCenter.x_ < center_.x_ ? 0 : 1;
  141. unsigned y = boxCenter.y_ < center_.y_ ? 0 : 2;
  142. unsigned z = boxCenter.z_ < center_.z_ ? 0 : 4;
  143. GetOrCreateChild(x + y + z)->InsertDrawable(drawable);
  144. }
  145. }
  146. bool Octant::CheckDrawableFit(const BoundingBox& box) const
  147. {
  148. Vector3 boxSize = box.Size();
  149. // If max split level, size always OK, otherwise check that box is at least half size of octant
  150. if (level_ >= root_->GetNumLevels() || boxSize.x_ >= halfSize_.x_ || boxSize.y_ >= halfSize_.y_ ||
  151. boxSize.z_ >= halfSize_.z_)
  152. return true;
  153. // Also check if the box can not fit a child octant's culling box, in that case size OK (must insert here)
  154. else
  155. {
  156. if (box.min_.x_ <= worldBoundingBox_.min_.x_ - 0.5f * halfSize_.x_ ||
  157. box.max_.x_ >= worldBoundingBox_.max_.x_ + 0.5f * halfSize_.x_ ||
  158. box.min_.y_ <= worldBoundingBox_.min_.y_ - 0.5f * halfSize_.y_ ||
  159. box.max_.y_ >= worldBoundingBox_.max_.y_ + 0.5f * halfSize_.y_ ||
  160. box.min_.z_ <= worldBoundingBox_.min_.z_ - 0.5f * halfSize_.z_ ||
  161. box.max_.z_ >= worldBoundingBox_.max_.z_ + 0.5f * halfSize_.z_)
  162. return true;
  163. }
  164. // Bounding box too small, should create a child octant
  165. return false;
  166. }
  167. void Octant::ResetRoot()
  168. {
  169. root_ = 0;
  170. // The whole octree is being destroyed, just detach the drawables
  171. for (PODVector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  172. (*i)->SetOctant(0);
  173. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  174. {
  175. if (children_[i])
  176. children_[i]->ResetRoot();
  177. }
  178. }
  179. void Octant::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  180. {
  181. if (debug && debug->IsInside(worldBoundingBox_))
  182. {
  183. debug->AddBoundingBox(worldBoundingBox_, Color(0.25f, 0.25f, 0.25f), depthTest);
  184. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  185. {
  186. if (children_[i])
  187. children_[i]->DrawDebugGeometry(debug, depthTest);
  188. }
  189. }
  190. }
  191. void Octant::Initialize(const BoundingBox& box)
  192. {
  193. worldBoundingBox_ = box;
  194. center_ = box.Center();
  195. halfSize_ = 0.5f * box.Size();
  196. cullingBox_ = BoundingBox(worldBoundingBox_.min_ - halfSize_, worldBoundingBox_.max_ + halfSize_);
  197. }
  198. void Octant::GetDrawablesInternal(OctreeQuery& query, bool inside) const
  199. {
  200. if (this != root_)
  201. {
  202. Intersection res = query.TestOctant(cullingBox_, inside);
  203. if (res == INSIDE)
  204. inside = true;
  205. else if (res == OUTSIDE)
  206. {
  207. // Fully outside, so cull this octant, its children & drawables
  208. return;
  209. }
  210. }
  211. if (drawables_.Size())
  212. {
  213. Drawable** start = const_cast<Drawable**>(&drawables_[0]);
  214. Drawable** end = start + drawables_.Size();
  215. query.TestDrawables(start, end, inside);
  216. }
  217. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  218. {
  219. if (children_[i])
  220. children_[i]->GetDrawablesInternal(query, inside);
  221. }
  222. }
  223. void Octant::GetDrawablesInternal(RayOctreeQuery& query) const
  224. {
  225. float octantDist = query.ray_.HitDistance(cullingBox_);
  226. if (octantDist >= query.maxDistance_)
  227. return;
  228. if (drawables_.Size())
  229. {
  230. Drawable** start = const_cast<Drawable**>(&drawables_[0]);
  231. Drawable** end = start + drawables_.Size();
  232. while (start != end)
  233. {
  234. Drawable* drawable = *start++;
  235. if ((drawable->GetDrawableFlags() & query.drawableFlags_) && (drawable->GetViewMask() & query.viewMask_))
  236. drawable->ProcessRayQuery(query, query.result_);
  237. }
  238. }
  239. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  240. {
  241. if (children_[i])
  242. children_[i]->GetDrawablesInternal(query);
  243. }
  244. }
  245. void Octant::GetDrawablesOnlyInternal(RayOctreeQuery& query, PODVector<Drawable*>& drawables) const
  246. {
  247. float octantDist = query.ray_.HitDistance(cullingBox_);
  248. if (octantDist >= query.maxDistance_)
  249. return;
  250. if (drawables_.Size())
  251. {
  252. Drawable** start = const_cast<Drawable**>(&drawables_[0]);
  253. Drawable** end = start + drawables_.Size();
  254. while (start != end)
  255. {
  256. Drawable* drawable = *start++;
  257. if ((drawable->GetDrawableFlags() & query.drawableFlags_) && (drawable->GetViewMask() & query.viewMask_))
  258. drawables.Push(drawable);
  259. }
  260. }
  261. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  262. {
  263. if (children_[i])
  264. children_[i]->GetDrawablesOnlyInternal(query, drawables);
  265. }
  266. }
  267. Octree::Octree(Context* context) :
  268. Component(context),
  269. Octant(BoundingBox(-DEFAULT_OCTREE_SIZE, DEFAULT_OCTREE_SIZE), 0, 0, this),
  270. numLevels_(DEFAULT_OCTREE_LEVELS)
  271. {
  272. // If the engine is running headless, subscribe to RenderUpdate events for manually updating the octree
  273. // to allow raycasts and animation update
  274. if (!GetSubsystem<Graphics>())
  275. SubscribeToEvent(E_RENDERUPDATE, ATOMIC_HANDLER(Octree, HandleRenderUpdate));
  276. }
  277. Octree::~Octree()
  278. {
  279. // Reset root pointer from all child octants now so that they do not move their drawables to root
  280. drawableUpdates_.Clear();
  281. ResetRoot();
  282. }
  283. void Octree::RegisterObject(Context* context)
  284. {
  285. context->RegisterFactory<Octree>(SUBSYSTEM_CATEGORY);
  286. Vector3 defaultBoundsMin = -Vector3::ONE * DEFAULT_OCTREE_SIZE;
  287. Vector3 defaultBoundsMax = Vector3::ONE * DEFAULT_OCTREE_SIZE;
  288. ATOMIC_ATTRIBUTE("Bounding Box Min", Vector3, worldBoundingBox_.min_, defaultBoundsMin, AM_DEFAULT);
  289. ATOMIC_ATTRIBUTE("Bounding Box Max", Vector3, worldBoundingBox_.max_, defaultBoundsMax, AM_DEFAULT);
  290. ATOMIC_ATTRIBUTE("Number of Levels", int, numLevels_, DEFAULT_OCTREE_LEVELS, AM_DEFAULT);
  291. }
  292. void Octree::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  293. {
  294. // If any of the (size) attributes change, resize the octree
  295. Serializable::OnSetAttribute(attr, src);
  296. SetSize(worldBoundingBox_, numLevels_);
  297. }
  298. void Octree::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  299. {
  300. if (debug)
  301. {
  302. ATOMIC_PROFILE(OctreeDrawDebug);
  303. Octant::DrawDebugGeometry(debug, depthTest);
  304. }
  305. }
  306. void Octree::SetSize(const BoundingBox& box, unsigned numLevels)
  307. {
  308. ATOMIC_PROFILE(ResizeOctree);
  309. // If drawables exist, they are temporarily moved to the root
  310. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  311. DeleteChild(i);
  312. Initialize(box);
  313. numDrawables_ = drawables_.Size();
  314. numLevels_ = Max(numLevels, 1U);
  315. }
  316. void Octree::Update(const FrameInfo& frame)
  317. {
  318. if (!Thread::IsMainThread())
  319. {
  320. ATOMIC_LOGERROR("Octree::Update() can not be called from worker threads");
  321. return;
  322. }
  323. // Let drawables update themselves before reinsertion. This can be used for animation
  324. if (!drawableUpdates_.Empty())
  325. {
  326. ATOMIC_PROFILE(UpdateDrawables);
  327. // Perform updates in worker threads. Notify the scene that a threaded update is going on and components
  328. // (for example physics objects) should not perform non-threadsafe work when marked dirty
  329. Scene* scene = GetScene();
  330. WorkQueue* queue = GetSubsystem<WorkQueue>();
  331. scene->BeginThreadedUpdate();
  332. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  333. int drawablesPerItem = Max((int)(drawableUpdates_.Size() / numWorkItems), 1);
  334. PODVector<Drawable*>::Iterator start = drawableUpdates_.Begin();
  335. // Create a work item for each thread
  336. for (int i = 0; i < numWorkItems; ++i)
  337. {
  338. SharedPtr<WorkItem> item = queue->GetFreeItem();
  339. item->priority_ = M_MAX_UNSIGNED;
  340. item->workFunction_ = UpdateDrawablesWork;
  341. item->aux_ = const_cast<FrameInfo*>(&frame);
  342. PODVector<Drawable*>::Iterator end = drawableUpdates_.End();
  343. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  344. end = start + drawablesPerItem;
  345. item->start_ = &(*start);
  346. item->end_ = &(*end);
  347. queue->AddWorkItem(item);
  348. start = end;
  349. }
  350. queue->Complete(M_MAX_UNSIGNED);
  351. scene->EndThreadedUpdate();
  352. }
  353. // If any drawables were inserted during threaded update, update them now from the main thread
  354. if (!threadedDrawableUpdates_.Empty())
  355. {
  356. ATOMIC_PROFILE(UpdateDrawablesQueuedDuringUpdate);
  357. for (PODVector<Drawable*>::ConstIterator i = threadedDrawableUpdates_.Begin(); i != threadedDrawableUpdates_.End(); ++i)
  358. {
  359. Drawable* drawable = *i;
  360. if (drawable)
  361. {
  362. drawable->Update(frame);
  363. drawableUpdates_.Push(drawable);
  364. }
  365. }
  366. threadedDrawableUpdates_.Clear();
  367. }
  368. // Notify drawable update being finished. Custom animation (eg. IK) can be done at this point
  369. Scene* scene = GetScene();
  370. if (scene)
  371. {
  372. using namespace SceneDrawableUpdateFinished;
  373. VariantMap& eventData = GetEventDataMap();
  374. eventData[P_SCENE] = scene;
  375. eventData[P_TIMESTEP] = frame.timeStep_;
  376. scene->SendEvent(E_SCENEDRAWABLEUPDATEFINISHED, eventData);
  377. }
  378. // Reinsert drawables that have been moved or resized, or that have been newly added to the octree and do not sit inside
  379. // the proper octant yet
  380. if (!drawableUpdates_.Empty())
  381. {
  382. ATOMIC_PROFILE(ReinsertToOctree);
  383. for (PODVector<Drawable*>::Iterator i = drawableUpdates_.Begin(); i != drawableUpdates_.End(); ++i)
  384. {
  385. Drawable* drawable = *i;
  386. drawable->updateQueued_ = false;
  387. Octant* octant = drawable->GetOctant();
  388. const BoundingBox& box = drawable->GetWorldBoundingBox();
  389. // Skip if no octant or does not belong to this octree anymore
  390. if (!octant || octant->GetRoot() != this)
  391. continue;
  392. // Skip if still fits the current octant
  393. if (drawable->IsOccludee() && octant->GetCullingBox().IsInside(box) == INSIDE && octant->CheckDrawableFit(box))
  394. continue;
  395. InsertDrawable(drawable);
  396. #ifdef _DEBUG
  397. // Verify that the drawable will be culled correctly
  398. octant = drawable->GetOctant();
  399. if (octant != this && octant->GetCullingBox().IsInside(box) != INSIDE)
  400. {
  401. ATOMIC_LOGERROR("Drawable is not fully inside its octant's culling bounds: drawable box " + box.ToString() +
  402. " octant box " + octant->GetCullingBox().ToString());
  403. }
  404. #endif
  405. }
  406. }
  407. drawableUpdates_.Clear();
  408. }
  409. void Octree::AddManualDrawable(Drawable* drawable)
  410. {
  411. if (!drawable || drawable->GetOctant())
  412. return;
  413. AddDrawable(drawable);
  414. }
  415. void Octree::RemoveManualDrawable(Drawable* drawable)
  416. {
  417. if (!drawable)
  418. return;
  419. Octant* octant = drawable->GetOctant();
  420. if (octant && octant->GetRoot() == this)
  421. octant->RemoveDrawable(drawable);
  422. }
  423. void Octree::GetDrawables(OctreeQuery& query) const
  424. {
  425. query.result_.Clear();
  426. GetDrawablesInternal(query, false);
  427. }
  428. void Octree::Raycast(RayOctreeQuery& query) const
  429. {
  430. ATOMIC_PROFILE(Raycast);
  431. query.result_.Clear();
  432. GetDrawablesInternal(query);
  433. Sort(query.result_.Begin(), query.result_.End(), CompareRayQueryResults);
  434. }
  435. void Octree::RaycastSingle(RayOctreeQuery& query) const
  436. {
  437. ATOMIC_PROFILE(Raycast);
  438. query.result_.Clear();
  439. rayQueryDrawables_.Clear();
  440. GetDrawablesOnlyInternal(query, rayQueryDrawables_);
  441. // Sort by increasing hit distance to AABB
  442. for (PODVector<Drawable*>::Iterator i = rayQueryDrawables_.Begin(); i != rayQueryDrawables_.End(); ++i)
  443. {
  444. Drawable* drawable = *i;
  445. drawable->SetSortValue(query.ray_.HitDistance(drawable->GetWorldBoundingBox()));
  446. }
  447. Sort(rayQueryDrawables_.Begin(), rayQueryDrawables_.End(), CompareDrawables);
  448. // Then do the actual test according to the query, and early-out as possible
  449. float closestHit = M_INFINITY;
  450. for (PODVector<Drawable*>::Iterator i = rayQueryDrawables_.Begin(); i != rayQueryDrawables_.End(); ++i)
  451. {
  452. Drawable* drawable = *i;
  453. if (drawable->GetSortValue() < Min(closestHit, query.maxDistance_))
  454. {
  455. unsigned oldSize = query.result_.Size();
  456. drawable->ProcessRayQuery(query, query.result_);
  457. if (query.result_.Size() > oldSize)
  458. closestHit = Min(closestHit, query.result_.Back().distance_);
  459. }
  460. else
  461. break;
  462. }
  463. if (query.result_.Size() > 1)
  464. {
  465. Sort(query.result_.Begin(), query.result_.End(), CompareRayQueryResults);
  466. query.result_.Resize(1);
  467. }
  468. }
  469. void Octree::QueueUpdate(Drawable* drawable)
  470. {
  471. Scene* scene = GetScene();
  472. if (scene && scene->IsThreadedUpdate())
  473. {
  474. MutexLock lock(octreeMutex_);
  475. threadedDrawableUpdates_.Push(drawable);
  476. }
  477. else
  478. drawableUpdates_.Push(drawable);
  479. drawable->updateQueued_ = true;
  480. }
  481. void Octree::CancelUpdate(Drawable* drawable)
  482. {
  483. // This doesn't have to take into account scene being in threaded update, because it is called only
  484. // when removing a drawable from octree, which should only ever happen from the main thread.
  485. drawableUpdates_.Remove(drawable);
  486. drawable->updateQueued_ = false;
  487. }
  488. void Octree::DrawDebugGeometry(bool depthTest)
  489. {
  490. DebugRenderer* debug = GetComponent<DebugRenderer>();
  491. DrawDebugGeometry(debug, depthTest);
  492. }
  493. void Octree::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  494. {
  495. // When running in headless mode, update the Octree manually during the RenderUpdate event
  496. Scene* scene = GetScene();
  497. if (!scene || !scene->IsUpdateEnabled())
  498. return;
  499. using namespace RenderUpdate;
  500. FrameInfo frame;
  501. frame.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  502. frame.timeStep_ = eventData[P_TIMESTEP].GetFloat();
  503. frame.camera_ = 0;
  504. Update(frame);
  505. }
  506. }