importer_mesh.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. /**************************************************************************/
  2. /* importer_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 "importer_mesh.h"
  31. #include "core/io/marshalls.h"
  32. #include "core/math/convex_hull.h"
  33. #include "core/math/random_pcg.h"
  34. #include "scene/resources/surface_tool.h"
  35. #include <cstdint>
  36. String ImporterMesh::validate_blend_shape_name(const String &p_name) {
  37. String name = p_name;
  38. const char *characters = ":";
  39. for (const char *p = characters; *p; p++) {
  40. name = name.replace(String::chr(*p), "_");
  41. }
  42. return name;
  43. }
  44. void ImporterMesh::add_blend_shape(const String &p_name) {
  45. ERR_FAIL_COND(surfaces.size() > 0);
  46. blend_shapes.push_back(validate_blend_shape_name(p_name));
  47. }
  48. int ImporterMesh::get_blend_shape_count() const {
  49. return blend_shapes.size();
  50. }
  51. String ImporterMesh::get_blend_shape_name(int p_blend_shape) const {
  52. ERR_FAIL_INDEX_V(p_blend_shape, blend_shapes.size(), String());
  53. return blend_shapes[p_blend_shape];
  54. }
  55. void ImporterMesh::set_blend_shape_mode(Mesh::BlendShapeMode p_blend_shape_mode) {
  56. blend_shape_mode = p_blend_shape_mode;
  57. }
  58. Mesh::BlendShapeMode ImporterMesh::get_blend_shape_mode() const {
  59. return blend_shape_mode;
  60. }
  61. void ImporterMesh::add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes, const Dictionary &p_lods, const Ref<Material> &p_material, const String &p_name, const uint64_t p_flags) {
  62. ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size());
  63. ERR_FAIL_COND(p_arrays.size() != Mesh::ARRAY_MAX);
  64. Surface s;
  65. s.primitive = p_primitive;
  66. s.arrays = p_arrays;
  67. s.name = p_name;
  68. s.flags = p_flags;
  69. Vector<Vector3> vertex_array = p_arrays[Mesh::ARRAY_VERTEX];
  70. int vertex_count = vertex_array.size();
  71. ERR_FAIL_COND(vertex_count == 0);
  72. for (int i = 0; i < blend_shapes.size(); i++) {
  73. Array bsdata = p_blend_shapes[i];
  74. ERR_FAIL_COND(bsdata.size() != Mesh::ARRAY_MAX);
  75. Vector<Vector3> vertex_data = bsdata[Mesh::ARRAY_VERTEX];
  76. ERR_FAIL_COND(vertex_data.size() != vertex_count);
  77. Surface::BlendShape bs;
  78. bs.arrays = bsdata;
  79. s.blend_shape_data.push_back(bs);
  80. }
  81. List<Variant> lods;
  82. p_lods.get_key_list(&lods);
  83. for (const Variant &E : lods) {
  84. ERR_CONTINUE(!E.is_num());
  85. Surface::LOD lod;
  86. lod.distance = E;
  87. lod.indices = p_lods[E];
  88. ERR_CONTINUE(lod.indices.is_empty());
  89. s.lods.push_back(lod);
  90. }
  91. s.material = p_material;
  92. surfaces.push_back(s);
  93. mesh.unref();
  94. }
  95. int ImporterMesh::get_surface_count() const {
  96. return surfaces.size();
  97. }
  98. Mesh::PrimitiveType ImporterMesh::get_surface_primitive_type(int p_surface) {
  99. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Mesh::PRIMITIVE_MAX);
  100. return surfaces[p_surface].primitive;
  101. }
  102. Array ImporterMesh::get_surface_arrays(int p_surface) const {
  103. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  104. return surfaces[p_surface].arrays;
  105. }
  106. String ImporterMesh::get_surface_name(int p_surface) const {
  107. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), String());
  108. return surfaces[p_surface].name;
  109. }
  110. void ImporterMesh::set_surface_name(int p_surface, const String &p_name) {
  111. ERR_FAIL_INDEX(p_surface, surfaces.size());
  112. surfaces.write[p_surface].name = p_name;
  113. mesh.unref();
  114. }
  115. Array ImporterMesh::get_surface_blend_shape_arrays(int p_surface, int p_blend_shape) const {
  116. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  117. ERR_FAIL_INDEX_V(p_blend_shape, surfaces[p_surface].blend_shape_data.size(), Array());
  118. return surfaces[p_surface].blend_shape_data[p_blend_shape].arrays;
  119. }
  120. int ImporterMesh::get_surface_lod_count(int p_surface) const {
  121. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  122. return surfaces[p_surface].lods.size();
  123. }
  124. Vector<int> ImporterMesh::get_surface_lod_indices(int p_surface, int p_lod) const {
  125. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Vector<int>());
  126. ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), Vector<int>());
  127. return surfaces[p_surface].lods[p_lod].indices;
  128. }
  129. float ImporterMesh::get_surface_lod_size(int p_surface, int p_lod) const {
  130. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  131. ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), 0);
  132. return surfaces[p_surface].lods[p_lod].distance;
  133. }
  134. uint64_t ImporterMesh::get_surface_format(int p_surface) const {
  135. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  136. return surfaces[p_surface].flags;
  137. }
  138. Ref<Material> ImporterMesh::get_surface_material(int p_surface) const {
  139. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Ref<Material>());
  140. return surfaces[p_surface].material;
  141. }
  142. void ImporterMesh::set_surface_material(int p_surface, const Ref<Material> &p_material) {
  143. ERR_FAIL_INDEX(p_surface, surfaces.size());
  144. surfaces.write[p_surface].material = p_material;
  145. mesh.unref();
  146. }
  147. template <typename T>
  148. static Vector<T> _remap_array(Vector<T> p_array, const Vector<uint32_t> &p_remap, uint32_t p_vertex_count) {
  149. ERR_FAIL_COND_V(p_array.size() % p_remap.size() != 0, p_array);
  150. int num_elements = p_array.size() / p_remap.size();
  151. T *data = p_array.ptrw();
  152. SurfaceTool::remap_vertex_func(data, data, p_remap.size(), sizeof(T) * num_elements, p_remap.ptr());
  153. p_array.resize(p_vertex_count * num_elements);
  154. return p_array;
  155. }
  156. static void _remap_arrays(Array &r_arrays, const Vector<uint32_t> &p_remap, uint32_t p_vertex_count) {
  157. for (int i = 0; i < r_arrays.size(); i++) {
  158. if (i == RS::ARRAY_INDEX) {
  159. continue;
  160. }
  161. switch (r_arrays[i].get_type()) {
  162. case Variant::NIL:
  163. break;
  164. case Variant::PACKED_VECTOR3_ARRAY:
  165. r_arrays[i] = _remap_array<Vector3>(r_arrays[i], p_remap, p_vertex_count);
  166. break;
  167. case Variant::PACKED_VECTOR2_ARRAY:
  168. r_arrays[i] = _remap_array<Vector2>(r_arrays[i], p_remap, p_vertex_count);
  169. break;
  170. case Variant::PACKED_FLOAT32_ARRAY:
  171. r_arrays[i] = _remap_array<float>(r_arrays[i], p_remap, p_vertex_count);
  172. break;
  173. case Variant::PACKED_INT32_ARRAY:
  174. r_arrays[i] = _remap_array<int32_t>(r_arrays[i], p_remap, p_vertex_count);
  175. break;
  176. case Variant::PACKED_BYTE_ARRAY:
  177. r_arrays[i] = _remap_array<uint8_t>(r_arrays[i], p_remap, p_vertex_count);
  178. break;
  179. case Variant::PACKED_COLOR_ARRAY:
  180. r_arrays[i] = _remap_array<Color>(r_arrays[i], p_remap, p_vertex_count);
  181. break;
  182. default:
  183. ERR_FAIL_MSG("Unhandled array type.");
  184. }
  185. }
  186. }
  187. void ImporterMesh::optimize_indices() {
  188. if (!SurfaceTool::optimize_vertex_cache_func) {
  189. return;
  190. }
  191. if (!SurfaceTool::optimize_vertex_fetch_remap_func || !SurfaceTool::remap_vertex_func || !SurfaceTool::remap_index_func) {
  192. return;
  193. }
  194. for (int i = 0; i < surfaces.size(); i++) {
  195. if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {
  196. continue;
  197. }
  198. Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
  199. PackedInt32Array indices = surfaces[i].arrays[RS::ARRAY_INDEX];
  200. unsigned int index_count = indices.size();
  201. unsigned int vertex_count = vertices.size();
  202. if (index_count == 0) {
  203. continue;
  204. }
  205. // Optimize indices for vertex cache to establish final triangle order.
  206. int *indices_ptr = indices.ptrw();
  207. SurfaceTool::optimize_vertex_cache_func((unsigned int *)indices_ptr, (const unsigned int *)indices_ptr, index_count, vertex_count);
  208. surfaces.write[i].arrays[RS::ARRAY_INDEX] = indices;
  209. for (int j = 0; j < surfaces[i].lods.size(); ++j) {
  210. Surface::LOD &lod = surfaces.write[i].lods.write[j];
  211. int *lod_indices_ptr = lod.indices.ptrw();
  212. SurfaceTool::optimize_vertex_cache_func((unsigned int *)lod_indices_ptr, (const unsigned int *)lod_indices_ptr, lod.indices.size(), vertex_count);
  213. }
  214. // Concatenate indices for all LODs in the order of coarse->fine; this establishes the effective order of vertices,
  215. // and is important to optimize for vertex fetch (all GPUs) and shading (Mali GPUs)
  216. PackedInt32Array merged_indices;
  217. for (int j = surfaces[i].lods.size() - 1; j >= 0; --j) {
  218. merged_indices.append_array(surfaces[i].lods[j].indices);
  219. }
  220. merged_indices.append_array(indices);
  221. // Generate remap array that establishes optimal vertex order according to the order of indices above.
  222. Vector<uint32_t> remap;
  223. remap.resize(vertex_count);
  224. unsigned int new_vertex_count = SurfaceTool::optimize_vertex_fetch_remap_func(remap.ptrw(), (const unsigned int *)merged_indices.ptr(), merged_indices.size(), vertex_count);
  225. // We need to remap all vertex and index arrays in lockstep according to the remap.
  226. SurfaceTool::remap_index_func((unsigned int *)indices_ptr, (const unsigned int *)indices_ptr, index_count, remap.ptr());
  227. surfaces.write[i].arrays[RS::ARRAY_INDEX] = indices;
  228. for (int j = 0; j < surfaces[i].lods.size(); ++j) {
  229. Surface::LOD &lod = surfaces.write[i].lods.write[j];
  230. int *lod_indices_ptr = lod.indices.ptrw();
  231. SurfaceTool::remap_index_func((unsigned int *)lod_indices_ptr, (const unsigned int *)lod_indices_ptr, lod.indices.size(), remap.ptr());
  232. }
  233. _remap_arrays(surfaces.write[i].arrays, remap, new_vertex_count);
  234. for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
  235. _remap_arrays(surfaces.write[i].blend_shape_data.write[j].arrays, remap, new_vertex_count);
  236. }
  237. }
  238. if (shadow_mesh.is_valid()) {
  239. shadow_mesh->optimize_indices();
  240. }
  241. }
  242. #define VERTEX_SKIN_FUNC(bone_count, vert_idx, read_array, write_array, transform_array, bone_array, weight_array) \
  243. Vector3 transformed_vert; \
  244. for (unsigned int weight_idx = 0; weight_idx < bone_count; weight_idx++) { \
  245. int bone_idx = bone_array[vert_idx * bone_count + weight_idx]; \
  246. float w = weight_array[vert_idx * bone_count + weight_idx]; \
  247. if (w < FLT_EPSILON) { \
  248. continue; \
  249. } \
  250. ERR_FAIL_INDEX(bone_idx, static_cast<int>(transform_array.size())); \
  251. transformed_vert += transform_array[bone_idx].xform(read_array[vert_idx]) * w; \
  252. } \
  253. write_array[vert_idx] = transformed_vert;
  254. void ImporterMesh::generate_lods(float p_normal_merge_angle, Array p_bone_transform_array) {
  255. if (!SurfaceTool::simplify_scale_func) {
  256. return;
  257. }
  258. if (!SurfaceTool::simplify_with_attrib_func) {
  259. return;
  260. }
  261. LocalVector<Transform3D> bone_transform_vector;
  262. for (int i = 0; i < p_bone_transform_array.size(); i++) {
  263. ERR_FAIL_COND(p_bone_transform_array[i].get_type() != Variant::TRANSFORM3D);
  264. bone_transform_vector.push_back(p_bone_transform_array[i]);
  265. }
  266. for (int i = 0; i < surfaces.size(); i++) {
  267. if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {
  268. continue;
  269. }
  270. surfaces.write[i].lods.clear();
  271. Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
  272. PackedInt32Array indices = surfaces[i].arrays[RS::ARRAY_INDEX];
  273. Vector<Vector3> normals = surfaces[i].arrays[RS::ARRAY_NORMAL];
  274. Vector<float> tangents = surfaces[i].arrays[RS::ARRAY_TANGENT];
  275. Vector<Vector2> uvs = surfaces[i].arrays[RS::ARRAY_TEX_UV];
  276. Vector<Vector2> uv2s = surfaces[i].arrays[RS::ARRAY_TEX_UV2];
  277. Vector<int> bones = surfaces[i].arrays[RS::ARRAY_BONES];
  278. Vector<float> weights = surfaces[i].arrays[RS::ARRAY_WEIGHTS];
  279. unsigned int index_count = indices.size();
  280. unsigned int vertex_count = vertices.size();
  281. if (index_count == 0) {
  282. continue; //no lods if no indices
  283. }
  284. const Vector3 *vertices_ptr = vertices.ptr();
  285. const int *indices_ptr = indices.ptr();
  286. if (normals.is_empty()) {
  287. normals.resize(index_count);
  288. Vector3 *n_ptr = normals.ptrw();
  289. for (unsigned int j = 0; j < index_count; j += 3) {
  290. const Vector3 &v0 = vertices_ptr[indices_ptr[j + 0]];
  291. const Vector3 &v1 = vertices_ptr[indices_ptr[j + 1]];
  292. const Vector3 &v2 = vertices_ptr[indices_ptr[j + 2]];
  293. Vector3 n = vec3_cross(v0 - v2, v0 - v1).normalized();
  294. n_ptr[j + 0] = n;
  295. n_ptr[j + 1] = n;
  296. n_ptr[j + 2] = n;
  297. }
  298. }
  299. if (bones.size() > 0 && weights.size() && bone_transform_vector.size() > 0) {
  300. Vector3 *vertices_ptrw = vertices.ptrw();
  301. // Apply bone transforms to regular surface.
  302. unsigned int bone_weight_length = surfaces[i].flags & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS ? 8 : 4;
  303. const int *bo = bones.ptr();
  304. const float *we = weights.ptr();
  305. for (unsigned int j = 0; j < vertex_count; j++) {
  306. VERTEX_SKIN_FUNC(bone_weight_length, j, vertices_ptr, vertices_ptrw, bone_transform_vector, bo, we)
  307. }
  308. vertices_ptr = vertices.ptr();
  309. }
  310. float normal_merge_threshold = Math::cos(Math::deg_to_rad(p_normal_merge_angle));
  311. const Vector3 *normals_ptr = normals.ptr();
  312. HashMap<Vector3, LocalVector<Pair<int, int>>> unique_vertices;
  313. LocalVector<int> vertex_remap;
  314. LocalVector<int> vertex_inverse_remap;
  315. LocalVector<Vector3> merged_vertices;
  316. LocalVector<Vector3> merged_normals;
  317. LocalVector<int> merged_normals_counts;
  318. const Vector2 *uvs_ptr = uvs.ptr();
  319. const Vector2 *uv2s_ptr = uv2s.ptr();
  320. const float *tangents_ptr = tangents.ptr();
  321. for (unsigned int j = 0; j < vertex_count; j++) {
  322. const Vector3 &v = vertices_ptr[j];
  323. const Vector3 &n = normals_ptr[j];
  324. HashMap<Vector3, LocalVector<Pair<int, int>>>::Iterator E = unique_vertices.find(v);
  325. if (E) {
  326. const LocalVector<Pair<int, int>> &close_verts = E->value;
  327. bool found = false;
  328. for (const Pair<int, int> &idx : close_verts) {
  329. bool is_uvs_close = (!uvs_ptr || uvs_ptr[j].distance_squared_to(uvs_ptr[idx.second]) < CMP_EPSILON2);
  330. bool is_uv2s_close = (!uv2s_ptr || uv2s_ptr[j].distance_squared_to(uv2s_ptr[idx.second]) < CMP_EPSILON2);
  331. bool is_tang_aligned = !tangents_ptr || (tangents_ptr[j * 4 + 3] < 0) == (tangents_ptr[idx.second * 4 + 3] < 0);
  332. ERR_FAIL_INDEX(idx.second, normals.size());
  333. bool is_normals_close = normals[idx.second].dot(n) > normal_merge_threshold;
  334. if (is_uvs_close && is_uv2s_close && is_normals_close && is_tang_aligned) {
  335. vertex_remap.push_back(idx.first);
  336. merged_normals[idx.first] += normals[idx.second];
  337. merged_normals_counts[idx.first]++;
  338. found = true;
  339. break;
  340. }
  341. }
  342. if (!found) {
  343. int vcount = merged_vertices.size();
  344. unique_vertices[v].push_back(Pair<int, int>(vcount, j));
  345. vertex_inverse_remap.push_back(j);
  346. merged_vertices.push_back(v);
  347. vertex_remap.push_back(vcount);
  348. merged_normals.push_back(normals_ptr[j]);
  349. merged_normals_counts.push_back(1);
  350. }
  351. } else {
  352. int vcount = merged_vertices.size();
  353. unique_vertices[v] = LocalVector<Pair<int, int>>();
  354. unique_vertices[v].push_back(Pair<int, int>(vcount, j));
  355. vertex_inverse_remap.push_back(j);
  356. merged_vertices.push_back(v);
  357. vertex_remap.push_back(vcount);
  358. merged_normals.push_back(normals_ptr[j]);
  359. merged_normals_counts.push_back(1);
  360. }
  361. }
  362. LocalVector<int> merged_indices;
  363. merged_indices.resize(index_count);
  364. for (unsigned int j = 0; j < index_count; j++) {
  365. merged_indices[j] = vertex_remap[indices[j]];
  366. }
  367. unsigned int merged_vertex_count = merged_vertices.size();
  368. const Vector3 *merged_vertices_ptr = merged_vertices.ptr();
  369. const int32_t *merged_indices_ptr = merged_indices.ptr();
  370. {
  371. const int *counts_ptr = merged_normals_counts.ptr();
  372. Vector3 *merged_normals_ptrw = merged_normals.ptr();
  373. for (unsigned int j = 0; j < merged_vertex_count; j++) {
  374. merged_normals_ptrw[j] /= counts_ptr[j];
  375. }
  376. }
  377. const float normal_weights[3] = {
  378. // Give some weight to normal preservation, may be worth exposing as an import setting
  379. 2.0f, 2.0f, 2.0f
  380. };
  381. Vector<float> merged_vertices_f32 = vector3_to_float32_array(merged_vertices_ptr, merged_vertex_count);
  382. float scale = SurfaceTool::simplify_scale_func(merged_vertices_f32.ptr(), merged_vertex_count, sizeof(float) * 3);
  383. unsigned int index_target = 12; // Start with the smallest target, 4 triangles
  384. unsigned int last_index_count = 0;
  385. const float max_mesh_error = FLT_MAX; // We don't want to limit by error, just by index target
  386. float mesh_error = 0.0f;
  387. while (index_target < index_count) {
  388. PackedInt32Array new_indices;
  389. new_indices.resize(index_count);
  390. Vector<float> merged_normals_f32 = vector3_to_float32_array(merged_normals.ptr(), merged_normals.size());
  391. const int simplify_options = SurfaceTool::SIMPLIFY_LOCK_BORDER;
  392. size_t new_index_count = SurfaceTool::simplify_with_attrib_func(
  393. (unsigned int *)new_indices.ptrw(),
  394. (const uint32_t *)merged_indices_ptr, index_count,
  395. merged_vertices_f32.ptr(), merged_vertex_count,
  396. sizeof(float) * 3, // Vertex stride
  397. merged_normals_f32.ptr(),
  398. sizeof(float) * 3, // Attribute stride
  399. normal_weights, 3,
  400. nullptr, // Vertex lock
  401. index_target,
  402. max_mesh_error,
  403. simplify_options,
  404. &mesh_error);
  405. if (new_index_count < last_index_count * 1.5f) {
  406. index_target = index_target * 1.5f;
  407. continue;
  408. }
  409. if (new_index_count == 0 || (new_index_count >= (index_count * 0.75f))) {
  410. break;
  411. }
  412. if (new_index_count > 5000000) {
  413. // This limit theoretically shouldn't be needed, but it's here
  414. // as an ad-hoc fix to prevent a crash with complex meshes.
  415. // The crash still happens with limit of 6000000, but 5000000 works.
  416. // In the future, identify what's causing that crash and fix it.
  417. WARN_PRINT("Mesh LOD generation failed for mesh " + get_name() + " surface " + itos(i) + ", mesh is too complex. Some automatic LODs were not generated.");
  418. break;
  419. }
  420. new_indices.resize(new_index_count);
  421. {
  422. int *ptrw = new_indices.ptrw();
  423. for (unsigned int j = 0; j < new_index_count; j++) {
  424. ptrw[j] = vertex_inverse_remap[ptrw[j]];
  425. }
  426. }
  427. Surface::LOD lod;
  428. lod.distance = MAX(mesh_error * scale, CMP_EPSILON2);
  429. lod.indices = new_indices;
  430. surfaces.write[i].lods.push_back(lod);
  431. index_target = MAX(new_index_count, index_target) * 2;
  432. last_index_count = new_index_count;
  433. if (mesh_error == 0.0f) {
  434. break;
  435. }
  436. }
  437. surfaces.write[i].lods.sort_custom<Surface::LODComparator>();
  438. }
  439. }
  440. void ImporterMesh::_generate_lods_bind(float p_normal_merge_angle, float p_normal_split_angle, Array p_skin_pose_transform_array) {
  441. // p_normal_split_angle is unused, but kept for compatibility
  442. generate_lods(p_normal_merge_angle, p_skin_pose_transform_array);
  443. }
  444. bool ImporterMesh::has_mesh() const {
  445. return mesh.is_valid();
  446. }
  447. Ref<ArrayMesh> ImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) {
  448. ERR_FAIL_COND_V(surfaces.is_empty(), Ref<ArrayMesh>());
  449. if (mesh.is_null()) {
  450. if (p_base.is_valid()) {
  451. mesh = p_base;
  452. }
  453. if (mesh.is_null()) {
  454. mesh.instantiate();
  455. }
  456. mesh->set_name(get_name());
  457. if (has_meta("import_id")) {
  458. mesh->set_meta("import_id", get_meta("import_id"));
  459. }
  460. for (int i = 0; i < blend_shapes.size(); i++) {
  461. mesh->add_blend_shape(blend_shapes[i]);
  462. }
  463. mesh->set_blend_shape_mode(blend_shape_mode);
  464. for (int i = 0; i < surfaces.size(); i++) {
  465. Array bs_data;
  466. if (surfaces[i].blend_shape_data.size()) {
  467. for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
  468. bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
  469. }
  470. }
  471. Dictionary lods;
  472. if (surfaces[i].lods.size()) {
  473. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  474. lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
  475. }
  476. }
  477. mesh->add_surface_from_arrays(surfaces[i].primitive, surfaces[i].arrays, bs_data, lods, surfaces[i].flags);
  478. if (surfaces[i].material.is_valid()) {
  479. mesh->surface_set_material(mesh->get_surface_count() - 1, surfaces[i].material);
  480. }
  481. if (!surfaces[i].name.is_empty()) {
  482. mesh->surface_set_name(mesh->get_surface_count() - 1, surfaces[i].name);
  483. }
  484. }
  485. mesh->set_lightmap_size_hint(lightmap_size_hint);
  486. if (shadow_mesh.is_valid()) {
  487. Ref<ArrayMesh> shadow = shadow_mesh->get_mesh();
  488. mesh->set_shadow_mesh(shadow);
  489. }
  490. }
  491. return mesh;
  492. }
  493. void ImporterMesh::clear() {
  494. surfaces.clear();
  495. blend_shapes.clear();
  496. mesh.unref();
  497. }
  498. void ImporterMesh::create_shadow_mesh() {
  499. if (shadow_mesh.is_valid()) {
  500. shadow_mesh.unref();
  501. }
  502. //no shadow mesh for blendshapes
  503. if (blend_shapes.size() > 0) {
  504. return;
  505. }
  506. //no shadow mesh for skeletons
  507. for (int i = 0; i < surfaces.size(); i++) {
  508. if (surfaces[i].arrays[RS::ARRAY_BONES].get_type() != Variant::NIL) {
  509. return;
  510. }
  511. if (surfaces[i].arrays[RS::ARRAY_WEIGHTS].get_type() != Variant::NIL) {
  512. return;
  513. }
  514. }
  515. shadow_mesh.instantiate();
  516. for (int i = 0; i < surfaces.size(); i++) {
  517. LocalVector<int> vertex_remap;
  518. Vector<Vector3> new_vertices;
  519. Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
  520. int vertex_count = vertices.size();
  521. {
  522. HashMap<Vector3, int> unique_vertices;
  523. const Vector3 *vptr = vertices.ptr();
  524. for (int j = 0; j < vertex_count; j++) {
  525. const Vector3 &v = vptr[j];
  526. HashMap<Vector3, int>::Iterator E = unique_vertices.find(v);
  527. if (E) {
  528. vertex_remap.push_back(E->value);
  529. } else {
  530. int vcount = unique_vertices.size();
  531. unique_vertices[v] = vcount;
  532. vertex_remap.push_back(vcount);
  533. new_vertices.push_back(v);
  534. }
  535. }
  536. }
  537. Array new_surface;
  538. new_surface.resize(RS::ARRAY_MAX);
  539. Dictionary lods;
  540. // print_line("original vertex count: " + itos(vertices.size()) + " new vertex count: " + itos(new_vertices.size()));
  541. new_surface[RS::ARRAY_VERTEX] = new_vertices;
  542. Vector<int> indices = surfaces[i].arrays[RS::ARRAY_INDEX];
  543. if (indices.size()) {
  544. int index_count = indices.size();
  545. const int *index_rptr = indices.ptr();
  546. Vector<int> new_indices;
  547. new_indices.resize(indices.size());
  548. int *index_wptr = new_indices.ptrw();
  549. for (int j = 0; j < index_count; j++) {
  550. int index = index_rptr[j];
  551. ERR_FAIL_INDEX(index, vertex_count);
  552. index_wptr[j] = vertex_remap[index];
  553. }
  554. new_surface[RS::ARRAY_INDEX] = new_indices;
  555. // Make sure the same LODs as the full version are used.
  556. // This makes it more coherent between rendered model and its shadows.
  557. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  558. indices = surfaces[i].lods[j].indices;
  559. index_count = indices.size();
  560. index_rptr = indices.ptr();
  561. new_indices.resize(indices.size());
  562. index_wptr = new_indices.ptrw();
  563. for (int k = 0; k < index_count; k++) {
  564. int index = index_rptr[k];
  565. ERR_FAIL_INDEX(index, vertex_count);
  566. index_wptr[k] = vertex_remap[index];
  567. }
  568. lods[surfaces[i].lods[j].distance] = new_indices;
  569. }
  570. }
  571. shadow_mesh->add_surface(surfaces[i].primitive, new_surface, Array(), lods, Ref<Material>(), surfaces[i].name, surfaces[i].flags);
  572. }
  573. }
  574. Ref<ImporterMesh> ImporterMesh::get_shadow_mesh() const {
  575. return shadow_mesh;
  576. }
  577. void ImporterMesh::_set_data(const Dictionary &p_data) {
  578. clear();
  579. if (p_data.has("blend_shape_names")) {
  580. blend_shapes = p_data["blend_shape_names"];
  581. }
  582. if (p_data.has("surfaces")) {
  583. Array surface_arr = p_data["surfaces"];
  584. for (int i = 0; i < surface_arr.size(); i++) {
  585. Dictionary s = surface_arr[i];
  586. ERR_CONTINUE(!s.has("primitive"));
  587. ERR_CONTINUE(!s.has("arrays"));
  588. Mesh::PrimitiveType prim = Mesh::PrimitiveType(int(s["primitive"]));
  589. ERR_CONTINUE(prim >= Mesh::PRIMITIVE_MAX);
  590. Array arr = s["arrays"];
  591. Dictionary lods;
  592. String surf_name;
  593. if (s.has("name")) {
  594. surf_name = s["name"];
  595. }
  596. if (s.has("lods")) {
  597. lods = s["lods"];
  598. }
  599. Array b_shapes;
  600. if (s.has("b_shapes")) {
  601. b_shapes = s["b_shapes"];
  602. }
  603. Ref<Material> material;
  604. if (s.has("material")) {
  605. material = s["material"];
  606. }
  607. uint64_t flags = 0;
  608. if (s.has("flags")) {
  609. flags = s["flags"];
  610. }
  611. add_surface(prim, arr, b_shapes, lods, material, surf_name, flags);
  612. }
  613. }
  614. }
  615. Dictionary ImporterMesh::_get_data() const {
  616. Dictionary data;
  617. if (blend_shapes.size()) {
  618. data["blend_shape_names"] = blend_shapes;
  619. }
  620. Array surface_arr;
  621. for (int i = 0; i < surfaces.size(); i++) {
  622. Dictionary d;
  623. d["primitive"] = surfaces[i].primitive;
  624. d["arrays"] = surfaces[i].arrays;
  625. if (surfaces[i].blend_shape_data.size()) {
  626. Array bs_data;
  627. for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
  628. bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
  629. }
  630. d["blend_shapes"] = bs_data;
  631. }
  632. if (surfaces[i].lods.size()) {
  633. Dictionary lods;
  634. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  635. lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
  636. }
  637. d["lods"] = lods;
  638. }
  639. if (surfaces[i].material.is_valid()) {
  640. d["material"] = surfaces[i].material;
  641. }
  642. if (!surfaces[i].name.is_empty()) {
  643. d["name"] = surfaces[i].name;
  644. }
  645. d["flags"] = surfaces[i].flags;
  646. surface_arr.push_back(d);
  647. }
  648. data["surfaces"] = surface_arr;
  649. return data;
  650. }
  651. Vector<Face3> ImporterMesh::get_faces() const {
  652. Vector<Face3> faces;
  653. for (int i = 0; i < surfaces.size(); i++) {
  654. if (surfaces[i].primitive == Mesh::PRIMITIVE_TRIANGLES) {
  655. Vector<Vector3> vertices = surfaces[i].arrays[Mesh::ARRAY_VERTEX];
  656. Vector<int> indices = surfaces[i].arrays[Mesh::ARRAY_INDEX];
  657. if (indices.size()) {
  658. for (int j = 0; j < indices.size(); j += 3) {
  659. Face3 f;
  660. f.vertex[0] = vertices[indices[j + 0]];
  661. f.vertex[1] = vertices[indices[j + 1]];
  662. f.vertex[2] = vertices[indices[j + 2]];
  663. faces.push_back(f);
  664. }
  665. } else {
  666. for (int j = 0; j < vertices.size(); j += 3) {
  667. Face3 f;
  668. f.vertex[0] = vertices[j + 0];
  669. f.vertex[1] = vertices[j + 1];
  670. f.vertex[2] = vertices[j + 2];
  671. faces.push_back(f);
  672. }
  673. }
  674. }
  675. }
  676. return faces;
  677. }
  678. Vector<Ref<Shape3D>> ImporterMesh::convex_decompose(const Ref<MeshConvexDecompositionSettings> &p_settings) const {
  679. ERR_FAIL_NULL_V(Mesh::convex_decomposition_function, Vector<Ref<Shape3D>>());
  680. const Vector<Face3> faces = get_faces();
  681. int face_count = faces.size();
  682. Vector<Vector3> vertices;
  683. uint32_t vertex_count = 0;
  684. vertices.resize(face_count * 3);
  685. Vector<uint32_t> indices;
  686. indices.resize(face_count * 3);
  687. {
  688. HashMap<Vector3, uint32_t> vertex_map;
  689. Vector3 *vertex_w = vertices.ptrw();
  690. uint32_t *index_w = indices.ptrw();
  691. for (int i = 0; i < face_count; i++) {
  692. for (int j = 0; j < 3; j++) {
  693. const Vector3 &vertex = faces[i].vertex[j];
  694. HashMap<Vector3, uint32_t>::Iterator found_vertex = vertex_map.find(vertex);
  695. uint32_t index;
  696. if (found_vertex) {
  697. index = found_vertex->value;
  698. } else {
  699. index = vertex_count++;
  700. vertex_map[vertex] = index;
  701. vertex_w[index] = vertex;
  702. }
  703. index_w[i * 3 + j] = index;
  704. }
  705. }
  706. }
  707. vertices.resize(vertex_count);
  708. Vector<Vector<Vector3>> decomposed = Mesh::convex_decomposition_function((real_t *)vertices.ptr(), vertex_count, indices.ptr(), face_count, p_settings, nullptr);
  709. Vector<Ref<Shape3D>> ret;
  710. for (int i = 0; i < decomposed.size(); i++) {
  711. Ref<ConvexPolygonShape3D> shape;
  712. shape.instantiate();
  713. shape->set_points(decomposed[i]);
  714. ret.push_back(shape);
  715. }
  716. return ret;
  717. }
  718. Ref<ConvexPolygonShape3D> ImporterMesh::create_convex_shape(bool p_clean, bool p_simplify) const {
  719. if (p_simplify) {
  720. Ref<MeshConvexDecompositionSettings> settings;
  721. settings.instantiate();
  722. settings->set_max_convex_hulls(1);
  723. Vector<Ref<Shape3D>> decomposed = convex_decompose(settings);
  724. if (decomposed.size() == 1) {
  725. return decomposed[0];
  726. } else {
  727. ERR_PRINT("Convex shape simplification failed, falling back to simpler process.");
  728. }
  729. }
  730. Vector<Vector3> vertices;
  731. for (int i = 0; i < get_surface_count(); i++) {
  732. Array a = get_surface_arrays(i);
  733. ERR_FAIL_COND_V(a.is_empty(), Ref<ConvexPolygonShape3D>());
  734. Vector<Vector3> v = a[Mesh::ARRAY_VERTEX];
  735. vertices.append_array(v);
  736. }
  737. Ref<ConvexPolygonShape3D> shape = memnew(ConvexPolygonShape3D);
  738. if (p_clean) {
  739. Geometry3D::MeshData md;
  740. Error err = ConvexHullComputer::convex_hull(vertices, md);
  741. if (err == OK) {
  742. shape->set_points(md.vertices);
  743. return shape;
  744. } else {
  745. ERR_PRINT("Convex shape cleaning failed, falling back to simpler process.");
  746. }
  747. }
  748. shape->set_points(vertices);
  749. return shape;
  750. }
  751. Ref<ConcavePolygonShape3D> ImporterMesh::create_trimesh_shape() const {
  752. Vector<Face3> faces = get_faces();
  753. if (faces.size() == 0) {
  754. return Ref<ConcavePolygonShape3D>();
  755. }
  756. Vector<Vector3> face_points;
  757. face_points.resize(faces.size() * 3);
  758. for (int i = 0; i < face_points.size(); i += 3) {
  759. Face3 f = faces.get(i / 3);
  760. face_points.set(i, f.vertex[0]);
  761. face_points.set(i + 1, f.vertex[1]);
  762. face_points.set(i + 2, f.vertex[2]);
  763. }
  764. Ref<ConcavePolygonShape3D> shape = memnew(ConcavePolygonShape3D);
  765. shape->set_faces(face_points);
  766. return shape;
  767. }
  768. Ref<NavigationMesh> ImporterMesh::create_navigation_mesh() {
  769. Vector<Face3> faces = get_faces();
  770. if (faces.size() == 0) {
  771. return Ref<NavigationMesh>();
  772. }
  773. HashMap<Vector3, int> unique_vertices;
  774. Vector<Vector<int>> face_polygons;
  775. face_polygons.resize(faces.size());
  776. for (int i = 0; i < faces.size(); i++) {
  777. Vector<int> face_indices;
  778. face_indices.resize(3);
  779. for (int j = 0; j < 3; j++) {
  780. Vector3 v = faces[i].vertex[j];
  781. int idx;
  782. if (unique_vertices.has(v)) {
  783. idx = unique_vertices[v];
  784. } else {
  785. idx = unique_vertices.size();
  786. unique_vertices[v] = idx;
  787. }
  788. face_indices.write[j] = idx;
  789. }
  790. face_polygons.write[i] = face_indices;
  791. }
  792. Vector<Vector3> vertices;
  793. vertices.resize(unique_vertices.size());
  794. for (const KeyValue<Vector3, int> &E : unique_vertices) {
  795. vertices.write[E.value] = E.key;
  796. }
  797. Ref<NavigationMesh> nm;
  798. nm.instantiate();
  799. nm->set_data(vertices, face_polygons);
  800. return nm;
  801. }
  802. extern 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);
  803. struct EditorSceneFormatImporterMeshLightmapSurface {
  804. Ref<Material> material;
  805. LocalVector<SurfaceTool::Vertex> vertices;
  806. Mesh::PrimitiveType primitive = Mesh::PrimitiveType::PRIMITIVE_MAX;
  807. uint64_t format = 0;
  808. String name;
  809. };
  810. static const uint32_t custom_shift[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM1_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM2_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM3_SHIFT };
  811. Error ImporterMesh::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) {
  812. ERR_FAIL_NULL_V(array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
  813. ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
  814. LocalVector<float> vertices;
  815. LocalVector<float> normals;
  816. LocalVector<int> indices;
  817. LocalVector<float> uv;
  818. LocalVector<Pair<int, int>> uv_indices;
  819. Vector<EditorSceneFormatImporterMeshLightmapSurface> lightmap_surfaces;
  820. // Keep only the scale
  821. Basis basis = p_base_transform.get_basis();
  822. Vector3 scale = Vector3(basis.get_column(0).length(), basis.get_column(1).length(), basis.get_column(2).length());
  823. Transform3D transform;
  824. transform.scale(scale);
  825. Basis normal_basis = transform.basis.inverse().transposed();
  826. for (int i = 0; i < get_surface_count(); i++) {
  827. EditorSceneFormatImporterMeshLightmapSurface s;
  828. s.primitive = get_surface_primitive_type(i);
  829. ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");
  830. Array arrays = get_surface_arrays(i);
  831. s.material = get_surface_material(i);
  832. s.name = get_surface_name(i);
  833. SurfaceTool::create_vertex_array_from_arrays(arrays, s.vertices, &s.format);
  834. PackedVector3Array rvertices = arrays[Mesh::ARRAY_VERTEX];
  835. int vc = rvertices.size();
  836. PackedVector3Array rnormals = arrays[Mesh::ARRAY_NORMAL];
  837. if (!rnormals.size()) {
  838. continue;
  839. }
  840. int vertex_ofs = vertices.size() / 3;
  841. vertices.resize((vertex_ofs + vc) * 3);
  842. normals.resize((vertex_ofs + vc) * 3);
  843. uv_indices.resize(vertex_ofs + vc);
  844. for (int j = 0; j < vc; j++) {
  845. Vector3 v = transform.xform(rvertices[j]);
  846. Vector3 n = normal_basis.xform(rnormals[j]).normalized();
  847. vertices[(j + vertex_ofs) * 3 + 0] = v.x;
  848. vertices[(j + vertex_ofs) * 3 + 1] = v.y;
  849. vertices[(j + vertex_ofs) * 3 + 2] = v.z;
  850. normals[(j + vertex_ofs) * 3 + 0] = n.x;
  851. normals[(j + vertex_ofs) * 3 + 1] = n.y;
  852. normals[(j + vertex_ofs) * 3 + 2] = n.z;
  853. uv_indices[j + vertex_ofs] = Pair<int, int>(i, j);
  854. }
  855. PackedInt32Array rindices = arrays[Mesh::ARRAY_INDEX];
  856. int ic = rindices.size();
  857. float eps = 1.19209290e-7F; // Taken from xatlas.h
  858. if (ic == 0) {
  859. for (int j = 0; j < vc / 3; j++) {
  860. Vector3 p0 = transform.xform(rvertices[j * 3 + 0]);
  861. Vector3 p1 = transform.xform(rvertices[j * 3 + 1]);
  862. Vector3 p2 = transform.xform(rvertices[j * 3 + 2]);
  863. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  864. continue;
  865. }
  866. indices.push_back(vertex_ofs + j * 3 + 0);
  867. indices.push_back(vertex_ofs + j * 3 + 1);
  868. indices.push_back(vertex_ofs + j * 3 + 2);
  869. }
  870. } else {
  871. for (int j = 0; j < ic / 3; j++) {
  872. ERR_FAIL_INDEX_V(rindices[j * 3 + 0], rvertices.size(), ERR_INVALID_DATA);
  873. ERR_FAIL_INDEX_V(rindices[j * 3 + 1], rvertices.size(), ERR_INVALID_DATA);
  874. ERR_FAIL_INDEX_V(rindices[j * 3 + 2], rvertices.size(), ERR_INVALID_DATA);
  875. Vector3 p0 = transform.xform(rvertices[rindices[j * 3 + 0]]);
  876. Vector3 p1 = transform.xform(rvertices[rindices[j * 3 + 1]]);
  877. Vector3 p2 = transform.xform(rvertices[rindices[j * 3 + 2]]);
  878. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  879. continue;
  880. }
  881. indices.push_back(vertex_ofs + rindices[j * 3 + 0]);
  882. indices.push_back(vertex_ofs + rindices[j * 3 + 1]);
  883. indices.push_back(vertex_ofs + rindices[j * 3 + 2]);
  884. }
  885. }
  886. lightmap_surfaces.push_back(s);
  887. }
  888. //unwrap
  889. bool use_cache = true; // Used to request cache generation and to know if cache was used
  890. uint8_t *gen_cache;
  891. int gen_cache_size;
  892. float *gen_uvs;
  893. int *gen_vertices;
  894. int *gen_indices;
  895. int gen_vertex_count;
  896. int gen_index_count;
  897. int size_x;
  898. int size_y;
  899. 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);
  900. if (!ok) {
  901. return ERR_CANT_CREATE;
  902. }
  903. //create surfacetools for each surface..
  904. LocalVector<Ref<SurfaceTool>> surfaces_tools;
  905. for (int i = 0; i < lightmap_surfaces.size(); i++) {
  906. Ref<SurfaceTool> st;
  907. st.instantiate();
  908. st->set_skin_weight_count((lightmap_surfaces[i].format & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS) ? SurfaceTool::SKIN_8_WEIGHTS : SurfaceTool::SKIN_4_WEIGHTS);
  909. st->begin(Mesh::PRIMITIVE_TRIANGLES);
  910. st->set_material(lightmap_surfaces[i].material);
  911. st->set_meta("name", lightmap_surfaces[i].name);
  912. for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
  913. st->set_custom_format(custom_i, (SurfaceTool::CustomFormat)((lightmap_surfaces[i].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK));
  914. }
  915. surfaces_tools.push_back(st); //stay there
  916. }
  917. //remove surfaces
  918. clear();
  919. print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
  920. //go through all indices
  921. for (int i = 0; i < gen_index_count; i += 3) {
  922. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], (int)uv_indices.size(), ERR_BUG);
  923. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], (int)uv_indices.size(), ERR_BUG);
  924. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], (int)uv_indices.size(), ERR_BUG);
  925. 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);
  926. int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;
  927. for (int j = 0; j < 3; j++) {
  928. SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];
  929. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_COLOR) {
  930. surfaces_tools[surface]->set_color(v.color);
  931. }
  932. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TEX_UV) {
  933. surfaces_tools[surface]->set_uv(v.uv);
  934. }
  935. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_NORMAL) {
  936. surfaces_tools[surface]->set_normal(v.normal);
  937. }
  938. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TANGENT) {
  939. Plane t;
  940. t.normal = v.tangent;
  941. t.d = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;
  942. surfaces_tools[surface]->set_tangent(t);
  943. }
  944. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_BONES) {
  945. surfaces_tools[surface]->set_bones(v.bones);
  946. }
  947. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_WEIGHTS) {
  948. surfaces_tools[surface]->set_weights(v.weights);
  949. }
  950. for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {
  951. if ((lightmap_surfaces[surface].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK) {
  952. surfaces_tools[surface]->set_custom(custom_i, v.custom[custom_i]);
  953. }
  954. }
  955. Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
  956. surfaces_tools[surface]->set_uv2(uv2);
  957. surfaces_tools[surface]->add_vertex(v.vertex);
  958. }
  959. }
  960. //generate surfaces
  961. for (int i = 0; i < lightmap_surfaces.size(); i++) {
  962. Ref<SurfaceTool> &tool = surfaces_tools[i];
  963. tool->index();
  964. Array arrays = tool->commit_to_arrays();
  965. uint64_t format = lightmap_surfaces[i].format;
  966. if (tool->get_skin_weight_count() == SurfaceTool::SKIN_8_WEIGHTS) {
  967. format |= RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  968. } else {
  969. format &= ~RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  970. }
  971. add_surface(tool->get_primitive_type(), arrays, Array(), Dictionary(), tool->get_material(), tool->get_meta("name"), format);
  972. }
  973. set_lightmap_size_hint(Size2(size_x, size_y));
  974. if (gen_cache_size > 0) {
  975. r_dst_cache.resize(gen_cache_size);
  976. memcpy(r_dst_cache.ptrw(), gen_cache, gen_cache_size);
  977. memfree(gen_cache);
  978. }
  979. if (!use_cache) {
  980. // Cache was not used, free the buffers
  981. memfree(gen_vertices);
  982. memfree(gen_indices);
  983. memfree(gen_uvs);
  984. }
  985. return OK;
  986. }
  987. void ImporterMesh::set_lightmap_size_hint(const Size2i &p_size) {
  988. lightmap_size_hint = p_size;
  989. }
  990. Size2i ImporterMesh::get_lightmap_size_hint() const {
  991. return lightmap_size_hint;
  992. }
  993. void ImporterMesh::_bind_methods() {
  994. ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ImporterMesh::add_blend_shape);
  995. ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ImporterMesh::get_blend_shape_count);
  996. ClassDB::bind_method(D_METHOD("get_blend_shape_name", "blend_shape_idx"), &ImporterMesh::get_blend_shape_name);
  997. ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ImporterMesh::set_blend_shape_mode);
  998. ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ImporterMesh::get_blend_shape_mode);
  999. ClassDB::bind_method(D_METHOD("add_surface", "primitive", "arrays", "blend_shapes", "lods", "material", "name", "flags"), &ImporterMesh::add_surface, DEFVAL(TypedArray<Array>()), DEFVAL(Dictionary()), DEFVAL(Ref<Material>()), DEFVAL(String()), DEFVAL(0));
  1000. ClassDB::bind_method(D_METHOD("get_surface_count"), &ImporterMesh::get_surface_count);
  1001. ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &ImporterMesh::get_surface_primitive_type);
  1002. ClassDB::bind_method(D_METHOD("get_surface_name", "surface_idx"), &ImporterMesh::get_surface_name);
  1003. ClassDB::bind_method(D_METHOD("get_surface_arrays", "surface_idx"), &ImporterMesh::get_surface_arrays);
  1004. ClassDB::bind_method(D_METHOD("get_surface_blend_shape_arrays", "surface_idx", "blend_shape_idx"), &ImporterMesh::get_surface_blend_shape_arrays);
  1005. ClassDB::bind_method(D_METHOD("get_surface_lod_count", "surface_idx"), &ImporterMesh::get_surface_lod_count);
  1006. ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_size);
  1007. ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_indices);
  1008. ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &ImporterMesh::get_surface_material);
  1009. ClassDB::bind_method(D_METHOD("get_surface_format", "surface_idx"), &ImporterMesh::get_surface_format);
  1010. ClassDB::bind_method(D_METHOD("set_surface_name", "surface_idx", "name"), &ImporterMesh::set_surface_name);
  1011. ClassDB::bind_method(D_METHOD("set_surface_material", "surface_idx", "material"), &ImporterMesh::set_surface_material);
  1012. ClassDB::bind_method(D_METHOD("generate_lods", "normal_merge_angle", "normal_split_angle", "bone_transform_array"), &ImporterMesh::_generate_lods_bind);
  1013. ClassDB::bind_method(D_METHOD("get_mesh", "base_mesh"), &ImporterMesh::get_mesh, DEFVAL(Ref<ArrayMesh>()));
  1014. ClassDB::bind_method(D_METHOD("clear"), &ImporterMesh::clear);
  1015. ClassDB::bind_method(D_METHOD("_set_data", "data"), &ImporterMesh::_set_data);
  1016. ClassDB::bind_method(D_METHOD("_get_data"), &ImporterMesh::_get_data);
  1017. ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &ImporterMesh::set_lightmap_size_hint);
  1018. ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &ImporterMesh::get_lightmap_size_hint);
  1019. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data");
  1020. }