importer_mesh.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. /*************************************************************************/
  2. /* importer_mesh.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "importer_mesh.h"
  31. #include "core/math/random_pcg.h"
  32. #include "core/math/static_raycaster.h"
  33. #include "scene/resources/surface_tool.h"
  34. #include <cstdint>
  35. void ImporterMesh::Surface::split_normals(const LocalVector<int> &p_indices, const LocalVector<Vector3> &p_normals) {
  36. _split_normals(arrays, p_indices, p_normals);
  37. for (BlendShape &blend_shape : blend_shape_data) {
  38. _split_normals(blend_shape.arrays, p_indices, p_normals);
  39. }
  40. }
  41. void ImporterMesh::Surface::_split_normals(Array &r_arrays, const LocalVector<int> &p_indices, const LocalVector<Vector3> &p_normals) {
  42. ERR_FAIL_COND(r_arrays.size() != RS::ARRAY_MAX);
  43. const PackedVector3Array &vertices = r_arrays[RS::ARRAY_VERTEX];
  44. int current_vertex_count = vertices.size();
  45. int new_vertex_count = p_indices.size();
  46. int final_vertex_count = current_vertex_count + new_vertex_count;
  47. const int *indices_ptr = p_indices.ptr();
  48. for (int i = 0; i < r_arrays.size(); i++) {
  49. if (i == RS::ARRAY_INDEX) {
  50. continue;
  51. }
  52. if (r_arrays[i].get_type() == Variant::NIL) {
  53. continue;
  54. }
  55. switch (r_arrays[i].get_type()) {
  56. case Variant::PACKED_VECTOR3_ARRAY: {
  57. PackedVector3Array data = r_arrays[i];
  58. data.resize(final_vertex_count);
  59. Vector3 *data_ptr = data.ptrw();
  60. if (i == RS::ARRAY_NORMAL) {
  61. const Vector3 *normals_ptr = p_normals.ptr();
  62. memcpy(&data_ptr[current_vertex_count], normals_ptr, sizeof(Vector3) * new_vertex_count);
  63. } else {
  64. for (int j = 0; j < new_vertex_count; j++) {
  65. data_ptr[current_vertex_count + j] = data_ptr[indices_ptr[j]];
  66. }
  67. }
  68. r_arrays[i] = data;
  69. } break;
  70. case Variant::PACKED_VECTOR2_ARRAY: {
  71. PackedVector2Array data = r_arrays[i];
  72. data.resize(final_vertex_count);
  73. Vector2 *data_ptr = data.ptrw();
  74. for (int j = 0; j < new_vertex_count; j++) {
  75. data_ptr[current_vertex_count + j] = data_ptr[indices_ptr[j]];
  76. }
  77. r_arrays[i] = data;
  78. } break;
  79. case Variant::PACKED_FLOAT32_ARRAY: {
  80. PackedFloat32Array data = r_arrays[i];
  81. int elements = data.size() / current_vertex_count;
  82. data.resize(final_vertex_count * elements);
  83. float *data_ptr = data.ptrw();
  84. for (int j = 0; j < new_vertex_count; j++) {
  85. memcpy(&data_ptr[(current_vertex_count + j) * elements], &data_ptr[indices_ptr[j] * elements], sizeof(float) * elements);
  86. }
  87. r_arrays[i] = data;
  88. } break;
  89. case Variant::PACKED_INT32_ARRAY: {
  90. PackedInt32Array data = r_arrays[i];
  91. int elements = data.size() / current_vertex_count;
  92. data.resize(final_vertex_count * elements);
  93. int32_t *data_ptr = data.ptrw();
  94. for (int j = 0; j < new_vertex_count; j++) {
  95. memcpy(&data_ptr[(current_vertex_count + j) * elements], &data_ptr[indices_ptr[j] * elements], sizeof(int32_t) * elements);
  96. }
  97. r_arrays[i] = data;
  98. } break;
  99. case Variant::PACKED_BYTE_ARRAY: {
  100. PackedByteArray data = r_arrays[i];
  101. int elements = data.size() / current_vertex_count;
  102. data.resize(final_vertex_count * elements);
  103. uint8_t *data_ptr = data.ptrw();
  104. for (int j = 0; j < new_vertex_count; j++) {
  105. memcpy(&data_ptr[(current_vertex_count + j) * elements], &data_ptr[indices_ptr[j] * elements], sizeof(uint8_t) * elements);
  106. }
  107. r_arrays[i] = data;
  108. } break;
  109. case Variant::PACKED_COLOR_ARRAY: {
  110. PackedColorArray data = r_arrays[i];
  111. data.resize(final_vertex_count);
  112. Color *data_ptr = data.ptrw();
  113. for (int j = 0; j < new_vertex_count; j++) {
  114. data_ptr[current_vertex_count + j] = data_ptr[indices_ptr[j]];
  115. }
  116. r_arrays[i] = data;
  117. } break;
  118. default: {
  119. ERR_FAIL_MSG("Unhandled array type.");
  120. } break;
  121. }
  122. }
  123. }
  124. void ImporterMesh::add_blend_shape(const String &p_name) {
  125. ERR_FAIL_COND(surfaces.size() > 0);
  126. blend_shapes.push_back(p_name);
  127. }
  128. int ImporterMesh::get_blend_shape_count() const {
  129. return blend_shapes.size();
  130. }
  131. String ImporterMesh::get_blend_shape_name(int p_blend_shape) const {
  132. ERR_FAIL_INDEX_V(p_blend_shape, blend_shapes.size(), String());
  133. return blend_shapes[p_blend_shape];
  134. }
  135. void ImporterMesh::set_blend_shape_mode(Mesh::BlendShapeMode p_blend_shape_mode) {
  136. blend_shape_mode = p_blend_shape_mode;
  137. }
  138. Mesh::BlendShapeMode ImporterMesh::get_blend_shape_mode() const {
  139. return blend_shape_mode;
  140. }
  141. void ImporterMesh::add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const Array &p_blend_shapes, const Dictionary &p_lods, const Ref<Material> &p_material, const String &p_name, const uint32_t p_flags) {
  142. ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size());
  143. ERR_FAIL_COND(p_arrays.size() != Mesh::ARRAY_MAX);
  144. Surface s;
  145. s.primitive = p_primitive;
  146. s.arrays = p_arrays;
  147. s.name = p_name;
  148. s.flags = p_flags;
  149. Vector<Vector3> vertex_array = p_arrays[Mesh::ARRAY_VERTEX];
  150. int vertex_count = vertex_array.size();
  151. ERR_FAIL_COND(vertex_count == 0);
  152. for (int i = 0; i < blend_shapes.size(); i++) {
  153. Array bsdata = p_blend_shapes[i];
  154. ERR_FAIL_COND(bsdata.size() != Mesh::ARRAY_MAX);
  155. Vector<Vector3> vertex_data = bsdata[Mesh::ARRAY_VERTEX];
  156. ERR_FAIL_COND(vertex_data.size() != vertex_count);
  157. Surface::BlendShape bs;
  158. bs.arrays = bsdata;
  159. s.blend_shape_data.push_back(bs);
  160. }
  161. List<Variant> lods;
  162. p_lods.get_key_list(&lods);
  163. for (const Variant &E : lods) {
  164. ERR_CONTINUE(!E.is_num());
  165. Surface::LOD lod;
  166. lod.distance = E;
  167. lod.indices = p_lods[E];
  168. ERR_CONTINUE(lod.indices.size() == 0);
  169. s.lods.push_back(lod);
  170. }
  171. s.material = p_material;
  172. surfaces.push_back(s);
  173. mesh.unref();
  174. }
  175. int ImporterMesh::get_surface_count() const {
  176. return surfaces.size();
  177. }
  178. Mesh::PrimitiveType ImporterMesh::get_surface_primitive_type(int p_surface) {
  179. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Mesh::PRIMITIVE_MAX);
  180. return surfaces[p_surface].primitive;
  181. }
  182. Array ImporterMesh::get_surface_arrays(int p_surface) const {
  183. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  184. return surfaces[p_surface].arrays;
  185. }
  186. String ImporterMesh::get_surface_name(int p_surface) const {
  187. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), String());
  188. return surfaces[p_surface].name;
  189. }
  190. void ImporterMesh::set_surface_name(int p_surface, const String &p_name) {
  191. ERR_FAIL_INDEX(p_surface, surfaces.size());
  192. surfaces.write[p_surface].name = p_name;
  193. mesh.unref();
  194. }
  195. Array ImporterMesh::get_surface_blend_shape_arrays(int p_surface, int p_blend_shape) const {
  196. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());
  197. ERR_FAIL_INDEX_V(p_blend_shape, surfaces[p_surface].blend_shape_data.size(), Array());
  198. return surfaces[p_surface].blend_shape_data[p_blend_shape].arrays;
  199. }
  200. int ImporterMesh::get_surface_lod_count(int p_surface) const {
  201. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  202. return surfaces[p_surface].lods.size();
  203. }
  204. Vector<int> ImporterMesh::get_surface_lod_indices(int p_surface, int p_lod) const {
  205. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Vector<int>());
  206. ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), Vector<int>());
  207. return surfaces[p_surface].lods[p_lod].indices;
  208. }
  209. float ImporterMesh::get_surface_lod_size(int p_surface, int p_lod) const {
  210. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  211. ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), 0);
  212. return surfaces[p_surface].lods[p_lod].distance;
  213. }
  214. uint32_t ImporterMesh::get_surface_format(int p_surface) const {
  215. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);
  216. return surfaces[p_surface].flags;
  217. }
  218. Ref<Material> ImporterMesh::get_surface_material(int p_surface) const {
  219. ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Ref<Material>());
  220. return surfaces[p_surface].material;
  221. }
  222. void ImporterMesh::set_surface_material(int p_surface, const Ref<Material> &p_material) {
  223. ERR_FAIL_INDEX(p_surface, surfaces.size());
  224. surfaces.write[p_surface].material = p_material;
  225. mesh.unref();
  226. }
  227. void ImporterMesh::generate_lods(float p_normal_merge_angle, float p_normal_split_angle) {
  228. if (!SurfaceTool::simplify_scale_func) {
  229. return;
  230. }
  231. if (!SurfaceTool::simplify_with_attrib_func) {
  232. return;
  233. }
  234. if (!SurfaceTool::optimize_vertex_cache_func) {
  235. return;
  236. }
  237. for (int i = 0; i < surfaces.size(); i++) {
  238. if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {
  239. continue;
  240. }
  241. surfaces.write[i].lods.clear();
  242. Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
  243. PackedInt32Array indices = surfaces[i].arrays[RS::ARRAY_INDEX];
  244. Vector<Vector3> normals = surfaces[i].arrays[RS::ARRAY_NORMAL];
  245. Vector<Vector2> uvs = surfaces[i].arrays[RS::ARRAY_TEX_UV];
  246. Vector<Vector2> uv2s = surfaces[i].arrays[RS::ARRAY_TEX_UV2];
  247. unsigned int index_count = indices.size();
  248. unsigned int vertex_count = vertices.size();
  249. if (index_count == 0) {
  250. continue; //no lods if no indices
  251. }
  252. const Vector3 *vertices_ptr = vertices.ptr();
  253. const int *indices_ptr = indices.ptr();
  254. if (normals.is_empty()) {
  255. normals.resize(index_count);
  256. Vector3 *n_ptr = normals.ptrw();
  257. for (unsigned int j = 0; j < index_count; j += 3) {
  258. const Vector3 &v0 = vertices_ptr[indices_ptr[j + 0]];
  259. const Vector3 &v1 = vertices_ptr[indices_ptr[j + 1]];
  260. const Vector3 &v2 = vertices_ptr[indices_ptr[j + 2]];
  261. Vector3 n = vec3_cross(v0 - v2, v0 - v1).normalized();
  262. n_ptr[j + 0] = n;
  263. n_ptr[j + 1] = n;
  264. n_ptr[j + 2] = n;
  265. }
  266. }
  267. float normal_merge_threshold = Math::cos(Math::deg_to_rad(p_normal_merge_angle));
  268. float normal_pre_split_threshold = Math::cos(Math::deg_to_rad(MIN(180.0f, p_normal_split_angle * 2.0f)));
  269. float normal_split_threshold = Math::cos(Math::deg_to_rad(p_normal_split_angle));
  270. const Vector3 *normals_ptr = normals.ptr();
  271. HashMap<Vector3, LocalVector<Pair<int, int>>> unique_vertices;
  272. LocalVector<int> vertex_remap;
  273. LocalVector<int> vertex_inverse_remap;
  274. LocalVector<Vector3> merged_vertices;
  275. LocalVector<Vector3> merged_normals;
  276. LocalVector<int> merged_normals_counts;
  277. const Vector2 *uvs_ptr = uvs.ptr();
  278. const Vector2 *uv2s_ptr = uv2s.ptr();
  279. for (unsigned int j = 0; j < vertex_count; j++) {
  280. const Vector3 &v = vertices_ptr[j];
  281. const Vector3 &n = normals_ptr[j];
  282. HashMap<Vector3, LocalVector<Pair<int, int>>>::Iterator E = unique_vertices.find(v);
  283. if (E) {
  284. const LocalVector<Pair<int, int>> &close_verts = E->value;
  285. bool found = false;
  286. for (unsigned int k = 0; k < close_verts.size(); k++) {
  287. const Pair<int, int> &idx = close_verts[k];
  288. bool is_uvs_close = (!uvs_ptr || uvs_ptr[j].distance_squared_to(uvs_ptr[idx.second]) < CMP_EPSILON2);
  289. bool is_uv2s_close = (!uv2s_ptr || uv2s_ptr[j].distance_squared_to(uv2s_ptr[idx.second]) < CMP_EPSILON2);
  290. ERR_FAIL_INDEX(idx.second, normals.size());
  291. bool is_normals_close = normals[idx.second].dot(n) > normal_merge_threshold;
  292. if (is_uvs_close && is_uv2s_close && is_normals_close) {
  293. vertex_remap.push_back(idx.first);
  294. merged_normals[idx.first] += normals[idx.second];
  295. merged_normals_counts[idx.first]++;
  296. found = true;
  297. break;
  298. }
  299. }
  300. if (!found) {
  301. int vcount = merged_vertices.size();
  302. unique_vertices[v].push_back(Pair<int, int>(vcount, j));
  303. vertex_inverse_remap.push_back(j);
  304. merged_vertices.push_back(v);
  305. vertex_remap.push_back(vcount);
  306. merged_normals.push_back(normals_ptr[j]);
  307. merged_normals_counts.push_back(1);
  308. }
  309. } else {
  310. int vcount = merged_vertices.size();
  311. unique_vertices[v] = LocalVector<Pair<int, int>>();
  312. unique_vertices[v].push_back(Pair<int, int>(vcount, j));
  313. vertex_inverse_remap.push_back(j);
  314. merged_vertices.push_back(v);
  315. vertex_remap.push_back(vcount);
  316. merged_normals.push_back(normals_ptr[j]);
  317. merged_normals_counts.push_back(1);
  318. }
  319. }
  320. LocalVector<int> merged_indices;
  321. merged_indices.resize(index_count);
  322. for (unsigned int j = 0; j < index_count; j++) {
  323. merged_indices[j] = vertex_remap[indices[j]];
  324. }
  325. unsigned int merged_vertex_count = merged_vertices.size();
  326. const Vector3 *merged_vertices_ptr = merged_vertices.ptr();
  327. const int32_t *merged_indices_ptr = merged_indices.ptr();
  328. {
  329. const int *counts_ptr = merged_normals_counts.ptr();
  330. Vector3 *merged_normals_ptrw = merged_normals.ptr();
  331. for (unsigned int j = 0; j < merged_vertex_count; j++) {
  332. merged_normals_ptrw[j] /= counts_ptr[j];
  333. }
  334. }
  335. LocalVector<float> normal_weights;
  336. normal_weights.resize(merged_vertex_count);
  337. for (unsigned int j = 0; j < merged_vertex_count; j++) {
  338. normal_weights[j] = 2.0; // Give some weight to normal preservation, may be worth exposing as an import setting
  339. }
  340. const float max_mesh_error = FLT_MAX; // We don't want to limit by error, just by index target
  341. float scale = SurfaceTool::simplify_scale_func((const float *)merged_vertices_ptr, merged_vertex_count, sizeof(Vector3));
  342. float mesh_error = 0.0f;
  343. unsigned int index_target = 12; // Start with the smallest target, 4 triangles
  344. unsigned int last_index_count = 0;
  345. int split_vertex_count = vertex_count;
  346. LocalVector<Vector3> split_vertex_normals;
  347. LocalVector<int> split_vertex_indices;
  348. split_vertex_normals.reserve(index_count / 3);
  349. split_vertex_indices.reserve(index_count / 3);
  350. RandomPCG pcg;
  351. pcg.seed(123456789); // Keep seed constant across imports
  352. Ref<StaticRaycaster> raycaster = StaticRaycaster::create();
  353. if (raycaster.is_valid()) {
  354. raycaster->add_mesh(vertices, indices, 0);
  355. raycaster->commit();
  356. }
  357. while (index_target < index_count) {
  358. PackedInt32Array new_indices;
  359. new_indices.resize(index_count);
  360. size_t new_index_count = SurfaceTool::simplify_with_attrib_func((unsigned int *)new_indices.ptrw(), (const uint32_t *)merged_indices_ptr, index_count, (const float *)merged_vertices_ptr, merged_vertex_count, sizeof(Vector3), index_target, max_mesh_error, &mesh_error, (float *)merged_normals.ptr(), normal_weights.ptr(), 3);
  361. if (new_index_count < last_index_count * 1.5f) {
  362. index_target = index_target * 1.5f;
  363. continue;
  364. }
  365. if (new_index_count == 0 || (new_index_count >= (index_count * 0.75f))) {
  366. break;
  367. }
  368. new_indices.resize(new_index_count);
  369. LocalVector<LocalVector<int>> vertex_corners;
  370. vertex_corners.resize(vertex_count);
  371. {
  372. int *ptrw = new_indices.ptrw();
  373. for (unsigned int j = 0; j < new_index_count; j++) {
  374. const int &remapped = vertex_inverse_remap[ptrw[j]];
  375. vertex_corners[remapped].push_back(j);
  376. ptrw[j] = remapped;
  377. }
  378. }
  379. if (raycaster.is_valid()) {
  380. float error_factor = 1.0f / (scale * MAX(mesh_error, 0.15));
  381. const float ray_bias = 0.05;
  382. float ray_length = ray_bias + mesh_error * scale * 3.0f;
  383. Vector<StaticRaycaster::Ray> rays;
  384. LocalVector<Vector2> ray_uvs;
  385. int32_t *new_indices_ptr = new_indices.ptrw();
  386. int current_ray_count = 0;
  387. for (unsigned int j = 0; j < new_index_count; j += 3) {
  388. const Vector3 &v0 = vertices_ptr[new_indices_ptr[j + 0]];
  389. const Vector3 &v1 = vertices_ptr[new_indices_ptr[j + 1]];
  390. const Vector3 &v2 = vertices_ptr[new_indices_ptr[j + 2]];
  391. Vector3 face_normal = vec3_cross(v0 - v2, v0 - v1);
  392. float face_area = face_normal.length(); // Actually twice the face area, since it's the same error_factor on all faces, we don't care
  393. Vector3 dir = face_normal / face_area;
  394. int ray_count = CLAMP(5.0 * face_area * error_factor, 16, 64);
  395. rays.resize(current_ray_count + ray_count);
  396. StaticRaycaster::Ray *rays_ptr = rays.ptrw();
  397. ray_uvs.resize(current_ray_count + ray_count);
  398. Vector2 *ray_uvs_ptr = ray_uvs.ptr();
  399. for (int k = 0; k < ray_count; k++) {
  400. float u = pcg.randf();
  401. float v = pcg.randf();
  402. if (u + v >= 1.0f) {
  403. u = 1.0f - u;
  404. v = 1.0f - v;
  405. }
  406. u = 0.9f * u + 0.05f / 3.0f; // Give barycentric coordinates some padding, we don't want to sample right on the edge
  407. v = 0.9f * v + 0.05f / 3.0f; // v = (v - one_third) * 0.95f + one_third;
  408. float w = 1.0f - u - v;
  409. Vector3 org = v0 * w + v1 * u + v2 * v;
  410. org -= dir * ray_bias;
  411. rays_ptr[current_ray_count + k] = StaticRaycaster::Ray(org, dir, 0.0f, ray_length);
  412. rays_ptr[current_ray_count + k].id = j / 3;
  413. ray_uvs_ptr[current_ray_count + k] = Vector2(u, v);
  414. }
  415. current_ray_count += ray_count;
  416. }
  417. raycaster->intersect(rays);
  418. LocalVector<Vector3> ray_normals;
  419. LocalVector<real_t> ray_normal_weights;
  420. ray_normals.resize(new_index_count);
  421. ray_normal_weights.resize(new_index_count);
  422. for (unsigned int j = 0; j < new_index_count; j++) {
  423. ray_normal_weights[j] = 0.0f;
  424. }
  425. const StaticRaycaster::Ray *rp = rays.ptr();
  426. for (int j = 0; j < rays.size(); j++) {
  427. if (rp[j].geomID != 0) { // Ray missed
  428. continue;
  429. }
  430. if (rp[j].normal.normalized().dot(rp[j].dir) > 0.0f) { // Hit a back face.
  431. continue;
  432. }
  433. const float &u = rp[j].u;
  434. const float &v = rp[j].v;
  435. const float w = 1.0f - u - v;
  436. const unsigned int &hit_tri_id = rp[j].primID;
  437. const unsigned int &orig_tri_id = rp[j].id;
  438. const Vector3 &n0 = normals_ptr[indices_ptr[hit_tri_id * 3 + 0]];
  439. const Vector3 &n1 = normals_ptr[indices_ptr[hit_tri_id * 3 + 1]];
  440. const Vector3 &n2 = normals_ptr[indices_ptr[hit_tri_id * 3 + 2]];
  441. Vector3 normal = n0 * w + n1 * u + n2 * v;
  442. Vector2 orig_uv = ray_uvs[j];
  443. const real_t orig_bary[3] = { 1.0f - orig_uv.x - orig_uv.y, orig_uv.x, orig_uv.y };
  444. for (int k = 0; k < 3; k++) {
  445. int idx = orig_tri_id * 3 + k;
  446. real_t weight = orig_bary[k];
  447. ray_normals[idx] += normal * weight;
  448. ray_normal_weights[idx] += weight;
  449. }
  450. }
  451. for (unsigned int j = 0; j < new_index_count; j++) {
  452. if (ray_normal_weights[j] < 1.0f) { // Not enough data, the new normal would be just a bad guess
  453. ray_normals[j] = Vector3();
  454. } else {
  455. ray_normals[j] /= ray_normal_weights[j];
  456. }
  457. }
  458. LocalVector<LocalVector<int>> normal_group_indices;
  459. LocalVector<Vector3> normal_group_averages;
  460. normal_group_indices.reserve(24);
  461. normal_group_averages.reserve(24);
  462. for (unsigned int j = 0; j < vertex_count; j++) {
  463. const LocalVector<int> &corners = vertex_corners[j];
  464. const Vector3 &vertex_normal = normals_ptr[j];
  465. for (unsigned int k = 0; k < corners.size(); k++) {
  466. const int &corner_idx = corners[k];
  467. const Vector3 &ray_normal = ray_normals[corner_idx];
  468. if (ray_normal.length_squared() < CMP_EPSILON2) {
  469. continue;
  470. }
  471. bool found = false;
  472. for (unsigned int l = 0; l < normal_group_indices.size(); l++) {
  473. LocalVector<int> &group_indices = normal_group_indices[l];
  474. Vector3 n = normal_group_averages[l] / group_indices.size();
  475. if (n.dot(ray_normal) > normal_pre_split_threshold) {
  476. found = true;
  477. group_indices.push_back(corner_idx);
  478. normal_group_averages[l] += ray_normal;
  479. break;
  480. }
  481. }
  482. if (!found) {
  483. LocalVector<int> new_group;
  484. new_group.push_back(corner_idx);
  485. normal_group_indices.push_back(new_group);
  486. normal_group_averages.push_back(ray_normal);
  487. }
  488. }
  489. for (unsigned int k = 0; k < normal_group_indices.size(); k++) {
  490. LocalVector<int> &group_indices = normal_group_indices[k];
  491. Vector3 n = normal_group_averages[k] / group_indices.size();
  492. if (vertex_normal.dot(n) < normal_split_threshold) {
  493. split_vertex_indices.push_back(j);
  494. split_vertex_normals.push_back(n);
  495. int new_idx = split_vertex_count++;
  496. for (unsigned int l = 0; l < group_indices.size(); l++) {
  497. new_indices_ptr[group_indices[l]] = new_idx;
  498. }
  499. }
  500. }
  501. normal_group_indices.clear();
  502. normal_group_averages.clear();
  503. }
  504. }
  505. Surface::LOD lod;
  506. lod.distance = MAX(mesh_error * scale, CMP_EPSILON2);
  507. lod.indices = new_indices;
  508. surfaces.write[i].lods.push_back(lod);
  509. index_target = MAX(new_index_count, index_target) * 2;
  510. last_index_count = new_index_count;
  511. if (mesh_error == 0.0f) {
  512. break;
  513. }
  514. }
  515. surfaces.write[i].split_normals(split_vertex_indices, split_vertex_normals);
  516. surfaces.write[i].lods.sort_custom<Surface::LODComparator>();
  517. for (int j = 0; j < surfaces.write[i].lods.size(); j++) {
  518. Surface::LOD &lod = surfaces.write[i].lods.write[j];
  519. unsigned int *lod_indices_ptr = (unsigned int *)lod.indices.ptrw();
  520. SurfaceTool::optimize_vertex_cache_func(lod_indices_ptr, lod_indices_ptr, lod.indices.size(), split_vertex_count);
  521. }
  522. }
  523. }
  524. bool ImporterMesh::has_mesh() const {
  525. return mesh.is_valid();
  526. }
  527. Ref<ArrayMesh> ImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) {
  528. ERR_FAIL_COND_V(surfaces.size() == 0, Ref<ArrayMesh>());
  529. if (mesh.is_null()) {
  530. if (p_base.is_valid()) {
  531. mesh = p_base;
  532. }
  533. if (mesh.is_null()) {
  534. mesh.instantiate();
  535. }
  536. mesh->set_name(get_name());
  537. if (has_meta("import_id")) {
  538. mesh->set_meta("import_id", get_meta("import_id"));
  539. }
  540. for (int i = 0; i < blend_shapes.size(); i++) {
  541. mesh->add_blend_shape(blend_shapes[i]);
  542. }
  543. mesh->set_blend_shape_mode(blend_shape_mode);
  544. for (int i = 0; i < surfaces.size(); i++) {
  545. Array bs_data;
  546. if (surfaces[i].blend_shape_data.size()) {
  547. for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
  548. bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
  549. }
  550. }
  551. Dictionary lods;
  552. if (surfaces[i].lods.size()) {
  553. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  554. lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
  555. }
  556. }
  557. mesh->add_surface_from_arrays(surfaces[i].primitive, surfaces[i].arrays, bs_data, lods, surfaces[i].flags);
  558. if (surfaces[i].material.is_valid()) {
  559. mesh->surface_set_material(mesh->get_surface_count() - 1, surfaces[i].material);
  560. }
  561. if (!surfaces[i].name.is_empty()) {
  562. mesh->surface_set_name(mesh->get_surface_count() - 1, surfaces[i].name);
  563. }
  564. }
  565. mesh->set_lightmap_size_hint(lightmap_size_hint);
  566. if (shadow_mesh.is_valid()) {
  567. Ref<ArrayMesh> shadow = shadow_mesh->get_mesh();
  568. mesh->set_shadow_mesh(shadow);
  569. }
  570. }
  571. return mesh;
  572. }
  573. void ImporterMesh::clear() {
  574. surfaces.clear();
  575. blend_shapes.clear();
  576. mesh.unref();
  577. }
  578. void ImporterMesh::create_shadow_mesh() {
  579. if (shadow_mesh.is_valid()) {
  580. shadow_mesh.unref();
  581. }
  582. //no shadow mesh for blendshapes
  583. if (blend_shapes.size() > 0) {
  584. return;
  585. }
  586. //no shadow mesh for skeletons
  587. for (int i = 0; i < surfaces.size(); i++) {
  588. if (surfaces[i].arrays[RS::ARRAY_BONES].get_type() != Variant::NIL) {
  589. return;
  590. }
  591. if (surfaces[i].arrays[RS::ARRAY_WEIGHTS].get_type() != Variant::NIL) {
  592. return;
  593. }
  594. }
  595. shadow_mesh.instantiate();
  596. for (int i = 0; i < surfaces.size(); i++) {
  597. LocalVector<int> vertex_remap;
  598. Vector<Vector3> new_vertices;
  599. Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];
  600. int vertex_count = vertices.size();
  601. {
  602. HashMap<Vector3, int> unique_vertices;
  603. const Vector3 *vptr = vertices.ptr();
  604. for (int j = 0; j < vertex_count; j++) {
  605. const Vector3 &v = vptr[j];
  606. HashMap<Vector3, int>::Iterator E = unique_vertices.find(v);
  607. if (E) {
  608. vertex_remap.push_back(E->value);
  609. } else {
  610. int vcount = unique_vertices.size();
  611. unique_vertices[v] = vcount;
  612. vertex_remap.push_back(vcount);
  613. new_vertices.push_back(v);
  614. }
  615. }
  616. }
  617. Array new_surface;
  618. new_surface.resize(RS::ARRAY_MAX);
  619. Dictionary lods;
  620. // print_line("original vertex count: " + itos(vertices.size()) + " new vertex count: " + itos(new_vertices.size()));
  621. new_surface[RS::ARRAY_VERTEX] = new_vertices;
  622. Vector<int> indices = surfaces[i].arrays[RS::ARRAY_INDEX];
  623. if (indices.size()) {
  624. int index_count = indices.size();
  625. const int *index_rptr = indices.ptr();
  626. Vector<int> new_indices;
  627. new_indices.resize(indices.size());
  628. int *index_wptr = new_indices.ptrw();
  629. for (int j = 0; j < index_count; j++) {
  630. int index = index_rptr[j];
  631. ERR_FAIL_INDEX(index, vertex_count);
  632. index_wptr[j] = vertex_remap[index];
  633. }
  634. new_surface[RS::ARRAY_INDEX] = new_indices;
  635. // Make sure the same LODs as the full version are used.
  636. // This makes it more coherent between rendered model and its shadows.
  637. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  638. indices = surfaces[i].lods[j].indices;
  639. index_count = indices.size();
  640. index_rptr = indices.ptr();
  641. new_indices.resize(indices.size());
  642. index_wptr = new_indices.ptrw();
  643. for (int k = 0; k < index_count; k++) {
  644. int index = index_rptr[k];
  645. ERR_FAIL_INDEX(index, vertex_count);
  646. index_wptr[k] = vertex_remap[index];
  647. }
  648. lods[surfaces[i].lods[j].distance] = new_indices;
  649. }
  650. }
  651. shadow_mesh->add_surface(surfaces[i].primitive, new_surface, Array(), lods, Ref<Material>(), surfaces[i].name, surfaces[i].flags);
  652. }
  653. }
  654. Ref<ImporterMesh> ImporterMesh::get_shadow_mesh() const {
  655. return shadow_mesh;
  656. }
  657. void ImporterMesh::_set_data(const Dictionary &p_data) {
  658. clear();
  659. if (p_data.has("blend_shape_names")) {
  660. blend_shapes = p_data["blend_shape_names"];
  661. }
  662. if (p_data.has("surfaces")) {
  663. Array surface_arr = p_data["surfaces"];
  664. for (int i = 0; i < surface_arr.size(); i++) {
  665. Dictionary s = surface_arr[i];
  666. ERR_CONTINUE(!s.has("primitive"));
  667. ERR_CONTINUE(!s.has("arrays"));
  668. Mesh::PrimitiveType prim = Mesh::PrimitiveType(int(s["primitive"]));
  669. ERR_CONTINUE(prim >= Mesh::PRIMITIVE_MAX);
  670. Array arr = s["arrays"];
  671. Dictionary lods;
  672. String name;
  673. if (s.has("name")) {
  674. name = s["name"];
  675. }
  676. if (s.has("lods")) {
  677. lods = s["lods"];
  678. }
  679. Array b_shapes;
  680. if (s.has("b_shapes")) {
  681. b_shapes = s["b_shapes"];
  682. }
  683. Ref<Material> material;
  684. if (s.has("material")) {
  685. material = s["material"];
  686. }
  687. uint32_t flags = 0;
  688. if (s.has("flags")) {
  689. flags = s["flags"];
  690. }
  691. add_surface(prim, arr, b_shapes, lods, material, name, flags);
  692. }
  693. }
  694. }
  695. Dictionary ImporterMesh::_get_data() const {
  696. Dictionary data;
  697. if (blend_shapes.size()) {
  698. data["blend_shape_names"] = blend_shapes;
  699. }
  700. Array surface_arr;
  701. for (int i = 0; i < surfaces.size(); i++) {
  702. Dictionary d;
  703. d["primitive"] = surfaces[i].primitive;
  704. d["arrays"] = surfaces[i].arrays;
  705. if (surfaces[i].blend_shape_data.size()) {
  706. Array bs_data;
  707. for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {
  708. bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);
  709. }
  710. d["blend_shapes"] = bs_data;
  711. }
  712. if (surfaces[i].lods.size()) {
  713. Dictionary lods;
  714. for (int j = 0; j < surfaces[i].lods.size(); j++) {
  715. lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;
  716. }
  717. d["lods"] = lods;
  718. }
  719. if (surfaces[i].material.is_valid()) {
  720. d["material"] = surfaces[i].material;
  721. }
  722. if (!surfaces[i].name.is_empty()) {
  723. d["name"] = surfaces[i].name;
  724. }
  725. if (surfaces[i].flags != 0) {
  726. d["flags"] = surfaces[i].flags;
  727. }
  728. surface_arr.push_back(d);
  729. }
  730. data["surfaces"] = surface_arr;
  731. return data;
  732. }
  733. Vector<Face3> ImporterMesh::get_faces() const {
  734. Vector<Face3> faces;
  735. for (int i = 0; i < surfaces.size(); i++) {
  736. if (surfaces[i].primitive == Mesh::PRIMITIVE_TRIANGLES) {
  737. Vector<Vector3> vertices = surfaces[i].arrays[Mesh::ARRAY_VERTEX];
  738. Vector<int> indices = surfaces[i].arrays[Mesh::ARRAY_INDEX];
  739. if (indices.size()) {
  740. for (int j = 0; j < indices.size(); j += 3) {
  741. Face3 f;
  742. f.vertex[0] = vertices[indices[j + 0]];
  743. f.vertex[1] = vertices[indices[j + 1]];
  744. f.vertex[2] = vertices[indices[j + 2]];
  745. faces.push_back(f);
  746. }
  747. } else {
  748. for (int j = 0; j < vertices.size(); j += 3) {
  749. Face3 f;
  750. f.vertex[0] = vertices[j + 0];
  751. f.vertex[1] = vertices[j + 1];
  752. f.vertex[2] = vertices[j + 2];
  753. faces.push_back(f);
  754. }
  755. }
  756. }
  757. }
  758. return faces;
  759. }
  760. Vector<Ref<Shape3D>> ImporterMesh::convex_decompose(const Mesh::ConvexDecompositionSettings &p_settings) const {
  761. ERR_FAIL_COND_V(!Mesh::convex_decomposition_function, Vector<Ref<Shape3D>>());
  762. const Vector<Face3> faces = get_faces();
  763. int face_count = faces.size();
  764. Vector<Vector3> vertices;
  765. uint32_t vertex_count = 0;
  766. vertices.resize(face_count * 3);
  767. Vector<uint32_t> indices;
  768. indices.resize(face_count * 3);
  769. {
  770. HashMap<Vector3, uint32_t> vertex_map;
  771. Vector3 *vertex_w = vertices.ptrw();
  772. uint32_t *index_w = indices.ptrw();
  773. for (int i = 0; i < face_count; i++) {
  774. for (int j = 0; j < 3; j++) {
  775. const Vector3 &vertex = faces[i].vertex[j];
  776. HashMap<Vector3, uint32_t>::Iterator found_vertex = vertex_map.find(vertex);
  777. uint32_t index;
  778. if (found_vertex) {
  779. index = found_vertex->value;
  780. } else {
  781. index = ++vertex_count;
  782. vertex_map[vertex] = index;
  783. vertex_w[index] = vertex;
  784. }
  785. index_w[i * 3 + j] = index;
  786. }
  787. }
  788. }
  789. vertices.resize(vertex_count);
  790. Vector<Vector<Vector3>> decomposed = Mesh::convex_decomposition_function((real_t *)vertices.ptr(), vertex_count, indices.ptr(), face_count, p_settings, nullptr);
  791. Vector<Ref<Shape3D>> ret;
  792. for (int i = 0; i < decomposed.size(); i++) {
  793. Ref<ConvexPolygonShape3D> shape;
  794. shape.instantiate();
  795. shape->set_points(decomposed[i]);
  796. ret.push_back(shape);
  797. }
  798. return ret;
  799. }
  800. Ref<Shape3D> ImporterMesh::create_trimesh_shape() const {
  801. Vector<Face3> faces = get_faces();
  802. if (faces.size() == 0) {
  803. return Ref<Shape3D>();
  804. }
  805. Vector<Vector3> face_points;
  806. face_points.resize(faces.size() * 3);
  807. for (int i = 0; i < face_points.size(); i += 3) {
  808. Face3 f = faces.get(i / 3);
  809. face_points.set(i, f.vertex[0]);
  810. face_points.set(i + 1, f.vertex[1]);
  811. face_points.set(i + 2, f.vertex[2]);
  812. }
  813. Ref<ConcavePolygonShape3D> shape = memnew(ConcavePolygonShape3D);
  814. shape->set_faces(face_points);
  815. return shape;
  816. }
  817. Ref<NavigationMesh> ImporterMesh::create_navigation_mesh() {
  818. Vector<Face3> faces = get_faces();
  819. if (faces.size() == 0) {
  820. return Ref<NavigationMesh>();
  821. }
  822. HashMap<Vector3, int> unique_vertices;
  823. LocalVector<int> face_indices;
  824. for (int i = 0; i < faces.size(); i++) {
  825. for (int j = 0; j < 3; j++) {
  826. Vector3 v = faces[i].vertex[j];
  827. int idx;
  828. if (unique_vertices.has(v)) {
  829. idx = unique_vertices[v];
  830. } else {
  831. idx = unique_vertices.size();
  832. unique_vertices[v] = idx;
  833. }
  834. face_indices.push_back(idx);
  835. }
  836. }
  837. Vector<Vector3> vertices;
  838. vertices.resize(unique_vertices.size());
  839. for (const KeyValue<Vector3, int> &E : unique_vertices) {
  840. vertices.write[E.value] = E.key;
  841. }
  842. Ref<NavigationMesh> nm;
  843. nm.instantiate();
  844. nm->set_vertices(vertices);
  845. Vector<int> v3;
  846. v3.resize(3);
  847. for (uint32_t i = 0; i < face_indices.size(); i += 3) {
  848. v3.write[0] = face_indices[i + 0];
  849. v3.write[1] = face_indices[i + 1];
  850. v3.write[2] = face_indices[i + 2];
  851. nm->add_polygon(v3);
  852. }
  853. return nm;
  854. }
  855. 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);
  856. struct EditorSceneFormatImporterMeshLightmapSurface {
  857. Ref<Material> material;
  858. LocalVector<SurfaceTool::Vertex> vertices;
  859. Mesh::PrimitiveType primitive = Mesh::PrimitiveType::PRIMITIVE_MAX;
  860. uint32_t format = 0;
  861. String name;
  862. };
  863. 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) {
  864. ERR_FAIL_COND_V(!array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);
  865. ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");
  866. LocalVector<float> vertices;
  867. LocalVector<float> normals;
  868. LocalVector<int> indices;
  869. LocalVector<float> uv;
  870. LocalVector<Pair<int, int>> uv_indices;
  871. Vector<EditorSceneFormatImporterMeshLightmapSurface> lightmap_surfaces;
  872. // Keep only the scale
  873. Basis basis = p_base_transform.get_basis();
  874. Vector3 scale = Vector3(basis.get_column(0).length(), basis.get_column(1).length(), basis.get_column(2).length());
  875. Transform3D transform;
  876. transform.scale(scale);
  877. Basis normal_basis = transform.basis.inverse().transposed();
  878. for (int i = 0; i < get_surface_count(); i++) {
  879. EditorSceneFormatImporterMeshLightmapSurface s;
  880. s.primitive = get_surface_primitive_type(i);
  881. ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");
  882. Array arrays = get_surface_arrays(i);
  883. s.material = get_surface_material(i);
  884. s.name = get_surface_name(i);
  885. SurfaceTool::create_vertex_array_from_triangle_arrays(arrays, s.vertices, &s.format);
  886. PackedVector3Array rvertices = arrays[Mesh::ARRAY_VERTEX];
  887. int vc = rvertices.size();
  888. PackedVector3Array rnormals = arrays[Mesh::ARRAY_NORMAL];
  889. if (!rnormals.size()) {
  890. continue;
  891. }
  892. int vertex_ofs = vertices.size() / 3;
  893. vertices.resize((vertex_ofs + vc) * 3);
  894. normals.resize((vertex_ofs + vc) * 3);
  895. uv_indices.resize(vertex_ofs + vc);
  896. for (int j = 0; j < vc; j++) {
  897. Vector3 v = transform.xform(rvertices[j]);
  898. Vector3 n = normal_basis.xform(rnormals[j]).normalized();
  899. vertices[(j + vertex_ofs) * 3 + 0] = v.x;
  900. vertices[(j + vertex_ofs) * 3 + 1] = v.y;
  901. vertices[(j + vertex_ofs) * 3 + 2] = v.z;
  902. normals[(j + vertex_ofs) * 3 + 0] = n.x;
  903. normals[(j + vertex_ofs) * 3 + 1] = n.y;
  904. normals[(j + vertex_ofs) * 3 + 2] = n.z;
  905. uv_indices[j + vertex_ofs] = Pair<int, int>(i, j);
  906. }
  907. PackedInt32Array rindices = arrays[Mesh::ARRAY_INDEX];
  908. int ic = rindices.size();
  909. float eps = 1.19209290e-7F; // Taken from xatlas.h
  910. if (ic == 0) {
  911. for (int j = 0; j < vc / 3; j++) {
  912. Vector3 p0 = transform.xform(rvertices[j * 3 + 0]);
  913. Vector3 p1 = transform.xform(rvertices[j * 3 + 1]);
  914. Vector3 p2 = transform.xform(rvertices[j * 3 + 2]);
  915. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  916. continue;
  917. }
  918. indices.push_back(vertex_ofs + j * 3 + 0);
  919. indices.push_back(vertex_ofs + j * 3 + 1);
  920. indices.push_back(vertex_ofs + j * 3 + 2);
  921. }
  922. } else {
  923. for (int j = 0; j < ic / 3; j++) {
  924. ERR_FAIL_INDEX_V(rindices[j * 3 + 0], rvertices.size(), ERR_INVALID_DATA);
  925. ERR_FAIL_INDEX_V(rindices[j * 3 + 1], rvertices.size(), ERR_INVALID_DATA);
  926. ERR_FAIL_INDEX_V(rindices[j * 3 + 2], rvertices.size(), ERR_INVALID_DATA);
  927. Vector3 p0 = transform.xform(rvertices[rindices[j * 3 + 0]]);
  928. Vector3 p1 = transform.xform(rvertices[rindices[j * 3 + 1]]);
  929. Vector3 p2 = transform.xform(rvertices[rindices[j * 3 + 2]]);
  930. if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {
  931. continue;
  932. }
  933. indices.push_back(vertex_ofs + rindices[j * 3 + 0]);
  934. indices.push_back(vertex_ofs + rindices[j * 3 + 1]);
  935. indices.push_back(vertex_ofs + rindices[j * 3 + 2]);
  936. }
  937. }
  938. lightmap_surfaces.push_back(s);
  939. }
  940. //unwrap
  941. bool use_cache = true; // Used to request cache generation and to know if cache was used
  942. uint8_t *gen_cache;
  943. int gen_cache_size;
  944. float *gen_uvs;
  945. int *gen_vertices;
  946. int *gen_indices;
  947. int gen_vertex_count;
  948. int gen_index_count;
  949. int size_x;
  950. int size_y;
  951. 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);
  952. if (!ok) {
  953. return ERR_CANT_CREATE;
  954. }
  955. //remove surfaces
  956. clear();
  957. //create surfacetools for each surface..
  958. LocalVector<Ref<SurfaceTool>> surfaces_tools;
  959. for (int i = 0; i < lightmap_surfaces.size(); i++) {
  960. Ref<SurfaceTool> st;
  961. st.instantiate();
  962. st->begin(Mesh::PRIMITIVE_TRIANGLES);
  963. st->set_material(lightmap_surfaces[i].material);
  964. st->set_meta("name", lightmap_surfaces[i].name);
  965. surfaces_tools.push_back(st); //stay there
  966. }
  967. print_verbose("Mesh: Gen indices: " + itos(gen_index_count));
  968. //go through all indices
  969. for (int i = 0; i < gen_index_count; i += 3) {
  970. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], (int)uv_indices.size(), ERR_BUG);
  971. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], (int)uv_indices.size(), ERR_BUG);
  972. ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], (int)uv_indices.size(), ERR_BUG);
  973. 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);
  974. int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;
  975. for (int j = 0; j < 3; j++) {
  976. SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];
  977. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_COLOR) {
  978. surfaces_tools[surface]->set_color(v.color);
  979. }
  980. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TEX_UV) {
  981. surfaces_tools[surface]->set_uv(v.uv);
  982. }
  983. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_NORMAL) {
  984. surfaces_tools[surface]->set_normal(v.normal);
  985. }
  986. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TANGENT) {
  987. Plane t;
  988. t.normal = v.tangent;
  989. t.d = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;
  990. surfaces_tools[surface]->set_tangent(t);
  991. }
  992. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_BONES) {
  993. surfaces_tools[surface]->set_bones(v.bones);
  994. }
  995. if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_WEIGHTS) {
  996. surfaces_tools[surface]->set_weights(v.weights);
  997. }
  998. Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);
  999. surfaces_tools[surface]->set_uv2(uv2);
  1000. surfaces_tools[surface]->add_vertex(v.vertex);
  1001. }
  1002. }
  1003. //generate surfaces
  1004. for (unsigned int i = 0; i < surfaces_tools.size(); i++) {
  1005. surfaces_tools[i]->index();
  1006. Array arrays = surfaces_tools[i]->commit_to_arrays();
  1007. add_surface(surfaces_tools[i]->get_primitive_type(), arrays, Array(), Dictionary(), surfaces_tools[i]->get_material(), surfaces_tools[i]->get_meta("name"));
  1008. }
  1009. set_lightmap_size_hint(Size2(size_x, size_y));
  1010. if (gen_cache_size > 0) {
  1011. r_dst_cache.resize(gen_cache_size);
  1012. memcpy(r_dst_cache.ptrw(), gen_cache, gen_cache_size);
  1013. memfree(gen_cache);
  1014. }
  1015. if (!use_cache) {
  1016. // Cache was not used, free the buffers
  1017. memfree(gen_vertices);
  1018. memfree(gen_indices);
  1019. memfree(gen_uvs);
  1020. }
  1021. return OK;
  1022. }
  1023. void ImporterMesh::set_lightmap_size_hint(const Size2i &p_size) {
  1024. lightmap_size_hint = p_size;
  1025. }
  1026. Size2i ImporterMesh::get_lightmap_size_hint() const {
  1027. return lightmap_size_hint;
  1028. }
  1029. void ImporterMesh::_bind_methods() {
  1030. ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ImporterMesh::add_blend_shape);
  1031. ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ImporterMesh::get_blend_shape_count);
  1032. ClassDB::bind_method(D_METHOD("get_blend_shape_name", "blend_shape_idx"), &ImporterMesh::get_blend_shape_name);
  1033. ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ImporterMesh::set_blend_shape_mode);
  1034. ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ImporterMesh::get_blend_shape_mode);
  1035. ClassDB::bind_method(D_METHOD("add_surface", "primitive", "arrays", "blend_shapes", "lods", "material", "name", "flags"), &ImporterMesh::add_surface, DEFVAL(Array()), DEFVAL(Dictionary()), DEFVAL(Ref<Material>()), DEFVAL(String()), DEFVAL(0));
  1036. ClassDB::bind_method(D_METHOD("get_surface_count"), &ImporterMesh::get_surface_count);
  1037. ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &ImporterMesh::get_surface_primitive_type);
  1038. ClassDB::bind_method(D_METHOD("get_surface_name", "surface_idx"), &ImporterMesh::get_surface_name);
  1039. ClassDB::bind_method(D_METHOD("get_surface_arrays", "surface_idx"), &ImporterMesh::get_surface_arrays);
  1040. ClassDB::bind_method(D_METHOD("get_surface_blend_shape_arrays", "surface_idx", "blend_shape_idx"), &ImporterMesh::get_surface_blend_shape_arrays);
  1041. ClassDB::bind_method(D_METHOD("get_surface_lod_count", "surface_idx"), &ImporterMesh::get_surface_lod_count);
  1042. ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_size);
  1043. ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_indices);
  1044. ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &ImporterMesh::get_surface_material);
  1045. ClassDB::bind_method(D_METHOD("get_surface_format", "surface_idx"), &ImporterMesh::get_surface_format);
  1046. ClassDB::bind_method(D_METHOD("set_surface_name", "surface_idx", "name"), &ImporterMesh::set_surface_name);
  1047. ClassDB::bind_method(D_METHOD("set_surface_material", "surface_idx", "material"), &ImporterMesh::set_surface_material);
  1048. ClassDB::bind_method(D_METHOD("generate_lods", "normal_merge_angle", "normal_split_angle"), &ImporterMesh::generate_lods);
  1049. ClassDB::bind_method(D_METHOD("get_mesh", "base_mesh"), &ImporterMesh::get_mesh, DEFVAL(Ref<ArrayMesh>()));
  1050. ClassDB::bind_method(D_METHOD("clear"), &ImporterMesh::clear);
  1051. ClassDB::bind_method(D_METHOD("_set_data", "data"), &ImporterMesh::_set_data);
  1052. ClassDB::bind_method(D_METHOD("_get_data"), &ImporterMesh::_get_data);
  1053. ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &ImporterMesh::set_lightmap_size_hint);
  1054. ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &ImporterMesh::get_lightmap_size_hint);
  1055. ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "_set_data", "_get_data");
  1056. }