NetworkBehaviour.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Runtime.CompilerServices;
  5. using UnityEngine;
  6. namespace Mirror
  7. {
  8. // SyncMode decides if a component is synced to all observers, or only owner
  9. public enum SyncMode { Observers, Owner }
  10. // SyncDirection decides if a component is synced from:
  11. // * server to all clients
  12. // * owner client, to server, to all other clients
  13. //
  14. // naming: 'ClientToServer' etc. instead of 'ClientAuthority', because
  15. // that wouldn't be accurate. server's OnDeserialize can still validate
  16. // client data before applying. it's really about direction, not authority.
  17. public enum SyncDirection { ServerToClient, ClientToServer }
  18. /// <summary>Base class for networked components.</summary>
  19. [AddComponentMenu("")]
  20. [RequireComponent(typeof(NetworkIdentity))]
  21. [HelpURL("https://mirror-networking.gitbook.io/docs/guides/networkbehaviour")]
  22. public abstract class NetworkBehaviour : MonoBehaviour
  23. {
  24. /// <summary>Sync direction for OnSerialize. ServerToClient by default. ClientToServer for client authority.</summary>
  25. [Tooltip("Server Authority calls OnSerialize on the server and syncs it to clients.\n\nClient Authority calls OnSerialize on the owning client, syncs it to server, which then broadcasts it to all other clients.\n\nUse server authority for cheat safety.")]
  26. [HideInInspector] public SyncDirection syncDirection = SyncDirection.ServerToClient;
  27. /// <summary>sync mode for OnSerialize</summary>
  28. // hidden because NetworkBehaviourInspector shows it only if has OnSerialize.
  29. [Tooltip("By default synced data is sent from the server to all Observers of the object.\nChange this to Owner to only have the server update the client that has ownership authority for this object")]
  30. [HideInInspector] public SyncMode syncMode = SyncMode.Observers;
  31. /// <summary>sync interval for OnSerialize (in seconds)</summary>
  32. // hidden because NetworkBehaviourInspector shows it only if has OnSerialize.
  33. // [0,2] should be enough. anything >2s is too laggy anyway.
  34. [Tooltip("Time in seconds until next change is synchronized to the client. '0' means send immediately if changed. '0.5' means only send changes every 500ms.\n(This is for state synchronization like SyncVars, SyncLists, OnSerialize. Not for Cmds, Rpcs, etc.)")]
  35. [Range(0, 2)]
  36. [HideInInspector] public float syncInterval = 0.1f;
  37. internal double lastSyncTime;
  38. /// <summary>True if this object is on the server and has been spawned.</summary>
  39. // This is different from NetworkServer.active, which is true if the
  40. // server itself is active rather than this object being active.
  41. public bool isServer => netIdentity.isServer;
  42. /// <summary>True if this object is on the client and has been spawned by the server.</summary>
  43. public bool isClient => netIdentity.isClient;
  44. /// <summary>True if this object is the the client's own local player.</summary>
  45. public bool isLocalPlayer => netIdentity.isLocalPlayer;
  46. /// <summary>True if this object is on the server-only, not host.</summary>
  47. public bool isServerOnly => netIdentity.isServerOnly;
  48. /// <summary>True if this object is on the client-only, not host.</summary>
  49. public bool isClientOnly => netIdentity.isClientOnly;
  50. /// <summary>isOwned is true on the client if this NetworkIdentity is one of the .owned entities of our connection on the server.</summary>
  51. // for example: main player & pets are owned. monsters & npcs aren't.
  52. public bool isOwned => netIdentity.isOwned;
  53. /// <summary>True on client if that component has been assigned to the client. E.g. player, pets, henchmen.</summary>
  54. [Obsolete(".hasAuthority was renamed to .isOwned. This is easier to understand and prepares for SyncDirection, where there is a difference betwen isOwned and authority.")] // 2022-10-13
  55. public bool hasAuthority => isOwned;
  56. /// <summary>authority is true if we are allowed to modify this component's state. On server, it's true if SyncDirection is ServerToClient. On client, it's true if SyncDirection is ClientToServer and(!) if this object is owned by the client.</summary>
  57. // on the client: if owned and if clientAuthority sync direction
  58. // on the server: if serverAuthority sync direction
  59. //
  60. // for example, NetworkTransform:
  61. // client may modify position if ClientAuthority mode and owned
  62. // server may modify position only if server authority
  63. //
  64. // note that in original Mirror, hasAuthority only meant 'isOwned'.
  65. // there was no syncDirection to check.
  66. //
  67. // also note that this is a per-NetworkBehaviour flag.
  68. // another component may not be client authoritative, etc.
  69. public bool authority =>
  70. isClient
  71. ? syncDirection == SyncDirection.ClientToServer && isOwned
  72. : syncDirection == SyncDirection.ServerToClient;
  73. /// <summary>The unique network Id of this object (unique at runtime).</summary>
  74. public uint netId => netIdentity.netId;
  75. /// <summary>Client's network connection to the server. This is only valid for player objects on the client.</summary>
  76. // TODO change to NetworkConnectionToServer, but might cause some breaking
  77. public NetworkConnection connectionToServer => netIdentity.connectionToServer;
  78. /// <summary>Server's network connection to the client. This is only valid for player objects on the server.</summary>
  79. public NetworkConnectionToClient connectionToClient => netIdentity.connectionToClient;
  80. // SyncLists, SyncSets, etc.
  81. protected readonly List<SyncObject> syncObjects = new List<SyncObject>();
  82. // NetworkBehaviourInspector needs to know if we have SyncObjects
  83. internal bool HasSyncObjects() => syncObjects.Count > 0;
  84. // NetworkIdentity based values set from NetworkIdentity.Awake(),
  85. // which is way more simple and way faster than trying to figure out
  86. // component index from in here by searching all NetworkComponents.
  87. /// <summary>Returns the NetworkIdentity of this object</summary>
  88. public NetworkIdentity netIdentity { get; internal set; }
  89. /// <summary>Returns the index of the component on this object</summary>
  90. public byte ComponentIndex { get; internal set; }
  91. // to avoid fully serializing entities every time, we have two options:
  92. // * run a delta compression algorithm
  93. // -> for fixed size types this is as easy as varint(b-a) for all
  94. // -> for dynamically sized types like strings this is not easy.
  95. // algorithms need to detect inserts/deletions, i.e. Myers Diff.
  96. // those are very cpu intensive and barely fast enough for large
  97. // scale multiplayer games (in Unity)
  98. // * or we use dirty bits as meta data about which fields have changed
  99. // -> spares us from running delta algorithms
  100. // -> still supports dynamically sized types
  101. //
  102. // 64 bit mask, tracking up to 64 SyncVars.
  103. protected ulong syncVarDirtyBits { get; private set; }
  104. // 64 bit mask, tracking up to 64 sync collections (internal for tests).
  105. // internal for tests, field for faster access (instead of property)
  106. // TODO 64 SyncLists are too much. consider smaller mask later.
  107. internal ulong syncObjectDirtyBits;
  108. // Weaver replaces '[SyncVar] int health' with 'Networkhealth' property.
  109. // setter calls the hook if value changed.
  110. // if we then modify the [SyncVar] from inside the setter,
  111. // the setter would call the hook and we deadlock.
  112. // hook guard prevents that.
  113. ulong syncVarHookGuard;
  114. // USED BY WEAVER to set syncvars in host mode without deadlocking
  115. protected bool GetSyncVarHookGuard(ulong dirtyBit) =>
  116. (syncVarHookGuard & dirtyBit) != 0UL;
  117. // USED BY WEAVER to set syncvars in host mode without deadlocking
  118. protected void SetSyncVarHookGuard(ulong dirtyBit, bool value)
  119. {
  120. // set the bit
  121. if (value)
  122. syncVarHookGuard |= dirtyBit;
  123. // clear the bit
  124. else
  125. syncVarHookGuard &= ~dirtyBit;
  126. }
  127. /// <summary>Set as dirty so that it's synced to clients again.</summary>
  128. // these are masks, not bit numbers, ie. 110011b not '2' for 2nd bit.
  129. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  130. public void SetSyncVarDirtyBit(ulong dirtyBit)
  131. {
  132. syncVarDirtyBits |= dirtyBit;
  133. }
  134. /// <summary>Set as dirty to trigger OnSerialize & send. Dirty bits are cleared after the send.</summary>
  135. // previously one had to use SetSyncVarDirtyBit(1), which is confusing.
  136. // simply reuse SetSyncVarDirtyBit for now.
  137. // instead of adding another field.
  138. // syncVarDirtyBits does trigger OnSerialize as well.
  139. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  140. public void SetDirty() => SetSyncVarDirtyBit(ulong.MaxValue);
  141. // true if syncInterval elapsed and any SyncVar or SyncObject is dirty
  142. // OR both bitmasks. != 0 if either was dirty.
  143. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  144. public bool IsDirty() =>
  145. // check bits first. this is basically free.
  146. (syncVarDirtyBits | syncObjectDirtyBits) != 0UL &&
  147. // only check time if bits were dirty. this is more expensive.
  148. NetworkTime.localTime - lastSyncTime >= syncInterval;
  149. /// <summary>Clears all the dirty bits that were set by SetDirtyBits()</summary>
  150. // automatically invoked when an update is sent for this object, but can
  151. // be called manually as well.
  152. public void ClearAllDirtyBits()
  153. {
  154. lastSyncTime = NetworkTime.localTime;
  155. syncVarDirtyBits = 0L;
  156. syncObjectDirtyBits = 0L;
  157. // clear all unsynchronized changes in syncobjects
  158. // (Linq allocates, use for instead)
  159. for (int i = 0; i < syncObjects.Count; ++i)
  160. {
  161. syncObjects[i].ClearChanges();
  162. }
  163. }
  164. // this gets called in the constructor by the weaver
  165. // for every SyncObject in the component (e.g. SyncLists).
  166. // We collect all of them and we synchronize them with OnSerialize/OnDeserialize
  167. protected void InitSyncObject(SyncObject syncObject)
  168. {
  169. if (syncObject == null)
  170. {
  171. Debug.LogError("Uninitialized SyncObject. Manually call the constructor on your SyncList, SyncSet, SyncDictionary or SyncField<T>");
  172. return;
  173. }
  174. // add it, remember the index in list (if Count=0, index=0 etc.)
  175. int index = syncObjects.Count;
  176. syncObjects.Add(syncObject);
  177. // OnDirty needs to set nth bit in our dirty mask
  178. ulong nthBit = 1UL << index;
  179. syncObject.OnDirty = () => syncObjectDirtyBits |= nthBit;
  180. // only record changes while we have observers.
  181. // prevents ever growing .changes lists:
  182. // if a monster has no observers but we keep modifing a SyncObject,
  183. // then the changes would never be flushed and keep growing,
  184. // because OnSerialize isn't called without observers.
  185. syncObject.IsRecording = () => netIdentity.observers?.Count > 0;
  186. }
  187. // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions
  188. protected void SendCommandInternal(string functionFullName, NetworkWriter writer, int channelId, bool requiresAuthority = true)
  189. {
  190. // this was in Weaver before
  191. // NOTE: we could remove this later to allow calling Cmds on Server
  192. // to avoid Wrapper functions. a lot of people requested this.
  193. if (!NetworkClient.active)
  194. {
  195. Debug.LogError($"Command Function {functionFullName} called on {name} without an active client.", gameObject);
  196. return;
  197. }
  198. // previously we used NetworkClient.readyConnection.
  199. // now we check .ready separately.
  200. if (!NetworkClient.ready)
  201. {
  202. // Unreliable Cmds from NetworkTransform may be generated,
  203. // or client may have been set NotReady intentionally, so
  204. // only warn if on the reliable channel.
  205. if (channelId == Channels.Reliable)
  206. Debug.LogWarning($"Command Function {functionFullName} called on {name} while NetworkClient is not ready.\nThis may be ignored if client intentionally set NotReady.", gameObject);
  207. return;
  208. }
  209. // local players can always send commands, regardless of authority, other objects must have authority.
  210. if (!(!requiresAuthority || isLocalPlayer || isOwned))
  211. {
  212. Debug.LogWarning($"Command Function {functionFullName} called on {name} without authority.", gameObject);
  213. return;
  214. }
  215. // IMPORTANT: can't use .connectionToServer here because calling
  216. // a command on other objects is allowed if requireAuthority is
  217. // false. other objects don't have a .connectionToServer.
  218. // => so we always need to use NetworkClient.connection instead.
  219. // => see also: https://github.com/vis2k/Mirror/issues/2629
  220. if (NetworkClient.connection == null)
  221. {
  222. Debug.LogError($"Command Function {functionFullName} called on {name} with no client running.", gameObject);
  223. return;
  224. }
  225. // construct the message
  226. CommandMessage message = new CommandMessage
  227. {
  228. netId = netId,
  229. componentIndex = ComponentIndex,
  230. // type+func so Inventory.RpcUse != Equipment.RpcUse
  231. functionHash = (ushort)functionFullName.GetStableHashCode(),
  232. // segment to avoid reader allocations
  233. payload = writer.ToArraySegment()
  234. };
  235. // IMPORTANT: can't use .connectionToServer here because calling
  236. // a command on other objects is allowed if requireAuthority is
  237. // false. other objects don't have a .connectionToServer.
  238. // => so we always need to use NetworkClient.connection instead.
  239. // => see also: https://github.com/vis2k/Mirror/issues/2629
  240. NetworkClient.connection.Send(message, channelId);
  241. }
  242. // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions
  243. protected void SendRPCInternal(string functionFullName, NetworkWriter writer, int channelId, bool includeOwner)
  244. {
  245. // this was in Weaver before
  246. if (!NetworkServer.active)
  247. {
  248. Debug.LogError($"RPC Function {functionFullName} called on Client.", gameObject);
  249. return;
  250. }
  251. // This cannot use NetworkServer.active, as that is not specific to this object.
  252. if (!isServer)
  253. {
  254. Debug.LogWarning($"ClientRpc {functionFullName} called on un-spawned object: {name}", gameObject);
  255. return;
  256. }
  257. // construct the message
  258. RpcMessage message = new RpcMessage
  259. {
  260. netId = netId,
  261. componentIndex = ComponentIndex,
  262. // type+func so Inventory.RpcUse != Equipment.RpcUse
  263. functionHash = (ushort)functionFullName.GetStableHashCode(),
  264. // segment to avoid reader allocations
  265. payload = writer.ToArraySegment()
  266. };
  267. NetworkServer.SendToReadyObservers(netIdentity, message, includeOwner, channelId);
  268. }
  269. // pass full function name to avoid ClassA.Func <-> ClassB.Func collisions
  270. protected void SendTargetRPCInternal(NetworkConnection conn, string functionFullName, NetworkWriter writer, int channelId)
  271. {
  272. if (!NetworkServer.active)
  273. {
  274. Debug.LogError($"TargetRPC {functionFullName} was called on {name} when server not active.", gameObject);
  275. return;
  276. }
  277. if (!isServer)
  278. {
  279. Debug.LogWarning($"TargetRpc {functionFullName} called on {name} but that object has not been spawned or has been unspawned.", gameObject);
  280. return;
  281. }
  282. // connection parameter is optional. assign if null.
  283. if (conn is null)
  284. {
  285. conn = connectionToClient;
  286. }
  287. // if still null
  288. if (conn is null)
  289. {
  290. Debug.LogError($"TargetRPC {functionFullName} can't be sent because it was given a null connection. Make sure {name} is owned by a connection, or if you pass a connection manually then make sure it's not null. For example, TargetRpcs can be called on Player/Pet which are owned by a connection. However, they can not be called on Monsters/Npcs which don't have an owner connection.", gameObject);
  291. return;
  292. }
  293. // TODO change conn type to NetworkConnectionToClient to begin with.
  294. if (!(conn is NetworkConnectionToClient))
  295. {
  296. Debug.LogError($"TargetRPC {functionFullName} called on {name} requires a NetworkConnectionToClient but was given {conn.GetType().Name}", gameObject);
  297. return;
  298. }
  299. // construct the message
  300. RpcMessage message = new RpcMessage
  301. {
  302. netId = netId,
  303. componentIndex = ComponentIndex,
  304. // type+func so Inventory.RpcUse != Equipment.RpcUse
  305. functionHash = (ushort)functionFullName.GetStableHashCode(),
  306. // segment to avoid reader allocations
  307. payload = writer.ToArraySegment()
  308. };
  309. conn.Send(message, channelId);
  310. }
  311. // move the [SyncVar] generated property's .set into C# to avoid much IL
  312. //
  313. // public int health = 42;
  314. //
  315. // public int Networkhealth
  316. // {
  317. // get
  318. // {
  319. // return health;
  320. // }
  321. // [param: In]
  322. // set
  323. // {
  324. // if (!NetworkBehaviour.SyncVarEqual(value, ref health))
  325. // {
  326. // int oldValue = health;
  327. // SetSyncVar(value, ref health, 1uL);
  328. // if (NetworkServer.localClientActive && !GetSyncVarHookGuard(1uL))
  329. // {
  330. // SetSyncVarHookGuard(1uL, value: true);
  331. // OnChanged(oldValue, value);
  332. // SetSyncVarHookGuard(1uL, value: false);
  333. // }
  334. // }
  335. // }
  336. // }
  337. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  338. public void GeneratedSyncVarSetter<T>(T value, ref T field, ulong dirtyBit, Action<T, T> OnChanged)
  339. {
  340. if (!SyncVarEqual(value, ref field))
  341. {
  342. T oldValue = field;
  343. SetSyncVar(value, ref field, dirtyBit);
  344. // call hook (if any)
  345. if (OnChanged != null)
  346. {
  347. // in host mode, setting a SyncVar calls the hook directly.
  348. // in client-only mode, OnDeserialize would call it.
  349. // we use hook guard to protect against deadlock where hook
  350. // changes syncvar, calling hook again.
  351. if (NetworkServer.localClientActive && !GetSyncVarHookGuard(dirtyBit))
  352. {
  353. SetSyncVarHookGuard(dirtyBit, true);
  354. OnChanged(oldValue, value);
  355. SetSyncVarHookGuard(dirtyBit, false);
  356. }
  357. }
  358. }
  359. }
  360. // GameObject needs custom handling for persistence via netId.
  361. // has one extra parameter.
  362. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  363. public void GeneratedSyncVarSetter_GameObject(GameObject value, ref GameObject field, ulong dirtyBit, Action<GameObject, GameObject> OnChanged, ref uint netIdField)
  364. {
  365. if (!SyncVarGameObjectEqual(value, netIdField))
  366. {
  367. GameObject oldValue = field;
  368. SetSyncVarGameObject(value, ref field, dirtyBit, ref netIdField);
  369. // call hook (if any)
  370. if (OnChanged != null)
  371. {
  372. // in host mode, setting a SyncVar calls the hook directly.
  373. // in client-only mode, OnDeserialize would call it.
  374. // we use hook guard to protect against deadlock where hook
  375. // changes syncvar, calling hook again.
  376. if (NetworkServer.localClientActive && !GetSyncVarHookGuard(dirtyBit))
  377. {
  378. SetSyncVarHookGuard(dirtyBit, true);
  379. OnChanged(oldValue, value);
  380. SetSyncVarHookGuard(dirtyBit, false);
  381. }
  382. }
  383. }
  384. }
  385. // NetworkIdentity needs custom handling for persistence via netId.
  386. // has one extra parameter.
  387. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  388. public void GeneratedSyncVarSetter_NetworkIdentity(NetworkIdentity value, ref NetworkIdentity field, ulong dirtyBit, Action<NetworkIdentity, NetworkIdentity> OnChanged, ref uint netIdField)
  389. {
  390. if (!SyncVarNetworkIdentityEqual(value, netIdField))
  391. {
  392. NetworkIdentity oldValue = field;
  393. SetSyncVarNetworkIdentity(value, ref field, dirtyBit, ref netIdField);
  394. // call hook (if any)
  395. if (OnChanged != null)
  396. {
  397. // in host mode, setting a SyncVar calls the hook directly.
  398. // in client-only mode, OnDeserialize would call it.
  399. // we use hook guard to protect against deadlock where hook
  400. // changes syncvar, calling hook again.
  401. if (NetworkServer.localClientActive && !GetSyncVarHookGuard(dirtyBit))
  402. {
  403. SetSyncVarHookGuard(dirtyBit, true);
  404. OnChanged(oldValue, value);
  405. SetSyncVarHookGuard(dirtyBit, false);
  406. }
  407. }
  408. }
  409. }
  410. // NetworkBehaviour needs custom handling for persistence via netId.
  411. // has one extra parameter.
  412. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  413. public void GeneratedSyncVarSetter_NetworkBehaviour<T>(T value, ref T field, ulong dirtyBit, Action<T, T> OnChanged, ref NetworkBehaviourSyncVar netIdField)
  414. where T : NetworkBehaviour
  415. {
  416. if (!SyncVarNetworkBehaviourEqual(value, netIdField))
  417. {
  418. T oldValue = field;
  419. SetSyncVarNetworkBehaviour(value, ref field, dirtyBit, ref netIdField);
  420. // call hook (if any)
  421. if (OnChanged != null)
  422. {
  423. // in host mode, setting a SyncVar calls the hook directly.
  424. // in client-only mode, OnDeserialize would call it.
  425. // we use hook guard to protect against deadlock where hook
  426. // changes syncvar, calling hook again.
  427. if (NetworkServer.localClientActive && !GetSyncVarHookGuard(dirtyBit))
  428. {
  429. SetSyncVarHookGuard(dirtyBit, true);
  430. OnChanged(oldValue, value);
  431. SetSyncVarHookGuard(dirtyBit, false);
  432. }
  433. }
  434. }
  435. }
  436. // helper function for [SyncVar] GameObjects.
  437. // needs to be public so that tests & NetworkBehaviours from other
  438. // assemblies both find it
  439. [EditorBrowsable(EditorBrowsableState.Never)]
  440. public static bool SyncVarGameObjectEqual(GameObject newGameObject, uint netIdField)
  441. {
  442. uint newNetId = 0;
  443. if (newGameObject != null)
  444. {
  445. NetworkIdentity identity = newGameObject.GetComponent<NetworkIdentity>();
  446. if (identity != null)
  447. {
  448. newNetId = identity.netId;
  449. if (newNetId == 0)
  450. {
  451. Debug.LogWarning($"SetSyncVarGameObject GameObject {newGameObject} has a zero netId. Maybe it is not spawned yet?");
  452. }
  453. }
  454. }
  455. return newNetId == netIdField;
  456. }
  457. // helper function for [SyncVar] GameObjects.
  458. // dirtyBit is a mask like 00010
  459. protected void SetSyncVarGameObject(GameObject newGameObject, ref GameObject gameObjectField, ulong dirtyBit, ref uint netIdField)
  460. {
  461. if (GetSyncVarHookGuard(dirtyBit))
  462. return;
  463. uint newNetId = 0;
  464. if (newGameObject != null)
  465. {
  466. NetworkIdentity identity = newGameObject.GetComponent<NetworkIdentity>();
  467. if (identity != null)
  468. {
  469. newNetId = identity.netId;
  470. if (newNetId == 0)
  471. {
  472. Debug.LogWarning($"SetSyncVarGameObject GameObject {newGameObject} has a zero netId. Maybe it is not spawned yet?");
  473. }
  474. }
  475. }
  476. //Debug.Log($"SetSyncVar GameObject {GetType().Name} bit:{dirtyBit} netfieldId:{netIdField} -> {newNetId}");
  477. SetSyncVarDirtyBit(dirtyBit);
  478. // assign new one on the server, and in case we ever need it on client too
  479. gameObjectField = newGameObject;
  480. netIdField = newNetId;
  481. }
  482. // helper function for [SyncVar] GameObjects.
  483. // -> ref GameObject as second argument makes OnDeserialize processing easier
  484. protected GameObject GetSyncVarGameObject(uint netId, ref GameObject gameObjectField)
  485. {
  486. // server always uses the field
  487. if (isServer)
  488. {
  489. return gameObjectField;
  490. }
  491. // client always looks up based on netId because objects might get in and out of range
  492. // over and over again, which shouldn't null them forever
  493. if (NetworkClient.spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null)
  494. return gameObjectField = identity.gameObject;
  495. return null;
  496. }
  497. // helper function for [SyncVar] NetworkIdentities.
  498. // needs to be public so that tests & NetworkBehaviours from other
  499. // assemblies both find it
  500. [EditorBrowsable(EditorBrowsableState.Never)]
  501. public static bool SyncVarNetworkIdentityEqual(NetworkIdentity newIdentity, uint netIdField)
  502. {
  503. uint newNetId = 0;
  504. if (newIdentity != null)
  505. {
  506. newNetId = newIdentity.netId;
  507. if (newNetId == 0)
  508. {
  509. Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newIdentity} has a zero netId. Maybe it is not spawned yet?");
  510. }
  511. }
  512. // netId changed?
  513. return newNetId == netIdField;
  514. }
  515. // move the [SyncVar] generated OnDeserialize C# to avoid much IL.
  516. //
  517. // before:
  518. // public override void DeserializeSyncVars(NetworkReader reader, bool initialState)
  519. // {
  520. // base.DeserializeSyncVars(reader, initialState);
  521. // if (initialState)
  522. // {
  523. // int num = health;
  524. // Networkhealth = reader.ReadInt();
  525. // if (!NetworkBehaviour.SyncVarEqual(num, ref health))
  526. // {
  527. // OnChanged(num, health);
  528. // }
  529. // return;
  530. // }
  531. // long num2 = (long)reader.ReadULong();
  532. // if ((num2 & 1L) != 0L)
  533. // {
  534. // int num3 = health;
  535. // Networkhealth = reader.ReadInt();
  536. // if (!NetworkBehaviour.SyncVarEqual(num3, ref health))
  537. // {
  538. // OnChanged(num3, health);
  539. // }
  540. // }
  541. // }
  542. //
  543. // after:
  544. //
  545. // public override void DeserializeSyncVars(NetworkReader reader, bool initialState)
  546. // {
  547. // base.DeserializeSyncVars(reader, initialState);
  548. // if (initialState)
  549. // {
  550. // GeneratedSyncVarDeserialize(reader, ref health, null, reader.ReadInt());
  551. // return;
  552. // }
  553. // long num = (long)reader.ReadULong();
  554. // if ((num & 1L) != 0L)
  555. // {
  556. // GeneratedSyncVarDeserialize(reader, ref health, null, reader.ReadInt());
  557. // }
  558. // }
  559. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  560. public void GeneratedSyncVarDeserialize<T>(ref T field, Action<T, T> OnChanged, T value)
  561. {
  562. T previous = field;
  563. field = value;
  564. // any hook? then call if changed.
  565. if (OnChanged != null && !SyncVarEqual(previous, ref field))
  566. {
  567. OnChanged(previous, field);
  568. }
  569. }
  570. // move the [SyncVar] generated OnDeserialize C# to avoid much IL.
  571. //
  572. // before:
  573. // public override void DeserializeSyncVars(NetworkReader reader, bool initialState)
  574. // {
  575. // base.DeserializeSyncVars(reader, initialState);
  576. // if (initialState)
  577. // {
  578. // uint __targetNetId = ___targetNetId;
  579. // GameObject networktarget = Networktarget;
  580. // ___targetNetId = reader.ReadUInt();
  581. // if (!NetworkBehaviour.SyncVarEqual(__targetNetId, ref ___targetNetId))
  582. // {
  583. // OnChangedNB(networktarget, Networktarget);
  584. // }
  585. // return;
  586. // }
  587. // long num = (long)reader.ReadULong();
  588. // if ((num & 1L) != 0L)
  589. // {
  590. // uint __targetNetId2 = ___targetNetId;
  591. // GameObject networktarget2 = Networktarget;
  592. // ___targetNetId = reader.ReadUInt();
  593. // if (!NetworkBehaviour.SyncVarEqual(__targetNetId2, ref ___targetNetId))
  594. // {
  595. // OnChangedNB(networktarget2, Networktarget);
  596. // }
  597. // }
  598. // }
  599. //
  600. // after:
  601. // public override void DeserializeSyncVars(NetworkReader reader, bool initialState)
  602. // {
  603. // base.DeserializeSyncVars(reader, initialState);
  604. // if (initialState)
  605. // {
  606. // GeneratedSyncVarDeserialize_GameObject(reader, ref target, OnChangedNB, ref ___targetNetId);
  607. // return;
  608. // }
  609. // long num = (long)reader.ReadULong();
  610. // if ((num & 1L) != 0L)
  611. // {
  612. // GeneratedSyncVarDeserialize_GameObject(reader, ref target, OnChangedNB, ref ___targetNetId);
  613. // }
  614. // }
  615. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  616. public void GeneratedSyncVarDeserialize_GameObject(ref GameObject field, Action<GameObject, GameObject> OnChanged, NetworkReader reader, ref uint netIdField)
  617. {
  618. uint previousNetId = netIdField;
  619. GameObject previousGameObject = field;
  620. netIdField = reader.ReadUInt();
  621. // get the new GameObject now that netId field is set
  622. field = GetSyncVarGameObject(netIdField, ref field);
  623. // any hook? then call if changed.
  624. if (OnChanged != null && !SyncVarEqual(previousNetId, ref netIdField))
  625. {
  626. OnChanged(previousGameObject, field);
  627. }
  628. }
  629. // move the [SyncVar] generated OnDeserialize C# to avoid much IL.
  630. //
  631. // before:
  632. // public override void DeserializeSyncVars(NetworkReader reader, bool initialState)
  633. // {
  634. // base.DeserializeSyncVars(reader, initialState);
  635. // if (initialState)
  636. // {
  637. // uint __targetNetId = ___targetNetId;
  638. // NetworkIdentity networktarget = Networktarget;
  639. // ___targetNetId = reader.ReadUInt();
  640. // if (!NetworkBehaviour.SyncVarEqual(__targetNetId, ref ___targetNetId))
  641. // {
  642. // OnChangedNI(networktarget, Networktarget);
  643. // }
  644. // return;
  645. // }
  646. // long num = (long)reader.ReadULong();
  647. // if ((num & 1L) != 0L)
  648. // {
  649. // uint __targetNetId2 = ___targetNetId;
  650. // NetworkIdentity networktarget2 = Networktarget;
  651. // ___targetNetId = reader.ReadUInt();
  652. // if (!NetworkBehaviour.SyncVarEqual(__targetNetId2, ref ___targetNetId))
  653. // {
  654. // OnChangedNI(networktarget2, Networktarget);
  655. // }
  656. // }
  657. // }
  658. //
  659. // after:
  660. //
  661. // public override void DeserializeSyncVars(NetworkReader reader, bool initialState)
  662. // {
  663. // base.DeserializeSyncVars(reader, initialState);
  664. // if (initialState)
  665. // {
  666. // GeneratedSyncVarDeserialize_NetworkIdentity(reader, ref target, OnChangedNI, ref ___targetNetId);
  667. // return;
  668. // }
  669. // long num = (long)reader.ReadULong();
  670. // if ((num & 1L) != 0L)
  671. // {
  672. // GeneratedSyncVarDeserialize_NetworkIdentity(reader, ref target, OnChangedNI, ref ___targetNetId);
  673. // }
  674. // }
  675. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  676. public void GeneratedSyncVarDeserialize_NetworkIdentity(ref NetworkIdentity field, Action<NetworkIdentity, NetworkIdentity> OnChanged, NetworkReader reader, ref uint netIdField)
  677. {
  678. uint previousNetId = netIdField;
  679. NetworkIdentity previousIdentity = field;
  680. netIdField = reader.ReadUInt();
  681. // get the new NetworkIdentity now that netId field is set
  682. field = GetSyncVarNetworkIdentity(netIdField, ref field);
  683. // any hook? then call if changed.
  684. if (OnChanged != null && !SyncVarEqual(previousNetId, ref netIdField))
  685. {
  686. OnChanged(previousIdentity, field);
  687. }
  688. }
  689. // move the [SyncVar] generated OnDeserialize C# to avoid much IL.
  690. //
  691. // before:
  692. //
  693. // public override void DeserializeSyncVars(NetworkReader reader, bool initialState)
  694. // {
  695. // base.DeserializeSyncVars(reader, initialState);
  696. // if (initialState)
  697. // {
  698. // NetworkBehaviourSyncVar __targetNetId = ___targetNetId;
  699. // Tank networktarget = Networktarget;
  700. // ___targetNetId = reader.ReadNetworkBehaviourSyncVar();
  701. // if (!NetworkBehaviour.SyncVarEqual(__targetNetId, ref ___targetNetId))
  702. // {
  703. // OnChangedNB(networktarget, Networktarget);
  704. // }
  705. // return;
  706. // }
  707. // long num = (long)reader.ReadULong();
  708. // if ((num & 1L) != 0L)
  709. // {
  710. // NetworkBehaviourSyncVar __targetNetId2 = ___targetNetId;
  711. // Tank networktarget2 = Networktarget;
  712. // ___targetNetId = reader.ReadNetworkBehaviourSyncVar();
  713. // if (!NetworkBehaviour.SyncVarEqual(__targetNetId2, ref ___targetNetId))
  714. // {
  715. // OnChangedNB(networktarget2, Networktarget);
  716. // }
  717. // }
  718. // }
  719. //
  720. // after:
  721. //
  722. // public override void DeserializeSyncVars(NetworkReader reader, bool initialState)
  723. // {
  724. // base.DeserializeSyncVars(reader, initialState);
  725. // if (initialState)
  726. // {
  727. // GeneratedSyncVarDeserialize_NetworkBehaviour(reader, ref target, OnChangedNB, ref ___targetNetId);
  728. // return;
  729. // }
  730. // long num = (long)reader.ReadULong();
  731. // if ((num & 1L) != 0L)
  732. // {
  733. // GeneratedSyncVarDeserialize_NetworkBehaviour(reader, ref target, OnChangedNB, ref ___targetNetId);
  734. // }
  735. // }
  736. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  737. public void GeneratedSyncVarDeserialize_NetworkBehaviour<T>(ref T field, Action<T, T> OnChanged, NetworkReader reader, ref NetworkBehaviourSyncVar netIdField)
  738. where T : NetworkBehaviour
  739. {
  740. NetworkBehaviourSyncVar previousNetId = netIdField;
  741. T previousBehaviour = field;
  742. netIdField = reader.ReadNetworkBehaviourSyncVar();
  743. // get the new NetworkBehaviour now that netId field is set
  744. field = GetSyncVarNetworkBehaviour(netIdField, ref field);
  745. // any hook? then call if changed.
  746. if (OnChanged != null && !SyncVarEqual(previousNetId, ref netIdField))
  747. {
  748. OnChanged(previousBehaviour, field);
  749. }
  750. }
  751. // helper function for [SyncVar] NetworkIdentities.
  752. // dirtyBit is a mask like 00010
  753. protected void SetSyncVarNetworkIdentity(NetworkIdentity newIdentity, ref NetworkIdentity identityField, ulong dirtyBit, ref uint netIdField)
  754. {
  755. if (GetSyncVarHookGuard(dirtyBit))
  756. return;
  757. uint newNetId = 0;
  758. if (newIdentity != null)
  759. {
  760. newNetId = newIdentity.netId;
  761. if (newNetId == 0)
  762. {
  763. Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newIdentity} has a zero netId. Maybe it is not spawned yet?");
  764. }
  765. }
  766. //Debug.Log($"SetSyncVarNetworkIdentity NetworkIdentity {GetType().Name} bit:{dirtyBit} netIdField:{netIdField} -> {newNetId}");
  767. SetSyncVarDirtyBit(dirtyBit);
  768. netIdField = newNetId;
  769. // assign new one on the server, and in case we ever need it on client too
  770. identityField = newIdentity;
  771. }
  772. // helper function for [SyncVar] NetworkIdentities.
  773. // -> ref GameObject as second argument makes OnDeserialize processing easier
  774. protected NetworkIdentity GetSyncVarNetworkIdentity(uint netId, ref NetworkIdentity identityField)
  775. {
  776. // server always uses the field
  777. if (isServer)
  778. {
  779. return identityField;
  780. }
  781. // client always looks up based on netId because objects might get in and out of range
  782. // over and over again, which shouldn't null them forever
  783. NetworkClient.spawned.TryGetValue(netId, out identityField);
  784. return identityField;
  785. }
  786. protected static bool SyncVarNetworkBehaviourEqual<T>(T newBehaviour, NetworkBehaviourSyncVar syncField) where T : NetworkBehaviour
  787. {
  788. uint newNetId = 0;
  789. byte newComponentIndex = 0;
  790. if (newBehaviour != null)
  791. {
  792. newNetId = newBehaviour.netId;
  793. newComponentIndex = newBehaviour.ComponentIndex;
  794. if (newNetId == 0)
  795. {
  796. Debug.LogWarning($"SetSyncVarNetworkIdentity NetworkIdentity {newBehaviour} has a zero netId. Maybe it is not spawned yet?");
  797. }
  798. }
  799. // netId changed?
  800. return syncField.Equals(newNetId, newComponentIndex);
  801. }
  802. // helper function for [SyncVar] NetworkIdentities.
  803. // dirtyBit is a mask like 00010
  804. protected void SetSyncVarNetworkBehaviour<T>(T newBehaviour, ref T behaviourField, ulong dirtyBit, ref NetworkBehaviourSyncVar syncField) where T : NetworkBehaviour
  805. {
  806. if (GetSyncVarHookGuard(dirtyBit))
  807. return;
  808. uint newNetId = 0;
  809. byte componentIndex = 0;
  810. if (newBehaviour != null)
  811. {
  812. newNetId = newBehaviour.netId;
  813. componentIndex = newBehaviour.ComponentIndex;
  814. if (newNetId == 0)
  815. {
  816. Debug.LogWarning($"{nameof(SetSyncVarNetworkBehaviour)} NetworkIdentity {newBehaviour} has a zero netId. Maybe it is not spawned yet?");
  817. }
  818. }
  819. syncField = new NetworkBehaviourSyncVar(newNetId, componentIndex);
  820. SetSyncVarDirtyBit(dirtyBit);
  821. // assign new one on the server, and in case we ever need it on client too
  822. behaviourField = newBehaviour;
  823. // Debug.Log($"SetSyncVarNetworkBehaviour NetworkIdentity {GetType().Name} bit [{dirtyBit}] netIdField:{oldField}->{syncField}");
  824. }
  825. // helper function for [SyncVar] NetworkIdentities.
  826. // -> ref GameObject as second argument makes OnDeserialize processing easier
  827. protected T GetSyncVarNetworkBehaviour<T>(NetworkBehaviourSyncVar syncNetBehaviour, ref T behaviourField) where T : NetworkBehaviour
  828. {
  829. // server always uses the field
  830. if (isServer)
  831. {
  832. return behaviourField;
  833. }
  834. // client always looks up based on netId because objects might get in and out of range
  835. // over and over again, which shouldn't null them forever
  836. if (!NetworkClient.spawned.TryGetValue(syncNetBehaviour.netId, out NetworkIdentity identity))
  837. {
  838. return null;
  839. }
  840. behaviourField = identity.NetworkBehaviours[syncNetBehaviour.componentIndex] as T;
  841. return behaviourField;
  842. }
  843. protected static bool SyncVarEqual<T>(T value, ref T fieldValue)
  844. {
  845. // newly initialized or changed value?
  846. // value.Equals(fieldValue) allocates without 'where T : IEquatable'
  847. // seems like we use EqualityComparer to avoid allocations,
  848. // because not all SyncVars<T> are IEquatable
  849. return EqualityComparer<T>.Default.Equals(value, fieldValue);
  850. }
  851. // dirtyBit is a mask like 00010
  852. protected void SetSyncVar<T>(T value, ref T fieldValue, ulong dirtyBit)
  853. {
  854. //Debug.Log($"SetSyncVar {GetType().Name} bit:{dirtyBit} fieldValue:{value}");
  855. SetSyncVarDirtyBit(dirtyBit);
  856. fieldValue = value;
  857. }
  858. /// <summary>Override to do custom serialization (instead of SyncVars/SyncLists). Use OnDeserialize too.</summary>
  859. // if a class has syncvars, then OnSerialize/OnDeserialize are added
  860. // automatically.
  861. //
  862. // initialState is true for full spawns, false for delta syncs.
  863. // note: SyncVar hooks are only called when inital=false
  864. public virtual void OnSerialize(NetworkWriter writer, bool initialState)
  865. {
  866. // if initialState: write all SyncVars.
  867. // otherwise write dirtyBits+dirty SyncVars
  868. if (initialState)
  869. SerializeObjectsAll(writer);
  870. else
  871. SerializeObjectsDelta(writer);
  872. SerializeSyncVars(writer, initialState);
  873. }
  874. /// <summary>Override to do custom deserialization (instead of SyncVars/SyncLists). Use OnSerialize too.</summary>
  875. public virtual void OnDeserialize(NetworkReader reader, bool initialState)
  876. {
  877. if (initialState)
  878. {
  879. DeserializeObjectsAll(reader);
  880. }
  881. else
  882. {
  883. DeserializeObjectsDelta(reader);
  884. }
  885. DeserializeSyncVars(reader, initialState);
  886. }
  887. // USED BY WEAVER
  888. protected virtual void SerializeSyncVars(NetworkWriter writer, bool initialState)
  889. {
  890. // SyncVar are written here in subclass
  891. // if initialState
  892. // write all SyncVars
  893. // else
  894. // write syncVarDirtyBits
  895. // write dirty SyncVars
  896. }
  897. // USED BY WEAVER
  898. protected virtual void DeserializeSyncVars(NetworkReader reader, bool initialState)
  899. {
  900. // SyncVars are read here in subclass
  901. // if initialState
  902. // read all SyncVars
  903. // else
  904. // read syncVarDirtyBits
  905. // read dirty SyncVars
  906. }
  907. public void SerializeObjectsAll(NetworkWriter writer)
  908. {
  909. for (int i = 0; i < syncObjects.Count; i++)
  910. {
  911. SyncObject syncObject = syncObjects[i];
  912. syncObject.OnSerializeAll(writer);
  913. }
  914. }
  915. public void SerializeObjectsDelta(NetworkWriter writer)
  916. {
  917. // write the mask
  918. writer.WriteULong(syncObjectDirtyBits);
  919. // serializable objects, such as synclists
  920. for (int i = 0; i < syncObjects.Count; i++)
  921. {
  922. // check dirty mask at nth bit
  923. SyncObject syncObject = syncObjects[i];
  924. if ((syncObjectDirtyBits & (1UL << i)) != 0)
  925. {
  926. syncObject.OnSerializeDelta(writer);
  927. }
  928. }
  929. }
  930. internal void DeserializeObjectsAll(NetworkReader reader)
  931. {
  932. for (int i = 0; i < syncObjects.Count; i++)
  933. {
  934. SyncObject syncObject = syncObjects[i];
  935. syncObject.OnDeserializeAll(reader);
  936. }
  937. }
  938. internal void DeserializeObjectsDelta(NetworkReader reader)
  939. {
  940. ulong dirty = reader.ReadULong();
  941. for (int i = 0; i < syncObjects.Count; i++)
  942. {
  943. // check dirty mask at nth bit
  944. SyncObject syncObject = syncObjects[i];
  945. if ((dirty & (1UL << i)) != 0)
  946. {
  947. syncObject.OnDeserializeDelta(reader);
  948. }
  949. }
  950. }
  951. // safely serialize each component in a way that one reading too much or
  952. // too few bytes will show obvious, easy to resolve error messages.
  953. //
  954. // prevents the original UNET bug which started Mirror:
  955. // https://github.com/vis2k/Mirror/issues/2617
  956. // where one component would read too much, and then all following reads
  957. // on other entities would be mismatched, causing the weirdest errors.
  958. //
  959. // reads <<len, payload, len, payload, ...>> for 100% safety.
  960. internal void Serialize(NetworkWriter writer, bool initialState)
  961. {
  962. // reserve length header to ensure the correct amount will be read.
  963. // originally we used a 4 byte header (too bandwidth heavy).
  964. // instead, let's "& 0xFF" the size.
  965. //
  966. // this is cleaner than barriers at the end of payload, because:
  967. // - ensures the correct safety is read _before_ payload.
  968. // - it's quite hard to break the check.
  969. // a component would need to read/write the intented amount
  970. // multiplied by 255 in order to miss the check.
  971. // with barriers, reading 1 byte too much may still succeed if the
  972. // next component's first byte matches the expected barrier.
  973. // - we can still attempt to correct the invalid position via the
  974. // safety length byte (we know that one is correct).
  975. //
  976. // it's just overall cleaner, and still low on bandwidth.
  977. // write placeholder length byte
  978. // (jumping back later is WAY faster than allocating a temporary
  979. // writer for the payload, then writing payload.size, payload)
  980. int headerPosition = writer.Position;
  981. writer.WriteByte(0);
  982. int contentPosition = writer.Position;
  983. // write payload
  984. try
  985. {
  986. // note this may not write anything if no syncIntervals elapsed
  987. OnSerialize(writer, initialState);
  988. }
  989. catch (Exception e)
  990. {
  991. // show a detailed error and let the user know what went wrong
  992. Debug.LogError($"OnSerialize failed for: object={name} component={GetType()} sceneId={netIdentity.sceneId:X}\n\n{e}");
  993. }
  994. int endPosition = writer.Position;
  995. // fill in length hash as the last byte of the 4 byte length
  996. writer.Position = headerPosition;
  997. int size = endPosition - contentPosition;
  998. byte safety = (byte)(size & 0xFF);
  999. writer.WriteByte(safety);
  1000. writer.Position = endPosition;
  1001. //Debug.Log($"OnSerializeSafely written for object {name} component:{GetType()} sceneId:{sceneId:X} header:{headerPosition} content:{contentPosition} end:{endPosition} contentSize:{endPosition - contentPosition}");
  1002. }
  1003. // correct the read size with the 1 byte length hash (by mischa).
  1004. // -> the component most likely read a few too many/few bytes.
  1005. // -> we know the correct last byte of the expected size (=the safety).
  1006. // -> attempt to reconstruct the size via safety byte.
  1007. // it will be correct unless someone wrote way way too much,
  1008. // as in > 255 bytes worth too much.
  1009. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1010. internal static int ErrorCorrection(int size, byte safety)
  1011. {
  1012. // clear the last byte which most likely contains the error
  1013. uint cleared = (uint)size & 0xFFFFFF00;
  1014. // insert the safety which we know to be correct
  1015. return (int)(cleared | safety);
  1016. }
  1017. // returns false in case of errors.
  1018. // server needs to know in order to disconnect on error.
  1019. internal bool Deserialize(NetworkReader reader, bool initialState)
  1020. {
  1021. // detect errors, but attempt to correct before returning
  1022. bool result = true;
  1023. // read 1 byte length hash safety & capture beginning for size check
  1024. byte safety = reader.ReadByte();
  1025. int chunkStart = reader.Position;
  1026. // call OnDeserialize and wrap it in a try-catch block so there's no
  1027. // way to mess up another component's deserialization
  1028. try
  1029. {
  1030. //Debug.Log($"OnDeserializeSafely: {name} component:{GetType()} sceneId:{sceneId:X} length:{contentSize}");
  1031. OnDeserialize(reader, initialState);
  1032. }
  1033. catch (Exception e)
  1034. {
  1035. // show a detailed error and let the user know what went wrong
  1036. Debug.LogError($"OnDeserialize failed Exception={e.GetType()} (see below) object={name} component={GetType()} netId={netId}. Possible Reasons:\n" +
  1037. $" * Do {GetType()}'s OnSerialize and OnDeserialize calls write the same amount of data? \n" +
  1038. $" * Was there an exception in {GetType()}'s OnSerialize/OnDeserialize code?\n" +
  1039. $" * Are the server and client the exact same project?\n" +
  1040. $" * Maybe this OnDeserialize call was meant for another GameObject? The sceneIds can easily get out of sync if the Hierarchy was modified only in the client OR the server. Try rebuilding both.\n\n" +
  1041. $"Exception {e}");
  1042. result = false;
  1043. }
  1044. // compare bytes read with length hash
  1045. int size = reader.Position - chunkStart;
  1046. byte sizeHash = (byte)(size & 0xFF);
  1047. if (sizeHash != safety)
  1048. {
  1049. // warn the user.
  1050. Debug.LogWarning($"{name} (netId={netId}): {GetType()} OnDeserialize size mismatch. It read {size} bytes, which caused a size hash mismatch of {sizeHash:X2} vs. {safety:X2}. Make sure that OnSerialize and OnDeserialize write/read the same amount of data in all cases.");
  1051. // attempt to fix the position, so the following components
  1052. // don't all fail. this is very likely to work, unless the user
  1053. // read more than 255 bytes too many / too few.
  1054. //
  1055. // see test: SerializationSizeMismatch.
  1056. int correctedSize = ErrorCorrection(size, safety);
  1057. reader.Position = chunkStart + correctedSize;
  1058. result = false;
  1059. }
  1060. return result;
  1061. }
  1062. internal void ResetSyncObjects()
  1063. {
  1064. foreach (SyncObject syncObject in syncObjects)
  1065. {
  1066. syncObject.Reset();
  1067. }
  1068. }
  1069. /// <summary>Like Start(), but only called on server and host.</summary>
  1070. public virtual void OnStartServer() {}
  1071. /// <summary>Stop event, only called on server and host.</summary>
  1072. public virtual void OnStopServer() {}
  1073. /// <summary>Like Start(), but only called on client and host.</summary>
  1074. public virtual void OnStartClient() {}
  1075. /// <summary>Stop event, only called on client and host.</summary>
  1076. public virtual void OnStopClient() {}
  1077. /// <summary>Like Start(), but only called on client and host for the local player object.</summary>
  1078. public virtual void OnStartLocalPlayer() {}
  1079. /// <summary>Stop event, but only called on client and host for the local player object.</summary>
  1080. public virtual void OnStopLocalPlayer() {}
  1081. /// <summary>Like Start(), but only called for objects the client has authority over.</summary>
  1082. public virtual void OnStartAuthority() {}
  1083. /// <summary>Stop event, only called for objects the client has authority over.</summary>
  1084. public virtual void OnStopAuthority() {}
  1085. }
  1086. }