resource_importer_obj.cpp 24 KB

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