Octree.cpp 19 KB

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