void EntityInventoryItemAmountChanged(MyEntity entity, MyInventory inventory, MyInventoryItem item, float number)
 {
     if (MyScriptWrapper.IsPlayerShip(entity))
     {
         CheckOre();
     }
 }
示例#2
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            m_cargoDefinition = (MyCargoContainerDefinition)MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId());
            var cargoBuilder = (MyObjectBuilder_CargoContainer)objectBuilder;
            m_containerType = cargoBuilder.ContainerType;

            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }

            // Backward compatibility - inventory component not defined in definition files and in entity container
            if (this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(m_cargoDefinition.InventorySize.Volume, m_cargoDefinition.InventorySize, MyInventoryFlags.CanSend | MyInventoryFlags.CanReceive);
                Components.Add<MyInventoryBase>(inventory);
                
                if (m_containerType != null && MyFakes.RANDOM_CARGO_PLACEMENT && (cargoBuilder.Inventory == null || cargoBuilder.Inventory.Items.Count == 0))
                    SpawnRandomCargo();
            }

            //Backward compatibility
            if (cargoBuilder.Inventory != null && cargoBuilder.Inventory.Items.Count > 0)
                this.GetInventory().Init(cargoBuilder.Inventory);

            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");
            this.GetInventory().SetFlags(MyInventoryFlags.CanSend | MyInventoryFlags.CanReceive);
            m_conveyorEndpoint = new MyMultilineConveyorEndpoint(this);
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint));
            UpdateIsWorking();
        }
示例#3
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            m_cargoDefinition = (MyCargoContainerDefinition)MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId());
            var cargoBuilder = (MyObjectBuilder_CargoContainer)objectBuilder;
            m_containerType = cargoBuilder.ContainerType;

            if (!Components.Has<MyInventoryBase>())
            {
                m_inventory = new MyInventory(m_cargoDefinition.InventorySize.Volume, m_cargoDefinition.InventorySize, MyInventoryFlags.CanSend | MyInventoryFlags.CanReceive, this);
				if(MyFakes.ENABLE_MEDIEVAL_INVENTORY)
					Components.Add<MyInventoryBase>(m_inventory);

                if (m_containerType != null && MyFakes.RANDOM_CARGO_PLACEMENT && (cargoBuilder.Inventory == null || cargoBuilder.Inventory.Items.Count == 0))
                    SpawnRandomCargo();
                else
                    m_inventory.Init(cargoBuilder.Inventory);
            }
            else
            {
                m_inventory = Components.Get<MyInventoryBase>() as MyInventory;
				Debug.Assert(m_inventory != null);
                //m_inventory.Owner = this;
            }

            if(MyPerGameSettings.InventoryMass)
                m_inventory.ContentsChanged += Inventory_ContentsChanged;

            m_conveyorEndpoint = new MyMultilineConveyorEndpoint(this);
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawConveyorEndpoint(m_conveyorEndpoint));
            UpdateIsWorking();
        }
示例#4
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {             
            base.Init(objectBuilder, cubeGrid);

            MyDebug.AssertDebug(BlockDefinition.Id.TypeId == typeof(MyObjectBuilder_Reactor));
            m_reactorDefinition = BlockDefinition as MyReactorDefinition;
            MyDebug.AssertDebug(m_reactorDefinition != null);

            CurrentPowerOutput = 0;
            m_inventory = new MyInventory(m_reactorDefinition.InventoryMaxVolume, m_reactorDefinition.InventorySize, MyInventoryFlags.CanReceive, this);

            var obGenerator = (MyObjectBuilder_Reactor)objectBuilder;
            m_inventory.Init(obGenerator.Inventory);
            m_inventory.ContentsChanged += inventory_ContentsChanged;
            m_inventory.Constraint = m_reactorDefinition.InventoryConstraint;
            RefreshRemainingCapacity();

            UpdateText();

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;
            //if (MyFakes.SHOW_DAMAGE_EFFECTS && IsWorking)
            //    NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;

            m_baseIdleSound = BlockDefinition.PrimarySound;

            m_useConveyorSystem = obGenerator.UseConveyorSystem;

            if (IsWorking)
                OnStartWorking();
        }
示例#5
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);
            var def = BlockDefinition as MyPoweredCargoContainerDefinition;
            var ob = objectBuilder as MyObjectBuilder_Collector;
            m_inventory = new MyInventory(def.InventorySize.Volume, def.InventorySize, MyInventoryFlags.CanSend, this);
            m_inventory.Init(ob.Inventory);
            m_inventory.ContentsChanged += Inventory_ContentChangedCallback;
            if (Sync.IsServer && CubeGrid.CreatePhysics)
                LoadDummies();

			var sinkComp = new MyResourceSinkComponent();
            sinkComp.Init(
                MyStringHash.GetOrCompute(def.ResourceSinkGroup),
                MyEnergyConstants.MAX_REQUIRED_POWER_COLLECTOR,
                () => base.CheckIsWorking() ? ResourceSink.MaxRequiredInput : 0f);
	        ResourceSink = sinkComp;
			ResourceSink.Update();
			ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(ResourceSink,this));

            SlimBlock.ComponentStack.IsFunctionalChanged += UpdateReceiver;
            base.EnabledChanged += UpdateReceiver;

            m_useConveyorSystem = ob.UseConveyorSystem;
        }
示例#6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MyEntity"/> class.
 /// </summary>
 protected MyShip()
 {
     this.Faction = MyMwcObjectBuilder_FactionEnum.Euroamerican;
     Inventory = new MyInventory();
     Inventory.OnInventoryContentChange += OnInventoryContentChange;
     Inventory.OnInventoryItemAmountChange += OnInventoryItemAmountChange;
     Inventory.OnInventoryContentChange += new AppCode.Game.Inventory.OnInventoryContentChange(Inventory_OnInventoryContentChange);
 }
示例#7
0
 private void OnInventoryAggregateRemoved(MyEntityComponentBase component)
 {
     this.m_inputInventory  = null;
     this.m_outputInventory = null;
     this.m_inventoryAggregate.BeforeRemovedFromContainer -= new Action <MyEntityComponentBase>(this.OnInventoryAggregateRemoved);
     this.m_inventoryAggregate.OnAfterComponentAdd        -= new Action <MyInventoryAggregate, MyInventoryBase>(this.OnInventoryAddedToAggregate);
     this.m_inventoryAggregate.OnBeforeComponentRemove    -= new Action <MyInventoryAggregate, MyInventoryBase>(this.OnBeforeInventoryRemovedFromAggregate);
     this.m_inventoryAggregate = null;
 }
示例#8
0
        private void Inventory_ContentChangedCallback(MyInventory inventory)
        {
            if (!Sync.IsServer)
            {
                return;
            }

            NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
        }
示例#9
0
 public MyEntityInventoryStateGroup(MyInventory entity, bool attach)
 {
     m_inventoryChangedDelegate = InventoryChanged;
     Inventory = entity;
     if (attach)
     {
         Inventory.ContentsChanged += m_inventoryChangedDelegate;
     }
 }
示例#10
0
            public static void IdleSupply(MyAssembler __instance) {
          
                if (!(__instance is MyAssembler assembler))
                    return;

                if (assembler.IsQueueEmpty && assembler.HasInventory)
                {
                    //figure out how to see if assembler is even connected to conveyors cause f**k me 
                    if (//assembler.f****e)
                    {
                        try
                        {
                            
                            var group =assembler.CubeGrid.BigOwners;
                            var me =group.First();
                            MyInventory inventory = assembler.GetInventory();
                            if ((double) inventory.VolumeFillFactor >= 0.990000009536743)
                                return;
                            MyGridConveyorSystem.PullAllItemsForConnector((IMyConveyorEndpointBlock) assembler, inventory, me, AssemblerSupplyChainPlugin.Instance.MAX_ITEMS_TO_PULL_IN_ONE_TICK);

                        }
                        catch (Exception e)
                        {
                            Log.Fatal("f**k my whole life" + e);
                        }
                    }    
                    
                    
                    /*MyInventory inventory = assembler.GetInventory();
                    if (inventory.GetItemsCount() <= 0)
                        return;
                    var blocks = assembler.CubeGrid.GridSystems.ConveyorSystem.
                    assembler.CubeGrid.GridSystems.ConveyorSystem.PullItems(_inventoryConstraint, MyFixedPoint.MaxValue, blocks, inventory );*/

                    

                    // this probably just yeets the contents of the assembler
                    //assembler.Components.Remove<MyInventory>();


                    /*MyGridConveyorSystem.PushAnyRequest((inventory) this, inventory);
                    if (assembler.GetInventory() == null)
                    {
                        MyInventory myInventory = new MyInventory(assembler.InventorySize.Volume, this.m_conveyorSorterDefinition.InventorySize, MyInventoryFlags.CanSend);
                        assembler.Components.Add<MyInventoryBase>((MyInventoryBase) myInventory);
                        myInventory.Init(builderConveyorSorter.Inventory);
                    }
                    var a = assembler.OutputInventory.InventoryId;
                    var i = assembler.ConveyorEndpoint.CubeBlock.InventoryCount;
                    assembler.Components.Clear();
                    assembler.drainall();
                    MyConveyorSorter sorter;
                    sorter.DrainAll = true;*/
                }

                return;
            }
示例#11
0
 private static void ItemPullAll(IMyConveyorEndpointBlock start, MyInventory destinationInventory)
 {
     // First, search through small conveyor tubes and request only small items
     PrepareTraversal(start.ConveyorEndpoint, null, IsAccessAllowedPredicate);
     ItemPullAllInternal(destinationInventory, m_tmpRequestedItemSet, true);
     // Then, search again through all tubes and request all items
     PrepareTraversal(start.ConveyorEndpoint, null, IsAccessAllowedPredicate, IsConveyorLargePredicate);
     ItemPullAllInternal(destinationInventory, m_tmpRequestedItemSet, false);
 }
 public static bool TryGetInventory(this MyEntity thisEntity, out MyInventory inventory)
 {
     inventory = null;
     if (thisEntity.Components.Has <MyInventoryBase>())
     {
         inventory = GetInventory(thisEntity, 0);
     }
     return(inventory != null);
 }
示例#13
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            m_conveyorSorterDefinition = (MyConveyorSorterDefinition)MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder.GetId());

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                m_conveyorSorterDefinition.ResourceSinkGroup,
                BlockDefinition.PowerInput,
                UpdatePowerInput);
            sinkComp.IsPoweredChanged += IsPoweredChanged;
            ResourceSink = sinkComp;

            base.Init(objectBuilder, cubeGrid);

            MyObjectBuilder_ConveyorSorter ob = (MyObjectBuilder_ConveyorSorter)objectBuilder;

            DrainAll    = ob.DrainAll;
            IsWhitelist = ob.IsWhiteList;

            foreach (var id in ob.DefinitionIds)
            {
                m_inventoryConstraint.Add(id);
            }
            foreach (byte b in ob.DefinitionTypes)
            {
                Tuple <MyObjectBuilderType, StringBuilder> tuple;
                if (!CandidateTypes.TryGetValue(b, out tuple))
                {
                    Debug.Assert(false, "type not in dictionary");
                    continue;
                }
                m_inventoryConstraint.AddObjectBuilderType(tuple.Item1);
            }

            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }


            if (this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(m_conveyorSorterDefinition.InventorySize.Volume, m_conveyorSorterDefinition.InventorySize, MyInventoryFlags.CanSend);
                Components.Add <MyInventoryBase>(inventory);
                inventory.Init(ob.Inventory);
            }
            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME | MyEntityUpdateEnum.EACH_10TH_FRAME;


            ResourceSink.Update();
            UpdateText();
        }
 private void OnInventoryAggregateRemoved(MyEntityComponentBase component)
 {
     m_inputInventory  = null;
     m_outputInventory = null;
     m_inventoryAggregate.BeforeRemovedFromContainer -= OnInventoryAggregateRemoved;
     m_inventoryAggregate.OnAfterComponentAdd        -= OnInventoryAddedToAggregate;
     m_inventoryAggregate.OnBeforeComponentRemove    -= OnBeforeInventoryRemovedFromAggregate;
     m_inventoryAggregate = null;
 }
 public MyEntityInventoryStateGroup(MyInventory entity, bool attach)
 {
     m_inventoryChangedDelegate = InventoryChanged;
     Inventory = entity;
     if (attach)
     {
         Inventory.ContentsChanged += m_inventoryChangedDelegate;
     }
 }
示例#16
0
        private void InventoryContentChanged(MyInventory sender, MyInventoryItem inventoryItem, float amountChanged)
        {
            float oreAmount = sender.GetInventoryItemsCount(MyMwcObjectBuilderTypeEnum.Ore, null);

            if (oreAmount >= 50)
            {
                m_objectives.Find(submission => submission.ID == MyMissionID.M01_Intro_Mining).Success();
            }
        }
示例#17
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);
        }
示例#18
0
        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            base.Init(builder, cubeGrid);
            m_defId = builder.GetId();
            var def = MyDefinitionManager.Static.GetCubeBlockDefinition(m_defId) as MyShipDrillDefinition;

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

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

            m_inventory            = new MyInventory(inventoryVolume, inventorySize, MyInventoryFlags.CanSend, this);
            m_inventory.Constraint = new MyInventoryConstraint(MySpaceTexts.ToolTipItemFilter_AnyOre)
                                     .AddObjectBuilderType(typeof(MyObjectBuilder_Ore));

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

            m_drillBase = new MyDrillBase(this,
                                          MyDrillConstants.DRILL_SHIP_DUST_EFFECT,
                                          MyDrillConstants.DRILL_SHIP_DUST_STONES_EFFECT,
                                          MyDrillConstants.DRILL_SHIP_SPARKS_EFFECT,
                                          new MyDrillSensorSphere(def.SensorRadius, def.SensorOffset),
                                          new MyDrillCutOut(def.SensorOffset, def.SensorRadius),
                                          HEAD_SLOWDOWN_TIME_IN_SECONDS,
                                          floatingObjectSpawnOffset: -0.4f,
                                          floatingObjectSpawnRadius: 0.4f,
                                          sounds: m_sounds,
                                          inventoryCollectionRatio: 0.7f
                                          );
            m_drillBase.OutputInventory = m_inventory;
            m_drillBase.IgnoredEntities.Add(this);
            m_drillBase.OnWorldPositionChanged(WorldMatrix);
            m_wantsToDrill   = false;
            m_wantsToCollect = false;
            AddDebugRenderComponent(new Components.MyDebugRenderCompomentDrawDrillBase(m_drillBase));

            PowerReceiver = new MyPowerReceiver(
                MyConsumerGroupEnum.Defense,
                false,
                MyEnergyConstants.MAX_REQUIRED_POWER_SHIP_DRILL,
                ComputeRequiredPower);
            PowerReceiver.IsPoweredChanged += Receiver_IsPoweredChanged;
            PowerReceiver.Update();

            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(PowerReceiver, this));

            var obDrill = (MyObjectBuilder_Drill)builder;

            m_inventory.Init(obDrill.Inventory);

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            m_useConveyorSystem = obDrill.UseConveyorSystem;
        }
示例#19
0
        private bool TransferFromTarget(IMyEntity target, bool transfer = true)
        {
            if (target is IMyCharacter)
            {
                if (transfer)
                {
                    MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                                                              { OpenCharacter(target); });
                }

                return(true);
            }

            if (target is MyInventoryBagEntity)
            {
                if (transfer)
                {
                    MyAPIGateway.Utilities.InvokeOnGameThread(() =>
                                                              { OpenBag(target); });
                }

                return(true);
            }

            MyInventory targetInventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory();
            var         def             = MyDefinitionManager.Static.GetPhysicalItemDefinition
                                              (new VRage.Game.MyDefinitionId(((MyFloatingObject)target).Item.Content.TypeId, ((MyFloatingObject)target).Item.Content.SubtypeId));
            float amount = GetNaniteInventoryAmountThatFits(target, (MyCubeBlock)m_constructionBlock.ConstructionBlock);

            if ((int)amount > 0 || MyAPIGateway.Session.CreativeMode)
            {
                if (MyAPIGateway.Session.CreativeMode)
                {
                    m_carryVolume = 10000f;
                }

                if ((int)amount > 1 && (amount / def.Volume) > m_carryVolume)
                {
                    amount = m_carryVolume / def.Volume;
                }

                if ((int)amount < 1)
                {
                    amount = 1f;
                }

                if (transfer)
                {
                    targetInventory.PickupItem(((MyFloatingObject)target), (int)amount);
                }

                return(true);
            }

            return(false);
        }
示例#20
0
        public void TakeFloatingObjectRequest(MyInventory inv, MyFloatingObject obj)
        {
            var msg = new TakeFloatingObjectMsg();

            msg.OwnerEntityId    = inv.Owner.EntityId;
            msg.InventoryIndex   = inv.InventoryIdx;
            msg.FloatingObjectId = obj.EntityId;

            Sync.Layer.SendMessageToServer(ref msg, MyTransportMessageEnum.Request);
        }
示例#21
0
        protected override void OnInventoryComponentRemoved(MyInventoryBase inventory)
        {
            base.OnInventoryComponentRemoved(inventory);
            MyInventory inventory2 = inventory as MyInventory;

            if (inventory2 != null)
            {
                inventory2.ContentsChanged -= new Action <MyInventoryBase>(this.Inventory_ContentChangedCallback);
            }
        }
        public MyInventorySynchronizer(MyInventory inventory, MyMustBeInventorySynchronizedDelegate mustBeInventorySynchronizedDelegate) 
        {
            m_inventoryItemsHelper = new List<MyInventoryItem>();
            m_inventoryItemsToAdd = new List<MyInventoryItem>();
            m_inventoryItemsAmountChanges = new List<MyInventoryItemAmountDefinition>();
            m_mustBeInventorySynchronizedDelegate = mustBeInventorySynchronizedDelegate;
            m_inventory = inventory;

            //MyMinerGame.OnGameUpdate += MyMinerGame_OnGameUpdate;
        }
示例#23
0
        protected override void OnInventoryComponentRemoved(MyInventoryBase inventory)
        {
            base.OnInventoryComponentRemoved(inventory);
            MyInventory inventory2 = inventory as MyInventory;

            if ((inventory2 != null) && MyPerGameSettings.InventoryMass)
            {
                inventory2.ContentsChanged -= new Action <MyInventoryBase>(this.Inventory_ContentsChanged);
            }
        }
示例#24
0
 public static void SendTransferInventoryMsg(long sourceEntityID, long destinationEntityID, MyInventory inventory, bool clearSourceInventories = false)
 {
     var msg = new TransferInventoryMsg();
     msg.SourceEntityID = sourceEntityID;
     msg.DestinationEntityID = destinationEntityID;
     msg.InventoryId = MyStringHash.GetOrCompute(inventory.InventoryId.ToString());
     msg.RemoveEntityOnEmpty = inventory.RemoveEntityOnEmpty;
     msg.ClearSourceInventories = clearSourceInventories;
     Sync.Layer.SendMessageToAllAndSelf(ref msg);
 }       
示例#25
0
        public void TransferInventoryItem(int sourceInventoryId, int destinationInventoryId, int itemId)
        {
            var sourceInventory      = TerminalScreen.LeftInventories()[sourceInventoryId];
            var rightInventory       = TerminalScreen.RightInventories();
            var destinationInventory = rightInventory[destinationInventoryId];

            MyInventory.TransferByUser(sourceInventory, destinationInventory, (uint)itemId,
                                       destinationInventory.ItemCount);
            TerminalInventoryController().CallMethod <object>("RefreshSelectedInventoryItem", new object[] { });
        }
        public override void OnRemovedByCubeBuilder()
        {
            MyInventory inventory = this.GetInventory();

            if (inventory != null)
            {
                ReleaseInventory(inventory);
            }
            base.OnRemovedByCubeBuilder();
        }
        public override void OnDestroy()
        {
            MyInventory inventory = this.GetInventory();

            if (inventory != null)
            {
                ReleaseInventory(inventory);
            }
            base.OnDestroy();
        }
        private bool PasteGridsInStaticMode(MyInventory buildInventory, bool deactivate)
        {
            // Paste generates grid from builder and use matrix from preview
            List <MyObjectBuilder_CubeGrid> copiedGridsOrig = new List <MyObjectBuilder_CubeGrid>();
            List <MatrixD> previewGridsWorldMatrices        = new List <MatrixD>();

            {
                // First grid is forced static
                MyObjectBuilder_CubeGrid originalCopiedGrid = CopiedGrids[0];
                copiedGridsOrig.Add(originalCopiedGrid);
                MatrixD previewGridWorldMatrix = PreviewGrids[0].WorldMatrix;
                // Convert grid builder to static
                var gridBuilder = ConvertGridBuilderToStatic(originalCopiedGrid, previewGridWorldMatrix);
                // Set it to copied grids
                CopiedGrids[0] = gridBuilder;

                previewGridsWorldMatrices.Add(previewGridWorldMatrix);
                PreviewGrids[0].WorldMatrix = MatrixD.CreateTranslation(previewGridWorldMatrix.Translation);
            }


            for (int i = 1; i < CopiedGrids.Count; ++i)
            {
                MyObjectBuilder_CubeGrid originalCopiedGrid = CopiedGrids[i];
                copiedGridsOrig.Add(originalCopiedGrid);
                MatrixD previewGridWorldMatrix = PreviewGrids[i].WorldMatrix;
                previewGridsWorldMatrices.Add(previewGridWorldMatrix);

                if (CopiedGrids[i].IsStatic)
                {
                    // Convert grid builder to static
                    var gridBuilder = ConvertGridBuilderToStatic(originalCopiedGrid, previewGridWorldMatrix);
                    // Set it to copied grids
                    CopiedGrids[i] = gridBuilder;

                    PreviewGrids[i].WorldMatrix = MatrixD.CreateTranslation(previewGridWorldMatrix.Translation);
                }
            }

            Debug.Assert(CopiedGrids.Count == copiedGridsOrig.Count);
            Debug.Assert(CopiedGrids.Count == previewGridsWorldMatrices.Count);

            bool result = PasteGridInternal(buildInventory: buildInventory, deactivate: deactivate);

            // Set original grids back
            CopiedGrids.Clear();
            CopiedGrids.AddList(copiedGridsOrig);

            for (int i = 0; i < PreviewGrids.Count; ++i)
            {
                PreviewGrids[i].WorldMatrix = previewGridsWorldMatrices[i];
            }

            return(result);
        }
示例#29
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;
            var ob = objectBuilder as MyObjectBuilder_SmallGatlingGun;

            var weaponBlockDefinition = BlockDefinition as MyWeaponBlockDefinition;

            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }
            //m_soundEmitterRotor = new MyEntity3DSoundEmitter(this);

            if (this.GetInventory() == null)
            {
                MyInventory inventory = null;
                if (weaponBlockDefinition != null)
                {
                    inventory = new MyInventory(weaponBlockDefinition.InventoryMaxVolume, new Vector3(0.4f, 0.4f, 0.4f), MyInventoryFlags.CanReceive);
                }
                else
                {
                    inventory = new MyInventory(64.0f / 1000, new Vector3(0.4f, 0.4f, 0.4f), MyInventoryFlags.CanReceive);
                }

                Components.Add <MyInventoryBase>(inventory);

                this.GetInventory().Init(ob.Inventory);
            }

            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                weaponBlockDefinition.ResourceSinkGroup,
                MyEnergyConstants.MAX_REQUIRED_POWER_SHIP_GUN,
                () => ResourceSink.MaxRequiredInput);
            sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink = sinkComp;

            base.Init(objectBuilder, cubeGrid);

            m_gunBase.Init(ob.GunBase, BlockDefinition, this);

            GetBarrelAndMuzzle();
            //if (m_ammoPerShotConsumption == 0)
            //    m_ammoPerShotConsumption = (MyFixedPoint)((45.0f / (1000.0f / MyGatlingConstants.SHOT_INTERVAL_IN_MILISECONDS)) / m_gunBase.WeaponProperties.AmmoMagazineDefinition.Capacity);


            ResourceSink.Update();
            AddDebugRenderComponent(new MyDebugRenderComponentDrawPowerReciever(ResourceSink, this));

            m_useConveyorSystem.Value = ob.UseConveyorSystem;
        }
        //[TerminalValues(MySpaceTexts.SwitchText_On, MySpaceTexts.SwitchText_Off)]
        //[Terminal(2, MyPropertyDisplayEnum.Switch, MySpaceTexts.Terminal_UseConveyorSystem, MySpaceTexts.Blank)]
        //[Obfuscation(Feature = Obfuscator.NoRename, Exclude = true)]
        //public MyStringId UseConveyorSystemGui
        //{
        //    get { return m_useConveyorSystem ? MySpaceTexts.SwitchText_On : MySpaceTexts.SwitchText_Off; }
        //    set
        //    {
        //        if (m_useConveyorSystem != (value == MySpaceTexts.SwitchText_On))
        //        {
        //            m_useConveyorSystem = (value == MySpaceTexts.SwitchText_On);
        //            OnPropertiesChanged();
        //        }
        //    }
        //}
        //[TerminalValueSetter(2)]
        //public void RequestUseConveyorSystemChange(MyStringId newVal)
        //{
        //    MySyncConveyors.SendChangeUseConveyorSystemRequest(EntityId, newVal == MySpaceTexts.SwitchText_On);
        //}

        public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid)
        {
            SyncFlag = true;
            var ob = builder as MyObjectBuilder_SmallMissileLauncher;

            m_gunBase = new MyGunBase();

            MyStringHash resourceSinkGroup;
            var          weaponBlockDefinition = BlockDefinition as MyWeaponBlockDefinition;

            if (weaponBlockDefinition != null)
            {
                m_ammoInventory   = new MyInventory(weaponBlockDefinition.InventoryMaxVolume, new Vector3(1.2f, 0.98f, 0.98f), MyInventoryFlags.CanReceive, this);
                resourceSinkGroup = weaponBlockDefinition.ResourceSinkGroup;
            }
            else
            {
                if (cubeGrid.GridSizeEnum == MyCubeSize.Small)
                {
                    m_ammoInventory = new MyInventory(240.0f / 1000, new Vector3(1.2f, 0.45f, 0.45f), MyInventoryFlags.CanReceive, this); // 4 missiles
                }
                else
                {
                    m_ammoInventory = new MyInventory(1140.0f / 1000, new Vector3(1.2f, 0.98f, 0.98f), MyInventoryFlags.CanReceive, this); // 19 missiles
                }
                resourceSinkGroup = MyStringHash.GetOrCompute("Defense");
            }

            base.Init(builder, cubeGrid);

            m_ammoInventory.Init(ob.Inventory);
            m_gunBase.Init(ob.GunBase, BlockDefinition, this);

            m_ammoInventory.ContentsChanged += m_ammoInventory_ContentsChanged;

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                resourceSinkGroup,
                MyEnergyConstants.MAX_REQUIRED_POWER_SHIP_GUN,
                () => (Enabled && IsFunctional) ? ResourceSink.MaxRequiredInput : 0.0f);
            ResourceSink = sinkComp;
            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink.Update();

            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(ResourceSink, this));

            m_useConveyorSystem = ob.UseConveyorSystem;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            LoadDummies();

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;
        }
示例#31
0
        internal void LoadData()
        {
            if (Entity.Storage == null)
            {
                // DebugLog.Write("storage is null, exiting loadData().");
                return;
            }
            string Data;

            if (Entity.Storage.TryGetValue(FilterStateGUID, out Data))
            {
                // DebugLog.Write(Data);
                Filterdata loadedfilterdata = new Filterdata();

                var base64 = Convert.FromBase64String(Data);
                loadedfilterdata = MyAPIGateway.Utilities.SerializeFromBinary <Filterdata>(base64);
                // DebugLog.Write($"loaded id: {loadedfilterdata.id}");
                if (loadedfilterdata.id == MyCargoContainer.EntityId)
                {
                    // DebugLog.Write($"Saved state found (id: {loadedfilterdata.id})");
                    MyInventory inventory = (MyInventory)MyCargoContainer.GetInventory();
                    if (loadedfilterdata.FilterItems != null)
                    {
                        for (int i = 0; i < loadedfilterdata.FilterItems.Count(); i++)
                        {
                            // DebugLog.Write($"{loadedfilterdata.FilterItems[i].DisplayName}");
                            FilterController.FilterList.Add(loadedfilterdata.FilterItems[i]);
                            if (loadedfilterdata.FilterItems[i].Type == FilterType.FILTER_TYPE)
                            {
                                MyObjectBuilderType type;
                                if (MyObjectBuilderType.TryParse(loadedfilterdata.FilterItems[i].ParseItem, out type) == true)
                                {
                                    inventory.Constraint.AddObjectBuilderType(type);
                                }
                            }
                            else if (loadedfilterdata.FilterItems[i].Type == FilterType.FILTER_ITEM)
                            {
                                MyDefinitionId Id;
                                if (MyDefinitionId.TryParse(loadedfilterdata.FilterItems[i].ParseItem, out Id) == true)
                                {
                                    inventory.Constraint.Add(Id);
                                }
                            }
                        }
                    }
                    inventory.Constraint.IsWhitelist = loadedfilterdata.FilterMode;
                    FilterController.FilterMode      = loadedfilterdata.FilterMode;
                    inventory.Constraint.Icon        = null;
                }
                else
                {
                    // DebugLog.Write($"Id mismatch - Entity Id: {Entity.EntityId}  MyCargoContainerId: {MyCargoContainer.EntityId}");
                }
            }
        }
示例#32
0
 protected virtual void OnInventoryAddedToAggregate(MyInventoryAggregate aggregate, MyInventoryBase inventory)
 {
     if (this.m_inputInventory == null)
     {
         this.m_inputInventory = inventory as MyInventory;
     }
     else if (this.m_outputInventory == null)
     {
         this.m_outputInventory = inventory as MyInventory;
     }
 }
示例#33
0
 private bool CheckInventoryContents(MyInventory inventory, MyBlueprintDefinitionBase.Item[] item, MyFixedPoint amountMultiplier)
 {
     for (int i = 0; i < item.Length; ++i)
     {
         if (!inventory.ContainItems(item[i].Amount * amountMultiplier, item[i].Id))
         {
             return(false);
         }
     }
     return(true);
 }
示例#34
0
        static void OnRemoveItemsSuccess(ref RemoveItemsMsg msg, MyNetworkClient sender)
        {
            if (!MyEntities.EntityExists(msg.OwnerEntityId))
            {
                return;
            }
            IMyInventoryOwner owner = MyEntities.GetEntityById(msg.OwnerEntityId) as IMyInventoryOwner;
            MyInventory       inv   = owner.GetInventory(msg.InventoryIndex);

            inv.RemoveItemsInternal(msg.itemId, msg.Amount);
        }
示例#35
0
 protected virtual void OnBeforeInventoryRemovedFromAggregate(MyInventoryAggregate aggregate, MyInventoryBase inventory)
 {
     if (ReferenceEquals(inventory, this.m_inputInventory))
     {
         this.m_inputInventory = null;
     }
     else if (ReferenceEquals(inventory, this.m_outputInventory))
     {
         this.m_outputInventory = null;
     }
 }
示例#36
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);

            m_entitiesInContact  = new Dictionary <MyEntity, int>();
            m_blocksToActivateOn = new HashSet <MySlimBlock>();
            m_tempBlocksBuffer   = new HashSet <MySlimBlock>();

            m_isActivated            = false;
            m_isActivatedOnSomething = false;
            m_wantsToActivate        = false;
            m_effectsSet             = false;

            m_shootHeatup     = 0;
            m_activateCounter = 0;

            m_defId = objectBuilder.GetId();
            var def = MyDefinitionManager.Static.GetCubeBlockDefinition(m_defId);

            var typedBuilder = objectBuilder as MyObjectBuilder_ShipToolBase;

            //each dimension of size needs to be scaled by grid size not only one
            float   inventoryVolume = def.Size.X * cubeGrid.GridSize * def.Size.Y * cubeGrid.GridSize * def.Size.Z * cubeGrid.GridSize * 0.5f;
            Vector3 inventorySize   = new Vector3(def.Size.X, def.Size.Y, def.Size.Z * 0.5f);

            m_inventory = new MyInventory(inventoryVolume, inventorySize, MyInventoryFlags.CanSend, this);
            m_inventory.Init(typedBuilder.Inventory);

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

            var sinkComp = new MyResourceSinkComponent();

            sinkComp.Init(
                MyStringHash.GetOrCompute("Defense"),
                MyEnergyConstants.MAX_REQUIRED_POWER_SHIP_GRINDER,
                ComputeRequiredPower);
            sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged;
            ResourceSink = sinkComp;

            Enabled           = typedBuilder.Enabled;
            UseConveyorSystem = typedBuilder.UseConveyorSystem;

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            LoadDummies();

            UpdateActivationState();

            IsWorkingChanged += MyShipToolBase_IsWorkingChanged;
            ResourceSink.Update();

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME | MyEntityUpdateEnum.EACH_10TH_FRAME | MyEntityUpdateEnum.EACH_FRAME;
        }
示例#37
0
        /// <summary>
        /// Called before update loop begins
        /// </summary>
        public virtual void Start()
        {
            WeaponDefinition = CubeBlock.BlockDefinition.Id;

            State = new NetSync <WeaponState>(ControlLayer, TransferType.Both, WeaponState.None);
            State.ValueChanged += StateChanged;
            Reloading           = new NetSync <bool>(ControlLayer, TransferType.ServerToClient, false);
            DeviationIndex      = new NetSync <sbyte>(ControlLayer, TransferType.ServerToClient, (sbyte)MyRandom.Instance.Next(0, sbyte.MaxValue));
            InventoryComponent.GetOrAddComponent(CubeBlock.CubeGrid);
            Inventory = CubeBlock.GetInventory();
        }
示例#38
0
        public MyEntityInventoryStateGroup(MyInventory entity, bool attach, IMyReplicable owner)
        {
            m_inventoryChangedDelegate = InventoryChanged;
            Inventory = entity;
            if (attach)
            {
                Inventory.ContentsChanged += m_inventoryChangedDelegate;
            }

            Owner = owner;
        }
        public override void OnCharacterDead()
        {
            System.Diagnostics.Debug.Assert(!Character.Definition.EnableSpawnInventoryAsContainer ||  (Character.Definition.EnableSpawnInventoryAsContainer && Character.Definition.InventorySpawnContainerId.HasValue), "Container id is not defined, but is enabled to spawn the inventory into container");
            
            if (Character.IsDead && Character.Definition.EnableSpawnInventoryAsContainer && Character.Definition.InventorySpawnContainerId.HasValue)
            {
                if (Character.Components.Has<MyInventoryBase>())
                {
                    var inventory = Character.Components.Get<MyInventoryBase>();
                    if (inventory is MyInventoryAggregate)
                    {
                        var inventoryAggregate = inventory as MyInventoryAggregate;
                        var components = new List<MyComponentBase>();
                        inventoryAggregate.GetComponentsFlattened(components);
                        foreach (var inventoryComponent in components)
                        {
                            //TODO: This spawn all MyInventory components, which are currently used with Characters
                            var myInventory = inventoryComponent as MyInventory;
                            if (myInventory != null && myInventory.GetItemsCount() > 0)
                            {
                                MyContainerDefinition containerDefinition;
                                if (MyDefinitionManager.Static.TryGetContainerDefinition(Character.Definition.InventorySpawnContainerId.Value, out containerDefinition))
                                {
                                    inventoryAggregate.RemoveComponent(myInventory);
                                    if (Sync.IsServer)
                                    {
                                        var bagEntityId = SpawnInventoryContainer(Character.Definition.InventorySpawnContainerId.Value, myInventory);
                                    }
                                }
                                else
                                {
                                    System.Diagnostics.Debug.Fail("The provided definiton of the container was not found!");
                                }
                            }
                            else
                            {
                                inventoryAggregate.RemoveComponent(inventoryComponent);
                            }

                        }
                    }
                    else if (inventory is MyInventory && Character.Definition.SpawnInventoryOnBodyRemoval)
                    {
                        m_spawnInventory = inventory as MyInventory;
                        Character.OnClosing += Character_OnClosing;
                    }                    
                    else
                    {
                        System.Diagnostics.Debug.Fail("Reached unpredicted branch on spawning inventory, can't spawn inventory if it is not in aggregate, or if it is not going to be spawned on body removal");
                    }
                }                
                CloseComponent();
            }            
        }
示例#40
0
 /// <summary>
 /// Adds a specified TF2 item by its itemid.
 /// If the item is not a TF2 item, use the AddItem(ulong itemid, int appid, long contextid) overload
 /// </summary>
 /// <returns><c>false</c> if the tf2 item was not found in the inventory.</returns>
 public bool AddItem(ulong itemid)
 {
     if (MyInventory.GetItem(itemid) == null)
     {
         return(false);
     }
     else
     {
         return(AddItem(new TradeUserAssets(440, 2, itemid)));
     }
 }
        private void RecalculateItemsCount(MyInventory inventory)
        {
            for (int index = 0; index < m_itemsToGet.Count; index++)
            {
                var itemToGet = m_itemsToGet[index];
                int itemCount = MyScriptWrapper.GetInventoryItemCount(inventory, itemToGet.ItemType, itemToGet.ItemId);
                if (itemCount >= itemToGet.Count)
                {
                    m_itemsToGet.Remove(itemToGet);
                    index--;

                }
            }
        }
        void Init()
        {
            m_enableBackgroundFade = true;
            m_size = new Vector2(0.99f, 0.95f);

            // Add screen title
            AddCaption();
            
            m_inventoryItemsRepository = new MyInventoryItemsRepository();
            m_allItemsInventory = new MyInventory();
            m_allItemsInventory.FillInventoryWithAllItems(null, 100, true);

            InitControls();
            AddOkAndCancelButtonControls();
        }
示例#43
0
 private void OnInventoryContentChanged(MyInventory sender)
 {
     if (sender.Contains(MyMwcObjectBuilderTypeEnum.SmallShip_Tool, (int)MyMwcObjectBuilder_SmallShip_Tool_TypesEnum.NANO_REPAIR_TOOL))
     {
         if (m_nanoRepairTool == null)
         {
             m_nanoRepairTool = new MyNanoRepairToolEntity(this);                    
         }
     }
     else
     {
         m_nanoRepairTool = null;                
     }
     RecheckNeedsUpdate();
 }
示例#44
0
        void Inventory_OnInventoryContentChange(MyInventory sender)
        {
            UpdateState();

            if (RespawnTime.HasValue && MyMultiplayerGameplay.IsRunning && !MyGuiScreenGamePlay.Static.IsGameStoryActive())
            {
                if (Inventory.GetInventoryItems().Count < m_inventoryTemplate.InventoryItems.Count)
                {
                    m_shouldRespawn = NeedsUpdate = true;
                }
            }

            if (sender.IsInventoryEmpty() && CloseAfterEmptied)
            {
                MarkForClose();
            }
        }
示例#45
0
 public void SetInventory(MyInventory inventory, int index)
 {
     switch (index)
     {
         case 0:
             InputInventory.ContentsChanged -= inventory_OnContentsChanged;
             InputInventory = inventory;
             InputInventory.ContentsChanged += inventory_OnContentsChanged;
             break;
         case 1:
             OutputInventory.ContentsChanged -= inventory_OnContentsChanged;
             OutputInventory = inventory;
             OutputInventory.ContentsChanged += inventory_OnContentsChanged;
             break;
         default:
             throw new InvalidBranchException();
     }
 }
        public void Close() 
        {
            foreach (var item in m_inventoryItemsToAdd) 
            {
                MyInventory.CloseInventoryItem(item);
            }
            m_inventoryItemsToAdd.Clear();
            m_inventoryItemsToAdd = null;

            m_inventoryItemsAmountChanges.Clear();
            m_inventoryItemsAmountChanges = null;

            m_inventoryItemsHelper.Clear();
            m_inventoryItemsHelper = null;

            m_mustBeInventorySynchronizedDelegate = null;

            m_inventory = null;

            //MyMinerGame.OnGameUpdate -= MyMinerGame_OnGameUpdate;
        }
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            var ob = objectBuilder as MyObjectBuilder_Collector;

            var sinkComp = new MyResourceSinkComponent();
            sinkComp.Init(
                MyStringHash.GetOrCompute(BlockDefinition.ResourceSinkGroup),
                BlockDefinition.RequiredPowerInput,
                ComputeRequiredPower);
            ResourceSink = sinkComp;

            base.Init(objectBuilder, cubeGrid);

            m_useConveyorSystem.Value = true;
            if (MyFakes.ENABLE_INVENTORY_FIX)
            {
                FixSingleInventory();
            }

            if (this.GetInventory() == null)
            {
                MyInventory inventory = new MyInventory(BlockDefinition.InventorySize.Volume, BlockDefinition.InventorySize, MyInventoryFlags.CanSend);
                Components.Add<MyInventoryBase>(inventory);
                inventory.Init(ob.Inventory);
            }
            Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!");

            if (Sync.IsServer && CubeGrid.CreatePhysics)
                LoadDummies();

            ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged;
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(ResourceSink,this));

            SlimBlock.ComponentStack.IsFunctionalChanged += UpdateReceiver;
            base.EnabledChanged += UpdateReceiver;

            m_useConveyorSystem.Value = ob.UseConveyorSystem;

            ResourceSink.Update();
        }
示例#48
0
 public void ActivateIfInInventory(MyInventory inventory)
 {
     MyInventoryItem item;
     switch (Type())
     {
         case MyMedicineType.MEDIKIT:
             item = inventory.GetInventoryItem(MyMwcObjectBuilderTypeEnum.SmallShip_Tool, (int?)MyMwcObjectBuilder_SmallShip_Tool_TypesEnum.MEDIKIT);
             if (item != null)
             {
                 Activate();
                 inventory.RemoveInventoryItemAmount(ref item, 1);
             }
             break;
         case MyMedicineType.ANTIRADIATION_MEDICINE:
             item = inventory.GetInventoryItem(MyMwcObjectBuilderTypeEnum.SmallShip_Tool, (int?)MyMwcObjectBuilder_SmallShip_Tool_TypesEnum.ANTIRADIATION_MEDICINE);
             if (item != null)
             {
                 Activate();
                 inventory.RemoveInventoryItemAmount(ref item, 1);
             }
             break;
         case MyMedicineType.HEALTH_ENHANCING_MEDICINE:
             item = inventory.GetInventoryItem(MyMwcObjectBuilderTypeEnum.SmallShip_Tool, (int?)MyMwcObjectBuilder_SmallShip_Tool_TypesEnum.HEALTH_ENHANCING_MEDICINE);
             if (item != null)
             {
                 Activate();
                 inventory.RemoveInventoryItem(item, true);
             }
             break;
         case MyMedicineType.PERFORMANCE_ENHANCING_MEDICINE:
             item = inventory.GetInventoryItem(MyMwcObjectBuilderTypeEnum.SmallShip_Tool, (int?)MyMwcObjectBuilder_SmallShip_Tool_TypesEnum.PERFORMANCE_ENHANCING_MEDICINE);
             if (item != null)
             {
                 Activate();
                 inventory.RemoveInventoryItem(item, true);
             }
             break;
     }
 }
示例#49
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {             
            base.Init(objectBuilder, cubeGrid);

            MyDebug.AssertDebug(BlockDefinition.Id.TypeId == typeof(MyObjectBuilder_Reactor));
            m_reactorDefinition = BlockDefinition as MyReactorDefinition;
            MyDebug.AssertDebug(m_reactorDefinition != null);

            SourceComp.Init(
                m_reactorDefinition.ResourceSourceGroup, 
                new MyResourceSourceInfo
                {
                    ResourceTypeId = MyResourceDistributorComponent.ElectricityId,
                    DefinedOutput = m_reactorDefinition.MaxPowerOutput, 
                    ProductionToCapacityMultiplier = 60 * 60
                });
	        SourceComp.HasCapacityRemainingChanged += (id, source) => UpdateIsWorking();
	        SourceComp.OutputChanged += Source_OnOutputChanged;
            SourceComp.ProductionEnabledChanged += Source_ProductionEnabledChanged;
            SourceComp.Enabled = Enabled;

            m_inventory = new MyInventory(m_reactorDefinition.InventoryMaxVolume, m_reactorDefinition.InventorySize, MyInventoryFlags.CanReceive, this);

            var obGenerator = (MyObjectBuilder_Reactor)objectBuilder;
            m_inventory.Init(obGenerator.Inventory);
            m_inventory.ContentsChanged += inventory_ContentsChanged;
            m_inventory.Constraint = m_reactorDefinition.InventoryConstraint;
            RefreshRemainingCapacity();

            UpdateText();

            SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged;

            NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;

            m_useConveyorSystem = obGenerator.UseConveyorSystem;
			UpdateMaxOutputAndEmissivity();
        }
示例#50
0
        public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid)
        {
            base.Init(objectBuilder, cubeGrid);
            var def = BlockDefinition as MyCargoContainerDefinition;
            var ob = objectBuilder as MyObjectBuilder_Collector;
            m_inventory = new MyInventory(def.InventorySize.Volume, def.InventorySize, MyInventoryFlags.CanSend, this);
            m_inventory.Init(ob.Inventory);
            m_inventory.ContentsChanged += Inventory_ContentChangedCallback;
            if (Sync.IsServer && CubeGrid.CreatePhysics)
                LoadDummies();
            PowerReceiver = new MyPowerReceiver(
                group: MyConsumerGroupEnum.Conveyors,
                isAdaptible: false,
                maxRequiredInput: MyEnergyConstants.MAX_REQUIRED_POWER_COLLECTOR,
                requiredInputFunc: () => base.CheckIsWorking() ? PowerReceiver.MaxRequiredInput : 0f);
            PowerReceiver.Update();
            PowerReceiver.IsPoweredChanged += Receiver_IsPoweredChanged;
            AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(PowerReceiver,this));

            SlimBlock.ComponentStack.IsFunctionalChanged += UpdateReceiver;
            base.EnabledChanged += UpdateReceiver;

            m_useConveyorSystem = ob.UseConveyorSystem;
        }
示例#51
0
        public bool CanContinueBuild(MyInventory sourceInventory)
        {
            if (IsFullIntegrity) return false;

            return m_componentStack.CanContinueBuild(sourceInventory, m_stockpile);
        }
示例#52
0
 public void ClearConstructionStockpile(MyInventory outputInventory)
 {
     if (!StockpileEmpty)
     {
         if (outputInventory != null && outputInventory.Owner.InventoryOwnerType == MyInventoryOwnerTypeEnum.Character)
         {
             MoveItemsFromConstructionStockpile(outputInventory);
         }
         else
         {
             m_stockpile.ClearSyncList();
             m_tmpItemList.Clear();
             foreach (var item in m_stockpile.GetItems())
             {
                 m_tmpItemList.Add(item);
             }
             foreach (var item in m_tmpItemList)
             {
                 RemoveFromConstructionStockpile(item);
             }
             CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList());
             m_stockpile.ClearSyncList();
         }
     }
     ReleaseConstructionStockpile();
 }
示例#53
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();
        }
示例#54
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();
        }
示例#55
0
        public void MoveItemsToConstructionStockpile(MyInventory fromInventory)
        {
            if (MySession.Static.CreativeMode)
                return;

            m_tmpComponents.Clear();
            GetMissingComponents(m_tmpComponents);

            if (m_tmpComponents.Count() != 0)
            {
                EnsureConstructionStockpileExists();

                m_stockpile.ClearSyncList();
                foreach (var kv in m_tmpComponents)
                {
                    var id = new MyDefinitionId(typeof(MyObjectBuilder_Component), kv.Key);
                    int amountAvailable = (int)fromInventory.GetItemAmount(id);
                    int moveAmount = Math.Min(kv.Value, amountAvailable);
                    if (moveAmount > 0)
                    {
                        fromInventory.RemoveItemsOfType(moveAmount, id);
                        m_stockpile.AddItems(moveAmount, new MyDefinitionId(typeof(MyObjectBuilder_Component), kv.Key));
                    }
                }
                CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList());
                m_stockpile.ClearSyncList();
            }
        }
示例#56
0
        public void MoveFirstItemToConstructionStockpile(MyInventory fromInventory)
        {
            if (MySession.Static.CreativeMode)
            {
                return;
            }

            EnsureConstructionStockpileExists();

            MyComponentStack.GroupInfo info = ComponentStack.GetGroupInfo(0);
            m_stockpile.ClearSyncList();
            if ((int)fromInventory.GetItemAmount(info.Component.Id) >= 1)
            {
                //Other player cant move your inventory and you also when trying to cosntruct so its safe already after check above ^^
                fromInventory.RemoveItemsOfType(1, info.Component.Id, MyItemFlags.None);
                //Debug.Assert(removed, "Item not found, but reported available few lines above");
                m_stockpile.AddItems(1, info.Component.Id);
            }
            CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList());
            m_stockpile.ClearSyncList();
        }
示例#57
0
        internal void RequestFillStockpile(MyInventory SourceInventory)
        {
            m_tmpComponents.Clear();
            GetMissingComponents(m_tmpComponents);

            foreach (var component in m_tmpComponents)
            {
                MyDefinitionId componentDefinition = new MyDefinitionId(typeof(MyObjectBuilder_Component), component.Key);
                if (SourceInventory.ContainItems(1, componentDefinition))
                {
                    CubeGrid.RequestFillStockpile(Position, SourceInventory);
                    return;
                }
            }
        }
示例#58
0
        public void DecreaseMountLevel(float grinderAmount, MyInventory outputInventory)
        {
            if (FatBlock != null)
                grinderAmount /= FatBlock.DisassembleRatio;
            else
                grinderAmount /= BlockDefinition.DisassembleRatio;

            grinderAmount = grinderAmount * BlockDefinition.IntegrityPointsPerSec;
            if (MySession.Static.CreativeMode)
            {
                ClearConstructionStockpile(outputInventory);
            }
            else
            {
                EnsureConstructionStockpileExists();
            }

            float oldBuildRatio = m_componentStack.BuildRatio;
            float newBuildRatio = (BuildIntegrity - grinderAmount) / BlockDefinition.MaxIntegrity;

            if (BlockDefinition.RatioEnoughForOwnership(BuildLevelRatio) && !BlockDefinition.RatioEnoughForOwnership(newBuildRatio))
            {
                if (FatBlock != null)
                {
                    FatBlock.OnIntegrityChanged(BuildIntegrity, Integrity, false, MySession.LocalPlayerId);
                }
            }

            long toolOwner = 0;
            if (outputInventory != null && outputInventory.Owner != null)
            {
                var moduleOwner = outputInventory.Owner as IMyComponentOwner<MyIDModule>;
                if (moduleOwner == null && outputInventory.Owner is MyCharacter)
                {
                    Debug.Assert((outputInventory.Owner as MyCharacter).ControllerInfo.Controller != null, "Controller was null on the character in DecreaseMountLevel!");
                    if ((outputInventory.Owner as MyCharacter).ControllerInfo.Controller == null)
                        toolOwner = (outputInventory.Owner as MyCharacter).ControllerInfo.ControllingIdentityId;
                }
                else
                {
                    MyIDModule module;
                    if (moduleOwner.GetComponent(out module))
                        toolOwner = module.Owner;
                }
            }

            UpdateHackingIndicator(newBuildRatio, oldBuildRatio, toolOwner);

            if (m_stockpile != null)
            {
                m_stockpile.ClearSyncList();
                m_componentStack.DecreaseMountLevel(grinderAmount, m_stockpile);
                CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList());
                m_stockpile.ClearSyncList();
            }
            else
            {
                m_componentStack.DecreaseMountLevel(grinderAmount, null);
            }

            bool modelChangeNeeded = BlockDefinition.ModelChangeIsNeeded(m_componentStack.BuildRatio, oldBuildRatio);

            MyCubeGrid.MyIntegrityChangeEnum integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.Damage;
            if (modelChangeNeeded)
            {
                UpdateVisual();

                if (FatBlock != null)
                {
                    int buildProgressID = CalculateCurrentModelID();
                    if ((buildProgressID == -1) || (BuildLevelRatio == 0f))
                    {
                        integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionEnd;
                    }
                    else if (buildProgressID == BlockDefinition.BuildProgressModels.Length - 1)
                    {
                        integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionBegin;
                    }
                    else
                    {
                        integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionProcess;
                    }
                }

                PlayConstructionSound(integrityChangeType, true);
                CreateConstructionSmokes();
            }

            if (CubeGrid.GridSystems.OxygenSystem != null)
            {
                CubeGrid.GridSystems.OxygenSystem.Pressurize();
            }

            CubeGrid.SyncObject.SendIntegrityChanged(this, integrityChangeType, toolOwner);
        }
示例#59
0
        public void IncreaseMountLevel(float welderMountAmount, long welderOwnerPlayerId, MyInventory outputInventory = null, float maxAllowedBoneMovement = 0.0f, bool isHelping = false, MyOwnershipShareModeEnum sharing = MyOwnershipShareModeEnum.Faction)
        {
            welderMountAmount *= BlockDefinition.IntegrityPointsPerSec;
            MySession.Static.PositiveIntegrityTotal += welderMountAmount;

            if (MySession.Static.CreativeMode)
            {
                ClearConstructionStockpile(outputInventory);
            }
            else
            {
                if (outputInventory != null && outputInventory.Owner.InventoryOwnerType == MyInventoryOwnerTypeEnum.Character)
                {
                    MoveItemsFromConstructionStockpile(outputInventory, MyItemFlags.Damaged);
                }
            }

            float oldPercentage = m_componentStack.BuildRatio;
            float oldDamage = CurrentDamage;

            if (!BlockDefinition.RatioEnoughForOwnership(BuildLevelRatio) && BlockDefinition.RatioEnoughForOwnership((BuildIntegrity + welderMountAmount) / BlockDefinition.MaxIntegrity))
            {
                if (FatBlock != null && outputInventory != null && !isHelping)
                {
                    FatBlock.OnIntegrityChanged(BuildIntegrity, Integrity, true, welderOwnerPlayerId, sharing);
                }
            }

            if (MyFakes.SHOW_DAMAGE_EFFECTS && FatBlock != null && !BlockDefinition.RationEnoughForDamageEffect((Integrity+welderMountAmount) / MaxIntegrity))
            {//stop effect
                FatBlock.SetDamageEffect(false);
            }


            if (m_stockpile != null)
            {
                m_stockpile.ClearSyncList();
                m_componentStack.IncreaseMountLevel(welderMountAmount, m_stockpile);
                CubeGrid.SyncObject.SendStockpileChanged(this, m_stockpile.GetSyncList());
                m_stockpile.ClearSyncList();
            }
            else
            {
                m_componentStack.IncreaseMountLevel(welderMountAmount, null);
            }

            if (m_componentStack.IsFullIntegrity)
            {
                ReleaseConstructionStockpile();
            }

            MyCubeGrid.MyIntegrityChangeEnum integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.Damage;
            if (BlockDefinition.ModelChangeIsNeeded(oldPercentage, m_componentStack.BuildRatio) || BlockDefinition.ModelChangeIsNeeded(m_componentStack.BuildRatio, oldPercentage))
            {
                if (FatBlock != null)
                {
                    // this needs to be detected here because for cubes the following call to UpdateVisual() set FatBlock to null when the construction is complete
                    if (m_componentStack.IsFunctional)
                    {
                        integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionEnd;
                    }
                }

                UpdateVisual();
                if (FatBlock != null)
                {
                    int buildProgressID = CalculateCurrentModelID();
                    if (buildProgressID == 0)
                    {
                        integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionBegin;
                    }
                    else if (!m_componentStack.IsFunctional)
                    {
                        integrityChangeType = MyCubeGrid.MyIntegrityChangeEnum.ConstructionProcess;
                    }
                }

                PlayConstructionSound(integrityChangeType);
                CreateConstructionSmokes();

                if (CubeGrid.GridSystems.OxygenSystem != null)
                {
                    CubeGrid.GridSystems.OxygenSystem.Pressurize();
                }
            }

            if (HasDeformation)
                CubeGrid.SetBlockDirty(this);

            CubeGrid.SyncObject.SendIntegrityChanged(this, integrityChangeType, 0);

            if (maxAllowedBoneMovement != 0.0f)
                FixBones(oldDamage, maxAllowedBoneMovement);
        }
示例#60
0
 public static bool TryGetInventory(this MyEntity thisEntity, out MyInventory inventory)
 {
     inventory = null;
     if (thisEntity.Components.Has<MyInventoryBase>())
     {
         inventory = GetInventory(thisEntity, 0);
     }
     return inventory != null;
 }