Octree.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. //
  2. // Copyright (c) 2008-2015 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 "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Core/Thread.h"
  27. #include "../Core/WorkQueue.h"
  28. #include "../Graphics/DebugRenderer.h"
  29. #include "../Graphics/Graphics.h"
  30. #include "../Graphics/Octree.h"
  31. #include "../IO/Log.h"
  32. #include "../Scene/Scene.h"
  33. #include "../Scene/SceneEvents.h"
  34. #include "../DebugNew.h"
  35. #ifdef _MSC_VER
  36. #pragma warning(disable:4355)
  37. #endif
  38. namespace Urho3D
  39. {
  40. static const float DEFAULT_OCTREE_SIZE = 1000.0f;
  41. static const int DEFAULT_OCTREE_LEVELS = 8;
  42. static const int RAYCASTS_PER_WORK_ITEM = 4;
  43. extern const char* SUBSYSTEM_CATEGORY;
  44. void RaycastDrawablesWork(const WorkItem* item, unsigned threadIndex)
  45. {
  46. Octree* octree = reinterpret_cast<Octree*>(item->aux_);
  47. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  48. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  49. const RayOctreeQuery& query = *octree->rayQuery_;
  50. PODVector<RayQueryResult>& results = octree->rayQueryResults_[threadIndex];
  51. while (start != end)
  52. {
  53. Drawable* drawable = *start;
  54. drawable->ProcessRayQuery(query, results);
  55. ++start;
  56. }
  57. }
  58. void UpdateDrawablesWork(const WorkItem* item, unsigned threadIndex)
  59. {
  60. const FrameInfo& frame = *(reinterpret_cast<FrameInfo*>(item->aux_));
  61. Drawable** start = reinterpret_cast<Drawable**>(item->start_);
  62. Drawable** end = reinterpret_cast<Drawable**>(item->end_);
  63. while (start != end)
  64. {
  65. Drawable* drawable = *start;
  66. if (drawable)
  67. drawable->Update(frame);
  68. ++start;
  69. }
  70. }
  71. inline bool CompareRayQueryResults(const RayQueryResult& lhs, const RayQueryResult& rhs)
  72. {
  73. return lhs.distance_ < rhs.distance_;
  74. }
  75. Octant::Octant(const BoundingBox& box, unsigned level, Octant* parent, Octree* root, unsigned index) :
  76. level_(level),
  77. numDrawables_(0),
  78. parent_(parent),
  79. root_(root),
  80. index_(index)
  81. {
  82. Initialize(box);
  83. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  84. children_[i] = 0;
  85. }
  86. Octant::~Octant()
  87. {
  88. if (root_)
  89. {
  90. // Remove the drawables (if any) from this octant to the root octant
  91. for (PODVector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  92. {
  93. (*i)->SetOctant(root_);
  94. root_->drawables_.Push(*i);
  95. root_->QueueUpdate(*i);
  96. }
  97. drawables_.Clear();
  98. numDrawables_ = 0;
  99. }
  100. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  101. DeleteChild(i);
  102. }
  103. Octant* Octant::GetOrCreateChild(unsigned index)
  104. {
  105. if (children_[index])
  106. return children_[index];
  107. Vector3 newMin = worldBoundingBox_.min_;
  108. Vector3 newMax = worldBoundingBox_.max_;
  109. Vector3 oldCenter = worldBoundingBox_.Center();
  110. if (index & 1)
  111. newMin.x_ = oldCenter.x_;
  112. else
  113. newMax.x_ = oldCenter.x_;
  114. if (index & 2)
  115. newMin.y_ = oldCenter.y_;
  116. else
  117. newMax.y_ = oldCenter.y_;
  118. if (index & 4)
  119. newMin.z_ = oldCenter.z_;
  120. else
  121. newMax.z_ = oldCenter.z_;
  122. children_[index] = new Octant(BoundingBox(newMin, newMax), level_ + 1, this, root_, index);
  123. return children_[index];
  124. }
  125. void Octant::DeleteChild(unsigned index)
  126. {
  127. assert(index < NUM_OCTANTS);
  128. delete children_[index];
  129. children_[index] = 0;
  130. }
  131. void Octant::InsertDrawable(Drawable* drawable)
  132. {
  133. const BoundingBox& box = drawable->GetWorldBoundingBox();
  134. // If root octant, insert all non-occludees here, so that octant occlusion does not hide the drawable.
  135. // Also if drawable is outside the root octant bounds, insert to root
  136. bool insertHere;
  137. if (this == root_)
  138. insertHere = !drawable->IsOccludee() || cullingBox_.IsInside(box) != INSIDE || CheckDrawableFit(box);
  139. else
  140. insertHere = CheckDrawableFit(box);
  141. if (insertHere)
  142. {
  143. Octant* oldOctant = drawable->octant_;
  144. if (oldOctant != this)
  145. {
  146. // Add first, then remove, because drawable count going to zero deletes the octree branch in question
  147. AddDrawable(drawable);
  148. if (oldOctant)
  149. oldOctant->RemoveDrawable(drawable, false);
  150. }
  151. }
  152. else
  153. {
  154. Vector3 boxCenter = box.Center();
  155. unsigned x = boxCenter.x_ < center_.x_ ? 0 : 1;
  156. unsigned y = boxCenter.y_ < center_.y_ ? 0 : 2;
  157. unsigned z = boxCenter.z_ < center_.z_ ? 0 : 4;
  158. GetOrCreateChild(x + y + z)->InsertDrawable(drawable);
  159. }
  160. }
  161. bool Octant::CheckDrawableFit(const BoundingBox& box) const
  162. {
  163. Vector3 boxSize = box.Size();
  164. // If max split level, size always OK, otherwise check that box is at least half size of octant
  165. if (level_ >= root_->GetNumLevels() || boxSize.x_ >= halfSize_.x_ || boxSize.y_ >= halfSize_.y_ ||
  166. boxSize.z_ >= halfSize_.z_)
  167. return true;
  168. // Also check if the box can not fit a child octant's culling box, in that case size OK (must insert here)
  169. else
  170. {
  171. if (box.min_.x_ <= worldBoundingBox_.min_.x_ - 0.5f * halfSize_.x_ ||
  172. box.max_.x_ >= worldBoundingBox_.max_.x_ + 0.5f * halfSize_.x_ ||
  173. box.min_.y_ <= worldBoundingBox_.min_.y_ - 0.5f * halfSize_.y_ ||
  174. box.max_.y_ >= worldBoundingBox_.max_.y_ + 0.5f * halfSize_.y_ ||
  175. box.min_.z_ <= worldBoundingBox_.min_.z_ - 0.5f * halfSize_.z_ ||
  176. box.max_.z_ >= worldBoundingBox_.max_.z_ + 0.5f * halfSize_.z_)
  177. return true;
  178. }
  179. // Bounding box too small, should create a child octant
  180. return false;
  181. }
  182. void Octant::ResetRoot()
  183. {
  184. root_ = 0;
  185. // The whole octree is being destroyed, just detach the drawables
  186. for (PODVector<Drawable*>::Iterator i = drawables_.Begin(); i != drawables_.End(); ++i)
  187. (*i)->SetOctant(0);
  188. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  189. {
  190. if (children_[i])
  191. children_[i]->ResetRoot();
  192. }
  193. }
  194. void Octant::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  195. {
  196. if (debug && debug->IsInside(worldBoundingBox_))
  197. {
  198. debug->AddBoundingBox(worldBoundingBox_, Color(0.25f, 0.25f, 0.25f), depthTest);
  199. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  200. {
  201. if (children_[i])
  202. children_[i]->DrawDebugGeometry(debug, depthTest);
  203. }
  204. }
  205. }
  206. void Octant::Initialize(const BoundingBox& box)
  207. {
  208. worldBoundingBox_ = box;
  209. center_ = box.Center();
  210. halfSize_ = 0.5f * box.Size();
  211. cullingBox_ = BoundingBox(worldBoundingBox_.min_ - halfSize_, worldBoundingBox_.max_ + halfSize_);
  212. }
  213. void Octant::GetDrawablesInternal(OctreeQuery& query, bool inside) const
  214. {
  215. if (this != root_)
  216. {
  217. Intersection res = query.TestOctant(cullingBox_, inside);
  218. if (res == INSIDE)
  219. inside = true;
  220. else if (res == OUTSIDE)
  221. {
  222. // Fully outside, so cull this octant, its children & drawables
  223. return;
  224. }
  225. }
  226. if (drawables_.Size())
  227. {
  228. Drawable** start = const_cast<Drawable**>(&drawables_[0]);
  229. Drawable** end = start + drawables_.Size();
  230. query.TestDrawables(start, end, inside);
  231. }
  232. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  233. {
  234. if (children_[i])
  235. children_[i]->GetDrawablesInternal(query, inside);
  236. }
  237. }
  238. void Octant::GetDrawablesInternal(RayOctreeQuery& query) const
  239. {
  240. float octantDist = query.ray_.HitDistance(cullingBox_);
  241. if (octantDist >= query.maxDistance_)
  242. return;
  243. if (drawables_.Size())
  244. {
  245. Drawable** start = const_cast<Drawable**>(&drawables_[0]);
  246. Drawable** end = start + drawables_.Size();
  247. while (start != end)
  248. {
  249. Drawable* drawable = *start++;
  250. if ((drawable->GetDrawableFlags() & query.drawableFlags_) && (drawable->GetViewMask() & query.viewMask_))
  251. drawable->ProcessRayQuery(query, query.result_);
  252. }
  253. }
  254. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  255. {
  256. if (children_[i])
  257. children_[i]->GetDrawablesInternal(query);
  258. }
  259. }
  260. void Octant::GetDrawablesOnlyInternal(RayOctreeQuery& query, PODVector<Drawable*>& drawables) const
  261. {
  262. float octantDist = query.ray_.HitDistance(cullingBox_);
  263. if (octantDist >= query.maxDistance_)
  264. return;
  265. if (drawables_.Size())
  266. {
  267. Drawable** start = const_cast<Drawable**>(&drawables_[0]);
  268. Drawable** end = start + drawables_.Size();
  269. while (start != end)
  270. {
  271. Drawable* drawable = *start++;
  272. if ((drawable->GetDrawableFlags() & query.drawableFlags_) && (drawable->GetViewMask() & query.viewMask_))
  273. drawables.Push(drawable);
  274. }
  275. }
  276. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  277. {
  278. if (children_[i])
  279. children_[i]->GetDrawablesOnlyInternal(query, drawables);
  280. }
  281. }
  282. Octree::Octree(Context* context) :
  283. Component(context),
  284. Octant(BoundingBox(-DEFAULT_OCTREE_SIZE, DEFAULT_OCTREE_SIZE), 0, 0, this),
  285. numLevels_(DEFAULT_OCTREE_LEVELS)
  286. {
  287. // Resize threaded ray query intermediate result vector according to number of worker threads
  288. WorkQueue* workQueue = GetSubsystem<WorkQueue>();
  289. rayQueryResults_.Resize(workQueue ? workQueue->GetNumThreads() + 1 : 1);
  290. // If the engine is running headless, subscribe to RenderUpdate events for manually updating the octree
  291. // to allow raycasts and animation update
  292. if (!GetSubsystem<Graphics>())
  293. SubscribeToEvent(E_RENDERUPDATE, URHO3D_HANDLER(Octree, HandleRenderUpdate));
  294. }
  295. Octree::~Octree()
  296. {
  297. // Reset root pointer from all child octants now so that they do not move their drawables to root
  298. drawableUpdates_.Clear();
  299. drawableReinsertions_.Clear();
  300. ResetRoot();
  301. }
  302. void Octree::RegisterObject(Context* context)
  303. {
  304. context->RegisterFactory<Octree>(SUBSYSTEM_CATEGORY);
  305. Vector3 defaultBoundsMin = -Vector3::ONE * DEFAULT_OCTREE_SIZE;
  306. Vector3 defaultBoundsMax = Vector3::ONE * DEFAULT_OCTREE_SIZE;
  307. ATTRIBUTE("Bounding Box Min", Vector3, worldBoundingBox_.min_, defaultBoundsMin, AM_DEFAULT);
  308. ATTRIBUTE("Bounding Box Max", Vector3, worldBoundingBox_.max_, defaultBoundsMax, AM_DEFAULT);
  309. ATTRIBUTE("Number of Levels", int, numLevels_, DEFAULT_OCTREE_LEVELS, AM_DEFAULT);
  310. }
  311. void Octree::OnSetAttribute(const AttributeInfo& attr, const Variant& src)
  312. {
  313. // If any of the (size) attributes change, resize the octree
  314. Serializable::OnSetAttribute(attr, src);
  315. SetSize(worldBoundingBox_, numLevels_);
  316. }
  317. void Octree::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  318. {
  319. if (debug)
  320. {
  321. PROFILE(OctreeDrawDebug);
  322. Octant::DrawDebugGeometry(debug, depthTest);
  323. }
  324. }
  325. void Octree::SetSize(const BoundingBox& box, unsigned numLevels)
  326. {
  327. PROFILE(ResizeOctree);
  328. // If drawables exist, they are temporarily moved to the root
  329. for (unsigned i = 0; i < NUM_OCTANTS; ++i)
  330. DeleteChild(i);
  331. Initialize(box);
  332. numDrawables_ = drawables_.Size();
  333. numLevels_ = (unsigned)Max((int)numLevels, 1);
  334. }
  335. void Octree::Update(const FrameInfo& frame)
  336. {
  337. // Let drawables update themselves before reinsertion. This can be used for animation
  338. if (!drawableUpdates_.Empty())
  339. {
  340. PROFILE(UpdateDrawables);
  341. // Perform updates in worker threads. Notify the scene that a threaded update is going on and components
  342. // (for example physics objects) should not perform non-threadsafe work when marked dirty
  343. Scene* scene = GetScene();
  344. WorkQueue* queue = GetSubsystem<WorkQueue>();
  345. scene->BeginThreadedUpdate();
  346. int numWorkItems = queue->GetNumThreads() + 1; // Worker threads + main thread
  347. int drawablesPerItem = Max((int)(drawableUpdates_.Size() / numWorkItems), 1);
  348. PODVector<Drawable*>::Iterator start = drawableUpdates_.Begin();
  349. // Create a work item for each thread
  350. for (int i = 0; i < numWorkItems; ++i)
  351. {
  352. SharedPtr<WorkItem> item = queue->GetFreeItem();
  353. item->priority_ = M_MAX_UNSIGNED;
  354. item->workFunction_ = UpdateDrawablesWork;
  355. item->aux_ = const_cast<FrameInfo*>(&frame);
  356. PODVector<Drawable*>::Iterator end = drawableUpdates_.End();
  357. if (i < numWorkItems - 1 && end - start > drawablesPerItem)
  358. end = start + drawablesPerItem;
  359. item->start_ = &(*start);
  360. item->end_ = &(*end);
  361. queue->AddWorkItem(item);
  362. start = end;
  363. }
  364. queue->Complete(M_MAX_UNSIGNED);
  365. scene->EndThreadedUpdate();
  366. }
  367. // Notify drawable update being finished. Custom animation (eg. IK) can be done at this point
  368. Scene* scene = GetScene();
  369. if (scene)
  370. {
  371. using namespace SceneDrawableUpdateFinished;
  372. VariantMap& eventData = GetEventDataMap();
  373. eventData[P_SCENE] = scene;
  374. eventData[P_TIMESTEP] = frame.timeStep_;
  375. scene->SendEvent(E_SCENEDRAWABLEUPDATEFINISHED, eventData);
  376. }
  377. // Reinsert drawables that have been moved or resized, or that have been newly added to the octree and do not sit inside
  378. // the proper octant yet
  379. if (!drawableUpdates_.Empty())
  380. {
  381. PROFILE(ReinsertToOctree);
  382. for (PODVector<Drawable*>::Iterator i = drawableUpdates_.Begin(); i != drawableUpdates_.End(); ++i)
  383. {
  384. Drawable* drawable = *i;
  385. drawable->updateQueued_ = false;
  386. Octant* octant = drawable->GetOctant();
  387. const BoundingBox& box = drawable->GetWorldBoundingBox();
  388. // Skip if no octant or does not belong to this octree anymore
  389. if (!octant || octant->GetRoot() != this)
  390. continue;
  391. // Skip if still fits the current octant
  392. if (drawable->IsOccludee() && octant->GetCullingBox().IsInside(box) == INSIDE && octant->CheckDrawableFit(box))
  393. continue;
  394. InsertDrawable(drawable);
  395. #ifdef _DEBUG
  396. // Verify that the drawable will be culled correctly
  397. octant = drawable->GetOctant();
  398. if (octant != this && octant->GetCullingBox().IsInside(box) != INSIDE)
  399. {
  400. LOGERROR("Drawable is not fully inside its octant's culling bounds: drawable box " + box.ToString() +
  401. " octant box " + octant->GetCullingBox().ToString());
  402. }
  403. #endif
  404. }
  405. }
  406. drawableUpdates_.Clear();
  407. }
  408. void Octree::AddManualDrawable(Drawable* drawable)
  409. {
  410. if (!drawable || drawable->GetOctant())
  411. return;
  412. AddDrawable(drawable);
  413. }
  414. void Octree::RemoveManualDrawable(Drawable* drawable)
  415. {
  416. if (!drawable)
  417. return;
  418. Octant* octant = drawable->GetOctant();
  419. if (octant && octant->GetRoot() == this)
  420. octant->RemoveDrawable(drawable);
  421. }
  422. void Octree::GetDrawables(OctreeQuery& query) const
  423. {
  424. query.result_.Clear();
  425. GetDrawablesInternal(query, false);
  426. }
  427. void Octree::Raycast(RayOctreeQuery& query) const
  428. {
  429. PROFILE(Raycast);
  430. query.result_.Clear();
  431. WorkQueue* queue = GetSubsystem<WorkQueue>();
  432. // If no worker threads or no triangle-level testing, or we are being called from a worker thread do not create work items
  433. if (query.level_ < RAY_TRIANGLE || !queue->GetNumThreads() || !Thread::IsMainThread() || queue->IsCompleting())
  434. GetDrawablesInternal(query);
  435. else
  436. {
  437. // Threaded ray query: first get the drawables
  438. rayQuery_ = &query;
  439. rayQueryDrawables_.Clear();
  440. GetDrawablesOnlyInternal(query, rayQueryDrawables_);
  441. // Check that amount of drawables is large enough to justify threading
  442. if (rayQueryDrawables_.Size() >= RAYCASTS_PER_WORK_ITEM * 2)
  443. {
  444. for (unsigned i = 0; i < rayQueryResults_.Size(); ++i)
  445. rayQueryResults_[i].Clear();
  446. PODVector<Drawable*>::Iterator start = rayQueryDrawables_.Begin();
  447. while (start != rayQueryDrawables_.End())
  448. {
  449. SharedPtr<WorkItem> item = queue->GetFreeItem();
  450. item->priority_ = M_MAX_UNSIGNED;
  451. item->workFunction_ = RaycastDrawablesWork;
  452. item->aux_ = const_cast<Octree*>(this);
  453. PODVector<Drawable*>::Iterator end = rayQueryDrawables_.End();
  454. if (end - start > RAYCASTS_PER_WORK_ITEM)
  455. end = start + RAYCASTS_PER_WORK_ITEM;
  456. item->start_ = &(*start);
  457. item->end_ = &(*end);
  458. queue->AddWorkItem(item);
  459. start = end;
  460. }
  461. // Merge per-thread results
  462. queue->Complete(M_MAX_UNSIGNED);
  463. for (unsigned i = 0; i < rayQueryResults_.Size(); ++i)
  464. query.result_.Insert(query.result_.End(), rayQueryResults_[i].Begin(), rayQueryResults_[i].End());
  465. }
  466. else
  467. {
  468. for (PODVector<Drawable*>::Iterator i = rayQueryDrawables_.Begin(); i != rayQueryDrawables_.End(); ++i)
  469. (*i)->ProcessRayQuery(query, query.result_);
  470. }
  471. }
  472. Sort(query.result_.Begin(), query.result_.End(), CompareRayQueryResults);
  473. }
  474. void Octree::RaycastSingle(RayOctreeQuery& query) const
  475. {
  476. PROFILE(Raycast);
  477. query.result_.Clear();
  478. rayQueryDrawables_.Clear();
  479. GetDrawablesOnlyInternal(query, rayQueryDrawables_);
  480. // Sort by increasing hit distance to AABB
  481. for (PODVector<Drawable*>::Iterator i = rayQueryDrawables_.Begin(); i != rayQueryDrawables_.End(); ++i)
  482. {
  483. Drawable* drawable = *i;
  484. drawable->SetSortValue(query.ray_.HitDistance(drawable->GetWorldBoundingBox()));
  485. }
  486. Sort(rayQueryDrawables_.Begin(), rayQueryDrawables_.End(), CompareDrawables);
  487. // Then do the actual test according to the query, and early-out as possible
  488. float closestHit = M_INFINITY;
  489. for (PODVector<Drawable*>::Iterator i = rayQueryDrawables_.Begin(); i != rayQueryDrawables_.End(); ++i)
  490. {
  491. Drawable* drawable = *i;
  492. if (drawable->GetSortValue() < Min(closestHit, query.maxDistance_))
  493. {
  494. unsigned oldSize = query.result_.Size();
  495. drawable->ProcessRayQuery(query, query.result_);
  496. if (query.result_.Size() > oldSize)
  497. closestHit = Min(closestHit, query.result_.Back().distance_);
  498. }
  499. else
  500. break;
  501. }
  502. if (query.result_.Size() > 1)
  503. {
  504. Sort(query.result_.Begin(), query.result_.End(), CompareRayQueryResults);
  505. query.result_.Resize(1);
  506. }
  507. }
  508. void Octree::QueueUpdate(Drawable* drawable)
  509. {
  510. Scene* scene = GetScene();
  511. if (scene && scene->IsThreadedUpdate())
  512. {
  513. MutexLock lock(octreeMutex_);
  514. drawableUpdates_.Push(drawable);
  515. }
  516. else
  517. drawableUpdates_.Push(drawable);
  518. drawable->updateQueued_ = true;
  519. }
  520. void Octree::CancelUpdate(Drawable* drawable)
  521. {
  522. drawableUpdates_.Remove(drawable);
  523. drawable->updateQueued_ = false;
  524. }
  525. void Octree::DrawDebugGeometry(bool depthTest)
  526. {
  527. DebugRenderer* debug = GetComponent<DebugRenderer>();
  528. DrawDebugGeometry(debug, depthTest);
  529. }
  530. void Octree::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  531. {
  532. // When running in headless mode, update the Octree manually during the RenderUpdate event
  533. Scene* scene = GetScene();
  534. if (!scene || !scene->IsUpdateEnabled())
  535. return;
  536. using namespace RenderUpdate;
  537. FrameInfo frame;
  538. frame.frameNumber_ = GetSubsystem<Time>()->GetFrameNumber();
  539. frame.timeStep_ = eventData[P_TIMESTEP].GetFloat();
  540. frame.camera_ = 0;
  541. Update(frame);
  542. }
  543. }