NetworkServer.cs 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Mirror.RemoteCalls;
  5. using UnityEngine;
  6. namespace Mirror
  7. {
  8. /// <summary>NetworkServer handles remote connections and has a local connection for a local client.</summary>
  9. public static class NetworkServer
  10. {
  11. static bool initialized;
  12. public static int maxConnections;
  13. /// <summary>Connection to host mode client (if any)</summary>
  14. public static NetworkConnectionToClient localConnection { get; private set; }
  15. /// <summary>True is a local client is currently active on the server</summary>
  16. public static bool localClientActive => localConnection != null;
  17. /// <summary>Dictionary of all server connections, with connectionId as key</summary>
  18. public static Dictionary<int, NetworkConnectionToClient> connections =
  19. new Dictionary<int, NetworkConnectionToClient>();
  20. /// <summary>Message Handlers dictionary, with mesageId as key</summary>
  21. internal static Dictionary<ushort, NetworkMessageDelegate> handlers =
  22. new Dictionary<ushort, NetworkMessageDelegate>();
  23. /// <summary>All spawned NetworkIdentities by netId.</summary>
  24. // server sees ALL spawned ones.
  25. public static readonly Dictionary<uint, NetworkIdentity> spawned =
  26. new Dictionary<uint, NetworkIdentity>();
  27. /// <summary>Single player mode can use dontListen to not accept incoming connections</summary>
  28. // see also: https://github.com/vis2k/Mirror/pull/2595
  29. public static bool dontListen;
  30. /// <summary>active checks if the server has been started</summary>
  31. public static bool active { get; internal set; }
  32. // scene loading
  33. public static bool isLoadingScene;
  34. // interest management component (optional)
  35. // by default, everyone observes everyone
  36. public static InterestManagement aoi;
  37. // OnConnected / OnDisconnected used to be NetworkMessages that were
  38. // invoked. this introduced a bug where external clients could send
  39. // Connected/Disconnected messages over the network causing undefined
  40. // behaviour.
  41. // => public so that custom NetworkManagers can hook into it
  42. public static Action<NetworkConnection> OnConnectedEvent;
  43. public static Action<NetworkConnection> OnDisconnectedEvent;
  44. public static Action<NetworkConnection, Exception> OnErrorEvent;
  45. // initialization / shutdown ///////////////////////////////////////////
  46. static void Initialize()
  47. {
  48. if (initialized)
  49. return;
  50. initialized = true;
  51. // Debug.Log($"NetworkServer Created version {Version.Current}");
  52. //Make sure connections are cleared in case any old connections references exist from previous sessions
  53. connections.Clear();
  54. // reset NetworkTime
  55. NetworkTime.Reset();
  56. Debug.Assert(Transport.activeTransport != null, "There was no active transport when calling NetworkServer.Listen, If you are calling Listen manually then make sure to set 'Transport.activeTransport' first");
  57. AddTransportHandlers();
  58. }
  59. static void AddTransportHandlers()
  60. {
  61. Transport.activeTransport.OnServerConnected = OnTransportConnected;
  62. Transport.activeTransport.OnServerDataReceived = OnTransportData;
  63. Transport.activeTransport.OnServerDisconnected = OnTransportDisconnected;
  64. Transport.activeTransport.OnServerError = OnError;
  65. }
  66. // calls OnStartClient for all SERVER objects in host mode once.
  67. // client doesn't get spawn messages for those, so need to call manually.
  68. public static void ActivateHostScene()
  69. {
  70. foreach (NetworkIdentity identity in spawned.Values)
  71. {
  72. if (!identity.isClient)
  73. {
  74. // Debug.Log($"ActivateHostScene {identity.netId} {identity}");
  75. identity.OnStartClient();
  76. }
  77. }
  78. }
  79. internal static void RegisterMessageHandlers()
  80. {
  81. RegisterHandler<ReadyMessage>(OnClientReadyMessage);
  82. RegisterHandler<CommandMessage>(OnCommandMessage);
  83. RegisterHandler<NetworkPingMessage>(NetworkTime.OnServerPing, false);
  84. }
  85. /// <summary>Starts server and listens to incoming connections with max connections limit.</summary>
  86. public static void Listen(int maxConns)
  87. {
  88. Initialize();
  89. maxConnections = maxConns;
  90. // only start server if we want to listen
  91. if (!dontListen)
  92. {
  93. Transport.activeTransport.ServerStart();
  94. //Debug.Log("Server started listening");
  95. }
  96. active = true;
  97. RegisterMessageHandlers();
  98. }
  99. // Note: NetworkClient.DestroyAllClientObjects does the same on client.
  100. static void CleanupSpawned()
  101. {
  102. // iterate a COPY of spawned.
  103. // DestroyObject removes them from the original collection.
  104. // removing while iterating is not allowed.
  105. foreach (NetworkIdentity identity in spawned.Values.ToList())
  106. {
  107. if (identity != null)
  108. {
  109. // scene object
  110. if (identity.sceneId != 0)
  111. {
  112. // spawned scene objects are unspawned and reset.
  113. // afterwards we disable them again.
  114. // (they always stay in the scene, we don't destroy them)
  115. DestroyObject(identity, DestroyMode.Reset);
  116. identity.gameObject.SetActive(false);
  117. }
  118. // spawned prefabs
  119. else
  120. {
  121. // spawned prefabs are unspawned and destroyed.
  122. DestroyObject(identity, DestroyMode.Destroy);
  123. }
  124. }
  125. }
  126. spawned.Clear();
  127. }
  128. /// <summary>Shuts down the server and disconnects all clients</summary>
  129. public static void Shutdown()
  130. {
  131. if (initialized)
  132. {
  133. DisconnectAll();
  134. // stop the server.
  135. // we do NOT call Transport.Shutdown, because someone only
  136. // called NetworkServer.Shutdown. we can't assume that the
  137. // client is supposed to be shut down too!
  138. //
  139. // NOTE: stop no matter what, even if 'dontListen':
  140. // someone might enabled dontListen at runtime.
  141. // but we still need to stop the server.
  142. // fixes https://github.com/vis2k/Mirror/issues/2536
  143. Transport.activeTransport.ServerStop();
  144. initialized = false;
  145. }
  146. dontListen = false;
  147. active = false;
  148. handlers.Clear();
  149. CleanupSpawned();
  150. NetworkIdentity.ResetNextNetworkId();
  151. // clear events. someone might have hooked into them before, but
  152. // we don't want to use those hooks after Shutdown anymore.
  153. OnConnectedEvent = null;
  154. OnDisconnectedEvent = null;
  155. }
  156. // connections /////////////////////////////////////////////////////////
  157. /// <summary>Add a connection and setup callbacks. Returns true if not added yet.</summary>
  158. public static bool AddConnection(NetworkConnectionToClient conn)
  159. {
  160. if (!connections.ContainsKey(conn.connectionId))
  161. {
  162. // connection cannot be null here or conn.connectionId
  163. // would throw NRE
  164. connections[conn.connectionId] = conn;
  165. return true;
  166. }
  167. // already a connection with this id
  168. return false;
  169. }
  170. /// <summary>Removes a connection by connectionId. Returns true if removed.</summary>
  171. public static bool RemoveConnection(int connectionId)
  172. {
  173. return connections.Remove(connectionId);
  174. }
  175. // called by LocalClient to add itself. don't call directly.
  176. // TODO consider internal setter instead?
  177. internal static void SetLocalConnection(LocalConnectionToClient conn)
  178. {
  179. if (localConnection != null)
  180. {
  181. Debug.LogError("Local Connection already exists");
  182. return;
  183. }
  184. localConnection = conn;
  185. }
  186. // removes local connection to client
  187. internal static void RemoveLocalConnection()
  188. {
  189. if (localConnection != null)
  190. {
  191. localConnection.Disconnect();
  192. localConnection = null;
  193. }
  194. RemoveConnection(0);
  195. }
  196. /// <summary>True if we have no external connections (host is allowed)</summary>
  197. public static bool NoExternalConnections()
  198. {
  199. return connections.Count == 0 ||
  200. (connections.Count == 1 && localConnection != null);
  201. }
  202. // send ////////////////////////////////////////////////////////////////
  203. /// <summary>Send a message to all clients, even those that haven't joined the world yet (non ready)</summary>
  204. public static void SendToAll<T>(T message, int channelId = Channels.Reliable, bool sendToReadyOnly = false)
  205. where T : struct, NetworkMessage
  206. {
  207. if (!active)
  208. {
  209. Debug.LogWarning("Can not send using NetworkServer.SendToAll<T>(T msg) because NetworkServer is not active");
  210. return;
  211. }
  212. // Debug.Log($"Server.SendToAll {typeof(T)}");
  213. using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
  214. {
  215. // pack message only once
  216. MessagePacking.Pack(message, writer);
  217. ArraySegment<byte> segment = writer.ToArraySegment();
  218. // filter and then send to all internet connections at once
  219. // -> makes code more complicated, but is HIGHLY worth it to
  220. // avoid allocations, allow for multicast, etc.
  221. int count = 0;
  222. foreach (NetworkConnectionToClient conn in connections.Values)
  223. {
  224. if (sendToReadyOnly && !conn.isReady)
  225. continue;
  226. count++;
  227. conn.Send(segment, channelId);
  228. }
  229. NetworkDiagnostics.OnSend(message, channelId, segment.Count, count);
  230. }
  231. }
  232. /// <summary>Send a message to all clients which have joined the world (are ready).</summary>
  233. // TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady!
  234. public static void SendToReady<T>(T message, int channelId = Channels.Reliable)
  235. where T : struct, NetworkMessage
  236. {
  237. if (!active)
  238. {
  239. Debug.LogWarning("Can not send using NetworkServer.SendToReady<T>(T msg) because NetworkServer is not active");
  240. return;
  241. }
  242. SendToAll(message, channelId, true);
  243. }
  244. // this is like SendToReadyObservers - but it doesn't check the ready flag on the connection.
  245. // this is used for ObjectDestroy messages.
  246. static void SendToObservers<T>(NetworkIdentity identity, T message, int channelId = Channels.Reliable)
  247. where T : struct, NetworkMessage
  248. {
  249. // Debug.Log($"Server.SendToObservers {typeof(T)}");
  250. if (identity == null || identity.observers == null || identity.observers.Count == 0)
  251. return;
  252. using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
  253. {
  254. // pack message into byte[] once
  255. MessagePacking.Pack(message, writer);
  256. ArraySegment<byte> segment = writer.ToArraySegment();
  257. foreach (NetworkConnection conn in identity.observers.Values)
  258. {
  259. conn.Send(segment, channelId);
  260. }
  261. NetworkDiagnostics.OnSend(message, channelId, segment.Count, identity.observers.Count);
  262. }
  263. }
  264. /// <summary>Send a message to only clients which are ready with option to include the owner of the object identity</summary>
  265. // TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady!
  266. public static void SendToReadyObservers<T>(NetworkIdentity identity, T message, bool includeOwner = true, int channelId = Channels.Reliable)
  267. where T : struct, NetworkMessage
  268. {
  269. // Debug.Log($"Server.SendToReady {typeof(T)}");
  270. if (identity == null || identity.observers == null || identity.observers.Count == 0)
  271. return;
  272. using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
  273. {
  274. // pack message only once
  275. MessagePacking.Pack(message, writer);
  276. ArraySegment<byte> segment = writer.ToArraySegment();
  277. int count = 0;
  278. foreach (NetworkConnection conn in identity.observers.Values)
  279. {
  280. bool isOwner = conn == identity.connectionToClient;
  281. if ((!isOwner || includeOwner) && conn.isReady)
  282. {
  283. count++;
  284. conn.Send(segment, channelId);
  285. }
  286. }
  287. NetworkDiagnostics.OnSend(message, channelId, segment.Count, count);
  288. }
  289. }
  290. // Deprecated 2021-09-19
  291. [Obsolete("SendToReady(identity, message, ...) was renamed to SendToReadyObservers because that's what it does.")]
  292. public static void SendToReady<T>(NetworkIdentity identity, T message, bool includeOwner = true, int channelId = Channels.Reliable)
  293. where T : struct, NetworkMessage =>
  294. SendToReadyObservers(identity, message, includeOwner, channelId);
  295. /// <summary>Send a message to only clients which are ready including the owner of the NetworkIdentity</summary>
  296. // TODO put rpcs into NetworkServer.Update WorldState packet, then finally remove SendToReady!
  297. public static void SendToReadyObservers<T>(NetworkIdentity identity, T message, int channelId)
  298. where T : struct, NetworkMessage
  299. {
  300. SendToReadyObservers(identity, message, true, channelId);
  301. }
  302. // Deprecated 2021-09-19
  303. [Obsolete("SendToReady(identity, message, ...) was renamed to SendToReadyObservers because that's what it does.")]
  304. public static void SendToReady<T>(NetworkIdentity identity, T message, int channelId)
  305. where T : struct, NetworkMessage =>
  306. SendToReadyObservers(identity, message, channelId);
  307. // transport events ////////////////////////////////////////////////////
  308. // called by transport
  309. static void OnTransportConnected(int connectionId)
  310. {
  311. // Debug.Log($"Server accepted client:{connectionId}");
  312. // connectionId needs to be != 0 because 0 is reserved for local player
  313. // note that some transports like kcp generate connectionId by
  314. // hashing which can be < 0 as well, so we need to allow < 0!
  315. if (connectionId == 0)
  316. {
  317. Debug.LogError($"Server.HandleConnect: invalid connectionId: {connectionId} . Needs to be != 0, because 0 is reserved for local player.");
  318. Transport.activeTransport.ServerDisconnect(connectionId);
  319. return;
  320. }
  321. // connectionId not in use yet?
  322. if (connections.ContainsKey(connectionId))
  323. {
  324. Transport.activeTransport.ServerDisconnect(connectionId);
  325. // Debug.Log($"Server connectionId {connectionId} already in use...kicked client");
  326. return;
  327. }
  328. // are more connections allowed? if not, kick
  329. // (it's easier to handle this in Mirror, so Transports can have
  330. // less code and third party transport might not do that anyway)
  331. // (this way we could also send a custom 'tooFull' message later,
  332. // Transport can't do that)
  333. if (connections.Count < maxConnections)
  334. {
  335. // add connection
  336. NetworkConnectionToClient conn = new NetworkConnectionToClient(connectionId);
  337. OnConnected(conn);
  338. }
  339. else
  340. {
  341. // kick
  342. Transport.activeTransport.ServerDisconnect(connectionId);
  343. // Debug.Log($"Server full, kicked client {connectionId}");
  344. }
  345. }
  346. internal static void OnConnected(NetworkConnectionToClient conn)
  347. {
  348. // Debug.Log($"Server accepted client:{conn}");
  349. // add connection and invoke connected event
  350. AddConnection(conn);
  351. OnConnectedEvent?.Invoke(conn);
  352. }
  353. static bool UnpackAndInvoke(NetworkConnectionToClient connection, NetworkReader reader, int channelId)
  354. {
  355. if (MessagePacking.Unpack(reader, out ushort msgType))
  356. {
  357. // try to invoke the handler for that message
  358. if (handlers.TryGetValue(msgType, out NetworkMessageDelegate handler))
  359. {
  360. handler.Invoke(connection, reader, channelId);
  361. connection.lastMessageTime = Time.time;
  362. return true;
  363. }
  364. else
  365. {
  366. // message in a batch are NOT length prefixed to save bandwidth.
  367. // every message needs to be handled and read until the end.
  368. // otherwise it would overlap into the next message.
  369. // => need to warn and disconnect to avoid undefined behaviour.
  370. // => WARNING, not error. can happen if attacker sends random data.
  371. Debug.LogWarning($"Unknown message id: {msgType} for connection: {connection}. This can happen if no handler was registered for this message.");
  372. // simply return false. caller is responsible for disconnecting.
  373. //connection.Disconnect();
  374. return false;
  375. }
  376. }
  377. else
  378. {
  379. // => WARNING, not error. can happen if attacker sends random data.
  380. Debug.LogWarning($"Invalid message header for connection: {connection}.");
  381. // simply return false. caller is responsible for disconnecting.
  382. //connection.Disconnect();
  383. return false;
  384. }
  385. }
  386. // called by transport
  387. internal static void OnTransportData(int connectionId, ArraySegment<byte> data, int channelId)
  388. {
  389. if (connections.TryGetValue(connectionId, out NetworkConnectionToClient connection))
  390. {
  391. // client might batch multiple messages into one packet.
  392. // feed it to the Unbatcher.
  393. // NOTE: we don't need to associate a channelId because we
  394. // always process all messages in the batch.
  395. if (!connection.unbatcher.AddBatch(data))
  396. {
  397. Debug.LogWarning($"NetworkServer: received Message was too short (messages should start with message id)");
  398. connection.Disconnect();
  399. return;
  400. }
  401. // process all messages in the batch.
  402. // only while NOT loading a scene.
  403. // if we get a scene change message, then we need to stop
  404. // processing. otherwise we might apply them to the old scene.
  405. // => fixes https://github.com/vis2k/Mirror/issues/2651
  406. //
  407. // NOTE: if scene starts loading, then the rest of the batch
  408. // would only be processed when OnTransportData is called
  409. // the next time.
  410. // => consider moving processing to NetworkEarlyUpdate.
  411. while (!isLoadingScene &&
  412. connection.unbatcher.GetNextMessage(out NetworkReader reader, out double remoteTimestamp))
  413. {
  414. // enough to read at least header size?
  415. if (reader.Remaining >= MessagePacking.HeaderSize)
  416. {
  417. // make remoteTimeStamp available to the user
  418. connection.remoteTimeStamp = remoteTimestamp;
  419. // handle message
  420. if (!UnpackAndInvoke(connection, reader, channelId))
  421. {
  422. // warn, disconnect and return if failed
  423. // -> warning because attackers might send random data
  424. // -> messages in a batch aren't length prefixed.
  425. // failing to read one would cause undefined
  426. // behaviour for every message afterwards.
  427. // so we need to disconnect.
  428. // -> return to avoid the below unbatches.count error.
  429. // we already disconnected and handled it.
  430. Debug.LogWarning($"NetworkServer: failed to unpack and invoke message. Disconnecting {connectionId}.");
  431. connection.Disconnect();
  432. return;
  433. }
  434. }
  435. // otherwise disconnect
  436. else
  437. {
  438. // WARNING, not error. can happen if attacker sends random data.
  439. Debug.LogWarning($"NetworkServer: received Message was too short (messages should start with message id). Disconnecting {connectionId}");
  440. connection.Disconnect();
  441. return;
  442. }
  443. }
  444. // if we weren't interrupted by a scene change,
  445. // then all batched messages should have been processed now.
  446. // otherwise batches would silently grow.
  447. // we need to log an error to avoid debugging hell.
  448. //
  449. // EXAMPLE: https://github.com/vis2k/Mirror/issues/2882
  450. // -> UnpackAndInvoke silently returned because no handler for id
  451. // -> Reader would never be read past the end
  452. // -> Batch would never be retired because end is never reached
  453. //
  454. // NOTE: prefixing every message in a batch with a length would
  455. // avoid ever not reading to the end. for extra bandwidth.
  456. //
  457. // IMPORTANT: always keep this check to detect memory leaks.
  458. // this took half a day to debug last time.
  459. if (!isLoadingScene && connection.unbatcher.BatchesCount > 0)
  460. {
  461. Debug.LogError($"Still had {connection.unbatcher.BatchesCount} batches remaining after processing, even though processing was not interrupted by a scene change. This should never happen, as it would cause ever growing batches.\nPossible reasons:\n* A message didn't deserialize as much as it serialized\n*There was no message handler for a message id, so the reader wasn't read until the end.");
  462. }
  463. }
  464. else Debug.LogError($"HandleData Unknown connectionId:{connectionId}");
  465. }
  466. // called by transport
  467. // IMPORTANT: often times when disconnecting, we call this from Mirror
  468. // too because we want to remove the connection and handle
  469. // the disconnect immediately.
  470. // => which is fine as long as we guarantee it only runs once
  471. // => which we do by removing the connection!
  472. internal static void OnTransportDisconnected(int connectionId)
  473. {
  474. // Debug.Log($"Server disconnect client:{connectionId}");
  475. if (connections.TryGetValue(connectionId, out NetworkConnectionToClient conn))
  476. {
  477. RemoveConnection(connectionId);
  478. // Debug.Log($"Server lost client:{connectionId}");
  479. // NetworkManager hooks into OnDisconnectedEvent to make
  480. // DestroyPlayerForConnection(conn) optional, e.g. for PvP MMOs
  481. // where players shouldn't be able to escape combat instantly.
  482. if (OnDisconnectedEvent != null)
  483. {
  484. OnDisconnectedEvent.Invoke(conn);
  485. }
  486. // if nobody hooked into it, then simply call DestroyPlayerForConnection
  487. else
  488. {
  489. DestroyPlayerForConnection(conn);
  490. }
  491. }
  492. }
  493. static void OnError(int connectionId, Exception exception)
  494. {
  495. Debug.LogException(exception);
  496. // try get connection. passes null otherwise.
  497. connections.TryGetValue(connectionId, out NetworkConnectionToClient conn);
  498. OnErrorEvent?.Invoke(conn, exception);
  499. }
  500. // message handlers ////////////////////////////////////////////////////
  501. /// <summary>Register a handler for message type T. Most should require authentication.</summary>
  502. public static void RegisterHandler<T>(Action<NetworkConnection, T> handler, bool requireAuthentication = true)
  503. where T : struct, NetworkMessage
  504. {
  505. ushort msgType = MessagePacking.GetId<T>();
  506. if (handlers.ContainsKey(msgType))
  507. {
  508. Debug.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning.");
  509. }
  510. handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
  511. }
  512. /// <summary>Replace a handler for message type T. Most should require authentication.</summary>
  513. public static void ReplaceHandler<T>(Action<NetworkConnection, T> handler, bool requireAuthentication = true)
  514. where T : struct, NetworkMessage
  515. {
  516. ushort msgType = MessagePacking.GetId<T>();
  517. handlers[msgType] = MessagePacking.WrapHandler(handler, requireAuthentication);
  518. }
  519. /// <summary>Replace a handler for message type T. Most should require authentication.</summary>
  520. public static void ReplaceHandler<T>(Action<T> handler, bool requireAuthentication = true)
  521. where T : struct, NetworkMessage
  522. {
  523. ReplaceHandler<T>((_, value) => { handler(value); }, requireAuthentication);
  524. }
  525. /// <summary>Unregister a handler for a message type T.</summary>
  526. public static void UnregisterHandler<T>()
  527. where T : struct, NetworkMessage
  528. {
  529. ushort msgType = MessagePacking.GetId<T>();
  530. handlers.Remove(msgType);
  531. }
  532. /// <summary>Clears all registered message handlers.</summary>
  533. public static void ClearHandlers() => handlers.Clear();
  534. internal static bool GetNetworkIdentity(GameObject go, out NetworkIdentity identity)
  535. {
  536. identity = go.GetComponent<NetworkIdentity>();
  537. if (identity == null)
  538. {
  539. Debug.LogError($"GameObject {go.name} doesn't have NetworkIdentity.");
  540. return false;
  541. }
  542. return true;
  543. }
  544. // disconnect //////////////////////////////////////////////////////////
  545. /// <summary>Disconnect all connections, including the local connection.</summary>
  546. // synchronous: handles disconnect events and cleans up fully before returning!
  547. public static void DisconnectAll()
  548. {
  549. // disconnect and remove all connections.
  550. // we can not use foreach here because if
  551. // conn.Disconnect -> Transport.ServerDisconnect calls
  552. // OnDisconnect -> NetworkServer.OnDisconnect(connectionId)
  553. // immediately then OnDisconnect would remove the connection while
  554. // we are iterating here.
  555. // see also: https://github.com/vis2k/Mirror/issues/2357
  556. // this whole process should be simplified some day.
  557. // until then, let's copy .Values to avoid InvalidOperatinException.
  558. // note that this is only called when stopping the server, so the
  559. // copy is no performance problem.
  560. foreach (NetworkConnectionToClient conn in connections.Values.ToList())
  561. {
  562. // disconnect via connection->transport
  563. conn.Disconnect();
  564. // we want this function to be synchronous: handle disconnect
  565. // events and clean up fully before returning.
  566. // -> OnTransportDisconnected can safely be called without
  567. // waiting for the Transport's callback.
  568. // -> it has checks to only run once.
  569. // call OnDisconnected unless local player in host mod
  570. // TODO unnecessary check?
  571. if (conn.connectionId != NetworkConnection.LocalConnectionId)
  572. OnTransportDisconnected(conn.connectionId);
  573. }
  574. // cleanup
  575. connections.Clear();
  576. localConnection = null;
  577. active = false;
  578. }
  579. // add/remove/replace player ///////////////////////////////////////////
  580. /// <summary>Called by server after AddPlayer message to add the player for the connection.</summary>
  581. // When a player is added for a connection, the client for that
  582. // connection is made ready automatically. The player object is
  583. // automatically spawned, so you do not need to call NetworkServer.Spawn
  584. // for that object. This function is used for "adding" a player, not for
  585. // "replacing" the player on a connection. If there is already a player
  586. // on this playerControllerId for this connection, this will fail.
  587. public static bool AddPlayerForConnection(NetworkConnection conn, GameObject player)
  588. {
  589. NetworkIdentity identity = player.GetComponent<NetworkIdentity>();
  590. if (identity == null)
  591. {
  592. Debug.LogWarning($"AddPlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}");
  593. return false;
  594. }
  595. // cannot have a player object in "Add" version
  596. if (conn.identity != null)
  597. {
  598. Debug.Log("AddPlayer: player object already exists");
  599. return false;
  600. }
  601. // make sure we have a controller before we call SetClientReady
  602. // because the observers will be rebuilt only if we have a controller
  603. conn.identity = identity;
  604. // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients)
  605. identity.SetClientOwner(conn);
  606. // special case, we are in host mode, set hasAuthority to true so that all overrides see it
  607. if (conn is LocalConnectionToClient)
  608. {
  609. identity.hasAuthority = true;
  610. NetworkClient.InternalAddPlayer(identity);
  611. }
  612. // set ready if not set yet
  613. SetClientReady(conn);
  614. // Debug.Log($"Adding new playerGameObject object netId: {identity.netId} asset ID: {identity.assetId}");
  615. Respawn(identity);
  616. return true;
  617. }
  618. /// <summary>Called by server after AddPlayer message to add the player for the connection.</summary>
  619. // When a player is added for a connection, the client for that
  620. // connection is made ready automatically. The player object is
  621. // automatically spawned, so you do not need to call NetworkServer.Spawn
  622. // for that object. This function is used for "adding" a player, not for
  623. // "replacing" the player on a connection. If there is already a player
  624. // on this playerControllerId for this connection, this will fail.
  625. public static bool AddPlayerForConnection(NetworkConnection conn, GameObject player, Guid assetId)
  626. {
  627. if (GetNetworkIdentity(player, out NetworkIdentity identity))
  628. {
  629. identity.assetId = assetId;
  630. }
  631. return AddPlayerForConnection(conn, player);
  632. }
  633. /// <summary>Replaces connection's player object. The old object is not destroyed.</summary>
  634. // This does NOT change the ready state of the connection, so it can
  635. // safely be used while changing scenes.
  636. public static bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, bool keepAuthority = false)
  637. {
  638. NetworkIdentity identity = player.GetComponent<NetworkIdentity>();
  639. if (identity == null)
  640. {
  641. Debug.LogError($"ReplacePlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to {player}");
  642. return false;
  643. }
  644. if (identity.connectionToClient != null && identity.connectionToClient != conn)
  645. {
  646. Debug.LogError($"Cannot replace player for connection. New player is already owned by a different connection{player}");
  647. return false;
  648. }
  649. //NOTE: there can be an existing player
  650. //Debug.Log("NetworkServer ReplacePlayer");
  651. NetworkIdentity previousPlayer = conn.identity;
  652. conn.identity = identity;
  653. // Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients)
  654. identity.SetClientOwner(conn);
  655. // special case, we are in host mode, set hasAuthority to true so that all overrides see it
  656. if (conn is LocalConnectionToClient)
  657. {
  658. identity.hasAuthority = true;
  659. NetworkClient.InternalAddPlayer(identity);
  660. }
  661. // add connection to observers AFTER the playerController was set.
  662. // by definition, there is nothing to observe if there is no player
  663. // controller.
  664. //
  665. // IMPORTANT: do this in AddPlayerForConnection & ReplacePlayerForConnection!
  666. SpawnObserversForConnection(conn);
  667. //Debug.Log($"Replacing playerGameObject object netId:{player.GetComponent<NetworkIdentity>().netId} asset ID {player.GetComponent<NetworkIdentity>().assetId}");
  668. Respawn(identity);
  669. if (!keepAuthority)
  670. previousPlayer.RemoveClientAuthority();
  671. return true;
  672. }
  673. /// <summary>Replaces connection's player object. The old object is not destroyed.</summary>
  674. // This does NOT change the ready state of the connection, so it can
  675. // safely be used while changing scenes.
  676. public static bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, Guid assetId, bool keepAuthority = false)
  677. {
  678. if (GetNetworkIdentity(player, out NetworkIdentity identity))
  679. {
  680. identity.assetId = assetId;
  681. }
  682. return ReplacePlayerForConnection(conn, player, keepAuthority);
  683. }
  684. // ready ///////////////////////////////////////////////////////////////
  685. /// <summary>Flags client connection as ready (=joined world).</summary>
  686. // When a client has signaled that it is ready, this method tells the
  687. // server that the client is ready to receive spawned objects and state
  688. // synchronization updates. This is usually called in a handler for the
  689. // SYSTEM_READY message. If there is not specific action a game needs to
  690. // take for this message, relying on the default ready handler function
  691. // is probably fine, so this call wont be needed.
  692. public static void SetClientReady(NetworkConnection conn)
  693. {
  694. // Debug.Log($"SetClientReadyInternal for conn:{conn}");
  695. // set ready
  696. conn.isReady = true;
  697. // client is ready to start spawning objects
  698. if (conn.identity != null)
  699. SpawnObserversForConnection(conn);
  700. }
  701. /// <summary>Marks the client of the connection to be not-ready.</summary>
  702. // Clients that are not ready do not receive spawned objects or state
  703. // synchronization updates. They client can be made ready again by
  704. // calling SetClientReady().
  705. public static void SetClientNotReady(NetworkConnection conn)
  706. {
  707. if (conn.isReady)
  708. {
  709. // Debug.Log($"PlayerNotReady {conn}");
  710. conn.isReady = false;
  711. conn.RemoveFromObservingsObservers();
  712. conn.Send(new NotReadyMessage());
  713. }
  714. }
  715. /// <summary>Marks all connected clients as no longer ready.</summary>
  716. // All clients will no longer be sent state synchronization updates. The
  717. // player's clients can call ClientManager.Ready() again to re-enter the
  718. // ready state. This is useful when switching scenes.
  719. public static void SetAllClientsNotReady()
  720. {
  721. foreach (NetworkConnectionToClient conn in connections.Values)
  722. {
  723. SetClientNotReady(conn);
  724. }
  725. }
  726. // default ready handler.
  727. static void OnClientReadyMessage(NetworkConnection conn, ReadyMessage msg)
  728. {
  729. // Debug.Log($"Default handler for ready message from {conn}");
  730. SetClientReady(conn);
  731. }
  732. // show / hide for connection //////////////////////////////////////////
  733. internal static void ShowForConnection(NetworkIdentity identity, NetworkConnection conn)
  734. {
  735. if (conn.isReady)
  736. SendSpawnMessage(identity, conn);
  737. }
  738. internal static void HideForConnection(NetworkIdentity identity, NetworkConnection conn)
  739. {
  740. ObjectHideMessage msg = new ObjectHideMessage
  741. {
  742. netId = identity.netId
  743. };
  744. conn.Send(msg);
  745. }
  746. /// <summary>Removes the player object from the connection</summary>
  747. // destroyServerObject: Indicates whether the server object should be destroyed
  748. public static void RemovePlayerForConnection(NetworkConnection conn, bool destroyServerObject)
  749. {
  750. if (conn.identity != null)
  751. {
  752. if (destroyServerObject)
  753. Destroy(conn.identity.gameObject);
  754. else
  755. UnSpawn(conn.identity.gameObject);
  756. conn.identity = null;
  757. }
  758. //else Debug.Log($"Connection {conn} has no identity");
  759. }
  760. // remote calls ////////////////////////////////////////////////////////
  761. // Handle command from specific player, this could be one of multiple
  762. // players on a single client
  763. static void OnCommandMessage(NetworkConnection conn, CommandMessage msg)
  764. {
  765. if (!spawned.TryGetValue(msg.netId, out NetworkIdentity identity))
  766. {
  767. Debug.LogWarning($"Spawned object not found when handling Command message [netId={msg.netId}]");
  768. return;
  769. }
  770. CommandInfo commandInfo = identity.GetCommandInfo(msg.componentIndex, msg.functionHash);
  771. // Commands can be for player objects, OR other objects with client-authority
  772. // -> so if this connection's controller has a different netId then
  773. // only allow the command if clientAuthorityOwner
  774. bool requiresAuthority = commandInfo.requiresAuthority;
  775. if (requiresAuthority && identity.connectionToClient != conn)
  776. {
  777. Debug.LogWarning($"Command for object without authority [netId={msg.netId}]");
  778. return;
  779. }
  780. // Debug.Log($"OnCommandMessage for netId:{msg.netId} conn:{conn}");
  781. using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(msg.payload))
  782. identity.HandleRemoteCall(msg.componentIndex, msg.functionHash, MirrorInvokeType.Command, networkReader, conn as NetworkConnectionToClient);
  783. }
  784. // spawning ////////////////////////////////////////////////////////////
  785. static ArraySegment<byte> CreateSpawnMessagePayload(bool isOwner, NetworkIdentity identity, PooledNetworkWriter ownerWriter, PooledNetworkWriter observersWriter)
  786. {
  787. // Only call OnSerializeAllSafely if there are NetworkBehaviours
  788. if (identity.NetworkBehaviours.Length == 0)
  789. {
  790. return default;
  791. }
  792. // serialize all components with initialState = true
  793. // (can be null if has none)
  794. identity.OnSerializeAllSafely(true, ownerWriter, observersWriter);
  795. // convert to ArraySegment to avoid reader allocations
  796. // if nothing was written, .ToArraySegment returns an empty segment.
  797. ArraySegment<byte> ownerSegment = ownerWriter.ToArraySegment();
  798. ArraySegment<byte> observersSegment = observersWriter.ToArraySegment();
  799. // use owner segment if 'conn' owns this identity, otherwise
  800. // use observers segment
  801. ArraySegment<byte> payload = isOwner ? ownerSegment : observersSegment;
  802. return payload;
  803. }
  804. internal static void SendSpawnMessage(NetworkIdentity identity, NetworkConnection conn)
  805. {
  806. if (identity.serverOnly) return;
  807. //Debug.Log($"Server SendSpawnMessage: name:{identity.name} sceneId:{identity.sceneId:X} netid:{identity.netId}");
  808. // one writer for owner, one for observers
  809. using (PooledNetworkWriter ownerWriter = NetworkWriterPool.GetWriter(), observersWriter = NetworkWriterPool.GetWriter())
  810. {
  811. bool isOwner = identity.connectionToClient == conn;
  812. ArraySegment<byte> payload = CreateSpawnMessagePayload(isOwner, identity, ownerWriter, observersWriter);
  813. SpawnMessage message = new SpawnMessage
  814. {
  815. netId = identity.netId,
  816. isLocalPlayer = conn.identity == identity,
  817. isOwner = isOwner,
  818. sceneId = identity.sceneId,
  819. assetId = identity.assetId,
  820. // use local values for VR support
  821. position = identity.transform.localPosition,
  822. rotation = identity.transform.localRotation,
  823. scale = identity.transform.localScale,
  824. payload = payload
  825. };
  826. conn.Send(message);
  827. }
  828. }
  829. internal static void SendChangeOwnerMessage(NetworkIdentity identity, NetworkConnection conn)
  830. {
  831. if (identity.serverOnly) return;
  832. //Debug.Log($"Server SendChangeOwnerMessage: name={identity.name} netid={identity.netId}");
  833. conn.Send(new ChangeOwnerMessage { netId = identity.netId, isOwner = identity.connectionToClient == conn });
  834. }
  835. static void SpawnObject(GameObject obj, NetworkConnection ownerConnection)
  836. {
  837. // verify if we an spawn this
  838. if (Utils.IsPrefab(obj))
  839. {
  840. Debug.LogError($"GameObject {obj.name} is a prefab, it can't be spawned. Instantiate it first.");
  841. return;
  842. }
  843. if (!active)
  844. {
  845. Debug.LogError($"SpawnObject for {obj}, NetworkServer is not active. Cannot spawn objects without an active server.");
  846. return;
  847. }
  848. NetworkIdentity identity = obj.GetComponent<NetworkIdentity>();
  849. if (identity == null)
  850. {
  851. Debug.LogError($"SpawnObject {obj} has no NetworkIdentity. Please add a NetworkIdentity to {obj}");
  852. return;
  853. }
  854. if (identity.SpawnedFromInstantiate)
  855. {
  856. // Using Instantiate on SceneObject is not allowed, so stop spawning here
  857. // NetworkIdentity.Awake already logs error, no need to log a second error here
  858. return;
  859. }
  860. identity.connectionToClient = (NetworkConnectionToClient)ownerConnection;
  861. // special case to make sure hasAuthority is set
  862. // on start server in host mode
  863. if (ownerConnection is LocalConnectionToClient)
  864. identity.hasAuthority = true;
  865. identity.OnStartServer();
  866. // Debug.Log($"SpawnObject instance ID {identity.netId} asset ID {identity.assetId}");
  867. if (aoi)
  868. {
  869. // This calls user code which might throw exceptions
  870. // We don't want this to leave us in bad state
  871. try
  872. {
  873. aoi.OnSpawned(identity);
  874. }
  875. catch (Exception e)
  876. {
  877. Debug.LogException(e);
  878. }
  879. }
  880. RebuildObservers(identity, true);
  881. }
  882. /// <summary>Spawn the given game object on all clients which are ready.</summary>
  883. // This will cause a new object to be instantiated from the registered
  884. // prefab, or from a custom spawn function.
  885. public static void Spawn(GameObject obj, NetworkConnection ownerConnection = null)
  886. {
  887. SpawnObject(obj, ownerConnection);
  888. }
  889. /// <summary>Spawns an object and also assigns Client Authority to the specified client.</summary>
  890. // This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.
  891. public static void Spawn(GameObject obj, GameObject ownerPlayer)
  892. {
  893. NetworkIdentity identity = ownerPlayer.GetComponent<NetworkIdentity>();
  894. if (identity == null)
  895. {
  896. Debug.LogError("Player object has no NetworkIdentity");
  897. return;
  898. }
  899. if (identity.connectionToClient == null)
  900. {
  901. Debug.LogError("Player object is not a player.");
  902. return;
  903. }
  904. Spawn(obj, identity.connectionToClient);
  905. }
  906. /// <summary>Spawns an object and also assigns Client Authority to the specified client.</summary>
  907. // This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.
  908. public static void Spawn(GameObject obj, Guid assetId, NetworkConnection ownerConnection = null)
  909. {
  910. if (GetNetworkIdentity(obj, out NetworkIdentity identity))
  911. {
  912. identity.assetId = assetId;
  913. }
  914. SpawnObject(obj, ownerConnection);
  915. }
  916. internal static bool ValidateSceneObject(NetworkIdentity identity)
  917. {
  918. if (identity.gameObject.hideFlags == HideFlags.NotEditable ||
  919. identity.gameObject.hideFlags == HideFlags.HideAndDontSave)
  920. return false;
  921. #if UNITY_EDITOR
  922. if (UnityEditor.EditorUtility.IsPersistent(identity.gameObject))
  923. return false;
  924. #endif
  925. // If not a scene object
  926. return identity.sceneId != 0;
  927. }
  928. /// <summary>Spawns NetworkIdentities in the scene on the server.</summary>
  929. // NetworkIdentity objects in a scene are disabled by default. Calling
  930. // SpawnObjects() causes these scene objects to be enabled and spawned.
  931. // It is like calling NetworkServer.Spawn() for each of them.
  932. public static bool SpawnObjects()
  933. {
  934. // only if server active
  935. if (!active)
  936. return false;
  937. NetworkIdentity[] identities = Resources.FindObjectsOfTypeAll<NetworkIdentity>();
  938. // first pass: activate all scene objects
  939. foreach (NetworkIdentity identity in identities)
  940. {
  941. if (ValidateSceneObject(identity))
  942. {
  943. // Debug.Log($"SpawnObjects sceneId:{identity.sceneId:X} name:{identity.gameObject.name}");
  944. identity.gameObject.SetActive(true);
  945. // fix https://github.com/vis2k/Mirror/issues/2778:
  946. // -> SetActive(true) does NOT call Awake() if the parent
  947. // is inactive
  948. // -> we need Awake() to initialize NetworkBehaviours[] etc.
  949. // because our second pass below spawns and works with it
  950. // => detect this situation and manually call Awake for
  951. // proper initialization
  952. if (!identity.gameObject.activeInHierarchy)
  953. identity.Awake();
  954. }
  955. }
  956. // second pass: spawn all scene objects
  957. foreach (NetworkIdentity identity in identities)
  958. {
  959. if (ValidateSceneObject(identity))
  960. Spawn(identity.gameObject);
  961. }
  962. return true;
  963. }
  964. static void Respawn(NetworkIdentity identity)
  965. {
  966. if (identity.netId == 0)
  967. {
  968. // If the object has not been spawned, then do a full spawn and update observers
  969. Spawn(identity.gameObject, identity.connectionToClient);
  970. }
  971. else
  972. {
  973. // otherwise just replace his data
  974. SendSpawnMessage(identity, identity.connectionToClient);
  975. }
  976. }
  977. static void SpawnObserversForConnection(NetworkConnection conn)
  978. {
  979. //Debug.Log($"Spawning {spawned.Count} objects for conn {conn}");
  980. if (!conn.isReady)
  981. {
  982. // client needs to finish initializing before we can spawn objects
  983. // otherwise it would not find them.
  984. return;
  985. }
  986. // let connection know that we are about to start spawning...
  987. conn.Send(new ObjectSpawnStartedMessage());
  988. // add connection to each nearby NetworkIdentity's observers, which
  989. // internally sends a spawn message for each one to the connection.
  990. foreach (NetworkIdentity identity in spawned.Values)
  991. {
  992. // try with far away ones in ummorpg!
  993. if (identity.gameObject.activeSelf) //TODO this is different
  994. {
  995. //Debug.Log($"Sending spawn message for current server objects name:{identity.name} netId:{identity.netId} sceneId:{identity.sceneId:X}");
  996. // we need to support three cases:
  997. // - legacy system (identity has .visibility)
  998. // - new system (networkserver has .aoi)
  999. // - default case: no .visibility and no .aoi means add all
  1000. // connections by default)
  1001. //
  1002. // ForceHidden/ForceShown overwrite all systems so check it
  1003. // first!
  1004. // ForceShown: add no matter what
  1005. if (identity.visible == Visibility.ForceShown)
  1006. {
  1007. identity.AddObserver(conn);
  1008. }
  1009. // ForceHidden: don't show no matter what
  1010. else if (identity.visible == Visibility.ForceHidden)
  1011. {
  1012. // do nothing
  1013. }
  1014. // default: legacy system / new system / no system support
  1015. else if (identity.visible == Visibility.Default)
  1016. {
  1017. // legacy system
  1018. #pragma warning disable 618
  1019. if (identity.visibility != null)
  1020. {
  1021. // call OnCheckObserver
  1022. if (identity.visibility.OnCheckObserver(conn))
  1023. identity.AddObserver(conn);
  1024. }
  1025. #pragma warning restore 618
  1026. // new system
  1027. else if (aoi != null)
  1028. {
  1029. // call OnCheckObserver
  1030. if (aoi.OnCheckObserver(identity, conn))
  1031. identity.AddObserver(conn);
  1032. }
  1033. // no system: add all observers by default
  1034. else
  1035. {
  1036. identity.AddObserver(conn);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. // let connection know that we finished spawning, so it can call
  1042. // OnStartClient on each one (only after all were spawned, which
  1043. // is how Unity's Start() function works too)
  1044. conn.Send(new ObjectSpawnFinishedMessage());
  1045. }
  1046. /// <summary>This takes an object that has been spawned and un-spawns it.</summary>
  1047. // The object will be removed from clients that it was spawned on, or
  1048. // the custom spawn handler function on the client will be called for
  1049. // the object.
  1050. // Unlike when calling NetworkServer.Destroy(), on the server the object
  1051. // will NOT be destroyed. This allows the server to re-use the object,
  1052. // even spawn it again later.
  1053. public static void UnSpawn(GameObject obj) => DestroyObject(obj, DestroyMode.Reset);
  1054. // destroy /////////////////////////////////////////////////////////////
  1055. /// <summary>Destroys all of the connection's owned objects on the server.</summary>
  1056. // This is used when a client disconnects, to remove the players for
  1057. // that client. This also destroys non-player objects that have client
  1058. // authority set for this connection.
  1059. public static void DestroyPlayerForConnection(NetworkConnection conn)
  1060. {
  1061. // destroy all objects owned by this connection, including the player object
  1062. conn.DestroyOwnedObjects();
  1063. // remove connection from all of its observing entities observers
  1064. // fixes https://github.com/vis2k/Mirror/issues/2737
  1065. // -> cleaning those up in NetworkConnection.Disconnect is NOT enough
  1066. // because voluntary disconnects from the other end don't call
  1067. // NetworkConnectionn.Disconnect()
  1068. conn.RemoveFromObservingsObservers();
  1069. conn.identity = null;
  1070. }
  1071. // sometimes we want to GameObject.Destroy it.
  1072. // sometimes we want to just unspawn on clients and .Reset() it on server.
  1073. // => 'bool destroy' isn't obvious enough. it's really destroy OR reset!
  1074. enum DestroyMode { Destroy, Reset }
  1075. static void DestroyObject(NetworkIdentity identity, DestroyMode mode)
  1076. {
  1077. if (aoi)
  1078. {
  1079. // This calls user code which might throw exceptions
  1080. // We don't want this to leave us in bad state
  1081. try
  1082. {
  1083. aoi.OnDestroyed(identity);
  1084. }
  1085. catch (Exception e)
  1086. {
  1087. Debug.LogException(e);
  1088. }
  1089. }
  1090. // Debug.Log($"DestroyObject instance:{identity.netId}");
  1091. spawned.Remove(identity.netId);
  1092. identity.connectionToClient?.RemoveOwnedObject(identity);
  1093. // send object destroy message to all observers, clear observers
  1094. SendToObservers(identity, new ObjectDestroyMessage{netId = identity.netId});
  1095. identity.ClearObservers();
  1096. // in host mode, call OnStopClient manually
  1097. if (NetworkClient.active && localClientActive)
  1098. {
  1099. identity.OnStopClient();
  1100. // The object may have been spawned with host client ownership,
  1101. // e.g. a pet so we need to clear hasAuthority and call
  1102. // NotifyAuthority which invokes OnStopAuthority if hasAuthority.
  1103. identity.hasAuthority = false;
  1104. identity.NotifyAuthority();
  1105. }
  1106. // we are on the server. call OnStopServer.
  1107. identity.OnStopServer();
  1108. // are we supposed to GameObject.Destroy() it completely?
  1109. if (mode == DestroyMode.Destroy)
  1110. {
  1111. identity.destroyCalled = true;
  1112. UnityEngine.Object.Destroy(identity.gameObject);
  1113. }
  1114. // otherwise simply .Reset() and set inactive again
  1115. else if (mode == DestroyMode.Reset)
  1116. {
  1117. identity.Reset();
  1118. }
  1119. }
  1120. static void DestroyObject(GameObject obj, DestroyMode mode)
  1121. {
  1122. if (obj == null)
  1123. {
  1124. Debug.Log("NetworkServer DestroyObject is null");
  1125. return;
  1126. }
  1127. if (GetNetworkIdentity(obj, out NetworkIdentity identity))
  1128. {
  1129. DestroyObject(identity, mode);
  1130. }
  1131. }
  1132. /// <summary>Destroys this object and corresponding objects on all clients.</summary>
  1133. // In some cases it is useful to remove an object but not delete it on
  1134. // the server. For that, use NetworkServer.UnSpawn() instead of
  1135. // NetworkServer.Destroy().
  1136. public static void Destroy(GameObject obj) => DestroyObject(obj, DestroyMode.Destroy);
  1137. // interest management /////////////////////////////////////////////////
  1138. // Helper function to add all server connections as observers.
  1139. // This is used if none of the components provides their own
  1140. // OnRebuildObservers function.
  1141. internal static void AddAllReadyServerConnectionsToObservers(NetworkIdentity identity)
  1142. {
  1143. // add all server connections
  1144. foreach (NetworkConnectionToClient conn in connections.Values)
  1145. {
  1146. // only if authenticated (don't send to people during logins)
  1147. if (conn.isReady)
  1148. identity.AddObserver(conn);
  1149. }
  1150. // add local host connection (if any)
  1151. if (localConnection != null && localConnection.isReady)
  1152. {
  1153. identity.AddObserver(localConnection);
  1154. }
  1155. }
  1156. // allocate newObservers helper HashSet only once
  1157. static readonly HashSet<NetworkConnection> newObservers = new HashSet<NetworkConnection>();
  1158. // rebuild observers default method (no AOI) - adds all connections
  1159. static void RebuildObserversDefault(NetworkIdentity identity, bool initialize)
  1160. {
  1161. // only add all connections when rebuilding the first time.
  1162. // second time we just keep them without rebuilding anything.
  1163. if (initialize)
  1164. {
  1165. // not force hidden?
  1166. if (identity.visible != Visibility.ForceHidden)
  1167. {
  1168. AddAllReadyServerConnectionsToObservers(identity);
  1169. }
  1170. }
  1171. }
  1172. // rebuild observers via interest management system
  1173. static void RebuildObserversCustom(NetworkIdentity identity, bool initialize)
  1174. {
  1175. // clear newObservers hashset before using it
  1176. newObservers.Clear();
  1177. // not force hidden?
  1178. if (identity.visible != Visibility.ForceHidden)
  1179. {
  1180. // obsolete legacy system support (for now)
  1181. #pragma warning disable 618
  1182. if (identity.visibility != null)
  1183. identity.visibility.OnRebuildObservers(newObservers, initialize);
  1184. #pragma warning restore 618
  1185. else
  1186. aoi.OnRebuildObservers(identity, newObservers, initialize);
  1187. }
  1188. // IMPORTANT: AFTER rebuilding add own player connection in any case
  1189. // to ensure player always sees himself no matter what.
  1190. // -> OnRebuildObservers might clear observers, so we need to add
  1191. // the player's own connection AFTER. 100% fail safe.
  1192. // -> fixes https://github.com/vis2k/Mirror/issues/692 where a
  1193. // player might teleport out of the ProximityChecker's cast,
  1194. // losing the own connection as observer.
  1195. if (identity.connectionToClient != null)
  1196. {
  1197. newObservers.Add(identity.connectionToClient);
  1198. }
  1199. bool changed = false;
  1200. // add all newObservers that aren't in .observers yet
  1201. foreach (NetworkConnection conn in newObservers)
  1202. {
  1203. // only add ready connections.
  1204. // otherwise the player might not be in the world yet or anymore
  1205. if (conn != null && conn.isReady)
  1206. {
  1207. if (initialize || !identity.observers.ContainsKey(conn.connectionId))
  1208. {
  1209. // new observer
  1210. conn.AddToObserving(identity);
  1211. // Debug.Log($"New Observer for {gameObject} {conn}");
  1212. changed = true;
  1213. }
  1214. }
  1215. }
  1216. // remove all old .observers that aren't in newObservers anymore
  1217. foreach (NetworkConnection conn in identity.observers.Values)
  1218. {
  1219. if (!newObservers.Contains(conn))
  1220. {
  1221. // removed observer
  1222. conn.RemoveFromObserving(identity, false);
  1223. // Debug.Log($"Removed Observer for {gameObjec} {conn}");
  1224. changed = true;
  1225. }
  1226. }
  1227. // copy new observers to observers
  1228. if (changed)
  1229. {
  1230. identity.observers.Clear();
  1231. foreach (NetworkConnection conn in newObservers)
  1232. {
  1233. if (conn != null && conn.isReady)
  1234. identity.observers.Add(conn.connectionId, conn);
  1235. }
  1236. }
  1237. // special case for host mode: we use SetHostVisibility to hide
  1238. // NetworkIdentities that aren't in observer range from host.
  1239. // this is what games like Dota/Counter-Strike do too, where a host
  1240. // does NOT see all players by default. they are in memory, but
  1241. // hidden to the host player.
  1242. //
  1243. // this code is from UNET, it's a bit strange but it works:
  1244. // * it hides newly connected identities in host mode
  1245. // => that part was the intended behaviour
  1246. // * it hides ALL NetworkIdentities in host mode when the host
  1247. // connects but hasn't selected a character yet
  1248. // => this only works because we have no .localConnection != null
  1249. // check. at this stage, localConnection is null because
  1250. // StartHost starts the server first, then calls this code,
  1251. // then starts the client and sets .localConnection. so we can
  1252. // NOT add a null check without breaking host visibility here.
  1253. // * it hides ALL NetworkIdentities in server-only mode because
  1254. // observers never contain the 'null' .localConnection
  1255. // => that was not intended, but let's keep it as it is so we
  1256. // don't break anything in host mode. it's way easier than
  1257. // iterating all identities in a special function in StartHost.
  1258. if (initialize)
  1259. {
  1260. if (!newObservers.Contains(localConnection))
  1261. {
  1262. // obsolete legacy system support (for now)
  1263. #pragma warning disable 618
  1264. if (identity.visibility != null)
  1265. identity.visibility.OnSetHostVisibility(false);
  1266. #pragma warning restore 618
  1267. else if (aoi != null)
  1268. aoi.SetHostVisibility(identity, false);
  1269. }
  1270. }
  1271. }
  1272. // RebuildObservers does a local rebuild for the NetworkIdentity.
  1273. // This causes the set of players that can see this object to be rebuild.
  1274. //
  1275. // IMPORTANT:
  1276. // => global rebuild would be more simple, BUT
  1277. // => local rebuild is way faster for spawn/despawn because we can
  1278. // simply rebuild a select NetworkIdentity only
  1279. // => having both .observers and .observing is necessary for local
  1280. // rebuilds
  1281. //
  1282. // in other words, this is the perfect solution even though it's not
  1283. // completely simple (due to .observers & .observing)
  1284. //
  1285. // Mirror maintains .observing automatically in the background. best of
  1286. // both worlds without any worrying now!
  1287. public static void RebuildObservers(NetworkIdentity identity, bool initialize)
  1288. {
  1289. // observers are null until OnStartServer creates them
  1290. if (identity.observers == null)
  1291. return;
  1292. // legacy proximitychecker support:
  1293. // make sure user doesn't use both new and old system.
  1294. #pragma warning disable 618
  1295. if (aoi != null & identity.visibility != null)
  1296. {
  1297. Debug.LogError($"RebuildObservers: {identity.name} has {identity.visibility.GetType()} component but there is also a global {aoi.GetType()} component. Can't use both systems at the same time!");
  1298. return;
  1299. }
  1300. #pragma warning restore 618
  1301. // if there is no interest management system,
  1302. // or if 'force shown' then add all connections
  1303. #pragma warning disable 618
  1304. if ((aoi == null && identity.visibility == null) ||
  1305. identity.visible == Visibility.ForceShown)
  1306. #pragma warning restore 618
  1307. {
  1308. RebuildObserversDefault(identity, initialize);
  1309. }
  1310. // otherwise let interest management system rebuild
  1311. else
  1312. {
  1313. RebuildObserversCustom(identity, initialize);
  1314. }
  1315. }
  1316. // broadcasting ////////////////////////////////////////////////////////
  1317. // helper function to get the right serialization for a connection
  1318. static NetworkWriter GetEntitySerializationForConnection(NetworkIdentity identity, NetworkConnectionToClient connection)
  1319. {
  1320. // get serialization for this entity (cached)
  1321. // IMPORTANT: int tick avoids floating point inaccuracy over days/weeks
  1322. NetworkIdentitySerialization serialization = identity.GetSerializationAtTick(Time.frameCount);
  1323. // is this entity owned by this connection?
  1324. bool owned = identity.connectionToClient == connection;
  1325. // send serialized data
  1326. // owner writer if owned
  1327. if (owned)
  1328. {
  1329. // was it dirty / did we actually serialize anything?
  1330. if (serialization.ownerWriter.Position > 0)
  1331. return serialization.ownerWriter;
  1332. }
  1333. // observers writer if not owned
  1334. else
  1335. {
  1336. // was it dirty / did we actually serialize anything?
  1337. if (serialization.observersWriter.Position > 0)
  1338. return serialization.observersWriter;
  1339. }
  1340. // nothing was serialized
  1341. return null;
  1342. }
  1343. // helper function to broadcast the world to a connection
  1344. static void BroadcastToConnection(NetworkConnectionToClient connection)
  1345. {
  1346. // for each entity that this connection is seeing
  1347. foreach (NetworkIdentity identity in connection.observing)
  1348. {
  1349. // make sure it's not null or destroyed.
  1350. // (which can happen if someone uses
  1351. // GameObject.Destroy instead of
  1352. // NetworkServer.Destroy)
  1353. if (identity != null)
  1354. {
  1355. // get serialization for this entity viewed by this connection
  1356. // (if anything was serialized this time)
  1357. NetworkWriter serialization = GetEntitySerializationForConnection(identity, connection);
  1358. if (serialization != null)
  1359. {
  1360. EntityStateMessage message = new EntityStateMessage
  1361. {
  1362. netId = identity.netId,
  1363. payload = serialization.ToArraySegment()
  1364. };
  1365. connection.Send(message);
  1366. }
  1367. // clear dirty bits only for the components that we serialized
  1368. // DO NOT clean ALL component's dirty bits, because
  1369. // components can have different syncIntervals and we don't
  1370. // want to reset dirty bits for the ones that were not
  1371. // synced yet.
  1372. // (we serialized only the IsDirty() components, or all of
  1373. // them if initialState. clearing the dirty ones is enough.)
  1374. //
  1375. // NOTE: this is what we did before push->pull
  1376. // broadcasting. let's keep doing this for
  1377. // feature parity to not break anyone's project.
  1378. // TODO make this more simple / unnecessary later.
  1379. identity.ClearDirtyComponentsDirtyBits();
  1380. }
  1381. // spawned list should have no null entries because we
  1382. // always call Remove in OnObjectDestroy everywhere.
  1383. // if it does have null then someone used
  1384. // GameObject.Destroy instead of NetworkServer.Destroy.
  1385. else Debug.LogWarning($"Found 'null' entry in observing list for connectionId={connection.connectionId}. Please call NetworkServer.Destroy to destroy networked objects. Don't use GameObject.Destroy.");
  1386. }
  1387. }
  1388. // NetworkLateUpdate called after any Update/FixedUpdate/LateUpdate
  1389. // (we add this to the UnityEngine in NetworkLoop)
  1390. static readonly List<NetworkConnectionToClient> connectionsCopy =
  1391. new List<NetworkConnectionToClient>();
  1392. static void Broadcast()
  1393. {
  1394. // copy all connections into a helper collection so that
  1395. // OnTransportDisconnected can be called while iterating.
  1396. // -> OnTransportDisconnected removes from the collection
  1397. // -> which would throw 'can't modify while iterating' errors
  1398. // => see also: https://github.com/vis2k/Mirror/issues/2739
  1399. // (copy nonalloc)
  1400. // TODO remove this when we move to 'lite' transports with only
  1401. // socket send/recv later.
  1402. connectionsCopy.Clear();
  1403. connections.Values.CopyTo(connectionsCopy);
  1404. // go through all connections
  1405. foreach (NetworkConnectionToClient connection in connectionsCopy)
  1406. {
  1407. // has this connection joined the world yet?
  1408. // for each READY connection:
  1409. // pull in UpdateVarsMessage for each entity it observes
  1410. if (connection.isReady)
  1411. {
  1412. // broadcast world state to this connection
  1413. BroadcastToConnection(connection);
  1414. }
  1415. // update connection to flush out batched messages
  1416. connection.Update();
  1417. }
  1418. // TODO this is way too slow because we iterate ALL spawned :/
  1419. // TODO this is way too complicated :/
  1420. // to understand what this tries to prevent, consider this example:
  1421. // monster has health=100
  1422. // we change health=200, dirty bit is set
  1423. // player comes in range, gets full serialization spawn packet.
  1424. // next Broadcast(), player gets the health=200 change because dirty bit was set.
  1425. //
  1426. // this code clears all dirty bits if no players are around to prevent it.
  1427. // BUT there are two issues:
  1428. // 1. what if a playerB was around the whole time?
  1429. // 2. why don't we handle broadcast and spawn packets both HERE?
  1430. // handling spawn separately is why we need this complex magic
  1431. //
  1432. // see test: DirtyBitsAreClearedForSpawnedWithoutObservers()
  1433. // see test: SyncObjectChanges_DontGrowWithoutObservers()
  1434. //
  1435. // PAUL: we also do this to avoid ever growing SyncList .changes
  1436. //ClearSpawnedDirtyBits();
  1437. //
  1438. // this was moved to NetworkIdentity.AddObserver!
  1439. // same result, but no more O(N) loop in here!
  1440. // TODO remove this comment after moving spawning into Broadcast()!
  1441. }
  1442. // update //////////////////////////////////////////////////////////////
  1443. // NetworkEarlyUpdate called before any Update/FixedUpdate
  1444. // (we add this to the UnityEngine in NetworkLoop)
  1445. internal static void NetworkEarlyUpdate()
  1446. {
  1447. // process all incoming messages first before updating the world
  1448. if (Transport.activeTransport != null)
  1449. Transport.activeTransport.ServerEarlyUpdate();
  1450. }
  1451. internal static void NetworkLateUpdate()
  1452. {
  1453. // only broadcast world if active
  1454. if (active)
  1455. Broadcast();
  1456. // process all outgoing messages after updating the world
  1457. // (even if not active. still want to process disconnects etc.)
  1458. if (Transport.activeTransport != null)
  1459. Transport.activeTransport.ServerLateUpdate();
  1460. }
  1461. }
  1462. }