importer_mesh.cpp 48 KB

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