protected override void ClientWrite(VRage.Library.Collections.BitStream stream,EndpointId forClient, uint timestamp, int maxBitPosition)
        {
            base.ClientWrite(stream,forClient,timestamp,maxBitPosition);

            stream.Write(Entity.WorldMatrix.Translation);

            MyShipController controller = MySession.Static.ControlledEntity as MyShipController;
            stream.WriteBool(m_grid != null && controller != null);
            if (m_grid != null && controller != null)
            {
                stream.WriteBool(m_grid.IsStatic);
                if (m_grid.IsStatic == false)
                {
                    stream.WriteBool(controller != null);
                    if (controller != null)
                    {
                        stream.WriteInt64(controller.EntityId);

                        Vector2 rotation = controller.RotationIndicator;
                        stream.WriteFloat(rotation.X);
                        stream.WriteFloat(rotation.Y);

                        stream.WriteHalf(controller.RollIndicator);

                        Vector3 position = controller.MoveIndicator;
                        stream.WriteHalf(position.X);
                        stream.WriteHalf(position.Y);
                        stream.WriteHalf(position.Z);

                        Vector3D gridPosition = m_grid.PositionComp.GetPosition();
                        MyGridPhysicsStateGroup.WriteSubgrids(m_grid, stream, ref forClient, timestamp, maxBitPosition, m_lowPositionOrientation, ref gridPosition, ref m_currentSentPosition);
                    }
                }
            }
        }
        public override bool Serialize(BitStream stream, EndpointId forClient, uint timestamp, byte packetId, int maxBitPosition)
        {
            bool lowPrecisionOrientation = true;
            bool applyWhenReading = true;
            SetSupport(FindSupportDelegate());
            if (stream.Writing)
            {
                bool moving = IsMoving(Entity);
                stream.WriteBool(moving);
                SerializeVelocities(stream, Entity, MyEntityPhysicsStateGroup.EffectiveSimulationRatio, applyWhenReading, moving);
                SerializeTransform(stream, Entity, null, lowPrecisionOrientation, applyWhenReading, moving, timestamp);
            }
            else
            {
                bool moving = stream.ReadBool();
                // reading
                SerializeServerVelocities(stream, Entity, MyEntityPhysicsStateGroup.EffectiveSimulationRatio, moving, ref Entity.m_serverLinearVelocity, ref Entity.m_serverAngularVelocity);

                applyWhenReading = SerializeServerTransform(stream, Entity, null, moving, timestamp, lowPrecisionOrientation,
                    ref Entity.m_serverPosition, ref Entity.m_serverOrientation, ref Entity.m_serverWorldMatrix, m_positionValidation);

                if (applyWhenReading && moving)
                {
                    Entity.PositionComp.SetWorldMatrix(Entity.m_serverWorldMatrix, null, true);
                    Entity.SetSpeedsAccordingToServerValues();
                }
            }

            SerializeFriction(stream, Entity);
            SerializeActive(stream, Entity);

            return true;
        }
        /// <summary>
        /// Initializes a new instance of the MyMultiplayerServerBase class.
        /// </summary>
        /// <param name="localClientEndpoint">Local client endpoint (for single player or lobby host) or null (for dedicated server)</param>
        public MyMultiplayerServerBase(MySyncLayer syncLayer, EndpointId? localClientEndpoint)
            : base(syncLayer)
        {
            Debug.Assert(MyEntities.GetEntities().Count == 0, "Multiplayer server must be created before any entities are loaded!");

            var replication = new MyReplicationServer(this, () => MySandboxGame.Static.UpdateTime, localClientEndpoint);
            if (MyFakes.MULTIPLAYER_REPLICATION_TEST)
            {
                replication.MaxSleepTime = MyTimeSpan.FromSeconds(30);
            }
            SetReplicationLayer(replication);
            ClientLeft += (steamId, e) => ReplicationLayer.OnClientLeft(new EndpointId(steamId));

            MyEntities.OnEntityCreate += CreateReplicableForObject;
            MyEntityComponentBase.OnAfterAddedToContainer += CreateReplicableForObject;
            MyExternalReplicable.Destroyed += DestroyReplicable;

            foreach (var entity in MyEntities.GetEntities())
            {
                CreateReplicableForObject(entity);
                var components = entity.Components;
                if (components != null)
                {
                    foreach (var comp in components)
                        CreateReplicableForObject(comp);
                }
            }

            syncLayer.TransportLayer.Register(MyMessageId.RPC, ReplicationLayer.ProcessEvent);
            syncLayer.TransportLayer.Register(MyMessageId.REPLICATION_READY, ReplicationLayer.ReplicableReady);
            syncLayer.TransportLayer.Register(MyMessageId.CLIENT_UPDATE, ReplicationLayer.OnClientUpdate);
            syncLayer.TransportLayer.Register(MyMessageId.CLIENT_READY, (p) => ClientReady(p));
        }
 private MyEventContext(EndpointId sender, MyClientStateBase clientState, bool validate)
 {
     Sender = sender;
     ClientState = clientState;
     IsValidationRequired = validate;
     m_validationFailed = false;
 }
        protected override void ClientWrite(VRage.Library.Collections.BitStream stream, EndpointId forClient, uint timestamp, int maxBitPosition)
        {

            base.ClientWrite(stream, forClient,timestamp,maxBitPosition);

            stream.WriteBool(m_character != null);
            if (m_character != null)
            {
                var physGroup = MyExternalReplicable.FindByObject(m_character).FindStateGroup<MyCharacterPhysicsStateGroup>();
                long? supportId = null;
                if (physGroup != null)
                {
                    physGroup.SetSupport(physGroup.FindSupportDelegate());
                    supportId = physGroup.GetSupportId();
                }

                stream.WriteBool(supportId.HasValue);
                if (supportId.HasValue)
                {
                    stream.WriteInt64(supportId.Value);
                }

                Vector3 position = m_character.MoveIndicator;
                stream.WriteHalf(position.X);
                stream.WriteHalf(position.Y);
                stream.WriteHalf(position.Z);

                Vector2 rotate = m_character.RotationIndicator;
                stream.WriteFloat(rotate.X);
                stream.WriteFloat(rotate.Y);

                stream.WriteFloat(m_character.RollIndicator);

                // Movement state, 2B
                stream.WriteUInt16((ushort)m_character.GetNetworkMovementState());
                // Movement flag.
                stream.WriteUInt16((ushort)m_character.PreviousMovementFlags);

                // Flags, 6 bits
                bool hasJetpack = m_character.JetpackComp != null;
                stream.WriteBool(hasJetpack ? m_character.JetpackComp.TurnedOn : false);
                stream.WriteBool(hasJetpack ? m_character.JetpackComp.DampenersTurnedOn : false);
                stream.WriteBool(m_character.LightEnabled); // TODO: Remove
                stream.WriteBool(m_character.ZoomMode == MyZoomModeEnum.IronSight);
                stream.WriteBool(m_character.RadioBroadcaster.WantsToBeEnabled); // TODO: Remove
                stream.WriteBool(m_character.TargetFromCamera);
                stream.WriteFloat(m_character.HeadLocalXAngle);
                stream.WriteFloat(m_character.HeadLocalYAngle);

                if ((hasJetpack && m_character.JetpackComp.TurnedOn) == false)
                {
                    MatrixD matrix = m_character.WorldMatrix;
                    stream.WriteQuaternionNorm(Quaternion.CreateFromForwardUp(matrix.Forward, matrix.Up));
                }
            }        
           
        }
        public override bool Serialize(BitStream stream, EndpointId forClient,uint timeStamp, byte packetId, int maxBitPosition)
        {
            base.Serialize(stream, forClient,timeStamp, packetId, maxBitPosition);

            if (stream.Writing)
            {
                // Head and spine stuff, 36 - 152b (4.5B - 19 B)
                stream.WriteHalf(Entity.HeadLocalXAngle); // 2B
                stream.WriteHalf(Entity.HeadLocalYAngle); // 2B

                // TODO: Spine has only one angle (bending forward backward)
                // Getting EULER angles from Matrix seems good way to get it (z-component)
                stream.WriteQuaternionNormCompressedIdentity(Entity.GetAdditionalRotation(Entity.Definition.SpineBone)); // 1b / 30b
                stream.WriteQuaternionNormCompressedIdentity(Entity.GetAdditionalRotation(Entity.Definition.HeadBone)); // 1b / 30b

                // Movement state, 2B
                stream.WriteUInt16((ushort)Entity.GetCurrentMovementState());
                // Movement flag.
                stream.WriteUInt16((ushort)Entity.MovementFlags);

                // Flags, 6 bits
                bool hasJetpack = Entity.JetpackComp != null;
                stream.WriteBool(hasJetpack ? Entity.JetpackComp.TurnedOn : false);
                stream.WriteBool(hasJetpack ? Entity.JetpackComp.DampenersTurnedOn : false);
                stream.WriteBool(Entity.LightEnabled); // TODO: Remove
                stream.WriteBool(Entity.ZoomMode == MyZoomModeEnum.IronSight);
                stream.WriteBool(Entity.RadioBroadcaster.WantsToBeEnabled); // TODO: Remove
                stream.WriteBool(Entity.TargetFromCamera);

                stream.WriteNormalizedSignedVector3(Entity.MoveIndicator, 8);

                float speed = Entity.Physics.CharacterProxy != null ? Entity.Physics.CharacterProxy.Speed : 0.0f;
                stream.WriteFloat(speed);

                stream.WriteFloat(Entity.RotationIndicator.X);
                stream.WriteFloat(Entity.RotationIndicator.Y);
                stream.WriteFloat(Entity.RollIndicator);

            }
            else
            {
                Vector3 move;
                MyCharacterNetState charNetState = ReadCharacterState(stream);

                if (!IsControlledLocally && !Entity.Closed)
                {
                   Entity.SetStateFromNetwork(ref charNetState);
                }
            }
            return true;
        }
        private static void OnAskInfo()
        {
            EndpointId sender;
            if (MyEventContext.Current.IsLocallyInvoked)
                sender = new EndpointId(Sync.MyId);
            else
                sender = MyEventContext.Current.Sender;

            bool isRunning = MyMultiplayer.Static.ScenarioStartTime > DateTime.MinValue;
            bool canJoin = !isRunning || MySession.Static.Settings.CanJoinRunning;
            MyMultiplayer.RaiseStaticEvent(s => MySyncScenario.OnAnswerInfo, isRunning, canJoin, sender);

            int index = (int)MyGuiScreenScenarioMpBase.Static.TimeoutCombo.GetSelectedIndex();
            MyMultiplayer.RaiseStaticEvent(s => MySyncScenario.OnSetTimeoutClient, index, sender);

            bool canJoinRunning = MySession.Static.Settings.CanJoinRunning;
            MyMultiplayer.RaiseStaticEvent(s => MySyncScenario.OnSetJoinRunningClient, canJoinRunning, sender);
        }
        public override bool Serialize(BitStream stream, EndpointId forClient, uint timestamp, byte packetId, int maxBitPosition)
        {
            bool lowPrecisionOrientation = true;
            bool applyWhenReading = true;
            if (stream.Writing)
            {
                bool moving = IsMoving(Entity);
                stream.WriteBool(moving);
                SerializeVelocities(stream, Entity, MyEntityPhysicsStateGroup.EffectiveSimulationRatio, applyWhenReading, moving);
                SerializeTransform(stream, Entity, null, lowPrecisionOrientation, applyWhenReading, moving, timestamp);
            }
            else
            {
                bool moving = stream.ReadBool();
                // reading
                SerializeServerVelocities(stream, Entity, MyEntityPhysicsStateGroup.EffectiveSimulationRatio, moving, ref Entity.m_serverLinearVelocity, ref Entity.m_serverAngularVelocity);
                float positionTolerancy = Math.Max(Entity.PositionComp.MaximalSize * 0.1f, 0.1f);
                float smallSpeed = 0.1f;
                if (Entity.m_serverLinearVelocity == Vector3.Zero || Entity.m_serverLinearVelocity.Length() < smallSpeed)
                {
                    positionTolerancy = Math.Max(Entity.PositionComp.MaximalSize * 0.5f, 1.0f);
                }

                applyWhenReading = SerializeServerTransform(stream, Entity, null, moving, timestamp, lowPrecisionOrientation, positionTolerancy,
                    ref Entity.m_serverPosition, ref Entity.m_serverOrientation, ref Entity.m_serverWorldMatrix, m_positionValidation);

                if (applyWhenReading && moving)
                {
                    Entity.PositionComp.SetWorldMatrix(Entity.m_serverWorldMatrix, null, true);
                    Entity.SetSpeedsAccordingToServerValues();
                }
            }

            SerializeFriction(stream, Entity);
            SerializeActive(stream, Entity);

            return true;
        }
 void IReplicationServerCallback.SendServerData(BitStream stream, EndpointId endpoint)
 {
     SyncLayer.TransportLayer.SendMessage(MyMessageId.SERVER_DATA, stream, true, endpoint);
 }
        public static  bool WriteSubgrids(MyCubeGrid masterGrid, BitStream stream, ref EndpointId forClient, uint timestamp, int maxBitPosition, bool lowPrecisionOrientation,ref Vector3D basePos, ref int currentSentPosition)
        {
            bool fullyWritten = true;
            var g = MyCubeGridGroups.Static.PhysicalDynamic.GetGroup(masterGrid);
            if (g == null)
            {
                stream.WriteBool(false);
            }
            else
            {
                m_groups.Clear();
                int i = 0;
                foreach (var node in g.Nodes)
                {
                    i++;

                    if (i < currentSentPosition)
                    {
                        continue;
                    }


                    var target = MyMultiplayer.Static.ReplicationLayer.GetProxyTarget((IMyEventProxy)node.NodeData);

                    int pos = stream.BitPosition;

                    if (node.NodeData != masterGrid && node.NodeData.Physics != null && !node.NodeData.Physics.IsStatic && target != null)
                    {
                        stream.WriteBool(true);
                        // ~26.5 bytes per grid, not bad
                        NetworkId networkId = MyMultiplayer.Static.ReplicationLayer.GetNetworkIdByObject(target);
                        stream.WriteNetworkId(networkId); // ~2 bytes

                        bool moving = IsMovingSubGrid(node.NodeData);
                        stream.WriteBool(moving);

                        SerializeTransform(stream, node.NodeData, basePos, lowPrecisionOrientation, false, moving, timestamp, null, null); // 12.5 bytes
                        SerializeVelocities(stream, node.NodeData, EffectiveSimulationRatio, false, moving); // 12 byte
                        UpdateGridMaxSpeed(node.NodeData, Sync.IsServer);
                        m_groups.Add(node.NodeData);

                        currentSentPosition++;
                    }

                    if (stream.BitPosition > maxBitPosition)
                    {
                        stream.SetBitPositionWrite(pos);
                        fullyWritten = false;
                        currentSentPosition--;
                        break;
                    }

                    if (i == g.Nodes.Count)
                    {
                        currentSentPosition = 0;
                    }
                }

                stream.WriteBool(false);
            }
            return fullyWritten;
        }
        public bool Serialize(VRage.Library.Collections.BitStream stream, EndpointId forClient, uint timestamp, byte packetId, int maxBitPosition)
        {
            if (stream.Writing)
            {
                if (Sync.IsServer)
                {
                    ServerWrite(stream, forClient.Value);
                }
                else
                {
                    ClientWrite(stream, forClient, timestamp,maxBitPosition);
                }
            }
            else
            {
                if (Sync.IsServer)
                {
                    ServerRead(stream, forClient.Value,timestamp);
                }
                else
                {
                    ClientRead(stream);
                }
            }

            return true;
        }
        static void OnRespawnRequest(RespawnMsg msg)
        {
            EndpointId sender;
            if (MyEventContext.Current.IsLocallyInvoked)
                sender = new EndpointId(Sync.MyId);
            else
                sender = MyEventContext.Current.Sender;

            Debug.Assert(Sync.IsServer, "This method can only be called on the server!");
            Debug.Assert(Sync.Players.RespawnComponent != null, "The respawn component is not set! Cannot handle respawn request!");
            if (Sync.Players.RespawnComponent == null)
            {
                return;
            }

            PlayerId playerId = new PlayerId(sender.Value, msg.PlayerSerialId);

            bool respawnSuccessful = Sync.Players.RespawnComponent.HandleRespawnRequest(
                msg.JoinGame,
                msg.NewIdentity,
                msg.RespawnEntityId,
                msg.RespawnShipId,
                playerId,
                msg.SpawnPosition,
                msg.BotDefinitionId
            );

            if (respawnSuccessful)
            {
                MyIdentity identity = Sync.Players.TryGetPlayerIdentity(playerId);
                Debug.Assert(identity != null, "Could not find identity of respawning player!");
                if (identity != null && !identity.FirstSpawnDone)
                {
                    MyMultiplayer.RaiseStaticEvent(s => MyPlayerCollection.OnIdentityFirstSpawn, identity.IdentityId);
                    identity.PerformFirstSpawn();
                }
            }
            else
            {
                if (MyEventContext.Current.IsLocallyInvoked)
                    OnRespawnRequestFailure(msg);
                else
                    MyMultiplayer.RaiseStaticEvent(s => MyPlayerCollection.OnRespawnRequestFailure, msg, sender);
            }
        }
 internal override bool DispatchBlockingEvent(BitStream stream, CallSite site, EndpointId recipient, IMyNetObject eventInstance, IMyNetObject blockedNetObj, float unreliablePriority)
 {
     Debug.Fail("Client should not call blocking events");
     // For client this code is old. Only server can dispatch blocking events.
     return DispatchEvent(stream, site, recipient, eventInstance, unreliablePriority);
 }
Exemple #14
0
        protected virtual void ProcessEvent(BitStream stream, NetworkId networkId, NetworkId blockedNetId, uint eventId, EndpointId sender)
        {
            CallSite     site;
            IMyNetObject sendAs;
            object       obj;

            if (networkId.IsInvalid) // Static event
            {
                site   = m_typeTable.StaticEventTable.Get(eventId);
                sendAs = null;
                obj    = null;
            }
            else // Instance event
            {
                sendAs = GetObjectByNetworkId(networkId);
                if (sendAs == null)
                {
                    return;
                }
                var typeInfo   = m_typeTable.Get(sendAs.GetType());
                int eventCount = typeInfo.EventTable.Count;
                if (eventId < eventCount) // Directly
                {
                    obj  = sendAs;
                    site = typeInfo.EventTable.Get(eventId);
                }
                else // Through proxy
                {
                    obj      = ((IMyProxyTarget)sendAs).Target;
                    typeInfo = m_typeTable.Get(obj.GetType());
                    site     = typeInfo.EventTable.Get(eventId - (uint)eventCount); // Subtract max id of Proxy
                    Debug.Assert(object.ReferenceEquals(GetProxyTarget(((IMyProxyTarget)sendAs).Target), sendAs), "There must be one-to-one relationship between IMyEventProxy and IMyEventTarget. Proxy.EventTarget.Target == Proxy");
                }
            }

            ProcessEvent(stream, site, obj, sendAs, sender);
        }
Exemple #15
0
 public void RaiseEvent <T1, T2, T3, T4, T5>(T1 arg1, T5 arg5, Func <T1, Action <T2, T3, T4> > action, T2 arg2, T3 arg3, T4 arg4, EndpointId endpointId = default(EndpointId), float unreliablePriority = 1)
     where T1 : IMyEventOwner
     where T5 : IMyEventOwner
 {
     DispatchEvent(GetCallSite(action, arg1), endpointId, unreliablePriority, ref arg1, ref arg2, ref arg3, ref arg4, ref e, ref e, ref e, ref arg5);
 }
Exemple #16
0
 public void RaiseEvent <T1, T2>(T1 arg1, T2 arg2, Func <T1, Action> action, EndpointId endpointId = default(EndpointId), float unreliablePriority = 1)
     where T1 : IMyEventOwner
     where T2 : IMyEventOwner
 {
     DispatchEvent(GetCallSite(action, arg1), endpointId, unreliablePriority, ref arg1, ref e, ref e, ref e, ref e, ref e, ref e, ref arg2);
 }
Exemple #17
0
 protected static bool ShouldServerInvokeLocally(CallSite site, EndpointId?localClientEndpoint, EndpointId recipient)
 {
     // Invoke locally when:
     // A) Has server flag
     // B) Has client flag and recipient is serverEndpoint and server is also client (e.g. single player, normal server)
     // C) Has broadcast flag and recipient is serverEndpoint and server is also client (e.g. single player, normal server)
     return(site.HasServerFlag || (localClientEndpoint.HasValue && recipient == localClientEndpoint.Value && (site.HasClientFlag || site.HasBroadcastFlag)));
 }
Exemple #18
0
 protected abstract void DispatchEvent <T1, T2, T3, T4, T5, T6, T7, T8>(CallSite callSite, EndpointId recipient, float unreliablePriority, ref T1 arg1, ref T2 arg2, ref T3 arg3, ref T4 arg4, ref T5 arg5, ref T6 arg6, ref T7 arg7, ref T8 arg8)
     where T1 : IMyEventOwner
     where T8 : IMyEventOwner;
Exemple #19
0
 public void RaiseEvent <T1, T2, T3, T4, T5, T6, T7, T8>(T1 arg1, T8 arg8, Func <T1, Action <T2, T3, T4, T5, T6, T7> > action, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, EndpointId endpointId = default(EndpointId), float unreliablePriority = 1)
     where T1 : IMyEventOwner
     where T8 : IMyEventOwner
 {
     DispatchEvent(GetCallSite(action, arg1), endpointId, unreliablePriority, ref arg1, ref arg2, ref arg3, ref arg4, ref arg5, ref arg6, ref arg7, ref arg8);
 }
 public MyReplicationSingle(EndpointId localEndpoint)
 {
     Debug.Assert(localEndpoint.IsValid, "localEndpoint even for singleplayer cannot be zero!");
     m_localEndpoint = localEndpoint;
 }
Exemple #21
0
 public virtual void SetPriorityMultiplier(EndpointId id, float priority)
 {
 }
Exemple #22
0
 /// <summary>
 /// Called when event is received over network.
 /// Event can be validated, invoked and/or transferred to other peers.
 /// </summary>
 internal abstract void ProcessEvent(BitStream stream, CallSite site, object obj, IMyNetObject sendAs, EndpointId source);
 internal override bool DispatchBlockingEvent(BitStream stream, CallSite site, EndpointId recipient, IMyNetObject eventInstance, IMyNetObject blockedNetObj, float unreliablePriority)
 {
     Debug.Fail("Client should not call blocking events");
     // For client this code is old. Only server can dispatch blocking events.
     return(DispatchEvent(stream, site, recipient, eventInstance, unreliablePriority));
 }
Exemple #24
0
        public virtual bool Serialize(BitStream stream, EndpointId forClient,uint timestamp, byte packetId, int maxBitPosition)
        {
            bool moving = false;
            if (stream.Writing)
            {
                moving = IsMoving(Entity);
                stream.WriteBool(moving);
            }
            else
            {
                moving = stream.ReadBool();
            }

            // When controlled by local player, don't apply what came from server
            SerializeTransform(stream, Entity, null, m_lowPrecisionOrientation, !IsControlledLocally, moving, timestamp, null, MoveHandler);
            SerializeVelocities(stream, Entity, EffectiveSimulationRatio, !IsControlledLocally, moving,VelocityHandler);

            return true;
        }
        protected override void ProcessEvent(BitStream stream, NetworkId networkId, NetworkId blockedNetId, uint eventId, EndpointId sender)
        {
            LastMessageFromServer = DateTime.UtcNow;
            // Check if any of them is not blocked already.
            bool anyContainsEvents = m_eventBuffer.ContainsEvents(networkId) || m_eventBuffer.ContainsEvents(blockedNetId);

            if (this.IsBlocked(networkId, blockedNetId) || anyContainsEvents)
            {
                m_eventBuffer.EnqueueEvent(stream, networkId, blockedNetId, eventId, sender);
                // Only enqueue barrier if blocking network id is set
                if (blockedNetId.IsValid)
                {
                    m_eventBuffer.EnqueueBarrier(blockedNetId, networkId);
                }
            }
            else
            {
                base.ProcessEvent(stream, networkId, blockedNetId, eventId, sender);
            }
        }
        protected override void ProcessEvent(BitStream stream, NetworkId networkId, NetworkId blockedNetId, uint eventId, EndpointId sender)
        {
            LastMessageFromServer = DateTime.UtcNow;
            // Check if any of them is not blocked already.
            bool anyContainsEvents = m_eventBuffer.ContainsEvents(networkId) || m_eventBuffer.ContainsEvents(blockedNetId);

            if (this.IsBlocked(networkId, blockedNetId) || anyContainsEvents)
            {
                m_eventBuffer.EnqueueEvent(stream, networkId, blockedNetId, eventId, sender);
                // Only enqueue barrier if blocking network id is set
                if(blockedNetId.IsValid)
                    m_eventBuffer.EnqueueBarrier(blockedNetId, networkId);
            }
            else
            {
                base.ProcessEvent(stream, networkId, blockedNetId, eventId, sender);
            }
        }
 internal override void ProcessEvent(BitStream stream, CallSite site, object obj, IMyNetObject sendAs, EndpointId source)
 {
     LastMessageFromServer = DateTime.UtcNow;
     // Client blindly invokes everything received from server (without validation)
     Invoke(site, stream, obj, source, null, false);
 }
        public bool Serialize(BitStream stream, EndpointId forClient, uint timestamp, byte packetId, int maxBitPosition)
        {
            if (stream.Writing)
            {
                InventoryClientData clientData = m_clientInventoryUpdate[forClient.Value];
                bool needsSplit = false;
                if (clientData.FailedIncompletePackets.Count > 0)
                {
                    InventoryDeltaInformation failedPacket = clientData.FailedIncompletePackets[0];
                    clientData.FailedIncompletePackets.RemoveAtFast(0);

                    InventoryDeltaInformation reSendPacket = WriteInventory(ref failedPacket, stream, packetId, maxBitPosition, out needsSplit);
                    
                    if (needsSplit)
                    {
                        //resend split doesnt generate new id becaose it was part of allreadt sent message
                        clientData.FailedIncompletePackets.Add(CreateSplit(ref failedPacket, ref reSendPacket));
                    }

                    if (reSendPacket.HasChanges)
                    {
                        clientData.SendPackets[packetId] = reSendPacket;
                    }
                }
                else
                {   
                    InventoryDeltaInformation difference  = CalculateInventoryDiff(ref clientData);
                    difference.MessageId = clientData.CurrentMessageId;

                    clientData.MainSendingInfo = WriteInventory(ref difference, stream, packetId, maxBitPosition,out needsSplit);
                    if (needsSplit)
                    {
                        //split generate new id becaose its different message 
                        clientData.CurrentMessageId++;
                        InventoryDeltaInformation split = CreateSplit(ref difference, ref clientData.MainSendingInfo);
                        split.MessageId = clientData.CurrentMessageId;
                        clientData.FailedIncompletePackets.Add(split);
                    }

                    if (clientData.MainSendingInfo.HasChanges)
                    {
                        clientData.SendPackets[packetId] = clientData.MainSendingInfo;
                        clientData.CurrentMessageId++;
                    }

                    clientData.Dirty = false;
                }
            }
            else
            {
                ReadInventory(stream);
            }

            return true;
        }
 protected virtual MyClientStateBase GetClientData(EndpointId endpointId)
 {
     return(null);
 }
 protected virtual void ClientWrite(VRage.Library.Collections.BitStream stream, EndpointId forClient, uint timestamp, int maxBitPosition)
 {
     MatrixD matrix = Entity.WorldMatrix;
     stream.WriteQuaternionNorm(Quaternion.CreateFromForwardUp(matrix.Forward, matrix.Up));
     stream.Write(matrix.Translation);
 }
 void IReplicationServerCallback.SendReplicationDestroy(BitStream stream, EndpointId endpoint)
 {
     SyncLayer.TransportLayer.SendMessage(MyMessageId.REPLICATION_DESTROY, stream, true, endpoint);
 }
        public override bool Serialize(BitStream stream, EndpointId forClient,uint timestamp, byte packetId, int maxBitPosition)
        {
            // Client does not care about slave grids, he always synced group through controlled object
            Debug.Assert(stream.Reading || !Sync.IsServer || Entity == GetMasterGrid(Entity), "Writing data from SlaveGrid!");

            bool apply = !IsControlledLocally;

            bool moving = false;
            if (stream.Writing)
            {
                moving = IsMoving(Entity);
                stream.WriteBool(moving);
            }
            else
            {
                moving = stream.ReadBool();
            }


            // Serialize this grid
            apply = SerializeTransform(stream, Entity, null, m_lowPrecisionOrientation, apply,moving, timestamp, m_positionValidation, MoveHandler);
            SerializeVelocities(stream, Entity, EffectiveSimulationRatio, apply, moving,VelocityHandler);

     
            // Serialize other grids in group
            Vector3D basePos = Entity.WorldMatrix.Translation;
            if (stream.Writing)
            {
 
                UpdateGridMaxSpeed(Entity, Sync.IsServer);

                bool fullyWritten = WriteSubgrids(Entity,stream, ref forClient, timestamp, maxBitPosition,m_lowPrecisionOrientation, ref basePos, ref m_currentSentPosition);

                stream.WriteBool(fullyWritten);

                if (fullyWritten)
                {
                    SerializeRopeData(stream, apply, gridsGroup: m_groups);
                }
                return fullyWritten;

            }
            else
            {
                UpdateGridMaxSpeed(Entity, !Sync.IsServer);

                ReadSubGrids(stream, timestamp, apply,m_lowPrecisionOrientation, ref basePos);

                if (stream.ReadBool())
                {
                    SerializeRopeData(stream, apply);
                }
            }
            return true;
        }
 void IReplicationServerCallback.SendEvent(BitStream stream, bool reliable, EndpointId endpoint)
 {
     SyncLayer.TransportLayer.SendMessage(MyMessageId.RPC, stream, reliable, endpoint);
 }
        protected override void ClientWrite(VRage.Library.Collections.BitStream stream, EndpointId forClient, uint timestamp, int maxBitPosition)
        {
            base.ClientWrite(stream, forClient,timestamp,maxBitPosition);

            stream.WriteBool(m_character != null);
            if (m_character != null)
            {

                stream.WriteBool(m_supportPhysics != null);
                if (m_supportPhysics != null)
                {
                    stream.WriteInt64(m_supportPhysics.Entity.EntityId);
                    stream.Write(m_supportPhysics.Entity.PositionComp.GetPosition());
                }
                
                Vector3 position = m_character.MoveIndicator;
                stream.WriteHalf(position.X);
                stream.WriteHalf(position.Y);
                stream.WriteHalf(position.Z);

                Vector2 rotate = m_character.RotationIndicator;
                stream.WriteFloat(rotate.X);
                stream.WriteFloat(rotate.Y);

                stream.WriteFloat(m_character.RollIndicator);

                // Movement state, 2B
                stream.WriteUInt16((ushort)m_character.GetNetworkMovementState());
                // Movement flag.
                stream.WriteUInt16((ushort)m_character.PreviousMovementFlags);

                // Flags, 6 bits
                bool hasJetpack = m_character.JetpackComp != null;
                stream.WriteBool(hasJetpack ? m_character.JetpackComp.TurnedOn : false);
                stream.WriteBool(hasJetpack ? m_character.JetpackComp.DampenersTurnedOn : false);
                stream.WriteBool(m_character.LightEnabled); // TODO: Remove
                stream.WriteBool(m_character.ZoomMode == MyZoomModeEnum.IronSight);
                stream.WriteBool(m_character.RadioBroadcaster.WantsToBeEnabled); // TODO: Remove
                stream.WriteBool(m_character.TargetFromCamera);
                stream.WriteFloat(m_character.HeadLocalXAngle);
                stream.WriteFloat(m_character.HeadLocalYAngle);
            }        
           
        }
Exemple #35
0
        protected sealed override void DispatchEvent <T1, T2, T3, T4, T5, T6, T7, T8>(CallSite callSite, EndpointId recipient, float unreliablePriority, ref T1 arg1, ref T2 arg2, ref T3 arg3, ref T4 arg4, ref T5 arg5, ref T6 arg6, ref T7 arg7, ref T8 arg8)
        {
            IMyNetObject sendAs;
            NetworkId    networkId;
            uint         sendId = callSite.Id;

            if (callSite.MethodInfo.IsStatic)
            {
                Debug.Assert(arg1 == null, "First argument (the instance on which is event invoked) should be null for static events");
                sendAs    = null;
                networkId = NetworkId.Invalid;
            }
            else if (arg1 == null)
            {
                throw new InvalidOperationException("First argument (the instance on which is event invoked) cannot be null for non-static events");
            }
            else if (arg1 is IMyEventProxy)
            {
                sendAs = GetProxyTarget((IMyEventProxy)arg1);

                if (sendAs == null)
                {
                    string msg = "Raising event on object which is not recognized by replication: " + arg1;
                    Debug.Fail(msg);
                    MyLog.Default.WriteLine(msg);
                    return;
                }

                sendId   += (uint)m_typeTable.Get(sendAs.GetType()).EventTable.Count; // Add max id of Proxy
                networkId = GetNetworkIdByObject(sendAs);
                Debug.Assert(object.ReferenceEquals(GetProxyTarget(((IMyProxyTarget)sendAs).Target), sendAs), "There must be one-to-one relationship between IMyEventProxy and IMyEventTarget. Proxy.EventTarget.Target == Proxy");
            }
            else if (arg1 is IMyNetObject)
            {
                sendAs    = (IMyNetObject)arg1;
                networkId = GetNetworkIdByObject(sendAs);
            }
            else
            {
                throw new InvalidOperationException("Instance events may be called only on IMyNetObject or IMyEventProxy");
            }

            NetworkId    blockingNetworkId = NetworkId.Invalid;
            IMyNetObject blockedNetObj     = null;

            if (arg8 is IMyEventProxy && callSite.IsBlocking)
            {
                blockedNetObj     = GetProxyTarget((IMyEventProxy)arg8);
                blockingNetworkId = GetNetworkIdByObject(blockedNetObj);
            }
            else if (arg8 is IMyEventProxy && !callSite.IsBlocking)
            {
                throw new InvalidOperationException("Rising blocking event but event itself does not have Blocking attribute");
            }
            else if (!(arg8 is IMyEventProxy) && callSite.IsBlocking)
            {
                throw new InvalidOperationException("Event contain Blocking attribute but blocked event proxy is not set or raised event is not blocking one");
            }

            Debug.Assert(sendId <= 255, "Max 256 events are supported per hierarchy");

            m_sendStreamEvent.ResetWrite();
            m_sendStreamEvent.WriteNetworkId(networkId);
            m_sendStreamEvent.WriteNetworkId(blockingNetworkId);
            m_sendStreamEvent.WriteByte((byte)sendId); // TODO: Compress eventId to necessary number of bits

            var site = (CallSite <T1, T2, T3, T4, T5, T6, T7>)callSite;

            using (MySerializerNetObject.Using(this))
            {
                site.Serializer(arg1, m_sendStreamEvent, ref arg2, ref arg3, ref arg4, ref arg5, ref arg6, ref arg7);
            }

            bool dispatchRes = false;

            // If blocking event, than process a little differently. (Internally it will call DispatchEvent anyway)
            if (!blockingNetworkId.IsInvalid)
            {
                dispatchRes = DispatchBlockingEvent(m_sendStreamEvent, callSite, recipient, sendAs, blockedNetObj, unreliablePriority);
            }
            else
            {
                dispatchRes = DispatchEvent(m_sendStreamEvent, callSite, recipient, sendAs, unreliablePriority);
            }

            if (dispatchRes)
            {
                InvokeLocally(site, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
            }
        }
 void IReplicationServerCallback.SendReplicationCreateStreamed(BitStream stream, EndpointId endpoint)
 {
     SyncLayer.TransportLayer.SendMessage(MyMessageId.REPLICATION_STREAM_BEGIN, stream, true, endpoint);
 }
 protected override void DispatchEvent <T1, T2, T3, T4, T5, T6, T7, T8>(CallSite callSite, EndpointId recipient, float unreliablePriority, ref T1 arg1, ref T2 arg2, ref T3 arg3, ref T4 arg4, ref T5 arg5, ref T6 arg6, ref T7 arg7, ref T8 arg8)
 {
     // Invoke locally when it's server method or client/broadcast method and target is my EndpointId
     if (ShouldServerInvokeLocally(callSite, m_localEndpoint, recipient))
     {
         var site = (CallSite <T1, T2, T3, T4, T5, T6, T7>)callSite;
         InvokeLocally(site, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
     }
 }
 void IReplicationServerCallback.SendStateSync(BitStream stream, EndpointId endpoint,bool reliable)
 {
     SyncLayer.TransportLayer.SendMessage(MyMessageId.SERVER_STATE_SYNC, stream, reliable, endpoint);
 }
        internal override bool DispatchEvent(BitStream stream, CallSite site, EndpointId target, IMyNetObject instance, float unreliablePriority)
        {
            Debug.Assert(site.HasServerFlag, String.Format("Event '{0}' does not have server flag, it can't be invoked on server!", site));

            if (site.HasServerFlag)
            {
                m_callback.SendEvent(stream, site.IsReliable);
                //Client.SendMessageToServer(stream, site.Reliability, PacketPriorityEnum.LOW_PRIORITY, MyChannelEnum.Replication);
            }
            else if (site.HasClientFlag)
            {
                // Invoke locally only when it has ClientFlag and no ServerFlag
                return true;
            }
            return false;
        }
 int IReplicationServerCallback.GetMTRSize(EndpointId clientId)
 {
     // Steam has MTU 1200, one byte is used by transport layer to write message id
     return 1024*1024 - 1;
 }
 internal override void ProcessEvent(BitStream stream, CallSite site, object obj, IMyNetObject sendAs, EndpointId source)
 {
     // Client blindly invokes everything received from server (without validation)
     Invoke(site, stream, obj, source, null, false);
 }
        public override bool Serialize(BitStream stream, EndpointId forClient,uint timestamp, byte packetId, int maxBitPosition)
        {
            // Client does not care about slave grids, he always synced group through controlled object
            Debug.Assert(stream.Reading || !Sync.IsServer || Entity == GetMasterGrid(Entity), "Writing data from SlaveGrid!");

            bool apply = !IsControlledLocally;

            bool moving = false;
            if (stream.Writing)
            {
                moving = IsMoving(Entity);
                stream.WriteBool(moving);
            }
            else
            {
                moving = stream.ReadBool();
            }


            // Serialize this grid
            apply = SerializeTransform(stream, Entity, null, m_lowPrecisionOrientation, apply,moving, timestamp, m_positionValidation, MoveHandler);
            SerializeVelocities(stream, Entity, EffectiveSimulationRatio, apply, moving,VelocityHandler);

     
            // Serialize other grids in group
            Vector3D basePos = Entity.WorldMatrix.Translation;
            if (stream.Writing)
            {
                bool fullyWritten = true;
                UpdateGridMaxSpeed(Entity, Sync.IsServer);
                var g = MyCubeGridGroups.Static.PhysicalDynamic.GetGroup(Entity);
                if (g == null)
                {
                    stream.WriteBool(false);
                }
                else
                {
                    m_groups.Clear();
                    int i = 0;
                    foreach (var node in g.Nodes)
                    {                        
                        i++;
                        if (ResponsibleForUpdate(node.NodeData, forClient))
                        {
                            continue;
                        } 

                        if(i < m_currentSentPosition)
                        {
                            continue;
                        }


                        var target = MyMultiplayer.Static.ReplicationLayer.GetProxyTarget((IMyEventProxy)node.NodeData);
                        
                        int pos = stream.BitPosition;

                        if (node.NodeData != Entity && !node.NodeData.IsStatic && target != null)
                        {                 
                            stream.WriteBool(true);
                            // ~26.5 bytes per grid, not bad
                            NetworkId networkId = MyMultiplayer.Static.ReplicationLayer.GetNetworkIdByObject(target);
                            stream.WriteNetworkId(networkId); // ~2 bytes
             
                            moving = IsMoving(node.NodeData);
                            stream.WriteBool(moving);

                            SerializeTransform(stream, node.NodeData, basePos, m_lowPrecisionOrientation, apply, moving, timestamp, null, null); // 12.5 bytes
                            SerializeVelocities(stream, node.NodeData, EffectiveSimulationRatio, apply, moving); // 12 byte
                            UpdateGridMaxSpeed(node.NodeData, Sync.IsServer);
                            m_groups.Add(node.NodeData);

                            m_currentSentPosition++;
                        }

                        if (stream.BitPosition > maxBitPosition)
                        {
                            stream.SetBitPositionWrite(pos);
                            fullyWritten = false;
                            m_currentSentPosition--;
                            break;
                        }

                        if (i == g.Nodes.Count)
                        {
                            m_currentSentPosition = 0;
                        }
                    }

                    stream.WriteBool(false);
                }

                stream.WriteBool(fullyWritten);

                if (fullyWritten)
                {
                    SerializeRopeData(stream, apply, gridsGroup: m_groups);
                }
                return fullyWritten;

            }
            else
            {
                UpdateGridMaxSpeed(Entity, !Sync.IsServer);

                while (stream.ReadBool())
                {               
                    NetworkId networkId = stream.ReadNetworkId(); // ~2 bytes
                    MyCubeGridReplicable replicable = MyMultiplayer.Static.ReplicationLayer.GetObjectByNetworkId(networkId) as MyCubeGridReplicable;
                    MyCubeGrid grid = replicable != null ? replicable.Grid : null;

                    moving = stream.ReadBool();
                    SerializeTransform(stream, grid, basePos, m_lowPrecisionOrientation, apply && grid != null, moving, timestamp, null, null); // 12.5 bytes
                    SerializeVelocities(stream, grid, EffectiveSimulationRatio, apply && grid != null, moving); // 12 bytes
                   
                    UpdateGridMaxSpeed(grid,!Sync.IsServer);
                }

                if (stream.ReadBool())
                {
                    SerializeRopeData(stream, apply);
                }
            }
            return true;
        }
Exemple #43
0
 internal abstract bool DispatchBlockingEvent(BitStream stream, CallSite site, EndpointId recipient, IMyNetObject eventInstance, IMyNetObject blockedNetObject, float unreliablePriority);
 protected override void ProcessEvent(BitStream stream, NetworkId networkId, uint eventId, EndpointId sender)
 {
     if (networkId.IsValid && m_pendingReplicables.ContainsKey(networkId))
     {
         m_eventBuffer.EnqueueEvent(stream, networkId, eventId, sender);
     }
     else
     {
         base.ProcessEvent(stream, networkId, eventId, sender);
     }
 }
Exemple #45
0
        public static bool ResponsibleForUpdate(MyEntity entity,EndpointId endpointId)
        {
            if (Sync.Players == null)
                return false;

            var controllingPlayer = Sync.Players.GetControllingPlayer(entity);
            if (controllingPlayer == null)
            {
                // TODO: Move to subclass?
                var character = entity as MyCharacter;
                if (character != null && character.CurrentRemoteControl != null)
                {
                    controllingPlayer = Sync.Players.GetControllingPlayer(character.CurrentRemoteControl as MyEntity);
                }
            }

            if (controllingPlayer == null)
            {
                // IsGameServer
                return endpointId.Value == Sync.ServerId;
            }
            else
            {
                return controllingPlayer.Client.SteamUserId == endpointId.Value;
            }
        }
        public void EnqueueEvent(BitStream stream, NetworkId objectInstance, uint eventId, EndpointId sender)
        {
            int requiredByteSize = stream.ByteLength - stream.BytePosition + 1;

            var e = ObtainEvent();
            e.Stream.ResetWrite();
            e.Stream.WriteBitStream(stream);
            e.Stream.ResetRead();
            e.ObjectInstance = objectInstance;
            e.EventId = eventId;
            e.Sender = sender;

            List<BufferedEvent> events;
            if (!m_buffer.TryGetValue(objectInstance, out events))
            {
                events = ObtainList();
                m_buffer.Add(objectInstance, events);
            }
            events.Add(e);
        }
Exemple #47
0
 public static Token Set(EndpointId endpoint, MyClientStateBase client, bool validate)
 {
     return(new Token(new MyEventContext(endpoint, client, validate)));
 }