Animation.cs 50 KB

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