Exemple #1
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            m_cameraDummy    = Matrix.Identity;
            m_characterDummy = Matrix.Identity;

            base.Init(objectBuilder, cubeGrid);

            var chamberOb = objectBuilder as MyObjectBuilder_CryoChamber;

            if (chamberOb.SteamId != null && chamberOb.SerialId != null)
            {
                m_currentPlayerId = new MyPlayer.PlayerId(chamberOb.SteamId.Value, chamberOb.SerialId.Value);
            }
            else
            {
                m_currentPlayerId = null;
            }

            var overlayTexture = BlockDefinition.OverlayTexture;

            if (!string.IsNullOrEmpty(overlayTexture))
            {
                m_overlayTextureName = overlayTexture;
            }

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                MyStringHash.GetOrCompute(BlockDefinition.ResourceSinkGroup),
                BlockDefinition.IdlePowerConsumption,
                this.CalculateRequiredPowerInput);
            sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink = sinkComp;

            NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
        }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);

            var gasTankDefinition = builder as MyObjectBuilder_GasTankDefinition;

            MyDebug.AssertDebug(gasTankDefinition != null, "Initializing gas tank definition using wrong object builder.");

            Capacity = gasTankDefinition.Capacity;

            MyDefinitionId gasId;

            if (gasTankDefinition.StoredGasId.IsNull())    // Backward compatibility
            {
                gasId = new MyDefinitionId(typeof(MyObjectBuilder_GasProperties), "Oxygen");
            }
            else
            {
                gasId = gasTankDefinition.StoredGasId;
            }

            StoredGasId         = gasId;
            ResourceSourceGroup = MyStringHash.GetOrCompute(gasTankDefinition.ResourceSourceGroup);
        }
Exemple #3
0
        public override void Deserialize(MyObjectBuilder_ComponentBase objectBuilder)
        {
            MyObjectBuilder_CharacterStatComponent component = objectBuilder as MyObjectBuilder_CharacterStatComponent;

            using (List <MyStatLogic> .Enumerator enumerator = this.m_scripts.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    enumerator.Current.Close();
                }
            }
            this.m_scripts.Clear();
            if (component != null)
            {
                if (component.Stats != null)
                {
                    foreach (MyObjectBuilder_EntityStat stat in component.Stats)
                    {
                        MyEntityStatDefinition definition = null;
                        if ((MyDefinitionManager.Static.TryGetDefinition <MyEntityStatDefinition>(new MyDefinitionId(stat.TypeId, stat.SubtypeId), out definition) && definition.Enabled) && ((definition.EnabledInCreative && MySession.Static.CreativeMode) || (definition.AvailableInSurvival && MySession.Static.SurvivalMode)))
                        {
                            this.AddStat(MyStringHash.GetOrCompute(definition.Name), stat, true);
                        }
                    }
                }
                if ((component.ScriptNames != null) && Sync.IsServer)
                {
                    component.ScriptNames = component.ScriptNames.Distinct <string>().ToArray <string>();
                    foreach (string str in component.ScriptNames)
                    {
                        this.InitScript(str);
                    }
                }
            }
            base.Deserialize(objectBuilder);
        }
Exemple #4
0
        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            m_objectBuilder = objectBuilder;

            Entity.NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_FRAME;

            MyResourceSinkInfo ElectricityResourceSinkInfo = new MyResourceSinkInfo {
                ResourceTypeId    = ElectricityDefinitionsId,
                MaxRequiredInput  = MaxElectricityConsumption,
                RequiredInputFunc = OnUpdateElectricityUsage
            };

            MyResourceSinkComponent ResourceSink = new MyResourceSinkComponent();

            ResourceSink.Init(MyStringHash.GetOrCompute("Factory"), ElectricityResourceSinkInfo);

            Entity.Components.Add <MyResourceSinkComponent>(ResourceSink);

            ResourceSink.Update();

            m_resourceSink = ResourceSink;

            /*
             * // Because a Cargo Container does not produce anything, we need to create a new Resource Source for it and attach it to the block
             * MyResourceSourceComponent ResourceSource = new MyResourceSourceComponent();
             * Entity.Components.Add<MyResourceSourceComponent>(ResourceSource);
             *
             * // We let it produce OxyHydrogen gas with a defined (changed by us later) maximum of 1200MW
             * MyResourceSourceInfo oxyHydrogenResourceSourceInfo = new MyResourceSourceInfo() {ResourceTypeId = ElectricityDefinitionsId, DefinedOutput = 0.0001f, IsInfiniteCapacity = true, ProductionToCapacityMultiplier = 60*60};
             * ResourceSource.Init(MyStringHash.GetOrCompute("Battery"), oxyHydrogenResourceSourceInfo);
             * ResourceSource.SetMaxOutputByType(ElectricityDefinitionsId, 0.00005f);
             * ResourceSource.SetProductionEnabledByType(ElectricityDefinitionsId, true);
             *
             * m_resourceSource = ResourceSource;
             */
        }
Exemple #5
0
        public override void ContactPointCallback(ref MyGridContactInfo value)
        {
            //return;
            var prop = value.Event.ContactProperties;

            prop.Friction           = Friction;
            prop.Restitution        = 0.5f;
            value.EnableParticles   = false;
            value.RubberDeformation = true;

            string particle = null;

            if (value.CollidingEntity is MyVoxelBase && MyFakes.ENABLE_DRIVING_PARTICLES)
            {
                MyVoxelBase voxel           = value.CollidingEntity as MyVoxelBase;
                Vector3D    contactPosition = value.ContactPosition;
                var         vmat            = voxel.GetMaterialAt(ref contactPosition);
                if (vmat == null)
                {
                    return;
                }

                MyStringHash material = MyStringHash.GetOrCompute(vmat.MaterialTypeName);
                particle = MyMaterialPropertiesHelper.Static.GetCollisionEffect(MyMaterialPropertiesHelper.CollisionType.Start, m_wheelStringHash, material);
            }
            else if (value.CollidingEntity is MyCubeGrid && MyFakes.ENABLE_DRIVING_PARTICLES)
            {
                MyCubeGrid   grid     = value.CollidingEntity as MyCubeGrid;
                MyStringHash material = grid.Physics.GetMaterialAt(value.ContactPosition);
                particle = MyMaterialPropertiesHelper.Static.GetCollisionEffect(MyMaterialPropertiesHelper.CollisionType.Start, m_wheelStringHash, material);
            }
            if (Render != null && particle != null)
            {
                Render.TrySpawnParticle((Vector3)value.ContactPosition, value.Event.ContactPoint.Normal, particle);
            }
        }
Exemple #6
0
        public virtual void Init(MyObjectBuilder_Base objectBuilder)
        {
            var builder = (MyObjectBuilder_EntityStat)objectBuilder;

            MyEntityStatDefinition definition;

            MyDefinitionManager.Static.TryGetDefinition <MyEntityStatDefinition>(new MyDefinitionId(builder.TypeId, builder.SubtypeId), out definition);

            Debug.Assert(definition != null);
            StatDefinition = definition;

            System.Diagnostics.Debug.Assert(!float.IsNaN(definition.MaxValue) && !float.IsNaN(definition.MinValue) && !float.IsNaN(definition.DefaultValue), "Invalid values in stat definition!");

            m_maxValue     = definition.MaxValue;
            m_minValue     = definition.MinValue;
            m_currentValue = builder.Value * m_maxValue;
            m_defaultValue = definition.DefaultValue;

            m_lastSyncValue = m_currentValue;
            m_statId        = MyStringHash.GetOrCompute(definition.Name);

            m_regenAmountMultiplier          = builder.StatRegenAmountMultiplier;
            m_regenAmountMultiplierDuration  = builder.StatRegenAmountMultiplierDuration;
            m_regenAmountMultiplierTimeStart = MySandboxGame.TotalGamePlayTimeInMilliseconds;
            m_regenAmountMultiplierTimeAlive = 0;
            m_regenAmountMultiplierActive    = m_regenAmountMultiplierDuration > 0;

            ClearEffects();
            if (builder.Effects != null)
            {
                foreach (var effectBuilder in builder.Effects)
                {
                    AddEffect(effectBuilder);
                }
            }
        }
Exemple #7
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.m_characterDummy = Matrix.Identity;
            base.Init(objectBuilder, cubeGrid);
            if (base.ResourceSink != null)
            {
                base.ResourceSink.SetMaxRequiredInputByType(MyResourceDistributorComponent.ElectricityId, this.BlockDefinition.IdlePowerConsumption);
                base.ResourceSink.SetRequiredInputFuncByType(MyResourceDistributorComponent.ElectricityId, new Func <float>(this.CalculateRequiredPowerInput));
                base.ResourceSink.IsPoweredChanged += new Action(this.Receiver_IsPoweredChanged);
            }
            else
            {
                MyResourceSinkComponent component = new MyResourceSinkComponent(1);
                component.Init(MyStringHash.GetOrCompute(this.BlockDefinition.ResourceSinkGroup), this.BlockDefinition.IdlePowerConsumption, new Func <float>(this.CalculateRequiredPowerInput));
                component.IsPoweredChanged += new Action(this.Receiver_IsPoweredChanged);
                base.ResourceSink           = component;
            }
            MyObjectBuilder_CryoChamber chamber = objectBuilder as MyObjectBuilder_CryoChamber;

            if ((chamber.SteamId == null) || (chamber.SerialId == null))
            {
                this.m_currentPlayerId = null;
            }
            else
            {
                this.m_currentPlayerId = new MyPlayer.PlayerId(chamber.SteamId.Value, chamber.SerialId.Value);
            }
            string overlayTexture = this.BlockDefinition.OverlayTexture;

            if (!string.IsNullOrEmpty(overlayTexture))
            {
                this.m_overlayTextureName = overlayTexture;
            }
            base.HorizonIndicatorEnabled = false;
            base.NeedsUpdate            |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_10TH_FRAME;
        }
Exemple #8
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;

            base.Init(objectBuilder, cubeGrid);
            NeedsUpdate = MyEntityUpdateEnum.EACH_FRAME | MyEntityUpdateEnum.EACH_10TH_FRAME;

            var ob = objectBuilder as MyObjectBuilder_CameraBlock;

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                MyStringHash.GetOrCompute(BlockDefinition.ResourceSinkGroup),
                BlockDefinition.RequiredPowerInput,
                CalculateRequiredPowerInput);

            sinkComp.IsPoweredChanged     += Receiver_IsPoweredChanged;
            sinkComp.RequiredInputChanged += Receiver_RequiredInputChanged;
            sinkComp.Update();
            ResourceSink = sinkComp;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
            IsWorkingChanged += MyCameraBlock_IsWorkingChanged;

            IsInFirstPersonView = true;

            if (ob.IsActive)
            {
                m_requestActivateAfterLoad = true;
                ob.IsActive = false;
            }

            OnChangeFov(ob.Fov);

            UpdateText();
        }
        public void Consume(MyFixedPoint amount, MyConsumableItemDefinition definition)
        {
            if (definition == null)
            {
                return;
            }

            MyEntityStat stat;
            var          regenEffect = new MyObjectBuilder_EntityStatRegenEffect();

            regenEffect.Interval      = 1.0f;
            regenEffect.MaxRegenRatio = 1.0f;
            regenEffect.MinRegenRatio = 0.0f;

            foreach (var statValue in definition.Stats)
            {
                if (Stats.TryGetValue(MyStringHash.GetOrCompute(statValue.Name), out stat))
                {
                    regenEffect.TickAmount = statValue.Value * (float)amount;
                    regenEffect.Duration   = statValue.Time;
                    stat.AddEffect(regenEffect);
                }
            }
        }
Exemple #10
0
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);
            MyObjectBuilder_ProductionBlockDefinition ob = builder as MyObjectBuilder_ProductionBlockDefinition;

            this.InventoryMaxVolume          = ob.InventoryMaxVolume;
            this.InventorySize               = ob.InventorySize;
            this.ResourceSinkGroup           = MyStringHash.GetOrCompute(ob.ResourceSinkGroup);
            this.StandbyPowerConsumption     = ob.StandbyPowerConsumption;
            this.OperationalPowerConsumption = ob.OperationalPowerConsumption;
            if (ob.BlueprintClasses == null)
            {
                this.InitializeLegacyBlueprintClasses(ob);
            }
            this.BlueprintClasses = new List <MyBlueprintClassDefinition>();
            foreach (string str in ob.BlueprintClasses)
            {
                MyBlueprintClassDefinition blueprintClass = MyDefinitionManager.Static.GetBlueprintClass(str);
                if (blueprintClass != null)
                {
                    this.BlueprintClasses.Add(blueprintClass);
                }
            }
        }
Exemple #11
0
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);
            MyObjectBuilder_EnvironmentItemsDefinition definition = builder as MyObjectBuilder_EnvironmentItemsDefinition;

            this.m_itemDefinitions = new HashSet <MyStringHash>(MyStringHash.Comparer);
            this.m_definitionList  = new List <MyStringHash>();
            object[] customAttributes = builder.Id.TypeId.GetCustomAttributes(typeof(MyEnvironmentItemsAttribute), false);
            if (customAttributes.Length != 1)
            {
                this.m_itemDefinitionType = typeof(MyObjectBuilder_EnvironmentItemDefinition);
            }
            else
            {
                MyEnvironmentItemsAttribute attribute = customAttributes[0] as MyEnvironmentItemsAttribute;
                this.m_itemDefinitionType = attribute.ItemDefinitionType;
            }
            this.Channel         = definition.Channel;
            this.MaxViewDistance = definition.MaxViewDistance;
            this.SectorSize      = definition.SectorSize;
            this.ItemSize        = definition.ItemSize;
            this.Material        = MyStringHash.GetOrCompute(definition.PhysicalMaterial);
            this.Frequencies     = new List <float>();
        }
Exemple #12
0
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            MyDefinitionId id;

            base.Init(builder);
            MyObjectBuilder_OxygenFarmDefinition definition = builder as MyObjectBuilder_OxygenFarmDefinition;

            this.ResourceSinkGroup   = MyStringHash.GetOrCompute(definition.ResourceSinkGroup);
            this.ResourceSourceGroup = MyStringHash.GetOrCompute(definition.ResourceSourceGroup);
            this.PanelOrientation    = definition.PanelOrientation;
            this.IsTwoSided          = definition.TwoSidedPanel;
            this.PanelOffset         = definition.PanelOffset;
            if (definition.ProducedGas.Id.IsNull())
            {
                id = new MyDefinitionId(typeof(MyObjectBuilder_GasProperties), "Oxygen");
            }
            else
            {
                id = definition.ProducedGas.Id;
            }
            this.ProducedGas  = id;
            this.MaxGasOutput = definition.ProducedGas.MaxOutputPerSecond;
            this.OperationalPowerConsumption = definition.OperationalPowerConsumption;
        }
Exemple #13
0
        public override void LoadData()
        {
            base.LoadData();
            var allDefs = MyDefinitionManager.Static.GetAllDefinitions().ToArray();

            foreach (var tankDef in allDefs.OfType <MyGasTankDefinition>())
            {
                var cubeSideLen  = tankDef.CubeSize.GetSizeM();
                var size         = tankDef.Size * cubeSideLen;
                var surfaceArea  = 2 * (size.X * size.Y + size.X * size.Z + size.Y * size.Z);    //m^2
                var tankWeightKg = surfaceArea * (tankDef.CubeSize == MyCubeSize.Large ? 9 : 4); //not sure this har is realistic
                tankDef.Capacity = tankDef.GetVolumeM3() * 1000;
                RescaleToHaveMass(tankDef, tankWeightKg);
            }


            // foreach(var oreDetector in allDefs.OfType<MyOreDetectorDefinition>())
            // {
            //     // ore detectors should be 10x longer
            //     var diameter = oreDetector.GetDiameter();
            //     oreDetector.MaximumRange = diameter * 100;
            // }

            // no you can't have a cookie.
            foreach (var medbay in allDefs.OfType <MyMedicalRoomDefinition>())
            {
                medbay.RespawnAllowed = false;
            }


            foreach (var wheelDef in allDefs.OfType <MyMotorSuspensionDefinition>())
            {
                // wheels in this game should be way more powerful
            }

            foreach (var componenet in allDefs.OfType <MyPhysicalItemDefinition>())
            {
                componenet.MinimalPricePerUnit = 0;
            }

            foreach (var batDef in allDefs.OfType <MyBatteryBlockDefinition>())
            {
                // todo use the number of battery componenets to figure out
                batDef.RequiredPowerInput      = batDef.MaxStoredPower * 6;  // 6 is charge to full in 10mins which is pretty close to what we have rn
                batDef.MaxPowerOutput          = batDef.MaxStoredPower * 40; // batts have a lot of power 80 continous is fairly common
                batDef.InitialStoredPowerRatio = 0.1f;
            }
            foreach (var thrusterDef in allDefs.OfType <MyThrustDefinition>())
            {
                ThrusterData thruster = null;
                var          diameter = thrusterDef.Size.Dot(ref Vector3I.Up) * thrusterDef.CubeSize.GetSizeM();

                if (thrusterDef.ThrusterType == MyStringHash.GetOrCompute("Ion"))
                {
                    // yeah ions don't really do much
                    thrusterDef.ForceMagnitude *= 1e-6f;
                    continue;
                }

                if (thrusterDef.ThrusterType == MyStringHash.GetOrCompute("Atmospheric"))
                {
                    thruster = ThrusterData.DjiQuadcopter;
                    thrusterDef.MinPlanetaryInfluence = 0.1f; // this is the best thing.
                }

                // normal thrusters start here
                if (thrusterDef.ThrusterType == MyStringHash.GetOrCompute("Hydrogen"))
                {
                    thruster = ThrusterData.RS25;
                }


                // this is in N
                var scale = Math.Pow(diameter / thruster.Diameter, 2);
                var mass  = scale * thruster.Mass;
                RescaleToHaveMass(thrusterDef, mass, true);


                var force = scale * thruster.MaxThrust; // force in newtons

                var maxIsp = Math.Max(thruster.IspSea, thruster.IspVac);

                var massFlowRate = force / (maxIsp * PhysicsData.G0);


                var fuel  = thruster.Fuel;
                var power = massFlowRate / fuel.Mass * fuel.Energy / Mwh;
                thrusterDef.ForceMagnitude = (float)force;
                //TODO i am sure this unit should be Mw and powe is in Mw but for some reason game wants it in Mwh/s not
                thrusterDef.MinPowerConsumption = 0;
                thrusterDef.MaxPowerConsumption = (float)(power);

                /*
                 * var twr = 0;
                 *
                 * var oiwer= mass* PhysicsData.G0* twr / (maxIsp * PhysicsData.G0) / fuel.Mass * fuel.Energy
                 * var oiwer= mass* twr / (maxIsp) / fuel.Mass * fuel.Energy
                 *
                 */

                //thrusterDef.FuelConverter.Efficiency = 1f; // assume

                //var fuelEnergyPerKg =

                // this is in
                //thruster.MaxPowerConsumption = 2790.0e-6f *
            }
        }
        private void SetThrustMountPoints(string subtypeId, params MyObjectBuilder_CubeBlockDefinition.MountPoint[] addMPObjects)
        {
            MyCubeBlockDefinition def;

            if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(new MyDefinitionId(typeof(MyObjectBuilder_Thrust), MyStringHash.GetOrCompute(subtypeId)), out def))
            {
                // HACK since there's no way to edit the flame properly, this hides it and the mod draws its own
                MyThrustDefinition thrustDef = (MyThrustDefinition)def;
                thrustDef.FlameFullColor = Vector4.Zero;
                thrustDef.FlameIdleColor = Vector4.Zero;

                MyCubeBlockDefinition.MountPoint[] mp = def.MountPoints;
                def.MountPoints = new MyCubeBlockDefinition.MountPoint[mp.Length + addMPObjects.Length];

                for (int i = 0; i < mp.Length; i++)
                {
                    def.MountPoints[i] = mp[i];
                }

                for (int i = 0; i < addMPObjects.Length; ++i)
                {
                    MyObjectBuilder_CubeBlockDefinition.MountPoint mpObj = addMPObjects[i];

                    Vector3 start = new Vector3(Vector2.Min(mpObj.Start, mpObj.End) + 0.001f, 0.0004f);
                    Vector3 end   = new Vector3(Vector2.Max(mpObj.Start, mpObj.End) - 0.001f, -0.0004f);

                    int side = (int)mpObj.Side;
                    TransformMountPointPosition(ref start, side, def.Size, out start);
                    TransformMountPointPosition(ref end, side, def.Size, out end);

                    Vector3I forward = Vector3I.Forward;
                    Vector3I.TransformNormal(ref forward, ref m_mountPointTransforms[side], out forward);

                    def.MountPoints[mp.Length + i] = new MyCubeBlockDefinition.MountPoint()
                    {
                        Start          = start,
                        End            = end,
                        Normal         = forward,
                        ExclusionMask  = mpObj.ExclusionMask,
                        PropertiesMask = mpObj.PropertiesMask,
                        Enabled        = mpObj.Enabled,
                        Default        = mpObj.Default,
                    };
                }
            }
        }
Exemple #15
0
        public override void Init(MyObjectBuilder_EntityBase builder, Sandbox.Engine.Voxels.IMyStorage storage)
        {
            ProfilerShort.Begin("MyPlanet::Init()");
            if (MyFakes.ENABLE_PLANETS == false)
            {
                throw new PlanetsNotEnabledException();
            }

            ProfilerShort.Begin("MyVoxelBase Init");

            SyncFlag = true;

            base.Init(builder);

            ProfilerShort.BeginNextBlock("Load Saved Data");

            var ob = (MyObjectBuilder_Planet)builder;

            if (ob == null)
            {
                return;
            }

            if (ob.MutableStorage)
            {
                StorageName = ob.StorageName;
            }
            else
            {
                StorageName = string.Format("{0}", ob.StorageName);
            }

            m_planetInitValues.StorageName           = StorageName;
            m_planetInitValues.PositionMinCorner     = ob.PositionAndOrientation.Value.Position;
            m_planetInitValues.HasAtmosphere         = ob.HasAtmosphere;
            m_planetInitValues.AtmosphereRadius      = ob.AtmosphereRadius;
            m_planetInitValues.AtmosphereWavelengths = ob.AtmosphereWavelengths;
            m_planetInitValues.GravityFalloff        = ob.GravityFalloff;
            m_planetInitValues.MarkAreaEmpty         = ob.MarkAreaEmpty;
            m_planetInitValues.SurfaceGravity        = ob.SurfaceGravity;
            m_planetInitValues.AddGps = ob.ShowGPS;
            m_planetInitValues.SpherizeWithDistance = ob.SpherizeWithDistance;
            m_planetInitValues.Generator            = ob.PlanetGenerator == "" ? null : MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(ob.PlanetGenerator));
            if (m_planetInitValues.Generator == null)
            {
                string message = string.Format("No definition found for planet generator {0}.", ob.PlanetGenerator);
                MyLog.Default.WriteLine(message);
                throw new Exception(message);
            }

            m_planetInitValues.AtmosphereSettings = m_planetInitValues.Generator.AtmosphereSettings.HasValue ? m_planetInitValues.Generator.AtmosphereSettings.Value : MyAtmosphereSettings.Defaults();
            m_planetInitValues.UserCreated        = false;

            ProfilerShort.BeginNextBlock("Load Storage");
            if (storage != null)
            {
                m_planetInitValues.Storage = storage;
            }
            else
            {
                m_planetInitValues.Storage = MyStorageBase.Load(ob.StorageName);
            }

            ProfilerShort.BeginNextBlock("Init Internal");
            Init(m_planetInitValues);
            ProfilerShort.End();

            ProfilerShort.End();
        }
Exemple #16
0
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_EquiHarvestableComponentDefinition)def;

            _lootTableByTag.Clear();
            _lootTableByItem.Clear();
            if (ob.Entries == null)
            {
                return;
            }
            foreach (var k in ob.Entries)
            {
                if (string.IsNullOrWhiteSpace(k.From))
                {
                    MyDefinitionErrors.Add(Package, $"{Id} has an entry with no from state", LogSeverity.Warning);
                    continue;
                }

                if (k.Harvesters == null || k.Harvesters.Length == 0)
                {
                    MyDefinitionErrors.Add(Package, $"{Id} has an entry with no harvesters", LogSeverity.Warning);
                    continue;
                }

                MyLootTableDefinition lootTable = null;
                if (k.LootTable.HasValue)
                {
                    lootTable = MyDefinitionManager.Get <MyLootTableDefinition>(k.LootTable.Value);
                    if (lootTable == null)
                    {
                        MyDefinitionErrors.Add(Package, $"{Id} has an entry from {k.From} referring to missing loot table {k.LootTable}",
                                               LogSeverity.Warning);
                        continue;
                    }
                }

                foreach (var item in k.Harvesters)
                {
                    if (!item.IsValid())
                    {
                        MyDefinitionErrors.Add(Package, $"{Id} has an entry with an invalid harvester", LogSeverity.Warning);
                    }
                }


                var sourceState = MyStringHash.GetOrCompute(k.From);
                var destState   = MyStringHash.GetOrCompute(k.To);
                var data        = new Data(lootTable, destState, k.RequiresPermission, k.ActionHint ?? "Harvest",
                                           MyStringHash.GetOrCompute(k.ActionIcon ?? "Pickup_Item"));

                foreach (var item in k.Harvesters)
                {
                    if (!item.IsValid())
                    {
                        continue;
                    }

                    if (!string.IsNullOrWhiteSpace(item.Tag))
                    {
                        _lootTableByTag[new TagKey(sourceState, MyStringHash.GetOrCompute(item.Tag))] = data;
                    }
                    else
                    {
                        _lootTableByItem[new DefinitionKey(sourceState, item)] = data;
                    }
                }
            }
        }
Exemple #17
0
        protected override unsafe void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);
            MyObjectBuilder_PlanetGeneratorDefinition definition = builder as MyObjectBuilder_PlanetGeneratorDefinition;

            if ((definition.InheritFrom != null) && (definition.InheritFrom.Length > 0))
            {
                this.InheritFrom(definition.InheritFrom);
            }
            if (definition.Environment != null)
            {
                this.EnvironmentId = new MyDefinitionId?(definition.Environment.Value);
            }
            else
            {
                this.m_pgob = definition;
            }
            if (definition.PlanetMaps != null)
            {
                this.PlanetMaps = definition.PlanetMaps.Value;
            }
            if (definition.HasAtmosphere != null)
            {
                this.HasAtmosphere = definition.HasAtmosphere.Value;
            }
            if (definition.CloudLayers != null)
            {
                this.CloudLayers = definition.CloudLayers;
            }
            if (definition.SoundRules != null)
            {
                this.SoundRules = new MyPlanetEnvironmentalSoundRule[definition.SoundRules.Length];
                for (int i = 0; i < definition.SoundRules.Length; i++)
                {
                    MyPlanetEnvironmentalSoundRule rule = new MyPlanetEnvironmentalSoundRule {
                        Latitude           = definition.SoundRules[i].Latitude,
                        Height             = definition.SoundRules[i].Height,
                        SunAngleFromZenith = definition.SoundRules[i].SunAngleFromZenith,
                        EnvironmentSound   = MyStringHash.GetOrCompute(definition.SoundRules[i].EnvironmentSound)
                    };
                    rule.Latitude.ConvertToSine();
                    rule.SunAngleFromZenith.ConvertToCosine();
                    this.SoundRules[i] = rule;
                }
            }
            if (definition.MusicCategories != null)
            {
                this.MusicCategories = definition.MusicCategories;
            }
            if (definition.HillParams != null)
            {
                this.HillParams = definition.HillParams.Value;
            }
            if (definition.Atmosphere != null)
            {
                this.Atmosphere = definition.Atmosphere;
            }
            if (definition.GravityFalloffPower != null)
            {
                this.GravityFalloffPower = definition.GravityFalloffPower.Value;
            }
            if (definition.HostileAtmosphereColorShift != null)
            {
                this.HostileAtmosphereColorShift = definition.HostileAtmosphereColorShift;
            }
            if (definition.MaterialsMaxDepth != null)
            {
                this.MaterialsMaxDepth = definition.MaterialsMaxDepth.Value;
            }
            if (definition.MaterialsMinDepth != null)
            {
                this.MaterialsMinDepth = definition.MaterialsMinDepth.Value;
            }
            if ((definition.CustomMaterialTable != null) && (definition.CustomMaterialTable.Length != 0))
            {
                this.SurfaceMaterialTable = new MyPlanetMaterialDefinition[definition.CustomMaterialTable.Length];
                for (int i = 0; i < this.SurfaceMaterialTable.Length; i++)
                {
                    this.SurfaceMaterialTable[i] = definition.CustomMaterialTable[i].Clone() as MyPlanetMaterialDefinition;
                    if ((this.SurfaceMaterialTable[i].Material == null) && !this.SurfaceMaterialTable[i].HasLayers)
                    {
                        MyLog.Default.WriteLine("Custom material does not contain any material ids.");
                    }
                    else if (this.SurfaceMaterialTable[i].HasLayers)
                    {
                        float depth = this.SurfaceMaterialTable[i].Layers[0].Depth;
                        for (int j = 1; j < this.SurfaceMaterialTable[i].Layers.Length; j++)
                        {
                            float *singlePtr1 = (float *)ref this.SurfaceMaterialTable[i].Layers[j].Depth;
                            singlePtr1[0] += depth;
                            depth          = this.SurfaceMaterialTable[i].Layers[j].Depth;
                        }
                    }
                }
            }
            if ((definition.DistortionTable != null) && (definition.DistortionTable.Length != 0))
            {
                this.DistortionTable = definition.DistortionTable;
            }
            if (definition.DefaultSurfaceMaterial != null)
            {
                this.DefaultSurfaceMaterial = definition.DefaultSurfaceMaterial;
            }
            if (definition.DefaultSubSurfaceMaterial != null)
            {
                this.DefaultSubSurfaceMaterial = definition.DefaultSubSurfaceMaterial;
            }
            if (definition.SurfaceGravity != null)
            {
                this.SurfaceGravity = definition.SurfaceGravity.Value;
            }
            if (definition.AtmosphereSettings != null)
            {
                this.AtmosphereSettings = definition.AtmosphereSettings;
            }
            this.FolderName = (definition.FolderName != null) ? definition.FolderName : definition.Id.SubtypeName;
            if ((definition.ComplexMaterials != null) && (definition.ComplexMaterials.Length != 0))
            {
                this.MaterialGroups = new MyPlanetMaterialGroup[definition.ComplexMaterials.Length];
                int index = 0;
                while (index < definition.ComplexMaterials.Length)
                {
                    this.MaterialGroups[index] = definition.ComplexMaterials[index].Clone() as MyPlanetMaterialGroup;
                    MyPlanetMaterialGroup           group         = this.MaterialGroups[index];
                    MyPlanetMaterialPlacementRule[] materialRules = group.MaterialRules;
                    List <int> indices = new List <int>();
                    int        num6    = 0;
                    while (true)
                    {
                        if (num6 >= materialRules.Length)
                        {
                            if (indices.Count > 0)
                            {
                                materialRules = materialRules.RemoveIndices <MyPlanetMaterialPlacementRule>(indices);
                            }
                            group.MaterialRules = materialRules;
                            index++;
                            break;
                        }
                        if ((materialRules[num6].Material == null) && ((materialRules[num6].Layers == null) || (materialRules[num6].Layers.Length == 0)))
                        {
                            MyLog.Default.WriteLine("Material rule does not contain any material ids.");
                            indices.Add(num6);
                        }
                        else
                        {
                            if ((materialRules[num6].Layers != null) && (materialRules[num6].Layers.Length != 0))
                            {
                                float depth = materialRules[num6].Layers[0].Depth;
                                for (int i = 1; i < materialRules[num6].Layers.Length; i++)
                                {
                                    float *singlePtr2 = (float *)ref materialRules[num6].Layers[i].Depth;
                                    singlePtr2[0] += depth;
                                    depth          = materialRules[num6].Layers[i].Depth;
                                }
                            }
                            materialRules[num6].Slope.ConvertToCosine();
                            materialRules[num6].Latitude.ConvertToSine();
                            materialRules[num6].Longitude.ConvertToCosineLongitude();
                        }
                        num6++;
                    }
                }
            }
            if (definition.OreMappings != null)
            {
                this.OreMappings = definition.OreMappings;
            }
            if (definition.MaterialBlending != null)
            {
                this.MaterialBlending = definition.MaterialBlending.Value;
            }
            if (definition.SurfaceDetail != null)
            {
                this.Detail = definition.SurfaceDetail;
            }
            if (definition.AnimalSpawnInfo != null)
            {
                this.AnimalSpawnInfo = definition.AnimalSpawnInfo;
            }
            if (definition.NightAnimalSpawnInfo != null)
            {
                this.NightAnimalSpawnInfo = definition.NightAnimalSpawnInfo;
            }
            if (definition.SectorDensity != null)
            {
                this.SectorDensity = definition.SectorDensity.Value;
            }
            MyObjectBuilder_PlanetMapProvider mapProvider = definition.MapProvider;

            if (definition.MapProvider == null)
            {
                MyObjectBuilder_PlanetMapProvider        local1    = definition.MapProvider;
                MyObjectBuilder_PlanetTextureMapProvider provider1 = new MyObjectBuilder_PlanetTextureMapProvider();
                provider1.Path = this.FolderName;
                mapProvider    = provider1;
            }
            this.MapProvider          = mapProvider;
            this.MesherPostprocessing = definition.MesherPostprocessing;
            if (this.MesherPostprocessing == null)
            {
                MyLog.Default.Warning("PERFORMANCE WARNING: Postprocessing voxel triangle decimation steps not defined for " + this, Array.Empty <object>());
            }
            this.MinimumSurfaceLayerDepth = definition.MinimumSurfaceLayerDepth;
        }
Exemple #18
0
        // receiving messages
        private void LiveDebugging_ReceivedMessageHandler(MyExternalDebugStructures.CommonMsgHeader messageHeader, IntPtr messageData)
        {
            MyExternalDebugStructures.ACReloadInGameMsg msgReload;
            if (MyExternalDebugStructures.ReadMessageFromPtr(ref messageHeader, messageData, out msgReload))
            {
                try
                {
                    string acContentPath = msgReload.ACContentAddress;
                    string acAddress     = msgReload.ACAddress;
                    string acName        = msgReload.ACName;

                    MyObjectBuilder_Definitions allDefinitions; // = null;
                    // load animation controller definition from SBC file
                    if (MyObjectBuilderSerializer.DeserializeXML(acAddress, out allDefinitions) &&
                        allDefinitions.Definitions != null &&
                        allDefinitions.Definitions.Length > 0)
                    {
                        var          firstDef = allDefinitions.Definitions[0];
                        MyModContext context  = new MyModContext();
                        context.Init("AnimationControllerDefinition", acAddress, acContentPath);
                        MyAnimationControllerDefinition animationControllerDefinition = new MyAnimationControllerDefinition();
                        animationControllerDefinition.Init(firstDef, context);
                        MyStringHash animSubtypeNameHash = MyStringHash.GetOrCompute(acName);

                        // post process and update in def. manager
                        MyAnimationControllerDefinition originalAnimationControllerDefinition =
                            MyDefinitionManagerBase.Static.GetDefinition <MyAnimationControllerDefinition>(
                                animSubtypeNameHash);

                        var postprocessor = MyDefinitionManagerBase.GetPostProcessor(typeof(MyObjectBuilder_AnimationControllerDefinition));
                        if (postprocessor != null)
                        {
                            MyDefinitionPostprocessor.Bundle originalBundle = new MyDefinitionPostprocessor.Bundle
                            {
                                Context     = MyModContext.BaseGame,
                                Definitions = new Dictionary <MyStringHash, MyDefinitionBase>
                                {
                                    { animSubtypeNameHash, originalAnimationControllerDefinition }
                                },
                                Set = new MyDefinitionSet()
                            };
                            originalBundle.Set.AddDefinition(originalAnimationControllerDefinition);

                            MyDefinitionPostprocessor.Bundle overridingBundle = new MyDefinitionPostprocessor.Bundle
                            {
                                Context     = context,
                                Definitions = new Dictionary <MyStringHash, MyDefinitionBase>
                                {
                                    { animSubtypeNameHash, animationControllerDefinition }
                                },
                                Set = new MyDefinitionSet()
                            };
                            overridingBundle.Set.AddDefinition(animationControllerDefinition);

                            // postprocess -> override existing definition in memory
                            postprocessor.AfterLoaded(ref overridingBundle);
                            postprocessor.OverrideBy(ref originalBundle, ref overridingBundle);
                        }

                        // swap animation controller for each entity
                        foreach (var component in m_skinnedEntityComponents)
                        {
                            if (component != null && component.SourceId.SubtypeName == acName)
                            {
                                component.Clear();
                                component.InitFromDefinition(originalAnimationControllerDefinition, forceReloadMwm: true); // reload from original def that was modified by postprocessor
                                if (component.ReloadBonesNeeded != null)
                                {
                                    component.ReloadBonesNeeded();
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e);
                }
            }
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            var medicalRoomDefinition = BlockDefinition as MyMedicalRoomDefinition;

            MyStringHash resourceSinkGroup;

            if (medicalRoomDefinition != null)
            {
                m_idleSound       = new MySoundPair(medicalRoomDefinition.IdleSound);
                m_progressSound   = new MySoundPair(medicalRoomDefinition.ProgressSound);
                resourceSinkGroup = MyStringHash.GetOrCompute(medicalRoomDefinition.ResourceSinkGroup);
            }
            else
            {
                m_idleSound       = new MySoundPair("BlockMedical");
                m_progressSound   = new MySoundPair("BlockMedicalProgress");
                resourceSinkGroup = MyStringHash.GetOrCompute("Utility");
            }

            m_rechargeSocket = new MyRechargeSocket();

            NeedsUpdate = MyEntityUpdateEnum.EACH_10TH_FRAME | MyEntityUpdateEnum.EACH_100TH_FRAME;

            SteamUserId = (objectBuilder as MyObjectBuilder_MedicalRoom).SteamUserId;

            if (SteamUserId != 0) //backward compatibility
            {
                MyPlayer controller = Sync.Players.GetPlayerById(new MyPlayer.PlayerId(SteamUserId));
                if (controller != null)
                {
                    IDModule.Owner     = controller.Identity.IdentityId;
                    IDModule.ShareMode = MyOwnershipShareModeEnum.Faction;
                }
            }
            SteamUserId = 0;

            m_takeSpawneeOwnership = (objectBuilder as MyObjectBuilder_MedicalRoom).TakeOwnership;
            m_setFactionToSpawnee  = (objectBuilder as MyObjectBuilder_MedicalRoom).SetFaction;

            SyncObject = new SyncClass(this);

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            InitializeConveyorEndpoint();

            SinkComp = new MyResourceSinkComponent();
            SinkComp.Init(
                resourceSinkGroup,
                MyEnergyConstants.MAX_REQUIRED_POWER_MEDICAL_ROOM,
                () => (Enabled && IsFunctional) ? SinkComp.MaxRequiredInput : 0f);
            SinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;
            SinkComp.Update();
            AddDebugRenderComponent(new MyDebugRenderComponentDrawPowerReciever(SinkComp, this));

            if (this.CubeGrid.CreatePhysics)
            {
                Components.Add <MyRespawnComponent>(new MyRespawnComponent());
            }
        }
        private void Grind()
        {
            var          block  = GetTargetBlock();
            MyStringHash target = m_metal;

            if (block != null && (!(MySession.Static.IsScenario || MySession.Static.Settings.ScenarioEditMode) || block.CubeGrid.BlocksDestructionEnabled))
            {
                float hackMultiplier = 1.0f;
                if (block.FatBlock != null && Owner != null && Owner.ControllerInfo.Controller != null && Owner.ControllerInfo.Controller.Player != null)
                {
                    var relation = block.FatBlock.GetUserRelationToOwner(Owner.ControllerInfo.Controller.Player.Identity.IdentityId);
                    if (relation == VRage.Game.MyRelationsBetweenPlayerAndBlock.Enemies || relation == VRage.Game.MyRelationsBetweenPlayerAndBlock.Neutral)
                    {
                        hackMultiplier = MySession.Static.HackSpeedMultiplier;
                    }
                }

                float damage = GrinderAmount;
                MyDamageInformation damageInfo = new MyDamageInformation(false, damage * hackMultiplier, MyDamageType.Grind, EntityId);

                if (block.UseDamageSystem)
                {
                    MyDamageSystem.Static.RaiseBeforeDamageApplied(block, ref damageInfo);
                }

                block.DecreaseMountLevel(damageInfo.Amount, CharacterInventory);
                block.MoveItemsFromConstructionStockpile(CharacterInventory);

                if (block.UseDamageSystem)
                {
                    MyDamageSystem.Static.RaiseAfterDamageApplied(block, damageInfo);
                }

                if (block.IsFullyDismounted)
                {
                    if (block.UseDamageSystem)
                    {
                        MyDamageSystem.Static.RaiseDestroyed(block, damageInfo);
                    }

                    block.SpawnConstructionStockpile();
                    block.CubeGrid.RazeBlock(block.Min);
                }
                if (block.BlockDefinition.PhysicalMaterial.Id.SubtypeName.Length > 0)
                {
                    target = block.BlockDefinition.PhysicalMaterial.Id.SubtypeId;
                }
            }

            var targetDestroyable = GetTargetDestroyable();

            if (targetDestroyable != null)
            {
                //HACK to not grind yourself
                if (targetDestroyable is MyCharacter && (targetDestroyable as MyCharacter) == Owner)
                {
                    return;
                }

                //damage tracking
                if (targetDestroyable is MyCharacter && MySession.Static.ControlledEntity == this.Owner && (targetDestroyable as MyCharacter).IsDead == false)
                {
                    MySession.Static.TotalDamageDealt += 20;
                }

                targetDestroyable.DoDamage(20, MyDamageType.Grind, true, attackerId: Owner != null ? Owner.EntityId : 0);
                if (targetDestroyable is MyCharacter)
                {
                    target = MyStringHash.GetOrCompute((targetDestroyable as MyCharacter).Definition.PhysicalMaterial);
                }
            }

            if (block != null || targetDestroyable != null)
            {
                m_actualSound = MyMaterialPropertiesHelper.Static.GetCollisionCue(MyMaterialPropertiesHelper.CollisionType.Start, m_source, target);
            }
        }
Exemple #21
0
        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            m_defId = builder.GetId();
            var def = MyDefinitionManager.Static.GetCubeBlockDefinition(m_defId) as MyShipDrillDefinition;

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                def.ResourceSinkGroup,
                ComputeMaxRequiredPower(),
                ComputeRequiredPower);
            ResourceSink = sinkComp;

            m_drillBase = new MyDrillBase(this,
                                          MyDrillConstants.DRILL_SHIP_DUST_EFFECT,
                                          MyDrillConstants.DRILL_SHIP_DUST_STONES_EFFECT,
                                          MyDrillConstants.DRILL_SHIP_SPARKS_EFFECT,
                                          new MyDrillSensorSphere(def.SensorRadius, def.SensorOffset),
                                          new MyDrillCutOut(def.SensorOffset, def.SensorRadius),
                                          HEAD_SLOWDOWN_TIME_IN_SECONDS, -0.4f, 0.4f, 1
                                          );

            base.Init(builder, cubeGrid);

            m_blockLength    = def.Size.Z;
            m_cubeSideLength = MyDefinitionManager.Static.GetCubeSize(def.CubeSize);

            float   inventoryVolume = def.Size.X * def.Size.Y * def.Size.Z * m_cubeSideLength * m_cubeSideLength * m_cubeSideLength * 0.5f;
            Vector3 inventorySize   = new Vector3(def.Size.X, def.Size.Y, def.Size.Z * 0.5f);

            if (this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(inventoryVolume, inventorySize, MyInventoryFlags.CanSend);
                Components.Add <MyInventoryBase>(inventory);
            }
            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            this.GetInventory().Constraint = new MyInventoryConstraint(MySpaceTexts.ToolTipItemFilter_AnyOre)
                                             .AddObjectBuilderType(typeof(MyObjectBuilder_Ore));

            SlimBlock.UsesDeformation  = false;
            SlimBlock.DeformationRatio = def.DeformationRatio; // 3x times harder for destruction by high speed


            m_drillBase.OutputInventory = this.GetInventory();
            m_drillBase.IgnoredEntities.Add(this);
            m_drillBase.OnWorldPositionChanged(WorldMatrix);
            m_wantsToCollect = false;
            AddDebugRenderComponent(new MyDebugRenderCompomentDrawDrillBase(m_drillBase));


            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink.Update();

            AddDebugRenderComponent(new MyDebugRenderComponentDrawPowerReciever(ResourceSink, this));

            var obDrill = (MyObjectBuilder_Drill)builder;

            this.GetInventory().Init(obDrill.Inventory);

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            m_useConveyorSystem.Value = obDrill.UseConveyorSystem;

            UpdateDetailedInfo();

            m_wantsToDrill    = obDrill.Enabled;
            IsWorkingChanged += OnIsWorkingChanged;

            m_drillBase.m_drillMaterial = MyStringHash.GetOrCompute("ShipDrill");
            m_drillBase.m_idleSoundLoop = new MySoundPair("ToolShipDrillIdle");
        }
Exemple #22
0
        public void DamageProcess()
        {
            Settings.Data.LastExecCommandTime = DateTime.Now;
            LogTo("Damage wave incoming");
            ReflectRevealAll();

            List <MyCubeGrid> AllGrids = MyEntities.GetEntities().OfType <MyCubeGrid>().ToList <MyCubeGrid>();

            LogTo("All grids count:" + AllGrids.Count());

            var tblocks = new ConcurrentDictionary <Sandbox.Game.Entities.Cube.MySlimBlock, float>();

            ParallelTasks.Parallel.ForEach(AllGrids, (cubegrid) => //cycles through all entities
            {
                try
                {
                    if (cubegrid.MarkedForClose || cubegrid.Closed)
                    {
                        return;                                               //if it is not a Physics grid, or no longer exists, skip to next
                    }
                    var blocks = new HashSet <Sandbox.Game.Entities.Cube.MySlimBlock>();
                    blocks     = cubegrid.GetBlocks();

                    if (blocks.Count == 0)
                    {
                        return;
                    }
                    foreach (var rule in Settings.Data.BigRuleList)
                    {
                        // LogTo("TargetSubtypeId " + rule.TargetSubtypeId + " TargetTypeIdString " + rule.TargetTypeId.ToString());
                        if (rule.TargetTypeIdString != null && rule.TargetSubtypeId != null)
                        {
                            foreach (var blockk in blocks)
                            {
                                //LogTo("block = SubtypeId: " + blockk.BlockDefinition.Id.SubtypeId.String + " TypeId:" + blockk.BlockDefinition.Id.TypeId);
                                if ((blockk.BlockDefinition.Id.TypeId.ToString() == rule.TargetTypeId.ToString()) && (blockk.BlockDefinition.Id.SubtypeId.String == rule.TargetSubtypeId))
                                {
                                    tblocks.AddOrUpdate(blockk, rule.Damage, (k, v) => v);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex) { LogTo("ex= " + ex.ToString()); }
            }, ParallelTasks.WorkPriority.High, null, true);

            var toRemove = new HashSet <Sandbox.Game.Entities.Cube.MySlimBlock>();


            foreach (var target in tblocks)  //cycles through list of targeted blocks
            {
                LogTo("Found block for damage " + target.Key.BlockDefinition.DisplayNameText + "Integrity " + target.Key.Integrity + "/" + target.Key.MaxIntegrity + " " + target.Key.CurrentDamage + " BuildPercent: " + target.Key.BuildPercent() + "damage percent: " + target.Value);
                if (target.Key?.CubeGrid == null || target.Key.BuildPercent() <= (float)0.05 || target.Key.Closed())  //if the block doesnt exist or is below min build percentage
                {
                    // LogTo("add block for delete: " + target.Key.FatBlock.DisplayName);
                    toRemove.Add(target.Key);  //mark block for removal, skips damage step
                    continue;
                }
                target.Key.DoDamage((target.Key.MaxIntegrity / 100) * target.Value, MyStringHash.GetOrCompute("Degradation"), true, null, 0);  //applies damage
            }

            foreach (Sandbox.Game.Entities.Cube.MySlimBlock block in toRemove)  //removes blocks marked for removal
            {
                LogTo("Remove critical damaged block " + block.BlockDefinition.Id.SubtypeId.String);
                block.CubeGrid.RemoveBlock(block);
            }

            Settings.Save(Path.Combine(StoragePath, "DamageWave.cfg"));
        }
Exemple #23
0
 private MyCueId CheckDistanceSounds(MyCueId soundId)
 {
     if (soundId.IsNull == false)
     {
         if (m_lastSoundData != null && m_lastSoundData.DistantSounds != null && m_lastSoundData.DistantSounds.Count > 0)
         {
             float distanceToSoundSquered = Vector3.DistanceSquared(MySector.MainCamera.Position, this.SourcePosition);
             int   bestSoundIndex         = -1;
             m_usesDistanceSounds = true;
             m_secondaryEnabled   = false;
             float dist, crossfadeDist;
             for (int i = 0; i < m_lastSoundData.DistantSounds.Count; i++)
             {
                 dist = m_lastSoundData.DistantSounds[i].distance * m_lastSoundData.DistantSounds[i].distance;
                 if (distanceToSoundSquered > dist)
                 {
                     bestSoundIndex = i;
                 }
                 else
                 {
                     crossfadeDist = m_lastSoundData.DistantSounds[i].distanceCrossfade >= 0f ? m_lastSoundData.DistantSounds[i].distanceCrossfade * m_lastSoundData.DistantSounds[i].distanceCrossfade : float.MaxValue;
                     if (distanceToSoundSquered > crossfadeDist)
                     {
                         m_secondaryVolumeRatio = (distanceToSoundSquered - crossfadeDist) / (dist - crossfadeDist);
                         m_secondaryEnabled     = true;
                         MySoundPair secondarySoundPair = new MySoundPair(m_lastSoundData.DistantSounds[i].sound);
                         if (secondarySoundPair != MySoundPair.Empty)
                         {
                             m_secondaryCueEnum = SelectCue(secondarySoundPair);
                         }
                         else
                         {
                             m_secondaryCueEnum = new MyCueId(MyStringHash.GetOrCompute(m_lastSoundData.DistantSounds[bestSoundIndex].sound));
                         }
                     }
                     else
                     {
                         break;
                     }
                 }
             }
             if (bestSoundIndex >= 0)
             {
                 MySoundPair soundPair = new MySoundPair(m_lastSoundData.DistantSounds[bestSoundIndex].sound);
                 if (soundPair != MySoundPair.Empty)
                 {
                     m_soundPair = soundPair;
                     soundId     = SelectCue(m_soundPair);
                 }
                 else
                 {
                     soundId = new MyCueId(MyStringHash.GetOrCompute(m_lastSoundData.DistantSounds[bestSoundIndex].sound));
                 }
             }
             else
             {
                 m_soundPair = m_closeSoundSoundPair;
             }
         }
         else
         {
             m_usesDistanceSounds = false;
         }
     }
     if (m_secondaryEnabled == false)
     {
         m_secondaryCueEnum = myEmptyCueId;
     }
     return(soundId);
 }
        public void Init(long seed, string generator, double radius)
        {
            Debug.Assert(radius > 0, "The planet radius must be a strictly positive number!");

            radius = Math.Max(radius, 1.0);

            var def = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(generator));

            if (def == null)
            {
                throw new Exception(String.Format("Cannot load planet generator definition for subtype '{0}'.", generator));
            }

            Generator = def;

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

            Init();
        }
        public override void Init(MyObjectBuilder_EntityBase builder, Sandbox.Engine.Voxels.IMyStorage storage)
        {
            ProfilerShort.Begin("MyPlanet::Init()");
            if (MyFakes.ENABLE_PLANETS == false)
            {
                throw new PlanetsNotEnabledException();
            }

            ProfilerShort.Begin("MyVoxelBase Init");

            SyncFlag = true;

            base.Init(builder);

            ProfilerShort.BeginNextBlock("Load Saved Data");

            var ob = (MyObjectBuilder_Planet)builder;

            if (ob == null)
            {
                return;
            }

            MyLog.Default.WriteLine("Planet init info - MutableStorage:" + ob.MutableStorage + " StorageName:" + ob.StorageName + " storage?:" + (storage != null).ToString());

            if (ob.MutableStorage)
            {
                StorageName = ob.StorageName;
            }
            else
            {
                StorageName = string.Format("{0}", ob.StorageName);
            }

            m_planetInitValues.StorageName           = StorageName;
            m_planetInitValues.PositionMinCorner     = ob.PositionAndOrientation.Value.Position;
            m_planetInitValues.HasAtmosphere         = ob.HasAtmosphere;
            m_planetInitValues.AtmosphereRadius      = ob.AtmosphereRadius;
            m_planetInitValues.AtmosphereWavelengths = ob.AtmosphereWavelengths;
            m_planetInitValues.GravityFalloff        = ob.GravityFalloff;
            m_planetInitValues.MarkAreaEmpty         = ob.MarkAreaEmpty;
            m_planetInitValues.SurfaceGravity        = ob.SurfaceGravity;
            m_planetInitValues.AddGps = ob.ShowGPS;
            m_planetInitValues.SpherizeWithDistance = ob.SpherizeWithDistance;
            m_planetInitValues.Generator            = ob.PlanetGenerator == ""
                ? null
                : MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(
                MyStringHash.GetOrCompute(ob.PlanetGenerator));
            if (m_planetInitValues.Generator == null)
            {
                string message = string.Format("No definition found for planet generator {0}.", ob.PlanetGenerator);
                MyLog.Default.WriteLine(message);
                throw new MyIncompatibleDataException(message);
            }

            m_planetInitValues.AtmosphereSettings = m_planetInitValues.Generator.AtmosphereSettings.HasValue
                ? m_planetInitValues.Generator.AtmosphereSettings.Value
                : MyAtmosphereSettings.Defaults();
            m_planetInitValues.UserCreated = false;

            ProfilerShort.BeginNextBlock("Load Storage");
            if (storage != null)
            {
                m_planetInitValues.Storage = storage;
            }
            else
            {
                m_planetInitValues.Storage = MyStorageBase.Load(ob.StorageName);

                if (m_planetInitValues.Storage == null)
                {
                    string message = string.Format("No storage loaded for planet {0}.", ob.StorageName);
                    MyLog.Default.WriteLine(message);
                    throw new MyIncompatibleDataException(message);
                }
            }

            m_planetInitValues.InitializeComponents = false;

            ProfilerShort.BeginNextBlock("Init Internal");

            // MZ: if any crashes are related to MP planet init in the future, i added logging of MyPlanetInitArguments and other sanity checks.
            //     we are currently having crashes without this additional info and it is likely that even after my hotfixes it is going to crash again
            //     ...but we can check the logs and know the setup of the player :)
            MyLog.Default.Log(MyLogSeverity.Info, "Planet generator name: {0}", ob.PlanetGenerator ?? "<null>");

            // Initialize!
            Init(m_planetInitValues);

            ProfilerShort.End();

            ProfilerShort.End();
        }
        public void ReadFrom(ref MyOctreeStorage.ChunkHeader header, System.IO.Stream stream, ref bool isOldFormat)
        {
            m_data.Version = stream.ReadInt64();
            m_data.Seed    = stream.ReadInt64();
            m_data.Radius  = stream.ReadDouble();
            string generator = stream.ReadString();

            if (m_data.Version != STORAGE_VERSION)
            {
                isOldFormat = true;
            }

            var def = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(generator));

            if (def == null)
            {
                throw new Exception(String.Format("Cannot load planet generator definition for subtype '{0}'.", generator));
            }

            Generator = def;

            Init();
        }
Exemple #27
0
       // --------------------------------------------------------------------------------------------

        /// <summary>
        /// Reload all mwm tracks while in-game. Mwms from cache are not used.
        /// </summary>
        public void ReloadMwmTracks()
        {
            foreach (var component in m_skinnedEntityComponents)
            {
                MyAnimationControllerDefinition animationControllerDefinition =
                    MyDefinitionManagerBase.Static.GetDefinition <MyAnimationControllerDefinition>(MyStringHash.GetOrCompute(component.SourceId.SubtypeName));
                if (animationControllerDefinition != null)
                {
                    component.Clear();
                    component.InitFromDefinition(animationControllerDefinition, forceReloadMwm: true); // reload from original def that was modified by postprocessor
                    if (component.ReloadBonesNeeded != null)
                    {
                        component.ReloadBonesNeeded();
                    }
                }
            }
        }
Exemple #28
0
        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            var          doorDefinition = BlockDefinition as MyDoorDefinition;
            MyStringHash resourceSinkGroup;

            if (doorDefinition != null)
            {
                MaxOpen           = doorDefinition.MaxOpen;
                m_openSound       = new MySoundPair(doorDefinition.OpenSound);
                m_closeSound      = new MySoundPair(doorDefinition.CloseSound);
                resourceSinkGroup = MyStringHash.GetOrCompute(doorDefinition.ResourceSinkGroup);
            }
            else
            {
                MaxOpen           = 1.2f;
                m_openSound       = new MySoundPair("BlockDoorSmallOpen");
                m_closeSound      = new MySoundPair("BlockDoorSmallClose");
                resourceSinkGroup = MyStringHash.GetOrCompute("Doors");
            }

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                resourceSinkGroup,
                MyEnergyConstants.MAX_REQUIRED_POWER_DOOR,
                () => (Enabled && IsFunctional) ? sinkComp.MaxRequiredInput : 0f);
            sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;


            ResourceSink = sinkComp;

            base.Init(builder, cubeGrid);

            //m_subpartsSize = 0.5f * (0.5f * SlimBlock.CubeGrid.GridSize - 0.3f);


            var ob = (MyObjectBuilder_Door)builder;

            m_open.Value = ob.State;
            if (ob.Opening == -1)
            {
                m_currOpening = IsFunctional ? 0 : MaxOpen;
                m_open.Value  = !IsFunctional;
            }
            else
            {
                m_currOpening = ob.Opening;
            }


            if (!Enabled || !ResourceSink.IsPowered)
            {
                UpdateSlidingDoorsPosition(true);
            }

            OnStateChange();

            if (m_open)
            {
                // required when reinitializing a door after the armor beneath it is destroyed
                if (Open && (m_currOpening == MaxOpen))
                {
                    UpdateSlidingDoorsPosition(true);
                }
            }
            sinkComp.Update();
            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;
        }
Exemple #29
0
        private void InheritFrom(string generator)
        {
            MyPlanetGeneratorDefinition definition = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(generator));

            if (definition == null)
            {
                MyDefinitionManager.Static.LoadingSet.m_planetGeneratorDefinitions.TryGetValue(new MyDefinitionId(typeof(MyObjectBuilder_PlanetGeneratorDefinition), generator), out definition);
            }
            if (definition == null)
            {
                MyLog.Default.WriteLine($"Could not find planet generator definition for '{generator}'.");
            }
            else
            {
                this.PlanetMaps                  = definition.PlanetMaps;
                this.HasAtmosphere               = definition.HasAtmosphere;
                this.Atmosphere                  = definition.Atmosphere;
                this.CloudLayers                 = definition.CloudLayers;
                this.SoundRules                  = definition.SoundRules;
                this.MusicCategories             = definition.MusicCategories;
                this.HillParams                  = definition.HillParams;
                this.MaterialsMaxDepth           = definition.MaterialsMaxDepth;
                this.MaterialsMinDepth           = definition.MaterialsMinDepth;
                this.GravityFalloffPower         = definition.GravityFalloffPower;
                this.HostileAtmosphereColorShift = definition.HostileAtmosphereColorShift;
                this.SurfaceMaterialTable        = definition.SurfaceMaterialTable;
                this.DistortionTable             = definition.DistortionTable;
                this.DefaultSurfaceMaterial      = definition.DefaultSurfaceMaterial;
                this.DefaultSubSurfaceMaterial   = definition.DefaultSubSurfaceMaterial;
                this.MaterialGroups              = definition.MaterialGroups;
                this.MaterialEnvironmentMappings = definition.MaterialEnvironmentMappings;
                this.SurfaceGravity              = definition.SurfaceGravity;
                this.AtmosphereSettings          = definition.AtmosphereSettings;
                this.FolderName                  = definition.FolderName;
                this.MaterialBlending            = definition.MaterialBlending;
                this.OreMappings                 = definition.OreMappings;
                this.AnimalSpawnInfo             = definition.AnimalSpawnInfo;
                this.NightAnimalSpawnInfo        = definition.NightAnimalSpawnInfo;
                this.Detail                   = definition.Detail;
                this.SectorDensity            = definition.SectorDensity;
                this.EnvironmentSectorType    = definition.EnvironmentSectorType;
                this.MesherPostprocessing     = definition.MesherPostprocessing;
                this.MinimumSurfaceLayerDepth = definition.MinimumSurfaceLayerDepth;
            }
        }
Exemple #30
0
 public static int GetHashFromType(Type type)
 {
     return(MyStringHash.GetOrCompute(type.FullName).GetHashCode());
 }