fix(production): correct full-load capture and solver scaling

Stop capturing the transient miner output damper, apply the sandbox boost state to artificial stars as for launchers, and keep lens-free photon flows when no ray receiver is selected.

Scale the planner conservation check by each ledger row and normalize the simplex right-hand side so large rates no longer fail. Skip non-production objects before copying native settings, decode blueprints through the native paste path, and simplify analyzer mode resolution.

Update stale ProductionCheck expectations, add regression checks, and document the rules.
This commit is contained in:
soarqin committed 2026-10-25 14:23:52 +08:00
1 parent 426cdf8975
commit b1b6785572
13 files changed
+418 -254

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@
## Architecture
- UXAssist production calculations must use immutable snapshots captured from loaded Proto, PrefabDesc, and Cargo data on the game thread. Keep the planner and fixed-building analyzer pure-managed, express material rates in double items per minute and power in watts, and report unknown material and power results independently with structured diagnostics. Convert native ticks, fixed-point speeds, and per-second rates explicitly. Use native facility-specific production and power rules; keep generation, accumulator charging and discharging, and Dyson-sphere demand separate. Require explicit resource and operating settings when they cannot be captured. Verify native rules against the original DLL and compile affected mods; leave in-game validation to a person rather than automated gameplay or save parsing. See [production architecture](UXAssist/docs/ProductionArchitecture.md).
- UXAssist production calculations must use immutable snapshots captured from loaded Proto, PrefabDesc, and Cargo data on the game thread. Keep the planner and fixed-building analyzer pure-managed, express material rates in double items per minute and power in watts, and report unknown material and power results independently with structured diagnostics. Convert native ticks, fixed-point speeds, and per-second rates explicitly. Use native facility-specific production and power rules; keep generation, accumulator charging and discharging, and Dyson-sphere demand separate. Require explicit resource and operating settings when they cannot be captured, and never capture transient runtime throttles such as the miner output damper. Treat a stored sandbox boost mode as applied only through an explicit or live-captured `BoostEnabled` state. Verify native rules against the original DLL, compile affected mods, and keep the synthetic `UXAssist/tools/ProductionCheck` checks passing; leave in-game validation to a person rather than automated gameplay or save parsing. See [production architecture](UXAssist/docs/ProductionArchitecture.md).
- Production catalog synthetic recipe IDs are calculation-only negative output item IDs; never pass them to native recipe lookups or setters. Rebuild the catalog on game begin after preload mutations, and invalidate derived caches on `ProductionCatalogService.Changed`, including catalog clearing. Preserve accumulator coating through exchange and bound spray reuse by same-item output and demand. Live-selection operating overrides use signed object IDs; blueprint overrides use blueprint indices. Keep renewable generation at ideal rated conditions and do not count gas collectors' self-fueling as grid consumption.
- CheatEnabler belt-signal upstream statistics use the shared production planner's independent production and consumption ledgers. Cache per-item material results by catalog and spray settings, keep separate per-belt fractional accumulators, and never run the solver in the logic tick. Missing data must not interrupt item generation.
- UXAssist Dark Fog buy-out belt signals keep each item ID, per-Metaverse rate, localization key, and embedded icon path in one definition. Name embedded icon files after the current English item names and synchronize resource includes and loader paths when renaming them. Preserve the legacy signal and saved-stock order. Rates represent equivalent single-material value: a native bundle of 10 Silicon-based Neurons, 10 Negentropy Singularities, and 10 Matter Recombinators per Metaverse corresponds to 30 of any one selected material per Metaverse.
+102 -110
View File
@@ -43,7 +43,8 @@ public static class BlueprintSelectionReader
public static BlueprintSelectionCapture Capture(PlanetFactory factory, IEnumerable<int> selectedObjectIds,
BlueprintSelectionContext context)
{
if (factory == null || ProductionCatalogService.Current == null)
var catalog = ProductionCatalogService.Current;
if (factory == null || catalog == null)
return Failure(ProductionDiagnosticCode.DataNotReady, "Factory or production data is not loaded.");
if (selectedObjectIds == null)
return Failure(ProductionDiagnosticCode.InvalidRequest, "The selected object IDs are required.");
@@ -60,56 +61,52 @@ public static class BlueprintSelectionReader
continue;
}
if (!IsLiveObject(factory, objectId))
var protoId = GetLiveProtoId(factory, objectId);
if (protoId == 0)
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"A blueprint-selected object no longer exists."));
continue;
}
if (!catalog.Buildings.TryGetValue(protoId, out var building)) continue;
var parameters = new BuildingParameters();
if (!parameters.CopyFromFactoryObject(objectId, factory, false))
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected building's settings could not be captured."));
"The selected building's settings could not be captured.", buildingItemId: protoId));
continue;
}
if (!ProductionCatalogService.Current.Buildings.ContainsKey(parameters.itemId)) continue;
var operation = new Dictionary<string, double>();
var mode = GetMode(parameters);
var speedFactor = GetLiveSpeed(factory, objectId, parameters.type, operation);
AddSettings(parameters, operation);
var kind = ProductionCatalogService.Current.Buildings[parameters.itemId].Kind;
if (parameters.type == BuildingType.Lab && operation.ContainsKey("ResearchMode"))
CaptureResearchSettings(factory, operation);
if (kind == ProductionBuildingKind.Miner)
CaptureMiningSettings(factory, objectId,
ProductionCatalogService.Current.Buildings[parameters.itemId], operation);
if (kind == ProductionBuildingKind.Collector)
CaptureCollectionSettings(factory, operation);
if (kind == ProductionBuildingKind.FuelGenerator)
CaptureFuelSettings(factory, objectId, operation);
if (kind == ProductionBuildingKind.RayReceiver)
CaptureRaySettings(factory, objectId, operation);
if (kind == ProductionBuildingKind.Ejector || kind == ProductionBuildingKind.Silo)
CaptureLaunchSettings(factory, objectId, kind, operation);
if (context?.OperatingParametersByObjectId.TryGetValue(objectId, out var supplied) == true && supplied != null)
if (operation.ContainsKey("ResearchMode")) CaptureResearchSettings(factory, operation);
switch (building.Kind)
{
foreach (var entry in supplied) operation[entry.Key] = entry.Value;
case ProductionBuildingKind.Miner:
CaptureMiningSettings(factory, objectId, building, operation);
break;
case ProductionBuildingKind.Collector:
CaptureCollectionSettings(factory, operation);
break;
case ProductionBuildingKind.FuelGenerator:
CaptureFuelSettings(factory, objectId, operation);
break;
case ProductionBuildingKind.RayReceiver:
CaptureRaySettings(factory, objectId, operation);
break;
case ProductionBuildingKind.Ejector:
case ProductionBuildingKind.Silo:
CaptureLaunchSettings(factory, objectId, building.Kind, operation);
break;
}
var recipeId = kind == ProductionBuildingKind.Fractionator
ApplySupplied(context?.OperatingParametersByObjectId, objectId, operation);
var recipeId = building.Kind == ProductionBuildingKind.Fractionator
? GetLiveFractionationRecipe(factory, objectId) : parameters.recipeId;
if (kind == ProductionBuildingKind.Fractionator &&
operation.TryGetValue("FluidItemId", out var fluidItemId))
recipeId = FindFractionationRecipe((int)fluidItemId);
ReportMissingSettings(kind, parameters, operation, diagnostics);
if (kind == ProductionBuildingKind.Fractionator && recipeId == 0)
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The fractionator's input item is not selected.", buildingItemId: parameters.itemId));
snapshots.Add(new ProductionBuildingSnapshot(objectId, parameters.itemId, recipeId, 1,
mode, speedFactor, operation));
snapshots.Add(CreateSnapshot(catalog, building, objectId, parameters, recipeId, speedFactor, operation,
diagnostics));
}
return new BlueprintSelectionCapture(snapshots, diagnostics);
@@ -118,7 +115,8 @@ public static class BlueprintSelectionReader
public static BlueprintSelectionCapture FromBlueprint(IEnumerable<BlueprintBuilding> buildings,
BlueprintSelectionContext context = null)
{
if (ProductionCatalogService.Current == null)
var catalog = ProductionCatalogService.Current;
if (catalog == null)
return Failure(ProductionDiagnosticCode.DataNotReady, "Production data is not loaded.");
if (buildings == null)
return Failure(ProductionDiagnosticCode.InvalidRequest, "A blueprint building list is required.");
@@ -142,43 +140,32 @@ public static class BlueprintSelectionReader
continue;
}
var item = LDB.items.Select(blueprint.itemId);
var model = LDB.models.Select(blueprint.modelIndex);
if (model?.prefabDesc == null || LDB.items.Select(blueprint.itemId) == null)
if (item == null || model?.prefabDesc == null)
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.UnknownItem,
"A blueprint building's model or item is unknown.", buildingItemId: blueprint.itemId));
continue;
}
if (!ProductionCatalogService.Current.Buildings.ContainsKey(blueprint.itemId)) continue;
if (!catalog.Buildings.TryGetValue(blueprint.itemId, out var building)) continue;
var parameters = new BuildingParameters
// Decode the settings the same way native blueprint paste does.
var parameters = new BuildingParameters();
parameters.CopyFromBuildPreview(new BuildPreview
{
type = ClassifyNativeType(model.prefabDesc),
itemId = blueprint.itemId,
modelIndex = blueprint.modelIndex,
item = item,
desc = model.prefabDesc,
recipeId = blueprint.recipeId,
filterId = blueprint.filterId
};
parameters.FromParamsArray(blueprint.parameters);
filterId = blueprint.filterId,
parameters = blueprint.parameters
});
var operation = new Dictionary<string, double>();
AddSettings(parameters, operation);
if (context?.OperatingParametersByIndex.TryGetValue(blueprint.index, out var supplied) == true)
{
foreach (var entry in supplied) operation[entry.Key] = entry.Value;
}
var kind = ProductionCatalogService.Current.Buildings[blueprint.itemId].Kind;
var recipeId = blueprint.recipeId;
if (kind == ProductionBuildingKind.Fractionator &&
operation.TryGetValue("FluidItemId", out var fluidItemId))
recipeId = FindFractionationRecipe((int)fluidItemId);
ReportMissingSettings(kind, parameters, operation, diagnostics);
if (kind == ProductionBuildingKind.Fractionator && recipeId == 0)
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"A blueprint fractionator needs its input item.", buildingItemId: blueprint.itemId));
snapshots.Add(new ProductionBuildingSnapshot(0, blueprint.itemId, recipeId, 1,
GetMode(parameters), operatingParameters: operation));
ApplySupplied(context?.OperatingParametersByIndex, blueprint.index, operation);
snapshots.Add(CreateSnapshot(catalog, building, 0, parameters, parameters.recipeId, null, operation,
diagnostics));
}
return new BlueprintSelectionCapture(snapshots, diagnostics);
@@ -190,15 +177,39 @@ public static class BlueprintSelectionReader
new[] { new ProductionDiagnostic(code, message) });
}
private static bool IsLiveObject(PlanetFactory factory, int objectId)
private static int GetLiveProtoId(PlanetFactory factory, int objectId)
{
if (objectId > 0)
return factory.entityPool != null && objectId < factory.entityCursor &&
objectId < factory.entityPool.Length && factory.entityPool[objectId].id == objectId;
if (objectId >= 0 || objectId == int.MinValue) return false;
objectId < factory.entityPool.Length && factory.entityPool[objectId].id == objectId
? factory.entityPool[objectId].protoId : 0;
if (objectId == 0 || objectId == int.MinValue) return 0;
var prebuildId = -objectId;
return factory.prebuildPool != null && prebuildId < factory.prebuildCursor &&
prebuildId < factory.prebuildPool.Length && factory.prebuildPool[prebuildId].id == prebuildId;
prebuildId < factory.prebuildPool.Length && factory.prebuildPool[prebuildId].id == prebuildId
? factory.prebuildPool[prebuildId].protoId : 0;
}
private static void ApplySupplied(IReadOnlyDictionary<int, Dictionary<string, double>> supplied, int key,
IDictionary<string, double> operation)
{
if (supplied == null || !supplied.TryGetValue(key, out var settings) || settings == null) return;
foreach (var entry in settings) operation[entry.Key] = entry.Value;
}
private static ProductionBuildingSnapshot CreateSnapshot(ProductionCatalog catalog, ProductionBuilding building,
int objectId, BuildingParameters parameters, int recipeId, double? speedFactor,
Dictionary<string, double> operation, ICollection<ProductionDiagnostic> diagnostics)
{
if (building.Kind == ProductionBuildingKind.Fractionator &&
operation.TryGetValue("FluidItemId", out var fluidItemId))
recipeId = FindFractionationRecipe((int)fluidItemId);
ReportMissingSettings(building, parameters, operation, diagnostics);
if (building.Kind == ProductionBuildingKind.Fractionator && recipeId == 0)
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The fractionator's input item is not selected.", buildingItemId: building.ItemId));
return new ProductionBuildingSnapshot(objectId, building.ItemId, recipeId, 1, GetMode(catalog, parameters),
speedFactor, operation);
}
private static double? GetLiveSpeed(PlanetFactory factory, int objectId, BuildingType type,
@@ -245,7 +256,6 @@ public static class BlueprintSelectionReader
if (minerId <= 0 || minerId >= pool.Length || pool[minerId].id != minerId) return;
ref var miner = ref pool[minerId];
operation["MachineSpeedFactor"] = miner.speed / ProductionUnits.FixedPointScale;
operation["SpeedDamper"] = miner.speedDamper;
if (building.MinerKind == ProductionMinerKind.Water || miner.veinCount <= 0 ||
miner.veins == null || miner.veinCount > miner.veins.Length || factory.veinPool == null) return;
@@ -300,8 +310,10 @@ public static class BlueprintSelectionReader
var generatorId = factory.entityPool[objectId].powerGenId;
var pool = factory.powerSystem.genPool;
if (generatorId <= 0 || generatorId >= pool.Length || pool[generatorId].id != generatorId) return;
var fuelId = pool[generatorId].curFuelId > 0 ? pool[generatorId].curFuelId : pool[generatorId].fuelId;
ref var generator = ref pool[generatorId];
var fuelId = generator.curFuelId > 0 ? generator.curFuelId : generator.fuelId;
if (fuelId > 0) operation["FuelItemId"] = fuelId;
if (generator.fuelMask == 4) operation[SandboxBoost.EnabledKey] = generator.boost ? 1 : 0;
}
private static void CaptureRaySettings(PlanetFactory factory, int objectId,
@@ -331,7 +343,7 @@ public static class BlueprintSelectionReader
var siloId = entity.siloId;
if (system.siloPool == null || siloId <= 0 || siloId >= system.siloPool.Length ||
system.siloPool[siloId].id != siloId) return;
operation["BoostEnabled"] = system.siloPool[siloId].boost ? 1 : 0;
operation[SandboxBoost.EnabledKey] = system.siloPool[siloId].boost ? 1 : 0;
operation["LaunchAvailable"] = factory.dysonSphere != null &&
factory.dysonSphere.GetAutoNodeCount() > 0 ? 1 : 0;
return;
@@ -341,7 +353,7 @@ public static class BlueprintSelectionReader
if (system.ejectorPool == null || ejectorId <= 0 || ejectorId >= system.ejectorPool.Length ||
system.ejectorPool[ejectorId].id != ejectorId) return;
ref var ejector = ref system.ejectorPool[ejectorId];
operation["BoostEnabled"] = ejector.boost ? 1 : 0;
operation[SandboxBoost.EnabledKey] = ejector.boost ? 1 : 0;
var swarm = factory.dysonSphere?.swarm;
operation["LaunchAvailable"] = 0;
if (swarm?.orbits == null) return;
@@ -378,15 +390,14 @@ public static class BlueprintSelectionReader
{
operation["Mode0"] = parameters.mode0;
operation["Mode1"] = parameters.mode1;
operation["Mode2"] = parameters.mode2;
operation["FilterItemId"] = parameters.filterId;
if (parameters.type == BuildingType.Lab && parameters.mode0 == 2)
operation["ResearchMode"] = 1;
}
private static void ReportMissingSettings(ProductionBuildingKind kind, BuildingParameters parameters,
private static void ReportMissingSettings(ProductionBuilding building, BuildingParameters parameters,
IReadOnlyDictionary<string, double> operation, ICollection<ProductionDiagnostic> diagnostics)
{
var kind = building.Kind;
var requiredKey = parameters.type == BuildingType.Lab && parameters.mode0 == 2 ? "TechId" :
kind == ProductionBuildingKind.Miner ? "ResourceItemId" :
kind == ProductionBuildingKind.Collector ? "GasCount" :
@@ -395,24 +406,24 @@ public static class BlueprintSelectionReader
if (requiredKey != null && !operation.ContainsKey(requiredKey))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
$"The selected building needs the {requiredKey} operating parameter.",
buildingItemId: parameters.itemId));
buildingItemId: building.ItemId));
if (parameters.type == BuildingType.Lab && parameters.mode0 == 2 &&
!operation.ContainsKey("ResearchSpeed"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The research lab needs the current research technology speed.",
buildingItemId: parameters.itemId));
buildingItemId: building.ItemId));
if (kind == ProductionBuildingKind.Fractionator && !operation.ContainsKey("StackSize"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The fractionator needs its circulating stack size.", buildingItemId: parameters.itemId));
"The fractionator needs its circulating stack size.", buildingItemId: building.ItemId));
if (kind == ProductionBuildingKind.RayReceiver)
{
if (!operation.ContainsKey("LensItemId"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The receiver needs a lens item ID, or zero for no lens.", buildingItemId: parameters.itemId));
"The receiver needs a lens item ID, or zero for no lens.", buildingItemId: building.ItemId));
if (!operation.ContainsKey("SolarEnergyLossRate"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The receiver needs the solar energy loss technology setting.",
buildingItemId: parameters.itemId));
buildingItemId: building.ItemId));
}
if (kind == ProductionBuildingKind.Collector)
{
@@ -420,7 +431,7 @@ public static class BlueprintSelectionReader
!operation.ContainsKey("MiningSpeedMultiplier"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The collector needs the planet's gas energy and current mining technology speed.",
buildingItemId: parameters.itemId));
buildingItemId: building.ItemId));
if (operation.TryGetValue("GasCount", out var count) && count > 0 && count <= 16 &&
count == Math.Truncate(count))
{
@@ -430,38 +441,34 @@ public static class BlueprintSelectionReader
operation.ContainsKey($"GasSpeedPerSecond{index}")) continue;
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
$"The collector needs gas item and speed for resource {index}.",
buildingItemId: parameters.itemId));
buildingItemId: building.ItemId));
}
}
}
if (kind == ProductionBuildingKind.Ejector || kind == ProductionBuildingKind.Silo)
{
if (!operation.ContainsKey("LaunchAvailable"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The launcher needs a usable orbit or Dyson-sphere node setting.",
buildingItemId: parameters.itemId));
var boostKey = kind == ProductionBuildingKind.Ejector ? "Mode1" : "Mode0";
if (operation.TryGetValue(boostKey, out var boostMode) && boostMode == 1 &&
!operation.ContainsKey("BoostEnabled"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The launcher needs its current sandbox boost setting.",
buildingItemId: parameters.itemId));
}
if ((kind == ProductionBuildingKind.Ejector || kind == ProductionBuildingKind.Silo) &&
!operation.ContainsKey("LaunchAvailable"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The launcher needs a usable orbit or Dyson-sphere node setting.",
buildingItemId: building.ItemId));
var boostKey = SandboxBoost.ModeKey(building);
if (boostKey != null && operation.TryGetValue(boostKey, out var boostMode) && boostMode == 1 &&
!operation.ContainsKey(SandboxBoost.EnabledKey))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The building needs its current sandbox boost setting.", buildingItemId: building.ItemId));
if (kind == ProductionBuildingKind.Miner)
{
if (!operation.ContainsKey("MiningSpeedMultiplier"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The miner needs the current mining technology speed.", buildingItemId: parameters.itemId));
var minerKind = ProductionCatalogService.Current.Buildings[parameters.itemId].MinerKind;
var factorName = minerKind == ProductionMinerKind.Vein ? "VeinCount" :
minerKind == ProductionMinerKind.Oil ? "OilUnits" : null;
"The miner needs the current mining technology speed.", buildingItemId: building.ItemId));
var factorName = building.MinerKind == ProductionMinerKind.Vein ? "VeinCount" :
building.MinerKind == ProductionMinerKind.Oil ? "OilUnits" : null;
if (factorName != null && !operation.ContainsKey(factorName))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
$"The miner needs its {factorName} resource factor.", buildingItemId: parameters.itemId));
$"The miner needs its {factorName} resource factor.", buildingItemId: building.ItemId));
}
}
private static ProliferationMode GetMode(BuildingParameters parameters)
private static ProliferationMode GetMode(ProductionCatalog catalog, BuildingParameters parameters)
{
if (parameters.type != BuildingType.Assembler && parameters.type != BuildingType.Lab)
return ProliferationMode.None;
@@ -473,22 +480,7 @@ public static class BlueprintSelectionReader
if (parameters.type == BuildingType.Assembler)
BuildingParameters.SimpleParamFromParamsArray(parameters.type, parameters.parameters,
ref recipeId, ref filterId, ref mode0, ref mode1);
var recipe = LDB.recipes.Select(recipeId);
return mode1 == 1 || recipe != null && !recipe.productive
return mode1 == 1 || catalog.Recipes.TryGetValue(recipeId, out var recipe) && !recipe.Productive
? ProliferationMode.Speedup : ProliferationMode.ExtraProducts;
}
private static BuildingType ClassifyNativeType(PrefabDesc prefab)
{
if (prefab.isAssembler) return BuildingType.Assembler;
if (prefab.isLab) return BuildingType.Lab;
if (prefab.isEjector) return BuildingType.Ejector;
if (prefab.isSilo) return BuildingType.Silo;
if (prefab.isPowerExchanger) return BuildingType.Exchanger;
if (prefab.gammaRayReceiver) return BuildingType.Gamma;
if (prefab.minerType != EMinerType.None) return BuildingType.Miner;
if (prefab.isPowerGen && prefab.fuelMask == 4) return BuildingType.ArtifacialStar;
if (prefab.geothermal) return BuildingType.Geothermal;
return BuildingType.Other;
}
}
+28 -29
View File
@@ -145,36 +145,9 @@ public sealed class FactoryBlackBoxAnalyzer
continue;
}
if (snapshot.SpeedFactor.HasValue)
building = new ProductionBuilding(building.ItemId, building.Category, snapshot.SpeedFactor.Value,
building.WorkingPowerWatts, building.IdlePowerWatts, building.Kind,
building.RatedGenerationWatts, building.ExchangeRateWatts,
building.AccumulatorEnergyJoules, building.EmptyAccumulatorItemId,
building.FullAccumulatorItemId, building.RenewableSource,
building.MinerKind, building.MiningPeriodTicks,
building.FuelMask, building.FuelUseWatts,
building.PowerProductItemId, building.PowerProductEnergyJoules,
building.CatalystMask, building.LaunchChargeTicks,
building.LaunchCooldownTicks, building.AmmunitionItemId,
building.CollectorSpeedMultiplier);
if (snapshot.SpeedFactor.HasValue) building = building.WithSpeedFactor(snapshot.SpeedFactor.Value);
var mode = request.ProliferationEnabled
? building.Kind == ProductionBuildingKind.Fractionator
? ProliferationMode.Speedup : building.Kind == ProductionBuildingKind.Exchanger &&
snapshot.OperatingParameters.TryGetValue("Mode0", out var exchangerMode) && exchangerMode != 0
? ProliferationMode.Speedup : building.Kind == ProductionBuildingKind.FuelGenerator
? ProliferationMode.Speedup : building.Kind == ProductionBuildingKind.RayReceiver
? snapshot.OperatingParameters.TryGetValue("LensItemId", out var lensId) && lensId > 0
? ProliferationMode.Speedup : ProliferationMode.None
: building.Kind == ProductionBuildingKind.Collector
? ProliferationMode.None
: building.Category == ProductionRecipeCategory.Research && snapshot.RecipeId == 0 &&
snapshot.OperatingParameters.TryGetValue("ResearchMode", out var researchModeSetting) &&
researchModeSetting > 0 ? ProliferationMode.ExtraProducts
: building.Kind == ProductionBuildingKind.Ejector ||
building.Kind == ProductionBuildingKind.Silo
? ProliferationMode.Speedup
: snapshot.ProliferationMode
: ProliferationMode.None;
? FullProliferationMode(building, snapshot) : ProliferationMode.None;
if (!_evaluator.TryEvaluate(_catalog, recipe, building, mode,
mode == ProliferationMode.None ? 0 : _catalog.MaximumProliferationLevel,
snapshot.OperatingParameters, out var process, out var diagnostic))
@@ -250,6 +223,32 @@ public sealed class FactoryBlackBoxAnalyzer
return new ProductionReport(status, materialComplete, powerComplete, flows, groups, diagnostics, power);
}
private static ProliferationMode FullProliferationMode(ProductionBuilding building,
ProductionBuildingSnapshot snapshot)
{
var parameters = snapshot.OperatingParameters;
switch (building.Kind)
{
case ProductionBuildingKind.Fractionator:
case ProductionBuildingKind.FuelGenerator:
case ProductionBuildingKind.Ejector:
case ProductionBuildingKind.Silo:
return ProliferationMode.Speedup;
case ProductionBuildingKind.Exchanger:
return parameters.TryGetValue("Mode0", out var exchangerMode) && exchangerMode != 0
? ProliferationMode.Speedup : snapshot.ProliferationMode;
case ProductionBuildingKind.RayReceiver:
return parameters.TryGetValue("LensItemId", out var lensId) && lensId > 0
? ProliferationMode.Speedup : ProliferationMode.None;
case ProductionBuildingKind.Collector:
return ProliferationMode.None;
default:
return building.Category == ProductionRecipeCategory.Research && snapshot.RecipeId == 0 &&
parameters.TryGetValue("ResearchMode", out var researchMode) && researchMode > 0
? ProliferationMode.ExtraProducts : snapshot.ProliferationMode;
}
}
private static Dictionary<int, double> Scale(IReadOnlyDictionary<int, double> flows, double factor)
{
return flows.ToDictionary(entry => entry.Key, entry => entry.Value * factor);
+6 -8
View File
@@ -57,17 +57,15 @@ public sealed class FuelGenerationAdapter : IProductionProcessAdapter
}
var boostFactor = 1.0;
if (building.FuelMask == 4)
var boostModeKey = SandboxBoost.ModeKey(building);
if (boostModeKey != null)
{
if (!operatingParameters.TryGetValue("Mode0", out var boostMode) ||
(boostMode != 0 && boostMode != 1))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Select the artificial star's native boost setting.", buildingItemId: building.ItemId);
if (!SandboxBoost.TryResolve(operatingParameters, boostModeKey, building.ItemId, out var boosted,
out diagnostic))
return false;
}
boostFactor = (boostMode == 1 ? 100 : 1) * fuel.StarOutputMultiplier;
// Artificial stars apply the sandbox boost and the strange annihilation fuel multiplier natively.
boostFactor = (boosted ? 100 : 1) * fuel.StarOutputMultiplier;
}
var proliferationFactor = mode == ProliferationMode.None ? 1 :
+2 -20
View File
@@ -58,27 +58,9 @@ public sealed class LaunchProcessAdapter : IProductionProcessAdapter
return false;
}
var boostModeKey = building.Kind == ProductionBuildingKind.Ejector ? "Mode1" : "Mode0";
if (!operatingParameters.TryGetValue(boostModeKey, out var boostMode) ||
(boostMode != 0 && boostMode != 1) ||
boostMode == 1 && !operatingParameters.ContainsKey("BoostEnabled"))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Provide the launcher's native boost mode and whether sandbox boost is active.",
buildingItemId: building.ItemId);
if (!SandboxBoost.TryResolve(operatingParameters, SandboxBoost.ModeKey(building), building.ItemId,
out var boosted, out diagnostic))
return false;
}
var boosted = operatingParameters.TryGetValue("BoostEnabled", out var boostEnabled) &&
boostEnabled == 1;
if (operatingParameters.ContainsKey("BoostEnabled") &&
(boostEnabled != 0 && boostEnabled != 1 || boosted && boostMode != 1))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The sandbox boost setting conflicts with the launcher's native mode.",
buildingItemId: building.ItemId);
return false;
}
var speedBonus = 0.0;
var powerMultiplier = 1.0;
+3 -15
View File
@@ -66,22 +66,10 @@ public sealed class MiningProcessAdapter : IProductionProcessAdapter
machineSpeed = suppliedSpeed;
}
var speedDamper = 1.0;
if (operatingParameters.TryGetValue("SpeedDamper", out var suppliedDamper))
{
if (!FinitePositive(suppliedDamper))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The miner speed damper must be positive.", buildingItemId: building.ItemId);
return false;
}
speedDamper = suppliedDamper;
}
// The native speed damper only throttles backed-up output, so full load keeps its unobstructed value of 1.
var perMinute = ProductionUnits.TicksPerMinute * ProductionUnits.FixedPointScale /
building.MiningPeriodTicks * miningSpeed * machineSpeed * speedDamper * resourceFactor;
var powerRatio = speedDamper * machineSpeed * machineSpeed;
building.MiningPeriodTicks * miningSpeed * machineSpeed * resourceFactor;
var powerRatio = machineSpeed * machineSpeed;
var workingWatts = building.WorkingPowerWatts * powerRatio +
building.IdlePowerWatts * (1 - powerRatio);
if (!FinitePositive(perMinute) || workingWatts < 0 ||
+9
View File
@@ -245,6 +245,15 @@ public sealed class ProductionBuilding
AmmunitionItemId = ammunitionItemId;
CollectorSpeedMultiplier = collectorSpeedMultiplier;
}
internal ProductionBuilding WithSpeedFactor(double speedFactor)
{
return new ProductionBuilding(ItemId, Category, speedFactor, WorkingPowerWatts, IdlePowerWatts, Kind,
RatedGenerationWatts, ExchangeRateWatts, AccumulatorEnergyJoules, EmptyAccumulatorItemId,
FullAccumulatorItemId, RenewableSource, MinerKind, MiningPeriodTicks, FuelMask, FuelUseWatts,
PowerProductItemId, PowerProductEnergyJoules, CatalystMask, LaunchChargeTicks, LaunchCooldownTicks,
AmmunitionItemId, CollectorSpeedMultiplier);
}
}
public sealed class ProductionCatalog
+8 -2
View File
@@ -238,9 +238,15 @@ public sealed partial class ProductionPlanner
for (var row = 0; row < constraintCount; row++)
{
var balance = -rhs[row];
var magnitude = Math.Max(1, Math.Abs(rhs[row]));
for (var column = 0; column < columnCount; column++)
balance += matrix[row, column] * solution.Values[column];
if (Math.Abs(balance) > 1e-7 * Math.Max(1, Math.Abs(rhs[row])))
{
var term = matrix[row, column] * solution.Values[column];
balance += term;
magnitude = Math.Max(magnitude, Math.Abs(term));
}
if (Math.Abs(balance) > 1e-7 * magnitude)
return Fail(ProductionDiagnosticCode.ConservationFailure,
"The solved production ledger does not conserve this item.",
row < rows.Length ? rows[row] : reusableSprayItems[(row - rows.Length) / 2]);
+35 -3
View File
@@ -17,10 +17,14 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
{
process = null;
diagnostic = null;
if (building?.Kind != ProductionBuildingKind.RayReceiver)
if (building == null)
return TryEvaluateWithoutReceiver(recipe, mode, operatingParameters, out process, out diagnostic);
if (building.Kind != ProductionBuildingKind.RayReceiver)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingBuilding,
"Select a ray receiver to evaluate photon generation.", recipeId: recipe?.Id ?? 0);
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding,
"The selected building cannot receive Dyson-sphere rays.", recipeId: recipe?.Id ?? 0,
buildingItemId: building.ItemId);
return false;
}
@@ -141,6 +145,34 @@ public sealed class RayReceiverAdapter : IProductionProcessAdapter
return true;
}
// Photon output per cycle does not depend on the receiver, but lens wear, speedup, and power do.
private static bool TryEvaluateWithoutReceiver(ProductionRecipe recipe, ProliferationMode mode,
IReadOnlyDictionary<string, double> operatingParameters, out ProductionProcess process,
out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (recipe.Inputs.Count != 0 || recipe.Outputs.Count != 1)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"A photon recipe must have one output and no inputs.", recipeId: recipe.Id);
return false;
}
if (mode != ProliferationMode.None ||
operatingParameters != null && operatingParameters.TryGetValue("LensItemId", out var lensId) &&
lensId != 0)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingBuilding,
"Select a ray receiver to evaluate lens consumption and speedup.", recipeId: recipe.Id);
return false;
}
process = new ProductionProcess(recipe.Id, 0, ProliferationMode.None, 0,
Array.Empty<KeyValuePair<int, double>>(), recipe.Outputs, 0, 0, false);
return true;
}
private static bool Finite(double value)
{
return !double.IsNaN(value) && !double.IsInfinity(value);
+50
View File
@@ -0,0 +1,50 @@
using System.Collections.Generic;
namespace UXAssist.Production;
internal static class SandboxBoost
{
internal const string EnabledKey = "BoostEnabled";
internal static string ModeKey(ProductionBuilding building)
{
switch (building.Kind)
{
case ProductionBuildingKind.Ejector:
return "Mode1";
case ProductionBuildingKind.Silo:
case ProductionBuildingKind.FuelGenerator when building.FuelMask == 4:
return "Mode0";
default:
return null;
}
}
// Native paste applies a stored boost mode only with sandbox tools enabled; live captures report the applied state.
internal static bool TryResolve(IReadOnlyDictionary<string, double> operatingParameters, string modeKey,
int buildingItemId, out bool boosted, out ProductionDiagnostic diagnostic)
{
boosted = false;
diagnostic = null;
if (operatingParameters == null || !operatingParameters.TryGetValue(modeKey, out var mode) ||
mode != 0 && mode != 1 || mode == 1 && !operatingParameters.ContainsKey(EnabledKey))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Provide the building's native boost mode and whether sandbox boost is active.",
buildingItemId: buildingItemId);
return false;
}
if (operatingParameters.TryGetValue(EnabledKey, out var enabled) &&
(enabled != 0 && enabled != 1 || enabled == 1 && mode != 1))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The sandbox boost setting conflicts with the building's native boost mode.",
buildingItemId: buildingItemId);
return false;
}
boosted = enabled == 1;
return true;
}
}
+27 -24
View File
@@ -46,9 +46,20 @@ internal static class TwoPhaseSimplex
if (rowCount == 0)
return new LinearSolveResult(LinearSolveStatus.Optimal, new double[columnCount]);
// Optimal values scale linearly with the right-hand side; normalize it so tolerances do not depend on rates.
var rightHandScale = 0.0;
foreach (var value in rightHandSide)
{
if (double.IsNaN(value) || double.IsInfinity(value))
throw new ArgumentException("The right-hand side contains a non-finite number.");
rightHandScale = Math.Max(rightHandScale, Math.Abs(value));
}
if (rightHandScale == 0) rightHandScale = 1;
var width = columnCount + rowCount;
var tableau = new double[rowCount, width + 1];
var basis = new int[rowCount];
var isBasic = new bool[width];
for (var row = 0; row < rowCount; row++)
{
var scale = 0.0;
@@ -59,27 +70,27 @@ internal static class TwoPhaseSimplex
scale = Math.Max(scale, Math.Abs(coefficients[row, column]));
}
if (double.IsNaN(rightHandSide[row]) || double.IsInfinity(rightHandSide[row]))
throw new ArgumentException("The right-hand side contains a non-finite number.");
var rightHand = rightHandSide[row] / rightHandScale;
if (scale == 0)
{
if (Math.Abs(rightHandSide[row]) > PivotTolerance)
if (Math.Abs(rightHand) > PivotTolerance)
return new LinearSolveResult(LinearSolveStatus.Infeasible);
scale = 1;
}
var sign = rightHandSide[row] < 0 ? -1 : 1;
var sign = rightHand < 0 ? -1 : 1;
for (var column = 0; column < columnCount; column++)
tableau[row, column] = sign * coefficients[row, column] / scale;
tableau[row, columnCount + row] = 1;
tableau[row, width] = sign * rightHandSide[row] / scale;
tableau[row, width] = sign * rightHand / scale;
basis[row] = columnCount + row;
isBasic[columnCount + row] = true;
}
var artificialObjective = new double[width];
for (var row = 0; row < rowCount; row++) artificialObjective[columnCount + row] = 1;
var iterations = 0;
var firstStatus = Optimize(tableau, basis, artificialObjective, Array.Empty<double[]>(),
var firstStatus = Optimize(tableau, basis, isBasic, artificialObjective, Array.Empty<double[]>(),
columnCount, ref iterations, iterationBudget, cancellation);
if (firstStatus != LinearSolveStatus.Optimal)
return new LinearSolveResult(firstStatus == LinearSolveStatus.Unbounded
@@ -93,8 +104,8 @@ internal static class TwoPhaseSimplex
for (var column = 0; column < columnCount; column++)
{
if (Contains(basis, column) || Math.Abs(tableau[row, column]) <= PivotTolerance) continue;
Pivot(tableau, basis, row, column);
if (isBasic[column] || Math.Abs(tableau[row, column]) <= PivotTolerance) continue;
Pivot(tableau, basis, isBasic, row, column);
break;
}
}
@@ -104,7 +115,7 @@ internal static class TwoPhaseSimplex
{
var costs = new double[width];
Array.Copy(objective, costs, columnCount);
var status = Optimize(tableau, basis, costs, optimizedObjectives, columnCount,
var status = Optimize(tableau, basis, isBasic, costs, optimizedObjectives, columnCount,
ref iterations, iterationBudget, cancellation);
if (status != LinearSolveStatus.Optimal) return new LinearSolveResult(status);
optimizedObjectives.Add(costs);
@@ -114,13 +125,13 @@ internal static class TwoPhaseSimplex
for (var row = 0; row < rowCount; row++)
{
if (basis[row] < columnCount)
values[basis[row]] = Math.Max(0, tableau[row, width]);
values[basis[row]] = Math.Max(0, tableau[row, width]) * rightHandScale;
}
return new LinearSolveResult(LinearSolveStatus.Optimal, values);
}
private static LinearSolveStatus Optimize(double[,] tableau, int[] basis, double[] costs,
private static LinearSolveStatus Optimize(double[,] tableau, int[] basis, bool[] isBasic, double[] costs,
IReadOnlyList<double[]> previousCosts, int enteringLimit, ref int iterations, int budget,
CancellationToken cancellation)
{
@@ -132,7 +143,7 @@ internal static class TwoPhaseSimplex
var entering = -1;
for (var column = 0; column < enteringLimit; column++)
{
if (Contains(basis, column) || ReducedCost(tableau, basis, costs, column) >= -ReducedTolerance)
if (isBasic[column] || ReducedCost(tableau, basis, costs, column) >= -ReducedTolerance)
continue;
var preservesPrevious = true;
foreach (var previous in previousCosts)
@@ -169,7 +180,7 @@ internal static class TwoPhaseSimplex
}
if (leaving < 0) return LinearSolveStatus.Unbounded;
Pivot(tableau, basis, leaving, entering);
Pivot(tableau, basis, isBasic, leaving, entering);
iterations++;
}
}
@@ -182,17 +193,7 @@ internal static class TwoPhaseSimplex
return reduced;
}
private static bool Contains(int[] basis, int column)
{
foreach (var basic in basis)
{
if (basic == column) return true;
}
return false;
}
private static void Pivot(double[,] tableau, int[] basis, int pivotRow, int pivotColumn)
private static void Pivot(double[,] tableau, int[] basis, bool[] isBasic, int pivotRow, int pivotColumn)
{
var rowCount = basis.Length;
var width = tableau.GetLength(1);
@@ -211,6 +212,8 @@ internal static class TwoPhaseSimplex
}
tableau[pivotRow, pivotColumn] = 1;
isBasic[basis[pivotRow]] = false;
isBasic[pivotColumn] = true;
basis[pivotRow] = pivotColumn;
}
}
+13 -8
View File
@@ -46,7 +46,7 @@ var selection = capture.CreateRequest(proliferationEnabled: true);
var report = new FactoryBlackBoxAnalyzer(ProductionCatalogService.Current).Analyze(selection);
```
`Capture` accepts existing entity IDs and negative prebuild IDs. Its optional third argument is a `BlueprintSelectionContext`; use `OperatingParametersByObjectId` to supply missing settings keyed by those same signed IDs. `FromBlueprint(blueprintBuildings, context)` captures a blueprint without live game objects and uses `OperatingParametersByIndex`, keyed by blueprint index. Supplied settings override captured values before validation. In particular, fractionator circulation and stack size must describe the intended full-load input, not transient inventory contents; `FluidItemId` can identify the input when the fractionator has not been filled.
`Capture` accepts existing entity IDs and negative prebuild IDs. Its optional third argument is a `BlueprintSelectionContext`; use `OperatingParametersByObjectId` to supply missing settings keyed by those same signed IDs. `FromBlueprint(blueprintBuildings, context)` captures a blueprint without live game objects, decodes settings through the native blueprint-paste path, and uses `OperatingParametersByIndex`, keyed by blueprint index. Supplied settings override captured values before validation. In particular, fractionator circulation and stack size must describe the intended full-load input, not transient inventory contents; `FluidItemId` can identify the input when the fractionator has not been filled. Transient runtime throttles, such as a miner's output backlog damper, are never captured.
The capture is read-only and does not alter the game's selection. `CreateRequest` carries capture diagnostics into the analyzer, so stale or unrecognized selected objects cannot turn into a falsely complete empty report. Duplicate selected IDs are diagnosed and counted once. Assembler proliferation modes are decoded from the native parameter array; lab modes use their native mode field. Nonproductive recipes use native acceleration rather than an invalid extra-products mode.
@@ -60,14 +60,16 @@ All parameters below are numbers in a building snapshot's `OperatingParameters`.
| --- | --- |
| Fractionator | A fractionation recipe, `CirculatingItemsPerMinute`, and `StackSize`. The throughput limit is 30 cargo per second times the stack size, or `1800 * StackSize` items per minute. Only successful conversions consume inputs; circulation changes throughput and power without becoming an external material input. The native power formula uses items per second, not per minute. |
| 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. 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. |
| 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` and `SpeedDamper` default to 1. Live capture records raw miner speed divided by 10,000 separately from the damper. Output scales by speed times damper; power uses `ratio = SpeedDamper * 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. 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 native `Mode0` (sandbox boost). 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); boosted modes also require `BoostEnabled`. 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. |
| 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. |
| Research-mode lab | `ResearchMode = 1`, `TechId`, and `ResearchSpeed`. The captured technology supplies matrix point requirements. Native matrix proliferation increases hashes and power, not matrix input per base hash; `ResearchHashesPerMinute` is separate from item production. |
Native blueprint paste applies a stored boost mode only while sandbox tools are enabled, so `BoostEnabled` states whether the boost is actually applied. Live capture reports the applied boost of ejectors, silos, and artificial stars; blueprint callers must supply it for boosted buildings.
The ejector and silo assume a usable orbit or node when `LaunchAvailable = 1`; their native geometric visibility and construction schedules are outside this full-load model. Power reports exclude logistics stations, distributors, transport, and mecha charging. Auxiliary power must come from an explicitly supplied list.
## CheatEnabler migration
@@ -76,14 +78,17 @@ The belt-signal generator uses `ProductionPlanner` material reports, not its for
## Validation
Use compilation and static review for development checks:
Use compilation, the synthetic game-free checks, and static review for development checks:
```powershell
dotnet build UXAssist/UXAssist.csproj -c Release --no-restore
dotnet build CheatEnabler/CheatEnabler.csproj -c Release --no-restore
dotnet run --project UXAssist/tools/ProductionCheck/ProductionCheck.csproj -c Release
git diff --check
```
`ProductionCheck` compiles the pure-managed production sources and the belt-signal statistics with hand-built catalogs. Update its expectations together with any intended change to production rules.
Compare special mechanics against method bodies in the original DSP DLL; the publicized repository reference is not an implementation source. Builds and DLL inspection do not establish in-game correctness. In-game acceptance is manual; automated tests and save parsing are not required.
Use a test game for the following manual checks. Compare full-load rates only with sufficient inputs, power, and output capacity; do not compare a throttled statistics window with theoretical capacity.
@@ -93,8 +98,8 @@ Use a test game for the following manual checks. Compare full-load rates only wi
- Supply fractionator circulation and stack context. For native 1% fractionation with fully sprayed input, 1,800 circulating items per minute yield 36 conversions per minute; at stack size 4, 7,200 circulating items per minute yield 144. Check throughput-dependent power separately.
- Request full accumulators and critical photons through the catalog's default synthetic routes. Confirm that missing building or receiver-loss settings produce incomplete power rather than an invented result.
- 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, a gas collector, and renewable generators. Check native miner power scaling, 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.
- 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.
- 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.
+134 -34
View File
@@ -17,6 +17,7 @@ internal static class Program
IntermediateBoundary();
ExternalSurplusAndNaturalOverrides();
ClosedLoopAndInfeasible();
LargeRatesConserve();
ProliferatorSupply();
ProliferatorGradesAndFinishedSpraying();
BlackBoxBalancesAndThreshold();
@@ -45,7 +46,13 @@ internal static class Program
var building = catalog.Buildings[10];
Check(evaluator.TryEvaluate(catalog, recipe, building, ProliferationMode.None, 0, null,
out var plain, out _), "ordinary process evaluates");
Equal(1, plain.CyclesPerBuildingPerMinute, "recipe tick duration");
Equal(1, plain.CyclesPerBuildingPerMinute, "a 3600-tick recipe completes one cycle per minute");
var oneSecond = new ProductionRecipe(105, ProductionRecipeCategory.Assemble, 60, true, recipe.Inputs,
recipe.Outputs);
Check(evaluator.TryEvaluate(catalog, oneSecond, building, ProliferationMode.None, 0, null,
out var nativeSecond, out _), "one-second process evaluates");
Equal(60, nativeSecond.CyclesPerBuildingPerMinute,
"native 60 ticks per second give a 60-tick recipe 60 cycles per minute");
Equal(1000, plain.WorkingPowerWatts, "working watts");
Check(evaluator.TryEvaluate(catalog, recipe, building, ProliferationMode.Speedup, 4, null,
out var speedup, out _), "speedup process evaluates");
@@ -186,6 +193,54 @@ internal static class Program
Check(failure.Diagnostics.Single().Code == ProductionDiagnosticCode.Infeasible, "infeasible loop diagnosed");
}
private static void LargeRatesConserve()
{
// Uneven ratios, coproducts, and spraying accumulate rounding that scales with the ledger rates.
var random = new Random(12345);
var items = Enumerable.Range(1, 8).Select(id => new ProductionItem(id, 0, true, false, 0, 0)).ToList();
items.Add(new ProductionItem(9, 909, false, false, 4, 60));
var recipes = new List<ProductionRecipe>
{
new ProductionRecipe(909, ProductionRecipeCategory.Assemble, 3600, true,
new[] { new KeyValuePair<int, double>(1, 1.7), new KeyValuePair<int, double>(2, 0.9) },
new[] { new KeyValuePair<int, double>(9, 1) })
};
for (var id = 10; id < 70; id++)
{
items.Add(new ProductionItem(id, 1000 + id, false, false, 0, 0));
var inputs = new Dictionary<int, double>();
for (var count = random.Next(1, 4); count > 0; count--)
{
var input = random.Next(1, id);
if (input == 9) input = 1;
inputs[input] = inputs.GetValueOrDefault(input) + Math.Round(random.NextDouble() * 5 + 0.1, 3);
}
var outputs = new Dictionary<int, double> { [id] = Math.Round(random.NextDouble() * 3 + 0.2, 3) };
if (random.NextDouble() < 0.3 && id > 11)
outputs[random.Next(10, id)] = Math.Round(random.NextDouble() + 0.05, 3);
recipes.Add(new ProductionRecipe(1000 + id, ProductionRecipeCategory.Assemble,
60 + random.Next(0, 600), random.NextDouble() < 0.7, inputs, outputs));
}
var catalog = new ProductionCatalog(items, recipes,
new[] { new ProductionBuilding(10, ProductionRecipeCategory.Assemble, 1.5, 270000, 12000) },
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 });
foreach (var scale in new[] { 1e-3, 1, 1e7 })
{
var request = Request((69, 7.3 * scale), (65, 3.1 * scale), (58, 1.9 * scale));
request.ProliferationEnabled = true;
request.ProliferatorItemId = 9;
request.SelfSprayProliferator = true;
request.SprayDeliveredItems.Add(69);
var report = new ProductionPlanner(catalog).Calculate(request);
Check(report.MaterialComplete && report.PowerComplete,
$"a plan scaled by {scale} conserves every ledger row");
}
}
private static void ProliferatorSupply()
{
var planner = new ProductionPlanner(Catalog());
@@ -339,23 +394,33 @@ internal static class Program
request.Buildings.Add(new ProductionBuildingSnapshot(301, 30, 501, 1, ProliferationMode.None,
operatingParameters: new Dictionary<string, double>
{
["CirculatingItemsPerMinute"] = 120,
["CirculatingItemsPerMinute"] = 7200,
["StackSize"] = 4
}));
var analyzer = new FactoryBlackBoxAnalyzer(catalog);
var plain = analyzer.Analyze(request);
Check(plain.MaterialComplete && plain.PowerComplete, "native fractionation inputs valid");
Equal(1.2, plain.ItemFlows[1].RequiredExternalSupply, "circulating fluid not an external import");
Equal(1.2, plain.ItemFlows[2].GrossProduction, "native fractionation probability");
Equal(5500, plain.Power.ConsumptionWatts, "native fractionation throughput power");
Equal(120, plain.Groups[0].Process.CirculatingItemsPerBuildingPerMinute,
Equal(72, plain.ItemFlows[1].RequiredExternalSupply, "circulating fluid not an external import");
Equal(72, plain.ItemFlows[2].GrossProduction, "native fractionation probability");
Equal(5500, plain.Power.ConsumptionWatts, "native fractionation power uses items per second");
Equal(7200, plain.Groups[0].Process.CirculatingItemsPerBuildingPerMinute,
"fractionation reports circulation separately");
request.ProliferationEnabled = true;
var sprayed = analyzer.Analyze(request);
Equal(2.4, sprayed.ItemFlows[2].GrossProduction, "native fractionation speedup probability");
Equal(144, sprayed.ItemFlows[2].GrossProduction, "native fractionation speedup probability");
Equal(13750, sprayed.Power.ConsumptionWatts, "native fractionation proliferation power");
request.ProliferationEnabled = false;
request.Buildings[0] = new ProductionBuildingSnapshot(301, 30, 501, 1, ProliferationMode.None,
operatingParameters: new Dictionary<string, double>
{
["CirculatingItemsPerMinute"] = 1800,
["StackSize"] = 1
});
Equal(1000, analyzer.Analyze(request).Power.ConsumptionWatts,
"an unstacked full buffer does not raise fractionation power");
var bad = new FactoryBlackBoxRequest();
bad.Buildings.Add(new ProductionBuildingSnapshot(301, 30, 501, 1, ProliferationMode.None));
Check(new FactoryBlackBoxAnalyzer(catalog).Analyze(bad).Diagnostics.Single().Code ==
@@ -436,20 +501,13 @@ internal static class Program
var request = new FactoryBlackBoxRequest();
request.Buildings.Add(new ProductionBuildingSnapshot(90, 90, 0, 1, ProliferationMode.None));
request.Buildings.Add(new ProductionBuildingSnapshot(91, 91, 0, 1, ProliferationMode.None));
request.Buildings.Add(new ProductionBuildingSnapshot(92, 92, 0, 1, ProliferationMode.None,
operatingParameters: new Dictionary<string, double> { ["GeothermalStrength"] = 0.5 }));
request.Buildings.Add(new ProductionBuildingSnapshot(92, 92, 0, 1, ProliferationMode.None));
var report = new FactoryBlackBoxAnalyzer(catalog).Analyze(request);
Check(report.MaterialComplete && report.PowerComplete, "ideal renewable generation complete");
Equal(12600, report.Power.GenerationWatts, "wind solar geothermal watts distinguished");
Check(report.MaterialComplete && report.PowerComplete && report.Diagnostics.Count == 0,
"ideal renewable generation complete");
Equal(16200, report.Power.GenerationWatts, "wind solar geothermal use ideal rated generation");
Equal(0, report.Power.ConsumptionWatts, "renewable generation is not demand");
Check(report.ItemFlows.Count == 0, "renewable generators do not invent products");
request.Buildings[2] = new ProductionBuildingSnapshot(92, 92, 0, 1, ProliferationMode.None);
var incomplete = new FactoryBlackBoxAnalyzer(catalog).Analyze(request);
Check(incomplete.MaterialComplete && !incomplete.PowerComplete && incomplete.Power == null,
"unknown ground heat leaves only power incomplete");
Check(incomplete.Diagnostics.Single().Code == ProductionDiagnosticCode.MissingOperatingParameter,
"missing geothermal strength diagnosed");
}
private static void MiningResources()
@@ -492,12 +550,27 @@ internal static class Program
var analyzer = new FactoryBlackBoxAnalyzer(catalog);
var report = analyzer.Analyze(request);
Check(report.MaterialComplete && report.PowerComplete, "native vein oil water mining complete");
Equal(8, report.ItemFlows[1].GrossProduction, "vein coverage multiplies native rate");
Equal(5, report.ItemFlows[2].GrossProduction, "oil resource factor retained");
Equal(2, report.ItemFlows[3].GrossProduction, "water pump uses planet resource type");
Equal(480, report.ItemFlows[1].GrossProduction, "vein coverage multiplies native rate");
Equal(300, report.ItemFlows[2].GrossProduction, "oil resource factor retained");
Equal(120, report.ItemFlows[3].GrossProduction, "water pump uses planet resource type");
Equal(3600, report.Power.ConsumptionWatts, "each mining facility draws working power");
Check(!report.ItemFlows.ContainsKey(0), "miners never invent zero-ID resources");
request.Buildings[0] = new ProductionBuildingSnapshot(20, 20, 0, 1, ProliferationMode.None,
operatingParameters: new Dictionary<string, double>
{
["ResourceItemId"] = 1,
["VeinCount"] = 4,
["MiningSpeedMultiplier"] = 2,
["MachineSpeedFactor"] = 1.5,
["SpeedDamper"] = 0.02
});
var fast = analyzer.Analyze(request);
Equal(720, fast.ItemFlows[1].GrossProduction,
"machine speed scales output while a transient output damper is ignored at full load");
Equal(1200 * 2.25 + 1400 + 1000, fast.Power.ConsumptionWatts,
"miner power follows the square of machine speed");
request.Buildings[0] = new ProductionBuildingSnapshot(20, 20, 0, 1, ProliferationMode.None,
operatingParameters: new Dictionary<string, double>
{
@@ -573,16 +646,32 @@ internal static class Program
"explicit unsupported fuel productivity mode is rejected");
request.ProliferationEnabled = false;
var starSettings = new Dictionary<string, double>
{
["FuelItemId"] = 1804,
["Mode0"] = 1,
["BoostEnabled"] = 1
};
request.Buildings[0] = new ProductionBuildingSnapshot(31, 31, 0, 1, ProliferationMode.None,
operatingParameters: new Dictionary<string, double>
{
["FuelItemId"] = 1804,
["Mode0"] = 1
});
operatingParameters: starSettings);
var star = analyzer.Analyze(request);
Equal(2000000, star.Power.GenerationWatts, "star boost and special fuel native multiplier");
Equal(60, star.ItemFlows[1804].GrossConsumption,
"star generation accounts for boosted fuel burn");
starSettings["BoostEnabled"] = 0;
request.Buildings[0] = new ProductionBuildingSnapshot(31, 31, 0, 1, ProliferationMode.None,
operatingParameters: starSettings);
Equal(20000, analyzer.Analyze(request).Power.GenerationWatts,
"a stored star boost flag outside sandbox mode keeps only the special fuel multiplier");
starSettings.Remove("BoostEnabled");
request.Buildings[0] = new ProductionBuildingSnapshot(31, 31, 0, 1, ProliferationMode.None,
operatingParameters: starSettings);
var unknownBoost = analyzer.Analyze(request);
Check(!unknownBoost.PowerComplete && unknownBoost.Diagnostics.Single().Code ==
ProductionDiagnosticCode.MissingOperatingParameter,
"a boosted star blueprint needs the sandbox boost state");
}
private static void BlackBoxBalancesAndThreshold()
@@ -595,10 +684,10 @@ internal static class Program
};
var recipes = new[]
{
new ProductionRecipe(401, ProductionRecipeCategory.Assemble, 60, true,
new ProductionRecipe(401, ProductionRecipeCategory.Assemble, 3600, true,
new[] { new KeyValuePair<int, double>(1, 1) },
new[] { new KeyValuePair<int, double>(2, 60) }),
new ProductionRecipe(402, ProductionRecipeCategory.Assemble, 60, true,
new ProductionRecipe(402, ProductionRecipeCategory.Assemble, 3600, true,
new[] { new KeyValuePair<int, double>(2, 150) },
new[] { new KeyValuePair<int, double>(3, 1) })
};
@@ -872,6 +961,16 @@ internal static class Program
Equal(1, planned.Groups.Single().EquivalentBuildings.Value,
"photon plan uses equivalent receivers for peak and Dyson demand");
var unbuilt = new ProductionPlanRequest();
unbuilt.Targets.Add(new ProductionTarget(456, 24));
var photonsOnly = new ProductionPlanner(catalog).Calculate(unbuilt);
Check(photonsOnly.MaterialComplete && !photonsOnly.PowerComplete && photonsOnly.Power == null,
"photons without a selected receiver keep material flows and leave power incomplete");
Equal(24, photonsOnly.ItemFlows[456].GrossProduction, "receiver-independent photon output is planned");
unbuilt.OperatingParametersByRecipe[999] = new Dictionary<string, double> { ["LensItemId"] = 123 };
Check(new ProductionPlanner(catalog).Calculate(unbuilt).Diagnostics.Single().Code ==
ProductionDiagnosticCode.MissingBuilding, "lens wear without a selected receiver is not invented");
parameters.Remove("SolarEnergyLossRate");
request.Buildings[0] = new ProductionBuildingSnapshot(1, 51, 0, 1,
ProliferationMode.None, operatingParameters: parameters);
@@ -923,7 +1022,7 @@ internal static class Program
var sprayed = analyzer.Analyze(request);
Equal(240, sprayed.ItemFlows[101].GrossConsumption, "ammo speedup shortens both ejector phases");
Equal(60, sprayed.ItemFlows[102].GrossConsumption, "ammo speedup shortens both silo phases");
Equal(4800, sprayed.Power.ConsumptionWatts, "launchers do not use manufacturing power multiplier");
Equal(12000, sprayed.Power.ConsumptionWatts, "ammo proliferation raises native launcher power");
ejectorSettings["Mode1"] = 1;
ejectorSettings["BoostEnabled"] = 1;
@@ -980,11 +1079,11 @@ internal static class Program
var analyzer = new FactoryBlackBoxAnalyzer(catalog);
var report = analyzer.Analyze(request);
Check(report.MaterialComplete && report.PowerComplete, "gas collection uses captured planet resources");
Equal(4.5, report.ItemFlows[111].GrossProduction,
"native gas self-power recovery and mining technology scale first resource");
Equal(1.8, report.ItemFlows[112].GrossProduction,
Equal(270, report.ItemFlows[111].GrossProduction,
"native gas self-power recovery and mining technology scale per-second speed to a minute");
Equal(108, report.ItemFlows[112].GrossProduction,
"second gas resource is not lost by a single-output adapter");
Equal(1000, report.Power.ConsumptionWatts, "gas collection includes native energy demand");
Equal(0, report.Power.ConsumptionWatts, "collector working energy is recovered gas, not grid demand");
settings.Remove("GasSpeedPerSecond1");
request.Buildings[0] = new ProductionBuildingSnapshot(1, 81, 0, 1,
@@ -1129,10 +1228,11 @@ internal static class Program
new[] { 1.0, 1.3, 1.7, 2.1, 2.5 });
}
// Synthetic recipes last 3600 ticks, so a unit-speed building completes one cycle per minute.
private static ProductionRecipe Recipe(int id, (int id, double count)[] input,
(int id, double count)[] output, bool productive = true)
{
return new ProductionRecipe(id, ProductionRecipeCategory.Assemble, 60, productive,
return new ProductionRecipe(id, ProductionRecipeCategory.Assemble, 3600, productive,
input.Select(flow => new KeyValuePair<int, double>(flow.id, flow.count)),
output.Select(flow => new KeyValuePair<int, double>(flow.id, flow.count)));
}