editor_import_collada.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269
  1. /*************************************************************************/
  2. /* editor_import_collada.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_import_collada.h"
  31. #include "editor/collada/collada.h"
  32. #include "editor/editor_node.h"
  33. #include "os/os.h"
  34. #include "scene/3d/camera.h"
  35. #include "scene/3d/light.h"
  36. #include "scene/3d/mesh_instance.h"
  37. #include "scene/3d/path.h"
  38. #include "scene/3d/skeleton.h"
  39. #include "scene/3d/spatial.h"
  40. #include "scene/animation/animation_player.h"
  41. #include "scene/resources/animation.h"
  42. #include "scene/resources/packed_scene.h"
  43. #include <iostream>
  44. struct ColladaImport {
  45. Collada collada;
  46. Spatial *scene;
  47. Vector<Ref<Animation> > animations;
  48. struct NodeMap {
  49. //String path;
  50. Spatial *node;
  51. int bone;
  52. List<int> anim_tracks;
  53. NodeMap() {
  54. node = NULL;
  55. bone = -1;
  56. }
  57. };
  58. bool found_ambient;
  59. Color ambient;
  60. bool found_directional;
  61. bool force_make_tangents;
  62. bool apply_mesh_xform_to_vertices;
  63. float bake_fps;
  64. Map<String, NodeMap> node_map; //map from collada node to engine node
  65. Map<String, String> node_name_map; //map from collada node to engine node
  66. Map<String, Ref<Mesh> > mesh_cache;
  67. Map<String, Ref<Curve3D> > curve_cache;
  68. Map<String, Ref<Material> > material_cache;
  69. Map<Collada::Node *, Skeleton *> skeleton_map;
  70. Map<Skeleton *, Map<String, int> > skeleton_bone_map;
  71. Set<String> valid_animated_nodes;
  72. Vector<int> valid_animated_properties;
  73. Map<String, bool> bones_with_animation;
  74. Error _populate_skeleton(Skeleton *p_skeleton, Collada::Node *p_node, int &r_bone, int p_parent);
  75. Error _create_scene_skeletons(Collada::Node *p_node);
  76. Error _create_scene(Collada::Node *p_node, Spatial *p_parent);
  77. Error _create_resources(Collada::Node *p_node);
  78. Error _create_material(const String &p_material);
  79. Error _create_mesh_surfaces(bool p_optimize, Ref<Mesh> &p_mesh, const Map<String, Collada::NodeGeometry::Material> &p_material_map, const Collada::MeshData &meshdata, const Transform &p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *p_skin_data, const Collada::MorphControllerData *p_morph_data, Vector<Ref<Mesh> > p_morph_meshes = Vector<Ref<Mesh> >());
  80. Error load(const String &p_path, int p_flags, bool p_force_make_tangents = false);
  81. void _fix_param_animation_tracks();
  82. void create_animation(int p_clip, bool p_make_tracks_in_all_bones, bool p_import_value_tracks);
  83. void create_animations(bool p_make_tracks_in_all_bones, bool p_import_value_tracks);
  84. Set<String> tracks_in_clips;
  85. Vector<String> missing_textures;
  86. void _pre_process_lights(Collada::Node *p_node);
  87. ColladaImport() {
  88. found_ambient = false;
  89. found_directional = false;
  90. force_make_tangents = false;
  91. apply_mesh_xform_to_vertices = true;
  92. bake_fps = 15;
  93. }
  94. };
  95. Error ColladaImport::_populate_skeleton(Skeleton *p_skeleton, Collada::Node *p_node, int &r_bone, int p_parent) {
  96. if (p_node->type != Collada::Node::TYPE_JOINT)
  97. return OK;
  98. Collada::NodeJoint *joint = static_cast<Collada::NodeJoint *>(p_node);
  99. print_line("populating joint " + joint->name);
  100. p_skeleton->add_bone(p_node->name);
  101. if (p_parent >= 0)
  102. p_skeleton->set_bone_parent(r_bone, p_parent);
  103. NodeMap nm;
  104. nm.node = p_skeleton;
  105. nm.bone = r_bone;
  106. node_map[p_node->id] = nm;
  107. node_name_map[p_node->name] = p_node->id;
  108. skeleton_bone_map[p_skeleton][joint->sid] = r_bone;
  109. if (collada.state.bone_rest_map.has(joint->sid)) {
  110. p_skeleton->set_bone_rest(r_bone, collada.fix_transform(collada.state.bone_rest_map[joint->sid]));
  111. //should map this bone to something for animation?
  112. } else {
  113. print_line("no rest: " + joint->sid);
  114. WARN_PRINT("Joint has no rest..");
  115. }
  116. int id = r_bone++;
  117. for (int i = 0; i < p_node->children.size(); i++) {
  118. Error err = _populate_skeleton(p_skeleton, p_node->children[i], r_bone, id);
  119. if (err)
  120. return err;
  121. }
  122. return OK;
  123. }
  124. void ColladaImport::_pre_process_lights(Collada::Node *p_node) {
  125. if (p_node->type == Collada::Node::TYPE_LIGHT) {
  126. Collada::NodeLight *light = static_cast<Collada::NodeLight *>(p_node);
  127. if (collada.state.light_data_map.has(light->light)) {
  128. Collada::LightData &ld = collada.state.light_data_map[light->light];
  129. if (ld.mode == Collada::LightData::MODE_AMBIENT) {
  130. found_ambient = true;
  131. ambient = ld.color;
  132. }
  133. if (ld.mode == Collada::LightData::MODE_DIRECTIONAL) {
  134. found_directional = true;
  135. }
  136. }
  137. }
  138. for (int i = 0; i < p_node->children.size(); i++)
  139. _pre_process_lights(p_node->children[i]);
  140. }
  141. Error ColladaImport::_create_scene_skeletons(Collada::Node *p_node) {
  142. if (p_node->type == Collada::Node::TYPE_SKELETON) {
  143. Skeleton *sk = memnew(Skeleton);
  144. int bone = 0;
  145. for (int i = 0; i < p_node->children.size(); i++) {
  146. _populate_skeleton(sk, p_node->children[i], bone, -1);
  147. }
  148. sk->localize_rests(); //after creating skeleton, rests must be localized...!
  149. skeleton_map[p_node] = sk;
  150. }
  151. for (int i = 0; i < p_node->children.size(); i++) {
  152. Error err = _create_scene_skeletons(p_node->children[i]);
  153. if (err)
  154. return err;
  155. }
  156. return OK;
  157. }
  158. Error ColladaImport::_create_scene(Collada::Node *p_node, Spatial *p_parent) {
  159. Spatial *node = NULL;
  160. switch (p_node->type) {
  161. case Collada::Node::TYPE_NODE: {
  162. node = memnew(Spatial);
  163. } break;
  164. case Collada::Node::TYPE_JOINT: {
  165. return OK; // do nothing
  166. } break;
  167. case Collada::Node::TYPE_LIGHT: {
  168. //node = memnew( Light)
  169. Collada::NodeLight *light = static_cast<Collada::NodeLight *>(p_node);
  170. if (collada.state.light_data_map.has(light->light)) {
  171. Collada::LightData &ld = collada.state.light_data_map[light->light];
  172. if (ld.mode == Collada::LightData::MODE_AMBIENT) {
  173. if (found_directional)
  174. return OK; //do nothing not needed
  175. if (!bool(GLOBAL_DEF("collada/use_ambient", false)))
  176. return OK;
  177. //well, it's an ambient light..
  178. Light *l = memnew(DirectionalLight);
  179. // l->set_color(Light::COLOR_AMBIENT,ld.color);
  180. l->set_color(Light::COLOR_DIFFUSE, Color(0, 0, 0));
  181. l->set_color(Light::COLOR_SPECULAR, Color(0, 0, 0));
  182. node = l;
  183. } else if (ld.mode == Collada::LightData::MODE_DIRECTIONAL) {
  184. //well, it's an ambient light..
  185. Light *l = memnew(DirectionalLight);
  186. //if (found_ambient) //use it here
  187. // l->set_color(Light::COLOR_AMBIENT,ambient);
  188. l->set_color(Light::COLOR_DIFFUSE, ld.color);
  189. l->set_color(Light::COLOR_SPECULAR, Color(1, 1, 1));
  190. node = l;
  191. } else {
  192. Light *l;
  193. if (ld.mode == Collada::LightData::MODE_OMNI)
  194. l = memnew(OmniLight);
  195. else {
  196. l = memnew(SpotLight);
  197. l->set_parameter(Light::PARAM_SPOT_ANGLE, ld.spot_angle);
  198. l->set_parameter(Light::PARAM_SPOT_ATTENUATION, ld.spot_exp);
  199. }
  200. //
  201. l->set_color(Light::COLOR_DIFFUSE, ld.color);
  202. l->set_color(Light::COLOR_SPECULAR, Color(1, 1, 1));
  203. l->approximate_opengl_attenuation(ld.constant_att, ld.linear_att, ld.quad_att);
  204. node = l;
  205. }
  206. } else {
  207. node = memnew(Spatial);
  208. }
  209. } break;
  210. case Collada::Node::TYPE_CAMERA: {
  211. Collada::NodeCamera *cam = static_cast<Collada::NodeCamera *>(p_node);
  212. Camera *camera = memnew(Camera);
  213. if (collada.state.camera_data_map.has(cam->camera)) {
  214. const Collada::CameraData &cd = collada.state.camera_data_map[cam->camera];
  215. switch (cd.mode) {
  216. case Collada::CameraData::MODE_ORTHOGONAL: {
  217. if (cd.orthogonal.y_mag) {
  218. camera->set_keep_aspect_mode(Camera::KEEP_HEIGHT);
  219. camera->set_orthogonal(cd.orthogonal.y_mag * 2.0, cd.z_near, cd.z_far);
  220. } else if (!cd.orthogonal.y_mag && cd.orthogonal.x_mag) {
  221. camera->set_keep_aspect_mode(Camera::KEEP_WIDTH);
  222. camera->set_orthogonal(cd.orthogonal.x_mag * 2.0, cd.z_near, cd.z_far);
  223. }
  224. } break;
  225. case Collada::CameraData::MODE_PERSPECTIVE: {
  226. if (cd.perspective.y_fov) {
  227. camera->set_perspective(cd.perspective.y_fov, cd.z_near, cd.z_far);
  228. } else if (!cd.perspective.y_fov && cd.perspective.x_fov) {
  229. camera->set_perspective(cd.perspective.x_fov / cd.aspect, cd.z_near, cd.z_far);
  230. }
  231. } break;
  232. }
  233. }
  234. node = camera;
  235. } break;
  236. case Collada::Node::TYPE_GEOMETRY: {
  237. Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(p_node);
  238. if (collada.state.curve_data_map.has(ng->source)) {
  239. node = memnew(Path);
  240. } else {
  241. //mesh since nothing else
  242. node = memnew(MeshInstance);
  243. node->cast_to<MeshInstance>()->set_flag(GeometryInstance::FLAG_USE_BAKED_LIGHT, true);
  244. }
  245. } break;
  246. case Collada::Node::TYPE_SKELETON: {
  247. ERR_FAIL_COND_V(!skeleton_map.has(p_node), ERR_CANT_CREATE);
  248. Skeleton *sk = skeleton_map[p_node];
  249. node = sk;
  250. } break;
  251. }
  252. if (p_node->name != "")
  253. node->set_name(p_node->name);
  254. NodeMap nm;
  255. nm.node = node;
  256. node_map[p_node->id] = nm;
  257. node_name_map[p_node->name] = p_node->id;
  258. Transform xf = p_node->default_transform;
  259. xf = collada.fix_transform(xf) * p_node->post_transform;
  260. node->set_transform(xf);
  261. p_parent->add_child(node);
  262. node->set_owner(scene);
  263. if (p_node->empty_draw_type != "") {
  264. node->set_meta("empty_draw_type", Variant(p_node->empty_draw_type));
  265. }
  266. for (int i = 0; i < p_node->children.size(); i++) {
  267. Error err = _create_scene(p_node->children[i], node);
  268. if (err)
  269. return err;
  270. }
  271. return OK;
  272. }
  273. Error ColladaImport::_create_material(const String &p_target) {
  274. ERR_FAIL_COND_V(material_cache.has(p_target), ERR_ALREADY_EXISTS);
  275. ERR_FAIL_COND_V(!collada.state.material_map.has(p_target), ERR_INVALID_PARAMETER);
  276. Collada::Material &src_mat = collada.state.material_map[p_target];
  277. ERR_FAIL_COND_V(!collada.state.effect_map.has(src_mat.instance_effect), ERR_INVALID_PARAMETER);
  278. Collada::Effect &effect = collada.state.effect_map[src_mat.instance_effect];
  279. Ref<FixedMaterial> material = memnew(FixedMaterial);
  280. if (src_mat.name != "")
  281. material->set_name(src_mat.name);
  282. else if (effect.name != "")
  283. material->set_name(effect.name);
  284. // DIFFUSE
  285. if (effect.diffuse.texture != "") {
  286. String texfile = effect.get_texture_path(effect.diffuse.texture, collada);
  287. if (texfile != "") {
  288. Ref<Texture> texture = ResourceLoader::load(texfile, "Texture");
  289. if (texture.is_valid()) {
  290. material->set_texture(FixedMaterial::PARAM_DIFFUSE, texture);
  291. material->set_parameter(FixedMaterial::PARAM_DIFFUSE, Color(1, 1, 1, 1));
  292. } else {
  293. missing_textures.push_back(texfile.get_file());
  294. }
  295. }
  296. } else {
  297. material->set_parameter(FixedMaterial::PARAM_DIFFUSE, effect.diffuse.color);
  298. }
  299. // SPECULAR
  300. if (effect.specular.texture != "") {
  301. String texfile = effect.get_texture_path(effect.specular.texture, collada);
  302. if (texfile != "") {
  303. Ref<Texture> texture = ResourceLoader::load(texfile, "Texture");
  304. if (texture.is_valid()) {
  305. material->set_texture(FixedMaterial::PARAM_SPECULAR, texture);
  306. material->set_parameter(FixedMaterial::PARAM_SPECULAR, Color(1, 1, 1, 1));
  307. } else {
  308. missing_textures.push_back(texfile.get_file());
  309. }
  310. }
  311. } else {
  312. material->set_parameter(FixedMaterial::PARAM_SPECULAR, effect.specular.color);
  313. }
  314. // EMISSION
  315. if (effect.emission.texture != "") {
  316. String texfile = effect.get_texture_path(effect.emission.texture, collada);
  317. if (texfile != "") {
  318. Ref<Texture> texture = ResourceLoader::load(texfile, "Texture");
  319. if (texture.is_valid()) {
  320. material->set_texture(FixedMaterial::PARAM_EMISSION, texture);
  321. material->set_parameter(FixedMaterial::PARAM_EMISSION, Color(1, 1, 1, 1));
  322. } else {
  323. missing_textures.push_back(texfile.get_file());
  324. }
  325. }
  326. } else {
  327. material->set_parameter(FixedMaterial::PARAM_EMISSION, effect.emission.color);
  328. }
  329. // NORMAL
  330. if (effect.bump.texture != "") {
  331. String texfile = effect.get_texture_path(effect.bump.texture, collada);
  332. if (texfile != "") {
  333. Ref<Texture> texture = ResourceLoader::load(texfile, "Texture");
  334. if (texture.is_valid()) {
  335. material->set_texture(FixedMaterial::PARAM_NORMAL, texture);
  336. } else {
  337. missing_textures.push_back(texfile.get_file());
  338. }
  339. }
  340. }
  341. material->set_parameter(FixedMaterial::PARAM_SPECULAR_EXP, effect.shininess);
  342. material->set_flag(Material::FLAG_DOUBLE_SIDED, effect.double_sided);
  343. material->set_flag(Material::FLAG_UNSHADED, effect.unshaded);
  344. material_cache[p_target] = material;
  345. return OK;
  346. }
  347. static void _generate_normals(const DVector<int> &p_indices, const DVector<Vector3> &p_vertices, DVector<Vector3> &r_normals) {
  348. r_normals.resize(p_vertices.size());
  349. DVector<Vector3>::Write narrayw = r_normals.write();
  350. int iacount = p_indices.size() / 3;
  351. DVector<int>::Read index_arrayr = p_indices.read();
  352. DVector<Vector3>::Read vertex_arrayr = p_vertices.read();
  353. for (int idx = 0; idx < iacount; idx++) {
  354. Vector3 v[3] = {
  355. vertex_arrayr[index_arrayr[idx * 3 + 0]],
  356. vertex_arrayr[index_arrayr[idx * 3 + 1]],
  357. vertex_arrayr[index_arrayr[idx * 3 + 2]]
  358. };
  359. Vector3 normal = Plane(v[0], v[1], v[2]).normal;
  360. narrayw[index_arrayr[idx * 3 + 0]] += normal;
  361. narrayw[index_arrayr[idx * 3 + 1]] += normal;
  362. narrayw[index_arrayr[idx * 3 + 2]] += normal;
  363. }
  364. int vlen = p_vertices.size();
  365. for (int idx = 0; idx < vlen; idx++) {
  366. narrayw[idx].normalize();
  367. }
  368. }
  369. static void _generate_tangents_and_binormals(const DVector<int> &p_indices, const DVector<Vector3> &p_vertices, const DVector<Vector3> &p_uvs, const DVector<Vector3> &p_normals, DVector<real_t> &r_tangents) {
  370. int vlen = p_vertices.size();
  371. Vector<Vector3> tangents;
  372. tangents.resize(vlen);
  373. Vector<Vector3> binormals;
  374. binormals.resize(vlen);
  375. int iacount = p_indices.size() / 3;
  376. DVector<int>::Read index_arrayr = p_indices.read();
  377. DVector<Vector3>::Read vertex_arrayr = p_vertices.read();
  378. DVector<Vector3>::Read narrayr = p_normals.read();
  379. DVector<Vector3>::Read uvarrayr = p_uvs.read();
  380. for (int idx = 0; idx < iacount; idx++) {
  381. Vector3 v1 = vertex_arrayr[index_arrayr[idx * 3 + 0]];
  382. Vector3 v2 = vertex_arrayr[index_arrayr[idx * 3 + 1]];
  383. Vector3 v3 = vertex_arrayr[index_arrayr[idx * 3 + 2]];
  384. Vector3 w1 = uvarrayr[index_arrayr[idx * 3 + 0]];
  385. Vector3 w2 = uvarrayr[index_arrayr[idx * 3 + 1]];
  386. Vector3 w3 = uvarrayr[index_arrayr[idx * 3 + 2]];
  387. real_t x1 = v2.x - v1.x;
  388. real_t x2 = v3.x - v1.x;
  389. real_t y1 = v2.y - v1.y;
  390. real_t y2 = v3.y - v1.y;
  391. real_t z1 = v2.z - v1.z;
  392. real_t z2 = v3.z - v1.z;
  393. real_t s1 = w2.x - w1.x;
  394. real_t s2 = w3.x - w1.x;
  395. real_t t1 = w2.y - w1.y;
  396. real_t t2 = w3.y - w1.y;
  397. real_t r = (s1 * t2 - s2 * t1);
  398. Vector3 tangent;
  399. Vector3 binormal;
  400. if (r == 0) {
  401. binormal = Vector3();
  402. tangent = Vector3();
  403. } else {
  404. tangent = Vector3((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r,
  405. (t2 * z1 - t1 * z2) * r)
  406. .normalized();
  407. binormal = Vector3((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r,
  408. (s1 * z2 - s2 * z1) * r)
  409. .normalized();
  410. }
  411. tangents[index_arrayr[idx * 3 + 0]] += tangent;
  412. binormals[index_arrayr[idx * 3 + 0]] += binormal;
  413. tangents[index_arrayr[idx * 3 + 1]] += tangent;
  414. binormals[index_arrayr[idx * 3 + 1]] += binormal;
  415. tangents[index_arrayr[idx * 3 + 2]] += tangent;
  416. binormals[index_arrayr[idx * 3 + 2]] += binormal;
  417. //print_line(itos(idx)+" tangent: "+tangent);
  418. //print_line(itos(idx)+" binormal: "+binormal);
  419. }
  420. r_tangents.resize(vlen * 4);
  421. DVector<real_t>::Write tarrayw = r_tangents.write();
  422. for (int idx = 0; idx < vlen; idx++) {
  423. Vector3 tangent = tangents[idx];
  424. Vector3 bingen = narrayr[idx].cross(tangent);
  425. float dir;
  426. if (bingen.dot(binormals[idx]) < 0)
  427. dir = -1.0;
  428. else
  429. dir = +1.0;
  430. tarrayw[idx * 4 + 0] = tangent.x;
  431. tarrayw[idx * 4 + 1] = tangent.y;
  432. tarrayw[idx * 4 + 2] = tangent.z;
  433. tarrayw[idx * 4 + 3] = dir;
  434. }
  435. }
  436. Error ColladaImport::_create_mesh_surfaces(bool p_optimize, Ref<Mesh> &p_mesh, const Map<String, Collada::NodeGeometry::Material> &p_material_map, const Collada::MeshData &meshdata, const Transform &p_local_xform, const Vector<int> &bone_remap, const Collada::SkinControllerData *skin_controller, const Collada::MorphControllerData *p_morph_data, Vector<Ref<Mesh> > p_morph_meshes) {
  437. bool local_xform_mirror = p_local_xform.basis.determinant() < 0;
  438. if (p_morph_data) {
  439. //add morphie target
  440. ERR_FAIL_COND_V(!p_morph_data->targets.has("MORPH_TARGET"), ERR_INVALID_DATA);
  441. String mt = p_morph_data->targets["MORPH_TARGET"];
  442. ERR_FAIL_COND_V(!p_morph_data->sources.has(mt), ERR_INVALID_DATA);
  443. int morph_targets = p_morph_data->sources[mt].sarray.size();
  444. for (int i = 0; i < morph_targets; i++) {
  445. String target = p_morph_data->sources[mt].sarray[i];
  446. ERR_FAIL_COND_V(!collada.state.mesh_data_map.has(target), ERR_INVALID_DATA);
  447. String name = collada.state.mesh_data_map[target].name;
  448. p_mesh->add_morph_target(name);
  449. }
  450. if (p_morph_data->mode == "RELATIVE")
  451. p_mesh->set_morph_target_mode(Mesh::MORPH_MODE_RELATIVE);
  452. else if (p_morph_data->mode == "NORMALIZED")
  453. p_mesh->set_morph_target_mode(Mesh::MORPH_MODE_NORMALIZED);
  454. }
  455. int surface = 0;
  456. for (int p_i = 0; p_i < meshdata.primitives.size(); p_i++) {
  457. const Collada::MeshData::Primitives &p = meshdata.primitives[p_i];
  458. /* VERTEX SOURCE */
  459. ERR_FAIL_COND_V(!p.sources.has("VERTEX"), ERR_INVALID_DATA);
  460. String vertex_src_id = p.sources["VERTEX"].source;
  461. int vertex_ofs = p.sources["VERTEX"].offset;
  462. ERR_FAIL_COND_V(!meshdata.vertices.has(vertex_src_id), ERR_INVALID_DATA);
  463. ERR_FAIL_COND_V(!meshdata.vertices[vertex_src_id].sources.has("POSITION"), ERR_INVALID_DATA);
  464. String position_src_id = meshdata.vertices[vertex_src_id].sources["POSITION"];
  465. ERR_FAIL_COND_V(!meshdata.sources.has(position_src_id), ERR_INVALID_DATA);
  466. const Collada::MeshData::Source *vertex_src = &meshdata.sources[position_src_id];
  467. /* NORMAL SOURCE */
  468. const Collada::MeshData::Source *normal_src = NULL;
  469. int normal_ofs = 0;
  470. if (p.sources.has("NORMAL")) {
  471. String normal_source_id = p.sources["NORMAL"].source;
  472. normal_ofs = p.sources["NORMAL"].offset;
  473. ERR_FAIL_COND_V(!meshdata.sources.has(normal_source_id), ERR_INVALID_DATA);
  474. normal_src = &meshdata.sources[normal_source_id];
  475. }
  476. const Collada::MeshData::Source *binormal_src = NULL;
  477. int binormal_ofs = 0;
  478. if (p.sources.has("TEXBINORMAL")) {
  479. String binormal_source_id = p.sources["TEXBINORMAL"].source;
  480. binormal_ofs = p.sources["TEXBINORMAL"].offset;
  481. ERR_FAIL_COND_V(!meshdata.sources.has(binormal_source_id), ERR_INVALID_DATA);
  482. binormal_src = &meshdata.sources[binormal_source_id];
  483. }
  484. const Collada::MeshData::Source *tangent_src = NULL;
  485. int tangent_ofs = 0;
  486. if (p.sources.has("TEXTANGENT")) {
  487. String tangent_source_id = p.sources["TEXTANGENT"].source;
  488. tangent_ofs = p.sources["TEXTANGENT"].offset;
  489. ERR_FAIL_COND_V(!meshdata.sources.has(tangent_source_id), ERR_INVALID_DATA);
  490. tangent_src = &meshdata.sources[tangent_source_id];
  491. }
  492. const Collada::MeshData::Source *uv_src = NULL;
  493. int uv_ofs = 0;
  494. if (p.sources.has("TEXCOORD0")) {
  495. String uv_source_id = p.sources["TEXCOORD0"].source;
  496. uv_ofs = p.sources["TEXCOORD0"].offset;
  497. ERR_FAIL_COND_V(!meshdata.sources.has(uv_source_id), ERR_INVALID_DATA);
  498. uv_src = &meshdata.sources[uv_source_id];
  499. }
  500. const Collada::MeshData::Source *uv2_src = NULL;
  501. int uv2_ofs = 0;
  502. if (p.sources.has("TEXCOORD1")) {
  503. String uv2_source_id = p.sources["TEXCOORD1"].source;
  504. uv2_ofs = p.sources["TEXCOORD1"].offset;
  505. ERR_FAIL_COND_V(!meshdata.sources.has(uv2_source_id), ERR_INVALID_DATA);
  506. uv2_src = &meshdata.sources[uv2_source_id];
  507. }
  508. const Collada::MeshData::Source *color_src = NULL;
  509. int color_ofs = 0;
  510. if (p.sources.has("COLOR")) {
  511. String color_source_id = p.sources["COLOR"].source;
  512. color_ofs = p.sources["COLOR"].offset;
  513. ERR_FAIL_COND_V(!meshdata.sources.has(color_source_id), ERR_INVALID_DATA);
  514. color_src = &meshdata.sources[color_source_id];
  515. }
  516. //find largest source..
  517. /************************/
  518. /* ADD WEIGHTS IF EXIST */
  519. /************************/
  520. Map<int, Vector<Collada::Vertex::Weight> > pre_weights;
  521. bool has_weights = false;
  522. if (skin_controller) {
  523. const Collada::SkinControllerData::Source *weight_src = NULL;
  524. int weight_ofs = 0;
  525. if (skin_controller->weights.sources.has("WEIGHT")) {
  526. String weight_id = skin_controller->weights.sources["WEIGHT"].source;
  527. weight_ofs = skin_controller->weights.sources["WEIGHT"].offset;
  528. if (skin_controller->sources.has(weight_id)) {
  529. weight_src = &skin_controller->sources[weight_id];
  530. }
  531. }
  532. int joint_ofs = 0;
  533. if (skin_controller->weights.sources.has("JOINT")) {
  534. joint_ofs = skin_controller->weights.sources["JOINT"].offset;
  535. }
  536. //should be OK, given this was pre-checked.
  537. int index_ofs = 0;
  538. int wstride = skin_controller->weights.sources.size();
  539. for (int w_i = 0; w_i < skin_controller->weights.sets.size(); w_i++) {
  540. int amount = skin_controller->weights.sets[w_i];
  541. Vector<Collada::Vertex::Weight> weights;
  542. for (int a_i = 0; a_i < amount; a_i++) {
  543. Collada::Vertex::Weight w;
  544. int read_from = index_ofs + a_i * wstride;
  545. ERR_FAIL_INDEX_V(read_from + wstride - 1, skin_controller->weights.indices.size(), ERR_INVALID_DATA);
  546. int weight_index = skin_controller->weights.indices[read_from + weight_ofs];
  547. ERR_FAIL_INDEX_V(weight_index, weight_src->array.size(), ERR_INVALID_DATA);
  548. w.weight = weight_src->array[weight_index];
  549. int bone_index = skin_controller->weights.indices[read_from + joint_ofs];
  550. if (bone_index == -1)
  551. continue; //ignore this weight (refers to bind shape)
  552. ERR_FAIL_INDEX_V(bone_index, bone_remap.size(), ERR_INVALID_DATA);
  553. w.bone_idx = bone_remap[bone_index];
  554. weights.push_back(w);
  555. }
  556. /* FIX WEIGHTS */
  557. weights.sort();
  558. if (weights.size() > 4) {
  559. //cap to 4 and make weights add up 1
  560. weights.resize(4);
  561. }
  562. //make sure weights allways add up to 1
  563. float total = 0;
  564. for (int i = 0; i < weights.size(); i++)
  565. total += weights[i].weight;
  566. if (total)
  567. for (int i = 0; i < weights.size(); i++)
  568. weights[i].weight /= total;
  569. if (weights.size() == 0 || total == 0) { //if nothing, add a weight to bone 0
  570. //no weights assigned
  571. Collada::Vertex::Weight w;
  572. w.bone_idx = 0;
  573. w.weight = 1.0;
  574. weights.clear();
  575. weights.push_back(w);
  576. }
  577. pre_weights[w_i] = weights;
  578. /*
  579. for(Set<int>::Element *E=vertex_map[w_i].front();E;E=E->next()) {
  580. int dst = E->get();
  581. ERR_EXPLAIN("invalid vertex index in array");
  582. ERR_FAIL_INDEX_V(dst,vertex_array.size(),ERR_INVALID_DATA);
  583. vertex_array[dst].weights=weights;
  584. }*/
  585. index_ofs += wstride * amount;
  586. }
  587. //vertices need to be localized
  588. has_weights = true;
  589. }
  590. Set<Collada::Vertex> vertex_set; //vertex set will be the vertices
  591. List<int> indices_list; //indices will be the indices
  592. //Map<int,Set<int> > vertex_map; //map vertices (for setting skinning/morph)
  593. /**************************/
  594. /* CREATE PRIMITIVE ARRAY */
  595. /**************************/
  596. // The way collada uses indices is more optimal, and friendlier with 3D modelling sofware,
  597. // because it can index everything, not only vertices (similar to how the WII works).
  598. // This is, however, more incompatible with standard video cards, so arrays must be converted.
  599. // Must convert to GL/DX format.
  600. int _prim_ofs = 0;
  601. int vertidx = 0;
  602. for (int p_i = 0; p_i < p.count; p_i++) {
  603. int amount;
  604. if (p.polygons.size()) {
  605. ERR_FAIL_INDEX_V(p_i, p.polygons.size(), ERR_INVALID_DATA);
  606. amount = p.polygons[p_i];
  607. } else {
  608. amount = 3; //triangles;
  609. }
  610. //COLLADA_PRINT("amount: "+itos(amount));
  611. int prev2[2] = { 0, 0 };
  612. for (int j = 0; j < amount; j++) {
  613. int src = _prim_ofs;
  614. //_prim_ofs+=p.sources.size()
  615. ERR_FAIL_INDEX_V(src, p.indices.size(), ERR_INVALID_DATA);
  616. Collada::Vertex vertex;
  617. if (!p_optimize)
  618. vertex.uid = vertidx++;
  619. int vertex_index = p.indices[src + vertex_ofs]; //used for index field (later used by controllers)
  620. int vertex_pos = (vertex_src->stride ? vertex_src->stride : 3) * vertex_index;
  621. ERR_FAIL_INDEX_V(vertex_pos, vertex_src->array.size(), ERR_INVALID_DATA);
  622. vertex.vertex = Vector3(vertex_src->array[vertex_pos + 0], vertex_src->array[vertex_pos + 1], vertex_src->array[vertex_pos + 2]);
  623. if (pre_weights.has(vertex_index)) {
  624. vertex.weights = pre_weights[vertex_index];
  625. }
  626. if (normal_src) {
  627. int normal_pos = (normal_src->stride ? normal_src->stride : 3) * p.indices[src + normal_ofs];
  628. ERR_FAIL_INDEX_V(normal_pos, normal_src->array.size(), ERR_INVALID_DATA);
  629. vertex.normal = Vector3(normal_src->array[normal_pos + 0], normal_src->array[normal_pos + 1], normal_src->array[normal_pos + 2]);
  630. vertex.normal = vertex.normal.snapped(0.001);
  631. if (tangent_src && binormal_src) {
  632. int binormal_pos = (binormal_src->stride ? binormal_src->stride : 3) * p.indices[src + binormal_ofs];
  633. ERR_FAIL_INDEX_V(binormal_pos, binormal_src->array.size(), ERR_INVALID_DATA);
  634. Vector3 binormal = Vector3(binormal_src->array[binormal_pos + 0], binormal_src->array[binormal_pos + 1], binormal_src->array[binormal_pos + 2]);
  635. int tangent_pos = (tangent_src->stride ? tangent_src->stride : 3) * p.indices[src + tangent_ofs];
  636. ERR_FAIL_INDEX_V(tangent_pos, tangent_src->array.size(), ERR_INVALID_DATA);
  637. Vector3 tangent = Vector3(tangent_src->array[tangent_pos + 0], tangent_src->array[tangent_pos + 1], tangent_src->array[tangent_pos + 2]);
  638. vertex.tangent.normal = tangent;
  639. vertex.tangent.d = vertex.normal.cross(tangent).dot(binormal) > 0 ? 1 : -1;
  640. }
  641. }
  642. if (uv_src) {
  643. int uv_pos = (uv_src->stride ? uv_src->stride : 2) * p.indices[src + uv_ofs];
  644. ERR_FAIL_INDEX_V(uv_pos, uv_src->array.size(), ERR_INVALID_DATA);
  645. vertex.uv = Vector3(uv_src->array[uv_pos + 0], 1.0 - uv_src->array[uv_pos + 1], 0);
  646. }
  647. if (uv2_src) {
  648. int uv2_pos = (uv2_src->stride ? uv2_src->stride : 2) * p.indices[src + uv2_ofs];
  649. ERR_FAIL_INDEX_V(uv2_pos, uv2_src->array.size(), ERR_INVALID_DATA);
  650. vertex.uv2 = Vector3(uv2_src->array[uv2_pos + 0], 1.0 - uv2_src->array[uv2_pos + 1], 0);
  651. }
  652. if (color_src) {
  653. int color_pos = (color_src->stride ? color_src->stride : 3) * p.indices[src + color_ofs]; // colors are RGB in collada..
  654. ERR_FAIL_INDEX_V(color_pos, color_src->array.size(), ERR_INVALID_DATA);
  655. vertex.color = Color(color_src->array[color_pos + 0], color_src->array[color_pos + 1], color_src->array[color_pos + 2], (color_src->stride > 3) ? color_src->array[color_pos + 3] : 1.0);
  656. }
  657. #ifndef NO_UP_AXIS_SWAP
  658. if (collada.state.up_axis == Vector3::AXIS_Z) {
  659. SWAP(vertex.vertex.z, vertex.vertex.y);
  660. vertex.vertex.z = -vertex.vertex.z;
  661. SWAP(vertex.normal.z, vertex.normal.y);
  662. vertex.normal.z = -vertex.normal.z;
  663. SWAP(vertex.tangent.normal.z, vertex.tangent.normal.y);
  664. vertex.tangent.normal.z = -vertex.tangent.normal.z;
  665. }
  666. #endif
  667. vertex.fix_unit_scale(collada);
  668. int index = 0;
  669. //COLLADA_PRINT("vertex: "+vertex.vertex);
  670. if (vertex_set.has(vertex)) {
  671. index = vertex_set.find(vertex)->get().idx;
  672. } else {
  673. index = vertex_set.size();
  674. vertex.idx = index;
  675. vertex_set.insert(vertex);
  676. }
  677. /* if (!vertex_map.has(vertex_index))
  678. vertex_map[vertex_index]=Set<int>();
  679. vertex_map[vertex_index].insert(index); //should be outside..*/
  680. //build triangles if needed
  681. if (j == 0)
  682. prev2[0] = index;
  683. if (j >= 2) {
  684. //insert indices in reverse order (collada uses CCW as frontface)
  685. if (local_xform_mirror) {
  686. indices_list.push_back(prev2[0]);
  687. indices_list.push_back(prev2[1]);
  688. indices_list.push_back(index);
  689. } else {
  690. indices_list.push_back(prev2[0]);
  691. indices_list.push_back(index);
  692. indices_list.push_back(prev2[1]);
  693. }
  694. }
  695. prev2[1] = index;
  696. _prim_ofs += p.vertex_size;
  697. }
  698. }
  699. Vector<Collada::Vertex> vertex_array; //there we go, vertex array
  700. vertex_array.resize(vertex_set.size());
  701. for (Set<Collada::Vertex>::Element *F = vertex_set.front(); F; F = F->next()) {
  702. vertex_array[F->get().idx] = F->get();
  703. }
  704. if (has_weights) {
  705. //if skeleton, localize
  706. Transform local_xform = p_local_xform;
  707. for (int i = 0; i < vertex_array.size(); i++) {
  708. vertex_array[i].vertex = local_xform.xform(vertex_array[i].vertex);
  709. vertex_array[i].normal = local_xform.basis.xform(vertex_array[i].normal).normalized();
  710. vertex_array[i].tangent.normal = local_xform.basis.xform(vertex_array[i].tangent.normal).normalized();
  711. if (local_xform_mirror) {
  712. //i shouldn't do this? wtf?
  713. //vertex_array[i].normal*=-1.0;
  714. //vertex_array[i].tangent.normal*=-1.0;
  715. }
  716. }
  717. }
  718. DVector<int> index_array;
  719. index_array.resize(indices_list.size());
  720. DVector<int>::Write index_arrayw = index_array.write();
  721. int iidx = 0;
  722. for (List<int>::Element *F = indices_list.front(); F; F = F->next()) {
  723. index_arrayw[iidx++] = F->get();
  724. }
  725. index_arrayw = DVector<int>::Write();
  726. /*****************/
  727. /* MAKE SURFACES */
  728. /*****************/
  729. {
  730. Ref<FixedMaterial> material;
  731. //find material
  732. Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
  733. {
  734. if (p_material_map.has(p.material)) {
  735. String target = p_material_map[p.material].target;
  736. if (!material_cache.has(target)) {
  737. Error err = _create_material(target);
  738. if (!err)
  739. material = material_cache[target];
  740. } else
  741. material = material_cache[target];
  742. } else if (p.material != "") {
  743. print_line("Warning, unreferenced material in geometry instance: " + p.material);
  744. }
  745. }
  746. DVector<Vector3> final_vertex_array;
  747. DVector<Vector3> final_normal_array;
  748. DVector<float> final_tangent_array;
  749. DVector<Color> final_color_array;
  750. DVector<Vector3> final_uv_array;
  751. DVector<Vector3> final_uv2_array;
  752. DVector<float> final_bone_array;
  753. DVector<float> final_weight_array;
  754. uint32_t final_format = 0;
  755. //create format
  756. final_format = Mesh::ARRAY_FORMAT_VERTEX | Mesh::ARRAY_FORMAT_INDEX;
  757. if (normal_src) {
  758. final_format |= Mesh::ARRAY_FORMAT_NORMAL;
  759. if (uv_src && binormal_src && tangent_src) {
  760. final_format |= Mesh::ARRAY_FORMAT_TANGENT;
  761. }
  762. }
  763. if (color_src)
  764. final_format |= Mesh::ARRAY_FORMAT_COLOR;
  765. if (uv_src)
  766. final_format |= Mesh::ARRAY_FORMAT_TEX_UV;
  767. if (uv2_src)
  768. final_format |= Mesh::ARRAY_FORMAT_TEX_UV2;
  769. if (has_weights) {
  770. final_format |= Mesh::ARRAY_FORMAT_WEIGHTS;
  771. final_format |= Mesh::ARRAY_FORMAT_BONES;
  772. }
  773. //set arrays
  774. int vlen = vertex_array.size();
  775. { //vertices
  776. DVector<Vector3> varray;
  777. varray.resize(vertex_array.size());
  778. DVector<Vector3>::Write varrayw = varray.write();
  779. for (int k = 0; k < vlen; k++)
  780. varrayw[k] = vertex_array[k].vertex;
  781. varrayw = DVector<Vector3>::Write();
  782. final_vertex_array = varray;
  783. }
  784. if (uv_src) { //compute uv first, may be needed for computing tangent/bionrmal
  785. DVector<Vector3> uvarray;
  786. uvarray.resize(vertex_array.size());
  787. DVector<Vector3>::Write uvarrayw = uvarray.write();
  788. for (int k = 0; k < vlen; k++) {
  789. uvarrayw[k] = vertex_array[k].uv;
  790. }
  791. uvarrayw = DVector<Vector3>::Write();
  792. final_uv_array = uvarray;
  793. }
  794. if (uv2_src) { //compute uv first, may be needed for computing tangent/bionrmal
  795. DVector<Vector3> uv2array;
  796. uv2array.resize(vertex_array.size());
  797. DVector<Vector3>::Write uv2arrayw = uv2array.write();
  798. for (int k = 0; k < vlen; k++) {
  799. uv2arrayw[k] = vertex_array[k].uv2;
  800. }
  801. uv2arrayw = DVector<Vector3>::Write();
  802. final_uv2_array = uv2array;
  803. }
  804. if (normal_src) {
  805. DVector<Vector3> narray;
  806. narray.resize(vertex_array.size());
  807. DVector<Vector3>::Write narrayw = narray.write();
  808. for (int k = 0; k < vlen; k++) {
  809. narrayw[k] = vertex_array[k].normal;
  810. }
  811. narrayw = DVector<Vector3>::Write();
  812. final_normal_array = narray;
  813. //DVector<Vector3> altnaray;
  814. //_generate_normals(index_array,final_vertex_array,altnaray);
  815. //for(int i=0;i<altnaray.size();i++)
  816. // print_line(rtos(altnaray[i].dot(final_normal_array[i])));
  817. } else if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  818. //generate normals (even if unused later)
  819. _generate_normals(index_array, final_vertex_array, final_normal_array);
  820. if (OS::get_singleton()->is_stdout_verbose())
  821. print_line("Collada: Triangle mesh lacks normals, so normals were generated.");
  822. final_format |= Mesh::ARRAY_FORMAT_NORMAL;
  823. }
  824. if (final_normal_array.size() && uv_src && binormal_src && tangent_src && !force_make_tangents) {
  825. DVector<real_t> tarray;
  826. tarray.resize(vertex_array.size() * 4);
  827. DVector<real_t>::Write tarrayw = tarray.write();
  828. for (int k = 0; k < vlen; k++) {
  829. tarrayw[k * 4 + 0] = vertex_array[k].tangent.normal.x;
  830. tarrayw[k * 4 + 1] = vertex_array[k].tangent.normal.y;
  831. tarrayw[k * 4 + 2] = vertex_array[k].tangent.normal.z;
  832. tarrayw[k * 4 + 3] = vertex_array[k].tangent.d;
  833. }
  834. tarrayw = DVector<real_t>::Write();
  835. final_tangent_array = tarray;
  836. } else if (final_normal_array.size() && primitive == Mesh::PRIMITIVE_TRIANGLES && final_uv_array.size() && (force_make_tangents || (material.is_valid() && material->get_texture(FixedMaterial::PARAM_NORMAL).is_valid()))) {
  837. //if this uses triangles, there are uvs and the material is using a normalmap, generate tangents and binormals, because they WILL be needed
  838. //generate binormals/tangents
  839. _generate_tangents_and_binormals(index_array, final_vertex_array, final_uv_array, final_normal_array, final_tangent_array);
  840. final_format |= Mesh::ARRAY_FORMAT_TANGENT;
  841. if (OS::get_singleton()->is_stdout_verbose())
  842. print_line("Collada: Triangle mesh lacks tangents (And normalmap was used), so tangents were generated.");
  843. }
  844. if (color_src) {
  845. DVector<Color> colorarray;
  846. colorarray.resize(vertex_array.size());
  847. DVector<Color>::Write colorarrayw = colorarray.write();
  848. for (int k = 0; k < vlen; k++) {
  849. colorarrayw[k] = vertex_array[k].color;
  850. }
  851. colorarrayw = DVector<Color>::Write();
  852. final_color_array = colorarray;
  853. }
  854. if (has_weights) {
  855. DVector<float> weightarray;
  856. DVector<float> bonearray;
  857. weightarray.resize(vertex_array.size() * 4);
  858. DVector<float>::Write weightarrayw = weightarray.write();
  859. bonearray.resize(vertex_array.size() * 4);
  860. DVector<float>::Write bonearrayw = bonearray.write();
  861. for (int k = 0; k < vlen; k++) {
  862. float sum = 0;
  863. for (int l = 0; l < VS::ARRAY_WEIGHTS_SIZE; l++) {
  864. if (l < vertex_array[k].weights.size()) {
  865. weightarrayw[k * VS::ARRAY_WEIGHTS_SIZE + l] = vertex_array[k].weights[l].weight;
  866. sum += weightarrayw[k * VS::ARRAY_WEIGHTS_SIZE + l];
  867. bonearrayw[k * VS::ARRAY_WEIGHTS_SIZE + l] = vertex_array[k].weights[l].bone_idx;
  868. //COLLADA_PRINT(itos(k)+": "+rtos(bonearrayw[k*VS::ARRAY_WEIGHTS_SIZE+l])+":"+rtos(weightarray[k*VS::ARRAY_WEIGHTS_SIZE+l]));
  869. } else {
  870. weightarrayw[k * VS::ARRAY_WEIGHTS_SIZE + l] = 0;
  871. bonearrayw[k * VS::ARRAY_WEIGHTS_SIZE + l] = 0;
  872. }
  873. }
  874. // if (sum<0.8)
  875. // COLLADA_PRINT("ERROR SUMMING INDEX "+itos(k)+" had weights: "+itos(vertex_array[k].weights.size()));
  876. }
  877. weightarrayw = DVector<float>::Write();
  878. bonearrayw = DVector<float>::Write();
  879. final_weight_array = weightarray;
  880. final_bone_array = bonearray;
  881. }
  882. ////////////////////////////
  883. // FINALLY CREATE SUFRACE //
  884. ////////////////////////////
  885. Array d;
  886. d.resize(VS::ARRAY_MAX);
  887. d[Mesh::ARRAY_INDEX] = index_array;
  888. d[Mesh::ARRAY_VERTEX] = final_vertex_array;
  889. if (final_normal_array.size())
  890. d[Mesh::ARRAY_NORMAL] = final_normal_array;
  891. if (final_tangent_array.size())
  892. d[Mesh::ARRAY_TANGENT] = final_tangent_array;
  893. if (final_uv_array.size())
  894. d[Mesh::ARRAY_TEX_UV] = final_uv_array;
  895. if (final_uv2_array.size())
  896. d[Mesh::ARRAY_TEX_UV2] = final_uv2_array;
  897. if (final_color_array.size())
  898. d[Mesh::ARRAY_COLOR] = final_color_array;
  899. if (final_weight_array.size())
  900. d[Mesh::ARRAY_WEIGHTS] = final_weight_array;
  901. if (final_bone_array.size())
  902. d[Mesh::ARRAY_BONES] = final_bone_array;
  903. Array mr;
  904. ////////////////////////////
  905. // THEN THE MORPH TARGETS //
  906. ////////////////////////////
  907. #if 0
  908. if (p_morph_data) {
  909. //add morphie target
  910. ERR_FAIL_COND_V( !p_morph_data->targets.has("MORPH_TARGET"), ERR_INVALID_DATA );
  911. String mt = p_morph_data->targets["MORPH_TARGET"];
  912. ERR_FAIL_COND_V( !p_morph_data->sources.has(mt), ERR_INVALID_DATA);
  913. int morph_targets = p_morph_data->sources[mt].sarray.size();
  914. mr.resize(morph_targets);
  915. for(int j=0;j<morph_targets;j++) {
  916. Array mrt;
  917. mrt.resize(VS::ARRAY_MAX);
  918. String target = p_morph_data->sources[mt].sarray[j];
  919. ERR_FAIL_COND_V( !collada.state.mesh_data_map.has(target), ERR_INVALID_DATA );
  920. String name = collada.state.mesh_data_map[target].name;
  921. Collada::MeshData &md = collada.state.mesh_data_map[target];
  922. // collada in itself supports morphing everything. However, the spec is unclear and no examples or exporters that
  923. // morph anything but "POSITIONS" seem to exit. Because of this, normals and binormals/tangents have to be regenerated here,
  924. // which may result in inaccurate (but most of the time good enough) results.
  925. DVector<Vector3> vertices;
  926. vertices.resize(vlen);
  927. ERR_FAIL_COND_V( md.vertices.size() != 1, ERR_INVALID_DATA);
  928. String vertex_src_id=md.vertices.front()->key();
  929. ERR_FAIL_COND_V(!md.vertices[vertex_src_id].sources.has("POSITION"),ERR_INVALID_DATA);
  930. String position_src_id = md.vertices[vertex_src_id].sources["POSITION"];
  931. ERR_FAIL_COND_V(!md.sources.has(position_src_id),ERR_INVALID_DATA);
  932. const Collada::MeshData::Source *m=&md.sources[position_src_id];
  933. ERR_FAIL_COND_V( m->array.size() != vertex_src->array.size(), ERR_INVALID_DATA);
  934. int stride=m->stride;
  935. if (stride==0)
  936. stride=3;
  937. //read vertices from morph target
  938. DVector<Vector3>::Write vertw = vertices.write();
  939. for(int m_i=0;m_i<m->array.size()/stride;m_i++) {
  940. int pos = m_i*stride;
  941. Vector3 vtx( m->array[pos+0], m->array[pos+1], m->array[pos+2] );
  942. #ifndef NO_UP_AXIS_SWAP
  943. if (collada.state.up_axis==Vector3::AXIS_Z) {
  944. SWAP( vtx.z, vtx.y );
  945. vtx.z = -vtx.z;
  946. }
  947. #endif
  948. Collada::Vertex vertex;
  949. vertex.vertex=vtx;
  950. vertex.fix_unit_scale(collada);
  951. vtx=vertex.vertex;
  952. vtx = p_local_xform.xform(vtx);
  953. if (vertex_map.has(m_i)) { //vertex may no longer be here, don't bother converting
  954. for (Set<int> ::Element *E=vertex_map[m_i].front() ; E; E=E->next() ) {
  955. vertw[E->get()]=vtx;
  956. }
  957. }
  958. }
  959. //vertices are in place, now generate everything else
  960. vertw = DVector<Vector3>::Write();
  961. DVector<Vector3> normals;
  962. DVector<float> tangents;
  963. print_line("vertex source id: "+vertex_src_id);
  964. if(md.vertices[vertex_src_id].sources.has("NORMAL")){
  965. //has normals
  966. normals.resize(vlen);
  967. //std::cout << "has normals" << std::endl;
  968. String normal_src_id = md.vertices[vertex_src_id].sources["NORMAL"];
  969. //std::cout << "normals source: "<< normal_src_id.utf8().get_data() <<std::endl;
  970. ERR_FAIL_COND_V(!md.sources.has(normal_src_id),ERR_INVALID_DATA);
  971. const Collada::MeshData::Source *m=&md.sources[normal_src_id];
  972. ERR_FAIL_COND_V( m->array.size() != vertex_src->array.size(), ERR_INVALID_DATA);
  973. int stride=m->stride;
  974. if (stride==0)
  975. stride=3;
  976. //read normals from morph target
  977. DVector<Vector3>::Write vertw = normals.write();
  978. for(int m_i=0;m_i<m->array.size()/stride;m_i++) {
  979. int pos = m_i*stride;
  980. Vector3 vtx( m->array[pos+0], m->array[pos+1], m->array[pos+2] );
  981. #ifndef NO_UP_AXIS_SWAP
  982. if (collada.state.up_axis==Vector3::AXIS_Z) {
  983. SWAP( vtx.z, vtx.y );
  984. vtx.z = -vtx.z;
  985. }
  986. #endif
  987. Collada::Vertex vertex;
  988. vertex.vertex=vtx;
  989. vertex.fix_unit_scale(collada);
  990. vtx=vertex.vertex;
  991. vtx = p_local_xform.xform(vtx);
  992. if (vertex_map.has(m_i)) { //vertex may no longer be here, don't bother converting
  993. for (Set<int> ::Element *E=vertex_map[m_i].front() ; E; E=E->next() ) {
  994. vertw[E->get()]=vtx;
  995. }
  996. }
  997. }
  998. print_line("using built-in normals");
  999. }else{
  1000. print_line("generating normals");
  1001. _generate_normals(index_array,vertices,normals);//no normals
  1002. }
  1003. if (final_tangent_array.size() && final_uv_array.size()) {
  1004. _generate_tangents_and_binormals(index_array,vertices,final_uv_array,normals,tangents);
  1005. }
  1006. mrt[Mesh::ARRAY_VERTEX]=vertices;
  1007. mrt[Mesh::ARRAY_NORMAL]=normals;
  1008. if (tangents.size())
  1009. mrt[Mesh::ARRAY_TANGENT]=tangents;
  1010. if (final_uv_array.size())
  1011. mrt[Mesh::ARRAY_TEX_UV]=final_uv_array;
  1012. if (final_uv2_array.size())
  1013. mrt[Mesh::ARRAY_TEX_UV2]=final_uv2_array;
  1014. if (final_color_array.size())
  1015. mrt[Mesh::ARRAY_COLOR]=final_color_array;
  1016. mr[j]=mrt;
  1017. }
  1018. }
  1019. #endif
  1020. for (int mi = 0; mi < p_morph_meshes.size(); mi++) {
  1021. // print_line("want surface "+itos(mi)+" has "+itos(p_morph_meshes[mi]->get_surface_count()));
  1022. Array a = p_morph_meshes[mi]->surface_get_arrays(surface);
  1023. a[Mesh::ARRAY_BONES] = Variant();
  1024. a[Mesh::ARRAY_WEIGHTS] = Variant();
  1025. a[Mesh::ARRAY_INDEX] = Variant();
  1026. //a.resize(Mesh::ARRAY_MAX); //no need for index
  1027. mr.push_back(a);
  1028. }
  1029. p_mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES, d, mr);
  1030. if (material.is_valid()) {
  1031. p_mesh->surface_set_material(surface, material);
  1032. p_mesh->surface_set_name(surface, material->get_name());
  1033. }
  1034. }
  1035. /*****************/
  1036. /* FIND MATERIAL */
  1037. /*****************/
  1038. surface++;
  1039. }
  1040. return OK;
  1041. }
  1042. Error ColladaImport::_create_resources(Collada::Node *p_node) {
  1043. if (p_node->type == Collada::Node::TYPE_GEOMETRY && node_map.has(p_node->id)) {
  1044. Spatial *node = node_map[p_node->id].node;
  1045. Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(p_node);
  1046. if (node->cast_to<Path>()) {
  1047. Path *path = node->cast_to<Path>();
  1048. String curve = ng->source;
  1049. if (curve_cache.has(ng->source)) {
  1050. path->set_curve(curve_cache[ng->source]);
  1051. } else {
  1052. Ref<Curve3D> c = memnew(Curve3D);
  1053. const Collada::CurveData &cd = collada.state.curve_data_map[ng->source];
  1054. ERR_FAIL_COND_V(!cd.control_vertices.has("POSITION"), ERR_INVALID_DATA);
  1055. ERR_FAIL_COND_V(!cd.control_vertices.has("IN_TANGENT"), ERR_INVALID_DATA);
  1056. ERR_FAIL_COND_V(!cd.control_vertices.has("OUT_TANGENT"), ERR_INVALID_DATA);
  1057. ERR_FAIL_COND_V(!cd.control_vertices.has("INTERPOLATION"), ERR_INVALID_DATA);
  1058. ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["POSITION"]), ERR_INVALID_DATA);
  1059. const Collada::CurveData::Source &vertices = cd.sources[cd.control_vertices["POSITION"]];
  1060. ERR_FAIL_COND_V(vertices.stride != 3, ERR_INVALID_DATA);
  1061. ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["IN_TANGENT"]), ERR_INVALID_DATA);
  1062. const Collada::CurveData::Source &in_tangents = cd.sources[cd.control_vertices["IN_TANGENT"]];
  1063. ERR_FAIL_COND_V(in_tangents.stride != 3, ERR_INVALID_DATA);
  1064. ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["OUT_TANGENT"]), ERR_INVALID_DATA);
  1065. const Collada::CurveData::Source &out_tangents = cd.sources[cd.control_vertices["OUT_TANGENT"]];
  1066. ERR_FAIL_COND_V(out_tangents.stride != 3, ERR_INVALID_DATA);
  1067. ERR_FAIL_COND_V(!cd.sources.has(cd.control_vertices["INTERPOLATION"]), ERR_INVALID_DATA);
  1068. const Collada::CurveData::Source &interps = cd.sources[cd.control_vertices["INTERPOLATION"]];
  1069. ERR_FAIL_COND_V(interps.stride != 1, ERR_INVALID_DATA);
  1070. const Collada::CurveData::Source *tilts = NULL;
  1071. if (cd.control_vertices.has("TILT") && cd.sources.has(cd.control_vertices["TILT"]))
  1072. tilts = &cd.sources[cd.control_vertices["TILT"]];
  1073. if (tilts) {
  1074. print_line("FOUND TILTS!!!");
  1075. }
  1076. int pc = vertices.array.size() / 3;
  1077. for (int i = 0; i < pc; i++) {
  1078. Vector3 pos(vertices.array[i * 3 + 0], vertices.array[i * 3 + 1], vertices.array[i * 3 + 2]);
  1079. Vector3 in(in_tangents.array[i * 3 + 0], in_tangents.array[i * 3 + 1], in_tangents.array[i * 3 + 2]);
  1080. Vector3 out(out_tangents.array[i * 3 + 0], out_tangents.array[i * 3 + 1], out_tangents.array[i * 3 + 2]);
  1081. #ifndef NO_UP_AXIS_SWAP
  1082. if (collada.state.up_axis == Vector3::AXIS_Z) {
  1083. SWAP(pos.y, pos.z);
  1084. pos.z = -pos.z;
  1085. SWAP(in.y, in.z);
  1086. in.z = -in.z;
  1087. SWAP(out.y, out.z);
  1088. out.z = -out.z;
  1089. }
  1090. #endif
  1091. pos *= collada.state.unit_scale;
  1092. in *= collada.state.unit_scale;
  1093. out *= collada.state.unit_scale;
  1094. c->add_point(pos, in - pos, out - pos);
  1095. if (tilts)
  1096. c->set_point_tilt(i, tilts->array[i]);
  1097. }
  1098. curve_cache[ng->source] = c;
  1099. path->set_curve(c);
  1100. }
  1101. }
  1102. if (node->cast_to<MeshInstance>()) {
  1103. Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(p_node);
  1104. MeshInstance *mi = node->cast_to<MeshInstance>();
  1105. ERR_FAIL_COND_V(!mi, ERR_BUG);
  1106. Collada::SkinControllerData *skin = NULL;
  1107. Collada::MorphControllerData *morph = NULL;
  1108. String meshid;
  1109. Transform apply_xform;
  1110. Vector<int> bone_remap;
  1111. Vector<Ref<Mesh> > morphs;
  1112. print_line("mesh: " + String(mi->get_name()));
  1113. if (ng->controller) {
  1114. print_line("has controller");
  1115. String ngsource = ng->source;
  1116. if (collada.state.skin_controller_data_map.has(ngsource)) {
  1117. ERR_FAIL_COND_V(!collada.state.skin_controller_data_map.has(ngsource), ERR_INVALID_DATA);
  1118. skin = &collada.state.skin_controller_data_map[ngsource];
  1119. Vector<String> skeletons = ng->skeletons;
  1120. ERR_FAIL_COND_V(skeletons.empty(), ERR_INVALID_DATA);
  1121. String skname = skeletons[0];
  1122. if (!node_map.has(skname)) {
  1123. print_line("no node for skeleton " + skname);
  1124. }
  1125. ERR_FAIL_COND_V(!node_map.has(skname), ERR_INVALID_DATA);
  1126. NodeMap nmsk = node_map[skname];
  1127. Skeleton *sk = nmsk.node->cast_to<Skeleton>();
  1128. ERR_FAIL_COND_V(!sk, ERR_INVALID_DATA);
  1129. ERR_FAIL_COND_V(!skeleton_bone_map.has(sk), ERR_INVALID_DATA);
  1130. Map<String, int> &bone_remap_map = skeleton_bone_map[sk];
  1131. meshid = skin->base;
  1132. if (collada.state.morph_controller_data_map.has(meshid)) {
  1133. //it's a morph!!
  1134. morph = &collada.state.morph_controller_data_map[meshid];
  1135. ngsource = meshid;
  1136. meshid = morph->mesh;
  1137. } else {
  1138. ngsource = "";
  1139. }
  1140. if (apply_mesh_xform_to_vertices) {
  1141. apply_xform = collada.fix_transform(p_node->default_transform);
  1142. node->set_transform(Transform());
  1143. } else {
  1144. apply_xform = Transform();
  1145. }
  1146. Collada::SkinControllerData::Source *joint_src = NULL;
  1147. ERR_FAIL_COND_V(!skin->weights.sources.has("JOINT"), ERR_INVALID_DATA);
  1148. String joint_id = skin->weights.sources["JOINT"].source;
  1149. ERR_FAIL_COND_V(!skin->sources.has(joint_id), ERR_INVALID_DATA);
  1150. joint_src = &skin->sources[joint_id];
  1151. bone_remap.resize(joint_src->sarray.size());
  1152. for (int i = 0; i < bone_remap.size(); i++) {
  1153. String str = joint_src->sarray[i];
  1154. if (!bone_remap_map.has(str)) {
  1155. print_line("bone not found for remap: " + str);
  1156. print_line("in skeleton: " + skname);
  1157. }
  1158. ERR_FAIL_COND_V(!bone_remap_map.has(str), ERR_INVALID_DATA);
  1159. bone_remap[i] = bone_remap_map[str];
  1160. }
  1161. }
  1162. if (collada.state.morph_controller_data_map.has(ngsource)) {
  1163. print_line("is morph " + ngsource);
  1164. //it's a morph!!
  1165. morph = &collada.state.morph_controller_data_map[ngsource];
  1166. meshid = morph->mesh;
  1167. printf("KKmorph: %p\n", morph);
  1168. print_line("morph mshid: " + meshid);
  1169. Vector<String> targets;
  1170. morph->targets.has("MORPH_TARGET");
  1171. String target = morph->targets["MORPH_TARGET"];
  1172. bool valid = false;
  1173. if (morph->sources.has(target)) {
  1174. valid = true;
  1175. Vector<String> names = morph->sources[target].sarray;
  1176. for (int i = 0; i < names.size(); i++) {
  1177. String meshid = names[i];
  1178. if (collada.state.mesh_data_map.has(meshid)) {
  1179. Ref<Mesh> mesh = Ref<Mesh>(memnew(Mesh));
  1180. const Collada::MeshData &meshdata = collada.state.mesh_data_map[meshid];
  1181. Error err = _create_mesh_surfaces(false, mesh, ng->material_map, meshdata, apply_xform, bone_remap, skin, NULL);
  1182. ERR_FAIL_COND_V(err, err);
  1183. morphs.push_back(mesh);
  1184. } else {
  1185. valid = false;
  1186. }
  1187. }
  1188. }
  1189. if (!valid)
  1190. morphs.clear();
  1191. ngsource = "";
  1192. }
  1193. if (ngsource != "") {
  1194. ERR_EXPLAIN("Controller Instance Source '" + ngsource + "' is neither skin or morph!");
  1195. ERR_FAIL_V(ERR_INVALID_DATA);
  1196. }
  1197. } else {
  1198. meshid = ng->source;
  1199. }
  1200. Ref<Mesh> mesh;
  1201. if (mesh_cache.has(meshid)) {
  1202. mesh = mesh_cache[meshid];
  1203. } else {
  1204. if (collada.state.mesh_data_map.has(meshid)) {
  1205. //bleh, must ignore invalid
  1206. ERR_FAIL_COND_V(!collada.state.mesh_data_map.has(meshid), ERR_INVALID_DATA);
  1207. mesh = Ref<Mesh>(memnew(Mesh));
  1208. const Collada::MeshData &meshdata = collada.state.mesh_data_map[meshid];
  1209. mesh->set_name(meshdata.name);
  1210. Error err = _create_mesh_surfaces(morphs.size() == 0, mesh, ng->material_map, meshdata, apply_xform, bone_remap, skin, morph, morphs);
  1211. ERR_FAIL_COND_V(err, err);
  1212. mesh_cache[meshid] = mesh;
  1213. } else {
  1214. print_line("Warning, will not import geometry: " + meshid);
  1215. }
  1216. }
  1217. if (!mesh.is_null()) {
  1218. mi->set_mesh(mesh);
  1219. }
  1220. }
  1221. }
  1222. for (int i = 0; i < p_node->children.size(); i++) {
  1223. Error err = _create_resources(p_node->children[i]);
  1224. if (err)
  1225. return err;
  1226. }
  1227. return OK;
  1228. }
  1229. Error ColladaImport::load(const String &p_path, int p_flags, bool p_force_make_tangents) {
  1230. Error err = collada.load(p_path, p_flags);
  1231. ERR_FAIL_COND_V(err, err);
  1232. force_make_tangents = p_force_make_tangents;
  1233. ERR_FAIL_COND_V(!collada.state.visual_scene_map.has(collada.state.root_visual_scene), ERR_INVALID_DATA);
  1234. Collada::VisualScene &vs = collada.state.visual_scene_map[collada.state.root_visual_scene];
  1235. scene = memnew(Spatial); // root
  1236. //determine what's going on with the lights
  1237. for (int i = 0; i < vs.root_nodes.size(); i++) {
  1238. _pre_process_lights(vs.root_nodes[i]);
  1239. }
  1240. //import scene
  1241. for (int i = 0; i < vs.root_nodes.size(); i++) {
  1242. Error err = _create_scene_skeletons(vs.root_nodes[i]);
  1243. if (err != OK) {
  1244. memdelete(scene);
  1245. ERR_FAIL_COND_V(err, err);
  1246. }
  1247. }
  1248. for (int i = 0; i < vs.root_nodes.size(); i++) {
  1249. Error err = _create_scene(vs.root_nodes[i], scene);
  1250. if (err != OK) {
  1251. memdelete(scene);
  1252. ERR_FAIL_COND_V(err, err);
  1253. }
  1254. Error err2 = _create_resources(vs.root_nodes[i]);
  1255. if (err2 != OK) {
  1256. memdelete(scene);
  1257. ERR_FAIL_COND_V(err2, err2);
  1258. }
  1259. }
  1260. //optatively, set unit scale in the root
  1261. scene->set_transform(collada.get_root_transform());
  1262. return OK;
  1263. }
  1264. void ColladaImport::_fix_param_animation_tracks() {
  1265. for (Map<String, Collada::Node *>::Element *E = collada.state.scene_map.front(); E; E = E->next()) {
  1266. Collada::Node *n = E->get();
  1267. switch (n->type) {
  1268. case Collada::Node::TYPE_NODE: {
  1269. // ? do nothing
  1270. } break;
  1271. case Collada::Node::TYPE_JOINT: {
  1272. } break;
  1273. case Collada::Node::TYPE_SKELETON: {
  1274. } break;
  1275. case Collada::Node::TYPE_LIGHT: {
  1276. } break;
  1277. case Collada::Node::TYPE_CAMERA: {
  1278. } break;
  1279. case Collada::Node::TYPE_GEOMETRY: {
  1280. Collada::NodeGeometry *ng = static_cast<Collada::NodeGeometry *>(n);
  1281. // test source(s)
  1282. String source = ng->source;
  1283. while (source != "") {
  1284. if (collada.state.skin_controller_data_map.has(source)) {
  1285. const Collada::SkinControllerData &skin = collada.state.skin_controller_data_map[source];
  1286. //nothing to animate here i think
  1287. source = skin.base;
  1288. } else if (collada.state.morph_controller_data_map.has(source)) {
  1289. const Collada::MorphControllerData &morph = collada.state.morph_controller_data_map[source];
  1290. if (morph.targets.has("MORPH_WEIGHT") && morph.targets.has("MORPH_TARGET")) {
  1291. String weights = morph.targets["MORPH_WEIGHT"];
  1292. String targets = morph.targets["MORPH_TARGET"];
  1293. //fails here
  1294. if (morph.sources.has(targets) && morph.sources.has(weights)) {
  1295. const Collada::MorphControllerData::Source &weight_src = morph.sources[weights];
  1296. const Collada::MorphControllerData::Source &target_src = morph.sources[targets];
  1297. ERR_FAIL_COND(weight_src.array.size() != target_src.sarray.size());
  1298. for (int i = 0; i < weight_src.array.size(); i++) {
  1299. String track_name = weights + "(" + itos(i) + ")";
  1300. String mesh_name = target_src.sarray[i];
  1301. if (collada.state.mesh_name_map.has(mesh_name) && collada.state.referenced_tracks.has(track_name)) {
  1302. const Vector<int> &rt = collada.state.referenced_tracks[track_name];
  1303. for (int rti = 0; rti < rt.size(); rti++) {
  1304. Collada::AnimationTrack *at = &collada.state.animation_tracks[rt[rti]];
  1305. at->target = E->key();
  1306. at->param = "morph/" + collada.state.mesh_name_map[mesh_name];
  1307. at->property = true;
  1308. //at->param
  1309. }
  1310. }
  1311. }
  1312. }
  1313. }
  1314. source = morph.mesh;
  1315. } else {
  1316. source = ""; // for now nothing else supported
  1317. }
  1318. }
  1319. } break;
  1320. }
  1321. }
  1322. }
  1323. void ColladaImport::create_animations(bool p_make_tracks_in_all_bones, bool p_import_value_tracks) {
  1324. _fix_param_animation_tracks();
  1325. for (int i = 0; i < collada.state.animation_clips.size(); i++) {
  1326. for (int j = 0; j < collada.state.animation_clips[i].tracks.size(); j++)
  1327. tracks_in_clips.insert(collada.state.animation_clips[i].tracks[j]);
  1328. }
  1329. for (int i = 0; i < collada.state.animation_tracks.size(); i++) {
  1330. Collada::AnimationTrack &at = collada.state.animation_tracks[i];
  1331. //print_line("CHANNEL: "+at.target+" PARAM: "+at.param);
  1332. String node;
  1333. if (!node_map.has(at.target)) {
  1334. if (node_name_map.has(at.target)) {
  1335. node = node_name_map[at.target];
  1336. } else {
  1337. print_line("Coudlnt find node: " + at.target);
  1338. continue;
  1339. }
  1340. } else {
  1341. node = at.target;
  1342. }
  1343. if (at.property) {
  1344. valid_animated_properties.push_back(i);
  1345. } else {
  1346. node_map[node].anim_tracks.push_back(i);
  1347. valid_animated_nodes.insert(node);
  1348. }
  1349. }
  1350. create_animation(-1, p_make_tracks_in_all_bones, p_import_value_tracks);
  1351. //print_line("clipcount: "+itos(collada.state.animation_clips.size()));
  1352. for (int i = 0; i < collada.state.animation_clips.size(); i++)
  1353. create_animation(i, p_make_tracks_in_all_bones, p_import_value_tracks);
  1354. }
  1355. void ColladaImport::create_animation(int p_clip, bool p_make_tracks_in_all_bones, bool p_import_value_tracks) {
  1356. Ref<Animation> animation = Ref<Animation>(memnew(Animation));
  1357. if (p_clip == -1) {
  1358. //print_line("default");
  1359. animation->set_name("default");
  1360. } else {
  1361. //print_line("clip name: "+collada.state.animation_clips[p_clip].name);
  1362. animation->set_name(collada.state.animation_clips[p_clip].name);
  1363. }
  1364. for (Map<String, NodeMap>::Element *E = node_map.front(); E; E = E->next()) {
  1365. if (E->get().bone < 0)
  1366. continue;
  1367. bones_with_animation[E->key()] = false;
  1368. }
  1369. //store and validate tracks
  1370. if (p_clip == -1) {
  1371. //main anim
  1372. }
  1373. Set<int> track_filter;
  1374. if (p_clip == -1) {
  1375. for (int i = 0; i < collada.state.animation_clips.size(); i++) {
  1376. int tc = collada.state.animation_clips[i].tracks.size();
  1377. for (int j = 0; j < tc; j++) {
  1378. String n = collada.state.animation_clips[i].tracks[j];
  1379. if (collada.state.by_id_tracks.has(n)) {
  1380. const Vector<int> &ti = collada.state.by_id_tracks[n];
  1381. for (int k = 0; k < ti.size(); k++) {
  1382. track_filter.insert(ti[k]);
  1383. }
  1384. }
  1385. }
  1386. }
  1387. } else {
  1388. int tc = collada.state.animation_clips[p_clip].tracks.size();
  1389. for (int j = 0; j < tc; j++) {
  1390. String n = collada.state.animation_clips[p_clip].tracks[j];
  1391. if (collada.state.by_id_tracks.has(n)) {
  1392. const Vector<int> &ti = collada.state.by_id_tracks[n];
  1393. for (int k = 0; k < ti.size(); k++) {
  1394. track_filter.insert(ti[k]);
  1395. }
  1396. }
  1397. }
  1398. }
  1399. //animation->set_loop(true);
  1400. //create animation tracks
  1401. Vector<float> base_snapshots;
  1402. float f = 0;
  1403. float snapshot_interval = 1.0 / bake_fps; //should be customizable somewhere...
  1404. float anim_length = collada.state.animation_length;
  1405. if (p_clip >= 0 && collada.state.animation_clips[p_clip].end)
  1406. anim_length = collada.state.animation_clips[p_clip].end;
  1407. while (f < anim_length) {
  1408. base_snapshots.push_back(f);
  1409. f += snapshot_interval;
  1410. if (f >= anim_length) {
  1411. base_snapshots.push_back(anim_length);
  1412. }
  1413. }
  1414. //print_line("anim len: "+rtos(anim_length));
  1415. animation->set_length(anim_length);
  1416. bool tracks_found = false;
  1417. for (Set<String>::Element *E = valid_animated_nodes.front(); E; E = E->next()) {
  1418. // take snapshots
  1419. if (!collada.state.scene_map.has(E->get())) {
  1420. continue;
  1421. }
  1422. NodeMap &nm = node_map[E->get()];
  1423. String path = scene->get_path_to(nm.node);
  1424. if (nm.bone >= 0) {
  1425. Skeleton *sk = static_cast<Skeleton *>(nm.node);
  1426. String name = sk->get_bone_name(nm.bone);
  1427. path = path + ":" + name;
  1428. }
  1429. bool found_anim = false;
  1430. Collada::Node *cn = collada.state.scene_map[E->get()];
  1431. if (cn->ignore_anim) {
  1432. continue;
  1433. }
  1434. animation->add_track(Animation::TYPE_TRANSFORM);
  1435. int track = animation->get_track_count() - 1;
  1436. animation->track_set_path(track, path);
  1437. animation->track_set_imported(track, true); //helps merging later
  1438. Vector<float> snapshots = base_snapshots;
  1439. if (nm.anim_tracks.size() == 1) {
  1440. //use snapshot keys from anim track instead, because this was most likely exported baked
  1441. Collada::AnimationTrack &at = collada.state.animation_tracks[nm.anim_tracks.front()->get()];
  1442. snapshots.clear();
  1443. for (int i = 0; i < at.keys.size(); i++)
  1444. snapshots.push_back(at.keys[i].time);
  1445. }
  1446. for (int i = 0; i < snapshots.size(); i++) {
  1447. for (List<int>::Element *ET = nm.anim_tracks.front(); ET; ET = ET->next()) {
  1448. //apply tracks
  1449. if (p_clip == -1) {
  1450. if (track_filter.has(ET->get())) {
  1451. continue;
  1452. }
  1453. } else {
  1454. if (!track_filter.has(ET->get()))
  1455. continue;
  1456. }
  1457. found_anim = true;
  1458. Collada::AnimationTrack &at = collada.state.animation_tracks[ET->get()];
  1459. int xform_idx = -1;
  1460. for (int j = 0; j < cn->xform_list.size(); j++) {
  1461. if (cn->xform_list[j].id == at.param) {
  1462. xform_idx = j;
  1463. break;
  1464. }
  1465. }
  1466. if (xform_idx == -1) {
  1467. print_line("couldnt find matching node " + at.target + " xform for track " + at.param);
  1468. continue;
  1469. }
  1470. ERR_CONTINUE(xform_idx == -1);
  1471. Vector<float> data = at.get_value_at_time(snapshots[i]);
  1472. ERR_CONTINUE(data.empty());
  1473. Collada::Node::XForm &xf = cn->xform_list[xform_idx];
  1474. if (at.component == "ANGLE") {
  1475. ERR_CONTINUE(data.size() != 1);
  1476. ERR_CONTINUE(xf.op != Collada::Node::XForm::OP_ROTATE);
  1477. ERR_CONTINUE(xf.data.size() < 4);
  1478. xf.data[3] = data[0];
  1479. } else if (at.component == "X" || at.component == "Y" || at.component == "Z") {
  1480. int cn = at.component[0] - 'X';
  1481. ERR_CONTINUE(cn >= xf.data.size());
  1482. ERR_CONTINUE(data.size() > 1);
  1483. xf.data[cn] = data[0];
  1484. } else if (data.size() == xf.data.size()) {
  1485. xf.data = data;
  1486. } else {
  1487. if (data.size() != xf.data.size()) {
  1488. print_line("component " + at.component + " datasize " + itos(data.size()) + " xfdatasize " + itos(xf.data.size()));
  1489. }
  1490. ERR_CONTINUE(data.size() != xf.data.size());
  1491. }
  1492. }
  1493. Transform xform = cn->compute_transform(collada);
  1494. xform = collada.fix_transform(xform) * cn->post_transform;
  1495. if (nm.bone >= 0) {
  1496. //make bone transform relative to rest (in case of skeleton)
  1497. Skeleton *sk = nm.node->cast_to<Skeleton>();
  1498. if (sk) {
  1499. xform = sk->get_bone_rest(nm.bone).affine_inverse() * xform;
  1500. } else {
  1501. ERR_PRINT("INVALID SKELETON!!!!");
  1502. }
  1503. }
  1504. Quat q = xform.basis;
  1505. q.normalize();
  1506. Vector3 s = xform.basis.get_scale();
  1507. Vector3 l = xform.origin;
  1508. animation->transform_track_insert_key(track, snapshots[i], l, q, s);
  1509. }
  1510. if (nm.bone >= 0) {
  1511. if (found_anim)
  1512. bones_with_animation[E->get()] = true;
  1513. }
  1514. if (found_anim)
  1515. tracks_found = true;
  1516. else {
  1517. animation->remove_track(track);
  1518. }
  1519. }
  1520. if (p_make_tracks_in_all_bones) {
  1521. //some bones may lack animation, but since we don't store pose as a property, we must add keyframes!
  1522. for (Map<String, bool>::Element *E = bones_with_animation.front(); E; E = E->next()) {
  1523. if (E->get())
  1524. continue;
  1525. //print_line("BONE LACKS ANIM: "+E->key());
  1526. NodeMap &nm = node_map[E->key()];
  1527. String path = scene->get_path_to(nm.node);
  1528. ERR_CONTINUE(nm.bone < 0);
  1529. Skeleton *sk = static_cast<Skeleton *>(nm.node);
  1530. String name = sk->get_bone_name(nm.bone);
  1531. path = path + ":" + name;
  1532. Collada::Node *cn = collada.state.scene_map[E->key()];
  1533. if (cn->ignore_anim) {
  1534. print_line("warning, ignoring animation on node: " + path);
  1535. continue;
  1536. }
  1537. animation->add_track(Animation::TYPE_TRANSFORM);
  1538. int track = animation->get_track_count() - 1;
  1539. animation->track_set_path(track, path);
  1540. animation->track_set_imported(track, true); //helps merging later
  1541. Transform xform = cn->compute_transform(collada);
  1542. xform = collada.fix_transform(xform) * cn->post_transform;
  1543. xform = sk->get_bone_rest(nm.bone).affine_inverse() * xform;
  1544. Quat q = xform.basis;
  1545. q.normalize();
  1546. Vector3 s = xform.basis.get_scale();
  1547. Vector3 l = xform.origin;
  1548. animation->transform_track_insert_key(track, 0, l, q, s);
  1549. tracks_found = true;
  1550. }
  1551. }
  1552. if (p_import_value_tracks) {
  1553. for (int i = 0; i < valid_animated_properties.size(); i++) {
  1554. int ti = valid_animated_properties[i];
  1555. if (p_clip == -1) {
  1556. if (track_filter.has(ti))
  1557. continue;
  1558. } else {
  1559. if (!track_filter.has(ti))
  1560. continue;
  1561. }
  1562. Collada::AnimationTrack &at = collada.state.animation_tracks[ti];
  1563. // take snapshots
  1564. if (!collada.state.scene_map.has(at.target))
  1565. continue;
  1566. NodeMap &nm = node_map[at.target];
  1567. String path = scene->get_path_to(nm.node);
  1568. animation->add_track(Animation::TYPE_VALUE);
  1569. int track = animation->get_track_count() - 1;
  1570. path = path + ":" + at.param;
  1571. animation->track_set_path(track, path);
  1572. animation->track_set_imported(track, true); //helps merging later
  1573. for (int i = 0; i < at.keys.size(); i++) {
  1574. float time = at.keys[i].time;
  1575. Variant value;
  1576. Vector<float> data = at.keys[i].data;
  1577. if (data.size() == 1) {
  1578. //push a float
  1579. value = data[0];
  1580. } else if (data.size() == 16) {
  1581. //matrix
  1582. print_line("value keys for matrices not supported");
  1583. } else {
  1584. print_line("don't know what to do with this amount of value keys: " + itos(data.size()));
  1585. }
  1586. animation->track_insert_key(track, time, value);
  1587. }
  1588. tracks_found = true;
  1589. }
  1590. }
  1591. if (tracks_found) {
  1592. animations.push_back(animation);
  1593. }
  1594. }
  1595. /*********************************************************************************/
  1596. /*************************************** SCENE ***********************************/
  1597. /*********************************************************************************/
  1598. #define DEBUG_ANIMATION
  1599. uint32_t EditorSceneImporterCollada::get_import_flags() const {
  1600. return IMPORT_SCENE | IMPORT_ANIMATION;
  1601. }
  1602. void EditorSceneImporterCollada::get_extensions(List<String> *r_extensions) const {
  1603. r_extensions->push_back("dae");
  1604. }
  1605. Node *EditorSceneImporterCollada::import_scene(const String &p_path, uint32_t p_flags, int p_bake_fps, List<String> *r_missing_deps, Error *r_err) {
  1606. ColladaImport state;
  1607. uint32_t flags = Collada::IMPORT_FLAG_SCENE;
  1608. if (p_flags & IMPORT_ANIMATION)
  1609. flags |= Collada::IMPORT_FLAG_ANIMATION;
  1610. state.bake_fps = p_bake_fps;
  1611. Error err = state.load(p_path, flags, p_flags & EditorSceneImporter::IMPORT_GENERATE_TANGENT_ARRAYS);
  1612. ERR_FAIL_COND_V(err != OK, NULL);
  1613. if (state.missing_textures.size()) {
  1614. //for(int i=0;i<state.missing_textures.size();i++) {
  1615. // EditorNode::add_io_error("Texture Not Found: "+state.missing_textures[i]);
  1616. // }
  1617. if (r_missing_deps) {
  1618. for (int i = 0; i < state.missing_textures.size(); i++) {
  1619. //EditorNode::add_io_error("Texture Not Found: "+state.missing_textures[i]);
  1620. r_missing_deps->push_back(state.missing_textures[i]);
  1621. }
  1622. }
  1623. }
  1624. if (p_flags & IMPORT_ANIMATION) {
  1625. state.create_animations(p_flags & IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS, p_flags & EditorSceneImporter::IMPORT_ANIMATION_KEEP_VALUE_TRACKS);
  1626. AnimationPlayer *ap = memnew(AnimationPlayer);
  1627. for (int i = 0; i < state.animations.size(); i++) {
  1628. String name;
  1629. if (state.animations[i]->get_name() == "")
  1630. name = "default";
  1631. else
  1632. name = state.animations[i]->get_name();
  1633. if (p_flags & IMPORT_ANIMATION_DETECT_LOOP) {
  1634. if (name.begins_with("loop") || name.ends_with("loop") || name.begins_with("cycle") || name.ends_with("cycle")) {
  1635. state.animations[i]->set_loop(true);
  1636. }
  1637. }
  1638. ap->add_animation(name, state.animations[i]);
  1639. }
  1640. state.scene->add_child(ap);
  1641. ap->set_owner(state.scene);
  1642. }
  1643. return state.scene;
  1644. }
  1645. Ref<Animation> EditorSceneImporterCollada::import_animation(const String &p_path, uint32_t p_flags) {
  1646. ColladaImport state;
  1647. Error err = state.load(p_path, Collada::IMPORT_FLAG_ANIMATION, p_flags & EditorSceneImporter::IMPORT_GENERATE_TANGENT_ARRAYS);
  1648. ERR_FAIL_COND_V(err != OK, RES());
  1649. state.create_animations(p_flags & EditorSceneImporter::IMPORT_ANIMATION_FORCE_ALL_TRACKS_IN_ALL_CLIPS, p_flags & EditorSceneImporter::IMPORT_ANIMATION_KEEP_VALUE_TRACKS);
  1650. if (state.scene)
  1651. memdelete(state.scene);
  1652. if (state.animations.size() == 0)
  1653. return Ref<Animation>();
  1654. Ref<Animation> anim = state.animations[0];
  1655. anim = state.animations[0];
  1656. print_line("Anim Load OK");
  1657. String base = p_path.basename().to_lower();
  1658. if (p_flags & IMPORT_ANIMATION_DETECT_LOOP) {
  1659. if (base.begins_with("loop") || base.ends_with("loop") || base.begins_with("cycle") || base.ends_with("cycle")) {
  1660. anim->set_loop(true);
  1661. }
  1662. }
  1663. return anim;
  1664. }
  1665. EditorSceneImporterCollada::EditorSceneImporterCollada() {
  1666. }