2
0

fbx_material.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*************************************************************************/
  2. /* fbx_material.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "fbx_material.h"
  31. // FIXME: Shouldn't depend on core_bind.h! Use DirAccessRef like the rest of
  32. // the engine instead of core_bind::Directory.
  33. #include "core/core_bind.h"
  34. #include "scene/resources/material.h"
  35. #include "scene/resources/texture.h"
  36. #include "tools/validation_tools.h"
  37. String FBXMaterial::get_material_name() const {
  38. return material_name;
  39. }
  40. void FBXMaterial::set_imported_material(FBXDocParser::Material *p_material) {
  41. material = p_material;
  42. }
  43. void FBXMaterial::add_search_string(String p_filename, String p_current_directory, String search_directory, Vector<String> &texture_search_paths) {
  44. if (search_directory.is_empty()) {
  45. texture_search_paths.push_back(p_current_directory.get_base_dir().plus_file(p_filename));
  46. } else {
  47. texture_search_paths.push_back(p_current_directory.get_base_dir().plus_file(search_directory + "/" + p_filename));
  48. texture_search_paths.push_back(p_current_directory.get_base_dir().plus_file("../" + search_directory + "/" + p_filename));
  49. }
  50. }
  51. String find_file(const String &p_base, const String &p_file_to_find) {
  52. core_bind::Directory dir;
  53. dir.open(p_base);
  54. dir.list_dir_begin();
  55. String n = dir.get_next();
  56. while (n != String()) {
  57. if (n == "." || n == "..") {
  58. n = dir.get_next();
  59. continue;
  60. }
  61. if (dir.current_is_dir()) {
  62. // Don't use `path_to` or the returned path will be wrong.
  63. const String f = find_file(p_base + "/" + n, p_file_to_find);
  64. if (f != "") {
  65. return f;
  66. }
  67. } else if (n == p_file_to_find) {
  68. return p_base + "/" + n;
  69. }
  70. n = dir.get_next();
  71. }
  72. dir.list_dir_end();
  73. return String();
  74. }
  75. // fbx will not give us good path information and let's not regex them to fix them
  76. // no relative paths are in fbx generally they have a rel field but it's populated incorrectly by the SDK.
  77. String FBXMaterial::find_texture_path_by_filename(const String p_filename, const String p_current_directory) {
  78. core_bind::Directory dir;
  79. Vector<String> paths;
  80. add_search_string(p_filename, p_current_directory, "", paths);
  81. add_search_string(p_filename, p_current_directory, "texture", paths);
  82. add_search_string(p_filename, p_current_directory, "textures", paths);
  83. add_search_string(p_filename, p_current_directory, "Textures", paths);
  84. add_search_string(p_filename, p_current_directory, "materials", paths);
  85. add_search_string(p_filename, p_current_directory, "mats", paths);
  86. add_search_string(p_filename, p_current_directory, "pictures", paths);
  87. add_search_string(p_filename, p_current_directory, "images", paths);
  88. for (int i = 0; i < paths.size(); i++) {
  89. if (dir.file_exists(paths[i])) {
  90. return paths[i];
  91. }
  92. }
  93. // We were not able to find the texture in the common locations,
  94. // try to find it into the project globally.
  95. // The common textures can be stored into one of those folders:
  96. // res://asset
  97. // res://texture
  98. // res://material
  99. // res://mat
  100. // res://image
  101. // res://picture
  102. //
  103. // Note the folders can also be called with custom names, like:
  104. // res://my_assets
  105. // since the keyword `asset` is into the directory name the textures will be
  106. // searched there too.
  107. dir.open("res://");
  108. dir.list_dir_begin();
  109. String n = dir.get_next();
  110. while (n != String()) {
  111. if (n == "." || n == "..") {
  112. n = dir.get_next();
  113. continue;
  114. }
  115. if (dir.current_is_dir()) {
  116. const String lower_n = n.to_lower();
  117. if (
  118. // Don't need to use plural.
  119. lower_n.find("asset") >= 0 ||
  120. lower_n.find("texture") >= 0 ||
  121. lower_n.find("material") >= 0 ||
  122. lower_n.find("mat") >= 0 ||
  123. lower_n.find("image") >= 0 ||
  124. lower_n.find("picture") >= 0) {
  125. // Don't use `path_to` or the returned path will be wrong.
  126. const String f = find_file(String("res://") + n, p_filename);
  127. if (f != "") {
  128. return f;
  129. }
  130. }
  131. }
  132. n = dir.get_next();
  133. }
  134. dir.list_dir_end();
  135. return "";
  136. }
  137. template <class T>
  138. T extract_from_prop(FBXDocParser::PropertyPtr prop, const T &p_default, const std::string &p_name, const String &p_type) {
  139. ERR_FAIL_COND_V_MSG(prop == nullptr, p_default, "invalid property passed to extractor");
  140. const FBXDocParser::TypedProperty<T> *val = dynamic_cast<const FBXDocParser::TypedProperty<T> *>(prop);
  141. ERR_FAIL_COND_V_MSG(val == nullptr, p_default, "The FBX is corrupted, the property `" + String(p_name.c_str()) + "` is a `" + String(typeid(*prop).name()) + "` but should be a " + p_type);
  142. // Make sure to not lost any eventual opacity.
  143. return val->Value();
  144. }
  145. Ref<StandardMaterial3D> FBXMaterial::import_material(ImportState &state) {
  146. ERR_FAIL_COND_V(material == nullptr, nullptr);
  147. const String p_fbx_current_directory = state.path;
  148. Ref<StandardMaterial3D> spatial_material;
  149. spatial_material.instantiate();
  150. // read the material file
  151. // is material two sided
  152. // read material name
  153. print_verbose("[material] material name: " + ImportUtils::FBXNodeToName(material->Name()));
  154. material_name = ImportUtils::FBXNodeToName(material->Name());
  155. for (const std::pair<std::string, const FBXDocParser::Texture *> iter : material->Textures()) {
  156. const uint64_t texture_id = iter.second->ID();
  157. const std::string &fbx_mapping_name = iter.first;
  158. const FBXDocParser::Texture *fbx_texture_data = iter.second;
  159. const String absolute_texture_path = iter.second->FileName().c_str();
  160. const String texture_name = absolute_texture_path.get_file();
  161. const String file_extension = absolute_texture_path.get_extension().to_upper();
  162. const String debug_string = "texture id: " + itos(texture_id) + " texture name: " + String(iter.second->Name().c_str()) + " mapping name: " + String(fbx_mapping_name.c_str());
  163. // remember errors STILL need this string at the end for when you aren't in verbose debug mode :) they need context for when you're not verbose-ing.
  164. print_verbose(debug_string);
  165. const String file_extension_uppercase = file_extension.to_upper();
  166. if (fbx_transparency_flags.count(fbx_mapping_name) > 0) {
  167. // just enable it later let's make this fine-tuned.
  168. spatial_material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA);
  169. }
  170. ERR_CONTINUE_MSG(file_extension.is_empty(), "your texture has no file extension so we had to ignore it, let us know if you think this is wrong file an issue on github! " + debug_string);
  171. ERR_CONTINUE_MSG(fbx_texture_map.count(fbx_mapping_name) <= 0, "This material has a texture with mapping name: " + String(fbx_mapping_name.c_str()) + " which is not yet supported by this importer. Consider opening an issue so we can support it.");
  172. ERR_CONTINUE_MSG(
  173. file_extension_uppercase != "PNG" &&
  174. file_extension_uppercase != "JPEG" &&
  175. file_extension_uppercase != "JPG" &&
  176. file_extension_uppercase != "TGA" &&
  177. file_extension_uppercase != "WEBP" &&
  178. file_extension_uppercase != "DDS",
  179. "The FBX file contains a texture with an unrecognized extension: " + file_extension_uppercase);
  180. print_verbose("Getting FBX mapping mode for " + String(fbx_mapping_name.c_str()));
  181. // get the texture map type
  182. const StandardMaterial3D::TextureParam mapping_mode = fbx_texture_map.at(fbx_mapping_name);
  183. print_verbose("Set FBX mapping mode to " + get_texture_param_name(mapping_mode));
  184. Ref<Texture> texture;
  185. print_verbose("texture mapping name: " + texture_name);
  186. if (state.cached_image_searches.has(texture_name)) {
  187. texture = state.cached_image_searches[texture_name];
  188. } else {
  189. String path = find_texture_path_by_filename(texture_name, p_fbx_current_directory);
  190. if (!path.is_empty()) {
  191. Ref<Texture2D> image_texture = ResourceLoader::load(path);
  192. ERR_CONTINUE(image_texture.is_null());
  193. texture = image_texture;
  194. state.cached_image_searches.insert(texture_name, texture);
  195. print_verbose("Created texture from loaded image file.");
  196. } else if (fbx_texture_data != nullptr && fbx_texture_data->Media() != nullptr && fbx_texture_data->Media()->IsEmbedded()) {
  197. // This is an embedded texture. Extract it.
  198. Ref<Image> image;
  199. //image.instantiate(); // oooo double instance bug? why make Image::_png_blah call
  200. const String extension = texture_name.get_extension().to_upper();
  201. if (extension == "PNG") {
  202. // The stored file is a PNG.
  203. image = Image::_png_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
  204. ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded PNG image load fail.");
  205. } else if (
  206. extension == "JPEG" ||
  207. extension == "JPG") {
  208. // The stored file is a JPEG.
  209. image = Image::_jpg_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
  210. ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded JPEG image load fail.");
  211. } else if (extension == "TGA") {
  212. // The stored file is a TGA.
  213. image = Image::_tga_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
  214. ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded TGA image load fail.");
  215. } else if (extension == "WEBP") {
  216. // The stored file is a WEBP.
  217. image = Image::_webp_mem_loader_func(fbx_texture_data->Media()->Content(), fbx_texture_data->Media()->ContentLength());
  218. ERR_CONTINUE_MSG(image.is_valid() == false, "FBX Embedded WEBP image load fail.");
  219. // } else if (extension == "DDS") {
  220. // // In this moment is not possible to extract a DDS from a buffer, TODO consider add it to godot. See `textureloader_dds.cpp::load().
  221. // // The stored file is a DDS.
  222. } else {
  223. ERR_CONTINUE_MSG(true, "The embedded image with extension: " + extension + " is not yet supported. Open an issue please.");
  224. }
  225. Ref<ImageTexture> image_texture;
  226. image_texture.instantiate();
  227. image_texture->create_from_image(image);
  228. texture = image_texture;
  229. // TODO: this is potentially making something with the same name have a match incorrectly USE FBX ID as Hash. #fuck it later.
  230. state.cached_image_searches[texture_name] = texture;
  231. print_verbose("Created texture from embedded image.");
  232. } else {
  233. ERR_CONTINUE_MSG(true, "The FBX texture, with name: `" + texture_name + "`, is not found into the project nor is stored as embedded file. Make sure to insert the texture as embedded file or into the project, then reimport.");
  234. }
  235. }
  236. spatial_material->set_texture(mapping_mode, texture);
  237. }
  238. if (spatial_material.is_valid()) {
  239. spatial_material->set_name(material_name);
  240. }
  241. /// ALL below is related to properties
  242. for (FBXDocParser::LazyPropertyMap::value_type iter : material->GetLazyProperties()) {
  243. const std::string name = iter.first;
  244. if (name.empty()) {
  245. continue;
  246. }
  247. PropertyDesc desc = PROPERTY_DESC_NOT_FOUND;
  248. if (fbx_properties_desc.count(name) > 0) {
  249. desc = fbx_properties_desc.at(name);
  250. }
  251. // check if we can ignore this it will be done at the next phase
  252. if (desc == PROPERTY_DESC_NOT_FOUND || desc == PROPERTY_DESC_IGNORE) {
  253. // count the texture mapping references. Skip this one if it's found and we can't look up a property value.
  254. if (fbx_texture_map.count(name) > 0) {
  255. continue; // safe to ignore it's a texture mapping.
  256. }
  257. }
  258. if (desc == PROPERTY_DESC_IGNORE) {
  259. //WARN_PRINT("[Ignored] The FBX material parameter: `" + String(name.c_str()) + "` is ignored.");
  260. continue;
  261. } else {
  262. print_verbose("FBX Material parameter: " + String(name.c_str()));
  263. // Check for Diffuse material system / lambert materials / legacy basically
  264. if (name == "Diffuse" && !warning_non_pbr_material) {
  265. ValidationTracker::get_singleton()->add_validation_error(state.path, "Invalid material settings change to Ai Standard Surface shader, mat name: " + material_name.c_escape());
  266. warning_non_pbr_material = true;
  267. }
  268. }
  269. // DISABLE when adding support for all weird and wonderful material formats
  270. if (desc == PROPERTY_DESC_NOT_FOUND) {
  271. continue;
  272. }
  273. ERR_CONTINUE_MSG(desc == PROPERTY_DESC_NOT_FOUND, "The FBX material parameter: `" + String(name.c_str()) + "` was not recognized. Please open an issue so we can add the support to it.");
  274. const FBXDocParser::PropertyTable *tbl = material;
  275. FBXDocParser::PropertyPtr prop = tbl->Get(name);
  276. ERR_CONTINUE_MSG(prop == nullptr, "This file may be corrupted because is not possible to extract the material parameter: " + String(name.c_str()));
  277. if (spatial_material.is_null()) {
  278. // Done here so if no data no material is created.
  279. spatial_material.instantiate();
  280. }
  281. const FBXDocParser::TypedProperty<real_t> *real_value = dynamic_cast<const FBXDocParser::TypedProperty<real_t> *>(prop);
  282. const FBXDocParser::TypedProperty<Vector3> *vector_value = dynamic_cast<const FBXDocParser::TypedProperty<Vector3> *>(prop);
  283. if (!real_value && !vector_value) {
  284. //WARN_PRINT("unsupported datatype in property: " + String(name.c_str()));
  285. continue;
  286. }
  287. if (vector_value && !real_value) {
  288. if (vector_value->Value() == Vector3(0, 0, 0) && !real_value) {
  289. continue;
  290. }
  291. }
  292. switch (desc) {
  293. case PROPERTY_DESC_ALBEDO_COLOR: {
  294. if (vector_value) {
  295. const Vector3 &color = vector_value->Value();
  296. // Make sure to not lost any eventual opacity.
  297. if (color != Vector3(0, 0, 0)) {
  298. Color c = Color();
  299. c[0] = color[0];
  300. c[1] = color[1];
  301. c[2] = color[2];
  302. spatial_material->set_albedo(c);
  303. }
  304. } else if (real_value) {
  305. print_error("albedo is unsupported format?");
  306. }
  307. } break;
  308. case PROPERTY_DESC_TRANSPARENT: {
  309. if (real_value) {
  310. const real_t opacity = real_value->Value();
  311. if (opacity < (1.0 - CMP_EPSILON)) {
  312. Color c = spatial_material->get_albedo();
  313. c.a = opacity;
  314. spatial_material->set_albedo(c);
  315. spatial_material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA);
  316. spatial_material->set_depth_draw_mode(BaseMaterial3D::DEPTH_DRAW_OPAQUE_ONLY);
  317. }
  318. } else if (vector_value) {
  319. print_error("unsupported transparent desc type vector!");
  320. }
  321. } break;
  322. case PROPERTY_DESC_SPECULAR: {
  323. if (real_value) {
  324. print_verbose("specular real value: " + rtos(real_value->Value()));
  325. spatial_material->set_specular(MIN(1.0, real_value->Value()));
  326. }
  327. if (vector_value) {
  328. print_error("unsupported specular vector value: " + vector_value->Value());
  329. }
  330. } break;
  331. case PROPERTY_DESC_SPECULAR_COLOR: {
  332. if (vector_value) {
  333. print_error("unsupported specular color: " + vector_value->Value());
  334. }
  335. } break;
  336. case PROPERTY_DESC_SHINYNESS: {
  337. if (real_value) {
  338. print_error("unsupported shinyness:" + rtos(real_value->Value()));
  339. }
  340. } break;
  341. case PROPERTY_DESC_METALLIC: {
  342. if (real_value) {
  343. print_verbose("metallic real value: " + rtos(real_value->Value()));
  344. spatial_material->set_metallic(MIN(1.0f, real_value->Value()));
  345. } else {
  346. print_error("unsupported value type for metallic");
  347. }
  348. } break;
  349. case PROPERTY_DESC_ROUGHNESS: {
  350. if (real_value) {
  351. print_verbose("roughness real value: " + rtos(real_value->Value()));
  352. spatial_material->set_roughness(MIN(1.0f, real_value->Value()));
  353. } else {
  354. print_error("unsupported value type for roughness");
  355. }
  356. } break;
  357. case PROPERTY_DESC_COAT: {
  358. if (real_value) {
  359. print_verbose("clearcoat real value: " + rtos(real_value->Value()));
  360. spatial_material->set_clearcoat(MIN(1.0f, real_value->Value()));
  361. } else {
  362. print_error("unsupported value type for clearcoat");
  363. }
  364. } break;
  365. case PROPERTY_DESC_COAT_ROUGHNESS: {
  366. // meaning is that approx equal to zero is disabled not actually zero. ;)
  367. if (real_value && Math::is_zero_approx(real_value->Value())) {
  368. print_verbose("clearcoat real value: " + rtos(real_value->Value()));
  369. spatial_material->set_clearcoat_gloss(1.0 - real_value->Value());
  370. } else {
  371. print_error("unsupported value type for clearcoat gloss");
  372. }
  373. } break;
  374. case PROPERTY_DESC_EMISSIVE: {
  375. if (real_value && Math::is_zero_approx(real_value->Value())) {
  376. print_verbose("Emissive real value: " + rtos(real_value->Value()));
  377. spatial_material->set_emission_energy(real_value->Value());
  378. } else if (vector_value && !vector_value->Value().is_equal_approx(Vector3(0, 0, 0))) {
  379. const Vector3 &color = vector_value->Value();
  380. Color c;
  381. c[0] = color[0];
  382. c[1] = color[1];
  383. c[2] = color[2];
  384. spatial_material->set_emission(c);
  385. }
  386. } break;
  387. case PROPERTY_DESC_EMISSIVE_COLOR: {
  388. if (vector_value && !vector_value->Value().is_equal_approx(Vector3(0, 0, 0))) {
  389. const Vector3 &color = vector_value->Value();
  390. Color c;
  391. c[0] = color[0];
  392. c[1] = color[1];
  393. c[2] = color[2];
  394. spatial_material->set_emission(c);
  395. } else {
  396. print_error("unsupported value type for emissive color");
  397. }
  398. } break;
  399. case PROPERTY_DESC_NOT_FOUND:
  400. case PROPERTY_DESC_IGNORE:
  401. break;
  402. default:
  403. break;
  404. }
  405. }
  406. return spatial_material;
  407. }