surface_tool.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  1. /**************************************************************************/
  2. /* surface_tool.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 "surface_tool.h"
  31. #include "core/templates/a_hash_map.h"
  32. #define EQ_VERTEX_DIST 0.00001
  33. SurfaceTool::OptimizeVertexCacheFunc SurfaceTool::optimize_vertex_cache_func = nullptr;
  34. SurfaceTool::OptimizeVertexFetchRemapFunc SurfaceTool::optimize_vertex_fetch_remap_func = nullptr;
  35. SurfaceTool::SimplifyFunc SurfaceTool::simplify_func = nullptr;
  36. SurfaceTool::SimplifyWithAttribFunc SurfaceTool::simplify_with_attrib_func = nullptr;
  37. SurfaceTool::SimplifyScaleFunc SurfaceTool::simplify_scale_func = nullptr;
  38. SurfaceTool::GenerateRemapFunc SurfaceTool::generate_remap_func = nullptr;
  39. SurfaceTool::RemapVertexFunc SurfaceTool::remap_vertex_func = nullptr;
  40. SurfaceTool::RemapIndexFunc SurfaceTool::remap_index_func = nullptr;
  41. void SurfaceTool::strip_mesh_arrays(PackedVector3Array &r_vertices, PackedInt32Array &r_indices) {
  42. ERR_FAIL_COND_MSG(!generate_remap_func || !remap_vertex_func || !remap_index_func, "Meshoptimizer library is not initialized.");
  43. Vector<uint32_t> remap;
  44. remap.resize(r_vertices.size());
  45. uint32_t new_vertex_count = generate_remap_func(remap.ptrw(), (unsigned int *)r_indices.ptr(), r_indices.size(), r_vertices.ptr(), r_vertices.size(), sizeof(Vector3));
  46. remap_vertex_func(r_vertices.ptrw(), r_vertices.ptr(), r_vertices.size(), sizeof(Vector3), remap.ptr());
  47. r_vertices.resize(new_vertex_count);
  48. remap_index_func((unsigned int *)r_indices.ptrw(), (unsigned int *)r_indices.ptr(), r_indices.size(), remap.ptr());
  49. AHashMap<const int *, bool, TriangleHasher, TriangleHasher> found_triangles;
  50. int *idx_ptr = r_indices.ptrw();
  51. int filtered_indices_count = 0;
  52. for (int i = 0; i < r_indices.size() / 3; i++) {
  53. const int *tri = idx_ptr + (i * 3);
  54. if (tri[0] == tri[1] || tri[1] == tri[2] || tri[2] == tri[0]) {
  55. continue;
  56. }
  57. if (found_triangles.has(tri)) {
  58. continue;
  59. }
  60. if (i != filtered_indices_count) {
  61. memcpy(idx_ptr + (filtered_indices_count * 3), tri, sizeof(int) * 3);
  62. }
  63. found_triangles.insert_new(tri, true);
  64. filtered_indices_count++;
  65. }
  66. r_indices.resize(filtered_indices_count * 3);
  67. }
  68. bool SurfaceTool::Vertex::operator==(const Vertex &p_vertex) const {
  69. if (vertex != p_vertex.vertex) {
  70. return false;
  71. }
  72. if (uv != p_vertex.uv) {
  73. return false;
  74. }
  75. if (uv2 != p_vertex.uv2) {
  76. return false;
  77. }
  78. if (normal != p_vertex.normal) {
  79. return false;
  80. }
  81. if (binormal != p_vertex.binormal) {
  82. return false;
  83. }
  84. if (tangent != p_vertex.tangent) {
  85. return false;
  86. }
  87. if (color != p_vertex.color) {
  88. return false;
  89. }
  90. if (bones.size() != p_vertex.bones.size()) {
  91. return false;
  92. }
  93. for (int i = 0; i < bones.size(); i++) {
  94. if (bones[i] != p_vertex.bones[i]) {
  95. return false;
  96. }
  97. }
  98. for (int i = 0; i < weights.size(); i++) {
  99. if (weights[i] != p_vertex.weights[i]) {
  100. return false;
  101. }
  102. }
  103. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  104. if (custom[i] != p_vertex.custom[i]) {
  105. return false;
  106. }
  107. }
  108. if (smooth_group != p_vertex.smooth_group) {
  109. return false;
  110. }
  111. return true;
  112. }
  113. uint32_t SurfaceTool::VertexHasher::hash(const Vertex &p_vtx) {
  114. uint32_t h = hash_djb2_buffer((const uint8_t *)p_vtx.bones.ptr(), p_vtx.bones.size() * sizeof(int));
  115. h = hash_djb2_buffer((const uint8_t *)p_vtx.weights.ptr(), p_vtx.weights.size() * sizeof(float), h);
  116. const int64_t length = (int64_t)&p_vtx.vertex - (int64_t)&p_vtx.smooth_group + sizeof(p_vtx.vertex);
  117. const void *key = &p_vtx.smooth_group;
  118. h = hash_murmur3_buffer(key, length, h);
  119. return h;
  120. }
  121. bool SurfaceTool::SmoothGroupVertex::operator==(const SmoothGroupVertex &p_vertex) const {
  122. if (vertex != p_vertex.vertex) {
  123. return false;
  124. }
  125. if (smooth_group != p_vertex.smooth_group) {
  126. return false;
  127. }
  128. return true;
  129. }
  130. uint32_t SurfaceTool::SmoothGroupVertexHasher::hash(const SmoothGroupVertex &p_vtx) {
  131. uint32_t h = HashMapHasherDefault::hash(p_vtx.vertex);
  132. h = hash_murmur3_one_32(p_vtx.smooth_group, h);
  133. h = hash_fmix32(h);
  134. return h;
  135. }
  136. uint32_t SurfaceTool::TriangleHasher::hash(const int *p_triangle) {
  137. int t0 = p_triangle[0];
  138. int t1 = p_triangle[1];
  139. int t2 = p_triangle[2];
  140. if (t0 > t1) {
  141. SWAP(t0, t1);
  142. }
  143. if (t1 > t2) {
  144. SWAP(t1, t2);
  145. }
  146. if (t0 > t1) {
  147. SWAP(t0, t1);
  148. }
  149. return (t0 * 73856093) ^ (t1 * 19349663) ^ (t2 * 83492791);
  150. }
  151. bool SurfaceTool::TriangleHasher::compare(const int *p_lhs, const int *p_rhs) {
  152. int r0 = p_rhs[0];
  153. int r1 = p_rhs[1];
  154. int r2 = p_rhs[2];
  155. if (r0 > r1) {
  156. SWAP(r0, r1);
  157. }
  158. if (r1 > r2) {
  159. SWAP(r1, r2);
  160. }
  161. if (r0 > r1) {
  162. SWAP(r0, r1);
  163. }
  164. int l0 = p_lhs[0];
  165. int l1 = p_lhs[1];
  166. int l2 = p_lhs[2];
  167. if (l0 > l1) {
  168. SWAP(l0, l1);
  169. }
  170. if (l1 > l2) {
  171. SWAP(l1, l2);
  172. }
  173. if (l0 > l1) {
  174. SWAP(l0, l1);
  175. }
  176. return l0 == r0 && l1 == r1 && l2 == r2;
  177. }
  178. void SurfaceTool::begin(Mesh::PrimitiveType p_primitive) {
  179. clear();
  180. primitive = p_primitive;
  181. begun = true;
  182. first = true;
  183. }
  184. void SurfaceTool::add_vertex(const Vector3 &p_vertex) {
  185. ERR_FAIL_COND(!begun);
  186. Vertex vtx;
  187. vtx.vertex = p_vertex;
  188. vtx.color = last_color;
  189. vtx.normal = last_normal;
  190. vtx.uv = last_uv;
  191. vtx.uv2 = last_uv2;
  192. vtx.weights = last_weights;
  193. vtx.bones = last_bones;
  194. vtx.tangent = last_tangent.normal;
  195. vtx.binormal = last_normal.cross(last_tangent.normal).normalized() * last_tangent.d;
  196. vtx.smooth_group = last_smooth_group;
  197. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  198. vtx.custom[i] = last_custom[i];
  199. }
  200. const int expected_vertices = skin_weights == SKIN_8_WEIGHTS ? 8 : 4;
  201. if ((format & Mesh::ARRAY_FORMAT_WEIGHTS || format & Mesh::ARRAY_FORMAT_BONES) && (vtx.weights.size() != expected_vertices || vtx.bones.size() != expected_vertices)) {
  202. //ensure vertices are the expected amount
  203. ERR_FAIL_COND(vtx.weights.size() != vtx.bones.size());
  204. if (vtx.weights.size() < expected_vertices) {
  205. //less than required, fill
  206. for (int i = vtx.weights.size(); i < expected_vertices; i++) {
  207. vtx.weights.push_back(0);
  208. vtx.bones.push_back(0);
  209. }
  210. } else if (vtx.weights.size() > expected_vertices) {
  211. //more than required, sort, cap and normalize.
  212. Vector<WeightSort> weights;
  213. for (int i = 0; i < vtx.weights.size(); i++) {
  214. WeightSort ws;
  215. ws.index = vtx.bones[i];
  216. ws.weight = vtx.weights[i];
  217. weights.push_back(ws);
  218. }
  219. //sort
  220. weights.sort();
  221. //cap
  222. weights.resize(expected_vertices);
  223. //renormalize
  224. float total = 0.0;
  225. for (int i = 0; i < expected_vertices; i++) {
  226. total += weights[i].weight;
  227. }
  228. vtx.weights.resize(expected_vertices);
  229. vtx.bones.resize(expected_vertices);
  230. for (int i = 0; i < expected_vertices; i++) {
  231. if (total > 0) {
  232. vtx.weights.write[i] = weights[i].weight / total;
  233. } else {
  234. vtx.weights.write[i] = 0;
  235. }
  236. vtx.bones.write[i] = weights[i].index;
  237. }
  238. }
  239. }
  240. vertex_array.push_back(vtx);
  241. first = false;
  242. format |= Mesh::ARRAY_FORMAT_VERTEX;
  243. }
  244. void SurfaceTool::set_color(Color p_color) {
  245. ERR_FAIL_COND(!begun);
  246. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_COLOR));
  247. format |= Mesh::ARRAY_FORMAT_COLOR;
  248. last_color = p_color;
  249. }
  250. void SurfaceTool::set_normal(const Vector3 &p_normal) {
  251. ERR_FAIL_COND(!begun);
  252. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_NORMAL));
  253. format |= Mesh::ARRAY_FORMAT_NORMAL;
  254. last_normal = p_normal;
  255. }
  256. void SurfaceTool::set_tangent(const Plane &p_tangent) {
  257. ERR_FAIL_COND(!begun);
  258. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TANGENT));
  259. format |= Mesh::ARRAY_FORMAT_TANGENT;
  260. last_tangent = p_tangent;
  261. }
  262. void SurfaceTool::set_uv(const Vector2 &p_uv) {
  263. ERR_FAIL_COND(!begun);
  264. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TEX_UV));
  265. format |= Mesh::ARRAY_FORMAT_TEX_UV;
  266. last_uv = p_uv;
  267. }
  268. void SurfaceTool::set_uv2(const Vector2 &p_uv2) {
  269. ERR_FAIL_COND(!begun);
  270. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_TEX_UV2));
  271. format |= Mesh::ARRAY_FORMAT_TEX_UV2;
  272. last_uv2 = p_uv2;
  273. }
  274. void SurfaceTool::set_custom(int p_channel_index, const Color &p_custom) {
  275. ERR_FAIL_INDEX(p_channel_index, RS::ARRAY_CUSTOM_COUNT);
  276. ERR_FAIL_COND(!begun);
  277. ERR_FAIL_COND(last_custom_format[p_channel_index] == CUSTOM_MAX);
  278. static const uint32_t mask[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0, Mesh::ARRAY_FORMAT_CUSTOM1, Mesh::ARRAY_FORMAT_CUSTOM2, Mesh::ARRAY_FORMAT_CUSTOM3 };
  279. ERR_FAIL_COND(!first && !(format & mask[p_channel_index]));
  280. if (first) {
  281. format |= mask[p_channel_index];
  282. }
  283. last_custom[p_channel_index] = p_custom;
  284. }
  285. void SurfaceTool::set_bones(const Vector<int> &p_bones) {
  286. ERR_FAIL_COND(!begun);
  287. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_BONES));
  288. format |= Mesh::ARRAY_FORMAT_BONES;
  289. if (skin_weights == SKIN_8_WEIGHTS) {
  290. format |= Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  291. }
  292. last_bones = p_bones;
  293. }
  294. void SurfaceTool::set_weights(const Vector<float> &p_weights) {
  295. ERR_FAIL_COND(!begun);
  296. ERR_FAIL_COND(!first && !(format & Mesh::ARRAY_FORMAT_WEIGHTS));
  297. format |= Mesh::ARRAY_FORMAT_WEIGHTS;
  298. if (skin_weights == SKIN_8_WEIGHTS) {
  299. format |= Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  300. }
  301. last_weights = p_weights;
  302. }
  303. void SurfaceTool::set_smooth_group(uint32_t p_group) {
  304. last_smooth_group = p_group;
  305. }
  306. void SurfaceTool::_add_triangle_fan(const Vector<Vector3> &p_vertices, const Vector<Vector2> &p_uvs, const Vector<Color> &p_colors, const Vector<Vector2> &p_uv2s, const Vector<Vector3> &p_normals, const TypedArray<Plane> &p_tangents) {
  307. add_triangle_fan(p_vertices, p_uvs, p_colors, p_uv2s, p_normals, Variant(p_tangents));
  308. }
  309. void SurfaceTool::add_triangle_fan(const Vector<Vector3> &p_vertices, const Vector<Vector2> &p_uvs, const Vector<Color> &p_colors, const Vector<Vector2> &p_uv2s, const Vector<Vector3> &p_normals, const Vector<Plane> &p_tangents) {
  310. ERR_FAIL_COND(!begun);
  311. ERR_FAIL_COND(primitive != Mesh::PRIMITIVE_TRIANGLES);
  312. ERR_FAIL_COND(p_vertices.size() < 3);
  313. #define ADD_POINT(n) \
  314. { \
  315. if (p_colors.size() > n) \
  316. set_color(p_colors[n]); \
  317. if (p_uvs.size() > n) \
  318. set_uv(p_uvs[n]); \
  319. if (p_uv2s.size() > n) \
  320. set_uv2(p_uv2s[n]); \
  321. if (p_normals.size() > n) \
  322. set_normal(p_normals[n]); \
  323. if (p_tangents.size() > n) \
  324. set_tangent(p_tangents[n]); \
  325. add_vertex(p_vertices[n]); \
  326. }
  327. for (int i = 0; i < p_vertices.size() - 2; i++) {
  328. ADD_POINT(0);
  329. ADD_POINT(i + 1);
  330. ADD_POINT(i + 2);
  331. }
  332. #undef ADD_POINT
  333. }
  334. void SurfaceTool::add_index(int p_index) {
  335. ERR_FAIL_COND(!begun);
  336. ERR_FAIL_COND(p_index < 0);
  337. format |= Mesh::ARRAY_FORMAT_INDEX;
  338. index_array.push_back(p_index);
  339. }
  340. Array SurfaceTool::commit_to_arrays() {
  341. int varr_len = vertex_array.size();
  342. Array a;
  343. a.resize(Mesh::ARRAY_MAX);
  344. for (int i = 0; i < Mesh::ARRAY_MAX; i++) {
  345. if (!(format & (1ULL << i))) {
  346. continue; //not in format
  347. }
  348. switch (i) {
  349. case Mesh::ARRAY_VERTEX:
  350. case Mesh::ARRAY_NORMAL: {
  351. Vector<Vector3> array;
  352. array.resize(varr_len);
  353. Vector3 *w = array.ptrw();
  354. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  355. const Vertex &v = vertex_array[idx];
  356. switch (i) {
  357. case Mesh::ARRAY_VERTEX: {
  358. w[idx] = v.vertex;
  359. } break;
  360. case Mesh::ARRAY_NORMAL: {
  361. w[idx] = v.normal;
  362. } break;
  363. }
  364. }
  365. a[i] = array;
  366. } break;
  367. case Mesh::ARRAY_TEX_UV:
  368. case Mesh::ARRAY_TEX_UV2: {
  369. Vector<Vector2> array;
  370. array.resize(varr_len);
  371. Vector2 *w = array.ptrw();
  372. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  373. const Vertex &v = vertex_array[idx];
  374. switch (i) {
  375. case Mesh::ARRAY_TEX_UV: {
  376. w[idx] = v.uv;
  377. } break;
  378. case Mesh::ARRAY_TEX_UV2: {
  379. w[idx] = v.uv2;
  380. } break;
  381. }
  382. }
  383. a[i] = array;
  384. } break;
  385. case Mesh::ARRAY_TANGENT: {
  386. Vector<float> array;
  387. array.resize(varr_len * 4);
  388. float *w = array.ptrw();
  389. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  390. const Vertex &v = vertex_array[idx];
  391. w[idx * 4 + 0] = v.tangent.x;
  392. w[idx * 4 + 1] = v.tangent.y;
  393. w[idx * 4 + 2] = v.tangent.z;
  394. //float d = v.tangent.dot(v.binormal,v.normal);
  395. float d = v.binormal.dot(v.normal.cross(v.tangent));
  396. w[idx * 4 + 3] = d < 0 ? -1 : 1;
  397. }
  398. a[i] = array;
  399. } break;
  400. case Mesh::ARRAY_COLOR: {
  401. Vector<Color> array;
  402. array.resize(varr_len);
  403. Color *w = array.ptrw();
  404. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  405. const Vertex &v = vertex_array[idx];
  406. w[idx] = v.color;
  407. }
  408. a[i] = array;
  409. } break;
  410. case Mesh::ARRAY_CUSTOM0:
  411. case Mesh::ARRAY_CUSTOM1:
  412. case Mesh::ARRAY_CUSTOM2:
  413. case Mesh::ARRAY_CUSTOM3: {
  414. int fmt = i - Mesh::ARRAY_CUSTOM0;
  415. switch (last_custom_format[fmt]) {
  416. case CUSTOM_RGBA8_UNORM: {
  417. Vector<uint8_t> array;
  418. array.resize(varr_len * 4);
  419. uint8_t *w = array.ptrw();
  420. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  421. const Vertex &v = vertex_array[idx];
  422. const Color &c = v.custom[fmt];
  423. w[idx * 4 + 0] = CLAMP(int32_t(c.r * 255.0), 0, 255);
  424. w[idx * 4 + 1] = CLAMP(int32_t(c.g * 255.0), 0, 255);
  425. w[idx * 4 + 2] = CLAMP(int32_t(c.b * 255.0), 0, 255);
  426. w[idx * 4 + 3] = CLAMP(int32_t(c.a * 255.0), 0, 255);
  427. }
  428. a[i] = array;
  429. } break;
  430. case CUSTOM_RGBA8_SNORM: {
  431. Vector<uint8_t> array;
  432. array.resize(varr_len * 4);
  433. uint8_t *w = array.ptrw();
  434. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  435. const Vertex &v = vertex_array[idx];
  436. const Color &c = v.custom[fmt];
  437. w[idx * 4 + 0] = uint8_t(int8_t(CLAMP(int32_t(c.r * 127.0), -128, 127)));
  438. w[idx * 4 + 1] = uint8_t(int8_t(CLAMP(int32_t(c.g * 127.0), -128, 127)));
  439. w[idx * 4 + 2] = uint8_t(int8_t(CLAMP(int32_t(c.b * 127.0), -128, 127)));
  440. w[idx * 4 + 3] = uint8_t(int8_t(CLAMP(int32_t(c.a * 127.0), -128, 127)));
  441. }
  442. a[i] = array;
  443. } break;
  444. case CUSTOM_RG_HALF: {
  445. Vector<uint8_t> array;
  446. array.resize(varr_len * 4);
  447. uint16_t *w = (uint16_t *)array.ptrw();
  448. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  449. const Vertex &v = vertex_array[idx];
  450. const Color &c = v.custom[fmt];
  451. w[idx * 2 + 0] = Math::make_half_float(c.r);
  452. w[idx * 2 + 1] = Math::make_half_float(c.g);
  453. }
  454. a[i] = array;
  455. } break;
  456. case CUSTOM_RGBA_HALF: {
  457. Vector<uint8_t> array;
  458. array.resize(varr_len * 8);
  459. uint16_t *w = (uint16_t *)array.ptrw();
  460. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  461. const Vertex &v = vertex_array[idx];
  462. const Color &c = v.custom[fmt];
  463. w[idx * 4 + 0] = Math::make_half_float(c.r);
  464. w[idx * 4 + 1] = Math::make_half_float(c.g);
  465. w[idx * 4 + 2] = Math::make_half_float(c.b);
  466. w[idx * 4 + 3] = Math::make_half_float(c.a);
  467. }
  468. a[i] = array;
  469. } break;
  470. case CUSTOM_R_FLOAT: {
  471. Vector<float> array;
  472. array.resize(varr_len);
  473. float *w = (float *)array.ptrw();
  474. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  475. const Vertex &v = vertex_array[idx];
  476. const Color &c = v.custom[fmt];
  477. w[idx] = c.r;
  478. }
  479. a[i] = array;
  480. } break;
  481. case CUSTOM_RG_FLOAT: {
  482. Vector<float> array;
  483. array.resize(varr_len * 2);
  484. float *w = (float *)array.ptrw();
  485. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  486. const Vertex &v = vertex_array[idx];
  487. const Color &c = v.custom[fmt];
  488. w[idx * 2 + 0] = c.r;
  489. w[idx * 2 + 1] = c.g;
  490. }
  491. a[i] = array;
  492. } break;
  493. case CUSTOM_RGB_FLOAT: {
  494. Vector<float> array;
  495. array.resize(varr_len * 3);
  496. float *w = (float *)array.ptrw();
  497. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  498. const Vertex &v = vertex_array[idx];
  499. const Color &c = v.custom[fmt];
  500. w[idx * 3 + 0] = c.r;
  501. w[idx * 3 + 1] = c.g;
  502. w[idx * 3 + 2] = c.b;
  503. }
  504. a[i] = array;
  505. } break;
  506. case CUSTOM_RGBA_FLOAT: {
  507. Vector<float> array;
  508. array.resize(varr_len * 4);
  509. float *w = (float *)array.ptrw();
  510. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  511. const Vertex &v = vertex_array[idx];
  512. const Color &c = v.custom[fmt];
  513. w[idx * 4 + 0] = c.r;
  514. w[idx * 4 + 1] = c.g;
  515. w[idx * 4 + 2] = c.b;
  516. w[idx * 4 + 3] = c.a;
  517. }
  518. a[i] = array;
  519. } break;
  520. default: {
  521. } //unreachable but compiler warning anyway
  522. }
  523. } break;
  524. case Mesh::ARRAY_BONES: {
  525. int count = skin_weights == SKIN_8_WEIGHTS ? 8 : 4;
  526. Vector<int> array;
  527. array.resize(varr_len * count);
  528. array.fill(0);
  529. int *w = array.ptrw();
  530. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  531. const Vertex &v = vertex_array[idx];
  532. if (v.bones.size() != count) {
  533. ERR_PRINT_ONCE(vformat("Invalid bones size %d vs count %d", v.bones.size(), count));
  534. continue;
  535. }
  536. for (int j = 0; j < count; j++) {
  537. w[idx * count + j] = v.bones[j];
  538. }
  539. }
  540. a[i] = array;
  541. } break;
  542. case Mesh::ARRAY_WEIGHTS: {
  543. Vector<float> array;
  544. int count = skin_weights == SKIN_8_WEIGHTS ? 8 : 4;
  545. array.resize(varr_len * count);
  546. array.fill(0.0f);
  547. float *w = array.ptrw();
  548. for (uint32_t idx = 0; idx < vertex_array.size(); idx++) {
  549. const Vertex &v = vertex_array[idx];
  550. if (v.weights.size() != count) {
  551. ERR_PRINT_ONCE(vformat("Invalid weight size %d vs count %d", v.weights.size(), count));
  552. continue;
  553. }
  554. for (int j = 0; j < count; j++) {
  555. w[idx * count + j] = v.weights[j];
  556. }
  557. }
  558. a[i] = array;
  559. } break;
  560. case Mesh::ARRAY_INDEX: {
  561. ERR_CONTINUE(index_array.is_empty());
  562. Vector<int> array;
  563. array.resize(index_array.size());
  564. int *w = array.ptrw();
  565. for (uint32_t idx = 0; idx < index_array.size(); idx++) {
  566. w[idx] = index_array[idx];
  567. }
  568. a[i] = array;
  569. } break;
  570. default: {
  571. }
  572. }
  573. }
  574. return a;
  575. }
  576. Ref<ArrayMesh> SurfaceTool::commit(const Ref<ArrayMesh> &p_existing, uint64_t p_compress_flags) {
  577. Ref<ArrayMesh> mesh;
  578. if (p_existing.is_valid()) {
  579. mesh = p_existing;
  580. } else {
  581. mesh.instantiate();
  582. }
  583. int varr_len = vertex_array.size();
  584. if (varr_len == 0) {
  585. return mesh;
  586. }
  587. int surface = mesh->get_surface_count();
  588. Array a = commit_to_arrays();
  589. uint64_t compress_flags = (p_compress_flags >> RS::ARRAY_COMPRESS_FLAGS_BASE) << RS::ARRAY_COMPRESS_FLAGS_BASE;
  590. static const uint64_t 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 };
  591. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  592. if (last_custom_format[i] != CUSTOM_MAX) {
  593. compress_flags |= uint64_t(last_custom_format[i]) << shift[i];
  594. }
  595. }
  596. mesh->add_surface_from_arrays(primitive, a, Array(), Dictionary(), compress_flags);
  597. if (material.is_valid()) {
  598. mesh->surface_set_material(surface, material);
  599. }
  600. return mesh;
  601. }
  602. void SurfaceTool::index() {
  603. if (index_array.size()) {
  604. return; //already indexed
  605. }
  606. AHashMap<Vertex &, int, VertexHasher> indices = vertex_array.size();
  607. uint32_t new_size = 0;
  608. for (Vertex &vertex : vertex_array) {
  609. int *idxptr = indices.getptr(vertex);
  610. int idx;
  611. if (!idxptr) {
  612. idx = indices.size();
  613. vertex_array[new_size] = vertex;
  614. indices.insert_new(vertex_array[new_size], idx);
  615. new_size++;
  616. } else {
  617. idx = *idxptr;
  618. }
  619. index_array.push_back(idx);
  620. }
  621. vertex_array.resize(new_size);
  622. format |= Mesh::ARRAY_FORMAT_INDEX;
  623. }
  624. void SurfaceTool::deindex() {
  625. if (index_array.size() == 0) {
  626. return; //nothing to deindex
  627. }
  628. LocalVector<Vertex> old_vertex_array = vertex_array;
  629. vertex_array.clear();
  630. for (const int &index : index_array) {
  631. ERR_FAIL_COND(uint32_t(index) >= old_vertex_array.size());
  632. vertex_array.push_back(old_vertex_array[index]);
  633. }
  634. format &= ~Mesh::ARRAY_FORMAT_INDEX;
  635. index_array.clear();
  636. }
  637. void SurfaceTool::_create_list(const Ref<Mesh> &p_existing, int p_surface, LocalVector<Vertex> *r_vertex, LocalVector<int> *r_index, uint64_t &lformat) {
  638. ERR_FAIL_COND_MSG(p_existing.is_null(), "First argument in SurfaceTool::_create_list() must be a valid object of type Mesh");
  639. Array arr = p_existing->surface_get_arrays(p_surface);
  640. ERR_FAIL_COND(arr.size() != RS::ARRAY_MAX);
  641. _create_list_from_arrays(arr, r_vertex, r_index, lformat);
  642. }
  643. const uint32_t SurfaceTool::custom_mask[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0, Mesh::ARRAY_FORMAT_CUSTOM1, Mesh::ARRAY_FORMAT_CUSTOM2, Mesh::ARRAY_FORMAT_CUSTOM3 };
  644. const uint32_t SurfaceTool::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 };
  645. void SurfaceTool::create_vertex_array_from_arrays(const Array &p_arrays, LocalVector<SurfaceTool::Vertex> &ret, uint64_t *r_format) {
  646. ERR_FAIL_INDEX(RS::ARRAY_WEIGHTS, p_arrays.size());
  647. ret.clear();
  648. Vector<Vector3> varr = p_arrays[RS::ARRAY_VERTEX];
  649. Vector<Vector3> narr = p_arrays[RS::ARRAY_NORMAL];
  650. Vector<float> tarr = p_arrays[RS::ARRAY_TANGENT];
  651. Vector<Color> carr = p_arrays[RS::ARRAY_COLOR];
  652. Vector<Vector2> uvarr = p_arrays[RS::ARRAY_TEX_UV];
  653. Vector<Vector2> uv2arr = p_arrays[RS::ARRAY_TEX_UV2];
  654. Vector<int> barr = p_arrays[RS::ARRAY_BONES];
  655. Vector<float> warr = p_arrays[RS::ARRAY_WEIGHTS];
  656. Vector<float> custom_float[RS::ARRAY_CUSTOM_COUNT];
  657. int vc = varr.size();
  658. if (vc == 0) {
  659. if (r_format) {
  660. *r_format = 0;
  661. }
  662. return;
  663. }
  664. uint64_t lformat = 0;
  665. if (varr.size()) {
  666. lformat |= RS::ARRAY_FORMAT_VERTEX;
  667. }
  668. if (narr.size()) {
  669. lformat |= RS::ARRAY_FORMAT_NORMAL;
  670. }
  671. if (tarr.size()) {
  672. lformat |= RS::ARRAY_FORMAT_TANGENT;
  673. }
  674. if (carr.size()) {
  675. lformat |= RS::ARRAY_FORMAT_COLOR;
  676. }
  677. if (uvarr.size()) {
  678. lformat |= RS::ARRAY_FORMAT_TEX_UV;
  679. }
  680. if (uv2arr.size()) {
  681. lformat |= RS::ARRAY_FORMAT_TEX_UV2;
  682. }
  683. int wcount = 0;
  684. if (barr.size() && warr.size()) {
  685. lformat |= RS::ARRAY_FORMAT_BONES;
  686. lformat |= RS::ARRAY_FORMAT_WEIGHTS;
  687. wcount = barr.size() / varr.size();
  688. if (wcount == 8) {
  689. lformat |= RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  690. }
  691. }
  692. if (warr.size()) {
  693. lformat |= RS::ARRAY_FORMAT_WEIGHTS;
  694. }
  695. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  696. ERR_CONTINUE_MSG(p_arrays[RS::ARRAY_CUSTOM0 + i].get_type() == Variant::PACKED_BYTE_ARRAY, "Extracting Byte/Half formats is not supported");
  697. if (p_arrays[RS::ARRAY_CUSTOM0 + i].get_type() == Variant::PACKED_FLOAT32_ARRAY) {
  698. lformat |= custom_mask[i];
  699. custom_float[i] = p_arrays[RS::ARRAY_CUSTOM0 + i];
  700. int fmt = custom_float[i].size() / varr.size();
  701. if (fmt == 1) {
  702. lformat |= CUSTOM_R_FLOAT << custom_shift[i];
  703. } else if (fmt == 2) {
  704. lformat |= CUSTOM_RG_FLOAT << custom_shift[i];
  705. } else if (fmt == 3) {
  706. lformat |= CUSTOM_RGB_FLOAT << custom_shift[i];
  707. } else if (fmt == 4) {
  708. lformat |= CUSTOM_RGBA_FLOAT << custom_shift[i];
  709. }
  710. }
  711. }
  712. for (int i = 0; i < vc; i++) {
  713. Vertex v;
  714. if (lformat & RS::ARRAY_FORMAT_VERTEX) {
  715. v.vertex = varr[i];
  716. }
  717. if (lformat & RS::ARRAY_FORMAT_NORMAL) {
  718. v.normal = narr[i];
  719. }
  720. if (lformat & RS::ARRAY_FORMAT_TANGENT) {
  721. v.tangent = Vector3(tarr[i * 4 + 0], tarr[i * 4 + 1], tarr[i * 4 + 2]);
  722. float d = tarr[i * 4 + 3];
  723. v.binormal = v.normal.cross(v.tangent).normalized() * d;
  724. }
  725. if (lformat & RS::ARRAY_FORMAT_COLOR) {
  726. v.color = carr[i];
  727. }
  728. if (lformat & RS::ARRAY_FORMAT_TEX_UV) {
  729. v.uv = uvarr[i];
  730. }
  731. if (lformat & RS::ARRAY_FORMAT_TEX_UV2) {
  732. v.uv2 = uv2arr[i];
  733. }
  734. if (lformat & RS::ARRAY_FORMAT_BONES) {
  735. Vector<int> b;
  736. b.resize(wcount);
  737. for (int j = 0; j < wcount; j++) {
  738. b.write[j] = barr[i * wcount + j];
  739. }
  740. v.bones = b;
  741. }
  742. if (lformat & RS::ARRAY_FORMAT_WEIGHTS) {
  743. Vector<float> w;
  744. w.resize(wcount);
  745. for (int j = 0; j < wcount; j++) {
  746. w.write[j] = warr[i * wcount + j];
  747. }
  748. v.weights = w;
  749. }
  750. for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
  751. if (lformat & custom_mask[j]) {
  752. int cc = custom_float[j].size() / varr.size();
  753. for (int k = 0; k < cc; k++) {
  754. v.custom[j][k] = custom_float[j][i * cc + k];
  755. }
  756. }
  757. }
  758. ret.push_back(v);
  759. }
  760. if (r_format) {
  761. *r_format = lformat;
  762. }
  763. }
  764. void SurfaceTool::_create_list_from_arrays(Array arr, LocalVector<Vertex> *r_vertex, LocalVector<int> *r_index, uint64_t &lformat) {
  765. create_vertex_array_from_arrays(arr, *r_vertex, &lformat);
  766. ERR_FAIL_COND(r_vertex->size() == 0);
  767. //indices
  768. r_index->clear();
  769. Vector<int> idx = arr[RS::ARRAY_INDEX];
  770. int is = idx.size();
  771. if (is) {
  772. lformat |= RS::ARRAY_FORMAT_INDEX;
  773. const int *iarr = idx.ptr();
  774. for (int i = 0; i < is; i++) {
  775. r_index->push_back(iarr[i]);
  776. }
  777. }
  778. }
  779. void SurfaceTool::create_from_arrays(const Array &p_arrays, Mesh::PrimitiveType p_primitive_type) {
  780. clear();
  781. primitive = p_primitive_type;
  782. _create_list_from_arrays(p_arrays, &vertex_array, &index_array, format);
  783. for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
  784. if (format & custom_mask[j]) {
  785. last_custom_format[j] = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
  786. }
  787. }
  788. }
  789. void SurfaceTool::create_from_triangle_arrays(const Array &p_arrays) {
  790. create_from_arrays(p_arrays, Mesh::PRIMITIVE_TRIANGLES);
  791. }
  792. void SurfaceTool::create_from(const Ref<Mesh> &p_existing, int p_surface) {
  793. ERR_FAIL_COND_MSG(p_existing.is_null(), "First argument in SurfaceTool::create_from() must be a valid object of type Mesh");
  794. clear();
  795. primitive = p_existing->surface_get_primitive_type(p_surface);
  796. _create_list(p_existing, p_surface, &vertex_array, &index_array, format);
  797. material = p_existing->surface_get_material(p_surface);
  798. for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
  799. if (format & custom_mask[j]) {
  800. last_custom_format[j] = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
  801. }
  802. }
  803. }
  804. void SurfaceTool::create_from_blend_shape(const Ref<Mesh> &p_existing, int p_surface, const String &p_blend_shape_name) {
  805. ERR_FAIL_COND_MSG(p_existing.is_null(), "First argument in SurfaceTool::create_from_blend_shape() must be a valid object of type Mesh");
  806. clear();
  807. primitive = p_existing->surface_get_primitive_type(p_surface);
  808. Array arr = p_existing->surface_get_blend_shape_arrays(p_surface);
  809. Array blend_shape_names;
  810. int32_t shape_idx = -1;
  811. for (int32_t i = 0; i < p_existing->get_blend_shape_count(); i++) {
  812. String name = p_existing->get_blend_shape_name(i);
  813. if (name == p_blend_shape_name) {
  814. shape_idx = i;
  815. break;
  816. }
  817. }
  818. ERR_FAIL_COND(shape_idx == -1);
  819. ERR_FAIL_COND(shape_idx >= arr.size());
  820. Array blendshape_mesh_arrays = arr[shape_idx];
  821. ERR_FAIL_COND(blendshape_mesh_arrays.size() != RS::ARRAY_MAX);
  822. Array source_mesh_arrays = p_existing->surface_get_arrays(p_surface);
  823. ERR_FAIL_COND(source_mesh_arrays.size() != RS::ARRAY_MAX);
  824. // Copy BlendShape vertex data over while keeping e.g. bones, weights, index from existing mesh intact.
  825. source_mesh_arrays[RS::ARRAY_VERTEX] = blendshape_mesh_arrays[RS::ARRAY_VERTEX];
  826. source_mesh_arrays[RS::ARRAY_NORMAL] = blendshape_mesh_arrays[RS::ARRAY_NORMAL];
  827. source_mesh_arrays[RS::ARRAY_TANGENT] = blendshape_mesh_arrays[RS::ARRAY_TANGENT];
  828. _create_list_from_arrays(source_mesh_arrays, &vertex_array, &index_array, format);
  829. material = p_existing->surface_get_material(p_surface);
  830. format = p_existing->surface_get_format(p_surface);
  831. for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
  832. if (format & custom_mask[j]) {
  833. last_custom_format[j] = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
  834. }
  835. }
  836. }
  837. void SurfaceTool::append_from(const Ref<Mesh> &p_existing, int p_surface, const Transform3D &p_xform) {
  838. ERR_FAIL_COND_MSG(p_existing.is_null(), "First argument in SurfaceTool::append_from() must be a valid object of type Mesh");
  839. if (vertex_array.size() == 0) {
  840. primitive = p_existing->surface_get_primitive_type(p_surface);
  841. format = 0;
  842. }
  843. uint64_t nformat = 0;
  844. LocalVector<Vertex> nvertices;
  845. LocalVector<int> nindices;
  846. _create_list(p_existing, p_surface, &nvertices, &nindices, nformat);
  847. format |= nformat;
  848. for (int j = 0; j < RS::ARRAY_CUSTOM_COUNT; j++) {
  849. if (format & custom_mask[j]) {
  850. CustomFormat new_format = (CustomFormat)((format >> custom_shift[j]) & RS::ARRAY_FORMAT_CUSTOM_MASK);
  851. last_custom_format[j] = new_format;
  852. }
  853. }
  854. int vfrom = vertex_array.size();
  855. for (Vertex &v : nvertices) {
  856. v.vertex = p_xform.xform(v.vertex);
  857. if (nformat & RS::ARRAY_FORMAT_NORMAL) {
  858. v.normal = p_xform.basis.xform(v.normal);
  859. }
  860. if (nformat & RS::ARRAY_FORMAT_TANGENT) {
  861. v.tangent = p_xform.basis.xform(v.tangent);
  862. v.binormal = p_xform.basis.xform(v.binormal);
  863. }
  864. vertex_array.push_back(v);
  865. }
  866. for (const int &index : nindices) {
  867. int dst_index = index + vfrom;
  868. index_array.push_back(dst_index);
  869. }
  870. if (index_array.size() % 3) {
  871. WARN_PRINT("SurfaceTool: Index array not a multiple of 3.");
  872. }
  873. }
  874. //mikktspace callbacks
  875. namespace {
  876. struct TangentGenerationContextUserData {
  877. LocalVector<SurfaceTool::Vertex> *vertices;
  878. LocalVector<int> *indices;
  879. };
  880. } // namespace
  881. int SurfaceTool::mikktGetNumFaces(const SMikkTSpaceContext *pContext) {
  882. TangentGenerationContextUserData &triangle_data = *reinterpret_cast<TangentGenerationContextUserData *>(pContext->m_pUserData);
  883. if (triangle_data.indices->size() > 0) {
  884. return triangle_data.indices->size() / 3;
  885. } else {
  886. return triangle_data.vertices->size() / 3;
  887. }
  888. }
  889. int SurfaceTool::mikktGetNumVerticesOfFace(const SMikkTSpaceContext *pContext, const int iFace) {
  890. return 3; //always 3
  891. }
  892. void SurfaceTool::mikktGetPosition(const SMikkTSpaceContext *pContext, float fvPosOut[], const int iFace, const int iVert) {
  893. TangentGenerationContextUserData &triangle_data = *reinterpret_cast<TangentGenerationContextUserData *>(pContext->m_pUserData);
  894. Vector3 v;
  895. if (triangle_data.indices->size() > 0) {
  896. uint32_t index = triangle_data.indices->operator[](iFace * 3 + iVert);
  897. if (index < triangle_data.vertices->size()) {
  898. v = triangle_data.vertices->operator[](index).vertex;
  899. }
  900. } else {
  901. v = triangle_data.vertices->operator[](iFace * 3 + iVert).vertex;
  902. }
  903. fvPosOut[0] = v.x;
  904. fvPosOut[1] = v.y;
  905. fvPosOut[2] = v.z;
  906. }
  907. void SurfaceTool::mikktGetNormal(const SMikkTSpaceContext *pContext, float fvNormOut[], const int iFace, const int iVert) {
  908. TangentGenerationContextUserData &triangle_data = *reinterpret_cast<TangentGenerationContextUserData *>(pContext->m_pUserData);
  909. Vector3 v;
  910. if (triangle_data.indices->size() > 0) {
  911. uint32_t index = triangle_data.indices->operator[](iFace * 3 + iVert);
  912. if (index < triangle_data.vertices->size()) {
  913. v = triangle_data.vertices->operator[](index).normal;
  914. }
  915. } else {
  916. v = triangle_data.vertices->operator[](iFace * 3 + iVert).normal;
  917. }
  918. fvNormOut[0] = v.x;
  919. fvNormOut[1] = v.y;
  920. fvNormOut[2] = v.z;
  921. }
  922. void SurfaceTool::mikktGetTexCoord(const SMikkTSpaceContext *pContext, float fvTexcOut[], const int iFace, const int iVert) {
  923. TangentGenerationContextUserData &triangle_data = *reinterpret_cast<TangentGenerationContextUserData *>(pContext->m_pUserData);
  924. Vector2 v;
  925. if (triangle_data.indices->size() > 0) {
  926. uint32_t index = triangle_data.indices->operator[](iFace * 3 + iVert);
  927. if (index < triangle_data.vertices->size()) {
  928. v = triangle_data.vertices->operator[](index).uv;
  929. }
  930. } else {
  931. v = triangle_data.vertices->operator[](iFace * 3 + iVert).uv;
  932. }
  933. fvTexcOut[0] = v.x;
  934. fvTexcOut[1] = v.y;
  935. }
  936. void SurfaceTool::mikktSetTSpaceDefault(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fvBiTangent[], const float fMagS, const float fMagT,
  937. const tbool bIsOrientationPreserving, const int iFace, const int iVert) {
  938. TangentGenerationContextUserData &triangle_data = *reinterpret_cast<TangentGenerationContextUserData *>(pContext->m_pUserData);
  939. Vertex *vtx = nullptr;
  940. if (triangle_data.indices->size() > 0) {
  941. uint32_t index = triangle_data.indices->operator[](iFace * 3 + iVert);
  942. if (index < triangle_data.vertices->size()) {
  943. vtx = &triangle_data.vertices->operator[](index);
  944. }
  945. } else {
  946. vtx = &triangle_data.vertices->operator[](iFace * 3 + iVert);
  947. }
  948. if (vtx != nullptr) {
  949. vtx->tangent = Vector3(fvTangent[0], fvTangent[1], fvTangent[2]);
  950. vtx->binormal = Vector3(-fvBiTangent[0], -fvBiTangent[1], -fvBiTangent[2]); // for some reason these are reversed, something with the coordinate system in Godot
  951. }
  952. }
  953. void SurfaceTool::generate_tangents() {
  954. ERR_FAIL_COND_MSG(!(format & Mesh::ARRAY_FORMAT_TEX_UV), "UVs are required to generate tangents.");
  955. ERR_FAIL_COND(!(format & Mesh::ARRAY_FORMAT_NORMAL));
  956. SMikkTSpaceInterface mkif;
  957. mkif.m_getNormal = mikktGetNormal;
  958. mkif.m_getNumFaces = mikktGetNumFaces;
  959. mkif.m_getNumVerticesOfFace = mikktGetNumVerticesOfFace;
  960. mkif.m_getPosition = mikktGetPosition;
  961. mkif.m_getTexCoord = mikktGetTexCoord;
  962. mkif.m_setTSpace = mikktSetTSpaceDefault;
  963. mkif.m_setTSpaceBasic = nullptr;
  964. SMikkTSpaceContext msc;
  965. msc.m_pInterface = &mkif;
  966. TangentGenerationContextUserData triangle_data;
  967. triangle_data.vertices = &vertex_array;
  968. for (Vertex &vertex : vertex_array) {
  969. vertex.binormal = Vector3();
  970. vertex.tangent = Vector3();
  971. }
  972. triangle_data.indices = &index_array;
  973. msc.m_pUserData = &triangle_data;
  974. bool res = genTangSpaceDefault(&msc);
  975. ERR_FAIL_COND(!res);
  976. format |= Mesh::ARRAY_FORMAT_TANGENT;
  977. }
  978. void SurfaceTool::generate_normals(bool p_flip) {
  979. ERR_FAIL_COND(primitive != Mesh::PRIMITIVE_TRIANGLES);
  980. bool was_indexed = index_array.size();
  981. deindex();
  982. ERR_FAIL_COND((vertex_array.size() % 3) != 0);
  983. AHashMap<SmoothGroupVertex, Vector3, SmoothGroupVertexHasher> smooth_hash = vertex_array.size();
  984. for (uint32_t vi = 0; vi < vertex_array.size(); vi += 3) {
  985. Vertex *v = &vertex_array[vi];
  986. Vector3 normal;
  987. if (!p_flip) {
  988. normal = Plane(v[0].vertex, v[1].vertex, v[2].vertex).normal;
  989. } else {
  990. normal = Plane(v[2].vertex, v[1].vertex, v[0].vertex).normal;
  991. }
  992. for (int i = 0; i < 3; i++) {
  993. // Add face normal to smooth vertex influence if vertex is member of a smoothing group
  994. if (v[i].smooth_group != UINT32_MAX) {
  995. Vector3 *lv = smooth_hash.getptr(v[i]);
  996. if (!lv) {
  997. smooth_hash.insert_new(v[i], normal);
  998. } else {
  999. (*lv) += normal;
  1000. }
  1001. } else {
  1002. v[i].normal = normal;
  1003. }
  1004. }
  1005. }
  1006. for (Vertex &vertex : vertex_array) {
  1007. if (vertex.smooth_group != UINT32_MAX) {
  1008. Vector3 *lv = smooth_hash.getptr(vertex);
  1009. if (!lv) {
  1010. vertex.normal = Vector3();
  1011. } else {
  1012. vertex.normal = lv->normalized();
  1013. }
  1014. }
  1015. }
  1016. format |= Mesh::ARRAY_FORMAT_NORMAL;
  1017. if (was_indexed) {
  1018. index();
  1019. }
  1020. }
  1021. void SurfaceTool::set_material(const Ref<Material> &p_material) {
  1022. material = p_material;
  1023. }
  1024. Ref<Material> SurfaceTool::get_material() const {
  1025. return material;
  1026. }
  1027. void SurfaceTool::clear() {
  1028. begun = false;
  1029. primitive = Mesh::PRIMITIVE_LINES;
  1030. format = 0;
  1031. last_bones.clear();
  1032. last_weights.clear();
  1033. index_array.clear();
  1034. vertex_array.clear();
  1035. material.unref();
  1036. last_smooth_group = 0;
  1037. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  1038. last_custom_format[i] = CUSTOM_MAX;
  1039. }
  1040. skin_weights = SKIN_4_WEIGHTS;
  1041. }
  1042. void SurfaceTool::set_skin_weight_count(SkinWeightCount p_weights) {
  1043. ERR_FAIL_COND(begun);
  1044. skin_weights = p_weights;
  1045. }
  1046. SurfaceTool::SkinWeightCount SurfaceTool::get_skin_weight_count() const {
  1047. return skin_weights;
  1048. }
  1049. void SurfaceTool::set_custom_format(int p_channel_index, CustomFormat p_format) {
  1050. ERR_FAIL_INDEX(p_channel_index, RS::ARRAY_CUSTOM_COUNT);
  1051. ERR_FAIL_COND(!begun);
  1052. ERR_FAIL_INDEX(p_format, CUSTOM_MAX + 1);
  1053. last_custom_format[p_channel_index] = p_format;
  1054. }
  1055. Mesh::PrimitiveType SurfaceTool::get_primitive_type() const {
  1056. return primitive;
  1057. }
  1058. SurfaceTool::CustomFormat SurfaceTool::get_custom_format(int p_channel_index) const {
  1059. ERR_FAIL_INDEX_V(p_channel_index, RS::ARRAY_CUSTOM_COUNT, CUSTOM_MAX);
  1060. return last_custom_format[p_channel_index];
  1061. }
  1062. void SurfaceTool::optimize_indices_for_cache() {
  1063. ERR_FAIL_NULL(optimize_vertex_cache_func);
  1064. ERR_FAIL_COND(index_array.is_empty());
  1065. ERR_FAIL_COND(primitive != Mesh::PRIMITIVE_TRIANGLES);
  1066. ERR_FAIL_COND(index_array.size() % 3 != 0);
  1067. LocalVector old_index_array = index_array;
  1068. memset(index_array.ptr(), 0, index_array.size() * sizeof(int));
  1069. optimize_vertex_cache_func((unsigned int *)index_array.ptr(), (unsigned int *)old_index_array.ptr(), old_index_array.size(), vertex_array.size());
  1070. }
  1071. AABB SurfaceTool::get_aabb() const {
  1072. ERR_FAIL_COND_V(vertex_array.is_empty(), AABB());
  1073. AABB aabb;
  1074. for (uint32_t i = 0; i < vertex_array.size(); i++) {
  1075. if (i == 0) {
  1076. aabb.position = vertex_array[i].vertex;
  1077. } else {
  1078. aabb.expand_to(vertex_array[i].vertex);
  1079. }
  1080. }
  1081. return aabb;
  1082. }
  1083. Vector<int> SurfaceTool::generate_lod(float p_threshold, int p_target_index_count) {
  1084. WARN_DEPRECATED_MSG(R"*(The "SurfaceTool.generate_lod()" method is deprecated. Consider using "ImporterMesh.generate_lods()" instead.)*");
  1085. Vector<int> lod;
  1086. ERR_FAIL_NULL_V(simplify_func, lod);
  1087. ERR_FAIL_COND_V(p_target_index_count < 0, lod);
  1088. ERR_FAIL_COND_V(vertex_array.is_empty(), lod);
  1089. ERR_FAIL_COND_V(index_array.is_empty(), lod);
  1090. ERR_FAIL_COND_V(index_array.size() % 3 != 0, lod);
  1091. ERR_FAIL_COND_V(index_array.size() < (unsigned int)p_target_index_count, lod);
  1092. lod.resize(index_array.size());
  1093. LocalVector<float> vertices; //uses floats
  1094. vertices.resize(vertex_array.size() * 3);
  1095. for (uint32_t i = 0; i < vertex_array.size(); i++) {
  1096. vertices[i * 3 + 0] = vertex_array[i].vertex.x;
  1097. vertices[i * 3 + 1] = vertex_array[i].vertex.y;
  1098. vertices[i * 3 + 2] = vertex_array[i].vertex.z;
  1099. }
  1100. float error;
  1101. const int simplify_options = SIMPLIFY_LOCK_BORDER;
  1102. uint32_t index_count = simplify_func((unsigned int *)lod.ptrw(), (unsigned int *)index_array.ptr(), index_array.size(), vertices.ptr(), vertex_array.size(), sizeof(float) * 3, p_target_index_count, p_threshold, simplify_options, &error);
  1103. ERR_FAIL_COND_V(index_count == 0, lod);
  1104. lod.resize(index_count);
  1105. return lod;
  1106. }
  1107. void SurfaceTool::_bind_methods() {
  1108. ClassDB::bind_method(D_METHOD("set_skin_weight_count", "count"), &SurfaceTool::set_skin_weight_count);
  1109. ClassDB::bind_method(D_METHOD("get_skin_weight_count"), &SurfaceTool::get_skin_weight_count);
  1110. ClassDB::bind_method(D_METHOD("set_custom_format", "channel_index", "format"), &SurfaceTool::set_custom_format);
  1111. ClassDB::bind_method(D_METHOD("get_custom_format", "channel_index"), &SurfaceTool::get_custom_format);
  1112. ClassDB::bind_method(D_METHOD("begin", "primitive"), &SurfaceTool::begin);
  1113. ClassDB::bind_method(D_METHOD("add_vertex", "vertex"), &SurfaceTool::add_vertex);
  1114. ClassDB::bind_method(D_METHOD("set_color", "color"), &SurfaceTool::set_color);
  1115. ClassDB::bind_method(D_METHOD("set_normal", "normal"), &SurfaceTool::set_normal);
  1116. ClassDB::bind_method(D_METHOD("set_tangent", "tangent"), &SurfaceTool::set_tangent);
  1117. ClassDB::bind_method(D_METHOD("set_uv", "uv"), &SurfaceTool::set_uv);
  1118. ClassDB::bind_method(D_METHOD("set_uv2", "uv2"), &SurfaceTool::set_uv2);
  1119. ClassDB::bind_method(D_METHOD("set_bones", "bones"), &SurfaceTool::set_bones);
  1120. ClassDB::bind_method(D_METHOD("set_weights", "weights"), &SurfaceTool::set_weights);
  1121. ClassDB::bind_method(D_METHOD("set_custom", "channel_index", "custom_color"), &SurfaceTool::set_custom);
  1122. ClassDB::bind_method(D_METHOD("set_smooth_group", "index"), &SurfaceTool::set_smooth_group);
  1123. ClassDB::bind_method(D_METHOD("add_triangle_fan", "vertices", "uvs", "colors", "uv2s", "normals", "tangents"), &SurfaceTool::_add_triangle_fan, DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Color>()), DEFVAL(Vector<Vector2>()), DEFVAL(Vector<Vector3>()), DEFVAL(TypedArray<Plane>()));
  1124. ClassDB::bind_method(D_METHOD("add_index", "index"), &SurfaceTool::add_index);
  1125. ClassDB::bind_method(D_METHOD("index"), &SurfaceTool::index);
  1126. ClassDB::bind_method(D_METHOD("deindex"), &SurfaceTool::deindex);
  1127. ClassDB::bind_method(D_METHOD("generate_normals", "flip"), &SurfaceTool::generate_normals, DEFVAL(false));
  1128. ClassDB::bind_method(D_METHOD("generate_tangents"), &SurfaceTool::generate_tangents);
  1129. ClassDB::bind_method(D_METHOD("optimize_indices_for_cache"), &SurfaceTool::optimize_indices_for_cache);
  1130. ClassDB::bind_method(D_METHOD("get_aabb"), &SurfaceTool::get_aabb);
  1131. ClassDB::bind_method(D_METHOD("generate_lod", "nd_threshold", "target_index_count"), &SurfaceTool::generate_lod, DEFVAL(3));
  1132. ClassDB::bind_method(D_METHOD("set_material", "material"), &SurfaceTool::set_material);
  1133. ClassDB::bind_method(D_METHOD("get_primitive_type"), &SurfaceTool::get_primitive_type);
  1134. ClassDB::bind_method(D_METHOD("clear"), &SurfaceTool::clear);
  1135. ClassDB::bind_method(D_METHOD("create_from", "existing", "surface"), &SurfaceTool::create_from);
  1136. ClassDB::bind_method(D_METHOD("create_from_arrays", "arrays", "primitive_type"), &SurfaceTool::create_from_arrays, DEFVAL(Mesh::PRIMITIVE_TRIANGLES));
  1137. ClassDB::bind_method(D_METHOD("create_from_blend_shape", "existing", "surface", "blend_shape"), &SurfaceTool::create_from_blend_shape);
  1138. ClassDB::bind_method(D_METHOD("append_from", "existing", "surface", "transform"), &SurfaceTool::append_from);
  1139. ClassDB::bind_method(D_METHOD("commit", "existing", "flags"), &SurfaceTool::commit, DEFVAL(Variant()), DEFVAL(0));
  1140. ClassDB::bind_method(D_METHOD("commit_to_arrays"), &SurfaceTool::commit_to_arrays);
  1141. BIND_ENUM_CONSTANT(CUSTOM_RGBA8_UNORM);
  1142. BIND_ENUM_CONSTANT(CUSTOM_RGBA8_SNORM);
  1143. BIND_ENUM_CONSTANT(CUSTOM_RG_HALF);
  1144. BIND_ENUM_CONSTANT(CUSTOM_RGBA_HALF);
  1145. BIND_ENUM_CONSTANT(CUSTOM_R_FLOAT);
  1146. BIND_ENUM_CONSTANT(CUSTOM_RG_FLOAT);
  1147. BIND_ENUM_CONSTANT(CUSTOM_RGB_FLOAT);
  1148. BIND_ENUM_CONSTANT(CUSTOM_RGBA_FLOAT);
  1149. BIND_ENUM_CONSTANT(CUSTOM_MAX);
  1150. BIND_ENUM_CONSTANT(SKIN_4_WEIGHTS);
  1151. BIND_ENUM_CONSTANT(SKIN_8_WEIGHTS);
  1152. }
  1153. SurfaceTool::SurfaceTool() {
  1154. for (int i = 0; i < RS::ARRAY_CUSTOM_COUNT; i++) {
  1155. last_custom_format[i] = CUSTOM_MAX;
  1156. }
  1157. }