Octree.cpp 19 KB

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