/// <summary> /// The capacity of the each container and all containers combined /// </summary> /// <param name="_containers">List with containers</param> /// <returns></returns> private string Capacity_Status(List <IMyCargoContainer> _containers) { VRage.MyFixedPoint currentVolume = 0; VRage.MyFixedPoint maxVolume = 0; string output = string.Empty; if (_containers.Count != 0) { for (int i = 0; i < _containers.Count; i++) { VRage.MyFixedPoint max = _containers [i].GetInventory().MaxVolume; VRage.MyFixedPoint current = _containers [i].GetInventory().CurrentVolume; currentVolume += current; maxVolume += max; double individualPercentage = (((double)current / (double)max) * 100); output += $" {( ( _containers [i].CustomName.Length >= 18 ) ? ( _containers [i].CustomName.Substring ( 0, 18 ) ) : ( _containers [i].CustomName ) )}: {individualPercentage.ToString ( "F" )}%\n"; } } else { return(null); } // Formula V / MV * 100 = P double percentage = (((double)currentVolume / (double)maxVolume) * 100); return($"{output}\nTotal: {percentage.ToString ( "F" )}%"); }
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); }
void AddToGlobalInventory( string TypeId, string SubtypeId, VRage.MyFixedPoint targetAmount) { AddGlobalInventorySlot(TypeId, SubtypeId); globalInventory[TypeId][SubtypeId].AddTargetAmount(targetAmount); }
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); }
void UpdateProduction() { if (autoAssemblers.Count == 0) { return; } // clear all queues foreach (IMyAssembler assembler in autoAssemblers) { assembler.ClearQueue(); assembler.CooperativeMode = true; } autoAssemblers[0].CooperativeMode = false; Dictionary <string, InventorySlot> missingItems = new Dictionary <string, InventorySlot>(); foreach (var kvp in globalInventory[componentType]) { if (kvp.Value.TargetAmount > 0 && kvp.Value.TargetAmount > kvp.Value.TotalAmount) { missingItems.Add(kvp.Key, kvp.Value); } } foreach (var kvp in globalInventory[ammoType]) { if (kvp.Value.TargetAmount > 0 && kvp.Value.TargetAmount > kvp.Value.TotalAmount) { missingItems.Add(kvp.Key, kvp.Value); } } // now add to production foreach (var kvp in missingItems.OrderBy(p => p.Value.Ratio)) { if (kvp.Value.TargetAmount == 0) { continue; } MyDefinitionId blueprint = MyDefinitionId.Parse("MyObjectBuilder_BlueprintDefinition/" + kvp.Key); VRage.MyFixedPoint missingAmount = kvp.Value.TargetAmount - kvp.Value.TotalAmount; if (TryAddToQueue(kvp.Key, missingAmount)) { continue; } if (TryAddToQueue(kvp.Key + "Component", missingAmount)) { continue; } if (TryAddToQueue(kvp.Key + "Magazine", missingAmount)) { continue; } } }
public VRage.MyFixedPoint Count() { VRage.MyFixedPoint Total = 0; for (int i = 0; i < Items.Count; i++) { Total += Items[i].Amount(); } return(Total); }
public void Main(string argument, UpdateType updateSource) { frame = display.DrawFrame(); VRage.MyFixedPoint totKg = 0; inventories.ForEach(delegate(IMyInventory i) { totKg += i.CurrentMass; }); draw(totKg.ToIntSafe()); frame.Dispose(); }
bool tryAddAssemblerTask(IMyProductionBlock assembler, string definition, VRage.MyFixedPoint count) { try { MyDefinitionId objectIdToAdd = new MyDefinitionId(); MyDefinitionId.TryParse(definition, out objectIdToAdd); assembler.AddQueueItem(objectIdToAdd, count); return(true); } catch (Exception e) { return(false); } }
bool TryQueue(MyDefinitionId item, VRage.MyFixedPoint amount, MyAssemblerMode mode) { foreach (var assembler in Assemblers) { if (assembler.CanUseBlueprint(item) && assembler.Mode == mode && assembler.IsQueueEmpty && !assembler.CooperativeMode) // Are these good conditions? { assembler.AddQueueItem(item, amount); return(true); } } return(false); }
public void Transfer() { Echo("###--- Transfersystem 2000 started"); List <IMyTerminalBlock> toCargoContainerList = new List <IMyTerminalBlock> (); List <IMyTerminalBlock> fromCargoContainerList = new List <IMyTerminalBlock> (); for (int nIndex = 0; nIndex < m_transferItemList.Length; nIndex++) { toCargoContainerList.Clear(); TransferItem transferItem = m_transferItemList[nIndex]; MyItemType itemType = GetItemType(transferItem.Type); GridTerminalSystem.GetBlocksOfType(toCargoContainerList, searchItem => searchItem.CustomName.Contains(transferItem.TagTo)); for (int nToContainerIndex = 0; nToContainerIndex < toCargoContainerList.Count; nToContainerIndex++) { IMyInventory toInventory = toCargoContainerList[nToContainerIndex].GetInventory(); fromCargoContainerList.Clear(); GridTerminalSystem.GetBlocksOfType(fromCargoContainerList, searchItem => searchItem.CustomName.Contains(transferItem.TagFrom)); for (int nFromContainerIndex = 0; nFromContainerIndex < fromCargoContainerList.Count; nFromContainerIndex++) { MyInventoryItem?steelPlateFoundTo = toInventory.FindItem(itemType); VRage.MyFixedPoint diffAmount = transferItem.Amount; if ((steelPlateFoundTo.HasValue)) { diffAmount = diffAmount - steelPlateFoundTo.Value.Amount; } if (0 < diffAmount) { IMyInventory fromInventory = fromCargoContainerList[nFromContainerIndex].GetInventory(); MyInventoryItem?steelPlateFound = fromInventory.FindItem(itemType); if (steelPlateFound.HasValue) { fromInventory.TransferItemTo(toInventory, steelPlateFound.Value, diffAmount); } } } } } Echo("###--- Transfersystem 2000 finished"); }
public static string GetFormatNumberStr(VRage.MyFixedPoint input) { int n = Math.Max(0, (int)input); if (n == 0) { return "0"; } else if (n < 10000) { return "#,,#"; } else if (n < 1000000) { return "###,,0,K"; } return string.Concat(Enumerable.Repeat("#", $"{n}".Length)) + "0,,#M"; }
private MyFixedPoint min(MyFixedPoint val1, int val2) { int amt = val1.ToIntSafe(); if (val2 <= amt) { return(val2); } else { return(val1); } }
bool TryAddToQueue(string type, VRage.MyFixedPoint amount) { try { MyDefinitionId blueprint = MyDefinitionId.Parse("MyObjectBuilder_BlueprintDefinition/" + type); autoAssemblers[0].AddQueueItem(blueprint, amount); return(true); } catch { return(false); } }
} // UnloadCargo method /// <summary> /// Not completed /// </summary> /// <param name="gts"></param> /// <param name="minUR"></param> public void ReactorRefuel(IMyGridTerminalSystem gts, VRage.MyFixedPoint minUR) { int i = 0; // counter int j = 0; // counter //IMyTerminalBlock reactor = null; //IMyTerminalBlock sourceReactor = null; blockList.Clear(); gts.GetBlocksOfType <IMyReactor>(blockList, g => g.CubeGrid != rc.CubeGrid); for (i = 0; i < blockList.Count; i++) { if (blockList[i].GetInventory(0).GetItems()[0].Amount < 2 * minUR) { blockList.Remove(blockList[i]); // remove item from list i = 0; // reset index to 0 } // if amount < 2 * minUR } // for i (block traverse) if (blockList.Count == 0) { return; } // no source reactors //reactor = GridTerminalSystem.GetBlockWithName(shipName + reactorName); // get ship reactor //if (reactor == null) // kill the program so it can be fixed //throw new Exception("ReactorRefuel: Cannot find reactor named " + shipName + reactorName); //sourceReactor = GridTerminalSystem.GetBlockWithName(baseReactorFuelName); // get source reactor //if (sourceReactor == null) //{ return; } // do not crash the program, return without refueling //if (reactor.GetInventory(0).GetItems()[0].Amount >= minUR) //{ return; } // no need to refuel //if (sourceReactor.GetInventory(0).GetItems()[0].Amount >= (2 * minUR)) //{ // sourceReactor.GetInventory(0).TransferItemTo(reactor.GetInventory(0), 0, null, true, // (minUR - reactor.GetInventory(0).GetItems()[0].Amount)); //} for (i = 0; i < reactorList.Count; i++) { if (reactorList[i].GetInventory(0).GetItems()[0].Amount < minUR) { } } } // ReactorRefuel method
public AttackDetector(StorageSetter storage, IMyGridTerminalSystem grid, IMyProgrammableBlock me, Action <string> echo, TimeSpan elapsedTime) : base(grid, me, echo, elapsedTime) { ammo = VRage.MyFixedPoint.DeserializeStringSafe(storage.getStorage()); turrets = Blocks.InGroupsNamed("Turrets"); log = new EasyLCD(Blocks.Named("LCD Panel Attacks Log")); beacon = Blocks.InGroupsNamed("Beacon Attack Detector").GetBlock(0); this.storage = storage; Every(5 * EasyAPI.Seconds, doWork); On("clear", delegate() { log.SetText(""); beacon.SetName("Beacon Attack Detector"); }); }
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); }
public void doWork() { VRage.MyFixedPoint newAmmo = turrets.Items().OfType("NATO_25x184mm").Count(); newAmmo = newAmmo + turrets.Items().OfType("Missile200mm").Count(); if (newAmmo < ammo) { string timestamp = DateTime.UtcNow.AddHours(3).ToString("dd.MM.yyyy HH:mm:ss"); log.SetText("[" + timestamp + "] Attack detected, fired " + (ammo - newAmmo) + " ammo; Remaining: " + newAmmo + "\n" + log.screen.GetPublicText()); beacon.SetName("!!! Attack detected at " + timestamp + " !!!"); } ammo = newAmmo; storage.setStorage(ammo.ToString()); }
private void tryMoveIce(IMyGasGenerator target) { //show("Attempting to move ice into "+target.CustomName); FoundItem item = findItem(new ItemProfile("ore/ice")); if (item != null) { MyFixedPoint amt = min(item.item.Amount, 1000); moveItem(item.source, target.GetInventory(), item.item, amt); } else { //show("Not found."); } }
void FillRefineries() { autoRefineryMaterial = ""; if (autoRefineries.Count == 0) { return; } // first find the material wich needs to be refined float minRatio = 999999.9f; foreach (string material in availableMaterials) { if (globalInventory[oreType][material].CargoAmount == 0) { continue; } if (globalInventory[ingotType][material].TargetAmount == 0) { continue; } float ratio = globalInventory[ingotType][material].Ratio; if (ratio < minRatio) { minRatio = ratio; autoRefineryMaterial = material; } } if (autoRefineryMaterial == "") { return; } VRage.MyFixedPoint amountPerRef = globalInventory[oreType][autoRefineryMaterial].CargoAmount; amountPerRef.RawValue /= autoRefineries.Count; if (amountPerRef > maxAutoRefineryOreAmount) { amountPerRef = maxAutoRefineryOreAmount; } foreach (var refinery in autoRefineries) { MoveItemFromStorageToInventory( new MyItemType(oreType, autoRefineryMaterial), refinery.GetInventory(0), amountPerRef); } }
public static VRage.MyFixedPoint RemoveMaxItems(this IMyInventory srcInventory, VRage.MyFixedPoint maxRemoveFP, MyObjectBuilder_PhysicalObject objectBuilder) { var contentId = objectBuilder.GetObjectId(); VRage.MyFixedPoint removedAmount = 0; if (!srcInventory.ContainItems(maxRemoveFP, objectBuilder)) { maxRemoveFP = srcInventory.GetItemAmount(contentId); } if (maxRemoveFP > 0) { srcInventory.RemoveItemsOfType(maxRemoveFP, contentId, MyItemFlags.None, false); removedAmount = maxRemoveFP; } return(maxRemoveFP); }
/// <summary> /// Storage info of the ship. Requers a key, which is writtin into the Custom name of an object, in order to locate each specific Object /// </summary> private void Storage_Status(LCDPos _position) { List <IMyInventory> Storage = new List <IMyInventory> (); VRage.MyFixedPoint MaxVolume = 0; VRage.MyFixedPoint CurrentVolume = 0; #region Collecting associated Inventories List <IMyTerminalBlock> AllBlocks = new List <IMyTerminalBlock> (); GridTerminalSystem.GetBlocks(AllBlocks); if (Storage.Count <= 0) { for (int i = 0; i < AllBlocks.Count; i++) { if (AllBlocks [i].CustomName.Contains(STORAGE_KEY)) { Storage.Add((IMyInventory)AllBlocks [i].GetInventory()); MaxVolume += AllBlocks [i].GetInventory().MaxVolume; CurrentVolume += AllBlocks [i].GetInventory().CurrentVolume; } } } else { Echo("No storage units on this ship"); } #endregion // Formula V / MV * 100 = P double Percentage = (((double)CurrentVolume / (double)MaxVolume) * 100); if (Percentage >= 50 && G_capacityAlert != true) { G_HUD [(int)_position].WritePublicText("\n<---VEHICLE IS HEAVY!--->", true); // In case the ships Storage Capacity reaches a point where the ship is less manuverable. G_HUD [(int)_position].SetValue("FontColor", G_alertColor [0]); G_capacityAlert = true; } else if (Percentage <= 49 && G_capacityAlert == true) { G_HUD [(int)_position].SetValue("FontColor", G_alertColor [1]); G_capacityAlert = false; } G_HUD [(int)_position].WritePublicText("\n<Volume>: " + Percentage.ToString("F") + "%", true); }
public static string GetFormatNumberStr(VRage.MyFixedPoint input) { int n = Math.Max(0, (int)input); if (n == 0) { return "0"; } else if (n < 10000) { return "#,,#"; } else if (n < 1000000) { return "###,,0,K"; } sb.Clear(); for (int i = $"{n}".Length; i > 0; --i) { sb.Append("#"); } return $"{sb}0,,.0M"; }
public bool SplitContainerContents(IMyCargoContainer container) { var inventory = ((Sandbox.ModAPI.Interfaces.IMyInventoryOwner)container).GetInventory(0); var items = inventory.GetItems(); // NB We only check the first item var item = items.Count > 0 ? items[0] : null; var amount = item != null ? (float)item.Amount : 0.0f; if (amount >= StackSize * 2.0f) { // Move to new stack VRage.MyFixedPoint newStackAmount = (VRage.MyFixedPoint)StackSize; inventory.TransferItemTo(inventory, 0, targetItemIndex: items.Count, stackIfPossible: false, amount: newStackAmount); return(true); } return(false); }
public override void UpdateBeforeSimulation100() { base.UpdateBeforeSimulation100(); if (m_generator.IsWorking) { if (IsInVoxel(m_generator as Sandbox.ModAPI.IMyTerminalBlock)) { IMyInventory inventory = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(1) as IMyInventory; VRage.MyFixedPoint amount = (VRage.MyFixedPoint)(2000 * (1 + (0.4 * m_generator.UpgradeValues["Productivity"]))); inventory.AddItems(amount, new MyObjectBuilder_Ore() { SubtypeName = "Stone" }); terminalBlock.RefreshCustomInfo(); } } }
private void tryMoveOre(string ore, Refinery refinery) { //show("Attempting to move "+ore+" into "+refinery.refinery.CustomName); FoundItem item = findItem(new ItemProfile("ore/" + ore)); if (item == null && ore == "scrap") { item = findItem(new ItemProfile("ingot/scrap")); } if (item != null) { MyFixedPoint amt = min(item.item.Amount, 1000); moveItem(item.source, refinery.refinery.InputInventory, item.item, amt); } else { //show("Not found."); } }
public string MetricFormat(VRage.MyFixedPoint fp, string formatter = "{0:f2}") { //string postfix = "g"; float K = 1000, T = 1000 * K, KT = 1000 * T, MT = 1000 * KT; float f = ((float)fp.ToIntSafe()); var postfixes = new List <String> { "", "k", "M", "G", "P" }; int i = 0; while (f / 1000 > 1) { i += 1; f /= 1000; } return(fill(string.Format(formatter, f), 5) + postfixes[i]); }
public static string FormatNumber(VRage.MyFixedPoint input) { string fmt; int n = Math.Max(0, (int)input); if (n < 10000) { fmt = "##"; } else if (n < 1000000) { fmt = "###0,K"; } else { fmt = "###0,,M"; } return(n.ToString(fmt, System.Globalization.CultureInfo.InvariantCulture)); }
void MoveItemFromStorageToInventory( MyItemType type, IMyInventory targetInv, VRage.MyFixedPoint amount ) { VRage.MyFixedPoint remainingAmount = amount; foreach (CargoContainer container in cargoContainers[Me.CubeGrid]) { IMyInventory inventory = container.container.GetInventory(); if (!inventory.IsConnectedTo(targetInv)) { continue; } for (int i = 0; i < inventory.ItemCount; ++i) { MyInventoryItem item = (MyInventoryItem)inventory.GetItemAt(i); if (item.Type != type) { continue; } if (!inventory.CanTransferItemTo(targetInv, item.Type)) { continue; } VRage.MyFixedPoint transferrableAmount = remainingAmount; if (item.Amount < transferrableAmount) { transferrableAmount = item.Amount; } if (inventory.TransferItemTo(targetInv, item, transferrableAmount)) { remainingAmount -= transferrableAmount; if (remainingAmount == 0) { return; } } } } }
// adds assembling or disassembling task for specified itemId and count public bool AddAssemblerTask(IMyProductionBlock assembler, string itemId, VRage.MyFixedPoint count) { var fixedItemId = "MyObjectBuilder_BlueprintDefinition/" + itemId.Split('/')[1]; if (fixedItemId.EndsWith("Item")) { fixedItemId = fixedItemId.Substring(0, fixedItemId.Count() - 4); } if (!tryAddAssemblerTask(assembler, fixedItemId, count)) { var fixedItemId2 = fixedItemId + "Component"; if (!tryAddAssemblerTask(assembler, fixedItemId2, count)) { Print(string.Format("AddQueueItem failed for {0}", itemId)); Print(string.Format("tried: {0}, {1}", fixedItemId, fixedItemId2)); return(false); } } //Print(string.Format("queued: {0} x {1}", itemId, count)); return(true); }
/// <summary> /// As long as ComputeAmountThatFits is not available for modding we have to try /// </summary> public static VRage.MyFixedPoint MaxFractionItemsAddable(this IMyInventory destInventory, VRage.MyFixedPoint maxNeeded, MyItemType itemType) { if (destInventory.CanItemsBeAdded(maxNeeded, itemType)) { return(maxNeeded); } VRage.MyFixedPoint maxPossible = 0; VRage.MyFixedPoint currentStep = (VRage.MyFixedPoint)((float)maxNeeded / 2); VRage.MyFixedPoint currentTry = 0; while (currentStep > VRage.MyFixedPoint.SmallestPossibleValue) { currentTry = maxPossible + currentStep; if (destInventory.CanItemsBeAdded(currentTry, itemType)) { maxPossible = currentTry; } currentStep = (VRage.MyFixedPoint)((float)currentStep / 2); } return(maxPossible); }
/// <summary> /// Updates uraniumMass with values from the reactors. /// </summary> void UpdateReactorUranium() { if (lastUpdate_uranium < updateInterval) return; lastUpdate_uranium = new TimeSpan(); uraniumMass = 0; GridTerminalSystem.GetBlocksOfType<IMyReactor>(blocks, BlockOnMyGrid); for (int bi = 0; bi < blocks.Count; bi++) { int inventoryCount = blocks[bi].GetInventoryCount(); for (int ii = 0; ii < inventoryCount; ii++) { VRage.Game.ModAPI.Ingame.IMyInventory inventory = blocks[bi].GetInventory(ii); uraniumMass += inventory.CurrentMass; } } Echo("Uranium: " + uraniumMass); }
public MissingStock(IMyInventory inventory, VRage.MyFixedPoint amount) { Inventory = inventory; Amount = amount; }