feat(production): include logistics charging in black-box power

This commit is contained in:
soarqin committed 2026-10-25 14:23:52 +08:00
1 parent b1b6785572
commit cc36edecc7
7 files changed
+164 -2

No files matched your search

+1
View File
@@ -30,6 +30,7 @@
## Architecture
- Fixed-building UXAssist power reports include each selected logistics station, distributor, or battle base at its captured configured charging maximum in watts, not its transient draw. Keep charging power separate from accumulator exchange and do not double-count advanced miners or gas collectors. Blueprint and prebuild capture use native stored settings or prefab defaults when no charging setting is applied.
- 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.
@@ -81,6 +81,16 @@ public static class BlueprintSelectionReader
var operation = new Dictionary<string, double>();
var speedFactor = GetLiveSpeed(factory, objectId, parameters.type, operation);
AddSettings(parameters, operation);
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 (operation.ContainsKey("ResearchMode")) CaptureResearchSettings(factory, operation);
switch (building.Kind)
{
@@ -163,6 +173,8 @@ public static class BlueprintSelectionReader
});
var operation = new Dictionary<string, double>();
AddSettings(parameters, operation);
if (building.Kind == ProductionBuildingKind.Logistics)
CaptureStoredChargePower(building, parameters, blueprint.parameters, operation);
ApplySupplied(context?.OperatingParametersByIndex, blueprint.index, operation);
snapshots.Add(CreateSnapshot(catalog, building, 0, parameters, parameters.recipeId, null, operation,
diagnostics));
@@ -197,6 +209,45 @@ public static class BlueprintSelectionReader
foreach (var entry in settings) operation[entry.Key] = entry.Value;
}
private static void CaptureLiveChargePower(PlanetFactory factory, int objectId,
IDictionary<string, double> operation)
{
var powerSystem = factory.powerSystem;
var pool = powerSystem?.consumerPool;
var consumerId = factory.entityPool[objectId].powerConId;
if (pool == null || consumerId <= 0 || consumerId >= powerSystem.consumerCursor ||
consumerId >= pool.Length || pool[consumerId].id != consumerId ||
pool[consumerId].entityId != objectId) return;
operation["ChargePowerWatts"] = pool[consumerId].workEnergyPerTick * ProductionUnits.TicksPerSecond;
}
private static void CaptureStoredChargePower(ProductionBuilding building, BuildingParameters parameters,
int[] storedParameters, IDictionary<string, double> operation)
{
var watts = building.WorkingPowerWatts;
switch (parameters.type)
{
case BuildingType.Station:
if (storedParameters != null &&
storedParameters.Length >= BuildingParameters.kStationParamsLength && storedParameters[320] > 0)
watts = storedParameters[320] * ProductionUnits.TicksPerSecond;
break;
case BuildingType.Dispenser:
if (storedParameters != null && storedParameters.Length >= BuildingParameters.kAddonParamsLength)
watts = storedParameters[2] * ProductionUnits.TicksPerSecond;
break;
case BuildingType.BattleBase:
var index = parameters.mode1 == 0 ? 10 : 70;
if (storedParameters != null && storedParameters.Length > index)
watts = storedParameters[index] * ProductionUnits.TicksPerSecond;
break;
default:
return;
}
operation["ChargePowerWatts"] = watts;
}
private static ProductionBuildingSnapshot CreateSnapshot(ProductionCatalog catalog, ProductionBuilding building,
int objectId, BuildingParameters parameters, int recipeId, double? speedFactor,
Dictionary<string, double> operation, ICollection<ProductionDiagnostic> diagnostics)
@@ -117,6 +117,29 @@ public sealed class FactoryBlackBoxAnalyzer
continue;
}
if (snapshot.RecipeId == 0 && building.Kind == ProductionBuildingKind.Logistics)
{
double? logisticsWatts = null;
if (!snapshot.OperatingParameters.TryGetValue("ChargePowerWatts", out var chargePowerWatts))
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))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected logistics charging power must be finite and nonnegative.",
buildingItemId: snapshot.BuildingItemId));
else
logisticsWatts = chargePowerWatts * snapshot.Count;
if (logisticsWatts.HasValue) consumptionWatts += logisticsWatts.Value;
else powerComplete = false;
groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count,
logisticsWatts, logisticsWatts, Array.Empty<KeyValuePair<int, double>>(),
Array.Empty<KeyValuePair<int, double>>()));
continue;
}
if (snapshot.RecipeId == 0 && (building.Kind == ProductionBuildingKind.Ordinary ||
building.Kind == ProductionBuildingKind.Auxiliary))
{
@@ -190,6 +190,8 @@ public static class ProductionCatalogReader
if (prefab.isPowerGen)
return prefab.photovoltaic || prefab.windForcedPower || prefab.geothermal
? ProductionBuildingKind.RenewableGenerator : ProductionBuildingKind.FuelGenerator;
if (prefab.isStation || prefab.isDispenser || prefab.isBattleBase)
return ProductionBuildingKind.Logistics;
if (prefab.isPowerConsumer && !prefab.isStation && !prefab.isDispenser)
return ProductionBuildingKind.Auxiliary;
return ProductionBuildingKind.Ordinary;
+2 -1
View File
@@ -46,7 +46,8 @@ public enum ProductionBuildingKind
RenewableGenerator,
Ejector,
Silo,
Auxiliary
Auxiliary,
Logistics
}
public enum RenewablePowerSource
+4 -1
View File
@@ -52,6 +52,8 @@ 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 makes the power result unknown without discarding material results. 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.
## Special-process settings
All parameters below are numbers in a building snapshot's `OperatingParameters`. A live capture supplies available values from the selected factory; either capture path may need supplementary context. Do not infer missing resource coverage, inventory contents, research technology, orbit readiness, or sandbox settings. Planner callers supply recipe-specific values through `OperatingParametersByRecipe`, including for synthetic recipes.
@@ -70,7 +72,7 @@ All parameters below are numbers in a building snapshot's `OperatingParameters`.
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.
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. Planner power excludes logistics charging, transport, and mecha charging; the fixed-building report includes charging limits for selected logistics facilities but does not simulate transport energy. Auxiliary power must come from an explicitly supplied list.
## CheatEnabler migration
@@ -95,6 +97,7 @@ Use a test game for the following manual checks. Compare full-load rates only wi
- Check ordinary production and mining against native cycle periods and the per-minute UI. A 60-tick recipe at unit speed completes 60 cycles per minute before proliferation.
- Capture assemblers in acceleration and extra-products modes, nonproductive recipes, prebuilds, and stacked labs. Confirm that each captured mode and building count matches the selection.
- Select logistics stations, distributors, and battle bases with different charge-power settings. Compare live, prebuild, and blueprint maximum demand with their native charging sliders; confirm that advanced miners and gas collectors do not gain an additional charging term.
- 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.
+81
View File
@@ -22,6 +22,7 @@ internal static class Program
ProliferatorGradesAndFinishedSpraying();
BlackBoxBalancesAndThreshold();
BlackBoxMixedModesAndDeficits();
LogisticsChargingPower();
FractionationFlow();
AccumulatorRoundTrip();
RenewableGeneration();
@@ -789,6 +790,86 @@ internal static class Program
"disabling proliferation does not throttle a shorted downstream recipe");
}
private static void LogisticsChargingPower()
{
var catalog = new ProductionCatalog(new[]
{
new ProductionItem(1, 0, true, false, 0, 0),
new ProductionItem(2, 101, false, false, 0, 0)
}, new[] { Recipe(101, new[] { (1, 1.0) }, new[] { (2, 1.0) }) }, new[]
{
new ProductionBuilding(10, ProductionRecipeCategory.Assemble, 1, 1000, 100),
new ProductionBuilding(20, ProductionRecipeCategory.None, 0, 3000000, 100,
ProductionBuildingKind.Logistics),
new ProductionBuilding(21, ProductionRecipeCategory.None, 0, 15000000, 100,
ProductionBuildingKind.Logistics),
new ProductionBuilding(22, ProductionRecipeCategory.None, 0, 300000, 100,
ProductionBuildingKind.Logistics),
new ProductionBuilding(23, ProductionRecipeCategory.None, 0, 600000, 100,
ProductionBuildingKind.Logistics)
}, new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 });
var request = new FactoryBlackBoxRequest();
request.Buildings.Add(new ProductionBuildingSnapshot(1, 10, 101, 1, ProliferationMode.None));
request.Buildings.Add(new ProductionBuildingSnapshot(2, 20, 0, 2, ProliferationMode.None,
operatingParameters: new Dictionary<string, double> { ["ChargePowerWatts"] = 3000000 }));
request.Buildings.Add(new ProductionBuildingSnapshot(3, 20, 0, 1, ProliferationMode.None,
operatingParameters: new Dictionary<string, double> { ["ChargePowerWatts"] = 4000000 }));
request.Buildings.Add(new ProductionBuildingSnapshot(4, 21, 0, 1, ProliferationMode.None,
operatingParameters: new Dictionary<string, double> { ["ChargePowerWatts"] = 15000000 }));
request.Buildings.Add(new ProductionBuildingSnapshot(5, 22, 0, 1, ProliferationMode.None,
operatingParameters: new Dictionary<string, double> { ["ChargePowerWatts"] = 300000 }));
request.Buildings.Add(new ProductionBuildingSnapshot(6, 23, 0, 1, ProliferationMode.None,
operatingParameters: new Dictionary<string, double> { ["ChargePowerWatts"] = 600000 }));
var analyzer = new FactoryBlackBoxAnalyzer(catalog);
var report = analyzer.Analyze(request);
Check(report.MaterialComplete && report.PowerComplete,
"selected logistics chargers have complete power and no material demand");
Equal(25901000, report.Power.ConsumptionWatts,
"theoretical grid demand sums each selected facility's configured charging limit");
Equal(25901000, report.Power.PeakConsumptionWatts,
"selected facilities use the same peak and full-load charging power");
Equal(6000000, report.Groups[1].ConsumptionWatts.Value,
"multiple identical chargers multiply their configured charging power");
Equal(4000000, report.Groups[2].ConsumptionWatts.Value,
"separately configured chargers of the same type stay independent");
Equal(1, report.ItemFlows[2].GrossProduction,
"logistics charging does not change manufacturing capacity");
Equal(0, report.Power.AccumulatorChargingWatts,
"logistics charging is not accumulator exchange");
request.Buildings[1] = new ProductionBuildingSnapshot(2, 20, 0, 2, ProliferationMode.None);
var missing = analyzer.Analyze(request);
Check(missing.MaterialComplete && !missing.PowerComplete && missing.Power == null &&
missing.Groups[1].ConsumptionWatts == null &&
missing.Diagnostics.Any(diagnostic =>
diagnostic.Code == ProductionDiagnosticCode.MissingOperatingParameter &&
diagnostic.BuildingItemId == 20),
"missing logistics settings invalidate power without losing material results");
Equal(1, missing.ItemFlows[2].GrossProduction,
"manufacturing still reports materials with an unknown charger");
foreach (var invalidWatts in new[] { -1.0, double.NaN, double.PositiveInfinity })
{
request.Buildings[1] = new ProductionBuildingSnapshot(2, 20, 0, 2, ProliferationMode.None,
operatingParameters: new Dictionary<string, double> { ["ChargePowerWatts"] = invalidWatts });
var invalid = analyzer.Analyze(request);
Check(invalid.MaterialComplete && !invalid.PowerComplete && invalid.Power == null &&
invalid.Diagnostics.Any(diagnostic =>
diagnostic.Code == ProductionDiagnosticCode.InvalidRequest &&
diagnostic.BuildingItemId == 20),
"invalid logistics charge power is diagnosed independently of material flows");
}
request.Buildings[1] = new ProductionBuildingSnapshot(2, 20, 0, 2, ProliferationMode.None,
operatingParameters: new Dictionary<string, double> { ["ChargePowerWatts"] = 3000000 });
request.Buildings.Add(request.Buildings[1]);
var duplicate = analyzer.Analyze(request);
Equal(25901000, duplicate.Power.ConsumptionWatts,
"repeated object selections do not double-count logistics charging");
Check(duplicate.Diagnostics.Any(diagnostic => diagnostic.Code == ProductionDiagnosticCode.DuplicateSelection),
"repeated logistics facility selection is diagnosed");
}
private static void BeltSignalStatistics()
{
var report = new ProductionPlanner(Catalog()).Calculate(Request((3, 1)));