public T GetPacketData <T>()
        {
            if (typeof(T).ToString() == "EntityNetworkingSystems.NetworkFieldPacket")
            {
                return((T)System.Convert.ChangeType(ENSSerialization.DeserializeNetworkFieldPacket(packetData), typeof(T)));
            }
            else if (typeof(T).ToString() == "EntityNetworkingSystems.RPCPacketData")
            {
                return((T)System.Convert.ChangeType(ENSSerialization.DeserializeRPCPacketData(packetData), typeof(T)));
            }


            try
            {
                return((T)System.Convert.ChangeType(packetData, typeof(T)));
            } catch
            {
                return(ENSSerialization.DeserializeObject <T>(packetData));
            }
            //System.Type t = System.Type.GetType(jsonDataTypeName);
            ////Debug.Log(t);
            //if (t.ToString() == "EntityNetworkingSystems.IntPacket")
            //{
            //    //If integer you must first convert it out of a IntPacket.
            //    return JsonUtility.FromJson<IntPacket>(jsonData).integer;
            //}
            //else
            //{
            //    return JsonUtility.FromJson(jsonData, t);
            //}
        }
 public PacketListPacket(List <Packet> packets)
 {
     foreach (Packet p in packets)
     {
         this.packets.Add(ENSSerialization.SerializePacket(p));
     }
 }
Beispiel #3
0
        public void CallRPC(Packet.sendType sendType = Packet.sendType.culledbuffered, params object[] list)
        {
            RPCPacketData rpcData = GenerateRPCData(sendType, list);

            Packet p = new Packet(Packet.pType.rpc, sendType, ENSSerialization.SerializeRPCPacketData(rpcData));

            p.sendToAll         = true;
            p.relatesToNetObjID = net.networkID;


            if (NetTools.IsMultiplayerGame() == false)
            {
                InvokeRPC(rpcData.ReturnArgs());
                return;
            }


            if (net == null || !net.initialized)
            {
                queued.Add(sendType, list);
                //Debug.Log("Rpc called before initialization. Adding to queue");
                return;
            }


            NetClient.instanceClient.SendPacket(p);
        }
        public void SendTCPPacket(NetworkPlayer player, Packet packet)//, bool queuedPacket = false)
        {
            //if(!queuedPacket)
            //{
            //    queuedSendingPackets.Add(packet, player);
            //    return;
            //}

            //if(packet.packetType == Packet.pType.netVarEdit && player.clientID == NetTools.clientID)
            //{
            //    return; //No need to double sync it.
            //}
            lock (player.netStream)
            {
                lock (player.tcpClient)
                {
                    byte[] array = ENSSerialization.SerializePacket(packet);//Encoding.ASCII.GetBytes(Packet.JsonifyPacket(packet));//Packet.SerializeObject(packet);

                    //First send packet size
                    byte[] arraySize = new byte[4];
                    arraySize = System.BitConverter.GetBytes(array.Length);
                    //Debug.Log("Length: " + arraySize.Length);

                    //player.tcpClient.SendBufferSize = array.Length+arraySize.Length;

                    player.netStream.Write(arraySize, 0, arraySize.Length);

                    //Send packet
                    player.netStream.Write(array, 0, array.Length);
                }
            }
        }
        //Not a good way to do it, suggested is making a custom serializor and using SetPacketData(byte[] data)
        public void SetPacketData(object obj)
        {
            if (obj.GetType().ToString() == "EntityNetworkingSystems.NetworkFieldPacket")
            {
                SetPacketData(ENSSerialization.SerializeNetworkFieldPacket((NetworkFieldPacket)obj));
                return;
            }

            SetPacketData(ENSSerialization.SerializeObject(obj));
        }
Beispiel #6
0
        public Packet GenerateRPCPacket(Packet.sendType sendType = Packet.sendType.culledbuffered, params object[] list)
        {
            RPCPacketData rpcData = new RPCPacketData(net.networkID, rpcIndex, NetTools.clientID, list);


            Packet p = new Packet(Packet.pType.rpc, sendType, ENSSerialization.SerializeRPCPacketData(rpcData));

            p.sendToAll         = true;
            p.relatesToNetObjID = net.networkID;


            return(p);
        }
        public Packet RecvPacket(NetworkPlayer player)
        {
            //First get packet size
            //byte[] packetSize = new byte[4];
            byte[] packetSize = RecieveSizeSpecificData(4, player.netStream);
            //player.netStream.Read(packetSize, 0, packetSize.Length);
            int pSize = System.BitConverter.ToInt32(packetSize, 0);

            //Debug.Log(pSize);

            //Get packet
            byte[] byteMessage = new byte[pSize];
            //player.tcpClient.ReceiveBufferSize = pSize;
            byteMessage = RecieveSizeSpecificData(pSize, player.netStream);
            //player.netStream.Read(byteMessage, 0, byteMessage.Length);
            return(ENSSerialization.DeserializePacket(byteMessage)); //Packet.DeJsonifyPacket(Encoding.ASCII.GetString(byteMessage));//(Packet)Packet.DeserializeObject(byteMessage);
        }
Beispiel #8
0
        public IEnumerator NetworkFieldPacketHandler()
        {
            yield return(new WaitUntil(() => initialized));

            while (initialized)
            {
                yield return(new WaitUntil(() => queuedNetworkPackets.Count > 0));

                Packet             curPacket = queuedNetworkPackets[0];
                NetworkFieldPacket nFP       = ENSSerialization.DeserializeNetworkFieldPacket(curPacket.packetData);

                if ((ownerID != curPacket.packetOwnerID && !curPacket.serverAuthority && !sharedObject) || (curPacket.packetOwnerID == NetTools.clientID && nFP.immediateOnSelf))
                {
                    queuedNetworkPackets.RemoveAt(0);
                    continue;
                }

                SetFieldLocal(nFP.fieldName, nFP.data.ToObject());
                queuedNetworkPackets.RemoveAt(0);
            }
        }
Beispiel #9
0
        public bool ConnectToServer(string ip = "127.0.0.1", int port = 24424)
        {
            //if(client != null)
            //{
            //    client.Dispose();
            //}

            client = new TcpClient();
            //client.NoDelay = true;
            NetTools.isClient = true;

            udpPlayer = new UDPPlayer(new IPEndPoint(IPAddress.Parse(ip), port));


            Debug.Log("Attempting Connection");
            try
            {
                client.Connect(ip, port);
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
                //Couldn't connect to server.
                Debug.LogError("Couldn't connect to server: " + ip + ":" + port);
                NetTools.isClient = false;
                client.Dispose();
                NetTools.onFailedServerConnection.Invoke();
                lastConnectionError = e.ToString();
                return(false);
            }
            Debug.Log("Connection Accepted");
            netStream = client.GetStream();



            //NetTools.isSingleplayer = false;
            ulong usedSteamID = 0;

            byte[] steamAuthData = new byte[0];
            int    buildID       = -1;

            if (useSteamworks)
            {
                if (!SteamInteraction.instance.clientStarted)
                {
                    SteamInteraction.instance.StartClient();
                }

                steamAuthData = SteamInteraction.instance.clientAuth.Data;
                usedSteamID   = SteamClient.SteamId.Value;
                buildID       = SteamApps.BuildId; //ADDING +1 TO TEST VERSION MISMATCHES SHOULD BE REMOVED AFTER.
            }

            Packet authPacket = new Packet(Packet.pType.networkAuth, Packet.sendType.nonbuffered, ENSSerialization.SerializeAuthPacket(new NetworkAuthPacket(steamAuthData, usedSteamID, udpPlayer.portToUse, password, buildID)));

            authPacket.sendToAll = false;
            authPacket.reliable  = true;
            SendTCPPacket(authPacket);


            connectedToServer = true;

            connectionHandler      = new Thread(new ThreadStart(ConnectionHandler));
            connectionHandler.Name = "ENSClientConnectionHandler";
            connectionHandler.Start();
            udpRecieveHandler      = new Thread(new ThreadStart(UDPHandler));
            udpRecieveHandler.Name = "ENSClientUDPReciever";
            udpRecieveHandler.Start();
            packetTCPSendQueue = new List <Packet>();
            packetUDPSendQueue = new List <Packet>();
            tcpSendHandler     = new Thread(new ParameterizedThreadStart(PacketSendThread))
            {
                Name = "ENSClientSendTCPHandler"
            };
            tcpSendHandler.Start(true);
            udpSendHandler = new Thread(new ParameterizedThreadStart(PacketSendThread))
            {
                Name = "ENSClientSendUDPHandler"
            };
            udpSendHandler.Start(false);

            if (!NetTools.isServer)
            {
                SteamFriends.SetRichPresence("connect", ip + ":" + port);
            }
            else
            {
                //Otherwise it'll set ip/port to 127.0.0.1, which will fail if someone else tries connecting.
                IPAddress final = null;
                foreach (IPAddress found in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                {
                    if (found.AddressFamily == AddressFamily.InterNetwork)
                    {
                        final = found;
                        break;
                    }
                }

                SteamFriends.SetRichPresence("connect", final + ":" + port);
            }

            SteamFriends.SetRichPresence("steam_display", "Multiplayer");
            //SteamFriends.SetRichPresence("steam_player_group", "Survival");
            //SteamFriends.SetRichPresence("steam_player_group_size", PlayerController.allPlayers.Count.ToString()); //Also gets updated in playercontroller.start

            return(true);
        }
        private void DirectKick(NetworkPlayer player, string reason, float delay = 0f)
        {
            Thread.Sleep((int)(delay * 1000)); //Convert to milliseconds.
            ConnectionPacket cP = new ConnectionPacket(true, reason);

            Packet p = new Packet(Packet.pType.connectionPacket, Packet.sendType.nonbuffered, ENSSerialization.SerializeConnectionPacket(cP));

            p.packetOwnerID   = -1;
            p.sendToAll       = false;
            p.serverAuthority = true;
            SendPacket(player, p);
            player.netStream.Close();
            player.playerConnected = false;
            SteamServer.EndSession(player.steamID);
            SteamUser.EndAuthSession(player.steamID);
            if (connections.Contains(player))
            {
                connections.Remove(player);
            }
            Debug.Log("Client<" + player.steamID + "> has been kicked for: " + reason);
        }
        public void HandlePacketFromClient(Packet pack, NetworkPlayer client, bool fromSelf = false)
        {
            if (pack == null)
            {
                return;
            }
            //if (fromSelf)
            //{
            //    Debug.Log("SELF PACKET: " + pack.packetType);
            //}

            if (pack.packetOwnerID != client.clientID)// && client.tcpClient == NetClient.instanceClient.client) //if server dont change cause if it is -1 it has all authority.
            {
                pack.packetOwnerID = client.clientID;
            }
            if (client.clientID == NetClient.instanceClient.clientID) //Setup server authority.
            {
                pack.serverAuthority = true;
            }
            else
            {
                pack.serverAuthority = false;
            }

            if (pack.packetType == Packet.pType.rpc)
            {
                RPCPacketData rPD = ENSSerialization.DeserializeRPCPacketData(pack.packetData);
                rPD.packetOwnerID = client.clientID;
                pack.packetData   = ENSSerialization.SerializeRPCPacketData(rPD);
            }

            if (pack.packetSendType == Packet.sendType.buffered || pack.packetSendType == Packet.sendType.culledbuffered)
            {
                //If it is a culledbuffered packet, if it is a netVarEdit packet, and it relates to the same netObj and is the RPC.
                //Then cull the previous of the same RPC to prevent RPC spam
                //This also happens with NetworkFields, even though network fields are generally *not buffered* the logic is here.
                //The reason NetworkFields aren't buffered is because the NetServer already syncs them when a client joins.
                if (pack.packetSendType == Packet.sendType.culledbuffered && (pack.packetType == Packet.pType.netVarEdit || pack.packetType == Packet.pType.rpc))
                {
                    List <Packet> related = new List <Packet>();
                    if (bufferedPackets.ContainsKey(pack.relatesToNetObjID.ToString()))
                    {
                        related.AddRange(bufferedPackets[pack.relatesToNetObjID.ToString()]);
                    }
                    if (bufferedPackets.ContainsKey(pack.tag) && bufferedPackets[pack.tag] != null)
                    {
                        related.AddRange(bufferedPackets[pack.tag]);
                    }

                    foreach (Packet buff in related)
                    {
                        if (buff.relatesToNetObjID == pack.relatesToNetObjID && buff.packetType == pack.packetType)
                        {
                            if (buff.packetType == Packet.pType.netVarEdit)
                            {
                                if (buff.GetPacketData <NetworkFieldPacket>().fieldName == pack.GetPacketData <NetworkField>().fieldName)
                                {
                                    RemoveBufferedPacket(buff);
                                }
                            }
                            else if (buff.packetType == Packet.pType.rpc)
                            {
                                if (buff.GetPacketData <RPCPacketData>().rpcIndex == pack.GetPacketData <RPCPacketData>().rpcIndex)
                                {
                                    RemoveBufferedPacket(buff);
                                }
                            }
                        }
                    }
                }

                //Debug.Log("Buffered Packet");
                AddBufferedPacket(pack);
            }

            UnityPacketHandler.instance.QueuePacket(pack);
            if (pack.sendToAll || pack.usersToRecieve.Count > 0)
            {
                foreach (NetworkPlayer player in connections.ToArray())
                {
                    //Debug.Log(player.clientID + " " + NetTools.clientID);
                    if (player == null || player.tcpClient == null || (player.clientID == NetTools.clientID))
                    {
                        continue;
                    }

                    if (pack.sendToAll == true || pack.usersToRecieve.Contains(player.clientID))
                    {
                        if (player.tcpClient.Connected)
                        {
                            try
                            {
                                SendPacket(player, pack);
                            }
                            catch (System.Exception e)
                            {
                                if (player.tcpClient.Connected)
                                {
                                    Debug.LogError(e); //If we ain't connected anymore then it makes sense.
                                    connections.Remove(player);
                                }
                            }
                        }
                        else
                        {
                            connections.Remove(player);
                        }
                    }
                }
            }
        }
        public void ClientHandler(NetworkPlayer client)
        {
            //Debug.Log(p.jsonData);
            Packet curPacket = RecvPacket(client);

            if (curPacket.packetType == Packet.pType.networkAuth)
            {
                NetworkAuthPacket clientAuthPacket = ENSSerialization.DeserializeAuthPacket(curPacket.packetData);

                if (!client.gotAuthPacket)
                {
                    //Check password.
                    if (password != "" && clientAuthPacket.password != password)
                    {
                        //Kick player wrong password.
                        KickPlayer(client, "password");
                        return;
                    }
                    else if (useSteamworks && SteamApps.BuildId != clientAuthPacket.steamBuildID)
                    {
                        //Kick player wrong version.
                        KickPlayer(client, "version");
                        return;
                    }



                    client.steamID = clientAuthPacket.steamID;


                    //Debug.Log(clientAuthPacket.udpPort);
                    client.udpEndpoint.Port = clientAuthPacket.udpPort;
                    client.playerPort       = clientAuthPacket.udpPort;
                    if (NetServer.serverInstance.useSteamworks)
                    {
                        //BeginAuthResult bAR = SteamUser.BeginAuthSession(clientAuthPacket.authData, clientAuthPacket.steamID);
                        bool worked = SteamServer.BeginAuthSession(clientAuthPacket.authData, clientAuthPacket.steamID);

                        //Debug.Log(clientSteamAuthTicket.steamID);
                        if (!worked && !client.playerIP.Contains("127.0.0.1"))    //(bAR != BeginAuthResult.OK && bAR != BeginAuthResult.DuplicateRequest)
                        {
                            KickPlayer(client, "Couldn't validate with steam. "); // + bAR.ToString());
                            //client.tcpClient.Close();
                            //Debug.Log(bAR);
                            //Debug.Log("Invalid auth ticket from: " + clientSteamAuthTicket.steamID);
                            //SteamUser.EndAuthSession(clientAuthPacket.steamID);
                            //SteamServer.EndSession(clientAuthPacket.steamID);
                        }
                        else
                        {
                            //SteamServer.UpdatePlayer(clientAuthPacket.steamID, "Player 1", 0);
                            //Debug.Log("Recieved Valid Client Auth Ticket.");
                            SteamInteraction.instance.connectedSteamIDs.Add(clientAuthPacket.steamID);
                            SteamServer.UpdatePlayer(client.steamID, new Friend(client.steamID).Name, 0);
                            SteamServer.ForceHeartbeat();
                            //Debug.Log(bAR);
                            //SteamServer.ForceHeartbeat();
                        }
                    }
                    client.gotAuthPacket = true;
                }
            }
            else
            {
                //Expected auth packet, got something else.
            }
            //Thread.Sleep(100);
            //Send login info
            //PlayerLoginData pLD = new PlayerLoginData();
            //pLD.playerNetworkID = client.clientID;
            Packet loginPacket = new Packet(Packet.pType.loginInfo, Packet.sendType.nonbuffered, new PlayerLoginData((short)client.clientID, mySteamID));

            loginPacket.packetOwnerID = -1;
            loginPacket.sendToAll     = false;
            SendPacket(client, loginPacket);


            //Thread.Sleep(50); //Prevents a memory error on the client side? bruh.
            //Send buffered packets
            if (bufferedPackets.Count > 0)
            {
                List <Packet> packetsToSend = new List <Packet>(); //Will contain buffered packets and all network fields to be updated.
                packetsToSend.AddRange(GetAllBufferedPackets());
                //Debug.Log(packetsToSend.Count);
                foreach (NetworkObject netObj in NetworkObject.allNetObjs.ToArray())
                {
                    if (netObj.fields.Count > 0)
                    {
                        List <Packet> temp = netObj.GeneratePacketListForFields();
                        packetsToSend.AddRange(temp);
                    }
                }



                List <Packet> tempPackets = new List <Packet>();


                foreach (Packet p in packetsToSend)
                {
                    tempPackets.Add(p);
                    if (tempPackets.Count >= 100)
                    {
                        Packet multiPack = new Packet(Packet.pType.multiPacket, Packet.sendType.nonbuffered, new PacketListPacket(tempPackets));
                        multiPack.sendToAll = false;
                        SendPacket(client, multiPack);

                        tempPackets = new List <Packet>();
                    }
                }

                //Send whatever remains in it otherwise max-1 or less packets will be lost.
                //Debug.Log(tempPackets.Count);
                Packet lastMulti = new Packet(Packet.pType.multiPacket, Packet.sendType.nonbuffered, new PacketListPacket(tempPackets));
                lastMulti.sendToAll = false;
                SendPacket(client, lastMulti);
                //Debug.Log(packetsToSend.Count);
                //Packet bpacket = new Packet(Packet.pType.multiPacket, Packet.sendType.nonbuffered, new PacketListPacket(packetsToSend));
                //bpacket.sendToAll = false;
                //SendPacket(client, bpacket);
            }
            NetTools.onPlayerJoin.Invoke(client);

            bool clientRunning = true;

            while (client != null && server != null && clientRunning)
            {
                try
                {
                    //Thread.Sleep(50);
                    Packet pack = RecvPacket(client);
                    HandlePacketFromClient(pack, client);
                }
                catch (System.Exception e)
                {
                    string error = e.ToString();
                    //These errors in the if statement, are already being handled. For most the usual occur when the server stops.
                    if (!error.Contains("WSACancelBlockingCall") && !error.Contains("transport connection") && !error.Contains("System.ObjectDisposedException")) //Server closed
                    {
                        Debug.LogError(e);
                    }
                    if (!error.Contains("Check destIndex and length"))
                    {
                        clientRunning = false; //Basically end the thread.
                    }
                }
            }
            client.netStream.Close();
            client.playerConnected = false;
            SteamServer.EndSession(client.steamID);
            if (connections.Contains(client))
            {
                connections.Remove(client);
            }
            NetTools.onPlayerDisconnect.Invoke(client);
            Debug.Log("NetServer.ClientHandler() thread has successfully finished.");
        }
        public void StopServer()
        {
            if (server != null)
            {
                ConnectionPacket cP = new ConnectionPacket(true, "Server Closed.");
                Packet           p  = new Packet(Packet.pType.connectionPacket, Packet.sendType.nonbuffered, ENSSerialization.SerializeConnectionPacket(cP));

                foreach (NetworkPlayer client in connections)
                {
                    SendPacket(client, p); //Server Closed Packet.
                    client.tcpClient.Close();
                    client.tcpClient.Dispose();
                }
                server.Stop();
                server = null;

                if (useSteamworks && !NetTools.isSingleplayer)
                {
                    SteamInteraction.instance.ShutdownServer();
                }
                UPnP.Shutdown();
            }
            if (udpListener != null)
            {
                udpListener.Stop();
                udpListener = null;
            }

            if (connectionHandler != null)
            {
                connectionHandler.Abort();
                connectionHandler = null;
            }
            if (udpHandler != null)
            {
                udpHandler.Abort();
                udpHandler = null;
            }

            if (GameObject.FindObjectOfType <UnityPacketHandler>() != null)
            {
                GameObject.Destroy(GameObject.FindObjectOfType <UnityPacketHandler>().gameObject);
            }
            //NetServer.serverInstance = null;
            connections     = new List <NetworkPlayer>();
            connectionsByID = new Dictionary <int, NetworkPlayer>();
            bufferedPackets = new Dictionary <string, List <Packet> >();
            if (NetServer.serverInstance != null && NetServer.serverInstance.myConnection != null)
            {
                NetServer.serverInstance.myConnection = null;
            }

            NetTools.isServer       = false;
            NetTools.isSingleplayer = false;
        }
        public static GameObject NetInstantiate(int prefabDomain, int prefabID, Vector3 position, Quaternion rotation, Packet.sendType sT = Packet.sendType.buffered, bool isSharedObject = false, List <NetworkFieldPacket> fieldDefaults = null)

        {
            int netObjID = GenerateNetworkObjectID();

            if (NetTools.IsMultiplayerGame())
            {
                if (!NetTools.isServer && NetworkData.instance.networkPrefabList[prefabDomain].prefabList[prefabID].serverInstantiateOnly)
                {
#if UNITY_EDITOR
                    Debug.LogWarning("Tried to make server authority only object: domain: " + prefabDomain + ", id: " + prefabID);
#endif
                    return(null); //If it is server only, and you aren't the server, don't do it.
                }

                SerializableVector     finalVector = new SerializableVector(position);
                SerializableQuaternion finalQuat   = new SerializableQuaternion(rotation);

                GameObjectInstantiateData gOID = new GameObjectInstantiateData();
                gOID.position       = finalVector;
                gOID.rotation       = finalQuat;
                gOID.prefabDomainID = prefabDomain;
                gOID.prefabID       = prefabID;
                gOID.isShared       = isSharedObject;
                gOID.netObjID       = netObjID;
                gOID.fieldDefaults  = fieldDefaults;

                Packet p = new Packet(Packet.pType.gOInstantiate, Packet.sendType.buffered, ENSSerialization.SerializeGOID(gOID));
                p.tag = NetworkData.instance.TagIDToTagName(NetworkData.instance.networkPrefabList[prefabDomain].defaultPacketTagID);


                //if(sT == Packet.sendType.buffered && isServer)
                //{
                //    NetServer.serverInstance.bufferedPackets.Add(p);
                //}
                NetClient.instanceClient.SendPacket(p);
            }

            //Try to get a pooled one first.
            GameObject g = NetworkData.instance.RequestPooledObject(prefabDomain, prefabID);

            if (g == null) //If there is no pooled remaining make a new one.
            {
                g = Instantiate(NetworkData.instance.networkPrefabList[prefabDomain].prefabList[prefabID].prefab, position, rotation);
            }
            else
            {
                //If pooled apply required position/rotation
                g.transform.position = position;
                g.transform.rotation = rotation;
            }
            NetworkObject nObj = g.GetComponent <NetworkObject>();
            if (nObj == null)
            {
                nObj = g.AddComponent <NetworkObject>();
            }


            nObj.ownerID             = NetTools.clientID;
            nObj.prefabDomainID      = prefabDomain;
            nObj.prefabID            = prefabID;
            nObj.networkID           = netObjID;
            nObj.sharedObject        = isSharedObject;
            nObj.detectNetworkStarts = NetworkData.instance.networkPrefabList[prefabDomain].detectNetworkStarts;

            nObj.Initialize();
            //nObj.DoRpcFieldInitialization();
            if (nObj.onNetworkStart != null)
            {
                nObj.onNetworkStart.Invoke();
            }
            //nObj.initialized = true;

            if (fieldDefaults != null)
            {
                foreach (NetworkFieldPacket nFP in fieldDefaults)
                {
                    nFP.networkObjID = netObjID;
                    nObj.SetFieldLocal(nFP.fieldName, nFP.data.ToObject());
                    //Instead just update it in UnityPacketHandler for everyone else, preventing extra packets and data from being send and lagging.
                    //nObj.UpdateField(nFP.fieldName, nFP.data.ToObject(), nFP.immediateOnSelf);
                }
            }

            return(g);
        }
Beispiel #15
0
        public void ExecutePacket(Packet curPacket)
        {
            if (curPacket.packetType == Packet.pType.gOInstantiate) //It gets instantiated NetTools.
            {
                NetworkObject             nObj = null;
                GameObjectInstantiateData gOID = ENSSerialization.DeserializeGOID(curPacket.packetData);

                //Debug.Log(NetTools.clientID + ", " + curPacket.packetOwnerID);
                if (NetTools.clientID != curPacket.packetOwnerID || NetworkObject.NetObjFromNetID(gOID.netObjID) == null)
                {
                    if (!curPacket.serverAuthority && NetworkData.instance.networkPrefabList[gOID.prefabDomainID].prefabList[gOID.prefabID].serverInstantiateOnly)
                    {
                        return; //If it is server only, and you aren't the server, don't do it.
                    }

                    GameObject g = NetworkData.instance.RequestPooledObject(gOID.prefabDomainID, gOID.prefabID);
                    if (g == null) //If a pooled object couldn't be found, make a new one.
                    {
                        try
                        {
                            g = Instantiate(NetworkData.instance.networkPrefabList[gOID.prefabDomainID].prefabList[gOID.prefabID].prefab, gOID.position.ToVec3(), gOID.rotation.ToQuaternion());
                        }
                        catch (System.Exception e)
                        {
                            Debug.Log("Error NetInstantiating: domainID: " + gOID.prefabDomainID + ", prefabID: " + gOID.prefabID + e);
                            return;
                        }
                    }
                    else
                    {
                        //If pooled apply required position/rotation/etc.
                        g.transform.position = gOID.position.ToVec3();
                        g.transform.rotation = gOID.rotation.ToQuaternion();
                    }
                    nObj = g.GetComponent <NetworkObject>();
                    if (nObj == null)
                    {
                        nObj = g.AddComponent <NetworkObject>();
                    }

                    foreach (NetworkField defaultField in NetworkData.instance.networkPrefabList[gOID.prefabDomainID].defaultFields)
                    {
                        nObj.fields.Add(defaultField.Clone());
                    }
                    foreach (RPC defaultRPC in NetworkData.instance.networkPrefabList[gOID.prefabDomainID].defaultRpcs)
                    {
                        nObj.rpcs.Add(defaultRPC.Clone());
                    }


                    nObj.ownerID        = curPacket.packetOwnerID;
                    nObj.prefabDomainID = gOID.prefabDomainID;
                    nObj.prefabID       = gOID.prefabID;
                    nObj.networkID      = gOID.netObjID;
                    nObj.sharedObject   = gOID.isShared;

                    nObj.Initialize();
                    //nObj.DoRpcFieldInitialization();

                    if (nObj.onNetworkStart != null)
                    {
                        nObj.onNetworkStart.Invoke();
                    }

                    if (gOID.fieldDefaults != null)
                    {
                        foreach (NetworkFieldPacket nFP in gOID.fieldDefaults)
                        {
                            nFP.networkObjID = gOID.netObjID;
                            //Debug.Log(nFP.data);
                            nObj.SetFieldLocal(nFP.fieldName, nFP.data.ToObject());
                        }
                    }
                }
            }
            else if (curPacket.packetType == Packet.pType.gODestroy)
            {
                //Debug.Log(curPacket.jsonData);
                //Debug.Log(curPacket.GetPacketData());
                //int netID = ENSSerialization.DeserializeInt(curPacket.packetData);
                NetworkObject found = NetworkObject.NetObjFromNetID(curPacket.relatesToNetObjID);
                if (found != null && (found.ownerID == curPacket.packetOwnerID || curPacket.serverAuthority || found.sharedObject))
                {
                    if (disableBeforeDestroy)
                    {
                        if (NetworkData.instance.ResetPooledObject(found) == false)
                        {
                            destroyQueue.Add(found.gameObject);
                        }
                    }
                    else
                    {
                        if (NetworkData.instance.ResetPooledObject(found) == false)
                        {
                            Destroy(found.gameObject);
                        }
                    }

                    if (NetTools.isServer && System.BitConverter.ToBoolean(curPacket.packetData, 0)) //Check NetTools.NetDestroy but basically it is cullRelatedPackets.
                    {
                        NetTools.CullPacketsByNetworkID(curPacket.relatesToNetObjID);
                    }
                }
                else if (found == null)
                {
                    Debug.LogWarning("Couldn't find NetworkObject of ID: " + curPacket.relatesToNetObjID);
                }
            }
            else if (curPacket.packetType == Packet.pType.multiPacket)
            {
                //Debug.Log("Recieved buffered packets.");
                List <byte[]> packetByteInfo = curPacket.GetPacketData <PacketListPacket>().packets;
                lock (packetQueue)
                {
                    foreach (byte[] packetByte in packetByteInfo)
                    {
                        packetQueue.Add(ENSSerialization.DeserializePacket(packetByte));
                    }
                }

                syncingBuffered = true;
            }
            else if (curPacket.packetType == Packet.pType.loginInfo)
            {
                //Debug.Log("Login Info Packet Recieved.");
                PlayerLoginData pLD = curPacket.GetPacketData <PlayerLoginData>();
                NetTools.clientID = pLD.clientID;//System.BitConverter.ToInt16(curPacket.packetData,0);
                NetClient.instanceClient.clientID       = NetTools.clientID;
                NetClient.instanceClient.serversSteamID = pLD.serverSteamID;

                if (NetTools.isServer)
                {
                    NetServer.serverInstance.myConnection = NetServer.serverInstance.GetPlayerByID(NetTools.clientID);
                }

                NetTools.onJoinServer.Invoke();

                //print("Test");
            }
            else if (curPacket.packetType == Packet.pType.netVarEdit)
            {
                NetworkFieldPacket nFP    = ENSSerialization.DeserializeNetworkFieldPacket(curPacket.packetData);
                NetworkObject      netObj = NetworkObject.NetObjFromNetID(nFP.networkObjID);

                if (netObj == null)
                {
                    return;
                }

                if (netObj.initialized == false)
                {
                    //netObj.queuedNetworkPackets.Add(curPacket);
                    return;
                }

                if ((netObj.ownerID != curPacket.packetOwnerID && !curPacket.serverAuthority && !netObj.sharedObject) || (curPacket.packetOwnerID == NetTools.clientID && nFP.immediateOnSelf))
                {
                    return;
                }


                //Debug.Log("Seting NetVarEdit.");
                try
                {
                    netObj.SetFieldLocal(nFP.fieldName, nFP.data.ToObject());
                }
                catch (System.Exception e)
                {
                    Debug.LogError(e);
                }
            }
            else if (curPacket.packetType == Packet.pType.rpc)
            {
                //Debug.Log(curPacket.jsonData);
                RPCPacketData rPD  = ENSSerialization.DeserializeRPCPacketData(curPacket.packetData);
                NetworkObject nObj = NetworkObject.NetObjFromNetID(rPD.networkObjectID);

                if (nObj == null || (nObj.rpcs[rPD.rpcIndex].serverAuthorityRequired && !curPacket.serverAuthority) || (nObj.ownerID != curPacket.packetOwnerID && !nObj.sharedObject && !curPacket.serverAuthority))
                {
                    return; //Means only server can run it.
                }
                nObj.rpcs[rPD.rpcIndex].InvokeRPC(rPD.ReturnArgs());
            }
            else if (curPacket.packetType == Packet.pType.connectionPacket)
            {
                if (!curPacket.serverAuthority && curPacket.packetOwnerID != -1)
                {
                    return; //Prevents anyone from disconnecting everyone.
                }

                ConnectionPacket cP = ENSSerialization.DeserializeConnectionPacket(curPacket.packetData);
                if (cP.immediateDisconnect)
                {
                    NetClient.instanceClient.DisconnectFromServer();
                    NetTools.onLeaveServer.Invoke(cP.reason);
                }
            }
            //else if (curPacket.packetType == Packet.pType.networkAuth && NetTools.isServer)
            //{



            //}
        }