Esempio n. 1
0
        public void TakeControl(IMessageRider token)
        {
            if (IsOwner)
            {
                if (HasControl)
                {
                    NetLog.Warn("You already have control of {0}", this);
                }
                else
                {
                    // revoke any existing control
                    RevokeControl(token);

                    // take control locally
                    TakeControlInternal(token);


                    // de-freeze
                    Freeze(false);
                }
            }
            else
            {
                NetLog.Error("Only the owner of {0} can take control of it", this);
            }
        }
        static void Entity_Only_Controller(Event ev)
        {
            if (ev.TargetEntity)
            {
                if (ev.TargetEntity.HasControl)
                {
                    RaiseLocal(ev);

                    // we can free this (never used after this)
                    ev.FreeStorage();
                }
                else
                {
                    if (ev.TargetEntity.IsOwner)
                    {
                        if (ev.TargetEntity.Controller != null)
                        {
                            ev.TargetEntity.Controller.eventChannel.Queue(ev);
                        }
                        else
                        {
                            NetLog.Warn("NetworkEvent sent to controller but no controller exists, event will NOT be raised");
                        }
                    }
                    else
                    {
                        ev.TargetEntity.Source.eventChannel.Queue(ev);
                    }
                }
            }
            else
            {
                NetLog.Warn("NetworkEvent with NULL target, event will NOT be forwarded or raised");
            }
        }
Esempio n. 3
0
        public bool ShouldPullDataFromMecanim(NetworkState state)
        {
#if DEBUG
            if (
#else
            return
                (#endif
                MecanimDirection == MecanimDirection.UsingAnimatorMethods && (state.Entity.IsOwner || state.Entity.HasPredictedControl)

#if DEBUG
                )
            {
                if (state.Animators.Count > 1)
                {
                    NetLog.Warn("Property '{0}' set to 'UsingAnimatorMethods' but several animators have been specified, only the first one added will be used.");
                }

                return true;
            }

                return false);
#else
                ;
#endif
        }
        private static void Entity_Only_Controller_And_Owner(Event ev)
        {
            if (ev.TargetEntity)
            {
                if (ev.TargetEntity.HasControl)
                {
                    RaiseLocal(ev);

                    if (ev.TargetEntity.IsOwner)
                    {
                        // if we're also owner, free this
                        ev.FreeStorage();
                    }
                    else
                    {
                        // check so this was not received from source, and if it wasn't then send it to it
                        if (ev.SourceConnection != ev.TargetEntity.Source)
                        {
                            ev.TargetEntity.Source.eventChannel.Queue(ev);
                        }
                    }
                }
                else
                {
                    if (ev.TargetEntity.IsOwner)
                    {
                        // raise this locally for owner
                        RaiseLocal(ev);

                        if (ev.TargetEntity.Controller != null)
                        {
                            // check so we didn't receive this from owner
                            if (ev.SourceConnection != ev.TargetEntity.Controller)
                            {
                                ev.TargetEntity.Controller.eventChannel.Queue(ev);
                            }
                        }
                        else
                        {
                            NetLog.Warn("NetworkEvent sent to controller but no controller exists, event will NOT be raised");
                        }
                    }
                    else
                    {
                        ev.TargetEntity.Source.eventChannel.Queue(ev);
                    }
                }
            }
            else
            {
                NetLog.Warn("NetworkEvent with NULL target, event will NOT be forwarded or raised");
            }
        }
Esempio n. 5
0
        public void Remove(MonoBehaviour behaviour)
        {
            for (int i = 0; i < targets.Count; ++i)
            {
                if (ReferenceEquals(targets[i].Behaviour, behaviour))
                {
                    targets.RemoveAt(i);
                    return;
                }
            }

            NetLog.Warn("Behaviour not available in this dispatcher, ignoring call to Remove.");
        }
Esempio n. 6
0
        public void WriteByteArrayLengthPrefixed(byte[] array, int maxLength)
        {
            if (WriteBool(array != null))
            {
                int length = Math.Min(array.Length, maxLength);

                if (length < array.Length)
                {
                    NetLog.Warn("Only sendig {0}/{1} bytes from byte array", length, array.Length);
                }

                WriteUShort((ushort)length);
                WriteByteArray(array, 0, length);
            }
        }
Esempio n. 7
0
        public static void WriteByteArraySimple(this BasePacket stream, byte[] array, int maxLength)
        {
            if (stream.WriteBool(array != null))
            {
                int length = Mathf.Min(array.Length, maxLength);

                if (length < array.Length)
                {
                    NetLog.Warn("Only sending {0}/{1} bytes from byte array", length, array.Length);
                }

                stream.WriteUShort((ushort)length);
                stream.WriteByteArray(array, 0, length);
            }
        }
Esempio n. 8
0
        public void Add(MonoBehaviour behaviour)
        {
            for (int i = 0; i < targets.Count; ++i)
            {
                if (ReferenceEquals(targets[i].Behaviour, behaviour))
                {
                    NetLog.Warn("Behaviour is already registered in this dispatcher, ignoring call to Add.");
                    return;
                }
            }

            targets.Add(new EventListener {
                Behaviour = behaviour, GameObject = behaviour.gameObject, Listener = behaviour as IEventListener
            });
        }
Esempio n. 9
0
        public void WriteEndPoint(IPEndPoint endpoint)
        {
            var parts = endpoint.Address.ToString().Split('.');

            if (parts.Length != 4)
            {
                NetLog.Warn(string.Format("IP address: {0} was malformed, could not write.", endpoint.Address));
                return;
            }

            WriteByte(Convert.ToByte(parts[0]));
            WriteByte(Convert.ToByte(parts[1]));
            WriteByte(Convert.ToByte(parts[2]));
            WriteByte(Convert.ToByte(parts[3]));
            WriteUShort((ushort)endpoint.Port);
        }
Esempio n. 10
0
        void OnDestroy()
        {
            if (entity && entity.IsAttached && Application.isPlaying)
            {
                if (entity.IsOwner)
                {
                    NetLog.Warn("{0} is being destroyed/disabled without being detached, forcing detach", AEntity);
                }
                else
                {
                    NetLog.Error("{0} is being destroyed/disabled without being detached by the owner, this will cause this peer to disconnect the next time it receives an update for this entity", AEntity);
                }

                // force detach
                entity.Detach();
                entity = null;
            }
        }
Esempio n. 11
0
        public void Remove <T>(Action <T> callback) where T : Event
        {
            List <CallbackWrapper> newCallbacks;

            if (callbacks.TryGetValue(typeof(T), out newCallbacks) == false)
            {
                for (int i = 0; i < callbacks.Count; ++i)
                {
                    var org = (Action <T>)newCallbacks[i].Original;
                    if (org == callback)
                    {
                        newCallbacks.RemoveAt(i);
                        return;
                    }
                }
            }

            NetLog.Warn("Could not find delegate registered as callback");
        }
Esempio n. 12
0
        public override void OnSimulateAfter(NetworkObj obj)
        {
            NetworkState state = (NetworkState)obj.Root;

            if (MecanimMode != MecanimMode.Disabled)
            {
                if (state.Animators.Count > 0)
                {
                    if (MecanimMode == MecanimMode.LayerWeight)
                    {
                        if (ShouldPullDataFromMecanim(state))
                        {
                            PullMecanimLayer(state);
                        }
                        else
                        {
                            PushMecanimLayer(state);
                        }
                    }
                    else
                    {
                        if (ShouldPullDataFromMecanim(state))
                        {
                            PullMecanimValue(state);
                        }
                        else
                        {
                            PushMecanimValue(state);
                        }
                    }
                }
                else
                {
#if DEBUG
                    if (state.MecanimWarningTimeout < UnityEngine.Time.time)
                    {
                        NetLog.Warn("You have not assigned a mecanim animator to the state on {0}, but you have properties set to use mecanim", state.Entity.UnityObject.gameObject.name);
                        state.MecanimWarningTimeout = UnityEngine.Time.time + 1;
                    }
#endif
                }
            }
        }
Esempio n. 13
0
        public static UniqueId Parse(string text)
        {
            if (string.IsNullOrEmpty(text) || text == "NONE")
            {
                return(None);
            }

            try
            {
                UniqueId id;
                id      = default(UniqueId);
                id.guid = new Guid(text);
                return(id);
            }
            catch
            {
                NetLog.Warn("Could not parse '{0}' as a UniqueId", text);
                return(UniqueId.None);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Find an entity based on unique id
        /// </summary>
        public static AscensionEntity FindEntity(NetworkId id)
        {
            VerifyIsRunning();

            if (id.Packed == 0)
            {
                return(null);
            }

            foreach (var itval in Core.entities)
            {
                if (itval.IsAttached && itval.UnityObject && itval.NetworkId.Packed == id.Packed)
                {
                    return(itval.UnityObject);
                }
            }

            NetLog.Warn("Could not find entity with {0}", id);
            return(null);
        }
Esempio n. 15
0
        public void ReleaseControl(IMessageRider token)
        {
            if (IsOwner)
            {
                if (HasControl)
                {
                    ReleaseControlInternal(token);

                    // un-freeze
                    Freeze(false);
                }
                else
                {
                    NetLog.Warn("You are not controlling {0}", this);
                }
            }
            else
            {
                NetLog.Error("You can not release control of {0}, you are not the owner", this);
            }
        }
Esempio n. 16
0
        public void Queue(Event ev)
        {
            if (ev.Reliability == ReliabilityModes.Unreliable)
            {
                // push on unreliable send queue
                unreliableSend.Add(EventUnreliable.Wrap(ev));

                // incr refs!
                ev.IncrementRefs();
            }
            else
            {
                if (reliableOrderedSend.TryEnqueue(EventReliable.Wrap(ev)))
                {
                    ev.IncrementRefs();
                }
                else
                {
                    NetLog.Warn("The reliable-ordered event queue for {0} is full, disconnecting", connection);
                    connection.Disconnect();
                }
            }
        }
Esempio n. 17
0
        private bool ReadUpdate(Packet packet)
        {
            if (packet.ReadBool() == false)
            {
                return(false);
            }
            // grab networkid
            NetworkId     networkId        = packet.ReadNetworkId();
            bool          isController     = packet.ReadBool();
            IMessageRider controlToken     = packet.ReadToken();
            bool          destroyRequested = packet.ReadBool();

            // we're destroying this proxy
            if (destroyRequested)
            {
                EntityProxy   proxy;
                IMessageRider detachToken = packet.ReadToken();

                if (_incommingDict.TryGetValue(networkId, out proxy))
                {
                    if (proxy.Entity.HasControl)
                    {
                        proxy.Entity.ReleaseControlInternal(controlToken);
                    }

                    DestroyIncommingProxy(proxy, detachToken);
                }
                else
                {
                    NetLog.Warn("Received destroy of {0} but no such proxy was found", networkId);
                }
            }
            else
            {
                IMessageRider attachToken = null;

                bool isSceneObject   = false;
                bool createRequested = packet.ReadBool();

                UniqueId   sceneId       = UniqueId.None;
                PrefabId   prefabId      = new PrefabId();
                TypeId     serializerId  = new TypeId();
                Vector3    spawnPosition = new Vector3();
                Quaternion spawnRotation = new Quaternion();

                if (createRequested)
                {
                    attachToken = packet.ReadToken();

                    prefabId      = packet.ReadPrefabId();
                    serializerId  = packet.ReadTypeId();
                    spawnPosition = packet.ReadVector3();
                    spawnRotation = packet.ReadQuaternion();
                    isSceneObject = packet.ReadBool();

                    if (isSceneObject)
                    {
                        sceneId = packet.ReadUniqueId();
                    }
                }

                Entity      entity = null;
                EntityProxy proxy  = null;

                if (createRequested && (_incommingDict.ContainsKey(networkId) == false))
                {
                    // create entity
                    if (isSceneObject)
                    {
                        GameObject go = Core.FindSceneObject(sceneId);

                        if (!go)
                        {
                            NetLog.Warn("Could not find scene object with {0}", sceneId);
                            go = Core.PrefabPool.Instantiate(prefabId, spawnPosition, spawnRotation);
                        }

                        entity = Entity.CreateFor(go, prefabId, serializerId, EntityFlags.SCENE_OBJECT);
                    }
                    else
                    {
                        GameObject go = Core.PrefabPool.LoadPrefab(prefabId);

                        // prefab checks (if applicable)
                        if (go)
                        {
                            if (Core.IsServer && !go.GetComponent <AscensionEntity>().allowInstantiateOnClient)
                            {
                                throw new AscensionException(
                                          "Received entity of prefab {0} from client at {1}, but this entity is not allowed to be instantiated from clients",
                                          go.name, connection.RemoteEndPoint);
                            }
                        }

                        NetLog.Warn("Creating instance of {0}", prefabId);
                        entity = Entity.CreateFor(prefabId, serializerId, spawnPosition, spawnRotation);
                    }

                    entity.Source    = connection;
                    entity.SceneId   = sceneId;
                    entity.NetworkId = networkId;

                    // handle case where we are given control (it needs to be true during the initialize, read and attached callbacks)
                    if (isController)
                    {
                        entity.Flags |= EntityFlags.HAS_CONTROL;
                    }

                    // initialize entity
                    entity.Initialize();

                    // create proxy
                    proxy            = entity.CreateProxy();
                    proxy.NetworkId  = networkId;
                    proxy.Connection = connection;

                    // register proxy
                    _incommingDict.Add(proxy.NetworkId, proxy);

                    // read packet
                    entity.Serializer.Read(connection, packet, packet.Frame);

                    // attach entity
                    proxy.Entity.AttachToken = attachToken;
                    proxy.Entity.Attach();

                    // assign control properly
                    if (isController)
                    {
                        proxy.Entity.Flags &= ~EntityFlags.HAS_CONTROL;
                        proxy.Entity.TakeControlInternal(controlToken);
                    }

                    // log debug info
                    NetLog.Debug("Received {0} from {1}", entity, connection);

                    // update last received frame
                    proxy.Entity.LastFrameReceived = AscensionNetwork.Frame;
                    proxy.Entity.Freeze(false);

                    // notify user
                    GlobalEventListenerBase.EntityReceivedInvoke(proxy.Entity.UnityObject);
                }
                else
                {
                    // find proxy
                    proxy = _incommingDict[networkId];

                    if (proxy == null)
                    {
                        throw new AscensionException("Couldn't find entity for {0}", networkId);
                    }

                    // update control state yes/no
                    if (proxy.Entity.HasControl ^ isController)
                    {
                        if (isController)
                        {
                            proxy.Entity.TakeControlInternal(controlToken);
                        }
                        else
                        {
                            proxy.Entity.ReleaseControlInternal(controlToken);
                        }
                    }

                    // read update
                    proxy.Entity.Serializer.Read(connection, packet, packet.Frame);
                    proxy.Entity.LastFrameReceived = AscensionNetwork.Frame;
                    proxy.Entity.Freeze(false);
                }
            }

            return(true);
        }