EditorAnimInfo.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using bs;
  7. namespace bs.Editor
  8. {
  9. /** @addtogroup AnimationEditor
  10. * @{
  11. */
  12. /// <summary>
  13. /// A set of animation curves for a field of a certain type.
  14. /// </summary>
  15. internal struct FieldAnimCurves
  16. {
  17. public SerializableProperty.FieldType type;
  18. public EdCurveDrawInfo[] curveInfos;
  19. public bool isPropertyCurve;
  20. }
  21. /// <summary>
  22. /// Stores tangent modes for an 3D vector animation curve (one mode for each keyframe).
  23. /// </summary>
  24. [SerializeObject]
  25. internal class EditorVector3CurveTangents
  26. {
  27. public string name;
  28. public TangentMode[] tangentsX;
  29. public TangentMode[] tangentsY;
  30. public TangentMode[] tangentsZ;
  31. }
  32. /// <summary>
  33. /// Stores tangent modes for an float animation curve (one mode for each keyframe).
  34. /// </summary>
  35. [SerializeObject]
  36. internal class EditorFloatCurveTangents
  37. {
  38. public string name;
  39. public TangentMode[] tangents;
  40. }
  41. /// <summary>
  42. /// Stores tangent information for all curves in an animation clip.
  43. /// </summary>
  44. [SerializeObject]
  45. internal class EditorAnimClipTangents
  46. {
  47. public EditorVector3CurveTangents[] positionCurves;
  48. public EditorVector3CurveTangents[] rotationCurves;
  49. public EditorVector3CurveTangents[] scaleCurves;
  50. public EditorFloatCurveTangents[] floatCurves;
  51. }
  52. /// <summary>
  53. /// Stores animation clip data for clips that are currently being edited.
  54. /// </summary>
  55. internal class EditorAnimClipInfo
  56. {
  57. public AnimationClip clip;
  58. public bool isImported;
  59. public int sampleRate;
  60. public Dictionary<string, FieldAnimCurves> curves = new Dictionary<string, FieldAnimCurves>();
  61. public AnimationEvent[] events = new AnimationEvent[0];
  62. /// <summary>
  63. /// Loads curve and event information from the provided clip, and creates a new instance of this object containing
  64. /// the required data for editing the source clip in the animation editor.
  65. /// </summary>
  66. /// <param name="clip">Clip to load.</param>
  67. /// <returns>Editor specific editable information about an animation clip.</returns>
  68. public static EditorAnimClipInfo Create(AnimationClip clip)
  69. {
  70. EditorAnimClipInfo clipInfo = new EditorAnimClipInfo();
  71. clipInfo.clip = clip;
  72. clipInfo.isImported = IsClipImported(clip);
  73. clipInfo.sampleRate = (int)clip.SampleRate;
  74. AnimationCurves clipCurves = clip.Curves;
  75. EditorAnimClipTangents editorCurveData = null;
  76. string resourcePath = ProjectLibrary.GetPath(clip);
  77. if (!string.IsNullOrEmpty(resourcePath))
  78. {
  79. LibraryEntry entry = ProjectLibrary.GetEntry(resourcePath);
  80. string clipName = PathEx.GetTail(resourcePath);
  81. if (entry != null && entry.Type == LibraryEntryType.File)
  82. {
  83. FileEntry fileEntry = (FileEntry)entry;
  84. ResourceMeta[] metas = fileEntry.ResourceMetas;
  85. if (clipInfo.isImported)
  86. {
  87. for (int i = 0; i < metas.Length; i++)
  88. {
  89. if (clipName == metas[i].SubresourceName)
  90. {
  91. editorCurveData = metas[i].EditorData as EditorAnimClipTangents;
  92. break;
  93. }
  94. }
  95. }
  96. else
  97. {
  98. if(metas.Length > 0)
  99. editorCurveData = metas[0].EditorData as EditorAnimClipTangents;
  100. }
  101. }
  102. }
  103. if (editorCurveData == null)
  104. editorCurveData = new EditorAnimClipTangents();
  105. int globalCurveIdx = 0;
  106. Action<NamedVector3Curve[], EditorVector3CurveTangents[], string> loadVector3Curve =
  107. (curves, tangents, subPath) =>
  108. {
  109. foreach (var curveEntry in curves)
  110. {
  111. TangentMode[] tangentsX = null;
  112. TangentMode[] tangentsY = null;
  113. TangentMode[] tangentsZ = null;
  114. if (tangents != null)
  115. {
  116. foreach (var tangentEntry in tangents)
  117. {
  118. if (tangentEntry.name == curveEntry.name)
  119. {
  120. tangentsX = tangentEntry.tangentsX;
  121. tangentsY = tangentEntry.tangentsY;
  122. tangentsZ = tangentEntry.tangentsZ;
  123. break;
  124. }
  125. }
  126. }
  127. // Convert compound curve to three per-component curves
  128. AnimationCurve[] componentCurves = AnimationUtility.SplitCurve3D(curveEntry.curve);
  129. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  130. fieldCurves.type = SerializableProperty.FieldType.Vector3;
  131. fieldCurves.curveInfos = new EdCurveDrawInfo[3];
  132. fieldCurves.isPropertyCurve = !clipInfo.isImported;
  133. fieldCurves.curveInfos[0] = new EdCurveDrawInfo();
  134. fieldCurves.curveInfos[0].curve = new EdAnimationCurve(componentCurves[0], tangentsX);
  135. fieldCurves.curveInfos[0].color = GetUniqueColor(globalCurveIdx++);
  136. fieldCurves.curveInfos[1] = new EdCurveDrawInfo();
  137. fieldCurves.curveInfos[1].curve = new EdAnimationCurve(componentCurves[1], tangentsY);
  138. fieldCurves.curveInfos[1].color = GetUniqueColor(globalCurveIdx++);
  139. fieldCurves.curveInfos[2] = new EdCurveDrawInfo();
  140. fieldCurves.curveInfos[2].curve = new EdAnimationCurve(componentCurves[2], tangentsZ);
  141. fieldCurves.curveInfos[2].color = GetUniqueColor(globalCurveIdx++);
  142. string curvePath = curveEntry.name.TrimEnd('/') + subPath;
  143. clipInfo.curves[curvePath] = fieldCurves;
  144. }
  145. };
  146. // Convert rotation from quaternion to euler
  147. NamedQuaternionCurve[] rotationCurves = clipCurves.Rotation;
  148. NamedVector3Curve[] eulerRotationCurves = new NamedVector3Curve[rotationCurves.Length];
  149. for(int i = 0; i < rotationCurves.Length; i++)
  150. {
  151. eulerRotationCurves[i] = new NamedVector3Curve();
  152. eulerRotationCurves[i].name = rotationCurves[i].name;
  153. eulerRotationCurves[i].flags = rotationCurves[i].flags;
  154. eulerRotationCurves[i].curve = AnimationUtility.QuaternionToEulerCurve(rotationCurves[i].curve);
  155. }
  156. loadVector3Curve(clipCurves.Position, editorCurveData.positionCurves, "/Position");
  157. loadVector3Curve(eulerRotationCurves, editorCurveData.rotationCurves, "/Rotation");
  158. loadVector3Curve(clipCurves.Scale, editorCurveData.scaleCurves, "/Scale");
  159. // Find which individual float curves belong to the same field
  160. Dictionary<string, Tuple<int, int, bool>[]> floatCurveMapping = new Dictionary<string, Tuple<int, int, bool>[]>();
  161. {
  162. int curveIdx = 0;
  163. foreach (var curveEntry in clipCurves.Generic)
  164. {
  165. string path = curveEntry.name;
  166. string pathNoSuffix = null;
  167. string pathSuffix;
  168. if (path.Length >= 2)
  169. {
  170. pathSuffix = path.Substring(path.Length - 2, 2);
  171. pathNoSuffix = path.Substring(0, path.Length - 2);
  172. }
  173. else
  174. pathSuffix = "";
  175. int tangentIdx = -1;
  176. int currentTangentIdx = 0;
  177. foreach (var tangentEntry in editorCurveData.floatCurves)
  178. {
  179. if (tangentEntry.name == curveEntry.name)
  180. {
  181. tangentIdx = currentTangentIdx;
  182. break;
  183. }
  184. currentTangentIdx++;
  185. }
  186. Animation.PropertySuffixInfo suffixInfo;
  187. if (Animation.PropertySuffixInfos.TryGetValue(pathSuffix, out suffixInfo))
  188. {
  189. Tuple<int, int, bool>[] curveInfo;
  190. if (!floatCurveMapping.TryGetValue(pathNoSuffix, out curveInfo))
  191. curveInfo = new Tuple<int, int, bool>[4];
  192. curveInfo[suffixInfo.elementIdx] = Tuple.Create(curveIdx, tangentIdx, suffixInfo.isVector);
  193. floatCurveMapping[pathNoSuffix] = curveInfo;
  194. }
  195. else
  196. {
  197. Tuple<int, int, bool>[] curveInfo = new Tuple<int, int, bool>[4];
  198. curveInfo[0] = Tuple.Create(curveIdx, tangentIdx, suffixInfo.isVector);
  199. floatCurveMapping[path] = curveInfo;
  200. }
  201. curveIdx++;
  202. }
  203. }
  204. foreach (var KVP in floatCurveMapping)
  205. {
  206. int numCurves = 0;
  207. for (int i = 0; i < 4; i++)
  208. {
  209. if (KVP.Value[i] == null)
  210. continue;
  211. numCurves++;
  212. }
  213. if (numCurves == 0)
  214. continue; // Invalid curve
  215. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  216. // Deduce type (note that all single value types are assumed to be float even if their source type is int or bool)
  217. if (numCurves == 1)
  218. fieldCurves.type = SerializableProperty.FieldType.Float;
  219. else if (numCurves == 2)
  220. fieldCurves.type = SerializableProperty.FieldType.Vector2;
  221. else if (numCurves == 3)
  222. fieldCurves.type = SerializableProperty.FieldType.Vector3;
  223. else // 4 curves
  224. {
  225. bool isVector = KVP.Value[0].Item3;
  226. if (isVector)
  227. fieldCurves.type = SerializableProperty.FieldType.Vector4;
  228. else
  229. fieldCurves.type = SerializableProperty.FieldType.Color;
  230. }
  231. bool isMorphCurve = false;
  232. string curvePath = KVP.Key;
  233. fieldCurves.curveInfos = new EdCurveDrawInfo[numCurves];
  234. for (int i = 0; i < numCurves; i++)
  235. {
  236. int curveIdx = KVP.Value[i].Item1;
  237. int tangentIdx = KVP.Value[i].Item2;
  238. TangentMode[] tangents = null;
  239. if (tangentIdx != -1)
  240. tangents = editorCurveData.floatCurves[tangentIdx].tangents;
  241. fieldCurves.curveInfos[i] = new EdCurveDrawInfo();
  242. fieldCurves.curveInfos[i].curve = new EdAnimationCurve(clipCurves.Generic[curveIdx].curve, tangents);
  243. fieldCurves.curveInfos[i].color = GetUniqueColor(globalCurveIdx++);
  244. if (clipCurves.Generic[curveIdx].flags.HasFlag(AnimationCurveFlags.MorphFrame))
  245. {
  246. curvePath = "MorphShapes/Frames/" + KVP.Key;
  247. isMorphCurve = true;
  248. }
  249. else if (clipCurves.Generic[curveIdx].flags.HasFlag(AnimationCurveFlags.MorphWeight))
  250. {
  251. curvePath = "MorphShapes/Weight/" + KVP.Key;
  252. isMorphCurve = true;
  253. }
  254. }
  255. fieldCurves.isPropertyCurve = !clipInfo.isImported && !isMorphCurve;
  256. clipInfo.curves[curvePath] = fieldCurves;
  257. }
  258. // Add events
  259. clipInfo.events = clip.Events;
  260. return clipInfo;
  261. }
  262. /// <summary>
  263. /// Checks is the specified animation clip is imported from an external file, or created within the editor.
  264. /// </summary>
  265. /// <param name="clip">Clip to check.</param>
  266. /// <returns>True if the clip is imported from an external file (e.g. FBX file), or false if the clip is a native
  267. /// resource created within the editor.</returns>
  268. public static bool IsClipImported(AnimationClip clip)
  269. {
  270. string resourcePath = ProjectLibrary.GetPath(clip);
  271. return ProjectLibrary.IsSubresource(resourcePath);
  272. }
  273. /// <summary>
  274. /// Checks does a curve with the specified path represent a curve affecting a morph shape.
  275. /// </summary>
  276. /// <param name="path">Path of the curve to check.</param>
  277. /// <returns>True if morph shape frame or weight animation, false otherwise.</returns>
  278. public static bool IsMorphShapeCurve(string path)
  279. {
  280. if (string.IsNullOrEmpty(path))
  281. return false;
  282. string trimmedPath = path.Trim('/');
  283. string[] entries = trimmedPath.Split('/');
  284. if (entries.Length < 3)
  285. return false;
  286. if (entries[entries.Length - 3] != "MorphShapes")
  287. return false;
  288. return entries[entries.Length - 2] == "Weight" || entries[entries.Length - 2] == "Frames";
  289. }
  290. /// <summary>
  291. /// Applies any changes made to the animation curves or events to the actual animation clip. Only works for
  292. /// non-imported animation clips.
  293. /// </summary>
  294. /// <param name="tangents">Tangent modes for all the saved animation curves.</param>
  295. public void Apply(out EditorAnimClipTangents tangents)
  296. {
  297. if (isImported || clip == null)
  298. {
  299. tangents = null;
  300. return;
  301. }
  302. List<NamedVector3Curve> positionCurves = new List<NamedVector3Curve>();
  303. List<NamedQuaternionCurve> rotationCurves = new List<NamedQuaternionCurve>();
  304. List<NamedVector3Curve> scaleCurves = new List<NamedVector3Curve>();
  305. List<NamedFloatCurve> floatCurves = new List<NamedFloatCurve>();
  306. List<EditorVector3CurveTangents> positionTangents = new List<EditorVector3CurveTangents>();
  307. List<EditorVector3CurveTangents> rotationTangents = new List<EditorVector3CurveTangents>();
  308. List<EditorVector3CurveTangents> scaleTangents = new List<EditorVector3CurveTangents>();
  309. List<EditorFloatCurveTangents> floatTangents = new List<EditorFloatCurveTangents>();
  310. foreach (var kvp in curves)
  311. {
  312. string[] pathEntries = kvp.Key.Split('/');
  313. if (pathEntries.Length == 0)
  314. continue;
  315. string lastEntry = pathEntries[pathEntries.Length - 1];
  316. if (lastEntry == "Position" || lastEntry == "Rotation" || lastEntry == "Scale")
  317. {
  318. StringBuilder sb = new StringBuilder();
  319. for (int i = 0; i < pathEntries.Length - 2; i++)
  320. sb.Append(pathEntries[i] + "/");
  321. if (pathEntries.Length > 1)
  322. sb.Append(pathEntries[pathEntries.Length - 2]);
  323. string curvePath = sb.ToString();
  324. NamedVector3Curve curve = new NamedVector3Curve();
  325. curve.name = curvePath;
  326. curve.curve = AnimationUtility.CombineCurve3D(new[]
  327. {
  328. new AnimationCurve(kvp.Value.curveInfos[0].curve.KeyFrames),
  329. new AnimationCurve(kvp.Value.curveInfos[1].curve.KeyFrames),
  330. new AnimationCurve(kvp.Value.curveInfos[2].curve.KeyFrames)
  331. });
  332. EditorVector3CurveTangents curveTangents = new EditorVector3CurveTangents();
  333. curveTangents.name = curvePath;
  334. curveTangents.tangentsX = kvp.Value.curveInfos[0].curve.TangentModes;
  335. curveTangents.tangentsY = kvp.Value.curveInfos[1].curve.TangentModes;
  336. curveTangents.tangentsZ = kvp.Value.curveInfos[2].curve.TangentModes;
  337. if (lastEntry == "Position")
  338. {
  339. positionCurves.Add(curve);
  340. positionTangents.Add(curveTangents);
  341. }
  342. else if (lastEntry == "Rotation")
  343. {
  344. NamedQuaternionCurve quatCurve = new NamedQuaternionCurve();
  345. quatCurve.name = curve.name;
  346. quatCurve.curve = AnimationUtility.EulerToQuaternionCurve(curve.curve);
  347. rotationCurves.Add(quatCurve);
  348. rotationTangents.Add(curveTangents);
  349. }
  350. else if (lastEntry == "Scale")
  351. {
  352. scaleCurves.Add(curve);
  353. scaleTangents.Add(curveTangents);
  354. }
  355. }
  356. else
  357. {
  358. Action<int, string, string, AnimationCurveFlags> addCurve = (idx, path, subPath, flags) =>
  359. {
  360. string fullPath = path + subPath;
  361. NamedFloatCurve curve = new NamedFloatCurve(fullPath,
  362. new AnimationCurve(kvp.Value.curveInfos[idx].curve.KeyFrames));
  363. curve.flags = flags;
  364. EditorFloatCurveTangents curveTangents = new EditorFloatCurveTangents();
  365. curveTangents.name = fullPath;
  366. curveTangents.tangents = kvp.Value.curveInfos[idx].curve.TangentModes;
  367. floatCurves.Add(curve);
  368. floatTangents.Add(curveTangents);
  369. };
  370. switch (kvp.Value.type)
  371. {
  372. case SerializableProperty.FieldType.Vector2:
  373. addCurve(0, kvp.Key, ".x", 0);
  374. addCurve(1, kvp.Key, ".y", 0);
  375. break;
  376. case SerializableProperty.FieldType.Vector3:
  377. addCurve(0, kvp.Key, ".x", 0);
  378. addCurve(1, kvp.Key, ".y", 0);
  379. addCurve(2, kvp.Key, ".z", 0);
  380. break;
  381. case SerializableProperty.FieldType.Vector4:
  382. addCurve(0, kvp.Key, ".x", 0);
  383. addCurve(1, kvp.Key, ".y", 0);
  384. addCurve(2, kvp.Key, ".z", 0);
  385. addCurve(3, kvp.Key, ".w", 0);
  386. break;
  387. case SerializableProperty.FieldType.Color:
  388. addCurve(0, kvp.Key, ".r", 0);
  389. addCurve(1, kvp.Key, ".g", 0);
  390. addCurve(2, kvp.Key, ".b", 0);
  391. addCurve(3, kvp.Key, ".a", 0);
  392. break;
  393. case SerializableProperty.FieldType.Bool:
  394. case SerializableProperty.FieldType.Int:
  395. case SerializableProperty.FieldType.Float:
  396. {
  397. AnimationCurveFlags flags = 0;
  398. string path = kvp.Key;
  399. if (IsMorphShapeCurve(kvp.Key))
  400. {
  401. string trimmedPath = path.Trim('/');
  402. string[] entries = trimmedPath.Split('/');
  403. bool isWeight = entries[entries.Length - 2] == "Weight";
  404. if (isWeight)
  405. flags = AnimationCurveFlags.MorphWeight;
  406. else
  407. flags = AnimationCurveFlags.MorphFrame;
  408. path = entries[entries.Length - 1];
  409. }
  410. addCurve(0, path, "", flags);
  411. }
  412. break;
  413. }
  414. }
  415. }
  416. AnimationCurves newClipCurves = new AnimationCurves();
  417. newClipCurves.Position = positionCurves.ToArray();
  418. newClipCurves.Rotation = rotationCurves.ToArray();
  419. newClipCurves.Scale = scaleCurves.ToArray();
  420. newClipCurves.Generic = floatCurves.ToArray();
  421. clip.Curves = newClipCurves;
  422. clip.Events = events;
  423. clip.SampleRate = sampleRate;
  424. tangents = new EditorAnimClipTangents();
  425. tangents.positionCurves = positionTangents.ToArray();
  426. tangents.rotationCurves = rotationTangents.ToArray();
  427. tangents.scaleCurves = scaleTangents.ToArray();
  428. tangents.floatCurves = floatTangents.ToArray();
  429. }
  430. /// <summary>
  431. /// Saves the animation curves and events stored in this object, into the associated animation clip resource.
  432. /// Relevant animation clip resource must already be created and exist in the project library.
  433. /// </summary>
  434. public void SaveToClip()
  435. {
  436. if (!isImported)
  437. {
  438. EditorAnimClipTangents tangents;
  439. Apply(out tangents);
  440. string resourcePath = ProjectLibrary.GetPath(clip);
  441. ProjectLibrary.Save(clip);
  442. ProjectLibrary.SetEditorData(resourcePath, tangents);
  443. }
  444. else
  445. {
  446. string resourcePath = ProjectLibrary.GetPath(clip);
  447. LibraryEntry entry = ProjectLibrary.GetEntry(resourcePath);
  448. if (entry != null && entry.Type == LibraryEntryType.File)
  449. {
  450. FileEntry fileEntry = (FileEntry)entry;
  451. MeshImportOptions meshImportOptions = (MeshImportOptions)fileEntry.Options;
  452. string clipName = PathEx.GetTail(resourcePath);
  453. List<ImportedAnimationEvents> newEvents = new List<ImportedAnimationEvents>();
  454. newEvents.AddRange(meshImportOptions.AnimationEvents);
  455. bool isExisting = false;
  456. for (int i = 0; i < newEvents.Count; i++)
  457. {
  458. if (newEvents[i].Name == clipName)
  459. {
  460. newEvents[i].Events = events;
  461. isExisting = true;
  462. break;
  463. }
  464. }
  465. if (!isExisting)
  466. {
  467. ImportedAnimationEvents newEntry = new ImportedAnimationEvents();
  468. newEntry.Name = clipName;
  469. newEntry.Events = events;
  470. newEvents.Add(newEntry);
  471. }
  472. meshImportOptions.AnimationEvents = newEvents.ToArray();
  473. ProjectLibrary.Reimport(resourcePath, meshImportOptions, true);
  474. }
  475. }
  476. }
  477. /// <summary>
  478. /// Generates a unique color based on the provided index.
  479. /// </summary>
  480. /// <param name="idx">Index to use for generating a color. Should be less than 30 in order to guarantee reasonably
  481. /// different colors.</param>
  482. /// <returns>Unique color.</returns>
  483. public static Color GetUniqueColor(int idx)
  484. {
  485. const int COLOR_SPACING = 359 / 15;
  486. float hue = ((idx * COLOR_SPACING) % 359) / 359.0f;
  487. return Color.HSV2RGB(new Color(hue, 175.0f / 255.0f, 175.0f / 255.0f));
  488. }
  489. }
  490. /** @} */
  491. }