Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Client and server keep their own spawned list #71

Merged
merged 1 commit into from
Mar 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 4 additions & 2 deletions Assets/Mirror/Examples/Room/Scripts/PlayerScore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ void OnControllerColliderHit(ControllerColliderHit hit)
// OnControllerColliderHit will fire many times as the player slides against the object.
controllerColliderHitObject.SetActive(false);

CmdClaimPrize(controllerColliderHitObject);
CmdClaimPrize(controllerColliderHitObject.GetComponent<NetworkIdentity>().netId);
}
}

[Command]
void CmdClaimPrize(GameObject hitObject)
void CmdClaimPrize(uint hitId)
{
NetworkIdentity hitObject = server.spawned[hitId];

// Null check is required, otherwise close timing of multiple claims could throw a null ref.
if (hitObject != null)
{
Expand Down
26 changes: 13 additions & 13 deletions Assets/Mirror/Runtime/ClientScene.cs
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ static bool InvokeUnSpawnHandler(Guid assetId, GameObject obj)
/// </summary>
public static void DestroyAllClientObjects()
{
foreach (NetworkIdentity identity in NetworkIdentity.spawned.Values)
foreach (NetworkIdentity identity in client.Spawned.Values)
{
if (identity != null && identity.gameObject != null)
{
Expand All @@ -448,7 +448,7 @@ public static void DestroyAllClientObjects()
}
}
}
NetworkIdentity.spawned.Clear();
client.Spawned.Clear();
}

static void ApplySpawnPayload(NetworkIdentity identity, SpawnMessage msg)
Expand Down Expand Up @@ -485,7 +485,7 @@ static void ApplySpawnPayload(NetworkIdentity identity, SpawnMessage msg)
}
}

NetworkIdentity.spawned[msg.netId] = identity;
client.Spawned[msg.netId] = identity;

// objects spawned as part of initial state are started on a second pass
if (isSpawnFinished)
Expand Down Expand Up @@ -524,7 +524,7 @@ internal static void OnSpawn(SpawnMessage msg)

static NetworkIdentity GetExistingObject(uint netid)
{
NetworkIdentity.spawned.TryGetValue(netid, out NetworkIdentity localObject);
client.Spawned.TryGetValue(netid, out NetworkIdentity localObject);
return localObject;
}

Expand Down Expand Up @@ -588,7 +588,7 @@ internal static void OnObjectSpawnFinished(ObjectSpawnFinishedMessage _)
// paul: Initialize the objects in the same order as they were initialized
// in the server. This is important if spawned objects
// use data from scene objects
foreach (NetworkIdentity identity in NetworkIdentity.spawned.Values.OrderBy(uv => uv.netId))
foreach (NetworkIdentity identity in client.Spawned.Values.OrderBy(uv => uv.netId))
{
identity.NotifyAuthority();
identity.OnStartClient();
Expand All @@ -611,7 +611,7 @@ static void DestroyObject(uint netId)
{
if (LogFilter.Debug) Debug.Log("ClientScene.OnObjDestroy netId:" + netId);

if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity localObject) && localObject != null)
if (client.Spawned.TryGetValue(netId, out NetworkIdentity localObject) && localObject != null)
{
localObject.OnNetworkDestroy();

Expand All @@ -629,7 +629,7 @@ static void DestroyObject(uint netId)
spawnableObjects[localObject.sceneId] = localObject;
}
}
NetworkIdentity.spawned.Remove(netId);
client.Spawned.Remove(netId);
localObject.MarkForReset();
}
else
Expand All @@ -642,22 +642,22 @@ internal static void OnHostClientObjectDestroy(ObjectDestroyMessage msg)
{
if (LogFilter.Debug) Debug.Log("ClientScene.OnLocalObjectObjDestroy netId:" + msg.netId);

NetworkIdentity.spawned.Remove(msg.netId);
client.Spawned.Remove(msg.netId);
}

internal static void OnHostClientObjectHide(ObjectHideMessage msg)
{
if (LogFilter.Debug) Debug.Log("ClientScene::OnLocalObjectObjHide netId:" + msg.netId);

if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
if (client.Spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
{
localObject.OnSetHostVisibility(false);
}
}

internal static void OnHostClientSpawn(SpawnMessage msg)
{
if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
if (client.Spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
{
if (msg.isLocalPlayer)
InternalAddPlayer(localObject);
Expand All @@ -674,7 +674,7 @@ internal static void OnUpdateVarsMessage(UpdateVarsMessage msg)
{
if (LogFilter.Debug) Debug.Log("ClientScene.OnUpdateVarsMessage " + msg.netId);

if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
if (client.Spawned.TryGetValue(msg.netId, out NetworkIdentity localObject) && localObject != null)
{
using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(msg.payload))
localObject.OnDeserializeAllSafely(networkReader, false);
Expand All @@ -689,7 +689,7 @@ internal static void OnRPCMessage(RpcMessage msg)
{
if (LogFilter.Debug) Debug.Log("ClientScene.OnRPCMessage hash:" + msg.functionHash + " netId:" + msg.netId);

if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity identity))
if (client.Spawned.TryGetValue(msg.netId, out NetworkIdentity identity))
{
using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(msg.payload))
identity.HandleRPC(msg.componentIndex, msg.functionHash, networkReader);
Expand All @@ -700,7 +700,7 @@ internal static void OnSyncEventMessage(SyncEventMessage msg)
{
if (LogFilter.Debug) Debug.Log("ClientScene.OnSyncEventMessage " + msg.netId);

if (NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity identity))
if (client.Spawned.TryGetValue(msg.netId, out NetworkIdentity identity))
{
using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(msg.payload))
identity.HandleSyncEvent(msg.componentIndex, msg.functionHash, networkReader);
Expand Down
4 changes: 2 additions & 2 deletions Assets/Mirror/Runtime/NetworkBehaviour.cs
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ protected GameObject GetSyncVarGameObject(uint netId, ref GameObject gameObjectF

// client always looks up based on netId because objects might get in and out of range
// over and over again, which shouldn't null them forever
if (NetworkIdentity.spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null)
if (client.Spawned.TryGetValue(netId, out NetworkIdentity identity) && identity != null)
return gameObjectField = identity.gameObject;
return null;
}
Expand Down Expand Up @@ -598,7 +598,7 @@ protected NetworkIdentity GetSyncVarNetworkIdentity(uint netId, ref NetworkIdent

// client always looks up based on netId because objects might get in and out of range
// over and over again, which shouldn't null them forever
NetworkIdentity.spawned.TryGetValue(netId, out identityField);
client.Spawned.TryGetValue(netId, out identityField);
return identityField;
}

Expand Down
17 changes: 17 additions & 0 deletions Assets/Mirror/Runtime/NetworkClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,23 @@ public class NetworkClient : MonoBehaviour
/// </summary>
public bool isConnected => connectState == ConnectState.Connected;

private readonly Dictionary<uint, NetworkIdentity> spawned = new Dictionary<uint, NetworkIdentity>();

/// <summary>
/// List of all objects spawned in this client
/// </summary>
public Dictionary<uint, NetworkIdentity> Spawned
{
get
{
// if we are in host mode, the list of spawned object is the same as the server list
if (hostServer != null)
return hostServer.spawned;
else
return spawned;
}
}

/// <summary>
/// The host server
/// </summary>
Expand Down
7 changes: 1 addition & 6 deletions Assets/Mirror/Runtime/NetworkIdentity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,6 @@ internal set
}
}

/// <summary>
/// All spawned NetworkIdentities by netId. Available on server and client.
/// </summary>
public static readonly Dictionary<uint, NetworkIdentity> spawned = new Dictionary<uint, NetworkIdentity>();

public NetworkBehaviour[] NetworkBehaviours => networkBehavioursCache = networkBehavioursCache ?? GetComponents<NetworkBehaviour>();

[SerializeField, HideInInspector] string m_AssetId;
Expand Down Expand Up @@ -516,7 +511,7 @@ internal void OnStartServer()

// add to spawned (note: the original EnableIsServer isn't needed
// because we already set m_isServer=true above)
spawned[netId] = this;
server.spawned[netId] = this;

foreach (NetworkBehaviour comp in NetworkBehaviours)
{
Expand Down
2 changes: 2 additions & 0 deletions Assets/Mirror/Runtime/NetworkReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ public static byte[] ReadBytes(this NetworkReader reader, int count)
}

public static Guid ReadGuid(this NetworkReader reader) => new Guid(reader.ReadBytes(16));
/*
public static Transform ReadTransform(this NetworkReader reader) => reader.ReadNetworkIdentity()?.transform;
public static GameObject ReadGameObject(this NetworkReader reader) => reader.ReadNetworkIdentity()?.gameObject;

Expand All @@ -356,6 +357,7 @@ public static NetworkIdentity ReadNetworkIdentity(this NetworkReader reader)
if (LogFilter.Debug) Debug.Log("ReadNetworkIdentity netId:" + netId + " not found in spawned");
return null;
}
*/

public static Uri ReadUri(this NetworkReader reader)
{
Expand Down
15 changes: 9 additions & 6 deletions Assets/Mirror/Runtime/NetworkServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ public class NetworkServer : MonoBehaviour
// cache the Send(connectionIds) list to avoid allocating each time
readonly List<int> connectionIdsCache = new List<int>();


public readonly Dictionary<uint, NetworkIdentity> spawned = new Dictionary<uint, NetworkIdentity>();

/// <summary>
/// This shuts down the server and disconnects all clients.
/// </summary>
Expand Down Expand Up @@ -201,7 +204,7 @@ internal void RemoveLocalConnection()

internal void ActivateHostScene()
{
foreach (NetworkIdentity identity in NetworkIdentity.spawned.Values)
foreach (NetworkIdentity identity in spawned.Values)
{
if (!identity.isClient)
{
Expand Down Expand Up @@ -409,7 +412,7 @@ internal void Update()
return;

// update all server objects
foreach (KeyValuePair<uint, NetworkIdentity> kvp in NetworkIdentity.spawned)
foreach (KeyValuePair<uint, NetworkIdentity> kvp in spawned)
{
if (kvp.Value != null && kvp.Value.gameObject != null)
{
Expand Down Expand Up @@ -631,7 +634,7 @@ public bool AddPlayerForConnection(NetworkConnection conn, GameObject player, Gu

void SpawnObserversForConnection(NetworkConnection conn)
{
if (LogFilter.Debug) Debug.Log("Spawning " + NetworkIdentity.spawned.Count + " objects for conn " + conn);
if (LogFilter.Debug) Debug.Log("Spawning " + spawned.Count + " objects for conn " + conn);

if (!conn.isReady)
{
Expand All @@ -645,7 +648,7 @@ void SpawnObserversForConnection(NetworkConnection conn)

// add connection to each nearby NetworkIdentity's observers, which
// internally sends a spawn message for each one to the connection.
foreach (NetworkIdentity identity in NetworkIdentity.spawned.Values)
foreach (NetworkIdentity identity in spawned.Values)
{
if (identity.gameObject.activeSelf) //TODO this is different // try with far away ones in ummorpg!
{
Expand Down Expand Up @@ -880,7 +883,7 @@ void OnRemovePlayerMessage(NetworkConnection conn, RemovePlayerMessage msg)
// Handle command from specific player, this could be one of multiple players on a single client
void OnCommandMessage(NetworkConnection conn, CommandMessage msg)
{
if (!NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity identity))
if (!spawned.TryGetValue(msg.netId, out NetworkIdentity identity))
{
Debug.LogWarning("Spawned object not found when handling Command message [netId=" + msg.netId + "]");
return;
Expand Down Expand Up @@ -1077,7 +1080,7 @@ public void Spawn(GameObject obj, NetworkConnection ownerConnection = null)
void DestroyObject(NetworkIdentity identity, bool destroyServerObject)
{
if (LogFilter.Debug) Debug.Log("DestroyObject instance:" + identity.netId);
NetworkIdentity.spawned.Remove(identity.netId);
spawned.Remove(identity.netId);

identity.connectionToClient?.RemoveOwnedObject(identity);

Expand Down
38 changes: 0 additions & 38 deletions Assets/Mirror/Tests/Editor/NetworkIdentityTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -370,44 +370,6 @@ public void ServerMode_IsFlags_Test()

// stop the server
server.Shutdown();
NetworkIdentity.spawned.Clear();
}

// check isClient/isServer/isLocalPlayer in host mode
[Test]
public void HostMode_IsFlags_Test()
{
// start the server
var networkManagerGameObject = new GameObject();
NetworkServer server = networkManagerGameObject.AddComponent<NetworkServer>();
NetworkClient client = networkManagerGameObject.AddComponent<NetworkClient>();
server.Listen(1000);

// start the client
client.ConnectHost(server);

// add component
IsClientServerCheckComponent component = gameObject.AddComponent<IsClientServerCheckComponent>();

// set is as local player
ClientScene.InternalAddPlayer(identity);

// spawn it
server.Spawn(gameObject);

// OnStartServer should have been called. check the flags.
Assert.That(component.OnStartServer_isClient, Is.EqualTo(true));
Assert.That(component.OnStartServer_isLocalPlayer, Is.EqualTo(true));
Assert.That(component.OnStartServer_isServer, Is.EqualTo(true));

// stop the client
client.Shutdown();
server.RemoveLocalConnection();
ClientScene.Shutdown();

// stop the server
server.Shutdown();
NetworkIdentity.spawned.Clear();
}

[Test]
Expand Down
4 changes: 2 additions & 2 deletions Assets/Mirror/Tests/Play/NetworkServerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ public void ActivateHostSceneCallsOnStartClient()
OnStartClientTestNetworkBehaviour comp = go.AddComponent<OnStartClientTestNetworkBehaviour>();
Assert.That(comp.called, Is.EqualTo(0));
//connection.identity = identity;
NetworkIdentity.spawned[identity.netId] = identity;
server.spawned[identity.netId] = identity;

// ActivateHostScene
server.ActivateHostScene();
Expand All @@ -551,7 +551,7 @@ public void ActivateHostSceneCallsOnStartClient()
Assert.That(comp.called, Is.EqualTo(1));

// clean up
NetworkIdentity.spawned.Clear();
server.spawned.Clear();
// destroy the test gameobject AFTER server was stopped.
// otherwise isServer is true in OnDestroy, which means it would try
// to call Destroy(go). but we need to use DestroyImmediate in
Expand Down