resource_importer_obj.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. /**************************************************************************/
  2. /* resource_importer_obj.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 "resource_importer_obj.h"
  31. #include "core/io/file_access.h"
  32. #include "core/io/resource_saver.h"
  33. #include "scene/3d/importer_mesh_instance_3d.h"
  34. #include "scene/3d/node_3d.h"
  35. #include "scene/resources/3d/importer_mesh.h"
  36. #include "scene/resources/mesh.h"
  37. #include "scene/resources/surface_tool.h"
  38. static Error _parse_material_library(const String &p_path, HashMap<String, Ref<StandardMaterial3D>> &material_map, List<String> *r_missing_deps) {
  39. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  40. ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Couldn't open MTL file '%s', it may not exist or not be readable.", p_path));
  41. Ref<StandardMaterial3D> current;
  42. String current_name;
  43. String base_path = p_path.get_base_dir();
  44. while (true) {
  45. String l = f->get_line().strip_edges();
  46. if (l.begins_with("newmtl ")) {
  47. //vertex
  48. current_name = l.replace("newmtl", "").strip_edges();
  49. current.instantiate();
  50. current->set_name(current_name);
  51. material_map[current_name] = current;
  52. } else if (l.begins_with("Ka ")) {
  53. //uv
  54. WARN_PRINT("OBJ: Ambient light for material '" + current_name + "' is ignored in PBR");
  55. } else if (l.begins_with("Kd ")) {
  56. //normal
  57. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  58. Vector<String> v = l.split(" ", false);
  59. ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
  60. Color c = current->get_albedo();
  61. c.r = v[1].to_float();
  62. c.g = v[2].to_float();
  63. c.b = v[3].to_float();
  64. current->set_albedo(c);
  65. } else if (l.begins_with("Ks ")) {
  66. //normal
  67. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  68. Vector<String> v = l.split(" ", false);
  69. ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
  70. float r = v[1].to_float();
  71. float g = v[2].to_float();
  72. float b = v[3].to_float();
  73. float metalness = MAX(r, MAX(g, b));
  74. current->set_metallic(metalness);
  75. } else if (l.begins_with("Ns ")) {
  76. //normal
  77. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  78. Vector<String> v = l.split(" ", false);
  79. ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
  80. float s = v[1].to_float();
  81. current->set_metallic((1000.0 - s) / 1000.0);
  82. } else if (l.begins_with("d ")) {
  83. //normal
  84. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  85. Vector<String> v = l.split(" ", false);
  86. ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
  87. float d = v[1].to_float();
  88. Color c = current->get_albedo();
  89. c.a = d;
  90. current->set_albedo(c);
  91. if (c.a < 0.99) {
  92. current->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  93. }
  94. } else if (l.begins_with("Tr ")) {
  95. //normal
  96. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  97. Vector<String> v = l.split(" ", false);
  98. ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
  99. float d = v[1].to_float();
  100. Color c = current->get_albedo();
  101. c.a = 1.0 - d;
  102. current->set_albedo(c);
  103. if (c.a < 0.99) {
  104. current->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  105. }
  106. } else if (l.begins_with("map_Ka ")) {
  107. //uv
  108. WARN_PRINT("OBJ: Ambient light texture for material '" + current_name + "' is ignored in PBR");
  109. } else if (l.begins_with("map_Kd ")) {
  110. //normal
  111. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  112. String p = l.replace("map_Kd", "").replace("\\", "/").strip_edges();
  113. String path;
  114. if (p.is_absolute_path()) {
  115. path = p;
  116. } else {
  117. path = base_path.path_join(p);
  118. }
  119. Ref<Texture2D> texture = ResourceLoader::load(path);
  120. if (texture.is_valid()) {
  121. current->set_texture(StandardMaterial3D::TEXTURE_ALBEDO, texture);
  122. } else if (r_missing_deps) {
  123. r_missing_deps->push_back(path);
  124. }
  125. } else if (l.begins_with("map_Ks ")) {
  126. //normal
  127. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  128. String p = l.replace("map_Ks", "").replace("\\", "/").strip_edges();
  129. String path;
  130. if (p.is_absolute_path()) {
  131. path = p;
  132. } else {
  133. path = base_path.path_join(p);
  134. }
  135. Ref<Texture2D> texture = ResourceLoader::load(path);
  136. if (texture.is_valid()) {
  137. current->set_texture(StandardMaterial3D::TEXTURE_METALLIC, texture);
  138. } else if (r_missing_deps) {
  139. r_missing_deps->push_back(path);
  140. }
  141. } else if (l.begins_with("map_Ns ")) {
  142. //normal
  143. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  144. String p = l.replace("map_Ns", "").replace("\\", "/").strip_edges();
  145. String path;
  146. if (p.is_absolute_path()) {
  147. path = p;
  148. } else {
  149. path = base_path.path_join(p);
  150. }
  151. Ref<Texture2D> texture = ResourceLoader::load(path);
  152. if (texture.is_valid()) {
  153. current->set_texture(StandardMaterial3D::TEXTURE_ROUGHNESS, texture);
  154. } else if (r_missing_deps) {
  155. r_missing_deps->push_back(path);
  156. }
  157. } else if (l.begins_with("map_bump ")) {
  158. //normal
  159. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  160. String p = l.replace("map_bump", "").replace("\\", "/").strip_edges();
  161. String path = base_path.path_join(p);
  162. Ref<Texture2D> texture = ResourceLoader::load(path);
  163. if (texture.is_valid()) {
  164. current->set_feature(StandardMaterial3D::FEATURE_NORMAL_MAPPING, true);
  165. current->set_texture(StandardMaterial3D::TEXTURE_NORMAL, texture);
  166. } else if (r_missing_deps) {
  167. r_missing_deps->push_back(path);
  168. }
  169. } else if (f->eof_reached()) {
  170. break;
  171. }
  172. }
  173. return OK;
  174. }
  175. static Error _parse_obj(const String &p_path, List<Ref<ImporterMesh>> &r_meshes, bool p_single_mesh, bool p_generate_tangents, bool p_generate_lods, bool p_generate_shadow_mesh, bool p_generate_lightmap_uv2, float p_generate_lightmap_uv2_texel_size, const PackedByteArray &p_src_lightmap_cache, Vector3 p_scale_mesh, Vector3 p_offset_mesh, bool p_disable_compression, Vector<Vector<uint8_t>> &r_lightmap_caches, List<String> *r_missing_deps) {
  176. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  177. ERR_FAIL_COND_V_MSG(f.is_null(), ERR_CANT_OPEN, vformat("Couldn't open OBJ file '%s', it may not exist or not be readable.", p_path));
  178. // Avoid trying to load/interpret potential build artifacts from Visual Studio (e.g. when compiling native plugins inside the project tree).
  179. // This should only match if it's indeed a COFF file header.
  180. // https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#machine-types
  181. const int first_bytes = f->get_16();
  182. static const Vector<int> coff_header_machines{
  183. 0x0, // IMAGE_FILE_MACHINE_UNKNOWN
  184. 0x8664, // IMAGE_FILE_MACHINE_AMD64
  185. 0x1c0, // IMAGE_FILE_MACHINE_ARM
  186. 0x14c, // IMAGE_FILE_MACHINE_I386
  187. 0x200, // IMAGE_FILE_MACHINE_IA64
  188. };
  189. ERR_FAIL_COND_V_MSG(coff_header_machines.has(first_bytes), ERR_FILE_CORRUPT, vformat("Couldn't read OBJ file '%s', it seems to be binary, corrupted, or empty.", p_path));
  190. f->seek(0);
  191. Ref<ImporterMesh> mesh;
  192. mesh.instantiate();
  193. bool generate_tangents = p_generate_tangents;
  194. Vector3 scale_mesh = p_scale_mesh;
  195. Vector3 offset_mesh = p_offset_mesh;
  196. Vector<Vector3> vertices;
  197. Vector<Vector3> normals;
  198. Vector<Vector2> uvs;
  199. Vector<Color> colors;
  200. const String default_name = "Mesh";
  201. String name = default_name;
  202. HashMap<String, HashMap<String, Ref<StandardMaterial3D>>> material_map;
  203. Ref<SurfaceTool> surf_tool = memnew(SurfaceTool);
  204. surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
  205. String current_material_library;
  206. String current_material;
  207. String current_group;
  208. uint32_t smooth_group = 0;
  209. bool smoothing = true;
  210. const uint32_t no_smoothing_smooth_group = (uint32_t)-1;
  211. bool uses_uvs = false;
  212. while (true) {
  213. String l = f->get_line().strip_edges();
  214. while (l.length() && l[l.length() - 1] == '\\') {
  215. String add = f->get_line().strip_edges();
  216. l += add;
  217. if (add.is_empty()) {
  218. break;
  219. }
  220. }
  221. if (l.begins_with("v ")) {
  222. //vertex
  223. Vector<String> v = l.split(" ", false);
  224. ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
  225. Vector3 vtx;
  226. vtx.x = v[1].to_float() * scale_mesh.x + offset_mesh.x;
  227. vtx.y = v[2].to_float() * scale_mesh.y + offset_mesh.y;
  228. vtx.z = v[3].to_float() * scale_mesh.z + offset_mesh.z;
  229. vertices.push_back(vtx);
  230. //vertex color
  231. if (v.size() >= 7) {
  232. while (colors.size() < vertices.size() - 1) {
  233. colors.push_back(Color(1.0, 1.0, 1.0));
  234. }
  235. Color c;
  236. c.r = v[4].to_float();
  237. c.g = v[5].to_float();
  238. c.b = v[6].to_float();
  239. colors.push_back(c);
  240. } else if (!colors.is_empty()) {
  241. colors.push_back(Color(1.0, 1.0, 1.0));
  242. }
  243. } else if (l.begins_with("vt ")) {
  244. //uv
  245. Vector<String> v = l.split(" ", false);
  246. ERR_FAIL_COND_V(v.size() < 3, ERR_FILE_CORRUPT);
  247. Vector2 uv;
  248. uv.x = v[1].to_float();
  249. uv.y = 1.0 - v[2].to_float();
  250. uvs.push_back(uv);
  251. } else if (l.begins_with("vn ")) {
  252. //normal
  253. Vector<String> v = l.split(" ", false);
  254. ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
  255. Vector3 nrm;
  256. nrm.x = v[1].to_float();
  257. nrm.y = v[2].to_float();
  258. nrm.z = v[3].to_float();
  259. normals.push_back(nrm);
  260. } else if (l.begins_with("f ")) {
  261. //vertex
  262. Vector<String> v = l.split(" ", false);
  263. ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
  264. //not very fast, could be sped up
  265. Vector<String> face[3];
  266. face[0] = v[1].split("/");
  267. face[1] = v[2].split("/");
  268. ERR_FAIL_COND_V(face[0].is_empty(), ERR_FILE_CORRUPT);
  269. ERR_FAIL_COND_V(face[0].size() != face[1].size(), ERR_FILE_CORRUPT);
  270. for (int i = 2; i < v.size() - 1; i++) {
  271. face[2] = v[i + 1].split("/");
  272. ERR_FAIL_COND_V(face[0].size() != face[2].size(), ERR_FILE_CORRUPT);
  273. for (int j = 0; j < 3; j++) {
  274. int idx = j;
  275. if (idx < 2) {
  276. idx = 1 ^ idx;
  277. }
  278. // Check UVs before faces as we may need to generate dummy tangents if there are no UVs.
  279. if (face[idx].size() >= 2 && !face[idx][1].is_empty()) {
  280. int uv = face[idx][1].to_int() - 1;
  281. if (uv < 0) {
  282. uv += uvs.size() + 1;
  283. }
  284. ERR_FAIL_INDEX_V(uv, uvs.size(), ERR_FILE_CORRUPT);
  285. surf_tool->set_uv(uvs[uv]);
  286. uses_uvs = true;
  287. }
  288. if (face[idx].size() == 3) {
  289. int norm = face[idx][2].to_int() - 1;
  290. if (norm < 0) {
  291. norm += normals.size() + 1;
  292. }
  293. ERR_FAIL_INDEX_V(norm, normals.size(), ERR_FILE_CORRUPT);
  294. surf_tool->set_normal(normals[norm]);
  295. if (generate_tangents && !uses_uvs) {
  296. // We can't generate tangents without UVs, so create dummy tangents.
  297. Vector3 tan = Vector3(normals[norm].z, -normals[norm].x, normals[norm].y).cross(normals[norm].normalized()).normalized();
  298. surf_tool->set_tangent(Plane(tan.x, tan.y, tan.z, 1.0));
  299. }
  300. } else {
  301. // No normals, use a dummy tangent since normals and tangents will be generated.
  302. if (generate_tangents && !uses_uvs) {
  303. // We can't generate tangents without UVs, so create dummy tangents.
  304. surf_tool->set_tangent(Plane(1.0, 0.0, 0.0, 1.0));
  305. }
  306. }
  307. int vtx = face[idx][0].to_int() - 1;
  308. if (vtx < 0) {
  309. vtx += vertices.size() + 1;
  310. }
  311. ERR_FAIL_INDEX_V(vtx, vertices.size(), ERR_FILE_CORRUPT);
  312. Vector3 vertex = vertices[vtx];
  313. if (!colors.is_empty()) {
  314. surf_tool->set_color(colors[vtx]);
  315. }
  316. surf_tool->set_smooth_group(smoothing ? smooth_group : no_smoothing_smooth_group);
  317. surf_tool->add_vertex(vertex);
  318. }
  319. face[1] = face[2];
  320. }
  321. } else if (l.begins_with("s ")) { //smoothing
  322. String what = l.substr(2).strip_edges();
  323. bool do_smooth;
  324. if (what == "off") {
  325. do_smooth = false;
  326. } else {
  327. do_smooth = true;
  328. }
  329. if (do_smooth != smoothing) {
  330. smoothing = do_smooth;
  331. if (smoothing) {
  332. smooth_group++;
  333. }
  334. }
  335. } else if (/*l.begins_with("g ") ||*/ l.begins_with("usemtl ") || (l.begins_with("o ") || f->eof_reached())) { //commit group to mesh
  336. uint64_t mesh_flags = RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES;
  337. if (p_disable_compression) {
  338. mesh_flags = 0;
  339. } else {
  340. bool is_mesh_2d = true;
  341. // Disable compression if all z equals 0 (the mesh is 2D).
  342. for (int i = 0; i < vertices.size(); i++) {
  343. if (!Math::is_zero_approx(vertices[i].z)) {
  344. is_mesh_2d = false;
  345. break;
  346. }
  347. }
  348. if (is_mesh_2d) {
  349. mesh_flags = 0;
  350. }
  351. }
  352. //groups are too annoying
  353. if (surf_tool->get_vertex_array().size()) {
  354. //another group going on, commit it
  355. if (normals.size() == 0) {
  356. surf_tool->generate_normals();
  357. }
  358. if (generate_tangents && uses_uvs) {
  359. surf_tool->generate_tangents();
  360. }
  361. surf_tool->index();
  362. print_verbose("OBJ: Current material library " + current_material_library + " has " + itos(material_map.has(current_material_library)));
  363. print_verbose("OBJ: Current material " + current_material + " has " + itos(material_map.has(current_material_library) && material_map[current_material_library].has(current_material)));
  364. Ref<StandardMaterial3D> material;
  365. if (material_map.has(current_material_library) && material_map[current_material_library].has(current_material)) {
  366. material = material_map[current_material_library][current_material];
  367. if (!colors.is_empty()) {
  368. material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  369. }
  370. surf_tool->set_material(material);
  371. }
  372. Array array = surf_tool->commit_to_arrays();
  373. if (mesh_flags & RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES && generate_tangents && uses_uvs) {
  374. // Compression is enabled, so let's validate that the normals and generated tangents are correct.
  375. Vector<Vector3> norms = array[Mesh::ARRAY_NORMAL];
  376. Vector<float> tangents = array[Mesh::ARRAY_TANGENT];
  377. ERR_FAIL_COND_V(tangents.is_empty(), ERR_FILE_CORRUPT);
  378. for (int vert = 0; vert < norms.size(); vert++) {
  379. Vector3 tan = Vector3(tangents[vert * 4 + 0], tangents[vert * 4 + 1], tangents[vert * 4 + 2]);
  380. if (abs(tan.dot(norms[vert])) > 0.0001) {
  381. // Tangent is not perpendicular to the normal, so we can't use compression.
  382. mesh_flags &= ~RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES;
  383. }
  384. }
  385. }
  386. mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES, array, TypedArray<Array>(), Dictionary(), material, name, mesh_flags);
  387. print_verbose("OBJ: Added surface :" + mesh->get_surface_name(mesh->get_surface_count() - 1));
  388. if (!current_material.is_empty()) {
  389. if (mesh->get_surface_count() >= 1) {
  390. mesh->set_surface_name(mesh->get_surface_count() - 1, current_material.get_basename());
  391. }
  392. } else if (!current_group.is_empty()) {
  393. if (mesh->get_surface_count() >= 1) {
  394. mesh->set_surface_name(mesh->get_surface_count() - 1, current_group);
  395. }
  396. }
  397. surf_tool->clear();
  398. surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
  399. uses_uvs = false;
  400. }
  401. if (l.begins_with("o ") || f->eof_reached()) {
  402. if (!p_single_mesh) {
  403. if (mesh->get_surface_count() > 0) {
  404. mesh->set_name(name);
  405. r_meshes.push_back(mesh);
  406. mesh.instantiate();
  407. }
  408. name = default_name;
  409. current_group = "";
  410. current_material = "";
  411. }
  412. }
  413. if (f->eof_reached()) {
  414. break;
  415. }
  416. if (l.begins_with("o ")) {
  417. name = l.substr(2).strip_edges();
  418. }
  419. if (l.begins_with("usemtl ")) {
  420. current_material = l.replace("usemtl", "").strip_edges();
  421. }
  422. if (l.begins_with("g ")) {
  423. current_group = l.substr(2).strip_edges();
  424. }
  425. } else if (l.begins_with("mtllib ")) { //parse material
  426. current_material_library = l.replace("mtllib", "").strip_edges();
  427. if (!material_map.has(current_material_library)) {
  428. HashMap<String, Ref<StandardMaterial3D>> lib;
  429. String lib_path = current_material_library;
  430. if (lib_path.is_relative_path()) {
  431. lib_path = p_path.get_base_dir().path_join(current_material_library);
  432. }
  433. Error err = _parse_material_library(lib_path, lib, r_missing_deps);
  434. if (err == OK) {
  435. material_map[current_material_library] = lib;
  436. }
  437. }
  438. }
  439. }
  440. if (p_generate_lightmap_uv2) {
  441. Vector<uint8_t> lightmap_cache;
  442. mesh->lightmap_unwrap_cached(Transform3D(), p_generate_lightmap_uv2_texel_size, p_src_lightmap_cache, lightmap_cache);
  443. if (!lightmap_cache.is_empty()) {
  444. if (r_lightmap_caches.is_empty()) {
  445. r_lightmap_caches.push_back(lightmap_cache);
  446. } else {
  447. // MD5 is stored at the beginning of the cache data.
  448. const String new_md5 = String::md5(lightmap_cache.ptr());
  449. for (int i = 0; i < r_lightmap_caches.size(); i++) {
  450. const String md5 = String::md5(r_lightmap_caches[i].ptr());
  451. if (new_md5 < md5) {
  452. r_lightmap_caches.insert(i, lightmap_cache);
  453. break;
  454. }
  455. if (new_md5 == md5) {
  456. break;
  457. }
  458. }
  459. }
  460. }
  461. }
  462. if (p_generate_lods) {
  463. // Use normal merge/split angles that match the defaults used for 3D scene importing.
  464. mesh->generate_lods(60.0f, {});
  465. }
  466. if (p_generate_shadow_mesh) {
  467. mesh->create_shadow_mesh();
  468. }
  469. mesh->optimize_indices();
  470. if (p_single_mesh && mesh->get_surface_count() > 0) {
  471. r_meshes.push_back(mesh);
  472. }
  473. return OK;
  474. }
  475. Node *EditorOBJImporter::import_scene(const String &p_path, uint32_t p_flags, const HashMap<StringName, Variant> &p_options, List<String> *r_missing_deps, Error *r_err) {
  476. List<Ref<ImporterMesh>> meshes;
  477. // LOD, shadow mesh and lightmap UV2 generation are handled by ResourceImporterScene in this case,
  478. // so disable it within the OBJ mesh import.
  479. Vector<Vector<uint8_t>> mesh_lightmap_caches;
  480. Error err = _parse_obj(p_path, meshes, false, p_flags & IMPORT_GENERATE_TANGENT_ARRAYS, false, false, false, 0.2, PackedByteArray(), Vector3(1, 1, 1), Vector3(0, 0, 0), p_flags & IMPORT_FORCE_DISABLE_MESH_COMPRESSION, mesh_lightmap_caches, r_missing_deps);
  481. if (err != OK) {
  482. if (r_err) {
  483. *r_err = err;
  484. }
  485. return nullptr;
  486. }
  487. Node3D *scene = memnew(Node3D);
  488. for (Ref<ImporterMesh> m : meshes) {
  489. ImporterMeshInstance3D *mi = memnew(ImporterMeshInstance3D);
  490. mi->set_mesh(m);
  491. mi->set_name(m->get_name());
  492. scene->add_child(mi, true);
  493. mi->set_owner(scene);
  494. }
  495. if (r_err) {
  496. *r_err = OK;
  497. }
  498. return scene;
  499. }
  500. void EditorOBJImporter::get_extensions(List<String> *r_extensions) const {
  501. r_extensions->push_back("obj");
  502. }
  503. EditorOBJImporter::EditorOBJImporter() {
  504. }
  505. ////////////////////////////////////////////////////
  506. String ResourceImporterOBJ::get_importer_name() const {
  507. return "wavefront_obj";
  508. }
  509. String ResourceImporterOBJ::get_visible_name() const {
  510. return "OBJ as Mesh";
  511. }
  512. void ResourceImporterOBJ::get_recognized_extensions(List<String> *p_extensions) const {
  513. p_extensions->push_back("obj");
  514. }
  515. String ResourceImporterOBJ::get_save_extension() const {
  516. return "mesh";
  517. }
  518. String ResourceImporterOBJ::get_resource_type() const {
  519. return "Mesh";
  520. }
  521. int ResourceImporterOBJ::get_format_version() const {
  522. return 1;
  523. }
  524. int ResourceImporterOBJ::get_preset_count() const {
  525. return 0;
  526. }
  527. String ResourceImporterOBJ::get_preset_name(int p_idx) const {
  528. return "";
  529. }
  530. void ResourceImporterOBJ::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
  531. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate_tangents"), true));
  532. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate_lods"), true));
  533. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate_shadow_mesh"), true));
  534. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate_lightmap_uv2", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), false));
  535. r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "generate_lightmap_uv2_texel_size", PROPERTY_HINT_RANGE, "0.001,100,0.001"), 0.2));
  536. r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "scale_mesh"), Vector3(1, 1, 1)));
  537. r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "offset_mesh"), Vector3(0, 0, 0)));
  538. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "force_disable_mesh_compression"), false));
  539. }
  540. bool ResourceImporterOBJ::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
  541. if (p_option == "generate_lightmap_uv2_texel_size" && !p_options["generate_lightmap_uv2"]) {
  542. // Only display the lightmap texel size import option when lightmap UV2 generation is enabled.
  543. return false;
  544. }
  545. return true;
  546. }
  547. Error ResourceImporterOBJ::import(ResourceUID::ID p_source_id, const String &p_source_file, const String &p_save_path, const HashMap<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
  548. List<Ref<ImporterMesh>> meshes;
  549. Vector<uint8_t> src_lightmap_cache;
  550. Vector<Vector<uint8_t>> mesh_lightmap_caches;
  551. Error err;
  552. {
  553. src_lightmap_cache = FileAccess::get_file_as_bytes(p_source_file + ".unwrap_cache", &err);
  554. if (err != OK) {
  555. src_lightmap_cache.clear();
  556. }
  557. }
  558. err = _parse_obj(p_source_file, meshes, true, p_options["generate_tangents"], p_options["generate_lods"], p_options["generate_shadow_mesh"], p_options["generate_lightmap_uv2"], p_options["generate_lightmap_uv2_texel_size"], src_lightmap_cache, p_options["scale_mesh"], p_options["offset_mesh"], p_options["force_disable_mesh_compression"], mesh_lightmap_caches, nullptr);
  559. if (mesh_lightmap_caches.size()) {
  560. Ref<FileAccess> f = FileAccess::open(p_source_file + ".unwrap_cache", FileAccess::WRITE);
  561. if (f.is_valid()) {
  562. f->store_32(mesh_lightmap_caches.size());
  563. for (int i = 0; i < mesh_lightmap_caches.size(); i++) {
  564. String md5 = String::md5(mesh_lightmap_caches[i].ptr());
  565. f->store_buffer(mesh_lightmap_caches[i].ptr(), mesh_lightmap_caches[i].size());
  566. }
  567. }
  568. }
  569. err = OK;
  570. ERR_FAIL_COND_V(err != OK, err);
  571. ERR_FAIL_COND_V(meshes.size() != 1, ERR_BUG);
  572. String save_path = p_save_path + ".mesh";
  573. err = ResourceSaver::save(meshes.front()->get()->get_mesh(), save_path);
  574. ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save Mesh to file '" + save_path + "'.");
  575. r_gen_files->push_back(save_path);
  576. return OK;
  577. }
  578. ResourceImporterOBJ::ResourceImporterOBJ() {
  579. }