NetworkAnimator.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. using System.Linq;
  2. using UnityEngine;
  3. using UnityEngine.Serialization;
  4. namespace Mirror
  5. {
  6. /// <summary>
  7. /// A component to synchronize Mecanim animation states for networked objects.
  8. /// </summary>
  9. /// <remarks>
  10. /// <para>The animation of game objects can be networked by this component. There are two models of authority for networked movement:</para>
  11. /// <para>If the object has authority on the client, then it should be animated locally on the owning client. The animation state information will be sent from the owning client to the server, then broadcast to all of the other clients. This is common for player objects.</para>
  12. /// <para>If the object has authority on the server, then it should be animated on the server and state information will be sent to all clients. This is common for objects not related to a specific client, such as an enemy unit.</para>
  13. /// <para>The NetworkAnimator synchronizes all animation parameters of the selected Animator. It does not automatically synchronize triggers. The function SetTrigger can by used by an object with authority to fire an animation trigger on other clients.</para>
  14. /// </remarks>
  15. [AddComponentMenu("Network/NetworkAnimator")]
  16. [RequireComponent(typeof(NetworkIdentity))]
  17. [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-animator")]
  18. public class NetworkAnimator : NetworkBehaviour
  19. {
  20. [Header("Authority")]
  21. [Tooltip("Set to true if animations come from owner client, set to false if animations always come from server")]
  22. public bool clientAuthority;
  23. /// <summary>
  24. /// The animator component to synchronize.
  25. /// </summary>
  26. [FormerlySerializedAs("m_Animator")]
  27. [Header("Animator")]
  28. [Tooltip("Animator that will have parameters synchronized")]
  29. public Animator animator;
  30. /// <summary>
  31. /// Syncs animator.speed
  32. /// </summary>
  33. [SyncVar(hook = nameof(OnAnimatorSpeedChanged))]
  34. float animatorSpeed;
  35. float previousSpeed;
  36. // Note: not an object[] array because otherwise initialization is real annoying
  37. int[] lastIntParameters;
  38. float[] lastFloatParameters;
  39. bool[] lastBoolParameters;
  40. AnimatorControllerParameter[] parameters;
  41. // multiple layers
  42. int[] animationHash;
  43. int[] transitionHash;
  44. float[] layerWeight;
  45. double nextSendTime;
  46. bool SendMessagesAllowed
  47. {
  48. get
  49. {
  50. if (isServer)
  51. {
  52. if (!clientAuthority)
  53. return true;
  54. // This is a special case where we have client authority but we have not assigned the client who has
  55. // authority over it, no animator data will be sent over the network by the server.
  56. //
  57. // So we check here for a connectionToClient and if it is null we will
  58. // let the server send animation data until we receive an owner.
  59. if (netIdentity != null && netIdentity.connectionToClient == null)
  60. return true;
  61. }
  62. return (hasAuthority && clientAuthority);
  63. }
  64. }
  65. void Awake()
  66. {
  67. // store the animator parameters in a variable - the "Animator.parameters" getter allocates
  68. // a new parameter array every time it is accessed so we should avoid doing it in a loop
  69. parameters = animator.parameters
  70. .Where(par => !animator.IsParameterControlledByCurve(par.nameHash))
  71. .ToArray();
  72. lastIntParameters = new int[parameters.Length];
  73. lastFloatParameters = new float[parameters.Length];
  74. lastBoolParameters = new bool[parameters.Length];
  75. animationHash = new int[animator.layerCount];
  76. transitionHash = new int[animator.layerCount];
  77. layerWeight = new float[animator.layerCount];
  78. }
  79. void FixedUpdate()
  80. {
  81. if (!SendMessagesAllowed)
  82. return;
  83. if (!animator.enabled)
  84. return;
  85. CheckSendRate();
  86. for (int i = 0; i < animator.layerCount; i++)
  87. {
  88. int stateHash;
  89. float normalizedTime;
  90. if (!CheckAnimStateChanged(out stateHash, out normalizedTime, i))
  91. {
  92. continue;
  93. }
  94. using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
  95. {
  96. WriteParameters(writer);
  97. SendAnimationMessage(stateHash, normalizedTime, i, layerWeight[i], writer.ToArray());
  98. }
  99. }
  100. CheckSpeed();
  101. }
  102. void CheckSpeed()
  103. {
  104. float newSpeed = animator.speed;
  105. if (Mathf.Abs(previousSpeed - newSpeed) > 0.001f)
  106. {
  107. previousSpeed = newSpeed;
  108. if (isServer)
  109. {
  110. animatorSpeed = newSpeed;
  111. }
  112. else if (isClient)
  113. {
  114. CmdSetAnimatorSpeed(newSpeed);
  115. }
  116. }
  117. }
  118. void OnAnimatorSpeedChanged(float _, float value)
  119. {
  120. // skip if host or client with authority
  121. // they will have already set the speed so don't set again
  122. if (isServer || (hasAuthority && clientAuthority))
  123. return;
  124. animator.speed = value;
  125. }
  126. bool CheckAnimStateChanged(out int stateHash, out float normalizedTime, int layerId)
  127. {
  128. bool change = false;
  129. stateHash = 0;
  130. normalizedTime = 0;
  131. float lw = animator.GetLayerWeight(layerId);
  132. if (Mathf.Abs(lw - layerWeight[layerId]) > 0.001f)
  133. {
  134. layerWeight[layerId] = lw;
  135. change = true;
  136. }
  137. if (animator.IsInTransition(layerId))
  138. {
  139. AnimatorTransitionInfo tt = animator.GetAnimatorTransitionInfo(layerId);
  140. if (tt.fullPathHash != transitionHash[layerId])
  141. {
  142. // first time in this transition
  143. transitionHash[layerId] = tt.fullPathHash;
  144. animationHash[layerId] = 0;
  145. return true;
  146. }
  147. return change;
  148. }
  149. AnimatorStateInfo st = animator.GetCurrentAnimatorStateInfo(layerId);
  150. if (st.fullPathHash != animationHash[layerId])
  151. {
  152. // first time in this animation state
  153. if (animationHash[layerId] != 0)
  154. {
  155. // came from another animation directly - from Play()
  156. stateHash = st.fullPathHash;
  157. normalizedTime = st.normalizedTime;
  158. }
  159. transitionHash[layerId] = 0;
  160. animationHash[layerId] = st.fullPathHash;
  161. return true;
  162. }
  163. return change;
  164. }
  165. void CheckSendRate()
  166. {
  167. double now = NetworkTime.localTime;
  168. if (SendMessagesAllowed && syncInterval >= 0 && now > nextSendTime)
  169. {
  170. nextSendTime = now + syncInterval;
  171. using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
  172. {
  173. if (WriteParameters(writer))
  174. SendAnimationParametersMessage(writer.ToArray());
  175. }
  176. }
  177. }
  178. void SendAnimationMessage(int stateHash, float normalizedTime, int layerId, float weight, byte[] parameters)
  179. {
  180. if (isServer)
  181. {
  182. RpcOnAnimationClientMessage(stateHash, normalizedTime, layerId, weight, parameters);
  183. }
  184. else if (isClient)
  185. {
  186. CmdOnAnimationServerMessage(stateHash, normalizedTime, layerId, weight, parameters);
  187. }
  188. }
  189. void SendAnimationParametersMessage(byte[] parameters)
  190. {
  191. if (isServer)
  192. {
  193. RpcOnAnimationParametersClientMessage(parameters);
  194. }
  195. else if (isClient)
  196. {
  197. CmdOnAnimationParametersServerMessage(parameters);
  198. }
  199. }
  200. void HandleAnimMsg(int stateHash, float normalizedTime, int layerId, float weight, NetworkReader reader)
  201. {
  202. if (hasAuthority && clientAuthority)
  203. return;
  204. // usually transitions will be triggered by parameters, if not, play anims directly.
  205. // NOTE: this plays "animations", not transitions, so any transitions will be skipped.
  206. // NOTE: there is no API to play a transition(?)
  207. if (stateHash != 0 && animator.enabled)
  208. {
  209. animator.Play(stateHash, layerId, normalizedTime);
  210. }
  211. animator.SetLayerWeight(layerId, weight);
  212. ReadParameters(reader);
  213. }
  214. void HandleAnimParamsMsg(NetworkReader reader)
  215. {
  216. if (hasAuthority && clientAuthority)
  217. return;
  218. ReadParameters(reader);
  219. }
  220. void HandleAnimTriggerMsg(int hash)
  221. {
  222. if (animator.enabled)
  223. animator.SetTrigger(hash);
  224. }
  225. void HandleAnimResetTriggerMsg(int hash)
  226. {
  227. if (animator.enabled)
  228. animator.ResetTrigger(hash);
  229. }
  230. ulong NextDirtyBits()
  231. {
  232. ulong dirtyBits = 0;
  233. for (int i = 0; i < parameters.Length; i++)
  234. {
  235. AnimatorControllerParameter par = parameters[i];
  236. bool changed = false;
  237. if (par.type == AnimatorControllerParameterType.Int)
  238. {
  239. int newIntValue = animator.GetInteger(par.nameHash);
  240. changed = newIntValue != lastIntParameters[i];
  241. if (changed)
  242. lastIntParameters[i] = newIntValue;
  243. }
  244. else if (par.type == AnimatorControllerParameterType.Float)
  245. {
  246. float newFloatValue = animator.GetFloat(par.nameHash);
  247. changed = Mathf.Abs(newFloatValue - lastFloatParameters[i]) > 0.001f;
  248. // only set lastValue if it was changed, otherwise value could slowly drift within the 0.001f limit each frame
  249. if (changed)
  250. lastFloatParameters[i] = newFloatValue;
  251. }
  252. else if (par.type == AnimatorControllerParameterType.Bool)
  253. {
  254. bool newBoolValue = animator.GetBool(par.nameHash);
  255. changed = newBoolValue != lastBoolParameters[i];
  256. if (changed)
  257. lastBoolParameters[i] = newBoolValue;
  258. }
  259. if (changed)
  260. {
  261. dirtyBits |= 1ul << i;
  262. }
  263. }
  264. return dirtyBits;
  265. }
  266. bool WriteParameters(NetworkWriter writer, bool forceAll = false)
  267. {
  268. ulong dirtyBits = forceAll ? (~0ul) : NextDirtyBits();
  269. writer.WriteULong(dirtyBits);
  270. for (int i = 0; i < parameters.Length; i++)
  271. {
  272. if ((dirtyBits & (1ul << i)) == 0)
  273. continue;
  274. AnimatorControllerParameter par = parameters[i];
  275. if (par.type == AnimatorControllerParameterType.Int)
  276. {
  277. int newIntValue = animator.GetInteger(par.nameHash);
  278. writer.WriteInt(newIntValue);
  279. }
  280. else if (par.type == AnimatorControllerParameterType.Float)
  281. {
  282. float newFloatValue = animator.GetFloat(par.nameHash);
  283. writer.WriteFloat(newFloatValue);
  284. }
  285. else if (par.type == AnimatorControllerParameterType.Bool)
  286. {
  287. bool newBoolValue = animator.GetBool(par.nameHash);
  288. writer.WriteBool(newBoolValue);
  289. }
  290. }
  291. return dirtyBits != 0;
  292. }
  293. void ReadParameters(NetworkReader reader)
  294. {
  295. bool animatorEnabled = animator.enabled;
  296. // need to read values from NetworkReader even if animator is disabled
  297. ulong dirtyBits = reader.ReadULong();
  298. for (int i = 0; i < parameters.Length; i++)
  299. {
  300. if ((dirtyBits & (1ul << i)) == 0)
  301. continue;
  302. AnimatorControllerParameter par = parameters[i];
  303. if (par.type == AnimatorControllerParameterType.Int)
  304. {
  305. int newIntValue = reader.ReadInt();
  306. if (animatorEnabled)
  307. animator.SetInteger(par.nameHash, newIntValue);
  308. }
  309. else if (par.type == AnimatorControllerParameterType.Float)
  310. {
  311. float newFloatValue = reader.ReadFloat();
  312. if (animatorEnabled)
  313. animator.SetFloat(par.nameHash, newFloatValue);
  314. }
  315. else if (par.type == AnimatorControllerParameterType.Bool)
  316. {
  317. bool newBoolValue = reader.ReadBool();
  318. if (animatorEnabled)
  319. animator.SetBool(par.nameHash, newBoolValue);
  320. }
  321. }
  322. }
  323. /// <summary>
  324. /// Custom Serialization
  325. /// </summary>
  326. /// <param name="writer"></param>
  327. /// <param name="initialState"></param>
  328. /// <returns></returns>
  329. public override bool OnSerialize(NetworkWriter writer, bool initialState)
  330. {
  331. bool changed = base.OnSerialize(writer, initialState);
  332. if (initialState)
  333. {
  334. for (int i = 0; i < animator.layerCount; i++)
  335. {
  336. if (animator.IsInTransition(i))
  337. {
  338. AnimatorStateInfo st = animator.GetNextAnimatorStateInfo(i);
  339. writer.WriteInt(st.fullPathHash);
  340. writer.WriteFloat(st.normalizedTime);
  341. }
  342. else
  343. {
  344. AnimatorStateInfo st = animator.GetCurrentAnimatorStateInfo(i);
  345. writer.WriteInt(st.fullPathHash);
  346. writer.WriteFloat(st.normalizedTime);
  347. }
  348. writer.WriteFloat(animator.GetLayerWeight(i));
  349. }
  350. WriteParameters(writer, initialState);
  351. return true;
  352. }
  353. return changed;
  354. }
  355. /// <summary>
  356. /// Custom Deserialization
  357. /// </summary>
  358. /// <param name="reader"></param>
  359. /// <param name="initialState"></param>
  360. public override void OnDeserialize(NetworkReader reader, bool initialState)
  361. {
  362. base.OnDeserialize(reader, initialState);
  363. if (initialState)
  364. {
  365. for (int i = 0; i < animator.layerCount; i++)
  366. {
  367. int stateHash = reader.ReadInt();
  368. float normalizedTime = reader.ReadFloat();
  369. animator.SetLayerWeight(i, reader.ReadFloat());
  370. animator.Play(stateHash, i, normalizedTime);
  371. }
  372. ReadParameters(reader);
  373. }
  374. }
  375. /// <summary>
  376. /// Causes an animation trigger to be invoked for a networked object.
  377. /// <para>If local authority is set, and this is called from the client, then the trigger will be invoked on the server and all clients. If not, then this is called on the server, and the trigger will be called on all clients.</para>
  378. /// </summary>
  379. /// <param name="triggerName">Name of trigger.</param>
  380. public void SetTrigger(string triggerName)
  381. {
  382. SetTrigger(Animator.StringToHash(triggerName));
  383. }
  384. /// <summary>
  385. /// Causes an animation trigger to be invoked for a networked object.
  386. /// </summary>
  387. /// <param name="hash">Hash id of trigger (from the Animator).</param>
  388. public void SetTrigger(int hash)
  389. {
  390. if (clientAuthority)
  391. {
  392. if (!isClient)
  393. {
  394. Debug.LogWarning("Tried to set animation in the server for a client-controlled animator");
  395. return;
  396. }
  397. if (!hasAuthority)
  398. {
  399. Debug.LogWarning("Only the client with authority can set animations");
  400. return;
  401. }
  402. if (isClient)
  403. CmdOnAnimationTriggerServerMessage(hash);
  404. // call on client right away
  405. HandleAnimTriggerMsg(hash);
  406. }
  407. else
  408. {
  409. if (!isServer)
  410. {
  411. Debug.LogWarning("Tried to set animation in the client for a server-controlled animator");
  412. return;
  413. }
  414. HandleAnimTriggerMsg(hash);
  415. RpcOnAnimationTriggerClientMessage(hash);
  416. }
  417. }
  418. /// <summary>
  419. /// Causes an animation trigger to be reset for a networked object.
  420. /// <para>If local authority is set, and this is called from the client, then the trigger will be reset on the server and all clients. If not, then this is called on the server, and the trigger will be reset on all clients.</para>
  421. /// </summary>
  422. /// <param name="triggerName">Name of trigger.</param>
  423. public void ResetTrigger(string triggerName)
  424. {
  425. ResetTrigger(Animator.StringToHash(triggerName));
  426. }
  427. /// <summary>
  428. /// Causes an animation trigger to be reset for a networked object.
  429. /// </summary>
  430. /// <param name="hash">Hash id of trigger (from the Animator).</param>
  431. public void ResetTrigger(int hash)
  432. {
  433. if (clientAuthority)
  434. {
  435. if (!isClient)
  436. {
  437. Debug.LogWarning("Tried to reset animation in the server for a client-controlled animator");
  438. return;
  439. }
  440. if (!hasAuthority)
  441. {
  442. Debug.LogWarning("Only the client with authority can reset animations");
  443. return;
  444. }
  445. if (isClient)
  446. CmdOnAnimationResetTriggerServerMessage(hash);
  447. // call on client right away
  448. HandleAnimResetTriggerMsg(hash);
  449. }
  450. else
  451. {
  452. if (!isServer)
  453. {
  454. Debug.LogWarning("Tried to reset animation in the client for a server-controlled animator");
  455. return;
  456. }
  457. HandleAnimResetTriggerMsg(hash);
  458. RpcOnAnimationResetTriggerClientMessage(hash);
  459. }
  460. }
  461. #region server message handlers
  462. [Command]
  463. void CmdOnAnimationServerMessage(int stateHash, float normalizedTime, int layerId, float weight, byte[] parameters)
  464. {
  465. // Ignore messages from client if not in client authority mode
  466. if (!clientAuthority)
  467. return;
  468. // Debug.Log("OnAnimationMessage for netId=" + netId);
  469. // handle and broadcast
  470. using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters))
  471. {
  472. HandleAnimMsg(stateHash, normalizedTime, layerId, weight, networkReader);
  473. RpcOnAnimationClientMessage(stateHash, normalizedTime, layerId, weight, parameters);
  474. }
  475. }
  476. [Command]
  477. void CmdOnAnimationParametersServerMessage(byte[] parameters)
  478. {
  479. // Ignore messages from client if not in client authority mode
  480. if (!clientAuthority)
  481. return;
  482. // handle and broadcast
  483. using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters))
  484. {
  485. HandleAnimParamsMsg(networkReader);
  486. RpcOnAnimationParametersClientMessage(parameters);
  487. }
  488. }
  489. [Command]
  490. void CmdOnAnimationTriggerServerMessage(int hash)
  491. {
  492. // Ignore messages from client if not in client authority mode
  493. if (!clientAuthority)
  494. return;
  495. // handle and broadcast
  496. // host should have already the trigger
  497. bool isHostOwner = isClient && hasAuthority;
  498. if (!isHostOwner)
  499. {
  500. HandleAnimTriggerMsg(hash);
  501. }
  502. RpcOnAnimationTriggerClientMessage(hash);
  503. }
  504. [Command]
  505. void CmdOnAnimationResetTriggerServerMessage(int hash)
  506. {
  507. // Ignore messages from client if not in client authority mode
  508. if (!clientAuthority)
  509. return;
  510. // handle and broadcast
  511. // host should have already the trigger
  512. bool isHostOwner = isClient && hasAuthority;
  513. if (!isHostOwner)
  514. {
  515. HandleAnimResetTriggerMsg(hash);
  516. }
  517. RpcOnAnimationResetTriggerClientMessage(hash);
  518. }
  519. [Command]
  520. void CmdSetAnimatorSpeed(float newSpeed)
  521. {
  522. // set animator
  523. animator.speed = newSpeed;
  524. animatorSpeed = newSpeed;
  525. }
  526. #endregion
  527. #region client message handlers
  528. [ClientRpc]
  529. void RpcOnAnimationClientMessage(int stateHash, float normalizedTime, int layerId, float weight, byte[] parameters)
  530. {
  531. using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters))
  532. HandleAnimMsg(stateHash, normalizedTime, layerId, weight, networkReader);
  533. }
  534. [ClientRpc]
  535. void RpcOnAnimationParametersClientMessage(byte[] parameters)
  536. {
  537. using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters))
  538. HandleAnimParamsMsg(networkReader);
  539. }
  540. [ClientRpc]
  541. void RpcOnAnimationTriggerClientMessage(int hash)
  542. {
  543. // host/owner handles this before it is sent
  544. if (isServer || (clientAuthority && hasAuthority)) return;
  545. HandleAnimTriggerMsg(hash);
  546. }
  547. [ClientRpc]
  548. void RpcOnAnimationResetTriggerClientMessage(int hash)
  549. {
  550. // host/owner handles this before it is sent
  551. if (isServer || (clientAuthority && hasAuthority)) return;
  552. HandleAnimResetTriggerMsg(hash);
  553. }
  554. #endregion
  555. }
  556. }