Animation.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  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.Runtime.InteropServices;
  6. using System.Text;
  7. namespace BansheeEngine
  8. {
  9. /** @addtogroup Animation
  10. * @{
  11. */
  12. /// <summary>
  13. /// Handles animation playback. Takes one or multiple animation clips as input and evaluates them every animation update
  14. /// tick depending on set properties.The evaluated data is used by the core thread for skeletal animation, by the sim
  15. /// thread for updating attached scene objects and bones (if skeleton is attached), or the data is made available for
  16. /// manual queries in the case of generic animation.
  17. /// </summary>
  18. public class Animation : Component
  19. {
  20. private NativeAnimation _native;
  21. [SerializeField] private SerializableData serializableData = new SerializableData();
  22. private FloatCurvePropertyInfo[] floatProperties;
  23. private List<SceneObjectMappingInfo> mappingInfo = new List<SceneObjectMappingInfo>();
  24. private AnimationClip primaryClip;
  25. private Renderable animatedRenderable;
  26. private State state = State.Inactive;
  27. /// <summary>
  28. /// Contains mapping for a suffix used by property paths used for curve identifiers, to their index and type.
  29. /// </summary>
  30. internal static readonly Dictionary<string, PropertySuffixInfo> PropertySuffixInfos = new Dictionary
  31. <string, PropertySuffixInfo>
  32. {
  33. {".x", new PropertySuffixInfo(0, true)},
  34. {".y", new PropertySuffixInfo(1, true)},
  35. {".z", new PropertySuffixInfo(2, true)},
  36. {".w", new PropertySuffixInfo(3, true)},
  37. {".r", new PropertySuffixInfo(0, false)},
  38. {".g", new PropertySuffixInfo(1, false)},
  39. {".b", new PropertySuffixInfo(2, false)},
  40. {".a", new PropertySuffixInfo(3, false)}
  41. };
  42. /// <summary>
  43. /// Returns the non-component version of Animation that is wrapped by this component.
  44. /// </summary>
  45. internal NativeAnimation Native
  46. {
  47. get { return _native; }
  48. }
  49. /// <summary>
  50. /// Determines the default clip to play as soon as the component is enabled. If more control over playing clips is
  51. /// needed use the <see cref="Play"/>, <see cref="Blend1D"/>, <see cref="Blend2D"/> and <see cref="CrossFade"/>
  52. /// methods to queue clips for playback manually, and <see cref="SetState"/> method for modify their states
  53. /// individually.
  54. /// </summary>
  55. public AnimationClip DefaultClip
  56. {
  57. get { return serializableData.defaultClip; }
  58. set
  59. {
  60. serializableData.defaultClip = value;
  61. if (value != null)
  62. {
  63. switch (state)
  64. {
  65. case State.Active:
  66. _native.Play(value);
  67. break;
  68. }
  69. }
  70. }
  71. }
  72. /// <summary>
  73. /// Determines the wrap mode for all active animations. Wrap mode determines what happens when animation reaches the
  74. /// first or last frame.
  75. /// <see cref="AnimWrapMode"/>
  76. /// </summary>
  77. public AnimWrapMode WrapMode
  78. {
  79. get { return serializableData.wrapMode; }
  80. set
  81. {
  82. serializableData.wrapMode = value;
  83. switch (state)
  84. {
  85. case State.Active:
  86. _native.WrapMode = value;
  87. break;
  88. }
  89. }
  90. }
  91. /// <summary>
  92. /// Determines the speed for all animations. The default value is 1.0f. Use negative values to play-back in reverse.
  93. /// </summary>
  94. public float Speed
  95. {
  96. get { return serializableData.speed; }
  97. set
  98. {
  99. serializableData.speed = value;
  100. switch (state)
  101. {
  102. case State.Active:
  103. _native.Speed = value;
  104. break;
  105. }
  106. }
  107. }
  108. /// <summary>
  109. /// Checks if any animation clips are currently playing.
  110. /// </summary>
  111. public bool IsPlaying
  112. {
  113. get
  114. {
  115. switch (state)
  116. {
  117. case State.Active:
  118. return _native.IsPlaying();
  119. default:
  120. return false;
  121. }
  122. }
  123. }
  124. /// <summary>
  125. /// Sets bounds that will be used for animation and mesh culling. Only relevant if <see cref="UseBounds"/> is set
  126. /// to true.
  127. /// </summary>
  128. public AABox Bounds
  129. {
  130. get { return serializableData.bounds; }
  131. set
  132. {
  133. serializableData.bounds = value;
  134. if (serializableData.useBounds)
  135. {
  136. if (animatedRenderable != null && animatedRenderable.Native != null)
  137. animatedRenderable.Native.OverrideBounds = value;
  138. AABox bounds = serializableData.bounds;
  139. Matrix4 parentTfrm;
  140. if (SceneObject.Parent != null)
  141. parentTfrm = SceneObject.Parent.WorldTransform;
  142. else
  143. parentTfrm = Matrix4.Identity;
  144. bounds.TransformAffine(parentTfrm);
  145. switch (state)
  146. {
  147. case State.Active:
  148. _native.Bounds = bounds;
  149. break;
  150. }
  151. }
  152. }
  153. }
  154. /// <summary>
  155. /// Determines should animation bounds be used for visibility determination (culling). If false the bounds of the
  156. /// mesh attached to the relevant <see cref="Renderable"/> component will be used instead.
  157. /// </summary>
  158. public bool UseBounds
  159. {
  160. get { return serializableData.useBounds; }
  161. set
  162. {
  163. serializableData.useBounds = value;
  164. UpdateBounds();
  165. }
  166. }
  167. /// <summary>
  168. /// If true, the animation will not be evaluated when it is out of view.
  169. /// </summary>
  170. public bool Cull
  171. {
  172. get { return serializableData.cull; }
  173. set
  174. {
  175. serializableData.cull = value;
  176. switch (state)
  177. {
  178. case State.Active:
  179. _native.Cull = value;
  180. break;
  181. }
  182. }
  183. }
  184. /// <summary>
  185. /// Plays the specified animation clip.
  186. /// </summary>
  187. /// <param name="clip">Clip to play.</param>
  188. public void Play(AnimationClip clip)
  189. {
  190. switch (state)
  191. {
  192. case State.Active:
  193. _native.Play(clip);
  194. break;
  195. }
  196. }
  197. /// <summary>
  198. /// Plays the specified animation clip on top of the animation currently playing in the main layer. Multiple such
  199. /// clips can be playing at once, as long as you ensure each is given its own layer. Each animation can also have a
  200. /// weight that determines how much it influences the main animation.
  201. /// </summary>
  202. /// <param name="clip">Clip to additively blend. Must contain additive animation curves.</param>
  203. /// <param name="weight">Determines how much of an effect will the blended animation have on the final output.
  204. /// In range [0, 1].</param>
  205. /// <param name="fadeLength">Applies the blend over a specified time period, increasing the weight as the time
  206. /// passes. Set to zero to blend immediately. In seconds.</param>
  207. /// <param name="layer">Layer to play the clip in. Multiple additive clips can be playing at once in separate layers
  208. /// and each layer has its own weight.</param>
  209. public void BlendAdditive(AnimationClip clip, float weight, float fadeLength, int layer)
  210. {
  211. switch (state)
  212. {
  213. case State.Active:
  214. _native.BlendAdditive(clip, weight, fadeLength, layer);
  215. break;
  216. }
  217. }
  218. /// <summary>
  219. /// Blends multiple animation clips between each other using linear interpolation. Unlike normal animations these
  220. /// animations are not advanced with the progress of time, and is instead expected the user manually changes the
  221. /// <see cref="t"/> parameter.
  222. /// </summary>
  223. /// <param name="info">Information about the clips to blend. Clip positions must be sorted from lowest to highest.
  224. /// </param>
  225. /// <param name="t">Parameter that controls the blending, in range [0, 1]. t = 0 means left animation has full
  226. /// influence, t = 1 means right animation has full influence.</param>
  227. public void Blend1D(Blend1DInfo info, float t)
  228. {
  229. switch (state)
  230. {
  231. case State.Active:
  232. _native.Blend1D(info, t);
  233. break;
  234. }
  235. }
  236. /// <summary>
  237. /// Blend four animation clips between each other using bilinear interpolation. Unlike normal animations these
  238. /// animations are not advanced with the progress of time, and is instead expected the user manually changes the
  239. /// <see cref="t"/> parameter.
  240. /// </summary>
  241. /// <param name="info">Information about the clips to blend.</param>
  242. /// <param name="t">Parameter that controls the blending, in range [(0, 0), (1, 1)]. t = (0, 0) means top left
  243. /// animation has full influence, t = (0, 1) means top right animation has full influence,
  244. /// t = (1, 0) means bottom left animation has full influence, t = (1, 1) means bottom right
  245. /// animation has full influence.
  246. /// </param>
  247. public void Blend2D(Blend2DInfo info, Vector2 t)
  248. {
  249. switch (state)
  250. {
  251. case State.Active:
  252. _native.Blend2D(info, t);
  253. break;
  254. }
  255. }
  256. /// <summary>
  257. /// Fades the specified animation clip in, while fading other playing animation out, over the specified time period.
  258. /// </summary>
  259. /// <param name="clip">Clip to fade in.</param>
  260. /// <param name="fadeLength">Determines the time period over which the fade occurs. In seconds.</param>
  261. public void CrossFade(AnimationClip clip, float fadeLength)
  262. {
  263. switch (state)
  264. {
  265. case State.Active:
  266. _native.CrossFade(clip, fadeLength);
  267. break;
  268. }
  269. }
  270. /// <summary>
  271. /// Samples an animation clip at the specified time, displaying only that particular frame without further playback.
  272. /// </summary>
  273. /// <param name="clip">Animation clip to sample.</param>
  274. /// <param name="time">Time to sample the clip at.</param>
  275. public void Sample(AnimationClip clip, float time)
  276. {
  277. switch (state)
  278. {
  279. case State.Active:
  280. case State.EditorActive:
  281. _native.Sample(clip, time);
  282. break;
  283. }
  284. }
  285. /// <summary>
  286. /// Stops playing all animations on the provided layer.
  287. /// </summary>
  288. /// <param name="layer">Layer on which to stop animations on.</param>
  289. public void Stop(int layer)
  290. {
  291. switch (state)
  292. {
  293. case State.Active:
  294. _native.Stop(layer);
  295. break;
  296. }
  297. }
  298. /// <summary>
  299. /// Stops playing all animations.
  300. /// </summary>
  301. public void StopAll()
  302. {
  303. switch (state)
  304. {
  305. case State.Active:
  306. _native.StopAll();
  307. break;
  308. }
  309. }
  310. /// <summary>
  311. /// Retrieves detailed information about a currently playing animation clip.
  312. /// </summary>
  313. /// <param name="clip">Clip to retrieve the information for.</param>
  314. /// <param name="state">Animation clip state containing the requested information. Only valid if the method returns
  315. /// true.</param>
  316. /// <returns>True if the state was found (animation clip is playing), false otherwise.</returns>
  317. public bool GetState(AnimationClip clip, out AnimationClipState state)
  318. {
  319. switch (this.state)
  320. {
  321. case State.Active:
  322. case State.EditorActive:
  323. return _native.GetState(clip, out state);
  324. default:
  325. state = new AnimationClipState();
  326. return false;
  327. }
  328. }
  329. /// <summary>
  330. /// Changes the state of a playing animation clip. If animation clip is not currently playing the state change is
  331. /// ignored.
  332. /// </summary>
  333. /// <param name="clip">Clip to change the state for.</param>
  334. /// <param name="state">New state of the animation (e.g. changing the time for seeking).</param>
  335. public void SetState(AnimationClip clip, AnimationClipState state)
  336. {
  337. switch (this.state)
  338. {
  339. case State.Active:
  340. case State.EditorActive:
  341. _native.SetState(clip, state);
  342. break;
  343. }
  344. }
  345. /// <summary>
  346. /// Changes a weight of a single morph shape, determining how much of it to apply on top of the base mesh.
  347. /// </summary>
  348. /// <param name="name">Name of the morph shape to modify the weight for. This depends on the mesh the animation
  349. /// is currently animating.</param>
  350. /// <param name="weight">Weight that determines how much of the shape to apply to the mesh, in range[0, 1].</param>
  351. public void SetMorphShapeWeight(string name, float weight)
  352. {
  353. switch (state)
  354. {
  355. case State.Active:
  356. if (animatedRenderable == null)
  357. return;
  358. Mesh mesh = animatedRenderable.Mesh;
  359. if (mesh == null)
  360. return;
  361. MorphShapes morphShapes = mesh.MorphShapes;
  362. if (morphShapes == null)
  363. return;
  364. string[] shapeNames = morphShapes.Shapes;
  365. for (int i = 0; i < shapeNames.Length; i++)
  366. {
  367. if (shapeNames[i] == name)
  368. {
  369. _native.SetMorphShapeWeight(i, weight);
  370. break;
  371. }
  372. }
  373. break;
  374. }
  375. }
  376. /// <summary>
  377. /// Allows the caller to play an animation clip during edit mode. This form of animation playback is limited as
  378. /// you have no control over clip properties, and features like blending, cross fade or animation events are not
  379. /// supported.
  380. ///
  381. /// Caller will need to manually call <see cref="UpdateFloatProperties"/> in order to apply evaluated animation data
  382. /// to relevant float properties (if required).
  383. ///
  384. /// Caller will also need to manually call <see cref="RefreshClipMappings"/> whenever the curves internal to the
  385. /// animation clip change. This should be called before the call to <see cref="UpdateFloatProperties"/>.
  386. /// </summary>
  387. /// <param name="clip">Animation clip to play.</param>
  388. /// <param name="startTime">Time to start playing at, in seconds.</param>
  389. /// <param name="freeze">If true, only the frame at the specified time will be shown, without advancing the
  390. /// animation.</param>
  391. internal void EditorPlay(AnimationClip clip, float startTime, bool freeze = false)
  392. {
  393. switch (state)
  394. {
  395. case State.Inactive:
  396. SwitchState(State.EditorActive);
  397. break;
  398. }
  399. switch (state)
  400. {
  401. case State.EditorActive:
  402. if (freeze)
  403. Sample(clip, startTime);
  404. else
  405. {
  406. AnimationClipState clipState = AnimationClipState.Create();
  407. clipState.time = startTime;
  408. SetState(clip, clipState);
  409. }
  410. RefreshClipMappings();
  411. break;
  412. }
  413. }
  414. /// <summary>
  415. /// Stops playback of animation whose playback what started using <see cref="EditorPlay"/>.
  416. /// </summary>
  417. internal void EditorStop()
  418. {
  419. switch (state)
  420. {
  421. case State.EditorActive:
  422. SwitchState(State.Inactive);
  423. break;
  424. }
  425. }
  426. /// <summary>
  427. /// Returns the current time of the currently playing editor animation clip.
  428. /// </summary>
  429. /// <returns>Time in seconds.</returns>
  430. internal float EditorGetTime()
  431. {
  432. switch (state)
  433. {
  434. case State.EditorActive:
  435. AnimationClip clip = _native.GetClip(0);
  436. AnimationClipState clipState;
  437. if (clip != null && GetState(clip, out clipState))
  438. return clipState.time;
  439. return 0.0f;
  440. }
  441. return 0.0f;
  442. }
  443. /// <summary>
  444. /// Rebuilds internal curve -> property mapping about the currently playing animation clip. This mapping allows the
  445. /// animation component to know which property to assign which values from an animation curve. This Should be called
  446. /// whenever playback for a new clip starts, or when clip curves change.
  447. /// </summary>
  448. internal void RefreshClipMappings()
  449. {
  450. primaryClip = _native.GetClip(0);
  451. RebuildFloatProperties(primaryClip);
  452. UpdateSceneObjectMapping();
  453. }
  454. /// <summary>
  455. /// Updates generic float properties on relevant objects, based on the most recently evaluated animation curve
  456. /// values.
  457. /// </summary>
  458. internal void UpdateFloatProperties()
  459. {
  460. // Apply values from generic float curves
  461. if (floatProperties != null)
  462. {
  463. foreach (var entry in floatProperties)
  464. {
  465. float curveValue;
  466. if (_native.GetGenericCurveValue(entry.curveIdx, out curveValue))
  467. entry.setter(curveValue);
  468. }
  469. }
  470. }
  471. /// <summary>
  472. /// Searches the scene object hierarchy to find a property at the given path.
  473. /// </summary>
  474. /// <param name="root">Root scene object to which the path is relative to.</param>
  475. /// <param name="path">Path to the property, where each element of the path is separated with "/".
  476. ///
  477. /// Path elements prefixed with "!" signify names of child scene objects (first one relative to
  478. /// <paramref name="root"/>. Name of the root element should not be included in the path.
  479. ///
  480. /// Path element prefixed with ":" signify names of components. If a path doesn't have a
  481. /// component element, it is assumed the field is relative to the scene object itself (only
  482. /// "Translation", "Rotation" and "Scale fields are supported in such case). Only one component
  483. /// path element per path is allowed.
  484. ///
  485. /// Path entries with no prefix are considered regular script object fields. Each path must have
  486. /// at least one such entry. Last field entry can optionally have a suffix separated from the
  487. /// path name with ".". This suffix is not parsed internally, but will be returned as
  488. /// <paramref name="suffix"/>.
  489. ///
  490. /// Path examples:
  491. /// :MyComponent/myInt (path to myInt variable on a component attached to this object)
  492. /// !childSO/:MyComponent/myInt (path to myInt variable on a child scene object)
  493. /// !childSO/Translation (path to the scene object translation)
  494. /// :MyComponent/myVector.z (path to the z component of myVector on this object)
  495. /// </param>
  496. /// <param name="suffix">Suffix of the last field entry, if it has any. Contains the suffix separator ".".</param>
  497. /// <returns>If found, property object you can use for setting and getting the value from the property, otherwise
  498. /// null.</returns>
  499. internal static SerializableProperty FindProperty(SceneObject root, string path, out string suffix)
  500. {
  501. suffix = null;
  502. if (string.IsNullOrEmpty(path) || root == null)
  503. return null;
  504. string trimmedPath = path.Trim('/');
  505. string[] entries = trimmedPath.Split('/');
  506. // Find scene object referenced by the path
  507. SceneObject so = root;
  508. int pathIdx = 0;
  509. for (; pathIdx < entries.Length; pathIdx++)
  510. {
  511. string entry = entries[pathIdx];
  512. if (string.IsNullOrEmpty(entry))
  513. continue;
  514. // Not a scene object, break
  515. if (entry[0] != '!')
  516. break;
  517. string childName = entry.Substring(1, entry.Length - 1);
  518. so = so.FindChild(childName);
  519. if (so == null)
  520. break;
  521. }
  522. // Child scene object couldn't be found
  523. if (so == null)
  524. return null;
  525. // Path too short, no field entry
  526. if (pathIdx >= entries.Length)
  527. return null;
  528. // Check if path is referencing a component, and if so find it
  529. Component component = null;
  530. {
  531. string entry = entries[pathIdx];
  532. if (entry[0] == ':')
  533. {
  534. string componentName = entry.Substring(1, entry.Length - 1);
  535. Component[] components = so.GetComponents();
  536. component = Array.Find(components, x => x.GetType().Name == componentName);
  537. // Cannot find component with specified type
  538. if (component == null)
  539. return null;
  540. }
  541. }
  542. // Look for a field within a component
  543. if (component != null)
  544. {
  545. pathIdx++;
  546. if (pathIdx >= entries.Length)
  547. return null;
  548. SerializableObject componentObj = new SerializableObject(component);
  549. StringBuilder pathBuilder = new StringBuilder();
  550. for (; pathIdx < entries.Length - 1; pathIdx++)
  551. pathBuilder.Append(entries[pathIdx] + "/");
  552. // Check last path entry for suffix and remove it
  553. int suffixIdx = entries[pathIdx].LastIndexOf(".");
  554. if (suffixIdx != -1)
  555. {
  556. string entryNoSuffix = entries[pathIdx].Substring(0, suffixIdx);
  557. suffix = entries[pathIdx].Substring(suffixIdx, entries[pathIdx].Length - suffixIdx);
  558. pathBuilder.Append(entryNoSuffix);
  559. }
  560. else
  561. pathBuilder.Append(entries[pathIdx]);
  562. return componentObj.FindProperty(pathBuilder.ToString());
  563. }
  564. else // Field is one of the builtin ones on the SceneObject itself
  565. {
  566. if ((pathIdx + 1) < entries.Length)
  567. return null;
  568. string entry = entries[pathIdx];
  569. if (entry == "Position")
  570. {
  571. SerializableProperty property = new SerializableProperty(
  572. SerializableProperty.FieldType.Vector3,
  573. typeof(Vector3),
  574. () => so.LocalPosition,
  575. (x) => so.LocalPosition = (Vector3)x);
  576. return property;
  577. }
  578. else if (entry == "Rotation")
  579. {
  580. SerializableProperty property = new SerializableProperty(
  581. SerializableProperty.FieldType.Vector3,
  582. typeof(Vector3),
  583. () => so.LocalRotation.ToEuler(),
  584. (x) => so.LocalRotation = Quaternion.FromEuler((Vector3)x));
  585. return property;
  586. }
  587. else if (entry == "Scale")
  588. {
  589. SerializableProperty property = new SerializableProperty(
  590. SerializableProperty.FieldType.Vector3,
  591. typeof(Vector3),
  592. () => so.LocalScale,
  593. (x) => so.LocalScale = (Vector3)x);
  594. return property;
  595. }
  596. return null;
  597. }
  598. }
  599. /// <summary>
  600. /// Searches the scene object hierarchy to find a child scene object using the provided path.
  601. /// </summary>
  602. /// <param name="root">Root scene object to which the path is relative to.</param>
  603. /// <param name="path">Path to the property, where each element of the path is separated with "/".
  604. ///
  605. /// Path elements signify names of child scene objects (first one relative to
  606. /// <paramref name="root"/>. Name of the root element should not be included in the path.
  607. /// Elements must be prefixed with "!" in order to match the path format of
  608. /// <see cref="FindProperty"/>.</param>
  609. /// <returns>Child scene object if found, or null otherwise.</returns>
  610. internal static SceneObject FindSceneObject(SceneObject root, string path)
  611. {
  612. if (string.IsNullOrEmpty(path) || root == null)
  613. return null;
  614. string trimmedPath = path.Trim('/');
  615. string[] entries = trimmedPath.Split('/');
  616. // Find scene object referenced by the path
  617. SceneObject so = root;
  618. int pathIdx = 0;
  619. for (; pathIdx < entries.Length; pathIdx++)
  620. {
  621. string entry = entries[pathIdx];
  622. if (string.IsNullOrEmpty(entry))
  623. continue;
  624. // Not a scene object, break
  625. if (entry[0] != '!')
  626. break;
  627. string childName = entry.Substring(1, entry.Length - 1);
  628. so = so.FindChild(childName);
  629. if (so == null)
  630. break;
  631. }
  632. return so;
  633. }
  634. private void OnInitialize()
  635. {
  636. NotifyFlags = TransformChangedFlags.Transform;
  637. }
  638. private void OnEnable()
  639. {
  640. switch (state)
  641. {
  642. case State.Inactive:
  643. SwitchState(State.Active);
  644. break;
  645. case State.EditorActive:
  646. SwitchState(State.Inactive);
  647. SwitchState(State.Active);
  648. break;
  649. }
  650. }
  651. private void OnDisable()
  652. {
  653. switch (state)
  654. {
  655. case State.Active:
  656. case State.EditorActive:
  657. SwitchState(State.Inactive);
  658. break;
  659. }
  660. }
  661. private void OnDestroy()
  662. {
  663. switch (state)
  664. {
  665. case State.Active:
  666. case State.EditorActive:
  667. SwitchState(State.Inactive);
  668. break;
  669. }
  670. }
  671. private void OnUpdate()
  672. {
  673. switch (state)
  674. {
  675. case State.Active:
  676. AnimationClip newPrimaryClip = _native.GetClip(0);
  677. if (newPrimaryClip != primaryClip)
  678. RefreshClipMappings();
  679. UpdateFloatProperties();
  680. break;
  681. }
  682. }
  683. private void OnTransformChanged(TransformChangedFlags flags)
  684. {
  685. if (!SceneObject.Active)
  686. return;
  687. if ((flags & (TransformChangedFlags.Transform)) != 0)
  688. UpdateBounds(false);
  689. }
  690. /// <summary>
  691. /// Changes the state of the animation state machine. Doesn't check for valid transitions.
  692. /// </summary>
  693. /// <param name="state">New state of the animation.</param>
  694. private void SwitchState(State state)
  695. {
  696. this.state = state;
  697. switch (state)
  698. {
  699. case State.Active:
  700. if (_native != null)
  701. _native.Destroy();
  702. _native = new NativeAnimation();
  703. _native.OnEventTriggered += EventTriggered;
  704. animatedRenderable = SceneObject.GetComponent<Renderable>();
  705. // Restore saved values after reset
  706. _native.WrapMode = serializableData.wrapMode;
  707. _native.Speed = serializableData.speed;
  708. _native.Cull = serializableData.cull;
  709. UpdateBounds();
  710. if (serializableData.defaultClip != null)
  711. _native.Play(serializableData.defaultClip);
  712. primaryClip = _native.GetClip(0);
  713. if (primaryClip != null)
  714. RebuildFloatProperties(primaryClip);
  715. SetBoneMappings();
  716. UpdateSceneObjectMapping();
  717. if (animatedRenderable != null)
  718. animatedRenderable.RegisterAnimation(this);
  719. break;
  720. case State.EditorActive:
  721. if (_native != null)
  722. _native.Destroy();
  723. _native = new NativeAnimation();
  724. animatedRenderable = SceneObject.GetComponent<Renderable>();
  725. UpdateBounds();
  726. SetBoneMappings();
  727. if (animatedRenderable != null)
  728. animatedRenderable.RegisterAnimation(this);
  729. break;
  730. case State.Inactive:
  731. if (animatedRenderable != null)
  732. animatedRenderable.UnregisterAnimation();
  733. if (_native != null)
  734. {
  735. _native.Destroy();
  736. _native = null;
  737. }
  738. primaryClip = null;
  739. mappingInfo.Clear();
  740. floatProperties = null;
  741. break;
  742. }
  743. }
  744. /// <summary>
  745. /// Finds any curves that affect a transform of a specific scene object, and ensures that animation properly updates
  746. /// those transforms. This does not include curves referencing bones.
  747. /// </summary>
  748. private void UpdateSceneObjectMapping()
  749. {
  750. List<SceneObjectMappingInfo> newMappingInfos = new List<SceneObjectMappingInfo>();
  751. foreach(var entry in mappingInfo)
  752. {
  753. if (entry.isMappedToBone)
  754. newMappingInfos.Add(entry);
  755. else
  756. _native.UnmapSceneObject(entry.sceneObject);
  757. }
  758. if (primaryClip != null)
  759. {
  760. SceneObject root = SceneObject;
  761. Action<NamedVector3Curve[]> findMappings = x =>
  762. {
  763. foreach (var curve in x)
  764. {
  765. if (curve.Flags.HasFlag(AnimationCurveFlags.ImportedCurve))
  766. continue;
  767. SceneObject currentSO = FindSceneObject(root, curve.Name);
  768. bool found = false;
  769. for (int i = 0; i < newMappingInfos.Count; i++)
  770. {
  771. if (newMappingInfos[i].sceneObject == currentSO)
  772. {
  773. found = true;
  774. break;
  775. }
  776. }
  777. if (!found)
  778. {
  779. SceneObjectMappingInfo newMappingInfo = new SceneObjectMappingInfo();
  780. newMappingInfo.isMappedToBone = false;
  781. newMappingInfo.sceneObject = currentSO;
  782. newMappingInfos.Add(newMappingInfo);
  783. _native.MapCurveToSceneObject(curve.Name, currentSO);
  784. }
  785. }
  786. };
  787. AnimationCurves curves = primaryClip.Curves;
  788. findMappings(curves.PositionCurves);
  789. findMappings(curves.RotationCurves);
  790. findMappings(curves.ScaleCurves);
  791. }
  792. mappingInfo = newMappingInfos;
  793. }
  794. /// <summary>
  795. /// Registers a new bone component, creating a new transform mapping from the bone name to the scene object
  796. /// the component is attached to.
  797. /// </summary>
  798. /// <param name="bone">Bone component to register.</param>
  799. internal void AddBone(Bone bone)
  800. {
  801. switch (state)
  802. {
  803. case State.Active:
  804. SceneObject currentSO = bone.SceneObject;
  805. SceneObjectMappingInfo newMapping = new SceneObjectMappingInfo();
  806. newMapping.sceneObject = currentSO;
  807. newMapping.isMappedToBone = true;
  808. newMapping.bone = bone;
  809. mappingInfo.Add(newMapping);
  810. _native.MapCurveToSceneObject(bone.Name, newMapping.sceneObject);
  811. break;
  812. }
  813. }
  814. /// <summary>
  815. /// Unregisters a bone component, removing the bone -> scene object mapping.
  816. /// </summary>
  817. /// <param name="bone">Bone to unregister.</param>
  818. internal void RemoveBone(Bone bone)
  819. {
  820. switch (state)
  821. {
  822. case State.Active:
  823. for (int i = 0; i < mappingInfo.Count; i++)
  824. {
  825. if (mappingInfo[i].bone == bone)
  826. {
  827. _native.UnmapSceneObject(mappingInfo[i].sceneObject);
  828. mappingInfo.RemoveAt(i);
  829. i--;
  830. }
  831. }
  832. break;
  833. }
  834. }
  835. /// <summary>
  836. /// Called whenever the bone the <see cref="Bone"/> component points to changed.
  837. /// </summary>
  838. /// <param name="bone">Bone component to modify.</param>
  839. internal void NotifyBoneChanged(Bone bone)
  840. {
  841. switch (state)
  842. {
  843. case State.Active:
  844. for (int i = 0; i < mappingInfo.Count; i++)
  845. {
  846. if (mappingInfo[i].bone == bone)
  847. {
  848. _native.UnmapSceneObject(mappingInfo[i].sceneObject);
  849. _native.MapCurveToSceneObject(bone.Name, mappingInfo[i].sceneObject);
  850. break;
  851. }
  852. }
  853. break;
  854. }
  855. }
  856. /// <summary>
  857. /// Finds any scene objects that are mapped to bone transforms. Such object's transforms will be affected by
  858. /// skeleton bone animation.
  859. /// </summary>
  860. private void SetBoneMappings()
  861. {
  862. mappingInfo.Clear();
  863. SceneObjectMappingInfo rootMapping = new SceneObjectMappingInfo();
  864. rootMapping.sceneObject = SceneObject;
  865. rootMapping.isMappedToBone = true;
  866. mappingInfo.Add(rootMapping);
  867. _native.MapCurveToSceneObject("", rootMapping.sceneObject);
  868. Bone[] childBones = FindChildBones();
  869. foreach (var entry in childBones)
  870. AddBone(entry);
  871. }
  872. /// <summary>
  873. /// Searches child scene objects for <see cref="Bone"/> components and returns any found ones.
  874. /// </summary>
  875. private Bone[] FindChildBones()
  876. {
  877. Stack<SceneObject> todo = new Stack<SceneObject>();
  878. todo.Push(SceneObject);
  879. List<Bone> bones = new List<Bone>();
  880. while (todo.Count > 0)
  881. {
  882. SceneObject currentSO = todo.Pop();
  883. Bone bone = currentSO.GetComponent<Bone>();
  884. if (bone != null)
  885. {
  886. bone.SetParent(this, true);
  887. bones.Add(bone);
  888. }
  889. int childCount = currentSO.GetNumChildren();
  890. for (int i = 0; i < childCount; i++)
  891. {
  892. SceneObject child = currentSO.GetChild(i);
  893. if (child.GetComponent<Animation>() != null)
  894. continue;
  895. todo.Push(child);
  896. }
  897. }
  898. return bones.ToArray();
  899. }
  900. /// <summary>
  901. /// Re-applies the bounds to the internal animation object, and the relevant renderable object if one exists.
  902. /// </summary>
  903. internal void UpdateBounds(bool updateRenderable = true)
  904. {
  905. NativeRenderable renderable = null;
  906. if (updateRenderable && animatedRenderable != null)
  907. renderable = animatedRenderable.Native;
  908. if (serializableData.useBounds)
  909. {
  910. if (renderable != null)
  911. {
  912. renderable.UseOverrideBounds = true;
  913. renderable.OverrideBounds = serializableData.bounds;
  914. }
  915. if (_native != null)
  916. {
  917. AABox bounds = serializableData.bounds;
  918. Matrix4 parentTfrm;
  919. if (SceneObject.Parent != null)
  920. parentTfrm = SceneObject.Parent.WorldTransform;
  921. else
  922. parentTfrm = Matrix4.Identity;
  923. bounds.TransformAffine(parentTfrm);
  924. _native.Bounds = bounds;
  925. }
  926. }
  927. else
  928. {
  929. if (renderable != null)
  930. renderable.UseOverrideBounds = false;
  931. if (_native != null)
  932. {
  933. AABox bounds = new AABox();
  934. if (animatedRenderable != null)
  935. bounds = animatedRenderable.Bounds.Box;
  936. _native.Bounds = bounds;
  937. }
  938. }
  939. }
  940. /// <summary>
  941. /// Registers an <see cref="Renderable"/> component with the animation. When registered the animation will use the
  942. /// renderable's bounds for culling, and the animation override bounds will be applied to the renderable.
  943. /// </summary>
  944. /// <param name="renderable">Component that was added</param>
  945. internal void RegisterRenderable(Renderable renderable)
  946. {
  947. animatedRenderable = renderable;
  948. UpdateBounds();
  949. }
  950. /// <summary>
  951. /// Removes renderable from the animation component. <see cref="RegisterRenderable"/>.
  952. /// </summary>
  953. internal void UnregisterRenderable()
  954. {
  955. animatedRenderable = null;
  956. }
  957. /// <summary>
  958. /// Builds a list of properties that will be animated using float animation curves.
  959. /// </summary>
  960. /// <param name="clip">Clip to retrieve the float animation curves from.</param>
  961. private void RebuildFloatProperties(AnimationClip clip)
  962. {
  963. if (clip == null)
  964. {
  965. floatProperties = null;
  966. return;
  967. }
  968. AnimationCurves curves = clip.Curves;
  969. List<FloatCurvePropertyInfo> newFloatProperties = new List<FloatCurvePropertyInfo>();
  970. for (int i = 0; i < curves.FloatCurves.Length; i++)
  971. {
  972. string suffix;
  973. SerializableProperty property = FindProperty(SceneObject, curves.FloatCurves[i].Name, out suffix);
  974. if (property == null)
  975. continue;
  976. int elementIdx = 0;
  977. if (!string.IsNullOrEmpty(suffix))
  978. {
  979. PropertySuffixInfo suffixInfo;
  980. if (PropertySuffixInfos.TryGetValue(suffix, out suffixInfo))
  981. elementIdx = suffixInfo.elementIdx;
  982. }
  983. Action<float> setter = null;
  984. Type internalType = property.InternalType;
  985. switch (property.Type)
  986. {
  987. case SerializableProperty.FieldType.Vector2:
  988. if (internalType == typeof(Vector2))
  989. {
  990. setter = f =>
  991. {
  992. Vector2 value = property.GetValue<Vector2>();
  993. value[elementIdx] = f;
  994. property.SetValue(value);
  995. };
  996. }
  997. break;
  998. case SerializableProperty.FieldType.Vector3:
  999. if (internalType == typeof(Vector3))
  1000. {
  1001. setter = f =>
  1002. {
  1003. Vector3 value = property.GetValue<Vector3>();
  1004. value[elementIdx] = f;
  1005. property.SetValue(value);
  1006. };
  1007. }
  1008. break;
  1009. case SerializableProperty.FieldType.Vector4:
  1010. if (internalType == typeof(Vector4))
  1011. {
  1012. setter = f =>
  1013. {
  1014. Vector4 value = property.GetValue<Vector4>();
  1015. value[elementIdx] = f;
  1016. property.SetValue(value);
  1017. };
  1018. }
  1019. else if (internalType == typeof(Quaternion))
  1020. {
  1021. setter = f =>
  1022. {
  1023. Quaternion value = property.GetValue<Quaternion>();
  1024. value[elementIdx] = f;
  1025. property.SetValue(value);
  1026. };
  1027. }
  1028. break;
  1029. case SerializableProperty.FieldType.Color:
  1030. if (internalType == typeof(Color))
  1031. {
  1032. setter = f =>
  1033. {
  1034. Color value = property.GetValue<Color>();
  1035. value[elementIdx] = f;
  1036. property.SetValue(value);
  1037. };
  1038. }
  1039. break;
  1040. case SerializableProperty.FieldType.Bool:
  1041. setter = f =>
  1042. {
  1043. bool value = f > 0.0f;
  1044. property.SetValue(value);
  1045. };
  1046. break;
  1047. case SerializableProperty.FieldType.Int:
  1048. setter = f =>
  1049. {
  1050. int value = (int)f;
  1051. property.SetValue(value);
  1052. };
  1053. break;
  1054. case SerializableProperty.FieldType.Float:
  1055. setter = f =>
  1056. {
  1057. property.SetValue(f);
  1058. };
  1059. break;
  1060. }
  1061. if (setter == null)
  1062. continue;
  1063. FloatCurvePropertyInfo propertyInfo = new FloatCurvePropertyInfo();
  1064. propertyInfo.curveIdx = i;
  1065. propertyInfo.setter = setter;
  1066. newFloatProperties.Add(propertyInfo);
  1067. }
  1068. floatProperties = newFloatProperties.ToArray();
  1069. }
  1070. /// <summary>
  1071. /// Called whenever an animation event triggers.
  1072. /// </summary>
  1073. /// <param name="clip">Clip that the event originated from.</param>
  1074. /// <param name="name">Name of the event.</param>
  1075. private void EventTriggered(AnimationClip clip, string name)
  1076. {
  1077. // Event should be in format "ComponentType/MethodName"
  1078. if (string.IsNullOrEmpty(name))
  1079. return;
  1080. string[] nameEntries = name.Split('/');
  1081. if (nameEntries.Length != 2)
  1082. return;
  1083. string typeName = nameEntries[0];
  1084. string methodName = nameEntries[1];
  1085. Component[] components = SceneObject.GetComponents();
  1086. for (int i = 0; i < components.Length; i++)
  1087. {
  1088. if (components[i].GetType().Name == typeName)
  1089. {
  1090. components[i].Invoke(methodName);
  1091. break;
  1092. }
  1093. }
  1094. }
  1095. /// <summary>
  1096. /// Holds all data the animation component needs to persist through serialization.
  1097. /// </summary>
  1098. [SerializeObject]
  1099. private class SerializableData
  1100. {
  1101. public AnimationClip defaultClip;
  1102. public AnimWrapMode wrapMode = AnimWrapMode.Loop;
  1103. public float speed = 1.0f;
  1104. public AABox bounds;
  1105. public bool useBounds;
  1106. public bool cull = true;
  1107. }
  1108. /// <summary>
  1109. /// Contains information about a property animated by a generic animation curve.
  1110. /// </summary>
  1111. private class FloatCurvePropertyInfo
  1112. {
  1113. public int curveIdx;
  1114. public Action<float> setter;
  1115. }
  1116. /// <summary>
  1117. /// Information about a suffix used in a property path.
  1118. /// </summary>
  1119. internal struct PropertySuffixInfo
  1120. {
  1121. public PropertySuffixInfo(int elementIdx, bool isVector)
  1122. {
  1123. this.elementIdx = elementIdx;
  1124. this.isVector = isVector;
  1125. }
  1126. public int elementIdx;
  1127. public bool isVector;
  1128. }
  1129. /// <summary>
  1130. /// Information about scene objects bound to a specific animation curve.
  1131. /// </summary>
  1132. internal struct SceneObjectMappingInfo
  1133. {
  1134. public SceneObject sceneObject;
  1135. public bool isMappedToBone;
  1136. public Bone bone;
  1137. }
  1138. /// <summary>
  1139. /// Possible states the animation component can be in.
  1140. /// </summary>
  1141. private enum State
  1142. {
  1143. /// <summary>
  1144. /// Animation object isn't constructed.
  1145. /// </summary>
  1146. Inactive,
  1147. /// <summary>
  1148. /// Animation object is constructed and fully functional.
  1149. /// </summary>
  1150. Active,
  1151. /// <summary>
  1152. /// Animation object is constructed and functional with limited funcionality for editor purposes.
  1153. /// </summary>
  1154. EditorActive
  1155. }
  1156. }
  1157. /// <summary>
  1158. /// Determines how an animation clip behaves when it reaches the end.
  1159. /// </summary>
  1160. public enum AnimWrapMode // Note: Must match C++ enum AnimWrapMode
  1161. {
  1162. /// <summary>
  1163. /// Loop around to the beginning/end when the last/first frame is reached.
  1164. /// </summary>
  1165. Loop,
  1166. /// <summary>
  1167. /// Clamp to end/beginning, keeping the last/first frame active.
  1168. /// </summary>
  1169. Clamp
  1170. }
  1171. /// <summary>
  1172. /// Represents an animation clip used in 1D blending. Each clip has a position on the number line.
  1173. /// </summary>
  1174. public class BlendClipInfo
  1175. {
  1176. public AnimationClip clip;
  1177. public float position;
  1178. }
  1179. /// <summary>
  1180. /// Defines a 1D blend where two animation clips are blended between each other using linear interpolation.
  1181. /// </summary>
  1182. public class Blend1DInfo
  1183. {
  1184. public Blend1DInfo()
  1185. { }
  1186. public Blend1DInfo(int numClips)
  1187. {
  1188. clips = new BlendClipInfo[numClips];
  1189. }
  1190. public BlendClipInfo[] clips;
  1191. }
  1192. /// <summary>
  1193. /// Defines a 2D blend where two animation clips are blended between each other using bilinear interpolation.
  1194. /// </summary>
  1195. public class Blend2DInfo
  1196. {
  1197. public AnimationClip topLeftClip;
  1198. public AnimationClip topRightClip;
  1199. public AnimationClip botLeftClip;
  1200. public AnimationClip botRightClip;
  1201. }
  1202. /// <summary>
  1203. /// Contains information about a currently playing animation clip.
  1204. /// </summary>
  1205. [StructLayout(LayoutKind.Sequential), SerializeObject]
  1206. public struct AnimationClipState // Note: Must match C++ struct AnimationClipState
  1207. {
  1208. /// <summary>
  1209. /// Layer the clip is playing on. Multiple clips can be played simulatenously on different layers.
  1210. /// </summary>
  1211. public int layer;
  1212. /// <summary>
  1213. /// Current time the animation is playing from.
  1214. /// </summary>
  1215. public float time;
  1216. /// <summary>
  1217. /// Speed at which the animation is playing.
  1218. /// </summary>
  1219. public float speed;
  1220. /// <summary>
  1221. /// Determines how much of an influence does the clip have on the final pose.
  1222. /// </summary>
  1223. public float weight;
  1224. /// <summary>
  1225. /// Determines what happens to other animation clips when a new clip starts playing.
  1226. /// </summary>
  1227. public AnimWrapMode wrapMode;
  1228. /// <summary>
  1229. /// Creates a new clip state, with default values initialized.
  1230. /// </summary>
  1231. /// <returns>New animation clip state.</returns>
  1232. public static AnimationClipState Create()
  1233. {
  1234. AnimationClipState state = new AnimationClipState();
  1235. state.speed = 1.0f;
  1236. state.weight = 1.0f;
  1237. state.wrapMode = AnimWrapMode.Loop;
  1238. return state;
  1239. }
  1240. }
  1241. /** @} */
  1242. }