Octree.cpp 14 KB

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