editor_import_collada.cpp 60 KB

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