csg.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. /**************************************************************************/
  2. /* csg.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 "csg.h"
  31. #include "core/math/geometry.h"
  32. #include "core/math/math_funcs.h"
  33. #include "core/sort_array.h"
  34. // Static helper functions.
  35. inline static bool is_snapable(const Vector3 &p_point1, const Vector3 &p_point2, real_t p_distance) {
  36. return (p_point1 - p_point2).length_squared() < p_distance * p_distance;
  37. }
  38. inline static Vector2 interpolate_segment_uv(const Vector2 p_segement_points[2], const Vector2 p_uvs[2], const Vector2 &p_interpolation_point) {
  39. float segment_length = (p_segement_points[1] - p_segement_points[0]).length();
  40. if (segment_length < CMP_EPSILON) {
  41. return p_uvs[0];
  42. }
  43. float distance = (p_interpolation_point - p_segement_points[0]).length();
  44. float fraction = distance / segment_length;
  45. return p_uvs[0].linear_interpolate(p_uvs[1], fraction);
  46. }
  47. inline static Vector2 interpolate_triangle_uv(const Vector2 p_vertices[3], const Vector2 p_uvs[3], const Vector2 &p_interpolation_point) {
  48. if (p_interpolation_point.distance_squared_to(p_vertices[0]) < CMP_EPSILON2) {
  49. return p_uvs[0];
  50. }
  51. if (p_interpolation_point.distance_squared_to(p_vertices[1]) < CMP_EPSILON2) {
  52. return p_uvs[1];
  53. }
  54. if (p_interpolation_point.distance_squared_to(p_vertices[2]) < CMP_EPSILON2) {
  55. return p_uvs[2];
  56. }
  57. Vector2 edge1 = p_vertices[1] - p_vertices[0];
  58. Vector2 edge2 = p_vertices[2] - p_vertices[0];
  59. Vector2 interpolation = p_interpolation_point - p_vertices[0];
  60. float edge1_on_edge1 = edge1.dot(edge1);
  61. float edge1_on_edge2 = edge1.dot(edge2);
  62. float edge2_on_edge2 = edge2.dot(edge2);
  63. float inter_on_edge1 = interpolation.dot(edge1);
  64. float inter_on_edge2 = interpolation.dot(edge2);
  65. float scale = (edge1_on_edge1 * edge2_on_edge2 - edge1_on_edge2 * edge1_on_edge2);
  66. if (scale == 0) {
  67. return p_uvs[0];
  68. }
  69. float v = (edge2_on_edge2 * inter_on_edge1 - edge1_on_edge2 * inter_on_edge2) / scale;
  70. float w = (edge1_on_edge1 * inter_on_edge2 - edge1_on_edge2 * inter_on_edge1) / scale;
  71. float u = 1.0f - v - w;
  72. return p_uvs[0] * u + p_uvs[1] * v + p_uvs[2] * w;
  73. }
  74. static inline bool ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 p_vertices[3], float p_tolerance, Vector3 &r_intersection_point) {
  75. Vector3 edge1 = p_vertices[1] - p_vertices[0];
  76. Vector3 edge2 = p_vertices[2] - p_vertices[0];
  77. Vector3 h = p_dir.cross(edge2);
  78. real_t a = edge1.dot(h);
  79. // Check if ray is parallel to triangle.
  80. if (Math::is_zero_approx(a)) {
  81. return false;
  82. }
  83. real_t f = 1.0 / a;
  84. Vector3 s = p_from - p_vertices[0];
  85. real_t u = f * s.dot(h);
  86. if (u < 0.0 - p_tolerance || u > 1.0 + p_tolerance) {
  87. return false;
  88. }
  89. Vector3 q = s.cross(edge1);
  90. real_t v = f * p_dir.dot(q);
  91. if (v < 0.0 - p_tolerance || u + v > 1.0 + p_tolerance) {
  92. return false;
  93. }
  94. // Ray intersects triangle.
  95. // Calculate distance.
  96. real_t t = f * edge2.dot(q);
  97. // Confirm triangle is in front of ray.
  98. if (t >= p_tolerance) {
  99. r_intersection_point = p_from + p_dir * t;
  100. return true;
  101. } else {
  102. return false;
  103. }
  104. }
  105. inline bool is_point_in_triangle(const Vector3 &p_point, const Vector3 p_vertices[3], int p_shifted = 0) {
  106. real_t det = p_vertices[0].dot(p_vertices[1].cross(p_vertices[2]));
  107. // If determinant is, zero try shift the triangle and the point.
  108. if (Math::is_zero_approx(det)) {
  109. if (p_shifted > 2) {
  110. // Triangle appears degenerate, so ignore it.
  111. return false;
  112. }
  113. Vector3 shift_by;
  114. shift_by[p_shifted] = 1;
  115. Vector3 shifted_point = p_point + shift_by;
  116. Vector3 shifted_vertices[3] = { p_vertices[0] + shift_by, p_vertices[1] + shift_by, p_vertices[2] + shift_by };
  117. return is_point_in_triangle(shifted_point, shifted_vertices, p_shifted + 1);
  118. }
  119. // Find the barycentric coordinates of the point with respect to the vertices.
  120. real_t lambda[3];
  121. lambda[0] = p_vertices[1].cross(p_vertices[2]).dot(p_point) / det;
  122. lambda[1] = p_vertices[2].cross(p_vertices[0]).dot(p_point) / det;
  123. lambda[2] = p_vertices[0].cross(p_vertices[1]).dot(p_point) / det;
  124. // Point is in the plane if all lambdas sum to 1.
  125. if (!Math::is_equal_approx(lambda[0] + lambda[1] + lambda[2], 1)) {
  126. return false;
  127. }
  128. // Point is inside the triangle if all lambdas are positive.
  129. if (lambda[0] < 0 || lambda[1] < 0 || lambda[2] < 0) {
  130. return false;
  131. }
  132. return true;
  133. }
  134. inline static bool is_triangle_degenerate(const Vector2 p_vertices[3], real_t p_vertex_snap2) {
  135. real_t det = p_vertices[0].x * p_vertices[1].y - p_vertices[0].x * p_vertices[2].y +
  136. p_vertices[0].y * p_vertices[2].x - p_vertices[0].y * p_vertices[1].x +
  137. p_vertices[1].x * p_vertices[2].y - p_vertices[1].y * p_vertices[2].x;
  138. return det < p_vertex_snap2;
  139. }
  140. inline static bool are_segements_parallel(const Vector2 p_segment1_points[2], const Vector2 p_segment2_points[2], float p_vertex_snap2) {
  141. Vector2 segment1 = p_segment1_points[1] - p_segment1_points[0];
  142. Vector2 segment2 = p_segment2_points[1] - p_segment2_points[0];
  143. real_t segment1_length2 = segment1.dot(segment1);
  144. real_t segment2_length2 = segment2.dot(segment2);
  145. real_t segment_onto_segment = segment2.dot(segment1);
  146. if (segment1_length2 < p_vertex_snap2 || segment2_length2 < p_vertex_snap2) {
  147. return true;
  148. }
  149. real_t max_separation2;
  150. if (segment1_length2 > segment2_length2) {
  151. max_separation2 = segment2_length2 - segment_onto_segment * segment_onto_segment / segment1_length2;
  152. } else {
  153. max_separation2 = segment1_length2 - segment_onto_segment * segment_onto_segment / segment2_length2;
  154. }
  155. return max_separation2 < p_vertex_snap2;
  156. }
  157. // CSGBrush
  158. void CSGBrush::_regen_face_aabbs() {
  159. for (int i = 0; i < faces.size(); i++) {
  160. faces.write[i].aabb = AABB();
  161. faces.write[i].aabb.position = faces[i].vertices[0];
  162. faces.write[i].aabb.expand_to(faces[i].vertices[1]);
  163. faces.write[i].aabb.expand_to(faces[i].vertices[2]);
  164. }
  165. }
  166. void CSGBrush::build_from_faces(const PoolVector<Vector3> &p_vertices, const PoolVector<Vector2> &p_uvs, const PoolVector<bool> &p_smooth, const PoolVector<Ref<Material>> &p_materials, const PoolVector<bool> &p_invert_faces) {
  167. faces.clear();
  168. int vc = p_vertices.size();
  169. ERR_FAIL_COND((vc % 3) != 0);
  170. PoolVector<Vector3>::Read rv = p_vertices.read();
  171. int uvc = p_uvs.size();
  172. PoolVector<Vector2>::Read ruv = p_uvs.read();
  173. int sc = p_smooth.size();
  174. PoolVector<bool>::Read rs = p_smooth.read();
  175. int mc = p_materials.size();
  176. PoolVector<Ref<Material>>::Read rm = p_materials.read();
  177. int ic = p_invert_faces.size();
  178. PoolVector<bool>::Read ri = p_invert_faces.read();
  179. Map<Ref<Material>, int> material_map;
  180. faces.resize(p_vertices.size() / 3);
  181. for (int i = 0; i < faces.size(); i++) {
  182. Face &f = faces.write[i];
  183. f.vertices[0] = rv[i * 3 + 0];
  184. f.vertices[1] = rv[i * 3 + 1];
  185. f.vertices[2] = rv[i * 3 + 2];
  186. if (uvc == vc) {
  187. f.uvs[0] = ruv[i * 3 + 0];
  188. f.uvs[1] = ruv[i * 3 + 1];
  189. f.uvs[2] = ruv[i * 3 + 2];
  190. }
  191. if (sc == vc / 3) {
  192. f.smooth = rs[i];
  193. } else {
  194. f.smooth = false;
  195. }
  196. if (ic == vc / 3) {
  197. f.invert = ri[i];
  198. } else {
  199. f.invert = false;
  200. }
  201. if (mc == vc / 3) {
  202. Ref<Material> mat = rm[i];
  203. if (mat.is_valid()) {
  204. const Map<Ref<Material>, int>::Element *E = material_map.find(mat);
  205. if (E) {
  206. f.material = E->get();
  207. } else {
  208. f.material = material_map.size();
  209. material_map[mat] = f.material;
  210. }
  211. } else {
  212. f.material = -1;
  213. }
  214. }
  215. }
  216. materials.resize(material_map.size());
  217. for (Map<Ref<Material>, int>::Element *E = material_map.front(); E; E = E->next()) {
  218. materials.write[E->get()] = E->key();
  219. }
  220. _regen_face_aabbs();
  221. }
  222. void CSGBrush::copy_from(const CSGBrush &p_brush, const Transform &p_xform) {
  223. faces = p_brush.faces;
  224. materials = p_brush.materials;
  225. for (int i = 0; i < faces.size(); i++) {
  226. for (int j = 0; j < 3; j++) {
  227. faces.write[i].vertices[j] = p_xform.xform(p_brush.faces[i].vertices[j]);
  228. }
  229. }
  230. _regen_face_aabbs();
  231. }
  232. // CSGBrushOperation
  233. void CSGBrushOperation::merge_brushes(Operation p_operation, const CSGBrush &p_brush_a, const CSGBrush &p_brush_b, CSGBrush &r_merged_brush, float p_vertex_snap) {
  234. // Check for face collisions and add necessary faces.
  235. Build2DFaceCollection build2DFaceCollection;
  236. for (int i = 0; i < p_brush_a.faces.size(); i++) {
  237. for (int j = 0; j < p_brush_b.faces.size(); j++) {
  238. if (p_brush_a.faces[i].aabb.intersects_inclusive(p_brush_b.faces[j].aabb)) {
  239. update_faces(p_brush_a, i, p_brush_b, j, build2DFaceCollection, p_vertex_snap);
  240. }
  241. }
  242. }
  243. // Add faces to MeshMerge.
  244. MeshMerge mesh_merge;
  245. mesh_merge.vertex_snap = p_vertex_snap;
  246. for (int i = 0; i < p_brush_a.faces.size(); i++) {
  247. Ref<Material> material;
  248. if (p_brush_a.faces[i].material != -1) {
  249. material = p_brush_a.materials[p_brush_a.faces[i].material];
  250. }
  251. if (build2DFaceCollection.build2DFacesA.has(i)) {
  252. build2DFaceCollection.build2DFacesA[i].addFacesToMesh(mesh_merge, p_brush_a.faces[i].smooth, p_brush_a.faces[i].invert, material, false);
  253. } else {
  254. Vector3 points[3];
  255. Vector2 uvs[3];
  256. for (int j = 0; j < 3; j++) {
  257. points[j] = p_brush_a.faces[i].vertices[j];
  258. uvs[j] = p_brush_a.faces[i].uvs[j];
  259. }
  260. mesh_merge.add_face(points, uvs, p_brush_a.faces[i].smooth, p_brush_a.faces[i].invert, material, false);
  261. }
  262. }
  263. for (int i = 0; i < p_brush_b.faces.size(); i++) {
  264. Ref<Material> material;
  265. if (p_brush_b.faces[i].material != -1) {
  266. material = p_brush_b.materials[p_brush_b.faces[i].material];
  267. }
  268. if (build2DFaceCollection.build2DFacesB.has(i)) {
  269. build2DFaceCollection.build2DFacesB[i].addFacesToMesh(mesh_merge, p_brush_b.faces[i].smooth, p_brush_b.faces[i].invert, material, true);
  270. } else {
  271. Vector3 points[3];
  272. Vector2 uvs[3];
  273. for (int j = 0; j < 3; j++) {
  274. points[j] = p_brush_b.faces[i].vertices[j];
  275. uvs[j] = p_brush_b.faces[i].uvs[j];
  276. }
  277. mesh_merge.add_face(points, uvs, p_brush_b.faces[i].smooth, p_brush_b.faces[i].invert, material, true);
  278. }
  279. }
  280. // Mark faces that ended up inside the intersection.
  281. mesh_merge.mark_inside_faces();
  282. // Create new brush and fill with new faces.
  283. r_merged_brush.faces.clear();
  284. switch (p_operation) {
  285. case OPERATION_UNION: {
  286. int outside_count = 0;
  287. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  288. if (mesh_merge.faces[i].inside) {
  289. continue;
  290. }
  291. outside_count++;
  292. }
  293. r_merged_brush.faces.resize(outside_count);
  294. outside_count = 0;
  295. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  296. if (mesh_merge.faces[i].inside) {
  297. continue;
  298. }
  299. for (int j = 0; j < 3; j++) {
  300. r_merged_brush.faces.write[outside_count].vertices[j] = mesh_merge.points[mesh_merge.faces[i].points[j]];
  301. r_merged_brush.faces.write[outside_count].uvs[j] = mesh_merge.faces[i].uvs[j];
  302. }
  303. r_merged_brush.faces.write[outside_count].smooth = mesh_merge.faces[i].smooth;
  304. r_merged_brush.faces.write[outside_count].invert = mesh_merge.faces[i].invert;
  305. r_merged_brush.faces.write[outside_count].material = mesh_merge.faces[i].material_idx;
  306. outside_count++;
  307. }
  308. r_merged_brush._regen_face_aabbs();
  309. } break;
  310. case OPERATION_INTERSECTION: {
  311. int inside_count = 0;
  312. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  313. if (!mesh_merge.faces[i].inside) {
  314. continue;
  315. }
  316. inside_count++;
  317. }
  318. r_merged_brush.faces.resize(inside_count);
  319. inside_count = 0;
  320. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  321. if (!mesh_merge.faces[i].inside) {
  322. continue;
  323. }
  324. for (int j = 0; j < 3; j++) {
  325. r_merged_brush.faces.write[inside_count].vertices[j] = mesh_merge.points[mesh_merge.faces[i].points[j]];
  326. r_merged_brush.faces.write[inside_count].uvs[j] = mesh_merge.faces[i].uvs[j];
  327. }
  328. r_merged_brush.faces.write[inside_count].smooth = mesh_merge.faces[i].smooth;
  329. r_merged_brush.faces.write[inside_count].invert = mesh_merge.faces[i].invert;
  330. r_merged_brush.faces.write[inside_count].material = mesh_merge.faces[i].material_idx;
  331. inside_count++;
  332. }
  333. r_merged_brush._regen_face_aabbs();
  334. } break;
  335. case OPERATION_SUBTRACTION: {
  336. int face_count = 0;
  337. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  338. if (mesh_merge.faces[i].from_b && !mesh_merge.faces[i].inside) {
  339. continue;
  340. }
  341. if (!mesh_merge.faces[i].from_b && mesh_merge.faces[i].inside) {
  342. continue;
  343. }
  344. face_count++;
  345. }
  346. r_merged_brush.faces.resize(face_count);
  347. face_count = 0;
  348. for (int i = 0; i < mesh_merge.faces.size(); i++) {
  349. if (mesh_merge.faces[i].from_b && !mesh_merge.faces[i].inside) {
  350. continue;
  351. }
  352. if (!mesh_merge.faces[i].from_b && mesh_merge.faces[i].inside) {
  353. continue;
  354. }
  355. for (int j = 0; j < 3; j++) {
  356. r_merged_brush.faces.write[face_count].vertices[j] = mesh_merge.points[mesh_merge.faces[i].points[j]];
  357. r_merged_brush.faces.write[face_count].uvs[j] = mesh_merge.faces[i].uvs[j];
  358. }
  359. if (mesh_merge.faces[i].from_b) {
  360. //invert facing of insides of B
  361. SWAP(r_merged_brush.faces.write[face_count].vertices[1], r_merged_brush.faces.write[face_count].vertices[2]);
  362. SWAP(r_merged_brush.faces.write[face_count].uvs[1], r_merged_brush.faces.write[face_count].uvs[2]);
  363. }
  364. r_merged_brush.faces.write[face_count].smooth = mesh_merge.faces[i].smooth;
  365. r_merged_brush.faces.write[face_count].invert = mesh_merge.faces[i].invert;
  366. r_merged_brush.faces.write[face_count].material = mesh_merge.faces[i].material_idx;
  367. face_count++;
  368. }
  369. r_merged_brush._regen_face_aabbs();
  370. } break;
  371. }
  372. // Update the list of materials.
  373. r_merged_brush.materials.resize(mesh_merge.materials.size());
  374. for (const Map<Ref<Material>, int>::Element *E = mesh_merge.materials.front(); E; E = E->next()) {
  375. r_merged_brush.materials.write[E->get()] = E->key();
  376. }
  377. }
  378. // CSGBrushOperation::MeshMerge
  379. // Use a limit to speed up bvh and limit the depth.
  380. #define BVH_LIMIT 8
  381. int CSGBrushOperation::MeshMerge::_create_bvh(FaceBVH *facebvhptr, FaceBVH **facebvhptrptr, int p_from, int p_size, int p_depth, int &r_max_depth, int &r_max_alloc) {
  382. if (p_depth > r_max_depth) {
  383. r_max_depth = p_depth;
  384. }
  385. if (p_size == 0) {
  386. return -1;
  387. }
  388. if (p_size <= BVH_LIMIT) {
  389. for (int i = 0; i < p_size - 1; i++) {
  390. facebvhptrptr[p_from + i]->next = facebvhptrptr[p_from + i + 1] - facebvhptr;
  391. }
  392. return facebvhptrptr[p_from] - facebvhptr;
  393. }
  394. AABB aabb;
  395. aabb = facebvhptrptr[p_from]->aabb;
  396. for (int i = 1; i < p_size; i++) {
  397. aabb.merge_with(facebvhptrptr[p_from + i]->aabb);
  398. }
  399. int li = aabb.get_longest_axis_index();
  400. switch (li) {
  401. case Vector3::AXIS_X: {
  402. SortArray<FaceBVH *, FaceBVHCmpX> sort_x;
  403. sort_x.nth_element(0, p_size, p_size / 2, &facebvhptrptr[p_from]);
  404. //sort_x.sort(&p_bb[p_from],p_size);
  405. } break;
  406. case Vector3::AXIS_Y: {
  407. SortArray<FaceBVH *, FaceBVHCmpY> sort_y;
  408. sort_y.nth_element(0, p_size, p_size / 2, &facebvhptrptr[p_from]);
  409. //sort_y.sort(&p_bb[p_from],p_size);
  410. } break;
  411. case Vector3::AXIS_Z: {
  412. SortArray<FaceBVH *, FaceBVHCmpZ> sort_z;
  413. sort_z.nth_element(0, p_size, p_size / 2, &facebvhptrptr[p_from]);
  414. //sort_z.sort(&p_bb[p_from],p_size);
  415. } break;
  416. }
  417. int left = _create_bvh(facebvhptr, facebvhptrptr, p_from, p_size / 2, p_depth + 1, r_max_depth, r_max_alloc);
  418. int right = _create_bvh(facebvhptr, facebvhptrptr, p_from + p_size / 2, p_size - p_size / 2, p_depth + 1, r_max_depth, r_max_alloc);
  419. int index = r_max_alloc++;
  420. FaceBVH *_new = &facebvhptr[index];
  421. _new->aabb = aabb;
  422. _new->center = aabb.position + aabb.size * 0.5;
  423. _new->face = -1;
  424. _new->left = left;
  425. _new->right = right;
  426. _new->next = -1;
  427. return index;
  428. }
  429. void CSGBrushOperation::MeshMerge::_add_distance(List<real_t> &r_intersectionsA, List<real_t> &r_intersectionsB, bool p_from_B, real_t p_distance) const {
  430. List<real_t> &intersections = p_from_B ? r_intersectionsB : r_intersectionsA;
  431. // Check if distance exists.
  432. for (const List<real_t>::Element *E = intersections.front(); E; E = E->next()) {
  433. if (Math::is_equal_approx(**E, p_distance)) {
  434. return;
  435. }
  436. }
  437. intersections.push_back(p_distance);
  438. }
  439. bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *facebvhptr, int p_max_depth, int p_bvh_first, int p_face_idx) const {
  440. Face face = faces[p_face_idx];
  441. Vector3 face_points[3] = {
  442. points[face.points[0]],
  443. points[face.points[1]],
  444. points[face.points[2]]
  445. };
  446. Vector3 face_center = (face_points[0] + face_points[1] + face_points[2]) / 3.0;
  447. Vector3 face_normal = Plane(face_points[0], face_points[1], face_points[2]).normal;
  448. uint32_t *stack = (uint32_t *)alloca(sizeof(int) * p_max_depth);
  449. enum {
  450. TEST_AABB_BIT = 0,
  451. VISIT_LEFT_BIT = 1,
  452. VISIT_RIGHT_BIT = 2,
  453. VISIT_DONE_BIT = 3,
  454. VISITED_BIT_SHIFT = 29,
  455. NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
  456. VISITED_BIT_MASK = ~NODE_IDX_MASK
  457. };
  458. List<real_t> intersectionsA;
  459. List<real_t> intersectionsB;
  460. int level = 0;
  461. int pos = p_bvh_first;
  462. stack[0] = pos;
  463. while (true) {
  464. uint32_t node = stack[level] & NODE_IDX_MASK;
  465. const FaceBVH *current_facebvhptr = &(facebvhptr[node]);
  466. bool done = false;
  467. switch (stack[level] >> VISITED_BIT_SHIFT) {
  468. case TEST_AABB_BIT: {
  469. if (current_facebvhptr->face >= 0) {
  470. while (current_facebvhptr) {
  471. if (p_face_idx != current_facebvhptr->face &&
  472. current_facebvhptr->aabb.intersects_ray(face_center, face_normal)) {
  473. const Face &current_face = faces[current_facebvhptr->face];
  474. Vector3 current_points[3] = {
  475. points[current_face.points[0]],
  476. points[current_face.points[1]],
  477. points[current_face.points[2]]
  478. };
  479. Vector3 current_normal = Plane(current_points[0], current_points[1], current_points[2]).normal;
  480. Vector3 intersection_point;
  481. // Check if faces are co-planar.
  482. if ((current_normal - face_normal).length_squared() < CMP_EPSILON2 &&
  483. is_point_in_triangle(face_center, current_points)) {
  484. // Only add an intersection if not a B face.
  485. if (!face.from_b) {
  486. _add_distance(intersectionsA, intersectionsB, current_face.from_b, 0);
  487. }
  488. } else if (ray_intersects_triangle(face_center, face_normal, current_points, CMP_EPSILON, intersection_point)) {
  489. real_t distance = (intersection_point - face_center).length();
  490. _add_distance(intersectionsA, intersectionsB, current_face.from_b, distance);
  491. }
  492. }
  493. if (current_facebvhptr->next != -1) {
  494. current_facebvhptr = &facebvhptr[current_facebvhptr->next];
  495. } else {
  496. current_facebvhptr = nullptr;
  497. }
  498. }
  499. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  500. } else {
  501. bool valid = current_facebvhptr->aabb.intersects_ray(face_center, face_normal);
  502. if (!valid) {
  503. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  504. } else {
  505. stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
  506. }
  507. }
  508. continue;
  509. }
  510. case VISIT_LEFT_BIT: {
  511. stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
  512. stack[level + 1] = current_facebvhptr->left | TEST_AABB_BIT;
  513. level++;
  514. continue;
  515. }
  516. case VISIT_RIGHT_BIT: {
  517. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  518. stack[level + 1] = current_facebvhptr->right | TEST_AABB_BIT;
  519. level++;
  520. continue;
  521. }
  522. case VISIT_DONE_BIT: {
  523. if (level == 0) {
  524. done = true;
  525. break;
  526. } else {
  527. level--;
  528. }
  529. continue;
  530. }
  531. }
  532. if (done) {
  533. break;
  534. }
  535. }
  536. // Inside if face normal intersects other faces an odd number of times.
  537. return (intersectionsA.size() + intersectionsB.size()) & 1;
  538. }
  539. void CSGBrushOperation::MeshMerge::mark_inside_faces() {
  540. // Mark faces that are inside. This helps later do the boolean ops when merging.
  541. // This approach is very brute force with a bunch of optimizations,
  542. // such as BVH and pre AABB intersection test.
  543. Vector<FaceBVH> bvhvec;
  544. bvhvec.resize(faces.size() * 3); // Will never be larger than this (TODO: Make better)
  545. FaceBVH *facebvh = bvhvec.ptrw();
  546. AABB aabb_a;
  547. AABB aabb_b;
  548. bool first_a = true;
  549. bool first_b = true;
  550. for (int i = 0; i < faces.size(); i++) {
  551. facebvh[i].left = -1;
  552. facebvh[i].right = -1;
  553. facebvh[i].face = i;
  554. facebvh[i].aabb.position = points[faces[i].points[0]];
  555. facebvh[i].aabb.expand_to(points[faces[i].points[1]]);
  556. facebvh[i].aabb.expand_to(points[faces[i].points[2]]);
  557. facebvh[i].center = facebvh[i].aabb.position + facebvh[i].aabb.size * 0.5;
  558. facebvh[i].aabb.grow_by(vertex_snap);
  559. facebvh[i].next = -1;
  560. if (faces[i].from_b) {
  561. if (first_b) {
  562. aabb_b = facebvh[i].aabb;
  563. first_b = false;
  564. } else {
  565. aabb_b.merge_with(facebvh[i].aabb);
  566. }
  567. } else {
  568. if (first_a) {
  569. aabb_a = facebvh[i].aabb;
  570. first_a = false;
  571. } else {
  572. aabb_a.merge_with(facebvh[i].aabb);
  573. }
  574. }
  575. }
  576. AABB intersection_aabb = aabb_a.intersection(aabb_b);
  577. // Check if shape AABBs intersect.
  578. if (intersection_aabb.size == Vector3()) {
  579. return;
  580. }
  581. Vector<FaceBVH *> bvhtrvec;
  582. bvhtrvec.resize(faces.size());
  583. FaceBVH **bvhptr = bvhtrvec.ptrw();
  584. for (int i = 0; i < faces.size(); i++) {
  585. bvhptr[i] = &facebvh[i];
  586. }
  587. int max_depth = 0;
  588. int max_alloc = faces.size();
  589. _create_bvh(facebvh, bvhptr, 0, faces.size(), 1, max_depth, max_alloc);
  590. for (int i = 0; i < faces.size(); i++) {
  591. // Check if face AABB intersects the intersection AABB.
  592. if (!intersection_aabb.intersects_inclusive(facebvh[i].aabb)) {
  593. continue;
  594. }
  595. if (_bvh_inside(facebvh, max_depth, max_alloc - 1, i)) {
  596. faces.write[i].inside = true;
  597. }
  598. }
  599. }
  600. void CSGBrushOperation::MeshMerge::add_face(const Vector3 p_points[3], const Vector2 p_uvs[3], bool p_smooth, bool p_invert, const Ref<Material> &p_material, bool p_from_b) {
  601. int indices[3];
  602. for (int i = 0; i < 3; i++) {
  603. VertexKey vk;
  604. vk.x = int((double(p_points[i].x) + double(vertex_snap) * 0.31234) / double(vertex_snap));
  605. vk.y = int((double(p_points[i].y) + double(vertex_snap) * 0.31234) / double(vertex_snap));
  606. vk.z = int((double(p_points[i].z) + double(vertex_snap) * 0.31234) / double(vertex_snap));
  607. int res;
  608. if (snap_cache.lookup(vk, res)) {
  609. indices[i] = res;
  610. } else {
  611. indices[i] = points.size();
  612. points.push_back(p_points[i]);
  613. snap_cache.set(vk, indices[i]);
  614. }
  615. }
  616. // Don't add degenerate faces.
  617. if (indices[0] == indices[2] || indices[0] == indices[1] || indices[1] == indices[2]) {
  618. return;
  619. }
  620. MeshMerge::Face face;
  621. face.from_b = p_from_b;
  622. face.inside = false;
  623. face.smooth = p_smooth;
  624. face.invert = p_invert;
  625. if (p_material.is_valid()) {
  626. if (!materials.has(p_material)) {
  627. face.material_idx = materials.size();
  628. materials[p_material] = face.material_idx;
  629. } else {
  630. face.material_idx = materials[p_material];
  631. }
  632. } else {
  633. face.material_idx = -1;
  634. }
  635. for (int k = 0; k < 3; k++) {
  636. face.points[k] = indices[k];
  637. face.uvs[k] = p_uvs[k];
  638. }
  639. faces.push_back(face);
  640. }
  641. // CSGBrushOperation::Build2DFaces
  642. int CSGBrushOperation::Build2DFaces::_get_point_idx(const Vector2 &p_point) {
  643. for (int vertex_idx = 0; vertex_idx < vertices.size(); ++vertex_idx) {
  644. if ((p_point - vertices[vertex_idx].point).length_squared() < vertex_snap2) {
  645. return vertex_idx;
  646. }
  647. }
  648. return -1;
  649. }
  650. int CSGBrushOperation::Build2DFaces::_add_vertex(const Vertex2D &p_vertex) {
  651. // Check if vertex exists.
  652. int vertex_id = _get_point_idx(p_vertex.point);
  653. if (vertex_id != -1) {
  654. return vertex_id;
  655. }
  656. vertices.push_back(p_vertex);
  657. return vertices.size() - 1;
  658. }
  659. void CSGBrushOperation::Build2DFaces::_add_vertex_idx_sorted(Vector<int> &r_vertex_indices, int p_new_vertex_index) {
  660. if (p_new_vertex_index >= 0 && r_vertex_indices.find(p_new_vertex_index) == -1) {
  661. ERR_FAIL_COND_MSG(p_new_vertex_index >= vertices.size(), "Invalid vertex index.");
  662. // The first vertex.
  663. if (r_vertex_indices.size() == 0) {
  664. // Simply add it.
  665. r_vertex_indices.push_back(p_new_vertex_index);
  666. return;
  667. }
  668. // The second vertex.
  669. if (r_vertex_indices.size() == 1) {
  670. Vector2 first_point = vertices[r_vertex_indices[0]].point;
  671. Vector2 new_point = vertices[p_new_vertex_index].point;
  672. // Sort along the axis with the greatest difference.
  673. int axis = 0;
  674. if (Math::abs(new_point.x - first_point.x) < Math::abs(new_point.y - first_point.y)) {
  675. axis = 1;
  676. }
  677. // Add it to the beginning or the end appropriately.
  678. if (new_point[axis] < first_point[axis]) {
  679. r_vertex_indices.insert(0, p_new_vertex_index);
  680. } else {
  681. r_vertex_indices.push_back(p_new_vertex_index);
  682. }
  683. return;
  684. }
  685. // Third or later vertices.
  686. Vector2 first_point = vertices[r_vertex_indices[0]].point;
  687. Vector2 last_point = vertices[r_vertex_indices[r_vertex_indices.size() - 1]].point;
  688. Vector2 new_point = vertices[p_new_vertex_index].point;
  689. // Determine axis being sorted against i.e. the axis with the greatest difference.
  690. int axis = 0;
  691. if (Math::abs(last_point.x - first_point.x) < Math::abs(last_point.y - first_point.y)) {
  692. axis = 1;
  693. }
  694. // Insert the point at the appropriate index.
  695. for (int insert_idx = 0; insert_idx < r_vertex_indices.size(); ++insert_idx) {
  696. Vector2 insert_point = vertices[r_vertex_indices[insert_idx]].point;
  697. if (new_point[axis] < insert_point[axis]) {
  698. r_vertex_indices.insert(insert_idx, p_new_vertex_index);
  699. return;
  700. }
  701. }
  702. // New largest, add it to the end.
  703. r_vertex_indices.push_back(p_new_vertex_index);
  704. }
  705. }
  706. void CSGBrushOperation::Build2DFaces::_merge_faces(const Vector<int> &p_segment_indices) {
  707. int segments = p_segment_indices.size() - 1;
  708. if (segments < 2) {
  709. return;
  710. }
  711. // Faces around an inner vertex are merged by moving the inner vertex to the first vertex.
  712. for (int sorted_idx = 1; sorted_idx < segments; ++sorted_idx) {
  713. int closest_idx = 0;
  714. int inner_idx = p_segment_indices[sorted_idx];
  715. if (sorted_idx > segments / 2) {
  716. // Merge to other segment end.
  717. closest_idx = segments;
  718. // Reverse the merge order.
  719. inner_idx = p_segment_indices[segments + segments / 2 - sorted_idx];
  720. }
  721. // Find the mergeable faces.
  722. Vector<int> merge_faces_idx;
  723. Vector<Face2D> merge_faces;
  724. Vector<int> merge_faces_inner_vertex_idx;
  725. for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
  726. for (int face_vertex_idx = 0; face_vertex_idx < 3; ++face_vertex_idx) {
  727. if (faces[face_idx].vertex_idx[face_vertex_idx] == inner_idx) {
  728. merge_faces_idx.push_back(face_idx);
  729. merge_faces.push_back(faces[face_idx]);
  730. merge_faces_inner_vertex_idx.push_back(face_vertex_idx);
  731. }
  732. }
  733. }
  734. Vector<int> degenerate_points;
  735. // Create the new faces.
  736. for (int merge_idx = 0; merge_idx < merge_faces.size(); ++merge_idx) {
  737. int outer_edge_idx[2];
  738. outer_edge_idx[0] = merge_faces[merge_idx].vertex_idx[(merge_faces_inner_vertex_idx[merge_idx] + 1) % 3];
  739. outer_edge_idx[1] = merge_faces[merge_idx].vertex_idx[(merge_faces_inner_vertex_idx[merge_idx] + 2) % 3];
  740. // Skip flattened faces.
  741. if (outer_edge_idx[0] == p_segment_indices[closest_idx] ||
  742. outer_edge_idx[1] == p_segment_indices[closest_idx]) {
  743. continue;
  744. }
  745. //Don't create degenerate triangles.
  746. Vector2 edge1[2] = {
  747. vertices[outer_edge_idx[0]].point,
  748. vertices[p_segment_indices[closest_idx]].point
  749. };
  750. Vector2 edge2[2] = {
  751. vertices[outer_edge_idx[1]].point,
  752. vertices[p_segment_indices[closest_idx]].point
  753. };
  754. if (are_segements_parallel(edge1, edge2, vertex_snap2)) {
  755. if (!degenerate_points.find(outer_edge_idx[0])) {
  756. degenerate_points.push_back(outer_edge_idx[0]);
  757. }
  758. if (!degenerate_points.find(outer_edge_idx[1])) {
  759. degenerate_points.push_back(outer_edge_idx[1]);
  760. }
  761. continue;
  762. }
  763. // Create new faces.
  764. Face2D new_face;
  765. new_face.vertex_idx[0] = p_segment_indices[closest_idx];
  766. new_face.vertex_idx[1] = outer_edge_idx[0];
  767. new_face.vertex_idx[2] = outer_edge_idx[1];
  768. faces.push_back(new_face);
  769. }
  770. // Delete the old faces in reverse index order.
  771. merge_faces_idx.sort();
  772. merge_faces_idx.invert();
  773. for (int i = 0; i < merge_faces_idx.size(); ++i) {
  774. faces.remove(merge_faces_idx[i]);
  775. }
  776. if (degenerate_points.size() == 0) {
  777. continue;
  778. }
  779. // Split faces using degenerate points.
  780. for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
  781. Face2D face = faces[face_idx];
  782. Vertex2D face_vertices[3] = {
  783. vertices[face.vertex_idx[0]],
  784. vertices[face.vertex_idx[1]],
  785. vertices[face.vertex_idx[2]]
  786. };
  787. Vector2 face_points[3] = {
  788. face_vertices[0].point,
  789. face_vertices[1].point,
  790. face_vertices[2].point
  791. };
  792. for (int point_idx = 0; point_idx < degenerate_points.size(); ++point_idx) {
  793. int degenerate_idx = degenerate_points[point_idx];
  794. Vector2 point_2D = vertices[degenerate_idx].point;
  795. // Check if point is existing face vertex.
  796. bool existing = false;
  797. for (int i = 0; i < 3; ++i) {
  798. if ((point_2D - face_vertices[i].point).length_squared() < vertex_snap2) {
  799. existing = true;
  800. break;
  801. }
  802. }
  803. if (existing) {
  804. continue;
  805. }
  806. // Check if point is on an each edge.
  807. for (int face_edge_idx = 0; face_edge_idx < 3; ++face_edge_idx) {
  808. Vector2 edge_points[2] = {
  809. face_points[face_edge_idx],
  810. face_points[(face_edge_idx + 1) % 3]
  811. };
  812. Vector2 closest_point = Geometry::get_closest_point_to_segment_2d(point_2D, edge_points);
  813. if ((closest_point - point_2D).length_squared() < vertex_snap2) {
  814. int opposite_vertex_idx = face.vertex_idx[(face_edge_idx + 2) % 3];
  815. // If new vertex snaps to degenerate vertex, just delete this face.
  816. if (degenerate_idx == opposite_vertex_idx) {
  817. faces.remove(face_idx);
  818. // Update index.
  819. --face_idx;
  820. break;
  821. }
  822. // Create two new faces around the new edge and remove this face.
  823. // The new edge is the last edge.
  824. Face2D left_face;
  825. left_face.vertex_idx[0] = degenerate_idx;
  826. left_face.vertex_idx[1] = face.vertex_idx[(face_edge_idx + 1) % 3];
  827. left_face.vertex_idx[2] = opposite_vertex_idx;
  828. Face2D right_face;
  829. right_face.vertex_idx[0] = opposite_vertex_idx;
  830. right_face.vertex_idx[1] = face.vertex_idx[face_edge_idx];
  831. right_face.vertex_idx[2] = degenerate_idx;
  832. faces.remove(face_idx);
  833. faces.insert(face_idx, right_face);
  834. faces.insert(face_idx, left_face);
  835. // Don't check against the new faces.
  836. ++face_idx;
  837. // No need to check other edges.
  838. break;
  839. }
  840. }
  841. }
  842. }
  843. }
  844. }
  845. void CSGBrushOperation::Build2DFaces::_find_edge_intersections(const Vector2 p_segment_points[2], Vector<int> &r_segment_indices) {
  846. // For each face.
  847. for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
  848. Face2D face = faces[face_idx];
  849. Vertex2D face_vertices[3] = {
  850. vertices[face.vertex_idx[0]],
  851. vertices[face.vertex_idx[1]],
  852. vertices[face.vertex_idx[2]]
  853. };
  854. // Check each edge.
  855. for (int face_edge_idx = 0; face_edge_idx < 3; ++face_edge_idx) {
  856. Vector2 edge_points[2] = {
  857. face_vertices[face_edge_idx].point,
  858. face_vertices[(face_edge_idx + 1) % 3].point
  859. };
  860. Vector2 edge_uvs[2] = {
  861. face_vertices[face_edge_idx].uv,
  862. face_vertices[(face_edge_idx + 1) % 3].uv
  863. };
  864. Vector2 intersection_point;
  865. // First check if the ends of the segment are on the edge.
  866. bool on_edge = false;
  867. for (int edge_point_idx = 0; edge_point_idx < 2; ++edge_point_idx) {
  868. intersection_point = Geometry::get_closest_point_to_segment_2d(p_segment_points[edge_point_idx], edge_points);
  869. if ((intersection_point - p_segment_points[edge_point_idx]).length_squared() < vertex_snap2) {
  870. on_edge = true;
  871. break;
  872. }
  873. }
  874. // Else check if the segment intersects the edge.
  875. if (on_edge || Geometry::segment_intersects_segment_2d(p_segment_points[0], p_segment_points[1], edge_points[0], edge_points[1], &intersection_point)) {
  876. // Check if intersection point is an edge point.
  877. if ((intersection_point - edge_points[0]).length_squared() < vertex_snap2 ||
  878. (intersection_point - edge_points[1]).length_squared() < vertex_snap2) {
  879. continue;
  880. }
  881. // Check if edge exists, by checking if the intersecting segment is parallel to the edge.
  882. if (are_segements_parallel(p_segment_points, edge_points, vertex_snap2)) {
  883. continue;
  884. }
  885. // Add the intersection point as a new vertex.
  886. Vertex2D new_vertex;
  887. new_vertex.point = intersection_point;
  888. new_vertex.uv = interpolate_segment_uv(edge_points, edge_uvs, intersection_point);
  889. int new_vertex_idx = _add_vertex(new_vertex);
  890. int opposite_vertex_idx = face.vertex_idx[(face_edge_idx + 2) % 3];
  891. _add_vertex_idx_sorted(r_segment_indices, new_vertex_idx);
  892. // If new vertex snaps to opposite vertex, just delete this face.
  893. if (new_vertex_idx == opposite_vertex_idx) {
  894. faces.remove(face_idx);
  895. // Update index.
  896. --face_idx;
  897. break;
  898. }
  899. // If opposite point is on the segemnt, add its index to segment indices too.
  900. Vector2 closest_point = Geometry::get_closest_point_to_segment_2d(vertices[opposite_vertex_idx].point, p_segment_points);
  901. if ((closest_point - vertices[opposite_vertex_idx].point).length_squared() < vertex_snap2) {
  902. _add_vertex_idx_sorted(r_segment_indices, opposite_vertex_idx);
  903. }
  904. // Create two new faces around the new edge and remove this face.
  905. // The new edge is the last edge.
  906. Face2D left_face;
  907. left_face.vertex_idx[0] = new_vertex_idx;
  908. left_face.vertex_idx[1] = face.vertex_idx[(face_edge_idx + 1) % 3];
  909. left_face.vertex_idx[2] = opposite_vertex_idx;
  910. Face2D right_face;
  911. right_face.vertex_idx[0] = opposite_vertex_idx;
  912. right_face.vertex_idx[1] = face.vertex_idx[face_edge_idx];
  913. right_face.vertex_idx[2] = new_vertex_idx;
  914. faces.remove(face_idx);
  915. faces.insert(face_idx, right_face);
  916. faces.insert(face_idx, left_face);
  917. // Check against the new faces.
  918. --face_idx;
  919. break;
  920. }
  921. }
  922. }
  923. }
  924. int CSGBrushOperation::Build2DFaces::_insert_point(const Vector2 &p_point) {
  925. int new_vertex_idx = -1;
  926. for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
  927. Face2D face = faces[face_idx];
  928. Vertex2D face_vertices[3] = {
  929. vertices[face.vertex_idx[0]],
  930. vertices[face.vertex_idx[1]],
  931. vertices[face.vertex_idx[2]]
  932. };
  933. Vector2 points[3] = {
  934. face_vertices[0].point,
  935. face_vertices[1].point,
  936. face_vertices[2].point
  937. };
  938. Vector2 uvs[3] = {
  939. face_vertices[0].uv,
  940. face_vertices[1].uv,
  941. face_vertices[2].uv
  942. };
  943. // Skip degenerate triangles.
  944. if (is_triangle_degenerate(points, vertex_snap2)) {
  945. continue;
  946. }
  947. // Check if point is existing face vertex.
  948. for (int i = 0; i < 3; ++i) {
  949. if ((p_point - face_vertices[i].point).length_squared() < vertex_snap2) {
  950. return face.vertex_idx[i];
  951. }
  952. }
  953. // Check if point is on an each edge.
  954. bool on_edge = false;
  955. for (int face_edge_idx = 0; face_edge_idx < 3; ++face_edge_idx) {
  956. Vector2 edge_points[2] = {
  957. points[face_edge_idx],
  958. points[(face_edge_idx + 1) % 3]
  959. };
  960. Vector2 edge_uvs[2] = {
  961. uvs[face_edge_idx],
  962. uvs[(face_edge_idx + 1) % 3]
  963. };
  964. Vector2 closest_point = Geometry::get_closest_point_to_segment_2d(p_point, edge_points);
  965. if ((closest_point - p_point).length_squared() < vertex_snap2) {
  966. on_edge = true;
  967. // Add the point as a new vertex.
  968. Vertex2D new_vertex;
  969. new_vertex.point = p_point;
  970. new_vertex.uv = interpolate_segment_uv(edge_points, edge_uvs, p_point);
  971. new_vertex_idx = _add_vertex(new_vertex);
  972. int opposite_vertex_idx = face.vertex_idx[(face_edge_idx + 2) % 3];
  973. // If new vertex snaps to opposite vertex, just delete this face.
  974. if (new_vertex_idx == opposite_vertex_idx) {
  975. faces.remove(face_idx);
  976. // Update index.
  977. --face_idx;
  978. break;
  979. }
  980. // Don't create degenerate triangles.
  981. Vector2 split_edge1[2] = { vertices[new_vertex_idx].point, edge_points[0] };
  982. Vector2 split_edge2[2] = { vertices[new_vertex_idx].point, edge_points[1] };
  983. Vector2 new_edge[2] = { vertices[new_vertex_idx].point, vertices[opposite_vertex_idx].point };
  984. if (are_segements_parallel(split_edge1, new_edge, vertex_snap2) &&
  985. are_segements_parallel(split_edge2, new_edge, vertex_snap2)) {
  986. break;
  987. }
  988. // Create two new faces around the new edge and remove this face.
  989. // The new edge is the last edge.
  990. Face2D left_face;
  991. left_face.vertex_idx[0] = new_vertex_idx;
  992. left_face.vertex_idx[1] = face.vertex_idx[(face_edge_idx + 1) % 3];
  993. left_face.vertex_idx[2] = opposite_vertex_idx;
  994. Face2D right_face;
  995. right_face.vertex_idx[0] = opposite_vertex_idx;
  996. right_face.vertex_idx[1] = face.vertex_idx[face_edge_idx];
  997. right_face.vertex_idx[2] = new_vertex_idx;
  998. faces.remove(face_idx);
  999. faces.insert(face_idx, right_face);
  1000. faces.insert(face_idx, left_face);
  1001. // Don't check against the new faces.
  1002. ++face_idx;
  1003. // No need to check other edges.
  1004. break;
  1005. }
  1006. }
  1007. // If not on an edge, check if the point is inside the face.
  1008. if (!on_edge && Geometry::is_point_in_triangle(p_point, face_vertices[0].point, face_vertices[1].point, face_vertices[2].point)) {
  1009. // Add the point as a new vertex.
  1010. Vertex2D new_vertex;
  1011. new_vertex.point = p_point;
  1012. new_vertex.uv = interpolate_triangle_uv(points, uvs, p_point);
  1013. new_vertex_idx = _add_vertex(new_vertex);
  1014. // Create three new faces around this point and remove this face.
  1015. // The new vertex is the last vertex.
  1016. for (int i = 0; i < 3; ++i) {
  1017. // Don't create degenerate triangles.
  1018. Vector2 new_points[3] = { points[i], points[(i + 1) % 3], vertices[new_vertex_idx].point };
  1019. if (is_triangle_degenerate(new_points, vertex_snap2)) {
  1020. continue;
  1021. }
  1022. Face2D new_face;
  1023. new_face.vertex_idx[0] = face.vertex_idx[i];
  1024. new_face.vertex_idx[1] = face.vertex_idx[(i + 1) % 3];
  1025. new_face.vertex_idx[2] = new_vertex_idx;
  1026. faces.push_back(new_face);
  1027. }
  1028. faces.remove(face_idx);
  1029. // No need to check other faces.
  1030. break;
  1031. }
  1032. }
  1033. return new_vertex_idx;
  1034. }
  1035. void CSGBrushOperation::Build2DFaces::insert(const CSGBrush &p_brush, int p_face_idx) {
  1036. // Find edge points that cross the plane and face points that are in the plane.
  1037. // Map those points to 2D.
  1038. // Create new faces from those points.
  1039. Vector2 points_2D[3];
  1040. int points_count = 0;
  1041. for (int i = 0; i < 3; i++) {
  1042. Vector3 point_3D = p_brush.faces[p_face_idx].vertices[i];
  1043. if (plane.has_point(point_3D)) {
  1044. // Point is in the plane, add it.
  1045. Vector3 point_2D = plane.project(point_3D);
  1046. point_2D = to_2D.xform(point_2D);
  1047. points_2D[points_count++] = Vector2(point_2D.x, point_2D.y);
  1048. } else {
  1049. Vector3 next_point_3D = p_brush.faces[p_face_idx].vertices[(i + 1) % 3];
  1050. if (plane.has_point(next_point_3D)) {
  1051. continue; // Next point is in plane, it will be added separately.
  1052. }
  1053. if (plane.is_point_over(point_3D) == plane.is_point_over(next_point_3D)) {
  1054. continue; // Both points on the same side of the plane, ignore.
  1055. }
  1056. // Edge crosses the plane, find and add the intersection point.
  1057. Vector3 point_2D;
  1058. if (plane.intersects_segment(point_3D, next_point_3D, &point_2D)) {
  1059. point_2D = to_2D.xform(point_2D);
  1060. points_2D[points_count++] = Vector2(point_2D.x, point_2D.y);
  1061. }
  1062. }
  1063. }
  1064. Vector<int> segment_indices;
  1065. Vector2 segment[2];
  1066. int inserted_index[3] = { -1, -1, -1 };
  1067. // Insert points.
  1068. for (int i = 0; i < points_count; ++i) {
  1069. inserted_index[i] = _insert_point(points_2D[i]);
  1070. }
  1071. if (points_count == 2) {
  1072. // Insert a single segment.
  1073. segment[0] = points_2D[0];
  1074. segment[1] = points_2D[1];
  1075. _find_edge_intersections(segment, segment_indices);
  1076. for (int i = 0; i < 2; ++i) {
  1077. _add_vertex_idx_sorted(segment_indices, inserted_index[i]);
  1078. }
  1079. _merge_faces(segment_indices);
  1080. }
  1081. if (points_count == 3) {
  1082. // Insert three segments.
  1083. for (int edge_idx = 0; edge_idx < 3; ++edge_idx) {
  1084. segment[0] = points_2D[edge_idx];
  1085. segment[1] = points_2D[(edge_idx + 1) % 3];
  1086. _find_edge_intersections(segment, segment_indices);
  1087. for (int i = 0; i < 2; ++i) {
  1088. _add_vertex_idx_sorted(segment_indices, inserted_index[(edge_idx + i) % 3]);
  1089. }
  1090. _merge_faces(segment_indices);
  1091. segment_indices.clear();
  1092. }
  1093. }
  1094. }
  1095. void CSGBrushOperation::Build2DFaces::addFacesToMesh(MeshMerge &r_mesh_merge, bool p_smooth, bool p_invert, const Ref<Material> &p_material, bool p_from_b) {
  1096. for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
  1097. Face2D face = faces[face_idx];
  1098. Vertex2D fv[3] = {
  1099. vertices[face.vertex_idx[0]],
  1100. vertices[face.vertex_idx[1]],
  1101. vertices[face.vertex_idx[2]]
  1102. };
  1103. // Convert 2D vertex points to 3D.
  1104. Vector3 points_3D[3];
  1105. Vector2 uvs[3];
  1106. for (int i = 0; i < 3; ++i) {
  1107. Vector3 point_2D(fv[i].point.x, fv[i].point.y, 0);
  1108. points_3D[i] = to_3D.xform(point_2D);
  1109. uvs[i] = fv[i].uv;
  1110. }
  1111. r_mesh_merge.add_face(points_3D, uvs, p_smooth, p_invert, p_material, p_from_b);
  1112. }
  1113. }
  1114. CSGBrushOperation::Build2DFaces::Build2DFaces(const CSGBrush &p_brush, int p_face_idx, float p_vertex_snap2) :
  1115. vertex_snap2(p_vertex_snap2 * p_vertex_snap2) {
  1116. // Convert 3D vertex points to 2D.
  1117. Vector3 points_3D[3] = {
  1118. p_brush.faces[p_face_idx].vertices[0],
  1119. p_brush.faces[p_face_idx].vertices[1],
  1120. p_brush.faces[p_face_idx].vertices[2],
  1121. };
  1122. plane = Plane(points_3D[0], points_3D[1], points_3D[2]);
  1123. to_3D.origin = points_3D[0];
  1124. to_3D.basis.set_axis(2, plane.normal);
  1125. to_3D.basis.set_axis(0, (points_3D[1] - points_3D[2]).normalized());
  1126. to_3D.basis.set_axis(1, to_3D.basis.get_axis(0).cross(to_3D.basis.get_axis(2)).normalized());
  1127. to_2D = to_3D.affine_inverse();
  1128. Face2D face;
  1129. for (int i = 0; i < 3; i++) {
  1130. Vertex2D vertex;
  1131. Vector3 point_2D = to_2D.xform(points_3D[i]);
  1132. vertex.point.x = point_2D.x;
  1133. vertex.point.y = point_2D.y;
  1134. vertex.uv = p_brush.faces[p_face_idx].uvs[i];
  1135. vertices.push_back(vertex);
  1136. face.vertex_idx[i] = i;
  1137. }
  1138. faces.push_back(face);
  1139. }
  1140. void CSGBrushOperation::update_faces(const CSGBrush &p_brush_a, const int p_face_idx_a, const CSGBrush &p_brush_b, const int p_face_idx_b, Build2DFaceCollection &p_collection, float p_vertex_snap) {
  1141. Vector3 vertices_a[3] = {
  1142. p_brush_a.faces[p_face_idx_a].vertices[0],
  1143. p_brush_a.faces[p_face_idx_a].vertices[1],
  1144. p_brush_a.faces[p_face_idx_a].vertices[2],
  1145. };
  1146. Vector3 vertices_b[3] = {
  1147. p_brush_b.faces[p_face_idx_b].vertices[0],
  1148. p_brush_b.faces[p_face_idx_b].vertices[1],
  1149. p_brush_b.faces[p_face_idx_b].vertices[2],
  1150. };
  1151. // Don't use degenerate faces.
  1152. bool has_degenerate = false;
  1153. if (is_snapable(vertices_a[0], vertices_a[1], p_vertex_snap) ||
  1154. is_snapable(vertices_a[0], vertices_a[2], p_vertex_snap) ||
  1155. is_snapable(vertices_a[1], vertices_a[2], p_vertex_snap)) {
  1156. p_collection.build2DFacesA[p_face_idx_a] = Build2DFaces();
  1157. has_degenerate = true;
  1158. }
  1159. if (is_snapable(vertices_b[0], vertices_b[1], p_vertex_snap) ||
  1160. is_snapable(vertices_b[0], vertices_b[2], p_vertex_snap) ||
  1161. is_snapable(vertices_b[1], vertices_b[2], p_vertex_snap)) {
  1162. p_collection.build2DFacesB[p_face_idx_b] = Build2DFaces();
  1163. has_degenerate = true;
  1164. }
  1165. if (has_degenerate) {
  1166. return;
  1167. }
  1168. // Ensure B has points either side of or in the plane of A.
  1169. int over_count = 0, under_count = 0;
  1170. Plane plane_a(vertices_a[0], vertices_a[1], vertices_a[2]);
  1171. ERR_FAIL_COND_MSG(plane_a.normal == Vector3(), "Couldn't form plane from Brush A face.");
  1172. for (int i = 0; i < 3; i++) {
  1173. if (plane_a.has_point(vertices_b[i])) {
  1174. // In plane.
  1175. } else if (plane_a.is_point_over(vertices_b[i])) {
  1176. over_count++;
  1177. } else {
  1178. under_count++;
  1179. }
  1180. }
  1181. // If all points under or over the plane, there is no intesection.
  1182. if (over_count == 3 || under_count == 3) {
  1183. return;
  1184. }
  1185. // Ensure A has points either side of or in the plane of B.
  1186. over_count = 0;
  1187. under_count = 0;
  1188. Plane plane_b(vertices_b[0], vertices_b[1], vertices_b[2]);
  1189. ERR_FAIL_COND_MSG(plane_b.normal == Vector3(), "Couldn't form plane from Brush B face.");
  1190. for (int i = 0; i < 3; i++) {
  1191. if (plane_b.has_point(vertices_a[i])) {
  1192. // In plane.
  1193. } else if (plane_b.is_point_over(vertices_a[i])) {
  1194. over_count++;
  1195. } else {
  1196. under_count++;
  1197. }
  1198. }
  1199. // If all points under or over the plane, there is no intesection.
  1200. if (over_count == 3 || under_count == 3) {
  1201. return;
  1202. }
  1203. // Check for intersection using the SAT theorem.
  1204. {
  1205. // Edge pair cross product combinations.
  1206. for (int i = 0; i < 3; i++) {
  1207. Vector3 axis_a = (vertices_a[i] - vertices_a[(i + 1) % 3]).normalized();
  1208. for (int j = 0; j < 3; j++) {
  1209. Vector3 axis_b = (vertices_b[j] - vertices_b[(j + 1) % 3]).normalized();
  1210. Vector3 sep_axis = axis_a.cross(axis_b);
  1211. if (sep_axis == Vector3()) {
  1212. continue; //colineal
  1213. }
  1214. sep_axis.normalize();
  1215. real_t min_a = 1e20, max_a = -1e20;
  1216. real_t min_b = 1e20, max_b = -1e20;
  1217. for (int k = 0; k < 3; k++) {
  1218. real_t d = sep_axis.dot(vertices_a[k]);
  1219. min_a = MIN(min_a, d);
  1220. max_a = MAX(max_a, d);
  1221. d = sep_axis.dot(vertices_b[k]);
  1222. min_b = MIN(min_b, d);
  1223. max_b = MAX(max_b, d);
  1224. }
  1225. min_b -= (max_a - min_a) * 0.5;
  1226. max_b += (max_a - min_a) * 0.5;
  1227. real_t dmin = min_b - (min_a + max_a) * 0.5;
  1228. real_t dmax = max_b - (min_a + max_a) * 0.5;
  1229. if (dmin > CMP_EPSILON || dmax < -CMP_EPSILON) {
  1230. return; // Does not contain zero, so they don't overlap.
  1231. }
  1232. }
  1233. }
  1234. }
  1235. // If we're still here, the faces probably intersect, so add new faces.
  1236. if (!p_collection.build2DFacesA.has(p_face_idx_a)) {
  1237. p_collection.build2DFacesA[p_face_idx_a] = Build2DFaces(p_brush_a, p_face_idx_a, p_vertex_snap);
  1238. }
  1239. p_collection.build2DFacesA[p_face_idx_a].insert(p_brush_b, p_face_idx_b);
  1240. if (!p_collection.build2DFacesB.has(p_face_idx_b)) {
  1241. p_collection.build2DFacesB[p_face_idx_b] = Build2DFaces(p_brush_b, p_face_idx_b, p_vertex_snap);
  1242. }
  1243. p_collection.build2DFacesB[p_face_idx_b].insert(p_brush_a, p_face_idx_a);
  1244. }