Author SHA1 Message Date
soarqin c7fcf31c30 fix(cheatenabler): require UXAssist 1.6.3 before loading
Align the runtime and package minimum with the official release that provides the shared production API. Keep official UXAssist 1.6.3 supported and document the dependency in both languages.

Assisted-by: Cindy (https://cindy.app)
2026-11-05 21:34:35 +08:00
soarqin 64a23e9772 fix(cheatenabler): restore mecha and fleet invincibility
Patch the native mecha damage and shield consumers so an inlined Player.invincible getter cannot bypass protection. Replace the fleet damage matcher with target-type prefixes to cover both space paths.

Synchronize the English and Chinese documentation without changing version 2.4.8.
2026-11-04 20:46:44 +08:00
soarqin 2eae91fa18 fix(uxassist): restore tech-tree arrows across save changes
Grow missing connection arrows when Peace-mode filtering is restored, preserving existing controls and native connection updates. Record the fix in UXAssist 1.7.0 and synchronize the manifest and bilingual documentation.
2026-11-02 21:02:08 +08:00
soarqin d728e8b4ae fix(uxassist): preserve blueprint layout and add production bases 2026-11-02 21:00:52 +08:00
soarqin 8fbb244ba2 chore: release dustbin v1.5.0 2026-10-31 16:21:03 +08:00
soarqin d68329ff9a fix: ZipMod target 2026-10-31 15:45:55 +08:00
soarqin 6263775dc1 fix(uxassist): limit quick miner diagnostics to Debug builds 2026-10-31 15:35:59 +08:00
soarqin 3580e9623f chore: release CheatEnabler 2.4.8 and UXAssist 1.6.3 2026-10-31 15:29:47 +08:00
soarqin 35f5cfcdd8 feat(uxassist): abbreviate exact blueprint material rates
Use the largest K/M/G suffix that preserves existing display precision with at most one decimal place, falling back to ordinary numbers otherwise.

Cover all material categories and formatting boundaries, and update English and Chinese documentation.
2026-10-31 13:58:54 +08:00
soarqin 0cd6008673 fix(uxassist): keep quick miners within the selected vein group
Restrict layout coverage and miner vein lists to the selected group so nearby deposits of the same resource cannot attract placement. Preserve neighboring vein collision checks and enforce the three-node minimum after planned burials.

Tag debug snapshots with target-group semantics, validate group membership during replay, and synchronize the English and Chinese documentation.
2026-10-31 13:58:14 +08:00
soarqin 5f9c6e05cb fix(cheatenabler): defer instant construction until prologue ends 2026-10-26 23:20:26 +08:00
soarqin ca884fe6af fix(uxassist): name item ID constants after their items
The game-constant centralization attached wrong names to many item IDs, such
as Steel for Titanium Alloy (1107) and HydrogenFuelRod for the Electromagnetic
Matrix (6001). Every remaining usage relies on the IDs, which match the items
in the belt-signal proliferation tips, the matrix metadata types, and the Dark
Fog buy-out definitions. Rename the constants after their actual items and
current Dark Fog item names, and remove the mislabeled constants that only the
retired proliferator source table used. Item groups and compiled values are
unchanged.
2026-10-25 22:04:50 +08:00
soarqin 3ca7b62ec6 fix(cheatenabler): track signal belts by their owning planet
The belt hooks keyed signal belts by the local planet's factory index. Battlefield
Analysis Base drones can finish belts on other planets and Dark Fog attacks can
destroy them there, so such changes started or stopped generation on a belt of
the current planet, or were dropped while in space, and a destroyed remote belt
kept its signal entry for any belt later built in its place. Use the factory that
owns the CargoTraffic instead.
2026-10-25 22:01:05 +08:00
soarqin a6225cf750 fix(cheatenabler): keep the rare-recipe preference for belt statistics
The planner migration switched belt-signal upstream statistics to each item's
standard recipe. Capture the native RecipeProto.Explicit flag in the production
catalog and let the belt preset prefer explicit recipes again, which include the
rare-resource alternatives such as Graphene from Fire Ice and Diamond from
Kimberlite Ore. As before, explicit recipes that consume their own product
(X-ray Cracking and Reforming Refine) never supply an item, and natural items
stay raw. Proliferation modes now follow the selected recipe.
2026-10-25 22:01:05 +08:00
soarqin 6d86e1f5dd docs: consolidate production documentation
Move the blueprint description notes to the unreleased 1.6.3 entry and limit
them to user-visible behavior, list the feature in the README, condense the
production guidance in AGENTS.md to durable rules, and remove the completed
planning documents that duplicated the architecture reference.
2026-10-25 22:01:05 +08:00
soarqin 79c736d90c fix(cheatenabler): plan belt-signal statistics outside the logic tick
Signals can change inside the logic tick when drones finish a blueprint, so a
cache miss now queues the belt and the production planner runs from the next
frame update; the tick only applies cached rates. Document the recipe-based
upstream statistics in the unreleased changelog.
2026-10-25 22:01:05 +08:00
soarqin f0773ffb9b fix(production): correct blueprint power and planner edge cases
Read the Advanced Mining Machine speed stored with station settings in prebuild
and blueprint captures, and count charging power nodes such as Satellite
Substations at their idle draw. Skip recipes that consume their own product when
choosing an item's default recipe, so Refined Oil uses Plasma Refining instead
of Reforming Refine.

Run each planner recipe in one proliferation mode and report conflicting
explicit modes, keep material flows for recipe types the catalog does not know,
and attribute receiver warnings to their recipe. Compare simplex ratio ties
relatively and drive out near-zero artificials without amplifying residuals.
Bound the steady-state reduction so lossless cycles cannot stall blueprint
descriptions, and choose power units after rounding.

Remove redundant code: share the numeric and flow helpers, and drop the unused
IsExcessIntermediate threshold, legacy constructor and Capture overloads, the
multi-field updater, and the unused proliferator source table.
2026-10-25 22:01:05 +08:00
soarqin 6345562c66 build: exclude nested test artifacts from parent projects 2026-10-25 22:01:05 +08:00
soarqin e2b8433252 feat(uxassist): generate blueprint production descriptions
Add native blueprint description generation with proliferation controls, separate power categories, and steady-state material and research reporting.

Distinguish necessary coproducts from overbuild and fractional headroom, with regression checks and updated architecture documentation.

Validation: 464 ProductionCheck checks and Release builds of UXAssist, CheatEnabler, and UniverseGenTweaks.
2026-10-25 22:01:05 +08:00
soarqin cada02fbf4 feat(production): include logistics charging in black-box power 2026-10-25 22:01:05 +08:00
soarqin 51e90a8e1d 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.
2026-10-25 22:01:05 +08:00
soarqin 97f032a5af feat(production): add shared planner and factory analysis
Add Proto-backed planning, fixed-building analysis, blueprint capture, and facility-specific material and power calculations.

Migrate belt-signal upstream statistics, include review fixes, and document the architecture and manual validation workflow.
2026-10-25 22:01:05 +08:00
59 changed files with 8333 additions and 439 deletions

No files matched your search

+3 -1
View File
@@ -20,7 +20,7 @@
## Build ## Build
- `Directory.Build.props` supplies common frameworks, BepInEx packages, game references, warning policy, and the `UpdateGameDlls` dependency. `Directory.Build.targets` defines `ZipMod` and `CopyToParentPackage`. - `Directory.Build.props` supplies common frameworks, BepInEx packages, game references, warning policy, and the `UpdateGameDlls` dependency. `Directory.Build.targets` defines `ZipMod` and `CopyToParentPackage`. Exclude nested test-tool `bin` and `obj` artifacts from parent-mod item globs, including explicit `None` includes, while keeping test sources visible.
- Normal validation: `dotnet build <project>/<project>.csproj -c Release --no-restore`. If NuGet assets are missing, run `dotnet restore <project>/<project>.csproj` before retrying the build. - Normal validation: `dotnet build <project>/<project>.csproj -c Release --no-restore`. If NuGet assets are missing, run `dotnet restore <project>/<project>.csproj` before retrying the build.
- Keep temporary verification projects under the mod's excluded root `obj/` directory. Remove abandoned generated outputs when their source project is gone so the SDK source glob cannot compile them into the mod. - Keep temporary verification projects under the mod's excluded root `obj/` directory. Remove abandoned generated outputs when their source project is gone so the SDK source glob cannot compile them into the mod.
- Refresh game references explicitly with `dotnet build UpdateGameDlls/UpdateGameDlls.csproj`; the script publicizes installed DLLs in staging and compares generated content hashes so checkout timestamps cannot hide game updates. Missing DSP or the publicizer is a warning, not a build failure. If `assembly-publicizer` requires an unavailable .NET runtime, retry with process-local `DOTNET_ROLL_FORWARD=Major` rather than changing global runtime settings. Verify discovery warnings against the actual configured library directories and original managed DLLs; absence from the VDF `apps` list alone does not establish that DSP is uninstalled. - Refresh game references explicitly with `dotnet build UpdateGameDlls/UpdateGameDlls.csproj`; the script publicizes installed DLLs in staging and compares generated content hashes so checkout timestamps cannot hide game updates. Missing DSP or the publicizer is a warning, not a build failure. If `assembly-publicizer` requires an unavailable .NET runtime, retry with process-local `DOTNET_ROLL_FORWARD=Major` rather than changing global runtime settings. Verify discovery warnings against the actual configured library directories and original managed DLLs; absence from the VDF `apps` list alone does not establish that DSP is uninstalled.
@@ -30,6 +30,8 @@
## Architecture ## Architecture
- UXAssist production calculations (catalog, planner, fixed-building analyzer, blueprint capture, and blueprint descriptions) are described in [production architecture](UXAssist/docs/ProductionArchitecture.md). Capture immutable Proto, PrefabDesc, and Cargo snapshots on the game thread and keep the calculation core pure-managed; report unknown material and power results independently instead of as zero. Verify special-building rules against the original DLL and update `UXAssist/tools/ProductionCheck` expectations with any rule change. Synthetic recipe IDs are calculation-only and must never reach native recipe lookups or setters.
- CheatEnabler belt-signal upstream statistics use cached `ProductionPlanner` reports; never run the solver in the logic tick, and missing production 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. - 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.
- Tech downgrades must validate the full dependency cascade and capacity reductions before changing game state. Recompute non-invertible bonuses from native defaults and surviving levels; replaying unrelated unlock side effects can corrupt inventory geometry and station limits. - Tech downgrades must validate the full dependency cascade and capacity reductions before changing game state. Recompute non-invertible bonuses from native defaults and surviving levels; replaying unrelated unlock side effects can corrupt inventory geometry and station limits.
- Custom critical-warning text must participate in both `WarningSystem.hasCriticalWarning` and `WarningSystem.UpdateCriticalWarningText`; preserve native warnings and use one shared display priority. - Custom critical-warning text must participate in both `WarningSystem.hasCriticalWarning` and `WarningSystem.UpdateCriticalWarningText`; preserve native warnings and use one shared display priority.
+14 -2
View File
@@ -3,7 +3,13 @@
## Changlog ## Changlog
* 2.4.8 - Unreleased * 2.4.8
* Require UXAssist 1.6.3 or later for the shared production API. Older versions are rejected before initialization instead of failing while loading belt-signal features.
* `Mecha and Drones/Fleets invincible`: Fix mecha HP and energy shield protection failing when enabled after taking damage, and restore protection for space fleets.
* `Finish build immediately`: Fix possible errors when starting a new game. Construction begins after the opening cutscene ends or is skipped.
* `Belt signal item generation`:
* Improve raw-material, intermediate, by-product and proliferator statistics using current recipes, with production and consumption counted separately. Incomplete recipe data only pauses the affected upstream statistics; item generation continues.
* Fix signal belts built or destroyed on other planets, such as by Battlefield Analysis Base drones or Dark Fog attacks, affecting belts on the current planet. Destroyed signal belts no longer cause replacement belts to keep generating items.
* 2.4.7 * 2.4.7
* `Dev Shortcuts`: Work immediately when enabled after loading a save, and process each key press once per frame at accelerated game speeds. * `Dev Shortcuts`: Work immediately when enabled after loading a save, and process each key press once per frame at accelerated game speeds.
* Extend `Unlock Tech with Key-Modifiers` with a downgrade mode. * Extend `Unlock Tech with Key-Modifiers` with a downgrade mode.
@@ -202,7 +208,13 @@
## 更新日志 ## 更新日志
* 2.4.8 - Unreleased * 2.4.8
* 需要 UXAssist 1.6.3 或更高版本提供共享生产计算 API。旧版本会在初始化前被拒绝加载,避免加载传送带信号功能时出错。
* `机甲和战斗无人机无敌`:修复受伤后启用时机甲耐久度和能量护盾保护可能失效的问题,并恢复太空编队的无敌保护。
* `建造秒完成`:修复开始新游戏时可能报错的问题。建造会在开场动画播放结束或跳过后开始。
* `传送带信号物品生成`:
* 按当前配方完善原料、中间产物、副产物和增产剂的统计,分别记录生产和消耗。配方数据不完整时,仅暂停受影响物品的上游统计,物品仍会正常生成。
* 修复其他星球上的信号传送带在建造或被摧毁时,错误影响当前星球上传送带的问题,例如战场分析基站无人机建造或黑雾摧毁传送带。被摧毁的信号传送带也不会再让之后替换它的传送带继续生成物品。
* 2.4.7 * 2.4.7
* `开发模式快捷键`:修复载入存档后启用时不生效的问题;加速游戏时每次按键仍只执行一次。 * `开发模式快捷键`:修复载入存档后启用时不生效的问题;加速游戏时每次按键仍只执行一次。
* `使用组合键点击解锁科技` 新增降级模式。 * `使用组合键点击解锁科技` 新增降级模式。
+1 -1
View File
@@ -10,7 +10,7 @@ using UXAssist.Common.ModFeatures;
namespace CheatEnabler; namespace CheatEnabler;
[BepInPlugin(PluginInfo.PLUGIN_GUID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)] [BepInPlugin(PluginInfo.PLUGIN_GUID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)]
[BepInDependency(UXAssist.PluginInfo.PLUGIN_GUID)] [BepInDependency(UXAssist.PluginInfo.PLUGIN_GUID, "1.6.3")]
public class CheatEnabler : BaseUnityPlugin public class CheatEnabler : BaseUnityPlugin
{ {
public new static readonly BepInEx.Logging.ManualLogSource Logger = public new static readonly BepInEx.Logging.ManualLogSource Logger =
+10 -10
View File
@@ -81,10 +81,10 @@ public static class PlayerFunctions
var propertySystem = DSPGame.propertySystem; var propertySystem = DSPGame.propertySystem;
if (propertySystem == null) return; if (propertySystem == null) return;
PurgePropertySystem(propertySystem); PurgePropertySystem(propertySystem);
var itemCnt = new int[ItemIds.Metaverse - ItemIds.HydrogenFuelRod + 1]; var itemCnt = new int[ItemIds.UniverseMatrix - ItemIds.ElectromagneticMatrix + 1];
foreach (var cons in propertySystem.propertyDatas.SelectMany(data => data.totalConsumption.Where(cons => cons.id is >= ItemIds.HydrogenFuelRod and <= ItemIds.Metaverse))) foreach (var cons in propertySystem.propertyDatas.SelectMany(data => data.totalConsumption.Where(cons => cons.id is >= ItemIds.ElectromagneticMatrix and <= ItemIds.UniverseMatrix)))
{ {
itemCnt[cons.id - ItemIds.HydrogenFuelRod] += cons.count; itemCnt[cons.id - ItemIds.ElectromagneticMatrix] += cons.count;
} }
if (itemCnt.All(cnt => cnt == 0)) if (itemCnt.All(cnt => cnt == 0))
@@ -97,7 +97,7 @@ public static class PlayerFunctions
{ {
if (itemCnt[i] > 0) if (itemCnt[i] > 0)
{ {
msg += $"\n {LDB.items.Select(i + ItemIds.HydrogenFuelRod).propertyName} x{itemCnt[i]}"; msg += $"\n {LDB.items.Select(i + ItemIds.ElectromagneticMatrix).propertyName} x{itemCnt[i]}";
} }
} }
UIMessageBox.Show(Localization.RemoveAllMetadataConsumptionRecords.Translate(), msg, Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () => UIMessageBox.Show(Localization.RemoveAllMetadataConsumptionRecords.Translate(), msg, Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () =>
@@ -121,7 +121,7 @@ public static class PlayerFunctions
var propertySystem = DSPGame.propertySystem; var propertySystem = DSPGame.propertySystem;
if (propertySystem == null) return; if (propertySystem == null) return;
PurgePropertySystem(propertySystem); PurgePropertySystem(propertySystem);
var itemCnt = new int[ItemIds.Metaverse - ItemIds.HydrogenFuelRod + 1]; var itemCnt = new int[ItemIds.UniverseMatrix - ItemIds.ElectromagneticMatrix + 1];
var seedKey = DSPGame.GameDesc.seedKey64; var seedKey = DSPGame.GameDesc.seedKey64;
var clusterPropertyData = propertySystem.propertyDatas.FirstOrDefault(cpd => cpd.seedKey == seedKey); var clusterPropertyData = propertySystem.propertyDatas.FirstOrDefault(cpd => cpd.seedKey == seedKey);
if (clusterPropertyData == null) if (clusterPropertyData == null)
@@ -130,9 +130,9 @@ public static class PlayerFunctions
return; return;
} }
var currentGamePropertyData = GameMain.data.history.propertyData; var currentGamePropertyData = GameMain.data.history.propertyData;
foreach (var cons in currentGamePropertyData.totalConsumption.Where(cons => cons.id is >= ItemIds.HydrogenFuelRod and <= ItemIds.Metaverse)) foreach (var cons in currentGamePropertyData.totalConsumption.Where(cons => cons.id is >= ItemIds.ElectromagneticMatrix and <= ItemIds.UniverseMatrix))
{ {
itemCnt[cons.id - ItemIds.HydrogenFuelRod] += cons.count; itemCnt[cons.id - ItemIds.ElectromagneticMatrix] += cons.count;
} }
if (itemCnt.All(cnt => cnt == 0)) if (itemCnt.All(cnt => cnt == 0))
@@ -145,7 +145,7 @@ public static class PlayerFunctions
{ {
if (itemCnt[i] > 0) if (itemCnt[i] > 0)
{ {
msg += $"\n {LDB.items.Select(i + ItemIds.HydrogenFuelRod).propertyName} x{itemCnt[i]}"; msg += $"\n {LDB.items.Select(i + ItemIds.ElectromagneticMatrix).propertyName} x{itemCnt[i]}";
} }
} }
UIMessageBox.Show(Localization.RemoveMetadataConsumptionRecordInCurrentGame.Translate(), msg, Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () => UIMessageBox.Show(Localization.RemoveMetadataConsumptionRecordInCurrentGame.Translate(), msg, Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () =>
@@ -154,8 +154,8 @@ public static class PlayerFunctions
{ {
if (clusterPropertyData.totalConsumption[i].count == 0) continue; if (clusterPropertyData.totalConsumption[i].count == 0) continue;
var id = clusterPropertyData.totalConsumption[i].id; var id = clusterPropertyData.totalConsumption[i].id;
if (id < ItemIds.HydrogenFuelRod || id > ItemIds.Metaverse) continue; if (id < ItemIds.ElectromagneticMatrix || id > ItemIds.UniverseMatrix) continue;
var currentGameCount = itemCnt[id - ItemIds.HydrogenFuelRod]; var currentGameCount = itemCnt[id - ItemIds.ElectromagneticMatrix];
if (currentGameCount == 0) continue; if (currentGameCount == 0) continue;
var totalCount = clusterPropertyData.totalConsumption[i].count; var totalCount = clusterPropertyData.totalConsumption[i].count;
clusterPropertyData.totalConsumption[i] = new IDCNT(id, totalCount > currentGameCount ? totalCount - currentGameCount : 0); clusterPropertyData.totalConsumption[i] = new IDCNT(id, totalCount > currentGameCount ? totalCount - currentGameCount : 0);
+29 -18
View File
@@ -1,10 +1,11 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Linq;
using System.Reflection.Emit; using System.Reflection.Emit;
using BepInEx.Configuration; using BepInEx.Configuration;
using HarmonyLib; using HarmonyLib;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.ModFeatures; using UXAssist.Common.ModFeatures;
using UXAssist.Common.Patching;
namespace CheatEnabler.Patches; namespace CheatEnabler.Patches;
@@ -48,27 +49,37 @@ public static class CombatPatch
); );
return matcher.InstructionEnumeration(); return matcher.InstructionEnumeration();
} }
// Harmony transpiler: SkillSystem_DamageObject_Transpiler // Harmony transpiler: Mecha_Invincible_Transpiler
// Target: SkillSystem.DamageGroundObjectByLocalCaster, SkillSystem.DamageGroundObjectByRemoteCaster, SkillSystem.DamageObject // Target: Mecha.TakeDamage, Mecha.EnergyShieldResist (both overloads)
// Fallback: None — patch will fail loudly if the target method body changes. // Fallback: Return original instructions if the invincibility check is not found.
[HarmonyTranspiler] [HarmonyTranspiler]
[HarmonyPatch(typeof(Mecha), nameof(Mecha.TakeDamage))]
[HarmonyPatch(typeof(Mecha), nameof(Mecha.EnergyShieldResist), [typeof(int)], [ArgumentType.Ref])]
[HarmonyPatch(typeof(Mecha), nameof(Mecha.EnergyShieldResist), [typeof(int), typeof(int)], [ArgumentType.Ref, ArgumentType.Out])]
private static IEnumerable<CodeInstruction> Mecha_Invincible_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
// Repatch the consumers too: an already inlined getter bypasses its own Harmony patch.
var original = instructions.ToList();
var matcher = new CodeMatcher(original, generator);
matcher.MatchForward(false, new CodeMatch(ci => ci.Calls(AccessTools.PropertyGetter(typeof(Player), nameof(Player.invincible)))));
if (matcher.IsInvalid) return matcher.Finish(original, CheatEnabler.Logger, nameof(Mecha_Invincible_Transpiler));
matcher.Set(OpCodes.Pop, null).Advance(1).Insert(new CodeInstruction(OpCodes.Ldc_I4_1));
return matcher.InstructionEnumeration();
}
[HarmonyPrefix]
[HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByLocalCaster))] [HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByLocalCaster))]
[HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByRemoteCaster))] [HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByRemoteCaster))]
[HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageObject))] private static void SkillSystem_DamageGroundObject_Prefix(ref int damage, ref SkillTargetLocal target)
private static IEnumerable<CodeInstruction> SkillSystem_DamageObject_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase __originalMethod)
{ {
var matcher = new CodeMatcher(instructions, generator); if (target.type == ETargetType.Craft) damage = 0;
matcher.MatchForward(false, }
new CodeMatch(ci => ci.IsLdarg()),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(SkillTargetLocal), nameof(SkillTargetLocal.type))), [HarmonyPrefix]
new CodeMatch(OpCodes.Ldc_I4_6), [HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageObject))]
new CodeMatch(ci => ci.opcode == OpCodes.Bne_Un || ci.opcode == OpCodes.Bne_Un_S) private static void SkillSystem_DamageObject_Prefix(ref int damage, ref SkillTarget target)
); {
matcher.Repeat(m => m.Advance(4).InsertAndAdvance( if (target.type == ETargetType.Craft) damage = 0;
new CodeInstruction(OpCodes.Ldc_I4_0),
new CodeInstruction(OpCodes.Starg_S, __originalMethod.Name == "DamageObject" ? 1 : 2)
));
return matcher.InstructionEnumeration();
} }
} }
+131 -263
View File
@@ -5,8 +5,8 @@ using HarmonyLib;
using UnityEngine; using UnityEngine;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.ModFeatures; using UXAssist.Common.ModFeatures;
using UXAssist.Production;
using GameLogicProc = UXAssist.Common.GameLogic; using GameLogicProc = UXAssist.Common.GameLogic;
using UXAssist.Common.GameConstants;
namespace CheatEnabler.Patches.Factory; namespace CheatEnabler.Patches.Factory;
@@ -18,15 +18,30 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
private static Dictionary<int, HashSet<long>> _portalTo; private static Dictionary<int, HashSet<long>> _portalTo;
private static int _signalBeltsCapacity; private static int _signalBeltsCapacity;
private static bool _initialized; private static bool _initialized;
private static ProductionCatalog _sourceCatalog;
private static ProductionItem _preferredProliferator;
private static readonly Dictionary<(int itemId, bool proliferated, bool sprayed),
IReadOnlyList<BeltSignalSourceRate>> SourceCache = [];
private static readonly HashSet<(int itemId, bool proliferated, bool sprayed)> FailedSources = [];
private static readonly HashSet<BeltSignal> PendingSources = [];
public static void Init() public static void Init()
{ {
GameLogicProc.OnGameEnd += ResetState; GameLogicProc.OnGameEnd += ResetState;
ProductionCatalogService.Changed += OnProductionCatalogChanged;
} }
public static void Uninit() public static void Uninit()
{ {
GameLogicProc.OnGameEnd -= ResetState; GameLogicProc.OnGameEnd -= ResetState;
ProductionCatalogService.Changed -= OnProductionCatalogChanged;
}
public static void OnUpdate()
{
if (PendingSources.Count == 0) return;
foreach (var beltSignal in PendingSources) TryApplySources(beltSignal, true);
PendingSources.Clear();
} }
private static void ResetState() private static void ResetState()
@@ -36,6 +51,16 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
_portalFrom = null; _portalFrom = null;
_portalTo = null; _portalTo = null;
_signalBeltsCapacity = 0; _signalBeltsCapacity = 0;
PendingSources.Clear();
ClearSourceCache();
}
private static void ClearSourceCache()
{
_sourceCatalog = null;
_preferredProliferator = null;
SourceCache.Clear();
FailedSources.Clear();
} }
private class BeltSignal private class BeltSignal
@@ -45,8 +70,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
public byte Stack; public byte Stack;
public byte Inc; public byte Inc;
public int Progress; public int Progress;
public (int itemId, float itemCount, bool isExtra)[] Sources; public BeltSignalSourceStats SourceStats;
public float[] SourceProgress;
} }
protected override void OnEnable() protected override void OnEnable()
@@ -61,6 +85,8 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
_initialized = false; _initialized = false;
_signalBelts = null; _signalBelts = null;
_signalBeltsCapacity = 0; _signalBeltsCapacity = 0;
PendingSources.Clear();
ClearSourceCache();
} }
internal static void OnAltFormatChanged() internal static void OnAltFormatChanged()
@@ -97,12 +123,38 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
} }
internal static void OnUseProliferatorChanged() internal static void OnUseProliferatorChanged()
{
ClearSourceCache();
RefreshSourceStats(true);
}
private static void OnProductionCatalogChanged()
{
ClearSourceCache();
RefreshSourceStats(false);
}
private static void RefreshSourceStats(bool resetGenerationProgress)
{ {
if (_signalBelts == null) return; if (_signalBelts == null) return;
if (ProductionCatalogService.Current == null)
{
foreach (var belts in _signalBelts)
{
if (belts == null) continue;
foreach (var belt in belts.Values)
{
belt.SourceStats = null;
if (resetGenerationProgress) belt.Progress = 0;
}
}
return;
}
var factories = GameMain.data?.factories; var factories = GameMain.data?.factories;
if (factories == null) return; if (factories == null) return;
var factoryCount = GameMain.data.factoryCount; var factoryCount = GameMain.data.factoryCount;
var altFormat = FactoryPatch.BeltSignalNumberAltFormat.Value;
for (var i = Math.Min(_signalBelts.Length, factoryCount) - 1; i >= 0; i--) for (var i = Math.Min(_signalBelts.Length, factoryCount) - 1; i >= 0; i--)
{ {
var factory = factories[i]; var factory = factories[i];
@@ -118,9 +170,8 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
ref var belt = ref cargoTraffic.beltPool[beltId]; ref var belt = ref cargoTraffic.beltPool[beltId];
if (belt.id != beltId) continue; if (belt.id != beltId) continue;
var signalBelt = pair.Value; var signalBelt = pair.Value;
signalBelt.Progress = 0; if (resetGenerationProgress) signalBelt.Progress = 0;
signalBelt.Sources = null; signalBelt.SourceStats = null;
signalBelt.SourceProgress = null;
AddSourcesToBeltSignal(signalBelt); AddSourcesToBeltSignal(signalBelt);
} }
} }
@@ -129,7 +180,6 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
private static void InitSignalBelts() private static void InitSignalBelts()
{ {
if (DSPGame.IsMenuDemo) return; if (DSPGame.IsMenuDemo) return;
InitItemSources();
_signalBelts = new Dictionary<int, BeltSignal>[64]; _signalBelts = new Dictionary<int, BeltSignal>[64];
_signalBeltsCapacity = 64; _signalBeltsCapacity = 64;
_portalFrom = []; _portalFrom = [];
@@ -231,14 +281,19 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
var signalBelts = GetOrCreateSignalBelts(factory); var signalBelts = GetOrCreateSignalBelts(factory);
if (signalBelts.TryGetValue(beltId, out var oldBeltSignal)) if (signalBelts.TryGetValue(beltId, out var oldBeltSignal))
{ {
if (oldBeltSignal.SignalId == signalId && oldBeltSignal.SpeedLimit == speedLimit && oldBeltSignal.Stack == stack && oldBeltSignal.Inc == inc) return; if (oldBeltSignal.SignalId == signalId && oldBeltSignal.SpeedLimit == speedLimit &&
oldBeltSignal.Stack == stack && oldBeltSignal.Inc == inc)
{
if (!ReferenceEquals(_sourceCatalog, ProductionCatalogService.Current))
AddSourcesToBeltSignal(oldBeltSignal);
return;
}
oldBeltSignal.SpeedLimit = speedLimit; oldBeltSignal.SpeedLimit = speedLimit;
oldBeltSignal.Stack = (byte)stack; oldBeltSignal.Stack = (byte)stack;
oldBeltSignal.Inc = (byte)inc; oldBeltSignal.Inc = (byte)inc;
oldBeltSignal.Progress = 0; oldBeltSignal.Progress = 0;
oldBeltSignal.SignalId = signalId; oldBeltSignal.SignalId = signalId;
oldBeltSignal.Sources = null; oldBeltSignal.SourceStats = null;
oldBeltSignal.SourceProgress = null;
AddSourcesToBeltSignal(oldBeltSignal); AddSourcesToBeltSignal(oldBeltSignal);
return; return;
} }
@@ -255,62 +310,69 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
} }
private static void AddSourcesToBeltSignal(BeltSignal beltSignal) private static void AddSourcesToBeltSignal(BeltSignal beltSignal)
{
beltSignal.SourceStats = null;
// Signals can change inside the logic tick, for example when drones finish a blueprint, so missing rates
// are planned in the next frame update and the tick only applies cached rates.
if (!TryApplySources(beltSignal, false)) PendingSources.Add(beltSignal);
}
private static bool TryApplySources(BeltSignal beltSignal, bool calculate)
{ {
var itemId = beltSignal.SignalId; var itemId = beltSignal.SignalId;
if (itemId < 1000) return; if (itemId < 1000 || beltSignal.Stack == 0) return true;
var result = new Dictionary<int, float>(); var catalog = ProductionCatalogService.Current;
var extra = new Dictionary<int, float>(); if (!ReferenceEquals(_sourceCatalog, catalog))
var sprayedCount = 0f;
CalculateAllProductions(result, extra, ref sprayedCount, itemId);
var proliferatorCount = 0f;
if (result.TryGetValue(ItemIds.ProliferatorMkIII, out var pv))
{ {
proliferatorCount = pv; ClearSourceCache();
result.Remove(ItemIds.ProliferatorMkIII); _sourceCatalog = catalog;
} _preferredProliferator = BeltSignalSourcePreset.SelectProliferator(catalog);
if (FactoryPatch.BeltSignalUseProliferatorEnabled.Value)
{
if (beltSignal.Inc / beltSignal.Stack >= 4)
{
sprayedCount += 1f;
}
if (sprayedCount > 0)
{
proliferatorCount += sprayedCount / ProliferatorSpayCount;
}
}
if (proliferatorCount > 0f)
{
foreach (var p in ItemIds.ProliferatorSources)
{
result[p.Item1] = (result.TryGetValue(p.Item1, out var v) ? v : 0) + p.Item2 * proliferatorCount / ProliferatorDenom;
}
} }
result.Remove(itemId); var proliferated = FactoryPatch.BeltSignalUseProliferatorEnabled.Value;
var sprayed = proliferated && _preferredProliferator != null &&
var cnt = result.Count + extra.Count; beltSignal.Inc / beltSignal.Stack >= _preferredProliferator.ProliferationLevel;
if (cnt == 0) var key = (itemId, proliferated, sprayed);
if (catalog == null)
{ {
beltSignal.Sources = null; LogSourceFailure(key, "Production data is not loaded.");
beltSignal.SourceProgress = null; return true;
return;
} }
var items = new (int itemId, float itemCount, bool isExtra)[cnt]; if (FailedSources.Contains(key)) return true;
var progress = new float[cnt]; if (!SourceCache.TryGetValue(key, out var rates))
foreach (var p in extra)
{ {
items[--cnt] = (p.Key, p.Value, true); if (!calculate) return false;
} try
foreach (var p in result)
{ {
items[--cnt] = (p.Key, p.Value, false); var request = BeltSignalSourcePreset.Create(catalog, itemId, proliferated, sprayed);
var report = new ProductionPlanner(catalog).Calculate(request);
if (!report.MaterialComplete)
{
LogSourceFailure(key, string.Join("; ", report.Diagnostics.Select(diagnostic => diagnostic.Message)));
return true;
} }
beltSignal.Sources = items; rates = BeltSignalSourceStats.FromReport(report, itemId);
beltSignal.SourceProgress = progress; }
catch (Exception exception)
{
LogSourceFailure(key, exception.ToString());
return true;
}
SourceCache[key] = rates;
}
if (rates.Count > 0) beltSignal.SourceStats = new BeltSignalSourceStats(rates);
return true;
}
private static void LogSourceFailure((int itemId, bool proliferated, bool sprayed) key, string reason)
{
if (FailedSources.Add(key))
CheatEnabler.Logger.LogWarning(
$"Belt signal upstream statistics for item {key.itemId} are suspended: {reason}");
} }
private static void SetSignalBeltPortalTo(int factory, int beltId, int number) private static void SetSignalBeltPortalTo(int factory, int beltId, int number)
@@ -365,13 +427,15 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
[HarmonyPrefix] [HarmonyPrefix]
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.RemoveBeltComponent))] [HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.RemoveBeltComponent))]
public static void CargoTraffic_RemoveBeltComponent_Prefix(int id) public static void CargoTraffic_RemoveBeltComponent_Prefix(CargoTraffic __instance, int id)
{ {
if (!_initialized) return; if (!_initialized) return;
var planet = GameMain.localPlanet; // Belts also change on planets other than the local one, for example through Battlefield Analysis Base
if (planet == null) return; // construction or Dark Fog attacks, so always use the factory that owns the belt.
RemoveSignalBeltPortalEnd(planet.factoryIndex, id); var factory = __instance.factory;
RemoveSignalBelt(planet.factoryIndex, id); if (factory == null) return;
RemoveSignalBeltPortalEnd(factory.index, id);
RemoveSignalBelt(factory.index, id);
} }
[HarmonyPostfix] [HarmonyPostfix]
@@ -379,9 +443,8 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
public static void CargoTraffic_SetBeltSignalIcon_Postfix(CargoTraffic __instance, int signalId, int entityId) public static void CargoTraffic_SetBeltSignalIcon_Postfix(CargoTraffic __instance, int signalId, int entityId)
{ {
if (!_initialized) return; if (!_initialized) return;
var planet = GameMain.localPlanet;
if (planet == null) return;
var factory = __instance.factory; var factory = __instance.factory;
if (factory == null) return;
int number; int number;
var needAdd = false; var needAdd = false;
switch (signalId) switch (signalId)
@@ -398,7 +461,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
break; break;
case >= 601 and <= 609: case >= 601 and <= 609:
number = Mathf.RoundToInt(factory.entitySignPool[entityId].count0); number = Mathf.RoundToInt(factory.entitySignPool[entityId].count0);
var factoryIndex = planet.factoryIndex; var factoryIndex = factory.index;
var beltId = factory.entityPool[entityId].beltId; var beltId = factory.entityPool[entityId].beltId;
if (number > 0) if (number > 0)
SetSignalBeltPortalTo(factoryIndex, beltId, number); SetSignalBeltPortalTo(factoryIndex, beltId, number);
@@ -410,7 +473,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
} }
{ {
var factoryIndex = planet.factoryIndex; var factoryIndex = factory.index;
var beltId = factory.entityPool[entityId].beltId; var beltId = factory.entityPool[entityId].beltId;
if (needAdd) if (needAdd)
{ {
@@ -430,9 +493,8 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
public static void CargoTraffic_SetBeltSignalNumber_Postfix(CargoTraffic __instance, float number, int entityId) public static void CargoTraffic_SetBeltSignalNumber_Postfix(CargoTraffic __instance, float number, int entityId)
{ {
if (!_initialized) return; if (!_initialized) return;
var planet = GameMain.localPlanet;
if (planet == null) return;
var factory = __instance.factory; var factory = __instance.factory;
if (factory == null) return;
var entitySignPool = factory.entitySignPool; var entitySignPool = factory.entitySignPool;
uint signalId; uint signalId;
if (entitySignPool[entityId].iconType == 0U || (signalId = entitySignPool[entityId].iconId0) == 0U) return; if (entitySignPool[entityId].iconType == 0U || (signalId = entitySignPool[entityId].iconId0) == 0U) return;
@@ -444,7 +506,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
case >= 1000 and < 20000: case >= 1000 and < 20000:
break; break;
case >= 601 and <= 609: case >= 601 and <= 609:
var factoryIndex = planet.factoryIndex; var factoryIndex = factory.index;
var beltId = factory.entityPool[entityId].beltId; var beltId = factory.entityPool[entityId].beltId;
RemoveSignalBeltPortalEnd(factoryIndex, beltId); RemoveSignalBeltPortalEnd(factoryIndex, beltId);
SetSignalBeltPortalTo(factoryIndex, beltId, Mathf.RoundToInt(number)); SetSignalBeltPortalTo(factoryIndex, beltId, Mathf.RoundToInt(number));
@@ -454,7 +516,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
} }
{ {
var factoryIndex = planet.factoryIndex; var factoryIndex = factory.index;
var beltId = factory.entityPool[entityId].beltId; var beltId = factory.entityPool[entityId].beltId;
var n = Mathf.RoundToInt(number); var n = Mathf.RoundToInt(number);
if (n == 0) if (n == 0)
@@ -570,26 +632,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
if (hasSpeedLimit) beltSignal.Progress -= 3600; if (hasSpeedLimit) beltSignal.Progress -= 3600;
if (FactoryPatch.BeltSignalCountGenEnabled.Value) productRegister[signalId] += stack; if (FactoryPatch.BeltSignalCountGenEnabled.Value) productRegister[signalId] += stack;
if (!countRecipe) continue; if (!countRecipe) continue;
var sources = beltSignal.Sources; beltSignal.SourceStats?.Apply(stack, productRegister, consumeRegister);
if (sources == null) continue;
var progress = beltSignal.SourceProgress;
var stackf = (float)stack;
for (var i = sources.Length - 1; i >= 0; i--)
{
var newCnt = progress[i] + sources[i].itemCount * stackf;
if (newCnt > 0)
{
var itemId = sources[i].itemId;
var cnt = Mathf.CeilToInt(newCnt);
productRegister[itemId] += cnt;
if (!sources[i].isExtra) consumeRegister[itemId] += cnt;
progress[i] = newCnt - cnt;
}
else
{
progress[i] = newCnt;
}
}
continue; continue;
} }
@@ -612,179 +655,4 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
ProcessBeltSignals(); ProcessBeltSignals();
} }
/* BEGIN: Item sources calculation */
// Item ID constants are provided by UXAssist.Common.GameConstants.ItemIds.
private const float ProliferatorDenom = 21f;
// One sprayed proliferator mk.III can spray 75 items, but one is used for spray itself, so the actual count is 74
private const float ProliferatorSpayCount = 74f;
private static readonly Dictionary<int, ItemSource> ItemSources = [];
private static bool _itemSourcesInitialized;
private class ItemSource
{
public float Count;
public Dictionary<int, float> From;
public Dictionary<int, float> Extra;
}
private static void InitItemSources()
{
if (_itemSourcesInitialized) return;
foreach (var vein in LDB.veins.dataArray)
{
ItemSources[vein.MiningItem] = new ItemSource { Count = 1 };
}
foreach (var ip in LDB.items.dataArray)
{
if (!string.IsNullOrEmpty(ip.MiningFrom))
{
ItemSources[ip.ID] = new ItemSource { Count = 1 };
}
}
// Water, sulfuric acid, hydrogen, deuterium, photons
foreach (var itemId in ItemIds.ExtraOreItemIds)
{
ItemSources[itemId] = new ItemSource { Count = 1 };
}
var recipes = LDB.recipes.dataArray;
foreach (var recipe in recipes)
{
if (!recipe.Explicit || recipe.ID == 58 || recipe.ID == 121) continue;
var res = recipe.Results;
var rescnt = recipe.ResultCounts;
var len = res.Length;
for (var i = 0; i < len; i++)
{
if (ItemSources.ContainsKey(res[i])) continue;
var rs = new ItemSource { Count = rescnt[i], From = [] };
var it = recipe.Items;
var itcnt = recipe.ItemCounts;
var len2 = it.Length;
for (var j = 0; j < len2; j++)
{
rs.From[it[j]] = itcnt[j];
}
if (len > 1)
{
rs.Extra = [];
for (var k = 0; k < len; k++)
{
if (i != k)
{
rs.Extra[res[k]] = rescnt[k];
}
}
}
ItemSources[res[i]] = rs;
}
}
foreach (var recipe in recipes)
{
if (recipe.Explicit) continue;
var res = recipe.Results;
var rescnt = recipe.ResultCounts;
var len = res.Length;
for (var i = 0; i < len; i++)
{
if (ItemSources.ContainsKey(res[i])) continue;
var rs = new ItemSource { Count = rescnt[i], From = [], Extra = null };
var it = recipe.Items;
var itcnt = recipe.ItemCounts;
var len2 = it.Length;
for (var j = 0; j < len2; j++)
{
rs.From[it[j]] = itcnt[j];
}
if (len > 1)
{
rs.Extra = [];
for (var k = 0; k < len; k++)
{
if (i != k)
{
rs.Extra[res[k]] = rescnt[k];
}
}
}
ItemSources[res[i]] = rs;
}
}
_itemSourcesInitialized = true;
}
private static void CalculateAllProductions(IDictionary<int, float> result, IDictionary<int, float> extra, ref float sprayedCount, int itemId, float count = 1f)
{
if (!ItemSources.TryGetValue(itemId, out var itemSource))
{
return;
}
var times = 1f;
if (Math.Abs(count - itemSource.Count) > 0.000001f)
{
times = count / itemSource.Count;
}
result[itemId] = (result.TryGetValue(itemId, out var oldCount) ? oldCount : 0) + count;
if (itemSource.Extra != null)
{
foreach (var p in itemSource.Extra)
{
extra[p.Key] = (extra.TryGetValue(p.Key, out oldCount) ? oldCount : 0) + times * p.Value;
}
}
if (itemId == ItemIds.ProliferatorMkIII || itemSource.From == null) return;
var useProliferator = FactoryPatch.BeltSignalUseProliferatorEnabled.Value;
if (useProliferator && ItemIds.ExtraProliferationItemIds.Contains(itemId))
{
times *= 0.8f;
}
foreach (var p in itemSource.From)
{
var value = p.Value * times;
if (useProliferator && !ItemIds.NoProliferationItemIds.Contains(p.Key)) sprayedCount += value;
if (extra.TryGetValue(p.Key, out var rcount))
{
if (value <= rcount)
{
if (value == rcount)
{
extra.Remove(p.Key);
}
else
{
extra[p.Key] = rcount - value;
}
continue;
}
extra.Remove(p.Key);
value -= rcount;
}
if (result.TryGetValue(p.Key, out rcount))
{
rcount -= value;
if (rcount <= 0)
{
result.Remove(p.Key);
}
else
{
result[p.Key] = rcount;
}
continue;
}
CalculateAllProductions(result, extra, ref sprayedCount, p.Key, value);
}
}
/* END: Item sources calculation */
} }
@@ -0,0 +1,146 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UXAssist.Common.GameConstants;
using UXAssist.Production;
namespace CheatEnabler.Patches.Factory;
internal readonly struct BeltSignalSourceRate
{
public int ItemId { get; }
public double ProductionPerItem { get; }
public double ConsumptionPerItem { get; }
public BeltSignalSourceRate(int itemId, double productionPerItem, double consumptionPerItem)
{
ItemId = itemId;
ProductionPerItem = productionPerItem;
ConsumptionPerItem = consumptionPerItem;
}
}
internal sealed class BeltSignalSourceStats
{
private readonly double[] _productionProgress;
private readonly double[] _consumptionProgress;
public IReadOnlyList<BeltSignalSourceRate> Rates { get; }
public BeltSignalSourceStats(IReadOnlyList<BeltSignalSourceRate> rates)
{
Rates = rates;
_productionProgress = new double[rates.Count];
_consumptionProgress = new double[rates.Count];
}
public static IReadOnlyList<BeltSignalSourceRate> FromReport(ProductionReport report, int targetItemId)
{
if (report == null || !report.MaterialComplete)
throw new InvalidOperationException("A complete material report is required for belt statistics.");
var rates = new List<BeltSignalSourceRate>();
foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
{
var produced = flow.GrossProduction + flow.ExternalImports -
(flow.ItemId == targetItemId ? flow.Delivered : 0);
var consumed = flow.GrossConsumption;
if (!ValidRate(produced) || !ValidRate(consumed))
throw new InvalidOperationException("The production report contains an invalid belt statistics rate.");
if (produced > 0 || consumed > 0)
rates.Add(new BeltSignalSourceRate(flow.ItemId, Math.Max(0, produced), consumed));
}
return Array.AsReadOnly(rates.ToArray());
}
public void Apply(int stack, int[] productRegister, int[] consumeRegister)
{
for (var index = 0; index < Rates.Count; index++)
{
var rate = Rates[index];
Accumulate(rate.ProductionPerItem, stack, ref _productionProgress[index],
productRegister, rate.ItemId);
Accumulate(rate.ConsumptionPerItem, stack, ref _consumptionProgress[index],
consumeRegister, rate.ItemId);
}
}
private static bool ValidRate(double rate)
{
return rate >= -1e-7 && rate < int.MaxValue / 4.0 &&
!double.IsNaN(rate) && !double.IsInfinity(rate);
}
private static void Accumulate(double rate, int stack, ref double progress, int[] register, int itemId)
{
if (rate <= 0) return;
var total = progress + rate * stack;
if (total <= 0)
{
progress = total;
return;
}
var count = (int)Math.Ceiling(total);
register[itemId] += count;
progress = total - count;
}
}
internal static class BeltSignalSourcePreset
{
public static ProductionItem SelectProliferator(ProductionCatalog catalog)
{
return catalog?.Items.Values.Where(item => item.ProliferationLevel > 0 && item.SpraysPerItem > 0)
.OrderByDescending(item => item.ProliferationLevel)
.ThenByDescending(item => item.SpraysPerItem)
.ThenBy(item => item.Id).FirstOrDefault();
}
public static ProductionPlanRequest Create(ProductionCatalog catalog, int itemId,
bool useProliferator, bool sprayDeliveredItem)
{
var request = new ProductionPlanRequest
{
ProliferationEnabled = useProliferator,
ProliferatorItemId = useProliferator ? SelectProliferator(catalog)?.Id ?? 0 : 0,
SelfSprayProliferator = useProliferator
};
request.Targets.Add(new ProductionTarget(itemId, 1));
foreach (var externalItemId in ItemIds.ExtraOreItemIds)
{
if (catalog.Items.ContainsKey(externalItemId)) request.ExternalMaterials.Add(externalItemId);
}
// Keep the legacy preference for explicit recipes, which include the rare-resource alternatives. Explicit
// recipes that consume their own product, X-ray Cracking and Reforming Refine, never supply an item.
foreach (var recipe in catalog.Recipes.Values
.Where(recipe => recipe.Explicit && !recipe.Outputs.Keys.Any(recipe.Inputs.ContainsKey))
.OrderBy(recipe => recipe.Id))
{
foreach (var outputId in recipe.Outputs.Keys)
{
if (request.RecipeByItem.ContainsKey(outputId) || request.ExternalMaterials.Contains(outputId) ||
!catalog.Items.TryGetValue(outputId, out var output) || output.IsNatural) continue;
request.RecipeByItem[outputId] = recipe.Id;
}
}
if (!useProliferator) return request;
if (sprayDeliveredItem) request.SprayDeliveredItems.Add(itemId);
foreach (var item in catalog.Items.Values)
{
var recipeId = request.RecipeByItem.TryGetValue(item.Id, out var selectedRecipeId)
? selectedRecipeId : item.DefaultRecipeId;
if (!catalog.Recipes.TryGetValue(recipeId, out var recipe) ||
!recipe.Outputs.ContainsKey(item.Id) || recipe.Inputs.Count == 0) continue;
request.ProliferationModeByItem[item.Id] = ItemIds.NoProliferationItemIds.Contains(item.Id)
? ProliferationMode.None
: ItemIds.ExtraProliferationItemIds.Contains(item.Id) && recipe.Productive
? ProliferationMode.ExtraProducts : ProliferationMode.Speedup;
}
return request;
}
}
+7 -4
View File
@@ -88,14 +88,14 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
ControlPanelRemoteLogistics.Enable(ControlPanelRemoteLogisticsEnabled.Value); ControlPanelRemoteLogistics.Enable(ControlPanelRemoteLogisticsEnabled.Value);
Enable(true); Enable(true);
CargoTrafficPatch.Enable(true); CargoTrafficPatch.Enable(true);
GameLogicProc.OnGameBegin += OnGameBegin_For_ImmBuild; GameLogicProc.OnGameBegin += OnGameBeginOrGuideComplete;
GameLogicProc.OnDataLoaded += OnDataLoaded; GameLogicProc.OnDataLoaded += OnDataLoaded;
} }
public static void Uninit() public static void Uninit()
{ {
GameLogicProc.OnDataLoaded -= OnDataLoaded; GameLogicProc.OnDataLoaded -= OnDataLoaded;
GameLogicProc.OnGameBegin -= OnGameBegin_For_ImmBuild; GameLogicProc.OnGameBegin -= OnGameBeginOrGuideComplete;
CargoTrafficPatch.Enable(false); CargoTrafficPatch.Enable(false);
Enable(false); Enable(false);
ImmediateBuild.Enable(false); ImmediateBuild.Enable(false);
@@ -152,7 +152,8 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
if (factory.prebuildCount <= 0) return; if (factory.prebuildCount <= 0) return;
var imm = ImmediateEnabled.Value; var imm = ImmediateEnabled.Value;
var architect = ArchitectModeEnabled.Value; var architect = ArchitectModeEnabled.Value;
if ((!imm && !architect) || GameMain.gameScenario == null) return; if ((!imm && !architect) || GameMain.gameScenario == null ||
GameMain.data?.guideComplete != true) return;
var prebuilds = factory.prebuildPool; var prebuilds = factory.prebuildPool;
if (imm) if (imm)
{ {
@@ -193,7 +194,9 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
} }
} }
private static void OnGameBegin_For_ImmBuild() [HarmonyPostfix]
[HarmonyPatch(typeof(GameData), nameof(GameData.EndStandardModeGuide))]
private static void OnGameBeginOrGuideComplete()
{ {
if (DSPGame.IsMenuDemo) return; if (DSPGame.IsMenuDemo) return;
var factory = GameMain.mainPlayer?.factory; var factory = GameMain.mainPlayer?.factory;
@@ -174,6 +174,7 @@ internal class ImmediateBuild : PatchImpl<ImmediateBuild>
[HarmonyPatch(typeof(GameLogic), nameof(GameLogic.FactoryConstructionSystemGameTick))] [HarmonyPatch(typeof(GameLogic), nameof(GameLogic.FactoryConstructionSystemGameTick))]
private static void GameLogic_FactoryConstructionSystemGameTick_Prefix(GameLogic __instance) private static void GameLogic_FactoryConstructionSystemGameTick_Prefix(GameLogic __instance)
{ {
if (GameMain.data?.guideComplete != true || GameMain.gameScenario == null) return;
var time = __instance.timei; var time = __instance.timei;
if (time % 6 != 0) return; if (time % 6 != 0) return;
var planet = GameMain.localPlanet; var planet = GameMain.localPlanet;
+7 -1
View File
@@ -26,6 +26,7 @@
* Factory: * Factory:
* Finish build immediately * Finish build immediately
* Completes pending buildings as soon as their required building items are available * Completes pending buildings as soon as their required building items are available
* Starts after the opening cutscene has ended or been skipped
* Architect mode * Architect mode
* Unlimited use of buildings, Logistics Bots, Logistics Drones and Interstellar Logistics Vessels * Unlimited use of buildings, Logistics Bots, Logistics Drones and Interstellar Logistics Vessels
* Construction and inventory availability checks show at least 999 of each supported item. * Construction and inventory availability checks show at least 999 of each supported item.
@@ -74,7 +75,8 @@
* Keep the highest-production shells and remove the others * Keep the highest-production shells and remove the others
* Duplicate the highest-production shells with a configurable shell count * Duplicate the highest-production shells with a configurable shell count
* Mecha/Combat: * Mecha/Combat:
* Mecha and Drones/Fleets invicible * Mecha and Drones/Fleets invincible
* Protects mecha HP and energy shields, ground combat drones, and space fleets, including when enabled during combat.
* Buildings invicible * Buildings invicible
* Enable warp without space warpers * Enable warp without space warpers
* Teleport to outer space * Teleport to outer space
@@ -91,6 +93,7 @@ The item icon selects the output; no hotkey is needed.
## Notes ## Notes
* Requires UXAssist 1.6.3 or later. When upgrading manually, replace the old UXAssist DLL and remove duplicate copies from the BepInEx plugins folder.
* Please upgrade `BepInEx` 5.4.21 or later if using with [BlueprintTweaks](https://dsp.thunderstore.io/package/kremnev8/BlueprintTweaks/) to avoid possible conflicts. * Please upgrade `BepInEx` 5.4.21 or later if using with [BlueprintTweaks](https://dsp.thunderstore.io/package/kremnev8/BlueprintTweaks/) to avoid possible conflicts.
* You can download [BepInEx here](https://github.com/bepinex/bepinex/releases/latest)(choose x64 edition). * You can download [BepInEx here](https://github.com/bepinex/bepinex/releases/latest)(choose x64 edition).
* If using with r2modman, you can upgrade `BepInEx` by clicking `Settings` -> `Browse profile folder`, then extract downloaded zip to the folder and overwrite existing files. * If using with r2modman, you can upgrade `BepInEx` by clicking `Settings` -> `Browse profile folder`, then extract downloaded zip to the folder and overwrite existing files.
@@ -129,6 +132,7 @@ The item icon selects the output; no hotkey is needed.
* 工厂: * 工厂:
* 建造秒完成 * 建造秒完成
* 所需建筑物品齐备后立即完成待建造建筑 * 所需建筑物品齐备后立即完成待建造建筑
* 开场动画播放结束或跳过后生效
* 建筑师模式 * 建筑师模式
* 建筑、配送运输机、物流运输机和星际物流运输船可无限使用 * 建筑、配送运输机、物流运输机和星际物流运输船可无限使用
* 建造及库存可用数量检查中,每种受支持物品至少显示 999 个。 * 建造及库存可用数量检查中,每种受支持物品至少显示 999 个。
@@ -178,6 +182,7 @@ The item icon selects the output; no hotkey is needed.
* 从发电量最高的壳复制戴森壳,可设置壳面数量 * 从发电量最高的壳复制戴森壳,可设置壳面数量
* 机甲/战斗: * 机甲/战斗:
* 机甲和战斗无人机无敌 * 机甲和战斗无人机无敌
* 保护机甲耐久度和能量护盾、地面战斗无人机和太空编队,战斗中开启同样生效。
* 建筑无敌 * 建筑无敌
* 无需空间翘曲器即可曲速飞行 * 无需空间翘曲器即可曲速飞行
* 传送到外太空 * 传送到外太空
@@ -194,6 +199,7 @@ The item icon selects the output; no hotkey is needed.
## 注意事项 ## 注意事项
* 需要 UXAssist 1.6.3 或更高版本。手动升级时,请替换旧的 UXAssist DLL,并删除 BepInEx 插件目录中的重复副本。
* 如果和[BlueprintTweaks](https://dsp.thunderstore.io/package/kremnev8/BlueprintTweaks/)一起使用,请升级`BepInEx`到5.4.21或更高版本,以避免可能的冲突 * 如果和[BlueprintTweaks](https://dsp.thunderstore.io/package/kremnev8/BlueprintTweaks/)一起使用,请升级`BepInEx`到5.4.21或更高版本,以避免可能的冲突
* 你可以在[这里](https://github.com/bepinex/bepinex/releases/latest)(选择x64版本)下载`BepInEx` * 你可以在[这里](https://github.com/bepinex/bepinex/releases/latest)(选择x64版本)下载`BepInEx`
* 如果使用r2modman,你可以点击`Settings` -> `Browse profile folder`,然后将下载的zip解压到该文件夹并覆盖现有文件 * 如果使用r2modman,你可以点击`Settings` -> `Browse profile folder`,然后将下载的zip解压到该文件夹并覆盖现有文件
+1 -1
View File
@@ -5,6 +5,6 @@
"description": "Add various cheat functions while disabling abnormal determinants / 添加一些作弊功能,同时屏蔽异常检测", "description": "Add various cheat functions while disabling abnormal determinants / 添加一些作弊功能,同时屏蔽异常检测",
"dependencies": [ "dependencies": [
"xiaoye97-BepInEx-5.4.17", "xiaoye97-BepInEx-5.4.17",
"soarqin-UXAssist-1.4.0" "soarqin-UXAssist-1.6.3"
] ]
} }
-14
View File
@@ -4,8 +4,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UXAssist", "UXAssist\UXAssi
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CheatEnabler", "CheatEnabler\CheatEnabler.csproj", "{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CheatEnabler", "CheatEnabler\CheatEnabler.csproj", "{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LogisticMiner", "LogisticMiner\LogisticMiner.csproj", "{7149D717-C913-4153-9425-38CB9D087F83}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HideTips", "HideTips\HideTips.csproj", "{4EABD71D-477F-448B-801B-48F8745A3FA7}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HideTips", "HideTips\HideTips.csproj", "{4EABD71D-477F-448B-801B-48F8745A3FA7}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dustbin", "Dustbin\Dustbin.csproj", "{931F0230-5941-4E49-AB19-66921AF14096}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dustbin", "Dustbin\Dustbin.csproj", "{931F0230-5941-4E49-AB19-66921AF14096}"
@@ -65,18 +63,6 @@ Global
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x64.Build.0 = Release|Any CPU {F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x64.Build.0 = Release|Any CPU
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x86.ActiveCfg = Release|Any CPU {F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x86.ActiveCfg = Release|Any CPU
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x86.Build.0 = Release|Any CPU {F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x86.Build.0 = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x64.ActiveCfg = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x64.Build.0 = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x86.ActiveCfg = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x86.Build.0 = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|Any CPU.Build.0 = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x64.ActiveCfg = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x64.Build.0 = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x86.ActiveCfg = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x86.Build.0 = Release|Any CPU
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|Any CPU.Build.0 = Debug|Any CPU {4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|x64.ActiveCfg = Debug|Any CPU {4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|x64.ActiveCfg = Debug|Any CPU
+1
View File
@@ -11,6 +11,7 @@
<NoWarn>0618</NoWarn> <NoWarn>0618</NoWarn>
<AnalysisLevel>none</AnalysisLevel> <AnalysisLevel>none</AnalysisLevel>
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild> <EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
<DefaultItemExcludesInProjectFolder>$(DefaultItemExcludesInProjectFolder);tools/**/bin/**;tools/**/obj/**</DefaultItemExcludesInProjectFolder>
<RestoreAdditionalProjectSources>https://nuget.bepinex.dev/v3/index.json</RestoreAdditionalProjectSources> <RestoreAdditionalProjectSources>https://nuget.bepinex.dev/v3/index.json</RestoreAdditionalProjectSources>
<!-- Set to true in projects that include a CHANGELOG.md in the package --> <!-- Set to true in projects that include a CHANGELOG.md in the package -->
<PackHasChangelog>false</PackHasChangelog> <PackHasChangelog>false</PackHasChangelog>
+5
View File
@@ -26,6 +26,11 @@
<_ZipPath>$(_PackageDir)\$(ProjectName)-$(Version).zip</_ZipPath> <_ZipPath>$(_PackageDir)\$(ProjectName)-$(Version).zip</_ZipPath>
</PropertyGroup> </PropertyGroup>
<!-- Refresh referenced preloaders before collecting patchers; other projects skip this target. -->
<MSBuild Projects="@(ProjectReference)" Targets="CopyToParentPackage"
Properties="Configuration=$(Configuration)"
Condition="'$(PackUsePluginsLayout)' == 'true'" />
<!-- Sync manifest.json version_number from .csproj $(Version) before packaging --> <!-- Sync manifest.json version_number from .csproj $(Version) before packaging -->
<Exec Condition="Exists('$(_PackageDir)\manifest.json')" <Exec Condition="Exists('$(_PackageDir)\manifest.json')"
Command="powershell.exe -NoProfile -ExecutionPolicy Bypass -Command &quot;$f='$(_PackageDir)\manifest.json'; $c=[IO.File]::ReadAllText($f); $c=$c -replace '(\u0022version_number\u0022\s*:\s*\u0022)[^\u0022]*(\u0022)','${1}$(Version)${2}'; [IO.File]::WriteAllText($f,$c,[Text.UTF8Encoding]::new($true))&quot;" /> Command="powershell.exe -NoProfile -ExecutionPolicy Bypass -Command &quot;$f='$(_PackageDir)\manifest.json'; $c=[IO.File]::ReadAllText($f); $c=$c -replace '(\u0022version_number\u0022\s*:\s*\u0022)[^\u0022]*(\u0022)','${1}$(Version)${2}'; [IO.File]::WriteAllText($f,$c,[Text.UTF8Encoding]::new($true))&quot;" />
+6 -2
View File
@@ -3,10 +3,12 @@
## Changelog ## Changelog
* 1.4.0 * 1.5.0
* `Storage dustbin`: Destroy splitter input to a storage placed above it, including stacked and proliferated cargo. Enabling dustbin mode also clears cached full-storage state. * `Storage dustbin`: Destroy splitter input to a storage placed above it, including stacked and proliferated cargo. Enabling dustbin mode also clears cached full-storage state.
* `Tank dustbin`: Fix single tanks blocking liquid input after receiving their first stack, both with and without dustbin mode. * `Tank dustbin`: Fix single tanks blocking liquid input after receiving their first stack, both with and without dustbin mode.
* `Belt signal dustbin`: Restore item disposal and startup compatibility with the current game simulation loop after DSP 0.10.33/0.10.34 updates. * `Belt signal dustbin`: Restore item disposal and startup compatibility with the current game simulation loop after DSP 0.10.33/0.10.34 updates.
* 1.4.0
* Refactorying Tank input logic codes, for better performance, and resolve a bug [#53](https://github.com/soarqin/DSP_Mods/issues/53) * Refactorying Tank input logic codes, for better performance, and resolve a bug [#53](https://github.com/soarqin/DSP_Mods/issues/53)
* Remove use of AssetBundle, move the belt signal icon into `Assembly Resources`, for better flexibility. * Remove use of AssetBundle, move the belt signal icon into `Assembly Resources`, for better flexibility.
@@ -46,10 +48,12 @@
## 更新日志 ## 更新日志
* 1.4.0 * 1.5.0
* `储物仓垃圾桶`:销毁四向分流器送入上方储物仓的物品,包括堆叠和喷涂增产剂的物品;启用垃圾桶时清除已满状态缓存。 * `储物仓垃圾桶`:销毁四向分流器送入上方储物仓的物品,包括堆叠和喷涂增产剂的物品;启用垃圾桶时清除已满状态缓存。
* `储液罐垃圾桶`:修复单层储液罐装入第一批液体后停止输入的问题,普通储存和垃圾桶模式均可正常工作。 * `储液罐垃圾桶`:修复单层储液罐装入第一批液体后停止输入的问题,普通储存和垃圾桶模式均可正常工作。
* `传送带信号垃圾桶`:适配当前游戏的模拟循环,修复 DSP 0.10.33/0.10.34 更新后的启动报错和物品无法销毁问题。 * `传送带信号垃圾桶`:适配当前游戏的模拟循环,修复 DSP 0.10.33/0.10.34 更新后的启动报错和物品无法销毁问题。
* 1.4.0
* 重构储液罐的输入逻辑代码,以提高性能并解决bug [#53](https://github.com/soarqin/DSP_Mods/issues/53) * 重构储液罐的输入逻辑代码,以提高性能并解决bug [#53](https://github.com/soarqin/DSP_Mods/issues/53)
* 移除了AssetBundle的使用,将传送带信号图标移入`Assembly资源`,以获得更好的灵活性 * 移除了AssetBundle的使用,将传送带信号图标移入`Assembly资源`,以获得更好的灵活性
+1 -1
View File
@@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<BepInExPluginGuid>org.soardev.dustbin</BepInExPluginGuid> <BepInExPluginGuid>org.soardev.dustbin</BepInExPluginGuid>
<Description>DSP MOD - Dustbin</Description> <Description>DSP MOD - Dustbin</Description>
<Version>1.4.0</Version> <Version>1.5.0</Version>
<PackageId>Dustbin</PackageId> <PackageId>Dustbin</PackageId>
<RootNamespace>Dustbin</RootNamespace> <RootNamespace>Dustbin</RootNamespace>
<PackHasChangelog>true</PackHasChangelog> <PackHasChangelog>true</PackHasChangelog>
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "Dustbin", "name": "Dustbin",
"version_number": "1.4.0", "version_number": "1.5.0",
"website_url": "https://github.com/soarqin/DSP_Mods/tree/master/Dustbin", "website_url": "https://github.com/soarqin/DSP_Mods/tree/master/Dustbin",
"description": "Can turn Storages and Tanks into Dustbin(Destroy incoming items) / 储物仓和储液罐可以转变为垃圾桶(销毁送进的物品)", "description": "Can turn Storages and Tanks into Dustbin(Destroy incoming items) / 储物仓和储液罐可以转变为垃圾桶(销毁送进的物品)",
"dependencies": [ "dependencies": [
+1 -1
View File
@@ -19,7 +19,7 @@
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Net.WebSockets.WebSocketProtocol" Version="5.1.3" /> <PackageReference Include="System.Net.WebSockets.WebSocketProtocol" Version="5.1.3" />
<Compile Remove="tools\**" /> <Compile Remove="tools\**" />
<None Include="tools\**" /> <None Include="tools\**" Exclude="tools\**\bin\**;tools\**\obj\**" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Connections.Abstractions.dll" /> <WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Connections.Abstractions.dll" />
+24 -6
View File
@@ -3,9 +3,18 @@
## Changlog ## Changlog
* 1.6.3 - Unreleased * 1.6.4
* `Sunlight at night`: Base lighting on the camera and the viewed surface instead of Icarus's facing direction, including planet view. Keep building, terrain, solar-panel, and belt lighting directions synchronized, recover when the active light or planet changes, and restore native lighting when sailing, disabling the feature, or using white rendering mode. * `Hide battle-related techs in Peace mode`: Fix an array index error when opening the tech tree after switching from a Peace-mode save to a Combat-mode save in the same game process, including when disabling the option after loading another Peace-mode save.
* `Quick build Mining Machines`: Add a Factory-tab button that searches dense layouts at the nearest solid vein group using native collision shapes, including interleaving feet, joint placement of nearby miners, and a final pass to fill remaining compatible positions. `Allow restoring/burying veins` is off by default: uses only visible nodes and skips all restoration and burial calculations. When enabled, restores available buried nodes and may bury unused nodes to improve coverage. Optimizes summed vein coverage, requires at least 3 covered nodes per miner after any burial, and places the full ordinary miner layout regardless of stock, leaving ghosts awaiting missing materials. Accelerates layout searches with up to 4 background workers, capped at half the available logical processors. Writes replayable JSON snapshots during feature tuning and keeps the completion tip visible for about 8 seconds. * 1.6.3
* `Quick build Mining Machines`:
* Add a Factory-tab button to arrange ordinary Mining Machines densely around the nearest solid vein group. Each miner covers at least 3 nodes from that group, without including nearby groups. Layouts are not limited by stock; missing miners remain as ghosts awaiting materials. Placement respects construction range and does not include belts or power facilities. Click again to cancel a search.
* `Allow restoring/burying veins` is off by default, using only visible nodes without restoring or burying any. Enable it to restore unobstructed nodes away from Dark Fog Planetary Bases and allow unused nodes to be buried for better coverage. Nodes used by existing miners or miner ghosts are protected.
* `Blueprint descriptions`:
* Add an `Auto-fill` entry to the native description header in the blueprint browser, copy, and paste inspectors. It opens generation options without moving native fields or covering the file list. Generation replaces the main description with material flows per minute, separating shortages, surpluses, inputs, outputs, and research use, and adds factory and logistics power demand to a `Power` custom field.
* Choose `Final-product output` (the default on opening the inspector) to retain rated final outputs and show intermediate shortages and excess, or `Lowest intermediate throughput` to scale the final-product mix to the bottleneck using recipe ratios. Complete, balanceable chains have no internal shortages in the latter mode; unused intermediate capacity appears as excess. External inputs use the selected basis; power still covers every selected building at full load. If a balanced basis cannot be determined, the original description is kept.
* A `Proliferation` checkbox controls whether calculations include proliferation, defaulting to on when the blueprint contains a Spray Coater. Large rates use K/M/G where display precision is preserved, and numbers with four or more integer digits use comma thousands separators, including before suffixes; unknown values are marked separately. Other custom fields are preserved, and the blueprint still needs to be saved manually.
* `Sunlight at night`: Lighting now follows the camera, including planet view, and stays consistent across buildings, terrain, solar panels, and belts. Restore lighting correctly after switching planets, and return to native lighting when sailing, disabling the feature, or using white rendering mode.
* `Protect veins from exhaustion`: Fix the option failing to take effect in 1.6.2, restoring protection of configured vein reserves and minimum oil rates, along with the corresponding mining statistics.
* 1.6.2 * 1.6.2
* `Increase maximum power usage in Logistic Stations and Advanced Mining Machines`: Fix zero or corrupted mining speeds when adjusting an Advanced Mining Machine's speed slider with the option enabled. * `Increase maximum power usage in Logistic Stations and Advanced Mining Machines`: Fix zero or corrupted mining speeds when adjusting an Advanced Mining Machine's speed slider with the option enabled.
* `Tweak building buffers`: Restore the Ray Receiver Graviton Lens buffer setting on DSP 0.10.35.29104 and later, and correct the displayed native buffer value to 2. * `Tweak building buffers`: Restore the Ray Receiver Graviton Lens buffer setting on DSP 0.10.35.29104 and later, and correct the displayed native buffer value to 2.
@@ -437,9 +446,18 @@
## 更新日志 ## 更新日志
* 1.6.3 - Unreleased * 1.6.4
* `夜间日光灯`:按镜头和当前观察位置的地表方向计算光照,不再跟随机甲朝向,行星视图也适用。统一建筑、地表、太阳能板和传送带的光照方向,在光源或行星切换后恢复功能,并在航行、关闭功能或白模渲染时恢复原版光照。 * `在和平模式下隐藏战斗相关科技`:修复在同一次游戏运行中从和平模式存档切换到战斗模式存档后打开科技树时的数组越界,以及再次加载和平模式存档后关闭选项时的同类问题。
* `快速铺设采矿机`:在「工厂」页增加按钮,按游戏实际碰撞体在最近的固体矿脉搜索密集布局,支持脚部交错、邻近矿机联动调整及结束前补入剩余可用位置。「允许恢复/掩埋矿物」默认关闭:仅使用可见矿点,跳过所有恢复和掩埋计算;开启后,恢复可恢复的掩埋矿点,并允许掩埋未被使用的矿点来提高覆盖数。以各台矿机覆盖矿点数之和为目标,要求每台在掩埋后仍覆盖至少 3 个矿点,不受库存限制地生成完整布局,缺少采矿机的位置保留待建造虚影。使用最多 4 个后台线程加速布局搜索,线程数不超过可用逻辑线程数的一半。功能调试期间输出可离线重放的 JSON 数据,完成提示保留约 8 秒。 * 1.6.3
* `快速铺设采矿机`:
* 在「工厂」页增加按钮,自动在最近的固体矿脉周围密集铺设普通采矿机。每台至少覆盖选中矿脉的 3 个矿点,不混入附近其他矿脉。布局数量不受库存限制,采矿机不足的位置保留待建造虚影。遵守建造范围,不自动铺设传送带和电力设施。计算期间再次点击可取消。
* 「允许恢复/掩埋矿物」默认关闭,仅使用可见矿点,不恢复或掩埋矿点。开启后可恢复未被建筑阻挡、且远离黑雾行星基地的矿点,并允许掩埋未使用的矿点来提高覆盖数;已有矿机和待建造矿机使用的矿点会受到保护。
* `蓝图说明`:
* 在蓝图浏览、复制和粘贴检查面板的说明标题行增加「自动填写」入口,点击展开生成选项,不移动原生字段或遮挡文件列表。生成时用每分钟的物料流量替换原说明,分别列出「缺少」「多余」「输入」「输出」「研究」,并将工厂与物流耗电写入「耗电」自定义字段。
* 可选择「最终产物产量」(每次打开检查面板时的默认值),保留最终产物的额定产量并显示中间产物的缺口和余量;也可选择「最低产量中间产物」,按配方比例换算瓶颈,等比例缩放各最终产物。后一种模式下,数据完整且可平衡的生产链没有内部缺口,未使用的中间产能列为「多余」。外部输入采用所选基准,耗电仍按所选全部建筑满载估算。无法确定平衡基准时保留原说明。
* 可用「增产」复选框选择是否计入增产效果,蓝图含喷涂机时默认勾选。较大的流量在保留显示精度的前提下使用 K/M/G 单位;整数部分达到四位的数字用逗号每三位分隔,带单位时也适用。无法计算的数值单独标注。保留其他自定义字段,填写后仍需手动保存蓝图。
* `夜间日光灯`:光照改为随镜头变化,行星视图也适用;建筑、地表、太阳能板和传送带的光照方向保持一致。切换行星后正确恢复光照,航行、关闭功能或进入白模渲染时恢复原版光照。
* `保护矿脉不会枯竭`:修复 1.6.2 中开启后仍不生效的问题,恢复设定的矿脉剩余量、油井最低流速保护及相应开采统计。
* 1.6.2 * 1.6.2
* `提升物流塔和大型采矿机的最大功耗`:修复启用后调整大型采矿机开采速度时出现 0% 或异常速度的问题。 * `提升物流塔和大型采矿机的最大功耗`:修复启用后调整大型采矿机开采速度时出现 0% 或异常速度的问题。
* `调整建筑输入缓冲`:修复 DSP 0.10.35.29104 及后续版本中射线接收器透镜缓冲设置不生效的问题,并将显示的游戏原始值更正为 2。 * `调整建筑输入缓冲`:修复 DSP 0.10.35.29104 及后续版本中射线接收器透镜缓冲设置不生效的问题,并将显示的游戏原始值更正为 2。
+50 -69
View File
@@ -13,49 +13,44 @@ public static class ItemIds
public const int SulfuricAcid = 1116; public const int SulfuricAcid = 1116;
public const int Hydrogen = 1120; public const int Hydrogen = 1120;
public const int Deuterium = 1121; public const int Deuterium = 1121;
public const int Photon = 1208; public const int CriticalPhoton = 1208;
/* Materials used by recipes */ /* Materials and components */
public const int OrganicCrystal = 1015; public const int TitaniumAlloy = 1107;
public const int FireIce = 1012; public const int Prism = 1111;
public const int CriticalPhoton = 1124; public const int FrameMaterial = 1125;
public const int CircuitBoard = 1112; // used in proliferator mk.III recipe public const int CasimirCrystal = 1126;
public const int Steel = 1107; public const int MagneticCoil = 1202;
public const int TitaniumGlass = 1111; public const int ElectricMotor = 1203;
public const int GravitonLens = 1125; public const int ElectromagneticTurbine = 1204;
public const int SuperMagneticRing = 1205;
public const int GravitonLens = 1209;
public const int CircuitBoard = 1301;
public const int QuantumChip = 1305;
public const int PlasmaExciter = 1401;
public const int ParticleBroadband = 1402;
public const int AnnihilationConstraintSphere = 1403;
public const int Thruster = 1405;
public const int ReinforcedThruster = 1406;
/* Proliferators */ /* Proliferators */
public const int ProliferatorMkI = 1141; public const int ProliferatorMkI = 1141;
public const int ProliferatorMkII = 1142; public const int ProliferatorMkII = 1142;
public const int ProliferatorMkIII = 1143; public const int ProliferatorMkIII = 1143;
/* Logistics carriers */ /* Logistics */
public const int SpaceWarper = 1210;
public const int LogisticsDrone = 5001; public const int LogisticsDrone = 5001;
public const int LogisticsVessel = 5002; public const int LogisticsVessel = 5002;
public const int LogisticsBot = 5003; public const int LogisticsBot = 5003;
public const int SpaceWarper = 1126;
/* Matrices */
public const int ElectromagneticMatrix = 1202;
public const int EnergyMatrix = 1203;
public const int StructureMatrix = 1204;
public const int InformationMatrix = 1205;
public const int UniverseMatrix = 1209;
public const int Antimatter = 1210;
/* Components */
public const int PlasmaExciter = 1301;
public const int ParticleBroadband = 1305;
public const int Processor = 1401;
public const int QuantumChip = 1402;
public const int MicrocrystallineComponent = 1403;
public const int PlaneFilter = 1405;
public const int ParticleContainer = 1406;
/* Dyson sphere materials */ /* Dyson sphere materials */
public const int SolarSail = 1502; public const int DysonSphereComponent = 1502;
public const int FrameMaterial = 1503; public const int SmallCarrierRocket = 1503;
public const int DysonSphereComponent = 1802;
/* Fuel rods */
public const int DeuteronFuelRod = 1802;
public const int StrangeAnnihilationFuelRod = 1804;
/* Power nodes */ /* Power nodes */
public const int TeslaTower = 2201; public const int TeslaTower = 2201;
@@ -67,63 +62,49 @@ public static class ItemIds
public const int MiningMachine = 2301; public const int MiningMachine = 2301;
/* Dark Fog items (combat expansion) */ /* Dark Fog items (combat expansion) */
public const int DarkFogMemoryUnit = 5201; public const int DarkFogMatrix = 5201;
public const int DarkFogSiliconNeuron = 5202; public const int DarkFogSiliconNeuron = 5202;
public const int DarkFogMatterReassembler = 5203; public const int DarkFogMatterRecombinator = 5203;
public const int DarkFogNegentropySingularity = 5204; public const int DarkFogNegentropySingularity = 5204;
public const int DarkFogVirtualParticle = 5205; public const int DarkFogCoreElement = 5205;
public const int DarkFogEnergyFragment = 5206; public const int DarkFogEnergyShard = 5206;
/* Fuel and advanced items */ /* Matrices. Metadata types use the same IDs; the Universe Matrix's metadata is Metaverse. */
public const int HydrogenFuelRod = 6001; public const int ElectromagneticMatrix = 6001;
public const int DeuteronFuelRod = 6002; public const int EnergyMatrix = 6002;
public const int AntimatterFuelRod = 6003; public const int StructureMatrix = 6003;
public const int StrangeMatter = 6004; public const int InformationMatrix = 6004;
public const int Foundation = 6005; public const int GravityMatrix = 6005;
public const int Metaverse = 6006; // also called property/meta-data item public const int UniverseMatrix = 6006;
/* Item groups used by belt signal recipe calculations. */ /* Item groups used by belt signal recipe calculations. */
public static readonly int[] ExtraOreItemIds = public static readonly int[] ExtraOreItemIds =
[ [
Water, SulfuricAcid, Hydrogen, Deuterium, Photon, Water, SulfuricAcid, Hydrogen, Deuterium, CriticalPhoton,
DarkFogMemoryUnit, DarkFogSiliconNeuron, DarkFogMatterReassembler, DarkFogMatrix, DarkFogSiliconNeuron, DarkFogMatterRecombinator,
DarkFogNegentropySingularity, DarkFogVirtualParticle, DarkFogEnergyFragment DarkFogNegentropySingularity, DarkFogCoreElement, DarkFogEnergyShard
]; ];
// Listed in the same order as the belt signal option tips.
public static readonly HashSet<int> ExtraProliferationItemIds = public static readonly HashSet<int> ExtraProliferationItemIds =
[ [
Steel, TitaniumGlass, GravitonLens, ProliferatorMkII, ProliferatorMkIII, TitaniumAlloy, Prism, FrameMaterial, ProliferatorMkII, ProliferatorMkIII,
ElectromagneticMatrix, EnergyMatrix, StructureMatrix, InformationMatrix, MagneticCoil, ElectricMotor, ElectromagneticTurbine, SuperMagneticRing,
UniverseMatrix, Antimatter, PlasmaExciter, ParticleBroadband, CircuitBoard, Thruster, ReinforcedThruster, PlasmaExciter, ParticleBroadband,
Processor, QuantumChip, MicrocrystallineComponent, PlaneFilter, ParticleContainer, GravitonLens, QuantumChip, AnnihilationConstraintSphere, DeuteronFuelRod, SpaceWarper,
SolarSail, FrameMaterial, DysonSphereComponent, DysonSphereComponent, SmallCarrierRocket, ElectromagneticMatrix, StructureMatrix,
HydrogenFuelRod, AntimatterFuelRod, StrangeMatter, Foundation, Metaverse InformationMatrix, GravityMatrix, UniverseMatrix
]; ];
public static readonly HashSet<int> NoProliferationItemIds = public static readonly HashSet<int> NoProliferationItemIds =
[ [
SpaceWarper, DeuteronFuelRod CasimirCrystal, EnergyMatrix
];
/// <summary>
/// All source items used to create 25 proliferators mk.III (not self-sprayed).
/// </summary>
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. */ /* Dark Fog materials used by production calculations. */
public static readonly int[] DarkFogItemIds = public static readonly int[] DarkFogItemIds =
[ [
DarkFogMemoryUnit, DarkFogSiliconNeuron, DarkFogMatterReassembler, DarkFogMatrix, DarkFogSiliconNeuron, DarkFogMatterRecombinator,
DarkFogNegentropySingularity, DarkFogVirtualParticle, DarkFogEnergyFragment DarkFogNegentropySingularity, DarkFogCoreElement, DarkFogEnergyShard
]; ];
} }
+63
View File
@@ -5,6 +5,34 @@ namespace UXAssist.Common;
public static class I18NKeys public static class I18NKeys
{ {
public const string Unknown = "Unknown"; public const string Unknown = "Unknown";
public const string BlueprintAutoFillDescription = "UXAssist Blueprint Auto-fill description";
public const string BlueprintDescriptionOptions = "UXAssist Blueprint Description Options";
public const string BlueprintDescriptionOptionsTip = "UXAssist Blueprint Description Options Tip";
public const string BlueprintProliferation = "UXAssist Blueprint Proliferation";
public const string BlueprintProductionBasis = "UXAssist Blueprint Production Basis";
public const string BlueprintFinalProducts = "UXAssist Blueprint Final Products";
public const string BlueprintBottleneckIntermediate = "UXAssist Blueprint Bottleneck Intermediate";
public const string BlueprintProductionBasisTip = "UXAssist Blueprint Production Basis Tip";
public const string BlueprintBasisUnavailable = "Cannot determine a balanced intermediate throughput. Check building settings and production-chain outputs, or use final-product output.";
public const string BlueprintPower = "UXAssist Blueprint Power";
public const string BlueprintPowerEnglish = "Power";
public const string BlueprintPowerChinese = "耗电";
public const string BlueprintInputLine = "UXAssist Blueprint Input Line";
public const string BlueprintOutputLine = "UXAssist Blueprint Output Line";
public const string BlueprintResearchLine = "UXAssist Blueprint Research Line";
public const string BlueprintFactoryPower = "UXAssist Blueprint Factory Power";
public const string BlueprintLogisticsPower = "UXAssist Blueprint Logistics Power";
public const string BlueprintMissing = "UXAssist Blueprint Missing";
public const string BlueprintExcess = "UXAssist Blueprint Excess";
public const string BlueprintKnownPortion = "UXAssist Blueprint Known Portion";
public const string BlueprintInvalid = "Cannot fill description: the blueprint is invalid.";
public const string BlueprintEmpty = "Cannot fill description: the blueprint has no buildings.";
public const string BlueprintDataUnavailable = "Production data is unavailable. Wait for it to load and try again.";
public const string BlueprintCalculationFailed = "Production calculation failed; no description was generated.";
public const string BlueprintDescriptionTooLong = "The generated description exceeds the game's 2,000-character limit. Reduce the blueprint's material types and try again.";
public const string BlueprintFieldLimit = "At most {0} custom fields are allowed. Remove an unused field and try again.";
public const string BlueprintInvalidFields = "Custom fields have invalid formatting. Fix them and try again.";
public const string BlueprintPartial = "Some building settings or recipes are unavailable; generated values show known portions.";
public const string DoYouWantToUseMetadataToBuyoutTheFollowingTech = "Do you want to use metadata to buyout the following tech?"; public const string DoYouWantToUseMetadataToBuyoutTheFollowingTech = "Do you want to use metadata to buyout the following tech?";
public const string TheFollowingIsTheRequiredMetadataForBuyout = "The following is the required metadata for buyout:"; public const string TheFollowingIsTheRequiredMetadataForBuyout = "The following is the required metadata for buyout:";
public const string BatchBuyoutTech = "Batch buyout tech"; public const string BatchBuyoutTech = "Batch buyout tech";
@@ -184,8 +212,10 @@ public static class I18NKeys
public const string QuickMinerFailed = "Miner placement stopped; check the log before retrying"; public const string QuickMinerFailed = "Miner placement stopped; check the log before retrying";
public const string QuickMinerVeinsChanged = "Veins changed during miner layout search"; public const string QuickMinerVeinsChanged = "Veins changed during miner layout search";
public const string QuickMinerResult = "Placed {0} Mining Machines, {1} total vein coverage, {2} buried nodes"; public const string QuickMinerResult = "Placed {0} Mining Machines, {1} total vein coverage, {2} buried nodes";
#if DEBUG
public const string QuickMinerDebugSaved = "Miner layout debug data: {0}"; public const string QuickMinerDebugSaved = "Miner layout debug data: {0}";
public const string QuickMinerDebugFailed = "Could not save miner layout debug data"; public const string QuickMinerDebugFailed = "Could not save miner layout debug data";
#endif
public const string MaximumCountToBuild = "Maximum count to build"; public const string MaximumCountToBuild = "Maximum count to build";
public const string Max = "max"; public const string Max = "max";
public const string StopEjectorsWhenAvailableNodesAreAllFilledUp = "Stop ejectors when available nodes are all filled up"; public const string StopEjectorsWhenAvailableNodesAreAllFilledUp = "Stop ejectors when available nodes are all filled up";
@@ -213,6 +243,37 @@ public static class I18NKeys
public static void Register() public static void Register()
{ {
I18N.Add(Unknown, "Unknown", "未知"); I18N.Add(Unknown, "Unknown", "未知");
I18N.Add(BlueprintAutoFillDescription, "Auto-fill description", "自动填写说明");
I18N.Add(BlueprintDescriptionOptions, "Auto-fill…", "自动填写…");
I18N.Add(BlueprintDescriptionOptionsTip,
"Choose production basis and proliferation, then fill the blueprint description.",
"选择产量基准和增产后,自动填写蓝图说明。");
I18N.Add(BlueprintProliferation, "Proliferation", "增产");
I18N.Add(BlueprintProductionBasis, "Production basis", "产量基准");
I18N.Add(BlueprintFinalProducts, "Final-product output", "最终产物产量");
I18N.Add(BlueprintBottleneckIntermediate, "Lowest intermediate throughput", "最低产量中间产物");
I18N.Add(BlueprintProductionBasisTip,
"Final-product output (default): keep rated final outputs and show intermediate shortages and excess.\nLowest intermediate throughput: convert capacities through recipe ratios and scale all final outputs together to the bottleneck; complete, balanceable chains have no internal shortages. Excess shows unused intermediate capacity. Power still sizes all selected buildings at full load.\nUnknown settings or an unresolved output prevent balanced generation; the existing description is kept.",
"最终产物产量(默认):保留最终产物的额定产量,显示中间产物的缺口和余量。\n最低产量中间产物:按配方比例换算产能,以瓶颈等比例缩放各最终产物;数据完整且可平衡时没有内部缺口,「多余」表示未使用的中间产能。耗电仍按所选全部建筑满载估算。\n缺少参数或无法确定输出时,不生成平衡说明,保留原说明。");
I18N.Add(BlueprintBasisUnavailable, BlueprintBasisUnavailable,
"无法确定可平衡的中间产物产量,原说明已保留。请检查建筑参数和生产链输出,或改用最终产物产量基准。");
I18N.Add(BlueprintPower, BlueprintPowerEnglish, BlueprintPowerChinese);
I18N.Add(BlueprintInputLine, "Input: ", "输入:");
I18N.Add(BlueprintOutputLine, "Output: ", "输出:");
I18N.Add(BlueprintResearchLine, "Research: ", "研究:");
I18N.Add(BlueprintFactoryPower, "Factory power", "工厂耗电");
I18N.Add(BlueprintLogisticsPower, "Logistics power", "物流耗电");
I18N.Add(BlueprintMissing, "Missing: ", "缺少:");
I18N.Add(BlueprintExcess, "Excess: ", "多余:");
I18N.Add(BlueprintKnownPortion, "(known portion)", "(已知部分)");
I18N.Add(BlueprintInvalid, BlueprintInvalid, "蓝图无效,请重新选择蓝图后重试。");
I18N.Add(BlueprintEmpty, BlueprintEmpty, "蓝图中没有建筑,请选择包含建筑的蓝图后重试。");
I18N.Add(BlueprintDataUnavailable, BlueprintDataUnavailable, "生产数据尚未加载,请等待加载完成后重试。");
I18N.Add(BlueprintCalculationFailed, BlueprintCalculationFailed, "生产计算失败,未生成说明。");
I18N.Add(BlueprintDescriptionTooLong, BlueprintDescriptionTooLong, "生成的说明超过游戏允许的 2000 字,请减少蓝图中的材料种类后重试。");
I18N.Add(BlueprintFieldLimit, BlueprintFieldLimit, "自定义字段最多 {0} 个,请先删除不需要的字段再重试。");
I18N.Add(BlueprintInvalidFields, BlueprintInvalidFields, "自定义字段格式无效,请先修正后重试。");
I18N.Add(BlueprintPartial, BlueprintPartial, "部分建筑缺少运行参数或配方;生成结果仅显示可计算的部分。");
I18N.Add(DoYouWantToUseMetadataToBuyoutTheFollowingTech, "Do you want to use metadata to buyout the following tech?", "要使用元数据买断以下科技吗?"); I18N.Add(DoYouWantToUseMetadataToBuyoutTheFollowingTech, "Do you want to use metadata to buyout the following tech?", "要使用元数据买断以下科技吗?");
I18N.Add(TheFollowingIsTheRequiredMetadataForBuyout, "The following is the required metadata for buyout:", "以下是买断所需元数据:"); I18N.Add(TheFollowingIsTheRequiredMetadataForBuyout, "The following is the required metadata for buyout:", "以下是买断所需元数据:");
I18N.Add(BatchBuyoutTech, "Batch buyout tech", "批量买断科技"); I18N.Add(BatchBuyoutTech, "Batch buyout tech", "批量买断科技");
@@ -461,8 +522,10 @@ You can set 2 shortcut keys in Settings panel:
I18N.Add(QuickMinerFailed, "Miner placement stopped. Check the UXAssist log before retrying.", "采矿机铺设已停止,请查看 UXAssist 日志后重试。"); I18N.Add(QuickMinerFailed, "Miner placement stopped. Check the UXAssist log before retrying.", "采矿机铺设已停止,请查看 UXAssist 日志后重试。");
I18N.Add(QuickMinerVeinsChanged, "The veins changed during calculation. Click the button again to recalculate the layout.", "计算期间矿点状态已变化,请再次点击按钮重新计算布局。"); I18N.Add(QuickMinerVeinsChanged, "The veins changed during calculation. Click the button again to recalculate the layout.", "计算期间矿点状态已变化,请再次点击按钮重新计算布局。");
I18N.Add(QuickMinerResult, "Placed {0} Mining Machines; total vein coverage: {1} (shared nodes counted per miner); buried nodes: {2}.", "已铺设 {0} 台采矿机,总覆盖 {1} 个矿点(各台分别计数),掩埋 {2} 个矿点。"); I18N.Add(QuickMinerResult, "Placed {0} Mining Machines; total vein coverage: {1} (shared nodes counted per miner); buried nodes: {2}.", "已铺设 {0} 台采矿机,总覆盖 {1} 个矿点(各台分别计数),掩埋 {2} 个矿点。");
#if DEBUG
I18N.Add(QuickMinerDebugSaved, "Debug data: {0}", "调试数据:{0}"); I18N.Add(QuickMinerDebugSaved, "Debug data: {0}", "调试数据:{0}");
I18N.Add(QuickMinerDebugFailed, "Could not save debug data. Check the UXAssist log before retrying.", "调试数据保存失败,请查看 UXAssist 日志后重试。"); I18N.Add(QuickMinerDebugFailed, "Could not save debug data. Check the UXAssist log before retrying.", "调试数据保存失败,请查看 UXAssist 日志后重试。");
#endif
I18N.Add(MaximumCountToBuild, "Maximum count to build", "最大建造数量"); I18N.Add(MaximumCountToBuild, "Maximum count to build", "最大建造数量");
I18N.Add(Max, "max", "最大"); I18N.Add(Max, "max", "最大");
I18N.Add(StopEjectorsWhenAvailableNodesAreAllFilledUp, "Stop ejectors when available nodes are all filled up", "可用节点全部造完时停止弹射"); I18N.Add(StopEjectorsWhenAvailableNodesAreAllFilledUp, "Stop ejectors when available nodes are all filled up", "可用节点全部造完时停止弹射");
@@ -15,7 +15,7 @@ internal static class MinerPlacementDebug
internal sealed class Snapshot internal sealed class Snapshot
{ {
public int schema = 4; public int schema = 4;
public string algorithm = "parallel-repack-v5-pose-exploration-min3-unlimited-stock"; public string algorithm = "parallel-repack-v5-pose-exploration-min3-unlimited-stock-target-group";
public int minimumCoverage = MinerPlacementSolver.MinimumCoverage; public int minimumCoverage = MinerPlacementSolver.MinimumCoverage;
public string version, gameVersion, startedUtc, outcome, error; public string version, gameVersion, startedUtc, outcome, error;
public int planetId, veinType, veinGroup, initialStock, placedCount, totalCoverage, buriedCount; public int planetId, veinType, veinGroup, initialStock, placedCount, totalCoverage, buriedCount;
+172 -28
View File
@@ -2,11 +2,15 @@ using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
#if DEBUG
using System.IO; using System.IO;
#endif
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
#if DEBUG
using BepInEx; using BepInEx;
#endif
using BepInEx.Configuration; using BepInEx.Configuration;
using UnityEngine; using UnityEngine;
using UXAssist.Common; using UXAssist.Common;
@@ -99,12 +103,13 @@ public static class QuickMinerBuild
private static void Fail(Exception exception) private static void Fail(Exception exception)
{ {
UXAssist.Logger.LogError($"Quick miner placement failed: {exception}"); UXAssist.Logger.LogError($"Quick miner placement failed: {exception}");
#if DEBUG
_job?.RecordFailure(exception); _job?.RecordFailure(exception);
#endif
Stop(); Stop();
UIRealtimeTip.Popup(I18NKeys.QuickMinerFailed.Translate()); UIRealtimeTip.Popup(I18NKeys.QuickMinerFailed.Translate());
} }
// Completion, failure and cancellation all finish the job, which records its debug data.
private static void Stop() private static void Stop()
{ {
var job = _job; var job = _job;
@@ -120,7 +125,9 @@ public static class QuickMinerBuild
private static void ShowResult(string message) private static void ShowResult(string message)
{ {
#if DEBUG
UXAssist.Logger.LogInfo($"Quick miner result: {message.Replace("\n", " | ")}"); UXAssist.Logger.LogInfo($"Quick miner result: {message.Replace("\n", " | ")}");
#endif
UIRealtimeTip.Popup(message); UIRealtimeTip.Popup(message);
foreach (var tip in UIRoot.instance.uiGame.generalTips.realtimeTips) foreach (var tip in UIRoot.instance.uiGame.generalTips.realtimeTips)
{ {
@@ -160,7 +167,10 @@ public static class QuickMinerBuild
private sealed class Node private sealed class Node
{ {
public int Id; public int Id;
public Vector3 Position, OriginalPosition; public Vector3 Position;
#if DEBUG
public Vector3 OriginalPosition;
#endif
public ColliderData Collider; public ColliderData Collider;
public bool Target, Visible, CanBury; public bool Target, Visible, CanBury;
public EVeinType Type; public EVeinType Type;
@@ -187,10 +197,12 @@ public static class QuickMinerBuild
private readonly ColliderData _body; private readonly ColliderData _body;
private readonly float _footprintRadius, _halfDiagonal; private readonly float _footprintRadius, _halfDiagonal;
private readonly bool _capsule, _allowVeinReform; private readonly bool _capsule, _allowVeinReform;
#if DEBUG
private readonly MinerPlacementDebug.Snapshot _debug = new(); private readonly MinerPlacementDebug.Snapshot _debug = new();
private readonly List<MinerPlacementDebug.Phase> _phases = []; private readonly List<MinerPlacementDebug.Phase> _phases = [];
private readonly List<MinerPlacementDebug.Placement> _placements = []; private readonly List<MinerPlacementDebug.Placement> _placements = [];
private readonly Stopwatch _timer = Stopwatch.StartNew(); private readonly Stopwatch _timer = Stopwatch.StartNew();
#endif
private readonly CancellationTokenSource _cancellation = new(); private readonly CancellationTokenSource _cancellation = new();
private readonly int _workers = MinerPlacementSolver.WorkerCount; private readonly int _workers = MinerPlacementSolver.WorkerCount;
private IEnumerator _work; private IEnumerator _work;
@@ -200,6 +212,7 @@ public static class QuickMinerBuild
private float _probeX = float.NaN, _probeZ = float.NaN; private float _probeX = float.NaN, _probeZ = float.NaN;
private bool _probeRestricted; private bool _probeRestricted;
private EVeinType _type; private EVeinType _type;
private int _group;
private float _minX, _maxX, _minZ, _maxZ; private float _minX, _maxX, _minZ, _maxZ;
public bool IsCurrent => GameMain.isRunning && GameMain.mainPlayer == _player && public bool IsCurrent => GameMain.isRunning && GameMain.mainPlayer == _player &&
@@ -231,6 +244,7 @@ public static class QuickMinerBuild
// Native clearance checks measure from the encompassing build collider. // Native clearance checks measure from the encompassing build collider.
_halfDiagonal = Mathf.Sqrt(desc.buildCollider.ext.x * desc.buildCollider.ext.x + desc.buildCollider.ext.z * desc.buildCollider.ext.z); _halfDiagonal = Mathf.Sqrt(desc.buildCollider.ext.x * desc.buildCollider.ext.x + desc.buildCollider.ext.z * desc.buildCollider.ext.z);
_capsule = planet.id == planet.galaxy.birthPlanetId && GameMain.history.SpaceCapsuleExist(); _capsule = planet.id == planet.galaxy.birthPlanetId && GameMain.history.SpaceCapsuleExist();
#if DEBUG
_debug.version = PluginInfo.PLUGIN_VERSION; _debug.version = PluginInfo.PLUGIN_VERSION;
_debug.gameVersion = GameConfig.gameVersion.ToString(); _debug.gameVersion = GameConfig.gameVersion.ToString();
_debug.startedUtc = DateTime.UtcNow.ToString("O"); _debug.startedUtc = DateTime.UtcNow.ToString("O");
@@ -247,15 +261,18 @@ public static class QuickMinerBuild
_debug.buildColliders = desc.buildColliders.Select(MinerPlacementDebug.Collider.Capture).ToArray(); _debug.buildColliders = desc.buildColliders.Select(MinerPlacementDebug.Collider.Capture).ToArray();
_debug.minerColliders = _nativeObstacles.Select(MinerPlacementDebug.Collider.Capture).ToArray(); _debug.minerColliders = _nativeObstacles.Select(MinerPlacementDebug.Collider.Capture).ToArray();
_debug.outcome = "cancelled"; _debug.outcome = "cancelled";
#endif
} }
public bool Step() => (_work ??= Run()).MoveNext(); public bool Step() => (_work ??= Run()).MoveNext();
#if DEBUG
public void RecordFailure(Exception exception) public void RecordFailure(Exception exception)
{ {
_debug.outcome = "failed"; _debug.outcome = "failed";
_debug.error = exception.ToString(); _debug.error = exception.ToString();
} }
#endif
public void Finish() public void Finish()
{ {
@@ -271,15 +288,20 @@ public static class QuickMinerBuild
_cancellation.Dispose(); _cancellation.Dispose();
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
(_work as IDisposable)?.Dispose(); (_work as IDisposable)?.Dispose();
#if DEBUG
var location = WriteDebug(); var location = WriteDebug();
if (_result != null) ShowResult(_result + "\n" + location); if (_result != null) _result += "\n" + location;
#endif
if (_result != null) ShowResult(_result);
} }
private IEnumerator Run() private IEnumerator Run()
{ {
if (!FindNodes()) if (!FindNodes())
{ {
#if DEBUG
_debug.outcome = "no-veins"; _debug.outcome = "no-veins";
#endif
_result = I18NKeys.QuickMinerNoVeins.Translate(); _result = I18NKeys.QuickMinerNoVeins.Translate();
yield break; yield break;
} }
@@ -299,23 +321,43 @@ public static class QuickMinerBuild
} }
} }
var solver = new MinerPlacementSolver(_candidates, _nodes.Count, _allowVeinReform); var solver = new MinerPlacementSolver(_candidates, _nodes.Count, _allowVeinReform);
var work = Search(solver, "coarse", 10); #if DEBUG
var work = Search(solver, 10, "coarse");
#else
var work = Search(solver, 10);
#endif
while (work.MoveNext()) yield return null; while (work.MoveNext()) yield return null;
work = Expand(solver.Best, 0.35f, 3f); work = Expand(solver.Best, 0.35f, 3f);
while (work.MoveNext()) yield return null; while (work.MoveNext()) yield return null;
work = Search(solver, "refine-position", 6); #if DEBUG
work = Search(solver, 6, "refine-position");
#else
work = Search(solver, 6);
#endif
while (work.MoveNext()) yield return null; while (work.MoveNext()) yield return null;
work = Expand(solver.Best, 0.12f, 1f); work = Expand(solver.Best, 0.12f, 1f);
while (work.MoveNext()) yield return null; while (work.MoveNext()) yield return null;
work = Search(solver, "refine-angle", 4); #if DEBUG
work = Search(solver, 4, "refine-angle");
#else
work = Search(solver, 4);
#endif
while (work.MoveNext()) yield return null; while (work.MoveNext()) yield return null;
#if DEBUG
_debug.outcome = "completed"; _debug.outcome = "completed";
#endif
Commit(solver.Best); Commit(solver.Best);
} }
private IEnumerator Search(MinerPlacementSolver solver, string phase, int passes) #if DEBUG
private IEnumerator Search(MinerPlacementSolver solver, int passes, string phase)
#else
private IEnumerator Search(MinerPlacementSolver solver, int passes)
#endif
{ {
#if DEBUG
var timer = Stopwatch.StartNew(); var timer = Stopwatch.StartNew();
#endif
if (_workers > 0) if (_workers > 0)
{ {
_search = solver.SearchAsync(passes, _cancellation.Token, _workers); _search = solver.SearchAsync(passes, _cancellation.Token, _workers);
@@ -328,14 +370,17 @@ public static class QuickMinerBuild
var work = solver.Search(passes); var work = solver.Search(passes);
while (work.MoveNext()) yield return null; while (work.MoveNext()) yield return null;
} }
#if DEBUG
_phases.Add(new MinerPlacementDebug.Phase _phases.Add(new MinerPlacementDebug.Phase
{ {
name = phase, candidateCount = _candidates.Count, passes = passes, score = solver.BestScore, name = phase, candidateCount = _candidates.Count, passes = passes, score = solver.BestScore,
searchMilliseconds = timer.ElapsedMilliseconds, elapsedMilliseconds = _timer.ElapsedMilliseconds, searchMilliseconds = timer.ElapsedMilliseconds, elapsedMilliseconds = _timer.ElapsedMilliseconds,
selected = solver.Best.Select(candidate => _candidates.IndexOf(candidate)).ToArray() selected = solver.Best.Select(candidate => _candidates.IndexOf(candidate)).ToArray()
}); });
#endif
} }
#if DEBUG
private string WriteDebug() private string WriteDebug()
{ {
try try
@@ -369,6 +414,7 @@ public static class QuickMinerBuild
return I18NKeys.QuickMinerDebugFailed.Translate(); return I18NKeys.QuickMinerDebugFailed.Translate();
} }
} }
#endif
private bool FindNodes() private bool FindNodes()
{ {
@@ -386,7 +432,10 @@ public static class QuickMinerBuild
_type = vein.type; _type = vein.type;
} }
if (group == 0) return false; if (group == 0) return false;
_group = group;
#if DEBUG
_debug.veinGroup = group; _debug.veinGroup = group;
#endif
var count = 0; var count = 0;
for (var i = 1; i < _factory.veinCursor; i++) for (var i = 1; i < _factory.veinCursor; i++)
{ {
@@ -438,11 +487,15 @@ public static class QuickMinerBuild
_nodes.Add(new Node _nodes.Add(new Node
{ {
Id = i, Target = vein.groupIndex == group, Type = vein.type, Id = i, Target = vein.groupIndex == group, Type = vein.type,
Position = vein.pos, OriginalPosition = vein.pos, Collider = _physics.GetColliderData(vein.colliderId), Position = vein.pos, Collider = _physics.GetColliderData(vein.colliderId),
#if DEBUG
OriginalPosition = vein.pos,
#endif
Visible = vein.pos.magnitude >= _planet.realRadius - 40f, Visible = vein.pos.magnitude >= _planet.realRadius - 40f,
CanBury = _allowVeinReform && vein.groupIndex == group && vein.minerCount == 0 && !reserved.Contains(i) CanBury = _allowVeinReform && vein.groupIndex == group && vein.minerCount == 0 && !reserved.Contains(i)
}); });
} }
#if DEBUG
var existing = new List<MinerPlacementDebug.ExistingMiner>(); var existing = new List<MinerPlacementDebug.ExistingMiner>();
for (var i = 1; i < _factory.entityCursor; i++) for (var i = 1; i < _factory.entityCursor; i++)
{ {
@@ -468,6 +521,7 @@ public static class QuickMinerBuild
}); });
} }
_debug.existingMiners = existing.ToArray(); _debug.existingMiners = existing.ToArray();
#endif
return _nodes.Count > 0; return _nodes.Count > 0;
} }
@@ -593,13 +647,26 @@ public static class QuickMinerBuild
private void TryCandidate(float x, float z, float yaw) private void TryCandidate(float x, float z, float yaw)
{ {
#if DEBUG
_debug.rejections.attempted++; _debug.rejections.attempted++;
#endif
if (x != _probeX || z != _probeZ) Probe(x, z); if (x != _probeX || z != _probeZ) Probe(x, z);
var pos = _probe; var pos = _probe;
if (!FactoryPatch.RemoveBuildRangeLimitEnabled.Value && if (!FactoryPatch.RemoveBuildRangeLimitEnabled.Value &&
(pos - _player.position).sqrMagnitude > _player.mecha.buildArea * _player.mecha.buildArea) (pos - _player.position).sqrMagnitude > _player.mecha.buildArea * _player.mecha.buildArea)
{ _debug.rejections.range++; return; } {
if (_probeRestricted) { _debug.rejections.clearance++; return; } #if DEBUG
_debug.rejections.range++;
#endif
return;
}
if (_probeRestricted)
{
#if DEBUG
_debug.rejections.clearance++;
#endif
return;
}
var rotation = Maths.SphericalRotation(pos, yaw); var rotation = Maths.SphericalRotation(pos, yaw);
var pose = new Pose(pos, rotation); var pose = new Pose(pos, rotation);
_covered.Clear(); _covered.Clear();
@@ -607,10 +674,22 @@ public static class QuickMinerBuild
{ {
var node = _nodes[i]; var node = _nodes[i];
if (!MinerComponent.IsTargetVeinInRange(node.Position, pose, _item.prefabDesc)) continue; if (!MinerComponent.IsTargetVeinInRange(node.Position, pose, _item.prefabDesc)) continue;
if (node.Type != _type) { _debug.rejections.mixedType++; return; } if (node.Type != _type)
_covered.Add(i); {
#if DEBUG
_debug.rejections.mixedType++;
#endif
return;
}
if (node.Target) _covered.Add(i);
}
if (_covered.Count < MinerPlacementSolver.MinimumCoverage)
{
#if DEBUG
_debug.rejections.noCoverage++;
#endif
return;
} }
if (_covered.Count < MinerPlacementSolver.MinimumCoverage) { _debug.rejections.noCoverage++; return; }
for (var i = 0; i < _buildBoxes.Length; i++) for (var i = 0; i < _buildBoxes.Length; i++)
_buildBoxes[i] = new Box(_item.prefabDesc.buildColliders[i].BindToObject(0, 0, EObjectType.None, pos, rotation)); _buildBoxes[i] = new Box(_item.prefabDesc.buildColliders[i].BindToObject(0, 0, EObjectType.None, pos, rotation));
_buried?.Clear(); _buried?.Clear();
@@ -618,17 +697,41 @@ public static class QuickMinerBuild
{ {
var node = _nodes[i]; var node = _nodes[i];
if (!Hits(node.Collider)) continue; if (!Hits(node.Collider)) continue;
if (!node.CanBury) { _debug.rejections.veinCollision++; return; } if (!node.CanBury)
{
#if DEBUG
_debug.rejections.veinCollision++;
#endif
return;
}
_buried.Add(i); _buried.Add(i);
} }
if (_allowVeinReform) if (_allowVeinReform)
{ {
foreach (var index in _buried) _covered.Remove(index); foreach (var index in _buried) _covered.Remove(index);
if (_covered.Count < MinerPlacementSolver.MinimumCoverage) { _debug.rejections.noCoverage++; return; } if (_covered.Count < MinerPlacementSolver.MinimumCoverage)
{
#if DEBUG
_debug.rejections.noCoverage++;
#endif
return;
}
} }
foreach (var obstacle in _nearObstacles) foreach (var obstacle in _nearObstacles)
if (Hits(obstacle)) { _debug.rejections.buildingCollision++; return; } {
if (!HasGround(pos, rotation)) { _debug.rejections.ground++; return; } if (!Hits(obstacle)) continue;
#if DEBUG
_debug.rejections.buildingCollision++;
#endif
return;
}
if (!HasGround(pos, rotation))
{
#if DEBUG
_debug.rejections.ground++;
#endif
return;
}
for (var i = 0; i < _nativeObstacles.Length; i++) for (var i = 0; i < _nativeObstacles.Length; i++)
_obstacleBoxes[i] = new Box(_nativeObstacles[i].BindToObject(0, 0, EObjectType.None, pos, rotation)); _obstacleBoxes[i] = new Box(_nativeObstacles[i].BindToObject(0, 0, EObjectType.None, pos, rotation));
_candidates.Add(new Candidate _candidates.Add(new Candidate
@@ -715,17 +818,25 @@ public static class QuickMinerBuild
{ {
if (layout.Count == 0) if (layout.Count == 0)
{ {
#if DEBUG
_debug.outcome = "no-placement"; _debug.outcome = "no-placement";
#endif
_result = I18NKeys.QuickMinerNoPlacement.Translate(); _result = I18NKeys.QuickMinerNoPlacement.Translate();
return; return;
} }
if (!NodesUnchanged(layout)) if (!NodesUnchanged(layout))
{ {
#if DEBUG
_debug.outcome = "veins-changed"; _debug.outcome = "veins-changed";
#endif
_result = I18NKeys.QuickMinerVeinsChanged.Translate(); _result = I18NKeys.QuickMinerVeinsChanged.Translate();
return; return;
} }
#if DEBUG
var placed = new List<(Candidate Candidate, int Prebuild, MinerPlacementDebug.Placement Debug)>(); var placed = new List<(Candidate Candidate, int Prebuild, MinerPlacementDebug.Placement Debug)>();
#else
var placed = new List<(Candidate Candidate, int Prebuild)>();
#endif
var plannedBurial = _allowVeinReform var plannedBurial = _allowVeinReform
? layout.SelectMany(candidate => candidate.Buried).Select(index => _nodes[index].Id).ToHashSet() : null; ? layout.SelectMany(candidate => candidate.Buried).Select(index => _nodes[index].Id).ToHashSet() : null;
var hidden = _allowVeinReform ? new Dictionary<int, Vector3>() : null; var hidden = _allowVeinReform ? new Dictionary<int, Vector3>() : null;
@@ -744,11 +855,13 @@ public static class QuickMinerBuild
validator.buildPreviews.Add(preview); validator.buildPreviews.Add(preview);
foreach (var candidate in layout) foreach (var candidate in layout)
{ {
#if DEBUG
var debug = new MinerPlacementDebug.Placement var debug = new MinerPlacementDebug.Placement
{ {
candidate = _candidates.IndexOf(candidate), outcome = "pending", nativeCondition = "not-checked", nativeVeins = [], plannedVeins = [], finalVeins = [] candidate = _candidates.IndexOf(candidate), outcome = "pending", nativeCondition = "not-checked", nativeVeins = [], plannedVeins = [], finalVeins = []
}; };
_placements.Add(debug); _placements.Add(debug);
#endif
// No yield between burial, native validation, item consumption, and creation. // No yield between burial, native validation, item consumption, and creation.
if (_allowVeinReform) if (_allowVeinReform)
{ {
@@ -763,7 +876,11 @@ public static class QuickMinerBuild
} }
// Validation needs current Unity colliders; GPU buffers are synced once at the end. // Validation needs current Unity colliders; GPU buffers are synced once at the end.
_physics.RefreshColliders(); _physics.RefreshColliders();
if (!Validate(validator, preview, candidate, plannedBurial, debug)) continue; #if DEBUG
if (!Validate(validator, preview, candidate, plannedBurial, out var plannedVeins, debug)) continue;
#else
if (!Validate(validator, preview, candidate, plannedBurial, out var plannedVeins)) continue;
#endif
var itemId = ItemIds.MiningMachine; var itemId = ItemIds.MiningMachine;
var count = 1; var count = 1;
if (_player.inhandItemId == itemId && _player.inhandItemCount > 0) _player.UseHandItems(1, out _); if (_player.inhandItemId == itemId && _player.inhandItemCount > 0) _player.UseHandItems(1, out _);
@@ -776,14 +893,20 @@ public static class QuickMinerBuild
itemRequired = count == 1 ? 0 : 1, itemRequired = count == 1 ? 0 : 1,
filterId = _factory.veinPool[_nodes[candidate.Covered[0]].Id].productId filterId = _factory.veinPool[_nodes[candidate.Covered[0]].Id].productId
}; };
prebuild.InitParametersArray(debug.plannedVeins.Length); prebuild.InitParametersArray(plannedVeins.Length);
Array.Copy(debug.plannedVeins, prebuild.parameters, debug.plannedVeins.Length); Array.Copy(plannedVeins, prebuild.parameters, plannedVeins.Length);
var id = _factory.AddPrebuildDataWithComponents(prebuild); var id = _factory.AddPrebuildDataWithComponents(prebuild);
#if DEBUG
debug.prebuildId = id; debug.prebuildId = id;
debug.itemRequired = prebuild.itemRequired; debug.itemRequired = prebuild.itemRequired;
debug.outcome = id > 0 ? "placed" : "prebuild-failed"; debug.outcome = id > 0 ? "placed" : "prebuild-failed";
#endif
if (id == 0 && count == 1) _player.TryAddItemToPackage(ItemIds.MiningMachine, 1, 0, true); if (id == 0 && count == 1) _player.TryAddItemToPackage(ItemIds.MiningMachine, 1, 0, true);
#if DEBUG
if (id > 0) placed.Add((candidate, id, debug)); if (id > 0) placed.Add((candidate, id, debug));
#else
if (id > 0) placed.Add((candidate, id));
#endif
} }
} }
finally finally
@@ -806,21 +929,25 @@ public static class QuickMinerBuild
foreach (var node in _nodes) foreach (var node in _nodes)
{ {
ref var vein = ref _factory.veinPool[node.Id]; ref var vein = ref _factory.veinPool[node.Id];
if (vein.id == node.Id && vein.amount > 0 && vein.type == _type && vein.pos.magnitude >= _planet.realRadius - 40f && if (node.Target && vein.id == node.Id && vein.amount > 0 && vein.type == _type && vein.pos.magnitude >= _planet.realRadius - 40f &&
MinerComponent.IsTargetVeinInRange(vein.pos, pose, _item.prefabDesc)) ids.Add(node.Id); MinerComponent.IsTargetVeinInRange(vein.pos, pose, _item.prefabDesc)) ids.Add(node.Id);
} }
ref var prebuild = ref _factory.prebuildPool[entry.Prebuild]; ref var prebuild = ref _factory.prebuildPool[entry.Prebuild];
prebuild.InitParametersArray(ids.Count); prebuild.InitParametersArray(ids.Count);
if (ids.Count > 0) ids.CopyTo(prebuild.parameters); if (ids.Count > 0) ids.CopyTo(prebuild.parameters);
#if DEBUG
entry.Debug.finalVeins = ids.ToArray(); entry.Debug.finalVeins = ids.ToArray();
#endif
coverage += ids.Count; coverage += ids.Count;
} }
if (_allowVeinReform) RefreshVeins(buriedCount > 0 ? 1 : 0); if (_allowVeinReform) RefreshVeins(buriedCount > 0 ? 1 : 0);
} }
#if DEBUG
_debug.placedCount = placed.Count; _debug.placedCount = placed.Count;
_debug.totalCoverage = coverage; _debug.totalCoverage = coverage;
_debug.buriedCount = buriedCount; _debug.buriedCount = buriedCount;
if (placed.Count == 0) _debug.outcome = "no-placement"; if (placed.Count == 0) _debug.outcome = "no-placement";
#endif
_result = placed.Count == 0 ? I18NKeys.QuickMinerNoPlacement.Translate() : _result = placed.Count == 0 ? I18NKeys.QuickMinerNoPlacement.Translate() :
string.Format(I18NKeys.QuickMinerResult.Translate(), placed.Count, coverage, buriedCount); string.Format(I18NKeys.QuickMinerResult.Translate(), placed.Count, coverage, buriedCount);
} }
@@ -846,9 +973,16 @@ public static class QuickMinerBuild
} }
// CheckBuildConditions repeats the search's land-point tests, so ground needs no separate check. // CheckBuildConditions repeats the search's land-point tests, so ground needs no separate check.
private bool Validate(BuildTool_Click validator, BuildPreview preview, Candidate candidate, HashSet<int> plannedBurial, MinerPlacementDebug.Placement debug) #if DEBUG
private bool Validate(BuildTool_Click validator, BuildPreview preview, Candidate candidate, HashSet<int> plannedBurial, out int[] plannedVeins, MinerPlacementDebug.Placement debug)
#else
private bool Validate(BuildTool_Click validator, BuildPreview preview, Candidate candidate, HashSet<int> plannedBurial, out int[] plannedVeins)
#endif
{ {
plannedVeins = [];
#if DEBUG
debug.outcome = "native-rejected"; debug.outcome = "native-rejected";
#endif
preview.ResetAll(); preview.ResetAll();
preview.item = _item; preview.item = _item;
preview.desc = _item.prefabDesc; preview.desc = _item.prefabDesc;
@@ -883,16 +1017,26 @@ public static class QuickMinerBuild
} }
Physics.SyncTransforms(); Physics.SyncTransforms();
var valid = validator.CheckBuildConditions(); var valid = validator.CheckBuildConditions();
#if DEBUG
debug.nativeCondition = preview.condition.ToString(); debug.nativeCondition = preview.condition.ToString();
debug.coverObjectId = preview.coverObjId; debug.coverObjectId = preview.coverObjId;
debug.nativeVeins = preview.parameters?.Take(preview.paramCount).ToArray() ?? []; debug.nativeVeins = preview.parameters?.Take(preview.paramCount).ToArray() ?? [];
#endif
if (!valid || preview.condition != EBuildCondition.Ok || preview.coverObjId != 0) return false; if (!valid || preview.condition != EBuildCondition.Ok || preview.coverObjId != 0) return false;
// Include every planned burial now, so a later miner cannot reduce this one // Native selection includes nearby groups of the same type. Keep only this
// below the minimum after its item has already been consumed. // group and exclude all planned burials before enforcing the minimum.
debug.plannedVeins = _allowVeinReform plannedVeins = preview.parameters?.Take(preview.paramCount).Where(id => _factory.veinPool[id].groupIndex == _group &&
? debug.nativeVeins.Where(id => !plannedBurial.Contains(id)).ToArray() : debug.nativeVeins; (!_allowVeinReform || !plannedBurial.Contains(id))).ToArray() ?? [];
if (debug.plannedVeins.Length < MinerPlacementSolver.MinimumCoverage) #if DEBUG
{ debug.outcome = "below-minimum-coverage"; return false; } debug.plannedVeins = plannedVeins;
#endif
if (plannedVeins.Length < MinerPlacementSolver.MinimumCoverage)
{
#if DEBUG
debug.outcome = "below-minimum-coverage";
#endif
return false;
}
for (var i = 0; i < preview.paramCount; i++) for (var i = 0; i < preview.paramCount; i++)
{ {
ref var vein = ref _factory.veinPool[preview.parameters[i]]; ref var vein = ref _factory.veinPool[preview.parameters[i]];
@@ -0,0 +1,393 @@
using System;
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
using UXAssist.Common;
using UXAssist.Production;
using UXAssist.UI;
using Util = UXAssist.UI.Util;
namespace UXAssist.Patches;
public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
{
private static readonly Dictionary<UIBlueprintInspector, InspectorControls> Inspectors = new();
public static void Start() => Enable(true);
public static void Uninit() => Enable(false);
protected override void OnDisable()
{
foreach (var controls in Inspectors.Values) controls.Destroy();
Inspectors.Clear();
}
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnCreate))]
private static void OnCreate(UIBlueprintInspector __instance)
{
GetControls(__instance);
}
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnOpen))]
private static void OnOpen(UIBlueprintInspector __instance)
{
GetControls(__instance)?.ResetSession();
}
[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), nameof(UIBlueprintInspector._OnFree))]
private static void OnFree(UIBlueprintInspector __instance)
{
if (!Inspectors.TryGetValue(__instance, out var controls)) return;
controls.Destroy();
Inspectors.Remove(__instance);
}
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnDestroy))]
private static void OnDestroy(UIBlueprintInspector __instance)
{
OnFree(__instance);
}
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector.Refresh))]
private static void Refresh(UIBlueprintInspector __instance)
{
try
{
GetControls(__instance)?.Refresh();
}
catch (Exception exception)
{
UXAssist.Logger.LogError($"Blueprint description inspector refresh failed: {exception}");
}
}
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector.OnLanguageChanged))]
private static void OnLanguageChanged(UIBlueprintInspector __instance)
{
try
{
if (Inspectors.TryGetValue(__instance, out var controls)) controls.UpdateLabels();
}
catch (Exception exception)
{
UXAssist.Logger.LogError($"Blueprint description localization refresh failed: {exception}");
}
}
private static InspectorControls GetControls(UIBlueprintInspector inspector)
{
if (!inspector) return null;
if (Inspectors.TryGetValue(inspector, out var controls)) return controls;
try
{
controls = new InspectorControls(inspector);
Inspectors.Add(inspector, controls);
return controls;
}
catch (Exception exception)
{
UXAssist.Logger.LogError($"Blueprint description controls could not be created: {exception}");
return null;
}
}
private sealed class InspectorControls
{
private const float Left = 12f;
private const float ControlsGap = 12f;
private readonly UIBlueprintInspector _inspector;
private RectTransform _panel;
private UIButton _entry;
private Text _entryText;
private UIButton _button;
private Text _buttonText;
private UIButton _cancelButton;
private Text _cancelText;
private MyCheckBox _checkbox;
private MyCornerComboBox _basisCombo;
private Text _basisLabel;
private UIButton _basisHelp;
private BlueprintData _currentBlueprint;
private bool _manualProliferation;
public InspectorControls(UIBlueprintInspector inspector)
{
_inspector = inspector;
try
{
// The native description has a 22px title row above its editable text.
_entry = LayoutHelper.AddButton(0, 0, inspector.descGroupTrans,
I18NKeys.BlueprintDescriptionOptions, 13, "blueprint-description-options", ToggleOptions);
_entryText = _entry.transform.Find("button-text").GetComponent<Text>();
_entry.tips = inspector.tipButton2.tips;
_entry.tips.topLevel = true;
Util.NormalizeRectWithTopRight(_entry, 0, 0, inspector.descGroupTrans);
// Reuse the native background, including its blur material, only while options are open.
var source = UIRoot.instance.uiGame.inserterWindow.transform.Find("panel-bg").GetComponent<Image>();
_panel = UnityEngine.Object.Instantiate(source, inspector.rectTrans).rectTransform;
_panel.gameObject.name = "uxassist-blueprint-description-options";
for (var i = _panel.childCount - 1; i >= 0; i--)
{
var child = _panel.GetChild(i).gameObject;
child.SetActive(false);
UnityEngine.Object.Destroy(child);
}
_panel.anchorMin = new Vector2(0, 1);
_panel.anchorMax = Vector2.one;
_panel.pivot = new Vector2(0, 1);
_panel.anchoredPosition = new Vector2(Left, -Left);
_panel.sizeDelta = new Vector2(-Left * 2, 152);
_button = LayoutHelper.AddButton(Left, 12, _panel,
I18NKeys.BlueprintAutoFillDescription, 15, "blueprint-auto-fill-description", Generate);
_buttonText = _button.transform.Find("button-text").GetComponent<Text>();
_cancelButton = LayoutHelper.AddButton(0, 0, _panel,
I18NKeys.Cancel, 14, "blueprint-description-cancel", CloseOptions);
_cancelText = _cancelButton.transform.Find("button-text").GetComponent<Text>();
Util.NormalizeRectWithTopRight(_cancelButton, Left, 14, _panel);
_checkbox = MyCheckBox.CreateCheckBox(Left, 52, _panel, false,
I18NKeys.BlueprintProliferation.Translate(), 15).WithSmallerBox(22f);
_checkbox.gameObject.name = "blueprint-proliferation";
_checkbox.OnChecked += OnProliferationChecked;
_basisLabel = LayoutHelper.AddText(Left, 80, _panel, I18NKeys.BlueprintProductionBasis, 14);
_basisCombo = MyCornerComboBox.CreateComboBox(Left, 108, _panel).WithFontSize(14)
.WithItems(I18NKeys.BlueprintFinalProducts, I18NKeys.BlueprintBottleneckIntermediate)
.WithIndex(0);
var combo = _basisCombo.GetComponent<UIComboBox>();
combo.CanInput = false;
combo.autoWidth = false;
var comboRect = (RectTransform)_basisCombo.transform;
comboRect.anchorMax = Vector2.one;
comboRect.sizeDelta = new Vector2(-Left * 2, 28);
_basisHelp = LayoutHelper.AddTipsButton(Left, 80, _panel,
I18NKeys.BlueprintProductionBasis.Translate(), I18NKeys.BlueprintProductionBasisTip.Translate(), "");
UpdateLabels();
_panel.gameObject.SetActive(false);
}
catch
{
Destroy();
throw;
}
}
public void ResetSession()
{
_currentBlueprint = null;
_manualProliferation = false;
_basisCombo.SetIndex(0);
if (_inspector.blueprint != null) SyncDefault();
else _checkbox.Checked = false;
CloseOptions();
_entry.gameObject.SetActive(_inspector.blueprint != null);
}
public void Refresh()
{
SyncDefault();
_entry.gameObject.SetActive(_inspector.blueprint != null);
}
private void ToggleOptions()
{
_panel.SetAsLastSibling();
_panel.gameObject.SetActive(!_panel.gameObject.activeSelf);
}
private void CloseOptions() => _panel.gameObject.SetActive(false);
public void UpdateLabels()
{
_entryText.text = I18NKeys.BlueprintDescriptionOptions.Translate();
((RectTransform)_entry.transform).sizeDelta =
new Vector2(Util.GetPreferredWidth(_entryText) + 16, 20);
_entry.tips.tipTitle = I18NKeys.BlueprintAutoFillDescription.Translate();
_entry.tips.tipText = I18NKeys.BlueprintDescriptionOptionsTip.Translate();
_entry.UpdateTip();
_buttonText.text = I18NKeys.BlueprintAutoFillDescription.Translate();
_cancelText.text = I18NKeys.Cancel.Translate();
((RectTransform)_cancelButton.transform).sizeDelta =
new Vector2(Util.GetPreferredWidth(_cancelText) + 20, 24);
_checkbox.SetLabelText(I18NKeys.BlueprintProliferation.Translate());
_basisLabel.text = I18NKeys.BlueprintProductionBasis.Translate();
var combo = _basisCombo.GetComponent<UIComboBox>();
var index = combo.itemIndex;
_basisCombo.SetItems(I18NKeys.BlueprintFinalProducts, I18NKeys.BlueprintBottleneckIntermediate);
_basisCombo.SetIndex(index);
_basisHelp.tips.tipTitle = I18NKeys.BlueprintProductionBasis.Translate();
_basisHelp.tips.tipText = I18NKeys.BlueprintProductionBasisTip.Translate();
_basisHelp.UpdateTip();
var width = Math.Max(160f, Util.GetPreferredWidth(_buttonText) + 26f);
_button.transform.GetComponent<RectTransform>().sizeDelta =
new Vector2(width, _button.transform.GetComponent<RectTransform>().sizeDelta.y);
var labelWidth = Util.GetPreferredWidth(_basisLabel);
_basisLabel.rectTransform.sizeDelta = new Vector2(labelWidth, _basisLabel.rectTransform.sizeDelta.y);
Util.NormalizeRectWithTopLeft(_basisHelp, Left + labelWidth + ControlsGap, 80, _panel);
}
public void Destroy()
{
if (_entry)
{
_entry.button.onClick.RemoveListener(ToggleOptions);
UnityEngine.Object.Destroy(_entry.gameObject);
}
if (_button)
_button.button.onClick.RemoveListener(Generate);
if (_cancelButton)
_cancelButton.button.onClick.RemoveListener(CloseOptions);
if (_checkbox)
_checkbox.OnChecked -= OnProliferationChecked;
if (!_panel) return;
_panel.gameObject.SetActive(false);
UnityEngine.Object.Destroy(_panel.gameObject);
}
private void SyncDefault()
{
var blueprint = _inspector.blueprint;
if (!ReferenceEquals(blueprint, _currentBlueprint))
{
CloseOptions();
_currentBlueprint = blueprint;
_manualProliferation = false;
}
if (!_manualProliferation)
{
var models = LDB.models;
_checkbox.Checked = blueprint?.buildings?.Any(building => building != null &&
models?.Select(building.modelIndex)?.prefabDesc?.isSpraycoster == true) == true;
}
}
private void OnProliferationChecked()
{
_manualProliferation = true;
}
private void Generate()
{
var blueprint = _inspector.blueprint;
if (blueprint == null || !blueprint.isValid)
{
UIRealtimeTip.Popup(I18NKeys.BlueprintInvalid.Translate());
return;
}
if (blueprint.buildings == null || blueprint.buildings.Length == 0)
{
UIRealtimeTip.Popup(I18NKeys.BlueprintEmpty.Translate());
return;
}
var catalog = ProductionCatalogService.Current;
if (catalog == null)
{
UIRealtimeTip.Popup(I18NKeys.BlueprintDataUnavailable.Translate());
return;
}
try
{
if (!BlueprintDescriptionFields.IsNativeFormatValid(blueprint.externalFields))
{
UIRealtimeTip.Popup(I18NKeys.BlueprintInvalidFields.Translate());
return;
}
_inspector.OnCustomFieldEndEdit(null);
blueprint = _inspector.blueprint;
var capture = BlueprintSelectionReader.FromBlueprint(blueprint.buildings);
if (capture.Diagnostics.Any(diagnostic => diagnostic.Code == ProductionDiagnosticCode.InvalidRequest ||
diagnostic.Code == ProductionDiagnosticCode.UnknownItem ||
diagnostic.Code == ProductionDiagnosticCode.DataNotReady))
{
UIRealtimeTip.Popup(I18NKeys.BlueprintInvalid.Translate());
return;
}
var request = capture.CreateRequest(_checkbox.Checked);
request.ProductionBasis = (BlueprintProductionBasis)_basisCombo.GetComponent<UIComboBox>().itemIndex;
var report = new FactoryBlackBoxAnalyzer(catalog).Analyze(request);
if (report.Diagnostics.Any(diagnostic => diagnostic.Code == ProductionDiagnosticCode.BlueprintBasisUnavailable))
{
UIRealtimeTip.Popup(I18NKeys.BlueprintBasisUnavailable.Translate());
return;
}
if (report.Status == ProductionStatus.Failed || report.Status == ProductionStatus.DataNotReady)
{
UIRealtimeTip.Popup((report.Status == ProductionStatus.DataNotReady
? I18NKeys.BlueprintDataUnavailable : I18NKeys.BlueprintCalculationFailed).Translate());
return;
}
var labels = new BlueprintDescriptionLabels(I18NKeys.BlueprintFactoryPower.Translate(),
I18NKeys.BlueprintLogisticsPower.Translate(), I18NKeys.BlueprintMissing.Translate(),
I18NKeys.BlueprintExcess.Translate(), I18NKeys.Unknown.Translate(),
I18NKeys.BlueprintKnownPortion.Translate(), I18NKeys.BlueprintInputLine.Translate(),
I18NKeys.BlueprintOutputLine.Translate(), I18NKeys.BlueprintResearchLine.Translate());
var description = BlueprintDescriptionFormatter.Format(report,
itemId => LDB.signals.IconTag(itemId, includeName: true), labels);
if (description.Description.Length > BlueprintDescriptionText.MaximumDescriptionLength)
{
UIRealtimeTip.Popup(I18NKeys.BlueprintDescriptionTooLong.Translate());
return;
}
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);
if (result != BlueprintFieldUpdateResult.Updated)
{
UIRealtimeTip.Popup(result == BlueprintFieldUpdateResult.CapacityExceeded
? string.Format(I18NKeys.BlueprintFieldLimit.Translate(), UIBlueprintInspector.kMaxFieldCount)
: I18NKeys.BlueprintInvalidFields.Translate());
return;
}
var previousFields = blueprint.externalFields;
var previousDescription = blueprint.desc;
var previousInput = _inspector.descTextInput.text;
try
{
blueprint.externalFields = updated;
blueprint.desc = description.Description;
_inspector.descTextInput.text = description.Description;
_inspector.Refresh(forModify: true, refreshComponent: false, refreshCode: true);
}
catch
{
blueprint.externalFields = previousFields;
blueprint.desc = previousDescription;
_inspector.descTextInput.text = previousInput;
throw;
}
CloseOptions();
if (!report.MaterialComplete || !report.PowerBreakdown.FactoryComplete ||
!report.PowerBreakdown.LogisticsComplete)
UIRealtimeTip.Popup(I18NKeys.BlueprintPartial.Translate());
}
catch (Exception exception)
{
UXAssist.Logger.LogError($"Blueprint description generation failed: {exception}");
UIRealtimeTip.Popup(I18NKeys.BlueprintCalculationFailed.Translate());
}
}
}
}
+8 -7
View File
@@ -63,12 +63,12 @@ internal static class BeltSignalPatch
// A belt selects one material, so its equivalent single-material rate is 30. // A belt selects one material, so its equivalent single-material rate is 30.
private static readonly (int ItemId, int ExchangeRate, string NameKey, string IconPath)[] DarkFogBuyOutDefinitions = private static readonly (int ItemId, int ExchangeRate, string NameKey, string IconPath)[] DarkFogBuyOutDefinitions =
[ [
(ItemIds.DarkFogMemoryUnit, 20, I18NKeys.MemoryUnit, "assets/signal/dark-fog-matrix.png"), (ItemIds.DarkFogMatrix, 20, I18NKeys.MemoryUnit, "assets/signal/dark-fog-matrix.png"),
(ItemIds.DarkFogEnergyFragment, 60, I18NKeys.EnergyFragment, "assets/signal/energy-shard.png"), (ItemIds.DarkFogEnergyShard, 60, I18NKeys.EnergyFragment, "assets/signal/energy-shard.png"),
(ItemIds.DarkFogSiliconNeuron, 30, I18NKeys.SiliconNeuron, "assets/signal/silicon-based-neuron.png"), (ItemIds.DarkFogSiliconNeuron, 30, I18NKeys.SiliconNeuron, "assets/signal/silicon-based-neuron.png"),
(ItemIds.DarkFogNegentropySingularity, 30, I18NKeys.NegentropySingularity, "assets/signal/negentropy-singularity.png"), (ItemIds.DarkFogNegentropySingularity, 30, I18NKeys.NegentropySingularity, "assets/signal/negentropy-singularity.png"),
(ItemIds.DarkFogMatterReassembler, 30, I18NKeys.MatterReassembler, "assets/signal/matter-recombinator.png"), (ItemIds.DarkFogMatterRecombinator, 30, I18NKeys.MatterReassembler, "assets/signal/matter-recombinator.png"),
(ItemIds.DarkFogVirtualParticle, 10, I18NKeys.VirtualParticle, "assets/signal/core-element.png") (ItemIds.DarkFogCoreElement, 10, I18NKeys.VirtualParticle, "assets/signal/core-element.png")
]; ];
public static readonly int[] DarkFogItemsInVoid = [0, 0, 0, 0, 0, 0]; public static readonly int[] DarkFogItemsInVoid = [0, 0, 0, 0, 0, 0];
private static Dictionary<int, uint>[] _signalBelts = new Dictionary<int, uint>[64]; private static Dictionary<int, uint>[] _signalBelts = new Dictionary<int, uint>[64];
@@ -327,13 +327,14 @@ internal static class BeltSignalPatch
var consume = (byte)Math.Min(DarkFogItemsInVoid[itemIdx], 4); var consume = (byte)Math.Min(DarkFogItemsInVoid[itemIdx], 4);
if (consume < 4) if (consume < 4)
{ {
var metaverseLong = propertySystem.GetItemAvaliableProperty(_clusterSeedKey, ItemIds.Metaverse); // Metaverse is the metadata of the Universe Matrix.
var metaverseLong = propertySystem.GetItemAvaliableProperty(_clusterSeedKey, ItemIds.UniverseMatrix);
if (metaverseLong > 0L) if (metaverseLong > 0L)
{ {
var metaverse = metaverseLong > 10 ? 10 : (int)metaverseLong; var metaverse = metaverseLong > 10 ? 10 : (int)metaverseLong;
propertySystem.AddItemConsumption(_clusterSeedKey, ItemIds.Metaverse, metaverse); propertySystem.AddItemConsumption(_clusterSeedKey, ItemIds.UniverseMatrix, metaverse);
var mainPlayer = GameMain.mainPlayer; var mainPlayer = GameMain.mainPlayer;
GameMain.history.AddPropertyItemConsumption(ItemIds.Metaverse, metaverse, true); GameMain.history.AddPropertyItemConsumption(ItemIds.UniverseMatrix, metaverse, true);
var count = definition.ExchangeRate * metaverse; var count = definition.ExchangeRate * metaverse;
DarkFogItemsInVoid[itemIdx] += count; DarkFogItemsInVoid[itemIdx] += count;
consume = (byte)Math.Min(DarkFogItemsInVoid[itemIdx], 4); consume = (byte)Math.Min(DarkFogItemsInVoid[itemIdx], 4);
+12 -1
View File
@@ -222,11 +222,22 @@ public static class TechPatch
foreach (var item in nodes) foreach (var item in nodes)
{ {
var node = item.Value; var node = item.Value;
var postTechArray = node.techProto.postTechArray;
// A new session can initialize nodes while the peace-mode graph is still filtered.
var arrowCount = node.arrows.Length;
if (arrowCount < postTechArray.Length)
{
System.Array.Resize(ref node.arrows, postTechArray.Length);
for (var i = arrowCount; i < postTechArray.Length; i++)
{
node.arrows[i] = UnityEngine.Object.Instantiate(node.arrowPrefab, node.arrowPrefab.parent);
node.arrows[i].SetAsFirstSibling();
}
}
foreach (var arrow in node.arrows) foreach (var arrow in node.arrows)
{ {
arrow.gameObject.SetActive(false); arrow.gameObject.SetActive(false);
} }
var postTechArray = node.techProto.postTechArray;
var active = postTechArray.Length > 0; var active = postTechArray.Length > 0;
node.connGroup.gameObject.SetActive(active); node.connGroup.gameObject.SetActive(active);
node.connImages = active ? node.connGroup.GetComponentsInChildren<Image>(true) : []; node.connImages = active ? node.connGroup.GetComponentsInChildren<Image>(true) : [];
@@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using System.Linq;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class AccumulatorExchangeAdapter : IProductionProcessAdapter
{
public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building)
{
return recipe?.Category == ProductionRecipeCategory.Exchange ||
recipe == null && building?.Kind == ProductionBuildingKind.Exchanger;
}
public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (building != null && building.Kind != ProductionBuildingKind.Exchanger)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding,
"This building cannot charge or discharge accumulators.", recipeId: recipe?.Id ?? 0,
buildingItemId: building.ItemId);
return false;
}
if (mode != ProliferationMode.None && mode != ProliferationMode.Speedup)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"Accumulator exchange supports native speedup only.", recipeId: recipe?.Id ?? 0);
return false;
}
var speedBonus = 0.0;
if (mode != ProliferationMode.None &&
(level <= 0 || !catalog.TryGetProliferation(level, out speedBonus, out _, out _)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"The accumulator proliferation level is unavailable.", recipeId: recipe?.Id ?? 0);
return false;
}
var state = 0;
if (recipe != null)
{
if (recipe.Inputs.Count != 1 || recipe.Outputs.Count != 1 ||
recipe.Inputs.Single().Value != 1 || recipe.Outputs.Single().Value != 1)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"Accumulator exchange requires one empty/full item conversion.", recipeId: recipe.Id);
return false;
}
var inputId = recipe.Inputs.Single().Key;
var outputId = recipe.Outputs.Single().Key;
state = building == null || inputId == building.EmptyAccumulatorItemId &&
outputId == building.FullAccumulatorItemId ? 1 :
inputId == building.FullAccumulatorItemId &&
outputId == building.EmptyAccumulatorItemId ? -1 : 0;
if (state == 0)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The exchanger's accumulator items do not match the recipe.", recipeId: recipe.Id);
return false;
}
}
else if (operatingParameters == null ||
!operatingParameters.TryGetValue("Mode0", out var selectedMode) ||
!Finite(selectedMode) || selectedMode != Math.Truncate(selectedMode) ||
selectedMode < -1 || selectedMode > 1)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Provide the exchanger's native charging, discharging, or idle mode.",
buildingItemId: building?.ItemId ?? 0);
return false;
}
else
{
state = (int)selectedMode;
}
if (recipe != null && operatingParameters != null &&
operatingParameters.TryGetValue("Mode0", out var requestedMode) && requestedMode != state)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The exchanger's operating mode conflicts with the selected recipe.", recipeId: recipe.Id);
return false;
}
var inputItem = recipe?.Inputs.Single().Key ??
(state == 1 ? building.EmptyAccumulatorItemId : building.FullAccumulatorItemId);
var outputItem = recipe?.Outputs.Single().Key ??
(state == 1 ? building.FullAccumulatorItemId : building.EmptyAccumulatorItemId);
if (state != 0 && (inputItem <= 0 || outputItem <= 0))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The exchanger's accumulator items are unavailable.", buildingItemId: building?.ItemId ?? 0);
return false;
}
if (building != null && state != 0 &&
(!FinitePositive(building.ExchangeRateWatts) || !FinitePositive(building.AccumulatorEnergyJoules)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The exchanger's energy capacity is unavailable.", buildingItemId: building.ItemId);
return false;
}
var effectiveWatts = building == null || state == 0 ? 0 : building.ExchangeRateWatts * (1 + speedBonus);
var cycles = building == null ? 0 : state == 0 ? 1 :
effectiveWatts * 60 / building.AccumulatorEnergyJoules;
var inputs = state == 0 ? Array.Empty<KeyValuePair<int, double>>() :
new[] { new KeyValuePair<int, double>(inputItem, 1) };
var outputs = state == 0 ? Array.Empty<KeyValuePair<int, double>>() :
new[] { new KeyValuePair<int, double>(outputItem, 1) };
process = new ProductionProcess(recipe?.Id ?? 0, building?.ItemId ?? 0,
state == 0 ? ProliferationMode.None : mode, state == 0 ? 0 : level,
inputs, outputs, cycles, state == 1 ? effectiveWatts : building?.IdlePowerWatts ?? 0,
building != null, accumulatorChargingWatts: state == 1 ? effectiveWatts : 0,
accumulatorDischargingWatts: state == -1 ? effectiveWatts : 0,
sprayedInputsPerCycle: state == 0 ? 0 : 1,
preservedSpraysPerCycle: mode == ProliferationMode.None
? Array.Empty<KeyValuePair<int, double>>() : outputs);
return true;
}
}
@@ -0,0 +1,251 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace UXAssist.Production;
internal sealed class BlackBoxProcessGroup
{
public ProductionProcess Process { get; }
public string StableKey { get; }
public int Count { get; }
public IReadOnlyDictionary<int, double> NetPerBuilding { get; }
public bool HasJointProducts { get; }
public BlackBoxProcessGroup(ProductionProcess process, ProductionBuildingSnapshot snapshot)
{
Process = process;
Count = snapshot.Count;
var net = new Dictionary<int, double>();
foreach (var flow in process.OutputsPerCycle)
net[flow.Key] = flow.Value * process.CyclesPerBuildingPerMinute;
foreach (var flow in process.InputsPerCycle)
net[flow.Key] = (net.TryGetValue(flow.Key, out var previous) ? previous : 0) -
flow.Value * process.CyclesPerBuildingPerMinute;
NetPerBuilding = net;
HasJointProducts = net.Values.Count(value => value > BlackBoxMaterialClassifier.Tolerance) > 1;
var key = new StringBuilder();
key.Append(process.RecipeId).Append(':').Append(process.BuildingItemId).Append(':')
.Append((int)process.ProliferationMode).Append(':').Append(process.ProliferationLevel)
.Append(':').Append(snapshot.SpeedFactor?.ToString("R", CultureInfo.InvariantCulture) ?? "-");
foreach (var parameter in snapshot.OperatingParameters.OrderBy(entry => entry.Key, StringComparer.Ordinal))
key.Append('|').Append(parameter.Key.Length).Append(':').Append(parameter.Key).Append(':')
.Append(parameter.Value.ToString("R", CultureInfo.InvariantCulture));
StableKey = key.ToString();
}
}
internal sealed class BlackBoxItemClassification
{
public bool IsFinalProduct { get; }
public bool IsResearchProduct { get; }
public double IntermediateShortage { get; }
public double? OverbuildSurplus { get; }
public double? CoproductSurplus { get; }
public BlackBoxItemClassification(bool isFinalProduct, bool isResearchProduct, double intermediateShortage,
double? overbuildSurplus, double? coproductSurplus)
{
IsFinalProduct = isFinalProduct;
IsResearchProduct = isResearchProduct;
IntermediateShortage = intermediateShortage;
OverbuildSurplus = overbuildSurplus;
CoproductSurplus = coproductSurplus;
}
}
internal static class BlackBoxMaterialClassifier
{
internal const double Tolerance = 1e-9;
private const int MaximumSteadyStatePasses = 10000;
private sealed class ReductionGroup
{
public BlackBoxProcessGroup Source { get; }
public int Count { get; }
public int Removed { get; set; }
public ReductionGroup(IGrouping<string, BlackBoxProcessGroup> grouped)
{
Source = grouped.First();
Count = grouped.Sum(entry => entry.Count);
}
}
public static IReadOnlyDictionary<int, BlackBoxItemClassification> Classify(
IReadOnlyList<BlackBoxProcessGroup> processes, IReadOnlyDictionary<int, double> grossProduction,
IReadOnlyDictionary<int, double> grossConsumption, bool materialComplete,
IReadOnlyCollection<int> uncertainDemandItems, bool unknownDemand, ISet<int> researchMatrixSinks,
out IReadOnlyDictionary<int, double> steadyStateBalance)
{
var producerItems = new HashSet<int>();
var consumerItems = new HashSet<int>();
foreach (var process in processes)
{
foreach (var flow in process.NetPerBuilding)
{
if (flow.Value > Tolerance) producerItems.Add(flow.Key);
if (flow.Value < -Tolerance) consumerItems.Add(flow.Key);
}
}
var allItems = new SortedSet<int>(grossProduction.Keys);
allItems.UnionWith(grossConsumption.Keys);
var originalBalance = allItems.ToDictionary(itemId => itemId, itemId =>
(grossProduction.TryGetValue(itemId, out var produced) ? produced : 0) -
(grossConsumption.TryGetValue(itemId, out var consumed) ? consumed : 0));
var remainingBalance = new Dictionary<int, double>(originalBalance);
var finalItems = new HashSet<int>(producerItems.Where(itemId => !consumerItems.Contains(itemId)));
var intermediateItems = new HashSet<int>(producerItems.Where(consumerItems.Contains));
var protectedItems = new HashSet<int>(finalItems);
protectedItems.UnionWith(producerItems.Where(researchMatrixSinks.Contains));
if (unknownDemand) protectedItems.UnionWith(producerItems);
else protectedItems.UnionWith(uncertainDemandItems);
var groups = processes.GroupBy(process => process.StableKey, StringComparer.Ordinal)
.Select(grouped => new ReductionGroup(grouped))
.OrderBy(group => group.Source.Process.RecipeId)
.ThenBy(group => group.Source.Process.BuildingItemId)
.ThenBy(group => group.Source.StableKey, StringComparer.Ordinal).ToList();
if (materialComplete)
{
bool changed;
do
{
changed = false;
foreach (var group in groups)
{
if (!group.Source.NetPerBuilding.Values.Any(value => value > Tolerance)) continue;
while (group.Removed < group.Count && CanRemove(group.Source.NetPerBuilding, originalBalance,
remainingBalance, protectedItems, intermediateItems))
{
foreach (var flow in group.Source.NetPerBuilding)
remainingBalance[flow.Key] -= flow.Value;
group.Removed++;
changed = true;
}
}
} while (changed);
}
var classification = new Dictionary<int, BlackBoxItemClassification>();
foreach (var itemId in allItems)
{
var originalNet = originalBalance[itemId];
var isIntermediate = intermediateItems.Contains(itemId);
double? overbuild = null;
double? coproduct = null;
if (materialComplete)
{
overbuild = 0;
coproduct = 0;
if (isIntermediate && !researchMatrixSinks.Contains(itemId))
{
overbuild = Math.Min(Math.Max(0, originalNet),
Math.Max(0, originalNet - remainingBalance[itemId]));
var necessaryJointProduction = groups.Sum(group => NecessaryJointProduction(group, itemId,
originalBalance, remainingBalance, protectedItems));
var internalConsumption = groups.Sum(group =>
group.Source.NetPerBuilding.TryGetValue(itemId, out var amount) && amount < -Tolerance
? -amount * (group.Count - group.Removed) : 0);
coproduct = Math.Min(Math.Max(0, remainingBalance[itemId]),
Math.Max(0, necessaryJointProduction - internalConsumption));
}
}
var finalKnown = !unknownDemand && !uncertainDemandItems.Contains(itemId);
var isResearchProduct = finalKnown && researchMatrixSinks.Contains(itemId) && originalNet > Tolerance;
classification[itemId] = new BlackBoxItemClassification(
finalKnown && finalItems.Contains(itemId) || isResearchProduct, isResearchProduct,
isIntermediate ? Math.Max(0, -originalNet) : 0, overbuild, coproduct);
}
steadyStateBalance = CalculateSteadyStateBalance(groups, originalBalance, remainingBalance,
protectedItems);
return classification;
}
private static double NecessaryJointProduction(ReductionGroup group, int itemId,
IReadOnlyDictionary<int, double> originalBalance, IReadOnlyDictionary<int, double> remainingBalance,
ISet<int> protectedItems)
{
var retained = group.Count - group.Removed;
if (retained == 0 || !group.Source.HasJointProducts ||
!group.Source.NetPerBuilding.TryGetValue(itemId, out var production) || production <= Tolerance)
return 0;
var removable = (double)retained;
foreach (var flow in group.Source.NetPerBuilding)
{
if (flow.Key == itemId || flow.Value <= Tolerance) 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));
}
return production * (retained - removable);
}
private static IReadOnlyDictionary<int, double> CalculateSteadyStateBalance(
IReadOnlyList<ReductionGroup> groups, IReadOnlyDictionary<int, double> originalBalance,
IReadOnlyDictionary<int, double> remainingBalance, ISet<int> protectedItems)
{
var balance = remainingBalance.ToDictionary(entry => entry.Key, entry => entry.Value);
var available = groups.ToDictionary(group => group, group => (double)(group.Count - group.Removed));
// 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++)
{
var changed = false;
foreach (var group in groups)
{
if (!group.Source.NetPerBuilding.Values.Any(value => value > Tolerance)) continue;
var reducible = available[group];
foreach (var flow in group.Source.NetPerBuilding)
{
if (flow.Value <= Tolerance) continue;
var minimum = MinimumBalance(flow.Key, originalBalance, protectedItems);
reducible = Math.Min(reducible, Math.Max(0, (balance[flow.Key] - minimum) / flow.Value));
}
if (reducible <= Tolerance) continue;
foreach (var flow in group.Source.NetPerBuilding)
balance[flow.Key] -= flow.Value * reducible;
available[group] -= reducible;
changed = true;
}
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<int, double> originalBalance,
ISet<int> protectedItems)
{
return protectedItems.Contains(itemId) ? originalBalance[itemId] : Math.Min(0, originalBalance[itemId]);
}
private static bool CanRemove(IReadOnlyDictionary<int, double> netPerBuilding,
IReadOnlyDictionary<int, double> originalBalance, IReadOnlyDictionary<int, double> remainingBalance,
ISet<int> protectedItems, ISet<int> intermediateItems)
{
foreach (var flow in netPerBuilding)
{
var reduced = remainingBalance[flow.Key] - flow.Value;
if (protectedItems.Contains(flow.Key) && reduced < originalBalance[flow.Key] - Tolerance)
return false;
if (intermediateItems.Contains(flow.Key) &&
Math.Max(0, -reduced) > Math.Max(0, -originalBalance[flow.Key]) + Tolerance)
return false;
}
return true;
}
}
@@ -0,0 +1,148 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
internal static class BlueprintBottleneckBalance
{
private const double Tolerance = 1e-7;
internal static bool TryCalculate(IReadOnlyList<BlackBoxProcessGroup> processes,
IReadOnlyDictionary<int, double> production, IReadOnlyDictionary<int, double> consumption,
ISet<int> researchMatrixSinks,
out SortedDictionary<int, double> balancedProduction, out SortedDictionary<int, double> balancedConsumption,
out IReadOnlyDictionary<int, BlackBoxItemClassification> balancedClassifications,
out IReadOnlyDictionary<int, double> balancedNet)
{
balancedProduction = null;
balancedConsumption = null;
balancedClassifications = null;
balancedNet = null;
if (production.Count == 0 && consumption.Count == 0)
{
balancedProduction = new SortedDictionary<int, double>();
balancedConsumption = new SortedDictionary<int, double>();
balancedClassifications = new Dictionary<int, BlackBoxItemClassification>();
balancedNet = new Dictionary<int, double>();
return true;
}
var groups = processes.GroupBy(process => process.StableKey, StringComparer.Ordinal)
.OrderBy(group => group.Key, StringComparer.Ordinal)
.Select(group => (source: group.First(), count: group.Sum(process => process.Count))).ToArray();
var produced = new HashSet<int>(groups.SelectMany(group => group.source.NetPerBuilding)
.Where(flow => flow.Value > BlackBoxMaterialClassifier.Tolerance).Select(flow => flow.Key));
var consumed = new HashSet<int>(groups.SelectMany(group => group.source.NetPerBuilding)
.Where(flow => flow.Value < -BlackBoxMaterialClassifier.Tolerance).Select(flow => flow.Key));
var items = produced.OrderBy(itemId => itemId).ToArray();
// Normalize only the scale variable; the solver still resolves shared demand, recipe ratios, and cycles together.
var commonScale = items.Where(consumed.Contains).Select(itemId => production[itemId] / consumption[itemId])
.Aggregate(1.0, Math.Min);
var targets = items.Where(itemId => !consumed.Contains(itemId) || researchMatrixSinks.Contains(itemId))
.ToDictionary(itemId => itemId, itemId => Math.Max(0, production[itemId] -
(consumption.TryGetValue(itemId, out var amount) ? amount : 0)));
// Launchers, generators, and precise research can terminate a chain without an item output.
var sinks = Enumerable.Range(0, groups.Length).Where(index =>
groups[index].source.NetPerBuilding.Values.Any(value => value < -BlackBoxMaterialClassifier.Tolerance) &&
!groups[index].source.NetPerBuilding.Values.Any(value => value > BlackBoxMaterialClassifier.Tolerance))
.ToArray();
if (!targets.Values.Any(FinitePositive) && sinks.Length == 0) return false;
var scaleColumn = groups.Length;
var surplusStart = scaleColumn + 1;
var capacitySlackStart = surplusStart + items.Length;
var columnCount = capacitySlackStart + groups.Length + 1;
var matrix = new double[items.Length + groups.Length + 1 + sinks.Length, columnCount];
var rhs = new double[matrix.GetLength(0)];
var maximizeOutput = new double[columnCount];
var minimizeUse = new double[columnCount];
var minimizeSurplus = new double[columnCount];
maximizeOutput[scaleColumn] = -1;
for (var row = 0; row < items.Length; row++)
{
var itemId = items[row];
var rowScale = Math.Max(production[itemId], consumption.TryGetValue(itemId, out var amount) ? amount : 0);
for (var index = 0; index < groups.Length; index++)
if (groups[index].source.NetPerBuilding.TryGetValue(itemId, out var net))
matrix[row, index] = net * groups[index].count / rowScale;
if (targets.TryGetValue(itemId, out var target)) matrix[row, scaleColumn] = -target / rowScale * commonScale;
matrix[row, surplusStart + row] = -1;
minimizeSurplus[surplusStart + row] = 1;
}
for (var index = 0; index <= groups.Length; index++)
{
var row = items.Length + index;
matrix[row, index] = index < groups.Length ? 1 : commonScale;
matrix[row, capacitySlackStart + index] = 1;
rhs[row] = 1;
if (index < groups.Length) minimizeUse[index] = groups[index].count;
}
for (var index = 0; index < sinks.Length; index++)
{
var row = items.Length + groups.Length + 1 + index;
matrix[row, sinks[index]] = 1;
matrix[row, scaleColumn] = -commonScale;
}
var solution = TwoPhaseSimplex.Solve(matrix, rhs,
new[] { maximizeOutput, minimizeUse, minimizeSurplus }, 20000, CancellationToken.None);
if (solution.Status != LinearSolveStatus.Optimal || !FinitePositive(solution.Values[scaleColumn])) return false;
for (var row = 0; row < rhs.Length; row++)
{
var residual = -rhs[row];
for (var column = 0; column < columnCount; column++) residual += matrix[row, column] * solution.Values[column];
if (Math.Abs(residual) > Tolerance) return false;
}
balancedProduction = new SortedDictionary<int, double>(production.ToDictionary(flow => flow.Key, _ => 0.0));
balancedConsumption = new SortedDictionary<int, double>(consumption.ToDictionary(flow => flow.Key, _ => 0.0));
var unusedProduction = new Dictionary<int, double>();
for (var index = 0; index < groups.Length; index++)
{
var group = groups[index];
var utilized = Math.Min(1, solution.Values[index]) * group.count;
var executions = group.source.Process.CyclesPerBuildingPerMinute * utilized;
foreach (var flow in group.source.Process.OutputsPerCycle)
AddFlow(balancedProduction, flow.Key, flow.Value * executions);
foreach (var flow in group.source.Process.InputsPerCycle)
AddFlow(balancedConsumption, flow.Key, flow.Value * executions);
foreach (var flow in group.source.NetPerBuilding)
if (flow.Value > 0) AddFlow(unusedProduction, flow.Key, flow.Value * (group.count - utilized));
}
var netFlows = new Dictionary<int, double>();
var result = new Dictionary<int, BlackBoxItemClassification>();
var allItems = new SortedSet<int>(production.Keys);
allItems.UnionWith(consumption.Keys);
foreach (var itemId in allItems)
{
var grossProduced = balancedProduction.TryGetValue(itemId, out var p) ? p : 0;
var grossConsumed = balancedConsumption.TryGetValue(itemId, out var c) ? c : 0;
var net = grossProduced - grossConsumed;
if (targets.TryGetValue(itemId, out var target))
{
var required = target * solution.Values[scaleColumn] * commonScale;
if (net < required - Tolerance * Math.Max(1, required)) return false;
}
if (Math.Abs(net) <= Tolerance * Math.Max(1, Math.Max(grossProduced, grossConsumed))) net = 0;
netFlows[itemId] = net;
var intermediate = produced.Contains(itemId) && consumed.Contains(itemId);
if (intermediate && net < 0) return false;
var research = researchMatrixSinks.Contains(itemId);
var researchProduct = research && net > 0;
result[itemId] = new BlackBoxItemClassification(produced.Contains(itemId) && !consumed.Contains(itemId) || researchProduct,
researchProduct, 0,
intermediate && !research && unusedProduction.TryGetValue(itemId, out var unused) ? unused : 0,
intermediate && !research ? Math.Max(0, net) : 0);
}
balancedClassifications = result;
balancedNet = netFlows;
return true;
}
}
@@ -0,0 +1,280 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class BlueprintDescriptionLabels
{
public string FactoryPower { get; }
public string LogisticsPower { get; }
public string Missing { get; }
public string Excess { get; }
public string Unknown { get; }
public string KnownPortion { get; }
public string InputLine { get; }
public string OutputLine { get; }
public string ResearchLine { get; }
public BlueprintDescriptionLabels(string factoryPower, string logisticsPower, string missing, string excess,
string unknown, string knownPortion, string inputLine, string outputLine, string researchLine)
{
FactoryPower = factoryPower;
LogisticsPower = logisticsPower;
Missing = missing;
Excess = excess;
Unknown = unknown;
KnownPortion = knownPortion;
InputLine = inputLine;
OutputLine = outputLine;
ResearchLine = researchLine;
}
}
public sealed class BlueprintDescriptionText
{
public const int MaximumDescriptionLength = 2000;
public string Power { get; }
public string Warnings { get; }
public string Input { get; }
public string Output { get; }
public string Research { get; }
public string Description { get; }
public BlueprintDescriptionText(string power, string warnings, string input, string output, string research,
string inputLine, string outputLine, string researchLine)
{
Power = power;
Warnings = warnings;
Input = input;
Output = output;
Research = research;
var lines = new List<string>();
if (warnings.Length > 0) lines.Add(warnings);
if (input.Length > 0) lines.Add(inputLine + input);
if (output.Length > 0) lines.Add(outputLine + output);
if (research.Length > 0) lines.Add(researchLine + research);
Description = string.Join("\n", lines);
}
}
public static class BlueprintDescriptionFormatter
{
private const double Tolerance = 1e-9;
private static readonly string[] RateUnits = { "K", "M", "G" };
private static readonly string[] PowerUnits = { "W", "kW", "MW", "GW", "TW" };
public static BlueprintDescriptionText Format(ProductionReport report, Func<int, string> itemTag,
BlueprintDescriptionLabels labels)
{
if (report == null || report.Status == ProductionStatus.Failed ||
report.Status == ProductionStatus.DataNotReady)
throw new InvalidOperationException("A usable blueprint production report is required.");
if (itemTag == null) throw new ArgumentNullException(nameof(itemTag));
if (labels == null) throw new ArgumentNullException(nameof(labels));
var breakdown = report.PowerBreakdown ??
throw new InvalidOperationException("A blueprint power breakdown is required.");
var power = new List<string>();
if (breakdown.KnownFactoryConsumptionWatts > 0 || !breakdown.FactoryComplete)
power.Add(labels.FactoryPower + " " + FormatPower(breakdown.FactoryConsumptionWatts, labels));
if (breakdown.KnownLogisticsConsumptionWatts > 0 || !breakdown.LogisticsComplete)
power.Add(labels.LogisticsPower + " " + FormatPower(breakdown.LogisticsConsumptionWatts, labels));
var missing = new List<string>();
var excess = new List<string>();
var input = new List<string>();
var output = new SortedDictionary<int, double>();
var research = new SortedDictionary<int, double>();
foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
{
var shortage = Math.Min(flow.IntermediateShortage,
flow.SteadyStateExternalSupply ?? flow.RequiredExternalSupply);
if (shortage > Tolerance)
missing.Add(FormatItem(flow.ItemId, shortage, itemTag));
}
if (report.MaterialComplete)
{
foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
{
if (flow.OverbuildSurplus.GetValueOrDefault() > Tolerance)
excess.Add(FormatItem(flow.ItemId, flow.OverbuildSurplus.Value, itemTag));
}
}
foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
{
var requiredSupply = flow.SteadyStateExternalSupply ?? flow.RequiredExternalSupply;
if (requiredSupply > Tolerance && flow.IntermediateShortage <= Tolerance)
input.Add(FormatItem(flow.ItemId, requiredSupply, itemTag));
var rate = flow.IsFinalProduct ? Math.Max(0, flow.NetFlow) : 0;
if (report.MaterialComplete) rate += flow.CoproductSurplus.GetValueOrDefault();
if (rate > Tolerance)
{
if (flow.IsResearchProduct) research[flow.ItemId] = rate;
else output[flow.ItemId] = rate;
}
}
var formattedOutput = output.Select(flow => FormatItem(flow.Key, flow.Value, itemTag));
var formattedResearch = research.Select(flow => FormatItem(flow.Key, flow.Value, itemTag));
var warnings = new List<string>();
if (missing.Count > 0)
warnings.Add(labels.Missing + FormatMaterial(missing, report.MaterialComplete, labels));
if (excess.Count > 0)
warnings.Add(labels.Excess + FormatMaterial(excess, report.MaterialComplete, labels));
return new BlueprintDescriptionText(string.Join(" | ", power),
string.Join("\n", warnings),
FormatMaterial(input, report.MaterialComplete, labels),
FormatMaterial(formattedOutput, report.MaterialComplete, labels),
FormatMaterial(formattedResearch, report.MaterialComplete, labels),
labels.InputLine, labels.OutputLine, labels.ResearchLine);
}
private static string FormatMaterial(IEnumerable<string> entries, bool complete,
BlueprintDescriptionLabels labels)
{
var text = string.Join(", ", entries);
if (text.Length == 0) return "";
return complete ? text : text + " " + labels.KnownPortion;
}
private static string FormatItem(int itemId, double rate, Func<int, string> itemTag)
{
var tag = itemTag(itemId);
if (string.IsNullOrEmpty(tag))
throw new InvalidOperationException("An item in the blueprint report has no native icon tag.");
return tag + " x" + FormatRate(rate);
}
private static string FormatRate(double value)
{
var rounded = RoundForDisplay(value);
for (var unit = RateUnits.Length - 1; unit >= 0; unit--)
{
var scale = Math.Pow(1000, unit + 1);
// Keep the existing display precision; abbreviate only exact tenths of a unit.
if (rounded >= scale && rounded % (scale / 10) == 0)
return (rounded / scale).ToString("#,##0.#", CultureInfo.InvariantCulture) + RateUnits[unit];
}
return FormatNumber(value);
}
private static string FormatPower(double? watts, BlueprintDescriptionLabels labels)
{
if (!watts.HasValue) return labels.Unknown;
var value = watts.Value;
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 (!FiniteNonnegative(value))
throw new InvalidOperationException("A blueprint report contains an invalid rate or power value.");
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);
return precise != "0" ? precise : value.ToString("0.###E+0", CultureInfo.InvariantCulture);
}
}
public sealed class BlueprintDescriptionField
{
public string Title { get; }
public string Value { get; }
public IReadOnlyList<string> MatchingTitles { get; }
public BlueprintDescriptionField(string title, string value, params string[] matchingTitles)
{
Title = title;
Value = value;
MatchingTitles = Array.AsReadOnly(matchingTitles);
}
public bool Matches(string title)
{
return string.Equals(Title, title, StringComparison.Ordinal) ||
MatchingTitles.Any(candidate => string.Equals(candidate, title, StringComparison.Ordinal));
}
}
public enum BlueprintFieldUpdateResult
{
Updated,
CapacityExceeded,
InvalidFields
}
public static class BlueprintDescriptionFields
{
public static bool IsNativeFormatValid(string serialized)
{
if (string.IsNullOrEmpty(serialized)) return true;
if (!serialized.EndsWith(";", StringComparison.Ordinal)) return false;
var parts = serialized.Split(';');
for (var index = 0; index < parts.Length - 1; index++)
{
var delimiter = parts[index].IndexOf(':');
if (delimiter < 0 || parts[index].IndexOf(':', delimiter + 1) >= 0) return false;
}
return true;
}
// 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<string, string> escape, Func<string, string> unescape, out string updated)
{
updated = existing;
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 entries = new List<string>();
var replaced = false;
for (var index = 0; index < parts.Length - 1; index++)
{
if (!field.Matches(unescape(parts[index].Substring(0, parts[index].IndexOf(':')))))
{
entries.Add(parts[index]);
}
else if (generated != null && !replaced)
{
entries.Add(generated);
replaced = true;
}
}
if (generated != null && !replaced)
{
if (entries.Count >= maximumFields) return BlueprintFieldUpdateResult.CapacityExceeded;
entries.Add(generated);
}
updated = string.Concat(entries.Select(entry => entry + ";"));
return BlueprintFieldUpdateResult.Updated;
}
}
@@ -0,0 +1,549 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace UXAssist.Production;
public sealed class BlueprintSelectionContext
{
public Dictionary<int, Dictionary<string, double>> OperatingParametersByIndex { get; } =
new Dictionary<int, Dictionary<string, double>>();
public Dictionary<int, Dictionary<string, double>> OperatingParametersByObjectId { get; } =
new Dictionary<int, Dictionary<string, double>>();
}
public sealed class BlueprintSelectionCapture
{
public IReadOnlyList<ProductionBuildingSnapshot> Buildings { get; }
public IReadOnlyList<ProductionDiagnostic> Diagnostics { get; }
public BlueprintSelectionCapture(IEnumerable<ProductionBuildingSnapshot> buildings,
IEnumerable<ProductionDiagnostic> diagnostics)
{
Buildings = Array.AsReadOnly(buildings.ToArray());
Diagnostics = Array.AsReadOnly(diagnostics.ToArray());
}
public FactoryBlackBoxRequest CreateRequest(bool proliferationEnabled)
{
var request = new FactoryBlackBoxRequest { ProliferationEnabled = proliferationEnabled };
request.Buildings.AddRange(Buildings);
request.CaptureDiagnostics.AddRange(Diagnostics);
return request;
}
}
public static class BlueprintSelectionReader
{
// 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<int> selectedObjectIds,
BlueprintSelectionContext context = 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.");
var snapshots = new List<ProductionBuildingSnapshot>();
var diagnostics = new List<ProductionDiagnostic>();
var seen = new HashSet<int>();
foreach (var objectId in selectedObjectIds)
{
if (!seen.Add(objectId))
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.DuplicateSelection,
"A blueprint-selected object ID is repeated."));
continue;
}
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.", buildingItemId: protoId));
continue;
}
var operation = new Dictionary<string, double>();
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 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);
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;
}
ApplySupplied(context?.OperatingParametersByObjectId, objectId, operation);
var recipeId = building.Kind == ProductionBuildingKind.Fractionator
? GetLiveFractionationRecipe(factory, objectId) : parameters.recipeId;
snapshots.Add(CreateSnapshot(catalog, building, objectId, parameters, recipeId, speedFactor, operation,
diagnostics));
}
return new BlueprintSelectionCapture(snapshots, diagnostics);
}
public static BlueprintSelectionCapture FromBlueprint(IEnumerable<BlueprintBuilding> buildings,
BlueprintSelectionContext context = 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.");
var snapshots = new List<ProductionBuildingSnapshot>();
var diagnostics = new List<ProductionDiagnostic>();
var seen = new HashSet<int>();
foreach (var blueprint in buildings)
{
if (blueprint == null)
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"A blueprint building is missing."));
continue;
}
if (!seen.Add(blueprint.index))
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.DuplicateSelection,
"A blueprint building index is repeated."));
continue;
}
var item = LDB.items.Select(blueprint.itemId);
var model = LDB.models.Select(blueprint.modelIndex);
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 (!catalog.Buildings.TryGetValue(blueprint.itemId, out var building)) continue;
// Decode the settings the same way native blueprint paste does.
var parameters = new BuildingParameters();
parameters.CopyFromBuildPreview(new BuildPreview
{
item = item,
desc = model.prefabDesc,
recipeId = blueprint.recipeId,
filterId = blueprint.filterId,
parameters = blueprint.parameters
});
var operation = new Dictionary<string, double>();
AddSettings(parameters, operation);
if (operation.ContainsKey("ResearchMode"))
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));
}
return new BlueprintSelectionCapture(snapshots, diagnostics);
}
private static BlueprintSelectionCapture Failure(ProductionDiagnosticCode code, string message)
{
return new BlueprintSelectionCapture(Array.Empty<ProductionBuildingSnapshot>(),
new[] { new ProductionDiagnostic(code, message) });
}
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
? 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
? 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 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[StationSettingsIndex] > 0)
watts = storedParameters[StationSettingsIndex] * 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;
}
// Advanced Mining Machines store their speed with the station settings; native construction restores it.
private static void CaptureStoredMinerSpeed(BuildingParameters parameters, int[] storedParameters,
IDictionary<string, double> 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<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,
IDictionary<string, double> operation)
{
if (objectId <= 0) return null;
ref var entity = ref factory.entityPool[objectId];
var system = factory.factorySystem;
if (type == BuildingType.Assembler && entity.assemblerId > 0 && system?.assemblerPool != null &&
entity.assemblerId < system.assemblerPool.Length &&
system.assemblerPool[entity.assemblerId].id == entity.assemblerId)
return system.assemblerPool[entity.assemblerId].speed / 10000.0;
if (type == BuildingType.Lab && entity.labId > 0 && system?.labPool != null &&
entity.labId < system.labPool.Length && system.labPool[entity.labId].id == entity.labId)
{
ref var lab = ref system.labPool[entity.labId];
if (lab.researchMode && lab.techId > 0) operation["TechId"] = lab.techId;
return lab.speed / 10000.0;
}
return null;
}
private static int GetLiveFractionationRecipe(PlanetFactory factory, int objectId)
{
if (objectId <= 0 || factory.factorySystem?.fractionatorPool == null) return 0;
var fractionatorId = factory.entityPool[objectId].fractionatorId;
var pool = factory.factorySystem.fractionatorPool;
return fractionatorId > 0 && fractionatorId < pool.Length && pool[fractionatorId].id == fractionatorId
? FindFractionationRecipe(pool[fractionatorId].fluidId) : 0;
}
private static void CaptureMiningSettings(PlanetFactory factory, int objectId, ProductionBuilding building,
IDictionary<string, double> operation)
{
var history = factory.gameData?.history;
if (history != null) operation["MiningSpeedMultiplier"] = history.miningSpeedScale;
if (building.MinerKind == ProductionMinerKind.Water && factory.planet?.waterItemId > 0)
operation["ResourceItemId"] = factory.planet.waterItemId;
if (objectId <= 0 || factory.factorySystem?.minerPool == null) return;
var minerId = factory.entityPool[objectId].minerId;
var pool = factory.factorySystem.minerPool;
if (minerId <= 0 || minerId >= pool.Length || pool[minerId].id != minerId) return;
ref var miner = ref pool[minerId];
operation["MachineSpeedFactor"] = miner.speed / ProductionUnits.FixedPointScale;
if (building.MinerKind == ProductionMinerKind.Water || miner.veinCount <= 0 ||
miner.veins == null || miner.veinCount > miner.veins.Length || factory.veinPool == null) return;
var resourceItemId = 0;
for (var index = 0; index < miner.veinCount; index++)
{
var veinId = miner.veins[index];
if (veinId <= 0 || veinId >= factory.veinPool.Length ||
factory.veinPool[veinId].id != veinId || factory.veinPool[veinId].productId <= 0 ||
resourceItemId != 0 && resourceItemId != factory.veinPool[veinId].productId) return;
resourceItemId = factory.veinPool[veinId].productId;
}
operation["ResourceItemId"] = resourceItemId;
if (building.MinerKind == ProductionMinerKind.Vein)
operation["VeinCount"] = miner.veinCount;
else if (building.MinerKind == ProductionMinerKind.Oil)
operation["OilUnits"] = factory.veinPool[miner.veins[0]].amount * VeinData.oilSpeedMultiplier;
}
private static void CaptureCollectionSettings(PlanetFactory factory,
IDictionary<string, double> operation)
{
var planet = factory.planet;
if (planet?.gasItems == null || planet.gasSpeeds == null ||
planet.gasItems.Length != planet.gasSpeeds.Length) return;
operation["GasCount"] = planet.gasItems.Length;
operation["GasTotalHeat"] = planet.gasTotalHeat;
if (factory.gameData?.history != null)
operation["MiningSpeedMultiplier"] = factory.gameData.history.miningSpeedScale;
for (var index = 0; index < planet.gasItems.Length; index++)
{
operation[$"GasItemId{index}"] = planet.gasItems[index];
operation[$"GasSpeedPerSecond{index}"] = planet.gasSpeeds[index];
}
}
private static void CaptureResearchSettings(PlanetFactory factory,
IDictionary<string, double> operation)
{
var history = factory.gameData?.history;
if (history == null) return;
operation["ResearchSpeed"] = history.techSpeed;
if (!operation.ContainsKey("TechId") && history.currentTech > 0)
operation["TechId"] = history.currentTech;
}
private static void CaptureFuelSettings(PlanetFactory factory, int objectId,
IDictionary<string, double> operation)
{
if (objectId <= 0 || factory.powerSystem?.genPool == null) return;
var generatorId = factory.entityPool[objectId].powerGenId;
var pool = factory.powerSystem.genPool;
if (generatorId <= 0 || generatorId >= pool.Length || pool[generatorId].id != generatorId) return;
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,
IDictionary<string, double> operation)
{
if (factory.gameData?.history != null)
operation["SolarEnergyLossRate"] = factory.gameData.history.solarEnergyLossRate;
if (objectId <= 0 || factory.powerSystem?.genPool == null) return;
var generatorId = factory.entityPool[objectId].powerGenId;
var pool = factory.powerSystem.genPool;
if (generatorId <= 0 || generatorId >= pool.Length || pool[generatorId].id != generatorId) return;
ref var generator = ref pool[generatorId];
operation["Mode0"] = generator.productId;
operation["LensItemId"] = generator.catalystPoint > 0 || generator.catalystCount > 0
? generator.catalystPoint > 0 && generator.curCatalystId > 0
? generator.curCatalystId : generator.catalystId : 0;
}
private static void CaptureLaunchSettings(PlanetFactory factory, int objectId,
ProductionBuildingKind kind, IDictionary<string, double> operation)
{
if (objectId <= 0 || factory.factorySystem == null) return;
ref var entity = ref factory.entityPool[objectId];
var system = factory.factorySystem;
if (kind == ProductionBuildingKind.Silo)
{
var siloId = entity.siloId;
if (system.siloPool == null || siloId <= 0 || siloId >= system.siloPool.Length ||
system.siloPool[siloId].id != siloId) return;
operation[SandboxBoost.EnabledKey] = system.siloPool[siloId].boost ? 1 : 0;
operation["LaunchAvailable"] = factory.dysonSphere != null &&
factory.dysonSphere.GetAutoNodeCount() > 0 ? 1 : 0;
return;
}
var ejectorId = entity.ejectorId;
if (system.ejectorPool == null || ejectorId <= 0 || ejectorId >= system.ejectorPool.Length ||
system.ejectorPool[ejectorId].id != ejectorId) return;
ref var ejector = ref system.ejectorPool[ejectorId];
operation[SandboxBoost.EnabledKey] = ejector.boost ? 1 : 0;
var swarm = factory.dysonSphere?.swarm;
operation["LaunchAvailable"] = 0;
if (swarm?.orbits == null) return;
if (ejector.autoOrbit)
{
for (var orbitId = 1; orbitId < swarm.orbitCursor; orbitId++)
{
if (swarm.orbits[orbitId].id != orbitId || !swarm.orbits[orbitId].enabled) continue;
operation["LaunchAvailable"] = 1;
break;
}
}
else if (ejector.orbitId > 0 && ejector.orbitId < swarm.orbitCursor &&
swarm.orbits[ejector.orbitId].id == ejector.orbitId &&
swarm.orbits[ejector.orbitId].enabled)
{
operation["LaunchAvailable"] = 1;
}
}
private static int FindFractionationRecipe(int inputItemId)
{
var recipes = RecipeProto.fractionatorRecipes;
if (inputItemId <= 0 || recipes == null) return 0;
foreach (var recipe in recipes)
{
if (recipe.Items.Length == 1 && recipe.Items[0] == inputItemId) return recipe.ID;
}
return 0;
}
private static void AddSettings(BuildingParameters parameters, IDictionary<string, double> operation)
{
operation["Mode0"] = parameters.mode0;
operation["Mode1"] = parameters.mode1;
if (parameters.type == BuildingType.Lab && parameters.mode0 == 2)
operation["ResearchMode"] = 1;
}
private static void ReportMissingSettings(ProductionBuilding building, BuildingParameters parameters,
IReadOnlyDictionary<string, double> operation, ICollection<ProductionDiagnostic> diagnostics)
{
var kind = building.Kind;
var researchNeedsTechnology = parameters.type == BuildingType.Lab && parameters.mode0 == 2 &&
(!operation.TryGetValue("ResearchMatrixSink", out var matrixSink) || matrixSink != 1);
var requiredKey = researchNeedsTechnology ? "TechId" :
kind == ProductionBuildingKind.Miner ? "ResourceItemId" :
kind == ProductionBuildingKind.Collector ? "GasCount" :
kind == ProductionBuildingKind.FuelGenerator ? "FuelItemId" :
kind == ProductionBuildingKind.Fractionator ? "CirculatingItemsPerMinute" : null;
if (requiredKey != null && !operation.ContainsKey(requiredKey))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
$"The selected building needs the {requiredKey} operating parameter.",
buildingItemId: building.ItemId));
if (researchNeedsTechnology && !operation.ContainsKey("ResearchSpeed"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The research lab needs the current research technology speed.",
buildingItemId: building.ItemId));
if (kind == ProductionBuildingKind.Fractionator && !operation.ContainsKey("StackSize"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"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: building.ItemId));
if (!operation.ContainsKey("SolarEnergyLossRate"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The receiver needs the solar energy loss technology setting.",
buildingItemId: building.ItemId));
}
if (kind == ProductionBuildingKind.Collector)
{
if (!operation.ContainsKey("GasTotalHeat") ||
!operation.ContainsKey("MiningSpeedMultiplier"))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The collector needs the planet's gas energy and current mining technology speed.",
buildingItemId: building.ItemId));
if (operation.TryGetValue("GasCount", out var count) && count > 0 && count <= 16 &&
count == Math.Truncate(count))
{
for (var index = 0; index < (int)count; index++)
{
if (operation.ContainsKey($"GasItemId{index}") &&
operation.ContainsKey($"GasSpeedPerSecond{index}")) continue;
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
$"The collector needs gas item and speed for resource {index}.",
buildingItemId: building.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: 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: building.ItemId));
}
}
private static ProliferationMode GetMode(ProductionCatalog catalog, BuildingParameters parameters)
{
if (parameters.type != BuildingType.Assembler && parameters.type != BuildingType.Lab)
return ProliferationMode.None;
var recipeId = parameters.recipeId;
var filterId = parameters.filterId;
var mode0 = parameters.mode0;
var mode1 = parameters.mode1;
if (parameters.type == BuildingType.Assembler)
BuildingParameters.SimpleParamFromParamsArray(parameters.type, parameters.parameters,
ref recipeId, ref filterId, ref mode0, ref mode1);
return mode1 == 1 || catalog.Recipes.TryGetValue(recipeId, out var recipe) && !recipe.Productive
? ProliferationMode.Speedup : ProliferationMode.ExtraProducts;
}
}
@@ -0,0 +1,378 @@
using System;
using System.Collections.Generic;
using System.Linq;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class ProductionBuildingSnapshot
{
public int ObjectId { get; }
public int BuildingItemId { get; }
public int RecipeId { get; }
public int Count { get; }
public ProliferationMode ProliferationMode { get; }
public double? SpeedFactor { get; }
public IReadOnlyDictionary<string, double> OperatingParameters { get; }
public ProductionBuildingSnapshot(int objectId, int buildingItemId, int recipeId, int count,
ProliferationMode proliferationMode, double? speedFactor = null,
IEnumerable<KeyValuePair<string, double>> operatingParameters = null)
{
ObjectId = objectId;
BuildingItemId = buildingItemId;
RecipeId = recipeId;
Count = count;
ProliferationMode = proliferationMode;
SpeedFactor = speedFactor;
OperatingParameters = new System.Collections.ObjectModel.ReadOnlyDictionary<string, double>(
operatingParameters?.ToDictionary(entry => entry.Key, entry => entry.Value) ??
new Dictionary<string, double>());
}
}
public enum BlueprintProductionBasis
{
FinalProducts,
BottleneckIntermediate
}
public sealed class FactoryBlackBoxRequest
{
public List<ProductionBuildingSnapshot> Buildings { get; } = new List<ProductionBuildingSnapshot>();
public List<ProductionDiagnostic> CaptureDiagnostics { get; } = new List<ProductionDiagnostic>();
public bool ProliferationEnabled { get; set; }
public BlueprintProductionBasis ProductionBasis { get; set; }
}
public sealed class FactoryBlackBoxAnalyzer
{
private readonly ProductionCatalog _catalog;
private readonly ProcessEvaluator _evaluator;
public FactoryBlackBoxAnalyzer(ProductionCatalog catalog, ProcessEvaluator evaluator = null)
{
_catalog = catalog;
_evaluator = evaluator ?? new ProcessEvaluator();
}
public ProductionReport Analyze(FactoryBlackBoxRequest request)
{
if (_catalog == null)
return ProductionReport.Failure(new ProductionDiagnostic(ProductionDiagnosticCode.DataNotReady,
"Production data is not loaded."));
if (request == null)
return ProductionReport.Failure(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"A building selection is required."));
var diagnostics = new List<ProductionDiagnostic>(request.CaptureDiagnostics);
var groups = new List<ProductionGroupFlow>();
var processGroups = new List<BlackBoxProcessGroup>();
var grossProduction = new SortedDictionary<int, double>();
var grossConsumption = new SortedDictionary<int, double>();
var producers = new Dictionary<int, List<int>>();
var consumers = new Dictionary<int, List<int>>();
var hasResearchMatrixSink = false;
var uncertainDemandItems = new HashSet<int>();
var selectedIds = new HashSet<int>();
var skippedSelection = diagnostics.Any(diagnostic =>
diagnostic.Code == ProductionDiagnosticCode.InvalidRequest ||
diagnostic.Code == ProductionDiagnosticCode.UnknownItem ||
diagnostic.Code == ProductionDiagnosticCode.DataNotReady);
var unknownDemand = skippedSelection;
var materialComplete = !skippedSelection;
var factoryPowerComplete = !skippedSelection;
var logisticsPowerComplete = !skippedSelection;
var totalPowerKnown = !skippedSelection;
var factoryConsumptionWatts = 0.0;
var logisticsConsumptionWatts = 0.0;
var generationWatts = 0.0;
var chargingWatts = 0.0;
var dischargingWatts = 0.0;
var dysonRequirementWatts = 0.0;
foreach (var snapshot in request.Buildings)
{
if (snapshot == null || snapshot.Count <= 0)
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"A selected building has an invalid count."));
materialComplete = false;
factoryPowerComplete = false;
logisticsPowerComplete = false;
unknownDemand = true;
continue;
}
if (snapshot.ObjectId != 0 && !selectedIds.Add(snapshot.ObjectId))
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.DuplicateSelection,
"A selected building was already included.", buildingItemId: snapshot.BuildingItemId));
continue;
}
if (!_catalog.Buildings.TryGetValue(snapshot.BuildingItemId, out var building))
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The selected building is not supported by the catalog.",
buildingItemId: snapshot.BuildingItemId));
materialComplete = false;
factoryPowerComplete = false;
logisticsPowerComplete = false;
unknownDemand = true;
continue;
}
if (snapshot.RecipeId != 0 &&
snapshot.OperatingParameters.TryGetValue("ResearchMode", out var activeResearchMode) &&
activeResearchMode > 0)
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"A research-mode lab cannot also run a manufacturing recipe.",
recipeId: snapshot.RecipeId, buildingItemId: snapshot.BuildingItemId));
materialComplete = false;
factoryPowerComplete = false;
logisticsPowerComplete = false;
unknownDemand = true;
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 (!FiniteNonnegative(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) logisticsConsumptionWatts += logisticsWatts.Value;
else logisticsPowerComplete = false;
groups.Add(PowerOnlyGroup(snapshot.Count, logisticsWatts));
continue;
}
if (snapshot.RecipeId == 0 && (building.Kind == ProductionBuildingKind.Ordinary ||
building.Kind == ProductionBuildingKind.Auxiliary))
{
if (building.Kind == ProductionBuildingKind.Auxiliary ||
!snapshot.OperatingParameters.TryGetValue("ResearchMode", out var researchMode) ||
researchMode <= 0)
{
var idleWatts = (building.Kind == ProductionBuildingKind.Auxiliary
? building.WorkingPowerWatts : building.IdlePowerWatts) * snapshot.Count;
factoryConsumptionWatts += idleWatts;
groups.Add(PowerOnlyGroup(snapshot.Count, idleWatts));
continue;
}
}
ProductionRecipe recipe = null;
if (snapshot.RecipeId != 0 && !_catalog.Recipes.TryGetValue(snapshot.RecipeId, out recipe))
{
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.UnknownRecipe,
"The selected building's recipe is missing.", recipeId: snapshot.RecipeId,
buildingItemId: snapshot.BuildingItemId));
materialComplete = false;
factoryPowerComplete = false;
unknownDemand = true;
continue;
}
if (snapshot.SpeedFactor.HasValue) building = building.WithSpeedFactor(snapshot.SpeedFactor.Value);
var mode = request.ProliferationEnabled
? FullProliferationMode(building, snapshot) : ProliferationMode.None;
if (IsResearchModeLab(building, snapshot) && _catalog.MaximumProliferationLevel == 0)
mode = ProliferationMode.None;
var researchMatrixSink = IsResearchModeLab(building, snapshot) &&
snapshot.OperatingParameters.TryGetValue("ResearchMatrixSink", out var sinkSetting) &&
sinkSetting == 1 && _catalog.ResearchMatrixItemIds.Count > 0;
if (researchMatrixSink) hasResearchMatrixSink = true;
if (!_evaluator.TryEvaluate(_catalog, recipe, building, mode,
mode == ProliferationMode.None ? 0 : _catalog.MaximumProliferationLevel,
snapshot.OperatingParameters, out var process, out var diagnostic))
{
diagnostics.Add(diagnostic);
if (building.Kind != ProductionBuildingKind.RenewableGenerator && !researchMatrixSink)
materialComplete = false;
if (recipe != null) uncertainDemandItems.UnionWith(recipe.Inputs.Keys);
else if (building.Kind != ProductionBuildingKind.Miner &&
building.Kind != ProductionBuildingKind.Collector &&
building.Kind != ProductionBuildingKind.RenewableGenerator && !researchMatrixSink)
unknownDemand = true;
if (TryGetConsumptionWithoutMaterials(building, snapshot, diagnostic, mode,
out var knownWatts))
{
if (!IsResearchModeLab(building, snapshot)) totalPowerKnown = false;
factoryConsumptionWatts += knownWatts;
groups.Add(PowerOnlyGroup(snapshot.Count, knownWatts));
}
else
{
totalPowerKnown = false;
factoryPowerComplete = false;
}
continue;
}
if (diagnostic != null) diagnostics.Add(diagnostic);
if (!process.PowerKnown) totalPowerKnown = false;
if (!FiniteNonnegative(process.WorkingPowerWatts * snapshot.Count)) factoryPowerComplete = false;
var cycleRate = process.CyclesPerBuildingPerMinute;
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)
{
AddFlow(grossProduction, flow.Key, flow.Value);
AddGroup(producers, flow.Key, groupIndex);
}
foreach (var flow in input)
{
AddFlow(grossConsumption, flow.Key, flow.Value);
AddGroup(consumers, flow.Key, groupIndex);
}
var watts = process.WorkingPowerWatts * snapshot.Count;
factoryConsumptionWatts += watts;
generationWatts += process.GenerationWatts * snapshot.Count;
chargingWatts += process.AccumulatorChargingWatts * snapshot.Count;
dischargingWatts += process.AccumulatorDischargingWatts * snapshot.Count;
dysonRequirementWatts += (process.DysonSphereRequirementWatts ?? 0) * snapshot.Count;
groups.Add(new ProductionGroupFlow(process, snapshot.Count, cycleRate * snapshot.Count,
snapshot.Count, snapshot.Count, watts, watts, output, input,
process.GenerationWatts * snapshot.Count, process.AccumulatorChargingWatts * snapshot.Count,
process.AccumulatorDischargingWatts * snapshot.Count,
process.DysonSphereRequirementWatts * snapshot.Count,
cycleRate * snapshot.Count * process.LaunchesPerCycle,
cycleRate * snapshot.Count * process.ResearchHashesPerCycle));
processGroups.Add(new BlackBoxProcessGroup(process, snapshot));
}
var matrixSinkItems = hasResearchMatrixSink
? new HashSet<int>(_catalog.ResearchMatrixItemIds) : new HashSet<int>();
IReadOnlyDictionary<int, BlackBoxItemClassification> classifications = null;
IReadOnlyDictionary<int, double> steadyStateBalance = null;
if (request.ProductionBasis == BlueprintProductionBasis.BottleneckIntermediate)
{
if (!materialComplete || !BlueprintBottleneckBalance.TryCalculate(processGroups,
grossProduction, grossConsumption, matrixSinkItems,
out var balancedProduction, out var balancedConsumption, out var balancedClassifications,
out var balancedNet))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.BlueprintBasisUnavailable,
"A complete material selection with a feasible final output is required for the bottleneck basis."));
else
{
grossProduction = balancedProduction;
grossConsumption = balancedConsumption;
classifications = balancedClassifications;
steadyStateBalance = balancedNet;
}
}
if (classifications == null)
classifications = BlackBoxMaterialClassifier.Classify(processGroups, grossProduction, grossConsumption,
materialComplete, uncertainDemandItems, unknownDemand, matrixSinkItems, out steadyStateBalance);
var flows = new List<ProductionItemFlow>();
var allItems = new SortedSet<int>(grossProduction.Keys);
allItems.UnionWith(grossConsumption.Keys);
foreach (var itemId in allItems)
{
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 classification = classifications[itemId];
flows.Add(new ProductionItemFlow(itemId, produced, consumed, 0, 0, 0,
Math.Max(0, net), Math.Max(0, -net), classification.IsFinalProduct,
producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty<int>(),
consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty<int>(),
classification.IntermediateShortage, classification.OverbuildSurplus,
classification.CoproductSurplus, Math.Max(0, -steadyStateBalance[itemId]),
classification.IsResearchProduct));
}
var powerComplete = factoryPowerComplete && logisticsPowerComplete && totalPowerKnown;
var consumptionWatts = factoryConsumptionWatts + logisticsConsumptionWatts;
var power = powerComplete ? new ProductionPower(consumptionWatts, consumptionWatts, generationWatts,
chargingWatts, dischargingWatts, dysonRequirementWatts,
ProductionPowerScope.SelectedFacilities) : null;
var status = materialComplete && powerComplete && diagnostics.Count == 0
? ProductionStatus.Complete : materialComplete || powerComplete || groups.Count > 0
? ProductionStatus.Partial : ProductionStatus.Failed;
return new ProductionReport(status, materialComplete, powerComplete, flows, groups, diagnostics, power,
new ProductionPowerBreakdown(factoryConsumptionWatts, logisticsConsumptionWatts,
factoryPowerComplete, logisticsPowerComplete));
}
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 bool TryGetConsumptionWithoutMaterials(ProductionBuilding building,
ProductionBuildingSnapshot snapshot, ProductionDiagnostic diagnostic, ProliferationMode mode,
out double watts)
{
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 &&
!_catalog.TryGetProliferation(_catalog.MaximumProliferationLevel, out _, out _, out multiplier))
return false;
watts = building.WorkingPowerWatts * multiplier * snapshot.Count;
return FinitePositive(watts);
}
if (diagnostic?.Code != ProductionDiagnosticCode.MissingOperatingParameter) return false;
if (building.Kind == ProductionBuildingKind.Collector) return true;
if (building.Kind != ProductionBuildingKind.Miner) return false;
var speed = snapshot.OperatingParameters.TryGetValue("MachineSpeedFactor", out var capturedSpeed)
? capturedSpeed : 1;
if (!FinitePositive(speed)) return false;
var ratio = speed * speed;
watts = (building.WorkingPowerWatts * ratio + building.IdlePowerWatts * (1 - ratio)) * snapshot.Count;
return FiniteNonnegative(watts);
}
private static bool IsResearchModeLab(ProductionBuilding building, ProductionBuildingSnapshot snapshot)
{
return building.Kind == ProductionBuildingKind.Ordinary &&
building.Category == ProductionRecipeCategory.Research && snapshot.RecipeId == 0 &&
snapshot.OperatingParameters.TryGetValue("ResearchMode", out var researchMode) && researchMode == 1;
}
private static ProductionGroupFlow PowerOnlyGroup(int count, double? watts)
{
return new ProductionGroupFlow(null, count, 0, count, count, watts, watts,
Array.Empty<KeyValuePair<int, double>>(), Array.Empty<KeyValuePair<int, double>>());
}
}
@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class FractionationProcessAdapter : IProductionProcessAdapter
{
public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building)
{
return recipe?.Category == ProductionRecipeCategory.Fractionate;
}
public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (recipe.Inputs.Count != 1 || recipe.Outputs.Count != 1 ||
!FinitePositive(recipe.Inputs.Values.Single()) ||
!FinitePositive(recipe.Outputs.Values.Single()) ||
mode != ProliferationMode.None && mode != ProliferationMode.Speedup)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"Fractionation requires one input, one output, and the native acceleration mode.",
recipeId: recipe.Id);
return false;
}
if (building != null && building.Kind != ProductionBuildingKind.Fractionator)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding,
"The selected building cannot fractionate items.", recipeId: recipe.Id,
buildingItemId: building.ItemId);
return false;
}
var speedBonus = 0.0;
var powerMultiplier = 1.0;
if (mode == ProliferationMode.Speedup &&
(level <= 0 || !catalog.TryGetProliferation(level, out speedBonus, out _, out powerMultiplier)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"The fractionator's proliferation level is unavailable.", recipeId: recipe.Id);
return false;
}
var throughput = 0.0;
if (building != null)
{
if (operatingParameters == null ||
!operatingParameters.TryGetValue("CirculatingItemsPerMinute", out throughput) ||
!operatingParameters.TryGetValue("StackSize", out var stackSize) ||
!FinitePositive(throughput) || !FinitePositive(stackSize) ||
stackSize > 4 || throughput > stackSize * 30 * ProductionUnits.SecondsPerMinute + 1e-9)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Provide circulating items per minute and a valid stack size for the fractionator.",
recipeId: recipe.Id, buildingItemId: building.ItemId);
return false;
}
}
var input = recipe.Inputs.Single();
var output = recipe.Outputs.Single();
var probability = Math.Min(1, output.Value / input.Value * (1 + speedBonus));
var throughputPerSecond = throughput / ProductionUnits.SecondsPerMinute;
var watts = building == null ? 0 : building.WorkingPowerWatts *
(1 + Math.Max(0, throughputPerSecond - 30) * 0.05) * powerMultiplier;
process = new ProductionProcess(recipe.Id, building?.ItemId ?? 0, mode,
mode == ProliferationMode.None ? 0 : level,
new[] { new KeyValuePair<int, double>(input.Key, probability) },
new[] { new KeyValuePair<int, double>(output.Key, probability) },
throughput, watts, building != null, throughput);
return true;
}
}
@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class FuelGenerationAdapter : IProductionProcessAdapter
{
public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building)
{
return recipe == null && building?.Kind == ProductionBuildingKind.FuelGenerator;
}
public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (operatingParameters == null ||
!operatingParameters.TryGetValue("FuelItemId", out var fuelId) || !PositiveId(fuelId) ||
!catalog.Items.TryGetValue((int)fuelId, out var fuel) ||
fuel.HeatValueJoules <= 0 || (fuel.FuelTypeMask & building.FuelMask) == 0)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Select a fuel item compatible with the generator's native fuel mask.",
buildingItemId: building.ItemId);
return false;
}
if (mode != ProliferationMode.None && mode != ProliferationMode.Speedup &&
mode != ProliferationMode.ExtraProducts ||
mode == ProliferationMode.ExtraProducts && !fuel.ProductiveFuel)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"The fuel cannot use the requested proliferation mode.", buildingItemId: building.ItemId);
return false;
}
if (!FinitePositive(building.FuelUseWatts) || !FinitePositive(building.RatedGenerationWatts))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The generator's fuel consumption or power rating is unavailable.",
buildingItemId: building.ItemId);
return false;
}
var speedBonus = 0.0;
var extraBonus = 0.0;
if (mode != ProliferationMode.None &&
(level <= 0 || !catalog.TryGetProliferation(level, out speedBonus, out extraBonus, out _)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"The fuel's proliferation level is unavailable.", buildingItemId: building.ItemId);
return false;
}
var boostFactor = 1.0;
var boostModeKey = SandboxBoost.ModeKey(building);
if (boostModeKey != null)
{
if (!SandboxBoost.TryResolve(operatingParameters, boostModeKey, building.ItemId, out var boosted,
out diagnostic))
return false;
// 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 :
fuel.ProductiveFuel ? 1 + extraBonus : 1 + speedBonus;
var generation = building.RatedGenerationWatts * proliferationFactor * boostFactor;
var burnedFuel = building.FuelUseWatts * (fuel.ProductiveFuel ? 1 : proliferationFactor) *
boostFactor * 60 / fuel.HeatValueJoules;
if (!Finite(generation) || !FinitePositive(burnedFuel))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected fuel produces an invalid generation rate.", buildingItemId: building.ItemId);
return false;
}
process = new ProductionProcess(0, building.ItemId,
mode == ProliferationMode.None ? mode : fuel.ProductiveFuel
? ProliferationMode.ExtraProducts : ProliferationMode.Speedup,
mode == ProliferationMode.None ? 0 : level,
new[] { new KeyValuePair<int, double>(fuel.Id, 1) },
Array.Empty<KeyValuePair<int, double>>(), burnedFuel,
building.WorkingPowerWatts, true, generationWatts: generation);
return true;
}
}
@@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class GasCollectionAdapter : IProductionProcessAdapter
{
public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building)
{
return building?.Kind == ProductionBuildingKind.Collector;
}
public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (recipe != null || mode != ProliferationMode.None)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding,
"Gas collection has no recipe or native proliferation mode.",
recipeId: recipe?.Id ?? 0, buildingItemId: building.ItemId);
return false;
}
if (operatingParameters == null ||
!operatingParameters.TryGetValue("GasCount", out var gasCount) ||
gasCount < 1 || gasCount > 16 || gasCount != Math.Truncate(gasCount) ||
!operatingParameters.TryGetValue("GasTotalHeat", out var totalHeat) ||
!FiniteNonnegative(totalHeat) ||
!operatingParameters.TryGetValue("MiningSpeedMultiplier", out var miningSpeed) ||
!FinitePositive(miningSpeed) || building.CollectorSpeedMultiplier <= 0 ||
!FiniteNonnegative(building.WorkingPowerWatts))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Provide the planet's gas composition, total fuel energy, mining speed and collector speed.",
buildingItemId: building.ItemId);
return false;
}
var workCost = building.WorkingPowerWatts / building.CollectorSpeedMultiplier;
var recovery = totalHeat == 0 ? 1 : 1 - workCost / totalHeat;
if (recovery == 0) recovery = 1;
var techRate = totalHeat - workCost <= 0 ? 1 :
(miningSpeed * totalHeat - workCost) / (totalHeat - workCost);
if (!FinitePositive(recovery) || !FinitePositive(techRate))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected gas flow cannot sustain the collector's native energy consumption.",
buildingItemId: building.ItemId);
return false;
}
var outputs = new List<KeyValuePair<int, double>>();
for (var index = 0; index < (int)gasCount; index++)
{
if (!operatingParameters.TryGetValue($"GasItemId{index}", out var itemId) || !PositiveId(itemId) ||
!catalog.Items.ContainsKey((int)itemId) ||
!operatingParameters.TryGetValue($"GasSpeedPerSecond{index}", out var gasSpeed) ||
!FiniteNonnegative(gasSpeed))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Each collected gas needs a valid item ID and native gas speed.",
buildingItemId: building.ItemId);
return false;
}
var rate = gasSpeed * ProductionUnits.SecondsPerMinute *
building.CollectorSpeedMultiplier * recovery * techRate;
if (!FiniteNonnegative(rate))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"A gas production rate is outside the supported range.",
itemId: (int)itemId, buildingItemId: building.ItemId);
return false;
}
if (rate > 0) outputs.Add(new KeyValuePair<int, double>((int)itemId, rate));
}
process = new ProductionProcess(0, building.ItemId, ProliferationMode.None, 0,
Array.Empty<KeyValuePair<int, double>>(), outputs,
1, 0, true);
return true;
}
}
+102
View File
@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class LaunchProcessAdapter : IProductionProcessAdapter
{
public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building)
{
return building?.Kind == ProductionBuildingKind.Ejector || building?.Kind == ProductionBuildingKind.Silo;
}
public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (recipe != null)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding,
"Launchers consume ammunition without producing a recipe item.", recipeId: recipe.Id,
buildingItemId: building.ItemId);
return false;
}
if (mode != ProliferationMode.None && mode != ProliferationMode.Speedup)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"Launch ammunition supports native speedup only.", buildingItemId: building.ItemId);
return false;
}
if (operatingParameters == null ||
!operatingParameters.TryGetValue("LaunchAvailable", out var launchAvailable) ||
(launchAvailable != 0 && launchAvailable != 1))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Specify whether a usable orbit or Dyson-sphere node is available.",
buildingItemId: building.ItemId);
return false;
}
if (launchAvailable == 0)
{
process = new ProductionProcess(0, building.ItemId, ProliferationMode.None, 0,
Array.Empty<KeyValuePair<int, double>>(), Array.Empty<KeyValuePair<int, double>>(),
1, building.IdlePowerWatts, true);
return true;
}
if (building.LaunchChargeTicks <= 0 || building.LaunchCooldownTicks <= 0 ||
building.AmmunitionItemId <= 0 || !catalog.Items.ContainsKey(building.AmmunitionItemId))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The launcher's native ammunition or cycle timings are unavailable.",
buildingItemId: building.ItemId);
return false;
}
if (!SandboxBoost.TryResolve(operatingParameters, SandboxBoost.ModeKey(building), building.ItemId,
out var boosted, out diagnostic))
return false;
var speedBonus = 0.0;
var powerMultiplier = 1.0;
if (mode != ProliferationMode.None &&
(level <= 0 || !catalog.TryGetProliferation(level, out speedBonus, out _, out powerMultiplier)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"The launch ammunition's proliferation level is unavailable.",
buildingItemId: building.ItemId);
return false;
}
var nativeStep = Math.Truncate(10000 * (1 + speedBonus) + 0.1) * (boosted ? 10 : 1);
if (!FinitePositive(nativeStep))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The launcher's native speed is outside the supported range.", buildingItemId: building.ItemId);
return false;
}
var cycleTicks = Math.Ceiling(building.LaunchChargeTicks * 10000.0 / nativeStep) +
Math.Ceiling(building.LaunchCooldownTicks * 10000.0 / nativeStep);
var launchesPerMinute = 3600.0 / cycleTicks;
if (!FinitePositive(launchesPerMinute))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The launcher cycle is outside the supported range.", buildingItemId: building.ItemId);
return false;
}
process = new ProductionProcess(0, building.ItemId, mode,
mode == ProliferationMode.None ? 0 : level,
new[] { new KeyValuePair<int, double>(building.AmmunitionItemId, 1) },
Array.Empty<KeyValuePair<int, double>>(), launchesPerMinute,
building.WorkingPowerWatts * powerMultiplier, true, launchesPerCycle: 1);
return true;
}
}
@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class MiningProcessAdapter : IProductionProcessAdapter
{
public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building)
{
return recipe == null && building?.Kind == ProductionBuildingKind.Miner;
}
public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (building.MiningPeriodTicks <= 0 || building.MinerKind == ProductionMinerKind.None)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The mining building has no native period or resource type.", buildingItemId: building.ItemId);
return false;
}
if (operatingParameters == null ||
!operatingParameters.TryGetValue("ResourceItemId", out var outputId) ||
!PositiveId(outputId) || !catalog.Items.ContainsKey((int)outputId) ||
!operatingParameters.TryGetValue("MiningSpeedMultiplier", out var miningSpeed) ||
!FinitePositive(miningSpeed))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Provide the resource item and mining technology speed.", buildingItemId: building.ItemId);
return false;
}
var resourceFactor = 1.0;
if (building.MinerKind == ProductionMinerKind.Vein &&
(!operatingParameters.TryGetValue("VeinCount", out resourceFactor) ||
resourceFactor != Math.Truncate(resourceFactor) || !FinitePositive(resourceFactor)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Provide the number of covered veins.", buildingItemId: building.ItemId);
return false;
}
if (building.MinerKind == ProductionMinerKind.Oil &&
(!operatingParameters.TryGetValue("OilUnits", out resourceFactor) ||
!FinitePositive(resourceFactor)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Provide the covered oil well's native flow factor.", buildingItemId: building.ItemId);
return false;
}
var machineSpeed = 1.0;
if (operatingParameters.TryGetValue("MachineSpeedFactor", out var suppliedSpeed))
{
if (!FinitePositive(suppliedSpeed))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The miner speed factor must be positive.", buildingItemId: building.ItemId);
return false;
}
machineSpeed = suppliedSpeed;
}
// 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 * resourceFactor;
var powerRatio = machineSpeed * machineSpeed;
var workingWatts = building.WorkingPowerWatts * powerRatio +
building.IdlePowerWatts * (1 - powerRatio);
if (!FinitePositive(perMinute) || !FiniteNonnegative(workingWatts))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The mineral output rate or power demand is outside the supported range.",
buildingItemId: building.ItemId);
return false;
}
process = new ProductionProcess(0, building.ItemId, ProliferationMode.None, 0,
Array.Empty<KeyValuePair<int, double>>(),
new[] { new KeyValuePair<int, double>((int)outputId, 1) },
perMinute, workingWatts, true);
return true;
}
}
+122
View File
@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class ProcessEvaluator
{
private readonly IProductionProcessAdapter[] _adapters;
public ProcessEvaluator(IEnumerable<IProductionProcessAdapter> adapters = null)
{
_adapters = (adapters ?? Array.Empty<IProductionProcessAdapter>())
.Concat(new IProductionProcessAdapter[]
{
new FractionationProcessAdapter(),
new AccumulatorExchangeAdapter(),
new RenewableGenerationAdapter(),
new MiningProcessAdapter(),
new FuelGenerationAdapter(),
new RayReceiverAdapter(),
new LaunchProcessAdapter(),
new GasCollectionAdapter(),
new ResearchProcessAdapter()
}).ToArray();
}
public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (catalog == null)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.DataNotReady, "Production data is not loaded.");
return false;
}
foreach (var adapter in _adapters)
{
if (adapter.CanEvaluate(recipe, building))
return adapter.TryEvaluate(catalog, recipe, building, mode, level, operatingParameters,
out process, out diagnostic);
}
if (recipe == null)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"No process adapter supports the selected building without a recipe.",
buildingItemId: building?.ItemId ?? 0);
return false;
}
// 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,
buildingItemId: building?.ItemId ?? 0);
return false;
}
if (building != null && (building.Category != recipe.Category || !FinitePositive(building.SpeedFactor) ||
!FiniteNonnegative(building.WorkingPowerWatts)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding,
"The selected building cannot execute this recipe.", recipeId: recipe.Id,
buildingItemId: building.ItemId);
return false;
}
if (recipe.TimeTicks <= 0 || !ValidFlows(recipe.Inputs) || !ValidFlows(recipe.Outputs) ||
!Enum.IsDefined(typeof(ProliferationMode), mode))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The recipe or proliferation mode is invalid.", recipeId: recipe.Id);
return false;
}
var speedBonus = 0.0;
var extraBonus = 0.0;
var powerMultiplier = 1.0;
if (mode != ProliferationMode.None)
{
if (recipe.Inputs.Count == 0 || level < 1 ||
!catalog.TryGetProliferation(level, out speedBonus, out extraBonus,
out powerMultiplier) ||
mode == ProliferationMode.ExtraProducts && !recipe.Productive)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"The selected proliferation mode or level is unavailable for this recipe.", recipeId: recipe.Id);
return false;
}
}
var outputMultiplier = mode == ProliferationMode.ExtraProducts ? 1 + extraBonus : 1;
var cycleMultiplier = mode == ProliferationMode.Speedup ? 1 + speedBonus : 1;
var cycles = building == null ? 0 :
ProductionUnits.TicksPerMinute * building.SpeedFactor / recipe.TimeTicks * cycleMultiplier;
var power = building == null ? 0 : building.WorkingPowerWatts * powerMultiplier;
process = new ProductionProcess(recipe.Id, building?.ItemId ?? 0, mode,
mode == ProliferationMode.None ? 0 : level, recipe.Inputs,
recipe.Outputs.Select(output => new KeyValuePair<int, double>(output.Key, output.Value * outputMultiplier)),
cycles, power, building != null);
return true;
}
private static bool IsOrdinary(ProductionRecipeCategory category)
{
return category == ProductionRecipeCategory.Assemble || category == ProductionRecipeCategory.Smelt ||
category == ProductionRecipeCategory.Chemical || category == ProductionRecipeCategory.Refine ||
category == ProductionRecipeCategory.Particle || category == ProductionRecipeCategory.Research;
}
private static bool ValidFlows(IReadOnlyDictionary<int, double> flows)
{
return flows.All(flow => flow.Key > 0 && FinitePositive(flow.Value));
}
}
@@ -0,0 +1,246 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UXAssist.Common;
using UXAssist.Common.GameConstants;
using GameLogicProc = UXAssist.Common.GameLogic;
namespace UXAssist.Production;
public static class ProductionCatalogReader
{
public static ProductionCatalog Capture()
{
var itemProtos = LDB.items?.dataArray;
var recipeProtos = LDB.recipes?.dataArray;
if (itemProtos == null || itemProtos.Length == 0 || recipeProtos == null || recipeProtos.Length == 0)
return null;
var naturalItems = new HashSet<int>();
if (LDB.veins?.dataArray != null)
{
foreach (var vein in LDB.veins.dataArray)
{
if (vein != null && vein.MiningItem > 0) naturalItems.Add(vein.MiningItem);
}
}
var proliferators = new HashSet<int>();
var buildings = new List<ProductionBuilding>();
foreach (var item in itemProtos)
{
if (item?.prefabDesc == null) continue;
var prefab = item.prefabDesc;
if (prefab.isSpraycoster && prefab.incItemId != null)
proliferators.UnionWith(prefab.incItemId);
var category = prefab.isLab ? ProductionRecipeCategory.Research :
prefab.isAssembler ? MapCategory(prefab.assemblerRecipeType) : ProductionRecipeCategory.None;
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,
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 :
prefab.photovoltaic ? RenewablePowerSource.Solar :
prefab.geothermal ? RenewablePowerSource.Geothermal : RenewablePowerSource.None,
prefab.minerType == EMinerType.Vein ? ProductionMinerKind.Vein :
prefab.minerType == EMinerType.Oil ? ProductionMinerKind.Oil :
prefab.minerType == EMinerType.Water ? ProductionMinerKind.Water : ProductionMinerKind.None,
prefab.minerPeriod, prefab.fuelMask, prefab.useFuelPerTick * 60.0,
prefab.powerProductId, prefab.powerProductHeat, prefab.powerCatalystMask,
prefab.isEjector ? prefab.ejectorChargeFrame : prefab.siloChargeFrame,
prefab.isEjector ? prefab.ejectorColdFrame : prefab.siloColdFrame,
prefab.isEjector ? prefab.ejectorBulletId : prefab.siloBulletId,
prefab.stationCollectSpeed));
}
var defaultRecipes = new Dictionary<int, (int recipeId, int resultIndex)>();
var recipes = new List<ProductionRecipe>();
foreach (var recipe in recipeProtos)
{
if (recipe == null || recipe.Items == null || recipe.ItemCounts == null ||
recipe.Results == null || recipe.ResultCounts == null ||
recipe.Items.Length != recipe.ItemCounts.Length ||
recipe.Results.Length != recipe.ResultCounts.Length) continue;
recipes.Add(new ProductionRecipe(recipe.ID, MapCategory(recipe.Type), recipe.TimeSpend, recipe.productive,
PairFlows(recipe.Items, recipe.ItemCounts), PairFlows(recipe.Results, recipe.ResultCounts),
recipe.Explicit));
// 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);
}
}
AddSpecialRecipes(itemProtos, buildings, recipes, defaultRecipes);
var items = new List<ProductionItem>();
foreach (var item in itemProtos)
{
if (item == null) continue;
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),
ItemIds.DarkFogItemIds.Contains(item.ID), isProliferator ? item.Ability : 0,
isProliferator ? item.HpMax : 0, item.HeatValue, item.FuelType,
item.Productive, item.ID == ItemIds.StrangeAnnihilationFuelRod ? 2 : 1,
item.CatalystType, item.CatalystType > 0 ? item.Ability * 0.01 : 0));
}
var matrixIds = new HashSet<int>(LabComponent.matrixIds);
var technologies = new List<ProductionTechnology>();
if (LDB.techs?.dataArray != null)
{
foreach (var tech in LDB.techs.dataArray)
{
if (tech == null || !tech.IsLabTech || tech.Items == null || tech.ItemPoints == null ||
tech.Items.Length != tech.ItemPoints.Length) continue;
var requirements = new Dictionary<int, double>();
for (var index = 0; index < tech.Items.Length; index++)
{
if (matrixIds.Contains(tech.Items[index]))
requirements[tech.Items[index]] = tech.ItemPoints[index];
}
technologies.Add(new ProductionTechnology(tech.ID, requirements));
}
}
return new ProductionCatalog(items, recipes, buildings,
(double[])Cargo.accTableMilli.Clone(), (double[])Cargo.incTableMilli.Clone(),
(double[])Cargo.powerTableRatio.Clone(), technologies, matrixIds);
}
private static void AddSpecialRecipes(IEnumerable<ItemProto> itemProtos,
IEnumerable<ProductionBuilding> buildings, ICollection<ProductionRecipe> recipes,
IDictionary<int, (int recipeId, int resultIndex)> defaultRecipes)
{
var itemIds = new HashSet<int>(itemProtos.Where(item => item != null).Select(item => item.ID));
var recipeIds = new HashSet<int>(recipes.Select(recipe => recipe.Id));
foreach (var building in buildings.OrderBy(building => building.ItemId))
{
var inputItemId = 0;
int outputItemId;
ProductionRecipeCategory category;
if (building.Kind == ProductionBuildingKind.Exchanger)
{
inputItemId = building.EmptyAccumulatorItemId;
outputItemId = building.FullAccumulatorItemId;
category = ProductionRecipeCategory.Exchange;
if (inputItemId <= 0 || inputItemId == outputItemId || !itemIds.Contains(inputItemId)) continue;
}
else if (building.Kind == ProductionBuildingKind.RayReceiver)
{
outputItemId = building.PowerProductItemId;
category = ProductionRecipeCategory.PhotonStore;
}
else
{
continue;
}
if (outputItemId <= 0 || !itemIds.Contains(outputItemId) || !recipeIds.Add(-outputItemId)) continue;
var inputs = inputItemId == 0 ? Array.Empty<KeyValuePair<int, double>>() :
new[] { new KeyValuePair<int, double>(inputItemId, 1) };
recipes.Add(new ProductionRecipe(-outputItemId, category, 1, false, inputs,
new[] { new KeyValuePair<int, double>(outputItemId, 1) }));
if (!defaultRecipes.ContainsKey(outputItemId)) defaultRecipes[outputItemId] = (-outputItemId, 0);
}
}
private static IEnumerable<KeyValuePair<int, double>> PairFlows(int[] itemIds, int[] counts)
{
for (var index = 0; index < itemIds.Length; index++)
yield return new KeyValuePair<int, double>(itemIds[index], counts[index]);
}
private static ProductionRecipeCategory MapCategory(ERecipeType type)
{
switch (type)
{
case ERecipeType.Smelt: return ProductionRecipeCategory.Smelt;
case ERecipeType.Chemical: return ProductionRecipeCategory.Chemical;
case ERecipeType.Refine: return ProductionRecipeCategory.Refine;
case ERecipeType.Assemble: return ProductionRecipeCategory.Assemble;
case ERecipeType.Particle: return ProductionRecipeCategory.Particle;
case ERecipeType.Research: return ProductionRecipeCategory.Research;
case ERecipeType.Fractionate: return ProductionRecipeCategory.Fractionate;
case ERecipeType.Exchange: return ProductionRecipeCategory.Exchange;
case ERecipeType.PhotonStore: return ProductionRecipeCategory.PhotonStore;
default: return ProductionRecipeCategory.None;
}
}
private static ProductionBuildingKind ClassifyBuilding(PrefabDesc prefab)
{
if (prefab.isLab || prefab.isAssembler) return ProductionBuildingKind.Ordinary;
if (prefab.isFractionator) return ProductionBuildingKind.Fractionator;
if (prefab.isPowerExchanger) return ProductionBuildingKind.Exchanger;
if (prefab.gammaRayReceiver) return ProductionBuildingKind.RayReceiver;
if (prefab.minerType != EMinerType.None) return ProductionBuildingKind.Miner;
if (prefab.isCollectStation) return ProductionBuildingKind.Collector;
if (prefab.isEjector) return ProductionBuildingKind.Ejector;
if (prefab.isSilo) return ProductionBuildingKind.Silo;
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.isPowerCharger)
return ProductionBuildingKind.Auxiliary;
return ProductionBuildingKind.Ordinary;
}
}
public static class ProductionCatalogService
{
private static ProductionCatalog _current;
private static bool _initialized;
public static ProductionCatalog Current => _current;
public static event Action Changed;
public static void Init()
{
if (_initialized) return;
_initialized = true;
GameLogicProc.OnDataLoaded += Rebuild;
GameLogicProc.OnGameBegin += Rebuild;
GameLogicProc.OnGameEnd += Clear;
}
public static void Uninit()
{
if (!_initialized) return;
_initialized = false;
GameLogicProc.OnDataLoaded -= Rebuild;
GameLogicProc.OnGameBegin -= Rebuild;
GameLogicProc.OnGameEnd -= Clear;
Clear();
}
public static void Rebuild()
{
_current = ProductionCatalogReader.Capture();
Changed.InvokeSafe(UXAssist.Logger, nameof(Changed));
}
private static void Clear()
{
if (_current == null) return;
_current = null;
Changed.InvokeSafe(UXAssist.Logger, nameof(Changed));
}
}
+407
View File
@@ -0,0 +1,407 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace UXAssist.Production;
public enum ProductionRecipeCategory
{
None,
Smelt,
Chemical,
Refine,
Assemble,
Particle,
Research,
Fractionate,
Exchange,
PhotonStore
}
internal static class ProductionUnits
{
internal const double SecondsPerMinute = 60;
internal const double TicksPerSecond = 60;
internal const double TicksPerMinute = SecondsPerMinute * TicksPerSecond;
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<int, double> flows, int itemId, double amount)
{
flows[itemId] = (flows.TryGetValue(itemId, out var previous) ? previous : 0) + amount;
}
internal static Dictionary<int, double> ScaleFlows(IReadOnlyDictionary<int, double> flows, double factor)
{
return flows.ToDictionary(flow => flow.Key, flow => flow.Value * factor);
}
internal static void AddGroup(IDictionary<int, List<int>> groups, int itemId, int groupIndex)
{
if (!groups.TryGetValue(itemId, out var indices))
{
indices = new List<int>();
groups[itemId] = indices;
}
indices.Add(groupIndex);
}
}
public enum ProliferationMode
{
None,
Speedup,
ExtraProducts
}
public enum ProductionBuildingKind
{
Ordinary,
Fractionator,
Exchanger,
RayReceiver,
Miner,
Collector,
FuelGenerator,
RenewableGenerator,
Ejector,
Silo,
Auxiliary,
Logistics
}
public enum RenewablePowerSource
{
None,
Wind,
Solar,
Geothermal
}
public enum ProductionMinerKind
{
None,
Vein,
Oil,
Water
}
public enum ProductionDiagnosticCode
{
DataNotReady,
UnknownItem,
UnknownRecipe,
MissingBuilding,
IncompatibleBuilding,
UnsupportedProcess,
UnsupportedProliferation,
InvalidRequest,
DuplicateSelection,
MissingOperatingParameter,
Infeasible,
Unbounded,
IterationLimit,
Cancelled,
ConservationFailure,
BlueprintBasisUnavailable
}
public sealed class ProductionDiagnostic
{
public ProductionDiagnosticCode Code { get; }
public string Message { get; }
public int ItemId { get; }
public int RecipeId { get; }
public int BuildingItemId { get; }
public ProductionDiagnostic(ProductionDiagnosticCode code, string message, int itemId = 0, int recipeId = 0,
int buildingItemId = 0)
{
Code = code;
Message = message;
ItemId = itemId;
RecipeId = recipeId;
BuildingItemId = buildingItemId;
}
}
public sealed class ProductionItem
{
public int Id { get; }
public int DefaultRecipeId { get; }
public bool IsNatural { get; }
public bool IsDarkFogMaterial { get; }
public int ProliferationLevel { get; }
public int SpraysPerItem { get; }
public long HeatValueJoules { get; }
public int FuelTypeMask { get; }
public bool ProductiveFuel { get; }
public double StarOutputMultiplier { get; }
public int CatalystTypeMask { get; }
public double CatalystAbilityMultiplier { get; }
public ProductionItem(int id, int defaultRecipeId, bool isNatural, bool isDarkFogMaterial,
int proliferationLevel, int spraysPerItem, long heatValueJoules = 0, int fuelTypeMask = 0,
bool productiveFuel = false, double starOutputMultiplier = 1, int catalystTypeMask = 0,
double catalystAbilityMultiplier = 0)
{
Id = id;
DefaultRecipeId = defaultRecipeId;
IsNatural = isNatural;
IsDarkFogMaterial = isDarkFogMaterial;
ProliferationLevel = proliferationLevel;
SpraysPerItem = spraysPerItem;
HeatValueJoules = heatValueJoules;
FuelTypeMask = fuelTypeMask;
ProductiveFuel = productiveFuel;
StarOutputMultiplier = starOutputMultiplier;
CatalystTypeMask = catalystTypeMask;
CatalystAbilityMultiplier = catalystAbilityMultiplier;
}
}
public sealed class ProductionRecipe
{
public int Id { get; }
public bool IsSynthetic => Id < 0;
public ProductionRecipeCategory Category { get; }
public int TimeTicks { get; }
public bool Productive { get; }
// Native RecipeProto.Explicit, set for named recipes such as the rare-resource alternatives.
public bool Explicit { get; }
public IReadOnlyDictionary<int, double> Inputs { get; }
public IReadOnlyDictionary<int, double> Outputs { get; }
public ProductionRecipe(int id, ProductionRecipeCategory category, int timeTicks, bool productive,
IEnumerable<KeyValuePair<int, double>> inputs, IEnumerable<KeyValuePair<int, double>> outputs,
bool explicitRecipe = false)
{
Id = id;
Category = category;
TimeTicks = timeTicks;
Productive = productive;
Explicit = explicitRecipe;
Inputs = CopyFlows(inputs);
Outputs = CopyFlows(outputs);
}
internal static IReadOnlyDictionary<int, double> CopyFlows(IEnumerable<KeyValuePair<int, double>> flows)
{
var result = new Dictionary<int, double>();
foreach (var flow in flows)
{
result[flow.Key] = result.TryGetValue(flow.Key, out var count) ? count + flow.Value : flow.Value;
}
return new ReadOnlyDictionary<int, double>(result);
}
}
public sealed class ProductionTechnology
{
public int Id { get; }
public IReadOnlyDictionary<int, double> MatrixPointsPerHash { get; }
public ProductionTechnology(int id, IEnumerable<KeyValuePair<int, double>> matrixPointsPerHash)
{
Id = id;
MatrixPointsPerHash = ProductionRecipe.CopyFlows(matrixPointsPerHash);
}
}
public sealed class ProductionBuilding
{
public int ItemId { get; }
public ProductionRecipeCategory Category { get; }
public double SpeedFactor { get; }
public double WorkingPowerWatts { get; }
public double IdlePowerWatts { get; }
public ProductionBuildingKind Kind { get; }
public double RatedGenerationWatts { get; }
public double ExchangeRateWatts { get; }
public double AccumulatorEnergyJoules { get; }
public int EmptyAccumulatorItemId { get; }
public int FullAccumulatorItemId { get; }
public RenewablePowerSource RenewableSource { get; }
public ProductionMinerKind MinerKind { get; }
public int MiningPeriodTicks { get; }
public int FuelMask { get; }
public double FuelUseWatts { get; }
public int PowerProductItemId { get; }
public double PowerProductEnergyJoules { get; }
public int CatalystMask { get; }
public int LaunchChargeTicks { get; }
public int LaunchCooldownTicks { get; }
public int AmmunitionItemId { get; }
public int CollectorSpeedMultiplier { get; }
public ProductionBuilding(int itemId, ProductionRecipeCategory category, double speedFactor,
double workingPowerWatts, double idlePowerWatts,
ProductionBuildingKind kind = ProductionBuildingKind.Ordinary, double ratedGenerationWatts = 0,
double exchangeRateWatts = 0, double accumulatorEnergyJoules = 0,
int emptyAccumulatorItemId = 0, int fullAccumulatorItemId = 0,
RenewablePowerSource renewableSource = RenewablePowerSource.None,
ProductionMinerKind minerKind = ProductionMinerKind.None, int miningPeriodTicks = 0,
int fuelMask = 0, double fuelUseWatts = 0, int powerProductItemId = 0,
double powerProductEnergyJoules = 0, int catalystMask = 0,
int launchChargeTicks = 0, int launchCooldownTicks = 0, int ammunitionItemId = 0,
int collectorSpeedMultiplier = 0)
{
ItemId = itemId;
Category = category;
SpeedFactor = speedFactor;
WorkingPowerWatts = workingPowerWatts;
IdlePowerWatts = idlePowerWatts;
Kind = kind;
RatedGenerationWatts = ratedGenerationWatts;
ExchangeRateWatts = exchangeRateWatts;
AccumulatorEnergyJoules = accumulatorEnergyJoules;
EmptyAccumulatorItemId = emptyAccumulatorItemId;
FullAccumulatorItemId = fullAccumulatorItemId;
RenewableSource = renewableSource;
MinerKind = minerKind;
MiningPeriodTicks = miningPeriodTicks;
FuelMask = fuelMask;
FuelUseWatts = fuelUseWatts;
PowerProductItemId = powerProductItemId;
PowerProductEnergyJoules = powerProductEnergyJoules;
CatalystMask = catalystMask;
LaunchChargeTicks = launchChargeTicks;
LaunchCooldownTicks = launchCooldownTicks;
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
{
private readonly double[] _speedBonus;
private readonly double[] _extraBonus;
private readonly double[] _powerMultiplier;
public IReadOnlyDictionary<int, ProductionItem> Items { get; }
public IReadOnlyDictionary<int, ProductionRecipe> Recipes { get; }
public IReadOnlyDictionary<int, ProductionBuilding> Buildings { get; }
public IReadOnlyDictionary<int, ProductionTechnology> Technologies { get; }
public IReadOnlyCollection<int> ResearchMatrixItemIds { get; }
public int MaximumProliferationLevel { get; }
public ProductionCatalog(IEnumerable<ProductionItem> items, IEnumerable<ProductionRecipe> recipes,
IEnumerable<ProductionBuilding> buildings, double[] speedBonus, double[] extraBonus, double[] powerMultiplier,
IEnumerable<ProductionTechnology> technologies = null, IEnumerable<int> researchMatrixItemIds = null)
{
Items = new ReadOnlyDictionary<int, ProductionItem>(items.ToDictionary(item => item.Id));
Recipes = new ReadOnlyDictionary<int, ProductionRecipe>(recipes.ToDictionary(recipe => recipe.Id));
Buildings = new ReadOnlyDictionary<int, ProductionBuilding>(buildings.ToDictionary(building => building.ItemId));
Technologies = new ReadOnlyDictionary<int, ProductionTechnology>(
(technologies ?? Array.Empty<ProductionTechnology>()).ToDictionary(tech => tech.Id));
ResearchMatrixItemIds = Array.AsReadOnly((researchMatrixItemIds ?? Array.Empty<int>())
.Where(itemId => Items.ContainsKey(itemId)).Distinct().OrderBy(itemId => itemId).ToArray());
_speedBonus = (double[])speedBonus.Clone();
_extraBonus = (double[])extraBonus.Clone();
_powerMultiplier = (double[])powerMultiplier.Clone();
MaximumProliferationLevel = Items.Values.Where(item => item.SpraysPerItem > 0)
.Select(item => item.ProliferationLevel).DefaultIfEmpty(0).Max();
}
public bool TryGetProliferation(int level, out double speedBonus, out double extraBonus,
out double powerMultiplier)
{
speedBonus = 0;
extraBonus = 0;
powerMultiplier = 1;
if (level < 0 || level >= _speedBonus.Length || level >= _extraBonus.Length ||
level >= _powerMultiplier.Length) return false;
speedBonus = _speedBonus[level];
extraBonus = _extraBonus[level];
powerMultiplier = _powerMultiplier[level];
return true;
}
}
public sealed class ProductionProcess
{
public int RecipeId { get; }
public int BuildingItemId { get; }
public ProliferationMode ProliferationMode { get; }
public int ProliferationLevel { get; }
public IReadOnlyDictionary<int, double> InputsPerCycle { get; }
public IReadOnlyDictionary<int, double> OutputsPerCycle { get; }
public double CyclesPerBuildingPerMinute { get; }
public double WorkingPowerWatts { get; }
public bool HasBuilding { get; }
public double CirculatingItemsPerBuildingPerMinute { get; }
public double GenerationWatts { get; }
public double AccumulatorChargingWatts { get; }
public double AccumulatorDischargingWatts { get; }
public double? DysonSphereRequirementWatts { get; }
public double SprayedInputsPerCycle { get; }
public IReadOnlyDictionary<int, double> PreservedSpraysPerCycle { get; }
public bool PowerKnown { get; }
public double LaunchesPerCycle { get; }
public double ResearchHashesPerCycle { get; }
public ProductionProcess(int recipeId, int buildingItemId, ProliferationMode proliferationMode,
int proliferationLevel, IEnumerable<KeyValuePair<int, double>> inputsPerCycle,
IEnumerable<KeyValuePair<int, double>> outputsPerCycle, double cyclesPerBuildingPerMinute,
double workingPowerWatts, bool hasBuilding, double circulatingItemsPerBuildingPerMinute = 0,
double generationWatts = 0, double accumulatorChargingWatts = 0,
double accumulatorDischargingWatts = 0, double? dysonSphereRequirementWatts = 0,
double? sprayedInputsPerCycle = null, bool powerKnown = true, double launchesPerCycle = 0,
double researchHashesPerCycle = 0,
IEnumerable<KeyValuePair<int, double>> preservedSpraysPerCycle = null)
{
RecipeId = recipeId;
BuildingItemId = buildingItemId;
ProliferationMode = proliferationMode;
ProliferationLevel = proliferationLevel;
InputsPerCycle = ProductionRecipe.CopyFlows(inputsPerCycle);
OutputsPerCycle = ProductionRecipe.CopyFlows(outputsPerCycle);
CyclesPerBuildingPerMinute = cyclesPerBuildingPerMinute;
WorkingPowerWatts = workingPowerWatts;
HasBuilding = hasBuilding;
CirculatingItemsPerBuildingPerMinute = circulatingItemsPerBuildingPerMinute;
GenerationWatts = generationWatts;
AccumulatorChargingWatts = accumulatorChargingWatts;
AccumulatorDischargingWatts = accumulatorDischargingWatts;
DysonSphereRequirementWatts = dysonSphereRequirementWatts;
SprayedInputsPerCycle = sprayedInputsPerCycle ?? InputsPerCycle.Values.Sum();
PreservedSpraysPerCycle = ProductionRecipe.CopyFlows(
preservedSpraysPerCycle ?? Array.Empty<KeyValuePair<int, double>>());
PowerKnown = powerKnown;
LaunchesPerCycle = launchesPerCycle;
ResearchHashesPerCycle = researchHashesPerCycle;
}
}
public interface IProductionProcessAdapter
{
bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building);
bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic);
}
@@ -0,0 +1,36 @@
using System.Collections.Generic;
namespace UXAssist.Production;
public sealed class ProductionTarget
{
public int ItemId { get; }
public double ItemsPerMinute { get; }
public ProductionTarget(int itemId, double itemsPerMinute)
{
ItemId = itemId;
ItemsPerMinute = itemsPerMinute;
}
}
public sealed class ProductionPlanRequest
{
public List<ProductionTarget> Targets { get; } = new List<ProductionTarget>();
public HashSet<int> ExternalMaterials { get; } = new HashSet<int>();
public Dictionary<int, int> RecipeByItem { get; } = new Dictionary<int, int>();
public Dictionary<int, ProliferationMode> ProliferationModeByItem { get; } =
new Dictionary<int, ProliferationMode>();
public Dictionary<int, int> BuildingByRecipe { get; } = new Dictionary<int, int>();
public Dictionary<ProductionRecipeCategory, int> BuildingByCategory { get; } =
new Dictionary<ProductionRecipeCategory, int>();
public Dictionary<int, double> KnownExternalSurplus { get; } = new Dictionary<int, double>();
public HashSet<int> SprayDeliveredItems { get; } = new HashSet<int>();
public Dictionary<int, Dictionary<string, double>> OperatingParametersByRecipe { get; } =
new Dictionary<int, Dictionary<string, double>>();
public List<ProductionBuildingSnapshot> AuxiliaryBuildings { get; } = new List<ProductionBuildingSnapshot>();
public bool ProliferationEnabled { get; set; }
public int ProliferatorItemId { get; set; }
public bool SelfSprayProliferator { get; set; }
public int IterationBudget { get; set; } = 20000;
}
@@ -0,0 +1,202 @@
using System;
using System.Collections.Generic;
using System.Linq;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed partial class ProductionPlanner
{
private ProductionReport BuildReport(ProductionPlanRequest request, IDictionary<int, double> targets, int[] rows,
ProductionProcess[] processes, int[] importItems, double[] solution, int importStart, int surplusStart,
int proliferatorItemId, double spraysPerBottle, List<ProductionDiagnostic> warnings,
int[] reusableSprayItems, int sprayCreditStart)
{
var remainingSprayCredits = new Dictionary<int, double>();
for (var index = 0; index < reusableSprayItems.Length; index++)
remainingSprayCredits[reusableSprayItems[index]] = solution[sprayCreditStart + index];
var grossProduction = new Dictionary<int, double>();
var grossConsumption = new Dictionary<int, double>();
var producers = new Dictionary<int, List<int>>();
var consumers = new Dictionary<int, List<int>>();
var groups = new List<ProductionGroupFlow>();
var activeRecipes = new HashSet<int>();
var powerComplete = true;
var factoryPowerComplete = true;
var workingPower = 0.0;
var peakPower = 0.0;
var generationWatts = 0.0;
var chargingWatts = 0.0;
var dischargingWatts = 0.0;
var dysonRequirementWatts = 0.0;
for (var index = 0; index < processes.Length; index++)
{
var executions = solution[index];
if (executions <= 1e-9) continue;
var process = processes[index];
activeRecipes.Add(process.RecipeId);
var output = ScaleFlows(process.OutputsPerCycle, executions);
var input = ScaleFlows(process.InputsPerCycle, executions);
if (proliferatorItemId > 0 && SpraysInputs(process))
{
var sprays = process.SprayedInputsPerCycle * executions;
foreach (var itemId in reusableSprayItems)
{
var reused = Math.Min(remainingSprayCredits[itemId],
SprayedInputAmount(process, itemId) * executions);
remainingSprayCredits[itemId] -= reused;
sprays -= reused;
}
if (sprays > 0) AddFlow(input, proliferatorItemId, sprays / spraysPerBottle);
}
var groupIndex = groups.Count;
foreach (var flow in output)
{
AddFlow(grossProduction, flow.Key, flow.Value);
AddGroup(producers, flow.Key, groupIndex);
}
foreach (var flow in input)
{
AddFlow(grossConsumption, flow.Key, flow.Value);
AddGroup(consumers, flow.Key, groupIndex);
}
double? equivalentBuildings = null;
int? deploymentCount = null;
double? consumedWatts = null;
double? peakWatts = null;
if (process.HasBuilding && process.CyclesPerBuildingPerMinute > 0)
{
equivalentBuildings = executions / process.CyclesPerBuildingPerMinute;
if (!process.PowerKnown) powerComplete = false;
if (equivalentBuildings.Value > int.MaxValue || double.IsInfinity(equivalentBuildings.Value))
{
powerComplete = false;
factoryPowerComplete = false;
warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The rounded deployment count exceeds the supported range.", recipeId: process.RecipeId));
}
else
{
deploymentCount = Math.Max(1, (int)Math.Ceiling(equivalentBuildings.Value - 1e-9));
consumedWatts = equivalentBuildings.Value * process.WorkingPowerWatts;
peakWatts = deploymentCount.Value * process.WorkingPowerWatts;
if (!FiniteNonnegative(consumedWatts.Value)) factoryPowerComplete = false;
workingPower += consumedWatts.Value;
peakPower += peakWatts.Value;
generationWatts += equivalentBuildings.Value * process.GenerationWatts;
chargingWatts += equivalentBuildings.Value * process.AccumulatorChargingWatts;
dischargingWatts += equivalentBuildings.Value * process.AccumulatorDischargingWatts;
dysonRequirementWatts += equivalentBuildings.Value * (process.DysonSphereRequirementWatts ?? 0);
}
}
else
{
powerComplete = false;
factoryPowerComplete = false;
if (!warnings.Any(warning => warning.RecipeId == process.RecipeId &&
(warning.Code == ProductionDiagnosticCode.MissingBuilding ||
warning.Code == ProductionDiagnosticCode.IncompatibleBuilding)))
warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingBuilding,
"Select a building to calculate power for this recipe.", recipeId: process.RecipeId));
}
groups.Add(new ProductionGroupFlow(process, equivalentBuildings ?? 0, executions, equivalentBuildings,
deploymentCount, consumedWatts, peakWatts, output, input,
equivalentBuildings * process.GenerationWatts,
equivalentBuildings * process.AccumulatorChargingWatts,
equivalentBuildings * process.AccumulatorDischargingWatts,
equivalentBuildings * process.DysonSphereRequirementWatts,
executions * process.LaunchesPerCycle,
executions * process.ResearchHashesPerCycle));
}
var auxiliaryIds = new HashSet<int>();
foreach (var auxiliary in request.AuxiliaryBuildings)
{
if (auxiliary == null || auxiliary.Count <= 0 || auxiliary.RecipeId != 0)
{
powerComplete = false;
factoryPowerComplete = false;
warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"Auxiliary power requires a positive building count and no production recipe."));
continue;
}
if (auxiliary.ObjectId != 0 && !auxiliaryIds.Add(auxiliary.ObjectId))
{
warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.DuplicateSelection,
"An auxiliary building was selected more than once.",
buildingItemId: auxiliary.BuildingItemId));
continue;
}
if (!_catalog.Buildings.TryGetValue(auxiliary.BuildingItemId, out var building) ||
building.Kind != ProductionBuildingKind.Auxiliary ||
!FiniteNonnegative(building.WorkingPowerWatts * auxiliary.Count))
{
powerComplete = false;
factoryPowerComplete = false;
warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The auxiliary building has no rated working power.",
buildingItemId: auxiliary.BuildingItemId));
continue;
}
var watts = building.WorkingPowerWatts * auxiliary.Count;
workingPower += watts;
peakPower += watts;
var process = new ProductionProcess(0, building.ItemId, ProliferationMode.None, 0,
Array.Empty<KeyValuePair<int, double>>(), Array.Empty<KeyValuePair<int, double>>(),
1, building.WorkingPowerWatts, true);
groups.Add(new ProductionGroupFlow(process, auxiliary.Count, 0, auxiliary.Count,
auxiliary.Count, watts, watts, Array.Empty<KeyValuePair<int, double>>(),
Array.Empty<KeyValuePair<int, double>>()));
}
if (proliferatorItemId > 0 && request.SprayDeliveredItems.Count > 0)
{
var sprays = request.SprayDeliveredItems.Sum(itemId => targets[itemId]);
foreach (var itemId in reusableSprayItems)
{
if (request.SprayDeliveredItems.Contains(itemId)) sprays -= remainingSprayCredits[itemId];
}
if (sprays > 0) AddFlow(grossConsumption, proliferatorItemId, sprays / spraysPerBottle);
}
var imports = new Dictionary<int, double>();
for (var index = 0; index < importItems.Length; index++)
imports[importItems[index]] = solution[importStart + index];
var itemFlows = new List<ProductionItemFlow>();
for (var index = 0; index < rows.Length; index++)
{
var itemId = rows[index];
var produced = grossProduction.TryGetValue(itemId, out var production) ? production : 0;
var consumed = grossConsumption.TryGetValue(itemId, out var consumption) ? consumption : 0;
var imported = imports.TryGetValue(itemId, out var externalImport) ? externalImport : 0;
var known = request.KnownExternalSurplus.TryGetValue(itemId, out var knownSupply) ? knownSupply : 0;
var delivered = targets.TryGetValue(itemId, out var target) ? target : 0;
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,
producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty<int>(),
consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty<int>()));
}
var diagnostics = warnings.Where(warning => warning.RecipeId == 0 || activeRecipes.Contains(warning.RecipeId))
.ToList();
var power = powerComplete ? new ProductionPower(workingPower, peakPower, generationWatts,
chargingWatts, dischargingWatts, dysonRequirementWatts,
request.AuxiliaryBuildings.Count == 0 ? ProductionPowerScope.ProductionBuildings :
ProductionPowerScope.ProductionBuildingsAndAuxiliary) : null;
var status = powerComplete && diagnostics.Count == 0 ? ProductionStatus.Complete : ProductionStatus.Partial;
return new ProductionReport(status, true, powerComplete, itemFlows, groups, diagnostics, power,
new ProductionPowerBreakdown(workingPower, 0, factoryPowerComplete, true));
}
}
+337
View File
@@ -0,0 +1,337 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed partial class ProductionPlanner
{
private readonly ProductionCatalog _catalog;
private readonly ProcessEvaluator _evaluator;
public ProductionPlanner(ProductionCatalog catalog, ProcessEvaluator evaluator = null)
{
_catalog = catalog;
_evaluator = evaluator ?? new ProcessEvaluator();
}
public ProductionReport Calculate(ProductionPlanRequest request, CancellationToken cancellation = default)
{
if (_catalog == null)
return ProductionReport.Failure(new ProductionDiagnostic(ProductionDiagnosticCode.DataNotReady,
"Production data is not loaded."));
if (request == null || request.IterationBudget <= 0)
return Fail(ProductionDiagnosticCode.InvalidRequest, "A valid plan request and iteration budget are required.");
if (cancellation.IsCancellationRequested)
return Fail(ProductionDiagnosticCode.Cancelled, "The production plan was cancelled.");
var targets = new SortedDictionary<int, double>();
foreach (var target in request.Targets)
{
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 (!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 || !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);
}
if (request.SprayDeliveredItems.Any(itemId => !targets.ContainsKey(itemId)))
return Fail(ProductionDiagnosticCode.InvalidRequest, "Finished-product spraying requires a target item.");
if (!request.ProliferationEnabled && request.SprayDeliveredItems.Count > 0)
return Fail(ProductionDiagnosticCode.InvalidRequest, "Finished-product spraying requires proliferation.");
var processes = new SortedDictionary<int, ProductionProcess>();
var externalItems = new SortedSet<int>();
var pending = new SortedSet<int>(targets.Keys);
var visited = new HashSet<int>();
var warnings = new List<ProductionDiagnostic>();
var hasSprayedTargets = request.SprayDeliveredItems.Any(id => targets[id] > 0);
var explicitModes = request.ProliferationEnabled
? ExplicitProliferationModes(request) : new Dictionary<int, ProliferationMode?>();
ProductionItem proliferator = null;
if (request.ProliferationEnabled)
{
if (!_catalog.Items.TryGetValue(request.ProliferatorItemId, out proliferator) ||
proliferator.SpraysPerItem <= 0 || proliferator.ProliferationLevel <= 0 ||
proliferator.ProliferationLevel > _catalog.MaximumProliferationLevel)
return Fail(ProductionDiagnosticCode.InvalidRequest, "Select a valid proliferator item.",
request.ProliferatorItemId);
if (hasSprayedTargets) pending.Add(proliferator.Id);
}
while (pending.Count > 0)
{
if (cancellation.IsCancellationRequested)
return Fail(ProductionDiagnosticCode.Cancelled, "The production plan was cancelled.");
var itemId = pending.Min;
pending.Remove(itemId);
if (!visited.Add(itemId)) continue;
if (!_catalog.Items.TryGetValue(itemId, out var item))
return Fail(ProductionDiagnosticCode.UnknownItem, "A required item is unknown.", itemId);
var hasExplicitRecipe = request.RecipeByItem.TryGetValue(itemId, out var recipeId);
if (IsExternal(request, item, hasExplicitRecipe))
{
externalItems.Add(itemId);
continue;
}
if (!hasExplicitRecipe) recipeId = item.DefaultRecipeId;
if (recipeId == 0 || !_catalog.Recipes.TryGetValue(recipeId, out var recipe))
return Fail(ProductionDiagnosticCode.UnknownRecipe, "An item has no selected production recipe.", itemId);
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)
{
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
: request.BuildingByCategory.TryGetValue(recipe.Category, out var categoryBuildingId)
? categoryBuildingId : 0;
_catalog.Buildings.TryGetValue(buildingId, out var building);
if (buildingId > 0 && building == null)
warnings.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingBuilding,
"The selected building is missing; material rates remain available.", itemId, recipeId, buildingId));
if (!_evaluator.TryEvaluate(_catalog, recipe, building, mode, level, parameters,
out var process, out var diagnostic))
{
if (diagnostic.Code != ProductionDiagnosticCode.IncompatibleBuilding ||
!_evaluator.TryEvaluate(_catalog, recipe, null, mode, level, parameters,
out process, out _))
return ProductionReport.Failure(diagnostic);
warnings.Add(diagnostic);
}
else if (diagnostic != null)
{
warnings.Add(diagnostic);
}
processes[recipeId] = process;
foreach (var input in process.InputsPerCycle.Keys) pending.Add(input);
if (SpraysInputs(process)) pending.Add(proliferator.Id);
}
var sprayDemand = hasSprayedTargets || processes.Values.Any(SpraysInputs);
var spraysPerBottle = 0.0;
if (sprayDemand)
{
spraysPerBottle = proliferator.SpraysPerItem;
if (request.SelfSprayProliferator)
{
_catalog.TryGetProliferation(proliferator.ProliferationLevel, out _, out var bonus, out _);
spraysPerBottle += Math.Floor(proliferator.SpraysPerItem * bonus + 0.1) - 1;
}
if (spraysPerBottle <= 0)
return Fail(ProductionDiagnosticCode.InvalidRequest, "The selected proliferator has no usable sprays.",
proliferator.Id);
}
var selectedProcesses = processes.Values.ToArray();
var reusableSprayItems = sprayDemand
? selectedProcesses.Where(process => process.ProliferationMode != ProliferationMode.None)
.SelectMany(process => process.PreservedSpraysPerCycle.Keys).Distinct().OrderBy(itemId => itemId).ToArray()
: Array.Empty<int>();
var itemIds = new SortedSet<int>(targets.Keys);
itemIds.UnionWith(request.KnownExternalSurplus.Keys);
itemIds.UnionWith(externalItems);
foreach (var process in selectedProcesses)
{
itemIds.UnionWith(process.InputsPerCycle.Keys);
itemIds.UnionWith(process.OutputsPerCycle.Keys);
}
if (sprayDemand) itemIds.Add(proliferator.Id);
var rows = itemIds.ToArray();
var rowByItem = rows.Select((id, index) => (id, index))
.ToDictionary(entry => entry.id, entry => entry.index);
var importItems = externalItems.ToArray();
var processCount = selectedProcesses.Length;
var importStart = processCount;
var surplusStart = importStart + importItems.Length;
var sprayCreditStart = surplusStart + rows.Length;
var spraySupplySlackStart = sprayCreditStart + reusableSprayItems.Length;
var sprayDemandSlackStart = spraySupplySlackStart + reusableSprayItems.Length;
var columnCount = sprayDemandSlackStart + reusableSprayItems.Length;
var constraintCount = rows.Length + reusableSprayItems.Length * 2;
var matrix = new double[constraintCount, columnCount];
var rhs = new double[constraintCount];
var priorityProcesses = new double[columnCount];
var priorityImports = new double[columnCount];
var prioritySprayReuse = new double[columnCount];
var prioritySurplus = new double[columnCount];
for (var index = 0; index < processCount; index++)
{
var process = selectedProcesses[index];
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 (SpraysInputs(process))
matrix[rowByItem[proliferator.Id], index] -= process.SprayedInputsPerCycle / spraysPerBottle;
}
for (var index = 0; index < importItems.Length; index++)
{
matrix[rowByItem[importItems[index]], importStart + index] = 1;
priorityImports[importStart + index] = 1;
}
for (var index = 0; index < rows.Length; index++)
{
var itemId = rows[index];
var target = targets.TryGetValue(itemId, out var amount) ? amount : 0;
rhs[index] = target - (request.KnownExternalSurplus.TryGetValue(itemId, out var known) ? known : 0);
if (sprayDemand && itemId == proliferator.Id)
rhs[index] += request.SprayDeliveredItems.Sum(targetId => targets[targetId]) / spraysPerBottle;
matrix[index, surplusStart + index] = -1;
prioritySurplus[surplusStart + index] = 1;
}
for (var index = 0; index < reusableSprayItems.Length; index++)
{
var itemId = reusableSprayItems[index];
var supplyRow = rows.Length + index * 2;
var demandRow = supplyRow + 1;
for (var processIndex = 0; processIndex < processCount; processIndex++)
{
var process = selectedProcesses[processIndex];
if (process.ProliferationMode != ProliferationMode.None &&
process.PreservedSpraysPerCycle.TryGetValue(itemId, out var preserved))
matrix[supplyRow, processIndex] = preserved;
matrix[demandRow, processIndex] = SprayedInputAmount(process, itemId);
}
matrix[supplyRow, sprayCreditStart + index] = -1;
matrix[supplyRow, spraySupplySlackStart + index] = -1;
matrix[demandRow, sprayCreditStart + index] = -1;
matrix[demandRow, sprayDemandSlackStart + index] = -1;
matrix[rowByItem[proliferator.Id], sprayCreditStart + index] = 1 / spraysPerBottle;
if (request.SprayDeliveredItems.Contains(itemId)) rhs[demandRow] = -targets[itemId];
prioritySprayReuse[sprayCreditStart + index] = -1;
}
var solution = TwoPhaseSimplex.Solve(matrix, rhs,
new[] { priorityProcesses, priorityImports, prioritySprayReuse, prioritySurplus },
request.IterationBudget, cancellation);
if (solution.Status != LinearSolveStatus.Optimal)
return SolverFailure(solution.Status);
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++)
{
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]);
}
return BuildReport(request, targets, rows, selectedProcesses, importItems, solution.Values,
importStart, surplusStart, sprayDemand ? proliferator.Id : 0, spraysPerBottle, warnings,
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<int, ProliferationMode?> ExplicitProliferationModes(ProductionPlanRequest request)
{
var modes = new Dictionary<int, ProliferationMode?>();
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 (!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;
}
private static ProliferationMode DefaultProliferationMode(ProductionRecipe recipe,
IReadOnlyDictionary<string, double> operatingParameters)
{
if (recipe.Category == ProductionRecipeCategory.Fractionate ||
recipe.Category == ProductionRecipeCategory.Exchange) return ProliferationMode.Speedup;
if (recipe.Category == ProductionRecipeCategory.PhotonStore)
return operatingParameters != null &&
operatingParameters.TryGetValue("LensItemId", out var lensItemId) && lensItemId > 0
? ProliferationMode.Speedup : ProliferationMode.None;
if (recipe.Inputs.Count == 0) return ProliferationMode.None;
return recipe.Productive ? ProliferationMode.ExtraProducts : ProliferationMode.Speedup;
}
private static ProductionReport Fail(ProductionDiagnosticCode code, string message, int itemId = 0,
int recipeId = 0)
{
return ProductionReport.Failure(new ProductionDiagnostic(code, message, itemId, recipeId));
}
private static ProductionReport SolverFailure(LinearSolveStatus status)
{
switch (status)
{
case LinearSolveStatus.Infeasible:
return Fail(ProductionDiagnosticCode.Infeasible, "The selected processes cannot satisfy the targets.");
case LinearSolveStatus.Unbounded:
return Fail(ProductionDiagnosticCode.Unbounded, "The production model is unbounded.");
case LinearSolveStatus.IterationLimit:
return Fail(ProductionDiagnosticCode.IterationLimit, "The simplex iteration budget was exhausted.");
default:
return Fail(ProductionDiagnosticCode.Cancelled, "The production plan was cancelled.");
}
}
}
+191
View File
@@ -0,0 +1,191 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace UXAssist.Production;
public enum ProductionStatus
{
Complete,
Partial,
Failed,
DataNotReady
}
public enum ProductionPowerScope
{
ProductionBuildings,
SelectedFacilities,
ProductionBuildingsAndAuxiliary
}
public sealed class ProductionPower
{
public double ConsumptionWatts { get; }
public double PeakConsumptionWatts { get; }
public double GenerationWatts { get; }
public double AccumulatorChargingWatts { get; }
public double AccumulatorDischargingWatts { get; }
public double DysonSphereRequirementWatts { get; }
public ProductionPowerScope Scope { get; }
public ProductionPower(double consumptionWatts, double peakConsumptionWatts, double generationWatts,
double accumulatorChargingWatts, double accumulatorDischargingWatts, double dysonSphereRequirementWatts,
ProductionPowerScope scope)
{
ConsumptionWatts = consumptionWatts;
PeakConsumptionWatts = peakConsumptionWatts;
GenerationWatts = generationWatts;
AccumulatorChargingWatts = accumulatorChargingWatts;
AccumulatorDischargingWatts = accumulatorDischargingWatts;
DysonSphereRequirementWatts = dysonSphereRequirementWatts;
Scope = scope;
}
}
public sealed class ProductionPowerBreakdown
{
public double KnownFactoryConsumptionWatts { get; }
public double KnownLogisticsConsumptionWatts { get; }
public bool FactoryComplete { get; }
public bool LogisticsComplete { get; }
public double? FactoryConsumptionWatts => FactoryComplete ? KnownFactoryConsumptionWatts : null;
public double? LogisticsConsumptionWatts => LogisticsComplete ? KnownLogisticsConsumptionWatts : null;
public ProductionPowerBreakdown(double knownFactoryConsumptionWatts, double knownLogisticsConsumptionWatts,
bool factoryComplete, bool logisticsComplete)
{
KnownFactoryConsumptionWatts = knownFactoryConsumptionWatts;
KnownLogisticsConsumptionWatts = knownLogisticsConsumptionWatts;
FactoryComplete = factoryComplete;
LogisticsComplete = logisticsComplete;
}
}
public sealed class ProductionItemFlow
{
public int ItemId { get; }
public double GrossProduction { get; }
public double GrossConsumption { get; }
public double NetFlow => GrossProduction - GrossConsumption;
public double ExternalImports { get; }
public double KnownExternalSupply { get; }
public double Delivered { get; }
public double Surplus { get; }
public double RequiredExternalSupply { get; }
public double? SteadyStateExternalSupply { get; }
public bool IsFinalProduct { get; }
public bool IsResearchProduct { get; }
public double IntermediateShortage { get; }
public double? OverbuildSurplus { get; }
public double? CoproductSurplus { get; }
public IReadOnlyList<int> ProducerGroups { get; }
public IReadOnlyList<int> ConsumerGroups { get; }
public ProductionItemFlow(int itemId, double grossProduction, double grossConsumption, double externalImports,
double knownExternalSupply, double delivered, double surplus, double requiredExternalSupply,
bool isFinalProduct, IEnumerable<int> producerGroups, IEnumerable<int> consumerGroups,
double intermediateShortage = 0, double? overbuildSurplus = null, double? coproductSurplus = null,
double? steadyStateExternalSupply = null, bool isResearchProduct = false)
{
ItemId = itemId;
GrossProduction = grossProduction;
GrossConsumption = grossConsumption;
ExternalImports = externalImports;
KnownExternalSupply = knownExternalSupply;
Delivered = delivered;
Surplus = surplus;
RequiredExternalSupply = requiredExternalSupply;
SteadyStateExternalSupply = steadyStateExternalSupply;
IsFinalProduct = isFinalProduct;
IsResearchProduct = isResearchProduct;
IntermediateShortage = intermediateShortage;
OverbuildSurplus = overbuildSurplus;
CoproductSurplus = coproductSurplus;
ProducerGroups = Array.AsReadOnly(producerGroups.ToArray());
ConsumerGroups = Array.AsReadOnly(consumerGroups.ToArray());
}
}
public sealed class ProductionGroupFlow
{
public ProductionProcess Process { get; }
public double BuildingCount { get; }
public double ExecutionsPerMinute { get; }
public double? EquivalentBuildings { get; }
public int? RoundedDeploymentCount { get; }
public double? ConsumptionWatts { get; }
public double? PeakConsumptionWatts { get; }
public double? GenerationWatts { get; }
public double? AccumulatorChargingWatts { get; }
public double? AccumulatorDischargingWatts { get; }
public double? DysonSphereRequirementWatts { get; }
public double LaunchesPerMinute { get; }
public double ResearchHashesPerMinute { get; }
public IReadOnlyDictionary<int, double> GrossProduction { get; }
public IReadOnlyDictionary<int, double> GrossConsumption { get; }
public ProductionGroupFlow(ProductionProcess process, double buildingCount, double executionsPerMinute,
double? equivalentBuildings, int? roundedDeploymentCount, double? consumptionWatts,
double? peakConsumptionWatts,
IEnumerable<KeyValuePair<int, double>> grossProduction,
IEnumerable<KeyValuePair<int, double>> grossConsumption, double? generationWatts = 0,
double? accumulatorChargingWatts = 0, double? accumulatorDischargingWatts = 0,
double? dysonSphereRequirementWatts = 0, double launchesPerMinute = 0,
double researchHashesPerMinute = 0)
{
Process = process;
BuildingCount = buildingCount;
ExecutionsPerMinute = executionsPerMinute;
EquivalentBuildings = equivalentBuildings;
RoundedDeploymentCount = roundedDeploymentCount;
ConsumptionWatts = consumptionWatts;
PeakConsumptionWatts = peakConsumptionWatts;
GenerationWatts = generationWatts;
AccumulatorChargingWatts = accumulatorChargingWatts;
AccumulatorDischargingWatts = accumulatorDischargingWatts;
DysonSphereRequirementWatts = dysonSphereRequirementWatts;
LaunchesPerMinute = launchesPerMinute;
ResearchHashesPerMinute = researchHashesPerMinute;
GrossProduction = ProductionRecipe.CopyFlows(grossProduction);
GrossConsumption = ProductionRecipe.CopyFlows(grossConsumption);
}
}
public sealed class ProductionReport
{
public ProductionStatus Status { get; }
public bool MaterialComplete { get; }
public bool PowerComplete { get; }
public IReadOnlyDictionary<int, ProductionItemFlow> ItemFlows { get; }
public IReadOnlyList<ProductionGroupFlow> Groups { get; }
public IReadOnlyList<ProductionDiagnostic> Diagnostics { get; }
public ProductionPower Power { get; }
public ProductionPowerBreakdown PowerBreakdown { get; }
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<ProductionItemFlow> itemFlows, IEnumerable<ProductionGroupFlow> groups,
IEnumerable<ProductionDiagnostic> diagnostics, ProductionPower power,
ProductionPowerBreakdown powerBreakdown = null)
{
Status = status;
MaterialComplete = materialComplete;
PowerComplete = powerComplete;
ItemFlows = new ReadOnlyDictionary<int, ProductionItemFlow>(itemFlows.ToDictionary(flow => flow.ItemId));
Groups = Array.AsReadOnly(groups.ToArray());
Diagnostics = Array.AsReadOnly(diagnostics.ToArray());
Power = power;
PowerBreakdown = powerBreakdown;
}
internal static ProductionReport Failure(ProductionDiagnostic diagnostic)
{
return new ProductionReport(diagnostic.Code == ProductionDiagnosticCode.DataNotReady
? ProductionStatus.DataNotReady : ProductionStatus.Failed,
false, false, Array.Empty<ProductionItemFlow>(), Array.Empty<ProductionGroupFlow>(),
new[] { diagnostic }, null);
}
}
+175
View File
@@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class RayReceiverAdapter : IProductionProcessAdapter
{
public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building)
{
return building?.Kind == ProductionBuildingKind.RayReceiver ||
recipe?.Category == ProductionRecipeCategory.PhotonStore;
}
public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (building == null)
return TryEvaluateWithoutReceiver(recipe, mode, operatingParameters, out process, out diagnostic);
if (building.Kind != ProductionBuildingKind.RayReceiver)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding,
"The selected building cannot receive Dyson-sphere rays.", recipeId: recipe?.Id ?? 0,
buildingItemId: building.ItemId);
return false;
}
if (!FinitePositive(building.RatedGenerationWatts) ||
(recipe != null && (recipe.Category != ProductionRecipeCategory.PhotonStore ||
recipe.Inputs.Count != 0 || recipe.Outputs.Count != 1 ||
!recipe.Outputs.ContainsKey(building.PowerProductItemId))))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.IncompatibleBuilding,
"The receiver's native photon product or power rating does not match the recipe.",
recipeId: recipe?.Id ?? 0, buildingItemId: building.ItemId);
return false;
}
var photonMode = recipe != null;
if (operatingParameters == null)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Provide the receiver's operating settings.", buildingItemId: building.ItemId);
return false;
}
var hasMode = operatingParameters.TryGetValue("Mode0", out var selectedMode);
if (!hasMode && !photonMode ||
hasMode && (selectedMode != 0 && selectedMode != building.PowerProductItemId ||
photonMode && selectedMode != building.PowerProductItemId))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Select the receiver's grid or native photon operating mode.",
recipeId: recipe?.Id ?? 0, buildingItemId: building.ItemId);
return false;
}
if (recipe == null && selectedMode > 0) photonMode = true;
if (photonMode && (building.PowerProductItemId <= 0 ||
!FinitePositive(building.PowerProductEnergyJoules) ||
!catalog.Items.ContainsKey(building.PowerProductItemId)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The ray receiver has no valid native photon product or required photon energy.",
buildingItemId: building.ItemId);
return false;
}
if (!operatingParameters.TryGetValue("LensItemId", out var 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);
return false;
}
ProductionItem lens = null;
if (lensId > 0 && (!catalog.Items.TryGetValue((int)lensId, out lens) ||
(lens.CatalystTypeMask & building.CatalystMask) == 0 ||
!FinitePositive(lens.CatalystAbilityMultiplier)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected item is not a compatible ray-receiver lens.",
itemId: (int)lensId, buildingItemId: building.ItemId);
return false;
}
if (mode != ProliferationMode.None && mode != ProliferationMode.Speedup ||
mode == ProliferationMode.Speedup && lens == null)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"Only an installed lens can receive native ray-receiver speedup.", buildingItemId: building.ItemId);
return false;
}
var speedBonus = 0.0;
if (mode != ProliferationMode.None &&
(level <= 0 || !catalog.TryGetProliferation(level, out speedBonus, out _, out _)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"The lens's proliferation level is unavailable.", buildingItemId: building.ItemId);
return false;
}
var energyWatts = building.RatedGenerationWatts * 2.5 *
(lens?.CatalystAbilityMultiplier ?? 1) *
(1 + speedBonus) * (photonMode ? 8 : 1);
var cyclesPerMinute = photonMode
? energyWatts * 60 / building.PowerProductEnergyJoules : 1;
if (!FinitePositive(cyclesPerMinute) || !Finite(energyWatts))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The receiver's native output is outside the supported range.", buildingItemId: building.ItemId);
return false;
}
var lossKnown = operatingParameters.TryGetValue("SolarEnergyLossRate", out var solarLoss);
if (lossKnown && (solarLoss < 0 || solarLoss >= 1 || !Finite(solarLoss)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"Solar energy loss must be a finite fraction below one.", buildingItemId: building.ItemId);
return false;
}
if (!lossKnown)
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The Dyson-sphere power requirement needs the current solar energy loss technology setting.",
recipeId: recipe?.Id ?? 0, buildingItemId: building.ItemId);
var lensFlow = lens == null ? Array.Empty<KeyValuePair<int, double>>() :
new[] { new KeyValuePair<int, double>(lens.Id, 0.1 / cyclesPerMinute) };
var productFlow = photonMode
? new[] { new KeyValuePair<int, double>(building.PowerProductItemId, 1) }
: Array.Empty<KeyValuePair<int, double>>();
process = new ProductionProcess(recipe?.Id ?? 0, building.ItemId, mode,
mode == ProliferationMode.None ? 0 : level, lensFlow, productFlow,
cyclesPerMinute, building.WorkingPowerWatts, true,
generationWatts: photonMode ? 0 : energyWatts,
dysonSphereRequirementWatts: lossKnown ? energyWatts / (1 - solarLoss * 0.6) : (double?)null,
powerKnown: lossKnown);
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;
}
}
@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class RenewableGenerationAdapter : IProductionProcessAdapter
{
public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building)
{
return recipe == null && building?.Kind == ProductionBuildingKind.RenewableGenerator;
}
public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (building.RenewableSource == RenewablePowerSource.None ||
!FiniteNonnegative(building.RatedGenerationWatts))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The generator has no renewable power rating.", buildingItemId: building.ItemId);
return false;
}
process = new ProductionProcess(0, building.ItemId, ProliferationMode.None, 0,
Array.Empty<KeyValuePair<int, double>>(), Array.Empty<KeyValuePair<int, double>>(),
1, building.WorkingPowerWatts, true,
generationWatts: building.RatedGenerationWatts);
return true;
}
}
@@ -0,0 +1,120 @@
using System;
using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
public sealed class ResearchProcessAdapter : IProductionProcessAdapter
{
public bool CanEvaluate(ProductionRecipe recipe, ProductionBuilding building)
{
return recipe == null && building?.Kind == ProductionBuildingKind.Ordinary &&
building.Category == ProductionRecipeCategory.Research;
}
public bool TryEvaluate(ProductionCatalog catalog, ProductionRecipe recipe, ProductionBuilding building,
ProliferationMode mode, int level, IReadOnlyDictionary<string, double> operatingParameters,
out ProductionProcess process, out ProductionDiagnostic diagnostic)
{
process = null;
diagnostic = null;
if (operatingParameters == null ||
!operatingParameters.TryGetValue("ResearchMode", out var researchMode) || researchMode != 1)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Research mode needs a lab technology and current research speed.",
buildingItemId: building.ItemId);
return false;
}
var matrixSink = operatingParameters.TryGetValue("ResearchMatrixSink", out var sinkSetting) &&
sinkSetting == 1;
var researchSpeed = 0.0;
ProductionTechnology technology = null;
if (matrixSink)
{
if (catalog.ResearchMatrixItemIds.Count == 0)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The catalog has no native research matrix item IDs.",
buildingItemId: building.ItemId);
return false;
}
}
else
{
if (!operatingParameters.TryGetValue("TechId", out var techId) || !PositiveId(techId) ||
!operatingParameters.TryGetValue("ResearchSpeed", out researchSpeed) ||
!FinitePositive(researchSpeed))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"Research mode needs a lab technology and current research speed.",
buildingItemId: building.ItemId);
return false;
}
if (!catalog.Technologies.TryGetValue((int)techId, out technology))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected technology is not a lab-research technology.",
buildingItemId: building.ItemId);
return false;
}
}
if (mode != ProliferationMode.None && mode != ProliferationMode.ExtraProducts)
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"Research proliferation creates extra hashes, not faster research cycles.",
buildingItemId: building.ItemId);
return false;
}
var extraBonus = 0.0;
var powerMultiplier = 1.0;
if (mode == ProliferationMode.ExtraProducts &&
(level <= 0 || !catalog.TryGetProliferation(level, out _, out extraBonus,
out powerMultiplier)))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProliferation,
"The matrix proliferation level is unavailable.", buildingItemId: building.ItemId);
return false;
}
var baseHashes = 3600.0 * researchSpeed;
var hashRate = baseHashes * (1 + extraBonus);
var workingWatts = building.WorkingPowerWatts * powerMultiplier;
if (!FinitePositive(workingWatts) || !matrixSink && !FinitePositive(hashRate))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The research hash rate or power demand is outside the supported range.",
buildingItemId: building.ItemId);
return false;
}
var inputs = new List<KeyValuePair<int, double>>();
if (!matrixSink)
{
foreach (var requirement in technology.MatrixPointsPerHash)
{
if (!catalog.Items.ContainsKey(requirement.Key) || !FinitePositive(requirement.Value) ||
!FinitePositive(researchSpeed * requirement.Value))
{
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The technology has an invalid matrix point requirement.",
itemId: requirement.Key, buildingItemId: building.ItemId);
return false;
}
inputs.Add(new KeyValuePair<int, double>(requirement.Key,
researchSpeed * requirement.Value));
}
}
process = new ProductionProcess(0, building.ItemId, mode,
mode == ProliferationMode.None ? 0 : level, inputs,
Array.Empty<KeyValuePair<int, double>>(), 1, workingWatts, true,
researchHashesPerCycle: hashRate);
return true;
}
}
+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;
}
}
+228
View File
@@ -0,0 +1,228 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace UXAssist.Production;
internal enum LinearSolveStatus
{
Optimal,
Infeasible,
Unbounded,
IterationLimit,
Cancelled
}
internal sealed class LinearSolveResult
{
internal LinearSolveStatus Status { get; }
internal double[] Values { get; }
internal LinearSolveResult(LinearSolveStatus status, double[] values = null)
{
Status = status;
Values = values;
}
}
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<double[]> objectives, int iterationBudget, CancellationToken cancellation)
{
var rowCount = rightHandSide.Length;
var columnCount = coefficients.GetLength(1);
if (coefficients.GetLength(0) != rowCount || iterationBudget <= 0)
throw new ArgumentException("The linear system or iteration budget is invalid.");
foreach (var objective in objectives)
{
if (objective.Length != columnCount)
throw new ArgumentException("An objective has an incorrect number of columns.");
}
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;
for (var column = 0; column < columnCount; column++)
{
if (double.IsNaN(coefficients[row, column]) || double.IsInfinity(coefficients[row, column]))
throw new ArgumentException("The constraint matrix contains a non-finite number.");
scale = Math.Max(scale, Math.Abs(coefficients[row, column]));
}
var rightHand = rightHandSide[row] / rightHandScale;
if (scale == 0)
{
if (Math.Abs(rightHand) > PivotTolerance)
return new LinearSolveResult(LinearSolveStatus.Infeasible);
scale = 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 * 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, isBasic, artificialObjective, Array.Empty<double[]>(),
columnCount, ref iterations, iterationBudget, cancellation);
if (firstStatus != LinearSolveStatus.Optimal)
return new LinearSolveResult(firstStatus == LinearSolveStatus.Unbounded
? LinearSolveStatus.Infeasible : firstStatus);
for (var row = 0; row < rowCount; row++)
{
if (basis[row] < columnCount) continue;
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;
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<double[]>();
foreach (var objective in objectives)
{
var costs = new double[width];
Array.Copy(objective, costs, 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);
}
var values = new double[columnCount];
for (var row = 0; row < rowCount; row++)
{
if (basis[row] < columnCount)
values[basis[row]] = Math.Max(0, tableau[row, width]) * rightHandScale;
}
return new LinearSolveResult(LinearSolveStatus.Optimal, values);
}
private static LinearSolveStatus Optimize(double[,] tableau, int[] basis, bool[] isBasic, double[] costs,
IReadOnlyList<double[]> previousCosts, int enteringLimit, ref int iterations, int budget,
CancellationToken cancellation)
{
var rowCount = basis.Length;
var rightColumn = tableau.GetLength(1) - 1;
while (true)
{
if (cancellation.IsCancellationRequested) return LinearSolveStatus.Cancelled;
var entering = -1;
for (var column = 0; column < enteringLimit; column++)
{
if (isBasic[column] || ReducedCost(tableau, basis, costs, column) >= -ReducedTolerance)
continue;
var preservesPrevious = true;
foreach (var previous in previousCosts)
{
if (Math.Abs(ReducedCost(tableau, basis, previous, column)) <= ReducedTolerance) continue;
preservesPrevious = false;
break;
}
if (preservesPrevious)
{
entering = column;
break;
}
}
if (entering < 0) return LinearSolveStatus.Optimal;
if (iterations >= budget) return LinearSolveStatus.IterationLimit;
var leaving = -1;
var minRatio = double.PositiveInfinity;
for (var row = 0; row < rowCount; row++)
{
var coefficient = tableau[row, entering];
if (coefficient <= PivotTolerance) continue;
var ratio = Math.Max(0, tableau[row, rightColumn]) / coefficient;
// 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;
}
}
if (leaving < 0) return LinearSolveStatus.Unbounded;
Pivot(tableau, basis, isBasic, leaving, entering);
iterations++;
}
}
private static double ReducedCost(double[,] tableau, int[] basis, double[] costs, int column)
{
var reduced = costs[column];
for (var row = 0; row < basis.Length; row++)
reduced -= costs[basis[row]] * tableau[row, column];
return reduced;
}
private static void Pivot(double[,] tableau, int[] basis, bool[] isBasic, int pivotRow, int pivotColumn)
{
var rowCount = basis.Length;
var width = tableau.GetLength(1);
var divisor = tableau[pivotRow, pivotColumn];
for (var column = 0; column < width; column++)
tableau[pivotRow, column] /= divisor;
for (var row = 0; row < rowCount; row++)
{
if (row == pivotRow) continue;
var factor = tableau[row, pivotColumn];
if (factor == 0) continue;
for (var column = 0; column < width; column++)
tableau[row, column] -= factor * tableau[pivotRow, column];
tableau[row, pivotColumn] = 0;
}
tableau[pivotRow, pivotColumn] = 1;
isBasic[basis[pivotRow]] = false;
isBasic[pivotColumn] = true;
basis[pivotRow] = pivotColumn;
}
}
+16 -4
View File
@@ -17,6 +17,11 @@
* Strict hotkey dectection for build menu, thus building hotkeys(0~9, F1~F10, X, U) are not triggered while holding Ctrl/Alt/Shift. * Strict hotkey dectection for build menu, thus building hotkeys(0~9, F1~F10, X, U) are not triggered while holding Ctrl/Alt/Shift.
* Fix a bug that warning popup on `Veins Utilization` upgraded to level 8000+ * Fix a bug that warning popup on `Veins Utilization` upgraded to level 8000+
* Sort blueprint structures before saving, to reduce generated blueprint data size a little * Sort blueprint structures before saving, to reduce generated blueprint data size a little
* Add an `Auto-fill` entry to the description header in the blueprint browser, copy, and paste inspectors. Click it to open generation options without moving or resizing native fields or covering the file list
* `Production basis` defaults to `Final-product output` each time the inspector opens, retaining rated final outputs and showing intermediate shortages and excess. Choose `Lowest intermediate throughput` to scale the final-product mix together to the bottleneck, using recipe ratios and shared intermediate demand. Complete, balanceable chains then have no internal shortages; unused intermediate capacity appears as excess. External inputs and final outputs use the same basis.
* `Proliferation` defaults to on when the blueprint contains a Spray Coater; it can be changed manually. Power demand still estimates all selected buildings at full load in either production basis.
* Replaces the main description with material flows per minute and writes power demand to a `Power` custom field, preserving other custom fields. If the bottleneck basis cannot be determined, the existing description is kept; check missing building settings and chain outputs, or select `Final-product output`. Save the blueprint manually to keep generated changes.
* Large material rates use the largest exact `K`/`M`/`G` suffix with at most one decimal place; rates that cannot be shortened without losing display precision keep their ordinary format. Numbers with four or more integer digits use comma thousands separators, including before suffixes (for example, `12,345` and `1,234.5K`).
* Increase maximum count of Metadata Instantiations to 20000 (from 2000) * Increase maximum count of Metadata Instantiations to 20000 (from 2000)
* Increase capacity of player order queue to 128 (from 16) * Increase capacity of player order queue to 128 (from 16)
* Enable `Hide UI` (`F11` by default) in Star Map view, hiding UI and other scene elements * Enable `Hide UI` (`F11` by default) in Star Map view, hiding UI and other scene elements
@@ -84,13 +89,13 @@
* Quick build Orbital Collectors * Quick build Orbital Collectors
* Set a maximum number to build per operation; 0 builds as many as possible * Set a maximum number to build per operation; 0 builds as many as possible
* Quick build Mining Machines * Quick build Mining Machines
* Use the button on the Factory tab near Quick build Orbital Collectors. Places the full ordinary Mining Machine layout at the nearest solid vein group regardless of carried stock. Uses available miners from the inventory and hand; missing miners remain as ghosts awaiting materials. Every placed miner must retain at least 3 covered nodes after all planned burials; miners below that minimum are invalid. * Use the button on the Factory tab near Quick build Orbital Collectors. Places the full ordinary Mining Machine layout at the nearest solid vein group regardless of carried stock. Mines only the selected group, even when another group of the same resource is nearby. Uses available miners from the inventory and hand; missing miners remain as ghosts awaiting materials. Every placed miner must retain at least 3 covered nodes in the selected group after all planned burials; miners below that minimum are invalid.
* `Allow restoring/burying veins` is off by default. When disabled, uses only visible nodes and skips all restoration and burial calculations. Enable it to restore buried nodes unless obstructed by buildings or near Dark Fog Planetary Bases. Changes apply to the next calculation. Searches individual native collision shapes so the miner's feet can interleave where the game permits. * `Allow restoring/burying veins` is off by default. When disabled, uses only visible nodes and skips all restoration and burial calculations. Enable it to restore buried nodes unless obstructed by buildings or near Dark Fog Planetary Bases. Changes apply to the next calculation. Searches individual native collision shapes so the miner's feet can interleave where the game permits.
* Uses multiple packing orders, exploration keyed by placement pose as well as candidate index, local position/rotation refinement, body-width neighbor candidates, and coordinated repacking of up to three nearby miners to seek a high sum of vein counts across all placed miners. A final pass fills remaining compatible candidates when they increase total coverage while preserving the three-node minimum. Shared nodes count once per miner; this bounded search does not guarantee a global optimum. * Uses multiple packing orders, exploration keyed by placement pose as well as candidate index, local position/rotation refinement, body-width neighbor candidates, and coordinated repacking of up to three nearby miners to seek a high sum of vein counts across all placed miners. A final pass fills remaining compatible candidates when they increase total coverage while preserving the three-node minimum. Shared nodes count once per miner; this bounded search does not guarantee a global optimum.
* Reuses collision checks and runs independent layout searches on up to 4 background workers, capped at half the available logical processors. Systems with one logical processor keep the search on the main thread with a frame budget. Native terrain checks and placement stay on the main thread; worker scheduling preserves the same layout as sequential search. * Reuses collision checks and runs independent layout searches on up to 4 background workers, capped at half the available logical processors. Systems with one logical processor keep the search on the main thread with a frame budget. Native terrain checks and placement stay on the main thread; worker scheduling preserves the same layout as sequential search.
* With `Allow restoring/burying veins` enabled, may bury unused nodes when that improves total coverage. Nodes already assigned to miners or miner prebuilds are protected. Ground, water, existing buildings, construction range, and the game's other placement clearances still apply. * With `Allow restoring/burying veins` enabled, may bury unused nodes when that improves total coverage. Nodes already assigned to miners or miner prebuilds are protected. Ground, water, existing buildings, construction range, and the game's other placement clearances still apply.
* Click again during calculation to cancel. Changing planets or leaving the game cancels automatically. Construction drones finish the prebuilds; belts and power supply are not placed. * Click again during calculation to cancel. Changing planets or leaving the game cancels automatically. Construction drones finish the prebuilds; belts and power supply are not placed.
* While tuning this feature, each calculation writes a timestamped JSON snapshot to `BepInEx/debug/UXAssist/QuickMiner/` in the active game profile, including the restoration/burial option, nodes, native colliders, accepted candidates, search phases and their search times, logical processor and worker counts, existing miners, and native placement results. The completion tip stays visible for about 8 seconds; the log also records the result summary and full file path. Replay and compare sequential/parallel results without loading a save using `powershell -File tools/tests/Test-QuickMinerPlacement.ps1 -Snapshot <file.json>` from the repository root. Replay fails if total coverage falls below the recorded result; add `-MinimumTotalCoverage <count>` to require a higher total. * Debug builds capture a timestamped JSON snapshot for each calculation and export it to `BepInEx/debug/UXAssist/QuickMiner/` in the active game profile, including the restoration/burial option, nodes, native colliders, accepted candidates, search phases and their search times, logical processor and worker counts, existing miners, and native placement results. Only Debug builds log the result summary and full file path; Release builds exclude this debug functionality. The completion tip stays visible for about 8 seconds in both builds. Replay and compare sequential/parallel results without loading a save using `powershell -File tools/tests/Test-QuickMinerPlacement.ps1 -Snapshot <file.json>` from the repository root. Replay fails if total coverage falls below the recorded result; add `-MinimumTotalCoverage <count>` to require a higher total.
* Belt signals for buy out dark fog items automatically * Belt signals for buy out dark fog items automatically
* 6 belt signals are added to the signal panel, which can be used to buy out dark fog items automatically. * 6 belt signals are added to the signal panel, which can be used to buy out dark fog items automatically.
* Generated items are stacked in 4 items. * Generated items are stacked in 4 items.
@@ -166,6 +171,7 @@
* Buy out techs with their prerequisites * Buy out techs with their prerequisites
* This enables batch buying out techs with their prerequisites. Buy-out buttons are shown for locked techs/upgrades. * This enables batch buying out techs with their prerequisites. Buy-out buttons are shown for locked techs/upgrades.
* Hide battle-related techs in Peace mode * Hide battle-related techs in Peace mode
* Battle-related techs and their connections return when disabling the option or loading a Combat-mode save; switching saves does not require restarting the game.
* Unlock all techs with metadata * Unlock all techs with metadata
* Use the config-panel button to confirm the metadata cost and buy out eligible techs in a batch; unlimited upgrade chains are excluded. * Use the config-panel button to confirm the metadata cost and buy out eligible techs in a batch; unlimited upgrade chains are excluded.
* Combat * Combat
@@ -219,6 +225,11 @@
* 更严格的建造菜单热键检测,因此在按住Ctrl/Alt/Shift时不再会触发建造热键(0~9, F1~F10, X, U) * 更严格的建造菜单热键检测,因此在按住Ctrl/Alt/Shift时不再会触发建造热键(0~9, F1~F10, X, U)
* 修复了`矿物利用`升级到8000级以上时弹出警告的bug * 修复了`矿物利用`升级到8000级以上时弹出警告的bug
* 保存蓝图前对建筑进行排序,以减少生成的蓝图数据大小 * 保存蓝图前对建筑进行排序,以减少生成的蓝图数据大小
* 在蓝图浏览、复制和粘贴检查面板的说明标题行增加「自动填写」入口,点击展开生成选项,不移动或缩放原生字段,也不遮挡文件列表
* 每次打开检查面板时,「产量基准」默认为「最终产物产量」,保留最终产物的额定产量,并显示中间产物的缺口和余量。选择「最低产量中间产物」后,按配方比例和共享中间物料的需求换算瓶颈,等比例缩放各最终产物。数据完整且可平衡的生产链没有内部缺口,未使用的中间产能列为「多余」;外部输入和最终输出采用同一基准。
* 蓝图含喷涂机时默认勾选「增产」,也可手动修改。两种产量基准均按所选全部建筑满载估算耗电。
* 用每分钟的物料流量替换原说明,将耗电写入「耗电」自定义字段,保留其他自定义字段。无法确定瓶颈基准时保留原说明;可检查缺失的建筑参数和生产链输出,或改选「最终产物产量」。填写后需手动保存蓝图。
* 较大的物料流量使用能精确表示的最大 `K`/`M`/`G` 单位,小数最多一位;无法在保留显示精度的前提下缩写时,保留普通数字格式。整数部分达到四位的数字用逗号每三位分隔,带单位时也适用,例如 `12,345` 和 `1,234.5K`。
* 将元数据提取的最大数量增加到20000(原来为2000) * 将元数据提取的最大数量增加到20000(原来为2000)
* 将玩家指令队列的容量增加到128(原来为16) * 将玩家指令队列的容量增加到128(原来为16)
* 在星图视图中启用 `隐藏 UI` 功能(默认按键为 `F11`),同时隐藏 UI 和场景中的其他元素 * 在星图视图中启用 `隐藏 UI` 功能(默认按键为 `F11`),同时隐藏 UI 和场景中的其他元素
@@ -286,13 +297,13 @@
* 快速建造轨道采集器 * 快速建造轨道采集器
* 可设置单次建造数量上限;设为 0 时尽可能多地建造 * 可设置单次建造数量上限;设为 0 时尽可能多地建造
* 快速铺设采矿机 * 快速铺设采矿机
* 点击「工厂」页中轨道采集器按钮附近的按钮,在最近的固体矿脉生成完整的普通采矿机布局,数量不受库存限制。有采矿机时正常消耗背包和手持物品,不足的位置保留待建造虚影,等待补充材料。所有计划掩埋完成后,每台矿机仍须覆盖至少 3 个矿点;少于 3 个的视为无效,不予铺设。 * 点击「工厂」页中轨道采集器按钮附近的按钮,在最近的固体矿脉生成完整的普通采矿机布局,数量不受库存限制。仅开采选中的矿脉,即使附近有同种资源的其他矿脉也不会混入。有采矿机时正常消耗背包和手持物品,不足的位置保留待建造虚影,等待补充材料。所有计划掩埋完成后,每台矿机仍须覆盖选中矿脉的至少 3 个矿点;少于 3 个的视为无效,不予铺设。
* 「允许恢复/掩埋矿物」默认关闭。关闭时仅使用可见矿点,跳过所有恢复和掩埋计算;开启后,先恢复未被建筑阻挡且不在黑雾行星基地附近的掩埋矿点。选项变更从下次计算生效。按原版独立碰撞体搜索布局,保留游戏允许的矿机脚部交叉空间。 * 「允许恢复/掩埋矿物」默认关闭。关闭时仅使用可见矿点,跳过所有恢复和掩埋计算;开启后,先恢复未被建筑阻挡且不在黑雾行星基地附近的掩埋矿点。选项变更从下次计算生效。按原版独立碰撞体搜索布局,保留游戏允许的矿机脚部交叉空间。
* 比较多种铺设顺序,同时按候选序号及位置朝向探索不同布局,细调位置和朝向,按机身宽度补充紧邻候选,并允许邻近的两三台矿机一起重新布局,尽量提高各台矿机覆盖矿点数之和。结束前再扫描全部候选,继续补入能提高总覆盖数、且不破坏每台至少覆盖 3 点要求的矿机。同一矿点被多台矿机覆盖时重复计数。计算有界,不保证全局最优。 * 比较多种铺设顺序,同时按候选序号及位置朝向探索不同布局,细调位置和朝向,按机身宽度补充紧邻候选,并允许邻近的两三台矿机一起重新布局,尽量提高各台矿机覆盖矿点数之和。结束前再扫描全部候选,继续补入能提高总覆盖数、且不破坏每台至少覆盖 3 点要求的矿机。同一矿点被多台矿机覆盖时重复计数。计算有界,不保证全局最优。
* 复用碰撞检查结果,使用最多 4 个后台线程并行搜索独立布局,线程数不超过可用逻辑线程数的一半。单逻辑线程系统继续在主线程按每帧预算计算。原生地形检查和实际铺设保留在主线程;并行调度与顺序搜索生成相同布局。 * 复用碰撞检查结果,使用最多 4 个后台线程并行搜索独立布局,线程数不超过可用逻辑线程数的一半。单逻辑线程系统继续在主线程按每帧预算计算。原生地形检查和实际铺设保留在主线程;并行调度与顺序搜索生成相同布局。
* 开启「允许恢复/掩埋矿物」后,允许掩埋未被使用的矿点来提高总覆盖数;保护已有矿机及待建造矿机使用的矿点。仍需满足地面、水面、现有建筑、建造范围及游戏的其他放置间距要求。 * 开启「允许恢复/掩埋矿物」后,允许掩埋未被使用的矿点来提高总覆盖数;保护已有矿机及待建造矿机使用的矿点。仍需满足地面、水面、现有建筑、建造范围及游戏的其他放置间距要求。
* 计算期间再次点击可取消,切换行星或退出游戏自动取消。待建造对象由建设机器人完成,不自动铺设传送带和电力设施。 * 计算期间再次点击可取消,切换行星或退出游戏自动取消。待建造对象由建设机器人完成,不自动铺设传送带和电力设施。
* 功能调试期间,每次计算都会在当前游戏配置目录的 `BepInEx/debug/UXAssist/QuickMiner/` 下写入带时间戳的 JSON 文件,记录恢复/掩埋选项、矿点、原生碰撞体、有效候选、搜索阶段及其搜索耗时、逻辑线程数和工作线程数、现有矿机和原生铺设校验结果。完成提示保留约 8 秒,日志也会记录结果摘要和文件的完整路径。在仓库根目录运行 `powershell -File tools/tests/Test-QuickMinerPlacement.ps1 -Snapshot <file.json>`,即可离线重放并比较顺序与并行搜索结果,无需读取存档。总覆盖数低于记录结果时,重放检查会失败;可追加 `-MinimumTotalCoverage <数量>`,要求达到更高的总覆盖数。 * 仅 Debug 版本会为每次计算采集带时间戳的 JSON 快照,并导出到当前游戏配置目录的 `BepInEx/debug/UXAssist/QuickMiner/`,记录恢复/掩埋选项、矿点、原生碰撞体、有效候选、搜索阶段及其搜索耗时、逻辑线程数和工作线程数、现有矿机和原生铺设校验结果。结果摘要和文件完整路径的日志也仅在 Debug 版本中输出;Release 版本不编译这些调试功能。两个版本的完成提示均保留约 8 秒。在仓库根目录运行 `powershell -File tools/tests/Test-QuickMinerPlacement.ps1 -Snapshot <file.json>`,即可离线重放并比较顺序与并行搜索结果,无需读取存档。总覆盖数低于记录结果时,重放检查会失败;可追加 `-MinimumTotalCoverage <数量>`,要求达到更高的总覆盖数。
* 用于自动购买黑雾物品的传送带信号 * 用于自动购买黑雾物品的传送带信号
* 在信号面板上添加了6个传送带信号,可以用于自动购买黑雾道具。 * 在信号面板上添加了6个传送带信号,可以用于自动购买黑雾道具。
* 生成的物品堆叠数为4。 * 生成的物品堆叠数为4。
@@ -368,6 +379,7 @@
* 买断科技也同时买断所有前置科技 * 买断科技也同时买断所有前置科技
* 可批量买断科技及其前置科技,未解锁的科技和升级会显示买断按钮。 * 可批量买断科技及其前置科技,未解锁的科技和升级会显示买断按钮。
* 在和平模式下隐藏战斗相关科技 * 在和平模式下隐藏战斗相关科技
* 关闭选项或加载战斗模式存档后恢复相关科技及连线,切换存档无需重启游戏。
* 使用元数据解锁所有科技 * 使用元数据解锁所有科技
* 在配置面板点击按钮并确认元数据消耗,批量买断符合条件的科技;不包含无限升级科技链。 * 在配置面板点击按钮并确认元数据消耗,批量买断符合条件的科技;不包含无限升级科技链。
* 战斗 * 战斗
+3
View File
@@ -17,6 +17,7 @@ using UXAssist.Functions.Factory;
using UXAssist.Patches; using UXAssist.Patches;
using UXAssist.Patches.Factory; using UXAssist.Patches.Factory;
using UXAssist.Patches.Logistics; using UXAssist.Patches.Logistics;
using UXAssist.Production;
using UXAssist.UI; using UXAssist.UI;
using Util = UXAssist.Common.Util; using Util = UXAssist.Common.Util;
using GameLogicProc = UXAssist.Common.GameLogic; using GameLogicProc = UXAssist.Common.GameLogic;
@@ -239,6 +240,7 @@ public class UXAssist : BaseUnityPlugin, IModCanSave
// UI Patches // UI Patches
GameLogicProc.Enable(true); GameLogicProc.Enable(true);
ProductionCatalogService.Init();
UIConfigWindow.Init(); UIConfigWindow.Init();
@@ -280,6 +282,7 @@ public class UXAssist : BaseUnityPlugin, IModCanSave
_patches?.Do(type => type.GetMethod("Uninit")?.Invoke(null, null)); _patches?.Do(type => type.GetMethod("Uninit")?.Invoke(null, null));
MyWindowManager.Enable(false); MyWindowManager.Enable(false);
ProductionCatalogService.Uninit();
GameLogicProc.Enable(false); GameLogicProc.Enable(false);
} }
+4 -2
View File
@@ -3,14 +3,16 @@
<PropertyGroup> <PropertyGroup>
<BepInExPluginGuid>org.soardev.uxassist</BepInExPluginGuid> <BepInExPluginGuid>org.soardev.uxassist</BepInExPluginGuid>
<Description>DSP MOD - UXAssist</Description> <Description>DSP MOD - UXAssist</Description>
<Version>1.6.3</Version> <Version>1.6.4</Version>
<PackageId>UXAssist</PackageId> <PackageId>UXAssist</PackageId>
<RootNamespace>UXAssist</RootNamespace> <RootNamespace>UXAssist</RootNamespace>
<PackHasChangelog>true</PackHasChangelog> <PackHasChangelog>true</PackHasChangelog>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System.Runtime.Serialization" /> <Compile Remove="tools/**/*.cs" />
<Compile Remove="Functions/Factory/MinerPlacementDebug.cs" Condition="'$(Configuration)' != 'Debug'" />
<Reference Include="System.Runtime.Serialization" Condition="'$(Configuration)' == 'Debug'" />
<PackageReference Include="DysonSphereProgram.Modding.CommonAPI" Version="1.*" /> <PackageReference Include="DysonSphereProgram.Modding.CommonAPI" Version="1.*" />
<PackageReference Include="DysonSphereProgram.Modding.DSPModSave" Version="1.*" /> <PackageReference Include="DysonSphereProgram.Modding.DSPModSave" Version="1.*" />
</ItemGroup> </ItemGroup>
@@ -0,0 +1,53 @@
# Blueprint Description Validation
This document records the native layout evidence for the UXAssist description-header entry and the checks needed for in-game acceptance. Compilation and managed production checks do not establish compatibility with other blueprint mods.
## Native evidence
Inspected on 2026-11-01 after discovering Steam through `HKCU`'s Steam path and `steamapps/libraryfolders.vdf`:
- Original assembly: `D:/Steam/steamapps/common/Dyson Sphere Program/DSPGAME_Data/Managed/Assembly-CSharp.dll`, SHA-256 `EF314425DADE51F529F184F07BE136CD3C2660A6A81515603C7226FBE7AB1D8C`.
- Native UI assets: `DSPGAME_Data/level0`, SHA-256 `04655A46BBEB113113688BCDC0E0EA8EC5F128B348E32194FC9743ADB48C8E91`.
- The installed version history ends at `0.10.35.29151`; the Steam manifest reports build ID `25955035`. Assembly file version `0.0.0.0` alone does not identify this game build.
The original `UIBlueprintInspector.Refresh` sizes the description and native groups, places groups 2 through 4, and updates the scroll content height. It does not restore group 1's position. The previous UXAssist layout shifted group 1 and repeatedly offset the later groups and content height, making both the native refresh and other layout patches share ownership of those transforms.
The relevant original methods can be reproduced by decompiling the following types from the original assembly:
| Native method | Observed behavior |
| --- | --- |
| `UIBlueprintInspector.Refresh(bool forModify, bool refreshComponent, bool refreshCode, bool loadExistHead = false)` | Controls native group sizes, later group positions, and content height; reloads the main description input only when `forModify` is false. |
| `UIBlueprintInspector._OnOpen()` and `_OnClose()` | Refresh and open native settings for the relevant mode; clear the blueprint on close. |
| `ManualBehaviour._Close()` | Deactivates the inspector GameObject, hiding children. |
| `UIBlueprintInspector.OnCustomFieldEndEdit(string str)` and `CollectExternalFields(int excludeTargetId = -1)` | Collect, escape, and validate pending custom-field edits through the native path. |
| `UIBlueprintInspector.OnCopyClick()`, `OnSaveChangesClick()`, and `OnSaveClick()` | Serialize or save the current blueprint with the game's native workflow. |
The native `descGroupTrans` in all three inspectors contains a description label at the top and an input beginning 22 pixels below it. The compact UXAssist entry occupies the right side of this existing title row; it does not move the title, input, groups, or scroll content. Options appear only on request inside the inspector and close after successful generation or inspector closure. The browser's file grid remains outside the UXAssist controls. Following the separate native settings panel is unnecessary, and no per-frame positioning patch is used.
`UIBlueprintInspector.Refresh(forModify: true)` does not reload `descTextInput`. Successful generation must assign both the blueprint description and its input before using the native modification refresh. Pending custom fields must first pass through the native field collection and escaping rules. Native copy and save handlers serialize the current blueprint, so they remain the actions used to share or persist a generated description.
Decompiled methods and extracted rectangle data are development artifacts under `UXAssist/obj/native-inspector/`. Reinspect the installed original assembly and assets after a game update; the publicized compile-time references omit method bodies.
## Managed production checks
Run the production checks and normal UXAssist build from the repository root:
```powershell
dotnet run --project UXAssist/tools/ProductionCheck/ProductionCheck.csproj -c Release
dotnet build UXAssist/UXAssist.csproj -c Release --no-restore
git diff --check
```
The production-basis cases check an undersupplied chain, recipe-ratio conversion, shared intermediate demand, joint products, a cycle with an output, research-matrix outlets, no internal intermediate, power-only selections, very different capacity scales, and unavailable material settings or final output. A successful bottleneck report must conserve material, normalize inputs and outputs to the same throughput, preserve rated group capacity and power, and avoid internal shortages. Existing default-mode expectations must continue to pass.
## Manual acceptance
No in-game, Unity event-loop, or third-party mod integration test has been performed for this change. Repeat these checks at the target profile's resolutions and UI scales, with each installed blueprint UI mod. The header entry avoids native layout writes but another mod may use the same extension space.
1. Open all three inspectors in English and Simplified Chinese. Confirm the header entry is readable without covering the title or editable description. Open and close its options, generate, and close the inspector. The options must not remain over the file grid or survive an inspector close.
2. Scroll the native description and custom fields and expand native foundation, fill-only, and reform settings. All native fields must retain their positions and sizes, and scrolling must reach every field.
3. Reopen each inspector and repeatedly refresh or change the blueprint selection. Confirm there is one entry, options are initially closed, the production basis resets to final-product output on opening, Spray Coaters set the automatic proliferation default, and a manual checkbox choice survives content refreshes in the current session.
4. Generate both production bases for an unbalanced chain. Final-product output should retain rated final capacity and show the missing intermediate; lowest intermediate throughput should reduce the common final-output mix, use correspondingly reduced external inputs, and show no internal shortage when the chain is complete and balanceable. Power should remain the same full-load estimate. Check necessary coproduct output separately from unused intermediate capacity.
5. Edit the description and unrelated custom fields before generating. Generate twice, including with 20 custom fields and with existing English or Chinese power fields. Confirm unrelated edits survive, duplicate power fields are consolidated, and failed generation leaves the prior description and fields intact. Include missing building settings, an unavailable bottleneck basis, and the native description length limit.
6. Save, copy the share code, and reopen or paste the blueprint through the native buttons. Confirm the generated main description, power field, and unrelated fields persist correctly. With a research-mode lab, confirm net produced matrices appear under Research without fabricated matrix imports or research speed.
7. Restart the test profile without UXAssist, then restore it and restart again. Confirm the entry and options are absent without UXAssist, native fields keep their normal layout in both cases, and repeated opening and generation work with the installed blueprint mods. `OnDisable` and inspector-destruction cleanup are code-review checks unless a development harness exercises them; a supported user-facing hot-disable workflow is not assumed.
+136
View File
@@ -0,0 +1,136 @@
# Production Calculation Architecture
UXAssist exposes a shared production catalog, a material planner, a fixed-building black box analyzer, and blueprint capture. These APIs calculate reports without changing DSP production or replacing factory updates. The blueprint inspector also offers an explicit, click-to-generate description; it is not a continuous factory calculator.
## Data and lifecycle
- `ProductionCatalogService.Current` is an immutable snapshot of loaded item, recipe, technology, building, `PrefabDesc`, and `Cargo` data. The service rebuilds after data preload and on game begin, so changes made by later preload callbacks are captured. It clears the snapshot when a game ends. It can be `null` before preload. Subscribe to `ProductionCatalogService.Changed` to invalidate derived reports and retry against the current snapshot; the event also reports clearing the catalog.
- Capture a live blueprint selection on the game thread. The planner, black box analyzer, adapters, and simplex implementation read only immutable snapshots and managed request data. They do not retain game component references or inspect current inventories during calculation.
- Material rates use `double` items per minute; process executions, hashes, and launches are also per minute. Native simulation runs at 60 ticks per second, so recipe cycle rates use 3,600 ticks per minute, not 60. Convert fixed-point speed values by 10,000 and energy per tick to watts by 60. Gas speeds arrive in items per second and must also be converted to per-minute outputs. Round only for display and for the separately reported building deployment count.
- A report carries separate `MaterialComplete` and `PowerComplete` flags, `Diagnostics`, individual `ItemFlows`, and `Groups`. `ProductionPower` is `null` if any power requirement is unknown; a group's unknown Dyson-sphere demand is also `null`. `PowerBreakdown` additionally reports independently complete factory and logistics consumption, with nullable category totals and known portions. The planner's breakdown has zero logistics consumption because logistics is outside its scope. Never interpret an absent result or incomplete category as zero.
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:
```csharp
var request = new ProductionPlanRequest();
request.Targets.Add(new ProductionTarget(itemId, 60));
request.BuildingByCategory[ProductionRecipeCategory.Assemble] = assemblerItemId;
request.ExternalMaterials.Add(rawResourceItemId);
var report = new ProductionPlanner(ProductionCatalogService.Current).Calculate(request);
if (report.MaterialComplete)
{
var rawImportsPerMinute = report.ItemFlows[rawResourceItemId].ExternalImports;
}
```
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. 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.
`GrossProduction` and `GrossConsumption` are independent ledgers. `NetFlow` is their difference; imports, known supply, target delivery, and surplus remain separate fields. `Power.ConsumptionWatts` uses equivalent fully utilized buildings, whereas `PeakConsumptionWatts` uses rounded deployment counts. Fixed layout power is not inferred: add explicitly selected sorters, spray coaters, or other non-logistics auxiliary devices to `request.AuxiliaryBuildings`. The power scope then changes from `ProductionBuildings` to `ProductionBuildingsAndAuxiliary`.
## Fixed-building analysis
By default, 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. The optional blueprint production basis below changes material ledgers only when explicitly requested.
`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 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.
`FactoryBlackBoxRequest.ProductionBasis` defaults to `BlueprintProductionBasis.FinalProducts`, preserving these existing full-load semantics for all callers. The blueprint inspector can explicitly select `BottleneckIntermediate`. This mode reuses `TwoPhaseSimplex` to maximize one common fraction, no greater than 1, of the selected final-product mix, bounded by each selected process's capacity. Terminal consumers without item outputs, such as launchers, fuel generators, or precisely configured research, operate at that same fraction. Every internally produced material must balance without external imports; only materials with no selected producer can enter from outside. Capacities are converted through recipe ratios and shared consumption, rather than comparing different items' absolute per-minute rates. Joint products and selected cycles participate in the same balance; no unselected recipe is introduced. After maximizing the common fraction, the solver minimizes used building capacity, then remaining normalized surplus.
On a successful bottleneck calculation, all material ledgers, external inputs, final outputs, and research-matrix outlets use the normalized process rates. Unused positive intermediate capacity, including fractional building capacity, is reported as excess. This measures spare rated capacity rather than actual surplus stock or extra throughput; that capacity may not be simultaneously attainable from the normalized upstream flow. Surplus necessarily produced alongside required joint products remains coproduct output. A complete, balanceable chain therefore has no internal shortage within numerical tolerance. `Groups` and power retain the full selected building capacities, so normalized material rates must not be used to infer reduced power demand. Unknown material data, an unidentified final outlet, zero feasible throughput, or a failed or limited solve produces `BlueprintBasisUnavailable`; the inspector then preserves the existing description and fields. A pure cycle without a final outlet cannot establish this basis. A selection with no internal intermediate can retain its rated final output; a known selection with no material flows can still generate its power field without a material solve. Independently unknown power does not become known through balancing.
```csharp
var capture = BlueprintSelectionReader.Capture(factory, selectedObjectIds);
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, 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.
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, 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.
Native research uses the current lab technology's matrix point requirements, with 3,600 points consumed per item. Precise live or manually supplied research settings still require `TechId` and `ResearchSpeed`. `ProductionCatalogReader` independently captures native `LabComponent.matrixIds` as immutable `ResearchMatrixItemIds`. `FromBlueprint` sets `ResearchMatrixSink` rather than using the current technology or research speed. In this blueprint-only model, one selected research lab provides a virtual outlet for every native matrix item manufactured in the blueprint. Protect this production against whole and fractional upstream reductions; classify its positive net rate after other buildings' known consumption as a final research product, not a redundant building or exported coproduct. Do not add a fabricated matrix consumption rate, external matrix requirement, or research hash rate to the lab's numeric report. Known matrix use by other selected processes remains a real material input; if native matrix IDs are unavailable, material completeness is unknown while separately known lab power remains available. The outlet is a planning convention, not a simulation of real lab throughput or belt connectivity.
## Blueprint descriptions
The shared `UIBlueprintInspector` in browser, copy, and paste modes adds a compact `Auto-fill` entry to the existing description header. Its options open on demand within the inspector, rather than occupying the browser file grid. Only UXAssist-owned transforms are positioned: native fields, groups, anchors, and scroll height remain owned by the game. No per-frame layout patch or native-settings tracking is needed. Disable and destruction remove only the UXAssist controls.
The options contain `Auto-fill description`, `Proliferation`, and a `Production basis` selector with a localized help tip. Each inspector open resets the basis to `Final-product output`, retaining existing calculation behavior; selecting `Lowest intermediate throughput` opts into `BottleneckIntermediate` for generation. The checkbox initially reflects the blueprint's Spray Coater prefab capability and tracks content changes until manually changed in the current editing session; changing it does not modify the blueprint. Generation captures only `blueprint.buildings` with `BlueprintSelectionReader.FromBlueprint` on the game thread, then runs `FactoryBlackBoxAnalyzer` against the captured catalog. A successful bottleneck solve supplies classification and steady-state balances directly; the original classifier runs only in final-product mode or after an unavailable bottleneck result. The maximum supported proliferation level applies while each building keeps its acceleration or extra-products mode. Input coating is assumed to be supplied externally; no spray routing or spray consumption is inferred from the Spray Coater.
`BlueprintDescriptionFormatter` builds replacement multiline `blueprint.desc` text in this order: optional `Missing:` and `Excess:` lines for intermediate shortages and excess classified by the selected production basis; `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. Large displayed rates use the largest exact K/M/G suffix with at most one decimal place (for example, 1,234,000 becomes 1,234K); if no suffix preserves that display precision, keep the ordinary number. Numbers with four or more integer digits use comma thousands separators, including coefficients before material or power units. Rates are 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 or bottleneck basis, 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` owns the groups' positions and scroll height. `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. See [blueprint description validation](BlueprintDescriptionValidation.md) for native layout evidence and manual compatibility checks.
## 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.
| Facility | Settings and behavior |
| --- | --- |
| 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. 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, 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. |
| Research-mode lab | `ResearchMode = 1`; precise research needs `TechId` and `ResearchSpeed`, neither stored in a blueprint. Blueprint capture sets `ResearchMatrixSink`: a single lab can receive all six native matrix types produced by the selection, without a numerical input or hash-rate estimate. All labs count at full working power even when technology is missing or invalid; apply the supported proliferation power factor or base power when no spray level exists. Precise native matrix proliferation increases hashes and power, not matrix input per base hash. |
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. 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
The belt-signal generator uses `ProductionPlanner` material reports, not its former recursive ingredient table. Its caller-side preset keeps the legacy recipe preference: explicit recipes, including the rare-resource alternatives, supply items first through `ProductionRecipe.Explicit`, except explicit recipes that consume their own product, such as X-ray Cracking and Reforming Refine; natural items stay raw. The preset also 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
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 build UniverseGenTweaks/UniverseGenTweaks.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.
- 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.
- 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. 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 the localized description-header entry and options, Spray Coater defaults and manual overrides, and native item tags in the generated description and `Power` field. Confirm options close after successful generation or inspector closure, the file grid stays usable, and native settings and description fields retain their positions. 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 both production bases on an undersupplied chain, uneven recipe ratios, shared intermediate branches, and a joint-product chain. Final-product mode must retain rated final outputs and expose intermediate shortages. Bottleneck mode must scale final outputs together, update raw inputs to the same throughput, and leave no internal shortage for a complete, balanceable chain. Confirm unused intermediate capacity and necessary coproduct output remain distinct, and that power stays at the same full-load estimate. Test a chain without internal intermediates, missing building settings, and a cycle without a final outlet; an unavailable bottleneck basis must preserve existing description and fields.
- 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.
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "UXAssist", "name": "UXAssist",
"version_number": "1.6.3", "version_number": "1.6.4",
"website_url": "https://github.com/soarqin/DSP_Mods/tree/master/UXAssist", "website_url": "https://github.com/soarqin/DSP_Mods/tree/master/UXAssist",
"description": "Some functions and patches for better user experience / 一些提升用户体验的功能和补丁", "description": "Some functions and patches for better user experience / 一些提升用户体验的功能和补丁",
"dependencies": [ "dependencies": [
@@ -0,0 +1,7 @@
<Project>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
</Project>
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="../../Production/*.cs"
Exclude="../../Production/ProductionCatalogReader.cs;../../Production/BlueprintSelectionReader.cs" />
<Compile Include="../../Common/GameConstants/ItemIds.cs" />
<Compile Include="../../../CheatEnabler/Patches/Factory/BeltSignalSourceStats.cs" />
</ItemGroup>
</Project>
File diff suppressed because it is too large. Load diff
+9
View File
@@ -381,6 +381,15 @@ internal static class QuickMinerPlacementTests
Check(snapshot.schema is 1 or 2 or 3 or 4, "Unsupported debug snapshot schema."); Check(snapshot.schema is 1 or 2 or 3 or 4, "Unsupported debug snapshot schema.");
Check(snapshot.nodes != null && snapshot.candidates != null && snapshot.buildColliders != null && snapshot.minerColliders != null && snapshot.phases != null, Check(snapshot.nodes != null && snapshot.candidates != null && snapshot.buildColliders != null && snapshot.minerColliders != null && snapshot.phases != null,
"This snapshot contains summary data only and cannot be replayed. Run quick miner placement again with the updated build."); "This snapshot contains summary data only and cannot be replayed. Run quick miner placement again with the updated build.");
if (snapshot.algorithm?.EndsWith("-target-group", StringComparison.Ordinal) == true)
{
var targetIds = snapshot.nodes.Where(node => node.target).Select(node => node.id).ToHashSet();
Check(snapshot.candidates.All(candidate => candidate.covered.All(index => snapshot.nodes[index].target)),
"Candidate coverage must exclude neighboring vein groups, including those of the same type.");
Check((snapshot.placements ?? []).All(placement =>
(placement.plannedVeins ?? []).Concat(placement.finalVeins ?? []).All(targetIds.Contains)),
"Planned and final miner parameters must contain only nodes from the selected vein group.");
}
Console.WriteLine($"Snapshot: outcome={snapshot.outcome}, nodes={snapshot.nodes.Length}, candidates={snapshot.candidates.Length}, placed={snapshot.placedCount}, actual coverage={snapshot.totalCoverage}"); Console.WriteLine($"Snapshot: outcome={snapshot.outcome}, nodes={snapshot.nodes.Length}, candidates={snapshot.candidates.Length}, placed={snapshot.placedCount}, actual coverage={snapshot.totalCoverage}");
foreach (var failure in (snapshot.placements ?? []).Where(p => p.outcome != "placed").GroupBy(p => (p.outcome, p.nativeCondition))) foreach (var failure in (snapshot.placements ?? []).Where(p => p.outcome != "placed").GroupBy(p => (p.outcome, p.nativeCondition)))
Console.WriteLine($"Placement {failure.Key.outcome}: native={failure.Key.nativeCondition}, count={failure.Count()}"); Console.WriteLine($"Placement {failure.Key.outcome}: native={failure.Key.nativeCondition}, count={failure.Count()}");