Esempio n. 1
0
        public bool CanSpawnMoreBots(MyPlayer.PlayerId pid)
        {
            if (!Sync.IsServer)
            {
                return(false);
            }
            if (MyFakes.DEVELOPMENT_PRESET)
            {
                return(true);
            }
            if (Sync.MyId == pid.SteamId)
            {
                AgentSpawnData data = new AgentSpawnData();
                return(this.m_agentsToSpawn.TryGetValue(pid.SerialId, out data) && (!data.CreatedByPlayer ? (this.Bots.GetGeneratedBotCount() < BotFactory.MaximumUncontrolledBotCount) : (this.Bots.GetCreatedBotCount() < BotFactory.MaximumBotPerPlayer)));
            }
            int   num     = 0;
            ulong steamId = pid.SteamId;

            foreach (MyPlayer player in Sync.Players.GetOnlinePlayers())
            {
                if (player.Id.SteamId != steamId)
                {
                    continue;
                }
                if (player.Id.SerialId != 0)
                {
                    num++;
                }
            }
            return(num < BotFactory.MaximumBotPerPlayer);
        }
Esempio n. 2
0
        public MyMissionTriggers TryCreateFromDefault(MyPlayer.PlayerId newId, bool overwrite = false)
        {
            MyMissionTriggers source;

            if (overwrite)
            {
                MissionTriggers.Remove(newId);
            }
            else
            if (MissionTriggers.TryGetValue(newId, out source)) //(MissionTriggers.ContainsKey(newId))
            {
                return(source);                                 //already exists, thats ok for us
            }
            MyMissionTriggers mtrig = new MyMissionTriggers();

            MissionTriggers.Add(newId, mtrig);

            MissionTriggers.TryGetValue(MyMissionTriggers.DefaultPlayerId, out source);
            if (source == null)
            {
                //older save which does not have defaults set
                source = new MyMissionTriggers();
                MySessionComponentMissionTriggers.Static.MissionTriggers.Add(MyMissionTriggers.DefaultPlayerId, source);
            }
            mtrig.CopyTriggersFrom(source);
            m_someoneWon = false;
            return(mtrig);
        }
Esempio n. 3
0
        private static void OnControlPilotMsg(MySyncCryoChamber syncObject, ref ControlPilotMsg msg, World.MyNetworkClient sender)
        {
            var playerId = new MyPlayer.PlayerId(msg.SteamId, msg.SerialId);
            var player = Sync.Players.TryGetPlayerById(playerId);

            var cryoChamber = syncObject.Entity as MyCryoChamber;

            if (player != null)
            {
                if (cryoChamber.Pilot != null)
                {
                    if (player == MySession.LocalHumanPlayer)
                    {
                        cryoChamber.OnPlayerLoaded();

                        if (MySession.Static.CameraController != cryoChamber)
                        {
                            MySession.SetCameraController(MyCameraControllerEnum.Entity, cryoChamber);
                        }
                    }
                 
                    player.Controller.TakeControl(cryoChamber);
                    player.Identity.ChangeCharacter(cryoChamber.Pilot);
                }
                else
                {
                    Debug.Fail("Selected cryo chamber doesn't have a pilot!");
                }
            }
            else
            {
                Debug.Fail("Failed to find player to put in cryo chamber!");
            }
        }
Esempio n. 4
0
        public bool Update(MyPlayer.PlayerId Id, MyEntity entity) //returns if lost
        {
            //MySessionComponentMission.Static.TryCreateFromDefault(Id);

            if (IsLocal(Id))
            {
                UpdateLocal(Id);
            }

            if (!Sync.IsServer)
            {
                return(false);
            }

            MyMissionTriggers mtrig;

            if (!MissionTriggers.TryGetValue(Id, out mtrig))
            {
                //Debug.Assert(false,"Bad ID for update in missionTriggers");
                mtrig = TryCreateFromDefault(Id, false);
            }
            mtrig.UpdateWin(Id, entity);
            if (!mtrig.Won)
            {
                mtrig.UpdateLose(Id, entity);
            }
            else
            {
                m_someoneWon = true;
            }
            return(mtrig.Lost);
        }
Esempio n. 5
0
        public void TryCreateFromDefault(MyPlayer.PlayerId newId, bool overwrite = false)
        {
            if (overwrite)
            {
                MissionTriggers.Remove(newId);
            }
            else
            if (MissionTriggers.ContainsKey(newId))
            {
                return;    //already exists, thats ok for us
            }
            MyMissionTriggers mtrig = new MyMissionTriggers();

            MissionTriggers.Add(newId, mtrig);

            MyMissionTriggers source;

            MissionTriggers.TryGetValue(MyMissionTriggers.DefaultPlayerId, out source);
            if (source == null)
            {
                //older save which does not have defaults set
                return;
            }
            mtrig.CopyTriggersFrom(source);
        }
Esempio n. 6
0
 private void AttachedPlayerChanged()
 {
     if (this.m_attachedPlayerId.Value != null)
     {
         MyPlayer.PlayerId id         = new MyPlayer.PlayerId(this.m_attachedPlayerId.Value.Value.SteamId, this.m_attachedPlayerId.Value.Value.SerialId);
         MyPlayer          playerById = Sync.Players.GetPlayerById(id);
         if (playerById == null)
         {
             this.m_retryAttachPilot = true;
         }
         else if (this.Pilot == null)
         {
             MyPlayer localHumanPlayer = MySession.Static.LocalHumanPlayer;
             MyPlayer player2          = playerById;
         }
         else
         {
             if (ReferenceEquals(playerById, MySession.Static.LocalHumanPlayer))
             {
                 this.OnPlayerLoaded();
                 if (!ReferenceEquals(MySession.Static.CameraController, this))
                 {
                     Vector3D?position = null;
                     MySession.Static.SetCameraController(MyCameraControllerEnum.Entity, this, position);
                 }
             }
             playerById.Controller.TakeControl(this);
             playerById.Identity.ChangeCharacter(this.Pilot);
         }
     }
 }
Esempio n. 7
0
        private void MotdOnce(IPlayer player)
        {
            //TODO: REMOVE ALL THIS TRASH!
            //implement a PlayerSpawned event in Torch. This will work for now.
            Task.Run(() =>
            {
                var start   = DateTime.Now;
                var timeout = TimeSpan.FromMinutes(5);
                var pid     = new MyPlayer.PlayerId(player.SteamId, 0);
                while (DateTime.Now - start <= timeout)
                {
                    if (!MySession.Static.Players.TryGetPlayerById(pid, out MyPlayer p) || p.Character == null)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }

                    Torch.Invoke(() =>
                    {
                        if (_motdOnce.Contains(player.SteamId))
                        {
                            return;
                        }

                        SendMotd(p, true);
                        _motdOnce.Add(player.SteamId);
                    });
                    break;
                }
            });
        }
        public void InitFromCheckpoint(MyObjectBuilder_Checkpoint checkpoint)
        {
            var cooldowns = checkpoint.RespawnCooldowns;

            m_lastUpdate = MySandboxGame.TotalGamePlayTimeInMilliseconds;
            m_globalRespawnTimesMs.Clear();

            if (cooldowns == null)
            {
                return;
            }

            foreach (var item in cooldowns)
            {
                var controllerId = new MyPlayer.PlayerId()
                {
                    SteamId = item.PlayerSteamId, SerialId = item.PlayerSerialId
                };
                var key = new RespawnKey()
                {
                    ControllerId = controllerId, RespawnShipId = item.RespawnShipId
                };
                m_globalRespawnTimesMs.Add(key, item.Cooldown + m_lastUpdate, immediate: true);
            }
        }
Esempio n. 9
0
 private void PlayerCreated(MyPlayer.PlayerId playerId)
 {
     if ((Sync.Players.GetPlayerById(playerId) != null) && !Sync.Players.GetPlayerById(playerId).IsRealPlayer)
     {
         this.CreateBot(playerId.SerialId);
     }
 }
Esempio n. 10
0
        private static void OnControlPilotMsg(MySyncCryoChamber syncObject, ref ControlPilotMsg msg, World.MyNetworkClient sender)
        {
            var playerId = new MyPlayer.PlayerId(msg.SteamId, msg.SerialId);
            var player   = Sync.Players.TryGetPlayerById(playerId);

            var cryoChamber = syncObject.Entity as MyCryoChamber;

            if (player != null)
            {
                if (cryoChamber.Pilot != null)
                {
                    if (player == MySession.LocalHumanPlayer)
                    {
                        cryoChamber.OnPlayerLoaded();

                        if (MySession.Static.CameraController != cryoChamber)
                        {
                            MySession.SetCameraController(MyCameraControllerEnum.Entity, cryoChamber);
                        }
                    }

                    player.Controller.TakeControl(cryoChamber);
                    player.Identity.ChangeCharacter(cryoChamber.Pilot);
                }
                else
                {
                    Debug.Fail("Selected cryo chamber doesn't have a pilot!");
                }
            }
            else
            {
                Debug.Fail("Failed to find player to put in cryo chamber!");
            }
        }
Esempio n. 11
0
        private void OnPlayersChanged(bool connected, MyPlayer.PlayerId pid)
        {
            MyIdentity identity = session.Players.TryGetPlayerIdentity(pid);

            ActivityCollector.Log.Info($"{identity.DisplayName} has {((connected) ? "Connected" : "Disconnected")}");
            if (connected)
            {
                MyPlayer p;
                session.Players.TryGetPlayerById(pid, out p);
                p.Controller.ControlledEntityChanged += OnControlledEntityChanged;

                SQLQueryData.WriteToDatabase(new UserDescription()
                {
                    SteamId   = pid.SteamId,
                    PlayerId  = identity.IdentityId,
                    Name      = identity.DisplayName,
                    Connected = Tools.DateTime,
                    State     = LoginState.Active
                });
            }
            else
            {
                SQLQueryData.WriteToDatabase(new UserDescription()
                {
                    SteamId      = pid.SteamId,
                    PlayerId     = identity.IdentityId,
                    Name         = identity.DisplayName,
                    Disconnected = Tools.DateTime,
                    State        = LoginState.Disconnected
                });
            }
        }
        private SyncCooldownResponseMessage SyncCooldownResponse(SyncCooldownResponseMessage msg)
        {
            int currentTime = MySandboxGame.TotalGamePlayTimeInMilliseconds;

            // msg.respawnTimes can be null, if the server sent empty list
            if (msg.RespawnTimes != null)
            {
                foreach (var respawnTime in msg.RespawnTimes)
                {
                    var controllerId = new MyPlayer.PlayerId()
                    {
                        SteamId = MySteam.UserId, SerialId = respawnTime.ControllerId
                    };
                    var key = new RespawnKey()
                    {
                        ControllerId = controllerId, RespawnShipId = respawnTime.ShipId
                    };

                    m_globalRespawnTimesMs.Add(key, currentTime + respawnTime.RelativeRespawnTime, immediate: true);
                }
            }

            m_synced = true;
            return(msg);
        }
        public bool CanSpawnMoreBots(MyPlayer.PlayerId pid)
        {
            if (!Sync.IsServer)
            {
                Debug.Assert(false, "Server only");
                return(false);
            }

            int perPlayerBotMultiplier = (MySession.Static.CreativeMode ? MySession.Static.MaxPlayers : 1);

            if (MySteam.UserId == pid.SteamId)
            {
                AgentSpawnData spawnData = default(AgentSpawnData);
                if (m_agentsToSpawn.TryGetValue(pid.SerialId, out spawnData))
                {
                    if (spawnData.CreatedByPlayer)
                    {
                        return(Bots.GetCreatedBotCount() < BotFactory.MaximumBotPerPlayer * perPlayerBotMultiplier);
                    }
                    else
                    {
                        return(Bots.GetGeneratedBotCount() < BotFactory.MaximumUncontrolledBotCount);
                    }
                }
                else
                {
                    Debug.Assert(false, "Bot doesn't exist");
                    return(false);
                }
            }
            else
            {
                int botCount     = 0;
                var lookedPlayer = pid.SteamId;
                var players      = Sync.Players.GetAllPlayers();

                if (MySession.Static.CreativeMode)
                {
                    foreach (var player in players)
                    {
                        if (player.SerialId != 0)
                        {
                            ++botCount;
                        }
                    }
                }
                else
                {
                    foreach (var player in players)
                    {
                        if (player.SteamId == lookedPlayer && player.SerialId != 0)
                        {
                            botCount++;
                        }
                    }
                }

                return(botCount < BotFactory.MaximumBotPerPlayer * perPlayerBotMultiplier);
            }
        }
 void Players_PlayersChanged(bool added, MyPlayer.PlayerId playerId)
 {
     if (!m_closed)
     {
         UpdatePlayerList();
     }
 }
Esempio n. 15
0
        public static MyCharacter SpawnAgent(ulong steamId, string name, Color color, MatrixD startPosition,
                                             long identityId = 1000)
        {
            var character = MyCharacter.CreateCharacter(
                startPosition, Vector3.Zero, name, "", color, null, identityId: identityId);

            character.SwitchJetpack();

            var playerId = new MyPlayer.PlayerId(steamId);

            var identityBuilder = new MyObjectBuilder_Identity
            {
                DisplayName       = name,
                CharacterEntityId = character.EntityId,
                ColorMask         = color.ToVector3()
            };
            var identity = new MyAgentIdentity().CreateNewIdentity(identityBuilder);

            var myPlayer = new MyPlayer(Sync.Clients.LocalClient, playerId)
            {
                Identity = identity
            };
            var characterController = new MyEntityController(myPlayer);

            characterController.TakeControl(character);

            return(character);
        }
Esempio n. 16
0
 private bool IsLocal(MyPlayer.PlayerId Id)
 {
     if (!MySandboxGame.IsDedicated && MySession.LocalHumanPlayer != null && Id == MySession.LocalHumanPlayer.Id)
     {
         return(true);
     }
     return(false);
 }
Esempio n. 17
0
 private void Players_PlayerRemoved(MyPlayer.PlayerId pid)
 {
     if (Sync.IsServer && (pid.SerialId != 0))
     {
         MyBotCollection bots = this.Bots;
         bots.TotalBotCount--;
     }
 }
Esempio n. 18
0
 public static void SuffixCreateNewIdentity(string identityName, MyPlayer.PlayerId playerId, string modelName, bool initialPlayer = false)
 {
     playerEvents.EnqueueFront(new PlayerEvent
     {
         Type     = "New",
         SteamId  = playerId.SteamId,
         Occurred = DateTime.Now,
     });
 }
Esempio n. 19
0
        private static void OnReserveAreaRequest(ref ReserveAreaMsg msg, MyNetworkClient sender)
        {
            if (!Sync.IsServer)
            {
                return;
            }

            if (!m_reservedAreas.ContainsKey(msg.ReservationName))
            {
                m_reservedAreas.Add(msg.ReservationName, new Dictionary <long, ReservedAreaData>());
            }

            var  reservations      = m_reservedAreas[msg.ReservationName];
            bool reservedBySomeone = false;

            MyPlayer.PlayerId requestId = new MyPlayer.PlayerId(sender.SteamUserId, msg.SenderSerialId);

            foreach (var r in reservations)
            {
                var  currentReservation = r.Value;
                var  sqDist             = (currentReservation.WorldPosition - msg.Position).LengthSquared();
                bool inRadius           = sqDist <= currentReservation.Radius * currentReservation.Radius;

                if (inRadius)
                {
                    reservedBySomeone = true;
                    break;
                }
            }

            if (!reservedBySomeone)
            {
                reservations[AreaReservationCounter++] = new ReservedAreaData()
                {
                    WorldPosition    = msg.Position,
                    Radius           = msg.Radius,
                    ReservationTimer = MySandboxGame.Static.UpdateTime + MyTimeSpan.FromMiliseconds(msg.ReservationTimeMs),
                    ReserverId       = requestId,
                };

                var allMsg = new ReserveAreaAllMsg()
                {
                    Id              = AreaReservationCounter,
                    Position        = msg.Position,
                    Radius          = msg.Radius,
                    ReservationName = msg.ReservationName,
                };

                Sync.Layer.SendMessageToAll(ref allMsg, MyTransportMessageEnum.Success);
                Sync.Layer.SendMessage(ref msg, sender.SteamUserId, MyTransportMessageEnum.Success);
            }
            else
            {
                Sync.Layer.SendMessage(ref msg, sender.SteamUserId, MyTransportMessageEnum.Failure);
            }
        }
Esempio n. 20
0
        static void SetPlayerLost(MyPlayer.PlayerId id, int triggerIndex)
        {
            MySessionComponentMissionTriggers.Static.SetLost(id, triggerIndex);
            if (!Sync.MultiplayerActive || !MySession.Static.IsScenario)
            {
                return;
            }

            MyMultiplayer.RaiseStaticEvent(s => MyMissionTriggers.OnPlayerLost, id, triggerIndex);
        }
Esempio n. 21
0
        public void SendNewGlobalMessage(MyPlayer.PlayerId senderId, string text)
        {
            var msg = new SendGlobalMessageMsg();

            msg.CharacterEntityId = Entity.EntityId;
            msg.SenderSteamId     = senderId.SteamId;
            msg.Text = text;

            Sync.Layer.SendMessageToServer(ref msg, MyTransportMessageEnum.Request);
        }
Esempio n. 22
0
        static void RespawnRequest_Implementation(ulong steamPlayerId, int serialId)
        {
            var playerId = new MyPlayer.PlayerId(steamPlayerId, serialId);
            var player   = Sync.Players.GetPlayerById(playerId);

            if (false == TryFindCryoChamberCharacter(player))
            {
                MyMultiplayer.RaiseStaticEvent(s => ShowMedicalScreen_Implementation, new EndpointId(steamPlayerId));
            }
        }
Esempio n. 23
0
        public bool CanSpawnMoreBots(MyPlayer.PlayerId pid)
        {
            if (!Sync.IsServer)
            {
                Debug.Assert(false, "Server only");
                return(false);
            }

            if (MyFakes.ENABLE_BRAIN_SIMULATOR)
            {
                return(true);
            }

            if (MyFakes.DEVELOPMENT_PRESET)
            {
                return(true);
            }

            if (MySteam.UserId == pid.SteamId)
            {
                AgentSpawnData spawnData = default(AgentSpawnData);
                if (m_agentsToSpawn.TryGetValue(pid.SerialId, out spawnData))
                {
                    if (spawnData.CreatedByPlayer)
                    {
                        return(Bots.GetCreatedBotCount() < BotFactory.MaximumBotPerPlayer);
                    }
                    else
                    {
                        return(Bots.GetGeneratedBotCount() < BotFactory.MaximumUncontrolledBotCount);
                    }
                }
                else
                {
                    Debug.Assert(false, "Bot doesn't exist");
                    return(false);
                }
            }
            else
            {
                int botCount     = 0;
                var lookedPlayer = pid.SteamId;
                var players      = Sync.Players.GetOnlinePlayers();

                foreach (var player in players)
                {
                    if (player.Id.SteamId == lookedPlayer && player.Id.SerialId != 0)
                    {
                        botCount++;
                    }
                }

                return(botCount < BotFactory.MaximumBotPerPlayer);
            }
        }
Esempio n. 24
0
        public void SetLost(MyPlayer.PlayerId Id, int index)
        {
            MyMissionTriggers mtrig;

            if (!MissionTriggers.TryGetValue(Id, out mtrig))
            {
                Debug.Fail("Bad ID for SetLost");
                return;
            }
            mtrig.SetLost(index);
        }
        private void EnsureIdentityUniqueness(int newBotId)
        {
            var pid      = new MyPlayer.PlayerId(MySteam.UserId, newBotId);
            var identity = Sync.Players.TryGetPlayerIdentity(pid);
            var player   = Sync.Players.TryGetPlayerById(pid);

            if (identity != null && identity.IdentityId != 0 && player == null)
            {
                Sync.Players.RemoveIdentity(pid); // removing old identity
            }
        }
Esempio n. 26
0
        private void Players_PlayerRemoved(MyPlayer.PlayerId pid)
        {
            if (!Sync.IsServer)
            {
                Debug.Assert(false, "Server only");
                return;
            }

            if (pid.SerialId != 0)
                Bots.TotalBotCount--;
        }
Esempio n. 27
0
        public void Add(int idx)
        {
            int num = this.m_clients.Count + 1;

            MyPlayer.PlayerId id         = Sync.Players.FindFreePlayerId(Sync.MyId);
            MyPlayer.PlayerId id2        = new MyPlayer.PlayerId(id.SteamId, id.SerialId + idx);
            MyPlayer          playerById = Sync.Players.GetPlayerById(new MyPlayer.PlayerId(Sync.MyId, 0));

            object[] objArray1 = new object[] { "Virtual ", playerById.DisplayName, " #", num + idx };
            Sync.Players.RequestNewPlayer(id2.SerialId, string.Concat(objArray1), null, true, false);
        }
Esempio n. 28
0
        public static bool CanRespawn(MyPlayer.PlayerId Id)
        {
            //beware, can be unreliable on client - you can call it before newest info from server arrives
            MyMissionTriggers mtrig;

            if (!Static.MissionTriggers.TryGetValue(Id, out mtrig))
            {
                Debug.Fail("Bad ID for CanRespawn");
                return(true);
            }
            return(!mtrig.Lost);
        }
Esempio n. 29
0
        public void SendNewPlayerMessage(MyPlayer.PlayerId senderId, MyPlayer.PlayerId receiverId, string text, TimeSpan timestamp)
        {
            var msg = new SendPlayerMessageMsg();

            msg.CharacterEntityId = Entity.EntityId;
            msg.SenderSteamId     = senderId.SteamId;
            msg.ReceiverSteamId   = receiverId.SteamId;
            msg.Text      = text;
            msg.Timestamp = timestamp.Ticks;

            Sync.Layer.SendMessageToServer(ref msg, MyTransportMessageEnum.Request);
        }
Esempio n. 30
0
 static void NewIdentityCreated_Response(MyPlayer.PlayerId playerId, bool joinGame)
 {
     if (MySession.Static != null && MySession.Static.LocalHumanPlayer != null)
     {
         int   firstLocalPlayer = MySession.Static.LocalHumanPlayer.Id.SerialId;
         ulong steamId          = MySession.Static.LocalHumanPlayer.Id.SteamId;
         if (steamId == playerId.SteamId && firstLocalPlayer == playerId.SerialId)
         {
             ShowPermaWarning = !joinGame;
         }
     }
 }
Esempio n. 31
0
 private void OnNewPlayerSuccess(MyPlayer.PlayerId playerId)
 {
     if (((playerId.SteamId == Sync.MyId) && (playerId.SerialId != 0)) && Sync.Players.GetPlayerById(playerId).IsRealPlayer)
     {
         MyPlayerCollection.RespawnRequest(true, true, 0L, string.Empty, playerId.SerialId, null, Color.Red);
         int             num  = this.m_clients.Count + 1;
         MyVirtualClient item = new MyVirtualClient(new Endpoint(Sync.MyId, (byte)num), CreateClientState(), playerId);
         this.m_clients.Add(item);
         EndpointId targetEndpoint = new EndpointId();
         Vector3D?  position       = null;
         MyMultiplayer.RaiseStaticEvent <int>(x => new Action <int>(MyVirtualClients.OnVirtualClientAdded), num, targetEndpoint, position);
     }
 }
        private static void OnReserveAreaRequest(ref ReserveAreaMsg msg, MyNetworkClient sender)
        {
            if (!Sync.IsServer)
                return;

            if (!m_reservedAreas.ContainsKey(msg.ReservationName))
                m_reservedAreas.Add(msg.ReservationName, new Dictionary<long, ReservedAreaData>());

            var reservations = m_reservedAreas[msg.ReservationName];
            bool reservedBySomeone = false;
            MyPlayer.PlayerId requestId = new MyPlayer.PlayerId(sender.SteamUserId, msg.SenderSerialId);

            foreach (var r in reservations)
            {
                var currentReservation = r.Value;
                var sqDist = (currentReservation.WorldPosition - msg.Position).LengthSquared();
                bool inRadius = sqDist <= currentReservation.Radius * currentReservation.Radius; 
                
                if (inRadius)
                {
                    reservedBySomeone = true;
                    break;
                }
            }

            if (!reservedBySomeone)
            {
                reservations[AreaReservationCounter++] = new ReservedAreaData()
                {
                    WorldPosition = msg.Position,
                    Radius = msg.Radius,
                    ReservationTimer = MySandboxGame.Static.UpdateTime + MyTimeSpan.FromMiliseconds(msg.ReservationTimeMs),
                    ReserverId = requestId,
                };

                var allMsg = new ReserveAreaAllMsg()
                {
                    Id = AreaReservationCounter,
                    Position = msg.Position,
                    Radius = msg.Radius,
                    ReservationName = msg.ReservationName,
                };

                Sync.Layer.SendMessageToAll(ref allMsg, MyTransportMessageEnum.Success);
                Sync.Layer.SendMessage(ref msg, sender.SteamUserId, MyTransportMessageEnum.Success);
            }
            else
            {
                Sync.Layer.SendMessage(ref msg, sender.SteamUserId, MyTransportMessageEnum.Failure);
            }

            
        }
Esempio n. 33
0
        private static void OnReserveAreaRequest(string reservationName, Vector3D position, float radius, long reservationTimeMs, int senderSerialId)
        {
            EndpointId sender;
            if (MyEventContext.Current.IsLocallyInvoked)
                sender = new EndpointId(Sync.MyId);
            else
                sender = MyEventContext.Current.Sender;

            if (!m_reservedAreas.ContainsKey(reservationName))
                m_reservedAreas.Add(reservationName, new Dictionary<long, ReservedAreaData>());

            var reservations = m_reservedAreas[reservationName];
            bool reservedBySomeone = false;
            MyPlayer.PlayerId requestId = new MyPlayer.PlayerId(sender.Value, senderSerialId);

            foreach (var r in reservations)
            {
                var currentReservation = r.Value;
                var sqDist = (currentReservation.WorldPosition - position).LengthSquared();
                bool inRadius = sqDist <= currentReservation.Radius * currentReservation.Radius; 
                
                if (inRadius)
                {
                    reservedBySomeone = true;
                    break;
                }
            }

            if (!reservedBySomeone)
            {
                reservations[AreaReservationCounter++] = new ReservedAreaData()
                {
                    WorldPosition = position,
                    Radius = radius,
                    ReservationTimer = MySandboxGame.Static.UpdateTime + MyTimeSpan.FromMiliseconds(reservationTimeMs),
                    ReserverId = requestId,
                };

                MyMultiplayer.RaiseStaticEvent(s => MyAiTargetManager.OnReserveAreaAllSuccess, AreaReservationCounter, reservationName, position, radius);

                if (MyEventContext.Current.IsLocallyInvoked)
                    OnReserveAreaSuccess(position, radius, senderSerialId);
                else
                    MyMultiplayer.RaiseStaticEvent(s => MyAiTargetManager.OnReserveAreaSuccess, position, radius, senderSerialId, sender);
            }
            else
            {
                if (MyEventContext.Current.IsLocallyInvoked)
                    OnReserveAreaFailure(position, radius, senderSerialId);
                else
                    MyMultiplayer.RaiseStaticEvent(s => MyAiTargetManager.OnReserveAreaFailure, position, radius, senderSerialId, sender);
            }
        }
Esempio n. 34
0
 private void EnsureIdentityUniqueness(int newBotId)
 {
     var pid = new MyPlayer.PlayerId(MySteam.UserId, newBotId);
     var identity = Sync.Players.TryGetPlayerIdentity(pid);
     var player = Sync.Players.TryGetPlayerById(pid);
     if (identity != null && identity.IdentityId != 0 && player == null)
     {
         Sync.Players.RemoveIdentity(pid); // removing old identity
     }
 }
Esempio n. 35
0
        /// <summary>
        /// Initializes a new single player session and start new game with parameters
        /// </summary>
        public static void Start(
            string name,
            string description,
            string password,
            MyObjectBuilder_SessionSettings settings,
            List<MyObjectBuilder_Checkpoint.ModItem> mods,
            MyWorldGenerator.Args generationArgs)
        {
            MyLog.Default.WriteLineAndConsole("Starting world " + name);

            MyEntityContainerEventExtensions.InitEntityEvents();

            Static = new MySession();
            Static.Name = name;
            Static.Mods = mods;
            Static.Description = description;
            Static.Password = password;
            Static.Settings = settings;
            Static.Scenario = generationArgs.Scenario;
            FixIncorrectSettings(Static.Settings);

            double radius = settings.WorldSizeKm * 500; //half size
            if (radius > 0)
            {
                Static.WorldBoundaries = new BoundingBoxD(new Vector3D(-radius, -radius, -radius), new Vector3D(radius, radius, radius));
            }

            Static.InGameTime = generationArgs.Scenario.GameDate;//MyObjectBuilder_Checkpoint.DEFAULT_DATE;
            Static.RequiresDX = generationArgs.Scenario.HasPlanets ? 11 : 9;

            if (Static.OnlineMode != MyOnlineModeEnum.OFFLINE)
                StartServerRequest();

            Static.IsCameraAwaitingEntity = true;

            // Find new non existing folder. The game folder name may be different from game name, so we have to
            // make sure we don't overwrite another save
            string safeName = MyUtils.StripInvalidChars(name);
            Static.CurrentPath = MyLocalCache.GetSessionSavesPath(safeName, false, false);

            while (Directory.Exists(Static.CurrentPath))
            {
                Static.CurrentPath = MyLocalCache.GetSessionSavesPath(safeName + MyUtils.GetRandomInt(int.MaxValue).ToString("########"), false, false);
            }

            Static.PrepareBaseSession(mods, generationArgs.Scenario);

            MySector.EnvironmentDefinition = MyDefinitionManager.Static.GetDefinition<MyEnvironmentDefinition>(generationArgs.Scenario.Environment);

            MyWorldGenerator.GenerateWorld(generationArgs);

            if (Sync.IsServer)
            {
                // Factions have to be initialized before world is generated/loaded.
                Static.InitializeFactions();
            }

            if (!Engine.Platform.Game.IsDedicated)
            {
                var playerId = new MyPlayer.PlayerId(Sync.MyId, 0);
                MyToolBarCollection.RequestCreateToolbar(playerId);
            }

            Static.SendSessionStartStats();
            var scenarioName = generationArgs.Scenario.DisplayNameText.ToString();
            Static.LogSettings(scenarioName, generationArgs.AsteroidAmount);

            if (generationArgs.Scenario.SunDirection.IsValid())
            {
                MySector.SunProperties.SunDirectionNormalized = Vector3.Normalize(generationArgs.Scenario.SunDirection);
                MySector.SunProperties.BaseSunDirectionNormalized = Vector3.Normalize(generationArgs.Scenario.SunDirection);
            }

            //Because blocks fills SubBlocks in this method..
            //TODO: Create LoadPhase2
            
            MyEntities.UpdateOnceBeforeFrame();
            Static.BeforeStartComponents();

            Static.Save();
            MyLocalCache.SaveLastLoadedTime(Static.CurrentPath, DateTime.Now);

            // Initialize Spectator light
            MySpectatorCameraController.Static.InitLight(false);
        }
Esempio n. 36
0
        private bool TryFindSavingPlayerId(SerializableDictionaryCompat<long, MyObjectBuilder_Checkpoint.PlayerId, ulong> controlledEntities, long controlledObject, out MyPlayer.PlayerId playerId)
        {
            playerId = new MyPlayer.PlayerId();
            if (MyFakes.REUSE_OLD_PLAYER_IDENTITY == false) return false;
            if (!Sync.IsServer || Sync.Clients.Count != 1) return false;
            //Never reuse identity in dedicated server!
            if (Engine.Platform.Game.IsDedicated) return false;
            if (controlledEntities == null) return false;

            bool foundLocalPlayer = false;

            foreach (var controlledEntityIt in controlledEntities.Dictionary)
            {
                // This can used if we load an existing game and want to impersonate the saving player
                if (controlledEntityIt.Key == controlledObject)
                {
                    playerId = new MyPlayer.PlayerId(controlledEntityIt.Value.ClientId, controlledEntityIt.Value.SerialId);
                }
                if (controlledEntityIt.Value.ClientId == Sync.MyId && controlledEntityIt.Value.SerialId == 0)
                {
                    foundLocalPlayer = true;
                }
            }

            // We can impersonate the other player only if we don't have an identity set on the server already
            return foundLocalPlayer == false;
        }
Esempio n. 37
0
        private void LoadWorld(MyObjectBuilder_Checkpoint checkpoint, MyObjectBuilder_Sector sector)
        {
            // Run compatibility helper.
            MySandboxGame.Static.SessionCompatHelper.FixSessionObjectBuilders(checkpoint, sector);

            //MyAudio.Static.Mute = true
            MyEntities.MemoryLimitAddFailureReset();

            ElapsedGameTime = new TimeSpan(checkpoint.ElapsedGameTime);
            InGameTime = checkpoint.InGameTime;
            Name = checkpoint.SessionName;
            Description = checkpoint.Description;
            PromotedUsers = new HashSet<ulong>(checkpoint.PromotedUsers ?? Enumerable.Empty<ulong>());
            Briefing = checkpoint.Briefing;
            BriefingVideo = checkpoint.BriefingVideo;
            WorkshopId = checkpoint.WorkshopId;
            Password = checkpoint.Password;
            PreviousEnvironmentHostility = checkpoint.PreviousEnvironmentHostility;
            RequiresDX = checkpoint.RequiresDX;
            FixIncorrectSettings(Settings);

            AppVersionFromSave = checkpoint.AppVersion;

            if (MyFakes.ENABLE_BATTLE_SYSTEM)
            {
                VoxelHandVolumeChanged = sector.VoxelHandVolumeChanged;
            }

            MyToolbarComponent.InitCharacterToolbar(checkpoint.CharacterToolbar);

            LoadCameraControllerSettings(checkpoint);;

            Sync.Players.RespawnComponent.InitFromCheckpoint(checkpoint);

            MyPlayer.PlayerId savingPlayer = new MyPlayer.PlayerId();
            MyPlayer.PlayerId? savingPlayerNullable = null;
            bool reuseSavingPlayerIdentity = TryFindSavingPlayerId(checkpoint.ControlledEntities, checkpoint.ControlledObject, out savingPlayer);
            if (reuseSavingPlayerIdentity && !(IsScenario && Static.OnlineMode != MyOnlineModeEnum.OFFLINE))
                savingPlayerNullable = savingPlayer;

            // Identities have to be loaded before entities (because of ownership)
            if (Sync.IsServer || (!Battle && MyPerGameSettings.Game == GameEnum.ME_GAME) || (!IsScenario && MyPerGameSettings.Game == GameEnum.SE_GAME)
                || (!IsScenario && MyPerGameSettings.Game == GameEnum.VRS_GAME))
                Sync.Players.LoadIdentities(checkpoint, savingPlayerNullable);

            Toolbars.LoadToolbars(checkpoint);

            if (!MyEntities.Load(sector.SectorObjects))
            {
                ShowLoadingError();
            }
            MySandboxGame.Static.SessionCompatHelper.AfterEntitiesLoad(sector.AppVersion);

            if (checkpoint.Factions != null && (Sync.IsServer || (!Battle && MyPerGameSettings.Game == GameEnum.ME_GAME) || (!IsScenario && MyPerGameSettings.Game == GameEnum.SE_GAME)))
            {
                Static.Factions.Init(checkpoint.Factions);
            }

            MyGlobalEvents.LoadEvents(sector.SectorEvents);
            // Regenerate default events if they are empty (i.e. we are loading an old save)

            // Initialize Spectator light
            MySpectatorCameraController.Static.InitLight(checkpoint.SpectatorIsLightOn);

            // MySpectator.Static.SpectatorCameraMovement = checkpoint.SpectatorCameraMovement;
            MySpectatorCameraController.Static.SetViewMatrix(MatrixD.Invert(checkpoint.SpectatorPosition.GetMatrix()));

            if (MyPerGameSettings.Game == GameEnum.UNKNOWN_GAME || ((!Battle && MyPerGameSettings.Game == GameEnum.ME_GAME) || ((!IsScenario || Static.OnlineMode == MyOnlineModeEnum.OFFLINE) && MyPerGameSettings.Game == GameEnum.SE_GAME)
                || ((!IsScenario || Static.OnlineMode == MyOnlineModeEnum.OFFLINE) && MyPerGameSettings.Game == GameEnum.VRS_GAME)))
            {
                if (!(Static.IsScenario && Static.Settings.StartInRespawnScreen))
                {
                    Sync.Players.LoadConnectedPlayers(checkpoint, savingPlayerNullable);
                    Sync.Players.LoadControlledEntities(checkpoint.ControlledEntities, checkpoint.ControlledObject, savingPlayerNullable);
                }
            }
            LoadCamera(checkpoint);

            //fix: saved in survival with dead player, changed to creative, loaded game, no character with no way to respawn
            if (CreativeMode && !Engine.Platform.Game.IsDedicated && LocalHumanPlayer != null && LocalHumanPlayer.Character != null && LocalHumanPlayer.Character.IsDead)
                MyPlayerCollection.RequestLocalRespawn();

            if (MyMultiplayer.Static != null && !Sync.IsServer)
            {
                Sync.Layer.TransportLayer.SendMessage(MyMessageId.CLIENT_READY, null, true, new EndpointId(Sync.ServerId));
                ((MyReplicationClient)MyMultiplayer.Static.ReplicationLayer).OnLocalClientReady();
            }

            // Create the player if he/she does not exist (on clients and server)
            if (!Engine.Platform.Game.IsDedicated && LocalHumanPlayer == null)
            {
                Sync.Players.RequestNewPlayer(0, MySteam.UserName, null);
            }
            // Fix missing controlled entity. This should be needed only on the server.
            // On the client, it will be done in reaction to new player creation (see "Create the player" above)
            else if (ControlledEntity == null && Sync.IsServer && !Engine.Platform.Game.IsDedicated)
            {
                MyLog.Default.WriteLine("ControlledObject was null, respawning character");
                m_cameraAwaitingEntity = true;
                MyPlayerCollection.RequestLocalRespawn();
            }

            if (!Engine.Platform.Game.IsDedicated)
            {
                var playerId = new MyPlayer.PlayerId(Sync.MyId, 0);
                var toolbar = Toolbars.TryGetPlayerToolbar(playerId);
                if (toolbar == null)
                {
                    MyToolBarCollection.RequestCreateToolbar(playerId);
                    MyToolbarComponent.InitCharacterToolbar(Scenario.DefaultToolbar);
                }
                else
                {
                    MyToolbarComponent.InitCharacterToolbar(toolbar.GetObjectBuilder());
                }
            }

            Gpss.LoadGpss(checkpoint);

            LoadChatHistory(checkpoint);

            if (MyFakes.ENABLE_MISSION_TRIGGERS)
                MySessionComponentMissionTriggers.Static.Load(checkpoint.MissionTriggers);

            MyEncounterGenerator.Load(sector.Encounters);
            MyRenderProxy.RebuildCullingStructure();

            Settings.ResetOwnership = false;

            if (MyFinalBuildConstants.IS_OFFICIAL && !CreativeMode)
                MyDebugDrawSettings.DEBUG_DRAW_PHYSICS = false;

            MyRenderProxy.CollectGarbage();
        }
 public void Load(MyObjectBuilder_SessionComponentMission obj)
 {
     MissionTriggers.Clear();
     if (obj!=null && obj.Triggers != null)
         foreach (var trigger in obj.Triggers.Dictionary)
         {
             var id=new MyPlayer.PlayerId(trigger.Key.stm, trigger.Key.ser);
             var triggers = new MyMissionTriggers(trigger.Value);
             MissionTriggers.Add(id, triggers);
         }
 }
        void AttachedPlayerChanged()
        {
            if (m_attachedPlayerId.Value.HasValue == false)
            {
                return;
            }

            var playerId = new MyPlayer.PlayerId(m_attachedPlayerId.Value.Value.SteamId, m_attachedPlayerId.Value.Value.SerialId);
            var player = Sync.Players.GetPlayerById(playerId);
            if (player != null)
            {
                if (Pilot != null)
                {
                    if (player == MySession.Static.LocalHumanPlayer)
                    {
                        OnPlayerLoaded();

                        if (MySession.Static.CameraController != this)
                        {
                            MySession.Static.SetCameraController(MyCameraControllerEnum.Entity, this);
                        }
                    }

                    player.Controller.TakeControl(this);
                    player.Identity.ChangeCharacter(Pilot);
                }
                else
                {
                    if (player == MySession.Static.LocalHumanPlayer)
                    {
                        Debug.Fail("Selected cryo chamber doesn't have a pilot!");
                    }
                }
            }
            else
            {
                m_retryAttachPilot = true;
            }
        }
Esempio n. 40
0
 public MyPlayer GetPlayer(int serialId)
 {
     var controllerId = new MyPlayer.PlayerId() { SteamId = m_steamUserId, SerialId = serialId };
     return Sync.Players.GetPlayerById(controllerId);
 }