Пример #1
0
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            base.Init(sessionComponent);

            if (m_CoreProcessor == null)
                startCore();
        }
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            base.Init(sessionComponent);
            var ob = sessionComponent as MyObjectBuilder_SharedStorageComponent;
            Debug.Assert(ob != null);
            m_objectBuilder = new MyObjectBuilder_SharedStorageComponent
            {
                BoolStorage = ob.BoolStorage,
                FloatStorage = ob.FloatStorage,
                StringStorage = ob.StringStorage,
                IntStorage = ob.IntStorage,
                Vector3DStorage = ob.Vector3DStorage,
                ExistingFieldsAndStaticAttribute = ob.ExistingFieldsAndStaticAttribute
            };

            m_instance = this;
        }
Пример #3
0
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            base.Init(sessionComponent);

            m_obForLoading = sessionComponent as MyObjectBuilder_SpaceFaunaComponent;
        }
Пример #4
0
 public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
 {
     DoWork();
 }
Пример #5
0
 public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
 {
     MyAPIGateway.Entities.OnEntityAdd    += AddPlanet;
     MyAPIGateway.Entities.OnEntityRemove += RemovePlanet;
 }
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            if (Instance == null)
            {
                Instance = this;
            }

            try
            {
                // This Variables are already loaded by this point, but unaccessible because we need Utilities.

                // Need to create the Utilities, as it isn't yet created by the game at this point.
                //MyModAPIHelper.OnSessionLoaded();

                if (MyAPIGateway.Utilities == null)
                {
                    MyAPIGateway.Utilities = MyAPIUtilities.Static;
                }
                //    MyAPIGateway.Utilities = new MyAPIUtilities();

                MyDefinitionId          missileId      = new MyDefinitionId(typeof(MyObjectBuilder_AmmoDefinition), "Missile");
                MyMissileAmmoDefinition ammoDefinition = MyDefinitionManager.Static.GetAmmoDefinition(missileId) as MyMissileAmmoDefinition;

                DefaultDefinitionValues = new MidspaceEnvironmentComponent
                {
                    LargeShipMaxSpeed         = (decimal)MyDefinitionManager.Static.EnvironmentDefinition.LargeShipMaxSpeed,
                    SmallShipMaxSpeed         = (decimal)MyDefinitionManager.Static.EnvironmentDefinition.SmallShipMaxSpeed,
                    MissileMinSpeed           = (decimal)(ammoDefinition?.MissileInitialSpeed ?? 0),
                    MissileMaxSpeed           = (decimal)(ammoDefinition?.DesiredSpeed ?? 0),
                    RemoteControlMaxSpeed     = 100, // game hardcoded default in MyRemoteControl.CreateTerminalControls()
                    ContainerDropDeployHeight = MessageConfig.DefaultContainerDropDeployHeight,
                    RespawnShipDeployHeight   = MessageConfig.DefaultRespawnShipDeployHeight
                };

                // Load the speed on both server and client.
                string xmlValue;
                if (MyAPIGateway.Utilities.GetVariable("MidspaceEnvironmentComponent", out xmlValue))
                {
                    EnvironmentComponent = MyAPIGateway.Utilities.SerializeFromXML <MidspaceEnvironmentComponent>(xmlValue);
                    if (EnvironmentComponent != null)
                    {
                        // Fix Defaults.
                        if (EnvironmentComponent.Version == 0)
                        {
                            EnvironmentComponent.Version = SpeedConsts.ModCommunicationVersion;
                        }
                        if (EnvironmentComponent.ThrustRatio <= 0)
                        {
                            EnvironmentComponent.ThrustRatio = 1;
                        }
                        if (EnvironmentComponent.GyroPowerMod <= 0)
                        {
                            EnvironmentComponent.GyroPowerMod = 1;
                        }
                        if (EnvironmentComponent.IonAirEfficient < 0 || EnvironmentComponent.IonAirEfficient > 1)
                        {
                            EnvironmentComponent.IonAirEfficient = 0;
                        }
                        if (EnvironmentComponent.AtmosphereSpaceEfficient < 0 || EnvironmentComponent.AtmosphereSpaceEfficient > 1)
                        {
                            EnvironmentComponent.AtmosphereSpaceEfficient = 0;
                        }
                        if (EnvironmentComponent.MissileMinSpeed == 0)
                        {
                            EnvironmentComponent.MissileMinSpeed = DefaultDefinitionValues.MissileMinSpeed;
                        }
                        if (EnvironmentComponent.MissileMaxSpeed == 0)
                        {
                            EnvironmentComponent.MissileMaxSpeed = DefaultDefinitionValues.MissileMaxSpeed;
                        }
                        if (EnvironmentComponent.RemoteControlMaxSpeed == 0)
                        {
                            EnvironmentComponent.RemoteControlMaxSpeed = DefaultDefinitionValues.RemoteControlMaxSpeed;
                        }
                        if (EnvironmentComponent.ContainerDropDeployHeight == 0)
                        {
                            EnvironmentComponent.ContainerDropDeployHeight = MessageConfig.DefaultContainerDropDeployHeight;
                        }
                        if (EnvironmentComponent.RespawnShipDeployHeight == 0)
                        {
                            EnvironmentComponent.RespawnShipDeployHeight = MessageConfig.DefaultRespawnShipDeployHeight;
                        }

                        // Apply settings.
                        if (EnvironmentComponent.LargeShipMaxSpeed > 0)
                        {
                            MyDefinitionManager.Static.EnvironmentDefinition.LargeShipMaxSpeed = (float)EnvironmentComponent.LargeShipMaxSpeed;
                        }
                        if (EnvironmentComponent.SmallShipMaxSpeed > 0)
                        {
                            MyDefinitionManager.Static.EnvironmentDefinition.SmallShipMaxSpeed = (float)EnvironmentComponent.SmallShipMaxSpeed;
                        }

                        if (EnvironmentComponent.EnableThrustRatio)
                        {
                            List <MyDefinitionBase> blocks = MyDefinitionManager.Static.GetAllDefinitions().Where(d => d is MyCubeBlockDefinition &&
                                                                                                                  (((MyCubeBlockDefinition)d).Id.TypeId == typeof(MyObjectBuilder_Thrust))).ToList();
                            foreach (var block in blocks)
                            {
                                MyThrustDefinition thrustBlock = (MyThrustDefinition)block;

                                /*
                                 * // thrustBlock.ThrusterType == // this only affects the sound type.
                                 *
                                 * //thrustBlock.ResourceSinkGroup
                                 *
                                 * //if (thrustBlock.NeedsAtmosphereForInfluence) // ??? might be indicative of atmosphic thruster.
                                 * if (thrustBlock.PropellerUse)
                                 * {
                                 *  // Is atmosphic thruster.
                                 *
                                 *  // MinPlanetaryInfluence is the one to adjust.
                                 *  // the default of 0.3 takes it down into the gravity well, somewhere below where Low Oxygen starts.
                                 *  // at 0.0, it is at the cusp between Low Oxygen and No oxygen.
                                 *  // at -0.3, it allows the atmosphic thruster to work in Space.
                                 *
                                 *  //thrustBlock.MinPlanetaryInfluence = -0.3f;       // 0.3
                                 *  //thrustBlock.MaxPlanetaryInfluence = 1f;         // 1.0
                                 *  //thrustBlock.EffectivenessAtMinInfluence = 0f;   // 0.0
                                 *  //thrustBlock.EffectivenessAtMaxInfluence = 1f;   // 1.0
                                 *  //thrustBlock.NeedsAtmosphereForInfluence = true; // true
                                 * }
                                 * else
                                 * {
                                 *  // Is Ion or Hydrogen thruster.
                                 *
                                 *  //thrustBlock.FuelConverter != null // ??? Hydrogen or other fuel propellant.
                                 *
                                 *  //thrustBlock.MinPlanetaryInfluence = 0.0f;       // 0.0
                                 *  //thrustBlock.MaxPlanetaryInfluence = 0.3f;         // 1.0
                                 *  //thrustBlock.EffectivenessAtMinInfluence = 1.0f;   // 1.0
                                 *  //thrustBlock.EffectivenessAtMaxInfluence = 0.0f;   // 0.3
                                 * }
                                 */
                                thrustBlock.ForceMagnitude *= (float)EnvironmentComponent.ThrustRatio;
                            }
                        }

                        /*
                         * // if enabled Gyro boost.
                         * {
                         *  List<MyDefinitionBase> blocks = MyDefinitionManager.Static.GetAllDefinitions().Where(d => d is MyCubeBlockDefinition &&
                         *          (((MyCubeBlockDefinition) d).Id.TypeId == typeof (MyObjectBuilder_Gyro))).ToList();
                         *  foreach (var block in blocks)
                         *  {
                         *      MyGyroDefinition gyroBlock = (MyGyroDefinition) block;
                         *      //gyroBlock.ForceMagnitude *= 100; // This works.
                         *  }
                         * }
                         */

                        if (ammoDefinition != null && EnvironmentComponent.MissileMinSpeed > 0)
                        {
                            ammoDefinition.MissileInitialSpeed = (float)EnvironmentComponent.MissileMinSpeed;
                        }
                        if (ammoDefinition != null && EnvironmentComponent.MissileMaxSpeed > 0)
                        {
                            ammoDefinition.DesiredSpeed = (float)EnvironmentComponent.MissileMaxSpeed;
                        }

                        #region ContainerDropDeployHeight

                        // We're basically changing the ContainerDrop prefabs that are loaded in memory before any of them are spawned.
                        // This is not my preferred approach, as these could be altered (by other mods) or reset (reload from disc by the game or mods).
                        // The prefered approach is to modify the chute.DeployHeight after a container is spawned, but it is not whitelisted.
                        DictionaryReader <string, MyDropContainerDefinition> dropContainers = MyDefinitionManager.Static.GetDropContainerDefinitions();
                        foreach (var kvp in dropContainers)
                        {
                            foreach (MyObjectBuilder_CubeGrid grid in kvp.Value.Prefab.CubeGrids)
                            {
                                foreach (MyObjectBuilder_CubeBlock block in grid.CubeBlocks)
                                {
                                    MyObjectBuilder_Parachute chute = block as MyObjectBuilder_Parachute;
                                    if (chute != null)
                                    {
                                        if (chute.DeployHeight < (float)EnvironmentComponent.ContainerDropDeployHeight)
                                        {
                                            chute.DeployHeight = (float)EnvironmentComponent.ContainerDropDeployHeight;
                                        }
                                    }
                                }
                            }
                        }

                        #endregion

                        #region RespawnShipDeployHeight

                        DictionaryReader <string, MyRespawnShipDefinition> respawnShips = MyDefinitionManager.Static.GetRespawnShipDefinitions();

                        foreach (var kvp in respawnShips)
                        {
                            foreach (MyObjectBuilder_CubeGrid grid in kvp.Value.Prefab.CubeGrids)
                            {
                                foreach (MyObjectBuilder_CubeBlock block in grid.CubeBlocks)
                                {
                                    MyObjectBuilder_Parachute chute = block as MyObjectBuilder_Parachute;
                                    if (chute != null)
                                    {
                                        if (chute.DeployHeight < (float)EnvironmentComponent.RespawnShipDeployHeight)
                                        {
                                            chute.DeployHeight = (float)EnvironmentComponent.RespawnShipDeployHeight;
                                        }
                                    }
                                }
                            }
                        }

                        #endregion

                        OldEnvironmentComponent = EnvironmentComponent.Clone();
                        return;
                    }
                }

                // creates a new EnvironmentComponent if one was not found in the game Variables.
                EnvironmentComponent = new MidspaceEnvironmentComponent
                {
                    Version                   = SpeedConsts.ModCommunicationVersion,
                    LargeShipMaxSpeed         = (decimal)MyDefinitionManager.Static.EnvironmentDefinition.LargeShipMaxSpeed,
                    SmallShipMaxSpeed         = (decimal)MyDefinitionManager.Static.EnvironmentDefinition.SmallShipMaxSpeed,
                    EnableThrustRatio         = false,
                    MissileMinSpeed           = (decimal)(ammoDefinition?.MissileInitialSpeed ?? 0),
                    MissileMaxSpeed           = (decimal)(ammoDefinition?.DesiredSpeed ?? 0),
                    ThrustRatio               = 1,
                    RemoteControlMaxSpeed     = 100,
                    ContainerDropDeployHeight = MessageConfig.DefaultContainerDropDeployHeight,
                    RespawnShipDeployHeight   = MessageConfig.DefaultRespawnShipDeployHeight
                };
                OldEnvironmentComponent = EnvironmentComponent.Clone();
            }
            catch (Exception ex)
            {
                VRage.Utils.MyLog.Default.WriteLine("##Mod## ERROR " + ex.Message);

                // The Loggers doesn't actually exist yet, as Init is called before UpdateBeforeSimulation.
                // TODO: should rework the code to change this.
                //ClientLogger.WriteException(ex);
                //ServerLogger.WriteException(ex);
            }
        }
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            base.Init(sessionComponent);

            // Only servers can run this session component
            if(!Session.IsServer) return;
            MyObjectBuilder_VisualScriptManagerSessionComponent ob = (MyObjectBuilder_VisualScriptManagerSessionComponent) sessionComponent;
            m_objectBuilder = ob;
            m_relativePathsToAbsolute.Clear();
            m_stateMachineDefinitionFilePaths.Clear();

            // Runs game started event
            m_firstUpdate = ob.FirstRun;

            // load vanilla level script files
            if (ob.LevelScriptFiles != null)
                foreach (string relativeFilePath in ob.LevelScriptFiles)
                {
                    var absolutePath = Path.Combine(MyFileSystem.ContentPath, relativeFilePath);
                    // Add only existing files
                    if(MyFileSystem.FileExists(absolutePath))
                    {
                        m_relativePathsToAbsolute.Add(relativeFilePath, absolutePath);
                    }
                    else
                    {
                        MyLog.Default.WriteLine(relativeFilePath + " Level Script was not found.");
                        Debug.Fail(relativeFilePath + " Level Script was not found.");
                    }
                }

            // load vanilla mission manchines
            if(ob.StateMachines != null)
                foreach (var relativeFilePath in ob.StateMachines)
                {
                    var absolutePath = Path.Combine(MyFileSystem.ContentPath, relativeFilePath);
                    // Add only existing files
                    if (MyFileSystem.FileExists(absolutePath))
                    {
                        if (!m_relativePathsToAbsolute.ContainsKey(relativeFilePath))
                        {
                            m_stateMachineDefinitionFilePaths.Add(absolutePath);
                        }

                        m_relativePathsToAbsolute.Add(relativeFilePath, absolutePath);
                    }
                    else
                    {
                        MyLog.Default.WriteLine(relativeFilePath + " Mission File was not found.");
                        Debug.Fail(relativeFilePath + " Mission File was not found.");
                    }
                }

            // Load mission machines and level scripts from mods
            // Overrides vanilla files
            if(Session.Mods != null)
            {
                foreach (var modItem in Session.Mods)
                {
                    // First try is a mod archive
                    var directoryPath = Path.Combine(MyFileSystem.ModsPath, modItem.PublishedFileId + ".sbm");
                    if (!MyFileSystem.DirectoryExists(directoryPath))
                    {
                        directoryPath = Path.Combine(MyFileSystem.ModsPath, modItem.Name);
                        if(!MyFileSystem.DirectoryExists(directoryPath))
                            directoryPath = null;
                    }

                    if (!string.IsNullOrEmpty(directoryPath))
                    {
                        foreach (var filePath in MyFileSystem.GetFiles(directoryPath, "*", MySearchOption.AllDirectories))
                        {
                            var extension = Path.GetExtension(filePath);
                            var relativePath = MyFileSystem.MakeRelativePath(Path.Combine(directoryPath, "VisualScripts"), filePath);
                            if (extension == ".vs" || extension == ".vsc")
                            {
                                if(m_relativePathsToAbsolute.ContainsKey(relativePath))
                                    m_relativePathsToAbsolute[relativePath] = filePath;
                                else
                                    m_relativePathsToAbsolute.Add(relativePath, filePath);
                            }
                        }
                    }
                }
            }

            // Provider will compile all required scripts for the session.
            MyVSAssemblyProvider.Init(m_relativePathsToAbsolute.Values);
            // Retrive the Level script instances
            m_levelScripts = MyVSAssemblyProvider.GetLevelScriptInstances();

            // mission manager initialization - state machine definitions
            m_smManager = new MyVSStateMachineManager();
            foreach (var stateMachineFilePath in m_stateMachineDefinitionFilePaths)
            {
                m_smManager.AddMachine(stateMachineFilePath);
            }
        }
Пример #8
0
        public override void Init(MyObjectBuilder_SessionComponent sessionComponentBuilder)
        {
            if (!MyPerGameSettings.EnableAi)
                return;

            base.Init(sessionComponentBuilder);

            var ob = (MyObjectBuilder_AIComponent)sessionComponentBuilder;

            foreach (var brain in ob.BotBrains)
            {
                m_loadedBotObjectBuildersByHandle[brain.PlayerHandle] = brain.BotBrain;
            }
        }
        public virtual void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            m_initialized = true;
            if (sessionComponent != null && sessionComponent.Definition.HasValue)
            {
                Definition = sessionComponent.Definition;
            }

            if (Definition.HasValue)
            {
                var def = MyDefinitionManagerBase.Static.GetDefinition<MySessionComponentDefinition>(Definition.Value);

                if (def == null)
                    MyLog.Default.Warning("Missing definition {0} : for session component {1}", Definition, GetType().Name);
                else
                    InitFromDefinition(def);
            }
        }
Пример #10
0
        public sealed override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            InitModSettings(out ModCommunicationVersion, out ServerConnectionId, out ServerLoggingLevel, out ServerLogFileName, out ClientConnectionId, out ClientLoggingLevel, out ClientLogFileName, out ModName, out ModTitle, out ExperimentalCreatorList);
            Guard.IsNotZero(ModCommunicationVersion, "SEModCore: InitModSettings must supply ModCommunicationVersion.");
            Guard.IsNotZero(ServerConnectionId, "SEModCore: InitModSettings must supply ServerConnectionId.");
            Guard.IsNotEmpty(ServerLogFileName, "SEModCore: InitModSettings must supply ServerLogFileName.");
            Guard.IsNotZero(ClientConnectionId, "SEModCore: InitModSettings must supply ClientConnectionId.");
            Guard.IsNotEmpty(ClientLogFileName, "SEModCore: InitModSettings must supply ClientLogFileName.");
            Guard.IsNotEmpty(ModName, "SEModCore: InitModSettings must supply ModName.");
            Guard.IsNotEmpty(ModTitle, "SEModCore: InitModSettings must supply ModTitle.");
            Guard.IsNotEqual(ServerConnectionId, ClientConnectionId, $"SEModCore: ServerConnectionId [{ServerConnectionId}] and ClientConnectionId [{ClientConnectionId}] must not be the same.");


            //TextLogger.WriteGameLog($"####### {ModConfigurationConsts.ModName} INIT");

            //if (MyAPIGateway.Utilities == null)
            //    MyAPIGateway.Utilities = MyAPIUtilities.Static;

            //TextLogger.WriteGameLog($"####### TEST1 {MyAPIGateway.Utilities == null}");
            ////TextLogger.WriteGameLog($"####### TEST2 {MyAPIGateway.Utilities?.ConfigDedicated == null}");  // FAIL
            //TextLogger.WriteGameLog($"####### TEST3 {MyAPIGateway.Utilities?.GamePaths == null}");
            //TextLogger.WriteGameLog($"####### TEST3 {MyAPIGateway.Utilities?.GamePaths?.UserDataPath ?? "FAIL"}");

            //TextLogger.WriteGameLog($"####### TEST4 {MyAPIGateway.Utilities?.IsDedicated == null}");

            //TextLogger.WriteGameLog($"####### TEST5 {MyAPIGateway.Session == null}");
            ////TextLogger.WriteGameLog($"####### TEST6 {MyAPIGateway.Session?.Player == null}");    // FAIL
            //TextLogger.WriteGameLog($"####### TEST7 {MyAPIGateway.Session?.OnlineMode ?? null}");
            ////MyAPIGateway.Session.OnlineMode.Equals(MyOnlineModeEnum.OFFLINE)

            //TextLogger.WriteGameLog($"####### TEST8 {MyAPIGateway.Multiplayer == null}");
            //TextLogger.WriteGameLog($"####### TEST9 {MyAPIGateway.Multiplayer?.IsServer ?? null}");

            VRage.Utils.MyLog.Default.WriteLine($"CHECK1. #########################################");
            VRage.Utils.MyLog.Default.WriteLine($"CHECK2. OnlineMode===== {MyAPIGateway.Session.OnlineMode} ");
            VRage.Utils.MyLog.Default.WriteLine($"CHECK3. IsServer===== {MyAPIGateway.Multiplayer.IsServer}");
            VRage.Utils.MyLog.Default.WriteLine($"CHECK4. IsDedicated==== {MyAPIGateway.Utilities.IsDedicated}");


            if (MyAPIGateway.Multiplayer.IsServer || MyAPIGateway.Utilities.IsDedicated)
            {
                InitServer();
            }
            if (!MyAPIGateway.Utilities.IsDedicated)
            {
                InitClient();
            }

            if (!_commandsRegistered)
            {
                foreach (ChatCommand command in GetAllChatCommands())
                {
                    ChatCommandService.Register(command);
                }
                _commandsRegistered = ChatCommandService.Init();
            }

            _isInitialized = true;

            if (_isServerRegistered)
            {
                ServerLoad();
            }

            if (_isClientRegistered)
            {
                ClientLoad();
            }

            ServerLogger.WriteInfo($"{ModName} Server is ready.");
            // Client is only `ready` after it has received the ClientConfigResponse. We log that in MessageClientConfig.
        }
Пример #11
0
 public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
 {
     base.Init(sessionComponent);
     Logger.Instance.Init();
 }
Пример #12
0
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            base.Init(sessionComponent);

            // Only servers can run this session component
            if (!Session.IsServer)
            {
                return;
            }
            MyObjectBuilder_VisualScriptManagerSessionComponent ob = (MyObjectBuilder_VisualScriptManagerSessionComponent)sessionComponent;

            m_objectBuilder = ob;
            m_relativePathsToAbsolute.Clear();
            m_stateMachineDefinitionFilePaths.Clear();

            // Runs game started event
            m_firstUpdate = ob.FirstRun;

            // load vanilla level script files
            if (ob.LevelScriptFiles != null)
            {
                foreach (string relativeFilePath in ob.LevelScriptFiles)
                {
                    var absolutePath = Path.Combine(MyFileSystem.ContentPath, relativeFilePath);
                    // Add only existing files
                    if (MyFileSystem.FileExists(absolutePath))
                    {
                        m_relativePathsToAbsolute.Add(relativeFilePath, absolutePath);
                    }
                    else
                    {
                        MyLog.Default.WriteLine(relativeFilePath + " Level Script was not found.");
                        Debug.Fail(relativeFilePath + " Level Script was not found.");
                    }
                }
            }

            // load vanilla mission manchines
            if (ob.StateMachines != null)
            {
                foreach (var relativeFilePath in ob.StateMachines)
                {
                    var absolutePath = Path.Combine(MyFileSystem.ContentPath, relativeFilePath);
                    // Add only existing files
                    if (MyFileSystem.FileExists(absolutePath))
                    {
                        if (!m_relativePathsToAbsolute.ContainsKey(relativeFilePath))
                        {
                            m_stateMachineDefinitionFilePaths.Add(absolutePath);
                        }

                        m_relativePathsToAbsolute.Add(relativeFilePath, absolutePath);
                    }
                    else
                    {
                        MyLog.Default.WriteLine(relativeFilePath + " Mission File was not found.");
                        Debug.Fail(relativeFilePath + " Mission File was not found.");
                    }
                }
            }

            // Load mission machines and level scripts from mods
            // Overrides vanilla files
            if (Session.Mods != null)
            {
                foreach (var modItem in Session.Mods)
                {
                    // First try is a mod archive
                    var directoryPath = Path.Combine(MyFileSystem.ModsPath, modItem.PublishedFileId + ".sbm");
                    if (!MyFileSystem.DirectoryExists(directoryPath))
                    {
                        directoryPath = Path.Combine(MyFileSystem.ModsPath, modItem.Name);
                        if (!MyFileSystem.DirectoryExists(directoryPath))
                        {
                            directoryPath = null;
                        }
                    }

                    if (!string.IsNullOrEmpty(directoryPath))
                    {
                        foreach (var filePath in MyFileSystem.GetFiles(directoryPath, "*", MySearchOption.AllDirectories))
                        {
                            var extension    = Path.GetExtension(filePath);
                            var relativePath = MyFileSystem.MakeRelativePath(Path.Combine(directoryPath, "VisualScripts"), filePath);
                            if (extension == ".vs" || extension == ".vsc")
                            {
                                if (m_relativePathsToAbsolute.ContainsKey(relativePath))
                                {
                                    m_relativePathsToAbsolute[relativePath] = filePath;
                                }
                                else
                                {
                                    m_relativePathsToAbsolute.Add(relativePath, filePath);
                                }
                            }
                        }
                    }
                }
            }

            // Provider will compile all required scripts for the session.
            MyVSAssemblyProvider.Init(m_relativePathsToAbsolute.Values);
            // Retrive the Level script instances
            m_levelScripts = MyVSAssemblyProvider.GetLevelScriptInstances();

            // mission manager initialization - state machine definitions
            m_smManager = new MyVSStateMachineManager();
            foreach (var stateMachineFilePath in m_stateMachineDefinitionFilePaths)
            {
                m_smManager.AddMachine(stateMachineFilePath);
            }
        }
Пример #13
0
 public virtual void Init(MyObjectBuilder_SessionComponent sessionComponent)
 {
 }
Пример #14
0
        /// <summary>
        /// Gets a session snapshot customized for an individual player. Removes data that player does not need,
        /// which improves download times, and fixes some exploits.
        /// </summary>
        /// <param name="steamId"></param>
        /// <returns></returns>
        private static MyObjectBuilder_Checkpoint GetClientCheckpoint(ulong steamId)
        {
            Log.Info($"Saving checkpoint...");
            var cpid = new MyObjectBuilder_Checkpoint.PlayerId(steamId);
            var ppid = new MyPlayer.PlayerId(steamId);

            if (_checkpoint == null)
            {
                _checkpoint     = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Checkpoint>();
                _cameraSettings = new List <CameraControllerSettings>();
                var settings = MyObjectBuilderSerializer.Clone(MySession.Static.Settings) as MyObjectBuilder_SessionSettings;
                bGps         = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Gps>();
                bGps.Entries = new List <MyObjectBuilder_Gps.Entry>();

                settings.ScenarioEditMode |= MySession.Static.PersistentEditMode;

                _checkpoint.SessionName   = MySession.Static.Name;
                _checkpoint.Description   = MySession.Static.Description;
                _checkpoint.PromotedUsers = new SerializableDictionary <ulong, MyPromoteLevel>(MySession.Static.PromotedUsers);
                _checkpoint.CreativeTools = new HashSet <ulong>();
                _checkpoint.Settings      = settings;
                //We're replacing the call to MySession.GetWorld, so Torch can't inject the torch mod. Do it here instead
                _checkpoint.Mods = MySession.Static.Mods.ToList();
                _checkpoint.Mods.AddRange(SessionManager.OverrideMods);
                _checkpoint.Scenario        = MySession.Static.Scenario.Id;
                _checkpoint.WorldBoundaries = MySession.Static.WorldBoundaries;
                _checkpoint.PreviousEnvironmentHostility = MySession.Static.PreviousEnvironmentHostility;
                _checkpoint.RequiresDX          = MySession.Static.RequiresDX;
                _checkpoint.CustomSkybox        = MySession.Static.CustomSkybox;
                _checkpoint.GameDefinition      = MySession.Static.GameDefinition.Id;
                _checkpoint.Gps                 = new SerializableDictionary <long, MyObjectBuilder_Gps>();
                _checkpoint.RespawnCooldowns    = new List <MyObjectBuilder_Checkpoint.RespawnCooldownItem>();
                _checkpoint.ControlledEntities  = new SerializableDictionary <long, MyObjectBuilder_Checkpoint.PlayerId>();
                _checkpoint.ChatHistory         = new List <MyObjectBuilder_ChatHistory>();
                _checkpoint.FactionChatHistory  = new List <MyObjectBuilder_FactionChatHistory>();
                _checkpoint.AppVersion          = MyFinalBuildConstants.APP_VERSION;
                _checkpoint.SessionComponents   = new List <MyObjectBuilder_SessionComponent>();
                _checkpoint.AllPlayersData      = new SerializableDictionary <MyObjectBuilder_Checkpoint.PlayerId, MyObjectBuilder_Player>();
                _checkpoint.AllPlayersColors    = new SerializableDictionary <MyObjectBuilder_Checkpoint.PlayerId, List <Vector3> >();
                _checkpoint.Identities          = new List <MyObjectBuilder_Identity>();
                _checkpoint.Clients             = new List <MyObjectBuilder_Client>();
                _checkpoint.NonPlayerIdentities = new List <long>();
                _checkpoint.CharacterToolbar    = null;
            }

            _checkpoint.CreativeTools.Clear();
            //Pool.DeallocateCollection(_checkpoint.Gps.Dictionary.Values);
            _checkpoint.Gps.Dictionary.Clear();
            //Pool.DeallocateAndClear(bGps.Entries);
            bGps.Entries.Clear();
            //Pool.DeallocateAndClear(_checkpoint.RespawnCooldowns);
            _checkpoint.RespawnCooldowns.Clear();
            Pool.DeallocateAndClear(_checkpoint.ChatHistory);
            _checkpoint.ControlledEntities.Dictionary.Clear();
            Pool.DeallocateAndClear(_checkpoint.FactionChatHistory);
            _checkpoint.SessionComponents.Clear();
            Pool.DeallocateCollection(_checkpoint.AllPlayersData.Dictionary.Values);
            _checkpoint.AllPlayersData.Dictionary.Clear();
            _checkpoint.AllPlayersColors.Dictionary.Clear();
            Pool.DeallocateAndClear(_checkpoint.Identities);
            Pool.DeallocateAndClear(_checkpoint.Clients);
            _checkpoint.NonPlayerIdentities.Clear();
            Pool.DeallocateAndClear(_cameraSettings);

            if (MySession.Static.CreativeToolsEnabled(steamId))
            {
                _checkpoint.CreativeTools.Add(steamId);
            }
            //checkpoint.Briefing = Briefing;
            //checkpoint.BriefingVideo = BriefingVideo;
            _checkpoint.LastSaveTime    = DateTime.Now;
            _checkpoint.WorkshopId      = MySession.Static.WorkshopId;
            _checkpoint.ElapsedGameTime = MySession.Static.ElapsedGameTime.Ticks;
            _checkpoint.InGameTime      = MySession.Static.InGameTime;
            //checkpoint.CharacterToolbar = MyToolbarComponent.CharacterToolbar.GetObjectBuilder();
            //TODO
            _checkpoint.CustomLoadingScreenImage = MySession.Static.CustomLoadingScreenImage;
            _checkpoint.CustomLoadingScreenText  = EssentialsPlugin.Instance.Config.LoadingText ?? MySession.Static.CustomLoadingScreenText;

            _checkpoint.SessionComponentDisabled = MySession.Static.SessionComponentDisabled;
            _checkpoint.SessionComponentEnabled  = MySession.Static.SessionComponentEnabled;

            //  checkpoint.PlayerToolbars = Toolbars.GetSerDictionary();

            //Sync.Players.SavePlayers(_checkpoint);
            ConcurrentDictionary <MyPlayer.PlayerId, MyPlayer> m_players           = Players_Getter(MySession.Static.Players);
            ConcurrentDictionary <MyPlayer.PlayerId, long>     m_playerIdentityIds = PlayerIdentities_Getter(MySession.Static.Players);

            foreach (MyPlayer p in m_players.Values)
            {
                var id = new MyObjectBuilder_Checkpoint.PlayerId {
                    ClientId = p.Id.SteamId, SerialId = p.Id.SerialId
                };
                var playerOb = Pool.AllocateOrCreate <MyObjectBuilder_Player>();

                playerOb.DisplayName     = p.DisplayName;
                playerOb.IdentityId      = p.Identity.IdentityId;
                playerOb.Connected       = true;
                playerOb.ForceRealPlayer = p.IsRealPlayer;

                if (playerOb.BuildColorSlots == null)
                {
                    playerOb.BuildColorSlots = new List <Vector3>();
                }
                else
                {
                    playerOb.BuildColorSlots.Clear();
                }

                foreach (Vector3 color in p.BuildColorSlots)
                {
                    playerOb.BuildColorSlots.Add(color);
                }

                _checkpoint.AllPlayersData.Dictionary.Add(id, playerOb);
            }

            foreach (KeyValuePair <MyPlayer.PlayerId, long> identityPair in m_playerIdentityIds)
            {
                if (m_players.ContainsKey(identityPair.Key))
                {
                    continue;
                }

                var id = new MyObjectBuilder_Checkpoint.PlayerId {
                    ClientId = identityPair.Key.SteamId, SerialId = identityPair.Key.SerialId
                };
                MyIdentity identity = MySession.Static.Players.TryGetIdentity(identityPair.Value);
                var        playerOb = Pool.AllocateOrCreate <MyObjectBuilder_Player>();

                playerOb.DisplayName = identity?.DisplayName;
                playerOb.IdentityId  = identityPair.Value;
                playerOb.Connected   = false;

                if (MyCubeBuilder.AllPlayersColors != null)
                {
                    MyCubeBuilder.AllPlayersColors.TryGetValue(identityPair.Key, out playerOb.BuildColorSlots);
                }

                _checkpoint.AllPlayersData.Dictionary.Add(id, playerOb);
            }

            if (MyCubeBuilder.AllPlayersColors != null)
            {
                foreach (KeyValuePair <MyPlayer.PlayerId, List <Vector3> > colorPair in MyCubeBuilder.AllPlayersColors)
                {
                    //TODO: check if the player exists in m_allIdentities
                    if (m_players.ContainsKey(colorPair.Key) || m_playerIdentityIds.ContainsKey(colorPair.Key))
                    {
                        continue;
                    }

                    var id = new MyObjectBuilder_Checkpoint.PlayerId {
                        ClientId = colorPair.Key.SteamId, SerialId = colorPair.Key.SerialId
                    };
                    _checkpoint.AllPlayersColors.Dictionary.Add(id, colorPair.Value);
                }
            }

            _checkpoint.AllPlayersData.Dictionary.TryGetValue(cpid, out MyObjectBuilder_Player player);

            if (player != null)
            {
                //Toolbars.SaveToolbars(checkpoint);
                MyToolbar toolbar = MySession.Static.Toolbars.TryGetPlayerToolbar(ppid);
                if (toolbar != null)
                {
                    player.Toolbar = toolbar.GetObjectBuilder();
                }
                else if (EssentialsPlugin.Instance.Config.EnableToolbarOverride)
                {
                    player.Toolbar = EssentialsPlugin.Instance.Config.DefaultToolbar;
                }

                //MySession.Static.Cameras.SaveCameraCollection(checkpoint);
                player.EntityCameraData = _cameraSettings;
                Dictionary <MyPlayer.PlayerId, Dictionary <long, MyEntityCameraSettings> > d = EntityCameraSettings;
                if (d.TryGetValue(ppid, out Dictionary <long, MyEntityCameraSettings> camera))
                {
                    foreach (KeyValuePair <long, MyEntityCameraSettings> cameraSetting in camera)
                    {
                        var set = Pool.AllocateOrCreate <CameraControllerSettings>();
                        set.Distance      = cameraSetting.Value.Distance;
                        set.IsFirstPerson = cameraSetting.Value.IsFirstPerson;
                        set.HeadAngle     = cameraSetting.Value.HeadAngle;
                        set.EntityId      = cameraSetting.Key;

                        player.EntityCameraData.Add(set);
                    }
                }

                //Gpss.SaveGpss(checkpoint);

                foreach (IMyGps igps in MyAPIGateway.Session.GPS.GetGpsList(player.IdentityId))
                {
                    var gps = igps as MyGps;
                    if (!gps.IsLocal)
                    {
                        if (gps.EntityId == 0 || MyEntities.GetEntityById(gps.EntityId) != null)
                        {
                            var builder = new MyObjectBuilder_Gps.Entry
                            {
                                name          = gps.Name,
                                description   = gps.Description,
                                coords        = gps.Coords,
                                isFinal       = gps.DiscardAt == null,
                                showOnHud     = gps.ShowOnHud,
                                alwaysVisible = gps.AlwaysVisible,
                                color         = gps.GPSColor,
                                entityId      = gps.EntityId,
                                DisplayName   = gps.DisplayName
                            };
                            bGps.Entries.Add(builder);
                        }
                    }
                }

                _checkpoint.Gps.Dictionary.Add(player.IdentityId, bGps);
            }

            if (MyFakes.ENABLE_MISSION_TRIGGERS)
            {
                //usually empty, so meh
                _checkpoint.MissionTriggers = MySessionComponentMissionTriggers.Static.GetObjectBuilder();
            }

            //bunch of allocations in here, but can't replace the logic easily because private types
            _checkpoint.Factions = MySession.Static.Factions.GetObjectBuilder();

            //ok for now, clients need to know about dead identities. Might filter out those that own no blocks.
            //amount of data per ID is low, and admins usually clean them, so meh
            //_checkpoint.Identities = Sync.Players.SaveIdentities();
            foreach (MyIdentity identity in MySession.Static.Players.GetAllIdentities())
            {
                if (MySession.Static.Players.TryGetPlayerId(identity.IdentityId, out MyPlayer.PlayerId id))
                {
                    MyPlayer p = MySession.Static.Players.GetPlayerById(id);
                    if (p != null)
                    {
                        identity.LastLogoutTime = DateTime.Now;
                    }
                }

                var objectBuilder = Pool.AllocateOrCreate <MyObjectBuilder_Identity>();
                objectBuilder.IdentityId         = identity.IdentityId;
                objectBuilder.DisplayName        = identity.DisplayName;
                objectBuilder.CharacterEntityId  = identity.Character?.EntityId ?? 0;
                objectBuilder.Model              = identity.Model;
                objectBuilder.ColorMask          = identity.ColorMask;
                objectBuilder.BlockLimitModifier = identity.BlockLimits.BlockLimitModifier;
                objectBuilder.LastLoginTime      = identity.LastLoginTime;
                objectBuilder.LastLogoutTime     = identity.LastLogoutTime;
                objectBuilder.SavedCharacters    = identity.SavedCharacters;
                objectBuilder.RespawnShips       = identity.RespawnShips;
                objectBuilder.LastDeathPosition  = identity.LastDeathPosition;

                _checkpoint.Identities.Add(objectBuilder);
            }

            Sync.Players.RespawnComponent.SaveToCheckpoint(_checkpoint);
            //count for these is low, and the store is internal, so removing unnecessary entries is cheaper than reflection (probably?)
            _checkpoint.RespawnCooldowns.RemoveAll(i => i.PlayerSteamId != steamId);

            //checkpoint.ControlledEntities = Sync.Players.SerializeControlledEntities();
            foreach (KeyValuePair <long, MyPlayer.PlayerId> entry in MySession.Static.Players.ControlledEntities)
            {
                if (entry.Value.SteamId == steamId)
                {
                    _checkpoint.ControlledEntities.Dictionary.Add(entry.Key, cpid);
                }
            }

            //checkpoint.SpectatorPosition = new MyPositionAndOrientation(ref spectatorMatrix);
            //checkpoint.SpectatorIsLightOn = MySpectatorCameraController.Static.IsLightOn;
            //checkpoint.SpectatorCameraMovement = MySpectator.Static.SpectatorCameraMovement;
            //checkpoint.SpectatorDistance = (float)MyThirdPersonSpectator.Static.GetViewerDistance();
            //checkpoint.CameraController = cameraControllerEnum;
            //if (cameraControllerEnum == MyCameraControllerEnum.Entity)
            //    checkpoint.CameraEntity = ((MyEntity)CameraController).EntityId;
            //if (ControlledEntity != null)
            //{
            //    checkpoint.ControlledObject = ControlledEntity.Entity.EntityId;

            //    if (ControlledEntity is MyCharacter)
            //    {
            //        Debug.Assert(LocalCharacter == null || !(LocalCharacter.IsUsing is MyCockpit), "Character in cockpit cannot be controlled entity");
            //    }
            //}
            //else
            _checkpoint.ControlledObject = -1;

            //SaveChatHistory(checkpoint);

            /*
             * if (player != null && MySession.Static.ChatHistory.TryGetValue(player.IdentityId, out MyChatHistory playerChat))
             * {
             *  var builder = Pool.AllocateOrCreate<MyObjectBuilder_ChatHistory>();
             *  builder.IdentityId = playerChat.IdentityId;
             *  if (builder.PlayerChatHistory != null)
             *      Pool.DeallocateAndClear(builder.PlayerChatHistory);
             *  else
             *      builder.PlayerChatHistory = new List<MyObjectBuilder_PlayerChatHistory>();
             *  foreach (MyPlayerChatHistory chat in playerChat.PlayerChatHistory.Values)
             *  {
             *      var cb = Pool.AllocateOrCreate<MyObjectBuilder_PlayerChatHistory>();
             *      if (cb.Chat != null)
             *          Pool.DeallocateAndClear(cb.Chat);
             *      else
             *          cb.Chat = new List<MyObjectBuilder_PlayerChatItem>();
             *      cb.IdentityId = chat.IdentityId;
             *      foreach (MyPlayerChatItem m in chat.Chat)
             *      {
             *          var mb = Pool.AllocateOrCreate<MyObjectBuilder_PlayerChatItem>();
             *          mb.Text = m.Text;
             *          mb.IdentityIdUniqueNumber = MyEntityIdentifier.GetIdUniqueNumber(m.IdentityId);
             *          mb.TimestampMs = (long)m.Timestamp.TotalMilliseconds;
             *          mb.Sent = m.Sent;
             *          cb.Chat.Add(mb);
             *      }
             *      builder.PlayerChatHistory.Add(cb);
             *  }
             *
             *  if (builder.GlobalChatHistory == null)
             *      builder.GlobalChatHistory = Pool.AllocateOrCreate<MyObjectBuilder_GlobalChatHistory>();
             *  if (builder.GlobalChatHistory.Chat != null)
             *      Pool.DeallocateAndClear(builder.GlobalChatHistory.Chat);
             *  else
             *      builder.GlobalChatHistory.Chat = new List<MyObjectBuilder_GlobalChatItem>();
             *
             *  foreach (MyGlobalChatItem g in playerChat.GlobalChatHistory.Chat)
             *  {
             *      var gb = Pool.AllocateOrCreate<MyObjectBuilder_GlobalChatItem>();
             *      gb.Text = g.Text;
             *      gb.Font = g.AuthorFont;
             *      if (g.IdentityId == 0)
             *      {
             *          gb.IdentityIdUniqueNumber = 0;
             *          gb.Author = g.Author;
             *      }
             *      else
             *      {
             *          gb.IdentityIdUniqueNumber = MyEntityIdentifier.GetIdUniqueNumber(g.IdentityId);
             *          gb.Author = string.Empty;
             *      }
             *      builder.GlobalChatHistory.Chat.Add(gb);
             *  }
             *
             *  _checkpoint.ChatHistory.Add(builder);
             * }
             *
             * if (player != null)
             * {
             *  IMyFaction pfac = MySession.Static.Factions.TryGetPlayerFaction(player.IdentityId);
             *  if (pfac != null)
             *  {
             *      foreach (MyFactionChatHistory history in MySession.Static.FactionChatHistory)
             *      {
             *          if (history.FactionId1 == pfac.FactionId || history.FactionId2 == pfac.FactionId)
             *          {
             *              var builder = Pool.AllocateOrCreate<MyObjectBuilder_FactionChatHistory>();
             *              if (builder.Chat != null)
             *                  Pool.DeallocateAndClear(builder.Chat);
             *              else
             *                  builder.Chat = new List<MyObjectBuilder_FactionChatItem>();
             *
             *              builder.FactionId1 = history.FactionId1;
             *              builder.FactionId2 = history.FactionId2;
             *
             *              foreach (MyFactionChatItem fc in history.Chat)
             *              {
             *                  if (fc.PlayersToSendTo != null && fc.PlayersToSendTo.Count > 0)
             *                  {
             *                      var fb = Pool.AllocateOrCreate<MyObjectBuilder_FactionChatItem>();
             *                      fb.Text = fc.Text;
             *                      fb.IdentityIdUniqueNumber = MyEntityIdentifier.GetIdUniqueNumber(fc.IdentityId);
             *                      fb.TimestampMs = (long)fc.Timestamp.TotalMilliseconds;
             *                      if (fb.PlayersToSendToUniqueNumber != null)
             *                          fb.PlayersToSendToUniqueNumber.Clear();
             *                      else
             *                          fb.PlayersToSendToUniqueNumber = new List<long>();
             *                      if (fb.IsAlreadySentTo != null)
             *                          fb.IsAlreadySentTo.Clear();
             *                      else
             *                          fb.IsAlreadySentTo = new List<bool>();
             *                      foreach (KeyValuePair<long, bool> pair in fc.PlayersToSendTo)
             *                      {
             *                          fb.PlayersToSendToUniqueNumber.Add(MyEntityIdentifier.GetIdUniqueNumber(pair.Key));
             *                          fb.IsAlreadySentTo.Add(pair.Value);
             *                      }
             *                      builder.Chat.Add(fb);
             *                  }
             *              }
             *          }
             *      }
             *  }
             * }
             */

            //_checkpoint.Clients = SaveMembers_Imp(MySession.Static, false);
            if (MyMultiplayer.Static.Members.Count() > 1)
            {
                foreach (ulong member in MyMultiplayer.Static.Members)
                {
                    var ob = Pool.AllocateOrCreate <MyObjectBuilder_Client>();
                    ob.SteamId = member;
                    ob.Name    = MyMultiplayer.Static.GetMemberName(member);
                    ob.IsAdmin = MySession.Static.IsUserAdmin(member);
                    _checkpoint.Clients.Add(ob);
                }
            }

            //_checkpoint.NonPlayerIdentities = Sync.Players.SaveNpcIdentities();
            foreach (long npc in MySession.Static.Players.GetNPCIdentities())
            {
                _checkpoint.NonPlayerIdentities.Add(npc);
            }

            //SaveSessionComponentObjectBuilders(checkpoint);
            CachingDictionary <Type, MySessionComponentBase> compDic = SessionComponents_Getter(MySession.Static);

            foreach (KeyValuePair <Type, MySessionComponentBase> entry in compDic)
            {
                //literally dozens of MB of duplicated garbage. Ignore all of it.
                //TODO: Keen fixed the duplication but this shouldn't exist at all. Rexxar has a plan
                //if (entry.Value is MyProceduralWorldGenerator)
                //    continue;

                MyObjectBuilder_SessionComponent ob = entry.Value.GetObjectBuilder();
                if (ob != null)
                {
                    _checkpoint.SessionComponents.Add(ob);
                }
            }

            _checkpoint.ScriptManagerData = MySession.Static.ScriptManager.GetObjectBuilder();

            //skipped on DS
            //GatherVicinityInformation(checkpoint);

            //if (OnSavingCheckpoint != null)
            //    OnSavingCheckpoint(checkpoint);
            Log.Info("Done.");
            return(_checkpoint);
        }
Пример #15
0
 public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
 {
     Instance = this;
 }
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            base.Init(sessionComponent);

            var ob = sessionComponent as MyObjectBuilder_LocalizationSessionComponent;

            if (ob != null)
            {
                m_language = ob.Language;
                LoadCampaignLocalization(ob.CampaignPaths, m_campaignModFolderName);
            }
        }
Пример #17
0
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            base.Init(sessionComponent);

            // Only servers can run this session component
            if (!Session.IsServer)
            {
                return;
            }
            MyObjectBuilder_VisualScriptManagerSessionComponent ob = (MyObjectBuilder_VisualScriptManagerSessionComponent)sessionComponent;

            m_objectBuilder = ob;
            m_relativePathsToAbsolute.Clear();
            m_stateMachineDefinitionFilePaths.Clear();

            // Runs game started event
            m_firstUpdate = ob.FirstRun;

            // load vanilla level script files
            if (ob.LevelScriptFiles != null)
            {
                foreach (string relativeFilePath in ob.LevelScriptFiles)
                {
                    var absolutePath = Path.Combine(MyFileSystem.ContentPath, relativeFilePath);
                    // Add only existing files
                    if (MyFileSystem.FileExists(absolutePath))
                    {
                        m_relativePathsToAbsolute.Add(relativeFilePath, absolutePath);
                    }
                    else
                    {
                        MyLog.Default.WriteLine(relativeFilePath + " Level Script was not found.");
                        Debug.Fail(relativeFilePath + " Level Script was not found.");
                    }
                }
            }

            // load vanilla mission manchines
            if (ob.StateMachines != null)
            {
                foreach (var relativeFilePath in ob.StateMachines)
                {
                    var absolutePath = Path.Combine(MyFileSystem.ContentPath, relativeFilePath);
                    // Add only existing files
                    if (MyFileSystem.FileExists(absolutePath))
                    {
                        if (!m_relativePathsToAbsolute.ContainsKey(relativeFilePath))
                        {
                            m_stateMachineDefinitionFilePaths.Add(absolutePath);
                        }

                        m_relativePathsToAbsolute.Add(relativeFilePath, absolutePath);
                    }
                    else
                    {
                        MyLog.Default.WriteLine(relativeFilePath + " Mission File was not found.");
                        Debug.Fail(relativeFilePath + " Mission File was not found.");
                    }
                }
            }

            // Load mission machines and level scripts from mods
            // Overrides vanilla files
            if (Session.Mods != null)
            {
                foreach (var modItem in Session.Mods)
                {
                    // First try is a mod archive
                    var directoryPath = Path.Combine(MyFileSystem.ModsPath, modItem.PublishedFileId + ".sbm");
                    if (!MyFileSystem.DirectoryExists(directoryPath))
                    {
                        directoryPath = Path.Combine(MyFileSystem.ModsPath, modItem.Name);
                        if (!MyFileSystem.DirectoryExists(directoryPath))
                        {
                            directoryPath = null;
                        }
                    }

                    if (!string.IsNullOrEmpty(directoryPath))
                    {
                        foreach (var filePath in MyFileSystem.GetFiles(directoryPath, "*", MySearchOption.AllDirectories))
                        {
                            var extension    = Path.GetExtension(filePath);
                            var relativePath = MyFileSystem.MakeRelativePath(Path.Combine(directoryPath, "VisualScripts"), filePath);
                            if (extension == ".vs" || extension == ".vsc")
                            {
                                if (m_relativePathsToAbsolute.ContainsKey(relativePath))
                                {
                                    m_relativePathsToAbsolute[relativePath] = filePath;
                                }
                                else
                                {
                                    m_relativePathsToAbsolute.Add(relativePath, filePath);
                                }
                            }
                        }
                    }
                }
            }

            // Provider will compile all required scripts for the session.
            MyVSAssemblyProvider.Init(m_relativePathsToAbsolute.Values);
            // Retrive the Level script instances
            m_levelScripts = new CachingList <IMyLevelScript>();
            var scriptInstances = MyVSAssemblyProvider.GetLevelScriptInstances();

            if (scriptInstances != null)
            {
                scriptInstances.ForEach(script => m_levelScripts.Add(script));
            }
            m_levelScripts.ApplyAdditions();

            // Store the names of the level scripts
            m_runningLevelScriptNames         = m_levelScripts.Select(x => x.GetType().Name).ToArray();
            m_failedLevelScriptExceptionTexts = new string[m_runningLevelScriptNames.Length];

            // mission manager initialization - state machine definitions
            m_smManager = new MyVSStateMachineManager();
            foreach (var stateMachineFilePath in m_stateMachineDefinitionFilePaths)
            {
                m_smManager.AddMachine(stateMachineFilePath);
            }

            // Restore the statemachines that were running before the save happened.
            if (m_objectBuilder != null && m_objectBuilder.ScriptStateMachineManager != null)
            {
                foreach (var cursorData in m_objectBuilder.ScriptStateMachineManager.ActiveStateMachines)
                {
                    if (!m_smManager.Restore(cursorData.StateMachineName, cursorData.Cursors))
                    {
                        Debug.Fail("Failed to load " + cursorData.StateMachineName + " mission state machine cursors.");
                    }
                }
            }
        }
Пример #18
0
        //variables for scripts:
        public override void Init(MyObjectBuilder_SessionComponent sessionComponentBuilder)
        {
            base.Init(sessionComponentBuilder);

            var ob = (MyObjectBuilder_ScriptManager)sessionComponentBuilder;
            MyAPIUtilities.Static.Variables = ob.variables.Dictionary;
        }
        public virtual void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            m_initialized = true;

        }
Пример #20
0
 public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
 {
     base.Init(sessionComponent);
     SetupTestItem2();
 }
        /// <summary>
        /// Initializes this component and sets the singleton instance
        /// </summary>
        /// <param name="sessionComponent"></param>
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            base.Init(sessionComponent);

            Static = this;
        }
Пример #22
0
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            base.Init(sessionComponent);

            var ob = sessionComponent as MyObjectBuilder_PirateAntennas;

            m_piratesIdentityId = ob.PiratesIdentity;

            int currentTime = MySandboxGame.TotalGamePlayTimeInMilliseconds;

            if (ob.Drones != null)
            {
                foreach (var entry in ob.Drones)
                {
                    m_droneInfos.Add(entry.EntityId, DroneInfo.Allocate(entry.AntennaEntityId, currentTime + entry.DespawnTimer), immediate: true);
                }
            }
        }
 public virtual void Init(MyObjectBuilder_SessionComponent sessionComponent)
 {
 }
Пример #24
0
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            MyAPIGateway.Utilities.SendModMessage(2546247, MyAPIGateway.Utilities.SerializeToBinary(@"
		LargeBlockBatteryBlock@15;
                BattleshipCannon@60;
                BattleshipCannonMK2@110;
                BattleshipCannonMK22@110;
                BattleshipCannonMK3@275;
                BFG_M@500;
                RailgunxTurretS@150;
                RailgunxTurretM@275;
                RailgunxTurret@400;
		StaticBattery1@100;
		StaticBattery1Stack@100;
		Railgunx@150;
                M1Torpedo@400;
                M8Launcher@300;
                BFTriCannon@375;
                MXA_SMAC@3000;
                C100mmTurret@100;
                C200mmTurret@160;
		C300mmTurret@300;
                CIWS@175;
                AMSlaser@125;
                AS2@450;
                AS3@300;
                AS4@500;
                EmitterL@50;
                EmitterLA@50;
                LargeShieldModulator@15;
                LargeEnhancer@15;
                MA_Gladius@450;
                MA_PDT@100;
                MA_Gimbal_Laser@80;
                MA_Gimbal_Laser_Armored@80;
                MA_Gimbal_Laser_Armored_Slope@80;
                MA_Gimbal_Laser_Armored_Slope2@80;
                MA_Gimbal_Laser_Armored_Slope45@80;
                MA_PDX@225;
                MA_Gimbal_Laser_T2@100;
                MA_Gimbal_Laser_T2_Armored@100;
                MA_Gimbal_Laser_T2_Armored_Slope@100;
                MA_Gimbal_Laser_T2_Armored_Slope2@100;
                MA_Gimbal_Laser_T2_Armored_Slope45@100;
                MA_T2PDX@120;
                MA_T2PDX_Slope@120;
                MA_T2PDX_Slope2@120;
                MA_Fixed_000@50;
                MA_Fixed_001@50;
                MA_Fixed_002@50;
                MA_Fixed_007@50;
                MA_Fixed_003@50;
                MA_Fixed_004@50;
                MA_Fixed_005@50;
                MA_Fixed_006@50;
                MA_Blister@50;
                MA_Blister45@50;
                MA_Blister30@50;
                MA_Blister32@50;
                MA_Meatball@150;
                MA_Tiger@150;
                MA_Designator@20;
                LargeBlockSmallGenerator@18;
                LargeBlockLargeGenerator@300;
                LargeBlockSmallThrust@15;
                LargeBlockLargeThrust@110;
                LargeBlockLargeIon@110;
                LargeBlockSmallIon@15;
		LargeBlockSmallThrustSciFi@15;
		LargeBlockLargeThrustSciFi@110;
                AQD_LG_IonThrusterS_ArmoredSlope@15;
                AQD_LG_IonThrusterS_Armored@15;
                AQD_LG_IonThrusterL_ArmoredSlope@110;
                AQD_LG_IonThrusterL_Armored@110;
                IonHeavyCovered@450;
                LargeWarhead@20;
                LargeDecoy@10;
                LargeStator@50;
                LargeAdvancedStator@50;
                LargeHinge@50;
                LargePistonBase@50;
                MCRNPDCTurretLB@200;
                MCRNPDCTurretSB@200;
                MCRNRightRetractPDC@200;
                MCRNLeftRetractPDC@200;
                MCRNTopRetractPDC@200;
                K_SA_Launcher_FixedMount@500;
                MA_Buster_ArmorBlock@1;
                MA_Buster_Window@1;
                MA_Buster_Camera@1;
                LargeBlockRemoteControl@50;
                LargeProgrammableBlock@50;
            "));
        }