Пример #1
0
        private static double TryAddToInventory(MyInventory inventory, double amount, MyObjectBuilder_Base newObject, MyDefinitionId itemId)
        {
            var remaining = 0D;

            if (amount > 1)
            {
                for (var i = 0; i < amount; i++)
                {
                    if (!inventory.CanItemsBeAdded(1, itemId) || !inventory.AddItems(1, newObject))
                    {
                        remaining = amount - i;
                        break;
                    }
                }
            }
            else
            {
                if (!inventory.CanItemsBeAdded(1, itemId) || !inventory.AddItems((MyFixedPoint)amount, newObject))
                {
                    remaining = amount;
                }
            }

            return(remaining);
        }
Пример #2
0
        private static void TransferItemsInternal(MyInventory src, MyInventory dst, uint itemId, bool spawn, int destItemIndex, MyFixedPoint amount)
        {
            Debug.Assert(Sync.IsServer);
            MyFixedPoint remove = amount;

            var srcItem = src.GetItemByID(itemId);

            if (!srcItem.HasValue)
            {
                return;
            }

            FixTransferAmount(src, dst, srcItem, spawn, ref remove, ref amount);

            if (amount != 0)
            {
                if (dst.AddItems(amount, srcItem.Value.Content, destItemIndex))
                {
                    if (remove != 0)
                    {
                        src.RemoveItems(itemId, remove);
                    }
                }
            }
        }
Пример #3
0
        private static void AddItemToLootBag(MyEntity itemOwner, MyPhysicalInventoryItem item, ref MyEntity lootBagEntity)
        {
            MyLootBagDefinition lootBagDefinition = MyDefinitionManager.Static.GetLootBagDefinition();

            if (lootBagDefinition != null)
            {
                MyDefinitionBase itemDefinition = item.GetItemDefinition();
                if (itemDefinition != null)
                {
                    if ((lootBagEntity == null) && (lootBagDefinition.SearchRadius > 0f))
                    {
                        Vector3D        position         = itemOwner.PositionComp.GetPosition();
                        BoundingSphereD boundingSphere   = new BoundingSphereD(position, (double)lootBagDefinition.SearchRadius);
                        List <MyEntity> entitiesInSphere = MyEntities.GetEntitiesInSphere(ref boundingSphere);
                        double          maxValue         = double.MaxValue;
                        foreach (MyEntity entity in entitiesInSphere)
                        {
                            if (entity.MarkedForClose)
                            {
                                continue;
                            }
                            if ((entity.GetType() == typeof(MyEntity)) && ((entity.DefinitionId != null) && (entity.DefinitionId.Value == lootBagDefinition.ContainerDefinition)))
                            {
                                double num2 = (entity.PositionComp.GetPosition() - position).LengthSquared();
                                if (num2 < maxValue)
                                {
                                    lootBagEntity = entity;
                                    maxValue      = num2;
                                }
                            }
                        }
                        entitiesInSphere.Clear();
                    }
                    if ((lootBagEntity == null) || (lootBagEntity.Components.Has <MyInventoryBase>() && !(lootBagEntity.Components.Get <MyInventoryBase>() as MyInventory).CanItemsBeAdded(item.Amount, itemDefinition.Id)))
                    {
                        MyContainerDefinition definition2;
                        lootBagEntity = null;
                        if (MyComponentContainerExtension.TryGetContainerDefinition(lootBagDefinition.ContainerDefinition.TypeId, lootBagDefinition.ContainerDefinition.SubtypeId, out definition2))
                        {
                            lootBagEntity = SpawnBagAround(itemOwner, definition2, 3, 2, 5, 1f);
                        }
                    }
                    if (lootBagEntity != null)
                    {
                        MyInventory inventory = lootBagEntity.Components.Get <MyInventoryBase>() as MyInventory;
                        if (inventory != null)
                        {
                            if (itemDefinition is MyCubeBlockDefinition)
                            {
                                inventory.AddBlocks(itemDefinition as MyCubeBlockDefinition, item.Amount);
                            }
                            else
                            {
                                inventory.AddItems(item.Amount, item.Content);
                            }
                        }
                    }
                }
            }
        }
Пример #4
0
        private void ReloadIce(MyEntity gun, SerializableDefinitionId ammo)
        {
            var         cGun = gun;
            MyInventory inv  = cGun.GetInventory(0);

            VRage.MyFixedPoint point = inv.GetItemAmount(ammo, MyItemFlags.None | MyItemFlags.Damaged);

            if (point.RawValue > 1000000)
            {
                return;
            }
            //inv.Clear();
            VRage.MyFixedPoint amount = new VRage.MyFixedPoint();
            amount.RawValue = 2000000;

            MyObjectBuilder_InventoryItem ii = new MyObjectBuilder_InventoryItem()
            {
                Amount  = 100,
                Content = new MyObjectBuilder_Ore()
                {
                    SubtypeName = ammo.SubtypeName
                }
            };

            inv.AddItems(amount, ii.Content);
        }
        private static void SpawnIntoContainer_Implementation(long amount, SerializableDefinitionId item, long entityId, long playerId)
        {
            if (!MyEventContext.Current.IsLocallyInvoked && !MySession.Static.HasPlayerCreativeRights(MyEventContext.Current.Sender.Value))
            {
                MyEventContext.ValidationFailed();
                return;
            }

            MyEntity entity;

            if (!MyEntities.TryGetEntityById(entityId, out entity))
            {
                return;
            }

            if (!entity.HasInventory || !((MyTerminalBlock)entity).HasPlayerAccess(playerId))
            {
                return;
            }

            MyInventory inventory = entity.GetInventory();

            if (!inventory.CheckConstraint(item))
            {
                return;
            }

            MyFixedPoint itemAmt = (MyFixedPoint)Math.Min(amount, (decimal)inventory.ComputeAmountThatFits(item));

            inventory.AddItems(itemAmt, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item));
        }
        public void ReplaceInventoryItem <TOld, TNew>(MyInventory inventory, string oldSubTypeName, int oldCount, string newSubTypeName, int newCount)
            where TOld : MyObjectBuilder_Base, new()
            where TNew : MyObjectBuilder_Base, new()
        {
            var oldBuilder   = MyObjectBuilderSerializer.CreateNewObject <TOld>(oldSubTypeName);
            var existingItem = inventory.FindItem(oldBuilder.GetId());

            if (existingItem == null)
            {
                this.messageLogger.LogMessage($"Existing Item ({typeof(TOld)} - {oldSubTypeName}) not found in inventory so no replacement will be done");
                return;
            }

            var removed = inventory.Remove(existingItem, oldCount);

            if (!removed)
            {
                this.messageLogger.LogMessage($"Removing {oldCount} of {typeof(TOld)} - {oldSubTypeName} could not be done so no replacement will be done");
                return;
            }
            this.messageLogger.LogMessage($"Removing {oldCount} of {typeof(TOld)} - {oldSubTypeName} was done successfully");

            var newBuilder = MyObjectBuilderSerializer.CreateNewObject <TNew>(newSubTypeName);
            var added      = inventory.AddItems(newCount, newBuilder);

            this.messageLogger.LogMessage($"Adding {newCount} of {typeof(TNew)} - {newSubTypeName} was{(!added ? " NOT" : String.Empty)} done successfully");
        }
Пример #7
0
        public void SpawnRandomCargo()
        {
            if (m_containerType == null)
            {
                return;
            }

            MyContainerTypeDefinition containerDefinition = MyDefinitionManager.Static.GetContainerTypeDefinition(m_containerType);

            if (containerDefinition != null && containerDefinition.Items.Count() > 0)
            {
                int itemNumber = MyUtils.GetRandomInt(containerDefinition.CountMin, containerDefinition.CountMax);
                for (int i = 0; i < itemNumber; ++i)
                {
                    MyContainerTypeDefinition.ContainerTypeItem item = containerDefinition.SelectNextRandomItem();
                    MyFixedPoint amount = (MyFixedPoint)MyRandom.Instance.NextFloat((float)item.AmountMin, (float)item.AmountMax);

                    if (MyDefinitionManager.Static.GetPhysicalItemDefinition(item.DefinitionId).HasIntegralAmounts)
                    {
                        amount = MyFixedPoint.Ceiling(amount); // Use ceiling to avoid amounts equal to 0
                    }

                    amount = MyFixedPoint.Min(m_inventory.ComputeAmountThatFits(item.DefinitionId), amount);
                    if (amount > 0)
                    {
                        var inventoryItem = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.DefinitionId);
                        m_inventory.AddItems(amount, inventoryItem);
                    }
                }
                containerDefinition.DeselectAll();
            }
        }
Пример #8
0
        private void Reload(MyEntity gun, SerializableDefinitionId ammo, bool reactor = false)
        {
            var         cGun = gun;
            MyInventory inv  = cGun.GetInventory(0);

            VRage.MyFixedPoint amount = new VRage.MyFixedPoint();
            amount.RawValue = 2000000;
            var hasEnough = inv.ContainItems(amount, new MyObjectBuilder_Ingot()
            {
                SubtypeName = ammo.SubtypeName
            });

            VRage.MyFixedPoint point = inv.GetItemAmount(ammo, MyItemFlags.None | MyItemFlags.Damaged);

            if (hasEnough)
            {
                return;
            }
            //inv.Clear();

            Logger.Debug(ammo.SubtypeName + " [ReloadGuns] Amount " + amount);
            MyObjectBuilder_InventoryItem ii;

            if (reactor)
            {
                Logger.Debug(ammo.SubtypeName + " [ReloadGuns] loading reactor " + point.RawValue);
                ii = new MyObjectBuilder_InventoryItem()
                {
                    Amount  = 10,
                    Content = new MyObjectBuilder_Ingot()
                    {
                        SubtypeName = ammo.SubtypeName
                    }
                };
                Logger.Debug(ammo.SubtypeName + " [ReloadGuns] loading reactor 2 " + point.RawValue);
            }
            else
            {
                Logger.Debug(ammo.SubtypeName + " [ReloadGuns] loading guns " + point.RawValue);
                ii = new MyObjectBuilder_InventoryItem()
                {
                    Amount  = 4,
                    Content = new MyObjectBuilder_AmmoMagazine()
                    {
                        SubtypeName = ammo.SubtypeName
                    }
                };
                Logger.Debug(ammo.SubtypeName + " [ReloadGuns] loading guns 2 " + point.RawValue);
            }
            //inv.
            Logger.Debug(amount + " Amount : content " + ii.Content);
            inv.AddItems(amount, ii.Content);


            point = inv.GetItemAmount(ammo, MyItemFlags.None | MyItemFlags.Damaged);
        }
Пример #9
0
 private void MeltGrids(IEnumerable <IMyCubeGrid> grids)
 {
     foreach (var grid in grids)
     {
         var ingotsWanted = grid.CalculateIngotCost();
         foreach (var entry in ingotsWanted)
         {
             var ingotBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ingot>(entry.Key.SubtypeName);
             furnaceOutput.AddItems(entry.Value * FractionOfMaterialsReturnedFromFurnace, ingotBuilder);
         }
         grid.CloseAll();
     }
 }
Пример #10
0
        private void Reload(MyEntity gun, SerializableDefinitionId ammo, bool reactor = false)
        {
            var         cGun = gun;
            MyInventory inv  = cGun.GetInventory(0);

            VRage.MyFixedPoint point = inv.GetItemAmount(ammo, MyItemFlags.None | MyItemFlags.Damaged);

            if (point.RawValue > 1000000)
            {
                return;
            }
            //inv.Clear();
            VRage.MyFixedPoint amount = new VRage.MyFixedPoint();
            amount.RawValue = 2000000;
            Util.GetInstance().Log(ammo.SubtypeName + " [ReloadGuns] Amount " + amount, logPath);
            MyObjectBuilder_InventoryItem ii;

            if (reactor)
            {
                Util.GetInstance().Log(ammo.SubtypeName + " [ReloadGuns] loading reactor " + point.RawValue, "ItemManager.txt");
                ii = new MyObjectBuilder_InventoryItem()
                {
                    Amount  = 10,
                    Content = new MyObjectBuilder_Ingot()
                    {
                        SubtypeName = ammo.SubtypeName
                    }
                };
                Util.GetInstance().Log(ammo.SubtypeName + " [ReloadGuns] loading reactor 2 " + point.RawValue, "ItemManager.txt");
            }
            else
            {
                Util.GetInstance().Log(ammo.SubtypeName + " [ReloadGuns] loading guns " + point.RawValue, "ItemManager.txt");
                ii = new MyObjectBuilder_InventoryItem()
                {
                    Amount  = 4,
                    Content = new MyObjectBuilder_AmmoMagazine()
                    {
                        SubtypeName = ammo.SubtypeName
                    }
                };
                Util.GetInstance().Log(ammo.SubtypeName + " [ReloadGuns] loading guns 2 " + point.RawValue, "ItemManager.txt");
            }
            //inv.
            Util.GetInstance().Log(amount + " Amount : content " + ii.Content, "ItemManager.txt");
            inv.AddItems(amount, ii.Content);


            point = inv.GetItemAmount(ammo, MyItemFlags.None | MyItemFlags.Damaged);
        }
Пример #11
0
        private void ProcessScrap(MyFixedPoint scrapAmount)
        {
            scrapIn.RemoveItemsOfType(scrapAmount, scrapMetal);
            var componentType = IronComponent.GenerateComponent(random);
            var amountToMake  = (int)(scrapAmount.ToIntSafe() / componentType.IronValue);

            if (amountToMake == 0)
            {
                return;
            }

            PlayRandomAudio(CalAudioClip.ThisIsGoodScrap, CalAudioClip.WhereDoYouGetScrapMetal, CalAudioClip.BestCustomer);
            output.AddItems(amountToMake, componentType.ObjectBuilder);
        }
Пример #12
0
        /// <summary>
        /// Converts voxel material to ore material and puts it into the inventory. If there is no
        /// corresponding ore for given voxel type, nothing happens.
        /// </summary>
        private bool TryHarvestOreMaterial(MyVoxelMaterialDefinition material, Vector3 hitPosition, int removedAmount, bool onlyCheck)
        {
            if (string.IsNullOrEmpty(material.MinedOre))
            {
                return(false);
            }

            //Do one frame heatup only in singleplayer, lag will solve it in multiplayer
            if (InitialHeatup())
            {
                return(true);
            }

            if (!onlyCheck)
            {
                ProfilerShort.Begin("TryHarvestOreMaterial");
                var oreObjBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>(material.MinedOre);
                oreObjBuilder.MaterialTypeName = material.Id.SubtypeId;
                float amountCubicMeters = (float)(((float)removedAmount / (float)MyVoxelConstants.VOXEL_CONTENT_FULL) * MyVoxelConstants.VOXEL_VOLUME_IN_METERS * VoxelHarvestRatio);
                amountCubicMeters *= (float)material.MinedOreRatio;

                if (!MySession.Static.AmountMined.ContainsKey(material.MinedOre))
                {
                    MySession.Static.AmountMined[material.MinedOre] = 0;
                }
                MySession.Static.AmountMined[material.MinedOre] += (MyFixedPoint)amountCubicMeters;

                float maxDropCubicMeters = MyDrillConstants.MAX_DROP_CUBIC_METERS;

                var          physItem          = MyDefinitionManager.Static.GetPhysicalItemDefinition(oreObjBuilder);
                MyFixedPoint amountInItemCount = (MyFixedPoint)(amountCubicMeters / physItem.Volume);
                MyFixedPoint maxAmountPerDrop  = (MyFixedPoint)(maxDropCubicMeters / physItem.Volume);

                if (OutputInventory != null)
                {
                    MyFixedPoint amountDropped = amountInItemCount * (1 - m_inventoryCollectionRatio);
                    amountDropped = MyFixedPoint.Min(maxAmountPerDrop * 10 - (MyFixedPoint)0.001, amountDropped);
                    MyFixedPoint inventoryAmount = (amountInItemCount * m_inventoryCollectionRatio) - amountDropped;
                    OutputInventory.AddItems(inventoryAmount, oreObjBuilder);
                    SpawnOrePieces(amountDropped, maxAmountPerDrop, hitPosition, oreObjBuilder, material);
                }
                else
                {
                    SpawnOrePieces(amountInItemCount, maxAmountPerDrop, hitPosition, oreObjBuilder, material);
                }
                ProfilerShort.End();
            }

            return(true);
        }
Пример #13
0
        private void TransferFromItem(MyObjectBuilder_PhysicalObject item, int count)
        {
            MyInventory targetInventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory();

            if (targetInventory.CanItemsBeAdded(count, item.GetId()))
            {
                targetInventory.AddItems(count, item);
                return;
            }

            var inventoryItem = new MyPhysicalInventoryItem(count, item);

            MyFloatingObjects.Spawn(inventoryItem, Vector3D.Transform(m_targetBlock.Position * m_targetBlock.CubeGrid.GridSize,
                                                                      m_targetBlock.CubeGrid.WorldMatrix), m_targetBlock.CubeGrid.WorldMatrix.Forward, m_targetBlock.CubeGrid.WorldMatrix.Up);
        }
        private static bool FillInventoryWithIron()
        {
            IMyInventoryOwner invObject = MySession.ControlledEntity as IMyInventoryOwner;

            if (invObject != null)
            {
                MyFixedPoint amount = 20000;

                var         oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Iron");
                MyInventory inventory  = invObject.GetInventory(0);
                amount = inventory.ComputeAmountThatFits(oreBuilder.GetId());

                inventory.AddItems(amount, oreBuilder);
            }

            return(true);
        }
        private static bool FillInventoryWithIron()
        {
            var invObject = MySession.Static.ControlledEntity as MyEntity;

            if (invObject != null && invObject.HasInventory)
            {
                MyFixedPoint amount = 20000;

                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Iron");
                System.Diagnostics.Debug.Assert(invObject.GetInventory(0) as MyInventory != null, "Null or unexpected inventory type returned!");
                MyInventory inventory = invObject.GetInventory(0) as MyInventory;
                amount = inventory.ComputeAmountThatFits(oreBuilder.GetId());

                inventory.AddItems(amount, oreBuilder);
            }

            return(true);
        }
 public bool AddItems(MyInventory inventory, MyObjectBuilder_PhysicalObject obj, bool overrideCheck, MyFixedPoint amount)
 {
     if (overrideCheck || !inventory.ContainItems(amount, obj))
     {
         if (inventory.CanItemsBeAdded(amount, obj.GetId()))
         {
             inventory.AddItems(amount, obj);
             return(true);
         }
         else
         {
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
Пример #17
0
        internal static void PlaceItemIntoCargo(MyInventory inventory, MyObjectBuilder_Base cargoitem, int amount)
        {
            if (inventory == null)
            {
                return;
            }
            bool bPlaced = false;

            do
            {
                bPlaced = inventory.AddItems(amount, cargoitem);
                if (!bPlaced)
                {
                    //                            MyLog.Default.WriteLine("LoadCargo: Does not fit-" + amount.ToString() + " "+cargo.GetDisplayName());
                    amount /= 2; // reduce size until it fits
                }
                if (amount < 3)
                {
                    bPlaced = true;             // force to true if it gets too small
                }
            } while (!bPlaced);
        }
Пример #18
0
        private void ConsumeFuel(int timeDelta)
        {
            RefreshRemainingCapacity();
            if (!HasCapacityRemaining)
            {
                return;
            }
            if (CurrentPowerOutput == 0.0f)
            {
                return;
            }

            float consumptionPerMillisecond = CurrentPowerOutput / (60 * 60 * 1000);

            consumptionPerMillisecond /= m_reactorDefinition.FuelDefinition.Mass; // Convert weight to number of items

            MyFixedPoint consumedFuel = (MyFixedPoint)(timeDelta * consumptionPerMillisecond);

            if (consumedFuel == 0)
            {
                consumedFuel = MyFixedPoint.SmallestPossibleValue;
            }

            if (m_inventory.ContainItems(consumedFuel, m_reactorDefinition.FuelId))
            {
                m_inventory.RemoveItemsOfType(consumedFuel, m_reactorDefinition.FuelId);
            }
            else if (MyFakes.ENABLE_INFINITE_REACTOR_FUEL)
            {
                m_inventory.AddItems((MyFixedPoint)(200 / m_reactorDefinition.FuelDefinition.Mass), m_reactorDefinition.FuelItem);
            }
            else
            {
                var amountAvailable = m_inventory.GetItemAmount(m_reactorDefinition.FuelId);
                m_inventory.RemoveItemsOfType(amountAvailable, m_reactorDefinition.FuelId);
            }

            //RefreshRemainingCapacity();
        }
Пример #19
0
        public static void AddItemsToInventory(MyInventory inventory, MyDefinitionId itemId, float amount = -1)
        {
            var itemDef = GetItemDefinition(itemId);

            if (itemDef == null)
            {
                return;
            }

            float freeSpace   = (float)(inventory.MaxVolume - inventory.CurrentVolume);
            var   amountToAdd = Math.Floor(freeSpace / itemDef.Volume);

            if (amountToAdd > amount && amount > -1)
            {
                var adjustedAmt = amountToAdd - amount;
                amountToAdd = adjustedAmt;
            }

            if (amountToAdd > 0 && inventory.CanItemsBeAdded((MyFixedPoint)amountToAdd, itemId) == true)
            {
                inventory.AddItems((MyFixedPoint)amountToAdd, MyObjectBuilderSerializer.CreateNewObject(itemId));
            }
        }
Пример #20
0
        void confirmButton_OnButtonClick(MyGuiControlButton sender)
        {
            IMyInventoryOwner invObject = MySession.ControlledEntity as IMyInventoryOwner;

            if (invObject != null)
            {
                double amountDec = 0;
                double.TryParse(m_amountTextbox.Text, out amountDec);

                MyFixedPoint amount = (MyFixedPoint)amountDec;

                var         itemId    = m_physicalItemDefinitions[(int)m_items.GetSelectedKey()].Id;
                MyInventory inventory = invObject.GetInventory(0);
                if (!MySession.Static.CreativeMode)
                {
                    amount = MyFixedPoint.Min(inventory.ComputeAmountThatFits(itemId), amount);
                }

                var builder = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(itemId);
                inventory.AddItems(amount, builder);
            }

            CloseScreen();
        }
Пример #21
0
        public void MoveUnneededItemsFromConstructionStockpile(MyInventory toInventory)
        {
            if (m_stockpile == null) return;

            Debug.Assert(toInventory != null);
            if (toInventory == null) return;

            m_tmpItemList.Clear();
            AcquireUnneededStockpileItems(m_tmpItemList);
            m_stockpile.ClearSyncList();

            foreach (var item in m_tmpItemList)
            {
                var amount = (int)toInventory.ComputeAmountThatFits(item.Content.GetId());
                amount = Math.Min(amount, item.Amount);
                toInventory.AddItems(amount, item.Content);
                m_stockpile.RemoveItems(amount, item.Content);
            }
            CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList());
            m_stockpile.ClearSyncList();
        }
Пример #22
0
        /// <summary>
        /// Moves items with the given flags from the construction inventory to the character.
        /// If the flags are None, all items are moved.
        /// </summary>
        public void MoveItemsFromConstructionStockpile(MyInventory toInventory, MyItemFlags flags = MyItemFlags.None)
        {
            if (m_stockpile == null) return;

            Debug.Assert(toInventory != null);
            if (toInventory == null) return;

            m_tmpItemList.Clear();
            foreach (var item in m_stockpile.GetItems())
            {
                if (flags == MyItemFlags.None || (item.Content.Flags & flags) != 0)
                    m_tmpItemList.Add(item);
            }
            m_stockpile.ClearSyncList();
            foreach (var item in m_tmpItemList)
            {
                var amount = (int)toInventory.ComputeAmountThatFits(item.Content.GetId());
                amount = Math.Min(amount, item.Amount);
                toInventory.AddItems(amount, item.Content);
                m_stockpile.RemoveItems(amount, item.Content);
            }
            CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList());
            m_stockpile.ClearSyncList();
        }
 public bool AddItems(MyInventory inventory, MyObjectBuilder_PhysicalObject obj, bool overrideCheck, MyFixedPoint amount)
 {
     if (overrideCheck || !inventory.ContainItems(amount, obj))
     {
         if (inventory.CanItemsBeAdded(amount, obj.GetId()))
         {
             inventory.AddItems(amount, obj);
             return true;
         }
         else
         {
             return false;
         }
     }
     else
     {
         return false;
     }
 }
Пример #24
0
        /// <summary>
        /// Add the given inventory item to loot bag. If loot bag does not exist then it will be created.
        /// </summary>
        private static void AddItemToLootBag(MyEntity itemOwner, MyPhysicalInventoryItem item, ref MyEntity lootBagEntity)
        {
            Debug.Assert(Sandbox.Game.Multiplayer.Sync.IsServer);

            var lootBagDefinition = MyDefinitionManager.Static.GetLootBagDefinition();

            Debug.Assert(lootBagDefinition != null, "Loot bag not definined");
            if (lootBagDefinition == null)
            {
                return;
            }

            // Block
            MyDefinitionBase itemDefinition = item.GetItemDefinition();

            Debug.Assert(itemDefinition != null, "Unknown inventory item");
            if (itemDefinition == null)
            {
                return;
            }

            // Find lootbag nearby.
            if (lootBagEntity == null && lootBagDefinition.SearchRadius > 0)
            {
                Vector3D        itemOwnerPosition = itemOwner.PositionComp.GetPosition();
                BoundingSphereD sphere            = new BoundingSphereD(itemOwnerPosition, lootBagDefinition.SearchRadius);
                var             entitiesInSphere  = MyEntities.GetEntitiesInSphere(ref sphere);
                double          minDistanceSq     = double.MaxValue;
                foreach (var entity in entitiesInSphere)
                {
                    if (!entity.MarkedForClose && (entity.GetType() == typeof(MyEntity)))
                    {
                        if (entity.DefinitionId != null && entity.DefinitionId.Value == lootBagDefinition.ContainerDefinition)
                        {
                            var distanceSq = (entity.PositionComp.GetPosition() - itemOwnerPosition).LengthSquared();
                            if (distanceSq < minDistanceSq)
                            {
                                lootBagEntity = entity;
                                minDistanceSq = distanceSq;
                            }
                        }
                    }
                }
                entitiesInSphere.Clear();
            }

            // Create lootbag
            if (lootBagEntity == null ||
                (lootBagEntity.Components.Has <MyInventoryBase>() && !(lootBagEntity.Components.Get <MyInventoryBase>() as MyInventory).CanItemsBeAdded(item.Amount, itemDefinition.Id)))
            {
                lootBagEntity = null;
                MyContainerDefinition lootBagDef;
                if (MyComponentContainerExtension.TryGetContainerDefinition(lootBagDefinition.ContainerDefinition.TypeId, lootBagDefinition.ContainerDefinition.SubtypeId, out lootBagDef))
                {
                    lootBagEntity = SpawnBagAround(itemOwner, lootBagDef);
                }
            }

            Debug.Assert(lootBagEntity != null, "Loot bag not created");

            // Fill lootbag inventory
            if (lootBagEntity != null)
            {
                MyInventory inventory = lootBagEntity.Components.Get <MyInventoryBase>() as MyInventory;
                Debug.Assert(inventory != null);
                if (inventory != null)
                {
                    if (itemDefinition is MyCubeBlockDefinition)
                    {
                        inventory.AddBlocks(itemDefinition as MyCubeBlockDefinition, item.Amount);
                    }
                    else
                    {
                        inventory.AddItems(item.Amount, item.Content);
                    }
                }
            }
        }
Пример #25
0
        private static void TransferItemsInternal(MyInventory src, MyInventory dst, uint itemId, bool spawn, int destItemIndex, MyFixedPoint amount)
        {
            Debug.Assert(Sync.IsServer);
            MyFixedPoint remove = amount;

            var srcItem = src.GetItemByID(itemId);
            if (!srcItem.HasValue) return;

            FixTransferAmount(src, dst, srcItem, spawn, ref remove, ref amount);

            if (remove != 0)
                src.RemoveItems(itemId, remove);

            if (amount != 0)
                dst.AddItems(amount, srcItem.Value.Content, destItemIndex);
        }
        public override bool HandleInput()
        {
            bool handled = false;

            if (m_gridDebugInfo)
            {
                LineD      line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 1000);
                MyCubeGrid grid;
                Vector3I   cubePos;
                double     distance;
                if (MyCubeGrid.GetLineIntersection(ref line, out grid, out cubePos, out distance))
                {
                    var gridMatrix = grid.WorldMatrix;
                    var boxMatrix  = Matrix.CreateTranslation(cubePos * grid.GridSize) * gridMatrix;
                    var block      = grid.GetCubeBlock(cubePos);

                    MyRenderProxy.DebugDrawText2D(new Vector2(), cubePos.ToString(), Color.White, 0.7f);
                    MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(new Vector3(grid.GridSize) + new Vector3(0.15f)) * boxMatrix, Color.Red.ToVector3(), 0.2f, true, true);

                    //int[, ,] bones = grid.Skeleton.AddCubeBones(cubePos);

                    //Vector3 closestBone = Vector3.Zero;
                    //Vector3I closestPoint = Vector3I.Zero;
                    //float closestPointDist = float.MaxValue;
                    //int closestBoneIndex = 0;

                    //for (int x = -1; x <= 1; x += 1)
                    //{
                    //    for (int y = -1; y <= 1; y += 1)
                    //    {
                    //        for (int z = -1; z <= 1; z += 1)
                    //        {
                    //            int boneIndex = bones[x + 1, y + 1, z + 1];
                    //            Vector3 bone = grid.Skeleton[boneIndex];

                    //            var pos = boxMatrix.Translation + new Vector3(grid.GridSize / 2) * new Vector3(x, y, z);
                    //            //MyRenderProxy.DebugDrawSphere(pos, 0.2f, Color.Blue.ToVector3(), 1.0f, false);
                    //            MyRenderProxy.DebugDrawText3D(pos, String.Format("{0:G2}, {1:G2}, {2:G2}", bone.X, bone.Y, bone.Z), Color.White, 0.5f, false);

                    //            var dist = MyUtils.GetPointLineDistance(ref line, ref pos);
                    //            if (dist < closestPointDist)
                    //            {
                    //                closestPointDist = dist;
                    //                closestPoint = new Vector3I(x, y, z);
                    //                closestBoneIndex = boneIndex;
                    //                closestBone = bone;

                    //            }
                    //        }
                    //    }
                    //}

                    //MyRenderProxy.DebugDrawText3D(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f, String.Format("{0:G2}, {1:G2}, {2:G2}", closestBone.X, closestBone.Y, closestBone.Z), Color.Red, 0.5f, false);
                    //var bonePos = grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]];
                    //MyRenderProxy.DebugDrawSphere(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f + bonePos, 0.5f, Color.Red.ToVector3(), 0.4f, true, true);

                    //if (input.IsNewKeyPressed(Keys.P) && block != null)
                    //{
                    //    if (input.IsAnyShiftKeyPressed())
                    //    {
                    //        grid.ResetBlockSkeleton(block);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]] = Vector3.Zero;
                    //        grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //        //grid.SetBlockDirty(block);
                    //    }
                    //    handled = true;
                    //}

                    //// Move bones to center by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemOpenBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    grid.Skeleton[index] -= Vector3.Sign(grid.Skeleton[index]) * 0.1f;
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}

                    //// Reduce max offset by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemCloseBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    var old = Vector3.Abs(grid.Skeleton[index]);
                    //    var max = new Vector3(Math.Max(Math.Max(old.X, old.Y), old.Z));
                    //    if (max.X > 0.1f)
                    //    {
                    //        grid.Skeleton[index] = Vector3.Clamp(grid.Skeleton[index], -max + 0.1f, max - 0.1f);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[index] = Vector3.Zero;
                    //    }
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}
                }
            }

            if (MyInput.Static.IsAnyAltKeyPressed())
            {
                return(handled);
            }

            bool shift = MyInput.Static.IsAnyShiftKeyPressed();
            bool ctrl  = MyInput.Static.IsAnyCtrlKeyPressed();

            //if (input.IsNewKeyPressed(Keys.I))
            //{
            //    foreach (var grid in MyEntities.GetEntities().OfType<MyCubeGrid>())
            //    {
            //        foreach (var block in grid.GetBlocks().ToArray())
            //        {
            //            grid.DetectMerge(block.Min, block.Max);
            //        }
            //    }
            //    handled = true;
            //}

            // Disabled since it is common to have normal control bound to O key.
            // If you ever need this again, bind it to something more complicated, like key combination.
            //if (input.IsNewKeyPressed(Keys.O))
            //{
            //    m_gridDebugInfo = !m_gridDebugInfo;
            //    handled = true;
            //}

            //for (int i = 0; i <= 9; i++)
            //{
            //    if (MyInput.Static.IsNewKeyPressed((Keys)(((int)Keys.D0) + i)))
            //    {
            //        string name = "Slot" + i.ToString();
            //        if (ctrl)
            //        {
            //            MySession.Static.Name = name;
            //            MySession.Static.WorldID = MySession.Static.GetNewWorldId();
            //            MySession.Static.Save(name);
            //        }
            //        else if (shift)
            //        {
            //            var path = MyLocalCache.GetSessionSavesPath(name, false, false);
            //            if (System.IO.Directory.Exists(path))
            //            {
            //                MySession.Static.Unload();
            //                MySession.Static.Load(path);
            //            }
            //        }
            //        handled = true;
            //    }
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.End))
            //{
            //    MyMeteorShower.MeteorWave(null);
            //}

            // Disabled for god sake!
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageUp) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = true;
            //}
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageDown) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = false;
            //}

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad6))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv  = Matrix.Invert(view);

                //MyPhysicalInventoryItem item = new MyPhysicalInventoryItem(100,
                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                var item       = new MyPhysicalInventoryItem(1, oreBuilder);
                var obj        = MyFloatingObjects.Spawn(item, inv.Translation + inv.Forward * 1.0f, inv.Forward, inv.Up);
                obj.Physics.LinearVelocity = inv.Forward * 50;
            }

            if (false && MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                List <HkShape>       trShapes = new List <HkShape>();
                List <HkConvexShape> shapes   = new List <HkConvexShape>();
                List <Matrix>        matrices = new List <Matrix>();

                var         grid = new HkGridShape(2.5f, HkReferencePolicy.None);
                const short size = 50;
                for (short x = 0; x < size; x++)
                {
                    for (short y = 0; y < size; y++)
                    {
                        for (short z = 0; z < size; z++)
                        {
                            var box = new HkBoxShape(Vector3.One);
                            grid.AddShapes(new System.Collections.Generic.List <HkShape>()
                            {
                                box
                            }, new Vector3S(x, y, z), new Vector3S(x, y, z));
                            trShapes.Add(new HkConvexTranslateShape(box, new Vector3(x, y, z), HkReferencePolicy.None));
                            shapes.Add(box);
                            matrices.Add(Matrix.CreateTranslation(new Vector3(x, y, z)));
                        }
                    }
                }

                var emptyGeom = new HkGeometry(new List <Vector3>(), new List <int>());

                var list         = new HkListShape(trShapes.ToArray(), trShapes.Count, HkReferencePolicy.None);
                var compressedBv = new HkBvCompressedMeshShape(emptyGeom, shapes, matrices, HkWeldingType.None);
                var mopp         = new HkMoppBvTreeShape(list, HkReferencePolicy.None);

                HkShapeBuffer buf = new HkShapeBuffer();

                //HkShapeContainerIterator i = compressedBv.GetIterator(buf);
                //int count = 0; // will be 125000
                //while (i.IsValid)
                //{
                //    count++;
                //    i.Next();
                //}

                buf.Dispose();
                var info = new HkRigidBodyCinfo();
                info.Mass = 10;
                info.CalculateBoxInertiaTensor(Vector3.One, 10);
                info.MotionType  = HkMotionType.Dynamic;
                info.QualityType = HkCollidableQualityType.Moving;
                info.Shape       = compressedBv;
                var body = new HkRigidBody(info);

                //MyPhysics.HavokWorld.AddRigidBody(body);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad7))
            {
                foreach (var g in MyEntities.GetEntities().OfType <MyCubeGrid>())
                {
                    foreach (var s in g.CubeBlocks.Select(s => s.FatBlock).Where(s => s != null).OfType <MyMotorStator>())
                    {
                        if (s.Rotor != null)
                        {
                            var q = Quaternion.CreateFromAxisAngle(s.Rotor.WorldMatrix.Up, MathHelper.ToRadians(45));
                            s.Rotor.CubeGrid.WorldMatrix = MatrixD.CreateFromQuaternion(q) * s.Rotor.CubeGrid.WorldMatrix;
                        }
                    }
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad8))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv  = Matrix.Invert(view);

                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                var obj        = new MyObjectBuilder_FloatingObject()
                {
                    Item = new MyObjectBuilder_InventoryItem()
                    {
                        PhysicalContent = oreBuilder, Amount = 1000
                    }
                };
                obj.PositionAndOrientation = new MyPositionAndOrientation(inv.Translation + 2.0f * inv.Forward, inv.Forward, inv.Up);
                obj.PersistentFlags        = MyPersistentEntityFlags2.InScene;
                var e = MyEntities.CreateFromObjectBuilderAndAdd(obj);
                e.Physics.LinearVelocity = Vector3.Normalize(inv.Forward) * 50.0f;
            }


            if (MyInput.Static.IsNewKeyPressed(MyKeys.Divide))
            {
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply))
            {
                MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW;
                MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true;

                var grids = MyEntities.GetEntities().OfType <MyCubeGrid>();
                foreach (var g in grids)
                {
                    if (!g.IsStatic)// || g.GetBlocks().Count < 800) //to compute only castle
                    {
                        continue;
                    }

                    g.CreateStructuralIntegrity();
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1))
            {
                var e = MyEntities.GetEntities().OfType <MyCubeGrid>().FirstOrDefault();
                if (e != null)
                {
                    e.Physics.RigidBody.MaxLinearVelocity = 1000;
                    if (e.Physics.RigidBody2 != null)
                    {
                        e.Physics.RigidBody2.MaxLinearVelocity = 1000;
                    }

                    e.Physics.LinearVelocity = new Vector3(1000, 0, 0);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                MyPrefabManager.Static.SpawnPrefab("respawnship", MySector.MainCamera.Position, MySector.MainCamera.ForwardVector, MySector.MainCamera.UpVector);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply) && MyInput.Static.IsAnyShiftKeyPressed())
            {
                GC.Collect(2);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                Thread.Sleep(250);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                var obj = MySession.Static.ControlledEntity != null ? MySession.Static.ControlledEntity.Entity : null;
                if (obj != null)
                {
                    const float dist = 5.0f;
                    obj.PositionComp.SetPosition(obj.PositionComp.GetPosition() + obj.WorldMatrix.Forward * dist);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad4))
            {
                MyEntity invObject = MySession.Static.ControlledEntity as MyEntity;
                if (invObject != null && invObject.HasInventory)
                {
                    MyFixedPoint amount = 20000;

                    var         oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                    MyInventory inventory  = invObject.GetInventory(0) as MyInventory;
                    System.Diagnostics.Debug.Assert(inventory != null, "Null or unexpected type returned!");
                    inventory.AddItems(amount, oreBuilder);
                }

                handled = true;
            }

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad8))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid = (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockArmorBlock";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad9))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid =  (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockGyro";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Delete))
            {
                int count = MyEntities.GetEntities().OfType <MyFloatingObject>().Count();
                foreach (var obj in MyEntities.GetEntities().OfType <MyFloatingObject>())
                {
                    if (obj == MySession.Static.ControlledEntity)
                    {
                        MySession.Static.SetCameraController(MyCameraControllerEnum.Spectator);
                    }
                    obj.Close();
                }
                handled = true;
            }

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                foreach (var obj in MyEntities.GetEntities())
                {
                    if (obj != MySession.Static.ControlledEntity && (MySession.Static.ControlledEntity == null || obj != MySession.Static.ControlledEntity.Entity.Parent) && obj != MyCubeBuilder.Static.FindClosestGrid())
                    {
                        obj.Close();
                    }
                }
                handled = true;
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9) || MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                //MyCubeGrid.UserCollisions = input.IsNewKeyPressed(Keys.NumPad9);

                var body = MySession.Static.ControlledEntity.Entity.GetTopMostParent().Physics;
                if (body.RigidBody != null)
                {
                    //body.AddForce(Engine.Physics.MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE, new Vector3(0, 0, 10 * body.Mass), null, null);
                    body.RigidBody.ApplyLinearImpulse(body.Entity.WorldMatrix.Forward * body.Mass * 2);
                }
                handled = true;
            }

            //if (input.IsNewKeyPressed(Keys.J) && input.IsAnyCtrlKeyPressed())
            //{
            //    MyGlobalInputComponent.CopyCurrentGridToClipboard();

            //    MyEntity addedEntity = MyGlobalInputComponent.PasteEntityFromClipboard();

            //    if (addedEntity != null)
            //    {
            //        Vector3 pos = addedEntity.GetPosition();
            //        pos.Z += addedEntity.WorldVolume.Radius * 1.5f;
            //        addedEntity.SetPosition(pos);
            //    }
            //    handled = true;
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.OemComma))
            {
                foreach (var e in MyEntities.GetEntities().OfType <MyFloatingObject>().ToArray())
                {
                    e.Close();
                }
            }

            return(handled);
        }
        private void TransferFromTarget(NaniteMiningItem target)
        { // Must be invoked from game thread
            IMyEntity entity;

            if (!MyAPIGateway.Entities.TryGetEntityById(target.VoxelId, out entity))
            {
                CancelTarget(target);
                return;
            }

            MyAPIGateway.Parallel.Start(() =>
            {
                try
                {
                    if (entity == null || !IsValidVoxelTarget(target, entity))
                    {
                        MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                                                                  { CancelTarget(target); });

                        return;
                    }

                    MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                    { // Invocation 0
                        try
                        {
                            var def       = MyDefinitionManager.Static.GetVoxelMaterialDefinition(target.VoxelMaterial);
                            var item      = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>(def.MinedOre);
                            var inventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory();
                            MyInventory targetInventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory();

                            if (targetInventory != null && targetInventory.CanItemsBeAdded((MyFixedPoint)(target.Amount), item.GetId()))
                            {
                                if (entity == null)
                                {
                                    CancelTarget(target);
                                    return;
                                }

                                var ownerName = targetInventory.Owner as IMyTerminalBlock;
                                if (ownerName != null)
                                {
                                    Logging.Instance.WriteLine($"[Mining] Transfer - Adding {target.Amount} {item.GetId().SubtypeName} to {ownerName.CustomName}", 1);
                                }

                                if (!targetInventory.AddItems((MyFixedPoint)(target.Amount), item))
                                {
                                    Logging.Instance.WriteLine($"Error while transferring {target.Amount} {item.GetId().SubtypeName}! Aborting mining operation.");
                                    return;
                                }

                                IMyVoxelBase voxel    = entity as IMyVoxelBase;
                                MyVoxelBase voxelBase = voxel as MyVoxelBase;

                                voxelBase.RequestVoxelOperationSphere(target.Position, 1f, target.VoxelMaterial, MyVoxelBase.OperationType.Cut);

                                AddMinedPosition(target);
                                CompleteTarget(target);
                                return;
                            }

                            Logging.Instance.WriteLine("[Mining] Mined materials could not be moved. No free cargo space (probably)!", 1);
                            CancelTarget(target);
                        }
                        catch (Exception e)
                        { Logging.Instance.WriteLine($"Exception in NaniteMiningTargets.TransferFromTarget (Invocation 0):\n{e}"); }
                    });
                }
                catch (Exception e)
                { Logging.Instance.WriteLine($"Exception in NaniteMiningTargets.TransferFromTarget:\n{e}"); }
            });
        }
Пример #28
0
        public static bool FindFreeCargo(MyCubeBlock startBlock, MyObjectBuilder_Base item, int count, bool order = true)
        {
            var list = Conveyor.GetConveyorListFromEntity(startBlock);

            if (list == null)
            {
                Logging.Instance.WriteLine(string.Format("Conveyor list is null!"));
                return(false);
            }

            if (!list.Contains(startBlock.EntityId))
            {
                list.Add(startBlock.EntityId);
            }

            List <MyInventory> inventoryList = new List <MyInventory>();

            foreach (var inventoryItem in list)
            {
                IMyEntity entity;
                if (MyAPIGateway.Entities.TryGetEntityById(inventoryItem, out entity))
                {
                    if (!(entity is IMyCubeBlock))
                    {
                        continue;
                    }

                    if (entity is Ingame.IMyRefinery || entity is Ingame.IMyAssembler)
                    {
                        continue;
                    }

                    MyCubeBlock block = (MyCubeBlock)entity;
                    if (!block.HasInventory)
                    {
                        continue;
                    }

                    if (block.EntityId == startBlock.EntityId)
                    {
                        inventoryList.Insert(0, block.GetInventory());
                    }
                    else
                    {
                        inventoryList.Add(block.GetInventory());
                    }
                }
            }

            MyInventory targetInventory = null;

            List <MyInventory> modifiedList;

            if (order)
            {
                modifiedList = inventoryList.OrderByDescending(x => (float)x.MaxVolume - (float)x.CurrentVolume).ToList();
            }
            else
            {
                modifiedList = inventoryList;
            }

            foreach (var inventoryItem in modifiedList)
            {
                targetInventory = inventoryItem;
                if (targetInventory.CanItemsBeAdded(count, item.GetId()))
                {
                    var ownerName = targetInventory.Owner as IMyTerminalBlock;
                    if (ownerName != null)
                    {
                        Logging.Instance.WriteLine(string.Format("TRANSFER Adding {0} {1} to {2}", count, item.GetId().SubtypeName, ownerName.CustomName));
                    }

                    targetInventory.AddItems(count, item);
                    return(true);
                }
            }

            return(false);
        }
Пример #29
0
        public static void OnSyncRequest(byte[] bytes)
        {
            try
            {
                Logger.Log.Debug("BeaconSecurity.OnSyncRequest() - starts");

                SyncPacket pckIn = new SyncPacket();
                string     data  = System.Text.Encoding.Unicode.GetString(bytes);
                //Logger.Log.Debug(@"*******************************\n{0}\n*******************************\n", data);
                pckIn = MyAPIGateway.Utilities.SerializeFromXML <SyncPacket>(data);
                Logger.Log.Info("OnSyncRequest COMMAND:{0}, id:{1}, entity:'{2}', steamid: {3}, isserver: {4}", Enum.GetName(typeof(Command), pckIn.command), pckIn.ownerId, pckIn.entityId, pckIn.steamId, Core.IsServer);

                if (pckIn.proto != SyncPacket.Version)
                {
                    Logger.Log.Error("Wrong version of sync protocol client [{0}] <> [{1}] server", SyncPacket.Version, pckIn.proto);
                    MyAPIGateway.Utilities.ShowNotification("同步协议版本不匹配!尝试重新启动游戏或服务器!", 5000, MyFontEnum.Red);
                    return;
                }

                switch ((Command)pckIn.command)
                {
                case Command.Redeem:
                {
                    //收到命令,给这个玩家加点东西?
                    if (Core.IsServer)
                    {
                        Logger.Log.Info("Some one with steamid={0} trying to redeem", pckIn.steamId);
                        //IMyPlayer player = Core.GetPlayer(pckIn.steamId) as IMyPlayer;
                        string msg = "返回信息";
                        MyAPIGateway.Utilities.ShowMessage(Core.MODSAY, String.Format(msg));
                        if (Core.Codes.RedeemedCodes.Contains(pckIn.message))
                        {
                            MyAPIGateway.Utilities.ShowNotification("已经兑换过了!", 2000, MyFontEnum.Green);
                            SyncPacket newpacket = new SyncPacket();
                            newpacket.proto   = SyncPacket.Version;
                            newpacket.command = (ushort)Command.MessageToChat;
                            newpacket.message = "已经兑换过了!";
                            Core.SendMessage(newpacket);         // send to others
                            return;
                            //MyAPIGateway.Utilities.ShowMessage(Core.MODSAY, String.Format("已经被兑换!"));
                            //msg = "已经被兑换!";
                        }
                        else
                        {
                            string t     = pckIn.message.Replace("-", "");
                            byte[] data2 = Base24Encoding.Default.GetBytes(t);
                            if (data2 == null)
                            {
                                return;
                            }
                            String str = System.Text.Encoding.ASCII.GetString(data2);
                            str = str.TrimStart('\0');
                            string[] sep  = { ":" };
                            string[] msgs = str.Split(sep, 4, StringSplitOptions.RemoveEmptyEntries);
                            if (msgs.Length != 4)
                            {
                                return;
                            }



                            string type = msgs[0];
                            if (type.Equals("Coin", StringComparison.OrdinalIgnoreCase))
                            {
                                var num = 0;
                                try { num = Int32.Parse(msgs[1]); } catch { }

                                if (num == 0)
                                {
                                    return;
                                }
                                var sum = 0;
                                try { sum = Int32.Parse(msgs[3]); } catch { }

                                string content = msgs[0] + ":" + msgs[1] + ":" + msgs[2];

                                var sum2 = 0;
                                foreach (char c in content)
                                {
                                    sum2 += (int)c;
                                }
                                sum2 = sum2 % 100;
                                if (sum2 != sum)
                                {
                                    //MyAPIGateway.Utilities.ShowMessage(Core.MODSAY, String.Format("兑换码错误!"));
                                    MyAPIGateway.Utilities.ShowNotification("兑换码错误!", 2000, MyFontEnum.Green);
                                    SyncPacket newpacket = new SyncPacket();
                                    newpacket.proto   = SyncPacket.Version;
                                    newpacket.command = (ushort)Command.MessageToChat;
                                    newpacket.message = "兑换码错误!";
                                    Core.SendMessage(newpacket);         // send to others
                                    return;
                                }

                                //IMyPlayer player = MyAPIGateway.Session.Player as IMyPlayer;
                                IMyPlayer player = Core.GetPlayer(pckIn.steamId) as IMyPlayer;

                                if (player == null)
                                {
                                    Logger.Log.Info("redeem player null");
                                    return;
                                }

                                MyEntity entity = player.Character.Entity as MyEntity;
                                if (entity != null && entity.HasInventory)
                                {
                                    MyInventory inventory = entity.GetInventoryBase() as MyInventory;

                                    inventory.AddItems(num, new MyObjectBuilder_Ingot {
                                            SubtypeName = "Coin"
                                        });

                                    Core.Codes.RedeemedCodes.Add(pckIn.message);

                                    Core.setCodes(Core.Codes);
                                    // Core.SendSettingsToServer(Core.Settings, pckIn.steamId);

                                    //MyAPIGateway.Utilities.ShowMessage(Core.MODSAY, String.Format("兑换成功!"));
                                    MyAPIGateway.Utilities.ShowNotification("兑换成功!", 2000, MyFontEnum.Green);
                                    SyncPacket newpacket = new SyncPacket();
                                    newpacket.proto   = SyncPacket.Version;
                                    newpacket.command = (ushort)Command.MessageToChat;
                                    newpacket.message = "兑换成功!";
                                    Core.SendMessage(newpacket);         // send to others
                                    //Core.setSettings(pckIn.settings);

                                    //// resend for all clients a new settings
                                    //SyncPacket newpacket = new SyncPacket();
                                    //newpacket.proto = SyncPacket.Version;
                                    //newpacket.request = false;
                                    //newpacket.command = (ushort)Command.SettingsSync;
                                    //newpacket.steamId = 0; // for all
                                    //newpacket.settings = Core.Settings;
                                    //Core.SendMessage(newpacket);
                                }
                            }
                        }



                        //IMyPlayer player = MyAPIGateway.Session.Player as IMyPlayer;
                        //if (player != null)
                        //{
                        //    MyEntity entity = player.Character.Entity as MyEntity;
                        //    if (entity.HasInventory)
                        //    {
                        //        IMyInventory inventory = entity.GetInventoryBase() as MyInventory;
                        //        if (!inventory.ContainItems(1000, new MyObjectBuilder_Ingot { SubtypeName = "Iron" }))
                        //        {
                        //            inventory.AddItems(1, new MyObjectBuilder_Ingot { SubtypeName = "Iron" });
                        //            Logger.Log.Info("Some one with steamid={0} trying to redeemed", pckIn.steamId);
                        //            //terminalBlock.RefreshCustomInfo();
                        //        }
                        //    }

                        //    // resend for all clients a new settings
                        //    SyncPacket newpacket = new SyncPacket();
                        //    newpacket.proto = SyncPacket.Version;
                        //    newpacket.request = false;
                        //    newpacket.command = (ushort)Command.Redeem;
                        //    newpacket.steamId = 0; // for all
                        //    newpacket.message = "兑换成功";
                        //    Core.SendMessage(newpacket);
                        //}
                        //else
                        //{
                        //    Logger.Log.Info("Some one with steamid={0} trying to redeem, no player", pckIn.steamId);
                        //}
                    }

                    break;
                }

                case Command.MessageToChat:
                {
                    MyAPIGateway.Utilities.ShowMessage(Core.MODSAY, pckIn.message);
                    break;
                }

                case Command.SettingsSync:
                {
                    if (pckIn.request)         // Settings sync request
                    {
                        if (Core.IsServer && Core.Settings != null)
                        {         // server send settings to client
                            Logger.Log.Info("Send sync packet with settings to user steamId {0}", pckIn.steamId);
                            SyncPacket pckOut = new SyncPacket();
                            pckOut.proto    = SyncPacket.Version;
                            pckOut.request  = false;
                            pckOut.command  = (ushort)Command.SettingsSync;
                            pckOut.steamId  = pckIn.steamId;
                            pckOut.settings = Core.Settings;
                            Core.SendMessage(pckOut, pckIn.steamId);
                        }
                    }
                    else
                    {
                        if (!Core.IsServer)
                        {         // setting sync only for clients
                            Logger.Log.Info("User config synced...");
                            // if settings changes or syncs...
                            Core.setSettings(pckIn.settings);
                            if (pckIn.steamId == 0)         // if steamid is zero, so we updating for all clients and notify this message
                            {
                                MyAPIGateway.Utilities.ShowNotification("设置已更新!", 2000, MyFontEnum.Green);
                            }
                        }
                    }
                    break;
                }

                case Command.SettingsChange:
                {
                    if (Core.IsServer)         // Only server can acccept this message
                    {
                        Logger.Log.Info("Some one with steamid={0} trying to change server settings", pckIn.steamId);
                        if (Core.IsAdmin(pckIn.steamId) || pckIn.steamId == MyAPIGateway.Session.Player.SteamUserId)
                        {
                            Logger.Log.Info("Server config changed by steamId {0}", pckIn.steamId);
                            Core.setSettings(pckIn.settings);

                            // resend for all clients a new settings
                            SyncPacket newpacket = new SyncPacket();
                            newpacket.proto    = SyncPacket.Version;
                            newpacket.request  = false;
                            newpacket.command  = (ushort)Command.SettingsSync;
                            newpacket.steamId  = 0;        // for all
                            newpacket.settings = Core.Settings;
                            Core.SendMessage(newpacket);
                        }
                    }
                    break;
                }

                case Command.SyncOff:
                {
                    break;
                }

                case Command.SyncOn:
                {
                    break;
                }

                default:
                {
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                Logger.Log.Error("Exception at BeaconSecurity.OnSyncRequest(): {0}", ex.Message);
                return;
            }
        }
Пример #30
0
        private void DoWork()
        {
            try
            {
                Vector3D     velocity = Vector3D.Zero;
                var          grid     = (Container.Entity as IMyCubeBlock).CubeGrid;
                var          entity   = (Container.Entity as IMyFunctionalBlock);
                MyFixedPoint amount   = 0;
                m_speed = 0;

                if (grid != null && entity != null && grid.Physics != null)
                {
                    velocity = grid.Physics.LinearVelocity;

                    var rotation = entity.WorldMatrix.GetDirectionVector(Base6Directions.Direction.Forward);
                    var start    = entity.GetPosition() + (entity.WorldAABB.Size.Z / 2 * rotation);
                    var end      = start + (100 * rotation);

                    if ((Container.Entity as IMyCubeBlock).CubeGrid.RayCastBlocks(start, end).HasValue)
                    {
                        m_state = RamscoopState.Blocked;
                    }
                    else if (!Vector3D.IsZero(velocity))
                    {
                        m_state = RamscoopState.Collecting;
                        m_speed = velocity.Length();

                        var rotdot = Vector3D.Dot(velocity, rotation);
                        var lens   = velocity.Length() * rotation.Length();

                        var cos_theta = (rotdot / lens);

                        cos_theta += 1.0f;  // positive offset, facing reverse will be 0.

                        m_cosTheta    = cos_theta / 2.0d;
                        m_amountAdded = amount = m_amount * (MyFixedPoint)m_cosTheta * (MyFixedPoint)m_speed * (MyFixedPoint)m_sizeFactor;
                    }
                }

                if (Sync.IsServer && m_inventory.CanItemsBeAdded(amount, m_definitionId))
                {
                    var content = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(m_definitionId);
                    if (content != null)
                    {
                        MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                        {
                            try
                            { if (content != null)
                              {
                                  m_inventory.AddItems(amount, content);
                              }
                            }
                            catch (Exception e)
                            { Debug.HandleException(e); }
                        });
                    }
                }
            }
            catch (Exception e)
            { Debug.HandleException(e); }
        }