Octree.cpp 13 KB

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