Octree.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 "DebugRenderer.h"
  25. #include "Deserializer.h"
  26. #include "Profiler.h"
  27. #include "Octree.h"
  28. #include "OctreeQuery.h"
  29. #include "Scene.h"
  30. #include "SceneEvents.h"
  31. #include "Serializer.h"
  32. #include "XMLElement.h"
  33. #include <algorithm>
  34. #include "DebugNew.h"
  35. #ifdef _MSC_VER
  36. #pragma warning(disable:4355)
  37. #endif
  38. inline static bool compareRayQueryResults(const RayQueryResult& lhs, const RayQueryResult& rhs)
  39. {
  40. return lhs.mDistance < rhs.mDistance;
  41. }
  42. Octant::Octant(const BoundingBox& box, unsigned level, Octant* parent, Octree* root) :
  43. mWorldBoundingBox(box),
  44. mLevel(level),
  45. mParent(parent),
  46. mRoot(root),
  47. mNumNodes(0)
  48. {
  49. Vector3 halfSize = mWorldBoundingBox.getSize() * 0.5f;
  50. mCullingBox = BoundingBox(mWorldBoundingBox.mMin - halfSize, mWorldBoundingBox.mMax + halfSize);
  51. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  52. mChildren[i] = 0;
  53. }
  54. Octant::~Octant()
  55. {
  56. release();
  57. }
  58. Octant* Octant::getOrCreateChild(unsigned index)
  59. {
  60. if (mChildren[index])
  61. return mChildren[index];
  62. Vector3 newMin = mWorldBoundingBox.mMin;
  63. Vector3 newMax = mWorldBoundingBox.mMax;
  64. Vector3 oldCenter = mWorldBoundingBox.getCenter();
  65. if (index & 1)
  66. newMin.mX = oldCenter.mX;
  67. else
  68. newMax.mX = oldCenter.mX;
  69. if (index & 2)
  70. newMin.mY = oldCenter.mY;
  71. else
  72. newMax.mY = oldCenter.mY;
  73. if (index & 4)
  74. newMin.mZ = oldCenter.mZ;
  75. else
  76. newMax.mZ = oldCenter.mZ;
  77. mChildren[index] = new Octant(BoundingBox(newMin, newMax), mLevel + 1, this, mRoot);
  78. return mChildren[index];
  79. }
  80. void Octant::deleteChild(unsigned index)
  81. {
  82. delete mChildren[index];
  83. mChildren[index] = 0;
  84. }
  85. void Octant::deleteChild(Octant* octant)
  86. {
  87. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  88. {
  89. if (mChildren[i] == octant)
  90. {
  91. delete octant;
  92. mChildren[i] = 0;
  93. return;
  94. }
  95. }
  96. }
  97. void Octant::insertNode(VolumeNode* node)
  98. {
  99. // If size OK or outside, stop recursion & insert here
  100. if ((checkNodeSize(node)) || (mCullingBox.isInside(node->getWorldBoundingBox()) != INSIDE))
  101. {
  102. if (node->mOctant != this)
  103. {
  104. // Add first, then remove, because node count going to zero deletes the octree branch in question
  105. Octant* oldOctant = node->mOctant;
  106. addNode(node);
  107. if (oldOctant)
  108. oldOctant->removeNode(node);
  109. }
  110. return;
  111. }
  112. Vector3 octantCenter = mWorldBoundingBox.getCenter();
  113. Vector3 nodeCenter = node->getWorldBoundingBox().getCenter();
  114. unsigned x = nodeCenter.mX < octantCenter.mX ? 0 : 1;
  115. unsigned y = nodeCenter.mY < octantCenter.mY ? 0 : 2;
  116. unsigned z = nodeCenter.mZ < octantCenter.mZ ? 0 : 4;
  117. getOrCreateChild(x + y + z)->insertNode(node);
  118. }
  119. bool Octant::checkNodeSize(VolumeNode* node) const
  120. {
  121. // If max split level, size always OK
  122. if (mLevel == mRoot->getNumLevels())
  123. return true;
  124. Vector3 octantHalfSize = mWorldBoundingBox.getSize() * 0.5;
  125. Vector3 nodeSize = node->getWorldBoundingBox().getSize();
  126. return (nodeSize.mX >= octantHalfSize.mX) || (nodeSize.mY >= octantHalfSize.mY) || (nodeSize.mZ >= octantHalfSize.mZ);
  127. }
  128. void Octant::resetRoot()
  129. {
  130. mRoot = 0;
  131. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  132. {
  133. if (mChildren[i])
  134. mChildren[i]->resetRoot();
  135. }
  136. }
  137. void Octant::drawDebugGeometry(DebugRenderer* debug, bool depthTest)
  138. {
  139. debug->addBoundingBox(mWorldBoundingBox, Color(0.25f, 0.25f, 0.25f), depthTest);
  140. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  141. {
  142. if (mChildren[i])
  143. mChildren[i]->drawDebugGeometry(debug, depthTest);
  144. }
  145. }
  146. void Octant::getNodesInternal(OctreeQuery& query, unsigned mask) const
  147. {
  148. if (!mNumNodes)
  149. return;
  150. if (mask != M_MAX_UNSIGNED)
  151. {
  152. Intersection res = query.testOctant(mCullingBox, mask);
  153. if ((res == OUTSIDE) && (this != mRoot))
  154. // Fully outside, so cull this octant, its children & nodes
  155. return;
  156. if (res == INSIDE)
  157. // Fully inside, no culling checks necessary for children & nodes
  158. mask = M_MAX_UNSIGNED;
  159. }
  160. for (std::vector<VolumeNode*>::const_iterator i = mNodes.begin(); i != mNodes.end(); ++i)
  161. {
  162. VolumeNode* node = *i;
  163. unsigned nodeFlags = node->getNodeFlags();
  164. if ((!(nodeFlags & query.mNodeFlags)) || (!node->isVisible()))
  165. continue;
  166. if ((query.mOccludersOnly) && (!node->isOccluder()))
  167. continue;
  168. if ((query.mShadowCastersOnly) && (!node->getCastShadows()))
  169. continue;
  170. if (query.testNode(node->getWorldBoundingBox(), mask) != OUTSIDE)
  171. query.mResult.push_back(node);
  172. }
  173. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  174. {
  175. if (mChildren[i])
  176. mChildren[i]->getNodesInternal(query, mask);
  177. }
  178. }
  179. void Octant::getNodesInternal(RayOctreeQuery& query) const
  180. {
  181. if (!mNumNodes)
  182. return;
  183. float octantDist = mCullingBox.getDistance(query.mRay);
  184. if (octantDist >= query.mMaxDistance)
  185. return;
  186. for (std::vector<VolumeNode*>::const_iterator i = mNodes.begin(); i != mNodes.end(); ++i)
  187. {
  188. VolumeNode* node = *i;
  189. unsigned nodeFlags = node->getNodeFlags();
  190. if ((!(nodeFlags & query.mNodeFlags)) || (!node->isVisible()))
  191. continue;
  192. if ((query.mOccludersOnly) && (!node->isOccluder()))
  193. continue;
  194. if ((query.mShadowCastersOnly) && (!node->getCastShadows()))
  195. continue;
  196. float nodeDist = node->getWorldBoundingBox().getDistance(query.mRay);
  197. // The node will possibly do more accurate collision testing, then store the result(s)
  198. if (nodeDist < query.mMaxDistance)
  199. node->processRayQuery(query, nodeDist);
  200. }
  201. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  202. {
  203. if (mChildren[i])
  204. mChildren[i]->getNodesInternal(query);
  205. }
  206. }
  207. void Octant::release()
  208. {
  209. if ((mRoot) && (this != mRoot))
  210. {
  211. // Remove the nodes (if any) from this octant to the root octant
  212. for (std::vector<VolumeNode*>::iterator i = mNodes.begin(); i != mNodes.end(); ++i)
  213. {
  214. (*i)->mOctant = mRoot;
  215. mRoot->mNodes.push_back(*i);
  216. mRoot->markNodeForReinsertion(*i);
  217. }
  218. mNodes.clear();
  219. mNumNodes = 0;
  220. }
  221. else if (!mRoot)
  222. {
  223. // If the whole octree is being destroyed, just detach the nodes
  224. for (std::vector<VolumeNode*>::iterator i = mNodes.begin(); i != mNodes.end(); ++i)
  225. (*i)->mOctant = 0;
  226. }
  227. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  228. deleteChild(i);
  229. }
  230. Octree::Octree(const BoundingBox& box, unsigned numLevels, bool headless) :
  231. Octant(box, 0, 0, this),
  232. mNumLevels(max((int)numLevels, 1)),
  233. mDrawDebugGeometry(false),
  234. mHeadless(headless)
  235. {
  236. }
  237. Octree::~Octree()
  238. {
  239. // Reset root pointer from all child octants now so that they do not move their scene nodes to root
  240. resetRoot();
  241. }
  242. void Octree::save(Serializer& dest)
  243. {
  244. writeExtensionType(dest);
  245. dest.writeBoundingBox(mWorldBoundingBox);
  246. dest.writeUInt(mNumLevels);
  247. }
  248. void Octree::load(Deserializer& source)
  249. {
  250. checkExtensionType(source);
  251. BoundingBox box = source.readBoundingBox();
  252. unsigned numLevels = source.readUInt();
  253. resize(box, numLevels);
  254. }
  255. void Octree::saveXML(XMLElement& dest)
  256. {
  257. XMLElement octreeElem = dest.createChildElement("octree");
  258. // Write octree properties
  259. octreeElem.setBoundingBox(mWorldBoundingBox);
  260. octreeElem.setInt("levels", mNumLevels);
  261. }
  262. void Octree::loadXML(const XMLElement& source)
  263. {
  264. XMLElement octreeElem = source.getChildElement("octree");
  265. BoundingBox box = octreeElem.getBoundingBox();
  266. unsigned numLevels = octreeElem.getInt("levels");
  267. resize(box, numLevels);
  268. }
  269. void Octree::update(float timeStep)
  270. {
  271. // If in headless mode, run an update now to update and reinsert nodes
  272. if (mHeadless)
  273. {
  274. FrameInfo frame;
  275. frame.mCamera = 0;
  276. frame.mFrameNumber = 0;
  277. frame.mTimeStep = timeStep;
  278. updateOctree(frame);
  279. }
  280. }
  281. void Octree::resize(const BoundingBox& box, unsigned numLevels)
  282. {
  283. numLevels = max((int)numLevels, 1);
  284. if ((numLevels == mNumLevels) && (box.mMin == mWorldBoundingBox.mMin) && (box.mMax == mWorldBoundingBox.mMax))
  285. return;
  286. // If nodes exist, they are temporarily moved to the root
  287. release();
  288. mNumNodes = mNodes.size();
  289. mWorldBoundingBox = box;
  290. mNumLevels = numLevels;
  291. Vector3 halfSize = mWorldBoundingBox.getSize() * 0.5f;
  292. mCullingBox = BoundingBox(mWorldBoundingBox.mMin - halfSize, mWorldBoundingBox.mMax + halfSize);
  293. }
  294. void Octree::updateOctree(const FrameInfo& frame)
  295. {
  296. {
  297. PROFILE(Octree_UpdateNodes);
  298. // Let nodes update themselves before reinsertion
  299. for (std::set<VolumeNode*>::iterator i = mNodeUpdates.begin(); i != mNodeUpdates.end(); ++i)
  300. (*i)->updateNode(frame);
  301. }
  302. {
  303. PROFILE(Octree_ReinsertNodes);
  304. // Reinsert nodes into the octree
  305. for (std::set<VolumeNode*>::iterator i = mNodeReinsertions.begin(); i != mNodeReinsertions.end(); ++i)
  306. {
  307. VolumeNode* node = *i;
  308. Octant* octant = node->mOctant;
  309. if (octant)
  310. {
  311. bool reinsert = false;
  312. if (octant == this)
  313. {
  314. // Handle root octant as special case: if outside the root, do not reinsert
  315. if ((getCullingBox().isInside(node->getWorldBoundingBox()) == INSIDE) && (!checkNodeSize(node)))
  316. reinsert = true;
  317. }
  318. else
  319. {
  320. // Otherwise reinsert if outside current octant or if size does not fit octant size
  321. if ((octant->getCullingBox().isInside(node->getWorldBoundingBox()) != INSIDE) || (!octant->checkNodeSize(node)))
  322. reinsert = true;
  323. }
  324. if (reinsert)
  325. insertNode(node);
  326. }
  327. else
  328. insertNode(node);
  329. }
  330. }
  331. mNodeUpdates.clear();
  332. mNodeReinsertions.clear();
  333. }
  334. void Octree::getNodes(OctreeQuery& query) const
  335. {
  336. PROFILE(Octree_GetNodes);
  337. query.mResult.clear();
  338. getNodesInternal(query, 0);
  339. }
  340. void Octree::getNodes(RayOctreeQuery& query) const
  341. {
  342. PROFILE(Octree_Raycast);
  343. query.mResult.clear();
  344. getNodesInternal(query);
  345. std::sort(query.mResult.begin(), query.mResult.end(), compareRayQueryResults);
  346. }
  347. void Octree::markNodeForUpdate(VolumeNode* node)
  348. {
  349. mNodeUpdates.insert(node);
  350. }
  351. void Octree::clearNodeUpdate(VolumeNode* node)
  352. {
  353. mNodeUpdates.erase(node);
  354. }
  355. void Octree::markNodeForReinsertion(VolumeNode* node)
  356. {
  357. mNodeReinsertions.insert(node);
  358. }
  359. void Octree::clearNodeReinsertion(VolumeNode* node)
  360. {
  361. mNodeReinsertions.erase(node);
  362. }
  363. void Octree::drawDebugGeometry(bool depthTest)
  364. {
  365. DebugRenderer* debug = mScene->getExtension<DebugRenderer>();
  366. if (!debug)
  367. return;
  368. PROFILE(Octree_DrawDebugGeometry);
  369. Octant::drawDebugGeometry(debug, depthTest);
  370. }