resource_importer_obj.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. /*************************************************************************/
  2. /* resource_importer_obj.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  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/resource_saver.h"
  32. #include "core/os/file_access.h"
  33. #include "scene/3d/mesh_instance.h"
  34. #include "scene/3d/spatial.h"
  35. #include "scene/resources/mesh.h"
  36. #include "scene/resources/surface_tool.h"
  37. uint32_t EditorOBJImporter::get_import_flags() const {
  38. return IMPORT_SCENE;
  39. }
  40. static Error _parse_material_library(const String &p_path, Map<String, Ref<SpatialMaterial> > &material_map, List<String> *r_missing_deps) {
  41. FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
  42. ERR_EXPLAIN(vformat("Couldn't open MTL file '%s', it may not exist or not be readable.", p_path));
  43. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  44. Ref<SpatialMaterial> current;
  45. String current_name;
  46. String base_path = p_path.get_base_dir();
  47. while (true) {
  48. String l = f->get_line().strip_edges();
  49. if (l.begins_with("newmtl ")) {
  50. //vertex
  51. current_name = l.replace("newmtl", "").strip_edges();
  52. current.instance();
  53. current->set_name(current_name);
  54. material_map[current_name] = current;
  55. } else if (l.begins_with("Ka ")) {
  56. //uv
  57. WARN_PRINTS("OBJ: Ambient light for material '" + current_name + "' is ignored in PBR");
  58. } else if (l.begins_with("Kd ")) {
  59. //normal
  60. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  61. Vector<String> v = l.split(" ", false);
  62. ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
  63. Color c = current->get_albedo();
  64. c.r = v[1].to_float();
  65. c.g = v[2].to_float();
  66. c.b = v[3].to_float();
  67. current->set_albedo(c);
  68. } else if (l.begins_with("Ks ")) {
  69. //normal
  70. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  71. Vector<String> v = l.split(" ", false);
  72. ERR_FAIL_COND_V(v.size() < 4, ERR_INVALID_DATA);
  73. float r = v[1].to_float();
  74. float g = v[2].to_float();
  75. float b = v[3].to_float();
  76. float metalness = MAX(r, MAX(g, b));
  77. current->set_metallic(metalness);
  78. } else if (l.begins_with("Ns ")) {
  79. //normal
  80. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  81. Vector<String> v = l.split(" ", false);
  82. ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
  83. float s = v[1].to_float();
  84. current->set_metallic((1000.0 - s) / 1000.0);
  85. } else if (l.begins_with("d ")) {
  86. //normal
  87. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  88. Vector<String> v = l.split(" ", false);
  89. ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
  90. float d = v[1].to_float();
  91. Color c = current->get_albedo();
  92. c.a = d;
  93. current->set_albedo(c);
  94. if (c.a < 0.99) {
  95. current->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  96. }
  97. } else if (l.begins_with("Tr ")) {
  98. //normal
  99. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  100. Vector<String> v = l.split(" ", false);
  101. ERR_FAIL_COND_V(v.size() != 2, ERR_INVALID_DATA);
  102. float d = v[1].to_float();
  103. Color c = current->get_albedo();
  104. c.a = 1.0 - d;
  105. current->set_albedo(c);
  106. if (c.a < 0.99) {
  107. current->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  108. }
  109. } else if (l.begins_with("map_Ka ")) {
  110. //uv
  111. WARN_PRINTS("OBJ: Ambient light texture for material '" + current_name + "' is ignored in PBR");
  112. } else if (l.begins_with("map_Kd ")) {
  113. //normal
  114. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  115. String p = l.replace("map_Kd", "").replace("\\", "/").strip_edges();
  116. String path;
  117. if (p.is_abs_path()) {
  118. path = p;
  119. } else {
  120. path = base_path.plus_file(p);
  121. }
  122. Ref<Texture> texture = ResourceLoader::load(path);
  123. if (texture.is_valid()) {
  124. current->set_texture(SpatialMaterial::TEXTURE_ALBEDO, texture);
  125. } else if (r_missing_deps) {
  126. r_missing_deps->push_back(path);
  127. }
  128. } else if (l.begins_with("map_Ks ")) {
  129. //normal
  130. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  131. String p = l.replace("map_Ks", "").replace("\\", "/").strip_edges();
  132. String path;
  133. if (p.is_abs_path()) {
  134. path = p;
  135. } else {
  136. path = base_path.plus_file(p);
  137. }
  138. Ref<Texture> texture = ResourceLoader::load(path);
  139. if (texture.is_valid()) {
  140. current->set_texture(SpatialMaterial::TEXTURE_METALLIC, texture);
  141. } else if (r_missing_deps) {
  142. r_missing_deps->push_back(path);
  143. }
  144. } else if (l.begins_with("map_Ns ")) {
  145. //normal
  146. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  147. String p = l.replace("map_Ns", "").replace("\\", "/").strip_edges();
  148. String path;
  149. if (p.is_abs_path()) {
  150. path = p;
  151. } else {
  152. path = base_path.plus_file(p);
  153. }
  154. Ref<Texture> texture = ResourceLoader::load(path);
  155. if (texture.is_valid()) {
  156. current->set_texture(SpatialMaterial::TEXTURE_ROUGHNESS, texture);
  157. } else if (r_missing_deps) {
  158. r_missing_deps->push_back(path);
  159. }
  160. } else if (l.begins_with("map_bump ")) {
  161. //normal
  162. ERR_FAIL_COND_V(current.is_null(), ERR_FILE_CORRUPT);
  163. String p = l.replace("map_bump", "").replace("\\", "/").strip_edges();
  164. String path = base_path.plus_file(p);
  165. Ref<Texture> texture = ResourceLoader::load(path);
  166. if (texture.is_valid()) {
  167. current->set_feature(SpatialMaterial::FEATURE_NORMAL_MAPPING, true);
  168. current->set_texture(SpatialMaterial::TEXTURE_NORMAL, texture);
  169. } else if (r_missing_deps) {
  170. r_missing_deps->push_back(path);
  171. }
  172. } else if (f->eof_reached()) {
  173. break;
  174. }
  175. }
  176. return OK;
  177. }
  178. static Error _parse_obj(const String &p_path, List<Ref<Mesh> > &r_meshes, bool p_single_mesh, bool p_generate_tangents, bool p_optimize, Vector3 p_scale_mesh, List<String> *r_missing_deps) {
  179. FileAccessRef f = FileAccess::open(p_path, FileAccess::READ);
  180. ERR_EXPLAIN(vformat("Couldn't open OBJ file '%s', it may not exist or not be readable.", p_path));
  181. ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
  182. Ref<ArrayMesh> mesh;
  183. mesh.instance();
  184. bool generate_tangents = p_generate_tangents;
  185. Vector3 scale_mesh = p_scale_mesh;
  186. bool flip_faces = false;
  187. int mesh_flags = p_optimize ? Mesh::ARRAY_COMPRESS_DEFAULT : 0;
  188. Vector<Vector3> vertices;
  189. Vector<Vector3> normals;
  190. Vector<Vector2> uvs;
  191. String name;
  192. Map<String, Map<String, Ref<SpatialMaterial> > > material_map;
  193. Ref<SurfaceTool> surf_tool = memnew(SurfaceTool);
  194. surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
  195. String current_material_library;
  196. String current_material;
  197. String current_group;
  198. while (true) {
  199. String l = f->get_line().strip_edges();
  200. while (l.length() && l[l.length() - 1] == '\\') {
  201. String add = f->get_line().strip_edges();
  202. l += add;
  203. if (add == String()) {
  204. break;
  205. }
  206. }
  207. if (l.begins_with("v ")) {
  208. //vertex
  209. Vector<String> v = l.split(" ", false);
  210. ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
  211. Vector3 vtx;
  212. vtx.x = v[1].to_float() * scale_mesh.x;
  213. vtx.y = v[2].to_float() * scale_mesh.y;
  214. vtx.z = v[3].to_float() * scale_mesh.z;
  215. vertices.push_back(vtx);
  216. } else if (l.begins_with("vt ")) {
  217. //uv
  218. Vector<String> v = l.split(" ", false);
  219. ERR_FAIL_COND_V(v.size() < 3, ERR_FILE_CORRUPT);
  220. Vector2 uv;
  221. uv.x = v[1].to_float();
  222. uv.y = 1.0 - v[2].to_float();
  223. uvs.push_back(uv);
  224. } else if (l.begins_with("vn ")) {
  225. //normal
  226. Vector<String> v = l.split(" ", false);
  227. ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
  228. Vector3 nrm;
  229. nrm.x = v[1].to_float();
  230. nrm.y = v[2].to_float();
  231. nrm.z = v[3].to_float();
  232. normals.push_back(nrm);
  233. } else if (l.begins_with("f ")) {
  234. //vertex
  235. Vector<String> v = l.split(" ", false);
  236. ERR_FAIL_COND_V(v.size() < 4, ERR_FILE_CORRUPT);
  237. //not very fast, could be sped up
  238. Vector<String> face[3];
  239. face[0] = v[1].split("/");
  240. face[1] = v[2].split("/");
  241. ERR_FAIL_COND_V(face[0].size() == 0, ERR_FILE_CORRUPT);
  242. ERR_FAIL_COND_V(face[0].size() != face[1].size(), ERR_FILE_CORRUPT);
  243. for (int i = 2; i < v.size() - 1; i++) {
  244. face[2] = v[i + 1].split("/");
  245. ERR_FAIL_COND_V(face[0].size() != face[2].size(), ERR_FILE_CORRUPT);
  246. for (int j = 0; j < 3; j++) {
  247. int idx = j;
  248. if (!flip_faces && idx < 2) {
  249. idx = 1 ^ idx;
  250. }
  251. if (face[idx].size() == 3) {
  252. int norm = face[idx][2].to_int() - 1;
  253. if (norm < 0)
  254. norm += normals.size() + 1;
  255. ERR_FAIL_INDEX_V(norm, normals.size(), ERR_FILE_CORRUPT);
  256. surf_tool->add_normal(normals[norm]);
  257. }
  258. if (face[idx].size() >= 2 && face[idx][1] != String()) {
  259. int uv = face[idx][1].to_int() - 1;
  260. if (uv < 0)
  261. uv += uvs.size() + 1;
  262. ERR_FAIL_INDEX_V(uv, uvs.size(), ERR_FILE_CORRUPT);
  263. surf_tool->add_uv(uvs[uv]);
  264. }
  265. int vtx = face[idx][0].to_int() - 1;
  266. if (vtx < 0)
  267. vtx += vertices.size() + 1;
  268. ERR_FAIL_INDEX_V(vtx, vertices.size(), ERR_FILE_CORRUPT);
  269. Vector3 vertex = vertices[vtx];
  270. //if (weld_vertices)
  271. // vertex.snap(Vector3(weld_tolerance, weld_tolerance, weld_tolerance));
  272. surf_tool->add_vertex(vertex);
  273. }
  274. face[1] = face[2];
  275. }
  276. } else if (l.begins_with("s ")) { //smoothing
  277. String what = l.substr(2, l.length()).strip_edges();
  278. if (what == "off")
  279. surf_tool->add_smooth_group(false);
  280. else
  281. surf_tool->add_smooth_group(true);
  282. } else if (/*l.begins_with("g ") ||*/ l.begins_with("usemtl ") || (l.begins_with("o ") || f->eof_reached())) { //commit group to mesh
  283. //groups are too annoying
  284. if (surf_tool->get_vertex_array().size()) {
  285. //another group going on, commit it
  286. if (normals.size() == 0) {
  287. surf_tool->generate_normals();
  288. }
  289. if (generate_tangents && uvs.size()) {
  290. surf_tool->generate_tangents();
  291. }
  292. surf_tool->index();
  293. print_verbose("OBJ: Current material library " + current_material_library + " has " + itos(material_map.has(current_material_library)));
  294. print_verbose("OBJ: Current material " + current_material + " has " + itos(material_map.has(current_material_library) && material_map[current_material_library].has(current_material)));
  295. if (material_map.has(current_material_library) && material_map[current_material_library].has(current_material)) {
  296. surf_tool->set_material(material_map[current_material_library][current_material]);
  297. }
  298. mesh = surf_tool->commit(mesh, mesh_flags);
  299. if (current_material != String()) {
  300. mesh->surface_set_name(mesh->get_surface_count() - 1, current_material.get_basename());
  301. } else if (current_group != String()) {
  302. mesh->surface_set_name(mesh->get_surface_count() - 1, current_group);
  303. }
  304. print_verbose("OBJ: Added surface :" + mesh->surface_get_name(mesh->get_surface_count() - 1));
  305. surf_tool->clear();
  306. surf_tool->begin(Mesh::PRIMITIVE_TRIANGLES);
  307. }
  308. if (l.begins_with("o ") || f->eof_reached()) {
  309. if (!p_single_mesh) {
  310. mesh->set_name(name);
  311. r_meshes.push_back(mesh);
  312. mesh.instance();
  313. current_group = "";
  314. current_material = "";
  315. }
  316. }
  317. if (f->eof_reached()) {
  318. break;
  319. }
  320. if (l.begins_with("o ")) {
  321. name = l.substr(2, l.length()).strip_edges();
  322. }
  323. if (l.begins_with("usemtl ")) {
  324. current_material = l.replace("usemtl", "").strip_edges();
  325. }
  326. if (l.begins_with("g ")) {
  327. current_group = l.substr(2, l.length()).strip_edges();
  328. }
  329. } else if (l.begins_with("mtllib ")) { //parse material
  330. current_material_library = l.replace("mtllib", "").strip_edges();
  331. if (!material_map.has(current_material_library)) {
  332. Map<String, Ref<SpatialMaterial> > lib;
  333. Error err = _parse_material_library(current_material_library, lib, r_missing_deps);
  334. if (err == ERR_CANT_OPEN) {
  335. String dir = p_path.get_base_dir();
  336. err = _parse_material_library(dir.plus_file(current_material_library), lib, r_missing_deps);
  337. }
  338. if (err == OK) {
  339. material_map[current_material_library] = lib;
  340. }
  341. }
  342. }
  343. }
  344. if (p_single_mesh) {
  345. r_meshes.push_back(mesh);
  346. }
  347. return OK;
  348. }
  349. Node *EditorOBJImporter::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err) {
  350. List<Ref<Mesh> > meshes;
  351. Error err = _parse_obj(p_path, meshes, false, p_flags & IMPORT_GENERATE_TANGENT_ARRAYS, p_flags & IMPORT_USE_COMPRESSION, Vector3(1, 1, 1), r_missing_deps);
  352. if (err != OK) {
  353. if (r_err) {
  354. *r_err = err;
  355. }
  356. return NULL;
  357. }
  358. Spatial *scene = memnew(Spatial);
  359. for (List<Ref<Mesh> >::Element *E = meshes.front(); E; E = E->next()) {
  360. MeshInstance *mi = memnew(MeshInstance);
  361. mi->set_mesh(E->get());
  362. mi->set_name(E->get()->get_name());
  363. scene->add_child(mi);
  364. mi->set_owner(scene);
  365. }
  366. if (r_err) {
  367. *r_err = OK;
  368. }
  369. return scene;
  370. }
  371. Ref<Animation> EditorOBJImporter::import_animation(const String &p_path, uint32_t p_flags, int p_bake_fps) {
  372. return Ref<Animation>();
  373. }
  374. void EditorOBJImporter::get_extensions(List<String> *r_extensions) const {
  375. r_extensions->push_back("obj");
  376. }
  377. EditorOBJImporter::EditorOBJImporter() {
  378. }
  379. ////////////////////////////////////////////////////
  380. String ResourceImporterOBJ::get_importer_name() const {
  381. return "wavefront_obj";
  382. }
  383. String ResourceImporterOBJ::get_visible_name() const {
  384. return "OBJ As Mesh";
  385. }
  386. void ResourceImporterOBJ::get_recognized_extensions(List<String> *p_extensions) const {
  387. p_extensions->push_back("obj");
  388. }
  389. String ResourceImporterOBJ::get_save_extension() const {
  390. return "mesh";
  391. }
  392. String ResourceImporterOBJ::get_resource_type() const {
  393. return "Mesh";
  394. }
  395. int ResourceImporterOBJ::get_preset_count() const {
  396. return 0;
  397. }
  398. String ResourceImporterOBJ::get_preset_name(int p_idx) const {
  399. return "";
  400. }
  401. void ResourceImporterOBJ::get_import_options(List<ImportOption> *r_options, int p_preset) const {
  402. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "generate_tangents"), true));
  403. r_options->push_back(ImportOption(PropertyInfo(Variant::VECTOR3, "scale_mesh"), Vector3(1, 1, 1)));
  404. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "optimize_mesh"), true));
  405. }
  406. bool ResourceImporterOBJ::get_option_visibility(const String &p_option, const Map<StringName, Variant> &p_options) const {
  407. return true;
  408. }
  409. Error ResourceImporterOBJ::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files) {
  410. List<Ref<Mesh> > meshes;
  411. Error err = _parse_obj(p_source_file, meshes, true, p_options["generate_tangents"], p_options["optimize_mesh"], p_options["scale_mesh"], NULL);
  412. ERR_FAIL_COND_V(err != OK, err);
  413. ERR_FAIL_COND_V(meshes.size() != 1, ERR_BUG);
  414. String save_path = p_save_path + ".mesh";
  415. err = ResourceSaver::save(save_path, meshes.front()->get());
  416. ERR_FAIL_COND_V(err != OK, err);
  417. r_gen_files->push_back(save_path);
  418. return OK;
  419. }
  420. ResourceImporterOBJ::ResourceImporterOBJ() {
  421. }