broad_phase_2d_hash_grid.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. /*************************************************************************/
  2. /* broad_phase_2d_hash_grid.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "broad_phase_2d_hash_grid.h"
  31. #include "collision_object_2d_sw.h"
  32. #include "core/project_settings.h"
  33. #define LARGE_ELEMENT_FI 1.01239812
  34. void BroadPhase2DHashGrid::_pair_attempt(Element *p_elem, Element *p_with) {
  35. Map<Element *, PairData *>::Element *E = p_elem->paired.find(p_with);
  36. ERR_FAIL_COND(p_elem->_static && p_with->_static);
  37. if (!E) {
  38. PairData *pd = memnew(PairData);
  39. p_elem->paired[p_with] = pd;
  40. p_with->paired[p_elem] = pd;
  41. } else {
  42. E->get()->rc++;
  43. }
  44. }
  45. void BroadPhase2DHashGrid::_unpair_attempt(Element *p_elem, Element *p_with) {
  46. Map<Element *, PairData *>::Element *E = p_elem->paired.find(p_with);
  47. ERR_FAIL_COND(!E); //this should really be paired..
  48. E->get()->rc--;
  49. if (E->get()->rc == 0) {
  50. if (E->get()->colliding) {
  51. //uncollide
  52. if (unpair_callback) {
  53. unpair_callback(p_elem->owner, p_elem->subindex, p_with->owner, p_with->subindex, E->get()->ud, unpair_userdata);
  54. }
  55. }
  56. memdelete(E->get());
  57. p_elem->paired.erase(E);
  58. p_with->paired.erase(p_elem);
  59. }
  60. }
  61. void BroadPhase2DHashGrid::_check_motion(Element *p_elem) {
  62. for (Map<Element *, PairData *>::Element *E = p_elem->paired.front(); E; E = E->next()) {
  63. bool physical_collision = p_elem->aabb.intersects(E->key()->aabb);
  64. bool logical_collision = p_elem->owner->test_collision_mask(E->key()->owner);
  65. if (physical_collision) {
  66. if (!E->get()->colliding || (logical_collision && !E->get()->ud && pair_callback)) {
  67. E->get()->ud = pair_callback(p_elem->owner, p_elem->subindex, E->key()->owner, E->key()->subindex, pair_userdata);
  68. } else if (E->get()->colliding && !logical_collision && E->get()->ud && unpair_callback) {
  69. unpair_callback(p_elem->owner, p_elem->subindex, E->key()->owner, E->key()->subindex, E->get()->ud, unpair_userdata);
  70. E->get()->ud = nullptr;
  71. }
  72. E->get()->colliding = true;
  73. } else { // No physcial_collision
  74. if (E->get()->colliding && unpair_callback) {
  75. unpair_callback(p_elem->owner, p_elem->subindex, E->key()->owner, E->key()->subindex, E->get()->ud, unpair_userdata);
  76. }
  77. E->get()->colliding = false;
  78. }
  79. }
  80. }
  81. void BroadPhase2DHashGrid::_enter_grid(Element *p_elem, const Rect2 &p_rect, bool p_static) {
  82. Vector2 sz = (p_rect.size / cell_size * LARGE_ELEMENT_FI); //use magic number to avoid floating point issues
  83. if (sz.width * sz.height > large_object_min_surface) {
  84. //large object, do not use grid, must check against all elements
  85. for (Map<ID, Element>::Element *E = element_map.front(); E; E = E->next()) {
  86. if (E->key() == p_elem->self)
  87. continue; // do not pair against itself
  88. if (E->get().owner == p_elem->owner)
  89. continue;
  90. if (E->get()._static && p_static)
  91. continue;
  92. _pair_attempt(p_elem, &E->get());
  93. }
  94. large_elements[p_elem].inc();
  95. return;
  96. }
  97. Point2i from = (p_rect.position / cell_size).floor();
  98. Point2i to = ((p_rect.position + p_rect.size) / cell_size).floor();
  99. for (int i = from.x; i <= to.x; i++) {
  100. for (int j = from.y; j <= to.y; j++) {
  101. PosKey pk;
  102. pk.x = i;
  103. pk.y = j;
  104. uint32_t idx = pk.hash() % hash_table_size;
  105. PosBin *pb = hash_table[idx];
  106. while (pb) {
  107. if (pb->key == pk) {
  108. break;
  109. }
  110. pb = pb->next;
  111. }
  112. bool entered = false;
  113. if (!pb) {
  114. //does not exist, create!
  115. pb = memnew(PosBin);
  116. pb->key = pk;
  117. pb->next = hash_table[idx];
  118. hash_table[idx] = pb;
  119. }
  120. if (p_static) {
  121. if (pb->static_object_set[p_elem].inc() == 1) {
  122. entered = true;
  123. }
  124. } else {
  125. if (pb->object_set[p_elem].inc() == 1) {
  126. entered = true;
  127. }
  128. }
  129. if (entered) {
  130. for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) {
  131. if (E->key()->owner == p_elem->owner)
  132. continue;
  133. _pair_attempt(p_elem, E->key());
  134. }
  135. if (!p_static) {
  136. for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) {
  137. if (E->key()->owner == p_elem->owner)
  138. continue;
  139. _pair_attempt(p_elem, E->key());
  140. }
  141. }
  142. }
  143. }
  144. }
  145. //pair separatedly with large elements
  146. for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
  147. if (E->key() == p_elem)
  148. continue; // do not pair against itself
  149. if (E->key()->owner == p_elem->owner)
  150. continue;
  151. if (E->key()->_static && p_static)
  152. continue;
  153. _pair_attempt(E->key(), p_elem);
  154. }
  155. }
  156. void BroadPhase2DHashGrid::_exit_grid(Element *p_elem, const Rect2 &p_rect, bool p_static) {
  157. Vector2 sz = (p_rect.size / cell_size * LARGE_ELEMENT_FI);
  158. if (sz.width * sz.height > large_object_min_surface) {
  159. //unpair all elements, instead of checking all, just check what is already paired, so we at least save from checking static vs static
  160. Map<Element *, PairData *>::Element *E = p_elem->paired.front();
  161. while (E) {
  162. Map<Element *, PairData *>::Element *next = E->next();
  163. _unpair_attempt(p_elem, E->key());
  164. E = next;
  165. }
  166. if (large_elements[p_elem].dec() == 0) {
  167. large_elements.erase(p_elem);
  168. }
  169. return;
  170. }
  171. Point2i from = (p_rect.position / cell_size).floor();
  172. Point2i to = ((p_rect.position + p_rect.size) / cell_size).floor();
  173. for (int i = from.x; i <= to.x; i++) {
  174. for (int j = from.y; j <= to.y; j++) {
  175. PosKey pk;
  176. pk.x = i;
  177. pk.y = j;
  178. uint32_t idx = pk.hash() % hash_table_size;
  179. PosBin *pb = hash_table[idx];
  180. while (pb) {
  181. if (pb->key == pk) {
  182. break;
  183. }
  184. pb = pb->next;
  185. }
  186. ERR_CONTINUE(!pb); //should exist!!
  187. bool exited = false;
  188. if (p_static) {
  189. if (pb->static_object_set[p_elem].dec() == 0) {
  190. pb->static_object_set.erase(p_elem);
  191. exited = true;
  192. }
  193. } else {
  194. if (pb->object_set[p_elem].dec() == 0) {
  195. pb->object_set.erase(p_elem);
  196. exited = true;
  197. }
  198. }
  199. if (exited) {
  200. for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) {
  201. if (E->key()->owner == p_elem->owner)
  202. continue;
  203. _unpair_attempt(p_elem, E->key());
  204. }
  205. if (!p_static) {
  206. for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) {
  207. if (E->key()->owner == p_elem->owner)
  208. continue;
  209. _unpair_attempt(p_elem, E->key());
  210. }
  211. }
  212. }
  213. if (pb->object_set.empty() && pb->static_object_set.empty()) {
  214. if (hash_table[idx] == pb) {
  215. hash_table[idx] = pb->next;
  216. } else {
  217. PosBin *px = hash_table[idx];
  218. while (px) {
  219. if (px->next == pb) {
  220. px->next = pb->next;
  221. break;
  222. }
  223. px = px->next;
  224. }
  225. ERR_CONTINUE(!px);
  226. }
  227. memdelete(pb);
  228. }
  229. }
  230. }
  231. for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
  232. if (E->key() == p_elem)
  233. continue; // do not pair against itself
  234. if (E->key()->owner == p_elem->owner)
  235. continue;
  236. if (E->key()->_static && p_static)
  237. continue;
  238. //unpair from large elements
  239. _unpair_attempt(p_elem, E->key());
  240. }
  241. }
  242. BroadPhase2DHashGrid::ID BroadPhase2DHashGrid::create(CollisionObject2DSW *p_object, int p_subindex) {
  243. current++;
  244. Element e;
  245. e.owner = p_object;
  246. e._static = false;
  247. e.subindex = p_subindex;
  248. e.self = current;
  249. e.pass = 0;
  250. element_map[current] = e;
  251. return current;
  252. }
  253. void BroadPhase2DHashGrid::move(ID p_id, const Rect2 &p_aabb) {
  254. Map<ID, Element>::Element *E = element_map.find(p_id);
  255. ERR_FAIL_COND(!E);
  256. Element &e = E->get();
  257. if (p_aabb != e.aabb) {
  258. if (p_aabb != Rect2()) {
  259. _enter_grid(&e, p_aabb, e._static);
  260. }
  261. if (e.aabb != Rect2()) {
  262. _exit_grid(&e, e.aabb, e._static);
  263. }
  264. e.aabb = p_aabb;
  265. }
  266. _check_motion(&e);
  267. }
  268. void BroadPhase2DHashGrid::set_static(ID p_id, bool p_static) {
  269. Map<ID, Element>::Element *E = element_map.find(p_id);
  270. ERR_FAIL_COND(!E);
  271. Element &e = E->get();
  272. if (e._static == p_static)
  273. return;
  274. if (e.aabb != Rect2())
  275. _exit_grid(&e, e.aabb, e._static);
  276. e._static = p_static;
  277. if (e.aabb != Rect2()) {
  278. _enter_grid(&e, e.aabb, e._static);
  279. _check_motion(&e);
  280. }
  281. }
  282. void BroadPhase2DHashGrid::remove(ID p_id) {
  283. Map<ID, Element>::Element *E = element_map.find(p_id);
  284. ERR_FAIL_COND(!E);
  285. Element &e = E->get();
  286. if (e.aabb != Rect2())
  287. _exit_grid(&e, e.aabb, e._static);
  288. element_map.erase(p_id);
  289. }
  290. CollisionObject2DSW *BroadPhase2DHashGrid::get_object(ID p_id) const {
  291. const Map<ID, Element>::Element *E = element_map.find(p_id);
  292. ERR_FAIL_COND_V(!E, NULL);
  293. return E->get().owner;
  294. }
  295. bool BroadPhase2DHashGrid::is_static(ID p_id) const {
  296. const Map<ID, Element>::Element *E = element_map.find(p_id);
  297. ERR_FAIL_COND_V(!E, false);
  298. return E->get()._static;
  299. }
  300. int BroadPhase2DHashGrid::get_subindex(ID p_id) const {
  301. const Map<ID, Element>::Element *E = element_map.find(p_id);
  302. ERR_FAIL_COND_V(!E, -1);
  303. return E->get().subindex;
  304. }
  305. template <bool use_aabb, bool use_segment>
  306. void BroadPhase2DHashGrid::_cull(const Point2i p_cell, const Rect2 &p_aabb, const Point2 &p_from, const Point2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices, int &index) {
  307. PosKey pk;
  308. pk.x = p_cell.x;
  309. pk.y = p_cell.y;
  310. uint32_t idx = pk.hash() % hash_table_size;
  311. PosBin *pb = hash_table[idx];
  312. while (pb) {
  313. if (pb->key == pk) {
  314. break;
  315. }
  316. pb = pb->next;
  317. }
  318. if (!pb)
  319. return;
  320. for (Map<Element *, RC>::Element *E = pb->object_set.front(); E; E = E->next()) {
  321. if (index >= p_max_results)
  322. break;
  323. if (E->key()->pass == pass)
  324. continue;
  325. E->key()->pass = pass;
  326. if (use_aabb && !p_aabb.intersects(E->key()->aabb))
  327. continue;
  328. if (use_segment && !E->key()->aabb.intersects_segment(p_from, p_to))
  329. continue;
  330. p_results[index] = E->key()->owner;
  331. p_result_indices[index] = E->key()->subindex;
  332. index++;
  333. }
  334. for (Map<Element *, RC>::Element *E = pb->static_object_set.front(); E; E = E->next()) {
  335. if (index >= p_max_results)
  336. break;
  337. if (E->key()->pass == pass)
  338. continue;
  339. if (use_aabb && !p_aabb.intersects(E->key()->aabb)) {
  340. continue;
  341. }
  342. if (use_segment && !E->key()->aabb.intersects_segment(p_from, p_to))
  343. continue;
  344. E->key()->pass = pass;
  345. p_results[index] = E->key()->owner;
  346. p_result_indices[index] = E->key()->subindex;
  347. index++;
  348. }
  349. }
  350. int BroadPhase2DHashGrid::cull_segment(const Vector2 &p_from, const Vector2 &p_to, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) {
  351. pass++;
  352. Vector2 dir = (p_to - p_from);
  353. if (dir == Vector2())
  354. return 0;
  355. //avoid divisions by zero
  356. dir.normalize();
  357. if (dir.x == 0.0)
  358. dir.x = 0.000001;
  359. if (dir.y == 0.0)
  360. dir.y = 0.000001;
  361. Vector2 delta = dir.abs();
  362. delta.x = cell_size / delta.x;
  363. delta.y = cell_size / delta.y;
  364. Point2i pos = (p_from / cell_size).floor();
  365. Point2i end = (p_to / cell_size).floor();
  366. Point2i step = Vector2(SGN(dir.x), SGN(dir.y));
  367. Vector2 max;
  368. if (dir.x < 0)
  369. max.x = (Math::floor((double)pos.x) * cell_size - p_from.x) / dir.x;
  370. else
  371. max.x = (Math::floor((double)pos.x + 1) * cell_size - p_from.x) / dir.x;
  372. if (dir.y < 0)
  373. max.y = (Math::floor((double)pos.y) * cell_size - p_from.y) / dir.y;
  374. else
  375. max.y = (Math::floor((double)pos.y + 1) * cell_size - p_from.y) / dir.y;
  376. int cullcount = 0;
  377. _cull<false, true>(pos, Rect2(), p_from, p_to, p_results, p_max_results, p_result_indices, cullcount);
  378. bool reached_x = false;
  379. bool reached_y = false;
  380. while (true) {
  381. if (max.x < max.y) {
  382. max.x += delta.x;
  383. pos.x += step.x;
  384. } else {
  385. max.y += delta.y;
  386. pos.y += step.y;
  387. }
  388. if (step.x > 0) {
  389. if (pos.x >= end.x)
  390. reached_x = true;
  391. } else if (pos.x <= end.x) {
  392. reached_x = true;
  393. }
  394. if (step.y > 0) {
  395. if (pos.y >= end.y)
  396. reached_y = true;
  397. } else if (pos.y <= end.y) {
  398. reached_y = true;
  399. }
  400. _cull<false, true>(pos, Rect2(), p_from, p_to, p_results, p_max_results, p_result_indices, cullcount);
  401. if (reached_x && reached_y)
  402. break;
  403. }
  404. for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
  405. if (cullcount >= p_max_results)
  406. break;
  407. if (E->key()->pass == pass)
  408. continue;
  409. E->key()->pass = pass;
  410. /*
  411. if (use_aabb && !p_aabb.intersects(E->key()->aabb))
  412. continue;
  413. */
  414. if (!E->key()->aabb.intersects_segment(p_from, p_to))
  415. continue;
  416. p_results[cullcount] = E->key()->owner;
  417. p_result_indices[cullcount] = E->key()->subindex;
  418. cullcount++;
  419. }
  420. return cullcount;
  421. }
  422. int BroadPhase2DHashGrid::cull_aabb(const Rect2 &p_aabb, CollisionObject2DSW **p_results, int p_max_results, int *p_result_indices) {
  423. pass++;
  424. Point2i from = (p_aabb.position / cell_size).floor();
  425. Point2i to = ((p_aabb.position + p_aabb.size) / cell_size).floor();
  426. int cullcount = 0;
  427. for (int i = from.x; i <= to.x; i++) {
  428. for (int j = from.y; j <= to.y; j++) {
  429. _cull<true, false>(Point2i(i, j), p_aabb, Point2(), Point2(), p_results, p_max_results, p_result_indices, cullcount);
  430. }
  431. }
  432. for (Map<Element *, RC>::Element *E = large_elements.front(); E; E = E->next()) {
  433. if (cullcount >= p_max_results)
  434. break;
  435. if (E->key()->pass == pass)
  436. continue;
  437. E->key()->pass = pass;
  438. if (!p_aabb.intersects(E->key()->aabb))
  439. continue;
  440. /*
  441. if (!E->key()->aabb.intersects_segment(p_from,p_to))
  442. continue;
  443. */
  444. p_results[cullcount] = E->key()->owner;
  445. p_result_indices[cullcount] = E->key()->subindex;
  446. cullcount++;
  447. }
  448. return cullcount;
  449. }
  450. void BroadPhase2DHashGrid::set_pair_callback(PairCallback p_pair_callback, void *p_userdata) {
  451. pair_callback = p_pair_callback;
  452. pair_userdata = p_userdata;
  453. }
  454. void BroadPhase2DHashGrid::set_unpair_callback(UnpairCallback p_unpair_callback, void *p_userdata) {
  455. unpair_callback = p_unpair_callback;
  456. unpair_userdata = p_userdata;
  457. }
  458. void BroadPhase2DHashGrid::update() {
  459. }
  460. BroadPhase2DSW *BroadPhase2DHashGrid::_create() {
  461. return memnew(BroadPhase2DHashGrid);
  462. }
  463. BroadPhase2DHashGrid::BroadPhase2DHashGrid() {
  464. hash_table_size = GLOBAL_DEF("physics/2d/bp_hash_table_size", 4096);
  465. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/bp_hash_table_size", PropertyInfo(Variant::INT, "physics/2d/bp_hash_table_size", PROPERTY_HINT_RANGE, "0,8192,1,or_greater"));
  466. hash_table_size = Math::larger_prime(hash_table_size);
  467. hash_table = memnew_arr(PosBin *, hash_table_size);
  468. cell_size = GLOBAL_DEF("physics/2d/cell_size", 128);
  469. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/cell_size", PropertyInfo(Variant::INT, "physics/2d/cell_size", PROPERTY_HINT_RANGE, "0,512,1,or_greater"));
  470. large_object_min_surface = GLOBAL_DEF("physics/2d/large_object_surface_threshold_in_cells", 512);
  471. ProjectSettings::get_singleton()->set_custom_property_info("physics/2d/large_object_surface_threshold_in_cells", PropertyInfo(Variant::INT, "physics/2d/large_object_surface_threshold_in_cells", PROPERTY_HINT_RANGE, "0,1024,1,or_greater"));
  472. for (uint32_t i = 0; i < hash_table_size; i++)
  473. hash_table[i] = NULL;
  474. pass = 1;
  475. current = 0;
  476. }
  477. BroadPhase2DHashGrid::~BroadPhase2DHashGrid() {
  478. for (uint32_t i = 0; i < hash_table_size; i++) {
  479. while (hash_table[i]) {
  480. PosBin *pb = hash_table[i];
  481. hash_table[i] = pb->next;
  482. memdelete(pb);
  483. }
  484. }
  485. memdelete_arr(hash_table);
  486. }
  487. /* 3D version of voxel traversal:
  488. public IEnumerable<Point3D> GetCellsOnRay(Ray ray, int maxDepth)
  489. {
  490. // Implementation is based on:
  491. // "A Fast Voxel Traversal Algorithm for Ray Tracing"
  492. // John Amanatides, Andrew Woo
  493. // http://www.cse.yorku.ca/~amana/research/grid.pdf
  494. // https://web.archive.org/web/20100616193049/http://www.devmaster.net/articles/raytracing_series/A%20faster%20voxel%20traversal%20algorithm%20for%20ray%20tracing.pdf
  495. // NOTES:
  496. // * This code assumes that the ray's position and direction are in 'cell coordinates', which means
  497. // that one unit equals one cell in all directions.
  498. // * When the ray doesn't start within the voxel grid, calculate the first position at which the
  499. // ray could enter the grid. If it never enters the grid, there is nothing more to do here.
  500. // * Also, it is important to test when the ray exits the voxel grid when the grid isn't infinite.
  501. // * The Point3D structure is a simple structure having three integer fields (X, Y and Z).
  502. // The cell in which the ray starts.
  503. Point3D start = GetCellAt(ray.Position); // Rounds the position's X, Y and Z down to the nearest integer values.
  504. int x = start.X;
  505. int y = start.Y;
  506. int z = start.Z;
  507. // Determine which way we go.
  508. int stepX = Math.Sign(ray.Direction.X);
  509. int stepY = Math.Sign(ray.Direction.Y);
  510. int stepZ = Math.Sign(ray.Direction.Z);
  511. // Calculate cell boundaries. When the step (i.e. direction sign) is positive,
  512. // the next boundary is AFTER our current position, meaning that we have to add 1.
  513. // Otherwise, it is BEFORE our current position, in which case we add nothing.
  514. Point3D cellBoundary = new Point3D(
  515. x + (stepX > 0 ? 1 : 0),
  516. y + (stepY > 0 ? 1 : 0),
  517. z + (stepZ > 0 ? 1 : 0));
  518. // NOTE: For the following calculations, the result will be Single.PositiveInfinity
  519. // when ray.Direction.X, Y or Z equals zero, which is OK. However, when the left-hand
  520. // value of the division also equals zero, the result is Single.NaN, which is not OK.
  521. // Determine how far we can travel along the ray before we hit a voxel boundary.
  522. Vector3 tMax = new Vector3(
  523. (cellBoundary.X - ray.Position.X) / ray.Direction.X, // Boundary is a plane on the YZ axis.
  524. (cellBoundary.Y - ray.Position.Y) / ray.Direction.Y, // Boundary is a plane on the XZ axis.
  525. (cellBoundary.Z - ray.Position.Z) / ray.Direction.Z); // Boundary is a plane on the XY axis.
  526. if (Single.IsNaN(tMax.X)) tMax.X = Single.PositiveInfinity;
  527. if (Single.IsNaN(tMax.Y)) tMax.Y = Single.PositiveInfinity;
  528. if (Single.IsNaN(tMax.Z)) tMax.Z = Single.PositiveInfinity;
  529. // Determine how far we must travel along the ray before we have crossed a gridcell.
  530. Vector3 tDelta = new Vector3(
  531. stepX / ray.Direction.X, // Crossing the width of a cell.
  532. stepY / ray.Direction.Y, // Crossing the height of a cell.
  533. stepZ / ray.Direction.Z); // Crossing the depth of a cell.
  534. if (Single.IsNaN(tDelta.X)) tDelta.X = Single.PositiveInfinity;
  535. if (Single.IsNaN(tDelta.Y)) tDelta.Y = Single.PositiveInfinity;
  536. if (Single.IsNaN(tDelta.Z)) tDelta.Z = Single.PositiveInfinity;
  537. // For each step, determine which distance to the next voxel boundary is lowest (i.e.
  538. // which voxel boundary is nearest) and walk that way.
  539. for (int i = 0; i < maxDepth; i++)
  540. {
  541. // Return it.
  542. yield return new Point3D(x, y, z);
  543. // Do the next step.
  544. if (tMax.X < tMax.Y && tMax.X < tMax.Z)
  545. {
  546. // tMax.X is the lowest, an YZ cell boundary plane is nearest.
  547. x += stepX;
  548. tMax.X += tDelta.X;
  549. }
  550. else if (tMax.Y < tMax.Z)
  551. {
  552. // tMax.Y is the lowest, an XZ cell boundary plane is nearest.
  553. y += stepY;
  554. tMax.Y += tDelta.Y;
  555. }
  556. else
  557. {
  558. // tMax.Z is the lowest, an XY cell boundary plane is nearest.
  559. z += stepZ;
  560. tMax.Z += tDelta.Z;
  561. }
  562. }
  563. */