Octree.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 "OctreeQuery.h"
  29. #include "Scene.h"
  30. #include "Sort.h"
  31. #include "WorkQueue.h"
  32. #include "DebugNew.h"
  33. #ifdef _MSC_VER
  34. #pragma warning(disable:4355)
  35. #endif
  36. static const float DEFAULT_OCTREE_SIZE = 1000.0f;
  37. static const int DEFAULT_OCTREE_LEVELS = 8;
  38. void UpdateDrawablesWork(const WorkItem* item, unsigned threadIndex)
  39. {
  40. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  41. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  42. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  43. while (start != end)
  44. {
  45. Drawable* drawable = *start;
  46. drawable->Update(frame);
  47. drawable->updateQueued_ = false;
  48. ++start;
  49. }
  50. }
  51. inline bool CompareRayQueryResults(const RayQueryResult& lhs, const RayQueryResult& rhs)
  52. {
  53. return lhs.distance_ < rhs.distance_;
  54. }
  55. Octant::Octant(const BoundingBox& box, unsigned level, Octant* parent, Octree* root) :
  56. worldBoundingBox_(box),
  57. level_(level),
  58. parent_(parent),
  59. root_(root),
  60. numDrawables_(0)
  61. {
  62. center_ = worldBoundingBox_.Center();
  63. halfSize_ = worldBoundingBox_.Size() * 0.5f;
  64. cullingBox_ = BoundingBox(worldBoundingBox_.min_ - halfSize_, worldBoundingBox_.max_ + halfSize_);
  65. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  66. children_[i] = 0;
  67. }
  68. Octant::~Octant()
  69. {
  70. Release();
  71. }
  72. Octant* Octant::GetOrCreateChild(unsigned index)
  73. {
  74. if (children_[index])
  75. return children_[index];
  76. Vector3 newMin = worldBoundingBox_.min_;
  77. Vector3 newMax = worldBoundingBox_.max_;
  78. Vector3 oldCenter = worldBoundingBox_.Center();
  79. if (index & 1)
  80. newMin.x_ = oldCenter.x_;
  81. else
  82. newMax.x_ = oldCenter.x_;
  83. if (index & 2)
  84. newMin.y_ = oldCenter.y_;
  85. else
  86. newMax.y_ = oldCenter.y_;
  87. if (index & 4)
  88. newMin.z_ = oldCenter.z_;
  89. else
  90. newMax.z_ = oldCenter.z_;
  91. children_[index] = new Octant(BoundingBox(newMin, newMax), level_ + 1, this, root_);
  92. return children_[index];
  93. }
  94. void Octant::DeleteChild(unsigned index)
  95. {
  96. delete children_[index];
  97. children_[index] = 0;
  98. }
  99. void Octant::DeleteChild(Octant* octant)
  100. {
  101. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  102. {
  103. if (children_[i] == octant)
  104. {
  105. delete octant;
  106. children_[i] = 0;
  107. return;
  108. }
  109. }
  110. }
  111. void Octant::InsertDrawable(Drawable* drawable, const Vector3& boxCenter, const Vector3& boxSize)
  112. {
  113. // If size OK or outside, stop recursion & insert here
  114. if (CheckDrawableSize(boxSize) || cullingBox_.IsInside(drawable->GetWorldBoundingBox()) != INSIDE)
  115. {
  116. Octant* oldOctant = drawable->octant_;
  117. if (oldOctant != this)
  118. {
  119. // Add first, then remove, because drawable count going to zero deletes the octree branch in question
  120. AddDrawable(drawable);
  121. if (oldOctant)
  122. oldOctant->RemoveDrawable(drawable, false);
  123. }
  124. return;
  125. }
  126. unsigned x = boxCenter.x_ < center_.x_ ? 0 : 1;
  127. unsigned y = boxCenter.y_ < center_.y_ ? 0 : 2;
  128. unsigned z = boxCenter.z_ < center_.z_ ? 0 : 4;
  129. GetOrCreateChild(x + y + z)->InsertDrawable(drawable, boxCenter, boxSize);
  130. }
  131. bool Octant::CheckDrawableSize(const Vector3& boxSize) const
  132. {
  133. // If max split level, size always OK
  134. if (level_ != root_->GetNumLevels())
  135. return boxSize.x_ >= halfSize_.x_ || boxSize.y_ >= halfSize_.y_ || boxSize.z_ >= halfSize_.z_;
  136. else
  137. return true;
  138. }
  139. void Octant::ResetRoot()
  140. {
  141. root_ = 0;
  142. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  143. {
  144. if (children_[i])
  145. children_[i]->ResetRoot();
  146. }
  147. }
  148. void Octant::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  149. {
  150. debug->AddBoundingBox(worldBoundingBox_, Color(0.25f, 0.25f, 0.25f), depthTest);
  151. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  152. {
  153. if (children_[i])
  154. children_[i]->DrawDebugGeometry(debug, depthTest);
  155. }
  156. }
  157. void Octant::GetDrawablesInternal(OctreeQuery& query, bool inside) const
  158. {
  159. if (this != root_)
  160. {
  161. Intersection res = query.TestOctant(cullingBox_, inside);
  162. if (res == OUTSIDE)
  163. // Fully outside, so cull this octant, its children & drawables
  164. return;
  165. if (res == INSIDE)
  166. inside = true;
  167. }
  168. for (PODVector<Drawable*>::ConstIterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  169. {
  170. Drawable* drawable = *i;
  171. if (!(drawable->GetDrawableFlags() & query.drawableFlags_) || !(drawable->GetViewMask() & query.viewMask_) ||
  172. (query.occludersOnly_ && !drawable->IsOccluder()) || (query.shadowCastersOnly_ && !drawable->GetCastShadows()) ||
  173. !drawable->IsVisible())
  174. continue;
  175. if (query.TestDrawable(drawable->GetWorldBoundingBox(), inside) != OUTSIDE)
  176. query.result_.Push(drawable);
  177. }
  178. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  179. {
  180. if (children_[i])
  181. children_[i]->GetDrawablesInternal(query, inside);
  182. }
  183. }
  184. void Octant::GetDrawablesInternal(RayOctreeQuery& query) const
  185. {
  186. if (!numDrawables_)
  187. return;
  188. float octantDist = query.ray_.HitDistance(cullingBox_);
  189. if (octantDist >= query.maxDistance_)
  190. return;
  191. for (PODVector<Drawable*>::ConstIterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  192. {
  193. Drawable* drawable = *i;
  194. unsigned drawableFlags = drawable->GetDrawableFlags();
  195. if (!(drawable->GetDrawableFlags() & query.drawableFlags_) || !(drawable->GetViewMask() & query.viewMask_) ||
  196. !drawable->IsVisible() || (query.occludersOnly_ && !drawable->IsOccluder()) || (query.shadowCastersOnly_ &&
  197. !drawable->GetCastShadows()))
  198. continue;
  199. float drawableDist = query.ray_.HitDistance(drawable->GetWorldBoundingBox());
  200. // The drawable will possibly do more accurate collision testing, then store the result(s)
  201. if (drawableDist < query.maxDistance_)
  202. drawable->ProcessRayQuery(query, drawableDist);
  203. }
  204. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  205. {
  206. if (children_[i])
  207. children_[i]->GetDrawablesInternal(query);
  208. }
  209. }
  210. void Octant::Release()
  211. {
  212. if (root_ && this != root_)
  213. {
  214. // Remove the drawables (if any) from this octant to the root octant
  215. for (PODVector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  216. {
  217. (*i)->SetOctant(root_);
  218. root_->drawables_.Push(*i);
  219. root_->QueueReinsertion(*i);
  220. }
  221. drawables_.Clear();
  222. numDrawables_ = 0;
  223. }
  224. else if (!root_)
  225. {
  226. // If the whole octree is being destroyed, just detach the drawables
  227. for (PODVector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  228. (*i)->SetOctant(0);
  229. }
  230. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  231. DeleteChild(i);
  232. }
  233. OBJECTTYPESTATIC(Octree);
  234. Octree::Octree(Context* context) :
  235. Component(context),
  236. Octant(BoundingBox(-DEFAULT_OCTREE_SIZE, DEFAULT_OCTREE_SIZE), 0, 0, this),
  237. scene_(0),
  238. numLevels_(DEFAULT_OCTREE_LEVELS)
  239. {
  240. }
  241. Octree::~Octree()
  242. {
  243. // Reset root pointer from all child octants now so that they do not move their drawables to root
  244. ResetRoot();
  245. }
  246. void Octree::RegisterObject(Context* context)
  247. {
  248. context->RegisterFactory<Octree>();
  249. Vector3 defaultBoundsMin = Vector3::ONE * DEFAULT_OCTREE_SIZE;
  250. Vector3 defaultBoundsMax = -Vector3::ONE * DEFAULT_OCTREE_SIZE;
  251. ATTRIBUTE(Octree, VAR_VECTOR3, "Bounding Box Min", worldBoundingBox_.min_, defaultBoundsMin, AM_DEFAULT);
  252. ATTRIBUTE(Octree, VAR_VECTOR3, "Bounding Box Max", worldBoundingBox_.max_, defaultBoundsMax, AM_DEFAULT);
  253. ATTRIBUTE(Octree, VAR_INT, "Number of Levels", numLevels_, DEFAULT_OCTREE_LEVELS, AM_DEFAULT);
  254. }
  255. void Octree::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  256. {
  257. // If any of the (size) attributes change, resize the octree
  258. Serializable::OnSetAttribute(attr, src);
  259. Resize(worldBoundingBox_, numLevels_);
  260. }
  261. void Octree::Resize(const BoundingBox& box, unsigned numLevels)
  262. {
  263. PROFILE(ResizeOctree);
  264. numLevels = Max((int)numLevels, 1);
  265. // If drawables exist, they are temporarily moved to the root
  266. Release();
  267. Vector3 halfSize = box.Size() * 0.5f;
  268. worldBoundingBox_ = box;
  269. cullingBox_ = BoundingBox(worldBoundingBox_.min_ - halfSize, worldBoundingBox_.max_ + halfSize);
  270. numDrawables_ = drawables_.Size();
  271. numLevels_ = numLevels;
  272. }
  273. void Octree::Update(const FrameInfo& frame)
  274. {
  275. UpdateDrawables(frame);
  276. ReinsertDrawables(frame);
  277. }
  278. void Octree::AddManualDrawable(Drawable* drawable, bool culling)
  279. {
  280. if (!drawable || drawable->GetOctant())
  281. return;
  282. if (culling)
  283. AddDrawable(drawable);
  284. else
  285. {
  286. for (Vector<WeakPtr<Drawable> >::ConstIterator i = unculledDrawables_.Begin(); i != unculledDrawables_.End(); ++i)
  287. {
  288. if ((*i) == drawable)
  289. return;
  290. }
  291. unculledDrawables_.Push(WeakPtr<Drawable>(drawable));
  292. }
  293. }
  294. void Octree::RemoveManualDrawable(Drawable* drawable)
  295. {
  296. if (!drawable)
  297. return;
  298. Octant* octant = drawable->GetOctant();
  299. if (octant && octant->GetRoot() == this)
  300. {
  301. CancelUpdate(drawable);
  302. CancelReinsertion(drawable);
  303. octant->RemoveDrawable(drawable);
  304. }
  305. else
  306. {
  307. for (Vector<WeakPtr<Drawable> >::Iterator i = unculledDrawables_.Begin(); i != unculledDrawables_.End(); ++i)
  308. {
  309. if ((*i) == drawable)
  310. {
  311. unculledDrawables_.Erase(i);
  312. return;
  313. }
  314. }
  315. }
  316. }
  317. void Octree::GetDrawables(OctreeQuery& query) const
  318. {
  319. query.result_.Clear();
  320. GetDrawablesInternal(query, false);
  321. }
  322. void Octree::GetDrawables(RayOctreeQuery& query) const
  323. {
  324. PROFILE(Raycast);
  325. query.result_.Clear();
  326. GetDrawablesInternal(query);
  327. Sort(query.result_.Begin(), query.result_.End(), CompareRayQueryResults);
  328. }
  329. void Octree::GetUnculledDrawables(PODVector<Drawable*>& dest, unsigned char drawableFlags) const
  330. {
  331. for (Vector<WeakPtr<Drawable> >::ConstIterator i = unculledDrawables_.Begin(); i != unculledDrawables_.End(); ++i)
  332. {
  333. if (*i && (*i)->IsVisible() && (*i)->GetDrawableFlags() & drawableFlags)
  334. dest.Push(*i);
  335. }
  336. }
  337. void Octree::QueueUpdate(Drawable* drawable)
  338. {
  339. drawableUpdates_.Push(drawable);
  340. drawable->updateQueued_ = true;
  341. }
  342. void Octree::QueueReinsertion(Drawable* drawable)
  343. {
  344. if (scene_ && scene_->IsThreadedUpdate())
  345. {
  346. MutexLock lock(octreeMutex_);
  347. drawableReinsertions_.Push(drawable);
  348. }
  349. else
  350. drawableReinsertions_.Push(drawable);
  351. drawable->reinsertionQueued_ = true;
  352. }
  353. void Octree::CancelUpdate(Drawable* drawable)
  354. {
  355. PODVector<Drawable*>::Iterator i = drawableUpdates_.Find(drawable);
  356. if (i != drawableUpdates_.End())
  357. {
  358. (*i)->updateQueued_ = false;
  359. drawableUpdates_.Erase(i);
  360. }
  361. }
  362. void Octree::CancelReinsertion(Drawable* drawable)
  363. {
  364. PODVector<Drawable*>::Iterator i = drawableReinsertions_.Find(drawable);
  365. if (i != drawableReinsertions_.End())
  366. {
  367. (*i)->reinsertionQueued_ = false;
  368. drawableReinsertions_.Erase(i);
  369. }
  370. }
  371. void Octree::DrawDebugGeometry(bool depthTest)
  372. {
  373. PROFILE(OctreeDrawDebug);
  374. DebugRenderer* debug = GetComponent<DebugRenderer>();
  375. if (!debug)
  376. return;
  377. Octant::DrawDebugGeometry(debug, depthTest);
  378. }
  379. void Octree::OnNodeSet(Node* node)
  380. {
  381. scene_ = node ? node->GetScene() : 0;
  382. }
  383. void Octree::UpdateDrawables(const FrameInfo& frame)
  384. {
  385. // Let drawables update themselves before reinsertion
  386. if (drawableUpdates_.Empty())
  387. return;
  388. PROFILE(UpdateDrawables);
  389. Scene* scene = node_->GetScene();
  390. WorkQueue* queue = GetSubsystem<WorkQueue>();
  391. scene->BeginThreadedUpdate();
  392. WorkItem item;
  393. item.workFunction_ = UpdateDrawablesWork;
  394. item.aux_ = const_cast<FrameInfo*>(&frame);
  395. PODVector<Drawable*>::Iterator start = drawableUpdates_.Begin();
  396. while (start != drawableUpdates_.End())
  397. {
  398. PODVector<Drawable*>::Iterator end = drawableUpdates_.End();
  399. if (end - start > DRAWABLES_PER_WORK_ITEM)
  400. end = start + DRAWABLES_PER_WORK_ITEM;
  401. item.start_ = &(*start);
  402. item.end_ = &(*end);
  403. queue->AddWorkItem(item);
  404. start = end;
  405. }
  406. queue->Complete();
  407. scene->EndThreadedUpdate();
  408. drawableUpdates_.Clear();
  409. for (unsigned i = unculledDrawables_.Size() - 1; i < unculledDrawables_.Size(); --i)
  410. {
  411. // Remove expired unculled drawables at this point
  412. if (!unculledDrawables_[i])
  413. unculledDrawables_.Erase(i, 1);
  414. }
  415. }
  416. void Octree::ReinsertDrawables(const FrameInfo& frame)
  417. {
  418. if (drawableReinsertions_.Empty())
  419. return;
  420. PROFILE(ReinsertDrawables);
  421. // Reinsert drawables into the octree
  422. for (PODVector<Drawable*>::Iterator i = drawableReinsertions_.Begin(); i != drawableReinsertions_.End(); ++i)
  423. {
  424. Drawable* drawable = *i;
  425. const BoundingBox& box = drawable->GetWorldBoundingBox();
  426. Vector3 boxCenter = box.Center();
  427. Vector3 boxSize = box.Size();
  428. Octant* octant = drawable->GetOctant();
  429. if (octant)
  430. {
  431. if (octant == this)
  432. {
  433. // Handle root octant as special case: if outside the root, do not reinsert
  434. if (GetCullingBox().IsInside(box) == INSIDE && !CheckDrawableSize(boxSize))
  435. InsertDrawable(drawable, boxCenter, boxSize);
  436. }
  437. else
  438. {
  439. // Otherwise reinsert if outside current octant or if size does not fit octant size
  440. if (octant->GetCullingBox().IsInside(box) != INSIDE || !octant->CheckDrawableSize(boxSize))
  441. InsertDrawable(drawable, boxCenter, boxSize);
  442. }
  443. }
  444. else
  445. InsertDrawable(drawable, boxCenter, boxSize);
  446. drawable->reinsertionQueued_ = false;
  447. }
  448. drawableReinsertions_.Clear();
  449. }