2
0

mesh.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142
  1. /**************************************************************************/
  2. /* mesh.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "mesh.h"
  31. #include "core/math/convex_hull.h"
  32. #include "core/templates/pair.h"
  33. #include "scene/resources/surface_tool.h"
  34. #include "scene/resources/concave_polygon_shape_3d.h"
  35. #include "scene/resources/convex_polygon_shape_3d.h"
  36. Mesh::ConvexDecompositionFunc Mesh::convex_decomposition_function = nullptr;
  37. int Mesh::get_surface_count() const {
  38. int ret = 0;
  39. GDVIRTUAL_REQUIRED_CALL(_get_surface_count, ret);
  40. return ret;
  41. }
  42. int Mesh::surface_get_array_len(int p_idx) const {
  43. int ret = 0;
  44. GDVIRTUAL_REQUIRED_CALL(_surface_get_array_len, p_idx, ret);
  45. return ret;
  46. }
  47. int Mesh::surface_get_array_index_len(int p_idx) const {
  48. int ret = 0;
  49. GDVIRTUAL_REQUIRED_CALL(_surface_get_array_index_len, p_idx, ret);
  50. return ret;
  51. }
  52. Array Mesh::surface_get_arrays(int p_surface) const {
  53. Array ret;
  54. GDVIRTUAL_REQUIRED_CALL(_surface_get_arrays, p_surface, ret);
  55. return ret;
  56. }
  57. TypedArray<Array> Mesh::surface_get_blend_shape_arrays(int p_surface) const {
  58. TypedArray<Array> ret;
  59. GDVIRTUAL_REQUIRED_CALL(_surface_get_blend_shape_arrays, p_surface, ret);
  60. return ret;
  61. }
  62. Dictionary Mesh::surface_get_lods(int p_surface) const {
  63. Dictionary ret;
  64. GDVIRTUAL_REQUIRED_CALL(_surface_get_lods, p_surface, ret);
  65. return ret;
  66. }
  67. BitField<Mesh::ArrayFormat> Mesh::surface_get_format(int p_idx) const {
  68. uint32_t ret = 0;
  69. GDVIRTUAL_REQUIRED_CALL(_surface_get_format, p_idx, ret);
  70. return ret;
  71. }
  72. Mesh::PrimitiveType Mesh::surface_get_primitive_type(int p_idx) const {
  73. uint32_t ret = PRIMITIVE_MAX;
  74. GDVIRTUAL_REQUIRED_CALL(_surface_get_primitive_type, p_idx, ret);
  75. return (Mesh::PrimitiveType)ret;
  76. }
  77. void Mesh::surface_set_material(int p_idx, const Ref<Material> &p_material) {
  78. GDVIRTUAL_REQUIRED_CALL(_surface_set_material, p_idx, p_material);
  79. }
  80. Ref<Material> Mesh::surface_get_material(int p_idx) const {
  81. Ref<Material> ret;
  82. GDVIRTUAL_REQUIRED_CALL(_surface_get_material, p_idx, ret);
  83. return ret;
  84. }
  85. int Mesh::get_blend_shape_count() const {
  86. int ret = 0;
  87. GDVIRTUAL_REQUIRED_CALL(_get_blend_shape_count, ret);
  88. return ret;
  89. }
  90. StringName Mesh::get_blend_shape_name(int p_index) const {
  91. StringName ret;
  92. GDVIRTUAL_REQUIRED_CALL(_get_blend_shape_name, p_index, ret);
  93. return ret;
  94. }
  95. void Mesh::set_blend_shape_name(int p_index, const StringName &p_name) {
  96. GDVIRTUAL_REQUIRED_CALL(_set_blend_shape_name, p_index, p_name);
  97. }
  98. AABB Mesh::get_aabb() const {
  99. AABB ret;
  100. GDVIRTUAL_REQUIRED_CALL(_get_aabb, ret);
  101. return ret;
  102. }
  103. Ref<TriangleMesh> Mesh::generate_triangle_mesh() const {
  104. if (triangle_mesh.is_valid()) {
  105. return triangle_mesh;
  106. }
  107. int faces_size = 0;
  108. for (int i = 0; i < get_surface_count(); i++) {
  109. switch (surface_get_primitive_type(i)) {
  110. case PRIMITIVE_TRIANGLES: {
  111. int len = (surface_get_format(i) & ARRAY_FORMAT_INDEX) ? surface_get_array_index_len(i) : surface_get_array_len(i);
  112. // Don't error if zero, it's valid (we'll just skip it later).
  113. ERR_CONTINUE_MSG((len % 3) != 0, vformat("Ignoring surface %d, incorrect %s count: %d (for PRIMITIVE_TRIANGLES).", i, (surface_get_format(i) & ARRAY_FORMAT_INDEX) ? "index" : "vertex", len));
  114. faces_size += len;
  115. } break;
  116. case PRIMITIVE_TRIANGLE_STRIP: {
  117. int len = (surface_get_format(i) & ARRAY_FORMAT_INDEX) ? surface_get_array_index_len(i) : surface_get_array_len(i);
  118. // Don't error if zero, it's valid (we'll just skip it later).
  119. ERR_CONTINUE_MSG(len != 0 && len < 3, vformat("Ignoring surface %d, incorrect %s count: %d (for PRIMITIVE_TRIANGLE_STRIP).", i, (surface_get_format(i) & ARRAY_FORMAT_INDEX) ? "index" : "vertex", len));
  120. faces_size += (len == 0) ? 0 : (len - 2) * 3;
  121. } break;
  122. default: {
  123. } break;
  124. }
  125. }
  126. if (faces_size == 0) {
  127. return triangle_mesh;
  128. }
  129. Vector<Vector3> faces;
  130. faces.resize(faces_size);
  131. Vector<int32_t> surface_indices;
  132. surface_indices.resize(faces_size / 3);
  133. Vector3 *facesw = faces.ptrw();
  134. int32_t *surface_indicesw = surface_indices.ptrw();
  135. int widx = 0;
  136. for (int i = 0; i < get_surface_count(); i++) {
  137. Mesh::PrimitiveType primitive = surface_get_primitive_type(i);
  138. if (primitive != PRIMITIVE_TRIANGLES && primitive != PRIMITIVE_TRIANGLE_STRIP) {
  139. continue;
  140. }
  141. int len = (surface_get_format(i) & ARRAY_FORMAT_INDEX) ? surface_get_array_index_len(i) : surface_get_array_len(i);
  142. if ((primitive == PRIMITIVE_TRIANGLES && (len == 0 || (len % 3) != 0)) ||
  143. (primitive == PRIMITIVE_TRIANGLE_STRIP && len < 3) ||
  144. (surface_get_format(i) & ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY)) {
  145. // Error was already shown, just skip (including zero).
  146. continue;
  147. }
  148. Array a = surface_get_arrays(i);
  149. ERR_FAIL_COND_V(a.is_empty(), Ref<TriangleMesh>());
  150. int vc = surface_get_array_len(i);
  151. Vector<Vector3> vertices = a[ARRAY_VERTEX];
  152. ERR_FAIL_COND_V(vertices.is_empty(), Ref<TriangleMesh>());
  153. const Vector3 *vr = vertices.ptr();
  154. int32_t from_index = widx / 3;
  155. if (surface_get_format(i) & ARRAY_FORMAT_INDEX) {
  156. int ic = surface_get_array_index_len(i);
  157. Vector<int> indices = a[ARRAY_INDEX];
  158. const int *ir = indices.ptr();
  159. if (primitive == PRIMITIVE_TRIANGLES) {
  160. for (int j = 0; j < ic; j++) {
  161. int index = ir[j];
  162. ERR_FAIL_COND_V(index >= vc, Ref<TriangleMesh>());
  163. facesw[widx++] = vr[index];
  164. }
  165. } else { // PRIMITIVE_TRIANGLE_STRIP
  166. for (int j = 2; j < ic; j++) {
  167. facesw[widx++] = vr[ir[j - 2]];
  168. facesw[widx++] = vr[ir[j - 1]];
  169. facesw[widx++] = vr[ir[j]];
  170. }
  171. }
  172. } else {
  173. if (primitive == PRIMITIVE_TRIANGLES) {
  174. for (int j = 0; j < vc; j++) {
  175. facesw[widx++] = vr[j];
  176. }
  177. } else { // PRIMITIVE_TRIANGLE_STRIP
  178. for (int j = 2; j < vc; j++) {
  179. facesw[widx++] = vr[j - 2];
  180. facesw[widx++] = vr[j - 1];
  181. facesw[widx++] = vr[j];
  182. }
  183. }
  184. }
  185. int32_t to_index = widx / 3;
  186. for (int j = from_index; j < to_index; j++) {
  187. surface_indicesw[j] = i;
  188. }
  189. }
  190. triangle_mesh = Ref<TriangleMesh>(memnew(TriangleMesh));
  191. triangle_mesh->create(faces);
  192. return triangle_mesh;
  193. }
  194. Ref<TriangleMesh> Mesh::generate_surface_triangle_mesh(int p_surface) const {
  195. ERR_FAIL_INDEX_V(p_surface, get_surface_count(), Ref<TriangleMesh>());
  196. if (surface_triangle_meshes.size() != get_surface_count()) {
  197. surface_triangle_meshes.resize(get_surface_count());
  198. }
  199. if (surface_triangle_meshes[p_surface].is_valid()) {
  200. return surface_triangle_meshes[p_surface];
  201. }
  202. int facecount = 0;
  203. if (surface_get_primitive_type(p_surface) != PRIMITIVE_TRIANGLES) {
  204. return Ref<TriangleMesh>();
  205. }
  206. if (surface_get_format(p_surface) & ARRAY_FORMAT_INDEX) {
  207. facecount += surface_get_array_index_len(p_surface);
  208. } else {
  209. facecount += surface_get_array_len(p_surface);
  210. }
  211. Vector<Vector3> faces;
  212. faces.resize(facecount);
  213. Vector3 *facesw = faces.ptrw();
  214. Array a = surface_get_arrays(p_surface);
  215. ERR_FAIL_COND_V(a.is_empty(), Ref<TriangleMesh>());
  216. int vc = surface_get_array_len(p_surface);
  217. Vector<Vector3> vertices = a[ARRAY_VERTEX];
  218. const Vector3 *vr = vertices.ptr();
  219. int widx = 0;
  220. if (surface_get_format(p_surface) & ARRAY_FORMAT_INDEX) {
  221. int ic = surface_get_array_index_len(p_surface);
  222. Vector<int> indices = a[ARRAY_INDEX];
  223. const int *ir = indices.ptr();
  224. for (int j = 0; j < ic; j++) {
  225. int index = ir[j];
  226. facesw[widx++] = vr[index];
  227. }
  228. } else {
  229. for (int j = 0; j < vc; j++) {
  230. facesw[widx++] = vr[j];
  231. }
  232. }
  233. Ref<TriangleMesh> tr_mesh = Ref<TriangleMesh>(memnew(TriangleMesh));
  234. tr_mesh->create(faces);
  235. surface_triangle_meshes.set(p_surface, tr_mesh);
  236. return tr_mesh;
  237. }
  238. void Mesh::generate_debug_mesh_lines(Vector<Vector3> &r_lines) {
  239. if (debug_lines.size() > 0) {
  240. r_lines = debug_lines;
  241. return;
  242. }
  243. Ref<TriangleMesh> tm = generate_triangle_mesh();
  244. if (tm.is_null()) {
  245. return;
  246. }
  247. Vector<int> triangle_indices;
  248. tm->get_indices(&triangle_indices);
  249. const int triangles_num = tm->get_triangles().size();
  250. Vector<Vector3> vertices = tm->get_vertices();
  251. debug_lines.resize(tm->get_triangles().size() * 6); // 3 lines x 2 points each line
  252. const int *ind_r = triangle_indices.ptr();
  253. const Vector3 *ver_r = vertices.ptr();
  254. for (int j = 0, x = 0, i = 0; i < triangles_num; j += 6, x += 3, ++i) {
  255. // Triangle line 1
  256. debug_lines.write[j + 0] = ver_r[ind_r[x + 0]];
  257. debug_lines.write[j + 1] = ver_r[ind_r[x + 1]];
  258. // Triangle line 2
  259. debug_lines.write[j + 2] = ver_r[ind_r[x + 1]];
  260. debug_lines.write[j + 3] = ver_r[ind_r[x + 2]];
  261. // Triangle line 3
  262. debug_lines.write[j + 4] = ver_r[ind_r[x + 2]];
  263. debug_lines.write[j + 5] = ver_r[ind_r[x + 0]];
  264. }
  265. r_lines = debug_lines;
  266. }
  267. void Mesh::generate_debug_mesh_indices(Vector<Vector3> &r_points) {
  268. Ref<TriangleMesh> tm = generate_triangle_mesh();
  269. if (tm.is_null()) {
  270. return;
  271. }
  272. Vector<Vector3> vertices = tm->get_vertices();
  273. int vertices_size = vertices.size();
  274. r_points.resize(vertices_size);
  275. for (int i = 0; i < vertices_size; ++i) {
  276. r_points.write[i] = vertices[i];
  277. }
  278. }
  279. Vector<Face3> Mesh::get_faces() const {
  280. Ref<TriangleMesh> tm = generate_triangle_mesh();
  281. if (tm.is_valid()) {
  282. return tm->get_faces();
  283. }
  284. return Vector<Face3>();
  285. }
  286. Vector<Face3> Mesh::get_surface_faces(int p_surface) const {
  287. Ref<TriangleMesh> tm = generate_surface_triangle_mesh(p_surface);
  288. if (tm.is_valid()) {
  289. return tm->get_faces();
  290. }
  291. return Vector<Face3>();
  292. }
  293. Ref<ConvexPolygonShape3D> Mesh::create_convex_shape(bool p_clean, bool p_simplify) const {
  294. if (p_simplify) {
  295. ConvexDecompositionSettings settings;
  296. settings.max_convex_hulls = 1;
  297. Vector<Ref<Shape3D>> decomposed = convex_decompose(settings);
  298. if (decomposed.size() == 1) {
  299. return decomposed[0];
  300. } else {
  301. ERR_PRINT("Convex shape simplification failed, falling back to simpler process.");
  302. }
  303. }
  304. Vector<Vector3> vertices;
  305. for (int i = 0; i < get_surface_count(); i++) {
  306. Array a = surface_get_arrays(i);
  307. ERR_FAIL_COND_V(a.is_empty(), Ref<ConvexPolygonShape3D>());
  308. Vector<Vector3> v = a[ARRAY_VERTEX];
  309. vertices.append_array(v);
  310. }
  311. Ref<ConvexPolygonShape3D> shape = memnew(ConvexPolygonShape3D);
  312. if (p_clean) {
  313. Geometry3D::MeshData md;
  314. Error err = ConvexHullComputer::convex_hull(vertices, md);
  315. if (err == OK) {
  316. shape->set_points(md.vertices);
  317. return shape;
  318. } else {
  319. ERR_PRINT("Convex shape cleaning failed, falling back to simpler process.");
  320. }
  321. }
  322. shape->set_points(vertices);
  323. return shape;
  324. }
  325. Ref<ConcavePolygonShape3D> Mesh::create_trimesh_shape() const {
  326. Vector<Face3> faces = get_faces();
  327. if (faces.size() == 0) {
  328. return Ref<ConcavePolygonShape3D>();
  329. }
  330. Vector<Vector3> face_points;
  331. face_points.resize(faces.size() * 3);
  332. for (int i = 0; i < face_points.size(); i += 3) {
  333. Face3 f = faces.get(i / 3);
  334. face_points.set(i, f.vertex[0]);
  335. face_points.set(i + 1, f.vertex[1]);
  336. face_points.set(i + 2, f.vertex[2]);
  337. }
  338. Ref<ConcavePolygonShape3D> shape = memnew(ConcavePolygonShape3D);
  339. shape->set_faces(face_points);
  340. return shape;
  341. }
  342. Ref<Mesh> Mesh::create_outline(float p_margin) const {
  343. Array arrays;
  344. int index_accum = 0;
  345. for (int i = 0; i < get_surface_count(); i++) {
  346. if (surface_get_primitive_type(i) != PRIMITIVE_TRIANGLES) {
  347. continue;
  348. }
  349. Array a = surface_get_arrays(i);
  350. ERR_FAIL_COND_V(a.is_empty(), Ref<ArrayMesh>());
  351. if (i == 0) {
  352. arrays = a;
  353. Vector<Vector3> v = a[ARRAY_VERTEX];
  354. index_accum += v.size();
  355. } else {
  356. int vcount = 0;
  357. for (int j = 0; j < arrays.size(); j++) {
  358. if (arrays[j].get_type() == Variant::NIL || a[j].get_type() == Variant::NIL) {
  359. //mismatch, do not use
  360. arrays[j] = Variant();
  361. continue;
  362. }
  363. switch (j) {
  364. case ARRAY_VERTEX:
  365. case ARRAY_NORMAL: {
  366. Vector<Vector3> dst = arrays[j];
  367. Vector<Vector3> src = a[j];
  368. if (j == ARRAY_VERTEX) {
  369. vcount = src.size();
  370. }
  371. if (dst.size() == 0 || src.size() == 0) {
  372. arrays[j] = Variant();
  373. continue;
  374. }
  375. dst.append_array(src);
  376. arrays[j] = dst;
  377. } break;
  378. case ARRAY_TANGENT:
  379. case ARRAY_BONES:
  380. case ARRAY_WEIGHTS: {
  381. Vector<real_t> dst = arrays[j];
  382. Vector<real_t> src = a[j];
  383. if (dst.size() == 0 || src.size() == 0) {
  384. arrays[j] = Variant();
  385. continue;
  386. }
  387. dst.append_array(src);
  388. arrays[j] = dst;
  389. } break;
  390. case ARRAY_COLOR: {
  391. Vector<Color> dst = arrays[j];
  392. Vector<Color> src = a[j];
  393. if (dst.size() == 0 || src.size() == 0) {
  394. arrays[j] = Variant();
  395. continue;
  396. }
  397. dst.append_array(src);
  398. arrays[j] = dst;
  399. } break;
  400. case ARRAY_TEX_UV:
  401. case ARRAY_TEX_UV2: {
  402. Vector<Vector2> dst = arrays[j];
  403. Vector<Vector2> src = a[j];
  404. if (dst.size() == 0 || src.size() == 0) {
  405. arrays[j] = Variant();
  406. continue;
  407. }
  408. dst.append_array(src);
  409. arrays[j] = dst;
  410. } break;
  411. case ARRAY_INDEX: {
  412. Vector<int> dst = arrays[j];
  413. Vector<int> src = a[j];
  414. if (dst.size() == 0 || src.size() == 0) {
  415. arrays[j] = Variant();
  416. continue;
  417. }
  418. {
  419. int ss = src.size();
  420. int *w = src.ptrw();
  421. for (int k = 0; k < ss; k++) {
  422. w[k] += index_accum;
  423. }
  424. }
  425. dst.append_array(src);
  426. arrays[j] = dst;
  427. index_accum += vcount;
  428. } break;
  429. }
  430. }
  431. }
  432. }
  433. ERR_FAIL_COND_V(arrays.size() != ARRAY_MAX, Ref<ArrayMesh>());
  434. {
  435. int *ir = nullptr;
  436. Vector<int> indices = arrays[ARRAY_INDEX];
  437. bool has_indices = false;
  438. Vector<Vector3> vertices = arrays[ARRAY_VERTEX];
  439. int vc = vertices.size();
  440. ERR_FAIL_COND_V(!vc, Ref<ArrayMesh>());
  441. Vector3 *r = vertices.ptrw();
  442. if (indices.size()) {
  443. ERR_FAIL_COND_V(indices.size() % 3 != 0, Ref<ArrayMesh>());
  444. vc = indices.size();
  445. ir = indices.ptrw();
  446. has_indices = true;
  447. } else {
  448. // Ensure there are enough vertices to construct at least one triangle.
  449. ERR_FAIL_COND_V(vertices.size() % 3 != 0, Ref<ArrayMesh>());
  450. }
  451. HashMap<Vector3, Vector3> normal_accum;
  452. //fill normals with triangle normals
  453. for (int i = 0; i < vc; i += 3) {
  454. Vector3 t[3];
  455. if (has_indices) {
  456. t[0] = r[ir[i + 0]];
  457. t[1] = r[ir[i + 1]];
  458. t[2] = r[ir[i + 2]];
  459. } else {
  460. t[0] = r[i + 0];
  461. t[1] = r[i + 1];
  462. t[2] = r[i + 2];
  463. }
  464. Vector3 n = Plane(t[0], t[1], t[2]).normal;
  465. for (int j = 0; j < 3; j++) {
  466. HashMap<Vector3, Vector3>::Iterator E = normal_accum.find(t[j]);
  467. if (!E) {
  468. normal_accum[t[j]] = n;
  469. } else {
  470. float d = n.dot(E->value);
  471. if (d < 1.0) {
  472. E->value += n * (1.0 - d);
  473. }
  474. //E->get()+=n;
  475. }
  476. }
  477. }
  478. //normalize
  479. for (KeyValue<Vector3, Vector3> &E : normal_accum) {
  480. E.value.normalize();
  481. }
  482. //displace normals
  483. int vc2 = vertices.size();
  484. for (int i = 0; i < vc2; i++) {
  485. Vector3 t = r[i];
  486. HashMap<Vector3, Vector3>::Iterator E = normal_accum.find(t);
  487. ERR_CONTINUE(!E);
  488. t += E->value * p_margin;
  489. r[i] = t;
  490. }
  491. arrays[ARRAY_VERTEX] = vertices;
  492. if (!has_indices) {
  493. Vector<int> new_indices;
  494. new_indices.resize(vertices.size());
  495. int *iw = new_indices.ptrw();
  496. for (int j = 0; j < vc2; j += 3) {
  497. iw[j] = j;
  498. iw[j + 1] = j + 2;
  499. iw[j + 2] = j + 1;
  500. }
  501. arrays[ARRAY_INDEX] = new_indices;
  502. } else {
  503. for (int j = 0; j < vc; j += 3) {
  504. SWAP(ir[j + 1], ir[j + 2]);
  505. }
  506. arrays[ARRAY_INDEX] = indices;
  507. }
  508. }
  509. Ref<ArrayMesh> newmesh = memnew(ArrayMesh);
  510. newmesh->add_surface_from_arrays(PRIMITIVE_TRIANGLES, arrays);
  511. return newmesh;
  512. }
  513. void Mesh::set_lightmap_size_hint(const Size2i &p_size) {
  514. lightmap_size_hint = p_size;
  515. }
  516. Size2i Mesh::get_lightmap_size_hint() const {
  517. return lightmap_size_hint;
  518. }
  519. Ref<Resource> Mesh::create_placeholder() const {
  520. Ref<PlaceholderMesh> placeholder;
  521. placeholder.instantiate();
  522. placeholder->set_aabb(get_aabb());
  523. return placeholder;
  524. }
  525. void Mesh::_bind_methods() {
  526. ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &Mesh::set_lightmap_size_hint);
  527. ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &Mesh::get_lightmap_size_hint);
  528. ClassDB::bind_method(D_METHOD("get_aabb"), &Mesh::get_aabb);
  529. ADD_PROPERTY(PropertyInfo(Variant::VECTOR2I, "lightmap_size_hint"), "set_lightmap_size_hint", "get_lightmap_size_hint");
  530. ClassDB::bind_method(D_METHOD("get_surface_count"), &Mesh::get_surface_count);
  531. ClassDB::bind_method(D_METHOD("surface_get_arrays", "surf_idx"), &Mesh::surface_get_arrays);
  532. ClassDB::bind_method(D_METHOD("surface_get_blend_shape_arrays", "surf_idx"), &Mesh::surface_get_blend_shape_arrays);
  533. ClassDB::bind_method(D_METHOD("surface_set_material", "surf_idx", "material"), &Mesh::surface_set_material);
  534. ClassDB::bind_method(D_METHOD("surface_get_material", "surf_idx"), &Mesh::surface_get_material);
  535. ClassDB::bind_method(D_METHOD("create_placeholder"), &Mesh::create_placeholder);
  536. BIND_ENUM_CONSTANT(PRIMITIVE_POINTS);
  537. BIND_ENUM_CONSTANT(PRIMITIVE_LINES);
  538. BIND_ENUM_CONSTANT(PRIMITIVE_LINE_STRIP);
  539. BIND_ENUM_CONSTANT(PRIMITIVE_TRIANGLES);
  540. BIND_ENUM_CONSTANT(PRIMITIVE_TRIANGLE_STRIP);
  541. BIND_ENUM_CONSTANT(ARRAY_VERTEX);
  542. BIND_ENUM_CONSTANT(ARRAY_NORMAL);
  543. BIND_ENUM_CONSTANT(ARRAY_TANGENT);
  544. BIND_ENUM_CONSTANT(ARRAY_COLOR);
  545. BIND_ENUM_CONSTANT(ARRAY_TEX_UV);
  546. BIND_ENUM_CONSTANT(ARRAY_TEX_UV2);
  547. BIND_ENUM_CONSTANT(ARRAY_CUSTOM0);
  548. BIND_ENUM_CONSTANT(ARRAY_CUSTOM1);
  549. BIND_ENUM_CONSTANT(ARRAY_CUSTOM2);
  550. BIND_ENUM_CONSTANT(ARRAY_CUSTOM3);
  551. BIND_ENUM_CONSTANT(ARRAY_BONES);
  552. BIND_ENUM_CONSTANT(ARRAY_WEIGHTS);
  553. BIND_ENUM_CONSTANT(ARRAY_INDEX);
  554. BIND_ENUM_CONSTANT(ARRAY_MAX);
  555. BIND_ENUM_CONSTANT(ARRAY_CUSTOM_RGBA8_UNORM);
  556. BIND_ENUM_CONSTANT(ARRAY_CUSTOM_RGBA8_SNORM);
  557. BIND_ENUM_CONSTANT(ARRAY_CUSTOM_RG_HALF);
  558. BIND_ENUM_CONSTANT(ARRAY_CUSTOM_RGBA_HALF);
  559. BIND_ENUM_CONSTANT(ARRAY_CUSTOM_R_FLOAT);
  560. BIND_ENUM_CONSTANT(ARRAY_CUSTOM_RG_FLOAT);
  561. BIND_ENUM_CONSTANT(ARRAY_CUSTOM_RGB_FLOAT);
  562. BIND_ENUM_CONSTANT(ARRAY_CUSTOM_RGBA_FLOAT);
  563. BIND_ENUM_CONSTANT(ARRAY_CUSTOM_MAX);
  564. BIND_BITFIELD_FLAG(ARRAY_FORMAT_VERTEX);
  565. BIND_BITFIELD_FLAG(ARRAY_FORMAT_NORMAL);
  566. BIND_BITFIELD_FLAG(ARRAY_FORMAT_TANGENT);
  567. BIND_BITFIELD_FLAG(ARRAY_FORMAT_COLOR);
  568. BIND_BITFIELD_FLAG(ARRAY_FORMAT_TEX_UV);
  569. BIND_BITFIELD_FLAG(ARRAY_FORMAT_TEX_UV2);
  570. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM0);
  571. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM1);
  572. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM2);
  573. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM3);
  574. BIND_BITFIELD_FLAG(ARRAY_FORMAT_BONES);
  575. BIND_BITFIELD_FLAG(ARRAY_FORMAT_WEIGHTS);
  576. BIND_BITFIELD_FLAG(ARRAY_FORMAT_INDEX);
  577. BIND_BITFIELD_FLAG(ARRAY_FORMAT_BLEND_SHAPE_MASK);
  578. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM_BASE);
  579. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM_BITS);
  580. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM0_SHIFT);
  581. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM1_SHIFT);
  582. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM2_SHIFT);
  583. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM3_SHIFT);
  584. BIND_BITFIELD_FLAG(ARRAY_FORMAT_CUSTOM_MASK);
  585. BIND_BITFIELD_FLAG(ARRAY_COMPRESS_FLAGS_BASE);
  586. BIND_BITFIELD_FLAG(ARRAY_FLAG_USE_2D_VERTICES);
  587. BIND_BITFIELD_FLAG(ARRAY_FLAG_USE_DYNAMIC_UPDATE);
  588. BIND_BITFIELD_FLAG(ARRAY_FLAG_USE_8_BONE_WEIGHTS);
  589. BIND_BITFIELD_FLAG(ARRAY_FLAG_USES_EMPTY_VERTEX_ARRAY);
  590. BIND_ENUM_CONSTANT(BLEND_SHAPE_MODE_NORMALIZED);
  591. BIND_ENUM_CONSTANT(BLEND_SHAPE_MODE_RELATIVE);
  592. GDVIRTUAL_BIND(_get_surface_count)
  593. GDVIRTUAL_BIND(_surface_get_array_len, "index")
  594. GDVIRTUAL_BIND(_surface_get_array_index_len, "index")
  595. GDVIRTUAL_BIND(_surface_get_arrays, "index")
  596. GDVIRTUAL_BIND(_surface_get_blend_shape_arrays, "index")
  597. GDVIRTUAL_BIND(_surface_get_lods, "index")
  598. GDVIRTUAL_BIND(_surface_get_format, "index")
  599. GDVIRTUAL_BIND(_surface_get_primitive_type, "index")
  600. GDVIRTUAL_BIND(_surface_set_material, "index", "material")
  601. GDVIRTUAL_BIND(_surface_get_material, "index")
  602. GDVIRTUAL_BIND(_get_blend_shape_count)
  603. GDVIRTUAL_BIND(_get_blend_shape_name, "index")
  604. GDVIRTUAL_BIND(_set_blend_shape_name, "index", "name")
  605. GDVIRTUAL_BIND(_get_aabb)
  606. }
  607. void Mesh::clear_cache() const {
  608. triangle_mesh.unref();
  609. debug_lines.clear();
  610. }
  611. Vector<Ref<Shape3D>> Mesh::convex_decompose(const ConvexDecompositionSettings &p_settings) const {
  612. ERR_FAIL_COND_V(!convex_decomposition_function, Vector<Ref<Shape3D>>());
  613. Ref<TriangleMesh> tm = generate_triangle_mesh();
  614. ERR_FAIL_COND_V(!tm.is_valid(), Vector<Ref<Shape3D>>());
  615. const Vector<TriangleMesh::Triangle> &triangles = tm->get_triangles();
  616. int triangle_count = triangles.size();
  617. Vector<uint32_t> indices;
  618. {
  619. indices.resize(triangle_count * 3);
  620. uint32_t *w = indices.ptrw();
  621. for (int i = 0; i < triangle_count; i++) {
  622. for (int j = 0; j < 3; j++) {
  623. w[i * 3 + j] = triangles[i].indices[j];
  624. }
  625. }
  626. }
  627. const Vector<Vector3> &vertices = tm->get_vertices();
  628. int vertex_count = vertices.size();
  629. Vector<Vector<Vector3>> decomposed = convex_decomposition_function((real_t *)vertices.ptr(), vertex_count, indices.ptr(), triangle_count, p_settings, nullptr);
  630. Vector<Ref<Shape3D>> ret;
  631. for (int i = 0; i < decomposed.size(); i++) {
  632. Ref<ConvexPolygonShape3D> shape;
  633. shape.instantiate();
  634. shape->set_points(decomposed[i]);
  635. ret.push_back(shape);
  636. }
  637. return ret;
  638. }
  639. int Mesh::get_builtin_bind_pose_count() const {
  640. return 0;
  641. }
  642. Transform3D Mesh::get_builtin_bind_pose(int p_index) const {
  643. return Transform3D();
  644. }
  645. Mesh::Mesh() {
  646. }
  647. enum OldArrayType {
  648. OLD_ARRAY_VERTEX,
  649. OLD_ARRAY_NORMAL,
  650. OLD_ARRAY_TANGENT,
  651. OLD_ARRAY_COLOR,
  652. OLD_ARRAY_TEX_UV,
  653. OLD_ARRAY_TEX_UV2,
  654. OLD_ARRAY_BONES,
  655. OLD_ARRAY_WEIGHTS,
  656. OLD_ARRAY_INDEX,
  657. OLD_ARRAY_MAX,
  658. };
  659. enum OldArrayFormat {
  660. /* OLD_ARRAY FORMAT FLAGS */
  661. OLD_ARRAY_FORMAT_VERTEX = 1 << OLD_ARRAY_VERTEX, // mandatory
  662. OLD_ARRAY_FORMAT_NORMAL = 1 << OLD_ARRAY_NORMAL,
  663. OLD_ARRAY_FORMAT_TANGENT = 1 << OLD_ARRAY_TANGENT,
  664. OLD_ARRAY_FORMAT_COLOR = 1 << OLD_ARRAY_COLOR,
  665. OLD_ARRAY_FORMAT_TEX_UV = 1 << OLD_ARRAY_TEX_UV,
  666. OLD_ARRAY_FORMAT_TEX_UV2 = 1 << OLD_ARRAY_TEX_UV2,
  667. OLD_ARRAY_FORMAT_BONES = 1 << OLD_ARRAY_BONES,
  668. OLD_ARRAY_FORMAT_WEIGHTS = 1 << OLD_ARRAY_WEIGHTS,
  669. OLD_ARRAY_FORMAT_INDEX = 1 << OLD_ARRAY_INDEX,
  670. OLD_ARRAY_COMPRESS_BASE = (OLD_ARRAY_INDEX + 1),
  671. OLD_ARRAY_COMPRESS_VERTEX = 1 << (OLD_ARRAY_VERTEX + OLD_ARRAY_COMPRESS_BASE), // mandatory
  672. OLD_ARRAY_COMPRESS_NORMAL = 1 << (OLD_ARRAY_NORMAL + OLD_ARRAY_COMPRESS_BASE),
  673. OLD_ARRAY_COMPRESS_TANGENT = 1 << (OLD_ARRAY_TANGENT + OLD_ARRAY_COMPRESS_BASE),
  674. OLD_ARRAY_COMPRESS_COLOR = 1 << (OLD_ARRAY_COLOR + OLD_ARRAY_COMPRESS_BASE),
  675. OLD_ARRAY_COMPRESS_TEX_UV = 1 << (OLD_ARRAY_TEX_UV + OLD_ARRAY_COMPRESS_BASE),
  676. OLD_ARRAY_COMPRESS_TEX_UV2 = 1 << (OLD_ARRAY_TEX_UV2 + OLD_ARRAY_COMPRESS_BASE),
  677. OLD_ARRAY_COMPRESS_BONES = 1 << (OLD_ARRAY_BONES + OLD_ARRAY_COMPRESS_BASE),
  678. OLD_ARRAY_COMPRESS_WEIGHTS = 1 << (OLD_ARRAY_WEIGHTS + OLD_ARRAY_COMPRESS_BASE),
  679. OLD_ARRAY_COMPRESS_INDEX = 1 << (OLD_ARRAY_INDEX + OLD_ARRAY_COMPRESS_BASE),
  680. OLD_ARRAY_FLAG_USE_2D_VERTICES = OLD_ARRAY_COMPRESS_INDEX << 1,
  681. OLD_ARRAY_FLAG_USE_16_BIT_BONES = OLD_ARRAY_COMPRESS_INDEX << 2,
  682. OLD_ARRAY_FLAG_USE_DYNAMIC_UPDATE = OLD_ARRAY_COMPRESS_INDEX << 3,
  683. OLD_ARRAY_FLAG_USE_OCTAHEDRAL_COMPRESSION = OLD_ARRAY_COMPRESS_INDEX << 4,
  684. };
  685. #ifndef DISABLE_DEPRECATED
  686. static Array _convert_old_array(const Array &p_old) {
  687. Array new_array;
  688. new_array.resize(Mesh::ARRAY_MAX);
  689. new_array[Mesh::ARRAY_VERTEX] = p_old[OLD_ARRAY_VERTEX];
  690. new_array[Mesh::ARRAY_NORMAL] = p_old[OLD_ARRAY_NORMAL];
  691. new_array[Mesh::ARRAY_TANGENT] = p_old[OLD_ARRAY_TANGENT];
  692. new_array[Mesh::ARRAY_COLOR] = p_old[OLD_ARRAY_COLOR];
  693. new_array[Mesh::ARRAY_TEX_UV] = p_old[OLD_ARRAY_TEX_UV];
  694. new_array[Mesh::ARRAY_TEX_UV2] = p_old[OLD_ARRAY_TEX_UV2];
  695. new_array[Mesh::ARRAY_BONES] = p_old[OLD_ARRAY_BONES];
  696. new_array[Mesh::ARRAY_WEIGHTS] = p_old[OLD_ARRAY_WEIGHTS];
  697. new_array[Mesh::ARRAY_INDEX] = p_old[OLD_ARRAY_INDEX];
  698. return new_array;
  699. }
  700. static Mesh::PrimitiveType _old_primitives[7] = {
  701. Mesh::PRIMITIVE_POINTS,
  702. Mesh::PRIMITIVE_LINES,
  703. Mesh::PRIMITIVE_LINE_STRIP,
  704. Mesh::PRIMITIVE_LINES,
  705. Mesh::PRIMITIVE_TRIANGLES,
  706. Mesh::PRIMITIVE_TRIANGLE_STRIP,
  707. Mesh::PRIMITIVE_TRIANGLE_STRIP
  708. };
  709. #endif // DISABLE_DEPRECATED
  710. void _fix_array_compatibility(const Vector<uint8_t> &p_src, uint32_t p_old_format, uint32_t p_new_format, uint32_t p_elements, Vector<uint8_t> &vertex_data, Vector<uint8_t> &attribute_data, Vector<uint8_t> &skin_data) {
  711. uint32_t dst_vertex_stride;
  712. uint32_t dst_attribute_stride;
  713. uint32_t dst_skin_stride;
  714. uint32_t dst_offsets[Mesh::ARRAY_MAX];
  715. RenderingServer::get_singleton()->mesh_surface_make_offsets_from_format(p_new_format & (~RS::ARRAY_FORMAT_INDEX), p_elements, 0, dst_offsets, dst_vertex_stride, dst_attribute_stride, dst_skin_stride);
  716. vertex_data.resize(dst_vertex_stride * p_elements);
  717. attribute_data.resize(dst_attribute_stride * p_elements);
  718. skin_data.resize(dst_skin_stride * p_elements);
  719. uint8_t *dst_vertex_ptr = vertex_data.ptrw();
  720. uint8_t *dst_attribute_ptr = attribute_data.ptrw();
  721. uint8_t *dst_skin_ptr = skin_data.ptrw();
  722. const uint8_t *src_vertex_ptr = p_src.ptr();
  723. uint32_t src_vertex_stride = p_src.size() / p_elements;
  724. uint32_t src_offset = 0;
  725. for (uint32_t j = 0; j < OLD_ARRAY_INDEX; j++) {
  726. if (!(p_old_format & (1 << j))) {
  727. continue;
  728. }
  729. switch (j) {
  730. case OLD_ARRAY_VERTEX: {
  731. if (p_old_format & OLD_ARRAY_FLAG_USE_2D_VERTICES) {
  732. if (p_old_format & OLD_ARRAY_COMPRESS_VERTEX) {
  733. for (uint32_t i = 0; i < p_elements; i++) {
  734. const uint16_t *src = (const uint16_t *)&src_vertex_ptr[i * src_vertex_stride];
  735. float *dst = (float *)&dst_vertex_ptr[i * dst_vertex_stride];
  736. dst[0] = Math::half_to_float(src[0]);
  737. dst[1] = Math::half_to_float(src[1]);
  738. }
  739. src_offset += sizeof(uint16_t) * 2;
  740. } else {
  741. for (uint32_t i = 0; i < p_elements; i++) {
  742. const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride];
  743. float *dst = (float *)&dst_vertex_ptr[i * dst_vertex_stride];
  744. dst[0] = src[0];
  745. dst[1] = src[1];
  746. }
  747. src_offset += sizeof(float) * 2;
  748. }
  749. } else {
  750. if (p_old_format & OLD_ARRAY_COMPRESS_VERTEX) {
  751. for (uint32_t i = 0; i < p_elements; i++) {
  752. const uint16_t *src = (const uint16_t *)&src_vertex_ptr[i * src_vertex_stride];
  753. float *dst = (float *)&dst_vertex_ptr[i * dst_vertex_stride];
  754. dst[0] = Math::half_to_float(src[0]);
  755. dst[1] = Math::half_to_float(src[1]);
  756. dst[2] = Math::half_to_float(src[2]);
  757. }
  758. src_offset += sizeof(uint16_t) * 4; //+pad
  759. } else {
  760. for (uint32_t i = 0; i < p_elements; i++) {
  761. const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride];
  762. float *dst = (float *)&dst_vertex_ptr[i * dst_vertex_stride];
  763. dst[0] = src[0];
  764. dst[1] = src[1];
  765. dst[2] = src[2];
  766. }
  767. src_offset += sizeof(float) * 3;
  768. }
  769. }
  770. } break;
  771. case OLD_ARRAY_NORMAL: {
  772. if (p_old_format & OLD_ARRAY_FLAG_USE_OCTAHEDRAL_COMPRESSION) {
  773. if ((p_old_format & OLD_ARRAY_COMPRESS_NORMAL) && (p_old_format & OLD_ARRAY_FORMAT_TANGENT) && (p_old_format & OLD_ARRAY_COMPRESS_TANGENT)) {
  774. for (uint32_t i = 0; i < p_elements; i++) {
  775. const int8_t *src = (const int8_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  776. int16_t *dst = (int16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
  777. dst[0] = (int16_t)CLAMP(src[0] / 127.0f * 32767, -32768, 32767);
  778. dst[1] = (int16_t)CLAMP(src[1] / 127.0f * 32767, -32768, 32767);
  779. }
  780. src_offset += sizeof(int8_t) * 2;
  781. } else {
  782. for (uint32_t i = 0; i < p_elements; i++) {
  783. const int16_t *src = (const int16_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  784. int16_t *dst = (int16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
  785. dst[0] = src[0];
  786. dst[1] = src[1];
  787. }
  788. src_offset += sizeof(int16_t) * 2;
  789. }
  790. } else { // No Octahedral compression
  791. if (p_old_format & OLD_ARRAY_COMPRESS_NORMAL) {
  792. for (uint32_t i = 0; i < p_elements; i++) {
  793. const int8_t *src = (const int8_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  794. const Vector3 original_normal(src[0], src[1], src[2]);
  795. Vector2 res = original_normal.octahedron_encode();
  796. uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
  797. dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
  798. dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
  799. }
  800. src_offset += sizeof(uint8_t) * 4; // 1 byte padding
  801. } else {
  802. for (uint32_t i = 0; i < p_elements; i++) {
  803. const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  804. const Vector3 original_normal(src[0], src[1], src[2]);
  805. Vector2 res = original_normal.octahedron_encode();
  806. uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
  807. dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
  808. dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
  809. }
  810. src_offset += sizeof(float) * 3;
  811. }
  812. }
  813. } break;
  814. case OLD_ARRAY_TANGENT: {
  815. if (p_old_format & OLD_ARRAY_FLAG_USE_OCTAHEDRAL_COMPRESSION) {
  816. if (p_old_format & OLD_ARRAY_COMPRESS_TANGENT) { // int8 SNORM -> uint16 UNORM
  817. for (uint32_t i = 0; i < p_elements; i++) {
  818. const int8_t *src = (const int8_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  819. uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_TANGENT]];
  820. dst[0] = (uint16_t)CLAMP((src[0] / 127.0f * .5f + .5f) * 65535, 0, 65535);
  821. dst[1] = (uint16_t)CLAMP((src[1] / 127.0f * .5f + .5f) * 65535, 0, 65535);
  822. }
  823. src_offset += sizeof(uint8_t) * 2;
  824. } else { // int16 SNORM -> uint16 UNORM
  825. for (uint32_t i = 0; i < p_elements; i++) {
  826. const int16_t *src = (const int16_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  827. uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_TANGENT]];
  828. dst[0] = (uint16_t)CLAMP((src[0] / 32767.0f * .5f + .5f) * 65535, 0, 65535);
  829. dst[1] = (uint16_t)CLAMP((src[1] / 32767.0f * .5f + .5f) * 65535, 0, 65535);
  830. }
  831. src_offset += sizeof(uint16_t) * 2;
  832. }
  833. } else { // No Octahedral compression
  834. if (p_old_format & OLD_ARRAY_COMPRESS_TANGENT) {
  835. for (uint32_t i = 0; i < p_elements; i++) {
  836. const int8_t *src = (const int8_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  837. const Vector3 original_tangent(src[0], src[1], src[2]);
  838. Vector2 res = original_tangent.octahedron_tangent_encode(src[3]);
  839. uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
  840. dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
  841. dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
  842. }
  843. src_offset += sizeof(uint8_t) * 4;
  844. } else {
  845. for (uint32_t i = 0; i < p_elements; i++) {
  846. const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  847. const Vector3 original_tangent(src[0], src[1], src[2]);
  848. Vector2 res = original_tangent.octahedron_tangent_encode(src[3]);
  849. uint16_t *dst = (uint16_t *)&dst_vertex_ptr[i * dst_vertex_stride + dst_offsets[Mesh::ARRAY_NORMAL]];
  850. dst[0] = (uint16_t)CLAMP(res.x * 65535, 0, 65535);
  851. dst[1] = (uint16_t)CLAMP(res.y * 65535, 0, 65535);
  852. }
  853. src_offset += sizeof(float) * 4;
  854. }
  855. }
  856. } break;
  857. case OLD_ARRAY_COLOR: {
  858. if (p_old_format & OLD_ARRAY_COMPRESS_COLOR) {
  859. for (uint32_t i = 0; i < p_elements; i++) {
  860. const uint32_t *src = (const uint32_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  861. uint32_t *dst = (uint32_t *)&dst_attribute_ptr[i * dst_attribute_stride + dst_offsets[Mesh::ARRAY_COLOR]];
  862. *dst = *src;
  863. }
  864. src_offset += sizeof(uint32_t);
  865. } else {
  866. for (uint32_t i = 0; i < p_elements; i++) {
  867. const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  868. uint8_t *dst = (uint8_t *)&dst_attribute_ptr[i * dst_attribute_stride + dst_offsets[Mesh::ARRAY_COLOR]];
  869. dst[0] = uint8_t(CLAMP(src[0] * 255.0, 0.0, 255.0));
  870. dst[1] = uint8_t(CLAMP(src[1] * 255.0, 0.0, 255.0));
  871. dst[2] = uint8_t(CLAMP(src[2] * 255.0, 0.0, 255.0));
  872. dst[3] = uint8_t(CLAMP(src[3] * 255.0, 0.0, 255.0));
  873. }
  874. src_offset += sizeof(float) * 4;
  875. }
  876. } break;
  877. case OLD_ARRAY_TEX_UV: {
  878. if (p_old_format & OLD_ARRAY_COMPRESS_TEX_UV) {
  879. for (uint32_t i = 0; i < p_elements; i++) {
  880. const uint16_t *src = (const uint16_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  881. float *dst = (float *)&dst_attribute_ptr[i * dst_attribute_stride + dst_offsets[Mesh::ARRAY_TEX_UV]];
  882. dst[0] = Math::half_to_float(src[0]);
  883. dst[1] = Math::half_to_float(src[1]);
  884. }
  885. src_offset += sizeof(uint16_t) * 2;
  886. } else {
  887. for (uint32_t i = 0; i < p_elements; i++) {
  888. const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  889. float *dst = (float *)&dst_attribute_ptr[i * dst_attribute_stride + dst_offsets[Mesh::ARRAY_TEX_UV]];
  890. dst[0] = src[0];
  891. dst[1] = src[1];
  892. }
  893. src_offset += sizeof(float) * 2;
  894. }
  895. } break;
  896. case OLD_ARRAY_TEX_UV2: {
  897. if (p_old_format & OLD_ARRAY_COMPRESS_TEX_UV2) {
  898. for (uint32_t i = 0; i < p_elements; i++) {
  899. const uint16_t *src = (const uint16_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  900. float *dst = (float *)&dst_attribute_ptr[i * dst_attribute_stride + dst_offsets[Mesh::ARRAY_TEX_UV2]];
  901. dst[0] = Math::half_to_float(src[0]);
  902. dst[1] = Math::half_to_float(src[1]);
  903. }
  904. src_offset += sizeof(uint16_t) * 2;
  905. } else {
  906. for (uint32_t i = 0; i < p_elements; i++) {
  907. const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  908. float *dst = (float *)&dst_attribute_ptr[i * dst_attribute_stride + dst_offsets[Mesh::ARRAY_TEX_UV2]];
  909. dst[0] = src[0];
  910. dst[1] = src[1];
  911. }
  912. src_offset += sizeof(float) * 2;
  913. }
  914. } break;
  915. case OLD_ARRAY_BONES: {
  916. if (p_old_format & OLD_ARRAY_FLAG_USE_16_BIT_BONES) {
  917. for (uint32_t i = 0; i < p_elements; i++) {
  918. const uint16_t *src = (const uint16_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  919. uint16_t *dst = (uint16_t *)&dst_skin_ptr[i * dst_skin_stride + dst_offsets[Mesh::ARRAY_BONES]];
  920. dst[0] = src[0];
  921. dst[1] = src[1];
  922. dst[2] = src[2];
  923. dst[3] = src[3];
  924. }
  925. src_offset += sizeof(uint16_t) * 4;
  926. } else {
  927. for (uint32_t i = 0; i < p_elements; i++) {
  928. const uint8_t *src = (const uint8_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  929. uint16_t *dst = (uint16_t *)&dst_skin_ptr[i * dst_skin_stride + dst_offsets[Mesh::ARRAY_BONES]];
  930. dst[0] = src[0];
  931. dst[1] = src[1];
  932. dst[2] = src[2];
  933. dst[3] = src[3];
  934. }
  935. src_offset += sizeof(uint8_t) * 4;
  936. }
  937. } break;
  938. case OLD_ARRAY_WEIGHTS: {
  939. if (p_old_format & OLD_ARRAY_COMPRESS_WEIGHTS) {
  940. for (uint32_t i = 0; i < p_elements; i++) {
  941. const uint16_t *src = (const uint16_t *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  942. uint16_t *dst = (uint16_t *)&dst_skin_ptr[i * dst_skin_stride + dst_offsets[Mesh::ARRAY_WEIGHTS]];
  943. dst[0] = src[0];
  944. dst[1] = src[1];
  945. dst[2] = src[2];
  946. dst[3] = src[3];
  947. }
  948. src_offset += sizeof(uint16_t) * 4;
  949. } else {
  950. for (uint32_t i = 0; i < p_elements; i++) {
  951. const float *src = (const float *)&src_vertex_ptr[i * src_vertex_stride + src_offset];
  952. uint16_t *dst = (uint16_t *)&dst_skin_ptr[i * dst_skin_stride + dst_offsets[Mesh::ARRAY_WEIGHTS]];
  953. dst[0] = uint16_t(CLAMP(src[0] * 65535.0, 0, 65535.0));
  954. dst[1] = uint16_t(CLAMP(src[1] * 65535.0, 0, 65535.0));
  955. dst[2] = uint16_t(CLAMP(src[2] * 65535.0, 0, 65535.0));
  956. dst[3] = uint16_t(CLAMP(src[3] * 65535.0, 0, 65535.0));
  957. }
  958. src_offset += sizeof(float) * 4;
  959. }
  960. } break;
  961. default: {
  962. }
  963. }
  964. }
  965. }
  966. bool ArrayMesh::_set(const StringName &p_name, const Variant &p_value) {
  967. String sname = p_name;
  968. if (sname.begins_with("surface_")) {
  969. int sl = sname.find("/");
  970. if (sl == -1) {
  971. return false;
  972. }
  973. int idx = sname.substr(8, sl - 8).to_int();
  974. String what = sname.get_slicec('/', 1);
  975. if (what == "material") {
  976. surface_set_material(idx, p_value);
  977. } else if (what == "name") {
  978. surface_set_name(idx, p_value);
  979. }
  980. return true;
  981. }
  982. #ifndef DISABLE_DEPRECATED
  983. // Kept for compatibility from 3.x to 4.0.
  984. if (!sname.begins_with("surfaces")) {
  985. return false;
  986. }
  987. WARN_DEPRECATED_MSG(vformat(
  988. "Mesh uses old surface format, which is deprecated (and loads slower). Consider re-importing or re-saving the scene. Path: \"%s\"",
  989. get_path()));
  990. int idx = sname.get_slicec('/', 1).to_int();
  991. String what = sname.get_slicec('/', 2);
  992. if (idx == surfaces.size()) {
  993. //create
  994. Dictionary d = p_value;
  995. ERR_FAIL_COND_V(!d.has("primitive"), false);
  996. if (d.has("arrays")) {
  997. //oldest format (2.x)
  998. ERR_FAIL_COND_V(!d.has("morph_arrays"), false);
  999. Array morph_arrays = d["morph_arrays"];
  1000. for (int i = 0; i < morph_arrays.size(); i++) {
  1001. morph_arrays[i] = _convert_old_array(morph_arrays[i]);
  1002. }
  1003. add_surface_from_arrays(_old_primitives[int(d["primitive"])], _convert_old_array(d["arrays"]), morph_arrays);
  1004. } else if (d.has("array_data")) {
  1005. //print_line("array data (old style");
  1006. //older format (3.x)
  1007. Vector<uint8_t> array_data = d["array_data"];
  1008. Vector<uint8_t> array_index_data;
  1009. if (d.has("array_index_data")) {
  1010. array_index_data = d["array_index_data"];
  1011. }
  1012. ERR_FAIL_COND_V(!d.has("format"), false);
  1013. uint32_t old_format = d["format"];
  1014. uint32_t primitive = d["primitive"];
  1015. primitive = _old_primitives[primitive]; //compatibility
  1016. ERR_FAIL_COND_V(!d.has("vertex_count"), false);
  1017. int vertex_count = d["vertex_count"];
  1018. uint32_t new_format = ARRAY_FORMAT_VERTEX;
  1019. if (old_format & OLD_ARRAY_FORMAT_NORMAL) {
  1020. new_format |= ARRAY_FORMAT_NORMAL;
  1021. }
  1022. if (old_format & OLD_ARRAY_FORMAT_TANGENT) {
  1023. new_format |= ARRAY_FORMAT_TANGENT;
  1024. }
  1025. if (old_format & OLD_ARRAY_FORMAT_COLOR) {
  1026. new_format |= ARRAY_FORMAT_COLOR;
  1027. }
  1028. if (old_format & OLD_ARRAY_FORMAT_TEX_UV) {
  1029. new_format |= ARRAY_FORMAT_TEX_UV;
  1030. }
  1031. if (old_format & OLD_ARRAY_FORMAT_TEX_UV2) {
  1032. new_format |= ARRAY_FORMAT_TEX_UV2;
  1033. }
  1034. if (old_format & OLD_ARRAY_FORMAT_BONES) {
  1035. new_format |= ARRAY_FORMAT_BONES;
  1036. }
  1037. if (old_format & OLD_ARRAY_FORMAT_WEIGHTS) {
  1038. new_format |= ARRAY_FORMAT_WEIGHTS;
  1039. }
  1040. if (old_format & OLD_ARRAY_FORMAT_INDEX) {
  1041. new_format |= ARRAY_FORMAT_INDEX;
  1042. }
  1043. if (old_format & OLD_ARRAY_FLAG_USE_2D_VERTICES) {
  1044. new_format |= OLD_ARRAY_FLAG_USE_2D_VERTICES;
  1045. }
  1046. Vector<uint8_t> vertex_array;
  1047. Vector<uint8_t> attribute_array;
  1048. Vector<uint8_t> skin_array;
  1049. _fix_array_compatibility(array_data, old_format, new_format, vertex_count, vertex_array, attribute_array, skin_array);
  1050. int index_count = 0;
  1051. if (d.has("index_count")) {
  1052. index_count = d["index_count"];
  1053. }
  1054. Vector<uint8_t> blend_shapes_new;
  1055. if (d.has("blend_shape_data")) {
  1056. Array blend_shape_data = d["blend_shape_data"];
  1057. for (int i = 0; i < blend_shape_data.size(); i++) {
  1058. Vector<uint8_t> blend_vertex_array;
  1059. Vector<uint8_t> blend_attribute_array;
  1060. Vector<uint8_t> blend_skin_array;
  1061. Vector<uint8_t> shape = blend_shape_data[i];
  1062. _fix_array_compatibility(shape, old_format, new_format, vertex_count, blend_vertex_array, blend_attribute_array, blend_skin_array);
  1063. blend_shapes_new.append_array(blend_vertex_array);
  1064. }
  1065. }
  1066. //clear unused flags
  1067. print_verbose("Mesh format pre-conversion: " + itos(old_format));
  1068. print_verbose("Mesh format post-conversion: " + itos(new_format));
  1069. ERR_FAIL_COND_V(!d.has("aabb"), false);
  1070. AABB aabb_new = d["aabb"];
  1071. Vector<AABB> bone_aabb;
  1072. if (d.has("skeleton_aabb")) {
  1073. Array baabb = d["skeleton_aabb"];
  1074. bone_aabb.resize(baabb.size());
  1075. for (int i = 0; i < baabb.size(); i++) {
  1076. bone_aabb.write[i] = baabb[i];
  1077. }
  1078. }
  1079. add_surface(new_format, PrimitiveType(primitive), vertex_array, attribute_array, skin_array, vertex_count, array_index_data, index_count, aabb_new, blend_shapes_new, bone_aabb);
  1080. } else {
  1081. ERR_FAIL_V(false);
  1082. }
  1083. if (d.has("material")) {
  1084. surface_set_material(idx, d["material"]);
  1085. }
  1086. if (d.has("name")) {
  1087. surface_set_name(idx, d["name"]);
  1088. }
  1089. return true;
  1090. }
  1091. #endif // DISABLE_DEPRECATED
  1092. return false;
  1093. }
  1094. void ArrayMesh::_set_blend_shape_names(const PackedStringArray &p_names) {
  1095. ERR_FAIL_COND(surfaces.size() > 0);
  1096. blend_shapes.resize(p_names.size());
  1097. for (int i = 0; i < p_names.size(); i++) {
  1098. blend_shapes.write[i] = p_names[i];
  1099. }
  1100. if (mesh.is_valid()) {
  1101. RS::get_singleton()->mesh_set_blend_shape_count(mesh, blend_shapes.size());
  1102. }
  1103. }
  1104. PackedStringArray ArrayMesh::_get_blend_shape_names() const {
  1105. PackedStringArray sarr;
  1106. sarr.resize(blend_shapes.size());
  1107. for (int i = 0; i < blend_shapes.size(); i++) {
  1108. sarr.write[i] = blend_shapes[i];
  1109. }
  1110. return sarr;
  1111. }
  1112. Array ArrayMesh::_get_surfaces() const {
  1113. if (mesh.is_null()) {
  1114. return Array();
  1115. }
  1116. Array ret;
  1117. for (int i = 0; i < surfaces.size(); i++) {
  1118. RenderingServer::SurfaceData surface = RS::get_singleton()->mesh_get_surface(mesh, i);
  1119. Dictionary data;
  1120. data["format"] = surface.format;
  1121. data["primitive"] = surface.primitive;
  1122. data["vertex_data"] = surface.vertex_data;
  1123. data["vertex_count"] = surface.vertex_count;
  1124. if (surface.skin_data.size()) {
  1125. data["skin_data"] = surface.skin_data;
  1126. }
  1127. if (surface.attribute_data.size()) {
  1128. data["attribute_data"] = surface.attribute_data;
  1129. }
  1130. data["aabb"] = surface.aabb;
  1131. if (surface.index_count) {
  1132. data["index_data"] = surface.index_data;
  1133. data["index_count"] = surface.index_count;
  1134. };
  1135. Array lods;
  1136. for (int j = 0; j < surface.lods.size(); j++) {
  1137. lods.push_back(surface.lods[j].edge_length);
  1138. lods.push_back(surface.lods[j].index_data);
  1139. }
  1140. if (lods.size()) {
  1141. data["lods"] = lods;
  1142. }
  1143. Array bone_aabbs;
  1144. for (int j = 0; j < surface.bone_aabbs.size(); j++) {
  1145. bone_aabbs.push_back(surface.bone_aabbs[j]);
  1146. }
  1147. if (bone_aabbs.size()) {
  1148. data["bone_aabbs"] = bone_aabbs;
  1149. }
  1150. if (surface.blend_shape_data.size()) {
  1151. data["blend_shapes"] = surface.blend_shape_data;
  1152. }
  1153. if (surfaces[i].material.is_valid()) {
  1154. data["material"] = surfaces[i].material;
  1155. }
  1156. if (!surfaces[i].name.is_empty()) {
  1157. data["name"] = surfaces[i].name;
  1158. }
  1159. if (surfaces[i].is_2d) {
  1160. data["2d"] = true;
  1161. }
  1162. ret.push_back(data);
  1163. }
  1164. return ret;
  1165. }
  1166. void ArrayMesh::_create_if_empty() const {
  1167. if (!mesh.is_valid()) {
  1168. mesh = RS::get_singleton()->mesh_create();
  1169. RS::get_singleton()->mesh_set_blend_shape_mode(mesh, (RS::BlendShapeMode)blend_shape_mode);
  1170. RS::get_singleton()->mesh_set_blend_shape_count(mesh, blend_shapes.size());
  1171. }
  1172. }
  1173. void ArrayMesh::_set_surfaces(const Array &p_surfaces) {
  1174. Vector<RS::SurfaceData> surface_data;
  1175. Vector<Ref<Material>> surface_materials;
  1176. Vector<String> surface_names;
  1177. Vector<bool> surface_2d;
  1178. for (int i = 0; i < p_surfaces.size(); i++) {
  1179. RS::SurfaceData surface;
  1180. Dictionary d = p_surfaces[i];
  1181. ERR_FAIL_COND(!d.has("format"));
  1182. ERR_FAIL_COND(!d.has("primitive"));
  1183. ERR_FAIL_COND(!d.has("vertex_data"));
  1184. ERR_FAIL_COND(!d.has("vertex_count"));
  1185. ERR_FAIL_COND(!d.has("aabb"));
  1186. surface.format = d["format"];
  1187. surface.primitive = RS::PrimitiveType(int(d["primitive"]));
  1188. surface.vertex_data = d["vertex_data"];
  1189. surface.vertex_count = d["vertex_count"];
  1190. if (d.has("attribute_data")) {
  1191. surface.attribute_data = d["attribute_data"];
  1192. }
  1193. if (d.has("skin_data")) {
  1194. surface.skin_data = d["skin_data"];
  1195. }
  1196. surface.aabb = d["aabb"];
  1197. if (d.has("index_data")) {
  1198. ERR_FAIL_COND(!d.has("index_count"));
  1199. surface.index_data = d["index_data"];
  1200. surface.index_count = d["index_count"];
  1201. }
  1202. if (d.has("lods")) {
  1203. Array lods = d["lods"];
  1204. ERR_FAIL_COND(lods.size() & 1); //must be even
  1205. for (int j = 0; j < lods.size(); j += 2) {
  1206. RS::SurfaceData::LOD lod;
  1207. lod.edge_length = lods[j + 0];
  1208. lod.index_data = lods[j + 1];
  1209. surface.lods.push_back(lod);
  1210. }
  1211. }
  1212. if (d.has("bone_aabbs")) {
  1213. Array bone_aabbs = d["bone_aabbs"];
  1214. for (int j = 0; j < bone_aabbs.size(); j++) {
  1215. surface.bone_aabbs.push_back(bone_aabbs[j]);
  1216. }
  1217. }
  1218. if (d.has("blend_shapes")) {
  1219. surface.blend_shape_data = d["blend_shapes"];
  1220. }
  1221. Ref<Material> material;
  1222. if (d.has("material")) {
  1223. material = d["material"];
  1224. if (material.is_valid()) {
  1225. surface.material = material->get_rid();
  1226. }
  1227. }
  1228. String surf_name;
  1229. if (d.has("name")) {
  1230. surf_name = d["name"];
  1231. }
  1232. bool _2d = false;
  1233. if (d.has("2d")) {
  1234. _2d = d["2d"];
  1235. }
  1236. surface_data.push_back(surface);
  1237. surface_materials.push_back(material);
  1238. surface_names.push_back(surf_name);
  1239. surface_2d.push_back(_2d);
  1240. }
  1241. if (mesh.is_valid()) {
  1242. //if mesh exists, it needs to be updated
  1243. RS::get_singleton()->mesh_clear(mesh);
  1244. for (int i = 0; i < surface_data.size(); i++) {
  1245. RS::get_singleton()->mesh_add_surface(mesh, surface_data[i]);
  1246. }
  1247. } else {
  1248. // if mesh does not exist (first time this is loaded, most likely),
  1249. // we can create it with a single call, which is a lot more efficient and thread friendly
  1250. mesh = RS::get_singleton()->mesh_create_from_surfaces(surface_data, blend_shapes.size());
  1251. RS::get_singleton()->mesh_set_blend_shape_mode(mesh, (RS::BlendShapeMode)blend_shape_mode);
  1252. }
  1253. surfaces.clear();
  1254. aabb = AABB();
  1255. for (int i = 0; i < surface_data.size(); i++) {
  1256. Surface s;
  1257. s.aabb = surface_data[i].aabb;
  1258. if (i == 0) {
  1259. aabb = s.aabb;
  1260. } else {
  1261. aabb.merge_with(s.aabb);
  1262. }
  1263. s.material = surface_materials[i];
  1264. s.is_2d = surface_2d[i];
  1265. s.name = surface_names[i];
  1266. s.format = surface_data[i].format;
  1267. s.primitive = PrimitiveType(surface_data[i].primitive);
  1268. s.array_length = surface_data[i].vertex_count;
  1269. s.index_array_length = surface_data[i].index_count;
  1270. surfaces.push_back(s);
  1271. }
  1272. }
  1273. bool ArrayMesh::_get(const StringName &p_name, Variant &r_ret) const {
  1274. if (_is_generated()) {
  1275. return false;
  1276. }
  1277. String sname = p_name;
  1278. if (sname.begins_with("surface_")) {
  1279. int sl = sname.find("/");
  1280. if (sl == -1) {
  1281. return false;
  1282. }
  1283. int idx = sname.substr(8, sl - 8).to_int();
  1284. String what = sname.get_slicec('/', 1);
  1285. if (what == "material") {
  1286. r_ret = surface_get_material(idx);
  1287. } else if (what == "name") {
  1288. r_ret = surface_get_name(idx);
  1289. }
  1290. return true;
  1291. }
  1292. return true;
  1293. }
  1294. void ArrayMesh::reset_state() {
  1295. clear_surfaces();
  1296. clear_blend_shapes();
  1297. aabb = AABB();
  1298. blend_shape_mode = BLEND_SHAPE_MODE_RELATIVE;
  1299. custom_aabb = AABB();
  1300. }
  1301. void ArrayMesh::_get_property_list(List<PropertyInfo> *p_list) const {
  1302. if (_is_generated()) {
  1303. return;
  1304. }
  1305. for (int i = 0; i < surfaces.size(); i++) {
  1306. p_list->push_back(PropertyInfo(Variant::STRING, "surface_" + itos(i) + "/name", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR));
  1307. if (surfaces[i].is_2d) {
  1308. p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "CanvasItemMaterial,ShaderMaterial", PROPERTY_USAGE_EDITOR));
  1309. } else {
  1310. p_list->push_back(PropertyInfo(Variant::OBJECT, "surface_" + itos(i) + "/material", PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial", PROPERTY_USAGE_EDITOR));
  1311. }
  1312. }
  1313. }
  1314. void ArrayMesh::_recompute_aabb() {
  1315. // regenerate AABB
  1316. aabb = AABB();
  1317. for (int i = 0; i < surfaces.size(); i++) {
  1318. if (i == 0) {
  1319. aabb = surfaces[i].aabb;
  1320. } else {
  1321. aabb.merge_with(surfaces[i].aabb);
  1322. }
  1323. }
  1324. }
  1325. // TODO: Need to add binding to add_surface using future MeshSurfaceData object.
  1326. void ArrayMesh::add_surface(BitField<ArrayFormat> p_format, PrimitiveType p_primitive, const Vector<uint8_t> &p_array, const Vector<uint8_t> &p_attribute_array, const Vector<uint8_t> &p_skin_array, int p_vertex_count, const Vector<uint8_t> &p_index_array, int p_index_count, const AABB &p_aabb, const Vector<uint8_t> &p_blend_shape_data, const Vector<AABB> &p_bone_aabbs, const Vector<RS::SurfaceData::LOD> &p_lods) {
  1327. ERR_FAIL_COND(surfaces.size() == RS::MAX_MESH_SURFACES);
  1328. _create_if_empty();
  1329. Surface s;
  1330. s.aabb = p_aabb;
  1331. s.is_2d = p_format & ARRAY_FLAG_USE_2D_VERTICES;
  1332. s.primitive = p_primitive;
  1333. s.array_length = p_vertex_count;
  1334. s.index_array_length = p_index_count;
  1335. s.format = p_format;
  1336. surfaces.push_back(s);
  1337. _recompute_aabb();
  1338. RS::SurfaceData sd;
  1339. sd.format = p_format;
  1340. sd.primitive = RS::PrimitiveType(p_primitive);
  1341. sd.aabb = p_aabb;
  1342. sd.vertex_count = p_vertex_count;
  1343. sd.vertex_data = p_array;
  1344. sd.attribute_data = p_attribute_array;
  1345. sd.skin_data = p_skin_array;
  1346. sd.index_count = p_index_count;
  1347. sd.index_data = p_index_array;
  1348. sd.blend_shape_data = p_blend_shape_data;
  1349. sd.bone_aabbs = p_bone_aabbs;
  1350. sd.lods = p_lods;
  1351. RenderingServer::get_singleton()->mesh_add_surface(mesh, sd);
  1352. clear_cache();
  1353. notify_property_list_changed();
  1354. emit_changed();
  1355. }
  1356. void ArrayMesh::add_surface_from_arrays(PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes, const Dictionary &p_lods, BitField<ArrayFormat> p_flags) {
  1357. ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size());
  1358. ERR_FAIL_COND(p_arrays.size() != ARRAY_MAX);
  1359. RS::SurfaceData surface;
  1360. 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);
  1361. ERR_FAIL_COND(err != OK);
  1362. /* Debug code.
  1363. print_line("format: " + itos(surface.format));
  1364. print_line("aabb: " + surface.aabb);
  1365. print_line("array size: " + itos(surface.vertex_data.size()));
  1366. print_line("vertex count: " + itos(surface.vertex_count));
  1367. print_line("index size: " + itos(surface.index_data.size()));
  1368. print_line("index count: " + itos(surface.index_count));
  1369. print_line("primitive: " + itos(surface.primitive));
  1370. */
  1371. add_surface(surface.format, PrimitiveType(surface.primitive), surface.vertex_data, surface.attribute_data, surface.skin_data, surface.vertex_count, surface.index_data, surface.index_count, surface.aabb, surface.blend_shape_data, surface.bone_aabbs, surface.lods);
  1372. }
  1373. Array ArrayMesh::surface_get_arrays(int p_surface) const {
  1374. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  1375. return RenderingServer::get_singleton()->mesh_surface_get_arrays(mesh, p_surface);
  1376. }
  1377. TypedArray<Array> ArrayMesh::surface_get_blend_shape_arrays(int p_surface) const {
  1378. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), TypedArray<Array>());
  1379. return RenderingServer::get_singleton()->mesh_surface_get_blend_shape_arrays(mesh, p_surface);
  1380. }
  1381. Dictionary ArrayMesh::surface_get_lods(int p_surface) const {
  1382. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Dictionary());
  1383. return RenderingServer::get_singleton()->mesh_surface_get_lods(mesh, p_surface);
  1384. }
  1385. int ArrayMesh::get_surface_count() const {
  1386. return surfaces.size();
  1387. }
  1388. void ArrayMesh::add_blend_shape(const StringName &p_name) {
  1389. ERR_FAIL_COND_MSG(surfaces.size(), "Can't add a shape key count if surfaces are already created.");
  1390. StringName shape_name = p_name;
  1391. if (blend_shapes.has(shape_name)) {
  1392. int count = 2;
  1393. do {
  1394. shape_name = String(p_name) + " " + itos(count);
  1395. count++;
  1396. } while (blend_shapes.has(shape_name));
  1397. }
  1398. blend_shapes.push_back(shape_name);
  1399. if (mesh.is_valid()) {
  1400. RS::get_singleton()->mesh_set_blend_shape_count(mesh, blend_shapes.size());
  1401. }
  1402. }
  1403. int ArrayMesh::get_blend_shape_count() const {
  1404. return blend_shapes.size();
  1405. }
  1406. StringName ArrayMesh::get_blend_shape_name(int p_index) const {
  1407. ERR_FAIL_INDEX_V(p_index, blend_shapes.size(), StringName());
  1408. return blend_shapes[p_index];
  1409. }
  1410. void ArrayMesh::set_blend_shape_name(int p_index, const StringName &p_name) {
  1411. ERR_FAIL_INDEX(p_index, blend_shapes.size());
  1412. StringName shape_name = p_name;
  1413. int found = blend_shapes.find(shape_name);
  1414. if (found != -1 && found != p_index) {
  1415. int count = 2;
  1416. do {
  1417. shape_name = String(p_name) + " " + itos(count);
  1418. count++;
  1419. } while (blend_shapes.find(shape_name) != -1);
  1420. }
  1421. blend_shapes.write[p_index] = shape_name;
  1422. }
  1423. void ArrayMesh::clear_blend_shapes() {
  1424. ERR_FAIL_COND_MSG(surfaces.size(), "Can't set shape key count if surfaces are already created.");
  1425. blend_shapes.clear();
  1426. if (mesh.is_valid()) {
  1427. RS::get_singleton()->mesh_set_blend_shape_count(mesh, 0);
  1428. }
  1429. }
  1430. void ArrayMesh::set_blend_shape_mode(BlendShapeMode p_mode) {
  1431. blend_shape_mode = p_mode;
  1432. if (mesh.is_valid()) {
  1433. RS::get_singleton()->mesh_set_blend_shape_mode(mesh, (RS::BlendShapeMode)p_mode);
  1434. }
  1435. }
  1436. ArrayMesh::BlendShapeMode ArrayMesh::get_blend_shape_mode() const {
  1437. return blend_shape_mode;
  1438. }
  1439. int ArrayMesh::surface_get_array_len(int p_idx) const {
  1440. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), -1);
  1441. return surfaces[p_idx].array_length;
  1442. }
  1443. int ArrayMesh::surface_get_array_index_len(int p_idx) const {
  1444. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), -1);
  1445. return surfaces[p_idx].index_array_length;
  1446. }
  1447. BitField<Mesh::ArrayFormat> ArrayMesh::surface_get_format(int p_idx) const {
  1448. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), 0);
  1449. return surfaces[p_idx].format;
  1450. }
  1451. ArrayMesh::PrimitiveType ArrayMesh::surface_get_primitive_type(int p_idx) const {
  1452. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), PRIMITIVE_LINES);
  1453. return surfaces[p_idx].primitive;
  1454. }
  1455. void ArrayMesh::surface_set_material(int p_idx, const Ref<Material> &p_material) {
  1456. ERR_FAIL_INDEX(p_idx, surfaces.size());
  1457. if (surfaces[p_idx].material == p_material) {
  1458. return;
  1459. }
  1460. surfaces.write[p_idx].material = p_material;
  1461. RenderingServer::get_singleton()->mesh_surface_set_material(mesh, p_idx, p_material.is_null() ? RID() : p_material->get_rid());
  1462. emit_changed();
  1463. }
  1464. int ArrayMesh::surface_find_by_name(const String &p_name) const {
  1465. for (int i = 0; i < surfaces.size(); i++) {
  1466. if (surfaces[i].name == p_name) {
  1467. return i;
  1468. }
  1469. }
  1470. return -1;
  1471. }
  1472. void ArrayMesh::surface_set_name(int p_idx, const String &p_name) {
  1473. ERR_FAIL_INDEX(p_idx, surfaces.size());
  1474. surfaces.write[p_idx].name = p_name;
  1475. emit_changed();
  1476. }
  1477. String ArrayMesh::surface_get_name(int p_idx) const {
  1478. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), String());
  1479. return surfaces[p_idx].name;
  1480. }
  1481. void ArrayMesh::surface_update_vertex_region(int p_surface, int p_offset, const Vector<uint8_t> &p_data) {
  1482. ERR_FAIL_INDEX(p_surface, surfaces.size());
  1483. RS::get_singleton()->mesh_surface_update_vertex_region(mesh, p_surface, p_offset, p_data);
  1484. emit_changed();
  1485. }
  1486. void ArrayMesh::surface_update_attribute_region(int p_surface, int p_offset, const Vector<uint8_t> &p_data) {
  1487. ERR_FAIL_INDEX(p_surface, surfaces.size());
  1488. RS::get_singleton()->mesh_surface_update_attribute_region(mesh, p_surface, p_offset, p_data);
  1489. emit_changed();
  1490. }
  1491. void ArrayMesh::surface_update_skin_region(int p_surface, int p_offset, const Vector<uint8_t> &p_data) {
  1492. ERR_FAIL_INDEX(p_surface, surfaces.size());
  1493. RS::get_singleton()->mesh_surface_update_skin_region(mesh, p_surface, p_offset, p_data);
  1494. emit_changed();
  1495. }
  1496. void ArrayMesh::surface_set_custom_aabb(int p_idx, const AABB &p_aabb) {
  1497. ERR_FAIL_INDEX(p_idx, surfaces.size());
  1498. surfaces.write[p_idx].aabb = p_aabb;
  1499. // set custom aabb too?
  1500. emit_changed();
  1501. }
  1502. Ref<Material> ArrayMesh::surface_get_material(int p_idx) const {
  1503. ERR_FAIL_INDEX_V(p_idx, surfaces.size(), Ref<Material>());
  1504. return surfaces[p_idx].material;
  1505. }
  1506. RID ArrayMesh::get_rid() const {
  1507. _create_if_empty();
  1508. return mesh;
  1509. }
  1510. AABB ArrayMesh::get_aabb() const {
  1511. return aabb;
  1512. }
  1513. void ArrayMesh::clear_surfaces() {
  1514. if (!mesh.is_valid()) {
  1515. return;
  1516. }
  1517. RS::get_singleton()->mesh_clear(mesh);
  1518. surfaces.clear();
  1519. aabb = AABB();
  1520. }
  1521. void ArrayMesh::set_custom_aabb(const AABB &p_custom) {
  1522. _create_if_empty();
  1523. custom_aabb = p_custom;
  1524. RS::get_singleton()->mesh_set_custom_aabb(mesh, custom_aabb);
  1525. emit_changed();
  1526. }
  1527. AABB ArrayMesh::get_custom_aabb() const {
  1528. return custom_aabb;
  1529. }
  1530. void ArrayMesh::regen_normal_maps() {
  1531. if (surfaces.size() == 0) {
  1532. return;
  1533. }
  1534. Vector<Ref<SurfaceTool>> surfs;
  1535. for (int i = 0; i < get_surface_count(); i++) {
  1536. Ref<SurfaceTool> st = memnew(SurfaceTool);
  1537. st->create_from(Ref<ArrayMesh>(this), i);
  1538. surfs.push_back(st);
  1539. }
  1540. clear_surfaces();
  1541. for (int i = 0; i < surfs.size(); i++) {
  1542. surfs.write[i]->generate_tangents();
  1543. surfs.write[i]->commit(Ref<ArrayMesh>(this));
  1544. }
  1545. }
  1546. //dirty hack
  1547. 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, const uint8_t *p_cache_data, bool *r_use_cache, uint8_t **r_mesh_cache, int *r_mesh_cache_size, 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) = nullptr;
  1548. struct ArrayMeshLightmapSurface {
  1549. Ref<Material> material;
  1550. LocalVector<SurfaceTool::Vertex> vertices;
  1551. Mesh::PrimitiveType primitive = Mesh::PrimitiveType::PRIMITIVE_MAX;
  1552. uint32_t format = 0;
  1553. };
  1554. Error ArrayMesh::lightmap_unwrap(const Transform3D &p_base_transform, float p_texel_size) {
  1555. Vector<uint8_t> null_cache;
  1556. return lightmap_unwrap_cached(p_base_transform, p_texel_size, null_cache, null_cache, false);
  1557. }
  1558. Error ArrayMesh::lightmap_unwrap_cached(const Transform3D &p_base_transform, float p_texel_size, const Vector<uint8_t> &p_src_cache, Vector<uint8_t> &r_dst_cache, bool p_generate_cache) {
  1559. ERR_FAIL_COND_V(!array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
  1560. ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
  1561. ERR_FAIL_COND_V_MSG(p_texel_size <= 0.0f, ERR_PARAMETER_RANGE_ERROR, "Texel size must be greater than 0.");
  1562. LocalVector<float> vertices;
  1563. LocalVector<float> normals;
  1564. LocalVector<int> indices;
  1565. LocalVector<float> uv;
  1566. LocalVector<Pair<int, int>> uv_indices;
  1567. Vector<ArrayMeshLightmapSurface> lightmap_surfaces;
  1568. // Keep only the scale
  1569. Basis basis = p_base_transform.get_basis();
  1570. Vector3 scale = Vector3(basis.get_column(0).length(), basis.get_column(1).length(), basis.get_column(2).length());
  1571. Transform3D transform;
  1572. transform.scale(scale);
  1573. Basis normal_basis = transform.basis.inverse().transposed();
  1574. for (int i = 0; i < get_surface_count(); i++) {
  1575. ArrayMeshLightmapSurface s;
  1576. s.primitive = surface_get_primitive_type(i);
  1577. ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");
  1578. s.format = surface_get_format(i);
  1579. ERR_FAIL_COND_V_MSG(!(s.format & ARRAY_FORMAT_NORMAL), ERR_UNAVAILABLE, "Normals are required for lightmap unwrap.");
  1580. Array arrays = surface_get_arrays(i);
  1581. s.material = surface_get_material(i);
  1582. SurfaceTool::create_vertex_array_from_triangle_arrays(arrays, s.vertices, &s.format);
  1583. PackedVector3Array rvertices = arrays[Mesh::ARRAY_VERTEX];
  1584. int vc = rvertices.size();
  1585. PackedVector3Array rnormals = arrays[Mesh::ARRAY_NORMAL];
  1586. int vertex_ofs = vertices.size() / 3;
  1587. vertices.resize((vertex_ofs + vc) * 3);
  1588. normals.resize((vertex_ofs + vc) * 3);
  1589. uv_indices.resize(vertex_ofs + vc);
  1590. for (int j = 0; j < vc; j++) {
  1591. Vector3 v = transform.xform(rvertices[j]);
  1592. Vector3 n = normal_basis.xform(rnormals[j]).normalized();
  1593. vertices[(j + vertex_ofs) * 3 + 0] = v.x;
  1594. vertices[(j + vertex_ofs) * 3 + 1] = v.y;
  1595. vertices[(j + vertex_ofs) * 3 + 2] = v.z;
  1596. normals[(j + vertex_ofs) * 3 + 0] = n.x;
  1597. normals[(j + vertex_ofs) * 3 + 1] = n.y;
  1598. normals[(j + vertex_ofs) * 3 + 2] = n.z;
  1599. uv_indices[j + vertex_ofs] = Pair<int, int>(i, j);
  1600. }
  1601. PackedInt32Array rindices = arrays[Mesh::ARRAY_INDEX];
  1602. int ic = rindices.size();
  1603. float eps = 1.19209290e-7F; // Taken from xatlas.h
  1604. if (ic == 0) {
  1605. for (int j = 0; j < vc / 3; j++) {
  1606. Vector3 p0 = transform.xform(rvertices[j * 3 + 0]);
  1607. Vector3 p1 = transform.xform(rvertices[j * 3 + 1]);
  1608. Vector3 p2 = transform.xform(rvertices[j * 3 + 2]);
  1609. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  1610. continue;
  1611. }
  1612. indices.push_back(vertex_ofs + j * 3 + 0);
  1613. indices.push_back(vertex_ofs + j * 3 + 1);
  1614. indices.push_back(vertex_ofs + j * 3 + 2);
  1615. }
  1616. } else {
  1617. for (int j = 0; j < ic / 3; j++) {
  1618. Vector3 p0 = transform.xform(rvertices[rindices[j * 3 + 0]]);
  1619. Vector3 p1 = transform.xform(rvertices[rindices[j * 3 + 1]]);
  1620. Vector3 p2 = transform.xform(rvertices[rindices[j * 3 + 2]]);
  1621. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  1622. continue;
  1623. }
  1624. indices.push_back(vertex_ofs + rindices[j * 3 + 0]);
  1625. indices.push_back(vertex_ofs + rindices[j * 3 + 1]);
  1626. indices.push_back(vertex_ofs + rindices[j * 3 + 2]);
  1627. }
  1628. }
  1629. lightmap_surfaces.push_back(s);
  1630. }
  1631. //unwrap
  1632. bool use_cache = p_generate_cache; // Used to request cache generation and to know if cache was used
  1633. uint8_t *gen_cache;
  1634. int gen_cache_size;
  1635. float *gen_uvs;
  1636. int *gen_vertices;
  1637. int *gen_indices;
  1638. int gen_vertex_count;
  1639. int gen_index_count;
  1640. int size_x;
  1641. int size_y;
  1642. bool ok = array_mesh_lightmap_unwrap_callback(p_texel_size, vertices.ptr(), normals.ptr(), vertices.size() / 3, indices.ptr(), indices.size(), p_src_cache.ptr(), &use_cache, &gen_cache, &gen_cache_size, &gen_uvs, &gen_vertices, &gen_vertex_count, &gen_indices, &gen_index_count, &size_x, &size_y);
  1643. if (!ok) {
  1644. return ERR_CANT_CREATE;
  1645. }
  1646. clear_surfaces();
  1647. //create surfacetools for each surface..
  1648. LocalVector<Ref<SurfaceTool>> surfaces_tools;
  1649. for (int i = 0; i < lightmap_surfaces.size(); i++) {
  1650. Ref<SurfaceTool> st;
  1651. st.instantiate();
  1652. st->begin(Mesh::PRIMITIVE_TRIANGLES);
  1653. st->set_material(lightmap_surfaces[i].material);
  1654. surfaces_tools.push_back(st); //stay there
  1655. }
  1656. print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
  1657. //go through all indices
  1658. for (int i = 0; i < gen_index_count; i += 3) {
  1659. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], (int)uv_indices.size(), ERR_BUG);
  1660. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], (int)uv_indices.size(), ERR_BUG);
  1661. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], (int)uv_indices.size(), ERR_BUG);
  1662. 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);
  1663. int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;
  1664. for (int j = 0; j < 3; j++) {
  1665. SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];
  1666. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_COLOR) {
  1667. surfaces_tools[surface]->set_color(v.color);
  1668. }
  1669. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_TEX_UV) {
  1670. surfaces_tools[surface]->set_uv(v.uv);
  1671. }
  1672. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_NORMAL) {
  1673. surfaces_tools[surface]->set_normal(v.normal);
  1674. }
  1675. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_TANGENT) {
  1676. Plane t;
  1677. t.normal = v.tangent;
  1678. t.d = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;
  1679. surfaces_tools[surface]->set_tangent(t);
  1680. }
  1681. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_BONES) {
  1682. surfaces_tools[surface]->set_bones(v.bones);
  1683. }
  1684. if (lightmap_surfaces[surface].format & ARRAY_FORMAT_WEIGHTS) {
  1685. surfaces_tools[surface]->set_weights(v.weights);
  1686. }
  1687. Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
  1688. surfaces_tools[surface]->set_uv2(uv2);
  1689. surfaces_tools[surface]->add_vertex(v.vertex);
  1690. }
  1691. }
  1692. //generate surfaces
  1693. for (unsigned int i = 0; i < surfaces_tools.size(); i++) {
  1694. surfaces_tools[i]->index();
  1695. surfaces_tools[i]->commit(Ref<ArrayMesh>((ArrayMesh *)this), lightmap_surfaces[i].format);
  1696. }
  1697. set_lightmap_size_hint(Size2(size_x, size_y));
  1698. if (gen_cache_size > 0) {
  1699. r_dst_cache.resize(gen_cache_size);
  1700. memcpy(r_dst_cache.ptrw(), gen_cache, gen_cache_size);
  1701. memfree(gen_cache);
  1702. }
  1703. if (!use_cache) {
  1704. // Cache was not used, free the buffers
  1705. memfree(gen_vertices);
  1706. memfree(gen_indices);
  1707. memfree(gen_uvs);
  1708. }
  1709. return OK;
  1710. }
  1711. void ArrayMesh::set_shadow_mesh(const Ref<ArrayMesh> &p_mesh) {
  1712. shadow_mesh = p_mesh;
  1713. if (shadow_mesh.is_valid()) {
  1714. RS::get_singleton()->mesh_set_shadow_mesh(mesh, shadow_mesh->get_rid());
  1715. } else {
  1716. RS::get_singleton()->mesh_set_shadow_mesh(mesh, RID());
  1717. }
  1718. }
  1719. Ref<ArrayMesh> ArrayMesh::get_shadow_mesh() const {
  1720. return shadow_mesh;
  1721. }
  1722. void ArrayMesh::_bind_methods() {
  1723. ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ArrayMesh::add_blend_shape);
  1724. ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ArrayMesh::get_blend_shape_count);
  1725. ClassDB::bind_method(D_METHOD("get_blend_shape_name", "index"), &ArrayMesh::get_blend_shape_name);
  1726. ClassDB::bind_method(D_METHOD("set_blend_shape_name", "index", "name"), &ArrayMesh::set_blend_shape_name);
  1727. ClassDB::bind_method(D_METHOD("clear_blend_shapes"), &ArrayMesh::clear_blend_shapes);
  1728. ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ArrayMesh::set_blend_shape_mode);
  1729. ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ArrayMesh::get_blend_shape_mode);
  1730. ClassDB::bind_method(D_METHOD("add_surface_from_arrays", "primitive", "arrays", "blend_shapes", "lods", "flags"), &ArrayMesh::add_surface_from_arrays, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(0));
  1731. ClassDB::bind_method(D_METHOD("clear_surfaces"), &ArrayMesh::clear_surfaces);
  1732. ClassDB::bind_method(D_METHOD("surface_update_vertex_region", "surf_idx", "offset", "data"), &ArrayMesh::surface_update_vertex_region);
  1733. ClassDB::bind_method(D_METHOD("surface_update_attribute_region", "surf_idx", "offset", "data"), &ArrayMesh::surface_update_attribute_region);
  1734. ClassDB::bind_method(D_METHOD("surface_update_skin_region", "surf_idx", "offset", "data"), &ArrayMesh::surface_update_skin_region);
  1735. ClassDB::bind_method(D_METHOD("surface_get_array_len", "surf_idx"), &ArrayMesh::surface_get_array_len);
  1736. ClassDB::bind_method(D_METHOD("surface_get_array_index_len", "surf_idx"), &ArrayMesh::surface_get_array_index_len);
  1737. ClassDB::bind_method(D_METHOD("surface_get_format", "surf_idx"), &ArrayMesh::surface_get_format);
  1738. ClassDB::bind_method(D_METHOD("surface_get_primitive_type", "surf_idx"), &ArrayMesh::surface_get_primitive_type);
  1739. ClassDB::bind_method(D_METHOD("surface_find_by_name", "name"), &ArrayMesh::surface_find_by_name);
  1740. ClassDB::bind_method(D_METHOD("surface_set_name", "surf_idx", "name"), &ArrayMesh::surface_set_name);
  1741. ClassDB::bind_method(D_METHOD("surface_get_name", "surf_idx"), &ArrayMesh::surface_get_name);
  1742. ClassDB::bind_method(D_METHOD("create_trimesh_shape"), &ArrayMesh::create_trimesh_shape);
  1743. ClassDB::bind_method(D_METHOD("create_convex_shape", "clean", "simplify"), &ArrayMesh::create_convex_shape, DEFVAL(true), DEFVAL(false));
  1744. ClassDB::bind_method(D_METHOD("create_outline", "margin"), &ArrayMesh::create_outline);
  1745. ClassDB::bind_method(D_METHOD("regen_normal_maps"), &ArrayMesh::regen_normal_maps);
  1746. ClassDB::set_method_flags(get_class_static(), _scs_create("regen_normal_maps"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
  1747. ClassDB::bind_method(D_METHOD("lightmap_unwrap", "transform", "texel_size"), &ArrayMesh::lightmap_unwrap);
  1748. ClassDB::set_method_flags(get_class_static(), _scs_create("lightmap_unwrap"), METHOD_FLAGS_DEFAULT | METHOD_FLAG_EDITOR);
  1749. ClassDB::bind_method(D_METHOD("get_faces"), &ArrayMesh::get_faces);
  1750. ClassDB::bind_method(D_METHOD("generate_triangle_mesh"), &ArrayMesh::generate_triangle_mesh);
  1751. ClassDB::bind_method(D_METHOD("set_custom_aabb", "aabb"), &ArrayMesh::set_custom_aabb);
  1752. ClassDB::bind_method(D_METHOD("get_custom_aabb"), &ArrayMesh::get_custom_aabb);
  1753. ClassDB::bind_method(D_METHOD("set_shadow_mesh", "mesh"), &ArrayMesh::set_shadow_mesh);
  1754. ClassDB::bind_method(D_METHOD("get_shadow_mesh"), &ArrayMesh::get_shadow_mesh);
  1755. ClassDB::bind_method(D_METHOD("_set_blend_shape_names", "blend_shape_names"), &ArrayMesh::_set_blend_shape_names);
  1756. ClassDB::bind_method(D_METHOD("_get_blend_shape_names"), &ArrayMesh::_get_blend_shape_names);
  1757. ClassDB::bind_method(D_METHOD("_set_surfaces", "surfaces"), &ArrayMesh::_set_surfaces);
  1758. ClassDB::bind_method(D_METHOD("_get_surfaces"), &ArrayMesh::_get_surfaces);
  1759. ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "_blend_shape_names", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_blend_shape_names", "_get_blend_shape_names");
  1760. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "_surfaces", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_surfaces", "_get_surfaces");
  1761. ADD_PROPERTY(PropertyInfo(Variant::INT, "blend_shape_mode", PROPERTY_HINT_ENUM, "Normalized,Relative"), "set_blend_shape_mode", "get_blend_shape_mode");
  1762. ADD_PROPERTY(PropertyInfo(Variant::AABB, "custom_aabb", PROPERTY_HINT_NONE, "suffix:m"), "set_custom_aabb", "get_custom_aabb");
  1763. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "shadow_mesh", PROPERTY_HINT_RESOURCE_TYPE, "ArrayMesh"), "set_shadow_mesh", "get_shadow_mesh");
  1764. }
  1765. void ArrayMesh::reload_from_file() {
  1766. RenderingServer::get_singleton()->mesh_clear(mesh);
  1767. surfaces.clear();
  1768. clear_blend_shapes();
  1769. clear_cache();
  1770. Resource::reload_from_file();
  1771. notify_property_list_changed();
  1772. }
  1773. ArrayMesh::ArrayMesh() {
  1774. //mesh is now created on demand
  1775. //mesh = RenderingServer::get_singleton()->mesh_create();
  1776. }
  1777. ArrayMesh::~ArrayMesh() {
  1778. if (mesh.is_valid()) {
  1779. ERR_FAIL_NULL(RenderingServer::get_singleton());
  1780. RenderingServer::get_singleton()->free(mesh);
  1781. }
  1782. }
  1783. ///////////////
  1784. void PlaceholderMesh::_bind_methods() {
  1785. ClassDB::bind_method(D_METHOD("set_aabb", "aabb"), &PlaceholderMesh::set_aabb);
  1786. ADD_PROPERTY(PropertyInfo(Variant::AABB, "aabb", PROPERTY_HINT_NONE, "suffix:m"), "set_aabb", "get_aabb");
  1787. }
  1788. PlaceholderMesh::PlaceholderMesh() {
  1789. rid = RS::get_singleton()->mesh_create();
  1790. }
  1791. PlaceholderMesh::~PlaceholderMesh() {
  1792. ERR_FAIL_NULL(RenderingServer::get_singleton());
  1793. RS::get_singleton()->free(rid);
  1794. }