csg.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  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_2d.h"
  32. #include "core/math/math_funcs.h"
  33. #include "core/templates/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_point2.distance_squared_to(p_point1) < p_distance * p_distance;
  37. }
  38. inline static Vector2 interpolate_segment_uv(const Vector2 p_segment_points[2], const Vector2 p_uvs[2], const Vector2 &p_interpolation_point) {
  39. if (p_segment_points[0].is_equal_approx(p_segment_points[1])) {
  40. return p_uvs[0];
  41. }
  42. float segment_length = p_segment_points[0].distance_to(p_segment_points[1]);
  43. float distance = p_segment_points[0].distance_to(p_interpolation_point);
  44. float fraction = distance / segment_length;
  45. return p_uvs[0].lerp(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.is_equal_approx(p_vertices[0])) {
  49. return p_uvs[0];
  50. }
  51. if (p_interpolation_point.is_equal_approx(p_vertices[1])) {
  52. return p_uvs[1];
  53. }
  54. if (p_interpolation_point.is_equal_approx(p_vertices[2])) {
  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_segments_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 Vector<Vector3> &p_vertices, const Vector<Vector2> &p_uvs, const Vector<bool> &p_smooth, const Vector<Ref<Material>> &p_materials, const Vector<bool> &p_flip_faces) {
  167. faces.clear();
  168. int vc = p_vertices.size();
  169. ERR_FAIL_COND((vc % 3) != 0);
  170. const Vector3 *rv = p_vertices.ptr();
  171. int uvc = p_uvs.size();
  172. const Vector2 *ruv = p_uvs.ptr();
  173. int sc = p_smooth.size();
  174. const bool *rs = p_smooth.ptr();
  175. int mc = p_materials.size();
  176. const Ref<Material> *rm = p_materials.ptr();
  177. int ic = p_flip_faces.size();
  178. const bool *ri = p_flip_faces.ptr();
  179. HashMap<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. HashMap<Ref<Material>, int>::ConstIterator E = material_map.find(mat);
  205. if (E) {
  206. f.material = E->value;
  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 (const KeyValue<Ref<Material>, int> &E : material_map) {
  218. materials.write[E.value] = E.key;
  219. }
  220. _regen_face_aabbs();
  221. }
  222. void CSGBrush::copy_from(const CSGBrush &p_brush, const Transform3D &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 KeyValue<Ref<Material>, int> &E : mesh_merge.materials) {
  375. r_merged_brush.materials.write[E.value] = 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 *r_facebvhptr, FaceBVH **r_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. r_facebvhptrptr[p_from + i]->next = r_facebvhptrptr[p_from + i + 1] - r_facebvhptr;
  391. }
  392. return r_facebvhptrptr[p_from] - r_facebvhptr;
  393. }
  394. AABB aabb;
  395. aabb = r_facebvhptrptr[p_from]->aabb;
  396. for (int i = 1; i < p_size; i++) {
  397. aabb.merge_with(r_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, &r_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, &r_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, &r_facebvhptrptr[p_from]);
  414. //sort_z.sort(&p_bb[p_from],p_size);
  415. } break;
  416. }
  417. int left = _create_bvh(r_facebvhptr, r_facebvhptrptr, p_from, p_size / 2, p_depth + 1, r_max_depth, r_max_alloc);
  418. int right = _create_bvh(r_facebvhptr, r_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 = &r_facebvhptr[index];
  421. _new->aabb = aabb;
  422. _new->center = aabb.get_center();
  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<IntersectionDistance> &r_intersectionsA, List<IntersectionDistance> &r_intersectionsB, bool p_from_B, real_t p_distance_squared, bool p_is_conormal) const {
  430. List<IntersectionDistance> &intersections = p_from_B ? r_intersectionsB : r_intersectionsA;
  431. // Check if distance exists.
  432. for (const IntersectionDistance E : intersections) {
  433. if (E.is_conormal == p_is_conormal && Math::is_equal_approx(E.distance_squared, p_distance_squared)) {
  434. return;
  435. }
  436. }
  437. IntersectionDistance distance;
  438. distance.is_conormal = p_is_conormal;
  439. distance.distance_squared = p_distance_squared;
  440. intersections.push_back(distance);
  441. }
  442. bool CSGBrushOperation::MeshMerge::_bvh_inside(FaceBVH *r_facebvhptr, int p_max_depth, int p_bvh_first, int p_face_idx) const {
  443. Face face = faces[p_face_idx];
  444. Vector3 face_points[3] = {
  445. points[face.points[0]],
  446. points[face.points[1]],
  447. points[face.points[2]]
  448. };
  449. Vector3 face_center = (face_points[0] + face_points[1] + face_points[2]) / 3.0;
  450. Vector3 face_normal = Plane(face_points[0], face_points[1], face_points[2]).normal;
  451. uint32_t *stack = (uint32_t *)alloca(sizeof(int) * p_max_depth);
  452. enum {
  453. TEST_AABB_BIT = 0,
  454. VISIT_LEFT_BIT = 1,
  455. VISIT_RIGHT_BIT = 2,
  456. VISIT_DONE_BIT = 3,
  457. VISITED_BIT_SHIFT = 29,
  458. NODE_IDX_MASK = (1 << VISITED_BIT_SHIFT) - 1,
  459. VISITED_BIT_MASK = ~NODE_IDX_MASK
  460. };
  461. List<IntersectionDistance> intersectionsA;
  462. List<IntersectionDistance> intersectionsB;
  463. Intersection closest_intersection;
  464. closest_intersection.found = false;
  465. int level = 0;
  466. int pos = p_bvh_first;
  467. stack[0] = pos;
  468. while (true) {
  469. uint32_t node = stack[level] & NODE_IDX_MASK;
  470. const FaceBVH *current_facebvhptr = &(r_facebvhptr[node]);
  471. bool done = false;
  472. switch (stack[level] >> VISITED_BIT_SHIFT) {
  473. case TEST_AABB_BIT: {
  474. if (current_facebvhptr->face >= 0) {
  475. while (current_facebvhptr) {
  476. if (p_face_idx != current_facebvhptr->face &&
  477. current_facebvhptr->aabb.intersects_ray(face_center, face_normal)) {
  478. const Face &current_face = faces[current_facebvhptr->face];
  479. Vector3 current_points[3] = {
  480. points[current_face.points[0]],
  481. points[current_face.points[1]],
  482. points[current_face.points[2]]
  483. };
  484. Vector3 current_normal = Plane(current_points[0], current_points[1], current_points[2]).normal;
  485. Vector3 intersection_point;
  486. // Check if faces are co-planar.
  487. if (current_normal.is_equal_approx(face_normal) &&
  488. is_point_in_triangle(face_center, current_points)) {
  489. // Only add an intersection if not a B face.
  490. if (!face.from_b) {
  491. _add_distance(intersectionsA, intersectionsB, current_face.from_b, 0, true);
  492. }
  493. } else if (ray_intersects_triangle(face_center, face_normal, current_points, CMP_EPSILON, intersection_point)) {
  494. real_t distance_squared = face_center.distance_squared_to(intersection_point);
  495. real_t inner = current_normal.dot(face_normal);
  496. // If the faces are perpendicular, ignore this face.
  497. // The triangles on the side should be intersected and result in the correct behavior.
  498. if (!Math::is_zero_approx(inner)) {
  499. _add_distance(intersectionsA, intersectionsB, current_face.from_b, distance_squared, inner > 0.0f);
  500. }
  501. }
  502. if (face.from_b != current_face.from_b) {
  503. if (current_normal.is_equal_approx(face_normal) &&
  504. is_point_in_triangle(face_center, current_points)) {
  505. // Only add an intersection if not a B face.
  506. if (!face.from_b) {
  507. closest_intersection.found = true;
  508. closest_intersection.conormal = 1.0f;
  509. closest_intersection.distance_squared = 0.0f;
  510. closest_intersection.origin_angle = -FLT_MAX;
  511. }
  512. } else if (ray_intersects_triangle(face_center, face_normal, current_points, CMP_EPSILON, intersection_point)) {
  513. Intersection potential_intersection;
  514. potential_intersection.found = true;
  515. potential_intersection.conormal = face_normal.dot(current_normal);
  516. potential_intersection.distance_squared = face_center.distance_squared_to(intersection_point);
  517. potential_intersection.origin_angle = Math::abs(potential_intersection.conormal);
  518. real_t intersection_dist_from_face = face_normal.dot(intersection_point - face_center);
  519. for (int i = 0; i < 3; i++) {
  520. real_t point_dist_from_face = face_normal.dot(current_points[i] - face_center);
  521. if (!Math::is_equal_approx(point_dist_from_face, intersection_dist_from_face) &&
  522. point_dist_from_face < intersection_dist_from_face) {
  523. potential_intersection.origin_angle = -potential_intersection.origin_angle;
  524. break;
  525. }
  526. }
  527. if (potential_intersection.conormal != 0.0f) {
  528. if (!closest_intersection.found) {
  529. closest_intersection = potential_intersection;
  530. } else if (!Math::is_equal_approx(potential_intersection.distance_squared, closest_intersection.distance_squared) &&
  531. potential_intersection.distance_squared < closest_intersection.distance_squared) {
  532. closest_intersection = potential_intersection;
  533. } else if (Math::is_equal_approx(potential_intersection.distance_squared, closest_intersection.distance_squared)) {
  534. if (potential_intersection.origin_angle < closest_intersection.origin_angle) {
  535. closest_intersection = potential_intersection;
  536. }
  537. }
  538. }
  539. }
  540. }
  541. }
  542. if (current_facebvhptr->next != -1) {
  543. current_facebvhptr = &r_facebvhptr[current_facebvhptr->next];
  544. } else {
  545. current_facebvhptr = nullptr;
  546. }
  547. }
  548. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  549. } else {
  550. bool valid = current_facebvhptr->aabb.intersects_ray(face_center, face_normal);
  551. if (!valid) {
  552. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  553. } else {
  554. stack[level] = (VISIT_LEFT_BIT << VISITED_BIT_SHIFT) | node;
  555. }
  556. }
  557. continue;
  558. }
  559. case VISIT_LEFT_BIT: {
  560. stack[level] = (VISIT_RIGHT_BIT << VISITED_BIT_SHIFT) | node;
  561. stack[level + 1] = current_facebvhptr->left | TEST_AABB_BIT;
  562. level++;
  563. continue;
  564. }
  565. case VISIT_RIGHT_BIT: {
  566. stack[level] = (VISIT_DONE_BIT << VISITED_BIT_SHIFT) | node;
  567. stack[level + 1] = current_facebvhptr->right | TEST_AABB_BIT;
  568. level++;
  569. continue;
  570. }
  571. case VISIT_DONE_BIT: {
  572. if (level == 0) {
  573. done = true;
  574. break;
  575. } else {
  576. level--;
  577. }
  578. continue;
  579. }
  580. }
  581. if (done) {
  582. break;
  583. }
  584. }
  585. if (!closest_intersection.found) {
  586. return false;
  587. } else {
  588. return closest_intersection.conormal > 0.0f;
  589. }
  590. }
  591. void CSGBrushOperation::MeshMerge::mark_inside_faces() {
  592. // Mark faces that are inside. This helps later do the boolean ops when merging.
  593. // This approach is very brute force with a bunch of optimizations,
  594. // such as BVH and pre AABB intersection test.
  595. Vector<FaceBVH> bvhvec;
  596. bvhvec.resize(faces.size() * 3); // Will never be larger than this (TODO: Make better)
  597. FaceBVH *facebvh = bvhvec.ptrw();
  598. AABB aabb_a;
  599. AABB aabb_b;
  600. bool first_a = true;
  601. bool first_b = true;
  602. for (int i = 0; i < faces.size(); i++) {
  603. facebvh[i].left = -1;
  604. facebvh[i].right = -1;
  605. facebvh[i].face = i;
  606. facebvh[i].aabb.position = points[faces[i].points[0]];
  607. facebvh[i].aabb.expand_to(points[faces[i].points[1]]);
  608. facebvh[i].aabb.expand_to(points[faces[i].points[2]]);
  609. facebvh[i].center = facebvh[i].aabb.get_center();
  610. facebvh[i].aabb.grow_by(vertex_snap);
  611. facebvh[i].next = -1;
  612. if (faces[i].from_b) {
  613. if (first_b) {
  614. aabb_b = facebvh[i].aabb;
  615. first_b = false;
  616. } else {
  617. aabb_b.merge_with(facebvh[i].aabb);
  618. }
  619. } else {
  620. if (first_a) {
  621. aabb_a = facebvh[i].aabb;
  622. first_a = false;
  623. } else {
  624. aabb_a.merge_with(facebvh[i].aabb);
  625. }
  626. }
  627. }
  628. AABB intersection_aabb = aabb_a.intersection(aabb_b);
  629. // Check if shape AABBs intersect.
  630. if (intersection_aabb.size == Vector3()) {
  631. return;
  632. }
  633. Vector<FaceBVH *> bvhtrvec;
  634. bvhtrvec.resize(faces.size());
  635. FaceBVH **bvhptr = bvhtrvec.ptrw();
  636. for (int i = 0; i < faces.size(); i++) {
  637. bvhptr[i] = &facebvh[i];
  638. }
  639. int max_depth = 0;
  640. int max_alloc = faces.size();
  641. _create_bvh(facebvh, bvhptr, 0, faces.size(), 1, max_depth, max_alloc);
  642. for (int i = 0; i < faces.size(); i++) {
  643. // Check if face AABB intersects the intersection AABB.
  644. if (!intersection_aabb.intersects_inclusive(facebvh[i].aabb)) {
  645. continue;
  646. }
  647. if (_bvh_inside(facebvh, max_depth, max_alloc - 1, i)) {
  648. faces.write[i].inside = true;
  649. }
  650. }
  651. }
  652. 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) {
  653. int indices[3];
  654. for (int i = 0; i < 3; i++) {
  655. VertexKey vk;
  656. vk.x = int((double(p_points[i].x) + double(vertex_snap) * 0.31234) / double(vertex_snap));
  657. vk.y = int((double(p_points[i].y) + double(vertex_snap) * 0.31234) / double(vertex_snap));
  658. vk.z = int((double(p_points[i].z) + double(vertex_snap) * 0.31234) / double(vertex_snap));
  659. int res;
  660. if (snap_cache.lookup(vk, res)) {
  661. indices[i] = res;
  662. } else {
  663. indices[i] = points.size();
  664. points.push_back(p_points[i]);
  665. snap_cache.set(vk, indices[i]);
  666. }
  667. }
  668. // Don't add degenerate faces.
  669. if (indices[0] == indices[2] || indices[0] == indices[1] || indices[1] == indices[2]) {
  670. return;
  671. }
  672. MeshMerge::Face face;
  673. face.from_b = p_from_b;
  674. face.inside = false;
  675. face.smooth = p_smooth;
  676. face.invert = p_invert;
  677. if (p_material.is_valid()) {
  678. if (!materials.has(p_material)) {
  679. face.material_idx = materials.size();
  680. materials[p_material] = face.material_idx;
  681. } else {
  682. face.material_idx = materials[p_material];
  683. }
  684. } else {
  685. face.material_idx = -1;
  686. }
  687. for (int k = 0; k < 3; k++) {
  688. face.points[k] = indices[k];
  689. face.uvs[k] = p_uvs[k];
  690. }
  691. faces.push_back(face);
  692. }
  693. // CSGBrushOperation::Build2DFaces
  694. int CSGBrushOperation::Build2DFaces::_get_point_idx(const Vector2 &p_point) {
  695. for (int vertex_idx = 0; vertex_idx < vertices.size(); ++vertex_idx) {
  696. if (vertices[vertex_idx].point.distance_squared_to(p_point) < vertex_snap2) {
  697. return vertex_idx;
  698. }
  699. }
  700. return -1;
  701. }
  702. int CSGBrushOperation::Build2DFaces::_add_vertex(const Vertex2D &p_vertex) {
  703. // Check if vertex exists.
  704. int vertex_id = _get_point_idx(p_vertex.point);
  705. if (vertex_id != -1) {
  706. return vertex_id;
  707. }
  708. vertices.push_back(p_vertex);
  709. return vertices.size() - 1;
  710. }
  711. void CSGBrushOperation::Build2DFaces::_add_vertex_idx_sorted(Vector<int> &r_vertex_indices, int p_new_vertex_index) {
  712. if (p_new_vertex_index >= 0 && !r_vertex_indices.has(p_new_vertex_index)) {
  713. ERR_FAIL_COND_MSG(p_new_vertex_index >= vertices.size(), "Invalid vertex index.");
  714. // The first vertex.
  715. if (r_vertex_indices.size() == 0) {
  716. // Simply add it.
  717. r_vertex_indices.push_back(p_new_vertex_index);
  718. return;
  719. }
  720. // The second vertex.
  721. if (r_vertex_indices.size() == 1) {
  722. Vector2 first_point = vertices[r_vertex_indices[0]].point;
  723. Vector2 new_point = vertices[p_new_vertex_index].point;
  724. // Sort along the axis with the greatest difference.
  725. int axis = 0;
  726. if (Math::abs(new_point.x - first_point.x) < Math::abs(new_point.y - first_point.y)) {
  727. axis = 1;
  728. }
  729. // Add it to the beginning or the end appropriately.
  730. if (new_point[axis] < first_point[axis]) {
  731. r_vertex_indices.insert(0, p_new_vertex_index);
  732. } else {
  733. r_vertex_indices.push_back(p_new_vertex_index);
  734. }
  735. return;
  736. }
  737. // Third or later vertices.
  738. Vector2 first_point = vertices[r_vertex_indices[0]].point;
  739. Vector2 last_point = vertices[r_vertex_indices[r_vertex_indices.size() - 1]].point;
  740. Vector2 new_point = vertices[p_new_vertex_index].point;
  741. // Determine axis being sorted against i.e. the axis with the greatest difference.
  742. int axis = 0;
  743. if (Math::abs(last_point.x - first_point.x) < Math::abs(last_point.y - first_point.y)) {
  744. axis = 1;
  745. }
  746. // Insert the point at the appropriate index.
  747. for (int insert_idx = 0; insert_idx < r_vertex_indices.size(); ++insert_idx) {
  748. Vector2 insert_point = vertices[r_vertex_indices[insert_idx]].point;
  749. if (new_point[axis] < insert_point[axis]) {
  750. r_vertex_indices.insert(insert_idx, p_new_vertex_index);
  751. return;
  752. }
  753. }
  754. // New largest, add it to the end.
  755. r_vertex_indices.push_back(p_new_vertex_index);
  756. }
  757. }
  758. void CSGBrushOperation::Build2DFaces::_merge_faces(const Vector<int> &p_segment_indices) {
  759. int segments = p_segment_indices.size() - 1;
  760. if (segments < 2) {
  761. return;
  762. }
  763. // Faces around an inner vertex are merged by moving the inner vertex to the first vertex.
  764. for (int sorted_idx = 1; sorted_idx < segments; ++sorted_idx) {
  765. int closest_idx = 0;
  766. int inner_idx = p_segment_indices[sorted_idx];
  767. if (sorted_idx > segments / 2) {
  768. // Merge to other segment end.
  769. closest_idx = segments;
  770. // Reverse the merge order.
  771. inner_idx = p_segment_indices[segments + segments / 2 - sorted_idx];
  772. }
  773. // Find the mergeable faces.
  774. Vector<int> merge_faces_idx;
  775. Vector<Face2D> merge_faces;
  776. Vector<int> merge_faces_inner_vertex_idx;
  777. for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
  778. for (int face_vertex_idx = 0; face_vertex_idx < 3; ++face_vertex_idx) {
  779. if (faces[face_idx].vertex_idx[face_vertex_idx] == inner_idx) {
  780. merge_faces_idx.push_back(face_idx);
  781. merge_faces.push_back(faces[face_idx]);
  782. merge_faces_inner_vertex_idx.push_back(face_vertex_idx);
  783. }
  784. }
  785. }
  786. Vector<int> degenerate_points;
  787. // Create the new faces.
  788. for (int merge_idx = 0; merge_idx < merge_faces.size(); ++merge_idx) {
  789. int outer_edge_idx[2];
  790. outer_edge_idx[0] = merge_faces[merge_idx].vertex_idx[(merge_faces_inner_vertex_idx[merge_idx] + 1) % 3];
  791. outer_edge_idx[1] = merge_faces[merge_idx].vertex_idx[(merge_faces_inner_vertex_idx[merge_idx] + 2) % 3];
  792. // Skip flattened faces.
  793. if (outer_edge_idx[0] == p_segment_indices[closest_idx] ||
  794. outer_edge_idx[1] == p_segment_indices[closest_idx]) {
  795. continue;
  796. }
  797. //Don't create degenerate triangles.
  798. Vector2 edge1[2] = {
  799. vertices[outer_edge_idx[0]].point,
  800. vertices[p_segment_indices[closest_idx]].point
  801. };
  802. Vector2 edge2[2] = {
  803. vertices[outer_edge_idx[1]].point,
  804. vertices[p_segment_indices[closest_idx]].point
  805. };
  806. if (are_segments_parallel(edge1, edge2, vertex_snap2)) {
  807. if (!degenerate_points.find(outer_edge_idx[0])) {
  808. degenerate_points.push_back(outer_edge_idx[0]);
  809. }
  810. if (!degenerate_points.find(outer_edge_idx[1])) {
  811. degenerate_points.push_back(outer_edge_idx[1]);
  812. }
  813. continue;
  814. }
  815. // Create new faces.
  816. Face2D new_face;
  817. new_face.vertex_idx[0] = p_segment_indices[closest_idx];
  818. new_face.vertex_idx[1] = outer_edge_idx[0];
  819. new_face.vertex_idx[2] = outer_edge_idx[1];
  820. faces.push_back(new_face);
  821. }
  822. // Delete the old faces in reverse index order.
  823. merge_faces_idx.sort();
  824. merge_faces_idx.reverse();
  825. for (int i = 0; i < merge_faces_idx.size(); ++i) {
  826. faces.remove_at(merge_faces_idx[i]);
  827. }
  828. if (degenerate_points.size() == 0) {
  829. continue;
  830. }
  831. // Split faces using degenerate points.
  832. for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
  833. Face2D face = faces[face_idx];
  834. Vertex2D face_vertices[3] = {
  835. vertices[face.vertex_idx[0]],
  836. vertices[face.vertex_idx[1]],
  837. vertices[face.vertex_idx[2]]
  838. };
  839. Vector2 face_points[3] = {
  840. face_vertices[0].point,
  841. face_vertices[1].point,
  842. face_vertices[2].point
  843. };
  844. for (int point_idx = 0; point_idx < degenerate_points.size(); ++point_idx) {
  845. int degenerate_idx = degenerate_points[point_idx];
  846. Vector2 point_2D = vertices[degenerate_idx].point;
  847. // Check if point is existing face vertex.
  848. bool existing = false;
  849. for (int i = 0; i < 3; ++i) {
  850. if (face_vertices[i].point.distance_squared_to(point_2D) < vertex_snap2) {
  851. existing = true;
  852. break;
  853. }
  854. }
  855. if (existing) {
  856. continue;
  857. }
  858. // Check if point is on each edge.
  859. for (int face_edge_idx = 0; face_edge_idx < 3; ++face_edge_idx) {
  860. Vector2 edge_points[2] = {
  861. face_points[face_edge_idx],
  862. face_points[(face_edge_idx + 1) % 3]
  863. };
  864. Vector2 closest_point = Geometry2D::get_closest_point_to_segment(point_2D, edge_points);
  865. if (point_2D.distance_squared_to(closest_point) < vertex_snap2) {
  866. int opposite_vertex_idx = face.vertex_idx[(face_edge_idx + 2) % 3];
  867. // If new vertex snaps to degenerate vertex, just delete this face.
  868. if (degenerate_idx == opposite_vertex_idx) {
  869. faces.remove_at(face_idx);
  870. // Update index.
  871. --face_idx;
  872. break;
  873. }
  874. // Create two new faces around the new edge and remove this face.
  875. // The new edge is the last edge.
  876. Face2D left_face;
  877. left_face.vertex_idx[0] = degenerate_idx;
  878. left_face.vertex_idx[1] = face.vertex_idx[(face_edge_idx + 1) % 3];
  879. left_face.vertex_idx[2] = opposite_vertex_idx;
  880. Face2D right_face;
  881. right_face.vertex_idx[0] = opposite_vertex_idx;
  882. right_face.vertex_idx[1] = face.vertex_idx[face_edge_idx];
  883. right_face.vertex_idx[2] = degenerate_idx;
  884. faces.remove_at(face_idx);
  885. faces.insert(face_idx, right_face);
  886. faces.insert(face_idx, left_face);
  887. // Don't check against the new faces.
  888. ++face_idx;
  889. // No need to check other edges.
  890. break;
  891. }
  892. }
  893. }
  894. }
  895. }
  896. }
  897. void CSGBrushOperation::Build2DFaces::_find_edge_intersections(const Vector2 p_segment_points[2], Vector<int> &r_segment_indices) {
  898. LocalVector<Vector<Vector2>> processed_edges;
  899. // For each face.
  900. for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
  901. Face2D face = faces[face_idx];
  902. Vertex2D face_vertices[3] = {
  903. vertices[face.vertex_idx[0]],
  904. vertices[face.vertex_idx[1]],
  905. vertices[face.vertex_idx[2]]
  906. };
  907. // Check each edge.
  908. for (int face_edge_idx = 0; face_edge_idx < 3; ++face_edge_idx) {
  909. Vector<Vector2> edge_points_and_uvs = {
  910. face_vertices[face_edge_idx].point,
  911. face_vertices[(face_edge_idx + 1) % 3].point,
  912. face_vertices[face_edge_idx].uv,
  913. face_vertices[(face_edge_idx + 1) % 3].uv
  914. };
  915. Vector2 edge_points[2] = {
  916. edge_points_and_uvs[0],
  917. edge_points_and_uvs[1],
  918. };
  919. Vector2 edge_uvs[2] = {
  920. edge_points_and_uvs[2],
  921. edge_points_and_uvs[3],
  922. };
  923. // Check if edge has already been processed.
  924. if (processed_edges.has(edge_points_and_uvs)) {
  925. continue;
  926. }
  927. processed_edges.push_back(edge_points_and_uvs);
  928. // First check if the ends of the segment are on the edge.
  929. Vector2 intersection_point;
  930. bool on_edge = false;
  931. for (int edge_point_idx = 0; edge_point_idx < 2; ++edge_point_idx) {
  932. intersection_point = Geometry2D::get_closest_point_to_segment(p_segment_points[edge_point_idx], edge_points);
  933. if (p_segment_points[edge_point_idx].distance_squared_to(intersection_point) < vertex_snap2) {
  934. on_edge = true;
  935. break;
  936. }
  937. }
  938. // Else check if the segment intersects the edge.
  939. if (on_edge || Geometry2D::segment_intersects_segment(p_segment_points[0], p_segment_points[1], edge_points[0], edge_points[1], &intersection_point)) {
  940. // Check if intersection point is an edge point.
  941. if ((edge_points[0].distance_squared_to(intersection_point) < vertex_snap2) ||
  942. (edge_points[1].distance_squared_to(intersection_point) < vertex_snap2)) {
  943. continue;
  944. }
  945. // Check if edge exists, by checking if the intersecting segment is parallel to the edge.
  946. if (are_segments_parallel(p_segment_points, edge_points, vertex_snap2)) {
  947. continue;
  948. }
  949. // Add the intersection point as a new vertex.
  950. Vertex2D new_vertex;
  951. new_vertex.point = intersection_point;
  952. new_vertex.uv = interpolate_segment_uv(edge_points, edge_uvs, intersection_point);
  953. int new_vertex_idx = _add_vertex(new_vertex);
  954. int opposite_vertex_idx = face.vertex_idx[(face_edge_idx + 2) % 3];
  955. _add_vertex_idx_sorted(r_segment_indices, new_vertex_idx);
  956. // If new vertex snaps to opposite vertex, just delete this face.
  957. if (new_vertex_idx == opposite_vertex_idx) {
  958. faces.remove_at(face_idx);
  959. // Update index.
  960. --face_idx;
  961. break;
  962. }
  963. // If opposite point is on the segment, add its index to segment indices too.
  964. Vector2 closest_point = Geometry2D::get_closest_point_to_segment(vertices[opposite_vertex_idx].point, p_segment_points);
  965. if (vertices[opposite_vertex_idx].point.distance_squared_to(closest_point) < vertex_snap2) {
  966. _add_vertex_idx_sorted(r_segment_indices, opposite_vertex_idx);
  967. }
  968. // Create two new faces around the new edge and remove this face.
  969. // The new edge is the last edge.
  970. Face2D left_face;
  971. left_face.vertex_idx[0] = new_vertex_idx;
  972. left_face.vertex_idx[1] = face.vertex_idx[(face_edge_idx + 1) % 3];
  973. left_face.vertex_idx[2] = opposite_vertex_idx;
  974. Face2D right_face;
  975. right_face.vertex_idx[0] = opposite_vertex_idx;
  976. right_face.vertex_idx[1] = face.vertex_idx[face_edge_idx];
  977. right_face.vertex_idx[2] = new_vertex_idx;
  978. faces.remove_at(face_idx);
  979. faces.insert(face_idx, right_face);
  980. faces.insert(face_idx, left_face);
  981. // Check against the new faces.
  982. --face_idx;
  983. break;
  984. }
  985. }
  986. }
  987. }
  988. int CSGBrushOperation::Build2DFaces::_insert_point(const Vector2 &p_point) {
  989. int new_vertex_idx = -1;
  990. for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
  991. Face2D face = faces[face_idx];
  992. Vertex2D face_vertices[3] = {
  993. vertices[face.vertex_idx[0]],
  994. vertices[face.vertex_idx[1]],
  995. vertices[face.vertex_idx[2]]
  996. };
  997. Vector2 points[3] = {
  998. face_vertices[0].point,
  999. face_vertices[1].point,
  1000. face_vertices[2].point
  1001. };
  1002. Vector2 uvs[3] = {
  1003. face_vertices[0].uv,
  1004. face_vertices[1].uv,
  1005. face_vertices[2].uv
  1006. };
  1007. // Skip degenerate triangles.
  1008. if (is_triangle_degenerate(points, vertex_snap2)) {
  1009. continue;
  1010. }
  1011. // Check if point is existing face vertex.
  1012. for (int i = 0; i < 3; ++i) {
  1013. if (face_vertices[i].point.distance_squared_to(p_point) < vertex_snap2) {
  1014. return face.vertex_idx[i];
  1015. }
  1016. }
  1017. // Check if point is on each edge.
  1018. bool on_edge = false;
  1019. for (int face_edge_idx = 0; face_edge_idx < 3; ++face_edge_idx) {
  1020. Vector2 edge_points[2] = {
  1021. points[face_edge_idx],
  1022. points[(face_edge_idx + 1) % 3]
  1023. };
  1024. Vector2 edge_uvs[2] = {
  1025. uvs[face_edge_idx],
  1026. uvs[(face_edge_idx + 1) % 3]
  1027. };
  1028. Vector2 closest_point = Geometry2D::get_closest_point_to_segment(p_point, edge_points);
  1029. if (p_point.distance_squared_to(closest_point) < vertex_snap2) {
  1030. on_edge = true;
  1031. // Add the point as a new vertex.
  1032. Vertex2D new_vertex;
  1033. new_vertex.point = p_point;
  1034. new_vertex.uv = interpolate_segment_uv(edge_points, edge_uvs, p_point);
  1035. new_vertex_idx = _add_vertex(new_vertex);
  1036. int opposite_vertex_idx = face.vertex_idx[(face_edge_idx + 2) % 3];
  1037. // If new vertex snaps to opposite vertex, just delete this face.
  1038. if (new_vertex_idx == opposite_vertex_idx) {
  1039. faces.remove_at(face_idx);
  1040. // Update index.
  1041. --face_idx;
  1042. break;
  1043. }
  1044. // Don't create degenerate triangles.
  1045. Vector2 split_edge1[2] = { vertices[new_vertex_idx].point, edge_points[0] };
  1046. Vector2 split_edge2[2] = { vertices[new_vertex_idx].point, edge_points[1] };
  1047. Vector2 new_edge[2] = { vertices[new_vertex_idx].point, vertices[opposite_vertex_idx].point };
  1048. if (are_segments_parallel(split_edge1, new_edge, vertex_snap2) &&
  1049. are_segments_parallel(split_edge2, new_edge, vertex_snap2)) {
  1050. break;
  1051. }
  1052. // Create two new faces around the new edge and remove this face.
  1053. // The new edge is the last edge.
  1054. Face2D left_face;
  1055. left_face.vertex_idx[0] = new_vertex_idx;
  1056. left_face.vertex_idx[1] = face.vertex_idx[(face_edge_idx + 1) % 3];
  1057. left_face.vertex_idx[2] = opposite_vertex_idx;
  1058. Face2D right_face;
  1059. right_face.vertex_idx[0] = opposite_vertex_idx;
  1060. right_face.vertex_idx[1] = face.vertex_idx[face_edge_idx];
  1061. right_face.vertex_idx[2] = new_vertex_idx;
  1062. faces.remove_at(face_idx);
  1063. faces.insert(face_idx, right_face);
  1064. faces.insert(face_idx, left_face);
  1065. // Don't check against the new faces.
  1066. ++face_idx;
  1067. // No need to check other edges.
  1068. break;
  1069. }
  1070. }
  1071. // If not on an edge, check if the point is inside the face.
  1072. if (!on_edge && Geometry2D::is_point_in_triangle(p_point, face_vertices[0].point, face_vertices[1].point, face_vertices[2].point)) {
  1073. // Add the point as a new vertex.
  1074. Vertex2D new_vertex;
  1075. new_vertex.point = p_point;
  1076. new_vertex.uv = interpolate_triangle_uv(points, uvs, p_point);
  1077. new_vertex_idx = _add_vertex(new_vertex);
  1078. // Create three new faces around this point and remove this face.
  1079. // The new vertex is the last vertex.
  1080. for (int i = 0; i < 3; ++i) {
  1081. // Don't create degenerate triangles.
  1082. Vector2 new_points[3] = { points[i], points[(i + 1) % 3], vertices[new_vertex_idx].point };
  1083. if (is_triangle_degenerate(new_points, vertex_snap2)) {
  1084. continue;
  1085. }
  1086. Face2D new_face;
  1087. new_face.vertex_idx[0] = face.vertex_idx[i];
  1088. new_face.vertex_idx[1] = face.vertex_idx[(i + 1) % 3];
  1089. new_face.vertex_idx[2] = new_vertex_idx;
  1090. faces.push_back(new_face);
  1091. }
  1092. faces.remove_at(face_idx);
  1093. // No need to check other faces.
  1094. break;
  1095. }
  1096. }
  1097. return new_vertex_idx;
  1098. }
  1099. void CSGBrushOperation::Build2DFaces::insert(const CSGBrush &p_brush, int p_face_idx) {
  1100. // Find edge points that cross the plane and face points that are in the plane.
  1101. // Map those points to 2D.
  1102. // Create new faces from those points.
  1103. Vector2 points_2D[3];
  1104. int points_count = 0;
  1105. for (int i = 0; i < 3; i++) {
  1106. Vector3 point_3D = p_brush.faces[p_face_idx].vertices[i];
  1107. if (plane.has_point(point_3D)) {
  1108. // Point is in the plane, add it.
  1109. Vector3 point_2D = plane.project(point_3D);
  1110. point_2D = to_2D.xform(point_2D);
  1111. points_2D[points_count++] = Vector2(point_2D.x, point_2D.y);
  1112. } else {
  1113. Vector3 next_point_3D = p_brush.faces[p_face_idx].vertices[(i + 1) % 3];
  1114. if (plane.has_point(next_point_3D)) {
  1115. continue; // Next point is in plane, it will be added separately.
  1116. }
  1117. if (plane.is_point_over(point_3D) == plane.is_point_over(next_point_3D)) {
  1118. continue; // Both points on the same side of the plane, ignore.
  1119. }
  1120. // Edge crosses the plane, find and add the intersection point.
  1121. Vector3 point_2D;
  1122. if (plane.intersects_segment(point_3D, next_point_3D, &point_2D)) {
  1123. point_2D = to_2D.xform(point_2D);
  1124. points_2D[points_count++] = Vector2(point_2D.x, point_2D.y);
  1125. }
  1126. }
  1127. }
  1128. Vector<int> segment_indices;
  1129. Vector2 segment[2];
  1130. int inserted_index[3] = { -1, -1, -1 };
  1131. // Insert points.
  1132. for (int i = 0; i < points_count; ++i) {
  1133. inserted_index[i] = _insert_point(points_2D[i]);
  1134. }
  1135. if (points_count == 2) {
  1136. // Insert a single segment.
  1137. segment[0] = points_2D[0];
  1138. segment[1] = points_2D[1];
  1139. _find_edge_intersections(segment, segment_indices);
  1140. for (int i = 0; i < 2; ++i) {
  1141. _add_vertex_idx_sorted(segment_indices, inserted_index[i]);
  1142. }
  1143. _merge_faces(segment_indices);
  1144. }
  1145. if (points_count == 3) {
  1146. // Insert three segments.
  1147. for (int edge_idx = 0; edge_idx < 3; ++edge_idx) {
  1148. segment[0] = points_2D[edge_idx];
  1149. segment[1] = points_2D[(edge_idx + 1) % 3];
  1150. _find_edge_intersections(segment, segment_indices);
  1151. for (int i = 0; i < 2; ++i) {
  1152. _add_vertex_idx_sorted(segment_indices, inserted_index[(edge_idx + i) % 3]);
  1153. }
  1154. _merge_faces(segment_indices);
  1155. segment_indices.clear();
  1156. }
  1157. }
  1158. }
  1159. void CSGBrushOperation::Build2DFaces::addFacesToMesh(MeshMerge &r_mesh_merge, bool p_smooth, bool p_invert, const Ref<Material> &p_material, bool p_from_b) {
  1160. for (int face_idx = 0; face_idx < faces.size(); ++face_idx) {
  1161. Face2D face = faces[face_idx];
  1162. Vertex2D fv[3] = {
  1163. vertices[face.vertex_idx[0]],
  1164. vertices[face.vertex_idx[1]],
  1165. vertices[face.vertex_idx[2]]
  1166. };
  1167. // Convert 2D vertex points to 3D.
  1168. Vector3 points_3D[3];
  1169. Vector2 uvs[3];
  1170. for (int i = 0; i < 3; ++i) {
  1171. Vector3 point_2D(fv[i].point.x, fv[i].point.y, 0);
  1172. points_3D[i] = to_3D.xform(point_2D);
  1173. uvs[i] = fv[i].uv;
  1174. }
  1175. r_mesh_merge.add_face(points_3D, uvs, p_smooth, p_invert, p_material, p_from_b);
  1176. }
  1177. }
  1178. CSGBrushOperation::Build2DFaces::Build2DFaces(const CSGBrush &p_brush, int p_face_idx, float p_vertex_snap2) :
  1179. vertex_snap2(p_vertex_snap2 * p_vertex_snap2) {
  1180. // Convert 3D vertex points to 2D.
  1181. Vector3 points_3D[3] = {
  1182. p_brush.faces[p_face_idx].vertices[0],
  1183. p_brush.faces[p_face_idx].vertices[1],
  1184. p_brush.faces[p_face_idx].vertices[2],
  1185. };
  1186. plane = Plane(points_3D[0], points_3D[1], points_3D[2]);
  1187. to_3D.origin = points_3D[0];
  1188. to_3D.basis.set_column(2, plane.normal);
  1189. to_3D.basis.set_column(0, (points_3D[1] - points_3D[2]).normalized());
  1190. to_3D.basis.set_column(1, to_3D.basis.get_column(0).cross(to_3D.basis.get_column(2)).normalized());
  1191. to_2D = to_3D.affine_inverse();
  1192. Face2D face;
  1193. for (int i = 0; i < 3; i++) {
  1194. Vertex2D vertex;
  1195. Vector3 point_2D = to_2D.xform(points_3D[i]);
  1196. vertex.point.x = point_2D.x;
  1197. vertex.point.y = point_2D.y;
  1198. vertex.uv = p_brush.faces[p_face_idx].uvs[i];
  1199. vertices.push_back(vertex);
  1200. face.vertex_idx[i] = i;
  1201. }
  1202. faces.push_back(face);
  1203. }
  1204. 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) {
  1205. Vector3 vertices_a[3] = {
  1206. p_brush_a.faces[p_face_idx_a].vertices[0],
  1207. p_brush_a.faces[p_face_idx_a].vertices[1],
  1208. p_brush_a.faces[p_face_idx_a].vertices[2],
  1209. };
  1210. Vector3 vertices_b[3] = {
  1211. p_brush_b.faces[p_face_idx_b].vertices[0],
  1212. p_brush_b.faces[p_face_idx_b].vertices[1],
  1213. p_brush_b.faces[p_face_idx_b].vertices[2],
  1214. };
  1215. // Don't use degenerate faces.
  1216. bool has_degenerate = false;
  1217. if (is_snapable(vertices_a[0], vertices_a[1], p_vertex_snap) ||
  1218. is_snapable(vertices_a[0], vertices_a[2], p_vertex_snap) ||
  1219. is_snapable(vertices_a[1], vertices_a[2], p_vertex_snap)) {
  1220. p_collection.build2DFacesA[p_face_idx_a] = Build2DFaces();
  1221. has_degenerate = true;
  1222. }
  1223. if (is_snapable(vertices_b[0], vertices_b[1], p_vertex_snap) ||
  1224. is_snapable(vertices_b[0], vertices_b[2], p_vertex_snap) ||
  1225. is_snapable(vertices_b[1], vertices_b[2], p_vertex_snap)) {
  1226. p_collection.build2DFacesB[p_face_idx_b] = Build2DFaces();
  1227. has_degenerate = true;
  1228. }
  1229. if (has_degenerate) {
  1230. return;
  1231. }
  1232. // Ensure B has points either side of or in the plane of A.
  1233. int over_count = 0, under_count = 0;
  1234. Plane plane_a(vertices_a[0], vertices_a[1], vertices_a[2]);
  1235. ERR_FAIL_COND_MSG(plane_a.normal == Vector3(), "Couldn't form plane from Brush A face.");
  1236. for (int i = 0; i < 3; i++) {
  1237. if (plane_a.has_point(vertices_b[i])) {
  1238. // In plane.
  1239. } else if (plane_a.is_point_over(vertices_b[i])) {
  1240. over_count++;
  1241. } else {
  1242. under_count++;
  1243. }
  1244. }
  1245. // If all points under or over the plane, there is no intersection.
  1246. if (over_count == 3 || under_count == 3) {
  1247. return;
  1248. }
  1249. // Ensure A has points either side of or in the plane of B.
  1250. over_count = 0;
  1251. under_count = 0;
  1252. Plane plane_b(vertices_b[0], vertices_b[1], vertices_b[2]);
  1253. ERR_FAIL_COND_MSG(plane_b.normal == Vector3(), "Couldn't form plane from Brush B face.");
  1254. for (int i = 0; i < 3; i++) {
  1255. if (plane_b.has_point(vertices_a[i])) {
  1256. // In plane.
  1257. } else if (plane_b.is_point_over(vertices_a[i])) {
  1258. over_count++;
  1259. } else {
  1260. under_count++;
  1261. }
  1262. }
  1263. // If all points under or over the plane, there is no intersection.
  1264. if (over_count == 3 || under_count == 3) {
  1265. return;
  1266. }
  1267. // Check for intersection using the SAT theorem.
  1268. {
  1269. // Edge pair cross product combinations.
  1270. for (int i = 0; i < 3; i++) {
  1271. Vector3 axis_a = (vertices_a[i] - vertices_a[(i + 1) % 3]).normalized();
  1272. for (int j = 0; j < 3; j++) {
  1273. Vector3 axis_b = (vertices_b[j] - vertices_b[(j + 1) % 3]).normalized();
  1274. Vector3 sep_axis = axis_a.cross(axis_b);
  1275. if (sep_axis == Vector3()) {
  1276. continue; //colineal
  1277. }
  1278. sep_axis.normalize();
  1279. real_t min_a = 1e20, max_a = -1e20;
  1280. real_t min_b = 1e20, max_b = -1e20;
  1281. for (int k = 0; k < 3; k++) {
  1282. real_t d = sep_axis.dot(vertices_a[k]);
  1283. min_a = MIN(min_a, d);
  1284. max_a = MAX(max_a, d);
  1285. d = sep_axis.dot(vertices_b[k]);
  1286. min_b = MIN(min_b, d);
  1287. max_b = MAX(max_b, d);
  1288. }
  1289. min_b -= (max_a - min_a) * 0.5;
  1290. max_b += (max_a - min_a) * 0.5;
  1291. real_t dmin = min_b - (min_a + max_a) * 0.5;
  1292. real_t dmax = max_b - (min_a + max_a) * 0.5;
  1293. if (dmin > CMP_EPSILON || dmax < -CMP_EPSILON) {
  1294. return; // Does not contain zero, so they don't overlap.
  1295. }
  1296. }
  1297. }
  1298. }
  1299. // If we're still here, the faces probably intersect, so add new faces.
  1300. if (!p_collection.build2DFacesA.has(p_face_idx_a)) {
  1301. p_collection.build2DFacesA[p_face_idx_a] = Build2DFaces(p_brush_a, p_face_idx_a, p_vertex_snap);
  1302. }
  1303. p_collection.build2DFacesA[p_face_idx_a].insert(p_brush_b, p_face_idx_b);
  1304. if (!p_collection.build2DFacesB.has(p_face_idx_b)) {
  1305. p_collection.build2DFacesB[p_face_idx_b] = Build2DFaces(p_brush_b, p_face_idx_b, p_vertex_snap);
  1306. }
  1307. p_collection.build2DFacesB[p_face_idx_b].insert(p_brush_a, p_face_idx_a);
  1308. }