static bool Prefix(Building culprit) { PowerNet powerNet = culprit.PowerComp.PowerNet; Map map = culprit.Map; float totalEnergy = 0f; float totalEnergyHistoric = 0f; if (powerNet.batteryComps.Any((CompPowerBattery x) => x.StoredEnergy > 20f)) { foreach (CompPowerBattery batteryComp in powerNet.batteryComps) { totalEnergy += batteryComp.StoredEnergy; batteryComp.DrawPower(batteryComp.StoredEnergy); } totalEnergyHistoric = totalEnergy; foreach (CompPower transmitter in powerNet.transmitters) { CompSurgeProducer surgeProd = transmitter.parent.GetComp <CompSurgeProducer>(); if (surgeProd != null) { totalEnergy -= surgeProd.ProduceThing(totalEnergy); if (totalEnergy <= 0) { break; } } } } return(false); }
public static bool Drain(this PowerNet powerNet, float amount) { if (amount <= 0) { return(true); } if (AvailablePower(powerNet) < amount) { return(false); } foreach (var battery in powerNet.batteryComps) { var drain = battery.StoredEnergy > amount ? amount : battery.StoredEnergy; battery.DrawPower(drain); amount -= drain; if (amount <= 0) { break; } } return(true); }
public override string CompInspectStringExtra() { StringBuilder stringBuilder = new StringBuilder(); if (emergencyPowerEnabled) { PowerNet powerNet = parent.Map.powerNetGrid.TransmittedPowerNetAt(MonitoredCell); if (powerNet != null) { float maxEnergy = 0; float storedEnergy = 0; foreach (CompPowerBattery compPowerBattery in powerNet.batteryComps) { maxEnergy += compPowerBattery.Props.storedEnergyMax; storedEnergy += compPowerBattery.StoredEnergy; } if (maxEnergy > 0.0f) { stringBuilder.Append("CompRTPowerSwitch_MonitoredNetwork".Translate( storedEnergy.ToString("N0"), maxEnergy.ToString(), (storedEnergy / maxEnergy).ToStringPercent())); } else { stringBuilder.Append("CompRTPowerSwitch_MonitoredNetworkInvalid".Translate()); } } else { stringBuilder.Append("CompRTPowerSwitch_MonitoredNetworkInvalid".Translate()); } } return(stringBuilder.ToString()); }
private BatteryState GetBatteryState(PowerNet pn) { if (Find.TickManager.TicksGame - FirstTick > 60 && pn.batteryComps.Count() > 0) { float cegr = pn.CurrentEnergyGainRate(); float cse = pn.CurrentStoredEnergy(); //!pn.Map.gameConditionManager.ConditionIsActive(GameConditionDefOf.SolarFlare) // Avoid spamming the warning when browning out by checking for insufficient power and keeping the alert on. if (cse / (float)pn.batteryComps.Sum(bc => bc.Props.storedEnergyMax) < 0.05f && pn.powerComps.Any(pc => !pc.PowerOn && FlickUtility.WantsToBeOn(pc.parent) && !pc.parent.IsBrokenDown())) { return(BatteryState.Brownout); } if (cegr < 0) { float timeLeft = (cse / cegr / -60f); if (timeLeft <= Power_Alerts.drainingBatteriesThresholdSeconds) { return(BatteryState.Draining); } } } return(BatteryState.Normal); }
public static bool Prefix(PowerNet __instance) { HighVoltagePowerNet hvpn = __instance as HighVoltagePowerNet; hvpn.PowerNetTick(); return(false); }
public static bool DrawPowerFromNetwork(PowerNet powerNet, float amount, bool simulate = false) { var batteries = powerNet.batteryComps.OrderByDescending((CompPowerBattery arg) => arg.StoredEnergy); float totalEnergy = batteries.Sum((CompPowerBattery arg) => arg.StoredEnergy); if (totalEnergy < amount) { return(false); } if (simulate && totalEnergy >= amount) { return(true); } float drawnEnergy = 0; foreach (var current in batteries) { float num = Math.Min(current.StoredEnergy, amount - drawnEnergy); current.DrawPower(num); drawnEnergy += num; if (drawnEnergy >= amount) { break; } } return(true); }
public override string GetInspectString() { string desc = base.GetInspectString(); return(I18n.StatusString(Status, batteryRange.min, batteryRange.max, PowerNet.StorageLevel()) + (desc.NullOrEmpty() ? "" : $"\n{desc}")); }
public static bool Prefix(Building root, ref PowerNet __result) { MethodInfo ContiguousPowerBuildings = AccessTools.Method(typeof(PowerNetMaker), "ContiguousPowerBuildings"); IEnumerable <CompPower> comps = (IEnumerable <CompPower>)ContiguousPowerBuildings.Invoke(null, new object[] { root }); __result = new HighVoltagePowerNet(comps); return(false); }
private static bool Prefix(PowerNet __instance, ref float __result) { if (ZUtils.ZTracker.connectedPowerNets.connectedPowerNetsDict.TryGetValue(__instance, out ConnectedPowerNet connectedPowerNet)) { __result = connectedPowerNet.TotalStoredEnergy; return(false); } return(true); }
public float CurrentStoredEnergy(PowerNet powerNet) { float num = 0f; for (int i = 0; i < powerNet.batteryComps.Count; i++) { num += powerNet.batteryComps[i].StoredEnergy; } return(num); }
public static bool TryConsumeFeedstock(this PowerNet net, float feedstockNeeded) { if (feedstockNeeded <= 0f) { Log.Warning("[Replimat] " + "Tried to draw 0 feedstock!"); return(false); } List <Building_ReplimatFeedTank> feedstockTanks = net.GetTanks(); if (!feedstockTanks.NullOrEmpty()) { float totalAvailableFeedstock = feedstockTanks.Sum(x => x.storedFeedstock); feedstockTanks.Shuffle(); if (totalAvailableFeedstock >= feedstockNeeded) { float feedstockLeftToConsume = feedstockNeeded; foreach (var currentTank in feedstockTanks) { if (feedstockLeftToConsume > 0) { float num = Math.Min(feedstockLeftToConsume, currentTank.StoredFeedstock); currentTank.DrawFeedstock(num); feedstockLeftToConsume -= num; if (feedstockLeftToConsume <= 0) { return(true); } } else { return(true); } } Log.Warning("[Replimat] " + "Tried but tanks ran out of feedstock, needed:" + feedstockNeeded); return(false); } else { Log.Warning("[Replimat] " + " Tanks didn't have enough feedstock, needed:" + feedstockNeeded); return(false); } } Log.Warning("[Replimat] " + "Tried to draw feedstock from non-existent tanks!"); return(false); }
public float GetPowerNetCurrentGain(PowerNet net) { float num = 0f; for (int i = 0; i < net.powerComps.Count; i++) { if (net.powerComps[i].PowerOn) { num += net.powerComps[i].EnergyOutputPerTick; } } return(num); }
public void PowerNetUpdate(PowerNet net, HashSet <Building_BackupPowerAttachment> brokers) { // get desired power var users = net.powerComps .Select(p => (comp: p, broker: p.parent is Building building ? brokers.FirstOrDefault(b => b.Parent == building) : null, consumption: Consumption(p), currentProduction: CurrentProduction(p), potentialProduction: PotentialProduction(p))); var need = users.Sum(u => u.consumption); var production = users.Sum(u => u.currentProduction); var hasStorage = net.HasStorage(); var storageLevel = net.StorageLevel(); // Log.Debug( $"need: {need}, production: {production}, static: {staticProduction}" ); if (production > need || hasStorage && storageLevel > 0) { // try to shut backups off var overProduction = production - need; var backups = users.Where(u => u.broker != null && u.currentProduction > 0 && u.currentProduction <= overProduction && (!hasStorage || storageLevel >= u.broker.batteryRange.max) && u.broker.CanTurnOff()) .ToList(); if (backups.TryRandomElementByWeight(c => 1 / c.currentProduction, out var backup)) { backup.broker.TurnOff(); } } if (production < need || hasStorage && storageLevel < 1) { // try to turn backups on var backups = users.Where(u => u.broker != null && Math.Abs(u.currentProduction) < Mathf.Epsilon && u.potentialProduction > 0 && (!hasStorage || storageLevel <= u.broker.batteryRange.min)) .ToList(); if (backups.TryRandomElementByWeight(c => c.potentialProduction, out var backup)) { backup.broker.TurnOn(); } } }
public static float StorageLevel(this PowerNet net) { if (net == null || net.batteryComps.NullOrEmpty()) { return(0); } (float current, float max) = net.batteryComps .Select(b => (b.StoredEnergy, b.Props.storedEnergyMax)) .Aggregate((a, b) => ( a.StoredEnergy + b.StoredEnergy, a.storedEnergyMax + b.storedEnergyMax)); return(current / max); }
public void PowerNetUpdate(PowerNet net, HashSet <Building_BackupPowerAttachment> brokers) { // get desired power IEnumerable <(CompPowerTrader comp, Building_BackupPowerAttachment broker, float consumption, float currentProduction, float potentialProduction)> users = net.powerComps .Select(p => (comp: p, broker: p.parent is Building building ? brokers.FirstOrDefault(b => b.Parent == building) : null, consumption: Consumption(p), currentProduction: CurrentProduction(p), potentialProduction: PotentialProduction(p))); float need = users.Sum(u => u.consumption); float production = users.Sum(u => u.currentProduction); bool hasStorage = net.HasStorage(); float storageLevel = net.StorageLevel(); // Log.Debug( $"need: {need}, production: {production}, static: {staticProduction}" ); if (production > need || (hasStorage && storageLevel > 0)) { // try to shut backups off List <(CompPowerTrader comp, Building_BackupPowerAttachment broker, float consumption, float currentProduction, float potentialProduction)> backups = users.Where(u => u.broker != null && u.currentProduction > 0 && (u.currentProduction <= (production - need) || u.broker.runOnBatteriesOnly) && ((!hasStorage && !u.broker.runOnBatteriesOnly) || storageLevel >= u.broker.batteryRange.max) && u.broker.CanTurnOff()) .ToList(); if (backups.TryRandomElementByWeight(c => 1 / c.currentProduction, out (CompPowerTrader comp, Building_BackupPowerAttachment broker, float consumption, float currentProduction, float potentialProduction)backup)) { backup.broker.TurnOff(); } } if (production < need || (hasStorage && storageLevel < 1)) { // try to turn backups on List <(CompPowerTrader comp, Building_BackupPowerAttachment broker, float consumption, float currentProduction, float potentialProduction)> backups = users.Where(u => u.broker != null && Math.Abs(u.currentProduction) < Mathf.Epsilon && u.potentialProduction > 0 && (!hasStorage || storageLevel <= u.broker.batteryRange.min)) .ToList(); if (backups.TryRandomElementByWeight(c => c.potentialProduction, out (CompPowerTrader comp, Building_BackupPowerAttachment broker, float consumption, float currentProduction, float potentialProduction)backup)) { backup.broker.TurnOn(); } } }
public static void Postfix(ref IEnumerable <CompPower> newTransmitters, PowerNet __instance) { //doing a foreach to access the first and only comp in a Alternator network foreach (CompPower comp in newTransmitters) { if (comp.parent.GetComp <CompSteamAlternator>() != null) { __instance.hasPowerSource = true; foreach (CompPower p in __instance.powerComps) { p.transNet = __instance; } } } }
public static float AvailablePower(this PowerNet powerNet) { if (powerNet == null) { return(0); } float availablePower = 0; foreach (var battery in powerNet.batteryComps) { availablePower += battery.StoredEnergy; } return(availablePower); }
public static void PowerMetrics(PowerNet net, out float production, out float consumption) { consumption = 0; production = 0; foreach (CompPowerTrader comp in net.powerComps) { if (comp.EnergyOutputPerTick > 0f) { production += comp.EnergyOutputPerTick; } else { consumption += comp.EnergyOutputPerTick; } } }
public static bool TryConsumeFeedstock(this PowerNet net, float feedstockNeeded) { if (feedstockNeeded <= 0f) { return(false); } List <Building_ReplimatFeedTank> feedstockTanks = net.GetTanks(); if (!feedstockTanks.NullOrEmpty()) { float totalAvailableFeedstock = feedstockTanks.Sum(x => x.storedFeedstock); feedstockTanks.Shuffle(); if (totalAvailableFeedstock >= feedstockNeeded) { float feedstockLeftToConsume = feedstockNeeded; foreach (var currentTank in feedstockTanks) { if (feedstockLeftToConsume > 0) { float num = Math.Min(feedstockLeftToConsume, currentTank.StoredFeedstock); currentTank.DrawFeedstock(num); feedstockLeftToConsume -= num; if (feedstockLeftToConsume <= 0) { return(true); } } else { return(true); } } return(false); } else { return(false); } } return(false); }
public static void SetNetColor(PowerNet net) { if (net.powerComps.Count == 0 && net.batteryComps.Count == 0) // just conduits { netColors.SetOrAdd(net, ActiveCircuitsSettings.justConduits); return; } float production; float consumption; PowerMetrics(net, out production, out consumption); if (consumption == 0) // nothing using power { netColors.SetOrAdd(net, ActiveCircuitsSettings.nothingConnected); return; } float rate = consumption + production; if (rate < 0) { float stored = net.CurrentStoredEnergy(); if (stored < 5f) { netColors.SetOrAdd(net, ActiveCircuitsSettings.noPower); } else { netColors.SetOrAdd(net, ActiveCircuitsSettings.drainingPower); } return; } else // rate >= 0 { if (rate > 1.5 * consumption || net.CurrentStoredEnergy() >= consumption) // 1 day of power { netColors.SetOrAdd(net, ActiveCircuitsSettings.surplusPower); } else { netColors.SetOrAdd(net, ActiveCircuitsSettings.hasPower); } return; } }
private bool HasEnoughEnergy() { float?num; if (powerTrader == null) { num = null; } else { PowerNet powerNet = powerTrader.PowerNet; num = ((powerNet != null) ? new float?(powerNet.CurrentStoredEnergy()) : null); } float?num2 = num; float num3 = activePower; return(num2.GetValueOrDefault() >= num3 & num2 != null); }
public override void CompTick() { base.CompTick(); if (this?.PowerNet != null) { if (this.PowerOn) { if (curPowerNet != this.PowerNet) { curPowerNet = this.PowerNet; ZUtils.ZTracker.connectedPowerNets.RegisterTransmitter(this); } } else { ZUtils.ZTracker.connectedPowerNets.DeregisterTransmitter(this); } } }
public override string CompInspectStringExtra() { if (PowerNet == null) { return("PowerNotConnected".Translate()); } StringBuilder str = new StringBuilder(); str.AppendLine("VoidNetConverterLabel1".Translate((-PowerConsumption).ToString("f0"))); string value = (PowerNet.CurrentEnergyGainRate() / CompPower.WattsToWattDaysPerTick).ToString("F0"); string value2 = PowerNet.CurrentStoredEnergy().ToString("F0"); str.Append("PowerConnectedRateStored".Translate(value, value2)); if (Prefs.DevMode) { str.Append("\n" + "VoidNetConverterLabel2".Translate(energyCost.ToString("f3")) + "\n" + "VoidNetConverterLabel3".Translate((convertRate * 100).ToString("F0"))); } return(str.ToString()); }
public static void Postfix(PowerNetManager __instance, ref IntVec3 cell) { if (__instance.map.powerNetGrid.TransmittedPowerNetAt(cell) == null && cell.GetFirstBuilding(__instance.map).TryGetComp <CompSteamAlternator>() != null) { Building_Steam alternator = null; foreach (Thing thing in cell.GetThingList(__instance.map)) { if (thing.TryGetComp <CompSteamAlternator>() != null) { alternator = (Building_Steam)thing; break; } } PowerNet powerNet = new PowerNet(new List <CompPower> { alternator.PowerComp }); __instance.RegisterPowerNet(powerNet); PowerConnectionMaker.ConnectAllConnectorsToTransmitter(powerNet.transmitters[0]); } }
public void ProcessCell(IntVec3 cell) { PowerNet powerNet = PowerNetGrid.TransmittedPowerNetAt(cell); if (powerNet != null) { float maxEnergy = 0.0f; float storedEnergy = 0.0f; float currentRate = powerNet.CurrentEnergyGainRate(); foreach (CompPowerBattery compPowerBattery in powerNet.batteryComps) { maxEnergy += compPowerBattery.Props.storedEnergyMax; storedEnergy += compPowerBattery.StoredEnergy; } if (!compFlickable.SwitchIsOn && currentRate < 0 && storedEnergy < -currentRate * GenDate.TicksPerHour / 6.0f) { System.Reflection.FieldInfo fieldInfo = typeof(CompFlickable).GetField( "wantSwitchOn", // Thanks Haplo! System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); fieldInfo.SetValue(compFlickable, true); compFlickable.SwitchIsOn = true; FlickUtility.UpdateFlickDesignation(parent); } else { if (storedEnergy >= maxEnergy) { System.Reflection.FieldInfo fieldInfo = typeof(CompFlickable).GetField( "wantSwitchOn", // Thanks Haplo! System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); fieldInfo.SetValue(compFlickable, false); compFlickable.SwitchIsOn = false; FlickUtility.UpdateFlickDesignation(parent); } } } }
private void EnsureBatteriesConnectedAndMakeSense(Map map) { tmpThings.Clear(); tmpThings.AddRange(map.listerThings.ThingsInGroup(ThingRequestGroup.BuildingArtificial)); for (int i = 0; i < tmpThings.Count; i++) { CompPowerBattery compPowerBattery = tmpThings[i].TryGetComp <CompPowerBattery>(); if (compPowerBattery == null) { continue; } PowerNet powerNet = compPowerBattery.PowerNet; if (powerNet != null && HasAnyPowerGenerator(powerNet)) { continue; } map.powerNetManager.UpdatePowerNetsAndConnections_First(); Building newPowerGenerator2; if (TryFindClosestReachableNet(compPowerBattery.parent.Position, (PowerNet x) => HasAnyPowerGenerator(x), map, out PowerNet foundNet, out IntVec3 closestTransmitter)) { map.floodFiller.ReconstructLastFloodFillPath(closestTransmitter, tmpCells); if (canSpawnPowerGenerators) { int count = tmpCells.Count; IntRange maxDistanceBetweenBatteryAndTransmitter = MaxDistanceBetweenBatteryAndTransmitter; float a = maxDistanceBetweenBatteryAndTransmitter.min; IntRange maxDistanceBetweenBatteryAndTransmitter2 = MaxDistanceBetweenBatteryAndTransmitter; float chance = Mathf.InverseLerp(a, maxDistanceBetweenBatteryAndTransmitter2.max, count); if (Rand.Chance(chance) && TrySpawnPowerGeneratorNear(compPowerBattery.parent.Position, map, compPowerBattery.parent.Faction, out Building newPowerGenerator)) { SpawnTransmitters(compPowerBattery.parent.Position, newPowerGenerator.Position, map, compPowerBattery.parent.Faction); foundNet = null; } } if (foundNet != null) { SpawnTransmitters(tmpCells, map, compPowerBattery.parent.Faction); } }
public void ProcessCell(IntVec3 cell) { PowerNet powerNet = parent.Map.powerNetGrid.TransmittedPowerNetAt(cell); if (powerNet != null) { float maxEnergy = 0.0f; float storedEnergy = 0.0f; float currentRate = powerNet.CurrentEnergyGainRate(); foreach (CompPowerBattery compPowerBattery in powerNet.batteryComps) { maxEnergy += compPowerBattery.Props.storedEnergyMax; storedEnergy += compPowerBattery.StoredEnergy; } if (compFlickable.SwitchIsOn) { if (storedEnergy >= maxEnergy) { wantsSwitchOnField.SetValue(compFlickable, false); compFlickable.SwitchIsOn = false; FlickUtility.UpdateFlickDesignation(parent); } } else { if (currentRate <= 0 && storedEnergy <= -currentRate * GenDate.TicksPerHour / 6.0f) { wantsSwitchOnField.SetValue(compFlickable, true); compFlickable.SwitchIsOn = true; FlickUtility.UpdateFlickDesignation(parent); } } } }
public static bool HasStorage(this PowerNet net) { return(!net.batteryComps.NullOrEmpty()); }
public static List <Building_ReplimatFeedTank> GetTanks(this PowerNet net) { return(net.Map.listerThings.ThingsOfDef(ReplimatDef.ReplimatFeedTank).OfType <Building_ReplimatFeedTank>().Where(x => x.GetPowerComp.PowerNet == net && CanFindComputer(x, net)).ToList()); }
public static bool CanFindComputer(Building building, PowerNet net) { return(building.Map.listerThings.ThingsOfDef(ReplimatDef.ReplimatComputer).OfType <Building_ReplimatComputer>().Any(x => x.GetPowerComp.PowerNet == net && x.Working)); }