Animation.cs 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  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. /// Stops playing all animations on the provided layer.
  272. /// </summary>
  273. /// <param name="layer">Layer on which to stop animations on.</param>
  274. public void Stop(int layer)
  275. {
  276. switch (state)
  277. {
  278. case State.Active:
  279. _native.Stop(layer);
  280. break;
  281. }
  282. }
  283. /// <summary>
  284. /// Stops playing all animations.
  285. /// </summary>
  286. public void StopAll()
  287. {
  288. switch (state)
  289. {
  290. case State.Active:
  291. _native.StopAll();
  292. break;
  293. }
  294. }
  295. /// <summary>
  296. /// Retrieves detailed information about a currently playing animation clip.
  297. /// </summary>
  298. /// <param name="clip">Clip to retrieve the information for.</param>
  299. /// <param name="state">Animation clip state containing the requested information. Only valid if the method returns
  300. /// true.</param>
  301. /// <returns>True if the state was found (animation clip is playing), false otherwise.</returns>
  302. public bool GetState(AnimationClip clip, out AnimationClipState state)
  303. {
  304. switch (this.state)
  305. {
  306. case State.Active:
  307. case State.EditorActive:
  308. return _native.GetState(clip, out state);
  309. default:
  310. state = new AnimationClipState();
  311. return false;
  312. }
  313. }
  314. /// <summary>
  315. /// Changes the state of a playing animation clip. If animation clip is not currently playing the state change is
  316. /// ignored.
  317. /// </summary>
  318. /// <param name="clip">Clip to change the state for.</param>
  319. /// <param name="state">New state of the animation (e.g. changing the time for seeking).</param>
  320. public void SetState(AnimationClip clip, AnimationClipState state)
  321. {
  322. switch (this.state)
  323. {
  324. case State.Active:
  325. case State.EditorActive:
  326. _native.SetState(clip, state);
  327. break;
  328. }
  329. }
  330. /// <summary>
  331. /// Allows the caller to play an animation clip during edit mode. This form of animation playback is limited as
  332. /// you have no control over clip properties, and features like blending, cross fade or animation events are not
  333. /// supported.
  334. ///
  335. /// Caller will need to manually call <see cref="UpdateFloatProperties"/> in order to apply evaluated animation data
  336. /// to relevant float properties (if required).
  337. ///
  338. /// Caller will also need to manually call <see cref="RefreshClipMappings"/> whenever the curves internal to the
  339. /// animation clip change. This should be called before the call to <see cref="UpdateFloatProperties"/>.
  340. /// </summary>
  341. /// <param name="clip">Animation clip to play.</param>
  342. /// <param name="startTime">Time to start playing at, in seconds.</param>
  343. /// <param name="freeze">If true, only the frame at the specified time will be shown, without advancing the
  344. /// animation.</param>
  345. internal void EditorPlay(AnimationClip clip, float startTime, bool freeze = false)
  346. {
  347. switch (state)
  348. {
  349. case State.Inactive:
  350. SwitchState(State.EditorActive);
  351. break;
  352. }
  353. switch (state)
  354. {
  355. case State.EditorActive:
  356. AnimationClipState clipState = AnimationClipState.Create();
  357. clipState.time = startTime;
  358. clipState.speed = freeze ? 0.0f : 1.0f;
  359. SetState(clip, clipState);
  360. RefreshClipMappings();
  361. break;
  362. }
  363. }
  364. /// <summary>
  365. /// Stops playback of animation whose playback what started using <see cref="EditorPlay"/>.
  366. /// </summary>
  367. internal void EditorStop()
  368. {
  369. switch (state)
  370. {
  371. case State.EditorActive:
  372. SwitchState(State.Inactive);
  373. break;
  374. }
  375. }
  376. /// <summary>
  377. /// Returns the current time of the currently playing editor animation clip.
  378. /// </summary>
  379. /// <returns>Time in seconds.</returns>
  380. internal float EditorGetTime()
  381. {
  382. switch (state)
  383. {
  384. case State.EditorActive:
  385. AnimationClip clip = _native.GetClip(0);
  386. AnimationClipState clipState;
  387. if (clip != null && GetState(clip, out clipState))
  388. return clipState.time;
  389. return 0.0f;
  390. }
  391. return 0.0f;
  392. }
  393. /// <summary>
  394. /// Rebuilds internal curve -> property mapping about the currently playing animation clip. This mapping allows the
  395. /// animation component to know which property to assign which values from an animation curve. This Should be called
  396. /// whenever playback for a new clip starts, or when clip curves change.
  397. /// </summary>
  398. internal void RefreshClipMappings()
  399. {
  400. primaryClip = _native.GetClip(0);
  401. RebuildFloatProperties(primaryClip);
  402. UpdateSceneObjectMapping();
  403. }
  404. /// <summary>
  405. /// Updates generic float properties on relevant objects, based on the most recently evaluated animation curve
  406. /// values.
  407. /// </summary>
  408. internal void UpdateFloatProperties()
  409. {
  410. // Apply values from generic float curves
  411. if (floatProperties != null)
  412. {
  413. foreach (var entry in floatProperties)
  414. {
  415. float curveValue;
  416. if (_native.GetGenericCurveValue(entry.curveIdx, out curveValue))
  417. entry.setter(curveValue);
  418. }
  419. }
  420. }
  421. /// <summary>
  422. /// Searches the scene object hierarchy to find a property at the given path.
  423. /// </summary>
  424. /// <param name="root">Root scene object to which the path is relative to.</param>
  425. /// <param name="path">Path to the property, where each element of the path is separated with "/".
  426. ///
  427. /// Path elements prefixed with "!" signify names of child scene objects (first one relative to
  428. /// <paramref name="root"/>. Name of the root element should not be included in the path.
  429. ///
  430. /// Path element prefixed with ":" signify names of components. If a path doesn't have a
  431. /// component element, it is assumed the field is relative to the scene object itself (only
  432. /// "Translation", "Rotation" and "Scale fields are supported in such case). Only one component
  433. /// path element per path is allowed.
  434. ///
  435. /// Path entries with no prefix are considered regular script object fields. Each path must have
  436. /// at least one such entry. Last field entry can optionally have a suffix separated from the
  437. /// path name with ".". This suffix is not parsed internally, but will be returned as
  438. /// <paramref name="suffix"/>.
  439. ///
  440. /// Path examples:
  441. /// :MyComponent/myInt (path to myInt variable on a component attached to this object)
  442. /// !childSO/:MyComponent/myInt (path to myInt variable on a child scene object)
  443. /// !childSO/Translation (path to the scene object translation)
  444. /// :MyComponent/myVector.z (path to the z component of myVector on this object)
  445. /// </param>
  446. /// <param name="suffix">Suffix of the last field entry, if it has any. Contains the suffix separator ".".</param>
  447. /// <returns>If found, property object you can use for setting and getting the value from the property, otherwise
  448. /// null.</returns>
  449. internal static SerializableProperty FindProperty(SceneObject root, string path, out string suffix)
  450. {
  451. suffix = null;
  452. if (string.IsNullOrEmpty(path) || root == null)
  453. return null;
  454. string trimmedPath = path.Trim('/');
  455. string[] entries = trimmedPath.Split('/');
  456. // Find scene object referenced by the path
  457. SceneObject so = root;
  458. int pathIdx = 0;
  459. for (; pathIdx < entries.Length; pathIdx++)
  460. {
  461. string entry = entries[pathIdx];
  462. if (string.IsNullOrEmpty(entry))
  463. continue;
  464. // Not a scene object, break
  465. if (entry[0] != '!')
  466. break;
  467. string childName = entry.Substring(1, entry.Length - 1);
  468. so = so.FindChild(childName);
  469. if (so == null)
  470. break;
  471. }
  472. // Child scene object couldn't be found
  473. if (so == null)
  474. return null;
  475. // Path too short, no field entry
  476. if (pathIdx >= entries.Length)
  477. return null;
  478. // Check if path is referencing a component, and if so find it
  479. Component component = null;
  480. {
  481. string entry = entries[pathIdx];
  482. if (entry[0] == ':')
  483. {
  484. string componentName = entry.Substring(1, entry.Length - 1);
  485. Component[] components = so.GetComponents();
  486. component = Array.Find(components, x => x.GetType().Name == componentName);
  487. // Cannot find component with specified type
  488. if (component == null)
  489. return null;
  490. }
  491. }
  492. // Look for a field within a component
  493. if (component != null)
  494. {
  495. pathIdx++;
  496. if (pathIdx >= entries.Length)
  497. return null;
  498. SerializableObject componentObj = new SerializableObject(component);
  499. StringBuilder pathBuilder = new StringBuilder();
  500. for (; pathIdx < entries.Length - 1; pathIdx++)
  501. pathBuilder.Append(entries[pathIdx] + "/");
  502. // Check last path entry for suffix and remove it
  503. int suffixIdx = entries[pathIdx].LastIndexOf(".");
  504. if (suffixIdx != -1)
  505. {
  506. string entryNoSuffix = entries[pathIdx].Substring(0, suffixIdx);
  507. suffix = entries[pathIdx].Substring(suffixIdx, entries[pathIdx].Length - suffixIdx);
  508. pathBuilder.Append(entryNoSuffix);
  509. }
  510. else
  511. pathBuilder.Append(entries[pathIdx]);
  512. return componentObj.FindProperty(pathBuilder.ToString());
  513. }
  514. else // Field is one of the builtin ones on the SceneObject itself
  515. {
  516. if ((pathIdx + 1) < entries.Length)
  517. return null;
  518. string entry = entries[pathIdx];
  519. if (entry == "Position")
  520. {
  521. SerializableProperty property = new SerializableProperty(
  522. SerializableProperty.FieldType.Vector3,
  523. typeof(Vector3),
  524. () => so.LocalPosition,
  525. (x) => so.LocalPosition = (Vector3)x);
  526. return property;
  527. }
  528. else if (entry == "Rotation")
  529. {
  530. SerializableProperty property = new SerializableProperty(
  531. SerializableProperty.FieldType.Vector3,
  532. typeof(Vector3),
  533. () => so.LocalRotation.ToEuler(),
  534. (x) => so.LocalRotation = Quaternion.FromEuler((Vector3)x));
  535. return property;
  536. }
  537. else if (entry == "Scale")
  538. {
  539. SerializableProperty property = new SerializableProperty(
  540. SerializableProperty.FieldType.Vector3,
  541. typeof(Vector3),
  542. () => so.LocalScale,
  543. (x) => so.LocalScale = (Vector3)x);
  544. return property;
  545. }
  546. return null;
  547. }
  548. }
  549. /// <summary>
  550. /// Searches the scene object hierarchy to find a child scene object using the provided path.
  551. /// </summary>
  552. /// <param name="root">Root scene object to which the path is relative to.</param>
  553. /// <param name="path">Path to the property, where each element of the path is separated with "/".
  554. ///
  555. /// Path elements signify names of child scene objects (first one relative to
  556. /// <paramref name="root"/>. Name of the root element should not be included in the path.
  557. /// Elements must be prefixed with "!" in order to match the path format of
  558. /// <see cref="FindProperty"/>.</param>
  559. /// <returns>Child scene object if found, or null otherwise.</returns>
  560. internal static SceneObject FindSceneObject(SceneObject root, string path)
  561. {
  562. if (string.IsNullOrEmpty(path) || root == null)
  563. return null;
  564. string trimmedPath = path.Trim('/');
  565. string[] entries = trimmedPath.Split('/');
  566. // Find scene object referenced by the path
  567. SceneObject so = root;
  568. int pathIdx = 0;
  569. for (; pathIdx < entries.Length; pathIdx++)
  570. {
  571. string entry = entries[pathIdx];
  572. if (string.IsNullOrEmpty(entry))
  573. continue;
  574. // Not a scene object, break
  575. if (entry[0] != '!')
  576. break;
  577. string childName = entry.Substring(1, entry.Length - 1);
  578. so = so.FindChild(childName);
  579. if (so == null)
  580. break;
  581. }
  582. return so;
  583. }
  584. private void OnInitialize()
  585. {
  586. NotifyFlags = TransformChangedFlags.Transform;
  587. }
  588. private void OnEnable()
  589. {
  590. switch (state)
  591. {
  592. case State.Inactive:
  593. SwitchState(State.Active);
  594. break;
  595. case State.EditorActive:
  596. SwitchState(State.Inactive);
  597. SwitchState(State.Active);
  598. break;
  599. }
  600. }
  601. private void OnDisable()
  602. {
  603. switch (state)
  604. {
  605. case State.Active:
  606. case State.EditorActive:
  607. SwitchState(State.Inactive);
  608. break;
  609. }
  610. }
  611. private void OnDestroy()
  612. {
  613. switch (state)
  614. {
  615. case State.Active:
  616. case State.EditorActive:
  617. SwitchState(State.Inactive);
  618. break;
  619. }
  620. }
  621. private void OnUpdate()
  622. {
  623. switch (state)
  624. {
  625. case State.Active:
  626. AnimationClip newPrimaryClip = _native.GetClip(0);
  627. if (newPrimaryClip != primaryClip)
  628. RefreshClipMappings();
  629. UpdateFloatProperties();
  630. break;
  631. }
  632. }
  633. private void OnTransformChanged(TransformChangedFlags flags)
  634. {
  635. if (!SceneObject.Active)
  636. return;
  637. if ((flags & (TransformChangedFlags.Transform)) != 0)
  638. UpdateBounds(false);
  639. }
  640. /// <summary>
  641. /// Changes the state of the animation state machine. Doesn't check for valid transitions.
  642. /// </summary>
  643. /// <param name="state">New state of the animation.</param>
  644. private void SwitchState(State state)
  645. {
  646. this.state = state;
  647. switch (state)
  648. {
  649. case State.Active:
  650. if (_native != null)
  651. _native.Destroy();
  652. _native = new NativeAnimation();
  653. _native.OnEventTriggered += EventTriggered;
  654. animatedRenderable = SceneObject.GetComponent<Renderable>();
  655. // Restore saved values after reset
  656. _native.WrapMode = serializableData.wrapMode;
  657. _native.Speed = serializableData.speed;
  658. _native.Cull = serializableData.cull;
  659. UpdateBounds();
  660. if (serializableData.defaultClip != null)
  661. _native.Play(serializableData.defaultClip);
  662. primaryClip = _native.GetClip(0);
  663. if (primaryClip != null)
  664. RebuildFloatProperties(primaryClip);
  665. SetBoneMappings();
  666. UpdateSceneObjectMapping();
  667. if (animatedRenderable != null)
  668. animatedRenderable.RegisterAnimation(this);
  669. break;
  670. case State.EditorActive:
  671. if (_native != null)
  672. _native.Destroy();
  673. _native = new NativeAnimation();
  674. animatedRenderable = SceneObject.GetComponent<Renderable>();
  675. UpdateBounds();
  676. SetBoneMappings();
  677. if (animatedRenderable != null)
  678. animatedRenderable.RegisterAnimation(this);
  679. break;
  680. case State.Inactive:
  681. if (animatedRenderable != null)
  682. animatedRenderable.UnregisterAnimation();
  683. if (_native != null)
  684. {
  685. _native.Destroy();
  686. _native = null;
  687. }
  688. primaryClip = null;
  689. mappingInfo.Clear();
  690. floatProperties = null;
  691. break;
  692. }
  693. }
  694. /// <summary>
  695. /// Finds any curves that affect a transform of a specific scene object, and ensures that animation properly updates
  696. /// those transforms. This does not include curves referencing bones.
  697. /// </summary>
  698. private void UpdateSceneObjectMapping()
  699. {
  700. List<SceneObjectMappingInfo> newMappingInfos = new List<SceneObjectMappingInfo>();
  701. foreach(var entry in mappingInfo)
  702. {
  703. if (entry.isMappedToBone)
  704. newMappingInfos.Add(entry);
  705. else
  706. _native.UnmapSceneObject(entry.sceneObject);
  707. }
  708. if (primaryClip != null)
  709. {
  710. SceneObject root = SceneObject;
  711. Action<NamedVector3Curve[]> findMappings = x =>
  712. {
  713. foreach (var curve in x)
  714. {
  715. if (curve.Flags.HasFlag(AnimationCurveFlags.ImportedCurve))
  716. continue;
  717. SceneObject currentSO = FindSceneObject(root, curve.Name);
  718. bool found = false;
  719. for (int i = 0; i < newMappingInfos.Count; i++)
  720. {
  721. if (newMappingInfos[i].sceneObject == currentSO)
  722. {
  723. found = true;
  724. break;
  725. }
  726. }
  727. if (!found)
  728. {
  729. SceneObjectMappingInfo newMappingInfo = new SceneObjectMappingInfo();
  730. newMappingInfo.isMappedToBone = false;
  731. newMappingInfo.sceneObject = currentSO;
  732. newMappingInfos.Add(newMappingInfo);
  733. _native.MapCurveToSceneObject(curve.Name, currentSO);
  734. }
  735. }
  736. };
  737. AnimationCurves curves = primaryClip.Curves;
  738. findMappings(curves.PositionCurves);
  739. findMappings(curves.RotationCurves);
  740. findMappings(curves.ScaleCurves);
  741. }
  742. mappingInfo = newMappingInfos;
  743. }
  744. /// <summary>
  745. /// Registers a new bone component, creating a new transform mapping from the bone name to the scene object
  746. /// the component is attached to.
  747. /// </summary>
  748. /// <param name="bone">Bone component to register.</param>
  749. internal void AddBone(Bone bone)
  750. {
  751. switch (state)
  752. {
  753. case State.Active:
  754. SceneObject currentSO = bone.SceneObject;
  755. SceneObjectMappingInfo newMapping = new SceneObjectMappingInfo();
  756. newMapping.sceneObject = currentSO;
  757. newMapping.isMappedToBone = true;
  758. newMapping.bone = bone;
  759. mappingInfo.Add(newMapping);
  760. _native.MapCurveToSceneObject(bone.Name, newMapping.sceneObject);
  761. break;
  762. }
  763. }
  764. /// <summary>
  765. /// Unregisters a bone component, removing the bone -> scene object mapping.
  766. /// </summary>
  767. /// <param name="bone">Bone to unregister.</param>
  768. internal void RemoveBone(Bone bone)
  769. {
  770. switch (state)
  771. {
  772. case State.Active:
  773. for (int i = 0; i < mappingInfo.Count; i++)
  774. {
  775. if (mappingInfo[i].bone == bone)
  776. {
  777. _native.UnmapSceneObject(mappingInfo[i].sceneObject);
  778. mappingInfo.RemoveAt(i);
  779. i--;
  780. }
  781. }
  782. break;
  783. }
  784. }
  785. /// <summary>
  786. /// Called whenever the bone the <see cref="Bone"/> component points to changed.
  787. /// </summary>
  788. /// <param name="bone">Bone component to modify.</param>
  789. internal void NotifyBoneChanged(Bone bone)
  790. {
  791. switch (state)
  792. {
  793. case State.Active:
  794. for (int i = 0; i < mappingInfo.Count; i++)
  795. {
  796. if (mappingInfo[i].bone == bone)
  797. {
  798. _native.UnmapSceneObject(mappingInfo[i].sceneObject);
  799. _native.MapCurveToSceneObject(bone.Name, mappingInfo[i].sceneObject);
  800. break;
  801. }
  802. }
  803. break;
  804. }
  805. }
  806. /// <summary>
  807. /// Finds any scene objects that are mapped to bone transforms. Such object's transforms will be affected by
  808. /// skeleton bone animation.
  809. /// </summary>
  810. private void SetBoneMappings()
  811. {
  812. mappingInfo.Clear();
  813. SceneObjectMappingInfo rootMapping = new SceneObjectMappingInfo();
  814. rootMapping.sceneObject = SceneObject;
  815. rootMapping.isMappedToBone = true;
  816. mappingInfo.Add(rootMapping);
  817. _native.MapCurveToSceneObject("", rootMapping.sceneObject);
  818. Bone[] childBones = FindChildBones();
  819. foreach (var entry in childBones)
  820. AddBone(entry);
  821. }
  822. /// <summary>
  823. /// Searches child scene objects for <see cref="Bone"/> components and returns any found ones.
  824. /// </summary>
  825. private Bone[] FindChildBones()
  826. {
  827. Stack<SceneObject> todo = new Stack<SceneObject>();
  828. todo.Push(SceneObject);
  829. List<Bone> bones = new List<Bone>();
  830. while (todo.Count > 0)
  831. {
  832. SceneObject currentSO = todo.Pop();
  833. Bone bone = currentSO.GetComponent<Bone>();
  834. if (bone != null)
  835. {
  836. bone.SetParent(this, true);
  837. bones.Add(bone);
  838. }
  839. int childCount = currentSO.GetNumChildren();
  840. for (int i = 0; i < childCount; i++)
  841. {
  842. SceneObject child = currentSO.GetChild(i);
  843. if (child.GetComponent<Animation>() != null)
  844. continue;
  845. todo.Push(child);
  846. }
  847. }
  848. return bones.ToArray();
  849. }
  850. /// <summary>
  851. /// Re-applies the bounds to the internal animation object, and the relevant renderable object if one exists.
  852. /// </summary>
  853. internal void UpdateBounds(bool updateRenderable = true)
  854. {
  855. NativeRenderable renderable = null;
  856. if (updateRenderable && animatedRenderable != null)
  857. renderable = animatedRenderable.Native;
  858. if (serializableData.useBounds)
  859. {
  860. if (renderable != null)
  861. {
  862. renderable.UseOverrideBounds = true;
  863. renderable.OverrideBounds = serializableData.bounds;
  864. }
  865. if (_native != null)
  866. {
  867. AABox bounds = serializableData.bounds;
  868. Matrix4 parentTfrm;
  869. if (SceneObject.Parent != null)
  870. parentTfrm = SceneObject.Parent.WorldTransform;
  871. else
  872. parentTfrm = Matrix4.Identity;
  873. bounds.TransformAffine(parentTfrm);
  874. _native.Bounds = bounds;
  875. }
  876. }
  877. else
  878. {
  879. if (renderable != null)
  880. renderable.UseOverrideBounds = false;
  881. if (_native != null)
  882. {
  883. AABox bounds = new AABox();
  884. if (animatedRenderable != null)
  885. bounds = animatedRenderable.Bounds.Box;
  886. _native.Bounds = bounds;
  887. }
  888. }
  889. }
  890. /// <summary>
  891. /// Registers an <see cref="Renderable"/> component with the animation. Rendering will be affected by the animation.
  892. /// </summary>
  893. /// <param name="renderable">Component that was added</param>
  894. internal void RegisterRenderable(Renderable renderable)
  895. {
  896. animatedRenderable = renderable;
  897. UpdateBounds();
  898. }
  899. /// <summary>
  900. /// Removes renderable from the animation component. Rendering will no longer be affected by animation.
  901. /// </summary>
  902. internal void UnregisterRenderable()
  903. {
  904. animatedRenderable = null;
  905. }
  906. /// <summary>
  907. /// Builds a list of properties that will be animated using float animation curves.
  908. /// </summary>
  909. /// <param name="clip">Clip to retrieve the float animation curves from.</param>
  910. private void RebuildFloatProperties(AnimationClip clip)
  911. {
  912. if (clip == null)
  913. {
  914. floatProperties = null;
  915. return;
  916. }
  917. AnimationCurves curves = clip.Curves;
  918. List<FloatCurvePropertyInfo> newFloatProperties = new List<FloatCurvePropertyInfo>();
  919. for (int i = 0; i < curves.FloatCurves.Length; i++)
  920. {
  921. string suffix;
  922. SerializableProperty property = FindProperty(SceneObject, curves.FloatCurves[i].Name, out suffix);
  923. if (property == null)
  924. continue;
  925. int elementIdx = 0;
  926. if (!string.IsNullOrEmpty(suffix))
  927. {
  928. PropertySuffixInfo suffixInfo;
  929. if (PropertySuffixInfos.TryGetValue(suffix, out suffixInfo))
  930. elementIdx = suffixInfo.elementIdx;
  931. }
  932. Action<float> setter = null;
  933. Type internalType = property.InternalType;
  934. switch (property.Type)
  935. {
  936. case SerializableProperty.FieldType.Vector2:
  937. if (internalType == typeof(Vector2))
  938. {
  939. setter = f =>
  940. {
  941. Vector2 value = property.GetValue<Vector2>();
  942. value[elementIdx] = f;
  943. property.SetValue(value);
  944. };
  945. }
  946. break;
  947. case SerializableProperty.FieldType.Vector3:
  948. if (internalType == typeof(Vector3))
  949. {
  950. setter = f =>
  951. {
  952. Vector3 value = property.GetValue<Vector3>();
  953. value[elementIdx] = f;
  954. property.SetValue(value);
  955. };
  956. }
  957. break;
  958. case SerializableProperty.FieldType.Vector4:
  959. if (internalType == typeof(Vector4))
  960. {
  961. setter = f =>
  962. {
  963. Vector4 value = property.GetValue<Vector4>();
  964. value[elementIdx] = f;
  965. property.SetValue(value);
  966. };
  967. }
  968. else if (internalType == typeof(Quaternion))
  969. {
  970. setter = f =>
  971. {
  972. Quaternion value = property.GetValue<Quaternion>();
  973. value[elementIdx] = f;
  974. property.SetValue(value);
  975. };
  976. }
  977. break;
  978. case SerializableProperty.FieldType.Color:
  979. if (internalType == typeof(Color))
  980. {
  981. setter = f =>
  982. {
  983. Color value = property.GetValue<Color>();
  984. value[elementIdx] = f;
  985. property.SetValue(value);
  986. };
  987. }
  988. break;
  989. case SerializableProperty.FieldType.Bool:
  990. setter = f =>
  991. {
  992. bool value = f > 0.0f;
  993. property.SetValue(value);
  994. };
  995. break;
  996. case SerializableProperty.FieldType.Int:
  997. setter = f =>
  998. {
  999. int value = (int)f;
  1000. property.SetValue(value);
  1001. };
  1002. break;
  1003. case SerializableProperty.FieldType.Float:
  1004. setter = f =>
  1005. {
  1006. property.SetValue(f);
  1007. };
  1008. break;
  1009. }
  1010. if (setter == null)
  1011. continue;
  1012. FloatCurvePropertyInfo propertyInfo = new FloatCurvePropertyInfo();
  1013. propertyInfo.curveIdx = i;
  1014. propertyInfo.setter = setter;
  1015. newFloatProperties.Add(propertyInfo);
  1016. }
  1017. floatProperties = newFloatProperties.ToArray();
  1018. }
  1019. /// <summary>
  1020. /// Called whenever an animation event triggers.
  1021. /// </summary>
  1022. /// <param name="clip">Clip that the event originated from.</param>
  1023. /// <param name="name">Name of the event.</param>
  1024. private void EventTriggered(AnimationClip clip, string name)
  1025. {
  1026. // Event should be in format "ComponentType/MethodName"
  1027. if (string.IsNullOrEmpty(name))
  1028. return;
  1029. string[] nameEntries = name.Split('/');
  1030. if (nameEntries.Length != 2)
  1031. return;
  1032. string typeName = nameEntries[0];
  1033. string methodName = nameEntries[1];
  1034. Component[] components = SceneObject.GetComponents();
  1035. for (int i = 0; i < components.Length; i++)
  1036. {
  1037. if (components[i].GetType().Name == typeName)
  1038. {
  1039. components[i].Invoke(methodName);
  1040. break;
  1041. }
  1042. }
  1043. }
  1044. /// <summary>
  1045. /// Holds all data the animation component needs to persist through serialization.
  1046. /// </summary>
  1047. [SerializeObject]
  1048. private class SerializableData
  1049. {
  1050. public AnimationClip defaultClip;
  1051. public AnimWrapMode wrapMode = AnimWrapMode.Loop;
  1052. public float speed = 1.0f;
  1053. public AABox bounds;
  1054. public bool useBounds;
  1055. public bool cull = true;
  1056. }
  1057. /// <summary>
  1058. /// Contains information about a property animated by a generic animation curve.
  1059. /// </summary>
  1060. private class FloatCurvePropertyInfo
  1061. {
  1062. public int curveIdx;
  1063. public Action<float> setter;
  1064. }
  1065. /// <summary>
  1066. /// Information about a suffix used in a property path.
  1067. /// </summary>
  1068. internal struct PropertySuffixInfo
  1069. {
  1070. public PropertySuffixInfo(int elementIdx, bool isVector)
  1071. {
  1072. this.elementIdx = elementIdx;
  1073. this.isVector = isVector;
  1074. }
  1075. public int elementIdx;
  1076. public bool isVector;
  1077. }
  1078. /// <summary>
  1079. /// Information about scene objects bound to a specific animation curve.
  1080. /// </summary>
  1081. internal struct SceneObjectMappingInfo
  1082. {
  1083. public SceneObject sceneObject;
  1084. public bool isMappedToBone;
  1085. public Bone bone;
  1086. }
  1087. /// <summary>
  1088. /// Possible states the animation component can be in.
  1089. /// </summary>
  1090. private enum State
  1091. {
  1092. /// <summary>
  1093. /// Animation object isn't constructed.
  1094. /// </summary>
  1095. Inactive,
  1096. /// <summary>
  1097. /// Animation object is constructed and fully functional.
  1098. /// </summary>
  1099. Active,
  1100. /// <summary>
  1101. /// Animation object is constructed and functional with limited funcionality for editor purposes.
  1102. /// </summary>
  1103. EditorActive
  1104. }
  1105. }
  1106. /// <summary>
  1107. /// Determines how an animation clip behaves when it reaches the end.
  1108. /// </summary>
  1109. public enum AnimWrapMode // Note: Must match C++ enum AnimWrapMode
  1110. {
  1111. /// <summary>
  1112. /// Loop around to the beginning/end when the last/first frame is reached.
  1113. /// </summary>
  1114. Loop,
  1115. /// <summary>
  1116. /// Clamp to end/beginning, keeping the last/first frame active.
  1117. /// </summary>
  1118. Clamp
  1119. }
  1120. /// <summary>
  1121. /// Represents an animation clip used in 1D blending. Each clip has a position on the number line.
  1122. /// </summary>
  1123. public class BlendClipInfo
  1124. {
  1125. public AnimationClip clip;
  1126. public float position;
  1127. }
  1128. /// <summary>
  1129. /// Defines a 1D blend where two animation clips are blended between each other using linear interpolation.
  1130. /// </summary>
  1131. public class Blend1DInfo
  1132. {
  1133. public Blend1DInfo()
  1134. { }
  1135. public Blend1DInfo(int numClips)
  1136. {
  1137. clips = new BlendClipInfo[numClips];
  1138. }
  1139. public BlendClipInfo[] clips;
  1140. }
  1141. /// <summary>
  1142. /// Defines a 2D blend where two animation clips are blended between each other using bilinear interpolation.
  1143. /// </summary>
  1144. public class Blend2DInfo
  1145. {
  1146. public AnimationClip topLeftClip;
  1147. public AnimationClip topRightClip;
  1148. public AnimationClip botLeftClip;
  1149. public AnimationClip botRightClip;
  1150. }
  1151. /// <summary>
  1152. /// Contains information about a currently playing animation clip.
  1153. /// </summary>
  1154. [StructLayout(LayoutKind.Sequential), SerializeObject]
  1155. public struct AnimationClipState // Note: Must match C++ struct AnimationClipState
  1156. {
  1157. /// <summary>
  1158. /// Layer the clip is playing on. Multiple clips can be played simulatenously on different layers.
  1159. /// </summary>
  1160. public int layer;
  1161. /// <summary>
  1162. /// Current time the animation is playing from.
  1163. /// </summary>
  1164. public float time;
  1165. /// <summary>
  1166. /// Speed at which the animation is playing.
  1167. /// </summary>
  1168. public float speed;
  1169. /// <summary>
  1170. /// Determines how much of an influence does the clip have on the final pose.
  1171. /// </summary>
  1172. public float weight;
  1173. /// <summary>
  1174. /// Determines what happens to other animation clips when a new clip starts playing.
  1175. /// </summary>
  1176. public AnimWrapMode wrapMode;
  1177. /// <summary>
  1178. /// Creates a new clip state, with default values initialized.
  1179. /// </summary>
  1180. /// <returns>New animation clip state.</returns>
  1181. public static AnimationClipState Create()
  1182. {
  1183. AnimationClipState state = new AnimationClipState();
  1184. state.speed = 1.0f;
  1185. state.weight = 1.0f;
  1186. state.wrapMode = AnimWrapMode.Loop;
  1187. return state;
  1188. }
  1189. }
  1190. /** @} */
  1191. }