mesh.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  1. /*************************************************************************/
  2. /* mesh.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "mesh.h"
  31. #include "core/pair.h"
  32. #include "scene/resources/concave_polygon_shape_3d.h"
  33. #include "scene/resources/convex_polygon_shape_3d.h"
  34. #include "surface_tool.h"
  35. #include <stdlib.h>
  36. Mesh::ConvexDecompositionFunc Mesh::convex_composition_function = nullptr;
  37. Ref<TriangleMesh> Mesh::generate_triangle_mesh() const {
  38. if (triangle_mesh.is_valid())
  39. return triangle_mesh;
  40. int facecount = 0;
  41. for (int i = 0; i < get_surface_count(); i++) {
  42. if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES)
  43. continue;
  44. if (surface_get_format(i) & ARRAY_FORMAT_INDEX) {
  45. facecount += surface_get_array_index_len(i);
  46. } else {
  47. facecount += surface_get_array_len(i);
  48. }
  49. }
  50. if (facecount == 0 || (facecount % 3) != 0)
  51. return triangle_mesh;
  52. Vector<Vector3> faces;
  53. faces.resize(facecount);
  54. Vector3 *facesw = faces.ptrw();
  55. int widx = 0;
  56. for (int i = 0; i < get_surface_count(); i++) {
  57. if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES)
  58. continue;
  59. Array a = surface_get_arrays(i);
  60. ERR_FAIL_COND_V(a.empty(), Ref<TriangleMesh>());
  61. int vc = surface_get_array_len(i);
  62. Vector<Vector3> vertices = a[ARRAY_VERTEX];
  63. const Vector3 *vr = vertices.ptr();
  64. if (surface_get_format(i) & ARRAY_FORMAT_INDEX) {
  65. int ic = surface_get_array_index_len(i);
  66. Vector<int> indices = a[ARRAY_INDEX];
  67. const int *ir = indices.ptr();
  68. for (int j = 0; j < ic; j++) {
  69. int index = ir[j];
  70. facesw[widx++] = vr[index];
  71. }
  72. } else {
  73. for (int j = 0; j < vc; j++)
  74. facesw[widx++] = vr[j];
  75. }
  76. }
  77. triangle_mesh = Ref<TriangleMesh>(memnew(TriangleMesh));
  78. triangle_mesh->create(faces);
  79. return triangle_mesh;
  80. }
  81. void Mesh::generate_debug_mesh_lines(Vector<Vector3> &r_lines) {
  82. if (debug_lines.size() > 0) {
  83. r_lines = debug_lines;
  84. return;
  85. }
  86. Ref<TriangleMesh> tm = generate_triangle_mesh();
  87. if (tm.is_null())
  88. return;
  89. Vector<int> triangle_indices;
  90. tm->get_indices(&triangle_indices);
  91. const int triangles_num = tm->get_triangles().size();
  92. Vector<Vector3> vertices = tm->get_vertices();
  93. debug_lines.resize(tm->get_triangles().size() * 6); // 3 lines x 2 points each line
  94. const int *ind_r = triangle_indices.ptr();
  95. const Vector3 *ver_r = vertices.ptr();
  96. for (int j = 0, x = 0, i = 0; i < triangles_num; j += 6, x += 3, ++i) {
  97. // Triangle line 1
  98. debug_lines.write[j + 0] = ver_r[ind_r[x + 0]];
  99. debug_lines.write[j + 1] = ver_r[ind_r[x + 1]];
  100. // Triangle line 2
  101. debug_lines.write[j + 2] = ver_r[ind_r[x + 1]];
  102. debug_lines.write[j + 3] = ver_r[ind_r[x + 2]];
  103. // Triangle line 3
  104. debug_lines.write[j + 4] = ver_r[ind_r[x + 2]];
  105. debug_lines.write[j + 5] = ver_r[ind_r[x + 0]];
  106. }
  107. r_lines = debug_lines;
  108. }
  109. void Mesh::generate_debug_mesh_indices(Vector<Vector3> &r_points) {
  110. Ref<TriangleMesh> tm = generate_triangle_mesh();
  111. if (tm.is_null())
  112. return;
  113. Vector<Vector3> vertices = tm->get_vertices();
  114. int vertices_size = vertices.size();
  115. r_points.resize(vertices_size);
  116. for (int i = 0; i < vertices_size; ++i) {
  117. r_points.write[i] = vertices[i];
  118. }
  119. }
  120. bool Mesh::surface_is_softbody_friendly(int p_idx) const {
  121. const uint32_t surface_format = surface_get_format(p_idx);
  122. return (surface_format & Mesh::ARRAY_FLAG_USE_DYNAMIC_UPDATE && (!(surface_format & Mesh::ARRAY_COMPRESS_NORMAL)));
  123. }
  124. Vector<Face3> Mesh::get_faces() const {
  125. Ref<TriangleMesh> tm = generate_triangle_mesh();
  126. if (tm.is_valid())
  127. return tm->get_faces();
  128. return Vector<Face3>();
  129. /*
  130. for (int i=0;i<surfaces.size();i++) {
  131. if (RenderingServer::get_singleton()->mesh_surface_get_primitive_type( mesh, i ) != RenderingServer::PRIMITIVE_TRIANGLES )
  132. continue;
  133. Vector<int> indices;
  134. Vector<Vector3> vertices;
  135. vertices=RenderingServer::get_singleton()->mesh_surface_get_array(mesh, i,RenderingServer::ARRAY_VERTEX);
  136. int len=RenderingServer::get_singleton()->mesh_surface_get_array_index_len(mesh, i);
  137. bool has_indices;
  138. if (len>0) {
  139. indices=RenderingServer::get_singleton()->mesh_surface_get_array(mesh, i,RenderingServer::ARRAY_INDEX);
  140. has_indices=true;
  141. } else {
  142. len=vertices.size();
  143. has_indices=false;
  144. }
  145. if (len<=0)
  146. continue;
  147. const int* indicesr = indices.ptr();
  148. const int *indicesptr = indicesr.ptr();
  149. const Vector3* verticesr = vertices.ptr();
  150. const Vector3 *verticesptr = verticesr.ptr();
  151. int old_faces=faces.size();
  152. int new_faces=old_faces+(len/3);
  153. faces.resize(new_faces);
  154. Face3* facesw = faces.ptrw();
  155. Face3 *facesptr=facesw.ptr();
  156. for (int i=0;i<len/3;i++) {
  157. Face3 face;
  158. for (int j=0;j<3;j++) {
  159. int idx=i*3+j;
  160. face.vertex[j] = has_indices ? verticesptr[ indicesptr[ idx ] ] : verticesptr[idx];
  161. }
  162. facesptr[i+old_faces]=face;
  163. }
  164. }
  165. */
  166. }
  167. Ref<Shape3D> Mesh::create_convex_shape() const {
  168. Vector<Vector3> vertices;
  169. for (int i = 0; i < get_surface_count(); i++) {
  170. Array a = surface_get_arrays(i);
  171. ERR_FAIL_COND_V(a.empty(), Ref<ConvexPolygonShape3D>());
  172. Vector<Vector3> v = a[ARRAY_VERTEX];
  173. vertices.append_array(v);
  174. }
  175. Ref<ConvexPolygonShape3D> shape = memnew(ConvexPolygonShape3D);
  176. shape->set_points(vertices);
  177. return shape;
  178. }
  179. Ref<Shape3D> Mesh::create_trimesh_shape() const {
  180. Vector<Face3> faces = get_faces();
  181. if (faces.size() == 0)
  182. return Ref<Shape3D>();
  183. Vector<Vector3> face_points;
  184. face_points.resize(faces.size() * 3);
  185. for (int i = 0; i < face_points.size(); i += 3) {
  186. Face3 f = faces.get(i / 3);
  187. face_points.set(i, f.vertex[0]);
  188. face_points.set(i + 1, f.vertex[1]);
  189. face_points.set(i + 2, f.vertex[2]);
  190. }
  191. Ref<ConcavePolygonShape3D> shape = memnew(ConcavePolygonShape3D);
  192. shape->set_faces(face_points);
  193. return shape;
  194. }
  195. Ref<Mesh> Mesh::create_outline(float p_margin) const {
  196. Array arrays;
  197. int index_accum = 0;
  198. for (int i = 0; i < get_surface_count(); i++) {
  199. if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES)
  200. continue;
  201. Array a = surface_get_arrays(i);
  202. ERR_FAIL_COND_V(a.empty(), Ref<ArrayMesh>());
  203. if (i == 0) {
  204. arrays = a;
  205. Vector<Vector3> v = a[ARRAY_VERTEX];
  206. index_accum += v.size();
  207. } else {
  208. int vcount = 0;
  209. for (int j = 0; j < arrays.size(); j++) {
  210. if (arrays[j].get_type() == Variant::NIL || a[j].get_type() == Variant::NIL) {
  211. //mismatch, do not use
  212. arrays[j] = Variant();
  213. continue;
  214. }
  215. switch (j) {
  216. case ARRAY_VERTEX:
  217. case ARRAY_NORMAL: {
  218. Vector<Vector3> dst = arrays[j];
  219. Vector<Vector3> src = a[j];
  220. if (j == ARRAY_VERTEX)
  221. vcount = src.size();
  222. if (dst.size() == 0 || src.size() == 0) {
  223. arrays[j] = Variant();
  224. continue;
  225. }
  226. dst.append_array(src);
  227. arrays[j] = dst;
  228. } break;
  229. case ARRAY_TANGENT:
  230. case ARRAY_BONES:
  231. case ARRAY_WEIGHTS: {
  232. Vector<real_t> dst = arrays[j];
  233. Vector<real_t> src = a[j];
  234. if (dst.size() == 0 || src.size() == 0) {
  235. arrays[j] = Variant();
  236. continue;
  237. }
  238. dst.append_array(src);
  239. arrays[j] = dst;
  240. } break;
  241. case ARRAY_COLOR: {
  242. Vector<Color> dst = arrays[j];
  243. Vector<Color> src = a[j];
  244. if (dst.size() == 0 || src.size() == 0) {
  245. arrays[j] = Variant();
  246. continue;
  247. }
  248. dst.append_array(src);
  249. arrays[j] = dst;
  250. } break;
  251. case ARRAY_TEX_UV:
  252. case ARRAY_TEX_UV2: {
  253. Vector<Vector2> dst = arrays[j];
  254. Vector<Vector2> src = a[j];
  255. if (dst.size() == 0 || src.size() == 0) {
  256. arrays[j] = Variant();
  257. continue;
  258. }
  259. dst.append_array(src);
  260. arrays[j] = dst;
  261. } break;
  262. case ARRAY_INDEX: {
  263. Vector<int> dst = arrays[j];
  264. Vector<int> src = a[j];
  265. if (dst.size() == 0 || src.size() == 0) {
  266. arrays[j] = Variant();
  267. continue;
  268. }
  269. {
  270. int ss = src.size();
  271. int *w = src.ptrw();
  272. for (int k = 0; k < ss; k++) {
  273. w[k] += index_accum;
  274. }
  275. }
  276. dst.append_array(src);
  277. arrays[j] = dst;
  278. index_accum += vcount;
  279. } break;
  280. }
  281. }
  282. }
  283. }
  284. ERR_FAIL_COND_V(arrays.size() != ARRAY_MAX, Ref<ArrayMesh>());
  285. {
  286. int *ir = nullptr;
  287. Vector<int> indices = arrays[ARRAY_INDEX];
  288. bool has_indices = false;
  289. Vector<Vector3> vertices = arrays[ARRAY_VERTEX];
  290. int vc = vertices.size();
  291. ERR_FAIL_COND_V(!vc, Ref<ArrayMesh>());
  292. Vector3 *r = vertices.ptrw();
  293. if (indices.size()) {
  294. ERR_FAIL_COND_V(indices.size() % 3 != 0, Ref<ArrayMesh>());
  295. vc = indices.size();
  296. ir = indices.ptrw();
  297. has_indices = true;
  298. }
  299. Map<Vector3, Vector3> normal_accum;
  300. //fill normals with triangle normals
  301. for (int i = 0; i < vc; i += 3) {
  302. Vector3 t[3];
  303. if (has_indices) {
  304. t[0] = r[ir[i + 0]];
  305. t[1] = r[ir[i + 1]];
  306. t[2] = r[ir[i + 2]];
  307. } else {
  308. t[0] = r[i + 0];
  309. t[1] = r[i + 1];
  310. t[2] = r[i + 2];
  311. }
  312. Vector3 n = Plane(t[0], t[1], t[2]).normal;
  313. for (int j = 0; j < 3; j++) {
  314. Map<Vector3, Vector3>::Element *E = normal_accum.find(t[j]);
  315. if (!E) {
  316. normal_accum[t[j]] = n;
  317. } else {
  318. float d = n.dot(E->get());
  319. if (d < 1.0)
  320. E->get() += n * (1.0 - d);
  321. //E->get()+=n;
  322. }
  323. }
  324. }
  325. //normalize
  326. for (Map<Vector3, Vector3>::Element *E = normal_accum.front(); E; E = E->next()) {
  327. E->get().normalize();
  328. }
  329. //displace normals
  330. int vc2 = vertices.size();
  331. for (int i = 0; i < vc2; i++) {
  332. Vector3 t = r[i];
  333. Map<Vector3, Vector3>::Element *E = normal_accum.find(t);
  334. ERR_CONTINUE(!E);
  335. t += E->get() * p_margin;
  336. r[i] = t;
  337. }
  338. arrays[ARRAY_VERTEX] = vertices;
  339. if (!has_indices) {
  340. Vector<int> new_indices;
  341. new_indices.resize(vertices.size());
  342. int *iw = new_indices.ptrw();
  343. for (int j = 0; j < vc2; j += 3) {
  344. iw[j] = j;
  345. iw[j + 1] = j + 2;
  346. iw[j + 2] = j + 1;
  347. }
  348. arrays[ARRAY_INDEX] = new_indices;
  349. } else {
  350. for (int j = 0; j < vc; j += 3) {
  351. SWAP(ir[j + 1], ir[j + 2]);
  352. }
  353. arrays[ARRAY_INDEX] = indices;
  354. }
  355. }
  356. Ref<ArrayMesh> newmesh = memnew(ArrayMesh);
  357. newmesh->add_surface_from_arrays(PRIMITIVE_TRIANGLES, arrays);
  358. return newmesh;
  359. }
  360. void Mesh::set_lightmap_size_hint(const Vector2 &p_size) {
  361. lightmap_size_hint = p_size;
  362. }
  363. Size2 Mesh::get_lightmap_size_hint() const {
  364. return lightmap_size_hint;
  365. }
  366. void Mesh::_bind_methods() {
  367. ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &Mesh::set_lightmap_size_hint);
  368. ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &Mesh::get_lightmap_size_hint);
  369. ClassDB::bind_method(D_METHOD("get_aabb"), &Mesh::get_aabb);
  370. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "lightmap_size_hint"), "set_lightmap_size_hint", "get_lightmap_size_hint");
  371. ClassDB::bind_method(D_METHOD("get_surface_count"), &Mesh::get_surface_count);
  372. ClassDB::bind_method(D_METHOD("surface_get_arrays", "surf_idx"), &Mesh::surface_get_arrays);
  373. ClassDB::bind_method(D_METHOD("surface_get_blend_shape_arrays", "surf_idx"), &Mesh::surface_get_blend_shape_arrays);
  374. ClassDB::bind_method(D_METHOD("surface_set_material", "surf_idx", "material"), &Mesh::surface_set_material);
  375. ClassDB::bind_method(D_METHOD("surface_get_material", "surf_idx"), &Mesh::surface_get_material);
  376. BIND_ENUM_CONSTANT(PRIMITIVE_POINTS);
  377. BIND_ENUM_CONSTANT(PRIMITIVE_LINES);
  378. BIND_ENUM_CONSTANT(PRIMITIVE_LINE_STRIP);
  379. BIND_ENUM_CONSTANT(PRIMITIVE_TRIANGLES);
  380. BIND_ENUM_CONSTANT(PRIMITIVE_TRIANGLE_STRIP);
  381. BIND_ENUM_CONSTANT(BLEND_SHAPE_MODE_NORMALIZED);
  382. BIND_ENUM_CONSTANT(BLEND_SHAPE_MODE_RELATIVE);
  383. BIND_ENUM_CONSTANT(ARRAY_FORMAT_VERTEX);
  384. BIND_ENUM_CONSTANT(ARRAY_FORMAT_NORMAL);
  385. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TANGENT);
  386. BIND_ENUM_CONSTANT(ARRAY_FORMAT_COLOR);
  387. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV);
  388. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV2);
  389. BIND_ENUM_CONSTANT(ARRAY_FORMAT_BONES);
  390. BIND_ENUM_CONSTANT(ARRAY_FORMAT_WEIGHTS);
  391. BIND_ENUM_CONSTANT(ARRAY_FORMAT_INDEX);
  392. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_NORMAL);
  393. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_TANGENT);
  394. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_COLOR);
  395. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_TEX_UV);
  396. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_TEX_UV2);
  397. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_INDEX);
  398. BIND_ENUM_CONSTANT(ARRAY_FLAG_USE_2D_VERTICES);
  399. BIND_ENUM_CONSTANT(ARRAY_COMPRESS_DEFAULT);
  400. BIND_ENUM_CONSTANT(ARRAY_VERTEX);
  401. BIND_ENUM_CONSTANT(ARRAY_NORMAL);
  402. BIND_ENUM_CONSTANT(ARRAY_TANGENT);
  403. BIND_ENUM_CONSTANT(ARRAY_COLOR);
  404. BIND_ENUM_CONSTANT(ARRAY_TEX_UV);
  405. BIND_ENUM_CONSTANT(ARRAY_TEX_UV2);
  406. BIND_ENUM_CONSTANT(ARRAY_BONES);
  407. BIND_ENUM_CONSTANT(ARRAY_WEIGHTS);
  408. BIND_ENUM_CONSTANT(ARRAY_INDEX);
  409. BIND_ENUM_CONSTANT(ARRAY_MAX);
  410. }
  411. void Mesh::clear_cache() const {
  412. triangle_mesh.unref();
  413. debug_lines.clear();
  414. }
  415. Vector<Ref<Shape3D>> Mesh::convex_decompose() const {
  416. ERR_FAIL_COND_V(!convex_composition_function, Vector<Ref<Shape3D>>());
  417. const Vector<Face3> faces = get_faces();
  418. Vector<Vector<Face3>> decomposed = convex_composition_function(faces);
  419. Vector<Ref<Shape3D>> ret;
  420. for (int i = 0; i < decomposed.size(); i++) {
  421. Set<Vector3> points;
  422. for (int j = 0; j < decomposed[i].size(); j++) {
  423. points.insert(decomposed[i][j].vertex[0]);
  424. points.insert(decomposed[i][j].vertex[1]);
  425. points.insert(decomposed[i][j].vertex[2]);
  426. }
  427. Vector<Vector3> convex_points;
  428. convex_points.resize(points.size());
  429. {
  430. Vector3 *w = convex_points.ptrw();
  431. int idx = 0;
  432. for (Set<Vector3>::Element *E = points.front(); E; E = E->next()) {
  433. w[idx++] = E->get();
  434. }
  435. }
  436. Ref<ConvexPolygonShape3D> shape;
  437. shape.instance();
  438. shape->set_points(convex_points);
  439. ret.push_back(shape);
  440. }
  441. return ret;
  442. }
  443. Mesh::Mesh() {
  444. }
  445. static Vector<uint8_t> _fix_array_compatibility(const Vector<uint8_t> &p_src, uint32_t p_format, uint32_t p_elements) {
  446. bool vertex_16bit = p_format & ((1 << (Mesh::ARRAY_VERTEX + Mesh::ARRAY_COMPRESS_BASE)));
  447. bool has_bones = (p_format & Mesh::ARRAY_FORMAT_BONES);
  448. bool bone_8 = has_bones && !(p_format & (Mesh::ARRAY_COMPRESS_INDEX << 2));
  449. bool weight_32 = has_bones && !(p_format & (Mesh::ARRAY_COMPRESS_TEX_UV2 << 2));
  450. print_line("convert vertex16: " + itos(vertex_16bit) + " convert bone 8 " + itos(bone_8) + " convert weight 32 " + itos(weight_32));
  451. if (!vertex_16bit && !bone_8 && !weight_32) {
  452. return p_src;
  453. }
  454. bool vertex_2d = (p_format & (Mesh::ARRAY_COMPRESS_INDEX << 1));
  455. uint32_t src_stride = p_src.size() / p_elements;
  456. uint32_t dst_stride = src_stride + (vertex_16bit ? 4 : 0) + (bone_8 ? 4 : 0) - (weight_32 ? 8 : 0);
  457. Vector<uint8_t> ret = p_src;
  458. ret.resize(dst_stride * p_elements);
  459. {
  460. uint8_t *w = ret.ptrw();
  461. const uint8_t *r = p_src.ptr();
  462. for (uint32_t i = 0; i < p_elements; i++) {
  463. uint32_t remaining = src_stride;
  464. const uint8_t *src = (const uint8_t *)(r + src_stride * i);
  465. uint8_t *dst = (uint8_t *)(w + dst_stride * i);
  466. if (!vertex_2d) { //3D
  467. if (vertex_16bit) {
  468. float *dstw = (float *)dst;
  469. const uint16_t *srcr = (const uint16_t *)src;
  470. dstw[0] = Math::half_to_float(srcr[0]);
  471. dstw[1] = Math::half_to_float(srcr[1]);
  472. dstw[2] = Math::half_to_float(srcr[2]);
  473. remaining -= 8;
  474. src += 8;
  475. } else {
  476. src += 12;
  477. remaining -= 12;
  478. }
  479. dst += 12;
  480. } else {
  481. if (vertex_16bit) {
  482. float *dstw = (float *)dst;
  483. const uint16_t *srcr = (const uint16_t *)src;
  484. dstw[0] = Math::half_to_float(srcr[0]);
  485. dstw[1] = Math::half_to_float(srcr[1]);
  486. remaining -= 4;
  487. src += 4;
  488. } else {
  489. src += 8;
  490. remaining -= 8;
  491. }
  492. dst += 8;
  493. }
  494. if (has_bones) {
  495. remaining -= bone_8 ? 4 : 8;
  496. remaining -= weight_32 ? 16 : 8;
  497. }
  498. for (uint32_t j = 0; j < remaining; j++) {
  499. dst[j] = src[j];
  500. }
  501. if (has_bones) {
  502. dst += remaining;
  503. src += remaining;
  504. if (bone_8) {
  505. const uint8_t *src_bones = (const uint8_t *)src;
  506. uint16_t *dst_bones = (uint16_t *)dst;
  507. dst_bones[0] = src_bones[0];
  508. dst_bones[1] = src_bones[1];
  509. dst_bones[2] = src_bones[2];
  510. dst_bones[3] = src_bones[3];
  511. src += 4;
  512. } else {
  513. for (uint32_t j = 0; j < 8; j++) {
  514. dst[j] = src[j];
  515. }
  516. src += 8;
  517. }
  518. dst += 8;
  519. if (weight_32) {
  520. const float *src_weights = (const float *)src;
  521. uint16_t *dst_weights = (uint16_t *)dst;
  522. dst_weights[0] = CLAMP(src_weights[0] * 65535, 0, 65535); //16bits unorm
  523. dst_weights[1] = CLAMP(src_weights[1] * 65535, 0, 65535);
  524. dst_weights[2] = CLAMP(src_weights[2] * 65535, 0, 65535);
  525. dst_weights[3] = CLAMP(src_weights[3] * 65535, 0, 65535);
  526. } else {
  527. for (uint32_t j = 0; j < 8; j++) {
  528. dst[j] = src[j];
  529. }
  530. }
  531. }
  532. }
  533. }
  534. return ret;
  535. }
  536. bool ArrayMesh::_set(const StringName &p_name, const Variant &p_value) {
  537. String sname = p_name;
  538. if (p_name == "blend_shape/names") {
  539. Vector<String> sk = p_value;
  540. int sz = sk.size();
  541. const String *r = sk.ptr();
  542. for (int i = 0; i < sz; i++)
  543. add_blend_shape(r[i]);
  544. return true;
  545. }
  546. if (p_name == "blend_shape/mode") {
  547. set_blend_shape_mode(BlendShapeMode(int(p_value)));
  548. return true;
  549. }
  550. if (sname.begins_with("surface_")) {
  551. int sl = sname.find("/");
  552. if (sl == -1)
  553. return false;
  554. int idx = sname.substr(8, sl - 8).to_int() - 1;
  555. String what = sname.get_slicec('/', 1);
  556. if (what == "material")
  557. surface_set_material(idx, p_value);
  558. else if (what == "name")
  559. surface_set_name(idx, p_value);
  560. return true;
  561. }
  562. #ifndef DISABLE_DEPRECATED
  563. // Kept for compatibility from 3.x to 4.0.
  564. if (!sname.begins_with("surfaces"))
  565. return false;
  566. WARN_DEPRECATED_MSG("Mesh uses old surface format, which is deprecated (and loads slower). Consider re-importing or re-saving the scene.");
  567. int idx = sname.get_slicec('/', 1).to_int();
  568. String what = sname.get_slicec('/', 2);
  569. if (idx == surfaces.size()) {
  570. //create
  571. Dictionary d = p_value;
  572. ERR_FAIL_COND_V(!d.has("primitive"), false);
  573. if (d.has("arrays")) {
  574. //oldest format (2.x)
  575. ERR_FAIL_COND_V(!d.has("morph_arrays"), false);
  576. add_surface_from_arrays(PrimitiveType(int(d["primitive"])), d["arrays"], d["morph_arrays"]);
  577. } else if (d.has("array_data")) {
  578. //print_line("array data (old style");
  579. //older format (3.x)
  580. Vector<uint8_t> array_data = d["array_data"];
  581. Vector<uint8_t> array_index_data;
  582. if (d.has("array_index_data"))
  583. array_index_data = d["array_index_data"];
  584. ERR_FAIL_COND_V(!d.has("format"), false);
  585. uint32_t format = d["format"];
  586. uint32_t primitive = d["primitive"];
  587. uint32_t primitive_remap[7] = {
  588. PRIMITIVE_POINTS,
  589. PRIMITIVE_LINES,
  590. PRIMITIVE_LINE_STRIP,
  591. PRIMITIVE_LINES,
  592. PRIMITIVE_TRIANGLES,
  593. PRIMITIVE_TRIANGLE_STRIP,
  594. PRIMITIVE_TRIANGLE_STRIP
  595. };
  596. primitive = primitive_remap[primitive]; //compatibility
  597. ERR_FAIL_COND_V(!d.has("vertex_count"), false);
  598. int vertex_count = d["vertex_count"];
  599. array_data = _fix_array_compatibility(array_data, format, vertex_count);
  600. int index_count = 0;
  601. if (d.has("index_count"))
  602. index_count = d["index_count"];
  603. Vector<Vector<uint8_t>> blend_shapes;
  604. if (d.has("blend_shape_data")) {
  605. Array blend_shape_data = d["blend_shape_data"];
  606. for (int i = 0; i < blend_shape_data.size(); i++) {
  607. Vector<uint8_t> shape = blend_shape_data[i];
  608. shape = _fix_array_compatibility(shape, format, vertex_count);
  609. blend_shapes.push_back(shape);
  610. }
  611. }
  612. //clear unused flags
  613. print_line("format pre: " + itos(format));
  614. format &= ~uint32_t((1 << (ARRAY_VERTEX + ARRAY_COMPRESS_BASE)) | (ARRAY_COMPRESS_INDEX << 2) | (ARRAY_COMPRESS_TEX_UV2 << 2));
  615. print_line("format post: " + itos(format));
  616. ERR_FAIL_COND_V(!d.has("aabb"), false);
  617. AABB aabb = d["aabb"];
  618. Vector<AABB> bone_aabb;
  619. if (d.has("skeleton_aabb")) {
  620. Array baabb = d["skeleton_aabb"];
  621. bone_aabb.resize(baabb.size());
  622. for (int i = 0; i < baabb.size(); i++) {
  623. bone_aabb.write[i] = baabb[i];
  624. }
  625. }
  626. add_surface(format, PrimitiveType(primitive), array_data, vertex_count, array_index_data, index_count, aabb, blend_shapes, bone_aabb);
  627. } else {
  628. ERR_FAIL_V(false);
  629. }
  630. if (d.has("material")) {
  631. surface_set_material(idx, d["material"]);
  632. }
  633. if (d.has("name")) {
  634. surface_set_name(idx, d["name"]);
  635. }
  636. return true;
  637. }
  638. #endif // DISABLE_DEPRECATED
  639. return false;
  640. }
  641. Array ArrayMesh::_get_surfaces() const {
  642. if (mesh.is_null()) {
  643. return Array();
  644. }
  645. Array ret;
  646. for (int i = 0; i < surfaces.size(); i++) {
  647. RenderingServer::SurfaceData surface = RS::get_singleton()->mesh_get_surface(mesh, i);
  648. Dictionary data;
  649. data["format"] = surface.format;
  650. data["primitive"] = surface.primitive;
  651. data["vertex_data"] = surface.vertex_data;
  652. data["vertex_count"] = surface.vertex_count;
  653. data["aabb"] = surface.aabb;
  654. if (surface.index_count) {
  655. data["index_data"] = surface.index_data;
  656. data["index_count"] = surface.index_count;
  657. };
  658. Array lods;
  659. for (int j = 0; j < surface.lods.size(); j++) {
  660. lods.push_back(surface.lods[j].edge_length);
  661. lods.push_back(surface.lods[j].index_data);
  662. }
  663. if (lods.size()) {
  664. data["lods"] = lods;
  665. }
  666. Array bone_aabbs;
  667. for (int j = 0; j < surface.bone_aabbs.size(); j++) {
  668. bone_aabbs.push_back(surface.bone_aabbs[j]);
  669. }
  670. if (bone_aabbs.size()) {
  671. data["bone_aabbs"] = bone_aabbs;
  672. }
  673. Array blend_shapes;
  674. for (int j = 0; j < surface.blend_shapes.size(); j++) {
  675. blend_shapes.push_back(surface.blend_shapes[j]);
  676. }
  677. if (surfaces[i].material.is_valid()) {
  678. data["material"] = surfaces[i].material;
  679. }
  680. if (surfaces[i].name != String()) {
  681. data["name"] = surfaces[i].name;
  682. }
  683. if (surfaces[i].is_2d) {
  684. data["2d"] = true;
  685. }
  686. ret.push_back(data);
  687. }
  688. print_line("Saving surfaces: " + itos(ret.size()));
  689. return ret;
  690. }
  691. void ArrayMesh::_create_if_empty() const {
  692. if (!mesh.is_valid()) {
  693. mesh = RS::get_singleton()->mesh_create();
  694. RS::get_singleton()->mesh_set_blend_shape_mode(mesh, (RS::BlendShapeMode)blend_shape_mode);
  695. }
  696. }
  697. void ArrayMesh::_set_surfaces(const Array &p_surfaces) {
  698. Vector<RS::SurfaceData> surface_data;
  699. Vector<Ref<Material>> surface_materials;
  700. Vector<String> surface_names;
  701. Vector<bool> surface_2d;
  702. for (int i = 0; i < p_surfaces.size(); i++) {
  703. RS::SurfaceData surface;
  704. Dictionary d = p_surfaces[i];
  705. ERR_FAIL_COND(!d.has("format"));
  706. ERR_FAIL_COND(!d.has("primitive"));
  707. ERR_FAIL_COND(!d.has("vertex_data"));
  708. ERR_FAIL_COND(!d.has("vertex_count"));
  709. ERR_FAIL_COND(!d.has("aabb"));
  710. surface.format = d["format"];
  711. surface.primitive = RS::PrimitiveType(int(d["primitive"]));
  712. surface.vertex_data = d["vertex_data"];
  713. surface.vertex_count = d["vertex_count"];
  714. surface.aabb = d["aabb"];
  715. if (d.has("index_data")) {
  716. ERR_FAIL_COND(!d.has("index_count"));
  717. surface.index_data = d["index_data"];
  718. surface.index_count = d["index_count"];
  719. }
  720. if (d.has("lods")) {
  721. Array lods = d["lods"];
  722. ERR_FAIL_COND(lods.size() & 1); //must be even
  723. for (int j = 0; j < lods.size(); j += 2) {
  724. RS::SurfaceData::LOD lod;
  725. lod.edge_length = lods[j + 0];
  726. lod.index_data = lods[j + 1];
  727. surface.lods.push_back(lod);
  728. }
  729. }
  730. if (d.has("bone_aabbs")) {
  731. Array bone_aabbs = d["bone_aabbs"];
  732. for (int j = 0; j < bone_aabbs.size(); j++) {
  733. surface.bone_aabbs.push_back(bone_aabbs[j]);
  734. }
  735. }
  736. if (d.has("blend_shapes")) {
  737. Array blend_shapes;
  738. for (int j = 0; j < blend_shapes.size(); j++) {
  739. surface.blend_shapes.push_back(blend_shapes[j]);
  740. }
  741. }
  742. Ref<Material> material;
  743. if (d.has("material")) {
  744. material = d["material"];
  745. if (material.is_valid()) {
  746. surface.material = material->get_rid();
  747. }
  748. }
  749. String name;
  750. if (d.has("name")) {
  751. name = d["name"];
  752. }
  753. bool _2d = false;
  754. if (d.has("2d")) {
  755. _2d = d["2d"];
  756. }
  757. /*
  758. print_line("format: " + itos(surface.format));
  759. print_line("aabb: " + surface.aabb);
  760. print_line("array size: " + itos(surface.vertex_data.size()));
  761. print_line("vertex count: " + itos(surface.vertex_count));
  762. print_line("index size: " + itos(surface.index_data.size()));
  763. print_line("index count: " + itos(surface.index_count));
  764. print_line("primitive: " + itos(surface.primitive));
  765. */
  766. surface_data.push_back(surface);
  767. surface_materials.push_back(material);
  768. surface_names.push_back(name);
  769. surface_2d.push_back(_2d);
  770. }
  771. if (mesh.is_valid()) {
  772. //if mesh exists, it needs to be updated
  773. RS::get_singleton()->mesh_clear(mesh);
  774. for (int i = 0; i < surface_data.size(); i++) {
  775. RS::get_singleton()->mesh_add_surface(mesh, surface_data[i]);
  776. }
  777. } else {
  778. // if mesh does not exist (first time this is loaded, most likely),
  779. // we can create it with a single call, which is a lot more efficient and thread friendly
  780. mesh = RS::get_singleton()->mesh_create_from_surfaces(surface_data);
  781. RS::get_singleton()->mesh_set_blend_shape_mode(mesh, (RS::BlendShapeMode)blend_shape_mode);
  782. }
  783. surfaces.clear();
  784. aabb = AABB();
  785. for (int i = 0; i < surface_data.size(); i++) {
  786. Surface s;
  787. s.aabb = surface_data[i].aabb;
  788. if (i == 0) {
  789. aabb = s.aabb;
  790. blend_shapes.resize(surface_data[i].blend_shapes.size());
  791. } else {
  792. aabb.merge_with(s.aabb);
  793. }
  794. s.material = surface_materials[i];
  795. s.is_2d = surface_2d[i];
  796. s.name = surface_names[i];
  797. s.format = surface_data[i].format;
  798. s.primitive = PrimitiveType(surface_data[i].primitive);
  799. s.array_length = surface_data[i].vertex_count;
  800. s.index_array_length = surface_data[i].index_count;
  801. surfaces.push_back(s);
  802. }
  803. }
  804. bool ArrayMesh::_get(const StringName &p_name, Variant &r_ret) const {
  805. if (_is_generated())
  806. return false;
  807. String sname = p_name;
  808. if (p_name == "blend_shape/names") {
  809. Vector<String> sk;
  810. for (int i = 0; i < blend_shapes.size(); i++)
  811. sk.push_back(blend_shapes[i]);
  812. r_ret = sk;
  813. return true;
  814. } else if (p_name == "blend_shape/mode") {
  815. r_ret = get_blend_shape_mode();
  816. return true;
  817. } else if (sname.begins_with("surface_")) {
  818. int sl = sname.find("/");
  819. if (sl == -1)
  820. return false;
  821. int idx = sname.substr(8, sl - 8).to_int() - 1;
  822. String what = sname.get_slicec('/', 1);
  823. if (what == "material")
  824. r_ret = surface_get_material(idx);
  825. else if (what == "name")
  826. r_ret = surface_get_name(idx);
  827. return true;
  828. }
  829. return true;
  830. }
  831. void ArrayMesh::_get_property_list(List<PropertyInfo> *p_list) const {
  832. if (_is_generated())
  833. return;
  834. if (blend_shapes.size()) {
  835. p_list->push_back(PropertyInfo(Variant::PACKED_STRING_ARRAY, "blend_shape/names", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
  836. p_list->push_back(PropertyInfo(Variant::INT, "blend_shape/mode", PROPERTY_HINT_ENUM, "Normalized,Relative"));
  837. }
  838. for (int i = 0; i < surfaces.size(); i++) {
  839. p_list->push_back(PropertyInfo(Variant::STRING, "surface_" + itos(i + 1) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR));
  840. if (surfaces[i].is_2d) {
  841. p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i + 1) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,CanvasItemMaterial", PROPERTY_USAGE_EDITOR));
  842. } else {
  843. p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i + 1) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "ShaderMaterial,StandardMaterial3D", PROPERTY_USAGE_EDITOR));
  844. }
  845. }
  846. }
  847. void ArrayMesh::_recompute_aabb() {
  848. // regenerate AABB
  849. aabb = AABB();
  850. for (int i = 0; i < surfaces.size(); i++) {
  851. if (i == 0)
  852. aabb = surfaces[i].aabb;
  853. else
  854. aabb.merge_with(surfaces[i].aabb);
  855. }
  856. }
  857. #ifndef _MSC_VER
  858. #warning need to add binding to add_surface using future MeshSurfaceData object
  859. #endif
  860. void ArrayMesh::add_surface(uint32_t p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<Vector<uint8_t>> &p_blend_shapes, const Vector<AABB> &p_bone_aabb, const Vector<RS::SurfaceData::LOD> &p_lods) {
  861. _create_if_empty();
  862. Surface s;
  863. s.aabb = p_aabb;
  864. s.is_2d = p_format & ARRAY_FLAG_USE_2D_VERTICES;
  865. s.primitive = p_primitive;
  866. s.array_length = p_vertex_count;
  867. s.index_array_length = p_index_count;
  868. s.format = p_format;
  869. surfaces.push_back(s);
  870. _recompute_aabb();
  871. RS::SurfaceData sd;
  872. sd.format = p_format;
  873. sd.primitive = RS::PrimitiveType(p_primitive);
  874. sd.aabb = p_aabb;
  875. sd.vertex_count = p_vertex_count;
  876. sd.vertex_data = p_array;
  877. sd.index_count = p_index_count;
  878. sd.index_data = p_index_array;
  879. sd.blend_shapes = p_blend_shapes;
  880. sd.bone_aabbs = p_bone_aabb;
  881. sd.lods = p_lods;
  882. RenderingServer::get_singleton()->mesh_add_surface(mesh, sd);
  883. clear_cache();
  884. _change_notify();
  885. emit_changed();
  886. }
  887. void ArrayMesh::add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, const Dictionary &p_lods, uint32_t p_flags) {
  888. ERR_FAIL_COND(p_arrays.size() != ARRAY_MAX);
  889. RS::SurfaceData surface;
  890. Error err = RS::get_singleton()->mesh_create_surface_data_from_arrays(&surface, (RenderingServer::PrimitiveType)p_primitive, p_arrays, p_blend_shapes, p_lods, p_flags);
  891. ERR_FAIL_COND(err != OK);
  892. /* print_line("format: " + itos(surface.format));
  893. print_line("aabb: " + surface.aabb);
  894. print_line("array size: " + itos(surface.vertex_data.size()));
  895. print_line("vertex count: " + itos(surface.vertex_count));
  896. print_line("index size: " + itos(surface.index_data.size()));
  897. print_line("index count: " + itos(surface.index_count));
  898. print_line("primitive: " + itos(surface.primitive));
  899. */
  900. add_surface(surface.format, PrimitiveType(surface.primitive), surface.vertex_data, surface.vertex_count, surface.index_data, surface.index_count, surface.aabb, surface.blend_shapes, surface.bone_aabbs, surface.lods);
  901. }
  902. Array ArrayMesh::surface_get_arrays(int p_surface) const {
  903. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  904. return RenderingServer::get_singleton()->mesh_surface_get_arrays(mesh, p_surface);
  905. }
  906. Array ArrayMesh::surface_get_blend_shape_arrays(int p_surface) const {
  907. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  908. return RenderingServer::get_singleton()->mesh_surface_get_blend_shape_arrays(mesh, p_surface);
  909. }
  910. Dictionary ArrayMesh::surface_get_lods(int p_surface) const {
  911. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Dictionary());
  912. return RenderingServer::get_singleton()->mesh_surface_get_lods(mesh, p_surface);
  913. }
  914. int ArrayMesh::get_surface_count() const {
  915. return surfaces.size();
  916. }
  917. void ArrayMesh::add_blend_shape(const StringName &p_name) {
  918. ERR_FAIL_COND_MSG(surfaces.size(), "Can't add a shape key count if surfaces are already created.");
  919. StringName name = p_name;
  920. if (blend_shapes.find(name) != -1) {
  921. int count = 2;
  922. do {
  923. name = String(p_name) + " " + itos(count);
  924. count++;
  925. } while (blend_shapes.find(name) != -1);
  926. }
  927. blend_shapes.push_back(name);
  928. //RS::get_singleton()->mesh_set_blend_shape_count(mesh, blend_shapes.size());
  929. }
  930. int ArrayMesh::get_blend_shape_count() const {
  931. return blend_shapes.size();
  932. }
  933. StringName ArrayMesh::get_blend_shape_name(int p_index) const {
  934. ERR_FAIL_INDEX_V(p_index, blend_shapes.size(), StringName());
  935. return blend_shapes[p_index];
  936. }
  937. void ArrayMesh::clear_blend_shapes() {
  938. ERR_FAIL_COND_MSG(surfaces.size(), "Can't set shape key count if surfaces are already created.");
  939. blend_shapes.clear();
  940. }
  941. void ArrayMesh::set_blend_shape_mode(BlendShapeMode p_mode) {
  942. blend_shape_mode = p_mode;
  943. if (mesh.is_valid()) {
  944. RS::get_singleton()->mesh_set_blend_shape_mode(mesh, (RS::BlendShapeMode)p_mode);
  945. }
  946. }
  947. ArrayMesh::BlendShapeMode ArrayMesh::get_blend_shape_mode() const {
  948. return blend_shape_mode;
  949. }
  950. int ArrayMesh::surface_get_array_len(int p_idx) const {
  951. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), -1);
  952. return surfaces[p_idx].array_length;
  953. }
  954. int ArrayMesh::surface_get_array_index_len(int p_idx) const {
  955. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), -1);
  956. return surfaces[p_idx].index_array_length;
  957. }
  958. uint32_t ArrayMesh::surface_get_format(int p_idx) const {
  959. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), 0);
  960. return surfaces[p_idx].format;
  961. }
  962. ArrayMesh::PrimitiveType ArrayMesh::surface_get_primitive_type(int p_idx) const {
  963. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), PRIMITIVE_LINES);
  964. return surfaces[p_idx].primitive;
  965. }
  966. void ArrayMesh::surface_set_material(int p_idx, const Ref<Material> &p_material) {
  967. ERR_FAIL_INDEX(p_idx, surfaces.size());
  968. if (surfaces[p_idx].material == p_material)
  969. return;
  970. surfaces.write[p_idx].material = p_material;
  971. RenderingServer::get_singleton()->mesh_surface_set_material(mesh, p_idx, p_material.is_null() ? RID() : p_material->get_rid());
  972. _change_notify("material");
  973. emit_changed();
  974. }
  975. int ArrayMesh::surface_find_by_name(const String &p_name) const {
  976. for (int i = 0; i < surfaces.size(); i++) {
  977. if (surfaces[i].name == p_name) {
  978. return i;
  979. }
  980. }
  981. return -1;
  982. }
  983. void ArrayMesh::surface_set_name(int p_idx, const String &p_name) {
  984. ERR_FAIL_INDEX(p_idx, surfaces.size());
  985. surfaces.write[p_idx].name = p_name;
  986. emit_changed();
  987. }
  988. String ArrayMesh::surface_get_name(int p_idx) const {
  989. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), String());
  990. return surfaces[p_idx].name;
  991. }
  992. void ArrayMesh::surface_update_region(int p_surface, int p_offset, const Vector<uint8_t> &p_data) {
  993. ERR_FAIL_INDEX(p_surface, surfaces.size());
  994. RS::get_singleton()->mesh_surface_update_region(mesh, p_surface, p_offset, p_data);
  995. emit_changed();
  996. }
  997. void ArrayMesh::surface_set_custom_aabb(int p_idx, const AABB &p_aabb) {
  998. ERR_FAIL_INDEX(p_idx, surfaces.size());
  999. surfaces.write[p_idx].aabb = p_aabb;
  1000. // set custom aabb too?
  1001. emit_changed();
  1002. }
  1003. Ref<Material> ArrayMesh::surface_get_material(int p_idx) const {
  1004. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), Ref<Material>());
  1005. return surfaces[p_idx].material;
  1006. }
  1007. RID ArrayMesh::get_rid() const {
  1008. _create_if_empty();
  1009. return mesh;
  1010. }
  1011. AABB ArrayMesh::get_aabb() const {
  1012. return aabb;
  1013. }
  1014. void ArrayMesh::clear_surfaces() {
  1015. if (!mesh.is_valid()) {
  1016. return;
  1017. }
  1018. RS::get_singleton()->mesh_clear(mesh);
  1019. surfaces.clear();
  1020. aabb = AABB();
  1021. }
  1022. void ArrayMesh::set_custom_aabb(const AABB &p_custom) {
  1023. _create_if_empty();
  1024. custom_aabb = p_custom;
  1025. RS::get_singleton()->mesh_set_custom_aabb(mesh, custom_aabb);
  1026. emit_changed();
  1027. }
  1028. AABB ArrayMesh::get_custom_aabb() const {
  1029. return custom_aabb;
  1030. }
  1031. void ArrayMesh::regen_normalmaps() {
  1032. if (surfaces.size() == 0) {
  1033. return;
  1034. }
  1035. Vector<Ref<SurfaceTool>> surfs;
  1036. for (int i = 0; i < get_surface_count(); i++) {
  1037. Ref<SurfaceTool> st = memnew(SurfaceTool);
  1038. st->create_from(Ref<ArrayMesh>(this), i);
  1039. surfs.push_back(st);
  1040. }
  1041. clear_surfaces();
  1042. for (int i = 0; i < surfs.size(); i++) {
  1043. surfs.write[i]->generate_tangents();
  1044. surfs.write[i]->commit(Ref<ArrayMesh>(this));
  1045. }
  1046. }
  1047. //dirty hack
  1048. bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, int p_index_count, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y, int *&r_cache_data, unsigned int &r_cache_size, bool &r_used_cache);
  1049. struct ArrayMeshLightmapSurface {
  1050. Ref<Material> material;
  1051. Vector<SurfaceTool::Vertex> vertices;
  1052. Mesh::PrimitiveType primitive;
  1053. uint32_t format;
  1054. };
  1055. Error ArrayMesh::lightmap_unwrap(const Transform &p_base_transform, float p_texel_size) {
  1056. int *cache_data = nullptr;
  1057. unsigned int cache_size = 0;
  1058. bool use_cache = false; // Don't use cache
  1059. return lightmap_unwrap_cached(cache_data, cache_size, use_cache, p_base_transform, p_texel_size);
  1060. }
  1061. Error ArrayMesh::lightmap_unwrap_cached(int *&r_cache_data, unsigned int &r_cache_size, bool &r_used_cache, const Transform &p_base_transform, float p_texel_size) {
  1062. ERR_FAIL_COND_V(!array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
  1063. ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
  1064. Vector<float> vertices;
  1065. Vector<float> normals;
  1066. Vector<int> indices;
  1067. Vector<float> uv;
  1068. Vector<Pair<int, int>> uv_indices;
  1069. Vector<ArrayMeshLightmapSurface> lightmap_surfaces;
  1070. // Keep only the scale
  1071. Transform transform = p_base_transform;
  1072. transform.origin = Vector3();
  1073. transform.looking_at(Vector3(1, 0, 0), Vector3(0, 1, 0));
  1074. Basis normal_basis = transform.basis.inverse().transposed();
  1075. for (int i = 0; i < get_surface_count(); i++) {
  1076. ArrayMeshLightmapSurface s;
  1077. s.primitive = surface_get_primitive_type(i);
  1078. ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");
  1079. s.format = surface_get_format(i);
  1080. ERR_FAIL_COND_V_MSG(!(s.format & ARRAY_FORMAT_NORMAL), ERR_UNAVAILABLE, "Normals are required for lightmap unwrap.");
  1081. Array arrays = surface_get_arrays(i);
  1082. s.material = surface_get_material(i);
  1083. s.vertices = SurfaceTool::create_vertex_array_from_triangle_arrays(arrays);
  1084. Vector<Vector3> rvertices = arrays[Mesh::ARRAY_VERTEX];
  1085. int vc = rvertices.size();
  1086. const Vector3 *r = rvertices.ptr();
  1087. Vector<Vector3> rnormals = arrays[Mesh::ARRAY_NORMAL];
  1088. const Vector3 *rn = rnormals.ptr();
  1089. int vertex_ofs = vertices.size() / 3;
  1090. vertices.resize((vertex_ofs + vc) * 3);
  1091. normals.resize((vertex_ofs + vc) * 3);
  1092. uv_indices.resize(vertex_ofs + vc);
  1093. for (int j = 0; j < vc; j++) {
  1094. Vector3 v = transform.xform(r[j]);
  1095. Vector3 n = normal_basis.xform(rn[j]).normalized();
  1096. vertices.write[(j + vertex_ofs) * 3 + 0] = v.x;
  1097. vertices.write[(j + vertex_ofs) * 3 + 1] = v.y;
  1098. vertices.write[(j + vertex_ofs) * 3 + 2] = v.z;
  1099. normals.write[(j + vertex_ofs) * 3 + 0] = n.x;
  1100. normals.write[(j + vertex_ofs) * 3 + 1] = n.y;
  1101. normals.write[(j + vertex_ofs) * 3 + 2] = n.z;
  1102. uv_indices.write[j + vertex_ofs] = Pair<int, int>(i, j);
  1103. }
  1104. Vector<int> rindices = arrays[Mesh::ARRAY_INDEX];
  1105. int ic = rindices.size();
  1106. if (ic == 0) {
  1107. for (int j = 0; j < vc / 3; j++) {
  1108. if (Face3(r[j * 3 + 0], r[j * 3 + 1], r[j * 3 + 2]).is_degenerate())
  1109. continue;
  1110. indices.push_back(vertex_ofs + j * 3 + 0);
  1111. indices.push_back(vertex_ofs + j * 3 + 1);
  1112. indices.push_back(vertex_ofs + j * 3 + 2);
  1113. }
  1114. } else {
  1115. const int *ri = rindices.ptr();
  1116. for (int j = 0; j < ic / 3; j++) {
  1117. if (Face3(r[ri[j * 3 + 0]], r[ri[j * 3 + 1]], r[ri[j * 3 + 2]]).is_degenerate())
  1118. continue;
  1119. indices.push_back(vertex_ofs + ri[j * 3 + 0]);
  1120. indices.push_back(vertex_ofs + ri[j * 3 + 1]);
  1121. indices.push_back(vertex_ofs + ri[j * 3 + 2]);
  1122. }
  1123. }
  1124. lightmap_surfaces.push_back(s);
  1125. }
  1126. //unwrap
  1127. float *gen_uvs;
  1128. int *gen_vertices;
  1129. int *gen_indices;
  1130. int gen_vertex_count;
  1131. int gen_index_count;
  1132. int size_x;
  1133. int size_y;
  1134. bool ok = array_mesh_lightmap_unwrap_callback(p_texel_size, vertices.ptr(), normals.ptr(), vertices.size() / 3, indices.ptr(), indices.size(), &gen_uvs, &gen_vertices, &gen_vertex_count, &gen_indices, &gen_index_count, &size_x, &size_y, r_cache_data, r_cache_size, r_used_cache);
  1135. if (!ok) {
  1136. return ERR_CANT_CREATE;
  1137. }
  1138. //remove surfaces
  1139. clear_surfaces();
  1140. //create surfacetools for each surface..
  1141. Vector<Ref<SurfaceTool>> surfaces_tools;
  1142. for (int i = 0; i < lightmap_surfaces.size(); i++) {
  1143. Ref<SurfaceTool> st;
  1144. st.instance();
  1145. st->begin(Mesh::PRIMITIVE_TRIANGLES);
  1146. st->set_material(lightmap_surfaces[i].material);
  1147. surfaces_tools.push_back(st); //stay there
  1148. }
  1149. print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
  1150. //go through all indices
  1151. for (int i = 0; i < gen_index_count; i += 3) {
  1152. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], uv_indices.size(), ERR_BUG);
  1153. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], uv_indices.size(), ERR_BUG);
  1154. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], uv_indices.size(), ERR_BUG);
  1155. ERR_FAIL_COND_V(uv_indices[gen_vertices[gen_indices[i + 0]]].first != uv_indices[gen_vertices[gen_indices[i + 1]]].first || uv_indices[gen_vertices[gen_indices[i + 0]]].first != uv_indices[gen_vertices[gen_indices[i + 2]]].first, ERR_BUG);
  1156. int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;
  1157. for (int j = 0; j < 3; j++) {
  1158. SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];
  1159. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_COLOR) {
  1160. surfaces_tools.write[surface]->add_color(v.color);
  1161. }
  1162. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_TEX_UV) {
  1163. surfaces_tools.write[surface]->add_uv(v.uv);
  1164. }
  1165. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_NORMAL) {
  1166. surfaces_tools.write[surface]->add_normal(v.normal);
  1167. }
  1168. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_TANGENT) {
  1169. Plane t;
  1170. t.normal = v.tangent;
  1171. t.distance = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;
  1172. surfaces_tools.write[surface]->add_tangent(t);
  1173. }
  1174. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_BONES) {
  1175. surfaces_tools.write[surface]->add_bones(v.bones);
  1176. }
  1177. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_WEIGHTS) {
  1178. surfaces_tools.write[surface]->add_weights(v.weights);
  1179. }
  1180. Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
  1181. surfaces_tools.write[surface]->add_uv2(uv2);
  1182. surfaces_tools.write[surface]->add_vertex(v.vertex);
  1183. }
  1184. }
  1185. //generate surfaces
  1186. for (int i = 0; i < surfaces_tools.size(); i++) {
  1187. surfaces_tools.write[i]->index();
  1188. surfaces_tools.write[i]->commit(Ref<ArrayMesh>((ArrayMesh *)this), lightmap_surfaces[i].format);
  1189. }
  1190. set_lightmap_size_hint(Size2(size_x, size_y));
  1191. if (!r_used_cache) {
  1192. //free stuff
  1193. ::free(gen_vertices);
  1194. ::free(gen_indices);
  1195. ::free(gen_uvs);
  1196. }
  1197. return OK;
  1198. }
  1199. void ArrayMesh::_bind_methods() {
  1200. ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ArrayMesh::add_blend_shape);
  1201. ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ArrayMesh::get_blend_shape_count);
  1202. ClassDB::bind_method(D_METHOD("get_blend_shape_name", "index"), &ArrayMesh::get_blend_shape_name);
  1203. ClassDB::bind_method(D_METHOD("clear_blend_shapes"), &ArrayMesh::clear_blend_shapes);
  1204. ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ArrayMesh::set_blend_shape_mode);
  1205. ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ArrayMesh::get_blend_shape_mode);
  1206. ClassDB::bind_method(D_METHOD("add_surface_from_arrays", "primitive", "arrays", "blend_shapes", "lods", "compress_flags"), &ArrayMesh::add_surface_from_arrays, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(ARRAY_COMPRESS_DEFAULT));
  1207. ClassDB::bind_method(D_METHOD("clear_surfaces"), &ArrayMesh::clear_surfaces);
  1208. ClassDB::bind_method(D_METHOD("surface_update_region", "surf_idx", "offset", "data"), &ArrayMesh::surface_update_region);
  1209. ClassDB::bind_method(D_METHOD("surface_get_array_len", "surf_idx"), &ArrayMesh::surface_get_array_len);
  1210. ClassDB::bind_method(D_METHOD("surface_get_array_index_len", "surf_idx"), &ArrayMesh::surface_get_array_index_len);
  1211. ClassDB::bind_method(D_METHOD("surface_get_format", "surf_idx"), &ArrayMesh::surface_get_format);
  1212. ClassDB::bind_method(D_METHOD("surface_get_primitive_type", "surf_idx"), &ArrayMesh::surface_get_primitive_type);
  1213. ClassDB::bind_method(D_METHOD("surface_find_by_name", "name"), &ArrayMesh::surface_find_by_name);
  1214. ClassDB::bind_method(D_METHOD("surface_set_name", "surf_idx", "name"), &ArrayMesh::surface_set_name);
  1215. ClassDB::bind_method(D_METHOD("surface_get_name", "surf_idx"), &ArrayMesh::surface_get_name);
  1216. ClassDB::bind_method(D_METHOD("create_trimesh_shape"), &ArrayMesh::create_trimesh_shape);
  1217. ClassDB::bind_method(D_METHOD("create_convex_shape"), &ArrayMesh::create_convex_shape);
  1218. ClassDB::bind_method(D_METHOD("create_outline", "margin"), &ArrayMesh::create_outline);
  1219. ClassDB::bind_method(D_METHOD("regen_normalmaps"), &ArrayMesh::regen_normalmaps);
  1220. ClassDB::set_method_flags(get_class_static(), _scs_create("regen_normalmaps"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
  1221. ClassDB::bind_method(D_METHOD("lightmap_unwrap", "transform", "texel_size"), &ArrayMesh::lightmap_unwrap);
  1222. ClassDB::set_method_flags(get_class_static(), _scs_create("lightmap_unwrap"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
  1223. ClassDB::bind_method(D_METHOD("get_faces"), &ArrayMesh::get_faces);
  1224. ClassDB::bind_method(D_METHOD("generate_triangle_mesh"), &ArrayMesh::generate_triangle_mesh);
  1225. ClassDB::bind_method(D_METHOD("set_custom_aabb", "aabb"), &ArrayMesh::set_custom_aabb);
  1226. ClassDB::bind_method(D_METHOD("get_custom_aabb"), &ArrayMesh::get_custom_aabb);
  1227. ClassDB::bind_method(D_METHOD("_set_surfaces", "surfaces"), &ArrayMesh::_set_surfaces);
  1228. ClassDB::bind_method(D_METHOD("_get_surfaces"), &ArrayMesh::_get_surfaces);
  1229. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "_surfaces", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_surfaces", "_get_surfaces");
  1230. ADD_PROPERTY(PropertyInfo(Variant::INT, "blend_shape_mode", PROPERTY_HINT_ENUM, "Normalized,Relative"), "set_blend_shape_mode", "get_blend_shape_mode");
  1231. ADD_PROPERTY(PropertyInfo(Variant::AABB, "custom_aabb", PROPERTY_HINT_NONE, ""), "set_custom_aabb", "get_custom_aabb");
  1232. BIND_CONSTANT(NO_INDEX_ARRAY);
  1233. BIND_CONSTANT(ARRAY_WEIGHTS_SIZE);
  1234. BIND_ENUM_CONSTANT(ARRAY_VERTEX);
  1235. BIND_ENUM_CONSTANT(ARRAY_NORMAL);
  1236. BIND_ENUM_CONSTANT(ARRAY_TANGENT);
  1237. BIND_ENUM_CONSTANT(ARRAY_COLOR);
  1238. BIND_ENUM_CONSTANT(ARRAY_TEX_UV);
  1239. BIND_ENUM_CONSTANT(ARRAY_TEX_UV2);
  1240. BIND_ENUM_CONSTANT(ARRAY_BONES);
  1241. BIND_ENUM_CONSTANT(ARRAY_WEIGHTS);
  1242. BIND_ENUM_CONSTANT(ARRAY_INDEX);
  1243. BIND_ENUM_CONSTANT(ARRAY_MAX);
  1244. BIND_ENUM_CONSTANT(ARRAY_FORMAT_VERTEX);
  1245. BIND_ENUM_CONSTANT(ARRAY_FORMAT_NORMAL);
  1246. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TANGENT);
  1247. BIND_ENUM_CONSTANT(ARRAY_FORMAT_COLOR);
  1248. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV);
  1249. BIND_ENUM_CONSTANT(ARRAY_FORMAT_TEX_UV2);
  1250. BIND_ENUM_CONSTANT(ARRAY_FORMAT_BONES);
  1251. BIND_ENUM_CONSTANT(ARRAY_FORMAT_WEIGHTS);
  1252. BIND_ENUM_CONSTANT(ARRAY_FORMAT_INDEX);
  1253. }
  1254. void ArrayMesh::reload_from_file() {
  1255. RenderingServer::get_singleton()->mesh_clear(mesh);
  1256. surfaces.clear();
  1257. clear_blend_shapes();
  1258. clear_cache();
  1259. Resource::reload_from_file();
  1260. _change_notify();
  1261. }
  1262. ArrayMesh::ArrayMesh() {
  1263. //mesh is now created on demand
  1264. //mesh = RenderingServer::get_singleton()->mesh_create();
  1265. blend_shape_mode = BLEND_SHAPE_MODE_RELATIVE;
  1266. }
  1267. ArrayMesh::~ArrayMesh() {
  1268. if (mesh.is_valid()) {
  1269. RenderingServer::get_singleton()->free(mesh);
  1270. }
  1271. }