Example #1
0
        public override void Init(long seed, MyPlanetGeneratorDefinition generator, MyObjectBuilder_PlanetMapProvider builder)
        {
            MyObjectBuilder_PlanetTextureMapProvider provider = (MyObjectBuilder_PlanetTextureMapProvider)builder;

            this.m_path = provider.Path;
            this.m_mod  = generator.Context;
        }
Example #2
0
            public override void Apply()
            {
                MyPlanetGeneratorDefinition planetDefinition = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(DefinitionName));

                if (planetDefinition == null)
                {
                    string message = String.Format("Definition for planet {0} could not be found. Skipping.", DefinitionName);
                    Debug.Fail(message);
                    MyLog.Default.WriteLine(message);
                    return;
                }

                Vector3D position = PositionMinCorner;

                if (PositionCenter.IsValid())
                {
                    position = PositionCenter;

                    var size = MyVoxelCoordSystems.FindBestOctreeSize(Diameter * (1 + planetDefinition.HillParams.Max));
                    position -= ((Vector3D)size) / 2;
                }

                int seed            = MyRandom.Instance.Next();
                var storageNameBase = DefinitionName + "-" + seed + "d" + Diameter;

                MyWorldGenerator.CreatePlanet(storageNameBase, planetDefinition.FolderName, ref position, seed, Diameter, MyRandom.Instance.NextLong(), ref planetDefinition, AddGPS);
            }
Example #3
0
        public void Close()
        {
            if (m_providerForRules == this)
            {
                m_providerForRules = null;
            }

            // Clear to speed up collection

            m_blendingTileset    = null;
            m_subsurfaceMaterial = null;
            m_generator          = null;
            m_biomeMap           = null;
            m_biomes             = null;
            m_materials          = null;
            m_planetShape        = null;
            m_ores = null;

            m_materialMap  = null;
            m_oreMap       = null;
            m_biomeMap     = null;
            m_occlusionMap = null;

            Closed = true;
        }
        private void CreatePlanet(int seed, float size)
        {
            Vector3D pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * size * 3 - new Vector3D(size);

            MyPlanetGeneratorDefinition planetDefinition = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(m_selectedPlanetName));
            MyPlanetStorageProvider     provider         = new MyPlanetStorageProvider();

            provider.Init(seed, planetDefinition, size / 2f);

            IMyStorage storage = new MyOctreeStorage(provider, provider.StorageSize);

            float minHillSize = provider.Radius * planetDefinition.HillParams.Min;
            float maxHillSize = provider.Radius * planetDefinition.HillParams.Max;

            float averagePlanetRadius = provider.Radius;

            float outerRadius = averagePlanetRadius + maxHillSize;
            float innerRadius = averagePlanetRadius + minHillSize;

            float atmosphereRadius = planetDefinition.AtmosphereSettings.HasValue && planetDefinition.AtmosphereSettings.Value.Scale > 1f ? 1 + planetDefinition.AtmosphereSettings.Value.Scale : 1.75f;

            atmosphereRadius *= provider.Radius;

            var planet = new MyPlanet();

            planet.EntityId = MyRandom.Instance.NextLong();

            MyPlanetInitArguments planetInitArguments;

            planetInitArguments.StorageName           = "test";
            planetInitArguments.Storage               = storage;
            planetInitArguments.PositionMinCorner     = pos;
            planetInitArguments.Radius                = provider.Radius;
            planetInitArguments.AtmosphereRadius      = atmosphereRadius;
            planetInitArguments.MaxRadius             = outerRadius;
            planetInitArguments.MinRadius             = innerRadius;
            planetInitArguments.HasAtmosphere         = planetDefinition.HasAtmosphere;
            planetInitArguments.AtmosphereWavelengths = Vector3.Zero;
            planetInitArguments.GravityFalloff        = planetDefinition.GravityFalloffPower;
            planetInitArguments.MarkAreaEmpty         = true;
            planetInitArguments.AtmosphereSettings    = planetDefinition.AtmosphereSettings.HasValue ? planetDefinition.AtmosphereSettings.Value : MyAtmosphereSettings.Defaults();
            planetInitArguments.SurfaceGravity        = planetDefinition.SurfaceGravity;
            planetInitArguments.AddGps                = false;
            planetInitArguments.SpherizeWithDistance  = true;
            planetInitArguments.Generator             = planetDefinition;
            planetInitArguments.UserCreated           = true;

            planet.Init(planetInitArguments);

            m_lastAsteroidInfo = new SpawnAsteroidInfo()
            {
                Asteroid         = null,
                RandomSeed       = seed,
                Position         = Vector3D.Zero,
                IsProcedural     = true,
                ProceduralRadius = size,
            };

            MyCubeBuilder.Static.ActivateVoxelClipboard(planet.GetObjectBuilder(), storage, MySector.MainCamera.ForwardVector, (storage.Size * 0.5f).Length());
        }
Example #5
0
        /// <summary>
        /// Calculates the size of a planet by its surface gravity using the world settings.
        /// </summary>
        /// <param name="planet">Planet to calculate size for</param>
        /// <returns>Diameter of the planet</returns>
        private double CalculatePlanetDiameter(MyPlanetGeneratorDefinition planet)
        {
            var   settings = MySettingsSession.Static.Settings.GeneratorSettings.PlanetSettings;
            float modifier = m_gasGiants.Contains(planet) ? 2 * settings.PlanetSizeMultiplier: settings.PlanetSizeMultiplier;

            return(Math.Min(Math.Sqrt(planet.SurfaceGravity * 120000 * 120000 * modifier * modifier), settings.PlanetSizeCap));
        }
Example #6
0
 private void PlanetDefListItemClicked(MyGuiControlListbox box)
 {
     if (box.SelectedItems.Count > 0)
     {
         m_selectedDefinition        = (MyPlanetGeneratorDefinition)box.SelectedItems[box.SelectedItems.Count - 1].UserData;
         m_spawnPlanetButton.Enabled = true;
     }
 }
        /// <summary>
        /// Calculates the size of a planet by its surface gravity using the world settings.
        /// </summary>
        /// <param name="planet">Planet to calculate size for</param>
        /// <returns>Diameter of the planet</returns>
        private double CalculatePlanetDiameter(MyPlanetGeneratorDefinition planet)
        {
            var   settings  = MySettingsSession.Static.Settings.GeneratorSettings.PlanetSettings;
            float modifier  = m_gasGiants.Contains(planet) ? 2 * settings.PlanetSizeMultiplier: settings.PlanetSizeMultiplier;
            float deviation = (MyRandom.Instance.NextFloat() - 0.5f) * 2f * settings.PlanetSizeDeviation + 1;

            return(Math.Min(planet.SurfaceGravity * 120000 * modifier * deviation, settings.PlanetSizeCap));
        }
Example #8
0
        private Vector3D GetPlanetOffset(MyPlanetGeneratorDefinition definition, float size)
        {
            MyPlanetStorageProvider myPlanetStorageProvider = new MyPlanetStorageProvider();

            myPlanetStorageProvider.Init(0, definition, size / 2f);
            IMyStorage myStorage = new MyOctreeStorage(myPlanetStorageProvider, myPlanetStorageProvider.StorageSize);

            return(myStorage.Size / 2.0f);
        }
Example #9
0
 public void Init(long seed, MyPlanetGeneratorDefinition generator, double radius)
 {
     radius    = Math.Max(radius, 1.0);
     Generator = generator;
     Radius    = radius;
     Seed      = seed;
     Version   = STORAGE_VERSION;
     Init();
 }
Example #10
0
        public MyPlanetShapeProvider(Vector3 translation, float radius, MyPlanetGeneratorDefinition definition)
        {
            m_radius      = radius;
            m_translation = translation;

            m_maxHillHeight = definition.HillParams.Max * m_radius;
            m_minHillHeight = definition.HillParams.Min * m_radius;

            InnerRadius = radius + m_minHillHeight;
            OuterRadius = radius + m_maxHillHeight;

            m_heightmap = new MyHeightCubemap(definition.FolderName, definition.Context);

            m_mapResolutionMinusOne = m_heightmap.Resolution - 1;

            m_heightRatio      = m_maxHillHeight - m_minHillHeight;
            m_heightRatioRecip = 1f / m_heightRatio;

            float faceSize = (float)(radius * Math.PI * .5);

            m_pixelSize       = faceSize / m_heightmap.Resolution;
            m_pixelSizeRecip  = 1f / m_pixelSize;
            m_pixelSizeRecip2 = .5f / m_pixelSize;

            // Calculate maximum tolerable curvature deviation when approximating the surface by a line
            // We use this for LOD1 raycasts so the maximum deviation is 8m(half a LOD1 cell)

            // Find the angle theta that produces an arc whose secant approximation deviates from the circle at most 8 meters
            var theta = Math.Acos((radius - 1) / radius); // this produces theta/2 but we use that later anyways

            // Find the length of this secant segment.
            var threshold = Math.Sin(theta) * 2 * radius;

            // Store it's reciprocal because that's all we use
            m_curvatureThresholdRecip = 1d / threshold;

            m_pixelSize4 = m_pixelSize * 4;

            // Used for inflating query boxes
            m_voxelSize = (float)(2.0 / (radius * Math.PI));

            m_mapStepScale       = m_pixelSize / m_heightRatio;
            m_mapStepScaleSquare = m_mapStepScale * m_mapStepScale;

            if (definition.Detail != null)
            {
                m_detail.Init(definition.Detail, faceSize);
            }

            Closed = false;
        }
Example #11
0
        public void Init(long seed, string generator, double radius)
        {
            radius = Math.Max(radius, 1.0);
            var def = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(generator));

            if (def == null)
            {
                throw new Exception($"Cannot load planet generator definition for subtype '{generator}'.");
            }
            Generator = def;
            Radius    = radius;
            Seed      = seed;
            Version   = STORAGE_VERSION;
            Init();
        }
Example #12
0
 public void Close()
 {
     this.m_blendingTileset    = null;
     this.m_subsurfaceMaterial = null;
     this.m_generator          = null;
     this.m_biomeMap           = null;
     this.m_biomes             = null;
     this.m_materials          = null;
     this.m_planetShape        = null;
     this.m_ores        = null;
     this.m_materialMap = null;
     this.m_oreMap      = null;
     this.m_biomeMap    = null;
     this.Maps          = null;
     this.Closed        = true;
 }
Example #13
0
        public void Init(long seed, MyPlanetGeneratorDefinition generator, double radius)
        {
            double num1 = Math.Max(radius, 1.0);

            radius         = num1;
            this.Generator = generator;
            PlanetData data = new PlanetData {
                Radius  = radius,
                Seed    = seed,
                Version = STORAGE_VERSION
            };

            this.m_data = data;
            this.Init(seed);
            this.Closed = false;
        }
        private static void BuildOreProbabilities(MyPlanetGeneratorDefinition planetDefinition)
        {
            m_oreCummulativeProbability = 0.0f;
            if (planetDefinition.MetalsOreProbability != null)
            {
                foreach (var oreProbability in planetDefinition.MetalsOreProbability)
                {
                    MyOreProbability probability = new MyOreProbability();

                    m_oreCummulativeProbability       += MyRandom.Instance.NextFloat(oreProbability.Min, oreProbability.Max);
                    probability.CummulativeProbability = m_oreCummulativeProbability;
                    probability.OreName = oreProbability.OreName;
                    m_oreProbalities.Add(probability);
                }
            }
        }
Example #15
0
        public override void AddRenderObjects()
        {
            base.AddRenderObjects();
            base.ResizeRenderObjectArray(0x10);
            int      length = base.RenderObjectIDs.Length;
            Vector3D positionLeftBottomCorner = this.m_planet.PositionLeftBottomCorner;
            Vector3  atmosphereWavelengths    = new Vector3 {
                X = 1f / ((float)Math.Pow((double)this.m_planet.AtmosphereWavelengths.X, 4.0)),
                Y = 1f / ((float)Math.Pow((double)this.m_planet.AtmosphereWavelengths.Y, 4.0)),
                Z = 1f / ((float)Math.Pow((double)this.m_planet.AtmosphereWavelengths.Z, 4.0))
            };
            IMyEntity entity = base.Entity;

            if (this.m_planet.HasAtmosphere)
            {
                MatrixD xd2 = MatrixD.Identity * this.m_planet.AtmosphereRadius;
                xd2.M44         = 1.0;
                xd2.Translation = base.Entity.PositionComp.GetPosition();
                this.m_atmosphereRenderIndex = length;
                length++;
                long entityId = base.Entity.EntityId;
                this.SetRenderObjectID(length, MyRenderProxy.CreateRenderEntityAtmosphere(base.Entity.GetFriendlyName() + " " + entityId.ToString(), @"Models\Environment\Atmosphere_sphere.mwm", xd2, MyMeshDrawTechnique.ATMOSPHERE, RenderFlags.DrawOutsideViewDistance | RenderFlags.Visible, this.GetRenderCullingOptions(), this.m_planet.AtmosphereRadius, this.m_planet.AverageRadius, atmosphereWavelengths, 0f, float.MaxValue, base.FadeIn));
                this.UpdateAtmosphereSettings(this.m_planet.AtmosphereSettings);
            }
            this.m_shadowHelperRenderObjectIndex = length;
            MatrixD worldMatrix = MatrixD.CreateScale((double)this.m_planet.MinimumRadius);

            worldMatrix.Translation = this.m_planet.WorldMatrix.Translation;
            length++;
            this.SetRenderObjectID(length, MyRenderProxy.CreateRenderEntity("Shadow helper", @"Models\Environment\Sky\ShadowHelperSphere.mwm", worldMatrix, MyMeshDrawTechnique.MESH, RenderFlags.CastShadowsOnLow | RenderFlags.SkipInMainView | RenderFlags.NoBackFaceCulling | RenderFlags.DrawOutsideViewDistance | RenderFlags.Visible | RenderFlags.CastShadows, CullingOptions.Default, Color.White, new Vector3(1f, 1f, 1f), 0f, float.MaxValue, 0, 1f, base.FadeIn));
            MyPlanetGeneratorDefinition generator = this.m_planet.Generator;

            if ((MyFakes.ENABLE_PLANETARY_CLOUDS && (generator != null)) && (generator.CloudLayers != null))
            {
                foreach (MyCloudLayerSettings settings in generator.CloudLayers)
                {
                    double   minScaledAltitude = ((double)(this.m_planet.AverageRadius + this.m_planet.MaximumRadius)) / 2.0;
                    double   altitude          = minScaledAltitude + ((this.m_planet.MaximumRadius - minScaledAltitude) * settings.RelativeAltitude);
                    Vector3D rotationAxis      = Vector3D.Normalize((settings.RotationAxis == Vector3D.Zero) ? Vector3D.Up : settings.RotationAxis);
                    int      index             = length + this.m_cloudLayerRenderObjectIndexList.Count;
                    this.SetRenderObjectID(index, MyRenderProxy.CreateRenderEntityCloudLayer((this.m_atmosphereRenderIndex != -1) ? base.m_renderObjectIDs[this.m_atmosphereRenderIndex] : uint.MaxValue, base.Entity.GetFriendlyName() + " " + base.Entity.EntityId.ToString(), settings.Model, settings.Textures, base.Entity.PositionComp.GetPosition(), altitude, minScaledAltitude, settings.ScalingEnabled, (double)settings.FadeOutRelativeAltitudeStart, (double)settings.FadeOutRelativeAltitudeEnd, settings.ApplyFogRelativeDistance, (double)this.m_planet.MaximumRadius, rotationAxis, settings.AngularVelocity, settings.InitialRotation, settings.Color.ToLinearRGB(), base.FadeIn));
                    this.m_cloudLayerRenderObjectIndexList.Add(index);
                }
                length += generator.CloudLayers.Count;
            }
        }
        /// <summary>
        /// Regenerate the Planet voxel.
        /// </summary>
        /// <param name="seed"></param>
        /// <param name="radius"></param>
        public void RegeneratePlanet(int seed, float radius)
        {
            MyPlanetStorageProvider     provider         = new MyPlanetStorageProvider();
            MyPlanetGeneratorDefinition planetDefinition = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(Planet.PlanetGenerator));

            provider.Init(seed, planetDefinition, radius);

            float minHillSize = provider.Radius * planetDefinition.HillParams.Min;
            float maxHillSize = provider.Radius * planetDefinition.HillParams.Max;

            float atmosphereRadius = planetDefinition.AtmosphereSettings.HasValue && planetDefinition.AtmosphereSettings.Value.Scale > 1f ? 1 + planetDefinition.AtmosphereSettings.Value.Scale : 1.75f;

            atmosphereRadius *= provider.Radius;

            Planet.Seed                 = seed;
            Planet.Radius               = radius;
            Planet.AtmosphereRadius     = atmosphereRadius;
            Planet.MinimumSurfaceRadius = radius + minHillSize;
            Planet.MaximumHillRadius    = radius + maxHillSize;

            provider.Init(Planet.Seed, planetDefinition, radius);

            var asteroid = new MyVoxelMap();

            asteroid.Storage = new MyOctreeStorage(provider, provider.StorageSize);
            var tempfilename = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);

            asteroid.Save(tempfilename);
            //SourceVoxelFilepath = tempfilename;
            UpdateNewSource(asteroid, tempfilename);

            RaisePropertyChanged(() => Seed);
            RaisePropertyChanged(() => Radius);
            RaisePropertyChanged(() => AtmosphereRadius);
            RaisePropertyChanged(() => MinimumSurfaceRadius);
            RaisePropertyChanged(() => MaximumHillRadius);

            //Size = _voxelMap.Size;
            //_contentCenter = _voxelMap.ContentCenter;
            //IsValid = _voxelMap.IsValid;
            //RaisePropertyChanged(() => Size);
            //RaisePropertyChanged(() => IsValid);
            //Center = new Vector3D(_contentCenter.X + 0.5f + PositionX, _contentCenter.Y + 0.5f + PositionY, _contentCenter.Z + 0.5f + PositionZ);
            //WorldAABB = new BoundingBoxD(PositionAndOrientation.Value.Position, PositionAndOrientation.Value.Position + new Vector3D(Size));
        }
        public void Init(long seed, MyPlanetGeneratorDefinition generator, double radius)
        {
            Debug.Assert(radius > 0, "The planet radius must be a strictly positive number!");

            radius = Math.Max(radius, 1.0);

            Generator = generator;

            m_data = new PlanetData()
            {
                Radius  = radius,
                Seed    = seed,
                Version = STORAGE_VERSION
            };

            Init();

            Closed = false;
        }
        public static void AddPlanetPrefab(string planetName, string definitionName, Vector3D position, bool addGPS)
        {
            DictionaryValuesReader <MyDefinitionId, MyPlanetPrefabDefinition> planetPrefabDefinitions = MyDefinitionManager.Static.GetPlanetsPrefabsDefinitions();

            foreach (var planetPrefabDefinition in planetPrefabDefinitions)
            {
                if (planetPrefabDefinition.Id.SubtypeName == planetName)
                {
                    MyPlanetGeneratorDefinition planetDefinition = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(definitionName));

                    var planet = new MyPlanet();
                    var ob     = planetPrefabDefinition.PlanetBuilder;

                    string storageName = MyFileSystem.ContentPath + "\\VoxelMaps\\" + ob.StorageName + MyVoxelConstants.FILE_EXTENSION;
                    planet.EntityId = ob.EntityId;

                    MyPlanetInitArguments planetInitArguments;
                    planetInitArguments.StorageName           = ob.StorageName;
                    planetInitArguments.Storage               = MyStorageBase.LoadFromFile(storageName);
                    planetInitArguments.PositionMinCorner     = position;
                    planetInitArguments.Radius                = ob.Radius;
                    planetInitArguments.AtmosphereRadius      = ob.AtmosphereRadius;
                    planetInitArguments.MaxRadius             = ob.MaximumHillRadius;
                    planetInitArguments.MinRadius             = ob.MinimumSurfaceRadius;
                    planetInitArguments.HasAtmosphere         = planetDefinition.HasAtmosphere;
                    planetInitArguments.AtmosphereWavelengths = ob.AtmosphereWavelengths;
                    planetInitArguments.GravityFalloff        = planetDefinition.GravityFalloffPower;
                    planetInitArguments.MarkAreaEmpty         = true;
                    planetInitArguments.AtmosphereSettings    = ob.AtmosphereSettings.HasValue ? ob.AtmosphereSettings.Value : MyAtmosphereSettings.Defaults();
                    planetInitArguments.SurfaceGravity        = planetDefinition.SurfaceGravity;
                    planetInitArguments.AddGps                = addGPS;
                    planetInitArguments.SpherizeWithDistance  = true;
                    planetInitArguments.Generator             = planetDefinition;
                    planetInitArguments.UserCreated           = false;
                    planetInitArguments.InitializeComponents  = true;

                    planet.Init(planetInitArguments);
                    MyEntities.Add(planet);
                    MyEntities.RaiseEntityCreated(planet);
                }
            }
        }
Example #19
0
        public void ReadFrom(int storageVersion, Stream stream, int size, ref bool isOldFormat)
        {
            this.m_data.Version = stream.ReadInt64();
            this.m_data.Seed    = stream.ReadInt64();
            this.m_data.Radius  = stream.ReadDouble();
            string str = stream.ReadString(null);

            if (this.m_data.Version != STORAGE_VERSION)
            {
                isOldFormat = true;
            }
            MyPlanetGeneratorDefinition definition = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(str));

            if (definition == null)
            {
                throw new Exception($"Cannot load planet generator definition for subtype '{str}'.");
            }
            this.Generator = definition;
            this.Init(this.m_data.Seed);
        }
Example #20
0
        public MyPlanetShapeProvider(Vector3 translation, float radius, MyPlanetGeneratorDefinition definition, MyHeightCubemap cubemap, MyPlanetTextureMapProvider texProvider)
        {
            this.m_radius                = radius;
            this.m_translation           = translation;
            this.m_maxHillHeight         = definition.HillParams.Max * this.m_radius;
            this.m_minHillHeight         = definition.HillParams.Min * this.m_radius;
            this.InnerRadius             = radius + this.m_minHillHeight;
            this.OuterRadius             = radius + this.m_maxHillHeight;
            this.m_heightmap             = cubemap;
            this.m_mapResolutionMinusOne = this.m_heightmap.Resolution - 1;
            this.m_heightRatio           = this.m_maxHillHeight - this.m_minHillHeight;
            this.m_heightRatioRecip      = 1f / this.m_heightRatio;
            float faceSize = (float)((radius * 3.1415926535897931) * 0.5);

            this.m_pixelSize       = faceSize / ((float)this.m_heightmap.Resolution);
            this.m_pixelSizeRecip  = 1f / this.m_pixelSize;
            this.m_pixelSizeRecip2 = 0.5f / this.m_pixelSize;
            double num2 = (Math.Sin(Math.Acos((double)((radius - 1f) / radius))) * 2.0) * radius;

            this.m_curvatureThresholdRecip = 1.0 / num2;
            this.m_pixelSize4         = this.m_pixelSize * 4f;
            this.m_voxelSize          = (float)(2.0 / (radius * 3.1415926535897931));
            this.m_mapStepScale       = this.m_pixelSize / this.m_heightRatio;
            this.m_mapStepScaleSquare = this.m_mapStepScale * this.m_mapStepScale;
            if (definition.Detail != null)
            {
                this.m_detail.Init(texProvider, definition.Detail, faceSize);
            }
            VrPlanetShape.Mapset        maps          = this.m_heightmap.GetMapset();
            VrPlanetShape.DetailMapData detailMapData = new VrPlanetShape.DetailMapData();
            if (definition.Detail != null)
            {
                detailMapData = this.m_detail.GetDetailMapData();
            }
            this.m_nativeShape = new VrPlanetShape(translation, radius, definition.HillParams.Min, definition.HillParams.Max, maps, detailMapData, true);
            this.Closed        = false;
        }
Example #21
0
        public override void AddRenderObjects()
        {
            var minCorner = m_planet.PositionLeftBottomCorner;

            m_renderObjectIDs = new uint[16];

            for (int index = 0; index < 16; ++index)
            {
                m_renderObjectIDs[index] = MyRenderProxy.RENDER_ID_UNASSIGNED;
            }

            int runningRenderObjectIndex = 0;

            Debug.Assert((m_planet.Size % MyVoxelCoordSystems.RenderCellSizeInLodVoxels(0)) == Vector3I.Zero);
            var clipmapSizeLod0 = m_planet.Size / MyVoxelCoordSystems.RenderCellSizeInLodVoxels(0);

            Vector3 atmosphereWavelengths = new Vector3();

            atmosphereWavelengths.X = 1.0f / (float)Math.Pow(m_planet.AtmosphereWavelengths.X, 4.0);
            atmosphereWavelengths.Y = 1.0f / (float)Math.Pow(m_planet.AtmosphereWavelengths.Y, 4.0);
            atmosphereWavelengths.Z = 1.0f / (float)Math.Pow(m_planet.AtmosphereWavelengths.Z, 4.0);

            var voxel = (Entity as MyVoxelBase);

            SetRenderObjectID(runningRenderObjectIndex++,
                              MyRenderProxy.CreateClipmap(
                                  MatrixD.CreateTranslation(minCorner),
                                  clipmapSizeLod0,
                                  m_planet.ScaleGroup,
                                  m_planet.PositionComp.GetPosition(),
                                  m_planet.AtmosphereRadius,
                                  m_planet.AverageRadius,
                                  m_planet.HasAtmosphere,
                                  atmosphereWavelengths,
                                  m_planet.SpherizeWithDistance,
                                  RenderFlags.Visible | RenderFlags.DrawOutsideViewDistance | RenderFlags.CastShadows,
                                  IntersectStorage));

            if (m_planet.HasAtmosphere)
            {
                MatrixD matrix = MatrixD.Identity * m_planet.AtmosphereRadius;
                matrix.M44         = 1;
                matrix.Translation = Entity.PositionComp.GetPosition();

                SetRenderObjectID(runningRenderObjectIndex++, MyRenderProxy.CreateRenderEntityAtmosphere(this.Entity.GetFriendlyName() + " " + this.Entity.EntityId.ToString(),
                                                                                                         "Models\\Environment\\Atmosphere_sphere.mwm",
                                                                                                         matrix,
                                                                                                         MyMeshDrawTechnique.ATMOSPHERE,
                                                                                                         RenderFlags.Visible | RenderFlags.DrawOutsideViewDistance,
                                                                                                         GetRenderCullingOptions(),
                                                                                                         m_planet.AtmosphereRadius,
                                                                                                         m_planet.AverageRadius,
                                                                                                         atmosphereWavelengths));

                SetRenderObjectID(runningRenderObjectIndex++, MyRenderProxy.CreateRenderEntityAtmosphere(this.Entity.GetFriendlyName() + " " + this.Entity.EntityId.ToString(),
                                                                                                         "Models\\Environment\\Atmosphere_sphere.mwm",
                                                                                                         matrix,
                                                                                                         MyMeshDrawTechnique.PLANET_SURFACE,
                                                                                                         RenderFlags.Visible | RenderFlags.DrawOutsideViewDistance,
                                                                                                         GetRenderCullingOptions(),
                                                                                                         m_planet.AtmosphereRadius,
                                                                                                         m_planet.AverageRadius,
                                                                                                         atmosphereWavelengths));

                UpdateAtmosphereSettings(m_planet.AtmosphereSettings);
            }

            if (m_renderEnabled == false)
            {
                MyRenderProxy.EnableRenderModule((uint)MyRenderModuleEnum.Atmosphere, true);
                m_renderEnabled = true;
            }

            m_shadowHelperRenderObjectIndex = runningRenderObjectIndex;
            MatrixD shadowHelperWorldMatrix = MatrixD.CreateScale(m_planet.MinimumRadius);

            shadowHelperWorldMatrix.Translation = m_planet.WorldMatrix.Translation;
            SetRenderObjectID(runningRenderObjectIndex++, MyRenderProxy.CreateRenderEntity("Shadow helper", "Models\\Environment\\Sky\\ShadowHelperSphere.mwm",
                                                                                           shadowHelperWorldMatrix,
                                                                                           MyMeshDrawTechnique.MESH,
                                                                                           RenderFlags.Visible | RenderFlags.CastShadows | RenderFlags.DrawOutsideViewDistance | RenderFlags.NoBackFaceCulling | RenderFlags.SkipInMainView,
                                                                                           CullingOptions.Default,
                                                                                           Color.White, new Vector3(1, 1, 1)));

            MyPlanetGeneratorDefinition definition = m_planet.Generator;

            if (!MyFakes.ENABLE_PLANETARY_CLOUDS || definition == null || definition.CloudLayers == null)
            {
                return;
            }

            foreach (var cloudLayer in definition.CloudLayers)
            {
                double   minScaledAltitude = (m_planet.AverageRadius + m_planet.MaximumRadius) / 2.0;
                double   layerAltitude     = minScaledAltitude + (m_planet.MaximumRadius - minScaledAltitude) * cloudLayer.RelativeAltitude;
                Vector3D rotationAxis      = Vector3D.Normalize(cloudLayer.RotationAxis == Vector3D.Zero ? Vector3D.Up : cloudLayer.RotationAxis);

                int index = runningRenderObjectIndex + m_cloudLayerRenderObjectIndexList.Count;
                SetRenderObjectID(index,
                                  MyRenderProxy.CreateRenderEntityCloudLayer(this.Entity.GetFriendlyName() + " " + this.Entity.EntityId.ToString(),
                                                                             cloudLayer.Model,
                                                                             cloudLayer.Textures,
                                                                             Entity.PositionComp.GetPosition(),
                                                                             layerAltitude,
                                                                             minScaledAltitude,
                                                                             cloudLayer.ScalingEnabled,
                                                                             cloudLayer.FadeOutRelativeAltitudeStart,
                                                                             cloudLayer.FadeOutRelativeAltitudeEnd,
                                                                             cloudLayer.ApplyFogRelativeDistance,
                                                                             m_planet.MaximumRadius,
                                                                             MyMeshDrawTechnique.CLOUD_LAYER,
                                                                             RenderFlags.Visible | RenderFlags.DrawOutsideViewDistance,
                                                                             GetRenderCullingOptions(),
                                                                             rotationAxis,
                                                                             cloudLayer.AngularVelocity,
                                                                             cloudLayer.InitialRotation));
                m_cloudLayerRenderObjectIndexList.Add(index);
            }
            runningRenderObjectIndex += definition.CloudLayers.Count;
        }
Example #22
0
        public MyPlanetDetailModulator(MyPlanetGeneratorDefinition planetDefinition, MyPlanetMaterialProvider oreDeposit, int seed, float radius)
        {
            m_planetDefinition = planetDefinition;
            m_oreDeposit       = oreDeposit;
            m_radius           = radius;

            foreach (var distortionDefinition in m_planetDefinition.DistortionTable)
            {
                MyModuleFast modulator = null;

                float frequency = distortionDefinition.Frequency;
                frequency *= radius / 6.0f;

                switch (distortionDefinition.Type)
                {
                case "Billow":
                {
                    modulator = new MyBillowFast(
                        seed: seed,
                        quality: MyNoiseQuality.High,
                        frequency: frequency,
                        layerCount: distortionDefinition.LayerCount);
                }
                break;

                case "RidgedMultifractal":
                {
                    modulator = new MyRidgedMultifractalFast(
                        seed: seed,
                        quality: MyNoiseQuality.High,
                        frequency: frequency,
                        layerCount: distortionDefinition.LayerCount);
                }
                break;

                case "Perlin":
                {
                    modulator = new MyPerlinFast(
                        seed: seed,
                        quality: MyNoiseQuality.High,
                        frequency: frequency,
                        octaveCount: distortionDefinition.LayerCount);
                }
                break;

                case "Simplex":
                {
                    modulator = new MySimplexFast()
                    {
                        Seed      = seed,
                        Frequency = frequency,
                    };
                }
                break;

                default:
                    System.Diagnostics.Debug.Fail("Unknown modulator type!");
                    break;
                }

                if (modulator != null)
                {
                    m_modulators.Add(distortionDefinition.Value,
                                     new MyModulatorData()
                    {
                        Height    = distortionDefinition.Height,
                        Modulator = modulator
                    }
                                     );
                }
            }
        }
Example #23
0
        private static MyMaterialLayer[] CreateMaterialLayers(MyPlanetGeneratorDefinition planetDefinition, bool isHostile, MyRandom random, float averagePlanetRadius, float hillHalfDeviation, float canyonHalfDeviation, ref float outerRadius, ref float innerRadius)
        {
            int numLayers = random.Next((int)planetDefinition.NumLayers.Min, (int)planetDefinition.NumLayers.Max);

            float startHeight = averagePlanetRadius - canyonHalfDeviation;

            outerRadius = averagePlanetRadius + hillHalfDeviation;
            innerRadius = averagePlanetRadius - canyonHalfDeviation;

            int layerOffset = 0;

            MyMaterialLayer southPoleLayer = CreatePoleLayer(random, planetDefinition.SouthPole, startHeight, outerRadius, ref layerOffset);
            MyMaterialLayer northPoleLayer = CreatePoleLayer(random, planetDefinition.NorthPole, startHeight, outerRadius, ref layerOffset);


            MyMaterialLayer[] materialLayers = new MyMaterialLayer[numLayers + layerOffset];

            float endAngle     = 1;
            float startAngle   = -1;
            int   currentLayer = 0;

            if (southPoleLayer != null)
            {
                materialLayers[currentLayer] = southPoleLayer;
                endAngle = southPoleLayer.StartAngle;
                currentLayer++;
            }

            if (northPoleLayer != null)
            {
                materialLayers[currentLayer]       = northPoleLayer;
                northPoleLayer.EndAngle            = northPoleLayer.StartAngle;
                northPoleLayer.StartAngle          = -1.0f;
                northPoleLayer.AngleEndDeviation   = northPoleLayer.AngleStartDeviation;
                northPoleLayer.AngleStartDeviation = 0.0f;
                startAngle = northPoleLayer.EndAngle;
            }

            float step = (outerRadius - innerRadius) / materialLayers.Length;

            float organicHeightEnd = random.NextFloat(planetDefinition.OrganicHeightEnd.Min, planetDefinition.OrganicHeightEnd.Max);
            float floraMaterialSpawnProbability = random.NextFloat(planetDefinition.FloraMaterialSpawnProbability.Min, planetDefinition.FloraMaterialSpawnProbability.Max);
            float metalsSpawnValue = random.NextFloat(0, 1);

            for (int i = layerOffset; i < materialLayers.Length; ++i)
            {
                float layerHeight = random.NextFloat(0, step);
                materialLayers[i]                      = new MyMaterialLayer();
                materialLayers[i].StartHeight          = startHeight;
                materialLayers[i].EndHeight            = startHeight + layerHeight;
                materialLayers[i].StartAngle           = startAngle;
                materialLayers[i].EndAngle             = endAngle;
                materialLayers[i].HeightStartDeviation = random.NextFloat(0, 100.0f / (float)(i + 1));
                materialLayers[i].AngleStartDeviation  = 0;
                materialLayers[i].HeightEndDeviation   = random.NextFloat(0, 100.0f / (float)(i + 1));
                materialLayers[i].AngleEndDeviation    = 0;

                MyVoxelMaterialDefinition materialDefinition = null;

                if (m_materialsByOreType.ContainsKey("Stone") == true)
                {
                    materialDefinition = m_materialsByOreType["Stone"][random.Next() % m_materialsByOreType["Stone"].Count];
                }

                if (planetDefinition.HasAtmosphere && isHostile == false)
                {
                    if ((outerRadius - startHeight) > ((outerRadius - innerRadius) * (1 - organicHeightEnd)))
                    {
                        float value = random.NextFloat(0, 1);
                        if (value > floraMaterialSpawnProbability)
                        {
                            materialDefinition = m_organicMaterials[random.Next() % m_organicMaterials.Count];
                        }
                        else
                        {
                            materialDefinition = m_spawningMaterials[random.Next() % m_spawningMaterials.Count];
                        }
                    }
                }

                materialLayers[i].MaterialDefinition = materialDefinition;
                startHeight += layerHeight;
            }
            return(materialLayers);
        }
Example #24
0
 public abstract void Init(long seed, MyPlanetGeneratorDefinition generator, MyObjectBuilder_PlanetMapProvider builder);
Example #25
0
        public MyPlanetMaterialProvider(MyPlanetGeneratorDefinition generatorDef, MyPlanetShapeProvider planetShape)
        {
            m_materials = new Dictionary <byte, PlanetMaterial>(generatorDef.SurfaceMaterialTable.Length);

            for (int i = 0; i < generatorDef.SurfaceMaterialTable.Length; ++i)
            {
                byte materialValue = (byte)generatorDef.SurfaceMaterialTable[i].Value;

                m_materials[materialValue] = new PlanetMaterial(generatorDef.SurfaceMaterialTable[i]);
            }

            m_defaultMaterial = new PlanetMaterial(generatorDef.DefaultSurfaceMaterial);

            if (generatorDef.DefaultSubSurfaceMaterial != null)
            {
                m_subsurfaceMaterial = new PlanetMaterial(generatorDef.DefaultSubSurfaceMaterial);
            }
            else
            {
                m_subsurfaceMaterial = m_defaultMaterial;
            }

            m_planetShape = planetShape;

            MyCubemap[] maps;
            MyHeightMapLoadingSystem.Static.GetPlanetMaps(generatorDef.FolderName, generatorDef.Context, generatorDef.PlanetMaps, out maps);


            m_materialMap  = maps[0];
            m_biomeMap     = maps[1];
            m_oreMap       = maps[2];
            m_occlusionMap = maps[3];

            if (m_biomeMap != null)
            {
                m_mapResolutionMinusOne = m_biomeMap.Resolution - 1;
            }

            m_generator = generatorDef;

            m_invHeightRange = 1 / (m_planetShape.MaxHillHeight - m_planetShape.MinHillHeight);

            m_biomePixelSize = (float)((planetShape.MaxHillHeight + planetShape.Radius) * Math.PI) / ((float)(m_mapResolutionMinusOne + 1) * 2);

            m_hashCode = generatorDef.FolderName.GetHashCode();

            // Material groups

            if (m_generator.MaterialGroups != null && m_generator.MaterialGroups.Length > 0)
            {
                m_biomes = new Dictionary <byte, PlanetBiome>();

                foreach (var group in m_generator.MaterialGroups)
                {
                    m_biomes.Add(group.Value, new PlanetBiome(group));
                }
            }

            m_blendingTileset = MyHeightMapLoadingSystem.Static.GetTerrainBlendTexture(m_generator.MaterialBlending);

            m_ores = new Dictionary <byte, PlanetOre>();

            foreach (var mapping in m_generator.OreMappings)
            {
                var mat = GetMaterial(mapping.Type);
                if (mat != null)
                {
                    if (m_ores.ContainsKey(mapping.Value))
                    {
                        string message = String.Format("Value {0} is already mapped to another ore.", mapping.Value);
                        Debug.Fail(message);
                        MyLog.Default.WriteLine(message);
                    }
                    else
                    {
                        m_ores[mapping.Value] = new PlanetOre()
                        {
                            Depth    = mapping.Depth,
                            Start    = mapping.Start,
                            Value    = mapping.Value,
                            Material = mat
                        };
                    }
                }
            }

            Closed = false;
        }
Example #26
0
        public static MyPlanet AddPlanet(string storageName, string planetName, string definitionName, Vector3D positionMinCorner, int seed, float size, long entityId = 0, bool addGPS = false, bool userCreated = false)
        {
            MyPlanetGeneratorDefinition planetDefinition = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(definitionName));

            return(CreatePlanet(storageName, planetName, ref positionMinCorner, seed, size, entityId, ref planetDefinition, addGPS, userCreated));
        }
Example #27
0
        public void GeneratePlanets()
        {
            foreach (var obj in SystemGenerator.Static.m_objects)
            {
                if (obj == null)
                {
                    continue;
                }
                if (obj.Type != SystemObjectType.PLANET)
                {
                    continue;
                }

                MyPlanetItem planet = (MyPlanetItem)obj;

                if (planet.Generated)
                {
                    continue;
                }
                MyPlanetGeneratorDefinition definition = GetDefinition(planet.DefName);
                if (definition == null)
                {
                    continue;
                }
                long   id   = MyRandom.Instance.NextLong();
                string name = (planet.DisplayName + " - " + definition.Id.SubtypeId).Replace(" ", "_");
                if (planet.CenterPosition.Equals(Vector3D.Zero))
                {
                    planet.CenterPosition = planet.OffsetPosition;
                }
                MyPlanet generatedPlanet = MyWorldGenerator.AddPlanet(name, planet.DisplayName, planet.DefName, planet.CenterPosition - GetPlanetOffset(definition, planet.Size), m_seed, planet.Size, true, id, false, true);

                if (generatedPlanet == null)
                {
                    continue;
                }

                planet.CenterPosition           = generatedPlanet.PositionComp.GetPosition();
                generatedPlanet.DisplayNameText = planet.DisplayName;
                generatedPlanet.AsteroidName    = planet.DisplayName;

                if (planet.PlanetRing != null)
                {
                    planet.PlanetRing.Center = planet.CenterPosition;
                }
                List <Vector3D> spawnedMoons = new List <Vector3D>();

                for (int i = 0; i < planet.PlanetMoons.Length; i++)
                {
                    MyPlanetMoonItem moon = planet.PlanetMoons[i];
                    if (moon == null)
                    {
                        continue;
                    }
                    MyPlanetGeneratorDefinition moonDef = GetDefinition(moon.DefName);
                    if (moonDef == null)
                    {
                        continue;
                    }
                    var    position        = new Vector3D(0, 0, 0);
                    long   mId             = MyRandom.Instance.NextLong();
                    string storageNameMoon = ("Moon " + moon.DisplayName + " - " + moonDef.Id.SubtypeId).Replace(" ", "_");
                    var    threshold       = 0;
                    do
                    {
                        double angle = MyRandom.Instance.GetRandomFloat(0, (float)Math.PI * 2f);
                        position = new Vector3D(moon.Distance * Math.Sin(angle), moon.Distance * Math.Cos(angle), moon.Distance * Math.Sin(MyRandom.Instance.GetRandomFloat((float)-Math.PI / 2, (float)Math.PI / 2)));
                        position = Vector3D.Add(planet.CenterPosition, position);
                        threshold++;
                    } while (ObstructedPlace(position, spawnedMoons, planet.Size, planet.PlanetRing) && threshold < 10000);
                    MyPlanet spawnedMoon = MyWorldGenerator.AddPlanet(storageNameMoon, moon.DisplayName, moon.DefName, position, m_seed, moon.Size, true, mId, false, true);
                    spawnedMoons.Add(spawnedMoon.PositionComp.GetPosition());

                    if (SettingsSession.Static.Settings.GeneratorSettings.PlanetSettings.ShowMoonGPS)
                    {
                        GlobalGpsManager.Static.AddGps(moon.DisplayName, Color.Aqua, spawnedMoon.PositionComp.GetPosition());
                    }
                }

                planet.Generated = true;
                if (SettingsSession.Static.Settings.GeneratorSettings.PlanetSettings.ShowPlanetGPS)
                {
                    GlobalGpsManager.Static.AddGps(planet.DisplayName, Color.Aqua, generatedPlanet.PositionComp.GetPosition());
                }
            }
        }
Example #28
0
        private static MyPlanet CreatePlanet(string storageName, string planetName, ref Vector3D positionMinCorner, int seed, float size, long entityId, ref MyPlanetGeneratorDefinition generatorDef, bool addGPS, bool userCreated = false)
        {
            if (MyFakes.ENABLE_PLANETS == false)
            {
                return(null);
            }

            var random = MyRandom.Instance;

            using (MyRandom.Instance.PushSeed(seed))
            {
                MyPlanetStorageProvider provider = new MyPlanetStorageProvider();
                provider.Init(seed, generatorDef, size / 2f);

                IMyStorage storage = new MyOctreeStorage(provider, provider.StorageSize);

                float minHillSize = provider.Radius * generatorDef.HillParams.Min;
                float maxHillSize = provider.Radius * generatorDef.HillParams.Max;

                float averagePlanetRadius = provider.Radius;

                float outerRadius = averagePlanetRadius + maxHillSize;
                float innerRadius = averagePlanetRadius + minHillSize;

                float atmosphereRadius = generatorDef.AtmosphereSettings.HasValue && generatorDef.AtmosphereSettings.Value.Scale > 1f ? 1 + generatorDef.AtmosphereSettings.Value.Scale : 1.75f;
                atmosphereRadius *= provider.Radius;

                float redAtmosphereShift   = random.NextFloat(generatorDef.HostileAtmosphereColorShift.R.Min, generatorDef.HostileAtmosphereColorShift.R.Max);
                float greenAtmosphereShift = random.NextFloat(generatorDef.HostileAtmosphereColorShift.G.Min, generatorDef.HostileAtmosphereColorShift.G.Max);
                float blueAtmosphereShift  = random.NextFloat(generatorDef.HostileAtmosphereColorShift.B.Min, generatorDef.HostileAtmosphereColorShift.B.Max);

                Vector3 atmosphereWavelengths = new Vector3(0.650f + redAtmosphereShift, 0.570f + greenAtmosphereShift, 0.475f + blueAtmosphereShift);

                atmosphereWavelengths.X = MathHelper.Clamp(atmosphereWavelengths.X, 0.1f, 1.0f);
                atmosphereWavelengths.Y = MathHelper.Clamp(atmosphereWavelengths.Y, 0.1f, 1.0f);
                atmosphereWavelengths.Z = MathHelper.Clamp(atmosphereWavelengths.Z, 0.1f, 1.0f);

                var planet = new MyPlanet();
                planet.EntityId = entityId;

                MyPlanetInitArguments planetInitArguments;
                planetInitArguments.StorageName           = storageName;
                planetInitArguments.Storage               = storage;
                planetInitArguments.PositionMinCorner     = positionMinCorner;
                planetInitArguments.Radius                = provider.Radius;
                planetInitArguments.AtmosphereRadius      = atmosphereRadius;
                planetInitArguments.MaxRadius             = outerRadius;
                planetInitArguments.MinRadius             = innerRadius;
                planetInitArguments.HasAtmosphere         = generatorDef.HasAtmosphere;
                planetInitArguments.AtmosphereWavelengths = atmosphereWavelengths;
                planetInitArguments.GravityFalloff        = generatorDef.GravityFalloffPower;
                planetInitArguments.MarkAreaEmpty         = true;
                planetInitArguments.AtmosphereSettings    = generatorDef.AtmosphereSettings.HasValue ? generatorDef.AtmosphereSettings.Value : MyAtmosphereSettings.Defaults();
                planetInitArguments.SurfaceGravity        = generatorDef.SurfaceGravity;
                planetInitArguments.AddGps                = addGPS;
                planetInitArguments.SpherizeWithDistance  = true;
                planetInitArguments.Generator             = generatorDef;
                planetInitArguments.UserCreated           = userCreated;

                planet.Init(planetInitArguments);

                MyEntities.Add(planet);
                MyEntities.RaiseEntityCreated(planet);

                return(planet);
            }
            return(null);
        }
Example #29
0
 public MyPlanetMaterialProvider(MyPlanetGeneratorDefinition generatorDef, MyPlanetShapeProvider planetShape, MyCubemap[] maps)
 {
     this.m_materials = new Dictionary <byte, PlanetMaterial>(generatorDef.SurfaceMaterialTable.Length);
     for (int i = 0; i < generatorDef.SurfaceMaterialTable.Length; i++)
     {
         byte num2 = generatorDef.SurfaceMaterialTable[i].Value;
         this.m_materials[num2] = new PlanetMaterial(generatorDef.SurfaceMaterialTable[i], generatorDef.MinimumSurfaceLayerDepth);
     }
     this.m_defaultMaterial    = new PlanetMaterial(generatorDef.DefaultSurfaceMaterial, generatorDef.MinimumSurfaceLayerDepth);
     this.m_subsurfaceMaterial = (generatorDef.DefaultSubSurfaceMaterial == null) ? this.m_defaultMaterial : new PlanetMaterial(generatorDef.DefaultSubSurfaceMaterial, generatorDef.MinimumSurfaceLayerDepth);
     this.m_planetShape        = planetShape;
     this.Maps          = maps;
     this.m_materialMap = maps[0];
     this.m_biomeMap    = maps[1];
     this.m_oreMap      = maps[2];
     if (this.m_materialMap != null)
     {
         this.m_mapResolutionMinusOne = this.m_materialMap.Resolution - 1;
     }
     this.m_generator      = generatorDef;
     this.m_invHeightRange = 1f / (this.m_planetShape.MaxHillHeight - this.m_planetShape.MinHillHeight);
     this.m_biomePixelSize = ((float)((planetShape.MaxHillHeight + planetShape.Radius) * 3.1415926535897931)) / ((this.m_mapResolutionMinusOne + 1) * 2f);
     this.m_hashCode       = generatorDef.FolderName.GetHashCode();
     if ((this.m_generator.MaterialGroups != null) && (this.m_generator.MaterialGroups.Length != 0))
     {
         this.m_biomes = new Dictionary <byte, PlanetBiome>();
         foreach (MyPlanetMaterialGroup group in this.m_generator.MaterialGroups)
         {
             this.m_biomes[group.Value] = new PlanetBiome(group, this.m_generator.MinimumSurfaceLayerDepth);
         }
     }
     if (MyHeightMapLoadingSystem.Static != null)
     {
         this.m_blendingTileset = MyHeightMapLoadingSystem.Static.GetTerrainBlendTexture(this.m_generator.MaterialBlending);
     }
     this.m_ores = new Dictionary <byte, List <PlanetOre> >();
     foreach (MyPlanetOreMapping mapping in this.m_generator.OreMappings)
     {
         MyVoxelMaterialDefinition material = GetMaterial(mapping.Type);
         if (material != null)
         {
             PlanetOre item = new PlanetOre {
                 Depth          = mapping.Depth,
                 Start          = mapping.Start,
                 Value          = mapping.Value,
                 Material       = material,
                 ColorInfluence = mapping.ColorInfluence
             };
             if (mapping.ColorShift != null)
             {
                 item.TargetColor = new Vector3?(mapping.ColorShift.Value.ColorToHSV());
             }
             if (!this.m_ores.ContainsKey(mapping.Value))
             {
                 List <PlanetOre> list1 = new List <PlanetOre>();
                 list1.Add(item);
                 List <PlanetOre> list = list1;
                 this.m_ores.Add(mapping.Value, list);
             }
             this.m_ores[mapping.Value].Add(item);
         }
     }
     this.Closed = false;
 }
        /// <summary>
        /// Generates a completely new system based on the
        /// world settings.
        /// </summary>
        /// <returns></returns>
        private MyObjectBuilder_SystemData GenerateNewStarSystem()
        {
            MyPluginLog.Log("Generating a new Solar system ...");

            int seed = MySession.Static.Settings.ProceduralSeed + Guid.NewGuid().GetHashCode();
            MyObjectBuilder_SystemData system = new MyObjectBuilder_SystemData();

            var settings = MySettingsSession.Static.Settings.GeneratorSettings;

            var orbitDistances       = settings.MinMaxOrbitDistance;
            var planetsAmount        = settings.MinMaxPlanets;
            var asteroidObjectAmount = settings.MinMaxAsteroidObjects;
            var worldSize            = settings.WorldSize;

            var asteroidProviders = MyAsteroidObjectsManager.Static.AsteroidObjectProviders;

            using (MyRandom.Instance.PushSeed(seed))
            {
                long planetCount          = MyRandom.Instance.Next(planetsAmount.Min, planetsAmount.Max + 1);
                long asteroidObjectCount  = MyRandom.Instance.Next(asteroidObjectAmount.Min, asteroidObjectAmount.Max + 1);
                long systemSize           = planetCount + asteroidObjectCount;
                int  currentPlanetIndex   = 0;
                int  currentAsteroidIndex = 0;
                long currentOrbitDistance = 0;

                double planetProb = planetCount / (double)(planetCount + asteroidObjectCount);

                if (m_suns.Count > 0)
                {
                    MyPlanetGeneratorDefinition sunDef = m_suns[MyRandom.Instance.Next(0, m_suns.Count)];
                    MySystemPlanet sun = new MySystemPlanet();
                    sun.CenterPosition = Vector3D.Zero;
                    sun.SubtypeId      = sunDef.Id.SubtypeId.String;
                    sun.DisplayName    = sunDef.Id.SubtypeId.String;
                    sun.Diameter       = CalculatePlanetDiameter(sunDef) * 2;
                    sun.ChildObjects   = new HashSet <MySystemObject>();
                    sun.Generated      = false;
                    sun.Type           = MySystemObjectType.PLANET;

                    system.CenterObject   = sun;
                    currentOrbitDistance += (long)sun.Diameter * 2 + (long)sunDef.AtmosphereHeight;
                }
                else
                {
                    system.CenterObject             = new MySystemObject();
                    system.CenterObject.Type        = MySystemObjectType.EMPTY;
                    system.CenterObject.DisplayName = "System center";
                }

                while (planetCount > 0 || asteroidObjectCount > 0)
                {
                    currentOrbitDistance += MyRandom.Instance.Next(orbitDistances.Min, orbitDistances.Max);

                    //Maybe rework to override orbit distance, so all objects fit
                    if (worldSize >= 0 && currentOrbitDistance >= worldSize)
                    {
                        return(system);
                    }

                    MySystemObject obj = null;

                    if (asteroidObjectCount <= 0 || (MyRandom.Instance.NextDouble() <= planetProb && planetCount > 0)) // Generate planet
                    {
                        obj = GeneratePlanet(currentPlanetIndex++, Math.Sin((system.Count() - 1) * Math.PI / systemSize), currentOrbitDistance);
                        planetCount--;
                    }
                    else if (asteroidObjectCount > 0) // Generate asteroid object
                    {
                        int providerIndex = MyRandom.Instance.Next(0, asteroidProviders.Keys.Count);
                        MyAbstractAsteroidObjectProvider provider = null;
                        foreach (var prov in asteroidProviders)
                        {
                            if (!prov.Value.IsSystemGeneratable())
                            {
                                continue;
                            }

                            if (providerIndex-- == 0)
                            {
                                provider = prov.Value;
                            }
                        }

                        if (provider == null)
                        {
                            continue;
                        }

                        obj = provider.GenerateInstance(currentAsteroidIndex++, null, currentOrbitDistance);

                        if (obj == null)
                        {
                            continue;
                        }

                        (obj as MySystemAsteroids).AsteroidTypeName = provider.GetTypeName();

                        asteroidObjectCount--;
                    }
                    if (obj == null)
                    {
                        continue;
                    }

                    obj.ParentId = system.CenterObject.Id;
                    system.CenterObject.ChildObjects.Add(obj);
                }
            }

            MyPluginLog.Log("Solar system generated ...");

            return(system);
        }