DaeExporter.cs 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230
  1. using UnityEngine;
  2. using UnityEngine.Assertions;
  3. using UnityEditor;
  4. using System;
  5. using System.IO;
  6. using System.Text;
  7. using System.Xml.Serialization;
  8. using System.Linq;
  9. using System.Collections.Generic;
  10. using VoxelImporter.grendgine_collada;
  11. namespace VoxelImporter
  12. {
  13. public class DaeExporter
  14. {
  15. private string ContributorAuthoring_Tool = "Voxel Importer";
  16. //private string ContributorComments = "https://www.assetstore.unity3d.com/#!/content/96826"; //VA
  17. private string ContributorComments = "https://www.assetstore.unity3d.com/#!/content/62914"; //VI
  18. public bool Export(string path, List<Transform> transforms, AnimationClip[] clips = null)
  19. {
  20. int progressTotal = 1 + (clips != null ? clips.Length : 0);
  21. int progressIndex = 0;
  22. EditorUtility.DisplayProgressBar("Exporting Collada(dae) File...", Path.GetFileName(path), (progressIndex++ / (float)progressTotal));
  23. #region TransformSave
  24. TransformSave[] transformSaves = new TransformSave[transforms.Count];
  25. for (int i = 0; i < transforms.Count; i++)
  26. {
  27. transformSaves[i] = new TransformSave(transforms[i]);
  28. }
  29. #endregion
  30. #region FixTransform
  31. foreach (var t in transforms)
  32. {
  33. #region Do not allow scale zero
  34. {
  35. bool update = false;
  36. var scale = t.localScale;
  37. for (int si = 0; si < 3; si++)
  38. {
  39. if (scale[si] == 0f)
  40. {
  41. scale[si] = Mathf.Epsilon;
  42. update = true;
  43. }
  44. }
  45. if (update)
  46. t.localScale = scale;
  47. }
  48. #endregion
  49. }
  50. #endregion
  51. try
  52. {
  53. exportedFiles.Clear();
  54. var rootObject = transforms[0].gameObject;
  55. Grendgine_Collada gCollada = new Grendgine_Collada();
  56. Func<UnityEngine.Object, string> MakeID = (o) =>
  57. {
  58. var id = o.GetInstanceID().ToString();
  59. return id.Replace('-', 'n');
  60. };
  61. Func<Transform, Mesh> MeshFromTransform = (t) =>
  62. {
  63. #region SkinnedMeshRenderer
  64. {
  65. var skinnedMeshRenderer = t.GetComponent<SkinnedMeshRenderer>();
  66. if (skinnedMeshRenderer != null && skinnedMeshRenderer.enabled && skinnedMeshRenderer.sharedMesh != null && skinnedMeshRenderer.sharedMaterials != null)
  67. return skinnedMeshRenderer.sharedMesh;
  68. }
  69. #endregion
  70. #region MeshFilter
  71. {
  72. var meshFilter = t.GetComponent<MeshFilter>();
  73. var meshRenderer = t.GetComponent<MeshRenderer>();
  74. if (meshFilter != null && meshFilter.sharedMesh != null && meshRenderer != null && meshRenderer.enabled && meshRenderer.sharedMaterials != null)
  75. return meshFilter.sharedMesh;
  76. }
  77. #endregion
  78. return null;
  79. };
  80. Func<Transform, Material[]> MaterialsFromTransform = (t) =>
  81. {
  82. #region SkinnedMeshRenderer
  83. {
  84. var skinnedMeshRenderer = t.GetComponent<SkinnedMeshRenderer>();
  85. if (skinnedMeshRenderer != null && skinnedMeshRenderer.enabled && skinnedMeshRenderer.sharedMesh != null && skinnedMeshRenderer.sharedMaterials != null)
  86. return skinnedMeshRenderer.sharedMaterials;
  87. }
  88. #endregion
  89. #region MeshFilter
  90. {
  91. var meshFilter = t.GetComponent<MeshFilter>();
  92. var meshRenderer = t.GetComponent<MeshRenderer>();
  93. if (meshFilter != null && meshFilter.sharedMesh != null && meshRenderer != null && meshRenderer.enabled && meshRenderer.sharedMaterials != null)
  94. return meshRenderer.sharedMaterials;
  95. }
  96. #endregion
  97. return null;
  98. };
  99. Action<Action<Transform, Mesh, Material[]>> MakeFromTransform = (action) =>
  100. {
  101. foreach (var t in transforms)
  102. {
  103. if (!t.gameObject.activeInHierarchy) continue;
  104. #region SkinnedMeshRenderer
  105. {
  106. var skinnedMeshRenderer = t.GetComponent<SkinnedMeshRenderer>();
  107. if (skinnedMeshRenderer != null && skinnedMeshRenderer.enabled && skinnedMeshRenderer.sharedMesh != null && skinnedMeshRenderer.sharedMaterials != null)
  108. {
  109. action(t, skinnedMeshRenderer.sharedMesh, skinnedMeshRenderer.sharedMaterials);
  110. continue;
  111. }
  112. }
  113. #endregion
  114. #region MeshFilter
  115. {
  116. var meshFilter = t.GetComponent<MeshFilter>();
  117. var meshRenderer = t.GetComponent<MeshRenderer>();
  118. if (meshFilter != null && meshFilter.sharedMesh != null && meshRenderer != null && meshRenderer.enabled && meshRenderer.sharedMaterials != null)
  119. {
  120. action(t, meshFilter.sharedMesh, meshRenderer.sharedMaterials);
  121. continue;
  122. }
  123. }
  124. #endregion
  125. }
  126. };
  127. Matrix4x4 matMirrorX = Matrix4x4.identity;
  128. matMirrorX.m00 = -matMirrorX.m00;
  129. var MatrixIdentity = new Grendgine_Collada_Matrix()
  130. {
  131. sID = "transform",
  132. };
  133. {
  134. var mat = Matrix4x4.identity;
  135. var sb = new StringBuilder();
  136. for (int r = 0; r < 4; r++)
  137. for (int c = 0; c < 4; c++)
  138. sb.AppendFormat("{0} ", mat[r, c]);
  139. sb.Remove(sb.Length - 1, 1);
  140. MatrixIdentity.Value_As_String = sb.ToString();
  141. }
  142. bool makeJoint = rootObject.GetComponentInChildren<SkinnedMeshRenderer>() != null;
  143. #region Header
  144. {
  145. gCollada.Collada_Version = "1.4.1"; //for Blender
  146. gCollada.Asset = new Grendgine_Collada_Asset()
  147. {
  148. Created = DateTime.Now,
  149. Modified = DateTime.Now,
  150. Contributor = new Grendgine_Collada_Asset_Contributor[]
  151. {
  152. new Grendgine_Collada_Asset_Contributor()
  153. {
  154. Authoring_Tool = ContributorAuthoring_Tool,
  155. Comments = ContributorComments,
  156. },
  157. },
  158. Revision = "1.0",
  159. Title = Path.GetFileNameWithoutExtension(path),
  160. Unit = new Grendgine_Collada_Asset_Unit()
  161. {
  162. Name = "meter",
  163. Meter = 1.0f,
  164. },
  165. };
  166. }
  167. #endregion
  168. #region Images
  169. var imagesDic = new Dictionary<Texture, Grendgine_Collada_Image>();
  170. if (settings_exportMesh)
  171. {
  172. var li = gCollada.Library_Images = new Grendgine_Collada_Library_Images()
  173. {
  174. ID = "Images_" + MakeID(rootObject),
  175. Name = "Images_" + rootObject.name,
  176. };
  177. bool singleImage;
  178. {
  179. var texList = new HashSet<Texture>();
  180. MakeFromTransform((t, mesh, materials) =>
  181. {
  182. foreach (var material in materials)
  183. {
  184. if (material.mainTexture != null)
  185. texList.Add(material.mainTexture);
  186. }
  187. });
  188. singleImage = texList.Count <= 1;
  189. }
  190. Func<Texture, string> ExportTexture = (tex) =>
  191. {
  192. string texpath;
  193. if (AssetDatabase.Contains(tex) && AssetDatabase.IsMainAsset(tex))
  194. {
  195. if (path.StartsWith(Application.dataPath))
  196. {
  197. var assetPath = AssetDatabase.GetAssetPath(tex);
  198. texpath = Path.GetDirectoryName(path).Replace(Application.dataPath, "Assets") + "/" + Path.GetFileName(assetPath);
  199. if (AssetDatabase.LoadAssetAtPath<Texture2D>(texpath) == null)
  200. AssetDatabase.CopyAsset(assetPath, texpath);
  201. else
  202. {
  203. assetPath = Application.dataPath + AssetDatabase.GetAssetPath(tex).Remove(0, "Assets".Length);
  204. texpath = Path.GetDirectoryName(path) + "/" + Path.GetFileName(assetPath);
  205. if (assetPath != texpath)
  206. File.Copy(assetPath, texpath, true);
  207. }
  208. }
  209. else
  210. {
  211. var assetPath = Application.dataPath + AssetDatabase.GetAssetPath(tex).Remove(0, "Assets".Length);
  212. texpath = Path.GetDirectoryName(path) + "/" + Path.GetFileName(assetPath);
  213. if (assetPath != texpath)
  214. File.Copy(assetPath, texpath, true);
  215. }
  216. }
  217. else
  218. {
  219. const string EXT = ".png";
  220. if (singleImage)
  221. texpath = path.Remove(path.Length - EXT.Length, EXT.Length) + EXT;
  222. else
  223. texpath = string.Format("{0}/{1}_tex{2}{3}", Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path), imagesDic.Count, EXT);
  224. Texture2D tex2D = null;
  225. bool created = false;
  226. if(tex is Texture2D)
  227. {
  228. tex2D = tex as Texture2D;
  229. }
  230. else
  231. {
  232. var currentRT = RenderTexture.active;
  233. RenderTexture rt = null;
  234. try
  235. {
  236. rt = new RenderTexture(tex.width, tex.height, 32);
  237. Graphics.Blit(tex, rt);
  238. RenderTexture.active = rt;
  239. tex2D = new Texture2D(tex.width, tex.height, TextureFormat.RGBA32, false);
  240. tex2D.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
  241. tex2D.Apply();
  242. created = true;
  243. }
  244. finally
  245. {
  246. RenderTexture.active = currentRT;
  247. if (rt != null)
  248. {
  249. rt.Release();
  250. RenderTexture.DestroyImmediate(rt);
  251. }
  252. }
  253. }
  254. if (tex2D != null)
  255. {
  256. try
  257. {
  258. File.WriteAllBytes(texpath, tex2D.EncodeToPNG());
  259. }
  260. catch
  261. {
  262. Debug.LogWarningFormat("<color=green>[{0}]</color> Texture Export Error. '{1}'", ContributorAuthoring_Tool, tex.name);
  263. }
  264. }
  265. else
  266. {
  267. Debug.LogWarningFormat("<color=green>[{0}]</color> Texture Export Error. '{1}'", ContributorAuthoring_Tool, tex.name);
  268. }
  269. if (created && tex2D)
  270. {
  271. Texture2D.DestroyImmediate(tex2D);
  272. }
  273. }
  274. exportedFiles.Add(texpath);
  275. return Path.GetFileName(texpath);
  276. };
  277. MakeFromTransform((t, mesh, materials) =>
  278. {
  279. foreach (var material in materials)
  280. {
  281. var tex = material.mainTexture;
  282. if (tex == null || imagesDic.ContainsKey(tex)) continue;
  283. var image = new Grendgine_Collada_Image()
  284. {
  285. ID = "Image_" + MakeID(tex),
  286. Name = tex.name,
  287. Init_From = Uri.EscapeDataString(ExportTexture(tex)),
  288. };
  289. imagesDic.Add(tex, image);
  290. }
  291. });
  292. li.Image = imagesDic.Values.ToArray();
  293. }
  294. #endregion
  295. #region Effects
  296. var effectsDic = new Dictionary<Material, Grendgine_Collada_Effect>();
  297. if (settings_exportMesh)
  298. {
  299. var le = gCollada.Library_Effects = new Grendgine_Collada_Library_Effects()
  300. {
  301. ID = "Effects_" + MakeID(rootObject),
  302. Name = "Effects_" + rootObject.name,
  303. };
  304. MakeFromTransform((t, mesh, materials) =>
  305. {
  306. foreach (var material in materials)
  307. {
  308. var tex = material.mainTexture;
  309. if (effectsDic.ContainsKey(material)) continue;
  310. Grendgine_Collada_New_Param[] New_Param = null;
  311. Grendgine_Collada_FX_Common_Color_Or_Texture_Type Diffuse = null;
  312. if (tex != null && imagesDic.ContainsKey(tex))
  313. {
  314. Grendgine_Collada_New_Param surfaceParam = new Grendgine_Collada_New_Param()
  315. {
  316. sID = "Surface_" + MakeID(material),
  317. Surface = new Grendgine_Collada_Surface_1_4_1()
  318. {
  319. Type = Grendgine_Collada_FX_Surface_Type._2D,
  320. Init_From = imagesDic[tex].ID,
  321. },
  322. };
  323. Grendgine_Collada_New_Param sampler2DParam = new Grendgine_Collada_New_Param()
  324. {
  325. sID = "Sampler2D_" + MakeID(material),
  326. Sampler2D = new Grendgine_Collada_Sampler2D()
  327. {
  328. Source = surfaceParam.sID,
  329. },
  330. };
  331. New_Param = new Grendgine_Collada_New_Param[]
  332. {
  333. surfaceParam,
  334. sampler2DParam,
  335. };
  336. Diffuse = new Grendgine_Collada_FX_Common_Color_Or_Texture_Type()
  337. {
  338. Texture = new Grendgine_Collada_Texture()
  339. {
  340. TexCoord = "TexCoord_" + MakeID(material.mainTexture),
  341. Texture = sampler2DParam.sID,
  342. },
  343. };
  344. }
  345. else
  346. {
  347. Color color = Color.white;
  348. if (material.HasProperty("_Color"))
  349. color = material.color;
  350. Diffuse = new Grendgine_Collada_FX_Common_Color_Or_Texture_Type()
  351. {
  352. Color = new Grendgine_Collada_Color()
  353. {
  354. sID = "diffuse",
  355. Value_As_String = string.Format("{0} {1} {2} {3}", color.r, color.g, color.b, color.a),
  356. },
  357. };
  358. }
  359. var e = new Grendgine_Collada_Effect()
  360. {
  361. ID = "Effect_" + MakeID(material),
  362. Name = material.name,
  363. Profile_COMMON = new Grendgine_Collada_Profile_COMMON[]
  364. {
  365. new Grendgine_Collada_Profile_COMMON()
  366. {
  367. ID = "Profile_" + MakeID(material),
  368. New_Param = New_Param,
  369. Technique = new Grendgine_Collada_Effect_Technique_COMMON()
  370. {
  371. sID = "Technique_" + MakeID(material),
  372. Phong = new Grendgine_Collada_Phong()
  373. {
  374. Emission = new Grendgine_Collada_FX_Common_Color_Or_Texture_Type()
  375. {
  376. Color = new Grendgine_Collada_Color()
  377. {
  378. sID = "emission",
  379. Value_As_String = "0 0 0 1",
  380. },
  381. },
  382. Ambient = new Grendgine_Collada_FX_Common_Color_Or_Texture_Type()
  383. {
  384. Color = new Grendgine_Collada_Color()
  385. {
  386. sID = "ambient",
  387. Value_As_String = "1 1 1 1",
  388. },
  389. },
  390. Diffuse = Diffuse,
  391. Specular = new Grendgine_Collada_FX_Common_Color_Or_Texture_Type()
  392. {
  393. Color = new Grendgine_Collada_Color()
  394. {
  395. sID = "specular",
  396. Value_As_String = "0 0 0 1",
  397. },
  398. },
  399. Shininess = new Grendgine_Collada_FX_Common_Float_Or_Param_Type()
  400. {
  401. Float = new Grendgine_Collada_SID_Float()
  402. {
  403. sID = "shininess",
  404. Value = 50,
  405. },
  406. },
  407. Index_Of_Refraction = new Grendgine_Collada_FX_Common_Float_Or_Param_Type()
  408. {
  409. Float = new Grendgine_Collada_SID_Float()
  410. {
  411. sID = "index_of_refraction",
  412. Value = 1,
  413. },
  414. },
  415. },
  416. },
  417. },
  418. },
  419. };
  420. effectsDic.Add(material, e);
  421. }
  422. });
  423. le.Effect = effectsDic.Values.ToArray();
  424. }
  425. #endregion
  426. #region Materials
  427. var materialsDic = new Dictionary<Material, Grendgine_Collada_Material>();
  428. if (settings_exportMesh)
  429. {
  430. var lm = gCollada.Library_Materials = new Grendgine_Collada_Library_Materials()
  431. {
  432. ID = "Materials_" + MakeID(rootObject),
  433. Name = "Materials_" + rootObject.name,
  434. };
  435. MakeFromTransform((t, mesh, materials) =>
  436. {
  437. foreach (var material in materials)
  438. {
  439. if (!effectsDic.ContainsKey(material)) continue;
  440. if (materialsDic.ContainsKey(material)) continue;
  441. var effect = effectsDic[material];
  442. var m = new Grendgine_Collada_Material()
  443. {
  444. ID = "Material_" + MakeID(material),
  445. Name = material.name,
  446. Instance_Effect = new Grendgine_Collada_Instance_Effect()
  447. {
  448. URL = "#" + effect.ID,
  449. },
  450. };
  451. materialsDic.Add(material, m);
  452. }
  453. });
  454. lm.Material = materialsDic.Values.ToArray();
  455. }
  456. #endregion
  457. #region Geometries
  458. var geometriesDic = new Dictionary<Transform, Grendgine_Collada_Geometry>();
  459. if (settings_exportMesh)
  460. {
  461. var lg = gCollada.Library_Geometries = new Grendgine_Collada_Library_Geometries()
  462. {
  463. ID = "Geometries_" + MakeID(rootObject),
  464. Name = "Geometries_" + rootObject.name,
  465. };
  466. MakeFromTransform((t, mesh, materials) =>
  467. {
  468. #region Source
  469. #region Vertex
  470. Grendgine_Collada_Source vertexSource;
  471. {
  472. Grendgine_Collada_Float_Array array;
  473. {
  474. var sb = new StringBuilder();
  475. foreach (var v in mesh.vertices)
  476. {
  477. var mv = matMirrorX.MultiplyPoint(v);
  478. sb.AppendFormat("\n{0} {1} {2}", mv.x, mv.y, mv.z);
  479. }
  480. array = new Grendgine_Collada_Float_Array()
  481. {
  482. ID = "VertexArray_" + MakeID(mesh),
  483. Name = mesh.name + "_vertex",
  484. Count = mesh.vertexCount * 3,
  485. Value_As_String = sb.ToString(),
  486. };
  487. }
  488. vertexSource = new Grendgine_Collada_Source()
  489. {
  490. ID = "VertexSource_" + MakeID(mesh),
  491. Name = mesh.name + "_vertex",
  492. Float_Array = array,
  493. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  494. {
  495. Accessor = new Grendgine_Collada_Accessor()
  496. {
  497. Count = (uint)mesh.vertexCount,
  498. Source = "#" + array.ID,
  499. Stride = 3,
  500. Param = new Grendgine_Collada_Param[]
  501. {
  502. new Grendgine_Collada_Param() { Name = "X", Type = "float", },
  503. new Grendgine_Collada_Param() { Name = "Y", Type = "float", },
  504. new Grendgine_Collada_Param() { Name = "Z", Type = "float", },
  505. },
  506. },
  507. },
  508. };
  509. }
  510. #endregion
  511. #region UV
  512. Grendgine_Collada_Source uvSource;
  513. {
  514. Grendgine_Collada_Float_Array array;
  515. {
  516. var sb = new StringBuilder();
  517. foreach (var uv in mesh.uv)
  518. sb.AppendFormat("\n{0} {1}", uv.x, uv.y);
  519. array = new Grendgine_Collada_Float_Array()
  520. {
  521. ID = "UVArray_" + MakeID(mesh),
  522. Name = mesh.name + "_uv",
  523. Count = mesh.vertexCount * 2,
  524. Value_As_String = sb.ToString(),
  525. };
  526. }
  527. uvSource = new Grendgine_Collada_Source()
  528. {
  529. ID = "UVSource_" + MakeID(mesh),
  530. Name = mesh.name + "_uv",
  531. Float_Array = array,
  532. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  533. {
  534. Accessor = new Grendgine_Collada_Accessor()
  535. {
  536. Count = (uint)mesh.vertexCount,
  537. Source = "#" + array.ID,
  538. Stride = 2,
  539. Param = new Grendgine_Collada_Param[]
  540. {
  541. new Grendgine_Collada_Param() { Name = "S", Type = "float", },
  542. new Grendgine_Collada_Param() { Name = "T", Type = "float", },
  543. },
  544. },
  545. },
  546. };
  547. }
  548. #endregion
  549. #region Normal
  550. Grendgine_Collada_Source normalSource;
  551. {
  552. Grendgine_Collada_Float_Array array;
  553. {
  554. var sb = new StringBuilder();
  555. foreach (var n in mesh.normals)
  556. {
  557. var mn = matMirrorX.MultiplyVector(n);
  558. sb.AppendFormat("\n{0} {1} {2}", mn.x, mn.y, mn.z);
  559. }
  560. array = new Grendgine_Collada_Float_Array()
  561. {
  562. ID = "NormalArray_" + MakeID(mesh),
  563. Name = mesh.name + "_normal",
  564. Count = mesh.vertexCount * 3,
  565. Value_As_String = sb.ToString(),
  566. };
  567. }
  568. normalSource = new Grendgine_Collada_Source()
  569. {
  570. ID = "NormalSource_" + MakeID(mesh),
  571. Name = mesh.name + "_normal",
  572. Float_Array = array,
  573. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  574. {
  575. Accessor = new Grendgine_Collada_Accessor()
  576. {
  577. Count = (uint)mesh.vertexCount,
  578. Source = "#" + array.ID,
  579. Stride = 3,
  580. Param = new Grendgine_Collada_Param[]
  581. {
  582. new Grendgine_Collada_Param() { Name = "X", Type = "float", },
  583. new Grendgine_Collada_Param() { Name = "Y", Type = "float", },
  584. new Grendgine_Collada_Param() { Name = "Z", Type = "float", },
  585. },
  586. },
  587. },
  588. };
  589. }
  590. #endregion
  591. #endregion
  592. #region Vertices
  593. Grendgine_Collada_Vertices vertices;
  594. {
  595. vertices = new Grendgine_Collada_Vertices()
  596. {
  597. ID = "Vertices_" + MakeID(mesh),
  598. Name = mesh.name + "_vertices",
  599. Input = new Grendgine_Collada_Input_Unshared[]
  600. {
  601. new Grendgine_Collada_Input_Unshared()
  602. {
  603. Semantic = Grendgine_Collada_Input_Semantic.POSITION,
  604. source = "#" + vertexSource.ID,
  605. },
  606. },
  607. };
  608. }
  609. #endregion
  610. #region Triangles
  611. Grendgine_Collada_Triangles[] triangles;
  612. {
  613. triangles = new Grendgine_Collada_Triangles[mesh.subMeshCount];
  614. for (int subMesh = 0; subMesh < mesh.subMeshCount; subMesh++)
  615. {
  616. if (mesh.GetTopology(subMesh) != MeshTopology.Triangles)
  617. {
  618. Debug.LogWarningFormat("<color=green>[{0}]</color> MeshTopology is not Triangles. Mesh = {1} - {2}, MeshTopology = {3}", ContributorAuthoring_Tool, mesh.name, subMesh, mesh.GetTopology(subMesh));
  619. continue;
  620. }
  621. Grendgine_Collada_Material material = null;
  622. materialsDic.TryGetValue(materials[subMesh], out material);
  623. var ts = mesh.GetTriangles(subMesh);
  624. var sb = new StringBuilder();
  625. {
  626. for (int i = 0; i < ts.Length; i += 3)
  627. sb.AppendFormat("\n{0} {0} {0} {1} {1} {1} {2} {2} {2}", ts[i + 0], ts[i + 2], ts[i + 1]);
  628. }
  629. triangles[subMesh] = new Grendgine_Collada_Triangles()
  630. {
  631. Count = ts.Length / 3,
  632. Name = mesh.name + "_triangles",
  633. Material = material != null ? material.ID : null,
  634. Input = new Grendgine_Collada_Input_Shared[]
  635. {
  636. new Grendgine_Collada_Input_Shared()
  637. {
  638. Semantic = Grendgine_Collada_Input_Semantic.VERTEX,
  639. source = "#" + vertices.ID,
  640. Offset = 0,
  641. },
  642. new Grendgine_Collada_Input_Shared()
  643. {
  644. Semantic = Grendgine_Collada_Input_Semantic.TEXCOORD,
  645. source = "#" + uvSource.ID,
  646. Offset = 1,
  647. },
  648. new Grendgine_Collada_Input_Shared()
  649. {
  650. Semantic = Grendgine_Collada_Input_Semantic.NORMAL,
  651. source = "#" + normalSource.ID,
  652. Offset = 2,
  653. },
  654. },
  655. P = new Grendgine_Collada_Int_Array_String()
  656. {
  657. Value_As_String = sb.ToString(),
  658. },
  659. };
  660. }
  661. }
  662. #endregion
  663. var g = new Grendgine_Collada_Geometry()
  664. {
  665. ID = "Geometry_" + MakeID(mesh),
  666. Name = mesh.name,
  667. Mesh = new Grendgine_Collada_Mesh()
  668. {
  669. Source = new Grendgine_Collada_Source[]
  670. {
  671. vertexSource,
  672. uvSource,
  673. normalSource,
  674. },
  675. Vertices = vertices,
  676. Triangles = triangles,
  677. },
  678. };
  679. geometriesDic.Add(t, g);
  680. });
  681. lg.Geometry = geometriesDic.Values.ToArray();
  682. }
  683. #endregion
  684. #region Nodes
  685. var nodesDic = new Dictionary<Transform, Grendgine_Collada_Node>();
  686. {
  687. Func<Transform, Grendgine_Collada_Node> MakeNode = null;
  688. MakeNode = (t) =>
  689. {
  690. var node = new Grendgine_Collada_Node()
  691. {
  692. ID = "Node_" + MakeID(t),
  693. Name = t.name,
  694. sID = "Node_" + MakeID(t),
  695. Type = Grendgine_Collada_Node_Type.NODE,
  696. };
  697. {
  698. var mat = Matrix4x4.TRS(matMirrorX.MultiplyPoint3x4(t.localPosition),
  699. new Quaternion(t.localRotation.x, -t.localRotation.y, -t.localRotation.z, t.localRotation.w), //mirrorX
  700. t.localScale);
  701. var sb = new StringBuilder();
  702. for (int r = 0; r < 4; r++)
  703. for (int c = 0; c < 4; c++)
  704. sb.AppendFormat("{0} ", mat[r, c]);
  705. sb.Remove(sb.Length - 1, 1);
  706. node.Matrix = new Grendgine_Collada_Matrix[]
  707. {
  708. new Grendgine_Collada_Matrix()
  709. {
  710. sID = "transform",
  711. Value_As_String = sb.ToString(),
  712. },
  713. };
  714. }
  715. {
  716. List<Grendgine_Collada_Node> nodes = new List<Grendgine_Collada_Node>();
  717. for (int i = 0; i < t.childCount; i++)
  718. {
  719. var ct = t.GetChild(i);
  720. if (!transforms.Contains(ct)) continue;
  721. if (!t.gameObject.activeInHierarchy) continue;
  722. var n = MakeNode(ct);
  723. nodes.Add(n);
  724. nodesDic.Add(ct, n);
  725. }
  726. node.node = nodes.ToArray();
  727. }
  728. if (geometriesDic.ContainsKey(t))
  729. {
  730. var mesh = MeshFromTransform(t);
  731. if (mesh == null) return node;
  732. var materials = MaterialsFromTransform(t);
  733. if (materials == null) return node;
  734. var Instance_Material = new Grendgine_Collada_Instance_Material_Geometry[materials.Length];
  735. for (int j = 0; j < materials.Length; j++)
  736. {
  737. if (!materialsDic.ContainsKey(materials[j])) continue;
  738. var mat = materialsDic[materials[j]];
  739. Instance_Material[j] = new Grendgine_Collada_Instance_Material_Geometry()
  740. {
  741. Target = "#" + mat.ID,
  742. Symbol = mat.ID,
  743. };
  744. if (effectsDic[materials[j]].Profile_COMMON[0].Technique.Phong.Diffuse.Texture != null)
  745. {
  746. Instance_Material[j].Bind_Vertex_Input = new Grendgine_Collada_Bind_Vertex_Input[]
  747. {
  748. new Grendgine_Collada_Bind_Vertex_Input()
  749. {
  750. Input_Semantic = "TEXCOORD",
  751. Input_Set = 1,
  752. Semantic = effectsDic[materials[j]].Profile_COMMON[0].Technique.Phong.Diffuse.Texture.TexCoord,
  753. },
  754. };
  755. }
  756. }
  757. node.Instance_Geometry = new Grendgine_Collada_Instance_Geometry[]
  758. {
  759. new Grendgine_Collada_Instance_Geometry()
  760. {
  761. URL = "#" + geometriesDic[t].ID,
  762. Bind_Material = new Grendgine_Collada_Bind_Material[]
  763. {
  764. new Grendgine_Collada_Bind_Material()
  765. {
  766. Technique_Common = new Grendgine_Collada_Technique_Common_Bind_Material()
  767. {
  768. Instance_Material = Instance_Material,
  769. },
  770. },
  771. },
  772. },
  773. };
  774. }
  775. return node;
  776. };
  777. nodesDic.Add(rootObject.transform, MakeNode(rootObject.transform));
  778. }
  779. #endregion
  780. #region Joints
  781. var jointsDic = new Dictionary<Transform, Grendgine_Collada_Node>();
  782. if (makeJoint)
  783. {
  784. Func<Transform, Grendgine_Collada_Node> MakeJoint = null;
  785. MakeJoint = (t) =>
  786. {
  787. var Doc = new System.Xml.XmlDocument();
  788. var Data = new System.Xml.XmlElement[]
  789. {
  790. Doc.CreateElement("tip_x"),
  791. Doc.CreateElement("tip_y"),
  792. Doc.CreateElement("tip_z"),
  793. };
  794. bool enable = true;
  795. {
  796. Vector3 offset = Vector3.zero;
  797. if (t.childCount > 0)
  798. {
  799. float dotMax = float.MinValue;
  800. for (int i = 0; i < t.childCount; i++)
  801. {
  802. var vec = rootObject.transform.worldToLocalMatrix.MultiplyVector(t.GetChild(i).position - t.position);
  803. vec = matMirrorX.MultiplyVector(vec);
  804. var dot = Mathf.Abs(Vector3.Dot(vec, Vector3.up));
  805. if (dot > dotMax)
  806. {
  807. offset = vec;
  808. dotMax = dot;
  809. }
  810. }
  811. }
  812. else
  813. {
  814. var vec = rootObject.transform.worldToLocalMatrix.MultiplyVector(t.position - t.parent.position);
  815. if (vec.sqrMagnitude > 0)
  816. {
  817. vec = vec.normalized * 0.0001f;
  818. offset = matMirrorX.MultiplyVector(vec);
  819. }
  820. else
  821. {
  822. offset = new Vector3(0, 0, 0.0001f);
  823. }
  824. }
  825. if (offset.sqrMagnitude <= 0f)
  826. enable = false;
  827. Data[0].InnerText = offset.x.ToString();
  828. Data[1].InnerText = offset.y.ToString();
  829. Data[2].InnerText = offset.z.ToString();
  830. }
  831. Grendgine_Collada_Node joint = new Grendgine_Collada_Node()
  832. {
  833. ID = "Joint_" + MakeID(t),
  834. Name = t.name,
  835. sID = "Joint_" + MakeID(t),
  836. Type = Grendgine_Collada_Node_Type.JOINT,
  837. Matrix = nodesDic[t].Matrix,
  838. Extra = enable ? new Grendgine_Collada_Extra[]
  839. {
  840. new Grendgine_Collada_Extra()
  841. {
  842. Technique = new Grendgine_Collada_Technique[]
  843. {
  844. new Grendgine_Collada_Technique()
  845. {
  846. profile = "blender",
  847. Data = Data,
  848. },
  849. },
  850. },
  851. } : null,
  852. };
  853. List<Grendgine_Collada_Node> joints = new List<Grendgine_Collada_Node>();
  854. for (int i = 0; i < t.childCount; i++)
  855. {
  856. var ct = t.GetChild(i);
  857. if (!transforms.Contains(ct)) continue;
  858. if (!t.gameObject.activeInHierarchy) continue;
  859. var n = MakeJoint(ct);
  860. joints.Add(n);
  861. jointsDic.Add(ct, n);
  862. }
  863. joint.node = joints.ToArray();
  864. return joint;
  865. };
  866. jointsDic.Add(rootObject.transform, MakeJoint(rootObject.transform));
  867. }
  868. #endregion
  869. #region Controllers
  870. var controllersDic = new Dictionary<Transform, Grendgine_Collada_Controller>();
  871. if (makeJoint && settings_exportMesh)
  872. {
  873. var lc = gCollada.Library_Controllers = new Grendgine_Collada_Library_Controllers()
  874. {
  875. ID = "Controllers_" + MakeID(rootObject),
  876. Name = "Controllers_" + rootObject.name,
  877. };
  878. foreach (var t in transforms)
  879. {
  880. if (!t.gameObject.activeInHierarchy) continue;
  881. Mesh mesh = null;
  882. Material[] materials = null;
  883. #region SkinnedMeshRenderer
  884. var skinnedMeshRenderer = t.GetComponent<SkinnedMeshRenderer>();
  885. {
  886. if (skinnedMeshRenderer != null && skinnedMeshRenderer.enabled && skinnedMeshRenderer.sharedMesh != null && skinnedMeshRenderer.sharedMaterials != null)
  887. {
  888. mesh = skinnedMeshRenderer.sharedMesh;
  889. materials = skinnedMeshRenderer.sharedMaterials;
  890. }
  891. }
  892. #endregion
  893. #region MeshFilter
  894. var meshFilter = t.GetComponent<MeshFilter>();
  895. var meshRenderer = t.GetComponent<MeshRenderer>();
  896. {
  897. if (meshFilter != null && meshFilter.sharedMesh != null && meshRenderer != null && meshRenderer.enabled && meshRenderer.sharedMaterials != null)
  898. {
  899. mesh = meshFilter.sharedMesh;
  900. materials = meshRenderer.sharedMaterials;
  901. }
  902. }
  903. #endregion
  904. Grendgine_Collada_Controller c;
  905. if (mesh != null && materials != null && skinnedMeshRenderer != null && mesh.boneWeights.Length > 0)
  906. {
  907. #region SkinnedMeshRenderer
  908. var bones = skinnedMeshRenderer.bones;
  909. var boneWeights = mesh.boneWeights;
  910. #region ErrorCheck
  911. {
  912. var checkBones = new List<Transform>(bones.Distinct());
  913. if (checkBones.Count != bones.Length)
  914. {
  915. Debug.LogWarningFormat("<color=green>[{0}]</color> There are two or more same Transforms in SkinnedMeshRenderer.bones. This is not supported.", ContributorAuthoring_Tool);
  916. }
  917. }
  918. #endregion
  919. #region Joints_Source
  920. Grendgine_Collada_Source Joints_Source;
  921. {
  922. var Joints_Name_Array = new Grendgine_Collada_Name_Array()
  923. {
  924. ID = "Joints_Name_Array_" + MakeID(t),
  925. Count = bones.Length,
  926. };
  927. {
  928. var names = new StringBuilder();
  929. foreach (var bone in bones)
  930. {
  931. if (bone != null && jointsDic.ContainsKey(bone))
  932. names.AppendFormat("\n{0}", jointsDic[bone].ID);
  933. else
  934. names.AppendFormat("\n{0}", 0);
  935. }
  936. Joints_Name_Array.Value_Pre_Parse = names.ToString();
  937. }
  938. Joints_Source = new Grendgine_Collada_Source()
  939. {
  940. ID = "Joints_" + MakeID(t),
  941. Name_Array = Joints_Name_Array,
  942. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  943. {
  944. Accessor = new Grendgine_Collada_Accessor()
  945. {
  946. Count = (uint)Joints_Name_Array.Count,
  947. Source = "#" + Joints_Name_Array.ID,
  948. Param = new Grendgine_Collada_Param[]
  949. {
  950. new Grendgine_Collada_Param()
  951. {
  952. Type = "name",
  953. },
  954. },
  955. },
  956. },
  957. };
  958. }
  959. #endregion
  960. #region Weights_Source
  961. Grendgine_Collada_Source Weights_Source;
  962. StringBuilder weightsVCountString = new StringBuilder();
  963. StringBuilder weightsVString = new StringBuilder();
  964. List<float> weightList = new List<float>();
  965. {
  966. var Weights_Float_Array = new Grendgine_Collada_Float_Array()
  967. {
  968. ID = "Weights_Float_Array_" + MakeID(t),
  969. };
  970. {
  971. var sb = new StringBuilder();
  972. for (int i = 0; i < boneWeights.Length; i++)
  973. {
  974. int count = 0;
  975. {
  976. if (!weightList.Contains(boneWeights[i].weight0))
  977. {
  978. weightList.Add(boneWeights[i].weight0);
  979. sb.AppendFormat("\n{0}", boneWeights[i].weight0);
  980. }
  981. weightsVString.AppendFormat("\n{0} {1}", boneWeights[i].boneIndex0, weightList.IndexOf(boneWeights[i].weight0));
  982. count++;
  983. }
  984. if (boneWeights[i].weight1 > 0f)
  985. {
  986. if (!weightList.Contains(boneWeights[i].weight1))
  987. {
  988. weightList.Add(boneWeights[i].weight1);
  989. sb.AppendFormat("\n{0}", boneWeights[i].weight1);
  990. }
  991. weightsVString.AppendFormat(" {0} {1}", boneWeights[i].boneIndex1, weightList.IndexOf(boneWeights[i].weight1));
  992. count++;
  993. }
  994. if (boneWeights[i].weight2 > 0f)
  995. {
  996. if (!weightList.Contains(boneWeights[i].weight2))
  997. {
  998. weightList.Add(boneWeights[i].weight2);
  999. sb.AppendFormat("\n{0}", boneWeights[i].weight2);
  1000. }
  1001. weightsVString.AppendFormat(" {0} {1}", boneWeights[i].boneIndex2, weightList.IndexOf(boneWeights[i].weight2));
  1002. count++;
  1003. }
  1004. if (boneWeights[i].weight3 > 0f)
  1005. {
  1006. if (!weightList.Contains(boneWeights[i].weight3))
  1007. {
  1008. weightList.Add(boneWeights[i].weight3);
  1009. sb.AppendFormat("\n{0}", boneWeights[i].weight3);
  1010. }
  1011. weightsVString.AppendFormat(" {0} {1}", boneWeights[i].boneIndex3, weightList.IndexOf(boneWeights[i].weight3));
  1012. count++;
  1013. }
  1014. weightsVCountString.AppendFormat("\n{0}", count);
  1015. }
  1016. Weights_Float_Array.Count = weightList.Count;
  1017. Weights_Float_Array.Value_As_String = sb.ToString();
  1018. }
  1019. Weights_Source = new Grendgine_Collada_Source()
  1020. {
  1021. ID = "Weights_" + MakeID(t),
  1022. Float_Array = Weights_Float_Array,
  1023. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  1024. {
  1025. Accessor = new Grendgine_Collada_Accessor()
  1026. {
  1027. Count = (uint)Weights_Float_Array.Count,
  1028. Source = "#" + Weights_Float_Array.ID,
  1029. Param = new Grendgine_Collada_Param[]
  1030. {
  1031. new Grendgine_Collada_Param()
  1032. {
  1033. Type = "float",
  1034. },
  1035. },
  1036. },
  1037. },
  1038. };
  1039. }
  1040. #endregion
  1041. #region Inv_Bind_Mats_Source
  1042. Grendgine_Collada_Source Inv_Bind_Mats_Source;
  1043. {
  1044. var Inv_Bind_Mats_Float_Array = new Grendgine_Collada_Float_Array()
  1045. {
  1046. ID = "Inv_Bind_Mats_" + MakeID(t),
  1047. };
  1048. {
  1049. var bindposes = skinnedMeshRenderer.sharedMesh.bindposes;
  1050. var sb = new StringBuilder();
  1051. for (int i = 0; i < bindposes.Length; i++)
  1052. {
  1053. Matrix4x4 mat = bindposes[i];
  1054. {
  1055. var position = mat.GetColumn(3);
  1056. var rotation = (mat.GetColumn(2).sqrMagnitude > 0f && mat.GetColumn(1).sqrMagnitude > 0f) ? Quaternion.LookRotation(mat.GetColumn(2), mat.GetColumn(1)) : Quaternion.identity;
  1057. var scale = new Vector3(mat.GetColumn(0).magnitude, mat.GetColumn(1).magnitude, mat.GetColumn(2).magnitude);
  1058. #region Do not allow scale zero
  1059. {
  1060. for (int si = 0; si < 3; si++)
  1061. {
  1062. if (scale[si] == 0f)
  1063. scale[si] = Mathf.Epsilon;
  1064. }
  1065. }
  1066. #endregion
  1067. mat = Matrix4x4.TRS(matMirrorX.MultiplyPoint3x4(position),
  1068. new Quaternion(rotation.x, -rotation.y, -rotation.z, rotation.w), //mirrorX
  1069. scale);
  1070. }
  1071. for (int r = 0; r < 4; r++)
  1072. sb.AppendFormat("\n{0} {1} {2} {3}", mat[r, 0], mat[r, 1], mat[r, 2], mat[r, 3]);
  1073. }
  1074. Inv_Bind_Mats_Float_Array.Count = bindposes.Length * 16;
  1075. Inv_Bind_Mats_Float_Array.Value_As_String = sb.ToString();
  1076. }
  1077. Inv_Bind_Mats_Source = new Grendgine_Collada_Source()
  1078. {
  1079. ID = "Inv_Bind_Mats_" + MakeID(t),
  1080. Float_Array = Inv_Bind_Mats_Float_Array,
  1081. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  1082. {
  1083. Accessor = new Grendgine_Collada_Accessor()
  1084. {
  1085. Count = (uint)(Inv_Bind_Mats_Float_Array.Count / 16),
  1086. Source = "#" + Inv_Bind_Mats_Float_Array.ID,
  1087. Stride = 16,
  1088. Param = new Grendgine_Collada_Param[]
  1089. {
  1090. new Grendgine_Collada_Param()
  1091. {
  1092. Type = "float4x4",
  1093. },
  1094. },
  1095. },
  1096. },
  1097. };
  1098. }
  1099. #endregion
  1100. c = new Grendgine_Collada_Controller()
  1101. {
  1102. ID = "Controller_" + MakeID(t),
  1103. Skin = new Grendgine_Collada_Skin()
  1104. {
  1105. SourceAt = "#" + geometriesDic[t].ID,
  1106. Source = new Grendgine_Collada_Source[]
  1107. {
  1108. Joints_Source,
  1109. Weights_Source,
  1110. Inv_Bind_Mats_Source,
  1111. },
  1112. Joints = new Grendgine_Collada_Joints()
  1113. {
  1114. Input = new Grendgine_Collada_Input_Unshared[]
  1115. {
  1116. new Grendgine_Collada_Input_Unshared()
  1117. {
  1118. Semantic = Grendgine_Collada_Input_Semantic.JOINT,
  1119. source = "#" + Joints_Source.ID,
  1120. },
  1121. new Grendgine_Collada_Input_Unshared()
  1122. {
  1123. Semantic = Grendgine_Collada_Input_Semantic.INV_BIND_MATRIX,
  1124. source = "#" + Inv_Bind_Mats_Source.ID,
  1125. },
  1126. },
  1127. },
  1128. Vertex_Weights = new Grendgine_Collada_Vertex_Weights()
  1129. {
  1130. Count = (uint)boneWeights.Length,
  1131. Input = new Grendgine_Collada_Input_Shared[]
  1132. {
  1133. new Grendgine_Collada_Input_Shared()
  1134. {
  1135. Semantic = Grendgine_Collada_Input_Semantic.JOINT,
  1136. source = "#" + Joints_Source.ID,
  1137. Offset = 0,
  1138. Set = 0,
  1139. },
  1140. new Grendgine_Collada_Input_Shared()
  1141. {
  1142. Semantic = Grendgine_Collada_Input_Semantic.WEIGHT,
  1143. source = "#" + Weights_Source.ID,
  1144. Offset = 1,
  1145. Set = 0,
  1146. },
  1147. },
  1148. VCount = new Grendgine_Collada_Int_Array_String()
  1149. {
  1150. Value_As_String = weightsVCountString.ToString(),
  1151. },
  1152. V = new Grendgine_Collada_Int_Array_String()
  1153. {
  1154. Value_As_String = weightsVString.ToString(),
  1155. },
  1156. },
  1157. },
  1158. };
  1159. #endregion
  1160. }
  1161. else if (mesh != null && materials != null)
  1162. {
  1163. #region MeshRenderer
  1164. var vertexCount = mesh.vertexCount;
  1165. const int boneCount = 1;
  1166. #region Joints_Source
  1167. Grendgine_Collada_Source Joints_Source;
  1168. {
  1169. var Joints_Name_Array = new Grendgine_Collada_Name_Array()
  1170. {
  1171. ID = "Joints_Name_Array_" + MakeID(t),
  1172. Count = boneCount,
  1173. };
  1174. {
  1175. var names = new StringBuilder();
  1176. {
  1177. names.AppendFormat("\n{0}", jointsDic[t].ID);
  1178. }
  1179. Joints_Name_Array.Value_Pre_Parse = names.ToString();
  1180. }
  1181. Joints_Source = new Grendgine_Collada_Source()
  1182. {
  1183. ID = "Joints_" + MakeID(t),
  1184. Name_Array = Joints_Name_Array,
  1185. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  1186. {
  1187. Accessor = new Grendgine_Collada_Accessor()
  1188. {
  1189. Count = (uint)Joints_Name_Array.Count,
  1190. Source = "#" + Joints_Name_Array.ID,
  1191. Param = new Grendgine_Collada_Param[]
  1192. {
  1193. new Grendgine_Collada_Param()
  1194. {
  1195. Type = "name",
  1196. },
  1197. },
  1198. },
  1199. },
  1200. };
  1201. }
  1202. #endregion
  1203. #region Weights_Source
  1204. Grendgine_Collada_Source Weights_Source;
  1205. StringBuilder weightsVCountString = new StringBuilder();
  1206. StringBuilder weightsVString = new StringBuilder();
  1207. List<float> weightList = new List<float>();
  1208. {
  1209. var Weights_Float_Array = new Grendgine_Collada_Float_Array()
  1210. {
  1211. ID = "Weights_Float_Array_" + MakeID(t),
  1212. };
  1213. {
  1214. const float weight0 = 1f;
  1215. const int index0 = 0;
  1216. var sb = new StringBuilder();
  1217. for (int i = 0; i < vertexCount; i++)
  1218. {
  1219. int count = 0;
  1220. {
  1221. if (!weightList.Contains(weight0))
  1222. {
  1223. weightList.Add(weight0);
  1224. sb.AppendFormat("\n{0}", weight0);
  1225. }
  1226. weightsVString.AppendFormat("\n{0} {1}", 0, index0);
  1227. count++;
  1228. }
  1229. weightsVCountString.AppendFormat("\n{0}", count);
  1230. }
  1231. Weights_Float_Array.Count = weightList.Count;
  1232. Weights_Float_Array.Value_As_String = sb.ToString();
  1233. }
  1234. Weights_Source = new Grendgine_Collada_Source()
  1235. {
  1236. ID = "Weights_" + MakeID(t),
  1237. Float_Array = Weights_Float_Array,
  1238. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  1239. {
  1240. Accessor = new Grendgine_Collada_Accessor()
  1241. {
  1242. Count = (uint)Weights_Float_Array.Count,
  1243. Source = "#" + Weights_Float_Array.ID,
  1244. Param = new Grendgine_Collada_Param[]
  1245. {
  1246. new Grendgine_Collada_Param()
  1247. {
  1248. Type = "float",
  1249. },
  1250. },
  1251. },
  1252. },
  1253. };
  1254. }
  1255. #endregion
  1256. #region Inv_Bind_Mats_Source
  1257. Grendgine_Collada_Source Inv_Bind_Mats_Source;
  1258. {
  1259. var Inv_Bind_Mats_Float_Array = new Grendgine_Collada_Float_Array()
  1260. {
  1261. ID = "Inv_Bind_Mats_" + MakeID(t),
  1262. };
  1263. {
  1264. var sb = new StringBuilder();
  1265. for (int i = 0; i < boneCount; i++)
  1266. {
  1267. Matrix4x4 mat = Matrix4x4.identity;
  1268. for (int r = 0; r < 4; r++)
  1269. sb.AppendFormat("\n{0} {1} {2} {3}", mat[r, 0], mat[r, 1], mat[r, 2], mat[r, 3]);
  1270. }
  1271. Inv_Bind_Mats_Float_Array.Count = boneCount * 16;
  1272. Inv_Bind_Mats_Float_Array.Value_As_String = sb.ToString();
  1273. }
  1274. Inv_Bind_Mats_Source = new Grendgine_Collada_Source()
  1275. {
  1276. ID = "Inv_Bind_Mats_" + MakeID(t),
  1277. Float_Array = Inv_Bind_Mats_Float_Array,
  1278. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  1279. {
  1280. Accessor = new Grendgine_Collada_Accessor()
  1281. {
  1282. Count = (uint)(Inv_Bind_Mats_Float_Array.Count / 16),
  1283. Source = "#" + Inv_Bind_Mats_Float_Array.ID,
  1284. Stride = 16,
  1285. Param = new Grendgine_Collada_Param[]
  1286. {
  1287. new Grendgine_Collada_Param()
  1288. {
  1289. Type = "float4x4",
  1290. },
  1291. },
  1292. },
  1293. },
  1294. };
  1295. }
  1296. #endregion
  1297. c = new Grendgine_Collada_Controller()
  1298. {
  1299. ID = "Controller_" + MakeID(t),
  1300. Skin = new Grendgine_Collada_Skin()
  1301. {
  1302. SourceAt = "#" + geometriesDic[t].ID,
  1303. Source = new Grendgine_Collada_Source[]
  1304. {
  1305. Joints_Source,
  1306. Weights_Source,
  1307. Inv_Bind_Mats_Source,
  1308. },
  1309. Joints = new Grendgine_Collada_Joints()
  1310. {
  1311. Input = new Grendgine_Collada_Input_Unshared[]
  1312. {
  1313. new Grendgine_Collada_Input_Unshared()
  1314. {
  1315. Semantic = Grendgine_Collada_Input_Semantic.JOINT,
  1316. source = "#" + Joints_Source.ID,
  1317. },
  1318. new Grendgine_Collada_Input_Unshared()
  1319. {
  1320. Semantic = Grendgine_Collada_Input_Semantic.INV_BIND_MATRIX,
  1321. source = "#" + Inv_Bind_Mats_Source.ID,
  1322. },
  1323. },
  1324. },
  1325. Vertex_Weights = new Grendgine_Collada_Vertex_Weights()
  1326. {
  1327. Count = (uint)vertexCount,
  1328. Input = new Grendgine_Collada_Input_Shared[]
  1329. {
  1330. new Grendgine_Collada_Input_Shared()
  1331. {
  1332. Semantic = Grendgine_Collada_Input_Semantic.JOINT,
  1333. source = "#" + Joints_Source.ID,
  1334. Offset = 0,
  1335. Set = 0,
  1336. },
  1337. new Grendgine_Collada_Input_Shared()
  1338. {
  1339. Semantic = Grendgine_Collada_Input_Semantic.WEIGHT,
  1340. source = "#" + Weights_Source.ID,
  1341. Offset = 1,
  1342. Set = 0,
  1343. },
  1344. },
  1345. VCount = new Grendgine_Collada_Int_Array_String()
  1346. {
  1347. Value_As_String = weightsVCountString.ToString(),
  1348. },
  1349. V = new Grendgine_Collada_Int_Array_String()
  1350. {
  1351. Value_As_String = weightsVString.ToString(),
  1352. },
  1353. },
  1354. },
  1355. };
  1356. #endregion
  1357. }
  1358. else
  1359. {
  1360. continue;
  1361. }
  1362. controllersDic.Add(t, c);
  1363. #region Node
  1364. nodesDic[t].Instance_Controller = new Grendgine_Collada_Instance_Controller[]
  1365. {
  1366. new Grendgine_Collada_Instance_Controller()
  1367. {
  1368. URL = "#" + c.ID,
  1369. Bind_Material = nodesDic[t].Instance_Geometry[0].Bind_Material,
  1370. },
  1371. };
  1372. nodesDic[t].Instance_Geometry = null;
  1373. #endregion
  1374. }
  1375. lc.Controller = controllersDic.Values.ToArray();
  1376. }
  1377. #endregion
  1378. #region Scene
  1379. {
  1380. gCollada.Library_Visual_Scene = new Grendgine_Collada_Library_Visual_Scenes()
  1381. {
  1382. Visual_Scene = new Grendgine_Collada_Visual_Scene[]
  1383. {
  1384. new Grendgine_Collada_Visual_Scene()
  1385. {
  1386. ID = "Scene_" + MakeID(rootObject),
  1387. Name = "Scene",
  1388. },
  1389. },
  1390. };
  1391. {
  1392. List<Grendgine_Collada_Node> nodes = new List<Grendgine_Collada_Node>();
  1393. if (makeJoint)
  1394. {
  1395. for (int i = 0; i < rootObject.transform.childCount; i++)
  1396. {
  1397. var t = rootObject.transform.GetChild(i);
  1398. if (jointsDic.ContainsKey(t))
  1399. nodes.Add(jointsDic[t]);
  1400. }
  1401. {
  1402. Func<string, string> GetUniqueName = null;
  1403. GetUniqueName = (name) =>
  1404. {
  1405. foreach (var pair in jointsDic)
  1406. {
  1407. if (pair.Value.Name == name)
  1408. return GetUniqueName(name + "_");
  1409. }
  1410. foreach (var pair in nodesDic)
  1411. {
  1412. if (pair.Value.Name == name)
  1413. return GetUniqueName(name + "_");
  1414. }
  1415. return name;
  1416. };
  1417. List<Grendgine_Collada_Node> list = new List<Grendgine_Collada_Node>();
  1418. foreach (var pair in nodesDic)
  1419. {
  1420. if (pair.Value.Instance_Geometry != null ||
  1421. pair.Value.Instance_Controller != null)
  1422. {
  1423. var node = pair.Value;
  1424. node.Name = GetUniqueName("Mesh_" + node.Name);
  1425. node.node = null;
  1426. node.Matrix = new Grendgine_Collada_Matrix[]
  1427. {
  1428. MatrixIdentity,
  1429. };
  1430. list.Add(node);
  1431. }
  1432. }
  1433. nodes.AddRange(list);
  1434. }
  1435. }
  1436. else
  1437. {
  1438. nodes.Add(nodesDic[rootObject.transform]);
  1439. }
  1440. gCollada.Library_Visual_Scene.Visual_Scene[0].Node = nodes.ToArray();
  1441. }
  1442. gCollada.Scene = new Grendgine_Collada_Scene()
  1443. {
  1444. Visual_Scene = new Grendgine_Collada_Instance_Visual_Scene()
  1445. {
  1446. URL = "#" + gCollada.Library_Visual_Scene.Visual_Scene[0].ID,
  1447. },
  1448. };
  1449. }
  1450. #endregion
  1451. #region Write
  1452. {
  1453. using (var writer = new StreamWriter(path))
  1454. {
  1455. var xmlSerializer = new XmlSerializer(typeof(Grendgine_Collada));
  1456. xmlSerializer.Serialize(writer, gCollada);
  1457. }
  1458. exportedFiles.Add(path);
  1459. }
  1460. if (clips != null)
  1461. {
  1462. var tmpObject = GameObject.Instantiate<GameObject>(rootObject);
  1463. tmpObject.hideFlags |= HideFlags.HideAndDontSave;
  1464. tmpObject.transform.SetParent(null);
  1465. tmpObject.transform.localPosition = Vector3.zero;
  1466. tmpObject.transform.localRotation = Quaternion.identity;
  1467. tmpObject.transform.localScale = Vector3.one;
  1468. { //Remove OnAnimatorMove etc
  1469. var component = tmpObject.GetComponents<Component>();
  1470. for (int i = 0; i < component.Length; i++)
  1471. {
  1472. if (component[i] is Transform || component[i] is Animator || component[i] is Animation || component[i] is Renderer || component[i] is MeshFilter) continue;
  1473. try
  1474. {
  1475. Component.DestroyImmediate(component[i]);
  1476. }
  1477. catch
  1478. {
  1479. }
  1480. }
  1481. }
  1482. Avatar tmpAvatar = null;
  1483. AnimationClip tmpClip = null;
  1484. try
  1485. {
  1486. var animator = tmpObject.GetComponent<Animator>();
  1487. if (animator != null && animator.isHuman && animator.avatar != null)
  1488. {
  1489. tmpAvatar = Avatar.Instantiate<Avatar>(animator.avatar);
  1490. tmpAvatar.hideFlags |= HideFlags.HideAndDontSave;
  1491. {
  1492. var serializedObject = new UnityEditor.SerializedObject(tmpAvatar);
  1493. var pArmStretch = serializedObject.FindProperty("m_Avatar.m_Human.data.m_ArmStretch");
  1494. pArmStretch.floatValue = 0.0001f; //Since it is occasionally wrong value when it is 0
  1495. var pLegStretch = serializedObject.FindProperty("m_Avatar.m_Human.data.m_LegStretch");
  1496. pLegStretch.floatValue = 0.0001f; //Since it is occasionally wrong value when it is 0
  1497. serializedObject.ApplyModifiedProperties();
  1498. }
  1499. animator.avatar = tmpAvatar;
  1500. }
  1501. var animation = tmpObject.GetComponent<Animation>();
  1502. if (animator != null || animation != null)
  1503. {
  1504. string[] paths = new string[transforms.Count];
  1505. Transform[] tmpTransforms = new Transform[transforms.Count];
  1506. {
  1507. Func<Transform, string, Transform> FindPathTransform = null;
  1508. FindPathTransform = (t, p) =>
  1509. {
  1510. if (AnimationUtility.CalculateTransformPath(t, tmpObject.transform) == p)
  1511. return t;
  1512. for (int i = 0; i < t.childCount; i++)
  1513. {
  1514. var rt = FindPathTransform(t.GetChild(i), p);
  1515. if (rt != null) return rt;
  1516. }
  1517. return null;
  1518. };
  1519. for (int i = 0; i < transforms.Count; i++)
  1520. {
  1521. paths[i] = AnimationUtility.CalculateTransformPath(transforms[i], rootObject.transform);
  1522. tmpTransforms[i] = FindPathTransform(tmpObject.transform, paths[i]);
  1523. }
  1524. }
  1525. foreach (var clip in clips)
  1526. {
  1527. tmpClip = AnimationClip.Instantiate<AnimationClip>(clip);
  1528. tmpClip.hideFlags |= HideFlags.HideAndDontSave;
  1529. tmpClip.name = clip.name;
  1530. AnimationUtility.SetAnimationEvents(tmpClip, new AnimationEvent[0]);
  1531. var pathAnim = path.Insert(path.LastIndexOf(".dae"), "@" + tmpClip.name);
  1532. EditorUtility.DisplayProgressBar("Exporting Collada(dae) File...", Path.GetFileName(pathAnim), (progressIndex++ / (float)progressTotal));
  1533. #region enableTransforms
  1534. bool[] enableTransforms = new bool[transforms.Count];
  1535. {
  1536. foreach (var binding in AnimationUtility.GetCurveBindings(tmpClip))
  1537. {
  1538. if (binding.type == typeof(Transform))
  1539. {
  1540. var index = ArrayUtility.IndexOf(paths, binding.path);
  1541. if (index >= 0)
  1542. enableTransforms[index] = true;
  1543. }
  1544. }
  1545. if (animator != null && animator.isHuman)
  1546. {
  1547. if (!animator.isInitialized)
  1548. animator.Rebind();
  1549. for (HumanBodyBones hi = 0; hi < HumanBodyBones.LastBone; hi++)
  1550. {
  1551. var t = animator.GetBoneTransform(hi);
  1552. while (t != null)
  1553. {
  1554. var index = ArrayUtility.IndexOf(tmpTransforms, t);
  1555. if (index >= 0)
  1556. enableTransforms[index] = true;
  1557. t = t.parent;
  1558. }
  1559. }
  1560. }
  1561. }
  1562. #endregion
  1563. #region transformCurves
  1564. TransformCurves[] transformCurves = new TransformCurves[tmpTransforms.Length];
  1565. for (int i = 0; i < tmpTransforms.Length; i++)
  1566. {
  1567. transformCurves[i] = new TransformCurves()
  1568. {
  1569. position = new AnimationCurve[]
  1570. {
  1571. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "m_LocalPosition.x")),
  1572. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "m_LocalPosition.y")),
  1573. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "m_LocalPosition.z")),
  1574. },
  1575. rotation = new AnimationCurve[]
  1576. {
  1577. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "m_LocalRotation.x")),
  1578. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "m_LocalRotation.y")),
  1579. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "m_LocalRotation.z")),
  1580. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "m_LocalRotation.w")),
  1581. },
  1582. scale = new AnimationCurve[]
  1583. {
  1584. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "m_LocalScale.x")),
  1585. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "m_LocalScale.y")),
  1586. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "m_LocalScale.z")),
  1587. },
  1588. };
  1589. if (transformCurves[i].rotation[0] == null)
  1590. {
  1591. transformCurves[i].rotation = new AnimationCurve[]
  1592. {
  1593. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "localEulerAnglesRaw.x")),
  1594. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "localEulerAnglesRaw.y")),
  1595. AnimationUtility.GetEditorCurve(tmpClip, EditorCurveBinding.FloatCurve(paths[i], typeof(Transform), "localEulerAnglesRaw.z")),
  1596. };
  1597. }
  1598. }
  1599. #endregion
  1600. AnimationClipSettings animationClipSettings = AnimationUtility.GetAnimationClipSettings(tmpClip);
  1601. var totalTime = animationClipSettings.stopTime - animationClipSettings.startTime;
  1602. #region frameTimes
  1603. float[] frameTimes;
  1604. {
  1605. var lastFrame = Mathf.RoundToInt(totalTime * tmpClip.frameRate);
  1606. frameTimes = new float[lastFrame + 1];
  1607. for (int i = 0; i <= lastFrame; i++)
  1608. {
  1609. var time = i * (1f / tmpClip.frameRate);
  1610. frameTimes[i] = Mathf.Round(time * tmpClip.frameRate) / tmpClip.frameRate;
  1611. }
  1612. }
  1613. #endregion
  1614. #region Transforms
  1615. Matrix4x4[,] tmpTransformMatrixs = new Matrix4x4[tmpTransforms.Length, frameTimes.Length];
  1616. if (animator != null)
  1617. {
  1618. animator.enabled = true;
  1619. animator.applyRootMotion = true;
  1620. animator.updateMode = AnimatorUpdateMode.Normal;
  1621. animator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
  1622. var originalAnimatorController = (animator != null) ? animator.runtimeAnimatorController : null;
  1623. var tmpAnimatorController = new UnityEditor.Animations.AnimatorController();
  1624. tmpAnimatorController.name = "Temporary Controller";
  1625. tmpAnimatorController.hideFlags |= HideFlags.HideAndDontSave;
  1626. {
  1627. tmpAnimatorController.AddLayer("Temporary Layer");
  1628. var layers = tmpAnimatorController.layers;
  1629. foreach (var layer in layers)
  1630. {
  1631. var stateMachine = layer.stateMachine;
  1632. stateMachine.hideFlags |= HideFlags.HideAndDontSave;
  1633. var state = stateMachine.AddState(tmpClip.name);
  1634. state.hideFlags |= HideFlags.HideAndDontSave;
  1635. state.iKOnFeet = settings_iKOnFeet;
  1636. state.motion = tmpClip;
  1637. layer.stateMachine = stateMachine;
  1638. }
  1639. tmpAnimatorController.layers = layers;
  1640. }
  1641. UnityEditor.Animations.AnimatorController.SetAnimatorController(animator, tmpAnimatorController);
  1642. if (!animator.isInitialized)
  1643. animator.Rebind();
  1644. #region ResetTransform
  1645. {
  1646. tmpTransforms[0].localPosition = Vector3.zero;
  1647. tmpTransforms[0].localRotation = Quaternion.identity;
  1648. tmpTransforms[0].localScale = Vector3.one;
  1649. }
  1650. for (int i = 1; i < transforms.Count; i++)
  1651. {
  1652. tmpTransforms[i].localPosition = transforms[i].localPosition;
  1653. tmpTransforms[i].localRotation = transforms[i].localRotation;
  1654. tmpTransforms[i].localScale = transforms[i].localScale;
  1655. }
  1656. #endregion
  1657. {
  1658. if (animator.isHuman)
  1659. {
  1660. #region Humanoid
  1661. animator.Play(tmpClip.name);
  1662. animator.Update(0f);
  1663. for (int i = 0; i < frameTimes.Length; i++)
  1664. {
  1665. tmpClip.SampleAnimation(tmpObject, frameTimes[i]); //It is not essential. Workarounds for unknown bugs where hair etc. are not reflected correctly.
  1666. var currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0);
  1667. var time = currentAnimatorStateInfo.length * currentAnimatorStateInfo.normalizedTime;
  1668. animator.Update(frameTimes[i] - time);
  1669. for (int j = 0; j < tmpTransforms.Length; j++)
  1670. {
  1671. var position = transformCurves[j].GetPosition(frameTimes[i]);
  1672. var rotation = transformCurves[j].GetRotation(frameTimes[i]);
  1673. var scale = transformCurves[j].GetScale(frameTimes[i]);
  1674. tmpTransformMatrixs[j, i] = Matrix4x4.TRS(position.HasValue ? position.Value : tmpTransforms[j].localPosition,
  1675. rotation.HasValue ? rotation.Value : tmpTransforms[j].localRotation,
  1676. scale.HasValue ? scale.Value : tmpTransforms[j].localScale);
  1677. }
  1678. }
  1679. #region BakeRootMotion
  1680. {
  1681. int bakeIndex = -1;
  1682. {
  1683. var t = animator.GetBoneTransform(HumanBodyBones.Hips);
  1684. while (t.parent != tmpObject.transform)
  1685. t = t.parent;
  1686. bakeIndex = ArrayUtility.IndexOf(tmpTransforms, t);
  1687. }
  1688. if (bakeIndex >= 0)
  1689. {
  1690. for (int i = 0; i < frameTimes.Length; i++)
  1691. {
  1692. tmpTransformMatrixs[bakeIndex, i] = tmpTransformMatrixs[0, i] * tmpTransformMatrixs[bakeIndex, i];
  1693. }
  1694. for (int i = 0; i < frameTimes.Length; i++)
  1695. {
  1696. tmpTransformMatrixs[0, i] = Matrix4x4.identity;
  1697. }
  1698. }
  1699. }
  1700. #endregion
  1701. #endregion
  1702. }
  1703. else
  1704. {
  1705. #region Generic
  1706. for (int i = 0; i < frameTimes.Length; i++)
  1707. {
  1708. tmpClip.SampleAnimation(tmpObject, frameTimes[i]);
  1709. for (int j = 0; j < tmpTransforms.Length; j++)
  1710. {
  1711. var position = transformCurves[j].GetPosition(frameTimes[i]);
  1712. var rotation = transformCurves[j].GetRotation(frameTimes[i]);
  1713. var scale = transformCurves[j].GetScale(frameTimes[i]);
  1714. tmpTransformMatrixs[j, i] = Matrix4x4.TRS(position.HasValue ? position.Value : tmpTransforms[j].localPosition,
  1715. rotation.HasValue ? rotation.Value : tmpTransforms[j].localRotation,
  1716. scale.HasValue ? scale.Value : tmpTransforms[j].localScale);
  1717. }
  1718. }
  1719. #endregion
  1720. }
  1721. }
  1722. {
  1723. var layerCount = tmpAnimatorController.layers.Length;
  1724. var parameterCount = tmpAnimatorController.parameters.Length;
  1725. for (int i = 0; i < layerCount; i++)
  1726. tmpAnimatorController.RemoveLayer(0);
  1727. for (int i = 0; i < parameterCount; i++)
  1728. tmpAnimatorController.RemoveParameter(0);
  1729. }
  1730. UnityEditor.Animations.AnimatorController.DestroyImmediate(tmpAnimatorController);
  1731. tmpAnimatorController = null;
  1732. animator.runtimeAnimatorController = originalAnimatorController;
  1733. }
  1734. else if (animation != null)
  1735. {
  1736. #region Legacy
  1737. for (int i = 0; i < frameTimes.Length; i++)
  1738. {
  1739. tmpClip.SampleAnimation(tmpObject, frameTimes[i]);
  1740. for (int j = 0; j < tmpTransforms.Length; j++)
  1741. {
  1742. var position = transformCurves[j].GetPosition(frameTimes[i]);
  1743. var rotation = transformCurves[j].GetRotation(frameTimes[i]);
  1744. var scale = transformCurves[j].GetScale(frameTimes[i]);
  1745. tmpTransformMatrixs[j, i] = Matrix4x4.TRS(position.HasValue ? position.Value : tmpTransforms[j].localPosition,
  1746. rotation.HasValue ? rotation.Value : tmpTransforms[j].localRotation,
  1747. scale.HasValue ? scale.Value : tmpTransforms[j].localScale);
  1748. }
  1749. }
  1750. #endregion
  1751. }
  1752. #endregion
  1753. #region Animations
  1754. var animationsDic = new Dictionary<AnimationClip, Grendgine_Collada_Animation>();
  1755. {
  1756. var la = gCollada.Library_Animations = new Grendgine_Collada_Library_Animations()
  1757. {
  1758. ID = "Animations_" + MakeID(rootObject),
  1759. Name = "Animations_" + rootObject.name,
  1760. };
  1761. {
  1762. List<Grendgine_Collada_Animation> animations = new List<Grendgine_Collada_Animation>();
  1763. for (int j = 0; j < tmpTransforms.Length; j++)
  1764. {
  1765. if (!enableTransforms[j])
  1766. continue;
  1767. if (makeJoint)
  1768. {
  1769. if (!jointsDic.ContainsKey(transforms[j]))
  1770. continue;
  1771. if (jointsDic[transforms[j]].Type != Grendgine_Collada_Node_Type.JOINT)
  1772. continue;
  1773. }
  1774. else
  1775. {
  1776. if (!nodesDic.ContainsKey(transforms[j]))
  1777. continue;
  1778. }
  1779. #region InputSource
  1780. Grendgine_Collada_Source InputSource;
  1781. {
  1782. var Input_Float_Array = new Grendgine_Collada_Float_Array()
  1783. {
  1784. ID = "Input_Float_Array_" + MakeID(transforms[j]),
  1785. Count = frameTimes.Length,
  1786. };
  1787. {
  1788. var sb = new StringBuilder();
  1789. for (int i = 0; i < frameTimes.Length; i++)
  1790. {
  1791. sb.AppendFormat("\n{0}", frameTimes[i]);
  1792. }
  1793. Input_Float_Array.Value_As_String = sb.ToString();
  1794. }
  1795. InputSource = new Grendgine_Collada_Source()
  1796. {
  1797. ID = "InputSource_" + MakeID(transforms[j]),
  1798. Float_Array = Input_Float_Array,
  1799. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  1800. {
  1801. Accessor = new Grendgine_Collada_Accessor()
  1802. {
  1803. Count = (uint)Input_Float_Array.Count,
  1804. Source = "#" + Input_Float_Array.ID,
  1805. Param = new Grendgine_Collada_Param[]
  1806. {
  1807. new Grendgine_Collada_Param()
  1808. {
  1809. Name = "TIME",
  1810. Type = "float",
  1811. },
  1812. },
  1813. },
  1814. },
  1815. };
  1816. }
  1817. #endregion
  1818. #region OutputSource
  1819. Grendgine_Collada_Source OutputSource;
  1820. {
  1821. var Output_Float_Array = new Grendgine_Collada_Float_Array()
  1822. {
  1823. ID = "Output_Float_Array_" + MakeID(transforms[j]),
  1824. Count = frameTimes.Length * 16,
  1825. };
  1826. {
  1827. var sb = new StringBuilder();
  1828. for (int i = 0; i < frameTimes.Length; i++)
  1829. {
  1830. Matrix4x4 mat = tmpTransformMatrixs[j, i];
  1831. {
  1832. var position = mat.GetColumn(3);
  1833. var rotation = (mat.GetColumn(2).sqrMagnitude > 0f && mat.GetColumn(1).sqrMagnitude > 0f) ? Quaternion.LookRotation(mat.GetColumn(2), mat.GetColumn(1)) : Quaternion.identity;
  1834. var scale = new Vector3(mat.GetColumn(0).magnitude, mat.GetColumn(1).magnitude, mat.GetColumn(2).magnitude);
  1835. #region Do not allow scale zero
  1836. {
  1837. for (int si = 0; si < 3; si++)
  1838. {
  1839. if (scale[si] == 0f)
  1840. scale[si] = Mathf.Epsilon;
  1841. }
  1842. }
  1843. #endregion
  1844. mat = Matrix4x4.TRS(matMirrorX.MultiplyPoint3x4(position),
  1845. new Quaternion(rotation.x, -rotation.y, -rotation.z, rotation.w), //mirrorX
  1846. scale);
  1847. }
  1848. for (int r = 0; r < 4; r++)
  1849. sb.AppendFormat("\n{0} {1} {2} {3}", mat[r, 0], mat[r, 1], mat[r, 2], mat[r, 3]);
  1850. }
  1851. Output_Float_Array.Value_As_String = sb.ToString();
  1852. }
  1853. OutputSource = new Grendgine_Collada_Source()
  1854. {
  1855. ID = "OutputSource_" + MakeID(transforms[j]),
  1856. Float_Array = Output_Float_Array,
  1857. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  1858. {
  1859. Accessor = new Grendgine_Collada_Accessor()
  1860. {
  1861. Count = (uint)(Output_Float_Array.Count / 16),
  1862. Source = "#" + Output_Float_Array.ID,
  1863. Stride = 16,
  1864. Param = new Grendgine_Collada_Param[]
  1865. {
  1866. new Grendgine_Collada_Param()
  1867. {
  1868. Name = "TRANSFORM",
  1869. Type = "float4x4",
  1870. },
  1871. }
  1872. },
  1873. },
  1874. };
  1875. }
  1876. #endregion
  1877. #region InterpolationSource
  1878. Grendgine_Collada_Source InterpolationSource;
  1879. {
  1880. var Interpolation_Name_Array = new Grendgine_Collada_Name_Array()
  1881. {
  1882. ID = "Interpolation_Name_Array" + MakeID(transforms[j]),
  1883. Count = frameTimes.Length,
  1884. };
  1885. {
  1886. var sb = new StringBuilder();
  1887. for (int i = 0; i < frameTimes.Length; i++)
  1888. {
  1889. sb.AppendFormat("\n{0}", "LINEAR");
  1890. }
  1891. Interpolation_Name_Array.Value_Pre_Parse = sb.ToString();
  1892. }
  1893. InterpolationSource = new Grendgine_Collada_Source()
  1894. {
  1895. ID = "InterpolationSource_" + MakeID(transforms[j]),
  1896. Name_Array = Interpolation_Name_Array,
  1897. Technique_Common = new Grendgine_Collada_Technique_Common_Source()
  1898. {
  1899. Accessor = new Grendgine_Collada_Accessor()
  1900. {
  1901. Count = (uint)Interpolation_Name_Array.Count,
  1902. Source = "#" + Interpolation_Name_Array.ID,
  1903. Param = new Grendgine_Collada_Param[]
  1904. {
  1905. new Grendgine_Collada_Param()
  1906. {
  1907. Name = "INTERPOLATION",
  1908. Type = "name",
  1909. },
  1910. },
  1911. },
  1912. },
  1913. };
  1914. }
  1915. #endregion
  1916. #region Sampler
  1917. var Sampler = new Grendgine_Collada_Sampler[]
  1918. {
  1919. new Grendgine_Collada_Sampler()
  1920. {
  1921. ID = "Sampler_" + MakeID(transforms[j]),
  1922. Input = new Grendgine_Collada_Input_Unshared[]
  1923. {
  1924. new Grendgine_Collada_Input_Unshared()
  1925. {
  1926. Semantic = Grendgine_Collada_Input_Semantic.INPUT,
  1927. source = "#" + InputSource.ID,
  1928. },
  1929. new Grendgine_Collada_Input_Unshared()
  1930. {
  1931. Semantic = Grendgine_Collada_Input_Semantic.OUTPUT,
  1932. source = "#" + OutputSource.ID,
  1933. },
  1934. new Grendgine_Collada_Input_Unshared()
  1935. {
  1936. Semantic = Grendgine_Collada_Input_Semantic.INTERPOLATION,
  1937. source = "#" + InterpolationSource.ID,
  1938. },
  1939. },
  1940. },
  1941. };
  1942. #endregion
  1943. var a = new Grendgine_Collada_Animation()
  1944. {
  1945. ID = "Animation_" + MakeID(transforms[j]),
  1946. Source = new Grendgine_Collada_Source[]
  1947. {
  1948. InputSource,
  1949. OutputSource,
  1950. InterpolationSource,
  1951. },
  1952. Sampler = Sampler,
  1953. Channel = new Grendgine_Collada_Channel[]
  1954. {
  1955. new Grendgine_Collada_Channel()
  1956. {
  1957. Source = "#" + Sampler[0].ID,
  1958. Target = (makeJoint ? jointsDic[transforms[j]].sID : nodesDic[transforms[j]].sID) + "/transform",
  1959. },
  1960. },
  1961. };
  1962. animations.Add(a);
  1963. }
  1964. var ra = new Grendgine_Collada_Animation()
  1965. {
  1966. ID = "Animation_" + MakeID(tmpClip),
  1967. Name = "Animation_" + tmpClip.name,
  1968. Animation = animations.ToArray(),
  1969. };
  1970. animationsDic.Add(tmpClip, ra);
  1971. }
  1972. la.Animation = animationsDic.Values.ToArray();
  1973. }
  1974. #endregion
  1975. #region AnimationClips
  1976. var animationClipsDic = new Dictionary<AnimationClip, Grendgine_Collada_Animation_Clip>();
  1977. {
  1978. var la = gCollada.Library_Animation_Clips = new Grendgine_Collada_Library_Animation_Clips()
  1979. {
  1980. ID = "Animation_Clips_" + MakeID(rootObject),
  1981. Name = "Animation_Clips_" + rootObject.name,
  1982. };
  1983. {
  1984. var ac = new Grendgine_Collada_Animation_Clip()
  1985. {
  1986. ID = "Animation_Clips_" + MakeID(tmpClip),
  1987. Name = tmpClip.name,
  1988. Start = 0f,
  1989. End = totalTime,
  1990. Instance_Animation = new Grendgine_Collada_Instance_Animation[1]
  1991. {
  1992. new Grendgine_Collada_Instance_Animation()
  1993. {
  1994. URL = "#" + animationsDic[tmpClip].ID,
  1995. },
  1996. },
  1997. };
  1998. animationClipsDic.Add(tmpClip, ac);
  1999. }
  2000. la.Animation_Clip = animationClipsDic.Values.ToArray();
  2001. }
  2002. #endregion
  2003. #region Scene
  2004. {
  2005. var Doc = new System.Xml.XmlDocument();
  2006. var frame_rate = Doc.CreateElement("frame_rate");
  2007. {
  2008. frame_rate.InnerText = tmpClip.frameRate.ToString();
  2009. }
  2010. var start_time = Doc.CreateElement("start_time");
  2011. {
  2012. start_time.InnerText = 0f.ToString();
  2013. }
  2014. var end_time = Doc.CreateElement("end_time");
  2015. {
  2016. end_time.InnerText = totalTime.ToString();
  2017. }
  2018. gCollada.Library_Visual_Scene.Visual_Scene[0].Extra = new Grendgine_Collada_Extra[]
  2019. {
  2020. new Grendgine_Collada_Extra()
  2021. {
  2022. Technique = new Grendgine_Collada_Technique[]
  2023. {
  2024. new Grendgine_Collada_Technique()
  2025. {
  2026. profile = "MAX3D",
  2027. Data = new System.Xml.XmlElement[]
  2028. {
  2029. frame_rate,
  2030. },
  2031. },
  2032. new Grendgine_Collada_Technique()
  2033. {
  2034. profile = "FCOLLADA",
  2035. Data = new System.Xml.XmlElement[]
  2036. {
  2037. start_time,
  2038. end_time,
  2039. },
  2040. },
  2041. },
  2042. },
  2043. };
  2044. }
  2045. #endregion
  2046. using (var writer = new StreamWriter(pathAnim))
  2047. {
  2048. var xmlSerializer = new XmlSerializer(typeof(Grendgine_Collada));
  2049. xmlSerializer.Serialize(writer, gCollada);
  2050. }
  2051. exportedFiles.Add(pathAnim);
  2052. }
  2053. }
  2054. AnimationClip.DestroyImmediate(tmpClip);
  2055. tmpClip = null;
  2056. }
  2057. finally
  2058. {
  2059. GameObject.DestroyImmediate(tmpObject);
  2060. if (tmpAvatar != null)
  2061. Avatar.DestroyImmediate(tmpAvatar);
  2062. if (tmpClip != null)
  2063. AnimationClip.DestroyImmediate(tmpClip);
  2064. }
  2065. }
  2066. #endregion
  2067. }
  2068. finally
  2069. {
  2070. #region TransformSave
  2071. for (int i = 0; i < transforms.Count; i++)
  2072. {
  2073. transformSaves[i].Load(transforms[i]);
  2074. }
  2075. #endregion
  2076. EditorUtility.ClearProgressBar();
  2077. }
  2078. return true;
  2079. }
  2080. #region Settings
  2081. public bool settings_exportMesh = true;
  2082. public bool settings_iKOnFeet = true;
  2083. #endregion
  2084. public List<string> exportedFiles = new List<string>();
  2085. private class TransformSave
  2086. {
  2087. public Vector3 localPosition;
  2088. public Quaternion localRotation;
  2089. public Vector3 localScale;
  2090. public TransformSave(Transform t)
  2091. {
  2092. localPosition = t.localPosition;
  2093. localRotation = t.localRotation;
  2094. localScale = t.localScale;
  2095. }
  2096. public void Load(Transform t)
  2097. {
  2098. t.localPosition = localPosition;
  2099. t.localRotation = localRotation;
  2100. t.localScale = localScale;
  2101. }
  2102. }
  2103. private class TransformCurves
  2104. {
  2105. public AnimationCurve[] position;
  2106. public AnimationCurve[] rotation;
  2107. public AnimationCurve[] scale;
  2108. public Vector3? GetPosition(float time)
  2109. {
  2110. Vector3 result = Vector3.zero;
  2111. int count = 0;
  2112. for (int i = 0; i < position.Length; i++)
  2113. {
  2114. if (position[i] == null) continue;
  2115. result[i] = position[i].Evaluate(time);
  2116. count++;
  2117. }
  2118. if (count == 3) return result;
  2119. else return null;
  2120. }
  2121. public Quaternion? GetRotation(float time)
  2122. {
  2123. if (rotation.Length == 3)
  2124. {
  2125. Vector3 result = Vector3.zero;
  2126. int count = 0;
  2127. for (int i = 0; i < rotation.Length; i++)
  2128. {
  2129. if (rotation[i] == null) continue;
  2130. result[i] = rotation[i].Evaluate(time);
  2131. count++;
  2132. }
  2133. if (count == 3) return Quaternion.Euler(result);
  2134. else return null;
  2135. }
  2136. else
  2137. {
  2138. Vector4 result = new Vector4(0, 0, 0, 1);
  2139. int count = 0;
  2140. for (int i = 0; i < rotation.Length; i++)
  2141. {
  2142. if (rotation[i] == null) continue;
  2143. result[i] = rotation[i].Evaluate(time);
  2144. count++;
  2145. }
  2146. if (count == 4 && result.sqrMagnitude > 0)
  2147. {
  2148. result.Normalize();
  2149. return new Quaternion(result[0], result[1], result[2], result[3]);
  2150. }
  2151. else
  2152. {
  2153. return null;
  2154. }
  2155. }
  2156. }
  2157. public Vector3? GetScale(float time)
  2158. {
  2159. Vector3 result = Vector3.one;
  2160. int count = 0;
  2161. for (int i = 0; i < scale.Length; i++)
  2162. {
  2163. if (scale[i] == null) continue;
  2164. result[i] = scale[i].Evaluate(time);
  2165. count++;
  2166. }
  2167. if (count == 3) return result;
  2168. else return null;
  2169. }
  2170. }
  2171. }
  2172. }