Octree.cpp 19 KB

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