surface_tool.cpp 43 KB

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