triangle_mesh.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. /**************************************************************************/
  2. /* triangle_mesh.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "triangle_mesh.h"
  31. #include "core/templates/sort_array.h"
  32. int TriangleMesh::_create_bvh(BVH *p_bvh, BVH **p_bb, int p_from, int p_size, int p_depth, int &r_max_depth, int &r_max_alloc) {
  33. if (p_depth > r_max_depth) {
  34. r_max_depth = p_depth;
  35. }
  36. if (p_size == 1) {
  37. return p_bb[p_from] - p_bvh;
  38. } else if (p_size == 0) {
  39. return -1;
  40. }
  41. AABB aabb;
  42. aabb = p_bb[p_from]->aabb;
  43. for (int i = 1; i < p_size; i++) {
  44. aabb.merge_with(p_bb[p_from + i]->aabb);
  45. }
  46. int li = aabb.get_longest_axis_index();
  47. switch (li) {
  48. case Vector3::AXIS_X: {
  49. SortArray<BVH *, BVHCmpX> sort_x;
  50. sort_x.nth_element(0, p_size, p_size / 2, &p_bb[p_from]);
  51. //sort_x.sort(&p_bb[p_from],p_size);
  52. } break;
  53. case Vector3::AXIS_Y: {
  54. SortArray<BVH *, BVHCmpY> sort_y;
  55. sort_y.nth_element(0, p_size, p_size / 2, &p_bb[p_from]);
  56. //sort_y.sort(&p_bb[p_from],p_size);
  57. } break;
  58. case Vector3::AXIS_Z: {
  59. SortArray<BVH *, BVHCmpZ> sort_z;
  60. sort_z.nth_element(0, p_size, p_size / 2, &p_bb[p_from]);
  61. //sort_z.sort(&p_bb[p_from],p_size);
  62. } break;
  63. }
  64. int left = _create_bvh(p_bvh, p_bb, p_from, p_size / 2, p_depth + 1, r_max_depth, r_max_alloc);
  65. int right = _create_bvh(p_bvh, p_bb, p_from + p_size / 2, p_size - p_size / 2, p_depth + 1, r_max_depth, r_max_alloc);
  66. int index = r_max_alloc++;
  67. BVH *_new = &p_bvh[index];
  68. _new->aabb = aabb;
  69. _new->center = aabb.get_center();
  70. _new->face_index = -1;
  71. _new->left = left;
  72. _new->right = right;
  73. return index;
  74. }
  75. void TriangleMesh::get_indices(Vector<int> *r_triangles_indices) const {
  76. if (!valid) {
  77. return;
  78. }
  79. const int triangles_num = triangles.size();
  80. // Parse vertices indices
  81. const Triangle *triangles_read = triangles.ptr();
  82. r_triangles_indices->resize(triangles_num * 3);
  83. int *r_indices_write = r_triangles_indices->ptrw();
  84. for (int i = 0; i < triangles_num; ++i) {
  85. r_indices_write[3 * i + 0] = triangles_read[i].indices[0];
  86. r_indices_write[3 * i + 1] = triangles_read[i].indices[1];
  87. r_indices_write[3 * i + 2] = triangles_read[i].indices[2];
  88. }
  89. }
  90. void TriangleMesh::create(const Vector<Vector3> &p_faces, const Vector<int32_t> &p_surface_indices) {
  91. valid = false;
  92. ERR_FAIL_COND(p_surface_indices.size() && p_surface_indices.size() != p_faces.size());
  93. int fc = p_faces.size();
  94. ERR_FAIL_COND(!fc || ((fc % 3) != 0));
  95. fc /= 3;
  96. triangles.resize(fc);
  97. bvh.resize(fc * 3); //will never be larger than this (todo make better)
  98. BVH *bw = bvh.ptrw();
  99. {
  100. //create faces and indices and base bvh
  101. //except for the Set for repeated triangles, everything
  102. //goes in-place.
  103. const Vector3 *r = p_faces.ptr();
  104. const int32_t *si = p_surface_indices.ptr();
  105. Triangle *w = triangles.ptrw();
  106. HashMap<Vector3, int> db;
  107. for (int i = 0; i < fc; i++) {
  108. Triangle &f = w[i];
  109. const Vector3 *v = &r[i * 3];
  110. for (int j = 0; j < 3; j++) {
  111. int vidx = -1;
  112. Vector3 vs = v[j].snappedf(0.0001);
  113. HashMap<Vector3, int>::Iterator E = db.find(vs);
  114. if (E) {
  115. vidx = E->value;
  116. } else {
  117. vidx = db.size();
  118. db[vs] = vidx;
  119. }
  120. f.indices[j] = vidx;
  121. if (j == 0) {
  122. bw[i].aabb.position = vs;
  123. } else {
  124. bw[i].aabb.expand_to(vs);
  125. }
  126. }
  127. f.normal = Face3(r[i * 3 + 0], r[i * 3 + 1], r[i * 3 + 2]).get_plane().get_normal();
  128. f.surface_index = si ? si[i] : 0;
  129. bw[i].left = -1;
  130. bw[i].right = -1;
  131. bw[i].face_index = i;
  132. bw[i].center = bw[i].aabb.get_center();
  133. }
  134. vertices.resize(db.size());
  135. Vector3 *vw = vertices.ptrw();
  136. for (const KeyValue<Vector3, int> &E : db) {
  137. vw[E.value] = E.key;
  138. }
  139. }
  140. Vector<BVH *> bwptrs;
  141. bwptrs.resize(fc);
  142. BVH **bwp = bwptrs.ptrw();
  143. for (int i = 0; i < fc; i++) {
  144. bwp[i] = &bw[i];
  145. }
  146. max_depth = 0;
  147. int max_alloc = fc;
  148. _create_bvh(bw, bwp, 0, fc, 1, max_depth, max_alloc);
  149. bvh.resize(max_alloc); //resize back
  150. valid = true;
  151. }
  152. bool TriangleMesh::intersect_segment(const Vector3 &p_begin, const Vector3 &p_end, Vector3 &r_point, Vector3 &r_normal, int32_t *r_surf_index, int32_t *r_face_index) const {
  153. if (!valid) {
  154. return false;
  155. }
  156. uint32_t *stack = (uint32_t *)alloca(sizeof(int) * max_depth);
  157. enum {
  158. TEST_AABB_BIT = 0,
  159. VISIT_LEFT_BIT = 1,
  160. VISIT_RIGHT_BIT = 2,
  161. VISIT_DONE_BIT = 3,
  162. VISITED_BIT_SHIFT = 29,
  163. NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
  164. VISITED_BIT_MASK = ~NODE_IDX_MASK,
  165. };
  166. Vector3 n = (p_end - p_begin).normalized();
  167. real_t d = 1e10;
  168. bool inters = false;
  169. int level = 0;
  170. const Triangle *triangleptr = triangles.ptr();
  171. const Vector3 *vertexptr = vertices.ptr();
  172. const BVH *bvhptr = bvh.ptr();
  173. int pos = bvh.size() - 1;
  174. stack[0] = pos;
  175. while (true) {
  176. uint32_t node = stack[level] & NODE_IDX_MASK;
  177. const BVH &b = bvhptr[node];
  178. bool done = false;
  179. switch (stack[level] >> VISITED_BIT_SHIFT) {
  180. case TEST_AABB_BIT: {
  181. if (!b.aabb.intersects_segment(p_begin, p_end)) {
  182. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  183. } else {
  184. if (b.face_index >= 0) {
  185. const Triangle &s = triangleptr[b.face_index];
  186. Face3 f3(vertexptr[s.indices[0]], vertexptr[s.indices[1]], vertexptr[s.indices[2]]);
  187. Vector3 res;
  188. if (f3.intersects_segment(p_begin, p_end, &res)) {
  189. real_t nd = n.dot(res);
  190. if (nd < d) {
  191. d = nd;
  192. r_point = res;
  193. r_normal = f3.get_plane().get_normal();
  194. if (r_surf_index) {
  195. *r_surf_index = s.surface_index;
  196. }
  197. if (r_face_index) {
  198. *r_face_index = b.face_index;
  199. }
  200. inters = true;
  201. }
  202. }
  203. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  204. } else {
  205. stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
  206. }
  207. }
  208. continue;
  209. }
  210. case VISIT_LEFT_BIT: {
  211. stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
  212. level++;
  213. stack[level] = b.left | TEST_AABB_BIT;
  214. continue;
  215. }
  216. case VISIT_RIGHT_BIT: {
  217. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  218. level++;
  219. stack[level] = b.right | TEST_AABB_BIT;
  220. continue;
  221. }
  222. case VISIT_DONE_BIT: {
  223. if (level == 0) {
  224. done = true;
  225. break;
  226. } else {
  227. level--;
  228. }
  229. continue;
  230. }
  231. }
  232. if (done) {
  233. break;
  234. }
  235. }
  236. if (inters) {
  237. if (n.dot(r_normal) > 0) {
  238. r_normal = -r_normal;
  239. }
  240. }
  241. return inters;
  242. }
  243. bool TriangleMesh::intersect_ray(const Vector3 &p_begin, const Vector3 &p_dir, Vector3 &r_point, Vector3 &r_normal, int32_t *r_surf_index, int32_t *r_face_index) const {
  244. if (!valid) {
  245. return false;
  246. }
  247. uint32_t *stack = (uint32_t *)alloca(sizeof(int) * max_depth);
  248. enum {
  249. TEST_AABB_BIT = 0,
  250. VISIT_LEFT_BIT = 1,
  251. VISIT_RIGHT_BIT = 2,
  252. VISIT_DONE_BIT = 3,
  253. VISITED_BIT_SHIFT = 29,
  254. NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
  255. VISITED_BIT_MASK = ~NODE_IDX_MASK,
  256. };
  257. Vector3 n = p_dir;
  258. real_t d = 1e20;
  259. bool inters = false;
  260. int level = 0;
  261. const Triangle *triangleptr = triangles.ptr();
  262. const Vector3 *vertexptr = vertices.ptr();
  263. const BVH *bvhptr = bvh.ptr();
  264. int pos = bvh.size() - 1;
  265. stack[0] = pos;
  266. while (true) {
  267. uint32_t node = stack[level] & NODE_IDX_MASK;
  268. const BVH &b = bvhptr[node];
  269. bool done = false;
  270. switch (stack[level] >> VISITED_BIT_SHIFT) {
  271. case TEST_AABB_BIT: {
  272. if (!b.aabb.intersects_ray(p_begin, p_dir)) {
  273. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  274. } else {
  275. if (b.face_index >= 0) {
  276. const Triangle &s = triangleptr[b.face_index];
  277. Face3 f3(vertexptr[s.indices[0]], vertexptr[s.indices[1]], vertexptr[s.indices[2]]);
  278. Vector3 res;
  279. if (f3.intersects_ray(p_begin, p_dir, &res)) {
  280. real_t nd = n.dot(res);
  281. if (nd < d) {
  282. d = nd;
  283. r_point = res;
  284. r_normal = f3.get_plane().get_normal();
  285. if (r_surf_index) {
  286. *r_surf_index = s.surface_index;
  287. }
  288. if (r_face_index) {
  289. *r_face_index = b.face_index;
  290. }
  291. inters = true;
  292. }
  293. }
  294. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  295. } else {
  296. stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
  297. }
  298. }
  299. continue;
  300. }
  301. case VISIT_LEFT_BIT: {
  302. stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
  303. level++;
  304. stack[level] = b.left | TEST_AABB_BIT;
  305. continue;
  306. }
  307. case VISIT_RIGHT_BIT: {
  308. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  309. level++;
  310. stack[level] = b.right | TEST_AABB_BIT;
  311. continue;
  312. }
  313. case VISIT_DONE_BIT: {
  314. if (level == 0) {
  315. done = true;
  316. break;
  317. } else {
  318. level--;
  319. }
  320. continue;
  321. }
  322. }
  323. if (done) {
  324. break;
  325. }
  326. }
  327. if (inters) {
  328. if (n.dot(r_normal) > 0) {
  329. r_normal = -r_normal;
  330. }
  331. }
  332. return inters;
  333. }
  334. bool TriangleMesh::inside_convex_shape(const Plane *p_planes, int p_plane_count, const Vector3 *p_points, int p_point_count, Vector3 p_scale) const {
  335. if (!valid) {
  336. return false;
  337. }
  338. uint32_t *stack = (uint32_t *)alloca(sizeof(int) * max_depth);
  339. enum {
  340. TEST_AABB_BIT = 0,
  341. VISIT_LEFT_BIT = 1,
  342. VISIT_RIGHT_BIT = 2,
  343. VISIT_DONE_BIT = 3,
  344. VISITED_BIT_SHIFT = 29,
  345. NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
  346. VISITED_BIT_MASK = ~NODE_IDX_MASK,
  347. };
  348. int level = 0;
  349. const Triangle *triangleptr = triangles.ptr();
  350. const Vector3 *vertexptr = vertices.ptr();
  351. const BVH *bvhptr = bvh.ptr();
  352. Transform3D scale(Basis().scaled(p_scale));
  353. int pos = bvh.size() - 1;
  354. stack[0] = pos;
  355. while (true) {
  356. uint32_t node = stack[level] & NODE_IDX_MASK;
  357. const BVH &b = bvhptr[node];
  358. bool done = false;
  359. switch (stack[level] >> VISITED_BIT_SHIFT) {
  360. case TEST_AABB_BIT: {
  361. bool intersects = scale.xform(b.aabb).intersects_convex_shape(p_planes, p_plane_count, p_points, p_point_count);
  362. if (!intersects) {
  363. return false;
  364. }
  365. bool inside = scale.xform(b.aabb).inside_convex_shape(p_planes, p_plane_count);
  366. if (inside) {
  367. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  368. } else {
  369. if (b.face_index >= 0) {
  370. const Triangle &s = triangleptr[b.face_index];
  371. for (int j = 0; j < 3; ++j) {
  372. Vector3 point = scale.xform(vertexptr[s.indices[j]]);
  373. for (int i = 0; i < p_plane_count; i++) {
  374. const Plane &p = p_planes[i];
  375. if (p.is_point_over(point)) {
  376. return false;
  377. }
  378. }
  379. }
  380. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  381. } else {
  382. stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
  383. }
  384. }
  385. continue;
  386. }
  387. case VISIT_LEFT_BIT: {
  388. stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
  389. level++;
  390. stack[level] = b.left | TEST_AABB_BIT;
  391. continue;
  392. }
  393. case VISIT_RIGHT_BIT: {
  394. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  395. level++;
  396. stack[level] = b.right | TEST_AABB_BIT;
  397. continue;
  398. }
  399. case VISIT_DONE_BIT: {
  400. if (level == 0) {
  401. done = true;
  402. break;
  403. } else {
  404. level--;
  405. }
  406. continue;
  407. }
  408. }
  409. if (done) {
  410. break;
  411. }
  412. }
  413. return true;
  414. }
  415. bool TriangleMesh::is_valid() const {
  416. return valid;
  417. }
  418. Vector<Face3> TriangleMesh::get_faces() const {
  419. if (!valid) {
  420. return Vector<Face3>();
  421. }
  422. Vector<Face3> faces;
  423. int ts = triangles.size();
  424. faces.resize(triangles.size());
  425. Face3 *w = faces.ptrw();
  426. const Triangle *r = triangles.ptr();
  427. const Vector3 *rv = vertices.ptr();
  428. for (int i = 0; i < ts; i++) {
  429. for (int j = 0; j < 3; j++) {
  430. w[i].vertex[j] = rv[r[i].indices[j]];
  431. }
  432. }
  433. return faces;
  434. }
  435. bool TriangleMesh::create_from_faces(const Vector<Vector3> &p_faces) {
  436. create(p_faces);
  437. return is_valid();
  438. }
  439. Dictionary TriangleMesh::intersect_segment_scriptwrap(const Vector3 &p_begin, const Vector3 &p_end) const {
  440. if (!valid) {
  441. return Dictionary();
  442. }
  443. Vector3 r_point;
  444. Vector3 r_normal;
  445. int32_t r_face_index = -1;
  446. bool intersected = intersect_segment(p_begin, p_end, r_point, r_normal, nullptr, &r_face_index);
  447. if (!intersected) {
  448. return Dictionary();
  449. }
  450. Dictionary result;
  451. result["position"] = r_point;
  452. result["normal"] = r_normal;
  453. result["face_index"] = r_face_index;
  454. return result;
  455. }
  456. Dictionary TriangleMesh::intersect_ray_scriptwrap(const Vector3 &p_begin, const Vector3 &p_dir) const {
  457. if (!valid) {
  458. return Dictionary();
  459. }
  460. Vector3 r_point;
  461. Vector3 r_normal;
  462. int32_t r_face_index = -1;
  463. bool intersected = intersect_ray(p_begin, p_dir, r_point, r_normal, nullptr, &r_face_index);
  464. if (!intersected) {
  465. return Dictionary();
  466. }
  467. Dictionary result;
  468. result["position"] = r_point;
  469. result["normal"] = r_normal;
  470. result["face_index"] = r_face_index;
  471. return result;
  472. }
  473. Vector<Vector3> TriangleMesh::get_faces_scriptwrap() const {
  474. if (!valid) {
  475. return Vector<Vector3>();
  476. }
  477. Vector<Vector3> faces;
  478. int ts = triangles.size();
  479. faces.resize(triangles.size() * 3);
  480. Vector3 *w = faces.ptrw();
  481. const Triangle *r = triangles.ptr();
  482. const Vector3 *rv = vertices.ptr();
  483. for (int i = 0; i < ts; i++) {
  484. for (int j = 0; j < 3; j++) {
  485. w[i * 3 + j] = rv[r[i].indices[j]];
  486. }
  487. }
  488. return faces;
  489. }
  490. void TriangleMesh::_bind_methods() {
  491. ClassDB::bind_method(D_METHOD("create_from_faces", "faces"), &TriangleMesh::create_from_faces);
  492. ClassDB::bind_method(D_METHOD("get_faces"), &TriangleMesh::get_faces_scriptwrap);
  493. ClassDB::bind_method(D_METHOD("intersect_segment", "begin", "end"), &TriangleMesh::intersect_segment_scriptwrap);
  494. ClassDB::bind_method(D_METHOD("intersect_ray", "begin", "dir"), &TriangleMesh::intersect_ray_scriptwrap);
  495. }
  496. TriangleMesh::TriangleMesh() {
  497. valid = false;
  498. max_depth = 0;
  499. }