diff --git a/UXAssist/Common/GameConstants/ItemIds.cs b/UXAssist/Common/GameConstants/ItemIds.cs
index 1c41adb..aba8312 100644
--- a/UXAssist/Common/GameConstants/ItemIds.cs
+++ b/UXAssist/Common/GameConstants/ItemIds.cs
@@ -106,21 +106,6 @@ public static class ItemIds
SpaceWarper, DeuteronFuelRod
];
- ///
- /// All source items used to create 25 proliferators mk.III (not self-sprayed).
- ///
- public static readonly List<(int ItemId, float Count)> ProliferatorSources =
- [
- (OrganicCrystal, 60f),
- (CriticalPhoton, 20f),
- (Coal, 64f),
- (FireIce, 16f),
- (CircuitBoard, 32f),
- (ProliferatorMkI, 64f),
- (ProliferatorMkII, 40f),
- (ProliferatorMkIII, 25f)
- ];
-
/* Dark Fog materials used by production calculations. */
public static readonly int[] DarkFogItemIds =
[
diff --git a/UXAssist/Patches/BlueprintDescriptionPatch.cs b/UXAssist/Patches/BlueprintDescriptionPatch.cs
index b8cf291..e02ff34 100644
--- a/UXAssist/Patches/BlueprintDescriptionPatch.cs
+++ b/UXAssist/Patches/BlueprintDescriptionPatch.cs
@@ -25,25 +25,25 @@ public class BlueprintDescriptionPatch : PatchImpl
Inspectors.Clear();
}
- [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnCreate")]
+ [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnCreate))]
private static void OnCreate(UIBlueprintInspector __instance)
{
GetControls(__instance);
}
- [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnOpen")]
+ [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnOpen))]
private static void OnOpen(UIBlueprintInspector __instance)
{
GetControls(__instance)?.ResetSession();
}
- [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnClose")]
+ [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnClose))]
private static void OnClose(UIBlueprintInspector __instance)
{
if (Inspectors.TryGetValue(__instance, out var controls)) controls.ResetSession();
}
- [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnFree")]
+ [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnFree))]
private static void OnFree(UIBlueprintInspector __instance)
{
if (!Inspectors.TryGetValue(__instance, out var controls)) return;
@@ -51,7 +51,7 @@ public class BlueprintDescriptionPatch : PatchImpl
Inspectors.Remove(__instance);
}
- [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnDestroy")]
+ [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnDestroy))]
private static void OnDestroy(UIBlueprintInspector __instance)
{
OnFree(__instance);
@@ -287,13 +287,10 @@ public class BlueprintDescriptionPatch : PatchImpl
return;
}
- var fields = new[]
- {
- new BlueprintDescriptionField(I18NKeys.BlueprintPower.Translate(),
- description.Power.Length > 0 ? description.Power : null,
- I18NKeys.BlueprintPowerEnglish, I18NKeys.BlueprintPowerChinese)
- };
- var result = BlueprintDescriptionFields.TryUpdate(blueprint.externalFields, fields,
+ var powerField = new BlueprintDescriptionField(I18NKeys.BlueprintPower.Translate(),
+ description.Power.Length > 0 ? description.Power : null,
+ I18NKeys.BlueprintPowerEnglish, I18NKeys.BlueprintPowerChinese);
+ var result = BlueprintDescriptionFields.TryUpdate(blueprint.externalFields, powerField,
UIBlueprintInspector.kMaxFieldCount,
value => BlueprintData.Validate(blueprint.ExternalFieldEscape(value)),
blueprint.ExternalFieldUnescape, out var updated);
diff --git a/UXAssist/Production/AccumulatorExchangeAdapter.cs b/UXAssist/Production/AccumulatorExchangeAdapter.cs
index 693a67c..b1144a5 100644
--- a/UXAssist/Production/AccumulatorExchangeAdapter.cs
+++ b/UXAssist/Production/AccumulatorExchangeAdapter.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -68,8 +69,7 @@ public sealed class AccumulatorExchangeAdapter : IProductionProcessAdapter
}
else if (operatingParameters == null ||
!operatingParameters.TryGetValue("Mode0", out var selectedMode) ||
- double.IsNaN(selectedMode) || double.IsInfinity(selectedMode) ||
- selectedMode != Math.Truncate(selectedMode) ||
+ !Finite(selectedMode) || selectedMode != Math.Truncate(selectedMode) ||
selectedMode < -1 || selectedMode > 1)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
@@ -126,9 +126,4 @@ public sealed class AccumulatorExchangeAdapter : IProductionProcessAdapter
? Array.Empty>() : outputs);
return true;
}
-
- private static bool FinitePositive(double value)
- {
- return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
- }
}
diff --git a/UXAssist/Production/BlackBoxMaterialClassifier.cs b/UXAssist/Production/BlackBoxMaterialClassifier.cs
index 58fc707..faf1c17 100644
--- a/UXAssist/Production/BlackBoxMaterialClassifier.cs
+++ b/UXAssist/Production/BlackBoxMaterialClassifier.cs
@@ -42,17 +42,15 @@ internal sealed class BlackBoxItemClassification
{
public bool IsFinalProduct { get; }
public bool IsResearchProduct { get; }
- public bool IsIntermediate { get; }
public double IntermediateShortage { get; }
public double? OverbuildSurplus { get; }
public double? CoproductSurplus { get; }
- public BlackBoxItemClassification(bool isFinalProduct, bool isResearchProduct, bool isIntermediate,
- double intermediateShortage, double? overbuildSurplus, double? coproductSurplus)
+ public BlackBoxItemClassification(bool isFinalProduct, bool isResearchProduct, double intermediateShortage,
+ double? overbuildSurplus, double? coproductSurplus)
{
IsFinalProduct = isFinalProduct;
IsResearchProduct = isResearchProduct;
- IsIntermediate = isIntermediate;
IntermediateShortage = intermediateShortage;
OverbuildSurplus = overbuildSurplus;
CoproductSurplus = coproductSurplus;
@@ -62,6 +60,7 @@ internal sealed class BlackBoxItemClassification
internal static class BlackBoxMaterialClassifier
{
internal const double Tolerance = 1e-9;
+ private const int MaximumSteadyStatePasses = 10000;
private sealed class ReductionGroup
{
@@ -148,7 +147,7 @@ internal static class BlackBoxMaterialClassifier
overbuild = Math.Min(Math.Max(0, originalNet),
Math.Max(0, originalNet - remainingBalance[itemId]));
var necessaryJointProduction = groups.Sum(group => NecessaryJointProduction(group, itemId,
- originalBalance, remainingBalance, protectedItems, intermediateItems));
+ originalBalance, remainingBalance, protectedItems));
var internalConsumption = groups.Sum(group =>
group.Source.NetPerBuilding.TryGetValue(itemId, out var amount) && amount < -Tolerance
? -amount * (group.Count - group.Removed) : 0);
@@ -161,17 +160,17 @@ internal static class BlackBoxMaterialClassifier
var isResearchProduct = finalKnown && researchMatrixSinks.Contains(itemId) && originalNet > Tolerance;
classification[itemId] = new BlackBoxItemClassification(
finalKnown && finalItems.Contains(itemId) || isResearchProduct, isResearchProduct,
- isIntermediate, isIntermediate ? Math.Max(0, -originalNet) : 0, overbuild, coproduct);
+ isIntermediate ? Math.Max(0, -originalNet) : 0, overbuild, coproduct);
}
steadyStateBalance = CalculateSteadyStateBalance(groups, originalBalance, remainingBalance,
- protectedItems, intermediateItems);
+ protectedItems);
return classification;
}
private static double NecessaryJointProduction(ReductionGroup group, int itemId,
IReadOnlyDictionary originalBalance, IReadOnlyDictionary remainingBalance,
- ISet protectedItems, ISet intermediateItems)
+ ISet protectedItems)
{
var retained = group.Count - group.Removed;
if (retained == 0 || !group.Source.HasJointProducts ||
@@ -182,10 +181,7 @@ internal static class BlackBoxMaterialClassifier
foreach (var flow in group.Source.NetPerBuilding)
{
if (flow.Key == itemId || flow.Value <= Tolerance) continue;
- double minimum;
- if (protectedItems.Contains(flow.Key)) minimum = originalBalance[flow.Key];
- else if (intermediateItems.Contains(flow.Key)) minimum = Math.Min(0, originalBalance[flow.Key]);
- else continue;
+ var minimum = MinimumBalance(flow.Key, originalBalance, protectedItems);
var available = Math.Floor((remainingBalance[flow.Key] - minimum + Tolerance) / flow.Value);
removable = Math.Min(removable, Math.Max(0, available));
}
@@ -195,14 +191,15 @@ internal static class BlackBoxMaterialClassifier
private static IReadOnlyDictionary CalculateSteadyStateBalance(
IReadOnlyList groups, IReadOnlyDictionary originalBalance,
- IReadOnlyDictionary remainingBalance, ISet protectedItems, ISet intermediateItems)
+ IReadOnlyDictionary remainingBalance, ISet protectedItems)
{
var balance = remainingBalance.ToDictionary(entry => entry.Key, entry => entry.Value);
var available = groups.ToDictionary(group => group, group => (double)(group.Count - group.Removed));
- bool changed;
- do
+ // A lossless cycle, such as charging and discharging accumulators, can pass a tiny leftover around
+ // indefinitely; stopping early only leaves the input estimate conservative.
+ for (var pass = 0; pass < MaximumSteadyStatePasses; pass++)
{
- changed = false;
+ var changed = false;
foreach (var group in groups)
{
if (!group.Source.NetPerBuilding.Values.Any(value => value > Tolerance)) continue;
@@ -210,10 +207,7 @@ internal static class BlackBoxMaterialClassifier
foreach (var flow in group.Source.NetPerBuilding)
{
if (flow.Value <= Tolerance) continue;
- double minimum;
- if (protectedItems.Contains(flow.Key)) minimum = originalBalance[flow.Key];
- else if (intermediateItems.Contains(flow.Key)) minimum = Math.Min(0, originalBalance[flow.Key]);
- else continue;
+ var minimum = MinimumBalance(flow.Key, originalBalance, protectedItems);
reducible = Math.Min(reducible, Math.Max(0, (balance[flow.Key] - minimum) / flow.Value));
}
@@ -223,11 +217,21 @@ internal static class BlackBoxMaterialClassifier
available[group] -= reducible;
changed = true;
}
- } while (changed);
+
+ if (!changed) break;
+ }
return balance;
}
+ // Every positive process output is a protected or intermediate item. Protected balances may not fall below
+ // their full-load value, and intermediates may not gain a new or larger shortage.
+ private static double MinimumBalance(int itemId, IReadOnlyDictionary originalBalance,
+ ISet protectedItems)
+ {
+ return protectedItems.Contains(itemId) ? originalBalance[itemId] : Math.Min(0, originalBalance[itemId]);
+ }
+
private static bool CanRemove(IReadOnlyDictionary netPerBuilding,
IReadOnlyDictionary originalBalance, IReadOnlyDictionary remainingBalance,
ISet protectedItems, ISet intermediateItems)
diff --git a/UXAssist/Production/BlueprintDescriptionText.cs b/UXAssist/Production/BlueprintDescriptionText.cs
index 6c253e4..e71d7eb 100644
--- a/UXAssist/Production/BlueprintDescriptionText.cs
+++ b/UXAssist/Production/BlueprintDescriptionText.cs
@@ -2,7 +2,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
-using System.Text;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -64,6 +64,7 @@ public sealed class BlueprintDescriptionText
public static class BlueprintDescriptionFormatter
{
private const double Tolerance = 1e-9;
+ private static readonly string[] PowerUnits = { "W", "kW", "MW", "GW", "TW" };
public static BlueprintDescriptionText Format(ProductionReport report, Func itemTag,
BlueprintDescriptionLabels labels)
@@ -153,18 +154,27 @@ public static class BlueprintDescriptionFormatter
{
if (!watts.HasValue) return labels.Unknown;
var value = watts.Value;
- if (value >= 1e12) return FormatNumber(value / 1e12) + "TW";
- if (value >= 1e9) return FormatNumber(value / 1e9) + "GW";
- if (value >= 1e6) return FormatNumber(value / 1e6) + "MW";
- if (value >= 1e3) return FormatNumber(value / 1e3) + "kW";
- return FormatNumber(value) + "W";
+ var unit = 0;
+ // Choose the unit after rounding so that 999.999 W displays as 1kW rather than 1000W.
+ while (unit < PowerUnits.Length - 1 && RoundForDisplay(value) >= 1000)
+ {
+ value /= 1000;
+ unit++;
+ }
+
+ return FormatNumber(value) + PowerUnits[unit];
+ }
+
+ private static double RoundForDisplay(double value)
+ {
+ return Math.Round(value, value < 1 ? 3 : 2, MidpointRounding.AwayFromZero);
}
private static string FormatNumber(double value)
{
- if (double.IsNaN(value) || double.IsInfinity(value) || value < 0)
+ if (!FiniteNonnegative(value))
throw new InvalidOperationException("A blueprint report contains an invalid rate or power value.");
- var rounded = Math.Round(value, value < 1 ? 3 : 2, MidpointRounding.AwayFromZero);
+ var rounded = RoundForDisplay(value);
if (rounded > 0 || value == 0)
return rounded.ToString(value < 1 ? "0.###" : "0.##", CultureInfo.InvariantCulture);
var precise = value.ToString("0.######", CultureInfo.InvariantCulture);
@@ -215,74 +225,41 @@ public static class BlueprintDescriptionFields
return true;
}
- public static BlueprintFieldUpdateResult TryUpdate(string existing, IReadOnlyList fields,
+ // Updates the first matching field in place and drops other matches; a null value removes them all. A new field
+ // is appended only when it fits, so other fields are never removed to make room.
+ public static BlueprintFieldUpdateResult TryUpdate(string existing, BlueprintDescriptionField field,
int maximumFields, Func escape, Func unescape, out string updated)
{
updated = existing;
- if (fields == null || escape == null || unescape == null)
- throw new ArgumentNullException(fields == null ? nameof(fields) : escape == null ? nameof(escape) : nameof(unescape));
+ if (field == null || escape == null || unescape == null)
+ throw new ArgumentNullException(field == null ? nameof(field) : escape == null ? nameof(escape) : nameof(unescape));
if (maximumFields < 0 || !IsNativeFormatValid(existing))
return BlueprintFieldUpdateResult.InvalidFields;
+ var generated = field.Value == null ? null : escape(field.Title) + ":" + escape(field.Value);
var parts = (existing ?? "").Split(';');
- var matches = new int[parts.Length];
- var found = new bool[fields.Count];
- var nativeCount = 0;
- var removedCount = 0;
+ var entries = new List();
+ var replaced = false;
for (var index = 0; index < parts.Length - 1; index++)
{
- var delimiter = parts[index].IndexOf(':');
- nativeCount++;
- var name = unescape(parts[index].Substring(0, delimiter));
- for (var fieldIndex = 0; fieldIndex < fields.Count; fieldIndex++)
+ if (!field.Matches(unescape(parts[index].Substring(0, parts[index].IndexOf(':')))))
{
- if (!fields[fieldIndex].Matches(name)) continue;
- if (fields[fieldIndex].Value == null || found[fieldIndex])
- {
- matches[index] = -1;
- removedCount++;
- }
- else
- {
- matches[index] = fieldIndex + 1;
- found[fieldIndex] = true;
- }
- break;
+ entries.Add(parts[index]);
+ }
+ else if (generated != null && !replaced)
+ {
+ entries.Add(generated);
+ replaced = true;
}
}
- var missingCount = 0;
- for (var index = 0; index < fields.Count; index++)
- if (!found[index] && fields[index].Value != null) missingCount++;
- if (nativeCount - removedCount + missingCount > maximumFields)
- return BlueprintFieldUpdateResult.CapacityExceeded;
-
- var serialized = new StringBuilder();
- for (var index = 0; index < parts.Length - 1; index++)
+ if (generated != null && !replaced)
{
- var match = matches[index];
- if (match < 0) continue;
- if (match > 0)
- {
- var field = fields[match - 1];
- serialized.Append(escape(field.Title)).Append(':').Append(escape(field.Value));
- }
- else
- {
- serialized.Append(parts[index]);
- }
-
- serialized.Append(';');
+ if (entries.Count >= maximumFields) return BlueprintFieldUpdateResult.CapacityExceeded;
+ entries.Add(generated);
}
- for (var index = 0; index < fields.Count; index++)
- {
- if (!found[index] && fields[index].Value != null)
- serialized.Append(escape(fields[index].Title)).Append(':').Append(escape(fields[index].Value))
- .Append(';');
- }
-
- updated = serialized.ToString();
+ updated = string.Concat(entries.Select(entry => entry + ";"));
return BlueprintFieldUpdateResult.Updated;
}
}
diff --git a/UXAssist/Production/BlueprintSelectionReader.cs b/UXAssist/Production/BlueprintSelectionReader.cs
index 15a17d1..eb25e36 100644
--- a/UXAssist/Production/BlueprintSelectionReader.cs
+++ b/UXAssist/Production/BlueprintSelectionReader.cs
@@ -35,13 +35,11 @@ public sealed class BlueprintSelectionCapture
public static class BlueprintSelectionReader
{
- public static BlueprintSelectionCapture Capture(PlanetFactory factory, IEnumerable selectedObjectIds)
- {
- return Capture(factory, selectedObjectIds, null);
- }
+ // Native station parameters store charging power at this index, followed by other station settings.
+ private const int StationSettingsIndex = 320;
public static BlueprintSelectionCapture Capture(PlanetFactory factory, IEnumerable selectedObjectIds,
- BlueprintSelectionContext context)
+ BlueprintSelectionContext context = null)
{
var catalog = ProductionCatalogService.Current;
if (factory == null || catalog == null)
@@ -81,21 +79,18 @@ public static class BlueprintSelectionReader
var operation = new Dictionary();
var speedFactor = GetLiveSpeed(factory, objectId, parameters.type, operation);
AddSettings(parameters, operation);
+ var storedParameters = objectId < 0 ? factory.prebuildPool[-objectId].parameters : null;
if (building.Kind == ProductionBuildingKind.Logistics)
{
- if (objectId > 0)
- CaptureLiveChargePower(factory, objectId, operation);
- else
- {
- ref var prebuild = ref factory.prebuildPool[-objectId];
- CaptureStoredChargePower(building, parameters, prebuild.parameters, operation);
- }
+ if (objectId > 0) CaptureLiveChargePower(factory, objectId, operation);
+ else CaptureStoredChargePower(building, parameters, storedParameters, operation);
}
if (operation.ContainsKey("ResearchMode")) CaptureResearchSettings(factory, operation);
switch (building.Kind)
{
case ProductionBuildingKind.Miner:
CaptureMiningSettings(factory, objectId, building, operation);
+ if (objectId < 0) CaptureStoredMinerSpeed(parameters, storedParameters, operation);
break;
case ProductionBuildingKind.Collector:
CaptureCollectionSettings(factory, operation);
@@ -177,6 +172,8 @@ public static class BlueprintSelectionReader
operation["ResearchMatrixSink"] = 1;
if (building.Kind == ProductionBuildingKind.Logistics)
CaptureStoredChargePower(building, parameters, blueprint.parameters, operation);
+ else if (building.Kind == ProductionBuildingKind.Miner)
+ CaptureStoredMinerSpeed(parameters, blueprint.parameters, operation);
ApplySupplied(context?.OperatingParametersByIndex, blueprint.index, operation);
snapshots.Add(CreateSnapshot(catalog, building, 0, parameters, parameters.recipeId, null, operation,
diagnostics));
@@ -231,8 +228,9 @@ public static class BlueprintSelectionReader
{
case BuildingType.Station:
if (storedParameters != null &&
- storedParameters.Length >= BuildingParameters.kStationParamsLength && storedParameters[320] > 0)
- watts = storedParameters[320] * ProductionUnits.TicksPerSecond;
+ storedParameters.Length >= BuildingParameters.kStationParamsLength &&
+ storedParameters[StationSettingsIndex] > 0)
+ watts = storedParameters[StationSettingsIndex] * ProductionUnits.TicksPerSecond;
break;
case BuildingType.Dispenser:
if (storedParameters != null && storedParameters.Length >= BuildingParameters.kAddonParamsLength)
@@ -250,6 +248,17 @@ public static class BlueprintSelectionReader
operation["ChargePowerWatts"] = watts;
}
+ // Advanced Mining Machines store their speed with the station settings; native construction restores it.
+ private static void CaptureStoredMinerSpeed(BuildingParameters parameters, int[] storedParameters,
+ IDictionary operation)
+ {
+ if (parameters.type == BuildingType.Station && storedParameters != null &&
+ storedParameters.Length >= BuildingParameters.kStationParamsLength &&
+ storedParameters[StationSettingsIndex] > 0 && storedParameters[StationSettingsIndex + 9] > 0)
+ operation["MachineSpeedFactor"] =
+ storedParameters[StationSettingsIndex + 9] / ProductionUnits.FixedPointScale;
+ }
+
private static ProductionBuildingSnapshot CreateSnapshot(ProductionCatalog catalog, ProductionBuilding building,
int objectId, BuildingParameters parameters, int recipeId, double? speedFactor,
Dictionary operation, ICollection diagnostics)
diff --git a/UXAssist/Production/FactoryBlackBoxAnalyzer.cs b/UXAssist/Production/FactoryBlackBoxAnalyzer.cs
index d73626f..4aa5c3e 100644
--- a/UXAssist/Production/FactoryBlackBoxAnalyzer.cs
+++ b/UXAssist/Production/FactoryBlackBoxAnalyzer.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -64,7 +65,6 @@ public sealed class FactoryBlackBoxAnalyzer
var grossConsumption = new SortedDictionary();
var producers = new Dictionary>();
var consumers = new Dictionary>();
- var smallestProducer = new Dictionary();
var hasResearchMatrixSink = false;
var uncertainDemandItems = new HashSet();
var selectedIds = new HashSet();
@@ -137,8 +137,7 @@ public sealed class FactoryBlackBoxAnalyzer
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The selected logistics facility needs its configured charging power.",
buildingItemId: snapshot.BuildingItemId));
- else if (chargePowerWatts < 0 || double.IsNaN(chargePowerWatts) ||
- double.IsInfinity(chargePowerWatts * snapshot.Count))
+ else if (!FiniteNonnegative(chargePowerWatts * snapshot.Count))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected logistics charging power must be finite and nonnegative.",
buildingItemId: snapshot.BuildingItemId));
@@ -147,9 +146,7 @@ public sealed class FactoryBlackBoxAnalyzer
if (logisticsWatts.HasValue) logisticsConsumptionWatts += logisticsWatts.Value;
else logisticsPowerComplete = false;
- groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count,
- logisticsWatts, logisticsWatts, Array.Empty>(),
- Array.Empty>()));
+ groups.Add(PowerOnlyGroup(snapshot.Count, logisticsWatts));
continue;
}
@@ -163,9 +160,7 @@ public sealed class FactoryBlackBoxAnalyzer
var idleWatts = (building.Kind == ProductionBuildingKind.Auxiliary
? building.WorkingPowerWatts : building.IdlePowerWatts) * snapshot.Count;
factoryConsumptionWatts += idleWatts;
- groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count,
- idleWatts, idleWatts, Array.Empty>(),
- Array.Empty>()));
+ groups.Add(PowerOnlyGroup(snapshot.Count, idleWatts));
continue;
}
}
@@ -208,9 +203,7 @@ public sealed class FactoryBlackBoxAnalyzer
{
if (!IsResearchModeLab(building, snapshot)) totalPowerKnown = false;
factoryConsumptionWatts += knownWatts;
- groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count,
- knownWatts, knownWatts, Array.Empty>(),
- Array.Empty>()));
+ groups.Add(PowerOnlyGroup(snapshot.Count, knownWatts));
}
else
{
@@ -222,26 +215,20 @@ public sealed class FactoryBlackBoxAnalyzer
if (diagnostic != null) diagnostics.Add(diagnostic);
if (!process.PowerKnown) totalPowerKnown = false;
- if (process.WorkingPowerWatts < 0 || double.IsNaN(process.WorkingPowerWatts) ||
- double.IsInfinity(process.WorkingPowerWatts * snapshot.Count)) factoryPowerComplete = false;
+ if (!FiniteNonnegative(process.WorkingPowerWatts * snapshot.Count)) factoryPowerComplete = false;
var cycleRate = process.CyclesPerBuildingPerMinute;
- var output = Scale(process.OutputsPerCycle, cycleRate * snapshot.Count);
- var input = Scale(process.InputsPerCycle, cycleRate * snapshot.Count);
+ var output = ScaleFlows(process.OutputsPerCycle, cycleRate * snapshot.Count);
+ var input = ScaleFlows(process.InputsPerCycle, cycleRate * snapshot.Count);
var groupIndex = groups.Count;
foreach (var flow in output)
{
- Add(grossProduction, flow.Key, flow.Value);
+ AddFlow(grossProduction, flow.Key, flow.Value);
AddGroup(producers, flow.Key, groupIndex);
- var perBuildingNet = (process.OutputsPerCycle[flow.Key] -
- (process.InputsPerCycle.TryGetValue(flow.Key, out var consumed) ? consumed : 0)) * cycleRate;
- if (perBuildingNet > 1e-9 &&
- (!smallestProducer.TryGetValue(flow.Key, out var previous) || perBuildingNet < previous))
- smallestProducer[flow.Key] = perBuildingNet;
}
foreach (var flow in input)
{
- Add(grossConsumption, flow.Key, flow.Value);
+ AddFlow(grossConsumption, flow.Key, flow.Value);
AddGroup(consumers, flow.Key, groupIndex);
}
@@ -273,19 +260,13 @@ public sealed class FactoryBlackBoxAnalyzer
var produced = grossProduction.TryGetValue(itemId, out var p) ? p : 0;
var consumed = grossConsumption.TryGetValue(itemId, out var c) ? c : 0;
var net = produced - consumed;
- var threshold = smallestProducer.TryGetValue(itemId, out var single) ? single : 0;
var classification = classifications[itemId];
- var isFinalProduct = classification.IsFinalProduct;
flows.Add(new ProductionItemFlow(itemId, produced, consumed, 0, 0, 0,
- Math.Max(0, net), Math.Max(0, -net), isFinalProduct,
- classification.IsIntermediate && !matrixSinkItems.Contains(itemId) &&
- net > 1e-9 && threshold > 0 &&
- net + 1e-9 >= threshold,
- threshold, producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty(),
+ Math.Max(0, net), Math.Max(0, -net), classification.IsFinalProduct,
+ producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty(),
consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty(),
classification.IntermediateShortage, classification.OverbuildSurplus,
- classification.CoproductSurplus,
- steadyStateBalance == null ? null : Math.Max(0, -steadyStateBalance[itemId]),
+ classification.CoproductSurplus, Math.Max(0, -steadyStateBalance[itemId]),
classification.IsResearchProduct));
}
@@ -335,17 +316,13 @@ public sealed class FactoryBlackBoxAnalyzer
watts = 0;
if (IsResearchModeLab(building, snapshot))
{
+ // Research-mode labs only receive extra products, and only when a proliferation level exists.
var multiplier = 1.0;
- if (mode != ProliferationMode.None)
- {
- if (mode != ProliferationMode.ExtraProducts) return false;
- if (_catalog.MaximumProliferationLevel > 0 &&
- !_catalog.TryGetProliferation(_catalog.MaximumProliferationLevel,
- out _, out _, out multiplier)) return false;
- }
-
+ if (mode != ProliferationMode.None &&
+ !_catalog.TryGetProliferation(_catalog.MaximumProliferationLevel, out _, out _, out multiplier))
+ return false;
watts = building.WorkingPowerWatts * multiplier * snapshot.Count;
- return watts > 0 && !double.IsNaN(watts) && !double.IsInfinity(watts);
+ return FinitePositive(watts);
}
if (diagnostic?.Code != ProductionDiagnosticCode.MissingOperatingParameter) return false;
@@ -354,10 +331,10 @@ public sealed class FactoryBlackBoxAnalyzer
var speed = snapshot.OperatingParameters.TryGetValue("MachineSpeedFactor", out var capturedSpeed)
? capturedSpeed : 1;
- if (speed <= 0 || double.IsNaN(speed) || double.IsInfinity(speed)) return false;
+ if (!FinitePositive(speed)) return false;
var ratio = speed * speed;
watts = (building.WorkingPowerWatts * ratio + building.IdlePowerWatts * (1 - ratio)) * snapshot.Count;
- return watts >= 0 && !double.IsNaN(watts) && !double.IsInfinity(watts);
+ return FiniteNonnegative(watts);
}
private static bool IsResearchModeLab(ProductionBuilding building, ProductionBuildingSnapshot snapshot)
@@ -367,24 +344,9 @@ public sealed class FactoryBlackBoxAnalyzer
snapshot.OperatingParameters.TryGetValue("ResearchMode", out var researchMode) && researchMode == 1;
}
- private static Dictionary Scale(IReadOnlyDictionary flows, double factor)
+ private static ProductionGroupFlow PowerOnlyGroup(int count, double? watts)
{
- return flows.ToDictionary(entry => entry.Key, entry => entry.Value * factor);
- }
-
- private static void Add(IDictionary flows, int itemId, double count)
- {
- flows[itemId] = (flows.TryGetValue(itemId, out var previous) ? previous : 0) + count;
- }
-
- private static void AddGroup(IDictionary> groups, int itemId, int index)
- {
- if (!groups.TryGetValue(itemId, out var indices))
- {
- indices = new List();
- groups[itemId] = indices;
- }
-
- indices.Add(index);
+ return new ProductionGroupFlow(null, count, 0, count, count, watts, watts,
+ Array.Empty>(), Array.Empty>());
}
}
diff --git a/UXAssist/Production/FractionationProcessAdapter.cs b/UXAssist/Production/FractionationProcessAdapter.cs
index 4df9731..ef041c4 100644
--- a/UXAssist/Production/FractionationProcessAdapter.cs
+++ b/UXAssist/Production/FractionationProcessAdapter.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -75,9 +76,4 @@ public sealed class FractionationProcessAdapter : IProductionProcessAdapter
throughput, watts, building != null, throughput);
return true;
}
-
- private static bool FinitePositive(double value)
- {
- return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
- }
}
diff --git a/UXAssist/Production/FuelGenerationAdapter.cs b/UXAssist/Production/FuelGenerationAdapter.cs
index 3e02944..da8bed8 100644
--- a/UXAssist/Production/FuelGenerationAdapter.cs
+++ b/UXAssist/Production/FuelGenerationAdapter.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -17,8 +18,7 @@ public sealed class FuelGenerationAdapter : IProductionProcessAdapter
process = null;
diagnostic = null;
if (operatingParameters == null ||
- !operatingParameters.TryGetValue("FuelItemId", out var fuelId) ||
- fuelId <= 0 || fuelId > int.MaxValue || fuelId != Math.Truncate(fuelId) ||
+ !operatingParameters.TryGetValue("FuelItemId", out var fuelId) || !PositiveId(fuelId) ||
!catalog.Items.TryGetValue((int)fuelId, out var fuel) ||
fuel.HeatValueJoules <= 0 || (fuel.FuelTypeMask & building.FuelMask) == 0)
{
@@ -37,8 +37,7 @@ public sealed class FuelGenerationAdapter : IProductionProcessAdapter
return false;
}
- if (building.FuelUseWatts <= 0 || building.RatedGenerationWatts <= 0 ||
- double.IsNaN(building.FuelUseWatts) || double.IsNaN(building.RatedGenerationWatts))
+ if (!FinitePositive(building.FuelUseWatts) || !FinitePositive(building.RatedGenerationWatts))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The generator's fuel consumption or power rating is unavailable.",
@@ -73,8 +72,7 @@ public sealed class FuelGenerationAdapter : IProductionProcessAdapter
var generation = building.RatedGenerationWatts * proliferationFactor * boostFactor;
var burnedFuel = building.FuelUseWatts * (fuel.ProductiveFuel ? 1 : proliferationFactor) *
boostFactor * 60 / fuel.HeatValueJoules;
- if (double.IsInfinity(generation) || double.IsInfinity(burnedFuel) || burnedFuel <= 0 ||
- double.IsNaN(generation) || double.IsNaN(burnedFuel))
+ if (!Finite(generation) || !FinitePositive(burnedFuel))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected fuel produces an invalid generation rate.", buildingItemId: building.ItemId);
diff --git a/UXAssist/Production/GasCollectionAdapter.cs b/UXAssist/Production/GasCollectionAdapter.cs
index 0ef16fe..99c8a55 100644
--- a/UXAssist/Production/GasCollectionAdapter.cs
+++ b/UXAssist/Production/GasCollectionAdapter.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -55,8 +56,7 @@ public sealed class GasCollectionAdapter : IProductionProcessAdapter
var outputs = new List>();
for (var index = 0; index < (int)gasCount; index++)
{
- if (!operatingParameters.TryGetValue($"GasItemId{index}", out var itemId) ||
- itemId <= 0 || itemId > int.MaxValue || itemId != Math.Truncate(itemId) ||
+ if (!operatingParameters.TryGetValue($"GasItemId{index}", out var itemId) || !PositiveId(itemId) ||
!catalog.Items.ContainsKey((int)itemId) ||
!operatingParameters.TryGetValue($"GasSpeedPerSecond{index}", out var gasSpeed) ||
!FiniteNonnegative(gasSpeed))
@@ -85,14 +85,4 @@ public sealed class GasCollectionAdapter : IProductionProcessAdapter
1, 0, true);
return true;
}
-
- private static bool FiniteNonnegative(double value)
- {
- return value >= 0 && !double.IsNaN(value) && !double.IsInfinity(value);
- }
-
- private static bool FinitePositive(double value)
- {
- return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
- }
}
diff --git a/UXAssist/Production/LaunchProcessAdapter.cs b/UXAssist/Production/LaunchProcessAdapter.cs
index e8ee6b0..898316c 100644
--- a/UXAssist/Production/LaunchProcessAdapter.cs
+++ b/UXAssist/Production/LaunchProcessAdapter.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -74,7 +75,7 @@ public sealed class LaunchProcessAdapter : IProductionProcessAdapter
}
var nativeStep = Math.Truncate(10000 * (1 + speedBonus) + 0.1) * (boosted ? 10 : 1);
- if (nativeStep <= 0 || double.IsInfinity(nativeStep) || double.IsNaN(nativeStep))
+ if (!FinitePositive(nativeStep))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The launcher's native speed is outside the supported range.", buildingItemId: building.ItemId);
@@ -84,8 +85,7 @@ public sealed class LaunchProcessAdapter : IProductionProcessAdapter
var cycleTicks = Math.Ceiling(building.LaunchChargeTicks * 10000.0 / nativeStep) +
Math.Ceiling(building.LaunchCooldownTicks * 10000.0 / nativeStep);
var launchesPerMinute = 3600.0 / cycleTicks;
- if (launchesPerMinute <= 0 || double.IsInfinity(launchesPerMinute) ||
- double.IsNaN(launchesPerMinute))
+ if (!FinitePositive(launchesPerMinute))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The launcher cycle is outside the supported range.", buildingItemId: building.ItemId);
diff --git a/UXAssist/Production/MiningProcessAdapter.cs b/UXAssist/Production/MiningProcessAdapter.cs
index 5ceb2f9..b7af20e 100644
--- a/UXAssist/Production/MiningProcessAdapter.cs
+++ b/UXAssist/Production/MiningProcessAdapter.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -25,7 +26,7 @@ public sealed class MiningProcessAdapter : IProductionProcessAdapter
if (operatingParameters == null ||
!operatingParameters.TryGetValue("ResourceItemId", out var outputId) ||
- !ValidItemId(outputId) || !catalog.Items.ContainsKey((int)outputId) ||
+ !PositiveId(outputId) || !catalog.Items.ContainsKey((int)outputId) ||
!operatingParameters.TryGetValue("MiningSpeedMultiplier", out var miningSpeed) ||
!FinitePositive(miningSpeed))
{
@@ -72,8 +73,7 @@ public sealed class MiningProcessAdapter : IProductionProcessAdapter
var powerRatio = machineSpeed * machineSpeed;
var workingWatts = building.WorkingPowerWatts * powerRatio +
building.IdlePowerWatts * (1 - powerRatio);
- if (!FinitePositive(perMinute) || workingWatts < 0 ||
- double.IsNaN(workingWatts) || double.IsInfinity(workingWatts))
+ if (!FinitePositive(perMinute) || !FiniteNonnegative(workingWatts))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The mineral output rate or power demand is outside the supported range.",
@@ -87,14 +87,4 @@ public sealed class MiningProcessAdapter : IProductionProcessAdapter
perMinute, workingWatts, true);
return true;
}
-
- private static bool ValidItemId(double value)
- {
- return value > 0 && value <= int.MaxValue && value == Math.Truncate(value);
- }
-
- private static bool FinitePositive(double value)
- {
- return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
- }
}
diff --git a/UXAssist/Production/ProcessEvaluator.cs b/UXAssist/Production/ProcessEvaluator.cs
index cc3ab63..6b68713 100644
--- a/UXAssist/Production/ProcessEvaluator.cs
+++ b/UXAssist/Production/ProcessEvaluator.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -52,7 +53,9 @@ public sealed class ProcessEvaluator
return false;
}
- if (!IsOrdinary(recipe.Category))
+ // Recipe types unknown to the catalog, such as ones added by other mods, keep their material flows only
+ // while no building is selected.
+ if (!IsOrdinary(recipe.Category) && (recipe.Category != ProductionRecipeCategory.None || building != null))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The recipe requires a special-process adapter.", recipeId: recipe.Id,
@@ -114,17 +117,6 @@ public sealed class ProcessEvaluator
private static bool ValidFlows(IReadOnlyDictionary flows)
{
- return flows.All(flow => flow.Key > 0 && flow.Value > 0 && !double.IsNaN(flow.Value) &&
- !double.IsInfinity(flow.Value));
- }
-
- private static bool FinitePositive(double value)
- {
- return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
- }
-
- private static bool FiniteNonnegative(double value)
- {
- return value >= 0 && !double.IsNaN(value) && !double.IsInfinity(value);
+ return flows.All(flow => flow.Key > 0 && FinitePositive(flow.Value));
}
}
diff --git a/UXAssist/Production/ProductionCatalogReader.cs b/UXAssist/Production/ProductionCatalogReader.cs
index 92b32c8..792d947 100644
--- a/UXAssist/Production/ProductionCatalogReader.cs
+++ b/UXAssist/Production/ProductionCatalogReader.cs
@@ -39,8 +39,10 @@ public static class ProductionCatalogReader
var kind = ClassifyBuilding(prefab);
if (category == ProductionRecipeCategory.None && kind == ProductionBuildingKind.Ordinary) continue;
var speed = prefab.isLab ? prefab.labAssembleSpeed : prefab.assemblerSpeed;
+ // Charging power nodes draw idle power except while charging a mecha, which production power excludes.
+ var workEnergyPerTick = prefab.isPowerCharger ? prefab.idleEnergyPerTick : prefab.workEnergyPerTick;
buildings.Add(new ProductionBuilding(item.ID, category, speed / 10000.0,
- prefab.workEnergyPerTick * 60.0, prefab.idleEnergyPerTick * 60.0, kind,
+ workEnergyPerTick * 60.0, prefab.idleEnergyPerTick * 60.0, kind,
prefab.genEnergyPerTick * 60.0, prefab.exchangeEnergyPerTick * 60.0,
prefab.maxExcEnergy, prefab.emptyId, prefab.fullId,
prefab.windForcedPower ? RenewablePowerSource.Wind :
@@ -68,9 +70,12 @@ public static class ProductionCatalogReader
recipes.Add(new ProductionRecipe(recipe.ID, MapCategory(recipe.Type), recipe.TimeSpend, recipe.productive,
PairFlows(recipe.Items, recipe.ItemCounts), PairFlows(recipe.Results, recipe.ResultCounts)));
+ // Follow native maincraft selection (lowest result index, then recipe order), but skip recipes such as
+ // Reforming Refine that consume their own product and so cannot start its production chain.
for (var resultIndex = 0; resultIndex < recipe.Results.Length; resultIndex++)
{
var productId = recipe.Results[resultIndex];
+ if (Array.IndexOf(recipe.Items, productId) >= 0) continue;
if (!defaultRecipes.TryGetValue(productId, out var old) || resultIndex < old.resultIndex)
defaultRecipes[productId] = (recipe.ID, resultIndex);
}
@@ -82,8 +87,8 @@ public static class ProductionCatalogReader
foreach (var item in itemProtos)
{
if (item == null) continue;
- var defaultRecipeId = item.maincraft?.ID ??
- (defaultRecipes.TryGetValue(item.ID, out var fallback) ? fallback.recipeId : 0);
+ var defaultRecipeId = defaultRecipes.TryGetValue(item.ID, out var defaultRecipe)
+ ? defaultRecipe.recipeId : 0;
var isProliferator = proliferators.Contains(item.ID);
items.Add(new ProductionItem(item.ID, defaultRecipeId,
naturalItems.Contains(item.ID) || !string.IsNullOrEmpty(item.MiningFrom),
@@ -192,7 +197,7 @@ public static class ProductionCatalogReader
? ProductionBuildingKind.RenewableGenerator : ProductionBuildingKind.FuelGenerator;
if (prefab.isStation || prefab.isDispenser || prefab.isBattleBase)
return ProductionBuildingKind.Logistics;
- if (prefab.isPowerConsumer && !prefab.isStation && !prefab.isDispenser)
+ if (prefab.isPowerConsumer || prefab.isPowerCharger)
return ProductionBuildingKind.Auxiliary;
return ProductionBuildingKind.Ordinary;
}
diff --git a/UXAssist/Production/ProductionModel.cs b/UXAssist/Production/ProductionModel.cs
index 5ab6495..e8fdd56 100644
--- a/UXAssist/Production/ProductionModel.cs
+++ b/UXAssist/Production/ProductionModel.cs
@@ -27,6 +27,40 @@ internal static class ProductionUnits
internal const double FixedPointScale = 10000;
}
+internal static class ProductionMath
+{
+ internal static bool Finite(double value) => !double.IsNaN(value) && !double.IsInfinity(value);
+
+ internal static bool FinitePositive(double value) => value > 0 && Finite(value);
+
+ internal static bool FiniteNonnegative(double value) => value >= 0 && Finite(value);
+
+ // Item and technology IDs arrive as double operating parameters.
+ internal static bool PositiveId(double value) =>
+ value > 0 && value <= int.MaxValue && value == Math.Truncate(value);
+
+ internal static void AddFlow(IDictionary flows, int itemId, double amount)
+ {
+ flows[itemId] = (flows.TryGetValue(itemId, out var previous) ? previous : 0) + amount;
+ }
+
+ internal static Dictionary ScaleFlows(IReadOnlyDictionary flows, double factor)
+ {
+ return flows.ToDictionary(flow => flow.Key, flow => flow.Value * factor);
+ }
+
+ internal static void AddGroup(IDictionary> groups, int itemId, int groupIndex)
+ {
+ if (!groups.TryGetValue(itemId, out var indices))
+ {
+ indices = new List();
+ groups[itemId] = indices;
+ }
+
+ indices.Add(groupIndex);
+ }
+}
+
public enum ProliferationMode
{
None,
diff --git a/UXAssist/Production/ProductionPlanner.Report.cs b/UXAssist/Production/ProductionPlanner.Report.cs
index c30aafa..7174378 100644
--- a/UXAssist/Production/ProductionPlanner.Report.cs
+++ b/UXAssist/Production/ProductionPlanner.Report.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -36,8 +37,7 @@ public sealed partial class ProductionPlanner
activeRecipes.Add(process.RecipeId);
var output = ScaleFlows(process.OutputsPerCycle, executions);
var input = ScaleFlows(process.InputsPerCycle, executions);
- if (proliferatorItemId > 0 && process.ProliferationMode != ProliferationMode.None &&
- process.SprayedInputsPerCycle > 0)
+ if (proliferatorItemId > 0 && SpraysInputs(process))
{
var sprays = process.SprayedInputsPerCycle * executions;
foreach (var itemId in reusableSprayItems)
@@ -84,8 +84,7 @@ public sealed partial class ProductionPlanner
deploymentCount = Math.Max(1, (int)Math.Ceiling(equivalentBuildings.Value - 1e-9));
consumedWatts = equivalentBuildings.Value * process.WorkingPowerWatts;
peakWatts = deploymentCount.Value * process.WorkingPowerWatts;
- if (consumedWatts.Value < 0 || double.IsNaN(consumedWatts.Value) ||
- double.IsInfinity(consumedWatts.Value)) factoryPowerComplete = false;
+ if (!FiniteNonnegative(consumedWatts.Value)) factoryPowerComplete = false;
workingPower += consumedWatts.Value;
peakPower += peakWatts.Value;
generationWatts += equivalentBuildings.Value * process.GenerationWatts;
@@ -137,9 +136,7 @@ public sealed partial class ProductionPlanner
if (!_catalog.Buildings.TryGetValue(auxiliary.BuildingItemId, out var building) ||
building.Kind != ProductionBuildingKind.Auxiliary ||
- building.WorkingPowerWatts < 0 || double.IsInfinity(building.WorkingPowerWatts) ||
- double.IsNaN(building.WorkingPowerWatts) ||
- double.IsInfinity(building.WorkingPowerWatts * auxiliary.Count))
+ !FiniteNonnegative(building.WorkingPowerWatts * auxiliary.Count))
{
powerComplete = false;
factoryPowerComplete = false;
@@ -187,8 +184,8 @@ public sealed partial class ProductionPlanner
var surplus = solution[surplusStart + index];
var finalProduct = produced > 1e-9 && consumed <= 1e-9;
itemFlows.Add(new ProductionItemFlow(itemId, produced, consumed, imported, known, delivered, surplus,
- imported, finalProduct, produced > 1e-9 && consumed > 1e-9 && surplus > 1e-9,
- 0, producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty(),
+ imported, finalProduct,
+ producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty(),
consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty()));
}
@@ -202,20 +199,4 @@ public sealed partial class ProductionPlanner
return new ProductionReport(status, true, powerComplete, itemFlows, groups, diagnostics, power,
new ProductionPowerBreakdown(workingPower, 0, factoryPowerComplete, true));
}
-
- private static Dictionary ScaleFlows(IReadOnlyDictionary flows, double multiplier)
- {
- return flows.ToDictionary(flow => flow.Key, flow => flow.Value * multiplier);
- }
-
- private static void AddGroup(IDictionary> groups, int itemId, int groupIndex)
- {
- if (!groups.TryGetValue(itemId, out var indices))
- {
- indices = new List();
- groups[itemId] = indices;
- }
-
- indices.Add(groupIndex);
- }
}
diff --git a/UXAssist/Production/ProductionPlanner.cs b/UXAssist/Production/ProductionPlanner.cs
index a0da011..55121e1 100644
--- a/UXAssist/Production/ProductionPlanner.cs
+++ b/UXAssist/Production/ProductionPlanner.cs
@@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -29,16 +30,16 @@ public sealed partial class ProductionPlanner
var targets = new SortedDictionary();
foreach (var target in request.Targets)
{
- if (target == null || target.ItemId <= 0 || !ValidNonnegative(target.ItemsPerMinute))
+ if (target == null || target.ItemId <= 0 || !FiniteNonnegative(target.ItemsPerMinute))
return Fail(ProductionDiagnosticCode.InvalidRequest, "A target has an invalid item or rate.");
AddFlow(targets, target.ItemId, target.ItemsPerMinute);
- if (!ValidNonnegative(targets[target.ItemId]))
+ if (!FiniteNonnegative(targets[target.ItemId]))
return Fail(ProductionDiagnosticCode.InvalidRequest, "The combined target rate is too large.");
}
foreach (var surplus in request.KnownExternalSurplus)
{
- if (surplus.Key <= 0 || !ValidNonnegative(surplus.Value))
+ if (surplus.Key <= 0 || !FiniteNonnegative(surplus.Value))
return Fail(ProductionDiagnosticCode.InvalidRequest, "Known external surplus must be nonnegative.");
if (!_catalog.Items.ContainsKey(surplus.Key))
return Fail(ProductionDiagnosticCode.UnknownItem, "An external-surplus item is unknown.", surplus.Key);
@@ -49,14 +50,14 @@ public sealed partial class ProductionPlanner
if (!request.ProliferationEnabled && request.SprayDeliveredItems.Count > 0)
return Fail(ProductionDiagnosticCode.InvalidRequest, "Finished-product spraying requires proliferation.");
- var processes = new SortedDictionary<(int recipeId, int buildingId, ProliferationMode mode, int level),
- ProductionProcess>();
+ var processes = new SortedDictionary();
var externalItems = new SortedSet();
var pending = new SortedSet(targets.Keys);
var visited = new HashSet();
var warnings = new List();
- var hasSprayedInputs = false;
var hasSprayedTargets = request.SprayDeliveredItems.Any(id => targets[id] > 0);
+ var explicitModes = request.ProliferationEnabled
+ ? ExplicitProliferationModes(request) : new Dictionary();
ProductionItem proliferator = null;
if (request.ProliferationEnabled)
{
@@ -79,8 +80,7 @@ public sealed partial class ProductionPlanner
return Fail(ProductionDiagnosticCode.UnknownItem, "A required item is unknown.", itemId);
var hasExplicitRecipe = request.RecipeByItem.TryGetValue(itemId, out var recipeId);
- if (item.IsDarkFogMaterial || request.ExternalMaterials.Contains(itemId) ||
- item.IsNatural && !hasExplicitRecipe)
+ if (IsExternal(request, item, hasExplicitRecipe))
{
externalItems.Add(itemId);
continue;
@@ -92,12 +92,21 @@ public sealed partial class ProductionPlanner
if (!recipe.Outputs.ContainsKey(itemId))
return Fail(ProductionDiagnosticCode.InvalidRequest, "The selected recipe does not produce the item.",
itemId, recipeId);
+ if (processes.ContainsKey(recipeId)) continue;
request.OperatingParametersByRecipe.TryGetValue(recipeId, out var parameters);
var mode = ProliferationMode.None;
if (request.ProliferationEnabled)
- mode = request.ProliferationModeByItem.TryGetValue(itemId, out var selectedMode)
- ? selectedMode : DefaultProliferationMode(recipe, parameters);
+ {
+ if (!explicitModes.TryGetValue(recipeId, out var explicitMode))
+ mode = DefaultProliferationMode(recipe, parameters);
+ else if (explicitMode.HasValue)
+ mode = explicitMode.Value;
+ else
+ return Fail(ProductionDiagnosticCode.InvalidRequest,
+ "The products of one recipe request different proliferation modes.", itemId, recipeId);
+ }
+
var level = mode == ProliferationMode.None ? 0 : proliferator.ProliferationLevel;
var buildingId = request.BuildingByRecipe.TryGetValue(recipeId, out var recipeBuildingId)
? recipeBuildingId
@@ -122,14 +131,12 @@ public sealed partial class ProductionPlanner
warnings.Add(diagnostic);
}
- processes[(recipeId, buildingId, mode, level)] = process;
+ processes[recipeId] = process;
foreach (var input in process.InputsPerCycle.Keys) pending.Add(input);
- if (mode == ProliferationMode.None || process.SprayedInputsPerCycle <= 0) continue;
- hasSprayedInputs = true;
- pending.Add(proliferator.Id);
+ if (SpraysInputs(process)) pending.Add(proliferator.Id);
}
- var sprayDemand = hasSprayedInputs || hasSprayedTargets;
+ var sprayDemand = hasSprayedTargets || processes.Values.Any(SpraysInputs);
var spraysPerBottle = 0.0;
if (sprayDemand)
{
@@ -185,9 +192,8 @@ public sealed partial class ProductionPlanner
priorityProcesses[index] = 1;
foreach (var input in process.InputsPerCycle) matrix[rowByItem[input.Key], index] -= input.Value;
foreach (var output in process.OutputsPerCycle) matrix[rowByItem[output.Key], index] += output.Value;
- if (process.ProliferationMode != ProliferationMode.None && process.SprayedInputsPerCycle > 0)
- matrix[rowByItem[proliferator.Id], index] -=
- process.SprayedInputsPerCycle / spraysPerBottle;
+ if (SpraysInputs(process))
+ matrix[rowByItem[proliferator.Id], index] -= process.SprayedInputsPerCycle / spraysPerBottle;
}
for (var index = 0; index < importItems.Length; index++)
@@ -257,10 +263,40 @@ public sealed partial class ProductionPlanner
reusableSprayItems, sprayCreditStart);
}
+ // A recipe runs in one mode, so explicit choices for the products it is selected to make must agree;
+ // null marks a conflict, which is reported only if the recipe is used.
+ private Dictionary ExplicitProliferationModes(ProductionPlanRequest request)
+ {
+ var modes = new Dictionary();
+ foreach (var choice in request.ProliferationModeByItem)
+ {
+ if (!_catalog.Items.TryGetValue(choice.Key, out var item)) continue;
+ var hasExplicitRecipe = request.RecipeByItem.TryGetValue(item.Id, out var recipeId);
+ if (IsExternal(request, item, hasExplicitRecipe)) continue;
+ if (!hasExplicitRecipe) recipeId = item.DefaultRecipeId;
+ if (!_catalog.Recipes.TryGetValue(recipeId, out var recipe) || !recipe.Outputs.ContainsKey(item.Id))
+ continue;
+ if (!modes.TryGetValue(recipeId, out var previous)) modes[recipeId] = choice.Value;
+ else if (previous != choice.Value) modes[recipeId] = null;
+ }
+
+ return modes;
+ }
+
+ private static bool IsExternal(ProductionPlanRequest request, ProductionItem item, bool hasExplicitRecipe)
+ {
+ return item.IsDarkFogMaterial || request.ExternalMaterials.Contains(item.Id) ||
+ item.IsNatural && !hasExplicitRecipe;
+ }
+
+ private static bool SpraysInputs(ProductionProcess process)
+ {
+ return process.ProliferationMode != ProliferationMode.None && process.SprayedInputsPerCycle > 0;
+ }
+
private static double SprayedInputAmount(ProductionProcess process, int itemId)
{
- if (process.ProliferationMode == ProliferationMode.None || process.SprayedInputsPerCycle <= 0 ||
- !process.InputsPerCycle.TryGetValue(itemId, out var amount)) return 0;
+ if (!SpraysInputs(process) || !process.InputsPerCycle.TryGetValue(itemId, out var amount)) return 0;
if (process.InputsPerCycle.Count == 1) return Math.Min(amount, process.SprayedInputsPerCycle);
return process.SprayedInputsPerCycle == process.InputsPerCycle.Values.Sum() ? amount : 0;
}
@@ -278,16 +314,6 @@ public sealed partial class ProductionPlanner
return recipe.Productive ? ProliferationMode.ExtraProducts : ProliferationMode.Speedup;
}
- private static bool ValidNonnegative(double value)
- {
- return value >= 0 && !double.IsNaN(value) && !double.IsInfinity(value);
- }
-
- private static void AddFlow(IDictionary flows, int itemId, double amount)
- {
- flows[itemId] = (flows.TryGetValue(itemId, out var old) ? old : 0) + amount;
- }
-
private static ProductionReport Fail(ProductionDiagnosticCode code, string message, int itemId = 0,
int recipeId = 0)
{
diff --git a/UXAssist/Production/ProductionReports.cs b/UXAssist/Production/ProductionReports.cs
index 45c54ac..ef3819b 100644
--- a/UXAssist/Production/ProductionReports.cs
+++ b/UXAssist/Production/ProductionReports.cs
@@ -77,8 +77,6 @@ public sealed class ProductionItemFlow
public double? SteadyStateExternalSupply { get; }
public bool IsFinalProduct { get; }
public bool IsResearchProduct { get; }
- public bool IsExcessIntermediate { get; }
- public double SingleBuildingSurplusThreshold { get; }
public double IntermediateShortage { get; }
public double? OverbuildSurplus { get; }
public double? CoproductSurplus { get; }
@@ -87,20 +85,9 @@ public sealed class ProductionItemFlow
public ProductionItemFlow(int itemId, double grossProduction, double grossConsumption, double externalImports,
double knownExternalSupply, double delivered, double surplus, double requiredExternalSupply,
- bool isFinalProduct, bool isExcessIntermediate, double singleBuildingSurplusThreshold,
- IEnumerable producerGroups, IEnumerable consumerGroups)
- : this(itemId, grossProduction, grossConsumption, externalImports, knownExternalSupply, delivered, surplus,
- requiredExternalSupply, isFinalProduct, isExcessIntermediate, singleBuildingSurplusThreshold,
- producerGroups, consumerGroups, 0, null, null)
- {
- }
-
- public ProductionItemFlow(int itemId, double grossProduction, double grossConsumption, double externalImports,
- double knownExternalSupply, double delivered, double surplus, double requiredExternalSupply,
- bool isFinalProduct, bool isExcessIntermediate, double singleBuildingSurplusThreshold,
- IEnumerable producerGroups, IEnumerable consumerGroups, double intermediateShortage,
- double? overbuildSurplus, double? coproductSurplus, double? steadyStateExternalSupply = null,
- bool isResearchProduct = false)
+ bool isFinalProduct, IEnumerable producerGroups, IEnumerable consumerGroups,
+ double intermediateShortage = 0, double? overbuildSurplus = null, double? coproductSurplus = null,
+ double? steadyStateExternalSupply = null, bool isResearchProduct = false)
{
ItemId = itemId;
GrossProduction = grossProduction;
@@ -113,8 +100,6 @@ public sealed class ProductionItemFlow
SteadyStateExternalSupply = steadyStateExternalSupply;
IsFinalProduct = isFinalProduct;
IsResearchProduct = isResearchProduct;
- IsExcessIntermediate = isExcessIntermediate;
- SingleBuildingSurplusThreshold = singleBuildingSurplusThreshold;
IntermediateShortage = intermediateShortage;
OverbuildSurplus = overbuildSurplus;
CoproductSurplus = coproductSurplus;
@@ -181,17 +166,10 @@ public sealed class ProductionReport
public double LaunchesPerMinute => Groups.Sum(group => group.LaunchesPerMinute);
public double ResearchHashesPerMinute => Groups.Sum(group => group.ResearchHashesPerMinute);
- public ProductionReport(ProductionStatus status, bool materialComplete, bool powerComplete,
- IEnumerable itemFlows, IEnumerable groups,
- IEnumerable diagnostics, ProductionPower power)
- : this(status, materialComplete, powerComplete, itemFlows, groups, diagnostics, power, null)
- {
- }
-
public ProductionReport(ProductionStatus status, bool materialComplete, bool powerComplete,
IEnumerable itemFlows, IEnumerable groups,
IEnumerable diagnostics, ProductionPower power,
- ProductionPowerBreakdown powerBreakdown)
+ ProductionPowerBreakdown powerBreakdown = null)
{
Status = status;
MaterialComplete = materialComplete;
diff --git a/UXAssist/Production/RayReceiverAdapter.cs b/UXAssist/Production/RayReceiverAdapter.cs
index 4c7a7e7..b373b77 100644
--- a/UXAssist/Production/RayReceiverAdapter.cs
+++ b/UXAssist/Production/RayReceiverAdapter.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -28,7 +29,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
return false;
}
- if (building.RatedGenerationWatts <= 0 || !Finite(building.RatedGenerationWatts) ||
+ if (!FinitePositive(building.RatedGenerationWatts) ||
(recipe != null && (recipe.Category != ProductionRecipeCategory.PhotonStore ||
recipe.Inputs.Count != 0 || recipe.Outputs.Count != 1 ||
!recipe.Outputs.ContainsKey(building.PowerProductItemId))))
@@ -60,8 +61,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
if (recipe == null && selectedMode > 0) photonMode = true;
if (photonMode && (building.PowerProductItemId <= 0 ||
- building.PowerProductEnergyJoules <= 0 ||
- !Finite(building.PowerProductEnergyJoules) ||
+ !FinitePositive(building.PowerProductEnergyJoules) ||
!catalog.Items.ContainsKey(building.PowerProductItemId)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
@@ -71,7 +71,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
}
if (!operatingParameters.TryGetValue("LensItemId", out var lensId) ||
- lensId < 0 || lensId > int.MaxValue || lensId != Math.Truncate(lensId))
+ lensId != 0 && !PositiveId(lensId))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Provide the receiver's lens item ID, or zero for no lens.", buildingItemId: building.ItemId);
@@ -81,7 +81,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
ProductionItem lens = null;
if (lensId > 0 && (!catalog.Items.TryGetValue((int)lensId, out lens) ||
(lens.CatalystTypeMask & building.CatalystMask) == 0 ||
- lens.CatalystAbilityMultiplier <= 0 || !Finite(lens.CatalystAbilityMultiplier)))
+ !FinitePositive(lens.CatalystAbilityMultiplier)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected item is not a compatible ray-receiver lens.",
@@ -111,7 +111,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
(1 + speedBonus) * (photonMode ? 8 : 1);
var cyclesPerMinute = photonMode
? energyWatts * 60 / building.PowerProductEnergyJoules : 1;
- if (cyclesPerMinute <= 0 || !Finite(cyclesPerMinute) || !Finite(energyWatts))
+ if (!FinitePositive(cyclesPerMinute) || !Finite(energyWatts))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The receiver's native output is outside the supported range.", buildingItemId: building.ItemId);
@@ -129,7 +129,7 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
if (!lossKnown)
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The Dyson-sphere power requirement needs the current solar energy loss technology setting.",
- buildingItemId: building.ItemId);
+ recipeId: recipe?.Id ?? 0, buildingItemId: building.ItemId);
var lensFlow = lens == null ? Array.Empty>() :
new[] { new KeyValuePair(lens.Id, 0.1 / cyclesPerMinute) };
@@ -172,9 +172,4 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
Array.Empty>(), recipe.Outputs, 0, 0, false);
return true;
}
-
- private static bool Finite(double value)
- {
- return !double.IsNaN(value) && !double.IsInfinity(value);
- }
}
diff --git a/UXAssist/Production/RenewableGenerationAdapter.cs b/UXAssist/Production/RenewableGenerationAdapter.cs
index 83bd942..2faa9fa 100644
--- a/UXAssist/Production/RenewableGenerationAdapter.cs
+++ b/UXAssist/Production/RenewableGenerationAdapter.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -17,8 +18,7 @@ public sealed class RenewableGenerationAdapter : IProductionProcessAdapter
process = null;
diagnostic = null;
if (building.RenewableSource == RenewablePowerSource.None ||
- building.RatedGenerationWatts < 0 || double.IsNaN(building.RatedGenerationWatts) ||
- double.IsInfinity(building.RatedGenerationWatts))
+ !FiniteNonnegative(building.RatedGenerationWatts))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The generator has no renewable power rating.", buildingItemId: building.ItemId);
diff --git a/UXAssist/Production/ResearchProcessAdapter.cs b/UXAssist/Production/ResearchProcessAdapter.cs
index d253472..4f4d660 100644
--- a/UXAssist/Production/ResearchProcessAdapter.cs
+++ b/UXAssist/Production/ResearchProcessAdapter.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
@@ -42,8 +43,7 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter
}
else
{
- if (!operatingParameters.TryGetValue("TechId", out var techId) || techId <= 0 ||
- techId > int.MaxValue || techId != Math.Truncate(techId) ||
+ if (!operatingParameters.TryGetValue("TechId", out var techId) || !PositiveId(techId) ||
!operatingParameters.TryGetValue("ResearchSpeed", out researchSpeed) ||
!FinitePositive(researchSpeed))
{
@@ -60,7 +60,6 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter
buildingItemId: building.ItemId);
return false;
}
-
}
if (mode != ProliferationMode.None && mode != ProliferationMode.ExtraProducts)
@@ -118,9 +117,4 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter
researchHashesPerCycle: hashRate);
return true;
}
-
- private static bool FinitePositive(double value)
- {
- return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
- }
}
diff --git a/UXAssist/Production/TwoPhaseSimplex.cs b/UXAssist/Production/TwoPhaseSimplex.cs
index 0742f46..899ea9b 100644
--- a/UXAssist/Production/TwoPhaseSimplex.cs
+++ b/UXAssist/Production/TwoPhaseSimplex.cs
@@ -29,6 +29,7 @@ internal static class TwoPhaseSimplex
{
private const double PivotTolerance = 1e-10;
private const double ReducedTolerance = 1e-8;
+ private const double RatioTieTolerance = 1e-9;
internal static LinearSolveResult Solve(double[,] coefficients, double[] rightHandSide,
IReadOnlyList objectives, int iterationBudget, CancellationToken cancellation)
@@ -102,12 +103,19 @@ internal static class TwoPhaseSimplex
if (Math.Abs(tableau[row, width]) > ReducedTolerance)
return new LinearSolveResult(LinearSolveStatus.Infeasible);
+ // The remaining artificial counts as zero. Pivot it out on its largest coefficient at exactly zero so a
+ // tiny residual divided by a tiny coefficient cannot move the other rows.
+ var pivotColumn = -1;
for (var column = 0; column < columnCount; column++)
{
if (isBasic[column] || Math.Abs(tableau[row, column]) <= PivotTolerance) continue;
- Pivot(tableau, basis, isBasic, row, column);
- break;
+ if (pivotColumn < 0 || Math.Abs(tableau[row, column]) > Math.Abs(tableau[row, pivotColumn]))
+ pivotColumn = column;
}
+
+ if (pivotColumn < 0) continue;
+ tableau[row, width] = 0;
+ Pivot(tableau, basis, isBasic, row, pivotColumn);
}
var optimizedObjectives = new List();
@@ -170,9 +178,10 @@ internal static class TwoPhaseSimplex
var coefficient = tableau[row, entering];
if (coefficient <= PivotTolerance) continue;
var ratio = Math.Max(0, tableau[row, rightColumn]) / coefficient;
- if (ratio < minRatio - ReducedTolerance ||
- Math.Abs(ratio - minRatio) <= ReducedTolerance &&
- (leaving < 0 || basis[row] < basis[leaving]))
+ // Ties are relative: an absolute tolerance would merge distinct small ratios and leave a row infeasible.
+ var tie = leaving < 0 ? 0 : RatioTieTolerance * Math.Max(ratio, minRatio);
+ if (ratio < minRatio - tie ||
+ Math.Abs(ratio - minRatio) <= tie && (leaving < 0 || basis[row] < basis[leaving]))
{
minRatio = ratio;
leaving = row;
diff --git a/UXAssist/docs/ProductionArchitecture.md b/UXAssist/docs/ProductionArchitecture.md
index 9ff306d..1aed774 100644
--- a/UXAssist/docs/ProductionArchitecture.md
+++ b/UXAssist/docs/ProductionArchitecture.md
@@ -11,6 +11,8 @@ UXAssist exposes a shared production catalog, a material planner, a fixed-buildi
Accumulator charging and critical photon production have no native `RecipeProto` entries. The catalog adds calculation-only recipes from the captured exchanger and receiver metadata, with stable IDs equal to the negative output item ID. `ProductionRecipe.IsSynthetic` identifies these entries. Resolve them through `ProductionCatalog.Recipes`, never through `LDB.recipes` or a native building recipe setter. They supply default routes only when no native recipe provides one.
+An item's default recipe follows the native `maincraft` choice, the recipe listing the item at the lowest result index, but skips recipes that consume their own product. Reforming Refine, for example, cannot start a Refined Oil chain, so Plasma Refining remains its default.
+
## Global production planning
Select a target and, if desired, a building for the recipe or its category:
@@ -28,9 +30,9 @@ if (report.MaterialComplete)
}
```
-The solver includes all selected recipes, coproducts, finite external supplies, permitted imports, and proliferator consumption in one material balance. It never silently chooses another recipe. Explicit boundaries and Dark Fog materials are external; natural items are external unless an explicit recipe overrides their default collection source. Without a building choice, material flows that do not depend on that choice remain available, but building power is incomplete. An explicit extra-products mode for a recipe without that native capability is an error.
+The solver includes all selected recipes, coproducts, finite external supplies, permitted imports, and proliferator consumption in one material balance. It never silently chooses another recipe. Explicit boundaries and Dark Fog materials are external; natural items are external unless an explicit recipe overrides their default collection source. Without a building choice, material flows that do not depend on that choice remain available, but building power is incomplete. This also keeps the material flows of recipe types the catalog does not recognize, such as ones added by other mods. An explicit extra-products mode for a recipe without that native capability is an error.
-When proliferation is enabled, ordinary recipes default to their native extra-products or acceleration capability. Fractionation and accumulator exchange use acceleration; a ray receiver uses acceleration only with a lens. Per-item choices can override these defaults when the process supports the selected mode.
+When proliferation is enabled, ordinary recipes default to their native extra-products or acceleration capability. Fractionation and accumulator exchange use acceleration; a ray receiver uses acceleration only with a lens. Per-item choices can override these defaults when the process supports the selected mode. A recipe runs in one mode: the explicit choice of any product it is selected to make applies to the whole recipe, and conflicting choices for products of one recipe are an error when that recipe is used.
`SelfSprayProliferator` uses the captured spray count and extra-products bonus to calculate effective sprays per produced proliferator, including the spray spent coating the proliferator itself. `SprayDeliveredItems` adds spraying for requested deliveries. Accumulators retain their coating during both charging and discharging: adapters expose `PreservedSpraysPerCycle`, and the planner credits that coating only against demand for the same item. Each credit is bounded by both preserved output and sprayed input or delivery demand, so coating is neither created nor charged twice. Credits reduce proliferator consumption, not material quantities. The solver minimizes process executions, then imports, maximizes valid spray reuse, and finally minimizes remaining surplus.
@@ -40,9 +42,9 @@ When proliferation is enabled, ordinary recipes default to their native extra-pr
The black box evaluates each selected building at full load, even if another selected building cannot provide all its inputs. It does not simulate belt layouts, startup storage, or logistics throughput. Missing inputs appear as `RequiredExternalSupply`; byproducts and internal deficits retain producer and consumer group attribution. `GrossProduction` and `GrossConsumption` remain separate even when a recipe returns some of its own input. Material classification uses each process's net per-item flow, so that return cannot become a false external requirement or coproduct.
-`IntermediateShortage` records the missing externally supplied portion of an item produced and consumed within the selection. `OverbuildSurplus` and `CoproductSurplus` are independent nullable amounts; both can be positive for the same item. Equivalent buildings are grouped by recipe, building, proliferation mode, speed, and operating settings in stable order. Whole-building reductions are tested against every item's shared balance: no final-product capacity may decrease and no internal shortage may increase. The reduction identifies redundancy only; gross flows, original full-load inputs, outputs, and power never change. Coproduct supply counts only retained whole buildings required by a process's other products, and internal net consumption is credited before exposing the remainder. Headroom from a single-output producer or a joint process's limiting product remains ordinary balance, not a coproduct. The older `IsExcessIntermediate` threshold flag is retained for callers but alone does not prove redundancy. When materials are incomplete, overbuild and coproduct amounts are unknown rather than fabricated from a partial layout.
+`IntermediateShortage` records the missing externally supplied portion of an item produced and consumed within the selection. `OverbuildSurplus` and `CoproductSurplus` are independent nullable amounts; both can be positive for the same item. Equivalent buildings are grouped by recipe, building, proliferation mode, speed, and operating settings in stable order. Whole-building reductions are tested against every item's shared balance: no final-product capacity may decrease and no internal shortage may increase. The reduction identifies redundancy only; gross flows, original full-load inputs, outputs, and power never change. Coproduct supply counts only retained whole buildings required by a process's other products, and internal net consumption is credited before exposing the remainder. Headroom from a single-output producer or a joint process's limiting product remains ordinary balance, not a coproduct. When materials are incomplete, overbuild and coproduct amounts are unknown rather than fabricated from a partial layout.
-`SteadyStateExternalSupply` is a separate input estimate from the known processes. After whole-building classification for complete selections, a bounded fractional reduction of surplus intermediate producers propagates downstream limits through upstream processes. Every reduction applies to the entire process, keeps rated final-product capacity, and never worsens an existing intermediate shortage; deterministic grouping and ordering keep results independent of blueprint building order. For partial selections, skip whole-building classification but still cap independently known upstream inputs against known demand. Protect any known inputs of an unresolved downstream process, or all known products if its possible inputs are unknown, instead of treating its demand as zero. Only the blueprint description uses this estimate, marked as a known portion when incomplete. Gross ledgers, `RequiredExternalSupply`, uncertain overbuild and coproduct classification, independently known rated outputs, and power retain their original meaning.
+`SteadyStateExternalSupply` is a separate input estimate from the known processes. After whole-building classification for complete selections, a fractional reduction of surplus intermediate producers propagates downstream limits through upstream processes. The reduction stops after a bounded number of passes, because a lossless cycle such as charging and discharging accumulators can otherwise pass a tiny leftover around indefinitely; stopping early only keeps the input estimate conservative. Every reduction applies to the entire process, keeps rated final-product capacity, and never worsens an existing intermediate shortage; deterministic grouping and ordering keep results independent of blueprint building order. For partial selections, skip whole-building classification but still cap independently known upstream inputs against known demand. Protect any known inputs of an unresolved downstream process, or all known products if its possible inputs are unknown, instead of treating its demand as zero. Only the blueprint description uses this estimate, marked as a known portion when incomplete. Gross ledgers, `RequiredExternalSupply`, uncertain overbuild and coproduct classification, independently known rated outputs, and power retain their original meaning.
```csharp
var capture = BlueprintSelectionReader.Capture(factory, selectedObjectIds);
@@ -56,7 +58,7 @@ The capture is read-only and does not alter the game's selection. `CreateRequest
The global proliferation switch uses the highest level supported by the captured proliferator items while preserving each production building's acceleration or extra-products setting. It also controls fuel and launch-ammunition proliferation. The black box assumes input coating is supplied externally and does not add proliferator consumption for that coating.
-Selected Planetary and Interstellar Logistics Stations, Logistics Distributors, and Battlefield Analysis Bases contribute their configured maximum charging power to both `Power.ConsumptionWatts` and `PeakConsumptionWatts`. These are charging limits, not current draw, inventory flow, or accumulator exchange. A manual building snapshot supplies `ChargePowerWatts` in watts; live capture reads the consumer's configured work energy per tick, while prebuild and blueprint captures use native stored settings or prefab defaults when no setting is applied. Missing or invalid charging power leaves logistics consumption and the combined power result unknown, without discarding known factory consumption or material results. Factory consumption also includes selected sorters and Spray Coaters. Advanced Mining Machines retain their mining power calculation rather than gaining a second charger; orbital collectors recover their own fuel instead of drawing grid power. A miner missing resource context can still report independently calculable speed-ratio power; a ray receiver missing Dyson loss settings retains its known factory draw even though total power remains incomplete.
+Selected Planetary and Interstellar Logistics Stations, Logistics Distributors, and Battlefield Analysis Bases contribute their configured maximum charging power to both `Power.ConsumptionWatts` and `PeakConsumptionWatts`. These are charging limits, not current draw, inventory flow, or accumulator exchange. A manual building snapshot supplies `ChargePowerWatts` in watts; live capture reads the consumer's configured work energy per tick, while prebuild and blueprint captures use native stored settings or prefab defaults when no setting is applied. Missing or invalid charging power leaves logistics consumption and the combined power result unknown, without discarding known factory consumption or material results. Factory consumption also includes selected sorters, Spray Coaters, and other powered auxiliary buildings. Charging power nodes such as Satellite Substations and Wireless Power Towers count at their idle draw, because only mecha charging raises them above it. Advanced Mining Machines retain their mining power calculation rather than gaining a second charger; orbital collectors recover their own fuel instead of drawing grid power. A miner missing resource context can still report independently calculable speed-ratio power; a ray receiver missing Dyson loss settings retains its known factory draw even though total power remains incomplete.
All selected research-mode labs contribute their full prefab working consumption to factory and total power, regardless of current technology validity or transient idle state. When proliferation is enabled, apply the highest supported matrix power multiplier; with no supported spray level, use base working power. This intentionally conservative blueprint estimate avoids undersizing the power supply. An invalid power rating or unavailable multiplier remains unknown.
@@ -68,7 +70,7 @@ The shared `UIBlueprintInspector` in browser, copy, and paste modes hosts `Auto-
`BlueprintDescriptionFormatter` builds replacement multiline `blueprint.desc` text in this order: optional `Missing:` and `Excess:` lines for intermediate shortages and true overbuild; `Input:` for external inputs capped by downstream demand; `Output:` for ordinary final products and necessary coproduct surplus; and `Research:` for positive net matrix production accepted by a selected research-mode lab. Each warning category has one label followed by comma-separated items; warnings do not repeat in Input, and a matrix on Research does not repeat in Output. It uses `SteadyStateExternalSupply` for complete and independently known partial inputs, labeling partial values as known portions. The assumed lab adds no numerical matrix consumption or external input; other buildings' known matrix demand is subtracted from the Research rate. Omit each empty line, including Research when no produced matrix remains. A single optional `Power` custom field separates factory and configured logistics consumption, omitting categories with no demand and removing the field altogether if neither consumes power; a present but unknown category displays `Unknown` rather than zero. Material rates remain items per minute even though the description labels omit the unit. Rates are rounded only for display, ordered by item ID within each category, and use native item icon/name tags with comma-separated entries inside each description line. Uncertain final-product, overbuild, or coproduct conclusions are omitted. Veins and other scene objects are not blueprint entries or requested parameters.
-`BlueprintDescriptionFields` matches only exact English or Simplified Chinese power field titles, updates or removes matching power fields, and collapses duplicate matches; all other fields, including input/output custom fields, stay intact. The inspector first collects pending custom-field edits, checks the native 2,000-character description limit and `kMaxFieldCount`, and applies native `ExternalFieldEscape` and `ExternalFieldUnescape` rules to the remaining power field. An invalid blueprint, unavailable catalog, failed calculation, malformed fields, overlong description, or insufficient capacity does not overwrite the description or generated fields. A successful update replaces the original description, synchronizes its native input control, and refreshes the inspector and share-code preview through the native modification path, leaving save and copy actions to the native buttons. The formatting and field updater remain pure-managed so `ProductionCheck` can verify them without loading Unity.
+`BlueprintDescriptionFields` matches only exact English or Simplified Chinese power field titles, updates or removes matching power fields, and collapses duplicate matches; all other fields, including input/output custom fields, stay intact. The inspector first collects pending custom-field edits, checks the native 2,000-character description limit and `kMaxFieldCount`, and applies native `ExternalFieldEscape` and `ExternalFieldUnescape` rules to the remaining power field. An invalid blueprint, unavailable catalog, failed calculation, malformed fields, overlong description, or insufficient capacity does not overwrite the description or generated fields. A successful update replaces the original description, synchronizes its native input control, and refreshes the inspector and share-code preview through the native modification path, leaving save and copy actions to the native buttons. Native `Refresh` recalculates the later groups' positions and the scroll height but not the first group's position, and `Refresh(forModify: true)` does not reload `descTextInput`, so assign it explicitly. `BlueprintData.Validate` strips newlines from custom fields, so multiline text belongs only in the main description. Recheck these inspector behaviors against the original DLL after game updates. The formatting and field updater remain pure-managed so `ProductionCheck` can verify them without loading Unity.
## Special-process settings
@@ -80,7 +82,7 @@ All parameters below are numbers in a building snapshot's `OperatingParameters`.
| Energy exchanger | `Mode0`: charging `1`, discharging `-1`, idle `0`. Charging converts empty accumulators to full ones and draws grid power. Discharging converts them back and is reported as discharge capacity, not generation. Coating accelerates both directions and is preserved on the output accumulator. |
| Ray receiver | `Mode0`: `0` for grid generation or its native photon item ID; `LensItemId`: zero or a compatible catalyst; `SolarEnergyLossRate`: technology loss fraction. Missing loss leaves photon flows available but Dyson power incomplete. Without a selected receiver, the planner keeps lens-free photon flows and leaves power incomplete; lens wear and speedup require a receiver. Ideal full illumination and warmup use the native 2.5 warmup factor, eightfold photon mode energy, and one lens per 36,000 game ticks. Grid generation and Dyson demand are separate. |
| Renewable generator | Wind, solar, and geothermal use ideal standard conditions and their rated generation. Local wind strength, day/night illumination, and geothermal ground heat do not modify this full-load model. |
-| Miner or water extractor | `ResourceItemId`, `MiningSpeedMultiplier`, and `VeinCount` or `OilUnits` for the matching resource. Optional `MachineSpeedFactor` defaults to 1; live capture records the raw miner speed divided by 10,000. The native speed damper only throttles backed-up output, so full load assumes its unobstructed value of 1. Output scales by machine speed; power uses `ratio = MachineSpeedFactor * MachineSpeedFactor` and `workingWatts * ratio + idleWatts * (1 - ratio)`. |
+| Miner or water extractor | `ResourceItemId`, `MiningSpeedMultiplier`, and `VeinCount` or `OilUnits` for the matching resource. Optional `MachineSpeedFactor` defaults to 1; live capture records the raw miner speed divided by 10,000, and prebuild and blueprint captures read an Advanced Mining Machine's stored speed setting. The native speed damper only throttles backed-up output, so full load assumes its unobstructed value of 1. Output scales by machine speed; power uses `ratio = MachineSpeedFactor * MachineSpeedFactor` and `workingWatts * ratio + idleWatts * (1 - ratio)`. |
| Gas collector | `GasCount`, `GasTotalHeat`, `MiningSpeedMultiplier`, and each `GasItemId{n}` and `GasSpeedPerSecond{n}`. Native self-power recovery and collection technology scale all gas outputs, which are reported per minute. Collector working energy reduces recovered gas; it is not counted again as grid consumption. |
| Fuel generator | `FuelItemId` compatible with the generator. Artificial stars also require the native boost mode `Mode0`, with `BoostEnabled` when it is set. Output and burned fuel follow the native fuel type and proliferation rule. |
| EM-rail ejector or vertical launching silo | `LaunchAvailable` plus the native boost mode (`Mode1` for ejectors, `Mode0` for silos), with `BoostEnabled` when it is set. An available ideal target consumes one ammunition item per completed charge/cooldown cycle. Proliferation changes both launch speed and working power. `LaunchesPerMinute` is separate from item production. |
@@ -92,7 +94,7 @@ The ejector and silo assume a usable orbit or node when `LaunchAvailable = 1`; t
## CheatEnabler migration
-The belt-signal generator uses `ProductionPlanner` material reports, not its former recursive ingredient table. Its caller-side preset chooses a proliferator with valid captured Proto capabilities and permits legacy natural-source boundaries only when those item IDs exist in the catalog. For each generated target unit, it records upstream gross production plus external imports, subtracts the already delivered target, and applies gross consumption independently. Each belt keeps separate fractional progress for production and consumption, while per-unit reports are cached by item, spray configuration, and catalog. `ProductionCatalogService.Changed` invalidates cached reports and refreshes existing belts; clearing the catalog drops their derived statistics without accessing unloaded factory objects. The game logic tick applies cached rates only. Request construction, calculation, and report conversion fail softly: if data is missing or calculation fails, only additional upstream statistics pause and a warning explains why; item generation and its own configured count switch remain unchanged.
+The belt-signal generator uses `ProductionPlanner` material reports, not its former recursive ingredient table. Its caller-side preset chooses a proliferator with valid captured Proto capabilities and permits legacy natural-source boundaries only when those item IDs exist in the catalog. For each generated target unit, it records upstream gross production plus external imports, subtracts the already delivered target, and applies gross consumption independently. Each belt keeps separate fractional progress for production and consumption, while per-unit reports are cached by item, spray configuration, and catalog. `ProductionCatalogService.Changed` invalidates cached reports and refreshes existing belts; clearing the catalog drops their derived statistics without accessing unloaded factory objects. The game logic tick applies cached rates only. Signals can change inside the tick, for example when drones finish a blueprint, so a cache miss queues the belt and the planner runs from the next frame update. Request construction, calculation, and report conversion fail softly: if data is missing or calculation fails, only additional upstream statistics pause and a warning explains why; item generation and its own configured count switch remain unchanged.
## Validation
@@ -120,8 +122,8 @@ Use a test game for the following manual checks. Compare full-load rates only wi
- Charge and discharge sprayed accumulators, then consume or deliver them with spraying enabled. Confirm acceleration in both directions and no repeated spray charge for inherited coating. Compare self-spraying enabled and disabled.
- Select miners at different machine speeds, including one with a backed-up output, a gas collector, and renewable generators. Check native miner power scaling, full-load miner output regardless of the output backlog, per-minute gas output without added grid demand, and ideal rated renewable power rather than local conditions.
- Select ray receivers in both modes, fuel generators, ejectors, and silos. Toggle proliferation and compare working power, generation, accumulator exchange, and Dyson demand as separate quantities. In a sandbox game, capture boosted artificial stars and launchers, and confirm that blueprint analysis of boosted buildings requires `BoostEnabled`.
-- Remove an upstream producer from a mixed production selection. Confirm that downstream capacity is unchanged and the missing material appears as required external supply. Check intermediate excess around the smallest selected producer's net output threshold.
-- In browser, copy, and paste inspectors, check localized control placement, Spray Coater defaults and manual overrides, and native item tags in the three generated fields. Generate twice and at the 20-field limit; verify that pending manual edits, unrelated fields, save/copy behavior, and ordinary blueprint sharing remain intact. Compare joint-production overbuild with necessary coproduct output without replacing original full-load rates or power.
+- Remove an upstream producer from a mixed production selection. Confirm that downstream capacity is unchanged and the missing material appears as required external supply. Add one producer more than downstream demand needs, and confirm that only that whole building's output is reported as excess.
+- In browser, copy, and paste inspectors, check localized control placement, Spray Coater defaults and manual overrides, and native item tags in the generated description and `Power` field. Generate twice and at the 20-field limit; verify that pending manual edits, unrelated fields, save/copy behavior, and ordinary blueprint sharing remain intact. Compare joint-production overbuild with necessary coproduct output without replacing original full-load rates or power.
- Place one research-mode lab alongside one or all six matrix production chains. Confirm the matrices' positive net production appears only in the Research line, other final products stay in Output, and known in-blueprint matrix consumption reduces the Research rate. Do not fabricate lab matrix imports, excess, or an estimated lab consumption rate; change current technology, add more labs, and toggle proliferation to check matrix routing stays independent while full working power updates. Without the lab, normal matrix output and overbuild rules resume.
- Combine planner targets with shared coproducts, explicit raw-material boundaries, and alternate selected recipes. Confirm material conservation, shared surplus reuse, and no introduction of unselected recipes.
- Toggle belt-signal proliferation and reload a game. Confirm that existing belts use the new catalog, item generation continues, and fractional production and consumption statistics remain independent.
diff --git a/UXAssist/tools/ProductionCheck/Program.cs b/UXAssist/tools/ProductionCheck/Program.cs
index b2ebeb7..d3e0259 100644
--- a/UXAssist/tools/ProductionCheck/Program.cs
+++ b/UXAssist/tools/ProductionCheck/Program.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Linq;
using System.Threading;
using CheatEnabler.Patches.Factory;
@@ -18,13 +19,17 @@ internal static class Program
ExternalSurplusAndNaturalOverrides();
ClosedLoopAndInfeasible();
LargeRatesConserve();
+ SimplexMixedMagnitudes();
+ RecipeProliferationModes();
+ UnusedProcessWarnings();
ProliferatorSupply();
ProliferatorGradesAndFinishedSpraying();
- BlackBoxBalancesAndThreshold();
+ BlackBoxBalancesAndOverbuild();
BlackBoxMixedModesAndDeficits();
BlueprintJointProduction();
BlueprintSteadyStateInputs();
BlueprintMixedProducersAndCycles();
+ SteadyStateLosslessCycle();
BlueprintProliferationAndCompleteness();
BlueprintDescriptionFormattingAndFields();
LogisticsChargingPower();
@@ -247,6 +252,115 @@ internal static class Program
}
}
+ private static void SimplexMixedMagnitudes()
+ {
+ // Ratios 4.84e-7 and 4.76e-7 are distinct pivots, not a tie, even though they differ by less than 1e-8.
+ var coefficients = new double[,]
+ {
+ { -90000, 2.13e6, 0, 0, 420000, -2.77e6 },
+ { -5.6, 0, 0, -25.4, 0, 0 },
+ { 0, 0, -231, 0, -190, 23 },
+ { -1700, 0, 0, 0, 25000, -800 }
+ };
+ var rightHandSide = new[] { 1.37e6, -4.2, -126, 16300 };
+ var solution = TwoPhaseSimplex.Solve(coefficients, rightHandSide,
+ new[] { new double[] { 0, 1, 1, 0, 1, 0 }, new double[] { 1, 0, 3, 3, 1, 0 } }, 20000,
+ CancellationToken.None);
+ Check(solution.Status == LinearSolveStatus.Optimal, "a feasible mixed-magnitude system is solved");
+ for (var row = 0; row < rightHandSide.Length; row++)
+ {
+ var total = 0.0;
+ for (var column = 0; column < coefficients.GetLength(1); column++)
+ total += coefficients[row, column] * solution.Values[column];
+ Check(Math.Abs(total - rightHandSide[row]) <= 1e-9 * Math.Abs(rightHandSide[row]),
+ "close pivot ratios still satisfy every constraint");
+ }
+
+ // A residual accepted as zero in phase one must not be divided by a tiny pivot coefficient.
+ var nearlyFeasible = TwoPhaseSimplex.Solve(new double[,] { { 1, 1, 0 }, { -1e-9, 0, -1 } },
+ new[] { 1.0, 5e-9 }, new[] { new double[] { 1, 1, 1 } }, 1000, CancellationToken.None);
+ Check(nearlyFeasible.Status == LinearSolveStatus.Optimal &&
+ Math.Abs(nearlyFeasible.Values[0] + nearlyFeasible.Values[1] - 1) < 1e-9,
+ "driving out a near-zero artificial keeps the other constraints satisfied");
+ }
+
+ private static void RecipeProliferationModes()
+ {
+ var items = new[]
+ {
+ new ProductionItem(1, 0, true, false, 0, 0),
+ new ProductionItem(2, 101, false, false, 0, 0),
+ new ProductionItem(3, 101, false, false, 0, 0),
+ new ProductionItem(4, 102, false, false, 0, 0),
+ new ProductionItem(9, 0, true, false, 4, 60)
+ };
+ var catalog = new ProductionCatalog(items, new[]
+ {
+ Recipe(101, new[] { (1, 1.0) }, new[] { (2, 2.0), (3, 1.0) }),
+ Recipe(102, new[] { (3, 1.0) }, new[] { (4, 1.0) })
+ }, new[] { new ProductionBuilding(10, ProductionRecipeCategory.Assemble, 1, 1000, 100) },
+ new[] { 0.0, 0.25, 0.5, 0.75, 1.0 },
+ new[] { 0.0, 0.125, 0.2, 0.225, 0.25 },
+ new[] { 1.0, 1.3, 1.7, 2.1, 2.5 });
+ var request = Request((2, 10), (4, 1));
+ request.ProliferationEnabled = true;
+ request.ProliferatorItemId = 9;
+ request.ProliferationModeByItem[2] = ProliferationMode.Speedup;
+ var report = new ProductionPlanner(catalog).Calculate(request);
+ var joint = report.Groups.Where(group => group.Process?.RecipeId == 101).ToArray();
+ Check(report.MaterialComplete && joint.Length == 1 &&
+ joint[0].Process.ProliferationMode == ProliferationMode.Speedup,
+ "a recipe keeps one product's explicit mode when its other product is also needed");
+ Equal(5, joint[0].ExecutionsPerMinute, "speedup adds no extra products to the joint recipe");
+ Equal(5, report.ItemFlows[1].ExternalImports, "the explicit mode determines the raw input");
+
+ request.ProliferationModeByItem[3] = ProliferationMode.ExtraProducts;
+ var conflict = new ProductionPlanner(catalog).Calculate(request);
+ Check(conflict.Status == ProductionStatus.Failed &&
+ conflict.Diagnostics.Single().Code == ProductionDiagnosticCode.InvalidRequest,
+ "products of one recipe cannot request different proliferation modes");
+
+ var modded = new ProductionCatalog(
+ new[] { new ProductionItem(1, 0, true, false, 0, 0), new ProductionItem(2, 701, false, false, 0, 0) },
+ new[]
+ {
+ new ProductionRecipe(701, ProductionRecipeCategory.None, 3600, true,
+ new[] { new KeyValuePair(1, 2) }, new[] { new KeyValuePair(2, 1) })
+ }, Array.Empty(), new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 });
+ var moddedReport = new ProductionPlanner(modded).Calculate(Request((2, 3)));
+ Check(moddedReport.MaterialComplete && !moddedReport.PowerComplete,
+ "a recipe type unknown to the catalog keeps its material flows without a building");
+ Equal(6, moddedReport.ItemFlows[1].ExternalImports, "unknown recipe types still balance their inputs");
+ }
+
+ private static void UnusedProcessWarnings()
+ {
+ var receiver = new ProductionBuilding(51, ProductionRecipeCategory.None, 1, 0, 0,
+ ProductionBuildingKind.RayReceiver, ratedGenerationWatts: 1000,
+ powerProductItemId: 456, powerProductEnergyJoules: 100000, catalystMask: 1);
+ var catalog = new ProductionCatalog(new[]
+ {
+ new ProductionItem(456, -456, false, false, 0, 0),
+ new ProductionItem(457, 900, false, false, 0, 0)
+ }, new[]
+ {
+ new ProductionRecipe(-456, ProductionRecipeCategory.PhotonStore, 1, false,
+ Array.Empty>(), new[] { new KeyValuePair(456, 1) }),
+ Recipe(900, new[] { (456, 1.0) }, new[] { (457, 1.0) })
+ }, new[] { receiver, new ProductionBuilding(10, ProductionRecipeCategory.Assemble, 1, 1000, 100) },
+ new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 });
+ var request = Request((457, 10));
+ request.BuildingByRecipe[-456] = 51;
+ request.OperatingParametersByRecipe[-456] = new Dictionary
+ {
+ ["Mode0"] = 456, ["LensItemId"] = 0
+ };
+ request.KnownExternalSurplus[456] = 10;
+ var report = new ProductionPlanner(catalog).Calculate(request);
+ Check(report.Status == ProductionStatus.Complete && report.Diagnostics.Count == 0,
+ "a warning from a receiver that does not run leaves the plan complete");
+ }
+
private static void ProliferatorSupply()
{
var planner = new ProductionPlanner(Catalog());
@@ -680,7 +794,7 @@ internal static class Program
"a boosted star blueprint needs the sandbox boost state");
}
- private static void BlackBoxBalancesAndThreshold()
+ private static void BlackBoxBalancesAndOverbuild()
{
var items = new[]
{
@@ -715,8 +829,6 @@ internal static class Program
Equal(30, report.ItemFlows[2].Surplus, "fractional intermediate balance retained");
Equal(0, report.ItemFlows[2].OverbuildSurplus.Value,
"sub-building ratio headroom is not redundant whole-building capacity");
- Equal(60, report.ItemFlows[2].SingleBuildingSurplusThreshold, "smallest actual producer threshold");
- Check(!report.ItemFlows[2].IsExcessIntermediate, "sub-threshold surplus is normally balanced");
Equal(2, report.ItemFlows[2].ProducerGroups.Count, "producer groups retained");
Equal(1, report.ItemFlows[2].ConsumerGroups.Count, "consumer groups retained");
Equal(3, report.ItemFlows[1].RequiredExternalSupply, "shortage is not silently suppressed");
@@ -730,7 +842,6 @@ internal static class Program
Equal(60, atThreshold.ItemFlows[2].Surplus, "intermediate at threshold");
Equal(60, atThreshold.ItemFlows[2].OverbuildSurplus.Value,
"a removable whole building accounts for the true overbuild");
- Check(atThreshold.ItemFlows[2].IsExcessIntermediate, "threshold reached qualifies as excess");
request.Buildings.Add(new ProductionBuildingSnapshot(102, 10, 402, 1, ProliferationMode.None));
var duplicate = analyzer.Analyze(request);
@@ -907,7 +1018,7 @@ internal static class Program
var asymmetrical = new ProductionReport(ProductionStatus.Complete, true, true,
new[] { new ProductionItemFlow(7, 0.25, 0.75, 0, 0, 0, 0, 0,
- false, false, 0, Array.Empty(), Array.Empty()) },
+ false, Array.Empty(), Array.Empty()) },
Array.Empty(), Array.Empty(), null);
var independent = new BeltSignalSourceStats(BeltSignalSourceStats.FromReport(asymmetrical, 8));
for (var insertion = 0; insertion < 4; insertion++)
@@ -1419,8 +1530,6 @@ internal static class Program
flow.CoproductSurplus == 0,
"matrices absorbed by research remain final products without excess warnings");
}
- Check(!withLab.ItemFlows[6001].IsExcessIntermediate,
- "matrix production absorbed by research is not flagged as overbuild");
Equal(3, withLab.ItemFlows[1].SteadyStateExternalSupply.Value,
"six-matrix production retains its full raw input throughput");
Equal(3, withLab.ItemFlows[2].SteadyStateExternalSupply.Value,
@@ -1752,6 +1861,32 @@ internal static class Program
}
}
+ private static void SteadyStateLosslessCycle()
+ {
+ // Charging and discharging pass a tiny leftover around a lossless cycle; the estimate must still finish.
+ var catalog = new ProductionCatalog(new[]
+ {
+ new ProductionItem(1, 0, true, false, 0, 0),
+ new ProductionItem(2, 0, false, false, 0, 0),
+ new ProductionItem(3, 0, false, false, 0, 0),
+ new ProductionItem(4, 0, false, false, 0, 0)
+ }, new[]
+ {
+ Recipe(701, new[] { (2, 1.0) }, new[] { (3, 1.0) }),
+ Recipe(702, new[] { (3, 1.0) }, new[] { (2, 1.0) }),
+ Recipe(703, new[] { (1, 1.0) }, new[] { (4, 1.0), (2, 1e-7) })
+ }, new[] { new ProductionBuilding(10, ProductionRecipeCategory.Assemble, 1, 1000, 100) },
+ new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 });
+ var request = new FactoryBlackBoxRequest();
+ request.Buildings.Add(new ProductionBuildingSnapshot(1, 10, 701, 10, ProliferationMode.None));
+ request.Buildings.Add(new ProductionBuildingSnapshot(2, 10, 702, 10, ProliferationMode.None));
+ request.Buildings.Add(new ProductionBuildingSnapshot(3, 10, 703, 1, ProliferationMode.None));
+ var watch = Stopwatch.StartNew();
+ var report = new FactoryBlackBoxAnalyzer(catalog).Analyze(request);
+ Check(watch.Elapsed.TotalSeconds < 10, "a lossless cycle cannot stall the steady-state estimate");
+ Equal(1, report.ItemFlows[1].SteadyStateExternalSupply.Value, "the cycle leaves the raw input unchanged");
+ }
+
private static void BlueprintProliferationAndCompleteness()
{
var analyzer = new FactoryBlackBoxAnalyzer(BlueprintCatalog());
@@ -1891,11 +2026,11 @@ internal static class Program
new[]
{
new ProductionItemFlow(52, 2, 3, 0, 0, 0, 0, 1,
- false, false, 0, Array.Empty(), Array.Empty(), 1, 0, 0),
+ false, Array.Empty(), Array.Empty(), 1, 0, 0),
new ProductionItemFlow(53, 1, 3, 0, 0, 0, 0, 2,
- false, false, 0, Array.Empty(), Array.Empty(), 2, 0, 0),
+ false, Array.Empty(), Array.Empty(), 2, 0, 0),
new ProductionItemFlow(54, 3, 0, 0, 0, 0, 3, 0,
- false, true, 3, Array.Empty(), Array.Empty(), 0, 3, 0)
+ false, Array.Empty(), Array.Empty(), 0, 3, 0)
},
Array.Empty(), Array.Empty(),
new ProductionPower(0, 0, 0, 0, 0, 0, ProductionPowerScope.SelectedFacilities),
@@ -1917,6 +2052,14 @@ internal static class Program
"gigawatt and megawatt display matches the native Chinese field example");
Check(large.Input == "" && large.Output == "" && large.Description == "",
"empty material categories add no description lines");
+ foreach (var (watts, expected) in new[] { (999.999, "1kW"), (999999.0, "1MW"), (999.994, "999.99W") })
+ {
+ var boundary = new ProductionReport(ProductionStatus.Complete, true, true,
+ Array.Empty(), Array.Empty(),
+ Array.Empty(), null, new ProductionPowerBreakdown(watts, 0, true, true));
+ Check(BlueprintDescriptionFormatter.Format(boundary, TestItemTag, labels).Power == "工厂耗电 " + expected,
+ "the power unit is chosen after rounding");
+ }
var logisticsRequest = new FactoryBlackBoxRequest();
logisticsRequest.Buildings.Add(new ProductionBuildingSnapshot(1, 30, 0, 1, ProliferationMode.None,
@@ -1979,9 +2122,9 @@ internal static class Program
new[]
{
new ProductionItemFlow(42, 0.125, 0, 0, 0, 0, 0.125, 0,
- true, false, 0, Array.Empty(), Array.Empty()),
+ true, Array.Empty(), Array.Empty()),
new ProductionItemFlow(43, 1.2, 0, 0, 0, 0, 1.2, 0,
- true, false, 0, Array.Empty(), Array.Empty())
+ true, Array.Empty(), Array.Empty())
}, Array.Empty(), Array.Empty(),
new ProductionPower(0, 0, 0, 0, 0, 0, ProductionPowerScope.SelectedFacilities),
new ProductionPowerBreakdown(0, 0, true, true));
@@ -1994,7 +2137,7 @@ internal static class Program
var inputOnlyReport = new ProductionReport(ProductionStatus.Complete, true, true,
new[] { new ProductionItemFlow(51, 0, 3, 0, 0, 0, 0, 3,
- false, false, 0, Array.Empty(), Array.Empty()) },
+ false, Array.Empty(), Array.Empty()) },
Array.Empty(), Array.Empty(),
new ProductionPower(0, 0, 0, 0, 0, 0, ProductionPowerScope.SelectedFacilities),
new ProductionPowerBreakdown(0, 0, true, true));
@@ -2004,7 +2147,7 @@ internal static class Program
var longReport = new ProductionReport(ProductionStatus.Complete, true, true,
Enumerable.Range(1000, 140).Select(itemId => new ProductionItemFlow(itemId, 1.2, 0, 0, 0, 0, 1.2, 0,
- true, false, 0, Array.Empty(), Array.Empty())),
+ true, Array.Empty(), Array.Empty())),
Array.Empty(), Array.Empty(),
new ProductionPower(0, 0, 0, 0, 0, 0, ProductionPowerScope.SelectedFacilities),
new ProductionPowerBreakdown(0, 0, true, true));
@@ -2017,28 +2160,28 @@ internal static class Program
private static void TestNativeFields()
{
- var firstFields = TestBlueprintFields("2.5GW");
- var result = BlueprintDescriptionFields.TryUpdate("Other:unchanged;", firstFields, 20,
+ var firstField = TestPowerField("2.5GW");
+ var result = BlueprintDescriptionFields.TryUpdate("Other:unchanged;", firstField, 20,
EscapeNativeField, UnescapeNativeField, out var generated);
Check(result == BlueprintFieldUpdateResult.Updated && generated == "Other:unchanged;Power:2.5GW;",
"only the power field is appended while unrelated fields remain intact");
- var escapedFields = TestBlueprintFields("2.5GW:250; " + (char)92 + "extra");
- result = BlueprintDescriptionFields.TryUpdate("", escapedFields, 20,
+ var escapedField = TestPowerField("2.5GW:250; " + (char)92 + "extra");
+ result = BlueprintDescriptionFields.TryUpdate("", escapedField, 20,
EscapeNativeField, UnescapeNativeField, out var escaped);
var escapedPower = escaped.Split(';')[0];
Check(result == BlueprintFieldUpdateResult.Updated &&
- UnescapeNativeField(escapedPower.Substring(escapedPower.IndexOf(':') + 1)) == escapedFields[0].Value,
+ UnescapeNativeField(escapedPower.Substring(escapedPower.IndexOf(':') + 1)) == escapedField.Value,
"native backslash, semicolon, and colon escaping still round-trips power fields");
result = BlueprintDescriptionFields.TryUpdate(generated,
- TestBlueprintFields("3GW"), 20,
+ TestPowerField("3GW"), 20,
EscapeNativeField, UnescapeNativeField, out var repeated);
Check(result == BlueprintFieldUpdateResult.Updated && repeated == "Other:unchanged;Power:3GW;",
"repeated generation updates the power field without appending duplicates");
result = BlueprintDescriptionFields.TryUpdate(
- "Note:keep;Input (per minute):manual;Output (per minute):manual;Power:old;", firstFields, 20,
+ "Note:keep;Input (per minute):manual;Output (per minute):manual;Power:old;", firstField, 20,
EscapeNativeField, UnescapeNativeField, out var preserved);
Check(result == BlueprintFieldUpdateResult.Updated &&
preserved == "Note:keep;Input (per minute):manual;Output (per minute):manual;Power:2.5GW;",
@@ -2046,64 +2189,61 @@ internal static class Program
var partialExisting = "Unrelated:hand edited;Input:manual;";
result = BlueprintDescriptionFields.TryUpdate(partialExisting,
- TestBlueprintFields("100MW"), 20,
+ TestPowerField("100MW"), 20,
EscapeNativeField, UnescapeNativeField, out var updated);
Check(result == BlueprintFieldUpdateResult.Updated &&
updated == "Unrelated:hand edited;Input:manual;Power:100MW;",
"a custom input field remains unchanged when power is appended");
- var chineseFields = new[]
- {
- new BlueprintDescriptionField("耗电", "新功率", "Power", "耗电")
- };
+ var chineseField = new BlueprintDescriptionField("耗电", "新功率", "Power", "耗电");
result = BlueprintDescriptionFields.TryUpdate("Power:old;输入:manual;Output (per minute):manual;",
- chineseFields, 3, EscapeNativeField, UnescapeNativeField, out var translated);
+ chineseField, 3, EscapeNativeField, UnescapeNativeField, out var translated);
Check(result == BlueprintFieldUpdateResult.Updated &&
translated == "耗电:新功率;输入:manual;Output (per minute):manual;",
"English and Chinese power titles match while other localized fields remain unchanged");
var duplicateNames = "Power:old;耗电:old;Note:Power Input Output;输入(每分钟):manual;Output:manual;";
result = BlueprintDescriptionFields.TryUpdate(duplicateNames,
- TestBlueprintFields("new"), 5, EscapeNativeField, UnescapeNativeField,
+ TestPowerField("new"), 5, EscapeNativeField, UnescapeNativeField,
out var keptDuplicates);
Check(result == BlueprintFieldUpdateResult.Updated &&
keptDuplicates == "Power:new;Note:Power Input Output;输入(每分钟):manual;Output:manual;",
"duplicate power slots are merged without modifying other titled fields");
- var noPowerFields = TestBlueprintFields(null);
+ var noPowerField = TestPowerField(null);
result = BlueprintDescriptionFields.TryUpdate("Other:keep;Power:old;耗电:old;输入:manual;Output:manual;",
- noPowerFields, 20, EscapeNativeField, UnescapeNativeField, out var removed);
+ noPowerField, 20, EscapeNativeField, UnescapeNativeField, out var removed);
Check(result == BlueprintFieldUpdateResult.Updated && removed == "Other:keep;输入:manual;Output:manual;",
"a blueprint without consumers removes only stale power fields");
- result = BlueprintDescriptionFields.TryUpdate("", noPowerFields, 20,
+ result = BlueprintDescriptionFields.TryUpdate("", noPowerField, 20,
EscapeNativeField, UnescapeNativeField, out var empty);
Check(result == BlueprintFieldUpdateResult.Updated && empty == "",
"empty power and material categories do not create any custom fields");
var full = string.Concat(Enumerable.Range(0, 20).Select(index => "Custom" + index + ":keep;"));
- result = BlueprintDescriptionFields.TryUpdate(full, firstFields, 20,
+ result = BlueprintDescriptionFields.TryUpdate(full, firstField, 20,
EscapeNativeField, UnescapeNativeField, out var rejected);
Check(result == BlueprintFieldUpdateResult.CapacityExceeded && rejected == full,
"a missing power field at native capacity causes an all-or-nothing refusal");
- result = BlueprintDescriptionFields.TryUpdate(full, noPowerFields, 20,
+ result = BlueprintDescriptionFields.TryUpdate(full, noPowerField, 20,
EscapeNativeField, UnescapeNativeField, out updated);
Check(result == BlueprintFieldUpdateResult.Updated && updated == full,
"description-only generation needs no custom-field slot even at native capacity");
var onePresent = "Power:old;" + string.Concat(Enumerable.Range(0, 19)
.Select(index => "Custom" + index + ":keep;"));
- result = BlueprintDescriptionFields.TryUpdate(onePresent, firstFields, 20,
+ result = BlueprintDescriptionFields.TryUpdate(onePresent, firstField, 20,
EscapeNativeField, UnescapeNativeField, out updated);
Check(result == BlueprintFieldUpdateResult.Updated &&
updated == "Power:2.5GW;" + onePresent.Substring("Power:old;".Length),
"existing power fields can be updated at the native field limit");
var otherFieldsAtCapacity = "Input:manual;Output:manual;" + string.Concat(Enumerable.Range(0, 18)
.Select(index => "Custom" + index + ":keep;"));
- result = BlueprintDescriptionFields.TryUpdate(otherFieldsAtCapacity, firstFields, 20,
+ result = BlueprintDescriptionFields.TryUpdate(otherFieldsAtCapacity, firstField, 20,
EscapeNativeField, UnescapeNativeField, out rejected);
Check(result == BlueprintFieldUpdateResult.CapacityExceeded && rejected == otherFieldsAtCapacity,
"other input and output fields cannot be removed to make room for power");
- result = BlueprintDescriptionFields.TryUpdate("Unterminated:old", firstFields, 20,
+ result = BlueprintDescriptionFields.TryUpdate("Unterminated:old", firstField, 20,
EscapeNativeField, UnescapeNativeField, out rejected);
Check(result == BlueprintFieldUpdateResult.InvalidFields && rejected == "Unterminated:old",
"invalid native serialization is rejected without changing existing text");
@@ -2111,16 +2251,16 @@ internal static class Program
{
Check(!BlueprintDescriptionFields.IsNativeFormatValid(malformed),
"malformed native fields are detected before the inspector collects pending edits");
- result = BlueprintDescriptionFields.TryUpdate(malformed, firstFields, 20,
+ result = BlueprintDescriptionFields.TryUpdate(malformed, firstField, 20,
EscapeNativeField, UnescapeNativeField, out rejected);
Check(result == BlueprintFieldUpdateResult.InvalidFields && rejected == malformed,
"malformed native fields cannot be partially replaced or silently discarded");
}
}
- private static BlueprintDescriptionField[] TestBlueprintFields(string power)
+ private static BlueprintDescriptionField TestPowerField(string power)
{
- return new[] { new BlueprintDescriptionField("Power", power, "耗电") };
+ return new BlueprintDescriptionField("Power", power, "耗电");
}
private static string EscapeNativeField(string value)