protected virtual void Init(MyObjectBuilder_DefinitionBase builder)
        {
            this.Id = builder.Id;
            this.Public = builder.Public;
            this.Enabled = builder.Enabled;
			this.AvailableInSurvival = builder.AvailableInSurvival;
            this.Icon = builder.Icon;

            if (builder.DisplayName != null && builder.DisplayName.StartsWith("DisplayName_"))
            {
                DisplayNameEnum = MyStringId.GetOrCompute(builder.DisplayName);
            }
            else
            {
                DisplayNameString = builder.DisplayName;
            }

            if (builder.Description != null && builder.Description.StartsWith("Description_"))
            {
                DescriptionEnum = MyStringId.GetOrCompute(builder.Description);
            }
            else
            {
                DescriptionString = builder.Description;
            }

            Debug.Assert(!Context.IsBaseGame || !Public || string.IsNullOrWhiteSpace(builder.DisplayName) || (DisplayNameEnum.HasValue && builder.DisplayName.StartsWith("DisplayName_")),
                string.Format("Bad display name '{0}' on definition '{1}'. It should either be empty, or it must start with 'DisplayName_' and have corresponding text enum defined.",
                    builder.DisplayName, Id));
            Debug.Assert(!Context.IsBaseGame || !Public || string.IsNullOrWhiteSpace(builder.Description) || (DescriptionEnum.HasValue && builder.Description.StartsWith("Description_")),
                string.Format("Bad description '{0}' on definition '{1}'. It should either be empty, or it must start with 'Description_' and have corresponding text enum defined.",
                    builder.Description, Id));
        }
Esempio n. 2
0
        public bool IsAllowed(MyDefinitionId itemId)
        {
			if (!Enabled || !IsFunctional || !IsWorking || !ResourceSink.IsPowered)
                return false;

            return m_inventoryConstraint.Check(itemId);
        }
Esempio n. 3
0
 private void AddToDictionary(Dictionary<MyDefinitionId, int> dict, MyDefinitionId myDefinitionId, int amount)
 {
     int presentAmount = 0;
     dict.TryGetValue(myDefinitionId, out presentAmount);
     presentAmount += amount;
     dict[myDefinitionId] = presentAmount;
 }
Esempio n. 4
0
        public override void DoDamage(float damage, int itemInstanceId, Vector3D position, Vector3 normal, MyStringHash type)
        {
            MyEnvironmentItemData itemData = m_itemsData[itemInstanceId];
            MyDefinitionId id = new MyDefinitionId(Definition.ItemDefinitionType, itemData.SubtypeId);
            var itemDefinition = (MyTreeDefinition)MyDefinitionManager.Static.GetEnvironmentItemDefinition(id);


            int effectId;
            if (itemDefinition.CutEffect != null && MyParticlesLibrary.GetParticleEffectsID(itemDefinition.CutEffect, out effectId))
            {
                MyParticleEffect effect;
                if (MyParticlesManager.TryCreateParticleEffect(effectId, out effect))
                {
                    effect.WorldMatrix = MatrixD.CreateWorld(position, Vector3.CalculatePerpendicularVector(normal), normal);
                }
            }

            if (!Sync.IsServer)
            {
                return;
            }

            MyCutTreeInfo cutTreeInfo = default(MyCutTreeInfo);
            int index = -1;
            for (int i = 0; i < m_cutTreeInfos.Count; ++i)
            {
                cutTreeInfo = m_cutTreeInfos[i];
                if (itemInstanceId == cutTreeInfo.ItemInstanceId)
                {
                    index = i;
                    break;
                }
            }

            if (index == -1)            
            {
                cutTreeInfo = new MyCutTreeInfo();
                cutTreeInfo.ItemInstanceId = itemInstanceId;

                cutTreeInfo.MaxPoints = cutTreeInfo.HitPoints = itemDefinition.HitPoints;

                index = m_cutTreeInfos.Count;
                m_cutTreeInfos.Add(cutTreeInfo);
            }

            cutTreeInfo.LastHit = MySandboxGame.TotalGamePlayTimeInMilliseconds;
            cutTreeInfo.HitPoints -= damage;

            if (cutTreeInfo.Progress >= 1)
            {
                CutTree(itemInstanceId, position, normal, type == MyDamageType.Drill ? 1.0f : 4.0f);
                m_cutTreeInfos.RemoveAtFast(index);
            }
            else
            {
                m_cutTreeInfos[index] = cutTreeInfo;
            }

            return;
        }
        public override unsafe void ProcessItems(Dictionary<short, MyLodEnvironmentItemSet> items, List<MySurfaceParams> surfaceParamsPerLod, int[] surfaceParamLodOffsets, int changedLodMin, int changedLodMax)
        {
            m_minScannedLod = changedLodMin;

            using (var batch = new MyEnvironmentModelUpdateBatch(Sector))
                foreach (var group in items)
                {
                    MyRuntimeEnvironmentItemInfo it;
                    Sector.GetItemDefinition((ushort)group.Key, out it);
                    MyDefinitionId modelCollection = new MyDefinitionId(typeof(MyObjectBuilder_PhysicalModelCollectionDefinition), it.Subtype);

                    MyPhysicalModelCollectionDefinition modelCollectionDef = MyDefinitionManager.Static.GetDefinition<MyPhysicalModelCollectionDefinition>(modelCollection);
                    if (modelCollectionDef != null)
                    {
                        var info = group.Value;
                        int offt = info.LodOffsets[changedLodMin];

                        for (int i = offt; i < info.Items.Count; ++i)
                        {
                            var position = info.Items[i];

                            if (m_disabledItems.Contains(position) || IsObstructed(position)) continue;
                            var modelDef = modelCollectionDef.Items.Sample(MyHashRandomUtils.UniformFloatFromSeed(position));

                            batch.Add(modelDef, position);
                        }
                }
            }
        }
Esempio n. 6
0
        public override void Shoot(MyShootActionEnum action, Vector3 direction, string gunAction)
        {
            if (MySession.Static.CreativeMode)
                return;

            base.Shoot(action, direction, gunAction);

            if (action == MyShootActionEnum.PrimaryAction && !m_firstShot)
            {
                if ((MySandboxGame.TotalGamePlayTimeInMilliseconds - m_lastKeyPress) >= 500)
                {
                    //MyRenderProxy.DebugDrawText2D(new Vector2(50.0f, 50.0f), "Holding cube placer", Color.Red, 1.0f);
                    // CH:TODO: This should probably be done only locally
                    var block = GetTargetBlock();
                    if (block != null)
                    {
                        MyDefinitionId welderDefinition = new MyDefinitionId(typeof(MyObjectBuilder_Welder));
                        if (Owner.CanSwitchToWeapon(welderDefinition))
                        {
                            Owner.SetupAutoswitch(new MyDefinitionId(typeof(MyObjectBuilder_Welder)), new MyDefinitionId(typeof(MyObjectBuilder_CubePlacer)));
                        }
                    }
                }
            }
        }
        public void AddItem(MyDefinitionId groupId, int itemValue, int amount)
        {
            List<int> items = null;

            var group = MyDefinitionManager.Static.GetComponentGroup(groupId);
            if (group == null)
            {
                Debug.Assert(false, "Could not find component group definition for group " + groupId);
                return;
            }

            if (!m_groups.TryGetValue(groupId, out items))
            {
                items = m_listAllocator.Allocate();
                items.Clear();

                // We'll have the zero item allocated (for convenience), but it won't be used
                for (int i = 0; i <= group.GetComponentNumber(); ++i)
                {
                    items.Add(0);
                }
                m_groups.Add(groupId, items);
            }

            items[itemValue] += amount;
            m_totalItemCounter += amount;
        }
        public void Postprocess()
        {
            List<MySpawnGroupDefinition> spawnGroups = new List<MySpawnGroupDefinition>();
            List<float> frequencies = new List<float>();

            foreach (var spawnGroupId in m_spawnGroups)
            {
                MySpawnGroupDefinition spawnGroupDef = null;
                var defId = new MyDefinitionId(typeof(MyObjectBuilder_SpawnGroupDefinition), spawnGroupId);
                MyDefinitionManager.Static.TryGetDefinition(defId, out spawnGroupDef);

                Debug.Assert(spawnGroupDef != null, "Could not find spawn group for pirate antenna " + Name);
                if (spawnGroupDef != null)
                {
                    spawnGroups.Add(spawnGroupDef);
                    frequencies.Add(spawnGroupDef.Frequency);
                }
            }

            m_spawnGroups = null;

            if (frequencies.Count != 0)
            {
                SpawnGroupSampler = new MyDiscreteSampler<MySpawnGroupDefinition>(spawnGroups, frequencies);
            }
        }
        public static void LoadDefinition(this MyHudBlockInfo blockInfo, MyCubeBlockDefinition definition, bool merge = true)
        {
            InitBlockInfo(blockInfo, definition);

            if (definition.MultiBlock != null)
            {
                MyDefinitionId defId = new MyDefinitionId(typeof(MyObjectBuilder_MultiBlockDefinition), definition.MultiBlock);
                MyMultiBlockDefinition multiBlockDef = MyDefinitionManager.Static.GetMultiBlockDefinition(defId);
                if (multiBlockDef != null)
                {
                    foreach (var blockPart in multiBlockDef.BlockDefinitions)
                    {
                        MyCubeBlockDefinition cubeBlockDef = null;
                        MyDefinitionManager.Static.TryGetDefinition(blockPart.Id, out cubeBlockDef);
                        if (cubeBlockDef != null)
                        {
                            AddComponentsForBlock(blockInfo, cubeBlockDef);
                        }
                    }
                }
            }
            else
            {
                AddComponentsForBlock(blockInfo, definition);
            }

            if (merge) MergeSameComponents(blockInfo, definition);
        }
Esempio n. 10
0
        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            if (objectBuilder.SubtypeName != null && objectBuilder.SubtypeName.Length > 0)
                m_physicalItemId = new MyDefinitionId(typeof(MyObjectBuilder_PhysicalGunObject), objectBuilder.SubtypeName + "Item");
            PhysicalObject = (MyObjectBuilder_PhysicalGunObject)MyObjectBuilderSerializer.CreateNewObject(m_physicalItemId);
            base.Init(objectBuilder, m_physicalItemId);

            var definition = MyDefinitionManager.Static.GetPhysicalItemDefinition(m_physicalItemId);
            Init(null, definition.Model, null, null, null);
            Render.CastShadows = true;
            Render.NeedsResolveCastShadow = false;

            PhysicalObject.GunEntity = (MyObjectBuilder_EntityBase)objectBuilder.Clone();
            PhysicalObject.GunEntity.EntityId = this.EntityId;

            foreach (ToolSound toolSound in m_handItemDef.ToolSounds)
            {
                if (toolSound.type == null || toolSound.subtype == null || toolSound.sound == null)
                    continue;
                if (toolSound.type.Equals("Main"))
                {
                    if(toolSound.subtype.Equals("Idle"))
                        weldSoundIdle = new MySoundPair(toolSound.sound);
                    if (toolSound.subtype.Equals("Weld"))
                        weldSoundWeld = new MySoundPair(toolSound.sound);
                }
            }
        }
			public void Init(MyDefinitionId typeId, IMyConveyorEndpointBlock block)
			{
				FirstEndpoint = block.ConveyorEndpoint;
				ClearData();

				Add(typeId, block);
			}
        public MyInventoryConstraint Remove(MyDefinitionId id)
        {

            m_constrainedIds.Remove(id);
            UpdateIcon();
            return this;
        }
        public override bool Activate()
        {
            var character = MySession.Static.LocalCharacter;

            MyDefinitionId weaponDefinition = new MyDefinitionId(typeof(MyObjectBuilder_CubePlacer));
            if (character != null)
            {
                if (!(character.CurrentWeapon != null && character.CurrentWeapon.DefinitionId == weaponDefinition))
                {
                    character.SwitchToWeapon(weaponDefinition);
                }

                MyCubeBuilder.Static.ActivateBlockCreation(((MyCubeBlockDefinition)Definition).Id);
            }
            else
            { }

            if (MyCubeBuilder.SpectatorIsBuilding)
            {
                MyCubeBuilder.Static.ActivateBlockCreation(((MyCubeBlockDefinition)Definition).Id);
                if (!MyCubeBuilder.Static.IsActivated)
                {
                    MyCubeBuilder.Static.Activate();
                }
            }
            return true;
        }
        public MyFixedPoint GetItemAmountCombined(MyInventoryBase inventory, MyDefinitionId contentId)
        {
            int amount = 0;
            var group = MyDefinitionManager.Static.GetGroupForComponent(contentId, out amount);
            if (group == null)
            {
                //MyComponentSubstitutionDefinition substitutions;
                //if (MyDefinitionManager.Static.TryGetComponentSubstitutionDefinition(contentId, out substitutions))
                //{
                //    foreach (var providingComponent in substitutions.ProvidingComponents)
                //    {
                //        amount += (int)inventory.GetItemAmount(providingComponent.Key) / providingComponent.Value;
                //    }
                //}

                return amount + inventory.GetItemAmount(contentId, substitute: true);
            }
            else
            {
                Clear();
                inventory.CountItems(m_componentCounts);
                AddItem(group.Id, amount, int.MaxValue);
                Solve(m_componentCounts);
                return GetSolvedItemCount();
            }
        }
Esempio n. 15
0
 protected internal void RemoveItemsCombined(MyInventoryBase inventory, int itemAmount, MyDefinitionId itemDefinitionId)
 {
     m_materialListCombined.Clear();
     m_materialListCombined.AddMaterial(itemDefinitionId, itemAmount);
     m_componentCombiner.RemoveItemsCombined(inventory, m_materialListCombined.TotalMaterials);
     m_materialListCombined.Clear();
     return;
 }
        public MyDefinitionId GetBaseBlock(MyDefinitionId id)
        {
            MyDefinitionId definitionId;
            if (m_blockVariationToBaseBlock.TryGetValue(id, out definitionId))
                return definitionId;

            return id;
        }
Esempio n. 17
0
 public CubeBlockType(MyDefinitionId definitionId)
     : base(definitionId)
 {
     if (!(Definition is MyCubeBlockDefinition))
         throw new InvalidOperationException(
             "Passed type/subtype is not a CubeBlock."
         );
 }
        public MyDefinitionId GetMainElement(MyDefinitionId id)
        {
            MyDefinitionId result;
            if (m_groupMain.TryGetValue(id, out result))
                return result;

            return id;
        }
Esempio n. 19
0
 public PhysicalItemType(MyDefinitionId definitionId)
     : base(definitionId)
 {
     if (!(Definition is MyPhysicalItemDefinition))
         throw new InvalidOperationException(
             "Passed type/subtype is not a PhysicalItem."
         );
 }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);

            var spawnDef = builder as MyObjectBuilder_InventorySpawnComponent_Definition;

            ContainerDefinition = spawnDef.ContainerDefinition;
        }
		public virtual void Init(MyObjectBuilder_Character characterBuilder)
		{
			if (characterBuilder == null)
				return;

			m_inertiaDampenersNotification = new MyHudNotification();
			m_jetpackToggleNotification = new MyHudNotification();

			CurrentAutoEnableDelay = characterBuilder.AutoenableJetpackDelay;

			if (ThrustComp != null)
				Character.Components.Remove<MyJetpackThrustComponent>();

		    var thrustProperties = Character.Definition.Jetpack.ThrustProperties;

		    FuelConverterDefinition = null;;
		    FuelConverterDefinition = !MyFakes.ENABLE_HYDROGEN_FUEL ? new MyFuelConverterInfo { Efficiency = 1.0f } : Character.Definition.Jetpack.ThrustProperties.FuelConverter;

		    MyDefinitionId fuelId = new MyDefinitionId();
		    if (!FuelConverterDefinition.FuelId.IsNull())
		        fuelId = thrustProperties.FuelConverter.FuelId;

		    MyGasProperties fuelDef = null;
            if (MyFakes.ENABLE_HYDROGEN_FUEL)
                MyDefinitionManager.Static.TryGetDefinition(fuelId, out fuelDef);

            FuelDefinition = fuelDef ?? new MyGasProperties // Use electricity by default
            {
                Id = MyResourceDistributorComponent.ElectricityId,
                EnergyDensity = 1f,
            };

            ForceMagnitude = thrustProperties.ForceMagnitude;
			MinPowerConsumption = thrustProperties.MinPowerConsumption;
			MaxPowerConsumption = thrustProperties.MaxPowerConsumption;
		    MinPlanetaryInfluence = thrustProperties.MinPlanetaryInfluence;
		    MaxPlanetaryInfluence = thrustProperties.MaxPlanetaryInfluence;
		    EffectivenessAtMinInfluence = thrustProperties.EffectivenessAtMinInfluence;
		    EffectivenessAtMaxInfluence = thrustProperties.EffectivenessAtMaxInfluence;
		    NeedsAtmosphereForInfluence = thrustProperties.NeedsAtmosphereForInfluence;
		    ConsumptionFactorPerG = thrustProperties.ConsumptionFactorPerG;

			MyEntityThrustComponent thrustComp = new MyJetpackThrustComponent();
			thrustComp.Init();
			Character.Components.Add(thrustComp);


			ThrustComp.DampenersEnabled = characterBuilder.DampenersEnabled;

			foreach (Vector3I direction in Base6Directions.IntDirections)
			{
				ThrustComp.Register(Character, direction);	// Preferably there should be a jetpack entity (equipment) that could hold the thrusts instead of the character
			}
		    thrustComp.ResourceSink(Character).TemporaryConnectedEntity = Character;
            Character.SuitRechargeDistributor.AddSink(thrustComp.ResourceSink(Character));
			TurnOnJetpack(characterBuilder.JetpackEnabled, true, true, true);
		}
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);

            var ob = builder as MyObjectBuilder_WeaponBlockDefinition;

            WeaponDefinitionId = new MyDefinitionId(ob.WeaponDefinitionId.Type, ob.WeaponDefinitionId.Subtype);
            InventoryMaxVolume = ob.InventoryMaxVolume;
        }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);

            var ob = builder as MyObjectBuilder_SchematicItemDefinition;

            MyDebug.AssertDebug(ob.Research.HasValue, String.Format("No research specified for {0}", ob.Id));
            Research = ob.Research.Value;
        }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);

            var ob = builder as MyObjectBuilder_WeaponItemDefinition;
            MyDebug.AssertDebug(ob != null);

            this.WeaponDefinitionId = new MyDefinitionId(ob.WeaponDefinitionId.Type, ob.WeaponDefinitionId.Subtype);
        }
        public bool TryAdapt(MyDefinitionId itemDefinition)
        {
            m_physItem = null;
            m_blockDef = null;

            if (MyDefinitionManager.Static.TryGetPhysicalItemDefinition(itemDefinition, out m_physItem)) return true;
            if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(itemDefinition, out m_blockDef)) return true;

            return false;
        }
            public MyPhysicalDistributionGroup(MyDefinitionId typeId, MyResourceSourceComponent tempConnectedSource)
            {
                SinksByPriority = null; SourcesByPriority = null; SinkSourcePairs = null; FirstEndpoint = null;
                SinkDataByPriority = null; SourceDataByPriority = null; StockpilingStorage = null; OtherStorage = null;
                InputOutputData = new MyTuple<MySinkGroupData, MySourceGroupData>();
                MaxAvailableResources = 0f; ResourceState = MyResourceStateEnum.NoPower;
                AllocateData();

                InitFromTempConnected(typeId, tempConnectedSource);
            }
        public static void RequestChangeSlotItem(PlayerId pid, int index, MyDefinitionId defId)
        {
            var msg = new PlayerToolbarChangeSlotMsg();
            msg.ClientSteamId = pid.SteamId;
            msg.PlayerSerialId = pid.SerialId;
            msg.Index = index;
            msg.DefId = defId;

            Sync.Layer.SendMessageToServer(ref msg);
        }
        public MyEnvironmentItemDefinition GetItemDefinition(MyStringHash subtypeId)
        {
            MyEnvironmentItemDefinition retval = null;

            MyDefinitionId defId = new MyDefinitionId(m_itemDefinitionType, subtypeId);
            MyDefinitionManager.Static.TryGetDefinition(defId, out retval);
            Debug.Assert(retval != null, "Could not find environment item with definition id " + defId);

            return retval;
        }
 public void Add(MyModContext context, MyDefinitionId obj)
 {
     Debug.Assert(context != null);
     if (context == null)
     {
         MyLog.Default.WriteLine("Writing to scripted group definition without context");
         return;
     }
     m_scriptedObjects.Add(obj);
 }
			public MyPhysicalDistributionGroup(MyDefinitionId typeId, IMyConveyorEndpointBlock block)
			{
			    SinksByPriority = null; SourcesByPriority = null; SinkSourcePairs = null; FirstEndpoint = null;
				SinkDataByPriority = null; SourceDataByPriority = null; StockpilingStorage = null; OtherStorage = null;
				InputOutputData = new MyTuple<MySinkGroupData, MySourceGroupData>();
				MaxAvailableResources = 0f; ResourceState = MyResourceStateEnum.NoPower;
				AllocateData();

				Init(typeId, block);
			}
Esempio n. 31
0
        public static void ReplenishGridSystems(IMyCubeGrid cubeGrid, bool randomReplaced)
        {
            var errorLogBuilder = new StringBuilder();

            errorLogBuilder.Append("Error: Something has gone wrong with Spawner Inventory Replenishment.").AppendLine();
            errorLogBuilder.Append("Please provide this data to Mod Author of Modular Encounters Spawner.").AppendLine();
            errorLogBuilder.Append(" - Start Replenish Of Inventories").AppendLine();

            try{
                errorLogBuilder.Append(" - Get Grid Terminal System").AppendLine();
                var gts       = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(cubeGrid);
                var blockList = new List <IMyTerminalBlock>();
                gts.GetBlocksOfType <IMyTerminalBlock>(blockList);

                errorLogBuilder.Append(" - Iterate Through Blocks").AppendLine();
                foreach (var block in blockList)
                {
                    //WeaponCore Replenishing
                    if (MES_SessionCore.Instance.WeaponCoreLoaded && GridBuilderManipulation.AllWeaponCoreIDs.Contains(block.SlimBlock.BlockDefinition.Id))
                    {
                        WeaponCoreReplenishment(block);
                        continue;
                    }

                    //Weapon Replenishing
                    if ((block as IMyUserControllableGun) != null)
                    {
                        var weaponBlockDefinition = block.SlimBlock.BlockDefinition as MyWeaponBlockDefinition;

                        if (weaponBlockDefinition != null)
                        {
                            errorLogBuilder.Append("   - Identified Weapon: ").Append(weaponBlockDefinition.Id.ToString()).AppendLine();
                            var weaponDefinition = MyDefinitionManager.Static.GetWeaponDefinition(weaponBlockDefinition.WeaponDefinitionId);

                            if (weaponDefinition == null)
                            {
                                errorLogBuilder.Append("   - Weapon Has No Weapon Definition. Skip.").AppendLine();
                                continue;
                            }

                            var ammoMagazineDefinitionList = new List <MyAmmoMagazineDefinition>();

                            foreach (var ammoId in weaponDefinition.AmmoMagazinesId)
                            {
                                var tempAmmoMag = MyDefinitionManager.Static.GetAmmoMagazineDefinition(ammoId);
                                ammoMagazineDefinitionList.Add(tempAmmoMag);
                            }

                            if (ammoMagazineDefinitionList.Count == 0)
                            {
                                errorLogBuilder.Append("   - Weapon Has No Ammo Magazine Definitions. Skip.").AppendLine();
                                continue;
                            }

                            var ammo      = ammoMagazineDefinitionList[SpawnResources.rnd.Next(0, ammoMagazineDefinitionList.Count)];
                            int totalAdds = 0;

                            errorLogBuilder.Append("   - Add Ammo To Weapon.").AppendLine();
                            while (totalAdds < 100)
                            {
                                var definitionId = new MyDefinitionId(typeof(MyObjectBuilder_AmmoMagazine), ammo.Id.SubtypeId.ToString());
                                var content      = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(definitionId);
                                MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem {
                                    Amount = 1, Content = content
                                };

                                if (block.GetInventory().CanItemsBeAdded(1, definitionId) == true)
                                {
                                    errorLogBuilder.Append("   - Adding Ammo.").AppendLine();
                                    block.GetInventory().AddItems(1, inventoryItem.Content);
                                    totalAdds++;
                                }
                                else
                                {
                                    totalAdds = 101;
                                }
                            }

                            errorLogBuilder.Append("   - Ammo Adding Complete.").AppendLine();
                            errorLogBuilder.Append("   - Assign Ammo To Gun Object.").AppendLine();

                            var weaponBlock = block as IMyUserControllableGun;
                            var gunObject   = weaponBlock as IMyGunObject <Sandbox.Game.Weapons.MyDeviceBase>;

                            if (gunObject != null)
                            {
                                var switchAmmo = gunObject.GunBase.SwitchAmmoMagazineToNextAvailable();
                            }

                            errorLogBuilder.Append("   - Ammo Assign To Gun Object Complete.").AppendLine();

                            var turretBlock = block as IMyLargeTurretBase;

                            if (turretBlock != null && randomReplaced == true)
                            {
                                errorLogBuilder.Append("   - Weapon Is Randomly Added Turret. Set Targeting.").AppendLine();

                                try{
                                    //turretBlock.SetValue<bool>("TargetSmallShips", true);
                                    //turretBlock.SetValue<bool>("TargetLargeShips", true);
                                    //turretBlock.SetValue<bool>("TargetStations", true);
                                    //turretBlock.SetValue<bool>("TargetNeutrals", true);
                                    //turretBlock.SetValue<bool>("TargetCharacters", true);
                                }catch (Exception exc) {
                                    errorLogBuilder.Append("   - Something Went Wrong With Random Turret Targeting...").AppendLine();
                                }
                            }
                        }
                    }
                    if (block as IMyReactor != null)
                    {
                        errorLogBuilder.Append(" - Identified Reactor Block.").AppendLine();
                        errorLogBuilder.Append("   - Filling Reactor With Uranium.").AppendLine();

                        var powerDef     = block.SlimBlock.BlockDefinition as MyPowerProducerDefinition;
                        var totalFuelAdd = (MyFixedPoint)powerDef.MaxPowerOutput;

                        var definitionId = new MyDefinitionId(typeof(MyObjectBuilder_Ingot), "Uranium");
                        var content      = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(definitionId);
                        MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem {
                            Amount = totalFuelAdd, Content = content
                        };

                        if (block.GetInventory().CanItemsBeAdded(totalFuelAdd, definitionId) == true)
                        {
                            errorLogBuilder.Append("   - Adding Fuel.").AppendLine();
                            block.GetInventory().AddItems(totalFuelAdd, inventoryItem.Content);
                        }

                        errorLogBuilder.Append("   - Completed Reactor Filling.").AppendLine();
                    }

                    if (block as IMyParachute != null)
                    {
                        errorLogBuilder.Append(" - Identified Parachute Block.").AppendLine();
                        errorLogBuilder.Append("   - Filling Parachute With Canvas Components.").AppendLine();

                        MyFixedPoint totalAdd = 5;

                        if (cubeGrid.GridSizeEnum == MyCubeSize.Large)
                        {
                            totalAdd *= 5;
                        }

                        var definitionId = new MyDefinitionId(typeof(MyObjectBuilder_Component), "Canvas");
                        var content      = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(definitionId);
                        MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem {
                            Amount = totalAdd, Content = content
                        };

                        for (int i = 0; i < (int)totalAdd; i++)
                        {
                            if (block.GetInventory().CanItemsBeAdded(1, definitionId) == true)
                            {
                                errorLogBuilder.Append("   - Adding Canvas'.").AppendLine();
                                block.GetInventory().AddItems(1, inventoryItem.Content);
                            }
                            else
                            {
                                break;
                            }
                        }

                        errorLogBuilder.Append("   - Completed Parachute Filling.").AppendLine();
                    }

                    if (block as IMyGasGenerator != null)
                    {
                        errorLogBuilder.Append(" - Identified O2/H2 Generator Block.").AppendLine();
                        errorLogBuilder.Append("   - Filling Generator With Ice.").AppendLine();

                        var availableVolume = (block.GetInventory().MaxVolume - block.GetInventory().CurrentVolume) * 1000;
                        availableVolume -= 10;

                        var definitionId = new MyDefinitionId(typeof(MyObjectBuilder_Ore), "Ice");
                        var content      = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(definitionId);
                        MyObjectBuilder_InventoryItem inventoryItem = new MyObjectBuilder_InventoryItem {
                            Amount = 1, Content = content
                        };

                        var itemDef = MyDefinitionManager.Static.GetPhysicalItemDefinition(definitionId);

                        if (itemDef == null)
                        {
                            errorLogBuilder.Append("   - Ice Definition Not Found. Skipping.").AppendLine();
                            continue;
                        }

                        var totalAdd = (double)availableVolume / ((double)itemDef.Volume * 1000);

                        if (block.GetInventory().CanItemsBeAdded((MyFixedPoint)totalAdd, definitionId) == true)
                        {
                            errorLogBuilder.Append("   - Adding Ice.").AppendLine();
                            block.GetInventory().AddItems((MyFixedPoint)totalAdd, inventoryItem.Content);
                        }

                        errorLogBuilder.Append("   - Completed O2/H2 Generator Filling.").AppendLine();
                    }
                }
            }catch (Exception exc) {
                //Logger.AddMsg(errorLogBuilder.ToString());
            }

            //Logger.AddMsg(errorLogBuilder.ToString(), true);
        }
Esempio n. 32
0
 private double IceToGasRatio(ref MyDefinitionId gasId) =>
 ((double)(this.SourceComp.DefinedOutputByType(gasId) / this.BlockDefinition.IceConsumptionPerSecond));
Esempio n. 33
0
        internal void ReallyStupidKeenShit() //aka block group removal of individual blocks
        {
            var categories = MyDefinitionManager.Static.GetCategories();

            var removeDefs = new HashSet <MyDefinitionId>(MyDefinitionId.Comparer);
            var keepDefs   = new HashSet <string>();

            foreach (var weaponDef in WeaponDefinitions)
            {
                foreach (var mount in weaponDef.Assignments.MountPoints)
                {
                    var subTypeId = mount.SubtypeId;

                    MyDefinitionId defId = new MyDefinitionId();

                    if ((ReplaceVanilla && VanillaCoreIds.TryGetValue(MyStringHash.GetOrCompute(subTypeId), out defId)))
                    {
                        removeDefs.Add(defId);
                    }
                    else
                    {
                        foreach (var def in AllDefinitions)
                        {
                            if (def.Id.SubtypeName == subTypeId)
                            {
                                removeDefs.Add(def.Id);
                                break;
                            }
                        }
                    }
                }
            }

            foreach (var def in AllDefinitions)
            {
                if (!removeDefs.Contains(def.Id))
                {
                    keepDefs.Add(def.Id.SubtypeName);
                }
            }

            foreach (var category in categories)
            {
                if (category.Value.IsShipCategory)
                {
                    var removeList = new List <string>();
                    foreach (var item in category.Value.ItemIds)
                    {
                        foreach (var def in removeDefs)
                        {
                            var type    = def.TypeId.ToString().Replace("MyObjectBuilder_", "");
                            var subType = string.IsNullOrEmpty(def.SubtypeName) ? "(null)" : def.SubtypeName;

                            if ((item.Contains(type) || item.Contains(subType)))
                            {
                                removeList.Add(item);
                            }
                        }
                    }

                    foreach (var keep in keepDefs)
                    {
                        for (int i = 0; i < removeList.Count; i++)
                        {
                            var toRemove = removeList[i];
                            if (!string.IsNullOrEmpty(keep) && toRemove.EndsWith(keep))
                            {
                                removeList.RemoveAtFast(i);
                            }
                        }
                    }

                    for (int i = 0; i < removeList.Count; i++)
                    {
                        category.Value.ItemIds.Remove(removeList[i]);
                    }
                }
            }
            CounterKeenLogMessage(false);
        }
Esempio n. 34
0
        public override void Update()
        {
            try
            {
                //slow this shit down so it doesnt lag out console, 32 is fine but i dont think it needs to check that often
                ++this.tick;


                if (this.tick % 128 == 0)
                {
                    if (DateTime.Now >= nextUpdate && config.UsingWhitelist)
                    {
                        nextUpdate = DateTime.Now.AddMinutes(5);
                        Whitelist.Clear();
                        Database.LoadWhitelist();
                    }
                    foreach (MyPlayer onlinePlayer in MySession.Static.Players.GetOnlinePlayers())
                    {
                        MyPlayer playerOnline = onlinePlayer;
                        if (onlinePlayer.Character != null && onlinePlayer?.Controller.ControlledEntity is MyCockpit controller)
                        {
                            MyCubeGrid grid = controller.CubeGrid;
                            if (TruckingPlugin.getActiveContract(onlinePlayer.Id.SteamId) != null)
                            {
                                Contract contract = TruckingPlugin.getActiveContract(onlinePlayer.Id.SteamId);
                                Vector3D coords   = contract.GetDeliveryLocation().Coords;
                                float    distance = Vector3.Distance(coords, onlinePlayer.Character.PositionComp.GetPosition());
                                if (distance <= 300)
                                {
                                    List <VRage.ModAPI.IMyEntity> l = new List <VRage.ModAPI.IMyEntity>();

                                    BoundingSphereD sphere = new BoundingSphereD(onlinePlayer.Character.PositionComp.GetPosition(), 1000);
                                    l = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere);

                                    Dictionary <MyDefinitionId, int> itemsToRemove = new Dictionary <MyDefinitionId, int>();
                                    int pay = 0;
                                    //calculate the pay since we only show the player the minimum they can get, this could be removed if the pay is made part of the contract
                                    //when its generated and stored in the db, reputation when completed could give a bonus percent
                                    foreach (ContractItems item in contract.getItemsInContract())
                                    {
                                        if (MyDefinitionId.TryParse("MyObjectBuilder_" + item.ItemType, item.SubType, out MyDefinitionId id))
                                        {
                                            itemsToRemove.Add(id, item.AmountToDeliver);
                                            pay += item.AmountToDeliver * item.GetPrice();
                                        }
                                    }


                                    List <VRage.Game.ModAPI.IMyInventory> inventories = TakeTheItems.GetInventories(grid);

                                    if (FacUtils.IsOwnerOrFactionOwned(grid, onlinePlayer.Identity.IdentityId, true) && Vector3.Distance(coords, grid.PositionComp.GetPosition()) <= 300)
                                    {
                                        if (TakeTheItems.ConsumeComponents(inventories, itemsToRemove, onlinePlayer.Id.SteamId))
                                        {
                                            MyBankingSystem.ChangeBalance(onlinePlayer.Identity.IdentityId, pay);
                                            Database.RemoveContract(onlinePlayer.Id.SteamId, true, contract, onlinePlayer.Identity.IdentityId);
                                            TruckingPlugin.SendMessage("The Boss", "Contract Complete, Payment delivered to bank account.", Color.Purple, onlinePlayer.Id.SteamId);
                                            //if (TruckingPlugin.config.DoBonusRewards)
                                            //{
                                            //    List<ContractItems> SortedList = bonusRewards.OrderByDescending(o => o.chance).ToList();
                                            //    Random random = new Random();
                                            //    foreach (ContractItems item in SortedList)
                                            //    {

                                            //        int chance = random.Next(101);
                                            //        if (chance <= item.chance)
                                            //        {

                                            //        }
                                            //    }
                                            //}
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TruckingPlugin.Log.Info("Space trucking error " + ex.ToString());
            }
        }
Esempio n. 35
0
        public void DoSort()
        {
            // Echo("dbg: DoSort()");
            neededItemCounts.Clear();

            // pull into each container
            foreach (var dest in sortedContainers)
            {
                //Echo($"dbg: sorting {dest.CustomName}");
                var inv = dest.GetInventory();
                if (inv == null)
                {
                    Echo($"Warning: Destination '{dest.CustomName}' doesn't have an inventory.");
                    continue;
                }

                // figure out what items we should be storing (by parsing the name)
                var nameWords = dest.CustomName.Split().Skip(1 /*"store"*/);
                //Echo($"dbg: nameWords: {String.Join(" ", nameWords)}");
                itemNames.Clear();
                itemDesiredCount.Clear();
                foreach (var word in nameWords)
                {
                    if (word.Length == 0)
                    {
                        continue;
                    }
                    var parts = word.Split('-');
                    var name  = parts[0];
                    var count = 0;
                    if (parts.Length == 2)
                    {
                        int.TryParse(parts[1], out count);
                    }
                    //Echo($"dbg: item name {name}-{count}");
                    itemNames.Add(name);
                    itemDesiredCount.Add(count);
                }
                if (itemNames.Count() == 0)
                {
                    continue;
                }

                // for each item...
                for (var i = 0; i < itemNames.Count(); i++)
                {
                    var name                  = itemNames[i];
                    var desiredCount          = itemDesiredCount[i];
                    var specifiesDesiredCount = desiredCount > 0;
                    // Echo($"dbg: we want {name}-{desiredCount}");

                    // figure out how many we already have
                    var iType = LookupItemType(name);
                    if (!iType.HasValue)
                    {
                        Echo($"Warning: '{dest.CustomName}' wants invalid item '{name}'. All known names: {String.Join(",", namesToKnownItems.Keys)}");
                        continue;
                    }
                    var currentCount = inv.GetItemAmount(iType.Value);
                    // Echo($"dbg: we have {currentCount}");
                    int currentGlobalCount = 0;
                    allItemCounts.TryGetValue(iType.Value, out currentGlobalCount);
                    var producingCount = 0;
                    allAssemblerWork.TryGetValue(iType.Value, out producingCount);
                    var neededCount = desiredCount - currentCount;
                    // TODO: Actually, take all we can get always
                    // if (neededCount <= 0)
                    //    continue;

                    if (neededCount > 0)
                    {
                        Echo($"We want {desiredCount} {name} and we have {currentCount} locally and {currentGlobalCount - currentCount} more globally and we are making {producingCount}.");
                        // Echo($"'{dest.CustomName}' wants {(specifiesDesiredCount ? neededCount.ToString() : "inf.")} more {iType.Value.SubtypeId}");
                    }
                    else /* taking all anyway */ } {
                    // search the grid
                    foreach (var src in sourceContainers)
                    {
                        // for each inventory
                        for (var invIdx = 0; invIdx < src.InventoryCount; invIdx++)
                        {
                            var srcInv = src.GetInventory(invIdx);
                            if (srcInv == null)
                            {
                                continue;
                            }

                            // see how many we have
                            var srcCount = srcInv.GetItemAmount(iType.Value);
                            if (srcCount <= 0)
                            {
                                continue;
                            }

                            // Echo($"dbg: {src.CustomName} has {srcCount}");

                            // transfer each occurrance
                            tempItems.Clear();
                            srcInv.GetItems(tempItems, item => item.Type.SubtypeId == iType.Value.SubtypeId);
                            foreach (var invI in tempItems)
                            {
                                var trasnferSuccess = srcInv.TransferItemTo(inv, invI, invI.Amount);
                                if (trasnferSuccess)
                                {
                                    Echo($"Transferred {invI.Amount} {name} from '{src.CustomName}'");
                                    neededCount -= invI.Amount;
                                }
                                else
                                {
                                    Echo($"dbg: Transferring {invI.Amount} {name} from '{src.CustomName}' to '{dest.CustomName} failed.");
                                    break;
                                    // TODO: log transfer success / fail ? Probably too noisy.
                                }
                            }
                        }
                    }

                    // update the counts of what we need
                    if (neededCount > 0)
                    {
                        //Echo($"dbg: we didn't get enough {name}; we need {neededCount} more");
                        int prevNeededCount;
                        if (neededItemCounts.TryGetValue(iType.Value, out prevNeededCount))
                        {
                            neededItemCounts[iType.Value] += (int)neededCount;
                        }
                        else
                        {
                            neededItemCounts[iType.Value] = (int)neededCount;
                        }
                    }
            }
        }

        // put items we still need into production
        // UpdateAllAssemblerWork(); // see how many we are already producing
        if (leadAssembler != null)
        {
            foreach (var typeAndCount in neededItemCounts)
            {
                var iType       = typeAndCount.Key;
                var wantedCount = typeAndCount.Value;
                if (wantedCount <= 0)
                {
                    continue;
                }
                // Echo($"dbg: We want {wantedCount} more {iType.SubtypeId}");

                // compare to what we are producing currently
                var producingCount = 0;
                allAssemblerWork.TryGetValue(iType, out producingCount);
                var neededCount = wantedCount - producingCount;
                // Echo($"dbg: We need {neededCount} more {iType.SubtypeId}");
                if (neededCount <= 0)
                {
                    // Echo($"We are already trying to produce {producingCount}.");
                    continue;
                }
                else
                {
                    // Echo($"dbg: We are producing any.");
                }

                // enqueue
                MyDefinitionId?blueprintOpt = FindBlueprint(iType);
                if (!blueprintOpt.HasValue)
                {
                    Echo($"Warning: Failed to find definition for {iType.SubtypeId}");
                    continue;
                }
                MyDefinitionId blueprint = blueprintOpt.Value;

                try
                {
                    leadAssembler.AddQueueItem(blueprint, (MyFixedPoint)neededCount);
                    if (allAssemblerWork.ContainsKey(iType))
                    {
                        allAssemblerWork[iType] += neededCount;
                    }
                    else
                    {
                        allAssemblerWork[iType] = neededCount;
                    }
                    Echo($"Enqueued {wantedCount} more {blueprint.SubtypeName}");
                } catch (Exception e)
                {
                    Echo($"Warning: Lead assembler failed to produce {blueprint.TypeId}/{blueprint.SubtypeName}");
                }
            }
        }
    }
Esempio n. 36
0
 private double GasOutputPerUpdate(ref MyDefinitionId gasId) =>
 (this.GasOutputPerSecond(ref gasId) * 0.01666666753590107);
Esempio n. 37
0
 private double GasToIce(ref MyDefinitionId gasId, double gasAmount) =>
 (gasAmount / this.IceToGasRatio(ref gasId));
Esempio n. 38
0
 private void PowerReceiver_RequiredInputChanged(MyDefinitionId resourceTypeId, MyResourceSinkComponent receiver, float oldRequirement, float newRequirement)
 {
     this.UpdateDetailedInfo();
 }
Esempio n. 39
0
 public abstract void RaiseItemEvent <T>(int logicalItem, ref MyDefinitionId modDef, T eventData, bool fromClient);
        public MyGlobalEventHandler(Type objectBuilderType, string subtypeName)
        {
            MyObjectBuilderType type = objectBuilderType;

            EventDefinitionId = new MyDefinitionId(type, subtypeName);
        }
Esempio n. 41
0
        private void RebuildQueue()
        {
            this.m_queueNeedsRebuild = false;
            base.ClearQueue(false);
            this.m_tmpSortedBlueprints.Clear();
            MyPhysicalInventoryItem[] itemArray = base.InputInventory.GetItems().ToArray();
            int index = 0;

            while (true)
            {
                int num2;
                while (true)
                {
                    if (index < itemArray.Length)
                    {
                        num2 = 0;
                        break;
                    }
                    int num4 = 0;
                    while (num4 < this.m_tmpSortedBlueprints.Count)
                    {
                        KeyValuePair <int, MyBlueprintDefinitionBase> pair = this.m_tmpSortedBlueprints[num4];
                        MyBlueprintDefinitionBase blueprint = pair.Value;
                        MyFixedPoint maxValue = MyFixedPoint.MaxValue;
                        MyBlueprintDefinitionBase.Item[] prerequisites = blueprint.Prerequisites;
                        int num5 = 0;
                        while (true)
                        {
                            if (num5 < prerequisites.Length)
                            {
                                MyBlueprintDefinitionBase.Item item = prerequisites[num5];
                                MyFixedPoint amount = itemArray[num4].Amount;
                                if (amount != 0)
                                {
                                    maxValue = MyFixedPoint.Min(amount * (1f / ((float)item.Amount)), maxValue);
                                    num5++;
                                    continue;
                                }
                                maxValue = 0;
                            }
                            if (blueprint.Atomic)
                            {
                                maxValue = MyFixedPoint.Floor(maxValue);
                            }
                            if ((maxValue > 0) && (maxValue != MyFixedPoint.MaxValue))
                            {
                                base.InsertQueueItemRequest(-1, blueprint, maxValue);
                            }
                            num4++;
                            break;
                        }
                    }
                    this.m_tmpSortedBlueprints.Clear();
                    return;
                }
                while (true)
                {
                    if (num2 >= this.m_refineryDef.BlueprintClasses.Count)
                    {
                        index++;
                        break;
                    }
                    using (IEnumerator <MyBlueprintDefinitionBase> enumerator = this.m_refineryDef.BlueprintClasses[num2].GetEnumerator())
                    {
                        while (true)
                        {
                            if (enumerator.MoveNext())
                            {
                                MyBlueprintDefinitionBase current = enumerator.Current;
                                bool           flag  = false;
                                MyDefinitionId other = new MyDefinitionId(itemArray[index].Content.TypeId, itemArray[index].Content.SubtypeId);
                                int            num3  = 0;
                                while (true)
                                {
                                    if (num3 < current.Prerequisites.Length)
                                    {
                                        if (!current.Prerequisites[num3].Id.Equals(other))
                                        {
                                            num3++;
                                            continue;
                                        }
                                        flag = true;
                                    }
                                    if (!flag)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        this.m_tmpSortedBlueprints.Add(new KeyValuePair <int, MyBlueprintDefinitionBase>(index, current));
                                    }
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    num2++;
                }
            }
        }
        private static void RegisterHandler(MyDefinitionId eventDefinitionId, GlobalEventHandler handler)
        {
            Debug.Assert(!m_typesToHandlers.ContainsKey(eventDefinitionId), "One event definition id can only have one event handler!");

            m_typesToHandlers[eventDefinitionId] = handler;
        }
Esempio n. 43
0
        public virtual void Init(MyObjectBuilder_Character characterBuilder)
        {
            if (characterBuilder == null)
            {
                return;
            }

            m_inertiaDampenersNotification = new MyHudNotification();
            m_jetpackToggleNotification    = new MyHudNotification();

            CurrentAutoEnableDelay = characterBuilder.AutoenableJetpackDelay;

            if (ThrustComp != null)
            {
                Character.Components.Remove <MyJetpackThrustComponent>();
            }

            var thrustProperties = Character.Definition.Jetpack.ThrustProperties;

            FuelConverterDefinition = null;;
            FuelConverterDefinition = !MyFakes.ENABLE_HYDROGEN_FUEL ? new MyFuelConverterInfo {
                Efficiency = 1.0f
            } : Character.Definition.Jetpack.ThrustProperties.FuelConverter;

            MyDefinitionId fuelId = new MyDefinitionId();

            if (!FuelConverterDefinition.FuelId.IsNull())
            {
                fuelId = thrustProperties.FuelConverter.FuelId;
            }

            MyGasProperties fuelDef = null;

            if (MyFakes.ENABLE_HYDROGEN_FUEL)
            {
                MyDefinitionManager.Static.TryGetDefinition(fuelId, out fuelDef);
            }

            FuelDefinition = fuelDef ?? new MyGasProperties // Use electricity by default
            {
                Id            = MyResourceDistributorComponent.ElectricityId,
                EnergyDensity = 1f,
            };

            ForceMagnitude              = thrustProperties.ForceMagnitude;
            MinPowerConsumption         = thrustProperties.MinPowerConsumption;
            MaxPowerConsumption         = thrustProperties.MaxPowerConsumption;
            MinPlanetaryInfluence       = thrustProperties.MinPlanetaryInfluence;
            MaxPlanetaryInfluence       = thrustProperties.MaxPlanetaryInfluence;
            EffectivenessAtMinInfluence = thrustProperties.EffectivenessAtMinInfluence;
            EffectivenessAtMaxInfluence = thrustProperties.EffectivenessAtMaxInfluence;
            NeedsAtmosphereForInfluence = thrustProperties.NeedsAtmosphereForInfluence;
            ConsumptionFactorPerG       = thrustProperties.ConsumptionFactorPerG;

            MyEntityThrustComponent thrustComp = new MyJetpackThrustComponent();

            thrustComp.Init();
            Character.Components.Add(thrustComp);

            ThrustComp.DampenersEnabled = characterBuilder.DampenersEnabled;

            foreach (Vector3I direction in Base6Directions.IntDirections)
            {
                ThrustComp.Register(Character, direction);  // Preferably there should be a jetpack entity (equipment) that could hold the thrusts instead of the character
            }
            thrustComp.ResourceSink(Character).TemporaryConnectedEntity = Character;
            Character.SuitRechargeDistributor.AddSink(thrustComp.ResourceSink(Character));
            TurnOnJetpack(characterBuilder.JetpackEnabled, true, true);
        }
Esempio n. 44
0
 int IMySlimBlock.GetConstructionStockpileItemAmount(MyDefinitionId id)
 {
     return(GetConstructionStockpileItemAmount(id));
 }
Esempio n. 45
0
 private double IceToGas(ref MyDefinitionId gasId, double iceAmount) =>
 (iceAmount * this.IceToGasRatio(ref gasId));
Esempio n. 46
0
 public void Init(MyObjectBuilder_EntityBase builder, MyDefinitionId id)
 {
     Init(builder, MyDefinitionManager.Static.TryGetHandItemForPhysicalItem(id));
 }
Esempio n. 47
0
        public void RefillBottles()
        {
            List <MyPhysicalInventoryItem> items = this.GetInventory(0).GetItems();

            using (List <MyDefinitionId> .Enumerator enumerator = this.SourceComp.ResourceTypes.GetEnumerator())
            {
                MyDefinitionId id2;
                double         num2;
                goto TR_001D;
TR_0003:
                if (num2 > 0.0)
                {
                    this.ProduceGas(ref id2, num2);
                    this.GetInventory(0).UpdateGasAmount();
                }
TR_001D:
                while (true)
                {
                    if (!enumerator.MoveNext())
                    {
                        break;
                    }
                    MyDefinitionId current = enumerator.Current;
                    id2 = current;
                    double num = 0.0;
                    if (MySession.Static.CreativeMode)
                    {
                        num = 3.4028234663852886E+38;
                    }
                    else
                    {
                        foreach (MyPhysicalInventoryItem item in items)
                        {
                            if (!(item.Content is MyObjectBuilder_GasContainerObject))
                            {
                                num += this.IceToGas(ref id2, (double)((float)item.Amount)) * ((Sandbox.ModAPI.IMyGasGenerator) this).ProductionCapacityMultiplier;
                            }
                        }
                    }
                    num2 = 0.0;
                    using (List <MyPhysicalInventoryItem> .Enumerator enumerator2 = items.GetEnumerator())
                    {
                        while (true)
                        {
                            if (enumerator2.MoveNext())
                            {
                                MyPhysicalInventoryItem item2 = enumerator2.Current;
                                if (num > 0.0)
                                {
                                    MyObjectBuilder_GasContainerObject content = item2.Content as MyObjectBuilder_GasContainerObject;
                                    if (content == null)
                                    {
                                        continue;
                                    }
                                    if (content.GasLevel >= 1f)
                                    {
                                        continue;
                                    }
                                    MyOxygenContainerDefinition physicalItemDefinition = MyDefinitionManager.Static.GetPhysicalItemDefinition(content) as MyOxygenContainerDefinition;
                                    if (physicalItemDefinition.StoredGasId != current)
                                    {
                                        continue;
                                    }
                                    float  num3 = content.GasLevel * physicalItemDefinition.Capacity;
                                    double num4 = Math.Min((double)(physicalItemDefinition.Capacity - num3), num);
                                    content.GasLevel = (float)Math.Min((double)((num3 + num4) / ((double)physicalItemDefinition.Capacity)), (double)1.0);
                                    num2            += num4;
                                    num -= num4;
                                    continue;
                                }
                            }
                            else
                            {
                                goto TR_0003;
                            }
                            break;
                        }
                        break;
                    }
                    goto TR_0003;
                }
            }
        }
Esempio n. 48
0
        private int TryCreatingItemsByMerge(MyComponentGroupDefinition group, int itemValue, int itemCount)
        {
            // Removal buffer is here so that the method does not do anything until it's clear that the operation can be successful
            List <int> removalBuffer = m_listAllocator.Allocate();

            removalBuffer.Clear();
            for (int i = 0; i <= group.GetComponentNumber(); ++i)
            {
                removalBuffer.Add(0);
            }

            int createdCount = 0;

            // Create the items one-by-one
            for (int i = 0; i < itemCount; ++i)
            {
                // What remains to be found to create this item
                int remainder = itemValue;

                // Fill this item with smaller items as long as possible
                for (int k = itemValue - 1; k >= 1; k--)
                {
                    int amount = 0;
                    if (m_presentItems.TryGetValue(k, out amount))
                    {
                        int removeCount = Math.Min(remainder / k, amount);
                        if (removeCount > 0)
                        {
                            remainder         = remainder - k * removeCount;
                            amount           -= removeCount;
                            removalBuffer[k] += removeCount;
                        }
                    }
                }

                // The remainder was not reduced by the remaining items, which means that we don't have any items left
                if (remainder == itemValue)
                {
                    Debug.Assert(m_presentItems.Count == 0 || itemValue == 1, "There are still items present in the cutting solver, but they were not used in the solution!");
                    break;
                }

                // There are no more smaller items to fill the remainder. Try to split one of the larger ones
                if (remainder != 0)
                {
                    for (int j = remainder + 1; j <= group.GetComponentNumber(); ++j)
                    {
                        int present = 0;
                        m_presentItems.TryGetValue(j, out present);
                        // If there is some present item that is not planned to be removed, use it
                        if (present > removalBuffer[j])
                        {
                            MyDefinitionId removedComponentId = group.GetComponentDefinition(j).Id;
                            MyDefinitionId addedComponentId   = group.GetComponentDefinition(j - remainder).Id;
                            AddChangeToSolution(removedComponentId, addedComponentId, 1);
                            int removed = TryRemovePresentItems(j, 1);
                            AddPresentItems(j - remainder, 1);
                            Debug.Assert(removed == 1);
                            remainder = 0;
                            break;
                        }
                    }
                }

                if (remainder == 0)
                {
                    createdCount++;
                    // Add the buffered removals of the smaller items here
                    for (int k = 1; k <= group.GetComponentNumber(); ++k)
                    {
                        if (removalBuffer[k] > 0)
                        {
                            MyDefinitionId removedComponentId = group.GetComponentDefinition(k).Id;
                            int            removed            = TryRemovePresentItems(k, removalBuffer[k]);
                            Debug.Assert(removed == removalBuffer[k]);
                            AddRemovalToSolution(removedComponentId, removalBuffer[k]);
                            removalBuffer[k] = 0; // We need to clear the buffer for the next item
                        }
                    }
                } // The item could not be created and neither would be the others
                else if (remainder > 0)
                {
                    break;
                }
            }

            m_listAllocator.Deallocate(removalBuffer);

            return(createdCount);
        }
Esempio n. 49
0
        protected override bool Activate(HashSet <MySlimBlock> targets)
        {
            bool welding = false;
            bool unweldedBlocksDetected = false;
            int  targetCount            = targets.Count;

            m_missingComponents.Clear();

            foreach (var block in targets)
            {
                if (block.BuildLevelRatio == 1.0f)
                {
                    targetCount--;
                    continue;
                }

                block.GetMissingComponents(m_missingComponents);
            }

            foreach (var component in m_missingComponents)
            {
                var componentId = new MyDefinitionId(typeof(MyObjectBuilder_Component), component.Key);
                int amount      = Math.Max(component.Value - (int)this.GetInventory().GetItemAmount(componentId), 0);
                if (amount == 0)
                {
                    continue;
                }

                if (Sync.IsServer && UseConveyorSystem)
                {
                    var group = MyDefinitionManager.Static.GetGroupForComponent(componentId, out amount);
                    if (group == null)
                    {
                        MyComponentSubstitutionDefinition substitutions;
                        if (MyDefinitionManager.Static.TryGetComponentSubstitutionDefinition(componentId, out substitutions))
                        {
                            foreach (var providingComponent in substitutions.ProvidingComponents)
                            {
                                MyFixedPoint substituionAmount = (int)component.Value / providingComponent.Value;
                                MyGridConveyorSystem.ItemPullRequest(this, this.GetInventory(), OwnerId, providingComponent.Key, substituionAmount);
                            }
                        }
                        else
                        {
                            MyGridConveyorSystem.ItemPullRequest(this, this.GetInventory(), OwnerId, componentId, component.Value);
                        }
                    }
                    else
                    {
                        MyGridConveyorSystem.ItemPullRequest(this, this.GetInventory(), OwnerId, componentId, component.Value);
                    }
                }
            }

            if (Sync.IsServer)
            {
                float coefficient = (MyShipGrinderConstants.GRINDER_COOLDOWN_IN_MILISECONDS * 0.001f) / (targetCount > 0?targetCount:1);
                foreach (var block in targets)
                {
                    if (!block.IsFullIntegrity)
                    {
                        unweldedBlocksDetected = true;
                    }

                    if (block.CanContinueBuild(this.GetInventory()))
                    {
                        welding = true;
                    }

                    block.MoveItemsToConstructionStockpile(this.GetInventory());

                    // Allow welding only for blocks with deformations or unfinished/damaged blocks
                    if ((block.HasDeformation || block.MaxDeformation > 0.0001f) || !block.IsFullIntegrity)
                    {
                        float maxAllowedBoneMovement = WELDER_MAX_REPAIR_BONE_MOVEMENT_SPEED * MyShipGrinderConstants.GRINDER_COOLDOWN_IN_MILISECONDS * 0.001f;
                        block.IncreaseMountLevel(MySession.Static.WelderSpeedMultiplier * WELDER_AMOUNT_PER_SECOND * coefficient, OwnerId, this.GetInventory(), maxAllowedBoneMovement, m_helpOthers, IDModule.ShareMode);
                    }
                }
            }
            else
            {
                foreach (var block in targets)
                {
                    if (block.CanContinueBuild(this.GetInventory()))
                    {
                        welding = true;
                    }
                }
            }

            m_missingComponents.Clear();

            if (!unweldedBlocksDetected && Sync.IsServer)
            {
                //Try to build blocks for projections
                var blocks = FindProjectedBlocks();

                //Try to acquire materials first, but only if it uses the conveyor system
                if (UseConveyorSystem)
                {
                    foreach (var info in blocks)
                    {
                        var components = info.hitCube.BlockDefinition.Components;
                        if (components == null || components.Length == 0)
                        {
                            continue;
                        }
                        var componentId = components[0].Definition.Id;
                        MyGridConveyorSystem.ItemPullRequest(this, this.GetInventory(), OwnerId, componentId, 1);
                    }
                }

                var locations = new HashSet <MyCubeGrid.MyBlockLocation>();

                foreach (var info in blocks)
                {
                    if (MySession.Static.CreativeMode || this.GetInventory().ContainItems(1, info.hitCube.BlockDefinition.Components[0].Definition.Id))
                    {
                        info.cubeProjector.Build(info.hitCube, OwnerId, EntityId);
                        welding = true;
                    }
                }
            }

            if (welding)
            {
                SetBuildingMusic(150);
            }

            return(welding);
        }
Esempio n. 50
0
 protected void Receiver_RequiredInputChanged(MyDefinitionId resourceTypeId, MyResourceSinkComponent receiver, float oldRequirement, float newRequirement)
 {
     UpdateText();
 }
Esempio n. 51
0
 public static string GetCompsString(int neededCount, MyDefinitionId compId)
 {
     return(neededCount + " " + IPSession.Instance.GetComponentName(compId) + Constants.msgMissingComp);
 }
Esempio n. 52
0
        private void AddSupportedGun(IMyEntity ent, MyDefinitionId physItemId)
        {
            DrawSettings settings;

            if (!drawSettings.TryGetValue(physItemId, out settings))
            {
                return;
            }

            for (int i = 0; i < drawInfo.Count; ++i)
            {
                if (drawInfo[i].Entity == ent)
                {
                    return;
                }
            }

            if (!settings.Processed) // parse dummies only once per gun subtype
            {
                settings.Processed = true;
                settings.Material  = MyStringId.GetOrCompute(settings.ReticleMaterial);

                dummies.Clear();
                ent.Model.GetDummies(dummies);

                foreach (var dummy in dummies.Values)
                {
                    if (dummy.Name.StartsWith(DUMMY_PREFIX))
                    {
                        var dummyMatrix = dummy.Matrix;
                        var gunMatrix   = ent.WorldMatrix;

                        var reticleProjectedPosition = Vector3D.Transform(dummyMatrix.Translation, gunMatrix) + gunMatrix.Forward * PROJECTED_DISTANCE;
                        var sightPositionLocal       = dummyMatrix.Translation;

                        if (dummy.Name.EndsWith(DUMMY_RECTANGLE_SUFFIX))
                        {
                            settings.Type = SightType.Rectangle;

                            var edgePosH          = Vector3D.Transform(sightPositionLocal + dummyMatrix.Left * 0.5f, gunMatrix);
                            var reticleToEdgePosH = Vector3D.Normalize(reticleProjectedPosition - edgePosH);
                            settings.MaxAngleH = Math.Acos(Vector3D.Dot(gunMatrix.Forward, reticleToEdgePosH));

                            var edgePosV          = Vector3D.Transform(sightPositionLocal + dummyMatrix.Up * 0.5f, gunMatrix);
                            var reticleToEdgePosV = Vector3D.Normalize(reticleProjectedPosition - edgePosV);
                            settings.MaxAngleV = Math.Acos(Vector3D.Dot(gunMatrix.Forward, reticleToEdgePosV));
                        }
                        else if (dummy.Name.EndsWith(DUMMY_CIRCLE_SUFFIX))
                        {
                            settings.Type = SightType.Circle;

                            var edgePos          = Vector3D.Transform(sightPositionLocal + dummyMatrix.Left * 0.5f, gunMatrix);
                            var reticleToEdgePos = Vector3D.Normalize(reticleProjectedPosition - edgePos);
                            settings.MaxAngleH = Math.Acos(Vector3D.Dot(gunMatrix.Forward, reticleToEdgePos));
                        }
                        else
                        {
                            throw new Exception($"{physItemId.SubtypeName} has unsupported dummy suffix: {dummy.Name}");
                        }

                        settings.DummyMatrix = dummy.Matrix;
                        break;
                    }
                }

                dummies.Clear();
            }

            drawInfo.Add(new DrawData(ent, settings));
        }
Esempio n. 53
0
        private int TryCreatingItemsByMerge(MyComponentGroupDefinition group, int itemValue, int itemCount)
        {
            int        num;
            List <int> item = this.m_listAllocator.Allocate();

            item.Clear();
            int num2 = 0;

            while (true)
            {
                if (num2 <= group.GetComponentNumber())
                {
                    item.Add(0);
                    num2++;
                    continue;
                }
                num = 0;
                int num3 = 0;
                while (true)
                {
                    if (num3 >= itemCount)
                    {
                        break;
                    }
                    int num4 = itemValue;
                    int key  = itemValue - 1;
                    while (true)
                    {
                        if (key >= 1)
                        {
                            int num6 = 0;
                            if (this.m_presentItems.TryGetValue(key, out num6))
                            {
                                int num7 = Math.Min(num4 / key, num6);
                                if (num7 > 0)
                                {
                                    num4 -= key * num7;
                                    num6 -= num7;
                                    List <int> list2 = item;
                                    int        num8  = key;
                                    list2[num8] += num7;
                                }
                            }
                            key--;
                            continue;
                        }
                        if (num4 != itemValue)
                        {
                            if (num4 != 0)
                            {
                                for (int i = num4 + 1; i <= group.GetComponentNumber(); i++)
                                {
                                    int num10 = 0;
                                    this.m_presentItems.TryGetValue(i, out num10);
                                    if (num10 > item[i])
                                    {
                                        MyDefinitionId removedComponentId = group.GetComponentDefinition(i).Id;
                                        this.AddChangeToSolution(removedComponentId, group.GetComponentDefinition(i - num4).Id, 1);
                                        this.TryRemovePresentItems(i, 1);
                                        this.AddPresentItems(i - num4, 1);
                                        num4 = 0;
                                        break;
                                    }
                                }
                            }
                            if (num4 == 0)
                            {
                                num++;
                                for (int i = 1; i <= group.GetComponentNumber(); i++)
                                {
                                    if (item[i] > 0)
                                    {
                                        MyDefinitionId id = group.GetComponentDefinition(i).Id;
                                        this.TryRemovePresentItems(i, item[i]);
                                        this.AddRemovalToSolution(id, item[i]);
                                        item[i] = 0;
                                    }
                                }
                                break;
                            }
                            if (num4 <= 0)
                            {
                                break;
                            }
                        }
                        break;
                    }
                    num3++;
                }
                break;
            }
            this.m_listAllocator.Deallocate(item);
            return(num);
        }
 public float GetMaxPower(MyDefinitionId weaponDef) => _getMaxPower?.Invoke(weaponDef) ?? 0f;
Esempio n. 55
0
        public override unsafe void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.SyncFlag = true;
            List <MyResourceSourceInfo> sourceResourceData = new List <MyResourceSourceInfo>();

            foreach (MyOxygenGeneratorDefinition.MyGasGeneratorResourceInfo info in this.BlockDefinition.ProducedGases)
            {
                MyResourceSourceInfo *infoPtr1;
                MyResourceSourceInfo  item = new MyResourceSourceInfo {
                    ResourceTypeId = info.Id
                };
                infoPtr1->DefinedOutput = (this.BlockDefinition.IceConsumptionPerSecond * info.IceToGasRatio) * (MySession.Static.CreativeMode ? 10f : 1f);
                infoPtr1 = (MyResourceSourceInfo *)ref item;
                item.ProductionToCapacityMultiplier = 1f;
                sourceResourceData.Add(item);
            }
            this.SourceComp.Init(this.BlockDefinition.ResourceSourceGroup, sourceResourceData);
            base.Init(objectBuilder, cubeGrid);
            MyObjectBuilder_OxygenGenerator generator = objectBuilder as MyObjectBuilder_OxygenGenerator;

            this.InitializeConveyorEndpoint();
            this.m_useConveyorSystem.SetLocalValue(generator.UseConveyorSystem);
            base.NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME | MyEntityUpdateEnum.EACH_FRAME;
            MyInventory component = this.GetInventory(0);

            if (component != null)
            {
                component.Constraint = this.BlockDefinition.InputInventoryConstraint;
            }
            else
            {
                component = new MyInventory(this.BlockDefinition.InventoryMaxVolume, this.BlockDefinition.InventorySize, MyInventoryFlags.CanReceive)
                {
                    Constraint = this.BlockDefinition.InputInventoryConstraint
                };
                base.Components.Add <MyInventoryBase>(component);
            }
            this.m_oreConstraint = new MyInventoryConstraint(component.Constraint.Description, component.Constraint.Icon, component.Constraint.IsWhitelist);
            foreach (MyDefinitionId id in component.Constraint.ConstrainedIds)
            {
                if (id.TypeId != typeof(MyObjectBuilder_GasContainerObject))
                {
                    this.m_oreConstraint.Add(id);
                }
            }
            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                base.FixSingleInventory();
            }
            if (component != null)
            {
                component.Init(generator.Inventory);
            }
            this.AutoRefill         = generator.AutoRefill;
            this.SourceComp.Enabled = base.Enabled;
            if (Sync.IsServer)
            {
                this.SourceComp.OutputChanged += new MyResourceOutputChangedDelegate(this.Source_OutputChanged);
            }
            float num = this.IceAmount();

            foreach (MyDefinitionId id2 in this.SourceComp.ResourceTypes)
            {
                MyDefinitionId gasId = id2;
                this.m_sourceComp.SetRemainingCapacityByType(id2, (float)this.IceToGas(ref gasId, (double)num));
            }
            MyResourceSinkInfo sinkData = new MyResourceSinkInfo {
                ResourceTypeId    = MyResourceDistributorComponent.ElectricityId,
                MaxRequiredInput  = this.BlockDefinition.OperationalPowerConsumption,
                RequiredInputFunc = new Func <float>(this.ComputeRequiredPower)
            };

            base.ResourceSink.Init(this.BlockDefinition.ResourceSinkGroup, sinkData);
            base.ResourceSink.IsPoweredChanged += new Action(this.PowerReceiver_IsPoweredChanged);
            base.ResourceSink.Update();
            this.UpdateText();
            base.AddDebugRenderComponent(new MyDebugRenderComponentDrawConveyorEndpoint(this.m_conveyorEndpoint));
            base.SlimBlock.ComponentStack.IsFunctionalChanged += new Action(this.ComponentStack_IsFunctionalChanged);
            base.IsWorkingChanged += new Action <MyCubeBlock>(this.MyGasGenerator_IsWorkingChanged);
        }
Esempio n. 56
0
        public override void ProcessServer()
        {
            var player = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId);

            // Only Admin can change Npc Market prices.
            if (!player.IsAdmin() && MarketId == EconomyConsts.NpcMerchantId)
            {
                EconomyScript.Instance.ServerLogger.WriteWarning("A Player without Admin \"{0}\" {1} attempted to set Default Market characteristics of item {2}/{3} to Quantity={4}.", SenderDisplayName, SenderSteamId, ItemTypeId, ItemSubTypeName, ItemQuantity);
                return;
            }

            // Only Player can change their own Market prices.
            if (SenderSteamId != MarketId && MarketId != EconomyConsts.NpcMerchantId)
            {
                EconomyScript.Instance.ServerLogger.WriteWarning("A Player \"{0}\" {1} attempted to set another Market characteristics of item {2}/{3} to Quantity={4}.", SenderDisplayName, SenderSteamId, ItemTypeId, ItemSubTypeName, ItemQuantity);
                return;
            }

            // TODO: do we check range to market?

            MyDefinitionBase    definition = null;
            MyObjectBuilderType result;

            if (MyObjectBuilderType.TryParse(ItemTypeId, out result))
            {
                var id = new MyDefinitionId(result, ItemSubTypeName);
                MyDefinitionManager.Static.TryGetDefinition(id, out definition);
            }

            if (definition == null)
            {
                // Passing bad data?
                MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "Sorry, the item you specified doesn't exist!");
                return;
            }

            if (SetType.HasFlag(SetMarketItemType.Quantity))
            {
                // Do a floating point check on the item item. Tools and components cannot have decimals. They must be whole numbers.
                if (definition.Id.TypeId != typeof(MyObjectBuilder_Ore) && definition.Id.TypeId != typeof(MyObjectBuilder_Ingot))
                {
                    if (ItemQuantity != Math.Truncate(ItemQuantity))
                    {
                        MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "You must provide a whole number for the quantity of that item.");
                        return;
                    }
                    //ItemQuantity = Math.Round(ItemQuantity, 0);  // Or do we just round the number?
                }

                if (ItemQuantity < 0)
                {
                    MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "Invalid quantity specified");
                    return;
                }
            }

            // Find the specified market.
            List <MarketStruct> markets;

            if (string.IsNullOrEmpty(MarketZone))
            {
                var character = player.Character;

                if (character == null)
                {
                    // Player has no body. Could mean they are dead.
                    MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "There is no market at your location to set.");
                    return;
                }

                var position = ((IMyEntity)character).WorldMatrix.Translation;
                markets = MarketManager.FindMarketsFromLocation(position).Where(m => m.MarketId == MarketId).ToList();
            }
            else
            {
                markets = EconomyScript.Instance.Data.Markets.Where(m => m.MarketId == MarketId && (MarketZone == "*" || m.DisplayName.Equals(MarketZone, StringComparison.InvariantCultureIgnoreCase))).ToList();
            }

            if (markets.Count == 0)
            {
                MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "Sorry, you are not near any markets currently or the market does not exist!");
                return;
            }

            var msg = new StringBuilder();

            msg.AppendFormat("Applying changes to : '{0}' {1}/{2}\r\n\r\n", definition.GetDisplayName(), ItemTypeId, ItemSubTypeName);

            foreach (var market in markets)
            {
                msg.AppendFormat("Market: '{0}'\r\n", market.DisplayName);

                var marketItem = market.MarketItems.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName);
                if (marketItem == null)
                {
                    msg.AppendLine("Sorry, the items you are trying to set doesn't have a market entry!");
                    // In reality, this shouldn't happen as all markets have their items synced up on start up of the mod.
                    continue;
                }

                if (SetType.HasFlag(SetMarketItemType.Quantity))
                {
                    marketItem.Quantity = ItemQuantity;
                    msg.AppendFormat("Stock on hand to {0} units", ItemQuantity);
                }

                // Validation to prevent admins setting prices too low for items.
                if (SetType.HasFlag(SetMarketItemType.BuyPrice))
                {
                    if (ItemBuyPrice >= 0)
                    {
                        marketItem.BuyPrice = ItemBuyPrice;
                        msg.AppendFormat("Buy price to {0}", ItemBuyPrice);
                    }
                    else
                    {
                        msg.AppendFormat("Could not set buy price to less than 0.");
                    }
                }

                // Validation to prevent admins setting prices too low for items.
                if (SetType.HasFlag(SetMarketItemType.SellPrice))
                {
                    if (ItemSellPrice >= 0)
                    {
                        marketItem.SellPrice = ItemSellPrice;
                        msg.AppendFormat("Sell price to {0}", ItemSellPrice);
                    }
                    else
                    {
                        msg.AppendFormat("Could not set sell price to less than 0.");
                    }
                }

                if (SetType.HasFlag(SetMarketItemType.Blacklisted))
                {
                    marketItem.IsBlacklisted = !marketItem.IsBlacklisted;
                    msg.AppendFormat("Blacklist to {0}", marketItem.IsBlacklisted ? "On" : "Off");
                }

                if (SetType.HasFlag(SetMarketItemType.StockLimit))
                {
                    if (ItemStockLimit > 0)
                    {
                        marketItem.StockLimit = ItemStockLimit;
                        if (ItemStockLimit == decimal.MaxValue)
                        {
                            msg.AppendFormat("Set stock limit to MAX");
                        }
                        else
                        {
                            msg.AppendFormat("Set stock limit to {0}", ItemStockLimit);
                        }
                    }
                    else
                    {
                        msg.AppendFormat("Can not set stock limit to less than 0.");
                    }
                }

                msg.AppendLine();
                msg.AppendLine();
            }

            #region update config for the item

            MarketItemStruct configItem = null;
            if (player.IsAdmin() && MarketId == EconomyConsts.NpcMerchantId)
            {
                configItem = EconomyScript.Instance.ServerConfig.DefaultPrices.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName);
            }

            if (configItem != null)
            {
                if (SetType.HasFlag(SetMarketItemType.BuyPrice))
                {
                    if (ItemBuyPrice >= 0)
                    {
                        configItem.BuyPrice = ItemBuyPrice;
                        msg.AppendFormat("Config updated Buy price to {0}", ItemBuyPrice);
                    }
                }

                // Validation to prevent admins setting prices too low for items.
                if (SetType.HasFlag(SetMarketItemType.SellPrice))
                {
                    if (ItemSellPrice >= 0)
                    {
                        configItem.SellPrice = ItemSellPrice;
                        msg.AppendFormat("Config updated Sell price to {0}", ItemSellPrice);
                    }
                }

                if (SetType.HasFlag(SetMarketItemType.Blacklisted))
                {
                    configItem.IsBlacklisted = !configItem.IsBlacklisted;
                    msg.AppendFormat("Config updated Blacklist to {0}", configItem.IsBlacklisted ? "On" : "Off");

                    // If config blacklisted, then all markets should be updated.
                    if (configItem.IsBlacklisted)
                    {
                        int counter = 0;
                        foreach (var market in EconomyScript.Instance.Data.Markets)
                        {
                            var marketItem = market.MarketItems.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName);
                            if (marketItem != null && !marketItem.IsBlacklisted)
                            {
                                counter++;
                                marketItem.IsBlacklisted = true;
                            }
                        }

                        msg.AppendFormat("Config updated {0} Markets to also Blacklist to {1}.", counter, configItem.IsBlacklisted ? "On" : "Off");
                    }
                }
            }

            #endregion

            MessageClientDialogMessage.SendMessage(SenderSteamId, "SET", " ", msg.ToString());
        }
Esempio n. 57
0
        public static string GetGunNotificationName(MyDefinitionId gunId)
        {
            var definition = MyDefinitionManager.Static.GetDefinition(gunId);

            return(definition.DisplayNameText);
        }
Esempio n. 58
0
 private double GasOutputPerSecond(ref MyDefinitionId gasId) =>
 ((double)(this.SourceComp.CurrentOutputByType(gasId) * ((Sandbox.ModAPI.IMyGasGenerator) this).ProductionCapacityMultiplier));
Esempio n. 59
0
 public static MyDefinitionId ToMyDefinitionId(DefinitionId definitionId)
 {
     return(MyDefinitionId.Parse(definitionId.ToString()));
 }
Esempio n. 60
0
        public static void ProcessLcdBlock(IMyTextPanel textPanel)
        {
            //counter++;

            var writer = TextPanelWriter.Create(textPanel);

            // Use the update interval on the LCD Panel to determine how often the display is updated.
            // It can only go as fast as the timer calling this code is.
            float interval;

            try
            {
                interval = Math.Max((float)EconomyScript.Instance.ServerConfig.MinimumLcdDisplayInterval, textPanel.GetValueFloat("ChangeIntervalSlider"));
            }
            catch (Exception ex)
            {
                // The game may generate an exception from the GetValueFloat(GetValue) call.
                EconomyScript.Instance.ServerLogger.WriteException(ex, UpdateCrashMessage);
                EconomyScript.Instance.ClientLogger.WriteException(ex, UpdateCrashMessage);
                // We can't safely ignore this one if it doesn't work, because this can affect the display timing.
                return;
            }
            if (writer.LastUpdate > DateTime.Now.AddSeconds(-interval))
            {
                return;
            }

            var       checkArray    = (textPanel.CustomName + ' ' + textPanel.GetPublicTitle()).Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var       showAll       = false;
            bool      showOre       = false;
            bool      showIngot     = false;
            bool      showComponent = false;
            bool      showAmmo      = false;
            bool      showTools     = false;
            bool      showSupplies  = false;
            bool      showGasses    = false;
            bool      showStock     = false;
            bool      showPrices    = true;
            bool      showTest1     = false;
            bool      showTest2     = false;
            StartFrom startFrom     = StartFrom.None; //if # is specified eg #20  then run the start line logic
            int       startLine     = 0;              //this is where our start line placeholder sits
            int       pageNo        = 1;

            // removed Linq, to reduce the looping through the array. This should only have to do one loop through all items in the array.
            foreach (var str in checkArray)
            {
                if (str.Equals("stock", StringComparison.InvariantCultureIgnoreCase))
                {
                    showStock = true;
                }
                if (str.Contains("#"))
                {
                    string[] lineNo = str.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                    if (lineNo.Length != 0 && int.TryParse(lineNo[0], out startLine))
                    {
                        //this only runs if they put a number in
                        startFrom = StartFrom.Line;
                    }
                }
                if (str.StartsWith("P", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (int.TryParse(str.Substring(1), out pageNo))
                    {
                        startFrom = StartFrom.Page;
                    }
                }
                if (str.Equals("*", StringComparison.InvariantCultureIgnoreCase))
                {
                    showAll = true;
                }
                if (!showAll)
                {
                    if (str.Equals("test1", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showTest1 = true;
                    }
                    else if (str.Equals("test2", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showTest2 = true;
                    }
                    else if (str.StartsWith("ore", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showOre = true;
                    }
                    else if (str.StartsWith("ingot", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showIngot = true;
                    }
                    else if (str.StartsWith("component", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showComponent = true;
                    }
                    else if (str.StartsWith("ammo", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showAmmo = true;
                    }
                    else if (str.StartsWith("tool", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showTools = true;
                    }
                    else if (str.StartsWith("supplies", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showSupplies = true;
                    }
                    else if (str.StartsWith("supply", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showSupplies = true;
                    }
                    else if (str.StartsWith("gas", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showGasses = true;
                    }
                }
            }

            bool showHelp = !showAll && !showOre && !showIngot && !showComponent && !showAmmo && !showSupplies && !showTools && !showGasses;



            showPrices = !showStock || writer.IsWide;

            if (showTest1)
            {
                Test1(writer);
                writer.UpdatePublic();
                return;
            }
            if (showTest2)
            {
                Test2(writer);
                writer.UpdatePublic();
                return;
            }

            if (showHelp)
            {
                writer.AddPublicLine("Please add a tag to the private or public title.");
                writer.AddPublicLine("ie., * ingot ore component ammo tools.");
                writer.UpdatePublic();
                return;
            }

            var buyColumn   = TextPanelWriter.LcdLineWidth - 180;
            var sellColumn  = TextPanelWriter.LcdLineWidth - 0;
            var stockColumn = TextPanelWriter.LcdLineWidth - 0;

            if (showPrices && showStock)
            {
                buyColumn   = TextPanelWriter.LcdLineWidth - 280;
                sellColumn  = TextPanelWriter.LcdLineWidth - 180;
                stockColumn = TextPanelWriter.LcdLineWidth - 0;
            }

            // This might be a costly operation to run.
            var markets = MarketManager.FindMarketsFromLocation(textPanel.WorldMatrix.Translation);

            if (markets.Count == 0)
            {
                writer.AddPublicCenterLine(TextPanelWriter.LcdLineWidth / 2f, "« {0} »", EconomyScript.Instance.ServerConfig.TradeNetworkName);
                writer.AddPublicCenterLine(TextPanelWriter.LcdLineWidth / 2f, "« No market in range »");
            }
            else
            {
                // TODO: not sure if we should display all markets, the cheapest market item, or the closet market.
                // LOGIC summary: it needs to show the cheapest in stock(in range) sell(to player) price, and the highest (in range) has funds buy(from player) price
                // but this logic depends on the buy/sell commands defaulting to the same buy/sell rules as above.
                // where buy /sell commands run out of funds or supply in a given market and need to pull from the next market
                //it will either have to stop at each price change and notify the player, and/or prompt to keep transacting at each new price, or blindly keep buying until the
                //order is filled, the market runs out of stock, or the money runs out. Blindly is probably not optimal unless we are using stockmarket logic (buy orders/offers)
                //so the prompt option is the safer
                var market = markets.FirstOrDefault();

                // Build a list of the items, so we can get the name so we can the sort the items by name.
                var list = new Dictionary <MarketItemStruct, string>();

                writer.AddPublicCenterLine(TextPanelWriter.LcdLineWidth / 2f, market.DisplayName);

                if (startFrom == StartFrom.Page)
                {
                    // convert the page to lines required.
                    if (pageNo < 1)
                    {
                        pageNo = 1;
                    }
                    startLine = ((writer.DisplayLines - 2) * (pageNo - 1));
                    startFrom = StartFrom.Line;
                }

                string fromLine = " (From item #" + startLine + ".)";
                writer.AddPublicText("« Market List");
                if (startLine >= 1)
                {
                    writer.AddPublicText(fromLine);
                }
                else
                {
                    startLine = 1; // needed for truncating end line.
                }
                if (showPrices && showStock)
                {
                    writer.AddPublicRightText(buyColumn, "Buy");
                    writer.AddPublicRightText(sellColumn, "Sell");
                    writer.AddPublicRightLine(stockColumn, "Stock »");
                }
                else if (showStock)
                {
                    writer.AddPublicRightLine(stockColumn, "Stock »");
                }
                else if (showPrices)
                {
                    writer.AddPublicRightText(buyColumn, "Buy");
                    writer.AddPublicRightLine(sellColumn, "Sell »");
                }

                foreach (var marketItem in market.MarketItems)
                {
                    if (marketItem.IsBlacklisted || marketItem.SubtypeName == "SpaceCredit" || marketItem.SubtypeName == "Space Credit")
                    {
                        continue;
                    }

                    MyObjectBuilderType result;
                    if (MyObjectBuilderType.TryParse(marketItem.TypeId, out result))
                    {
                        var id      = new MyDefinitionId(result, marketItem.SubtypeName);
                        var content = Support.ProducedType(id);

                        //if (((Type)id.TypeId).IsSubclassOf(typeof(MyObjectBuilder_GasContainerObject))) // TODO: Not valid call yet.

                        // Cannot check the Type of the item, without having to use MyObjectBuilderSerializer.CreateNewObject().

                        if (showAll ||
                            (showOre && content is MyObjectBuilder_Ore) ||
                            (showIngot && content is MyObjectBuilder_Ingot) ||
                            (showComponent && content is MyObjectBuilder_Component) ||
                            (showAmmo && content is MyObjectBuilder_AmmoMagazine) ||
                            (showSupplies && content is MyObjectBuilder_ConsumableItem) ||
                            (showSupplies && content is MyObjectBuilder_Package) ||
                            (showSupplies && content is MyObjectBuilder_Datapad) ||
                            (showTools && content is MyObjectBuilder_PhysicalGunObject) ||   // guns, welders, hand drills, grinders.
                            (showGasses && content is MyObjectBuilder_GasContainerObject) || // aka gas bottle.
                            (showGasses && content is MyObjectBuilder_GasProperties))        // Type check here allows mods that inherit from the same type to also appear in the lists.
                        {
                            MyDefinitionBase definition;
                            if (MyDefinitionManager.Static.TryGetDefinition(id, out definition))
                            {
                                list.Add(marketItem, definition == null ? marketItem.TypeId + "/" + marketItem.SubtypeName : definition.GetDisplayName());
                            }
                        }
                    }
                }
                int line = 0;
                foreach (var kvp in list.OrderBy(k => k.Value))
                {
                    line++;
                    if (startFrom == StartFrom.Line && line < startLine) //if we have a start line specified skip all lines up to that
                    {
                        continue;
                    }
                    if (startFrom == StartFrom.Line && line - startLine >= writer.WholeDisplayLines - 2) // counts 2 lines of headers.
                    {
                        break;                                                                           // truncate the display and don't display the text on the bottom edge of the display.
                    }
                    writer.AddPublicLeftTrim(buyColumn - 120, kvp.Value);

                    decimal showBuy  = kvp.Key.BuyPrice;
                    decimal showSell = kvp.Key.SellPrice;
                    if ((EconomyScript.Instance.ServerConfig.PriceScaling) && (market.MarketId == EconomyConsts.NpcMerchantId))
                    {
                        showBuy  = EconDataManager.PriceAdjust(kvp.Key.BuyPrice, kvp.Key.Quantity, PricingBias.Buy);
                        showSell = EconDataManager.PriceAdjust(kvp.Key.SellPrice, kvp.Key.Quantity, PricingBias.Sell);
                    }

                    if (showPrices && showStock)
                    {
                        writer.AddPublicRightText(buyColumn, showBuy.ToString("\t0.000", EconomyScript.ServerCulture));
                        writer.AddPublicRightText(sellColumn, showSell.ToString("\t0.000", EconomyScript.ServerCulture));

                        // TODO: components and tools should be displayed as whole numbers. Will be hard to align with other values.
                        writer.AddPublicRightText(stockColumn, kvp.Key.Quantity.ToString("\t0.0000", EconomyScript.ServerCulture)); // TODO: recheck number of decimal places.
                    }
                    else if (showStock)                                                                                             //does this ever actually run? seems to already be in the above?
                    {
                        // TODO: components and tools should be displayed as whole numbers. Will be hard to align with other values.

                        writer.AddPublicRightText(stockColumn, kvp.Key.Quantity.ToString("\t0.0000", EconomyScript.ServerCulture)); // TODO: recheck number of decimal places.
                    }
                    else if (showPrices)
                    {
                        writer.AddPublicRightText(buyColumn, showBuy.ToString("\t0.000", EconomyScript.ServerCulture));
                        writer.AddPublicRightText(sellColumn, showSell.ToString("\t0.000", EconomyScript.ServerCulture));
                    }
                    writer.AddPublicLine();
                }
            }

            writer.UpdatePublic();
        }