Exemple #1
0
        private static void SendRemoveSystemObjectServer(Guid objectId, ulong callbackId, ulong clientId)
        {
            MyPluginLog.Log("Server: Removing object " + objectId.ToString() + " from system");
            MySystemObject o = Static.StarSystem.GetObjectById(objectId);

            if (o != null && o.DisplayName != Static.StarSystem.CenterObject.DisplayName)
            {
                if (o.Type == MySystemObjectType.ASTEROIDS)
                {
                    var asteroids = o as MySystemAsteroids;
                    if (MyAsteroidObjectsManager.Static.AsteroidObjectProviders.ContainsKey(asteroids.AsteroidTypeName))
                    {
                        bool removed = MyAsteroidObjectsManager.Static.AsteroidObjectProviders[asteroids.AsteroidTypeName].RemoveInstance(asteroids);
                        if (removed)
                        {
                            MyGPSManager.Static.RemovePersistentGps(objectId);
                            PluginEventHandler.Static.RaiseStaticEvent(SendSimpleActionCallbackClient, Static.StarSystem.RemoveObject(objectId), callbackId, clientId);
                            return;
                        }
                    }
                }
                else
                {
                    MyGPSManager.Static.RemovePersistentGps(objectId);
                    PluginEventHandler.Static.RaiseStaticEvent(SendSimpleActionCallbackClient, Static.StarSystem.RemoveObject(objectId), callbackId, clientId);
                    return;
                }
            }
            PluginEventHandler.Static.RaiseStaticEvent(SendSimpleActionCallbackClient, false, callbackId, clientId);
        }
        /// <summary>
        /// Loads data used by the procedural generator
        /// </summary>
        public override void LoadData()
        {
            if (!MySettingsSession.Static.IsEnabled())
            {
                return;
            }

            MyPluginLog.Log("Loading Procedural Generator Component");

            Static = this;

            m_procDensity = MySession.Static.Settings.ProceduralDensity;
            m_seed        = MySession.Static.Settings.ProceduralSeed;

            if (MySettingsSession.Static.Settings.GeneratorSettings.AsteroidGenerator == ObjectBuilders.AsteroidGenerationMethod.PLUGIN)
            {
                MySession.Static.Settings.ProceduralDensity = 0f;
            }

            m_isEnabled = true;

            //Add default impl of registering of standard generator components
            RegisterModule(new MyProceduralPlanetModule(m_seed));
            RegisterModule(new MyProceduralAsteroidsModule(m_seed));

            MyPluginLog.Log("Loading Procedural Generator Component completed");
        }
 /// <summary>
 /// Tries to apply the harmony patches to fix more complicated bugs.
 /// Will only actually patch, if 0harmony.dll is found AND patching is enabled in the global settings.
 /// </summary>
 private void TryEnablePatches()
 {
     if (settings.Settings.EnablePatching)
     {
         try
         {
             MyPluginLog.Log("Patching...");
             Patch();
             MyPluginLog.Log("Patches applied");
         }
         catch (FileNotFoundException)
         {
             MyPluginLog.Log("0harmony.dll not found, skipping patching.", LogLevel.WARNING);
         }
         catch (Exception e)
         {
             MyPluginLog.Log("Something went wrong while patching: ", LogLevel.ERROR);
             MyPluginLog.Log(e.StackTrace, LogLevel.ERROR);
         }
     }
     else
     {
         MyPluginLog.Log("Patching is disabled, skipping patches.");
     }
 }
        /// <summary>
        /// Retreives the data for the vanilla asteroid generator to
        /// correctly generate asteroids.
        /// </summary>
        /// <returns>The asteroid generator definition</returns>
        private MyAsteroidGeneratorDefinition GetData()
        {
            MyAsteroidGeneratorDefinition myAsteroidGeneratorDefinition = null;
            int voxelGeneratorVersion = MySession.Static.Settings.VoxelGeneratorVersion;

            foreach (MyAsteroidGeneratorDefinition value in MyDefinitionManager.Static.GetAsteroidGeneratorDefinitions().Values)
            {
                if (value.Version == voxelGeneratorVersion)
                {
                    myAsteroidGeneratorDefinition = value;
                    break;
                }
            }
            if (myAsteroidGeneratorDefinition == null)
            {
                MyPluginLog.Log("Generator of version " + voxelGeneratorVersion + "not found!");
                {
                    foreach (MyAsteroidGeneratorDefinition value2 in MyDefinitionManager.Static.GetAsteroidGeneratorDefinitions().Values)
                    {
                        if (myAsteroidGeneratorDefinition == null || (value2.Version > voxelGeneratorVersion && (myAsteroidGeneratorDefinition.Version < voxelGeneratorVersion || value2.Version < myAsteroidGeneratorDefinition.Version)))
                        {
                            myAsteroidGeneratorDefinition = value2;
                        }
                    }
                    return(myAsteroidGeneratorDefinition);
                }
            }
            return(myAsteroidGeneratorDefinition);
        }
        /// <summary>
        /// Checks all planets of the star system, and whether they are still existent as objects
        /// in the world. Just to clear up deleted objects from the system at world loading
        /// </summary>
        private void CheckIntegrityOfSystem()
        {
            foreach (var obj in StarSystem.GetAllObjects())
            {
                if (obj is MySystemPlanet)
                {
                    if (!MyEntities.EntityExists((obj as MySystemPlanet).EntityId) && (obj as MySystemPlanet).Generated)
                    {
                        MyPluginLog.Debug("Planet " + obj.Id + " does not exist anymore, deleting it", LogLevel.WARNING);
                        StarSystem.RemoveObject(obj.Id);
                        MyGPSManager.Static.RemovePersistentGps(obj.Id);
                    }
                }
                else if (obj is MySystemAsteroids)
                {
                    var instance = obj as MySystemAsteroids;

                    if (MyAsteroidObjectsManager.Static.AsteroidObjectProviders.ContainsKey(instance.AsteroidTypeName))
                    {
                        var data = MyAsteroidObjectsManager.Static.AsteroidObjectProviders[instance.AsteroidTypeName].GetInstanceData(instance);
                        if (data == null)
                        {
                            MyPluginLog.Debug("Asteroid instance " + obj.Id + " has no data attached, deleting it", LogLevel.WARNING);
                            MyAsteroidObjectsManager.Static.AsteroidObjectProviders[instance.AsteroidTypeName].RemoveInstance(instance);
                            MyGPSManager.Static.RemovePersistentGps(obj.Id);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Loads the savefile of the plugin settings of the world and stores it
        /// int the Settings member variable
        /// </summary>
        public override void LoadData()
        {
            MyPluginLog.Log("Loading Session settings data");
            Static = this;
            if (MyFileUtils.FileExistsInWorldStorage(FILE_NAME))
            {
                Settings = MyFileUtils.ReadXmlFileFromWorld <MyObjectBuilder_WorldSettings>(FILE_NAME);

                MyPluginLog.Log("Session settings read from file");
            }
            else
            {
                MyPluginLog.Log("Session settings do not exist, creating new ones.");
                if (MySettings.Static == null)
                {
                    var s = new MySettings();
                    s.LoadSettings();
                }
                if (MySettings.Static.SessionSettings != null)
                {
                    Settings = MySettings.Static.SessionSettings;
                }
                else
                {
                    Settings = new MyObjectBuilder_WorldSettings();
                }

                MySettings.Static.SessionSettings = null;
            }

            MyPluginLog.Log("Loading Session settings data completed");
        }
Exemple #7
0
        private static void SendAddSystemObjectServer(MySystemObject obj, Guid parentId, ulong callbackId, ulong clientId)
        {
            MyPluginLog.Log("Server: Add object " + obj.DisplayName + " to system");
            if (obj != null)
            {
                if (!Static.StarSystem.ObjectExists(obj.Id))
                {
                    var parent = Static.StarSystem.GetObjectById(parentId);
                    if (parent != null)
                    {
                        parent.ChildObjects.Add(obj);
                        obj.ParentId = parentId;
                        PluginEventHandler.Static.RaiseStaticEvent(SendSimpleActionCallbackClient, true, callbackId, clientId);
                    }
                    else
                    {
                        Static.StarSystem.CenterObject.ChildObjects.Add(obj);
                        obj.ParentId = Static.StarSystem.CenterObject.Id;
                        PluginEventHandler.Static.RaiseStaticEvent(SendSimpleActionCallbackClient, true, callbackId, clientId);
                    }

                    Static.AddAllPersistentGps();
                    return;
                }
            }
            PluginEventHandler.Static.RaiseStaticEvent(SendSimpleActionCallbackClient, false, callbackId, clientId);
        }
        /// <summary>
        /// Saves the gpss to the file
        /// </summary>
        public override void SaveData()
        {
            if (!MySettingsSession.Static.IsEnabled())
            {
                return;
            }

            MyPluginLog.Log("Saving GPS manager data");

            MyObjectBuilder_WorldGpsData ob = new MyObjectBuilder_WorldGpsData();

            foreach (var entry in m_globalGpss)
            {
                PersistentGpsData item = new PersistentGpsData();
                item.Name      = entry.Value.Name;
                item.Color     = entry.Value.Color;
                item.Position  = entry.Value.Position;
                item.PlayerIds = entry.Value.Players;
                item.Id        = entry.Key;
                item.Hidden    = entry.Value.Hidden;

                ob.PersistentGpss.Add(item);
            }

            MyFileUtils.WriteXmlFileToWorld(ob, FILENAME);

            MyPluginLog.Log("Saving GPS manager data completed");
        }
        /// <summary>
        /// Generates a random amount of moons for a planet
        /// </summary>
        /// <param name="parentPlanet"></param>
        /// <returns></returns>
        private MySystemPlanetMoon[] GeneratePlanetMoons(MySystemPlanet parentPlanet)
        {
            MyPluginLog.Log("Generating moons for planet " + parentPlanet.DisplayName);
            var settings = MySettingsSession.Static.Settings.GeneratorSettings;

            uint maxMoons = (uint)Math.Ceiling(parentPlanet.Diameter / 120000 * 2);

            maxMoons = (uint)Math.Min(maxMoons, settings.PlanetSettings.MinMaxMoons.Max);

            uint numMoons = (uint)MyRandom.Instance.Next(settings.PlanetSettings.MinMaxMoons.Min, (int)maxMoons + 1);

            numMoons = Math.Min(numMoons, 25);

            if (settings.SystemGenerator == SystemGenerationMethod.UNIQUE)
            {
                numMoons = Math.Min(numMoons, (uint)m_moons.Count);
            }

            MySystemPlanetMoon[] moons = new MySystemPlanetMoon[numMoons];

            for (int i = 0; i < numMoons; i++)
            {
                MyPluginLog.Log("Generating moon " + i);

                double distance = parentPlanet.Diameter * (i + 1) + parentPlanet.Diameter * MyRandom.Instance.GetRandomFloat(1f, 1.5f);
                double diameter;

                var definition = FindPlanetDefinitionForSize(parentPlanet.Diameter * 0.75f, out diameter, true);
                if (definition == null)
                {
                    return(moons);
                }

                Vector3D position;

                int tries2 = 0;

                do
                {
                    double angle = MyRandom.Instance.GetRandomFloat(0, (float)Math.PI * 2f);
                    position = new Vector3D(distance * Math.Sin(angle), distance * Math.Cos(angle), distance * Math.Sin(MyRandom.Instance.GetRandomFloat((float)-Math.PI / 2, (float)Math.PI / 2)));
                    position = Vector3D.Add(position, parentPlanet.CenterPosition);
                } while (IsMoonPositionObstructed(position, diameter, parentPlanet, moons) && ++tries2 < MAX_DEF_FIND_ROUNDS);

                MySystemPlanetMoon moon = new MySystemPlanetMoon();
                moon.CenterPosition = position;
                moon.Diameter       = diameter;
                moon.DisplayName    = GetMoonName(i, definition.Id.SubtypeId.String, parentPlanet.DisplayName);
                moon.SubtypeId      = definition.Id.SubtypeId.String;
                moon.ParentId       = parentPlanet.Id;

                moons[i] = moon;
            }

            MyPluginLog.Log("Generating moons for planet " + parentPlanet.DisplayName + " completed");

            return(moons);
        }
        protected override MyProceduralCell GenerateCellSeeds(Vector3I cellId)
        {
            if (m_loadedCells.ContainsKey(cellId))
            {
                return(null);
            }

            var settings = MySettingsSession.Static.Settings.GeneratorSettings;

            if (settings.AsteroidGenerator == AsteroidGenerationMethod.VANILLA)
            {
                return(null);
            }

            MyProceduralCell cell = new MyProceduralCell(cellId, CELL_SIZE);
            int    cellSeed       = CalculateCellSeed(cellId);
            int    index          = 0;
            double subCellSize    = OBJECT_SIZE_MAX * 1f / settings.AsteroidDensity;
            int    subcells       = (int)(CELL_SIZE / subCellSize);

            using (MyRandom.Instance.PushSeed(cellSeed))
            {
                Vector3I subcellId = Vector3I.Zero;
                Vector3I max       = new Vector3I(subcells - 1);

                for (var it = new Vector3I_RangeIterator(ref Vector3I.Zero, ref max); it.IsValid(); it.GetNext(out subcellId))
                {
                    Vector3D position = new Vector3D(MyRandom.Instance.NextDouble(), MyRandom.Instance.NextDouble(), MyRandom.Instance.NextDouble());
                    position += (Vector3D)subcellId;
                    position *= subCellSize;
                    position += ((Vector3D)cellId) * CELL_SIZE;

                    if (!MyEntities.IsInsideWorld(position) || (settings.WorldSize >= 0 && position.Length() > settings.WorldSize))
                    {
                        continue;
                    }

                    var ring = GetAsteroidObjectAt(position);

                    if (ring == null)
                    {
                        continue;
                    }

                    var cellObjectSeed = new MyObjectSeed(cell, position, MyRandom.Instance.Next(ring.AsteroidSize.Min, ring.AsteroidSize.Max));
                    cellObjectSeed.Params.Type          = VRage.Game.MyObjectSeedType.Asteroid;
                    cellObjectSeed.Params.Seed          = MyRandom.Instance.Next();
                    cellObjectSeed.Params.Index         = index++;
                    cellObjectSeed.Params.GeneratorSeed = m_definition.UseGeneratorSeed ? MyRandom.Instance.Next() : 0;

                    cell.AddObject(cellObjectSeed);

                    MyPluginLog.Debug("Adding seed");
                }
            }

            return(cell);
        }
        /// <summary>
        /// Builds the spawn menu
        /// </summary>
        private void BuildSpawnMenu()
        {
            MyPluginLog.Debug("Create Spawn Menu");

            var     topCombo = GetCombo();
            Vector2 start    = topCombo.Position + new Vector2(0, MARGIN_VERT * 2 + GetCombo().Size.Y);
            Vector2 end      = start + new Vector2(topCombo.Size.X, 0.8f - MARGIN_VERT);

            MyGuiControlParentTableLayout table = new MyGuiControlParentTableLayout(1, false, Vector2.Zero);

            table.OriginAlign = MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP;

            m_spawnTypeCombo = new MyGuiControlCombobox();
            m_spawnTypeCombo.AddItem(0L, "Planet");
            m_spawnTypeCombo.AddItem(1L, "Asteroid object");
            m_spawnTypeCombo.OriginAlign = MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP;
            m_spawnTypeCombo.SelectItemByKey(m_spawnType);
            m_spawnTypeCombo.ItemSelected += OnSpawnTypeChange;
            m_spawnTypeCombo.Size          = new Vector2(m_usableWidth * 0.9f, m_spawnTypeCombo.Size.Y);
            m_spawnTypeCombo.SetToolTip(MyPluginTexts.TOOLTIPS.ADMIN_SPAWN_TYPE);

            table.AddTableRow(m_spawnTypeCombo);

            table.AddTableSeparator();

            switch (m_spawnType)
            {
            case 0L:
                CreatePlanetSpawnMenu(table);
                break;

            case 1L:
                CreateAsteroidSpawnMenu(table);
                break;
            }

            table.AddTableSeparator();

            table.ApplyRows();

            MyGuiControlScrollablePanel scrollPane = new MyGuiControlScrollablePanel(table);

            scrollPane.OriginAlign       = MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_TOP;
            scrollPane.ScrollbarVEnabled = true;
            scrollPane.Size     = end - start;
            scrollPane.Size     = new Vector2(0.315f, scrollPane.Size.Y);
            scrollPane.Position = new Vector2(0, start.Y);

            Controls.Add(scrollPane);

            MyGuiControlSeparatorList sep = new MyGuiControlSeparatorList();

            sep.AddHorizontal(new Vector2(scrollPane.Position.X - scrollPane.Size.X / 2, scrollPane.Position.Y + scrollPane.Size.Y), m_usableWidth);

            Controls.Add(sep);

            MyPluginLog.Debug("Added spawn menu");
        }
Exemple #12
0
        /// <summary>
        /// Verifies a double and sets it to def, if it is outside of the min max bounds.
        /// </summary>
        /// <param name="min">Minimum value</param>
        /// <param name="max">Maximum value</param>
        /// <param name="def">Default value</param>
        /// <param name="name">Name of the variable</param>
        /// <param name="value">Reference to the value to check</param>
        public static void VerifyDouble(double min, double max, double def, string name, ref double value)
        {
            if (value < min || value > max)
            {
                value = def;

                MyPluginLog.Log("Config value " + name + " of was invalid and will be set to default.", LogLevel.WARNING);
            }
        }
        /// <summary>
        /// Saves the system objects to a file, if the plugin is enabled.
        /// </summary>
        public override void SaveData()
        {
            if (MySettingsSession.Static.IsEnabled())
            {
                MyPluginLog.Log("Saving system data");

                MyFileUtils.WriteXmlFileToWorld(StarSystem, STORAGE_FILE);
            }
        }
Exemple #14
0
 private static void SendGetStarSystemClient(MyObjectBuilder_SystemData starSystem, ulong callbackId)
 {
     MyPluginLog.Debug("Client: Received star system");
     if (Static.m_getSystemCallbacks.ContainsKey(callbackId))
     {
         Static.m_getSystemCallbacks[callbackId](starSystem);
         Static.m_getSystemCallbacks.Remove(callbackId);
     }
 }
        /// <summary>
        /// Registers a new module for this instance of the procedural generator
        /// </summary>
        /// <param name="module"></param>
        public void RegisterModule(MyAbstractProceduralObjectModul module)
        {
            MyPluginLog.Log("Registering new Procedural generation module " + module.GetType());

            if (!m_objectModules.Contains(module))
            {
                m_objectModules.Add(module);
            }
        }
Exemple #16
0
 private static void SendSimpleActionCallbackClient(bool success, ulong callbackId)
 {
     MyPluginLog.Log("Client: Getting simple callback with success=" + success + " from server");
     if (Static.m_simpleActionsCallbacks.ContainsKey(callbackId))
     {
         Static.m_simpleActionsCallbacks[callbackId](success);
         Static.m_simpleActionsCallbacks.Remove(callbackId);
     }
 }
        /// <summary>
        /// Generates a ring for the given planet
        /// </summary>
        /// <param name="parentPlanet">Planet the ring is based on</param>
        /// <returns>The ring for the planet</returns>
        private MySystemAsteroids GenrateRing(MySystemPlanet parentPlanet)
        {
            MyPluginLog.Log("Generating ring for planet " + parentPlanet.DisplayName);

            var provider = MyAsteroidObjectsManager.Static.AsteroidObjectProviders[MyAsteroidRingProvider.TYPE_NAME];
            var ring     = provider.GenerateInstance(0, parentPlanet, 0);

            return(ring);
        }
Exemple #18
0
        /// <summary>
        /// Verifies a float and sets it to def, if it is outside of the min max bounds.
        /// </summary>
        /// <param name="min">Minimum value</param>
        /// <param name="max">Maximum value</param>
        /// <param name="def">Default value</param>
        /// <param name="name">Name of the variable</param>
        /// <param name="value">Reference to the value to check</param>
        public static void VerifyFloat(float min, float max, float def, string name, ref float value)
        {
            if (value < min || value > max)
            {
                value = def;

                MyPluginLog.Log("Config value " + name + " of was invalid and will be set to default.", LogLevel.WARNING);
            }
        }
        /// <summary>
        /// Unloads used data.
        /// </summary>
        protected override void UnloadData()
        {
            MyPluginLog.Log("Unloading Procedural Generator Component");

            m_trackedEntities.Clear();
            m_cellModules.Clear();
            m_objectModules.Clear();

            MyPluginLog.Log("Unloading Procedural Generator Component completed");
        }
Exemple #20
0
        private static void SendGetObjectClient(bool success, MySystemObject obj, ulong callbackId)
        {
            MyPluginLog.Log("Client: Received get object message from server with success " + success);

            if (Static.m_getActionCallbacks.ContainsKey(callbackId))
            {
                Static.m_getActionCallbacks[callbackId](success, obj);
                Static.m_getActionCallbacks.Remove(callbackId);
            }
        }
Exemple #21
0
        protected override void UnloadData()
        {
            MyPluginLog.Log("Asteroid object manager unloading data");

            base.UnloadData();

            AsteroidObjectProviders.Clear();
            Static = null;

            MyPluginLog.Log("Asteroid object manager unloading data completed");
        }
Exemple #22
0
        public override void LoadData()
        {
            base.LoadData();

            MyPluginLog.Log("Asteroid object manager loading data");

            Static = this;
            AsteroidObjectProviders = new Dictionary <string, MyAbstractAsteroidObjectProvider>();
            LoadAllAsteroidTypes();

            MyPluginLog.Log("Asteroid object manager loading data completed");
        }
Exemple #23
0
 /// <summary>
 /// Loads the global configuration file if it exists, otherwise creates a new one.
 /// </summary>
 public void LoadSettings()
 {
     MyPluginLog.Log("Loading the global config file");
     if (MyFileUtils.FileExistsInGlobalStorage(FILENAME))
     {
         try
         {
             using (var reader = MyFileUtils.ReadFileInGlobalStorage(FILENAME))
             {
                 MyPluginLog.Log("Reading global config file");
                 MyObjectBuilder_GlobalSettings saveFile = MyFileUtils.SerializeFromXml <MyObjectBuilder_GlobalSettings>(reader.ReadToEnd());
                 if (saveFile != null)
                 {
                     MyPluginLog.Log("Serialized global config file");
                     Settings = saveFile;
                 }
             }
         }
         catch (Exception e)
         {
             MyPluginLog.Log("Couldnt load Plugin config file.", LogLevel.ERROR);
             MyPluginLog.Log(e.Message + "\n" + e.StackTrace, LogLevel.ERROR);
             MyFileUtils.DeleteFileInGlobalStorage(FILENAME);
             Settings = new MyObjectBuilder_GlobalSettings();
             Settings.MoonDefinitions.Add("Moon");
             Settings.MoonDefinitions.Add("Titan");
             Settings.MoonDefinitions.Add("Europa");
             Settings.MoonDefinitions.Add("Triton");
             Settings.BlacklistedPlanetDefinitions.Add("EarthLikeTutorial");
             Settings.BlacklistedPlanetDefinitions.Add("MarsTutorial");
             Settings.BlacklistedPlanetDefinitions.Add("MoonTutorial");
             Settings.BlacklistedPlanetDefinitions.Add("SystemTestMap");
             Settings.BlacklistedPlanetDefinitions.Add("EarthLikeModExample");
         }
     }
     else
     {
         MyPluginLog.Log("Config does not exist, creating default one");
         Settings = new MyObjectBuilder_GlobalSettings();
         Settings.MoonDefinitions.Add("Moon");
         Settings.MoonDefinitions.Add("Titan");
         Settings.MoonDefinitions.Add("Europa");
         Settings.MoonDefinitions.Add("Triton");
         Settings.BlacklistedPlanetDefinitions.Add("EarthLikeTutorial");
         Settings.BlacklistedPlanetDefinitions.Add("MarsTutorial");
         Settings.BlacklistedPlanetDefinitions.Add("MoonTutorial");
         Settings.BlacklistedPlanetDefinitions.Add("SystemTestMap");
         Settings.BlacklistedPlanetDefinitions.Add("EarthLikeModExample");
     }
     Settings.Verify();
     MyPluginLog.Log("Config loaded");
 }
Exemple #24
0
        /// <summary>
        /// Finds a fit planet definition for a planet with a diameter less than maxDiameter.
        /// If none can be found, a random one will be returned.
        /// </summary>
        /// <param name="maxDiameter">Max diameter of the planet in meters</param>
        /// <param name="diameter">The diameter of the planet for the returned definition</param>
        /// <param name="isMoon">If it should use moon definitions</param>
        /// <returns>A definition of a planet that tries to be smaller than maxDiameter</returns>
        private MyPlanetGeneratorDefinition FindPlanetDefinitionForSize(double maxDiameter, out double diameter, bool isMoon = false)
        {
            var settings  = MySettingsSession.Static.Settings.GeneratorSettings;
            var planets   = isMoon ? m_uniqueMoons : m_uniquePlanets;
            var mandatory = isMoon ? m_mandatoryMoons : m_mandatoryPlanets;
            MyPlanetGeneratorDefinition def;
            int tries = 0;

            if (planets == null || planets.Count <= 0)
            {
                if (isMoon)
                {
                    m_uniqueMoons = new List <MyPlanetGeneratorDefinition>(m_moons);
                    planets       = m_uniqueMoons;
                }
                else
                {
                    m_uniquePlanets = new List <MyPlanetGeneratorDefinition>(m_planets);
                    planets         = m_uniquePlanets;
                }
            }

            if (planets.Count <= 0)
            {
                MyPluginLog.Log("Cant find planet definition", LogLevel.WARNING);
                diameter = 0;
                return(null);
            }

            if (settings.SystemGenerator >= SystemGenerationMethod.MANDATORY_FIRST && mandatory.Count > 0)
            {
                planets = mandatory;
            }

            do
            {
                def      = planets[MyRandom.Instance.Next(0, planets.Count)];
                diameter = CalculatePlanetDiameter(def);
            } while (diameter > maxDiameter && ++tries < MAX_DEF_FIND_ROUNDS);

            if (settings.SystemGenerator == SystemGenerationMethod.MANDATORY_FIRST)
            {
                mandatory.Remove(def);
            }

            if (settings.SystemGenerator == SystemGenerationMethod.UNIQUE)
            {
                planets.Remove(def);
            }
            return(def);
        }
Exemple #25
0
        /// <summary>
        /// Generates a planet for the star system.
        /// </summary>
        /// <param name="planetIndex">Index of the planet in the system</param>
        /// <param name="maxDiameter">The largest diameter the planet should have</param>
        /// <param name="orbitDistance">The distance the planet is away from Vector3D.Zero</param>
        /// <returns>A new MySystemPlanet</returns>
        private MySystemPlanet GeneratePlanet(int planetIndex, double maxDiameter, long orbitDistance)
        {
            MyPluginLog.Log("Generating new planet");

            var settings = MySettingsSession.Static.Settings.GeneratorSettings.PlanetSettings;

            var def = FindPlanetDefinitionForSize(maxDiameter);

            if (def == null)
            {
                MyPluginLog.Log("Could not load a planet definition for this planet.", LogLevel.WARNING);
                return(null);
            }


            var diameter = CalculatePlanetDiameter(def);

            var      angle     = MyRandom.Instance.GetRandomFloat(0, (float)(2 * Math.PI));
            var      elevation = MyRandom.Instance.GetRandomFloat((float)Math.PI / 180 * -5, (float)Math.PI / 180 * 5);
            Vector3D pos       = new Vector3D(orbitDistance * Math.Sin(angle), orbitDistance * Math.Cos(angle), orbitDistance * Math.Sin(elevation));

            string name = GetPlanetName(planetIndex, def.Id.SubtypeId.String);

            MySystemPlanet planet = new MySystemPlanet()
            {
                CenterPosition = pos,
                Diameter       = diameter,
                DisplayName    = name,
                Generated      = false,
                SubtypeId      = def.Id.SubtypeId.String,
            };

            if (MyRandom.Instance.NextFloat() < settings.BaseRingProbability * def.SurfaceGravity)
            {
                planet.ChildObjects.Add(GenrateRing(planet));
            }

            if (MyRandom.Instance.NextFloat() < settings.BaseMoonProbability * def.SurfaceGravity)
            {
                foreach (var moon in GeneratePlanetMoons(planet))
                {
                    if (moon == null)
                    {
                        continue;
                    }
                    planet.ChildObjects.Add(moon);
                }
            }
            MyPluginLog.Log("Planet generated");
            return(planet);
        }
        /// <summary>
        /// This method adds the MyEntity to the MyEntityTrackerComponent as a
        /// tracked Entity.
        /// </summary>
        /// <param name="thisEntity">The Entiy this method executes on</param>
        public static void EntityTracking(this MyEntity thisEntity)
        {
            MyPluginLog.Debug("Try Track Entity" + thisEntity.Name);

            if (thisEntity is MyVoxelBase)
            {
                return;
            }
            if (MyEntityTrackerComponent.Static != null)
            {
                MyPluginLog.Debug("Track Entity");
                MyEntityTrackerComponent.Static.TrackEntity(thisEntity);
            }
        }
Exemple #27
0
        /// <summary>
        /// Saves the global configuration file
        /// </summary>
        public void SaveSettings()
        {
            MyFileUtils.DeleteFileInGlobalStorage(FILENAME);

            string xml = MyFileUtils.SerializeToXml(Settings);

            MyPluginLog.Log("Saving global SEWorldGenPlugin config file: " + xml);

            using (var writer = MyFileUtils.WriteFileInGlobalStorage(FILENAME))
            {
                writer.Write(xml);
                writer.Close();
            }
        }
Exemple #28
0
        /// <summary>
        /// Loads necessary data for this class and initializes the fields
        /// </summary>
        public override void LoadData()
        {
            MyPluginLog.Log("Entity tracker loading data");

            base.LoadData();

            Static               = this;
            m_entityTrackers     = new List <IMyEntityTracker>();
            m_trackedEntities    = new List <MyEntity>();
            m_newTrackedEntities = new List <MyEntity>();
            m_toUntrackEntities  = new List <MyEntity>();

            MyPluginLog.Log("Entity tracker loading data completed");
        }
 /// <summary>
 /// Registers all types with the EventOwnerAttribute.
 /// </summary>
 public void RegisterAll()
 {
     foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
     {
         foreach (var type in assembly.GetTypes())
         {
             if (type.GetCustomAttributes(typeof(EventOwnerAttribute), true).Length > 0)
             {
                 MyPluginLog.Log("Registering type " + type.Name + " in PluginEventHandler.");
                 Register(type);
             }
         }
     }
 }
        /// <summary>
        /// Unloads the used data of this session component.
        /// </summary>
        protected override void UnloadData()
        {
            MyPluginLog.Log("Unloading Session settings data");

            if (Sync.IsServer)
            {
                MyFileUtils.WriteXmlFileToWorld(Settings, FILE_NAME);
            }
            Settings = null;

            MySettings.Static.SessionSettings = null;

            MyPluginLog.Log("Unloading Session settings data completed");
        }