editor_scene_importer_assimp.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  1. /*************************************************************************/
  2. /* editor_scene_importer_assimp.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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 "editor_scene_importer_assimp.h"
  31. #include "core/io/image_loader.h"
  32. #include "editor/import/resource_importer_scene.h"
  33. #include "import_utils.h"
  34. #include "scene/3d/camera_3d.h"
  35. #include "scene/3d/light_3d.h"
  36. #include "scene/3d/mesh_instance_3d.h"
  37. #include "scene/main/node.h"
  38. #include "scene/resources/material.h"
  39. #include "scene/resources/surface_tool.h"
  40. #include <assimp/matrix4x4.h>
  41. #include <assimp/postprocess.h>
  42. #include <assimp/scene.h>
  43. #include <assimp/Importer.hpp>
  44. #include <assimp/LogStream.hpp>
  45. #include <string>
  46. // move into assimp
  47. aiBone *get_bone_by_name(const aiScene *scene, aiString bone_name) {
  48. for (unsigned int mesh_id = 0; mesh_id < scene->mNumMeshes; ++mesh_id) {
  49. aiMesh *mesh = scene->mMeshes[mesh_id];
  50. // iterate over all the bones on the mesh for this node only!
  51. for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) {
  52. aiBone *bone = mesh->mBones[boneIndex];
  53. if (bone->mName == bone_name) {
  54. printf("matched bone by name: %s\n", bone->mName.C_Str());
  55. return bone;
  56. }
  57. }
  58. }
  59. return nullptr;
  60. }
  61. void EditorSceneImporterAssimp::get_extensions(List<String> *r_extensions) const {
  62. const String import_setting_string = "filesystem/import/open_asset_import/";
  63. Map<String, ImportFormat> import_format;
  64. {
  65. Vector<String> exts;
  66. exts.push_back("fbx");
  67. ImportFormat import = { exts, true };
  68. import_format.insert("fbx", import);
  69. }
  70. for (Map<String, ImportFormat>::Element *E = import_format.front(); E; E = E->next()) {
  71. _register_project_setting_import(E->key(), import_setting_string, E->get().extensions, r_extensions,
  72. E->get().is_default);
  73. }
  74. }
  75. void EditorSceneImporterAssimp::_register_project_setting_import(const String generic, const String import_setting_string,
  76. const Vector<String> &exts, List<String> *r_extensions,
  77. const bool p_enabled) const {
  78. const String use_generic = "use_" + generic;
  79. _GLOBAL_DEF(import_setting_string + use_generic, p_enabled, true);
  80. if (ProjectSettings::get_singleton()->get(import_setting_string + use_generic)) {
  81. for (int32_t i = 0; i < exts.size(); i++) {
  82. r_extensions->push_back(exts[i]);
  83. }
  84. }
  85. }
  86. uint32_t EditorSceneImporterAssimp::get_import_flags() const {
  87. return IMPORT_SCENE;
  88. }
  89. void EditorSceneImporterAssimp::_bind_methods() {
  90. }
  91. Node *EditorSceneImporterAssimp::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps,
  92. List<String> *r_missing_deps, Error *r_err) {
  93. Assimp::Importer importer;
  94. std::wstring w_path = ProjectSettings::get_singleton()->globalize_path(p_path).c_str();
  95. std::string s_path(w_path.begin(), w_path.end());
  96. importer.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true);
  97. // Cannot remove pivot points because the static mesh will be in the wrong place
  98. importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false);
  99. int32_t max_bone_weights = 4;
  100. //if (p_flags & IMPORT_ANIMATION_EIGHT_WEIGHTS) {
  101. // const int eight_bones = 8;
  102. // importer.SetPropertyBool(AI_CONFIG_PP_LBW_MAX_WEIGHTS, eight_bones);
  103. // max_bone_weights = eight_bones;
  104. //}
  105. importer.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT);
  106. //importer.SetPropertyFloat(AI_CONFIG_PP_DB_THRESHOLD, 1.0f);
  107. int32_t post_process_Steps = aiProcess_CalcTangentSpace |
  108. aiProcess_GlobalScale |
  109. // imports models and listens to their file scale for CM to M conversions
  110. //aiProcess_FlipUVs |
  111. aiProcess_FlipWindingOrder |
  112. // very important for culling so that it is done in the correct order.
  113. //aiProcess_DropNormals |
  114. //aiProcess_GenSmoothNormals |
  115. //aiProcess_JoinIdenticalVertices |
  116. aiProcess_ImproveCacheLocality |
  117. //aiProcess_RemoveRedundantMaterials | // Causes a crash
  118. //aiProcess_SplitLargeMeshes |
  119. aiProcess_Triangulate |
  120. aiProcess_GenUVCoords |
  121. //aiProcess_FindDegenerates |
  122. //aiProcess_SortByPType |
  123. // aiProcess_FindInvalidData |
  124. aiProcess_TransformUVCoords |
  125. aiProcess_FindInstances |
  126. //aiProcess_FixInfacingNormals |
  127. //aiProcess_ValidateDataStructure |
  128. aiProcess_OptimizeMeshes |
  129. aiProcess_PopulateArmatureData |
  130. //aiProcess_OptimizeGraph |
  131. //aiProcess_Debone |
  132. // aiProcess_EmbedTextures |
  133. //aiProcess_SplitByBoneCount |
  134. 0;
  135. aiScene *scene = (aiScene *)importer.ReadFile(s_path.c_str(), post_process_Steps);
  136. ERR_FAIL_COND_V_MSG(scene == nullptr, nullptr, String("Open Asset Import failed to open: ") + String(importer.GetErrorString()));
  137. return _generate_scene(p_path, scene, p_flags, p_bake_fps, max_bone_weights);
  138. }
  139. template <class T>
  140. struct EditorSceneImporterAssetImportInterpolate {
  141. T lerp(const T &a, const T &b, float c) const {
  142. return a + (b - a) * c;
  143. }
  144. T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
  145. float t2 = t * t;
  146. float t3 = t2 * t;
  147. return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4.0f * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
  148. }
  149. T bezier(T start, T control_1, T control_2, T end, float t) {
  150. /* Formula from Wikipedia article on Bezier curves. */
  151. real_t omt = (1.0 - t);
  152. real_t omt2 = omt * omt;
  153. real_t omt3 = omt2 * omt;
  154. real_t t2 = t * t;
  155. real_t t3 = t2 * t;
  156. return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
  157. }
  158. };
  159. //thank you for existing, partial specialization
  160. template <>
  161. struct EditorSceneImporterAssetImportInterpolate<Quat> {
  162. Quat lerp(const Quat &a, const Quat &b, float c) const {
  163. ERR_FAIL_COND_V_MSG(!a.is_normalized(), Quat(), "The quaternion \"a\" must be normalized.");
  164. ERR_FAIL_COND_V_MSG(!b.is_normalized(), Quat(), "The quaternion \"b\" must be normalized.");
  165. return a.slerp(b, c).normalized();
  166. }
  167. Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, float c) {
  168. ERR_FAIL_COND_V_MSG(!p1.is_normalized(), Quat(), "The quaternion \"p1\" must be normalized.");
  169. ERR_FAIL_COND_V_MSG(!p2.is_normalized(), Quat(), "The quaternion \"p2\" must be normalized.");
  170. return p1.slerp(p2, c).normalized();
  171. }
  172. Quat bezier(Quat start, Quat control_1, Quat control_2, Quat end, float t) {
  173. ERR_FAIL_COND_V_MSG(!start.is_normalized(), Quat(), "The start quaternion must be normalized.");
  174. ERR_FAIL_COND_V_MSG(!end.is_normalized(), Quat(), "The end quaternion must be normalized.");
  175. return start.slerp(end, t).normalized();
  176. }
  177. };
  178. template <class T>
  179. T EditorSceneImporterAssimp::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, float p_time,
  180. AssetImportAnimation::Interpolation p_interp) {
  181. //could use binary search, worth it?
  182. int idx = -1;
  183. for (int i = 0; i < p_times.size(); i++) {
  184. if (p_times[i] > p_time) {
  185. break;
  186. }
  187. idx++;
  188. }
  189. EditorSceneImporterAssetImportInterpolate<T> interp;
  190. switch (p_interp) {
  191. case AssetImportAnimation::INTERP_LINEAR: {
  192. if (idx == -1) {
  193. return p_values[0];
  194. } else if (idx >= p_times.size() - 1) {
  195. return p_values[p_times.size() - 1];
  196. }
  197. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  198. return interp.lerp(p_values[idx], p_values[idx + 1], c);
  199. } break;
  200. case AssetImportAnimation::INTERP_STEP: {
  201. if (idx == -1) {
  202. return p_values[0];
  203. } else if (idx >= p_times.size() - 1) {
  204. return p_values[p_times.size() - 1];
  205. }
  206. return p_values[idx];
  207. } break;
  208. case AssetImportAnimation::INTERP_CATMULLROMSPLINE: {
  209. if (idx == -1) {
  210. return p_values[1];
  211. } else if (idx >= p_times.size() - 1) {
  212. return p_values[1 + p_times.size() - 1];
  213. }
  214. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  215. return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
  216. } break;
  217. case AssetImportAnimation::INTERP_CUBIC_SPLINE: {
  218. if (idx == -1) {
  219. return p_values[1];
  220. } else if (idx >= p_times.size() - 1) {
  221. return p_values[(p_times.size() - 1) * 3 + 1];
  222. }
  223. float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  224. T from = p_values[idx * 3 + 1];
  225. T c1 = from + p_values[idx * 3 + 2];
  226. T to = p_values[idx * 3 + 4];
  227. T c2 = to + p_values[idx * 3 + 3];
  228. return interp.bezier(from, c1, c2, to, c);
  229. } break;
  230. }
  231. ERR_FAIL_V(p_values[0]);
  232. }
  233. aiBone *EditorSceneImporterAssimp::get_bone_from_stack(ImportState &state, aiString name) {
  234. List<aiBone *>::Element *iter;
  235. aiBone *bone = nullptr;
  236. for (iter = state.bone_stack.front(); iter; iter = iter->next()) {
  237. bone = (aiBone *)iter->get();
  238. if (bone && bone->mName == name) {
  239. state.bone_stack.erase(bone);
  240. return bone;
  241. }
  242. }
  243. return nullptr;
  244. }
  245. Node3D *
  246. EditorSceneImporterAssimp::_generate_scene(const String &p_path, aiScene *scene, const uint32_t p_flags, int p_bake_fps,
  247. const int32_t p_max_bone_weights) {
  248. ERR_FAIL_COND_V(scene == nullptr, nullptr);
  249. ImportState state;
  250. state.path = p_path;
  251. state.assimp_scene = scene;
  252. state.max_bone_weights = p_max_bone_weights;
  253. state.animation_player = nullptr;
  254. state.import_flags = p_flags;
  255. // populate light map
  256. for (unsigned int l = 0; l < scene->mNumLights; l++) {
  257. aiLight *ai_light = scene->mLights[l];
  258. ERR_CONTINUE(ai_light == nullptr);
  259. state.light_cache[AssimpUtils::get_assimp_string(ai_light->mName)] = l;
  260. }
  261. // fill camera cache
  262. for (unsigned int c = 0; c < scene->mNumCameras; c++) {
  263. aiCamera *ai_camera = scene->mCameras[c];
  264. ERR_CONTINUE(ai_camera == nullptr);
  265. state.camera_cache[AssimpUtils::get_assimp_string(ai_camera->mName)] = c;
  266. }
  267. if (scene->mRootNode) {
  268. state.nodes.push_back(scene->mRootNode);
  269. // make flat node tree - in order to make processing deterministic
  270. for (unsigned int i = 0; i < scene->mRootNode->mNumChildren; i++) {
  271. _generate_node(state, scene->mRootNode->mChildren[i]);
  272. }
  273. RegenerateBoneStack(state);
  274. Node *last_valid_parent = nullptr;
  275. List<const aiNode *>::Element *iter;
  276. for (iter = state.nodes.front(); iter; iter = iter->next()) {
  277. const aiNode *element_assimp_node = iter->get();
  278. const aiNode *parent_assimp_node = element_assimp_node->mParent;
  279. String node_name = AssimpUtils::get_assimp_string(element_assimp_node->mName);
  280. //print_verbose("node: " + node_name);
  281. Node3D *spatial = nullptr;
  282. Transform transform = AssimpUtils::assimp_matrix_transform(element_assimp_node->mTransformation);
  283. // retrieve this node bone
  284. aiBone *bone = get_bone_from_stack(state, element_assimp_node->mName);
  285. if (state.light_cache.has(node_name)) {
  286. spatial = create_light(state, node_name, transform);
  287. } else if (state.camera_cache.has(node_name)) {
  288. spatial = create_camera(state, node_name, transform);
  289. } else if (state.armature_nodes.find(element_assimp_node)) {
  290. // create skeleton
  291. print_verbose("Making skeleton: " + node_name);
  292. Skeleton3D *skeleton = memnew(Skeleton3D);
  293. spatial = skeleton;
  294. if (!state.armature_skeletons.has(element_assimp_node)) {
  295. state.armature_skeletons.insert(element_assimp_node, skeleton);
  296. }
  297. } else if (bone != nullptr) {
  298. continue;
  299. } else {
  300. spatial = memnew(Node3D);
  301. }
  302. ERR_CONTINUE_MSG(spatial == nullptr, "FBX Import - are we out of ram?");
  303. // we on purpose set the transform and name after creating the node.
  304. spatial->set_name(node_name);
  305. spatial->set_global_transform(transform);
  306. // first element is root
  307. if (iter == state.nodes.front()) {
  308. state.root = spatial;
  309. }
  310. // flat node map parent lookup tool
  311. state.flat_node_map.insert(element_assimp_node, spatial);
  312. Map<const aiNode *, Node3D *>::Element *parent_lookup = state.flat_node_map.find(parent_assimp_node);
  313. // note: this always fails on the root node :) keep that in mind this is by design
  314. if (parent_lookup) {
  315. Node3D *parent_node = parent_lookup->value();
  316. ERR_FAIL_COND_V_MSG(parent_node == nullptr, state.root,
  317. "Parent node invalid even though lookup successful, out of ram?");
  318. if (spatial != state.root) {
  319. parent_node->add_child(spatial);
  320. spatial->set_owner(state.root);
  321. } else {
  322. // required - think about it root never has a parent yet is valid, anything else without a parent is not valid.
  323. }
  324. } else if (spatial != state.root) {
  325. // if the ainode is not in the tree
  326. // parent it to the last good parent found
  327. if (last_valid_parent) {
  328. last_valid_parent->add_child(spatial);
  329. spatial->set_owner(state.root);
  330. } else {
  331. // this is a serious error?
  332. memdelete(spatial);
  333. }
  334. }
  335. // update last valid parent
  336. last_valid_parent = spatial;
  337. }
  338. print_verbose("node counts: " + itos(state.nodes.size()));
  339. // make clean bone stack
  340. RegenerateBoneStack(state);
  341. print_verbose("generating godot bone data");
  342. print_verbose("Godot bone stack count: " + itos(state.bone_stack.size()));
  343. // This is a list of bones, duplicates are from other meshes and must be dealt with properly
  344. for (List<aiBone *>::Element *element = state.bone_stack.front(); element; element = element->next()) {
  345. aiBone *bone = element->get();
  346. ERR_CONTINUE_MSG(!bone, "invalid bone read from assimp?");
  347. // Utilities for armature lookup - for now only FBX makes these
  348. aiNode *armature_for_bone = bone->mArmature;
  349. // Utilities for bone node lookup - for now only FBX makes these
  350. aiNode *bone_node = bone->mNode;
  351. aiNode *parent_node = bone_node->mParent;
  352. String bone_name = AssimpUtils::get_anim_string_from_assimp(bone->mName);
  353. ERR_CONTINUE_MSG(armature_for_bone == nullptr, "Armature for bone invalid: " + bone_name);
  354. Skeleton3D *skeleton = state.armature_skeletons[armature_for_bone];
  355. state.skeleton_bone_map[bone] = skeleton;
  356. if (bone_name.empty()) {
  357. bone_name = "untitled_bone_name";
  358. WARN_PRINT("Untitled bone name detected... report with file please");
  359. }
  360. // todo: this is where skin support goes
  361. if (skeleton && skeleton->find_bone(bone_name) == -1) {
  362. print_verbose("[Godot Glue] Imported bone" + bone_name);
  363. int boneIdx = skeleton->get_bone_count();
  364. Transform pform = AssimpUtils::assimp_matrix_transform(bone->mNode->mTransformation);
  365. skeleton->add_bone(bone_name);
  366. skeleton->set_bone_rest(boneIdx, pform);
  367. skeleton->set_bone_pose(boneIdx, pform);
  368. if (parent_node != nullptr) {
  369. int parent_bone_id = skeleton->find_bone(AssimpUtils::get_anim_string_from_assimp(parent_node->mName));
  370. int current_bone_id = boneIdx;
  371. skeleton->set_bone_parent(current_bone_id, parent_bone_id);
  372. }
  373. }
  374. }
  375. print_verbose("generating mesh phase from skeletal mesh");
  376. List<Node3D *> cleanup_template_nodes;
  377. for (Map<const aiNode *, Node3D *>::Element *key_value_pair = state.flat_node_map.front(); key_value_pair; key_value_pair = key_value_pair->next()) {
  378. const aiNode *assimp_node = key_value_pair->key();
  379. Node3D *mesh_template = key_value_pair->value();
  380. ERR_CONTINUE(assimp_node == nullptr);
  381. ERR_CONTINUE(mesh_template == nullptr);
  382. Node *parent_node = mesh_template->get_parent();
  383. if (mesh_template == state.root) {
  384. continue;
  385. }
  386. if (parent_node == nullptr) {
  387. print_error("Found invalid parent node!");
  388. continue; // root node
  389. }
  390. String node_name = AssimpUtils::get_assimp_string(assimp_node->mName);
  391. Transform node_transform = AssimpUtils::assimp_matrix_transform(assimp_node->mTransformation);
  392. if (assimp_node->mNumMeshes > 0) {
  393. MeshInstance3D *mesh = create_mesh(state, assimp_node, node_name, parent_node, node_transform);
  394. if (mesh) {
  395. parent_node->remove_child(mesh_template);
  396. // re-parent children
  397. List<Node *> children;
  398. // re-parent all children to new node
  399. // note: since get_child_count will change during execution we must build a list first to be safe.
  400. for (int childId = 0; childId < mesh_template->get_child_count(); childId++) {
  401. // get child
  402. Node *child = mesh_template->get_child(childId);
  403. children.push_back(child);
  404. }
  405. for (List<Node *>::Element *element = children.front(); element; element = element->next()) {
  406. // reparent the children to the real mesh node.
  407. mesh_template->remove_child(element->get());
  408. mesh->add_child(element->get());
  409. element->get()->set_owner(state.root);
  410. }
  411. // update mesh in list so that each mesh node is available
  412. // this makes the template unavailable which is the desired behaviour
  413. state.flat_node_map[assimp_node] = mesh;
  414. cleanup_template_nodes.push_back(mesh_template);
  415. // clean up this list we don't need it
  416. children.clear();
  417. }
  418. }
  419. }
  420. for (List<Node3D *>::Element *element = cleanup_template_nodes.front(); element; element = element->next()) {
  421. if (element->get()) {
  422. memdelete(element->get());
  423. }
  424. }
  425. }
  426. if (p_flags & IMPORT_ANIMATION && scene->mNumAnimations) {
  427. state.animation_player = memnew(AnimationPlayer);
  428. state.root->add_child(state.animation_player);
  429. state.animation_player->set_owner(state.root);
  430. for (uint32_t i = 0; i < scene->mNumAnimations; i++) {
  431. _import_animation(state, i, p_bake_fps);
  432. }
  433. }
  434. //
  435. // Cleanup operations
  436. //
  437. state.mesh_cache.clear();
  438. state.material_cache.clear();
  439. state.light_cache.clear();
  440. state.camera_cache.clear();
  441. state.assimp_node_map.clear();
  442. state.path_to_image_cache.clear();
  443. state.nodes.clear();
  444. state.flat_node_map.clear();
  445. state.armature_skeletons.clear();
  446. state.bone_stack.clear();
  447. return state.root;
  448. }
  449. void EditorSceneImporterAssimp::_insert_animation_track(ImportState &scene, const aiAnimation *assimp_anim, int track_id,
  450. int anim_fps, Ref<Animation> animation, float ticks_per_second,
  451. Skeleton3D *skeleton, const NodePath &node_path,
  452. const String &node_name, aiBone *track_bone) {
  453. const aiNodeAnim *assimp_track = assimp_anim->mChannels[track_id];
  454. //make transform track
  455. int track_idx = animation->get_track_count();
  456. animation->add_track(Animation::TYPE_TRANSFORM);
  457. animation->track_set_path(track_idx, node_path);
  458. //first determine animation length
  459. float increment = 1.0 / float(anim_fps);
  460. float time = 0.0;
  461. bool last = false;
  462. Vector<Vector3> pos_values;
  463. Vector<float> pos_times;
  464. Vector<Vector3> scale_values;
  465. Vector<float> scale_times;
  466. Vector<Quat> rot_values;
  467. Vector<float> rot_times;
  468. for (size_t p = 0; p < assimp_track->mNumPositionKeys; p++) {
  469. aiVector3D pos = assimp_track->mPositionKeys[p].mValue;
  470. pos_values.push_back(Vector3(pos.x, pos.y, pos.z));
  471. pos_times.push_back(assimp_track->mPositionKeys[p].mTime / ticks_per_second);
  472. }
  473. for (size_t r = 0; r < assimp_track->mNumRotationKeys; r++) {
  474. aiQuaternion quat = assimp_track->mRotationKeys[r].mValue;
  475. rot_values.push_back(Quat(quat.x, quat.y, quat.z, quat.w).normalized());
  476. rot_times.push_back(assimp_track->mRotationKeys[r].mTime / ticks_per_second);
  477. }
  478. for (size_t sc = 0; sc < assimp_track->mNumScalingKeys; sc++) {
  479. aiVector3D scale = assimp_track->mScalingKeys[sc].mValue;
  480. scale_values.push_back(Vector3(scale.x, scale.y, scale.z));
  481. scale_times.push_back(assimp_track->mScalingKeys[sc].mTime / ticks_per_second);
  482. }
  483. while (true) {
  484. Vector3 pos;
  485. Quat rot;
  486. Vector3 scale(1, 1, 1);
  487. if (pos_values.size()) {
  488. pos = _interpolate_track<Vector3>(pos_times, pos_values, time, AssetImportAnimation::INTERP_LINEAR);
  489. }
  490. if (rot_values.size()) {
  491. rot = _interpolate_track<Quat>(rot_times, rot_values, time,
  492. AssetImportAnimation::INTERP_LINEAR)
  493. .normalized();
  494. }
  495. if (scale_values.size()) {
  496. scale = _interpolate_track<Vector3>(scale_times, scale_values, time, AssetImportAnimation::INTERP_LINEAR);
  497. }
  498. if (skeleton) {
  499. int skeleton_bone = skeleton->find_bone(node_name);
  500. if (skeleton_bone >= 0 && track_bone) {
  501. Transform xform;
  502. xform.basis.set_quat_scale(rot, scale);
  503. xform.origin = pos;
  504. xform = skeleton->get_bone_pose(skeleton_bone).inverse() * xform;
  505. rot = xform.basis.get_rotation_quat();
  506. rot.normalize();
  507. scale = xform.basis.get_scale();
  508. pos = xform.origin;
  509. } else {
  510. ERR_FAIL_MSG("Skeleton bone lookup failed for skeleton: " + skeleton->get_name());
  511. }
  512. }
  513. animation->track_set_interpolation_type(track_idx, Animation::INTERPOLATION_LINEAR);
  514. animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
  515. if (last) { //done this way so a key is always inserted past the end (for proper interpolation)
  516. break;
  517. }
  518. time += increment;
  519. if (time >= animation->get_length()) {
  520. last = true;
  521. }
  522. }
  523. }
  524. // I really do not like this but need to figure out a better way of removing it later.
  525. Node *EditorSceneImporterAssimp::get_node_by_name(ImportState &state, String name) {
  526. for (Map<const aiNode *, Node3D *>::Element *key_value_pair = state.flat_node_map.front(); key_value_pair; key_value_pair = key_value_pair->next()) {
  527. const aiNode *assimp_node = key_value_pair->key();
  528. Node3D *node = key_value_pair->value();
  529. String node_name = AssimpUtils::get_assimp_string(assimp_node->mName);
  530. if (name == node_name && node) {
  531. return node;
  532. }
  533. }
  534. return nullptr;
  535. }
  536. /* Bone stack is a fifo handler for multiple armatures since armatures aren't a thing in assimp (yet) */
  537. void EditorSceneImporterAssimp::RegenerateBoneStack(ImportState &state) {
  538. state.bone_stack.clear();
  539. // build bone stack list
  540. for (unsigned int mesh_id = 0; mesh_id < state.assimp_scene->mNumMeshes; ++mesh_id) {
  541. aiMesh *mesh = state.assimp_scene->mMeshes[mesh_id];
  542. // iterate over all the bones on the mesh for this node only!
  543. for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) {
  544. aiBone *bone = mesh->mBones[boneIndex];
  545. // doubtful this is required right now but best to check
  546. if (!state.bone_stack.find(bone)) {
  547. //print_verbose("[assimp] bone stack added: " + String(bone->mName.C_Str()) );
  548. state.bone_stack.push_back(bone);
  549. }
  550. }
  551. }
  552. }
  553. /* Bone stack is a fifo handler for multiple armatures since armatures aren't a thing in assimp (yet) */
  554. void EditorSceneImporterAssimp::RegenerateBoneStack(ImportState &state, aiMesh *mesh) {
  555. state.bone_stack.clear();
  556. // iterate over all the bones on the mesh for this node only!
  557. for (unsigned int boneIndex = 0; boneIndex < mesh->mNumBones; boneIndex++) {
  558. aiBone *bone = mesh->mBones[boneIndex];
  559. if (state.bone_stack.find(bone) == nullptr) {
  560. state.bone_stack.push_back(bone);
  561. }
  562. }
  563. }
  564. // animation tracks are per bone
  565. void EditorSceneImporterAssimp::_import_animation(ImportState &state, int p_animation_index, int p_bake_fps) {
  566. ERR_FAIL_INDEX(p_animation_index, (int)state.assimp_scene->mNumAnimations);
  567. const aiAnimation *anim = state.assimp_scene->mAnimations[p_animation_index];
  568. String name = AssimpUtils::get_anim_string_from_assimp(anim->mName);
  569. if (name == String()) {
  570. name = "Animation " + itos(p_animation_index + 1);
  571. }
  572. print_verbose("import animation: " + name);
  573. float ticks_per_second = anim->mTicksPerSecond;
  574. if (state.assimp_scene->mMetaData != nullptr && Math::is_equal_approx(ticks_per_second, 0.0f)) {
  575. int32_t time_mode = 0;
  576. state.assimp_scene->mMetaData->Get("TimeMode", time_mode);
  577. ticks_per_second = AssimpUtils::get_fbx_fps(time_mode, state.assimp_scene);
  578. }
  579. //?
  580. //if ((p_path.get_file().get_extension().to_lower() == "glb" || p_path.get_file().get_extension().to_lower() == "gltf") && Math::is_equal_approx(ticks_per_second, 0.0f)) {
  581. // ticks_per_second = 1000.0f;
  582. //}
  583. if (Math::is_equal_approx(ticks_per_second, 0.0f)) {
  584. ticks_per_second = 25.0f;
  585. }
  586. Ref<Animation> animation;
  587. animation.instance();
  588. animation->set_name(name);
  589. animation->set_length(anim->mDuration / ticks_per_second);
  590. if (name.begins_with("loop") || name.ends_with("loop") || name.begins_with("cycle") || name.ends_with("cycle")) {
  591. animation->set_loop(true);
  592. }
  593. // generate bone stack for animation import
  594. RegenerateBoneStack(state);
  595. //regular tracks
  596. for (size_t i = 0; i < anim->mNumChannels; i++) {
  597. const aiNodeAnim *track = anim->mChannels[i];
  598. String node_name = AssimpUtils::get_assimp_string(track->mNodeName);
  599. print_verbose("track name import: " + node_name);
  600. if (track->mNumRotationKeys == 0 && track->mNumPositionKeys == 0 && track->mNumScalingKeys == 0) {
  601. continue; //do not bother
  602. }
  603. Skeleton3D *skeleton = nullptr;
  604. NodePath node_path;
  605. aiBone *bone = nullptr;
  606. // Import skeleton bone animation for this track
  607. // Any bone will do, no point in processing more than just what is in the skeleton
  608. {
  609. bone = get_bone_from_stack(state, track->mNodeName);
  610. if (bone) {
  611. // get skeleton by bone
  612. skeleton = state.armature_skeletons[bone->mArmature];
  613. if (skeleton) {
  614. String path = state.root->get_path_to(skeleton);
  615. path += ":" + node_name;
  616. node_path = path;
  617. if (node_path != NodePath()) {
  618. _insert_animation_track(state, anim, i, p_bake_fps, animation, ticks_per_second, skeleton,
  619. node_path, node_name, bone);
  620. } else {
  621. print_error("Failed to find valid node path for animation");
  622. }
  623. }
  624. }
  625. }
  626. // not a bone
  627. // note this is flaky it uses node names which is unreliable
  628. Node *allocated_node = get_node_by_name(state, node_name);
  629. // todo: implement skeleton grabbing for node based animations too :)
  630. // check if node exists, if it does then also apply animation track for node and bones above are all handled.
  631. // this is now inclusive animation handling so that
  632. // we import all the data and do not miss anything.
  633. if (allocated_node) {
  634. node_path = state.root->get_path_to(allocated_node);
  635. if (node_path != NodePath()) {
  636. _insert_animation_track(state, anim, i, p_bake_fps, animation, ticks_per_second, skeleton,
  637. node_path, node_name, nullptr);
  638. }
  639. }
  640. }
  641. //blend shape tracks
  642. for (size_t i = 0; i < anim->mNumMorphMeshChannels; i++) {
  643. const aiMeshMorphAnim *anim_mesh = anim->mMorphMeshChannels[i];
  644. const String prop_name = AssimpUtils::get_assimp_string(anim_mesh->mName);
  645. const String mesh_name = prop_name.split("*")[0];
  646. ERR_CONTINUE(prop_name.split("*").size() != 2);
  647. Node *item = get_node_by_name(state, mesh_name);
  648. ERR_CONTINUE_MSG(!item, "failed to look up node by name");
  649. const MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(item);
  650. ERR_CONTINUE(mesh_instance == nullptr);
  651. String base_path = state.root->get_path_to(mesh_instance);
  652. Ref<Mesh> mesh = mesh_instance->get_mesh();
  653. ERR_CONTINUE(mesh.is_null());
  654. //add the tracks for this mesh
  655. int base_track = animation->get_track_count();
  656. for (int j = 0; j < mesh->get_blend_shape_count(); j++) {
  657. animation->add_track(Animation::TYPE_VALUE);
  658. animation->track_set_path(base_track + j, base_path + ":blend_shapes/" + mesh->get_blend_shape_name(j));
  659. }
  660. for (size_t k = 0; k < anim_mesh->mNumKeys; k++) {
  661. for (size_t j = 0; j < anim_mesh->mKeys[k].mNumValuesAndWeights; j++) {
  662. float t = anim_mesh->mKeys[k].mTime / ticks_per_second;
  663. float w = anim_mesh->mKeys[k].mWeights[j];
  664. animation->track_insert_key(base_track + j, t, w);
  665. }
  666. }
  667. }
  668. if (animation->get_track_count()) {
  669. state.animation_player->add_animation(name, animation);
  670. }
  671. }
  672. //
  673. // Mesh Generation from indices ? why do we need so much mesh code
  674. // [debt needs looked into]
  675. Ref<Mesh>
  676. EditorSceneImporterAssimp::_generate_mesh_from_surface_indices(ImportState &state, const Vector<int> &p_surface_indices,
  677. const aiNode *assimp_node, Ref<Skin> &skin,
  678. Skeleton3D *&skeleton_assigned) {
  679. Ref<ArrayMesh> mesh;
  680. mesh.instance();
  681. bool has_uvs = false;
  682. bool compress_vert_data = state.import_flags & IMPORT_USE_COMPRESSION;
  683. uint32_t mesh_flags = compress_vert_data ? Mesh::ARRAY_COMPRESS_DEFAULT : 0;
  684. Map<String, uint32_t> morph_mesh_string_lookup;
  685. for (int i = 0; i < p_surface_indices.size(); i++) {
  686. const unsigned int mesh_idx = p_surface_indices[0];
  687. const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_idx];
  688. for (size_t j = 0; j < ai_mesh->mNumAnimMeshes; j++) {
  689. String ai_anim_mesh_name = AssimpUtils::get_assimp_string(ai_mesh->mAnimMeshes[j]->mName);
  690. if (!morph_mesh_string_lookup.has(ai_anim_mesh_name)) {
  691. morph_mesh_string_lookup.insert(ai_anim_mesh_name, j);
  692. mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  693. if (ai_anim_mesh_name.empty()) {
  694. ai_anim_mesh_name = String("morph_") + itos(j);
  695. }
  696. mesh->add_blend_shape(ai_anim_mesh_name);
  697. }
  698. }
  699. }
  700. //
  701. // Process Vertex Weights
  702. //
  703. for (int i = 0; i < p_surface_indices.size(); i++) {
  704. const unsigned int mesh_idx = p_surface_indices[i];
  705. const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_idx];
  706. Map<uint32_t, Vector<BoneInfo>> vertex_weights;
  707. if (ai_mesh->mNumBones > 0) {
  708. for (size_t b = 0; b < ai_mesh->mNumBones; b++) {
  709. aiBone *bone = ai_mesh->mBones[b];
  710. if (!skeleton_assigned) {
  711. print_verbose("Assigned mesh skeleton during mesh creation");
  712. skeleton_assigned = state.skeleton_bone_map[bone];
  713. if (!skin.is_valid()) {
  714. print_verbose("Configured new skin");
  715. skin.instance();
  716. } else {
  717. print_verbose("Reusing existing skin!");
  718. }
  719. }
  720. // skeleton_assigned =
  721. String bone_name = AssimpUtils::get_assimp_string(bone->mName);
  722. int bone_index = skeleton_assigned->find_bone(bone_name);
  723. ERR_CONTINUE(bone_index == -1);
  724. for (size_t w = 0; w < bone->mNumWeights; w++) {
  725. aiVertexWeight ai_weights = bone->mWeights[w];
  726. BoneInfo bi;
  727. uint32_t vertex_index = ai_weights.mVertexId;
  728. bi.bone = bone_index;
  729. bi.weight = ai_weights.mWeight;
  730. if (!vertex_weights.has(vertex_index)) {
  731. vertex_weights[vertex_index] = Vector<BoneInfo>();
  732. }
  733. vertex_weights[vertex_index].push_back(bi);
  734. }
  735. }
  736. }
  737. //
  738. // Create mesh from data from assimp
  739. //
  740. Ref<SurfaceTool> st;
  741. st.instance();
  742. st->begin(Mesh::PRIMITIVE_TRIANGLES);
  743. for (size_t j = 0; j < ai_mesh->mNumVertices; j++) {
  744. // Get the texture coordinates if they exist
  745. if (ai_mesh->HasTextureCoords(0)) {
  746. has_uvs = true;
  747. st->add_uv(Vector2(ai_mesh->mTextureCoords[0][j].x, 1.0f - ai_mesh->mTextureCoords[0][j].y));
  748. }
  749. if (ai_mesh->HasTextureCoords(1)) {
  750. has_uvs = true;
  751. st->add_uv2(Vector2(ai_mesh->mTextureCoords[1][j].x, 1.0f - ai_mesh->mTextureCoords[1][j].y));
  752. }
  753. // Assign vertex colors
  754. if (ai_mesh->HasVertexColors(0)) {
  755. Color color = Color(ai_mesh->mColors[0]->r, ai_mesh->mColors[0]->g, ai_mesh->mColors[0]->b,
  756. ai_mesh->mColors[0]->a);
  757. st->add_color(color);
  758. }
  759. // Work out normal calculations? - this needs work it doesn't work properly on huestos
  760. if (ai_mesh->mNormals != nullptr) {
  761. const aiVector3D normals = ai_mesh->mNormals[j];
  762. const Vector3 godot_normal = Vector3(normals.x, normals.y, normals.z);
  763. st->add_normal(godot_normal);
  764. if (ai_mesh->HasTangentsAndBitangents()) {
  765. const aiVector3D tangents = ai_mesh->mTangents[j];
  766. const Vector3 godot_tangent = Vector3(tangents.x, tangents.y, tangents.z);
  767. const aiVector3D bitangent = ai_mesh->mBitangents[j];
  768. const Vector3 godot_bitangent = Vector3(bitangent.x, bitangent.y, bitangent.z);
  769. float d = godot_normal.cross(godot_tangent).dot(godot_bitangent) > 0.0f ? 1.0f : -1.0f;
  770. st->add_tangent(Plane(tangents.x, tangents.y, tangents.z, d));
  771. }
  772. }
  773. // We have vertex weights right?
  774. if (vertex_weights.has(j)) {
  775. Vector<BoneInfo> bone_info = vertex_weights[j];
  776. Vector<int> bones;
  777. bones.resize(bone_info.size());
  778. Vector<float> weights;
  779. weights.resize(bone_info.size());
  780. // todo? do we really need to loop over all bones? - assimp may have helper to find all influences on this vertex.
  781. for (int k = 0; k < bone_info.size(); k++) {
  782. bones.write[k] = bone_info[k].bone;
  783. weights.write[k] = bone_info[k].weight;
  784. }
  785. st->add_bones(bones);
  786. st->add_weights(weights);
  787. }
  788. // Assign vertex
  789. const aiVector3D pos = ai_mesh->mVertices[j];
  790. // note we must include node offset transform as this is relative to world space not local space.
  791. Vector3 godot_pos = Vector3(pos.x, pos.y, pos.z);
  792. st->add_vertex(godot_pos);
  793. }
  794. // fire replacement for face handling
  795. for (size_t j = 0; j < ai_mesh->mNumFaces; j++) {
  796. const aiFace face = ai_mesh->mFaces[j];
  797. for (unsigned int k = 0; k < face.mNumIndices; k++) {
  798. st->add_index(face.mIndices[k]);
  799. }
  800. }
  801. if (ai_mesh->HasTangentsAndBitangents() == false && has_uvs) {
  802. st->generate_tangents();
  803. }
  804. aiMaterial *ai_material = state.assimp_scene->mMaterials[ai_mesh->mMaterialIndex];
  805. Ref<StandardMaterial3D> mat;
  806. mat.instance();
  807. int32_t mat_two_sided = 0;
  808. if (AI_SUCCESS == ai_material->Get(AI_MATKEY_TWOSIDED, mat_two_sided)) {
  809. if (mat_two_sided > 0) {
  810. mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
  811. } else {
  812. mat->set_cull_mode(StandardMaterial3D::CULL_BACK);
  813. }
  814. }
  815. aiString mat_name;
  816. if (AI_SUCCESS == ai_material->Get(AI_MATKEY_NAME, mat_name)) {
  817. mat->set_name(AssimpUtils::get_assimp_string(mat_name));
  818. }
  819. // Culling handling for meshes
  820. // cull all back faces
  821. mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
  822. // Now process materials
  823. aiTextureType base_color = aiTextureType_BASE_COLOR;
  824. {
  825. String filename, path;
  826. AssimpImageData image_data;
  827. if (AssimpUtils::GetAssimpTexture(state, ai_material, base_color, filename, path, image_data)) {
  828. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  829. // anything transparent must be culled
  830. if (image_data.raw_image->detect_alpha() != Image::ALPHA_NONE) {
  831. mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
  832. mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED); // since you can see both sides in transparent mode
  833. }
  834. mat->set_texture(StandardMaterial3D::TEXTURE_ALBEDO, image_data.texture);
  835. }
  836. }
  837. aiTextureType tex_diffuse = aiTextureType_DIFFUSE;
  838. {
  839. String filename, path;
  840. AssimpImageData image_data;
  841. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_diffuse, filename, path, image_data)) {
  842. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  843. // anything transparent must be culled
  844. if (image_data.raw_image->detect_alpha() != Image::ALPHA_NONE) {
  845. mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
  846. mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED); // since you can see both sides in transparent mode
  847. }
  848. mat->set_texture(StandardMaterial3D::TEXTURE_ALBEDO, image_data.texture);
  849. }
  850. aiColor4D clr_diffuse;
  851. if (AI_SUCCESS == ai_material->Get(AI_MATKEY_COLOR_DIFFUSE, clr_diffuse)) {
  852. if (Math::is_equal_approx(clr_diffuse.a, 1.0f) == false) {
  853. mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
  854. mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED); // since you can see both sides in transparent mode
  855. }
  856. mat->set_albedo(Color(clr_diffuse.r, clr_diffuse.g, clr_diffuse.b, clr_diffuse.a));
  857. }
  858. }
  859. aiTextureType tex_normal = aiTextureType_NORMALS;
  860. {
  861. String filename, path;
  862. Ref<ImageTexture> texture;
  863. AssimpImageData image_data;
  864. // Process texture normal map
  865. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_normal, filename, path, image_data)) {
  866. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  867. mat->set_feature(StandardMaterial3D::Feature::FEATURE_NORMAL_MAPPING, true);
  868. mat->set_texture(StandardMaterial3D::TEXTURE_NORMAL, image_data.texture);
  869. } else {
  870. aiString texture_path;
  871. if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_NORMAL_TEXTURE, AI_PROPERTIES, texture_path)) {
  872. if (AssimpUtils::CreateAssimpTexture(state, texture_path, filename, path, image_data)) {
  873. mat->set_feature(StandardMaterial3D::Feature::FEATURE_NORMAL_MAPPING, true);
  874. mat->set_texture(StandardMaterial3D::TEXTURE_NORMAL, image_data.texture);
  875. }
  876. }
  877. }
  878. }
  879. aiTextureType tex_normal_camera = aiTextureType_NORMAL_CAMERA;
  880. {
  881. String filename, path;
  882. Ref<ImageTexture> texture;
  883. AssimpImageData image_data;
  884. // Process texture normal map
  885. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_normal_camera, filename, path, image_data)) {
  886. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  887. mat->set_feature(StandardMaterial3D::Feature::FEATURE_NORMAL_MAPPING, true);
  888. mat->set_texture(StandardMaterial3D::TEXTURE_NORMAL, image_data.texture);
  889. }
  890. }
  891. aiTextureType tex_emission_color = aiTextureType_EMISSION_COLOR;
  892. {
  893. String filename, path;
  894. Ref<ImageTexture> texture;
  895. AssimpImageData image_data;
  896. // Process texture normal map
  897. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_emission_color, filename, path, image_data)) {
  898. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  899. mat->set_feature(StandardMaterial3D::Feature::FEATURE_NORMAL_MAPPING, true);
  900. mat->set_texture(StandardMaterial3D::TEXTURE_NORMAL, image_data.texture);
  901. }
  902. }
  903. aiTextureType tex_metalness = aiTextureType_METALNESS;
  904. {
  905. String filename, path;
  906. Ref<ImageTexture> texture;
  907. AssimpImageData image_data;
  908. // Process texture normal map
  909. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_metalness, filename, path, image_data)) {
  910. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  911. mat->set_texture(StandardMaterial3D::TEXTURE_METALLIC, image_data.texture);
  912. }
  913. }
  914. aiTextureType tex_roughness = aiTextureType_DIFFUSE_ROUGHNESS;
  915. {
  916. String filename, path;
  917. Ref<ImageTexture> texture;
  918. AssimpImageData image_data;
  919. // Process texture normal map
  920. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_roughness, filename, path, image_data)) {
  921. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  922. mat->set_texture(StandardMaterial3D::TEXTURE_ROUGHNESS, image_data.texture);
  923. }
  924. }
  925. aiTextureType tex_emissive = aiTextureType_EMISSIVE;
  926. {
  927. String filename = "";
  928. String path = "";
  929. Ref<Image> texture;
  930. AssimpImageData image_data;
  931. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_emissive, filename, path, image_data)) {
  932. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  933. mat->set_feature(StandardMaterial3D::FEATURE_EMISSION, true);
  934. mat->set_texture(StandardMaterial3D::TEXTURE_EMISSION, image_data.texture);
  935. } else {
  936. // Process emission textures
  937. aiString texture_emissive_path;
  938. if (AI_SUCCESS ==
  939. ai_material->Get(AI_MATKEY_FBX_MAYA_EMISSION_TEXTURE, AI_PROPERTIES, texture_emissive_path)) {
  940. if (AssimpUtils::CreateAssimpTexture(state, texture_emissive_path, filename, path, image_data)) {
  941. mat->set_feature(StandardMaterial3D::FEATURE_EMISSION, true);
  942. mat->set_texture(StandardMaterial3D::TEXTURE_EMISSION, image_data.texture);
  943. }
  944. } else {
  945. float pbr_emission = 0.0f;
  946. if (AI_SUCCESS == ai_material->Get(AI_MATKEY_FBX_MAYA_EMISSIVE_FACTOR, AI_NULL, pbr_emission)) {
  947. mat->set_emission(Color(pbr_emission, pbr_emission, pbr_emission, 1.0f));
  948. }
  949. }
  950. }
  951. }
  952. aiTextureType tex_specular = aiTextureType_SPECULAR;
  953. {
  954. String filename, path;
  955. Ref<ImageTexture> texture;
  956. AssimpImageData image_data;
  957. // Process texture normal map
  958. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_specular, filename, path, image_data)) {
  959. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  960. mat->set_texture(StandardMaterial3D::TEXTURE_METALLIC, image_data.texture);
  961. }
  962. }
  963. aiTextureType tex_ao_map = aiTextureType_AMBIENT_OCCLUSION;
  964. {
  965. String filename, path;
  966. Ref<ImageTexture> texture;
  967. AssimpImageData image_data;
  968. // Process texture normal map
  969. if (AssimpUtils::GetAssimpTexture(state, ai_material, tex_ao_map, filename, path, image_data)) {
  970. AssimpUtils::set_texture_mapping_mode(image_data.map_mode, image_data.texture);
  971. mat->set_feature(StandardMaterial3D::FEATURE_AMBIENT_OCCLUSION, true);
  972. mat->set_texture(StandardMaterial3D::TEXTURE_AMBIENT_OCCLUSION, image_data.texture);
  973. }
  974. }
  975. Array array_mesh = st->commit_to_arrays();
  976. Array morphs;
  977. morphs.resize(ai_mesh->mNumAnimMeshes);
  978. Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
  979. for (size_t j = 0; j < ai_mesh->mNumAnimMeshes; j++) {
  980. String ai_anim_mesh_name = AssimpUtils::get_assimp_string(ai_mesh->mAnimMeshes[j]->mName);
  981. if (ai_anim_mesh_name.empty()) {
  982. ai_anim_mesh_name = String("morph_") + itos(j);
  983. }
  984. Array array_copy;
  985. array_copy.resize(RenderingServer::ARRAY_MAX);
  986. for (int l = 0; l < RenderingServer::ARRAY_MAX; l++) {
  987. array_copy[l] = array_mesh[l].duplicate(true);
  988. }
  989. const size_t num_vertices = ai_mesh->mAnimMeshes[j]->mNumVertices;
  990. array_copy[Mesh::ARRAY_INDEX] = Variant();
  991. if (ai_mesh->mAnimMeshes[j]->HasPositions()) {
  992. PackedVector3Array vertices;
  993. vertices.resize(num_vertices);
  994. for (size_t l = 0; l < num_vertices; l++) {
  995. const aiVector3D ai_pos = ai_mesh->mAnimMeshes[j]->mVertices[l];
  996. Vector3 position = Vector3(ai_pos.x, ai_pos.y, ai_pos.z);
  997. vertices.ptrw()[l] = position;
  998. }
  999. PackedVector3Array new_vertices = array_copy[RenderingServer::ARRAY_VERTEX].duplicate(true);
  1000. ERR_CONTINUE(vertices.size() != new_vertices.size());
  1001. for (int32_t l = 0; l < new_vertices.size(); l++) {
  1002. Vector3 *w = new_vertices.ptrw();
  1003. w[l] = vertices[l];
  1004. }
  1005. array_copy[RenderingServer::ARRAY_VERTEX] = new_vertices;
  1006. }
  1007. int32_t color_set = 0;
  1008. if (ai_mesh->mAnimMeshes[j]->HasVertexColors(color_set)) {
  1009. PackedColorArray colors;
  1010. colors.resize(num_vertices);
  1011. for (size_t l = 0; l < num_vertices; l++) {
  1012. const aiColor4D ai_color = ai_mesh->mAnimMeshes[j]->mColors[color_set][l];
  1013. Color color = Color(ai_color.r, ai_color.g, ai_color.b, ai_color.a);
  1014. colors.ptrw()[l] = color;
  1015. }
  1016. PackedColorArray new_colors = array_copy[RenderingServer::ARRAY_COLOR].duplicate(true);
  1017. ERR_CONTINUE(colors.size() != new_colors.size());
  1018. for (int32_t l = 0; l < colors.size(); l++) {
  1019. Color *w = new_colors.ptrw();
  1020. w[l] = colors[l];
  1021. }
  1022. array_copy[RenderingServer::ARRAY_COLOR] = new_colors;
  1023. }
  1024. if (ai_mesh->mAnimMeshes[j]->HasNormals()) {
  1025. PackedVector3Array normals;
  1026. normals.resize(num_vertices);
  1027. for (size_t l = 0; l < num_vertices; l++) {
  1028. const aiVector3D ai_normal = ai_mesh->mAnimMeshes[j]->mNormals[l];
  1029. Vector3 normal = Vector3(ai_normal.x, ai_normal.y, ai_normal.z);
  1030. normals.ptrw()[l] = normal;
  1031. }
  1032. PackedVector3Array new_normals = array_copy[RenderingServer::ARRAY_NORMAL].duplicate(true);
  1033. ERR_CONTINUE(normals.size() != new_normals.size());
  1034. for (int l = 0; l < normals.size(); l++) {
  1035. Vector3 *w = new_normals.ptrw();
  1036. w[l] = normals[l];
  1037. }
  1038. array_copy[RenderingServer::ARRAY_NORMAL] = new_normals;
  1039. }
  1040. if (ai_mesh->mAnimMeshes[j]->HasTangentsAndBitangents()) {
  1041. PackedColorArray tangents;
  1042. tangents.resize(num_vertices);
  1043. Color *w = tangents.ptrw();
  1044. for (size_t l = 0; l < num_vertices; l++) {
  1045. AssimpUtils::calc_tangent_from_mesh(ai_mesh, j, l, l, w);
  1046. }
  1047. PackedFloat32Array new_tangents = array_copy[RenderingServer::ARRAY_TANGENT].duplicate(true);
  1048. ERR_CONTINUE(new_tangents.size() != tangents.size() * 4);
  1049. for (int32_t l = 0; l < tangents.size(); l++) {
  1050. new_tangents.ptrw()[l + 0] = tangents[l].r;
  1051. new_tangents.ptrw()[l + 1] = tangents[l].g;
  1052. new_tangents.ptrw()[l + 2] = tangents[l].b;
  1053. new_tangents.ptrw()[l + 3] = tangents[l].a;
  1054. }
  1055. array_copy[RenderingServer::ARRAY_TANGENT] = new_tangents;
  1056. }
  1057. morphs[j] = array_copy;
  1058. }
  1059. mesh->add_surface_from_arrays(primitive, array_mesh, morphs, Dictionary(), mesh_flags);
  1060. mesh->surface_set_material(i, mat);
  1061. mesh->surface_set_name(i, AssimpUtils::get_assimp_string(ai_mesh->mName));
  1062. }
  1063. return mesh;
  1064. }
  1065. /**
  1066. * Create a new mesh for the node supplied
  1067. */
  1068. MeshInstance3D *
  1069. EditorSceneImporterAssimp::create_mesh(ImportState &state, const aiNode *assimp_node, const String &node_name, Node *active_node, Transform node_transform) {
  1070. /* MESH NODE */
  1071. Ref<Mesh> mesh;
  1072. Ref<Skin> skin;
  1073. // see if we have mesh cache for this.
  1074. Vector<int> surface_indices;
  1075. RegenerateBoneStack(state);
  1076. // Configure indices
  1077. for (uint32_t i = 0; i < assimp_node->mNumMeshes; i++) {
  1078. int mesh_index = assimp_node->mMeshes[i];
  1079. // create list of mesh indexes
  1080. surface_indices.push_back(mesh_index);
  1081. }
  1082. //surface_indices.sort();
  1083. String mesh_key;
  1084. for (int i = 0; i < surface_indices.size(); i++) {
  1085. if (i > 0) {
  1086. mesh_key += ":";
  1087. }
  1088. mesh_key += itos(surface_indices[i]);
  1089. }
  1090. Skeleton3D *skeleton = nullptr;
  1091. aiNode *armature = nullptr;
  1092. if (!state.mesh_cache.has(mesh_key)) {
  1093. mesh = _generate_mesh_from_surface_indices(state, surface_indices, assimp_node, skin, skeleton);
  1094. state.mesh_cache[mesh_key] = mesh;
  1095. }
  1096. MeshInstance3D *mesh_node = memnew(MeshInstance3D);
  1097. mesh = state.mesh_cache[mesh_key];
  1098. mesh_node->set_mesh(mesh);
  1099. // if we have a valid skeleton set it up
  1100. if (skin.is_valid()) {
  1101. for (uint32_t i = 0; i < assimp_node->mNumMeshes; i++) {
  1102. unsigned int mesh_index = assimp_node->mMeshes[i];
  1103. const aiMesh *ai_mesh = state.assimp_scene->mMeshes[mesh_index];
  1104. // please remember bone id relative to the skin is NOT the mesh relative index.
  1105. // it is the index relative to the skeleton that is why
  1106. // we have state.bone_id_map, it allows for duplicate bone id's too :)
  1107. // hope this makes sense
  1108. int bind_count = 0;
  1109. for (unsigned int boneId = 0; boneId < ai_mesh->mNumBones; ++boneId) {
  1110. aiBone *iterBone = ai_mesh->mBones[boneId];
  1111. // used to reparent mesh to the correct armature later on if assigned.
  1112. if (!armature) {
  1113. print_verbose("Configured mesh armature, will reparent later to armature");
  1114. armature = iterBone->mArmature;
  1115. }
  1116. if (skeleton) {
  1117. int id = skeleton->find_bone(AssimpUtils::get_assimp_string(iterBone->mName));
  1118. if (id != -1) {
  1119. print_verbose("Set bind bone: mesh: " + itos(mesh_index) + " bone index: " + itos(id));
  1120. Transform t = AssimpUtils::assimp_matrix_transform(iterBone->mOffsetMatrix);
  1121. skin->add_bind(bind_count, t);
  1122. skin->set_bind_bone(bind_count, id);
  1123. bind_count++;
  1124. }
  1125. }
  1126. }
  1127. }
  1128. print_verbose("Finished configuring bind pose for skin mesh");
  1129. }
  1130. // this code parents all meshes with bones to the armature they are for
  1131. // GLTF2 specification relies on this and we are enforcing it for FBX.
  1132. if (armature && state.flat_node_map[armature]) {
  1133. Node *armature_parent = state.flat_node_map[armature];
  1134. print_verbose("Parented mesh " + node_name + " to armature " + armature_parent->get_name());
  1135. // static mesh handling
  1136. armature_parent->add_child(mesh_node);
  1137. // transform must be identity
  1138. mesh_node->set_global_transform(Transform());
  1139. mesh_node->set_name(node_name);
  1140. mesh_node->set_owner(state.root);
  1141. } else {
  1142. // static mesh handling
  1143. active_node->add_child(mesh_node);
  1144. mesh_node->set_global_transform(node_transform);
  1145. mesh_node->set_name(node_name);
  1146. mesh_node->set_owner(state.root);
  1147. }
  1148. if (skeleton) {
  1149. print_verbose("Attempted to set skeleton path!");
  1150. mesh_node->set_skeleton_path(mesh_node->get_path_to(skeleton));
  1151. mesh_node->set_skin(skin);
  1152. }
  1153. return mesh_node;
  1154. }
  1155. /**
  1156. * Create a light for the scene
  1157. * Automatically caches lights for lookup later
  1158. */
  1159. Node3D *EditorSceneImporterAssimp::create_light(
  1160. ImportState &state,
  1161. const String &node_name,
  1162. Transform &look_at_transform) {
  1163. Light3D *light = nullptr;
  1164. aiLight *assimp_light = state.assimp_scene->mLights[state.light_cache[node_name]];
  1165. ERR_FAIL_COND_V(!assimp_light, nullptr);
  1166. if (assimp_light->mType == aiLightSource_DIRECTIONAL) {
  1167. light = memnew(DirectionalLight3D);
  1168. } else if (assimp_light->mType == aiLightSource_POINT) {
  1169. light = memnew(OmniLight3D);
  1170. } else if (assimp_light->mType == aiLightSource_SPOT) {
  1171. light = memnew(SpotLight3D);
  1172. }
  1173. ERR_FAIL_COND_V(light == nullptr, nullptr);
  1174. if (assimp_light->mType != aiLightSource_POINT) {
  1175. Vector3 pos = Vector3(
  1176. assimp_light->mPosition.x,
  1177. assimp_light->mPosition.y,
  1178. assimp_light->mPosition.z);
  1179. Vector3 look_at = Vector3(
  1180. assimp_light->mDirection.y,
  1181. assimp_light->mDirection.x,
  1182. assimp_light->mDirection.z)
  1183. .normalized();
  1184. Vector3 up = Vector3(
  1185. assimp_light->mUp.x,
  1186. assimp_light->mUp.y,
  1187. assimp_light->mUp.z);
  1188. look_at_transform.set_look_at(pos, look_at, up);
  1189. }
  1190. // properties for light variables should be put here.
  1191. // not really hugely important yet but we will need them in the future
  1192. light->set_color(
  1193. Color(assimp_light->mColorDiffuse.r, assimp_light->mColorDiffuse.g, assimp_light->mColorDiffuse.b));
  1194. return light;
  1195. }
  1196. /**
  1197. * Create camera for the scene
  1198. */
  1199. Node3D *EditorSceneImporterAssimp::create_camera(
  1200. ImportState &state,
  1201. const String &node_name,
  1202. Transform &look_at_transform) {
  1203. aiCamera *camera = state.assimp_scene->mCameras[state.camera_cache[node_name]];
  1204. ERR_FAIL_COND_V(!camera, nullptr);
  1205. Camera3D *camera_node = memnew(Camera3D);
  1206. ERR_FAIL_COND_V(!camera_node, nullptr);
  1207. float near = camera->mClipPlaneNear;
  1208. if (Math::is_equal_approx(near, 0.0f)) {
  1209. near = 0.1f;
  1210. }
  1211. camera_node->set_perspective(Math::rad2deg(camera->mHorizontalFOV) * 2.0f, near, camera->mClipPlaneFar);
  1212. Vector3 pos = Vector3(camera->mPosition.x, camera->mPosition.y, camera->mPosition.z);
  1213. Vector3 look_at = Vector3(camera->mLookAt.y, camera->mLookAt.x, camera->mLookAt.z).normalized();
  1214. Vector3 up = Vector3(camera->mUp.x, camera->mUp.y, camera->mUp.z);
  1215. look_at_transform.set_look_at(pos + look_at_transform.origin, look_at, up);
  1216. return camera_node;
  1217. }
  1218. /**
  1219. * Generate node
  1220. * Recursive call to iterate over all nodes
  1221. */
  1222. void EditorSceneImporterAssimp::_generate_node(
  1223. ImportState &state,
  1224. const aiNode *assimp_node) {
  1225. ERR_FAIL_COND(assimp_node == nullptr);
  1226. state.nodes.push_back(assimp_node);
  1227. String parent_name = AssimpUtils::get_assimp_string(assimp_node->mParent->mName);
  1228. // please note
  1229. // duplicate bone names exist
  1230. // this is why we only check if the bone exists
  1231. // so everything else is useless but the name
  1232. // please do not copy any other values from get_bone_by_name.
  1233. aiBone *parent_bone = get_bone_by_name(state.assimp_scene, assimp_node->mParent->mName);
  1234. aiBone *current_bone = get_bone_by_name(state.assimp_scene, assimp_node->mName);
  1235. // is this an armature
  1236. // parent null
  1237. // and this is the first bone :)
  1238. if (parent_bone == nullptr && current_bone) {
  1239. state.armature_nodes.push_back(assimp_node->mParent);
  1240. print_verbose("found valid armature: " + parent_name);
  1241. }
  1242. for (size_t i = 0; i < assimp_node->mNumChildren; i++) {
  1243. _generate_node(state, assimp_node->mChildren[i]);
  1244. }
  1245. }