public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            m_handItemDefinitionId = objectBuilder.GetId();
            m_physItemDef          = MyDefinitionManager.Static.GetPhysicalItemForHandItem(m_handItemDefinitionId);
            base.Init(objectBuilder);
            Init(null, PhysicalItemDefinition.Model, null, null, null);

            Save = false;

            PhysicalObject                    = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_PhysicalGunObject>(m_handItemDefinitionId.SubtypeName);
            PhysicalObject.GunEntity          = (MyObjectBuilder_EntityBase)objectBuilder.Clone();
            PhysicalObject.GunEntity.EntityId = this.EntityId;

            m_toolItemDef = PhysicalItemDefinition as MyToolItemDefinition;

            m_notEnoughStatNotification = new MyHudNotification(MyCommonTexts.NotificationStatNotEnough, disappearTimeMs: 1000, font: MyFontEnum.Red, level: MyNotificationLevel.Important);

            InitToolComponents();

            NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME | MyEntityUpdateEnum.EACH_10TH_FRAME;

            var builder = objectBuilder as MyObjectBuilder_HandToolBase;

            if (builder.DeviceBase != null)
            {
                GunBase.Init(builder.DeviceBase);
            }
        }
        public MyFixedPoint ComputeAmountThatFits(MyDefinitionId contentId)
        {
            if (!MyPerGameSettings.ConstrainInventory())
            {
                return(MyFixedPoint.MaxValue);
            }
            float volume, mass;

            if (!GetVolumeAndMass(ref contentId, out volume, out mass))
            {
                return(0);
            }
            var amountThatFits = (m_maxVolume - m_currentVolume) * (1.0f / volume);

            amountThatFits = MyFixedPoint.Max(amountThatFits, 0); // In case we added more than we can carry using debug keys.

            MyPhysicalItemDefinition physicalItemDefinition = null;

            MyDefinitionManager.Static.TryGetPhysicalItemDefinition(contentId, out physicalItemDefinition);
            if (contentId.TypeId == typeof(MyObjectBuilder_CubeBlock) || (physicalItemDefinition != null && physicalItemDefinition.HasIntegralAmounts))
            {
                amountThatFits = MyFixedPoint.Floor(amountThatFits);
            }

            return(amountThatFits);
        }
        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            var builder = objectBuilder as MyObjectBuilder_FloatingObject;

            if (builder.Item.Amount <= 0)
            {
                // I can only prevent creation of entity by throwing exception. This might cause crashes when thrown outside of MyEntities.CreateFromObjectBuilder().
                throw new ArgumentOutOfRangeException("MyPhysicalInventoryItem.Amount", string.Format("Creating floating object with invalid amount: {0}x '{1}'", builder.Item.Amount, builder.Item.PhysicalContent.GetId()));
            }
            base.Init(objectBuilder);

            this.Item           = new MyPhysicalInventoryItem(builder.Item);
            this.m_modelVariant = builder.ModelVariant;

            InitInternal();

            NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;

            UseDamageSystem = true;

            MyPhysicalItemDefinition itemDefinition = null;

            if (!MyDefinitionManager.Static.TryGetPhysicalItemDefinition(Item.GetDefinitionId(), out itemDefinition))
            {
                System.Diagnostics.Debug.Fail("Creating floating object, but it's physical item definition wasn't found! - " + Item.ItemId);
                ItemDefinition = null;
            }
            else
            {
                ItemDefinition = itemDefinition;
            }
            m_timeFromSpawn = MySession.Static.ElapsedPlayTime;
        }
Exemple #4
0
        public override void Init(MyObjectBuilder_EntityBase objectBuilder)
        {
            MyObjectBuilder_FloatingObject obj2 = objectBuilder as MyObjectBuilder_FloatingObject;

            if (obj2.Item.Amount <= 0)
            {
                throw new ArgumentOutOfRangeException("MyPhysicalInventoryItem.Amount", $"Creating floating object with invalid amount: {obj2.Item.Amount}x '{obj2.Item.PhysicalContent.GetId()}'");
            }
            base.Init(objectBuilder);
            this.Item           = new MyPhysicalInventoryItem(obj2.Item);
            this.m_modelVariant = obj2.ModelVariant;
            this.Amount.SetLocalValue(this.Item.Amount);
            this.Amount.ValueChanged += delegate(SyncBase x) {
                this.Item.Amount = this.Amount.Value;
                this.UpdateInternalState();
            };
            this.InitInternal();
            base.NeedsUpdate    |= MyEntityUpdateEnum.EACH_FRAME;
            this.UseDamageSystem = true;
            MyPhysicalItemDefinition definition = null;

            this.ItemDefinition     = MyDefinitionManager.Static.TryGetPhysicalItemDefinition(this.Item.GetDefinitionId(), out definition) ? definition : null;
            this.m_timeFromSpawn    = MySession.Static.ElapsedPlayTime;
            this.m_smoothGravity    = this.Physics.RigidBody.Gravity;
            this.m_smoothGravityDir = this.m_smoothGravity;
            this.m_smoothGravityDir.Normalize();
            this.m_supportNormals          = new List <Vector3>();
            this.m_supportNormals.Capacity = 3;
            if (!Sync.IsServer)
            {
                this.Physics.RigidBody.UpdateMotionType(HkMotionType.Fixed);
            }
        }
Exemple #5
0
        private void SetupPhysicalItem()
        {
            // 1) Physical Item
            MyObjectBuilder_PhysicalItemDefinition newPhysDefOb = new MyObjectBuilder_PhysicalItemDefinition
            {
                Id = new SerializableDefinitionId
                {
                    TypeId    = typeof(MyObjectBuilder_Ore),
                    SubtypeId = "BulletproofGlassScrap2"
                },
                DisplayName      = "Bulletproof Glass Scrap 2",
                Icons            = new[] { Constants.IconLocation + Constants.BulletproofGlassIcon },
                Size             = new Vector3(0.2, 0.2, 0.1),
                Mass             = 1,
                Volume           = 0.254f,
                Model            = Constants.KnownScrapModelLocation + Constants.Scrap2,
                PhysicalMaterial = "Metal"
            };

            // 1b) Physical Item Def -- May not be needed...
            MyPhysicalItemDefinition newPhysItemDef = new MyPhysicalItemDefinition
            {
                Id = newPhysDefOb.Id,
                AvailableInSurvival = true
            };

            WriteToLog("Added", $"{ManualAddToDefinitions(newPhysItemDef)}", LogType.General);
            //WriteToLog("Added",$"{MyDefinitionManager.Static.Definitions.AddOrRelaceDefinition(newPhysItemDef)}",LogType.General);
        }
Exemple #6
0
        //private void PrintProductionBlocksDefinitions()
        //{
        //	foreach (var def in MyDefinitionManager.Static.GetDefinitionsOfType<MyRefineryDefinition>())
        //	{
        //		WriteToLog("", $"{def}", LogType.General);

        //		foreach (var cls in def.BlueprintClasses)
        //		{
        //			WriteToLog("", $"{cls}", LogType.General);
        //		}
        //	}

        //	foreach (var def in MyDefinitionManager.Static.GetDefinitionsOfType<MySurvivalKitDefinition>())
        //	{
        //		WriteToLog("", $"{def}", LogType.General);
        //		foreach (var cls in def.BlueprintClasses)
        //		{
        //			WriteToLog("", $"{cls}", LogType.General);
        //		}
        //	}
        //}

        private void SetupCollections()
        {
            foreach (var def in MyDefinitionManager.Static.GetAllDefinitions())
            {
                MyPhysicalItemDefinition physDef = def as MyPhysicalItemDefinition;
                if (physDef != null && physDef.Public)
                {
                    if (physDef.Id.TypeId == typeof(MyObjectBuilder_Component))
                    {
                        _components.Add(physDef);
                    }

                    if (def.Id.TypeId == typeof(MyObjectBuilder_Ore))
                    {
                        _ores.Add(physDef);
                    }
                    continue;
                }

                MyCubeBlockDefinition blockDef = def as MyCubeBlockDefinition;
                if (blockDef != null && blockDef.Public)
                {
                    _cubes.Add(blockDef);
                }
            }

            foreach (var bp in MyDefinitionManager.Static.GetBlueprintDefinitions())
            {
                MyBlueprintDefinition bpDef = bp as MyBlueprintDefinition;
                if (bpDef != null && bpDef.Public)
                {
                    _blueprints.Add(bpDef);
                }
            }
        }
Exemple #7
0
        private long SpawnInventoryContainer(MyPhysicalItemDefinition bagDefinition)
        {
            MyEntity builder     = Character;
            var      worldMatrix = Character.WorldMatrix;

            worldMatrix.Translation += worldMatrix.Up + worldMatrix.Forward;

            MyObjectBuilder_EntityBase bagBuilder = new MyObjectBuilder_EntityBase();

            bagBuilder.Name = bagDefinition.DisplayNameText;
            var position = new MyPositionAndOrientation(worldMatrix);

            bagBuilder.PositionAndOrientation = position;
            bagBuilder.EntityId    = MyEntityIdentifier.AllocateId();
            bagBuilder.SubtypeName = bagDefinition.Id.SubtypeName;

            var entity = MyEntities.CreateAndAddFromDefinition(bagBuilder, bagDefinition);

            entity.Physics.ForceActivate();
            entity.Physics.ApplyImpulse(builder.Physics.LinearVelocity, Vector3.Zero);

            MySyncCreate.SendEntityCreated(entity.GetObjectBuilder(), bagDefinition.Id);

            return(entity.EntityId);
        }
Exemple #8
0
        public static void GetAllBehaviorProfiles()
        {
            BehaviorProfiles.Clear();
            var defList = MyDefinitionManager.Static.GetPhysicalItemDefinitions();

            foreach (var def in defList)
            {
                if (string.IsNullOrWhiteSpace(def.DescriptionText) == true)
                {
                    continue;
                }

                if (def.DescriptionText.Contains("[Rival AI Behavior]") == true)
                {
                    MyPhysicalItemDefinition item = null;
                    if (BehaviorProfiles.TryGetValue(def.Id.SubtypeName, out item) == false)
                    {
                        BehaviorProfiles.Add(def.Id.SubtypeName, def);
                    }
                    else
                    {
                        var sb = new StringBuilder();
                        sb.Append("Error Adding RivalAI Profile: ").Append(def.Id.SubtypeName).Append(" - Profile Already Exists.");
                        Logger.MsgDebug(sb.ToString());
                    }
                }
            }
        }
        public static MyEntity Spawn(MyPhysicalInventoryItem item, Vector3D position, Vector3D forward, Vector3D up, MyPhysicsComponentBase motionInheritedFrom = null)
        {
            var orientedForward = forward;
            var orientedUp      = up;

            var left = Vector3D.Cross(up, forward);

            MyPhysicalItemDefinition itemDefinition = null;

            if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalItemDefinition>(item.Content.GetObjectId(), out itemDefinition))
            {
                if (itemDefinition.RotateOnSpawnX)
                {
                    orientedForward = up;
                    orientedUp      = -forward;
                }
                if (itemDefinition.RotateOnSpawnY)
                {
                    orientedForward = left;
                }
                if (itemDefinition.RotateOnSpawnZ)
                {
                    orientedUp = -left;
                }
            }

            return(Spawn(item, MatrixD.CreateWorld(position, orientedForward, orientedUp), motionInheritedFrom));
        }
 private static void ProcessReactor(MyObjectBuilder_CubeBlock block, Options options, MyCubeSize size)
 {         // Has it's own inventory, but it doesn't work, so still needs supporting function to add inventory
     if (options.PowerDownGrid)
     {
         ((MyObjectBuilder_Reactor)block).Enabled = false;
     }
     if (!options.Restock)
     {
         return;
     }
     try
     {
         List <MyDefinitionId> fuelList = GetItemDefinitionList(block);
         if (fuelList == null)
         {
             return;
         }
         MyObjectBuilder_Ingot fuel = new MyObjectBuilder_Ingot {
             SubtypeName = fuelList[0].SubtypeName
         };
         MyPhysicalItemDefinition fuelDefinition = MyDefinitionManager.Static.GetPhysicalItemDefinition(fuel.GetId());
         //AddToInventory(block.ComponentContainer, fuel, (int)(GetMaxVolume(block, size) / fuelDefinition.Volume), true);
         int amountToAdd = GetAmount(GetMaxVolume(block, size), fuelDefinition.Volume);
         if (options.MaxAmmo != 0 && amountToAdd > options.MaxUranium)
         {
             amountToAdd = options.MaxAmmo;
         }
         AddToInventory(block.ComponentContainer, fuel, amountToAdd, true);
     }
     catch (Exception e)
     {
         Core.GeneralLog.WriteToLog("MyObjectBuilder_Reactor", $"Exception! {e}");
     }
 }
Exemple #11
0
        public static MyPhysicalItemDefinition GetItemDefinition(MyDefinitionId itemId)
        {
            if (_allItems.Count == 0)
            {
                _allItems = MyDefinitionManager.Static.GetPhysicalItemDefinitions();
            }

            MyPhysicalItemDefinition item = null;

            if (_cachedItemDefinitions.TryGetValue(itemId, out item))
            {
                return(item);
            }

            foreach (var itemdef in _allItems)
            {
                if (itemdef.Id == itemId)
                {
                    item = itemdef;
                    _cachedItemDefinitions.Add(itemId, item);
                    break;
                }
            }

            return(item);
        }
 private static void ProcessParachute(MyObjectBuilder_CubeBlock block, Options options, MyCubeSize size)
 {         // Doesn't have it's own inventory, needs supporting function to add inventory
     if (!options.Restock)
     {
         return;
     }
     try
     {
         List <MyDefinitionId> parachuteMaterialList = GetItemDefinitionList(block);
         if (parachuteMaterialList == null)
         {
             return;
         }
         MyObjectBuilder_Component parachuteMaterial = new MyObjectBuilder_Component {
             SubtypeName = parachuteMaterialList[0].SubtypeName
         };
         MyPhysicalItemDefinition parachuteMaterialDefinition = MyDefinitionManager.Static.GetPhysicalItemDefinition(parachuteMaterial.GetId());
         //AddToInventory(block.ComponentContainer, parachuteMaterial, (int)(GetMaxVolume(block, size) / parachuteMaterialDefinition.Volume));
         AddToInventory(block.ComponentContainer, parachuteMaterial, GetAmount(GetMaxVolume(block, size), parachuteMaterialDefinition.Volume), true);
     }
     catch (Exception e)
     {
         Core.GeneralLog.WriteToLog("MyObjectBuilder_Parachute", $"Exception! {e}");
     }
 }
 private static void ProcessOxygenGenerator(MyObjectBuilder_CubeBlock block, Options options, MyCubeSize size)
 {         // Has it's own inventory, supporting function to add inventory doesn't work on this block
     if (!options.Restock)
     {
         return;
     }
     try
     {
         MyObjectBuilder_Ore ice = new MyObjectBuilder_Ore {
             SubtypeName = "Ice"
         };
         MyPhysicalItemDefinition iceDefinition = MyDefinitionManager.Static.GetPhysicalItemDefinition(ice.GetId());
         ((MyObjectBuilder_OxygenGenerator)block).Inventory.Clear();
         ((MyObjectBuilder_OxygenGenerator)block).Inventory.Items.Add(
             new MyObjectBuilder_InventoryItem
         {
             Amount          = (int)((GetMaxVolume(block, size) / iceDefinition.Volume) * 0.90),                  // I want to leave some room for bottles
             PhysicalContent = ice
         });
         Core.GeneralLog.WriteToLog("MyObjectBuilder_OxygenGenerator", $"Amount:\t{(int)((GetMaxVolume(block, size) / iceDefinition.Volume) * 0.9)}");
     }
     catch (Exception e)
     {
         Core.GeneralLog.WriteToLog("MyObjectBuilder_OxygenGenerator", $"Exception! {e}");
     }
 }
        private void AddItems(IMyCubeGrid toGrid, MyPhysicalItemDefinition itemDefinition, decimal quantity)
        {
            var terminalSystem = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(toGrid);
            var blocks         = new List <IMyCargoContainer>();

            terminalSystem.GetBlocksOfType(blocks);

            var remaining = quantity;

            foreach (var cargoBlock in blocks.Where(b => b.CubeGrid.EntityId == toGrid.EntityId))
            {
                var inventory = (MyInventoryBase)cargoBlock.GetInventory();
                var available = (decimal)inventory.ComputeAmountThatFits(itemDefinition.Id);

                if (available >= remaining)
                {
                    ((IMyInventory)inventory).BetterAddItems((MyFixedPoint)remaining, itemDefinition.Id);
                    remaining = 0;
                }
                else if (available > 0)
                {
                    ((IMyInventory)inventory).BetterAddItems((MyFixedPoint)available, itemDefinition.Id);
                    remaining -= available;
                }

                if (remaining == 0)
                {
                    return;
                }
            }
        }
        public override MyFixedPoint ComputeAmountThatFits(MyDefinitionId contentId)
        {
            if (!MyPerGameSettings.ConstrainInventory())
            {
                return(MyFixedPoint.MaxValue);
            }
            float volume, mass;

            if (!GetVolumeAndMass(ref contentId, out volume, out mass))
            {
                return(0);
            }
            var amountThatFitsVolume = MyFixedPoint.Max((MyFixedPoint)((float)m_maxVolume - (float)m_currentVolume) * (1.0f / (float)volume), 0);
            var amountThatFitsMass   = MyFixedPoint.Max((MyFixedPoint)(((float)m_maxMass - (float)m_currentMass) * (1.0f / (float)mass)), 0);
            var amountThatFits       = MyFixedPoint.Min(amountThatFitsVolume, amountThatFitsMass);

            MyPhysicalItemDefinition physicalItemDefinition = null;

            MyDefinitionManager.Static.TryGetPhysicalItemDefinition(contentId, out physicalItemDefinition);
            if (contentId.TypeId == typeof(MyObjectBuilder_CubeBlock) || (physicalItemDefinition != null && physicalItemDefinition.HasIntegralAmounts))
            {
                amountThatFits = MyFixedPoint.Floor(amountThatFits);
            }

            return(amountThatFits);
        }
Exemple #16
0
        public static void LoadDefinition(this MyHudBlockInfo blockInfo, MyCubeBlockDefinition definition, DictionaryReader <MyDefinitionId, int> materials, bool merge = true)
        {
            InitBlockInfo(blockInfo, definition);

            foreach (var material in materials)
            {
                var componentDefinition = MyDefinitionManager.Static.GetComponentDefinition(material.Key);
                var info = new MyHudBlockInfo.ComponentInfo();
                if (componentDefinition == null)
                {
                    MyPhysicalItemDefinition physicalDefinition = null;
                    if (!MyDefinitionManager.Static.TryGetPhysicalItemDefinition(material.Key, out physicalDefinition))
                    {
                        continue;
                    }
                    info.ComponentName = physicalDefinition.DisplayNameText;
                    info.Icon          = physicalDefinition.Icon;
                    info.DefinitionId  = physicalDefinition.Id;
                    info.TotalCount    = 1;
                }
                else
                {
                    info.DefinitionId  = componentDefinition.Id;
                    info.ComponentName = componentDefinition.DisplayNameText;
                    info.Icon          = componentDefinition.Icon;
                    info.TotalCount    = material.Value;
                }
                blockInfo.Components.Add(info);
            }

            if (merge)
            {
                MergeSameComponents(blockInfo);
            }
        }
Exemple #17
0
        public MyEngineerToolBase(MyHandItemDefinition definition, float toolDistance, int cooldownMs)
        {
            ToolCooldownMs       = cooldownMs;
            m_toolActionDistance = toolDistance;
            m_handItemDef        = definition;
            System.Diagnostics.Debug.Assert(definition != null, "Missing definition for tool!");
            if (definition != null)
            {
                m_physItemDef = MyDefinitionManager.Static.GetPhysicalItemForHandItem(definition.Id);
                m_gunBase     = new MyToolBase(m_handItemDef.MuzzlePosition, WorldMatrix);
            }
            else
            {
                m_gunBase = new MyToolBase(Vector3.Zero, WorldMatrix);
            }
            m_activated  = false;
            m_wasPowered = false;

            NeedsUpdate      = MyEntityUpdateEnum.EACH_FRAME;
            Render.NeedsDraw = true;

            (PositionComp as MyPositionComponent).WorldPositionChanged = WorldPositionChanged;
            Render = new Components.MyRenderComponentEngineerTool();
            AddDebugRenderComponent(new MyDebugRenderComponentEngineerTool(this));
        }
Exemple #18
0
        public static void AddOrDropItem(MyPlayer player, MyPhysicalItemDefinition item, ref double amount, MatrixD position)
        {
            var inventory = player.Character.GetInventory();
            var newObject = MyObjectBuilderSerializer.CreateNewObject(item.Id);

            amount = TryAddToInventory(inventory, amount, newObject, item.Id);
            if (amount > 0)
            {
                var controlledEntity = player.Controller.ControlledEntity;
                if (controlledEntity is MyShipController controller)
                {
                    foreach (var gridInventory in controller.CubeGrid.Inventories)
                    {
                        amount = TryAddToInventory(gridInventory.GetInventory(), amount, newObject, item.Id);
                        if (amount <= Double.Epsilon)
                        {
                            break;
                        }
                    }
                }

                if (amount > 0)
                {
                    MyFloatingObjects.Spawn(item, position.Translation, position.Forward, position.Up, (int)Math.Ceiling(amount));
                    amount = 0;
                }
            }
        }
Exemple #19
0
        private float priceWorth(MyCubeBlockDefinition.Component component, string priceType)
        {
            MyBlueprintDefinitionBase bpDef = MyDefinitionManager.Static.TryGetBlueprintDefinitionByResultId(component.Definition.Id);
            int   p     = 0;
            float price = 0;

            if (priceType == "Ingot")
            {
                for (p = 0; p < bpDef.Prerequisites.Length; p++)
                {
                    if (bpDef.Prerequisites[p].Id != null)
                    {
                        MyDefinitionBase oreDef = MyDefinitionManager.Static.GetDefinition(bpDef.Prerequisites[p].Id);
                        if (oreDef != null)
                        {
                            MyPhysicalItemDefinition ore = oreDef as MyPhysicalItemDefinition;
                            float amn = Math.Abs(ore.MinimumOfferAmount);
                            amn   = (float)Math.Round(amn * 2);
                            price = price + amn;
                            //MyVisualScriptLogicProvider.SendChatMessage(bpDef.Prerequisites[p].Id.ToString() + " - " + amn.ToString() + " SC");
                        }
                    }
                }
            }
            if (priceType == "Component")
            {
                float amn = Math.Abs(component.Definition.MinimumOfferAmount);
                //MyAPIGateway.Utilities.ShowNotification(amn.ToString(), 1, "White");
                amn   = (float)Math.Round(amn * 8);
                price = price + amn;
                //MyVisualScriptLogicProvider.SendChatMessage(component.Definition.Id.ToString() + " - " + amn.ToString() + " SC");
            }

            return(price);
        }
Exemple #20
0
 public static void Spawn(MyPhysicalInventoryItem item, Vector3D position, Vector3D forward, Vector3D up, MyPhysicsComponentBase motionInheritedFrom = null, Action <MyEntity> completionCallback = null)
 {
     if (MyEntities.IsInsideWorld(position))
     {
         Vector3D vectord  = forward;
         Vector3D vectord2 = up;
         Vector3D vectord3 = Vector3D.Cross(up, forward);
         MyPhysicalItemDefinition definition = null;
         if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalItemDefinition>(item.Content.GetObjectId(), out definition))
         {
             if (definition.RotateOnSpawnX)
             {
                 vectord  = up;
                 vectord2 = -forward;
             }
             if (definition.RotateOnSpawnY)
             {
                 vectord = vectord3;
             }
             if (definition.RotateOnSpawnZ)
             {
                 vectord2 = -vectord3;
             }
         }
         Spawn(item, MatrixD.CreateWorld(position, vectord, vectord2), motionInheritedFrom, completionCallback);
     }
 }
        private void RemoveItems(IMyCubeGrid fromGrid, MyPhysicalItemDefinition itemDefinition, decimal quantity)
        {
            var terminalSystem = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(fromGrid);
            var blocks         = new List <IMyCargoContainer>();

            terminalSystem.GetBlocksOfType(blocks);

            var remaining = quantity;

            foreach (var cargoBlock in blocks.Where(b => b.CubeGrid.EntityId == fromGrid.EntityId))
            {
                var inventory = cargoBlock.GetInventory();
                var available = (decimal)inventory.GetItemAmount(itemDefinition.Id);

                if (available > remaining)
                {
                    inventory.RemoveItemsOfType((MyFixedPoint)remaining, itemDefinition.Id);
                    remaining = 0;
                }
                else
                {
                    inventory.RemoveItemsOfType((MyFixedPoint)available, itemDefinition.Id);
                    remaining -= available;
                }

                if (remaining == 0)
                {
                    return;
                }
            }
        }
Exemple #22
0
        public MyHandDrill()
        {
            NeedsUpdate = MyEntityUpdateEnum.EACH_FRAME;

            PhysicalObject = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_PhysicalGunObject>("HandDrillItem");
            m_physItemDef  = MyDefinitionManager.Static.GetPhysicalItemDefinition(new MyDefinitionId(typeof(MyObjectBuilder_PhysicalGunObject), "HandDrillItem"));
            (PositionComp as MyPositionComponent).WorldPositionChanged = WorldPositionChanged;
        }
        private Promise TransferInventory(IMyCubeGrid fromGrid, IMyCubeGrid toGrid, MyPhysicalItemDefinition itemDefinition,
                                          decimal quantity, bool fromGridIsNpc = false, bool toGridIsNpc = false)
        {
            return(new Promise((resolve, reject) =>
            {
                var payloadMass = quantity * (decimal)itemDefinition.Mass;

                if (!fromGridIsNpc)
                {
                    var fromTerminalSystem = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(fromGrid);
                    var fromBlocks = new List <IMyCargoContainer>();
                    fromTerminalSystem.GetBlocksOfType(fromBlocks);

                    var storedAmount =
                        fromBlocks
                        .Select(c => c.GetInventory())
                        .Sum(i => (decimal)i.GetItemAmount(itemDefinition.Id));
                    if (storedAmount < quantity)
                    {
                        reject(new LogicLevelException(
                                   $"Inventory lacks {quantity - storedAmount}x {itemDefinition.DisplayNameText} to sell. Inventory only has {storedAmount}."));
                        return;
                    }
                }

                if (!toGridIsNpc)
                {
                    var toTerminalSystem = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(toGrid);
                    var toBlocks = new List <IMyCargoContainer>();
                    toTerminalSystem.GetBlocksOfType(toBlocks);

                    var availableMass =
                        toBlocks
                        .Select(c => c.GetInventory())
                        .Where(i => !i.IsFull)
                        .Sum(i => (decimal)(i.MaxVolume - i.CurrentVolume));
                    if (availableMass < payloadMass)
                    {
                        reject(new LogicLevelException(
                                   $"Inventory lacks the required space to hold the payload. Required Mass: {payloadMass}, Available Mass: {availableMass}."));
                        return;
                    }
                }

                // We're clear to change inventories...
                if (!fromGridIsNpc)
                {
                    RemoveItems(fromGrid, itemDefinition, quantity);
                }
                if (!toGridIsNpc)
                {
                    AddItems(toGrid, itemDefinition, quantity);
                }

                resolve();
            }));
        }
Exemple #24
0
        // from MyGridConveyorSystem.NeedsLargeTube()
        public static bool Conveyors_ItemNeedsLargeTube(MyPhysicalItemDefinition physicalItemDefinition)
        {
            if (physicalItemDefinition.Id.TypeId == typeof(MyObjectBuilder_PhysicalGunObject))
            {
                return(false);
            }

            return(physicalItemDefinition.Size.AbsMax() > 0.25f);
        }
        public static PhysicalItemDefinition ToPhysicalItemDefinition(this MyPhysicalItemDefinition myDefinitionBase)
        {
            var result = new PhysicalItemDefinition();

            BlockDefinitionEntityBuilder.AddBaseFields(myDefinitionBase, result);
            result.Health = myDefinitionBase.Health;
            result.Mass   = myDefinitionBase.Mass;
            result.Volume = myDefinitionBase.Volume;
            result.Size   = myDefinitionBase.Size.ToPlain();
            return(result);
        }
        private static PhysicalItemDefinition GetPhysicalItemDefinition(MyPhysicalItemDefinition myDefinitionBase)
        {
            var result = new PhysicalItemDefinition();

            AddBaseFields(myDefinitionBase, result);
            result.Health = myDefinitionBase.Health;
            result.Mass   = myDefinitionBase.Mass;
            result.Volume = myDefinitionBase.Volume;
            result.Size   = myDefinitionBase.Size.ToPlain();
            return(result);
        }
        public static MyEntity Spawn(MyPhysicalItemDefinition itemDefinition, Vector3D translation, Vector3D forward, Vector3D up, int amount = 1, float scale = 1)
        {
            var objectBuilder = MyObjectBuilderSerializer.CreateNewObject(itemDefinition.Id.TypeId, itemDefinition.Id.SubtypeName) as MyObjectBuilder_PhysicalObject;

            var floatingObj = MyFloatingObjects.Spawn(
                new MyPhysicalInventoryItem((MyFixedPoint)amount, objectBuilder, scale),
                translation,
                forward,
                up);

            return(floatingObj);
        }
Exemple #28
0
        private void FormatDisplayName(StringBuilder outputBuffer, MyPhysicalInventoryItem item)
        {
            MyPhysicalItemDefinition physicalItemDefinition = MyDefinitionManager.Static.GetPhysicalItemDefinition(item.Content);

            outputBuffer.Clear().Append(physicalItemDefinition.DisplayNameText);
            if (this.Item.Amount != 1)
            {
                outputBuffer.Append(" (");
                MyGuiControlInventoryOwner.FormatItemAmount(item, outputBuffer);
                outputBuffer.Append(")");
            }
        }
        private static bool NeedsLargeTube(MyDefinitionId itemDefinitionId)
        {
            MyPhysicalItemDefinition itemDef = MyDefinitionManager.Static.GetPhysicalItemDefinition(itemDefinitionId);

            // A bit hacky but in this case better than adding something to the definitions
            if (itemDefinitionId.TypeId == typeof(MyObjectBuilder_PhysicalGunObject))
            {
                return(false);
            }

            return(itemDef.Size.AbsMax() > 0.25f);
        }
        /// <summary>
        ///     Change model for specified definition.
        /// </summary>
        /// <param name="definition">The definition where the model should be changed.</param>
        /// <param name="modelPath">The path to the model relative to game path.</param>
        private void ChangeModel(MyPhysicalItemDefinition definition, string modelPath)
        {
            if (definition?.Model != null)
            {
                if (!_replacedModels.ContainsKey(definition))
                {
                    _replacedModels.Add(definition, definition.Model);
                }

                definition.Model = modelPath;
                MyLog.Default.WriteLineAndConsole($"{definition.Id} -> {modelPath}");
            }
        }