surface_tool.cpp 43 KB

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