diff --git a/AGENTS.md b/AGENTS.md index cf5a595..d74328a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,9 +30,11 @@ ## Architecture -- Fixed-building UXAssist power reports include each selected logistics station, distributor, or battle base at its captured configured charging maximum in watts, not its transient draw. Keep charging power separate from accumulator exchange and do not double-count advanced miners or gas collectors. Blueprint and prebuild capture use native stored settings or prefab defaults when no charging setting is applied. +- Fixed-building UXAssist power reports include each selected logistics station, distributor, or battle base at its captured configured charging maximum in watts, not its transient draw. Keep factory and logistics consumption independently usable when the other category is unknown; retain the original total-power API and never display an incomplete category as zero. Keep charging power separate from accumulator exchange and do not double-count advanced miners or gas collectors. Blueprint and prebuild capture use native stored settings or prefab defaults when no charging setting is applied. - UXAssist production calculations must use immutable snapshots captured from loaded Proto, PrefabDesc, and Cargo data on the game thread. Keep the planner and fixed-building analyzer pure-managed, express material rates in double items per minute and power in watts, and report unknown material and power results independently with structured diagnostics. Convert native ticks, fixed-point speeds, and per-second rates explicitly. Use native facility-specific production and power rules; keep generation, accumulator charging and discharging, and Dyson-sphere demand separate. Require explicit resource and operating settings when they cannot be captured, and never capture transient runtime throttles such as the miner output damper. Treat a stored sandbox boost mode as applied only through an explicit or live-captured `BoostEnabled` state. Verify native rules against the original DLL, compile affected mods, and keep the synthetic `UXAssist/tools/ProductionCheck` checks passing; leave in-game validation to a person rather than automated gameplay or save parsing. See [production architecture](UXAssist/docs/ProductionArchitecture.md). - Production catalog synthetic recipe IDs are calculation-only negative output item IDs; never pass them to native recipe lookups or setters. Rebuild the catalog on game begin after preload mutations, and invalidate derived caches on `ProductionCatalogService.Changed`, including catalog clearing. Preserve accumulator coating through exchange and bound spray reuse by same-item output and demand. Live-selection operating overrides use signed object IDs; blueprint overrides use blueprint indices. Keep renewable generation at ideal rated conditions and do not count gas collectors' self-fueling as grid consumption. +- Black-box material classification must use process net flows while retaining gross production and consumption. Attribute redundant whole-building output using one stable shared material budget that preserves final-product capacity and does not worsen internal shortages; derive coproduct surplus from retained whole buildings required by other products, crediting internal net consumption first. Do not relabel limiting-product or single-product headroom as a coproduct or change the original full-load report. Derive separate steady-state external inputs by throttling surplus upstream processes together with all their outputs and inputs, including fractional and multi-stage headroom; preserve independently known rated final outputs and do not worsen shortages. For incomplete materials, still cap independently known upstream inputs against known demand, but protect potential consumers of unresolved processes rather than treating their demand as zero. A blueprint research-mode lab protects all native matrices manufactured in the selection from upstream reduction; classify their positive net production after other buildings' known consumption as final research products without falsely reporting excess or adding fictitious gross consumption. Leave other uncertain overbuild, coproduct, and final-product conclusions unknown. +- Blueprint auto-description reads only the current blueprint's buildings on button click. Keep the proliferation checkbox to the right of the button on one compact row above all description boxes. Shift the first native inspector group down once and the following groups after every refresh, restoring the original layout on disable. Replace the main description with nonempty Missing, Excess, Input, Output, and Research lines; group each warning category under one prefix, omit the per-minute suffix without changing rate units, and use only an optional power custom field with absent consumption categories omitted. Format material inputs from the separate steady-state estimate without altering full-load ledgers or power. Budget every research-mode lab at full prefab working power for conservative blueprint power capacity, even if current research is idle or technology is missing or invalid; apply a supported proliferation multiplier. Blueprint research treats one lab as an outlet for all six native matrix types actually manufactured within the selected buildings; capture their IDs independently of technology requirements and do not infer matrix demand, research speed, hashes, or external inputs from the current save. Display positive net matrix output only on Research, not ordinary Output; keep precise technology-dependent research requirements for callers without this blueprint assumption. Treat research power as independently complete when no other power category is unknown. Synchronize pending native field edits; update or remove exact bilingual power fields without changing any other custom fields, including fields titled Input or Output. Check the native description and field limits before writing, use native field escaping and item tags, and refresh the inspector without automatic saving or changes to native rendering or validation. Keep Spray Coater defaults and manual proliferation overrides scoped to the editing session; keep text formatting and field updates pure-managed under `ProductionCheck`. See [production architecture](UXAssist/docs/ProductionArchitecture.md). - CheatEnabler belt-signal upstream statistics use the shared production planner's independent production and consumption ledgers. Cache per-item material results by catalog and spray settings, keep separate per-belt fractional accumulators, and never run the solver in the logic tick. Missing data must not interrupt item generation. - UXAssist Dark Fog buy-out belt signals keep each item ID, per-Metaverse rate, localization key, and embedded icon path in one definition. Name embedded icon files after the current English item names and synchronize resource includes and loader paths when renaming them. Preserve the legacy signal and saved-stock order. Rates represent equivalent single-material value: a native bundle of 10 Silicon-based Neurons, 10 Negentropy Singularities, and 10 Matter Recombinators per Metaverse corresponds to 30 of any one selected material per Metaverse. - 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. diff --git a/UXAssist/CHANGELOG.md b/UXAssist/CHANGELOG.md index 8c69d50..0a78fee 100644 --- a/UXAssist/CHANGELOG.md +++ b/UXAssist/CHANGELOG.md @@ -18,6 +18,7 @@ * `Belt signals for buy out dark fog items automatically`: Use the current in-game material names and retain the original exchange ratios. * `Initialize This Planet`: Fix an occasional array index error after initializing a planet with Holo Beacons. * `Planet vein utilization`: Restore the original vertical alignment of vein-group counts and keep resource names in their original positions. + * `Blueprint descriptions`: Add a row with an Auto-fill description button and a right-hand Proliferation checkbox above all description boxes in the browser, copy, and paste inspectors. Replace the main description with wrapping, nonempty Missing, Excess, Input, Output, and Research lines: group each warning category under one label and omit the per-minute suffix while keeping per-minute rates. Cap upstream inputs at sustainable downstream throughput even when unrelated parameters are unknown, without assuming unknown downstream demand is zero; keep independently known rated outputs and power. Budget every research-mode lab at full working power, and treat one selected lab as an outlet for all six matrix types made within the blueprint, regardless of the save's technology or research speed. Display positive net matrix output only under Research, after other buildings' known matrix use; keep unrelated final products under Output. Do not invent matrix consumption rates or imports, and do not flag the accepted output as excess. Keep Power as the only optional generated custom field, showing factory and logistics demand only when present and marking unknown demand separately. Report necessary coproducts and incomplete results, preserve other custom fields, and never save automatically. Fix false coproduct output in mixed production lines and at fractional building ratios. * 1.6.1 * `Larger area for terraform`: Restore 11x11 through 30x30 foundation and Restore Terrain brushes after DSP 0.10.35.29104. * Fix the title-screen background turning black, even when the UXAssist window is closed. @@ -452,6 +453,7 @@ * `用于自动购买黑雾物品的传送带信号`:统一使用当前游戏中的材料名称,保留原有兑换比例。 * `初始化本行星`:修复行星上存在全息信标时,初始化后可能出现数组越界报错的问题。 * `宇宙视图行星/星系矿脉数量显示`:修复矿脉数量文字偏下和矿物名称向右偏移的问题。 + * `蓝图说明`:在蓝图浏览、复制和粘贴界面的所有说明框上方增加「自动填写说明」按钮,并将「增产」复选框放在按钮右侧。直接用可换行内容替换原说明:按需依次显示「缺少:」「多余:」「输入:」「输出:」「研究:」,缺少或多余的物品共用一次行标签;标签不再显示「每分钟」,材料速率仍按每分钟计算。上游产量超过下游需求时,即使其他参数未知,也按已知下游的可持续产量估算输入;不把未知下游需求当作零。独立可确定的输出和耗电仍按额定值计算。所有研究模式研究站都按额定满负荷计入耗电;只要蓝图内有一座研究站,就假设它能接纳蓝图内产出的全部六种矩阵,不受存档科技或研究速度影响。扣除蓝图内其他建筑已知的矩阵消耗后,仅将净产量写入「研究」行;其他最终产物仍写入「输出」行。既不虚构研究站的矩阵消耗速率或外部需求,也不把被接纳的矩阵计为多余产量。仅在有耗电或耗电未知时生成「耗电」自定义字段,分别标注工厂与物流的有效类别。标出必要的联产盈余和数据不完整的结果;保留其他自定义字段,也不自动保存蓝图。修复混合生产线及非整数建筑配比下的副产物误报。 * 1.6.1 * `范围铺设地基的最大区域扩大`:适配 DSP 0.10.35.29104,恢复 11x11 至 30x30 的铺设地基与恢复地形范围。 * 修复标题画面背景变黑的问题,包括关闭 UXAssist 窗口后背景仍不显示的情况。 diff --git a/UXAssist/Common/I18NKeys.cs b/UXAssist/Common/I18NKeys.cs index 0a354f1..5112554 100644 --- a/UXAssist/Common/I18NKeys.cs +++ b/UXAssist/Common/I18NKeys.cs @@ -5,6 +5,27 @@ namespace UXAssist.Common; public static class I18NKeys { public const string Unknown = "Unknown"; + public const string BlueprintAutoFillDescription = "UXAssist Blueprint Auto-fill description"; + public const string BlueprintProliferation = "UXAssist Blueprint Proliferation"; + 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 TheFollowingIsTheRequiredMetadataForBuyout = "The following is the required metadata for buyout:"; public const string BatchBuyoutTech = "Batch buyout tech"; @@ -213,6 +234,25 @@ public static class I18NKeys public static void Register() { I18N.Add(Unknown, "Unknown", "未知"); + I18N.Add(BlueprintAutoFillDescription, "Auto-fill description", "自动填写说明"); + I18N.Add(BlueprintProliferation, "Proliferation", "增产"); + 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(TheFollowingIsTheRequiredMetadataForBuyout, "The following is the required metadata for buyout:", "以下是买断所需元数据:"); I18N.Add(BatchBuyoutTech, "Batch buyout tech", "批量买断科技"); diff --git a/UXAssist/Patches/BlueprintDescriptionPatch.cs b/UXAssist/Patches/BlueprintDescriptionPatch.cs new file mode 100644 index 0000000..b8cf291 --- /dev/null +++ b/UXAssist/Patches/BlueprintDescriptionPatch.cs @@ -0,0 +1,337 @@ +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 +{ + private static readonly Dictionary 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), "_OnCreate")] + private static void OnCreate(UIBlueprintInspector __instance) + { + GetControls(__instance); + } + + [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnOpen")] + private static void OnOpen(UIBlueprintInspector __instance) + { + GetControls(__instance)?.ResetSession(); + } + + [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnClose")] + private static void OnClose(UIBlueprintInspector __instance) + { + if (Inspectors.TryGetValue(__instance, out var controls)) controls.ResetSession(); + } + + [HarmonyPostfix, HarmonyPatch(typeof(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), "_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 = 22f; + private const float ControlsGap = 12f; + + private readonly UIBlueprintInspector _inspector; + private readonly float _controlsHeight; + private UIButton _button; + private Text _buttonText; + private MyCheckBox _checkbox; + private BlueprintData _currentBlueprint; + private bool _manualProliferation; + private bool _layoutApplied; + + public InspectorControls(UIBlueprintInspector inspector) + { + _inspector = inspector; + try + { + _button = LayoutHelper.AddButton(Left, 0, inspector.group1, + I18NKeys.BlueprintAutoFillDescription, 15, "blueprint-auto-fill-description", Generate); + _buttonText = _button.transform.Find("button-text").GetComponent(); + _checkbox = MyCheckBox.CreateCheckBox(Left, 0, inspector.group1, false, + I18NKeys.BlueprintProliferation.Translate(), 15).WithSmallerBox(22f); + _checkbox.gameObject.name = "blueprint-proliferation"; + _checkbox.OnChecked += OnProliferationChecked; + UpdateLabels(); + _controlsHeight = Math.Max(_button.transform.GetComponent().rect.height, + _checkbox.rectTrans.rect.height) + 10f; + } + catch + { + if (_button) UnityEngine.Object.Destroy(_button.gameObject); + if (_checkbox) UnityEngine.Object.Destroy(_checkbox.gameObject); + throw; + } + } + + public void ResetSession() + { + _currentBlueprint = null; + _manualProliferation = false; + if (_inspector.blueprint != null) SyncDefault(); + else _checkbox.Checked = false; + } + + public void Refresh() + { + SyncDefault(); + if (!_layoutApplied) + _inspector.group1.anchoredPosition += new Vector2(0, -_controlsHeight); + PositionControls(); + _inspector.group2.anchoredPosition += new Vector2(0, -_controlsHeight); + _inspector.group3.anchoredPosition += new Vector2(0, -_controlsHeight); + _inspector.group4.anchoredPosition += new Vector2(0, -_controlsHeight); + _inspector.contentTrans.sizeDelta += new Vector2(0, _controlsHeight); + _layoutApplied = true; + } + + public void UpdateLabels() + { + _buttonText.text = I18NKeys.BlueprintAutoFillDescription.Translate(); + _checkbox.SetLabelText(I18NKeys.BlueprintProliferation.Translate()); + var width = Math.Max(160f, Util.GetPreferredWidth(_buttonText) + 26f); + _button.transform.GetComponent().sizeDelta = + new Vector2(width, _button.transform.GetComponent().sizeDelta.y); + if (_layoutApplied) PositionControls(); + } + + public void Destroy() + { + if (_layoutApplied && _inspector) + { + _inspector.group1.anchoredPosition += new Vector2(0, _controlsHeight); + _inspector.group2.anchoredPosition += new Vector2(0, _controlsHeight); + _inspector.group3.anchoredPosition += new Vector2(0, _controlsHeight); + _inspector.group4.anchoredPosition += new Vector2(0, _controlsHeight); + _inspector.contentTrans.sizeDelta += new Vector2(0, -_controlsHeight); + _layoutApplied = false; + } + + if (_button) + { + _button.button.onClick.RemoveListener(Generate); + UnityEngine.Object.Destroy(_button.gameObject); + } + + if (_checkbox) + { + _checkbox.OnChecked -= OnProliferationChecked; + UnityEngine.Object.Destroy(_checkbox.gameObject); + } + } + + private void PositionControls() + { + var buttonRect = _button.transform.GetComponent(); + var top = 4f - _controlsHeight; + Util.NormalizeRectWithTopLeft(_button, Left, top, _inspector.group1); + Util.NormalizeRectWithTopLeft(_checkbox, Left + buttonRect.rect.width + ControlsGap, + top + (buttonRect.rect.height - _checkbox.rectTrans.rect.height) / 2f, _inspector.group1); + } + + private void SyncDefault() + { + var blueprint = _inspector.blueprint; + if (!ReferenceEquals(blueprint, _currentBlueprint)) + { + _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 report = new FactoryBlackBoxAnalyzer(catalog).Analyze(capture.CreateRequest(_checkbox.Checked)); + 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 fields = new[] + { + new BlueprintDescriptionField(I18NKeys.BlueprintPower.Translate(), + description.Power.Length > 0 ? description.Power : null, + I18NKeys.BlueprintPowerEnglish, I18NKeys.BlueprintPowerChinese) + }; + var result = BlueprintDescriptionFields.TryUpdate(blueprint.externalFields, fields, + 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; + } + + 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()); + } + } + } +} diff --git a/UXAssist/Production/BlackBoxMaterialClassifier.cs b/UXAssist/Production/BlackBoxMaterialClassifier.cs new file mode 100644 index 0000000..58fc707 --- /dev/null +++ b/UXAssist/Production/BlackBoxMaterialClassifier.cs @@ -0,0 +1,247 @@ +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 NetPerBuilding { get; } + public bool HasJointProducts { get; } + + public BlackBoxProcessGroup(ProductionProcess process, ProductionBuildingSnapshot snapshot) + { + Process = process; + Count = snapshot.Count; + var net = new Dictionary(); + 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 bool IsIntermediate { get; } + public double IntermediateShortage { get; } + public double? OverbuildSurplus { get; } + public double? CoproductSurplus { get; } + + public BlackBoxItemClassification(bool isFinalProduct, bool isResearchProduct, bool isIntermediate, + double intermediateShortage, double? overbuildSurplus, double? coproductSurplus) + { + IsFinalProduct = isFinalProduct; + IsResearchProduct = isResearchProduct; + IsIntermediate = isIntermediate; + IntermediateShortage = intermediateShortage; + OverbuildSurplus = overbuildSurplus; + CoproductSurplus = coproductSurplus; + } +} + +internal static class BlackBoxMaterialClassifier +{ + internal const double Tolerance = 1e-9; + + private sealed class ReductionGroup + { + public BlackBoxProcessGroup Source { get; } + public int Count { get; } + public int Removed { get; set; } + + public ReductionGroup(IGrouping grouped) + { + Source = grouped.First(); + Count = grouped.Sum(entry => entry.Count); + } + } + + public static IReadOnlyDictionary Classify( + IReadOnlyList processes, IReadOnlyDictionary grossProduction, + IReadOnlyDictionary grossConsumption, bool materialComplete, + IReadOnlyCollection uncertainDemandItems, bool unknownDemand, ISet researchMatrixSinks, + out IReadOnlyDictionary steadyStateBalance) + { + var producerItems = new HashSet(); + var consumerItems = new HashSet(); + 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(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(originalBalance); + var finalItems = new HashSet(producerItems.Where(itemId => !consumerItems.Contains(itemId))); + var intermediateItems = new HashSet(producerItems.Where(consumerItems.Contains)); + var protectedItems = new HashSet(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(); + 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, intermediateItems)); + 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, isIntermediate ? Math.Max(0, -originalNet) : 0, overbuild, coproduct); + } + + steadyStateBalance = CalculateSteadyStateBalance(groups, originalBalance, remainingBalance, + protectedItems, intermediateItems); + return classification; + } + + private static double NecessaryJointProduction(ReductionGroup group, int itemId, + IReadOnlyDictionary originalBalance, IReadOnlyDictionary remainingBalance, + ISet protectedItems, ISet intermediateItems) + { + 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; + double minimum; + if (protectedItems.Contains(flow.Key)) minimum = originalBalance[flow.Key]; + else if (intermediateItems.Contains(flow.Key)) minimum = Math.Min(0, originalBalance[flow.Key]); + else continue; + var 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 CalculateSteadyStateBalance( + IReadOnlyList groups, IReadOnlyDictionary originalBalance, + IReadOnlyDictionary remainingBalance, ISet protectedItems, ISet intermediateItems) + { + var balance = remainingBalance.ToDictionary(entry => entry.Key, entry => entry.Value); + var available = groups.ToDictionary(group => group, group => (double)(group.Count - group.Removed)); + bool changed; + do + { + 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; + double minimum; + if (protectedItems.Contains(flow.Key)) minimum = originalBalance[flow.Key]; + else if (intermediateItems.Contains(flow.Key)) minimum = Math.Min(0, originalBalance[flow.Key]); + else continue; + 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; + } + } while (changed); + + return balance; + } + + private static bool CanRemove(IReadOnlyDictionary netPerBuilding, + IReadOnlyDictionary originalBalance, IReadOnlyDictionary remainingBalance, + ISet protectedItems, ISet 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; + } +} diff --git a/UXAssist/Production/BlueprintDescriptionText.cs b/UXAssist/Production/BlueprintDescriptionText.cs new file mode 100644 index 0000000..6c253e4 --- /dev/null +++ b/UXAssist/Production/BlueprintDescriptionText.cs @@ -0,0 +1,288 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; + +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(); + 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; + + public static BlueprintDescriptionText Format(ProductionReport report, Func 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(); + 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(); + var excess = new List(); + var input = new List(); + var output = new SortedDictionary(); + var research = new SortedDictionary(); + 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(); + 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 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 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" + FormatNumber(rate); + } + + private static string FormatPower(double? watts, BlueprintDescriptionLabels labels) + { + if (!watts.HasValue) return labels.Unknown; + var value = watts.Value; + if (value >= 1e12) return FormatNumber(value / 1e12) + "TW"; + if (value >= 1e9) return FormatNumber(value / 1e9) + "GW"; + if (value >= 1e6) return FormatNumber(value / 1e6) + "MW"; + if (value >= 1e3) return FormatNumber(value / 1e3) + "kW"; + return FormatNumber(value) + "W"; + } + + private static string FormatNumber(double value) + { + if (double.IsNaN(value) || double.IsInfinity(value) || value < 0) + throw new InvalidOperationException("A blueprint report contains an invalid rate or power value."); + var rounded = Math.Round(value, value < 1 ? 3 : 2, MidpointRounding.AwayFromZero); + 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 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; + } + + public static BlueprintFieldUpdateResult TryUpdate(string existing, IReadOnlyList fields, + int maximumFields, Func escape, Func unescape, out string updated) + { + updated = existing; + if (fields == null || escape == null || unescape == null) + throw new ArgumentNullException(fields == null ? nameof(fields) : escape == null ? nameof(escape) : nameof(unescape)); + if (maximumFields < 0 || !IsNativeFormatValid(existing)) + return BlueprintFieldUpdateResult.InvalidFields; + + var parts = (existing ?? "").Split(';'); + var matches = new int[parts.Length]; + var found = new bool[fields.Count]; + var nativeCount = 0; + var removedCount = 0; + for (var index = 0; index < parts.Length - 1; index++) + { + var delimiter = parts[index].IndexOf(':'); + nativeCount++; + var name = unescape(parts[index].Substring(0, delimiter)); + for (var fieldIndex = 0; fieldIndex < fields.Count; fieldIndex++) + { + if (!fields[fieldIndex].Matches(name)) continue; + if (fields[fieldIndex].Value == null || found[fieldIndex]) + { + matches[index] = -1; + removedCount++; + } + else + { + matches[index] = fieldIndex + 1; + found[fieldIndex] = true; + } + break; + } + } + + var missingCount = 0; + for (var index = 0; index < fields.Count; index++) + if (!found[index] && fields[index].Value != null) missingCount++; + if (nativeCount - removedCount + missingCount > maximumFields) + return BlueprintFieldUpdateResult.CapacityExceeded; + + var serialized = new StringBuilder(); + for (var index = 0; index < parts.Length - 1; index++) + { + var match = matches[index]; + if (match < 0) continue; + if (match > 0) + { + var field = fields[match - 1]; + serialized.Append(escape(field.Title)).Append(':').Append(escape(field.Value)); + } + else + { + serialized.Append(parts[index]); + } + + serialized.Append(';'); + } + + for (var index = 0; index < fields.Count; index++) + { + if (!found[index] && fields[index].Value != null) + serialized.Append(escape(fields[index].Title)).Append(':').Append(escape(fields[index].Value)) + .Append(';'); + } + + updated = serialized.ToString(); + return BlueprintFieldUpdateResult.Updated; + } +} diff --git a/UXAssist/Production/BlueprintSelectionReader.cs b/UXAssist/Production/BlueprintSelectionReader.cs index 8852004..15a17d1 100644 --- a/UXAssist/Production/BlueprintSelectionReader.cs +++ b/UXAssist/Production/BlueprintSelectionReader.cs @@ -173,6 +173,8 @@ public static class BlueprintSelectionReader }); var operation = new Dictionary(); AddSettings(parameters, operation); + if (operation.ContainsKey("ResearchMode")) + operation["ResearchMatrixSink"] = 1; if (building.Kind == ProductionBuildingKind.Logistics) CaptureStoredChargePower(building, parameters, blueprint.parameters, operation); ApplySupplied(context?.OperatingParametersByIndex, blueprint.index, operation); @@ -449,7 +451,9 @@ public static class BlueprintSelectionReader IReadOnlyDictionary operation, ICollection diagnostics) { var kind = building.Kind; - var requiredKey = parameters.type == BuildingType.Lab && parameters.mode0 == 2 ? "TechId" : + 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" : @@ -458,8 +462,7 @@ public static class BlueprintSelectionReader diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, $"The selected building needs the {requiredKey} operating parameter.", buildingItemId: building.ItemId)); - if (parameters.type == BuildingType.Lab && parameters.mode0 == 2 && - !operation.ContainsKey("ResearchSpeed")) + if (researchNeedsTechnology && !operation.ContainsKey("ResearchSpeed")) diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, "The research lab needs the current research technology speed.", buildingItemId: building.ItemId)); diff --git a/UXAssist/Production/FactoryBlackBoxAnalyzer.cs b/UXAssist/Production/FactoryBlackBoxAnalyzer.cs index 50228f4..d73626f 100644 --- a/UXAssist/Production/FactoryBlackBoxAnalyzer.cs +++ b/UXAssist/Production/FactoryBlackBoxAnalyzer.cs @@ -59,19 +59,26 @@ public sealed class FactoryBlackBoxAnalyzer var diagnostics = new List(request.CaptureDiagnostics); var groups = new List(); + var processGroups = new List(); var grossProduction = new SortedDictionary(); var grossConsumption = new SortedDictionary(); var producers = new Dictionary>(); var consumers = new Dictionary>(); var smallestProducer = new Dictionary(); + var hasResearchMatrixSink = false; + var uncertainDemandItems = new HashSet(); var selectedIds = new HashSet(); var skippedSelection = diagnostics.Any(diagnostic => diagnostic.Code == ProductionDiagnosticCode.InvalidRequest || diagnostic.Code == ProductionDiagnosticCode.UnknownItem || diagnostic.Code == ProductionDiagnosticCode.DataNotReady); + var unknownDemand = skippedSelection; var materialComplete = !skippedSelection; - var powerComplete = !skippedSelection; - var consumptionWatts = 0.0; + 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; @@ -84,7 +91,9 @@ public sealed class FactoryBlackBoxAnalyzer diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, "A selected building has an invalid count.")); materialComplete = false; - powerComplete = false; + factoryPowerComplete = false; + logisticsPowerComplete = false; + unknownDemand = true; continue; } @@ -101,7 +110,9 @@ public sealed class FactoryBlackBoxAnalyzer "The selected building is not supported by the catalog.", buildingItemId: snapshot.BuildingItemId)); materialComplete = false; - powerComplete = false; + factoryPowerComplete = false; + logisticsPowerComplete = false; + unknownDemand = true; continue; } @@ -113,7 +124,9 @@ public sealed class FactoryBlackBoxAnalyzer "A research-mode lab cannot also run a manufacturing recipe.", recipeId: snapshot.RecipeId, buildingItemId: snapshot.BuildingItemId)); materialComplete = false; - powerComplete = false; + factoryPowerComplete = false; + logisticsPowerComplete = false; + unknownDemand = true; continue; } @@ -132,8 +145,8 @@ public sealed class FactoryBlackBoxAnalyzer else logisticsWatts = chargePowerWatts * snapshot.Count; - if (logisticsWatts.HasValue) consumptionWatts += logisticsWatts.Value; - else powerComplete = false; + if (logisticsWatts.HasValue) logisticsConsumptionWatts += logisticsWatts.Value; + else logisticsPowerComplete = false; groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count, logisticsWatts, logisticsWatts, Array.Empty>(), Array.Empty>())); @@ -149,7 +162,7 @@ public sealed class FactoryBlackBoxAnalyzer { var idleWatts = (building.Kind == ProductionBuildingKind.Auxiliary ? building.WorkingPowerWatts : building.IdlePowerWatts) * snapshot.Count; - consumptionWatts += idleWatts; + factoryConsumptionWatts += idleWatts; groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count, idleWatts, idleWatts, Array.Empty>(), Array.Empty>())); @@ -164,25 +177,53 @@ public sealed class FactoryBlackBoxAnalyzer "The selected building's recipe is missing.", recipeId: snapshot.RecipeId, buildingItemId: snapshot.BuildingItemId)); materialComplete = false; - powerComplete = 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) materialComplete = false; - powerComplete = false; + 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(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count, + knownWatts, knownWatts, Array.Empty>(), + Array.Empty>())); + } + else + { + totalPowerKnown = false; + factoryPowerComplete = false; + } continue; } if (diagnostic != null) diagnostics.Add(diagnostic); - if (!process.PowerKnown) powerComplete = false; + if (!process.PowerKnown) totalPowerKnown = false; + if (process.WorkingPowerWatts < 0 || double.IsNaN(process.WorkingPowerWatts) || + double.IsInfinity(process.WorkingPowerWatts * snapshot.Count)) factoryPowerComplete = false; var cycleRate = process.CyclesPerBuildingPerMinute; var output = Scale(process.OutputsPerCycle, cycleRate * snapshot.Count); var input = Scale(process.InputsPerCycle, cycleRate * snapshot.Count); @@ -205,7 +246,7 @@ public sealed class FactoryBlackBoxAnalyzer } var watts = process.WorkingPowerWatts * snapshot.Count; - consumptionWatts += watts; + factoryConsumptionWatts += watts; generationWatts += process.GenerationWatts * snapshot.Count; chargingWatts += process.AccumulatorChargingWatts * snapshot.Count; dischargingWatts += process.AccumulatorDischargingWatts * snapshot.Count; @@ -217,8 +258,13 @@ public sealed class FactoryBlackBoxAnalyzer 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(_catalog.ResearchMatrixItemIds) : new HashSet(); + var classifications = BlackBoxMaterialClassifier.Classify(processGroups, grossProduction, grossConsumption, + materialComplete, uncertainDemandItems, unknownDemand, matrixSinkItems, out var steadyStateBalance); var flows = new List(); var allItems = new SortedSet(grossProduction.Keys); allItems.UnionWith(grossConsumption.Keys); @@ -228,22 +274,32 @@ public sealed class FactoryBlackBoxAnalyzer var consumed = grossConsumption.TryGetValue(itemId, out var c) ? c : 0; var net = produced - consumed; var threshold = smallestProducer.TryGetValue(itemId, out var single) ? single : 0; - var isFinalProduct = produced > 1e-9 && consumed <= 1e-9; + var classification = classifications[itemId]; + var isFinalProduct = classification.IsFinalProduct; flows.Add(new ProductionItemFlow(itemId, produced, consumed, 0, 0, 0, Math.Max(0, net), Math.Max(0, -net), isFinalProduct, - !isFinalProduct && consumed > 1e-9 && net > 1e-9 && threshold > 0 && + classification.IsIntermediate && !matrixSinkItems.Contains(itemId) && + net > 1e-9 && threshold > 0 && net + 1e-9 >= threshold, threshold, producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty(), - consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty())); + consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty(), + classification.IntermediateShortage, classification.OverbuildSurplus, + classification.CoproductSurplus, + steadyStateBalance == null ? null : Math.Max(0, -steadyStateBalance[itemId]), + classification.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); + return new ProductionReport(status, materialComplete, powerComplete, flows, groups, diagnostics, power, + new ProductionPowerBreakdown(factoryConsumptionWatts, logisticsConsumptionWatts, + factoryPowerComplete, logisticsPowerComplete)); } private static ProliferationMode FullProliferationMode(ProductionBuilding building, @@ -272,6 +328,45 @@ public sealed class FactoryBlackBoxAnalyzer } } + private bool TryGetConsumptionWithoutMaterials(ProductionBuilding building, + ProductionBuildingSnapshot snapshot, ProductionDiagnostic diagnostic, ProliferationMode mode, + out double watts) + { + watts = 0; + if (IsResearchModeLab(building, snapshot)) + { + var multiplier = 1.0; + if (mode != ProliferationMode.None) + { + if (mode != ProliferationMode.ExtraProducts) return false; + if (_catalog.MaximumProliferationLevel > 0 && + !_catalog.TryGetProliferation(_catalog.MaximumProliferationLevel, + out _, out _, out multiplier)) return false; + } + + watts = building.WorkingPowerWatts * multiplier * snapshot.Count; + return watts > 0 && !double.IsNaN(watts) && !double.IsInfinity(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 (speed <= 0 || double.IsNaN(speed) || double.IsInfinity(speed)) return false; + var ratio = speed * speed; + watts = (building.WorkingPowerWatts * ratio + building.IdlePowerWatts * (1 - ratio)) * snapshot.Count; + return watts >= 0 && !double.IsNaN(watts) && !double.IsInfinity(watts); + } + + 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 Dictionary Scale(IReadOnlyDictionary flows, double factor) { return flows.ToDictionary(entry => entry.Key, entry => entry.Value * factor); diff --git a/UXAssist/Production/ProductionCatalogReader.cs b/UXAssist/Production/ProductionCatalogReader.cs index 1a42d47..92b32c8 100644 --- a/UXAssist/Production/ProductionCatalogReader.cs +++ b/UXAssist/Production/ProductionCatalogReader.cs @@ -114,7 +114,7 @@ public static class ProductionCatalogReader return new ProductionCatalog(items, recipes, buildings, (double[])Cargo.accTableMilli.Clone(), (double[])Cargo.incTableMilli.Clone(), - (double[])Cargo.powerTableRatio.Clone(), technologies); + (double[])Cargo.powerTableRatio.Clone(), technologies, matrixIds); } private static void AddSpecialRecipes(IEnumerable itemProtos, diff --git a/UXAssist/Production/ProductionModel.cs b/UXAssist/Production/ProductionModel.cs index 2ea4e92..5ab6495 100644 --- a/UXAssist/Production/ProductionModel.cs +++ b/UXAssist/Production/ProductionModel.cs @@ -267,17 +267,20 @@ public sealed class ProductionCatalog public IReadOnlyDictionary Recipes { get; } public IReadOnlyDictionary Buildings { get; } public IReadOnlyDictionary Technologies { get; } + public IReadOnlyCollection ResearchMatrixItemIds { get; } public int MaximumProliferationLevel { get; } public ProductionCatalog(IEnumerable items, IEnumerable recipes, IEnumerable buildings, double[] speedBonus, double[] extraBonus, double[] powerMultiplier, - IEnumerable technologies = null) + IEnumerable technologies = null, IEnumerable researchMatrixItemIds = null) { Items = new ReadOnlyDictionary(items.ToDictionary(item => item.Id)); Recipes = new ReadOnlyDictionary(recipes.ToDictionary(recipe => recipe.Id)); Buildings = new ReadOnlyDictionary(buildings.ToDictionary(building => building.ItemId)); Technologies = new ReadOnlyDictionary( (technologies ?? Array.Empty()).ToDictionary(tech => tech.Id)); + ResearchMatrixItemIds = Array.AsReadOnly((researchMatrixItemIds ?? Array.Empty()) + .Where(itemId => Items.ContainsKey(itemId)).Distinct().OrderBy(itemId => itemId).ToArray()); _speedBonus = (double[])speedBonus.Clone(); _extraBonus = (double[])extraBonus.Clone(); _powerMultiplier = (double[])powerMultiplier.Clone(); diff --git a/UXAssist/Production/ProductionPlanner.Report.cs b/UXAssist/Production/ProductionPlanner.Report.cs index 47f6ae1..c30aafa 100644 --- a/UXAssist/Production/ProductionPlanner.Report.cs +++ b/UXAssist/Production/ProductionPlanner.Report.cs @@ -21,6 +21,7 @@ public sealed partial class ProductionPlanner var groups = new List(); var activeRecipes = new HashSet(); var powerComplete = true; + var factoryPowerComplete = true; var workingPower = 0.0; var peakPower = 0.0; var generationWatts = 0.0; @@ -74,6 +75,7 @@ public sealed partial class ProductionPlanner 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)); } @@ -82,6 +84,8 @@ public sealed partial class ProductionPlanner deploymentCount = Math.Max(1, (int)Math.Ceiling(equivalentBuildings.Value - 1e-9)); consumedWatts = equivalentBuildings.Value * process.WorkingPowerWatts; peakWatts = deploymentCount.Value * process.WorkingPowerWatts; + if (consumedWatts.Value < 0 || double.IsNaN(consumedWatts.Value) || + double.IsInfinity(consumedWatts.Value)) factoryPowerComplete = false; workingPower += consumedWatts.Value; peakPower += peakWatts.Value; generationWatts += equivalentBuildings.Value * process.GenerationWatts; @@ -93,6 +97,7 @@ public sealed partial class ProductionPlanner else { powerComplete = false; + factoryPowerComplete = false; if (!warnings.Any(warning => warning.RecipeId == process.RecipeId && (warning.Code == ProductionDiagnosticCode.MissingBuilding || warning.Code == ProductionDiagnosticCode.IncompatibleBuilding))) @@ -116,6 +121,7 @@ public sealed partial class ProductionPlanner 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; @@ -136,6 +142,7 @@ public sealed partial class ProductionPlanner double.IsInfinity(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)); @@ -192,7 +199,8 @@ public sealed partial class ProductionPlanner 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); + return new ProductionReport(status, true, powerComplete, itemFlows, groups, diagnostics, power, + new ProductionPowerBreakdown(workingPower, 0, factoryPowerComplete, true)); } private static Dictionary ScaleFlows(IReadOnlyDictionary flows, double multiplier) diff --git a/UXAssist/Production/ProductionReports.cs b/UXAssist/Production/ProductionReports.cs index 875b93a..45c54ac 100644 --- a/UXAssist/Production/ProductionReports.cs +++ b/UXAssist/Production/ProductionReports.cs @@ -44,6 +44,25 @@ public sealed class ProductionPower } } +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; } @@ -55,9 +74,14 @@ public sealed class ProductionItemFlow 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 bool IsExcessIntermediate { get; } public double SingleBuildingSurplusThreshold { get; } + public double IntermediateShortage { get; } + public double? OverbuildSurplus { get; } + public double? CoproductSurplus { get; } public IReadOnlyList ProducerGroups { get; } public IReadOnlyList ConsumerGroups { get; } @@ -65,6 +89,18 @@ public sealed class ProductionItemFlow double knownExternalSupply, double delivered, double surplus, double requiredExternalSupply, bool isFinalProduct, bool isExcessIntermediate, double singleBuildingSurplusThreshold, IEnumerable producerGroups, IEnumerable consumerGroups) + : this(itemId, grossProduction, grossConsumption, externalImports, knownExternalSupply, delivered, surplus, + requiredExternalSupply, isFinalProduct, isExcessIntermediate, singleBuildingSurplusThreshold, + producerGroups, consumerGroups, 0, null, null) + { + } + + public ProductionItemFlow(int itemId, double grossProduction, double grossConsumption, double externalImports, + double knownExternalSupply, double delivered, double surplus, double requiredExternalSupply, + bool isFinalProduct, bool isExcessIntermediate, double singleBuildingSurplusThreshold, + IEnumerable producerGroups, IEnumerable consumerGroups, double intermediateShortage, + double? overbuildSurplus, double? coproductSurplus, double? steadyStateExternalSupply = null, + bool isResearchProduct = false) { ItemId = itemId; GrossProduction = grossProduction; @@ -74,9 +110,14 @@ public sealed class ProductionItemFlow Delivered = delivered; Surplus = surplus; RequiredExternalSupply = requiredExternalSupply; + SteadyStateExternalSupply = steadyStateExternalSupply; IsFinalProduct = isFinalProduct; + IsResearchProduct = isResearchProduct; IsExcessIntermediate = isExcessIntermediate; SingleBuildingSurplusThreshold = singleBuildingSurplusThreshold; + IntermediateShortage = intermediateShortage; + OverbuildSurplus = overbuildSurplus; + CoproductSurplus = coproductSurplus; ProducerGroups = Array.AsReadOnly(producerGroups.ToArray()); ConsumerGroups = Array.AsReadOnly(consumerGroups.ToArray()); } @@ -136,12 +177,21 @@ public sealed class ProductionReport public IReadOnlyList Groups { get; } public IReadOnlyList 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 itemFlows, IEnumerable groups, IEnumerable diagnostics, ProductionPower power) + : this(status, materialComplete, powerComplete, itemFlows, groups, diagnostics, power, null) + { + } + + public ProductionReport(ProductionStatus status, bool materialComplete, bool powerComplete, + IEnumerable itemFlows, IEnumerable groups, + IEnumerable diagnostics, ProductionPower power, + ProductionPowerBreakdown powerBreakdown) { Status = status; MaterialComplete = materialComplete; @@ -150,6 +200,7 @@ public sealed class ProductionReport Groups = Array.AsReadOnly(groups.ToArray()); Diagnostics = Array.AsReadOnly(diagnostics.ToArray()); Power = power; + PowerBreakdown = powerBreakdown; } internal static ProductionReport Failure(ProductionDiagnostic diagnostic) diff --git a/UXAssist/Production/ResearchProcessAdapter.cs b/UXAssist/Production/ResearchProcessAdapter.cs index d85d7ec..d253472 100644 --- a/UXAssist/Production/ResearchProcessAdapter.cs +++ b/UXAssist/Production/ResearchProcessAdapter.cs @@ -18,11 +18,7 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter process = null; diagnostic = null; if (operatingParameters == null || - !operatingParameters.TryGetValue("ResearchMode", out var researchMode) || researchMode != 1 || - !operatingParameters.TryGetValue("TechId", out var techId) || - techId <= 0 || techId > int.MaxValue || techId != Math.Truncate(techId) || - !operatingParameters.TryGetValue("ResearchSpeed", out var researchSpeed) || - !FinitePositive(researchSpeed)) + !operatingParameters.TryGetValue("ResearchMode", out var researchMode) || researchMode != 1) { diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, "Research mode needs a lab technology and current research speed.", @@ -30,12 +26,41 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter return false; } - if (!catalog.Technologies.TryGetValue((int)techId, out var tech)) + var matrixSink = operatingParameters.TryGetValue("ResearchMatrixSink", out var sinkSetting) && + sinkSetting == 1; + var researchSpeed = 0.0; + ProductionTechnology technology = null; + if (matrixSink) { - diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, - "The selected technology is not a lab-research technology.", - buildingItemId: building.ItemId); - return false; + 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) || techId <= 0 || + techId > int.MaxValue || techId != Math.Truncate(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) @@ -60,7 +85,7 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter var baseHashes = 3600.0 * researchSpeed; var hashRate = baseHashes * (1 + extraBonus); var workingWatts = building.WorkingPowerWatts * powerMultiplier; - if (!FinitePositive(hashRate) || !FinitePositive(workingWatts)) + if (!FinitePositive(workingWatts) || !matrixSink && !FinitePositive(hashRate)) { diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, "The research hash rate or power demand is outside the supported range.", @@ -69,19 +94,22 @@ public sealed class ResearchProcessAdapter : IProductionProcessAdapter } var inputs = new List>(); - foreach (var requirement in tech.MatrixPointsPerHash) + if (!matrixSink) { - if (!catalog.Items.ContainsKey(requirement.Key) || !FinitePositive(requirement.Value) || - !FinitePositive(researchSpeed * requirement.Value)) + foreach (var requirement in technology.MatrixPointsPerHash) { - diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, - "The technology has an invalid matrix point requirement.", - itemId: requirement.Key, buildingItemId: building.ItemId); - return false; - } + 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(requirement.Key, - researchSpeed * requirement.Value)); + inputs.Add(new KeyValuePair(requirement.Key, + researchSpeed * requirement.Value)); + } } process = new ProductionProcess(0, building.ItemId, mode, diff --git a/UXAssist/docs/BlueprintDescriptionPlan.md b/UXAssist/docs/BlueprintDescriptionPlan.md new file mode 100644 index 0000000..c59a1c2 --- /dev/null +++ b/UXAssist/docs/BlueprintDescriptionPlan.md @@ -0,0 +1,186 @@ +# UXAssist Automatic Blueprint Description Plan + +Status: Updated implementation specification, September 27, 2026. + +The maintained production reference is [ProductionArchitecture.md](ProductionArchitecture.md). This document records the current behavior and acceptance criteria for the automatic blueprint description. + +Keep shared production changes focused on this feature, update affected callers and tests, and preserve existing full-load accounting. + +## 1. Confirmed Behavior and Display + +Add an **Auto-fill description** button and a **Proliferation** checkbox to the shared blueprint inspector used in browser, copy, and paste modes. Place the checkbox immediately to the right of the button in one compact row above every description box, including the smaller description fields and the main description. On generation, replace the existing main description text with nonempty missing, excess, input, output, and research lines; use at most one native custom field for power. Preserve the author, version, short description, and unrelated custom fields. + +| Purpose | English label | Simplified Chinese label | Value format | +| --- | --- | --- | --- | +| Generate or update | Auto-fill description | `自动填写说明` | Button | +| Calculation setting | Proliferation | `增产` | Checkbox | +| Optional power field | Power | `耗电` | Present factory and/or logistics consumption only | +| Description missing line | Missing: | `缺少:` | Intermediate shortages, with the label shown only once | +| Description excess line | Excess: | `多余:` | True overbuild, with the label shown only once | +| Description input line | Input: | `输入:` | External inputs only, at estimated steady-state rates | +| Description output line | Output: | `输出:` | Ordinary final products and necessary coproduct surplus | +| Description research line | Research: | `研究:` | Net positive matrix output accepted by selected research-mode labs | + +The Chinese power example is `工厂耗电 2.5GW | 物流耗电 600MW` when both categories consume power. Omit a category without consumption; if neither consumes power, do not create the power field and remove an obsolete matching one. Keep a present but unmeasurable category marked as `未知`. Each material entry has the form `Item name x100`. All material rates remain items per minute, but no description label includes the time unit. Separate items with commas, write each label only once per line, and put newlines only between nonempty lines in this order: missing, excess, input, output, research. Omit empty categories even when material data is incomplete; a warning-only description has no empty input line. + +Use the native multiline description so long material lines wrap within the large editor. The power custom field remains single-line; do not add line breaks to custom fields, custom newline tokens, hidden ownership markers, sidecar metadata, a custom serialization format, or a mod-specific display protocol. Do not extend the native text renderer. + +Use native item icon/name tags so the stored text remains compatible with ordinary blueprint saving and sharing. Round only for display, omit unnecessary trailing zeros, and do not display an unknown value as zero. Register UI strings, line labels, and the power field title through UXAssist's localization registration and use translation keys at call sites. + +## 2. Inspector Integration and Safe Field Updates + +### Proliferation setting + +- Initialize the checkbox from whether the current blueprint contains a Spray Coater. Use the building's native prefab capability rather than its localized name. +- While the user has not overridden the setting, update that default when the blueprint contents change. Preserve a manual override for the current editing session; opening or switching to another blueprint resets the default. +- Changing the checkbox does not rewrite the blueprint. Replace the description and update the optional power field only when the button is clicked. +- When enabled, use the highest proliferation level supported by the captured catalog and preserve each building's extra-products or acceleration mode. +- Retain the black box analyzer's existing assumption that input coating is supplied externally. The presence of a Spray Coater only initializes the checkbox; it does not establish spray routing or justify adding an inferred proliferator-consumption flow. + +### Click-to-write flow + +1. Synchronize pending custom-field edits before reading native fields, so clicking the button does not discard unsaved manual field changes. The existing main description is intentionally replaced, including pending text there. +2. Read the inspector's current blueprint. Capture its buildings on the game thread with `BlueprintSelectionReader.FromBlueprint`, then create a request using the checkbox value and call `FactoryBlackBoxAnalyzer.Analyze`. Do not substitute the current planet's entire factory or live inventories. +3. Format a power value and up to five labeled description lines (Missing, Excess, Input, Output, Research), omitting empty categories. Keep calculation and formatting separate from Unity controls so their behavior can be checked with synthetic data. Refuse descriptions longer than the native 2,000-character limit before making generated changes. +4. Match only existing power custom fields by exact registered English or Chinese titles. Update one power field in place or append one when needed; merge duplicate matching power fields, and remove matching power fields when neither category consumes power. Do not inspect or delete input/output custom fields. Preserve every other field and its order, and do not search ordinary description prose for loose matches. +5. Check the native field capacity before changing generated data. If a required new power field cannot fit, explain the limit and leave the existing description and fields unchanged. +6. Commit both the prepared custom-field string and replacement `blueprint.desc`, update the native description input, and refresh the inspector through its native modification path. Refresh the displayed description, fields, and share-code preview, but do not save or overwrite a file automatically. The native save and copy buttons remain responsible for those actions. + +Use existing UXAssist UI helpers and native styling. Reserve one compact row above all description fields for the button and its right-hand checkbox, not between smaller fields and the main description. Shift the first inspector group and following groups down together, increase the scroll content height, and size localized labels using the established UI utilities. Keep creation, event registration, refresh, and cleanup idempotent across inspector reuse and game sessions. Do not run the calculation repeatedly in a logic tick or per-frame update. + +### Native integration reference + +These integration points were checked in the original installed game DLL. Recheck their signatures and behavior against the original DLL after game updates, following the repository's Steam-install discovery guidance. Do not use stripped publicized method bodies as evidence. + +- `UIBlueprintInspector` is shared by its `Browser`, `Copy`, and `Paste` usages. It stores the current `blueprint` and provides native refresh and custom-field editing paths. +- Native `Refresh` recalculates `descGroupTrans.anchoredPosition`, `group1.sizeDelta`, the following groups' positions, and `contentTrans.sizeDelta`, but does not reset `group1.anchoredPosition`. Move `group1` down once while the controls are active, position their row above its first native field, offset the following groups and scroll height after each native refresh, and restore the one-time shift on teardown. Do not move only `descGroupTrans`: that puts the new row between description sections. +- `BlueprintData.desc` stores the multiline description, including native item tags. Assign the inspector's `descTextInput.text` when replacing it because `Refresh(forModify: true)` does not reload that input from the blueprint. `BlueprintData.externalFields` stores custom fields; apply `ExternalFieldEscape` and `ExternalFieldUnescape` to power names and values. +- `UIBlueprintInspector.CollectExternalFields`, `OnCustomFieldEndEdit`, and `Refresh` establish the native collection and refresh sequence. Collect current edits before replacing generated values, not afterward. +- `UIBlueprintInspector.kMaxFieldCount` supplies the field limit; it was 20 in the inspected game build. A power update requires no new slot; unrelated custom fields are never removed to make room. The inspector rejects a `desc` longer than 2,000 characters; refuse that generated text instead of leaving the blueprint unsavable. +- `BlueprintData.Validate` removes literal newlines from native custom-field content, and the inspector lays out those fields at a fixed row height. It does not strip newlines from the main `desc`. Keep multiline text there, not in custom fields, without globally patching validation. +- `UIInputField` uses `LDB.signals.IconTag`; its `includeName` option supplies the native icon and localized item name together in the description text. The blueprint's normal serialization escapes and restores that text. + +## 3. Material Classification and Shared API Changes + +### Preserve the full-load report + +Calculate from the buildings, recipes, and settings actually present in the blueprint. Keep all selected buildings at their modeled full load, even when upstream production is insufficient. Do not simulate belt reachability, logistics throughput, startup inventories, or runtime throttling. + +Keep `GrossProduction`, `GrossConsumption`, `NetFlow`, producer/consumer attribution, and the original power calculations available. Material rates remain `double` items per minute and power remains watts. + +For classification, account for a process's net production and consumption of each item. A material returned or recirculated within the same recipe must not become a false external requirement or surplus merely because it appears in both gross ledgers. Preserve the gross ledgers themselves for existing callers. + +### Separate shortages, true overbuild, and coproducts + +Extend the shared report with numeric results for: + +- Intermediate material shortages requiring additional external supply. +- Net surplus attributable to genuinely redundant whole buildings. +- Net coproduct surplus left by necessary joint production after internal use. + +One item can have both overbuild surplus and necessary coproduct surplus. Represent the amounts separately; a mutually exclusive item classification or a single boolean is insufficient. The existing per-item `IsExcessIntermediate` threshold alone does not prove that a building is redundant. + +Use all products of a production group together when checking redundancy: + +- Group equivalent buildings and process them in a stable order based on recipe, building, and operating settings so blueprint array order does not affect the result. +- Iteratively test whole-building reductions against the shared material balance. A reduction qualifies only if it does not lower final-product capacity and does not create or enlarge an internal material shortage. +- All items share the same selected redundant-building set and material budget. Do not independently claim the same surplus for several alternative reductions. +- Attribute overbuild and coproduct quantities to the original report without double-counting mixed single-output and multi-output producers. Do not classify a material solely by its position in the recipe's result array. +- Preserve the existing treatment of sub-building single-product ratio headroom as normal balance rather than an overbuild warning. + +The whole-building reduction is only a classification calculation. Keep the actual blueprint's gross full-load inputs, outputs, original external-supply ledger, and rated power in the shared report. This feature does not remove buildings or become a separate factory-layout optimizer. + +### Steady-state input demand + +The displayed input rates must account for upstream production blocked by surplus intermediates. After identifying redundant whole buildings, allow fractional reductions of the remaining processes until each intermediate's production meets downstream demand. Apply each process reduction to all its inputs and joint products together; preserve rated final-product capacity and never enlarge an existing intermediate shortage. Propagate reductions through multiple upstream stages using a stable process order. The resulting external input is a separate steady-state estimate, not a replacement for gross full-load ledgers, output classification, or rated power. When other materials are incomplete, still cap independently known upstream processes against their known downstream demand and label the resulting input as a known portion. Do not mistake unmodeled downstream demand for zero: protect an unresolved process's known inputs, or all known products if its possible inputs are unknown. Keep whole-building overbuild and coproduct conclusions unknown until the material selection is complete. + +A blueprint research-mode lab is a terminal outlet for all six native matrix types manufactured inside that same blueprint. One selected lab is enough to preserve the full rated output of every matrix producer, even when other known processes use some of those matrices. Classify positive net matrix production as final research output and place it on the separate Research line, not the ordinary Output line or an excess/coproduct entry. Subtract other buildings' known matrix consumption from the displayed research quantity, but do not add virtual research consumption to the gross material ledger or invent external matrix inputs. Other buildings' known matrix requirements still count, including external supply when no matrix is produced. Without a selected research-mode lab, use ordinary material classification and upstream throttling. This is a blueprint-planning assumption about where manufactured matrices can go, not a claim that a real lab has unlimited research throughput. + +### Description lines + +- If present, place intermediate shortages on a `Missing: ` / `缺少:` line and true overbuild on a separate `Excess: ` / `多余:` line, in that order before Input. Put each label only once before its comma-separated item list, not before every item. Do not mix warnings into Input or repeat a shortage as an ordinary input. +- Put only external raw-material inputs in the Input line, using the estimated steady-state rate rather than theoretical gross consumption. +- Put ordinary final products and necessary net coproduct surplus in the Output line. Do not include the overbuild portion again or duplicate research matrices here. +- Put positive net matrix output accepted by a selected research-mode lab in the separate Research line, after Output. For example, 12 matrices produced per minute minus 1 consumed by another selected process yields 11 per minute in Research, not 12; omit this line if no matrices are made or none remain. +- Merge entries for the same item within a category and sort each category by item ID. Use commas between entries and keep all rates in items per minute even though the labels omit the unit. Omit an entire line if it has no entries; do not generate `None` or `Unknown` as a stand-alone material line. Mark known entries as partial when material results are incomplete. + +### Required joint-production example + +Each upstream building produces A60 and B60 per minute. Internal downstream requirements are A120 and B30 per minute, and downstream capacity remains fixed. + +| Selected upstream buildings | Original A/B production | True overbuild shown in Excess | Necessary coproduct shown in Output | +| --- | --- | --- | --- | +| 2 | A120, B120 | None | B90 | +| 3 | A180, B180 | A60, B60 | B90 | + +In the three-building case, preserve gross consumption and rated power for all three buildings, but display external input for only the two upstream buildings needed by downstream demand. Do not reclassify the entire B150 net surplus as overbuild, and do not report B150 as coproduct output while also warning about the redundant B60. + +## 4. Power, Scope Boundaries, and Incomplete Results + +### Independent power categories + +Extend `ProductionReport` with independently usable factory-consumption and logistics-consumption results and completeness information. Preserve the existing total-power API and migrate affected callers without weakening their accounting. + +- Factory consumption includes production buildings and non-logistics auxiliary demand, including sorters and Spray Coaters. +- Logistics consumption uses stored configured charging limits, or native prefab defaults where no charging setting is applied, for the selected logistics facilities. Do not use transient draw. +- Do not subtract generation from consumption. Keep accumulator exchange and logistics charging distinct and count charging demand only once. Do not add a second logistics charging term to advanced miners or grid consumption for gas collectors' self-fueling. +- Unknown factory power must not discard known logistics power, or vice versa. For example, `工厂耗电 未知 | 物流耗电 600MW` is valid when only the factory total is unknown. +- A research-mode lab blueprint does not store its current technology or research speed. Capture native `LabComponent.matrixIds` with the catalog and mark blueprint labs as `ResearchMatrixSink`; do not consult current technology, technology requirements, unlock state, or research speed to determine matrix use. An assumed lab has no numeric matrix input or hash throughput in the report. Other callers without this blueprint assumption still need explicit `TechId` and `ResearchSpeed` to calculate exact research flows. If native matrix item IDs are unavailable, retain an incomplete material result instead of treating the lab as unable to accept matrices. +- Budget every selected research-mode lab at its full prefab working consumption, including labs currently unable to research or with invalid technology data. Apply the selected proliferation power multiplier when available; use base working power when no spray level is supported. This deliberately conservative estimate protects blueprint power capacity and keeps factory and total power independent of material-rate assumptions. +- Omit a power category when its demand is known to be zero; do not show `0W` for an absent factory or logistics consumer. An unknown category tied to a selected building remains visible as `Unknown`. If neither category has consumption, do not create a power field and remove an earlier generated one. + +### Blueprint-only scope and missing data + +- Do not generate description entries or requested-parameter lists for veins or other scene objects that are not part of a blueprint. Do not expand this feature into a resource-context or planet-analysis interface. +- If a building actually present in the blueprint still lacks a necessary operating parameter, retain independently calculable results and explicitly mark the affected result incomplete. The research-mode matrix outlet assumption above is an intentional exception; do not invent other external conditions. +- Preserve the common analyzer's resource and operating-parameter requirements for its other callers; the description feature's scope does not authorize globally suppressing those diagnostics. +- Keep material and power completeness independent. Mark partial material values as known portions, cap known upstream inputs against known demand, and suppress any final-output, overbuild, or coproduct conclusion that unresolved downstream consumers could invalidate. +- An invalid blueprint, unavailable catalog, calculation exception, overlong description, or insufficient field capacity must leave the existing description and custom fields unchanged and show a useful localized explanation. A failed or unavailable calculation is not a complete empty report. + +## 5. Validation and Maintenance + +### Synthetic checks + +Extend `UXAssist/tools/ProductionCheck` with focused tests for: + +- The two- and three-building joint-production example above. +- A shared item supplied by both single-output and multi-output processes, including simultaneous coproduct and overbuild amounts without duplication. +- Whole-building thresholds, fractional ratio headroom, internal deficits, and stable results after reordering blueprint buildings. +- Internal material return and cyclic recipes without losing the original gross production/consumption ledgers. +- Proliferation on/off, the highest captured supported level, and preservation of building acceleration/extra-product modes. +- Independent material, factory-power, and logistics-power completeness, including one research lab accepting all six manufactured matrix types without technology data, invented external matrix inputs, or hash rates; preserve full-load power with and without supported proliferation. +- No research station, no matrix production, one produced matrix type, multiple labs, and a separate building that genuinely needs external matrices. Classify positive net matrix production as final research output, preserve known gross flows, prevent false matrix coproduct or overbuild warnings, and avoid throttling producers whose matrix output has an assumed research outlet. +- Separate steady-state external inputs for whole and fractional upstream excess, multi-stage dependencies, shared producers, order stability, and shortages; cap known upstream inputs in partially known layouts while protecting unresolved downstream demand. Preserve gross ledgers, independently known rated output, and power. +- Pure formatting for separate nonempty Missing, Excess, Input, Output, and Research lines in that order, including multiple items per warning line without repeated labels. Verify labels omit the per-minute suffix without changing rate units. Cover long material lists, independent power-category omission, and present-but-unknown power; check that matrix output appears exactly once in Research at its net rate while non-matrix final output stays in Output. +- Pure field updates for first generation, repeated updates, exact bilingual power-title recognition, duplicate power fields, preservation of all other fields including input/output titles, and native-capacity rejection without partial writes. Check the description length before committing either change. + +Keep game-dependent capture and inspector code separate from the pure-managed sources compiled by these checks. + +Run the narrow checks and affected builds from the repository root: + +```powershell +dotnet run --project UXAssist/tools/ProductionCheck/ProductionCheck.csproj -c Release +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 +git diff --check +``` + +### Manual game acceptance + +- Check browser, copy, and paste inspectors in English and Simplified Chinese. Confirm the checkbox sits directly to the right of the button without overlap, their row precedes all small and main description boxes, and the native description wraps long icon/name material lines. Reopen, refresh, and change language to ensure the row stays at the top and the original layout returns when the feature is disabled. +- Check checkbox defaults with and without a Spray Coater, blueprint-content changes before a manual override, preservation of a manual override during refresh, and reset after switching blueprints. +- Generate with no existing fields, generate again, and generate with unrelated custom fields, including fields titled Input or Output. Confirm the main description replaces its previous text, at most one power field remains, and other fields and pending manual custom-field edits survive unchanged. +- Try factory-only, logistics-only, both, neither, and partially unknown consumption. Confirm absent categories and the entire empty power field disappear, while genuinely unknown demand stays labeled. Confirm Missing and Excess each use one label followed by comma-separated items before Input, with no per-minute suffix on any description label; empty material categories produce no lines. +- Reach the native field limit. Confirm a missing power field causes an all-or-nothing refusal without deleting other fields, while an existing power field can be updated and description-only generation remains possible. Generate a description over 2,000 characters and confirm it is rejected without changing the blueprint. +- Save, reopen, copy a share code, and import it again through the native UI. Confirm description newlines, native item icons, the optional power field, and unrelated fields survive without a custom format or a modified renderer. +- Confirm no file is written just by toggling proliferation or clicking generation, and that errors preserve the previous description and fields. +- Compare full-load rates and configured logistics charging limits under suitable conditions. Do not compare against transient, starved, or output-blocked production. +- With no external outlet for surplus intermediates, compare the description's input after upstream output buffers fill against downstream demand, including when an unrelated building lacks operating data. Confirm that unresolved downstream consumers prevent unsupported input reductions while known rated output and power remain independent. +- Generate blueprints with one research-mode lab and six matrix types made inside the blueprint, then with only one matrix type or none. Confirm every manufactured matrix has an outlet and its positive net rate appears once in the Research line, after the unrelated final products in Output. Known consumption by another blueprint building reduces the Research rate; do not estimate lab matrix use, hashes, or external matrix demand. Vary current technology and research speed, add more labs, and toggle proliferation: matrix throughput must not change, but each lab must still contribute its full applicable working power. Without a lab, ordinary matrix output and overbuild rules apply. + +Game validation is manual. Do not add automated gameplay or save-file parsing as an acceptance requirement. + +### Documentation and repository hygiene + +Keep the maintained English production architecture documentation and aligned English/Chinese changelog notes consistent with this behavior and the repository's version rules. Put only durable standards or maintained architecture references in `AGENTS.md`, not this task's progress, investigation evidence, or completed plan. Do not stage unrelated files, create a branch, or commit without an explicit request. diff --git a/UXAssist/docs/ProductionArchitecture.md b/UXAssist/docs/ProductionArchitecture.md index 5d050b2..9ff306d 100644 --- a/UXAssist/docs/ProductionArchitecture.md +++ b/UXAssist/docs/ProductionArchitecture.md @@ -1,13 +1,13 @@ # 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; they do not change DSP production, replace factory updates, or provide a calculator UI. +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`. Do not interpret an absent power result as zero. +- 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. @@ -38,7 +38,11 @@ When proliferation is enabled, ordinary recipes default to their native extra-pr ## Fixed-building analysis -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. A positive intermediate balance is classified as excess only when it reaches the smallest net per-building output among actual producers of that item. The underlying fractional ledger is never discarded. +The black box evaluates each selected building at full load, even if another selected building cannot provide all its inputs. It does not simulate belt layouts, startup storage, or logistics throughput. Missing inputs appear as `RequiredExternalSupply`; byproducts and internal deficits retain producer and consumer group attribution. `GrossProduction` and `GrossConsumption` remain separate even when a recipe returns some of its own input. Material classification uses each process's net per-item flow, so that return cannot become a false external requirement or coproduct. + +`IntermediateShortage` records the missing externally supplied portion of an item produced and consumed within the selection. `OverbuildSurplus` and `CoproductSurplus` are independent nullable amounts; both can be positive for the same item. Equivalent buildings are grouped by recipe, building, proliferation mode, speed, and operating settings in stable order. Whole-building reductions are tested against every item's shared balance: no final-product capacity may decrease and no internal shortage may increase. The reduction identifies redundancy only; gross flows, original full-load inputs, outputs, and power never change. Coproduct supply counts only retained whole buildings required by a process's other products, and internal net consumption is credited before exposing the remainder. Headroom from a single-output producer or a joint process's limiting product remains ordinary balance, not a coproduct. The older `IsExcessIntermediate` threshold flag is retained for callers but alone does not prove redundancy. When materials are incomplete, overbuild and coproduct amounts are unknown rather than fabricated from a partial layout. + +`SteadyStateExternalSupply` is a separate input estimate from the known processes. After whole-building classification for complete selections, a bounded fractional reduction of surplus intermediate producers propagates downstream limits through upstream processes. Every reduction applies to the entire process, keeps rated final-product capacity, and never worsens an existing intermediate shortage; deterministic grouping and ordering keep results independent of blueprint building order. For partial selections, skip whole-building classification but still cap independently known upstream inputs against known demand. Protect any known inputs of an unresolved downstream process, or all known products if its possible inputs are unknown, instead of treating its demand as zero. Only the blueprint description uses this estimate, marked as a known portion when incomplete. Gross ledgers, `RequiredExternalSupply`, uncertain overbuild and coproduct classification, independently known rated outputs, and power retain their original meaning. ```csharp var capture = BlueprintSelectionReader.Capture(factory, selectedObjectIds); @@ -52,7 +56,19 @@ The capture is read-only and does not alter the game's selection. `CreateRequest The global proliferation switch uses the highest level supported by the captured proliferator items while preserving each production building's acceleration or extra-products setting. It also controls fuel and launch-ammunition proliferation. The black box assumes input coating is supplied externally and does not add proliferator consumption for that coating. -Selected Planetary and Interstellar Logistics Stations, Logistics Distributors, and Battlefield Analysis Bases contribute their configured maximum charging power to both `Power.ConsumptionWatts` and `PeakConsumptionWatts`. These are charging limits, not current draw, inventory flow, or accumulator exchange. A manual building snapshot supplies `ChargePowerWatts` in watts; live capture reads the consumer's configured work energy per tick, while prebuild and blueprint captures use native stored settings or prefab defaults when no setting is applied. Missing or invalid charging power makes the power result unknown without discarding material results. Advanced Mining Machines retain their mining power calculation rather than gaining a second charger; orbital collectors recover their own fuel instead of drawing grid power. +Selected Planetary and Interstellar Logistics Stations, Logistics Distributors, and Battlefield Analysis Bases contribute their configured maximum charging power to both `Power.ConsumptionWatts` and `PeakConsumptionWatts`. These are charging limits, not current draw, inventory flow, or accumulator exchange. A manual building snapshot supplies `ChargePowerWatts` in watts; live capture reads the consumer's configured work energy per tick, while prebuild and blueprint captures use native stored settings or prefab defaults when no setting is applied. Missing or invalid charging power leaves logistics consumption and the combined power result unknown, without discarding known factory consumption or material results. Factory consumption also includes selected sorters and Spray Coaters. Advanced Mining Machines retain their mining power calculation rather than gaining a second charger; orbital collectors recover their own fuel instead of drawing grid power. A miner missing resource context can still report independently calculable speed-ratio power; a ray receiver missing Dyson loss settings retains its known factory draw even though total power remains incomplete. + +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 hosts `Auto-fill description` with `Proliferation` immediately to its right in one row above every description box. Move the first native inspector group down once, and offset later groups and the scroll height after each native refresh so the controls do not split the smaller fields from the main description. 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. Clicking the button captures only `blueprint.buildings` with `BlueprintSelectionReader.FromBlueprint` on the game thread, then runs `FactoryBlackBoxAnalyzer` against the captured catalog. 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 true overbuild; `Input:` for external inputs capped by downstream demand; `Output:` for ordinary final products and necessary coproduct surplus; and `Research:` for positive net matrix production accepted by a selected research-mode lab. Each warning category has one label followed by comma-separated items; warnings do not repeat in Input, and a matrix on Research does not repeat in Output. It uses `SteadyStateExternalSupply` for complete and independently known partial inputs, labeling partial values as known portions. The assumed lab adds no numerical matrix consumption or external input; other buildings' known matrix demand is subtracted from the Research rate. Omit each empty line, including Research when no produced matrix remains. A single optional `Power` custom field separates factory and configured logistics consumption, omitting categories with no demand and removing the field altogether if neither consumes power; a present but unknown category displays `Unknown` rather than zero. Material rates remain items per minute even though the description labels omit the unit. Rates are rounded only for display, ordered by item ID within each category, and use native item icon/name tags with comma-separated entries inside each description line. Uncertain final-product, overbuild, or coproduct conclusions are omitted. Veins and other scene objects are not blueprint entries or requested parameters. + +`BlueprintDescriptionFields` matches only exact English or Simplified Chinese power field titles, updates or removes matching power fields, and collapses duplicate matches; all other fields, including input/output custom fields, stay intact. The inspector first collects pending custom-field edits, checks the native 2,000-character description limit and `kMaxFieldCount`, and applies native `ExternalFieldEscape` and `ExternalFieldUnescape` rules to the remaining power field. An invalid blueprint, unavailable catalog, failed calculation, malformed fields, overlong description, or insufficient capacity does not overwrite the description or generated fields. A successful update replaces the original description, synchronizes its native input control, and refreshes the inspector and share-code preview through the native modification path, leaving save and copy actions to the native buttons. The formatting and field updater remain pure-managed so `ProductionCheck` can verify them without loading Unity. ## Special-process settings @@ -68,7 +84,7 @@ All parameters below are numbers in a building snapshot's `OperatingParameters`. | 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`, `TechId`, and `ResearchSpeed`. The captured technology supplies matrix point requirements. Native matrix proliferation increases hashes and power, not matrix input per base hash; `ResearchHashesPerMinute` is separate from item production. | +| 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. @@ -85,6 +101,7 @@ Use compilation, the synthetic game-free checks, and static review for developme ```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 ``` @@ -104,5 +121,7 @@ Use a test game for the following manual checks. Compare full-load rates only wi - Select miners at different machine speeds, including one with a backed-up output, a gas collector, and renewable generators. Check native miner power scaling, full-load miner output regardless of the output backlog, per-minute gas output without added grid demand, and ideal rated renewable power rather than local conditions. - Select ray receivers in both modes, fuel generators, ejectors, and silos. Toggle proliferation and compare working power, generation, accumulator exchange, and Dyson demand as separate quantities. In a sandbox game, capture boosted artificial stars and launchers, and confirm that blueprint analysis of boosted buildings requires `BoostEnabled`. - Remove an upstream producer from a mixed production selection. Confirm that downstream capacity is unchanged and the missing material appears as required external supply. Check intermediate excess around the smallest selected producer's net output threshold. +- In browser, copy, and paste inspectors, check localized control placement, Spray Coater defaults and manual overrides, and native item tags in the three generated fields. Generate twice and at the 20-field limit; verify that pending manual edits, unrelated fields, save/copy behavior, and ordinary blueprint sharing remain intact. Compare joint-production overbuild with necessary coproduct output without replacing original full-load rates or power. +- Place one research-mode lab alongside one or all six matrix production chains. Confirm the matrices' positive net production appears only in the Research line, other final products stay in Output, and known in-blueprint matrix consumption reduces the Research rate. Do not fabricate lab matrix imports, excess, or an estimated lab consumption rate; change current technology, add more labs, and toggle proliferation to check matrix routing stays independent while full working power updates. Without the lab, normal matrix output and overbuild rules resume. - Combine planner targets with shared coproducts, explicit raw-material boundaries, and alternate selected recipes. Confirm material conservation, shared surplus reuse, and no introduction of unselected recipes. - Toggle belt-signal proliferation and reload a game. Confirm that existing belts use the new catalog, item generation continues, and fractional production and consumption statistics remain independent. diff --git a/UXAssist/tools/ProductionCheck/Program.cs b/UXAssist/tools/ProductionCheck/Program.cs index e099492..b2ebeb7 100644 --- a/UXAssist/tools/ProductionCheck/Program.cs +++ b/UXAssist/tools/ProductionCheck/Program.cs @@ -22,6 +22,11 @@ internal static class Program ProliferatorGradesAndFinishedSpraying(); BlackBoxBalancesAndThreshold(); BlackBoxMixedModesAndDeficits(); + BlueprintJointProduction(); + BlueprintSteadyStateInputs(); + BlueprintMixedProducersAndCycles(); + BlueprintProliferationAndCompleteness(); + BlueprintDescriptionFormattingAndFields(); LogisticsChargingPower(); FractionationFlow(); AccumulatorRoundTrip(); @@ -708,6 +713,8 @@ internal static class Program Equal(180, report.ItemFlows[2].GrossProduction, "tiers retain separate capacities"); Equal(150, report.ItemFlows[2].GrossConsumption, "downstream runs at full load"); Equal(30, report.ItemFlows[2].Surplus, "fractional intermediate balance retained"); + Equal(0, report.ItemFlows[2].OverbuildSurplus.Value, + "sub-building ratio headroom is not redundant whole-building capacity"); Equal(60, report.ItemFlows[2].SingleBuildingSurplusThreshold, "smallest actual producer threshold"); Check(!report.ItemFlows[2].IsExcessIntermediate, "sub-threshold surplus is normally balanced"); Equal(2, report.ItemFlows[2].ProducerGroups.Count, "producer groups retained"); @@ -721,6 +728,8 @@ internal static class Program speedFactor: 0.8)); var atThreshold = analyzer.Analyze(request); Equal(60, atThreshold.ItemFlows[2].Surplus, "intermediate at threshold"); + Equal(60, atThreshold.ItemFlows[2].OverbuildSurplus.Value, + "a removable whole building accounts for the true overbuild"); Check(atThreshold.ItemFlows[2].IsExcessIntermediate, "threshold reached qualifies as excess"); request.Buildings.Add(new ProductionBuildingSnapshot(102, 10, 402, 1, ProliferationMode.None)); @@ -1062,6 +1071,15 @@ internal static class Program "unknown Dyson power is not reported as zero"); Check(missingTechnology.Diagnostics.Any(d => d.Code == ProductionDiagnosticCode.MissingOperatingParameter), "missing solar-loss technology is diagnosed"); + Check(missingTechnology.PowerBreakdown.FactoryComplete && + missingTechnology.PowerBreakdown.FactoryConsumptionWatts == 0, + "unknown Dyson requirement does not erase known factory consumption"); + plan.OperatingParametersByRecipe[999] = parameters; + var plannedWithoutLoss = new ProductionPlanner(catalog).Calculate(plan); + Check(plannedWithoutLoss.MaterialComplete && !plannedWithoutLoss.PowerComplete && + plannedWithoutLoss.PowerBreakdown.FactoryComplete && + plannedWithoutLoss.PowerBreakdown.FactoryConsumptionWatts == 0, + "planner retains calculable factory watts while Dyson requirement is unknown"); } private static void LauncherCyclesAndAmmunition() @@ -1173,6 +1191,8 @@ internal static class Program Check(!missing.MaterialComplete && missing.Diagnostics.Any(d => d.Code == ProductionDiagnosticCode.MissingOperatingParameter), "unavailable gas composition is diagnosed instead of inventing outputs"); + Check(missing.PowerBreakdown.FactoryComplete && missing.PowerBreakdown.FactoryConsumptionWatts == 0, + "missing gas composition does not turn collector self-fueling into grid consumption"); } private static void ResearchHashesAndMatrices() @@ -1181,17 +1201,27 @@ internal static class Program { new KeyValuePair(6001, 2), new KeyValuePair(6002, 1) }); + var otherTech = new ProductionTechnology(402, new[] + { + new KeyValuePair(6001, 4), new KeyValuePair(6002, 2), + new KeyValuePair(6003, 3), new KeyValuePair(6004, 1), + new KeyValuePair(6005, 5), new KeyValuePair(6006, 1) + }); var catalog = new ProductionCatalog(new[] { new ProductionItem(6001, 0, false, false, 0, 0), new ProductionItem(6002, 0, false, false, 0, 0), + new ProductionItem(6003, 0, false, false, 0, 0), + new ProductionItem(6004, 0, false, false, 0, 0), + new ProductionItem(6005, 0, false, false, 0, 0), + new ProductionItem(6006, 0, false, false, 0, 0), new ProductionItem(7000, 0, false, false, 4, 75) }, Array.Empty(), new[] { new ProductionBuilding(91, ProductionRecipeCategory.Research, 1, 1000, 100) }, new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, - new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }, new[] { tech }); + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }, new[] { tech, otherTech }, Enumerable.Range(6001, 6)); var settings = new Dictionary { ["ResearchMode"] = 1, ["TechId"] = 401, ["ResearchSpeed"] = 0.5 @@ -1219,6 +1249,18 @@ internal static class Program Check(sprayed.Groups.Single().Process.ProliferationMode == ProliferationMode.ExtraProducts, "research mode does not mistake copied assembler speedup setting for hash mode"); + settings["TechId"] = 999; + request.Buildings[0] = new ProductionBuildingSnapshot(1, 91, 0, 2, + ProliferationMode.None, operatingParameters: settings); + var unrecognizedTech = analyzer.Analyze(request); + Check(!unrecognizedTech.MaterialComplete && + unrecognizedTech.Diagnostics.Any(d => d.Code == ProductionDiagnosticCode.InvalidRequest) && + unrecognizedTech.PowerBreakdown.FactoryComplete && + unrecognizedTech.PowerBreakdown.FactoryConsumptionWatts == 5000, + "every research-mode lab retains full working power when its technology cannot be evaluated"); + Check(unrecognizedTech.PowerComplete && unrecognizedTech.Power?.ConsumptionWatts == 5000, + "invalid research technology does not hide an independently known full-load power total"); + settings.Remove("TechId"); request.Buildings[0] = new ProductionBuildingSnapshot(1, 91, 0, 1, ProliferationMode.None, operatingParameters: settings); @@ -1226,6 +1268,227 @@ internal static class Program Check(!missing.MaterialComplete && missing.Diagnostics.Any(d => d.Code == ProductionDiagnosticCode.MissingOperatingParameter), "missing technology cannot silently report zero matrices"); + Check(missing.PowerBreakdown.FactoryComplete && + missing.PowerBreakdown.FactoryConsumptionWatts == 2500, + "research power remains calculable without the technology when proliferation is enabled"); + Check(missing.PowerComplete && missing.Power?.ConsumptionWatts == 2500, + "missing research technology does not hide rated total power"); + + request.Buildings.Add(new ProductionBuildingSnapshot(2, 91, 0, 2, + ProliferationMode.None, operatingParameters: new Dictionary + { + ["ResearchMode"] = 1, ["TechId"] = 401, ["ResearchSpeed"] = 0.5 + })); + var mixedResearch = analyzer.Analyze(request); + Check(!mixedResearch.MaterialComplete && mixedResearch.PowerBreakdown.FactoryComplete && + mixedResearch.PowerBreakdown.FactoryConsumptionWatts == 7500, + "all research-mode labs add their rated power even when settings differ"); + Check(mixedResearch.PowerComplete && mixedResearch.Power?.ConsumptionWatts == 7500, + "every research-mode lab contributes to the independent power total"); + request.Buildings.RemoveAt(1); + + var noSprayCatalog = new ProductionCatalog(catalog.Items.Values.Where(item => item.Id != 7000), + Array.Empty(), catalog.Buildings.Values, + new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 }, catalog.Technologies.Values, + catalog.ResearchMatrixItemIds); + var noSpray = new FactoryBlackBoxAnalyzer(noSprayCatalog).Analyze(request); + Check(noSpray.PowerComplete && noSpray.Power?.ConsumptionWatts == 1000, + "without a supported spray level, research mode still budgets full base power"); + + request.Buildings[0] = new ProductionBuildingSnapshot(1, 91, 0, 2, + ProliferationMode.None, operatingParameters: new Dictionary { ["ResearchMode"] = 1 }); + request.ProliferationEnabled = false; + var blueprintLab = analyzer.Analyze(request); + Check(!blueprintLab.MaterialComplete && blueprintLab.PowerBreakdown.FactoryComplete && + blueprintLab.PowerBreakdown.FactoryConsumptionWatts == 2000, + "blueprint research labs report working watts without transient technology or speed"); + Check(blueprintLab.PowerComplete && blueprintLab.Power?.ConsumptionWatts == 2000, + "an unconfigured research blueprint reports known full-load power separately from unknown matrices"); + var researchDescription = BlueprintDescriptionFormatter.Format(blueprintLab, TestItemTag, + new BlueprintDescriptionLabels("Factory power", "Logistics power", "Missing: ", "Excess: ", "Unknown", + "(known portion)", "Input: ", "Output: ", "Research: ")); + Check(researchDescription.Power == "Factory power 2kW" && researchDescription.Description == "", + "blueprint descriptions show research power without inventing matrix materials"); + + request.Buildings[0] = new ProductionBuildingSnapshot(1, 91, 0, 2, + ProliferationMode.None, operatingParameters: new Dictionary + { + ["ResearchMode"] = 1, ["ResearchMatrixSink"] = 1, + ["TechId"] = 999, ["ResearchSpeed"] = 0.01 + }); + var assumed = analyzer.Analyze(request); + Check(assumed.MaterialComplete && assumed.PowerComplete && assumed.Diagnostics.Count == 0, + "blueprint labs do not require a valid research technology or speed"); + Check(assumed.ItemFlows.Count == 0 && assumed.ResearchHashesPerMinute == 0, + "labs alone do not invent matrix inputs or research hashes"); + var assumedDescription = BlueprintDescriptionFormatter.Format(assumed, TestItemTag, + new BlueprintDescriptionLabels("Factory power", "Logistics power", "Missing: ", "Excess: ", "Unknown", + "(known portion)", "Input: ", "Output: ", "Research: ")); + Check(assumedDescription.Power == "Factory power 2kW" && assumedDescription.Description == "", + "research-only blueprints show power but no imaginary matrix demand"); + + request.ProliferationEnabled = true; + var assumedSprayed = analyzer.Analyze(request); + Check(assumedSprayed.MaterialComplete && assumedSprayed.PowerComplete && + assumedSprayed.ItemFlows.Count == 0, + "spraying research stations does not invent matrix consumption"); + Equal(5000, assumedSprayed.Power.ConsumptionWatts, + "every research station still uses its full sprayed power"); + var unsprayableResearch = new FactoryBlackBoxAnalyzer(noSprayCatalog).Analyze(request); + Check(unsprayableResearch.MaterialComplete && unsprayableResearch.PowerComplete, + "a catalog without proliferation keeps research material accounting complete"); + Equal(2000, unsprayableResearch.Power.ConsumptionWatts, + "unavailable proliferation does not change full-load research power"); + var missingMatricesCatalog = new ProductionCatalog(catalog.Items.Values, + catalog.Recipes.Values, catalog.Buildings.Values, + new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }, + researchMatrixItemIds: catalog.ResearchMatrixItemIds); + var missingMatrices = new FactoryBlackBoxAnalyzer(missingMatricesCatalog).Analyze(request); + Check(missingMatrices.MaterialComplete && missingMatrices.PowerComplete && + missingMatrices.ItemFlows.Count == 0, + "blueprint matrix routing does not depend on a catalog of unlocked technologies"); + var noNativeIdsCatalog = new ProductionCatalog(catalog.Items.Values, catalog.Recipes.Values, + catalog.Buildings.Values, new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }, catalog.Technologies.Values); + var noNativeIds = new FactoryBlackBoxAnalyzer(noNativeIdsCatalog).Analyze(request); + Check(!noNativeIds.MaterialComplete && noNativeIds.PowerComplete && + noNativeIds.Diagnostics.Any(d => d.Code == ProductionDiagnosticCode.MissingOperatingParameter), + "missing native matrix IDs remain unknown without hiding research power"); + request.ProliferationEnabled = false; + + var matrixCatalog = new ProductionCatalog(catalog.Items.Values.Concat(new[] + { + new ProductionItem(1, 0, true, false, 0, 0), + new ProductionItem(2, 0, true, false, 0, 0), + new ProductionItem(8000, 0, false, false, 0, 0) + }), new[] + { + Recipe(910, new[] { (1, 1.0) }, new[] + { + (6001, 2.0), (6002, 1.0), (6003, 1.0), + (6004, 1.0), (6005, 1.0), (6006, 1.0) + }), + Recipe(911, new[] { (6001, 1.0) }, new[] { (8000, 1.0) }), + Recipe(912, new[] { (2, 1.0) }, new[] { (6001, 2.0) }) + }, catalog.Buildings.Values.Concat(new[] + { + new ProductionBuilding(92, ProductionRecipeCategory.Assemble, 1, 100, 10), + new ProductionBuilding(93, ProductionRecipeCategory.Assemble, 1, 200, 20) + }), new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }, catalog.Technologies.Values, + catalog.ResearchMatrixItemIds); + var matrixRequest = new FactoryBlackBoxRequest(); + matrixRequest.Buildings.Add(new ProductionBuildingSnapshot(1, 92, 910, 3, ProliferationMode.None)); + matrixRequest.Buildings.Add(new ProductionBuildingSnapshot(2, 93, 911, 1, ProliferationMode.None)); + matrixRequest.Buildings.Add(new ProductionBuildingSnapshot(3, 92, 912, 3, ProliferationMode.None)); + var withoutLab = new FactoryBlackBoxAnalyzer(matrixCatalog).Analyze(matrixRequest); + Equal(0, withoutLab.ItemFlows[2].SteadyStateExternalSupply.Value, + "without a research station, excess single-matrix production slows upstream"); + Equal(6, withoutLab.ItemFlows[6001].OverbuildSurplus.Value, + "without a research station, unnecessary matrix production is excess"); + Check(withoutLab.ItemFlows[6002].IsFinalProduct, + "without a research station, exported matrix production remains visible"); + var withoutLabText = BlueprintDescriptionFormatter.Format(withoutLab, TestItemTag, + new BlueprintDescriptionLabels("Factory power", "Logistics power", "Missing: ", "Excess: ", "Unknown", + "(known portion)", "Input: ", "Output: ", "Research: ")); + Check(withoutLabText.Research == "" && withoutLabText.Warnings.Contains("Excess: " + TestItemTag(6001)) && + withoutLabText.Output.Contains(TestItemTag(6002) + " x3"), + "without a research station, matrices use ordinary output and excess rules"); + + matrixRequest.Buildings.Add(new ProductionBuildingSnapshot(4, 91, 0, 1, + ProliferationMode.None, operatingParameters: new Dictionary + { + ["ResearchMode"] = 1, ["ResearchMatrixSink"] = 1, + ["TechId"] = 999, ["ResearchSpeed"] = 0.01 + })); + var withLab = new FactoryBlackBoxAnalyzer(matrixCatalog).Analyze(matrixRequest); + Check(withLab.MaterialComplete && withLab.PowerComplete, + "one research station accepts every matrix made inside the blueprint"); + foreach (var itemId in Enumerable.Range(6001, 6)) + { + var flow = withLab.ItemFlows[itemId]; + Equal(itemId == 6001 ? 12 : 3, flow.GrossProduction, + "research does not replace the known gross matrix production ledger"); + Equal(itemId == 6001 ? 1 : 0, flow.GrossConsumption, + "a research sink does not invent numerical matrix consumption"); + Check(flow.IsFinalProduct && flow.IsResearchProduct && flow.OverbuildSurplus == 0 && + flow.CoproductSurplus == 0, + "matrices absorbed by research remain final products without excess warnings"); + } + Check(!withLab.ItemFlows[6001].IsExcessIntermediate, + "matrix production absorbed by research is not flagged as overbuild"); + Equal(3, withLab.ItemFlows[1].SteadyStateExternalSupply.Value, + "six-matrix production retains its full raw input throughput"); + Equal(3, withLab.ItemFlows[2].SteadyStateExternalSupply.Value, + "one research station prevents throttling additional matrix-only producers"); + Equal(1800, withLab.Power.ConsumptionWatts, + "one research station contributes its full power independently of matrix routing"); + var withLabText = BlueprintDescriptionFormatter.Format(withLab, TestItemTag, + new BlueprintDescriptionLabels("Factory power", "Logistics power", "Missing: ", "Excess: ", "Unknown", + "(known portion)", "Input: ", "Output: ", "Research: ")); + var researchOutput = string.Join(", ", Enumerable.Range(6001, 6) + .Select(itemId => TestItemTag(itemId) + " x" + (itemId == 6001 ? 11 : 3))); + Check(withLabText.Input == TestItemTag(1) + " x3, " + TestItemTag(2) + " x3" && + withLabText.Output == TestItemTag(8000) + " x1" && + withLabText.Research == researchOutput && withLabText.Warnings == "" && + withLabText.Description == "Input: " + withLabText.Input + "\nOutput: " + withLabText.Output + + "\nResearch: " + researchOutput, + "the net matrix output appears once in research, separate from ordinary final products"); + + matrixRequest.Buildings[3] = new ProductionBuildingSnapshot(4, 91, 0, 2, + ProliferationMode.None, operatingParameters: new Dictionary + { + ["ResearchMode"] = 1, ["ResearchMatrixSink"] = 1, + ["TechId"] = 401, ["ResearchSpeed"] = 1000000 + }); + var twoLabs = new FactoryBlackBoxAnalyzer(matrixCatalog).Analyze(matrixRequest); + Equal(3, twoLabs.ItemFlows[2].SteadyStateExternalSupply.Value, + "lab count and technology-specific research speed never throttle matrix producers"); + Equal(2800, twoLabs.Power.ConsumptionWatts, + "each additional lab still contributes its rated power"); + + var noTechMatrixCatalog = new ProductionCatalog(matrixCatalog.Items.Values, + matrixCatalog.Recipes.Values, matrixCatalog.Buildings.Values, + new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }, + researchMatrixItemIds: matrixCatalog.ResearchMatrixItemIds); + var noTechMatrixReport = new FactoryBlackBoxAnalyzer(noTechMatrixCatalog).Analyze(matrixRequest); + Check(noTechMatrixReport.MaterialComplete && noTechMatrixReport.ItemFlows[6001].IsFinalProduct, + "matrix producers remain final research output without technology records"); + Equal(3, noTechMatrixReport.ItemFlows[2].SteadyStateExternalSupply.Value, + "unlocked-technology data cannot change upstream matrix throughput"); + + var oneMatrixRequest = new FactoryBlackBoxRequest(); + oneMatrixRequest.Buildings.Add(matrixRequest.Buildings[2]); + oneMatrixRequest.Buildings.Add(matrixRequest.Buildings[3]); + var oneMatrix = new FactoryBlackBoxAnalyzer(matrixCatalog).Analyze(oneMatrixRequest); + Check(oneMatrix.MaterialComplete && oneMatrix.ItemFlows.Keys.OrderBy(itemId => itemId) + .SequenceEqual(new[] { 2, 6001 }) && oneMatrix.ItemFlows[6001].IsFinalProduct && + oneMatrix.ItemFlows[6001].IsResearchProduct, + "research output includes only the matrix types made in the blueprint"); + Equal(3, oneMatrix.ItemFlows[2].SteadyStateExternalSupply.Value, + "a single produced matrix type retains full upstream inputs"); + var oneMatrixText = BlueprintDescriptionFormatter.Format(oneMatrix, TestItemTag, + new BlueprintDescriptionLabels("Factory power", "Logistics power", "Missing: ", "Excess: ", "Unknown", + "(known portion)", "Input: ", "Output: ", "Research: ")); + Check(oneMatrixText.Output == "" && oneMatrixText.Research == TestItemTag(6001) + " x6" && + oneMatrixText.Description == "Input: " + oneMatrixText.Input + + "\nResearch: " + oneMatrixText.Research, + "research-only output does not add an empty ordinary output line"); + + var externalMatrixRequest = new FactoryBlackBoxRequest(); + externalMatrixRequest.Buildings.Add(matrixRequest.Buildings[1]); + externalMatrixRequest.Buildings.Add(matrixRequest.Buildings[3]); + var externalMatrix = new FactoryBlackBoxAnalyzer(matrixCatalog).Analyze(externalMatrixRequest); + Equal(1, externalMatrix.ItemFlows[6001].RequiredExternalSupply, + "other buildings still require externally supplied matrices when none are made"); + Equal(1, externalMatrix.ItemFlows[6001].SteadyStateExternalSupply.Value, + "a research lab does not erase known external matrix requirements"); request.Buildings[0] = new ProductionBuildingSnapshot(1, 91, 0, 1, ProliferationMode.None); @@ -1275,6 +1538,677 @@ internal static class Program var missing = planner.Calculate(request); Check(missing.MaterialComplete && !missing.PowerComplete, "missing auxiliary rating does not discard complete material ledger"); + Check(!missing.PowerBreakdown.FactoryComplete && missing.PowerBreakdown.LogisticsComplete, + "planner marks factory consumption incomplete without inventing logistics demand"); + } + + private static void BlueprintJointProduction() + { + var analyzer = new FactoryBlackBoxAnalyzer(BlueprintCatalog()); + var request = BlueprintRequest(2); + var two = analyzer.Analyze(request); + Check(two.MaterialComplete && two.PowerComplete, "two joint-production buildings are complete"); + Equal(120, two.ItemFlows[2].GrossProduction, "two upstream buildings run at full load"); + Equal(120, two.ItemFlows[2].GrossConsumption, "downstream demand stays at full load"); + Equal(0, two.ItemFlows[2].OverbuildSurplus.Value, "both upstream buildings are necessary"); + Equal(0, two.ItemFlows[3].OverbuildSurplus.Value, "joint output is not falsely redundant"); + Equal(90, two.ItemFlows[3].CoproductSurplus.Value, "necessary joint production leaves B90"); + Equal(4000, two.Power.ConsumptionWatts, "two upstream and one downstream consume full power"); + + request.Buildings[0] = new ProductionBuildingSnapshot(1, 10, 610, 3, ProliferationMode.None); + var three = analyzer.Analyze(request); + Equal(180, three.ItemFlows[2].GrossProduction, "three upstream buildings retain their gross output"); + Equal(60, three.ItemFlows[2].OverbuildSurplus.Value, "third building's A60 is excess"); + Equal(60, three.ItemFlows[3].OverbuildSurplus.Value, "third building's B60 is excess"); + Equal(90, three.ItemFlows[3].CoproductSurplus.Value, + "B90 from necessary buildings remains a separate coproduct"); + Equal(150, three.ItemFlows[3].Surplus, "original B150 balance is not replaced by reduced output"); + Equal(5000, three.Power.ConsumptionWatts, "the redundant building still consumes full power"); + Equal(3, three.ItemFlows[1].RequiredExternalSupply, + "full-load raw material accounting remains unchanged"); + Equal(2, three.ItemFlows[1].SteadyStateExternalSupply.Value, + "an idle redundant joint producer consumes no steady-state raw material"); + + var reordered = new FactoryBlackBoxRequest(); + reordered.Buildings.Add(request.Buildings[1]); + reordered.Buildings.Add(new ProductionBuildingSnapshot(103, 10, 610, 1, ProliferationMode.None)); + reordered.Buildings.Add(new ProductionBuildingSnapshot(101, 10, 610, 1, ProliferationMode.None)); + reordered.Buildings.Add(new ProductionBuildingSnapshot(102, 10, 610, 1, ProliferationMode.None)); + var reverse = analyzer.Analyze(reordered); + foreach (var itemId in new[] { 2, 3 }) + { + Equal(three.ItemFlows[itemId].OverbuildSurplus.Value, reverse.ItemFlows[itemId].OverbuildSurplus.Value, + "reordered equivalent buildings retain one shared overbuild budget"); + Equal(three.ItemFlows[itemId].CoproductSurplus.Value, reverse.ItemFlows[itemId].CoproductSurplus.Value, + "reordered equivalent buildings retain their coproduct amounts"); + } + Equal(three.ItemFlows[1].SteadyStateExternalSupply.Value, + reverse.ItemFlows[1].SteadyStateExternalSupply.Value, + "steady-state inputs do not depend on blueprint building order"); + } + + private static void BlueprintSteadyStateInputs() + { + var catalog = BlueprintCatalog(); + var fractionalCatalog = new ProductionCatalog(catalog.Items.Values, + catalog.Recipes.Values.Where(recipe => recipe.Id != 611).Concat(new[] + { + Recipe(611, new[] { (2, 90.0), (3, 30.0) }, new[] { (4, 1.0) }) + }), catalog.Buildings.Values, new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var fractional = new FactoryBlackBoxAnalyzer(fractionalCatalog).Analyze(BlueprintRequest(2)); + Equal(2, fractional.ItemFlows[1].RequiredExternalSupply, + "the full-load report retains raw consumption below one-building headroom"); + Equal(1.5, fractional.ItemFlows[1].SteadyStateExternalSupply.Value, + "part of an upstream building slows when its output exceeds downstream demand"); + Equal(0, fractional.ItemFlows[2].OverbuildSurplus.Value, + "fractional throttling does not create a false whole-building overbuild warning"); + Equal(0, fractional.ItemFlows[2].CoproductSurplus.Value, + "the limiting joint product's fractional headroom is not an unavoidable coproduct"); + Equal(90, fractional.ItemFlows[3].CoproductSurplus.Value, + "necessary whole joint producers retain the other product's rated coproduct"); + + var singleOutput = new FactoryBlackBoxRequest(); + singleOutput.Buildings.Add(new ProductionBuildingSnapshot(1, 10, 612, 1, ProliferationMode.None)); + singleOutput.Buildings.Add(new ProductionBuildingSnapshot(2, 20, 611, 1, ProliferationMode.None)); + var single = new FactoryBlackBoxAnalyzer(catalog).Analyze(singleOutput); + Equal(0.5, single.ItemFlows[1].SteadyStateExternalSupply.Value, + "single-output headroom reduces upstream raw inputs without losing final capacity"); + Equal(120, single.ItemFlows[2].SteadyStateExternalSupply.Value, + "unavailable intermediate material remains an external input"); + + var chainCatalog = new ProductionCatalog(new[] + { + new ProductionItem(1, 0, true, false, 0, 0), + new ProductionItem(2, 710, false, false, 0, 0), + new ProductionItem(3, 711, false, false, 0, 0), + new ProductionItem(4, 712, false, false, 0, 0) + }, new[] + { + Recipe(710, new[] { (1, 1.0) }, new[] { (2, 4.0) }), + Recipe(711, new[] { (2, 4.0) }, new[] { (3, 2.0) }), + Recipe(712, new[] { (3, 1.0) }, new[] { (4, 1.0) }) + }, new[] { new ProductionBuilding(10, ProductionRecipeCategory.Assemble, 1, 1000, 100) }, + new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 }); + var chainRequest = new FactoryBlackBoxRequest(); + chainRequest.Buildings.Add(new ProductionBuildingSnapshot(1, 10, 710, 1, ProliferationMode.None)); + chainRequest.Buildings.Add(new ProductionBuildingSnapshot(2, 10, 711, 1, ProliferationMode.None)); + chainRequest.Buildings.Add(new ProductionBuildingSnapshot(3, 10, 712, 1, ProliferationMode.None)); + var chain = new FactoryBlackBoxAnalyzer(chainCatalog).Analyze(chainRequest); + Equal(0.5, chain.ItemFlows[1].SteadyStateExternalSupply.Value, + "downstream throttling propagates through multiple upstream stages"); + Equal(0, chain.ItemFlows[2].SteadyStateExternalSupply.Value, + "throttling does not invent external supply for balanced intermediates"); + Equal(1, chain.ItemFlows[4].GrossProduction, + "final rated output remains unchanged when upstream inputs are capped"); + Equal(3000, chain.Power.ConsumptionWatts, + "rated power remains distinct from estimated steady-state materials"); + } + + private static void BlueprintMixedProducersAndCycles() + { + var analyzer = new FactoryBlackBoxAnalyzer(BlueprintCatalog()); + var request = BlueprintRequest(3); + request.Buildings.Add(new ProductionBuildingSnapshot(3, 10, 612, 1, ProliferationMode.None)); + var mixed = analyzer.Analyze(request); + Equal(240, mixed.ItemFlows[3].GrossProduction, "single and joint B producers share the ledger"); + Equal(30, mixed.ItemFlows[3].GrossConsumption, "shared B keeps its downstream consumption"); + Equal(120, mixed.ItemFlows[3].OverbuildSurplus.Value, + "one joint and one single-output building are both redundant"); + Equal(90, mixed.ItemFlows[3].CoproductSurplus.Value, + "B90 from necessary joint production is not counted as excess again"); + Equal(60, mixed.ItemFlows[2].OverbuildSurplus.Value, + "all products of the removable joint building are accounted for"); + Equal(6000, mixed.Power.ConsumptionWatts, "mixed producers keep original full-load power"); + Equal(2, mixed.ItemFlows[1].SteadyStateExternalSupply.Value, + "shared intermediate producers use one steady-state raw material budget"); + + var catalog = BlueprintCatalog(); + var consumedJointCatalog = new ProductionCatalog(catalog.Items.Values, + catalog.Recipes.Values.Where(recipe => recipe.Id != 611).Concat(new[] + { + Recipe(611, new[] { (2, 60.0), (3, 90.0) }, new[] { (4, 1.0) }) + }), catalog.Buildings.Values, new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 }); + var consumedJointRequest = BlueprintRequest(1); + consumedJointRequest.Buildings.Add(new ProductionBuildingSnapshot(3, 10, 612, 1, + ProliferationMode.None)); + var consumedJoint = new FactoryBlackBoxAnalyzer(consumedJointCatalog).Analyze(consumedJointRequest); + Equal(30, consumedJoint.ItemFlows[3].Surplus, + "mixed producers retain their full-load ratio headroom"); + Equal(0, consumedJoint.ItemFlows[3].OverbuildSurplus.Value, + "both mixed producers are needed at the whole-building level"); + Equal(0, consumedJoint.ItemFlows[3].CoproductSurplus.Value, + "fully consumed joint output does not turn single-product headroom into a coproduct"); + Equal(1.5, consumedJoint.ItemFlows[1].SteadyStateExternalSupply.Value, + "single-product headroom still reduces steady-state input"); + var consumedJointText = BlueprintDescriptionFormatter.Format(consumedJoint, TestItemTag, + new BlueprintDescriptionLabels("Factory power", "Logistics power", "Missing: ", "Excess: ", "Unknown", + "(known portion)", "Input: ", "Output: ", "Research: ")); + Check(!consumedJointText.Output.Contains(TestItemTag(3)), + "the description does not export internally consumed joint products"); + + var sharedJointCatalog = new ProductionCatalog(catalog.Items.Values, + catalog.Recipes.Values.Where(recipe => recipe.Id != 611 && recipe.Id != 612).Concat(new[] + { + Recipe(611, new[] { (2, 60.0), (3, 90.0), (5, 60.0) }, new[] { (4, 1.0) }), + Recipe(612, new[] { (1, 1.0) }, new[] { (3, 60.0), (5, 60.0) }) + }), catalog.Buildings.Values, new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 }); + var sharedJoint = new FactoryBlackBoxAnalyzer(sharedJointCatalog).Analyze(consumedJointRequest); + Equal(30, sharedJoint.ItemFlows[3].CoproductSurplus.Value, + "necessary joint producers share internal consumption before exposing a coproduct"); + Equal(0, sharedJoint.ItemFlows[3].OverbuildSurplus.Value, + "shared coproduct output does not imply a removable joint producer"); + Equal(2, sharedJoint.ItemFlows[1].SteadyStateExternalSupply.Value, + "both necessary joint producers retain their steady-state input"); + + var reversedResults = new ProductionCatalog(catalog.Items.Values, + catalog.Recipes.Values.Where(recipe => recipe.Id != 610).Concat(new[] + { + Recipe(610, new[] { (1, 1.0) }, new[] { (3, 60.0), (2, 60.0) }) + }), catalog.Buildings.Values, + new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); + var alternate = new FactoryBlackBoxAnalyzer(reversedResults).Analyze(request); + Equal(mixed.ItemFlows[3].OverbuildSurplus.Value, alternate.ItemFlows[3].OverbuildSurplus.Value, + "overbuild does not depend on a recipe's result array order"); + Equal(mixed.ItemFlows[3].CoproductSurplus.Value, alternate.ItemFlows[3].CoproductSurplus.Value, + "coproduct does not depend on a recipe's result array order"); + + var shortage = analyzer.Analyze(BlueprintRequest(1)); + Equal(60, shortage.ItemFlows[2].IntermediateShortage, + "joint production with insufficient A reports an intermediate shortage"); + Equal(60, shortage.ItemFlows[2].RequiredExternalSupply, + "intermediate shortages remain external material requirements"); + Equal(60, shortage.ItemFlows[2].SteadyStateExternalSupply.Value, + "stable throughput never worsens an existing intermediate shortage"); + Equal(0, shortage.ItemFlows[2].OverbuildSurplus.Value, "a needed producer cannot be removed"); + Equal(30, shortage.ItemFlows[3].CoproductSurplus.Value, + "a known A shortage does not hide independently known B coproduct"); + Equal(3000, shortage.Power.ConsumptionWatts, "shortage does not throttle downstream power"); + + request.Buildings.Clear(); + request.Buildings.Add(new ProductionBuildingSnapshot(1, 10, 620, 1, ProliferationMode.None)); + var returned = analyzer.Analyze(request); + Equal(1, returned.ItemFlows[2].GrossProduction, "returned material keeps gross production"); + Equal(1, returned.ItemFlows[2].GrossConsumption, "returned material keeps gross consumption"); + Equal(0, returned.ItemFlows[2].RequiredExternalSupply, + "internal return does not create a false external input"); + Check(!returned.ItemFlows[2].IsFinalProduct, "a pure material return is not a final product"); + Equal(60, returned.ItemFlows[3].Surplus, "the same recipe still supplies its net output"); + + request.Buildings.Clear(); + request.Buildings.Add(new ProductionBuildingSnapshot(1, 10, 621, 1, ProliferationMode.None)); + request.Buildings.Add(new ProductionBuildingSnapshot(2, 10, 622, 1, ProliferationMode.None)); + var cycle = analyzer.Analyze(request); + foreach (var itemId in new[] { 5, 6 }) + { + Equal(1, cycle.ItemFlows[itemId].GrossProduction, "cyclic production stays gross"); + Equal(1, cycle.ItemFlows[itemId].GrossConsumption, "cyclic consumption stays gross"); + Equal(0, cycle.ItemFlows[itemId].IntermediateShortage, "balanced cycle has no missing inputs"); + Equal(0, cycle.ItemFlows[itemId].OverbuildSurplus.Value, "balanced cycle has no excess"); + Equal(0, cycle.ItemFlows[itemId].CoproductSurplus.Value, "balanced cycle has no coproduct"); + } + } + + private static void BlueprintProliferationAndCompleteness() + { + var analyzer = new FactoryBlackBoxAnalyzer(BlueprintCatalog()); + var sprayedRequest = new FactoryBlackBoxRequest { ProliferationEnabled = true }; + sprayedRequest.Buildings.Add(new ProductionBuildingSnapshot(1, 10, 610, 1, + ProliferationMode.ExtraProducts)); + sprayedRequest.Buildings.Add(new ProductionBuildingSnapshot(2, 10, 610, 1, + ProliferationMode.Speedup)); + var sprayed = analyzer.Analyze(sprayedRequest); + Equal(195, sprayed.ItemFlows[2].GrossProduction, + "highest captured proliferation keeps distinct extra-product and speedup modes"); + Check(sprayed.Groups[0].Process.ProliferationMode == ProliferationMode.ExtraProducts && + sprayed.Groups[1].Process.ProliferationMode == ProliferationMode.Speedup && + sprayed.Groups.All(group => group.Process.ProliferationLevel == 4), + "each building retains its native mode at the highest supported level"); + Check(!sprayed.ItemFlows.ContainsKey(7), "externally supplied input coating adds no inferred spray flow"); + sprayedRequest.ProliferationEnabled = false; + var unsprayed = analyzer.Analyze(sprayedRequest); + Equal(120, unsprayed.ItemFlows[2].GrossProduction, "unchecked proliferation restores plain capacity"); + Equal(2000, unsprayed.Power.ConsumptionWatts, "unchecked proliferation restores plain power"); + + var request = BlueprintRequest(2); + request.Buildings.Add(new ProductionBuildingSnapshot(3, 30, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary { ["ChargePowerWatts"] = 600000000 })); + var complete = analyzer.Analyze(request); + Equal(4000, complete.PowerBreakdown.FactoryConsumptionWatts.Value, + "factory consumption excludes selected logistics chargers"); + Equal(600000000, complete.PowerBreakdown.LogisticsConsumptionWatts.Value, + "logistics consumption uses configured charging maximum"); + Equal(600004000, complete.Power.ConsumptionWatts, "the existing total still includes both categories"); + Equal(0, complete.Power.AccumulatorChargingWatts, + "logistics charging does not become accumulator exchange"); + + request.Buildings.Add(new ProductionBuildingSnapshot(4, 31, 0, 1, ProliferationMode.None)); + request.Buildings.Add(new ProductionBuildingSnapshot(5, 32, 0, 1, ProliferationMode.None)); + var withAuxiliaries = analyzer.Analyze(request); + Equal(5100, withAuxiliaries.PowerBreakdown.FactoryConsumptionWatts.Value, + "sorters and spray coaters add to factory rather than logistics consumption"); + Equal(600000000, withAuxiliaries.PowerBreakdown.LogisticsConsumptionWatts.Value, + "non-logistics auxiliary watts do not change charging limits"); + request.Buildings.RemoveRange(3, 2); + + request.Buildings[2] = new ProductionBuildingSnapshot(3, 30, 0, 1, ProliferationMode.None); + var missingLogistics = analyzer.Analyze(request); + Check(missingLogistics.MaterialComplete && !missingLogistics.PowerComplete && + missingLogistics.PowerBreakdown.FactoryComplete && + !missingLogistics.PowerBreakdown.LogisticsComplete, + "unknown logistics charging does not discard known factory watts"); + Equal(4000, missingLogistics.PowerBreakdown.FactoryConsumptionWatts.Value, + "factory category remains usable when logistics power is unknown"); + + request.Buildings[0] = new ProductionBuildingSnapshot(1, 10, 999, 2, ProliferationMode.None); + request.Buildings[2] = new ProductionBuildingSnapshot(3, 30, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary { ["ChargePowerWatts"] = 600000000 }); + var missingFactory = analyzer.Analyze(request); + Check(!missingFactory.MaterialComplete && !missingFactory.PowerComplete && + !missingFactory.PowerBreakdown.FactoryComplete && missingFactory.PowerBreakdown.LogisticsComplete, + "unknown factory process does not discard known logistics charging"); + Equal(600000000, missingFactory.PowerBreakdown.LogisticsConsumptionWatts.Value, + "known logistics consumption remains independently reportable"); + + request = BlueprintRequest(3); + request.Buildings.Add(new ProductionBuildingSnapshot(3, 40, 0, 2, ProliferationMode.None, + operatingParameters: new Dictionary { ["MachineSpeedFactor"] = 1.5 })); + var partialMaterials = analyzer.Analyze(request); + Check(!partialMaterials.MaterialComplete && !partialMaterials.PowerComplete && + partialMaterials.PowerBreakdown.FactoryComplete, + "a miner lacking blueprint resource context retains calculable native demand"); + Equal(22500, partialMaterials.PowerBreakdown.FactoryConsumptionWatts.Value, + "miner speed-ratio watts add to the other full-load factory consumers"); + Check(partialMaterials.ItemFlows[3].OverbuildSurplus == null && + partialMaterials.ItemFlows[3].CoproductSurplus == null, + "partial materials cannot establish overbuild or coproduct conclusions"); + Equal(3, partialMaterials.ItemFlows[1].RequiredExternalSupply, + "partial materials retain the full-load input ledger"); + Equal(2, partialMaterials.ItemFlows[1].SteadyStateExternalSupply.Value, + "unrelated unknown settings do not prevent capping known upstream inputs"); + Equal(1, partialMaterials.ItemFlows[4].NetFlow, + "partial material estimates keep independently known rated final outputs"); + + var unknownRecipeRequest = BlueprintRequest(3); + unknownRecipeRequest.Buildings.Add(new ProductionBuildingSnapshot(3, 10, 999, 1, + ProliferationMode.None)); + var unknownRecipe = analyzer.Analyze(unknownRecipeRequest); + Equal(3, unknownRecipe.ItemFlows[1].SteadyStateExternalSupply.Value, + "unknown downstream recipe must not be mistaken for zero demand"); + Check(!unknownRecipe.ItemFlows[4].IsFinalProduct, + "an unrecognized downstream recipe cannot establish a final product"); + + var partialCatalog = new ProductionCatalog(BlueprintCatalog().Items.Values, + BlueprintCatalog().Recipes.Values.Concat(new[] + { + new ProductionRecipe(613, ProductionRecipeCategory.Fractionate, 3600, false, + new[] { new KeyValuePair(2, 1) }, + new[] { new KeyValuePair(4, 1) }) + }), BlueprintCatalog().Buildings.Values.Concat(new[] + { + new ProductionBuilding(50, ProductionRecipeCategory.Fractionate, 1, 300, 30, + ProductionBuildingKind.Fractionator) + }), new[] { 0.0 }, new[] { 0.0 }, new[] { 1.0 }); + var incompleteDownstreamRequest = BlueprintRequest(3); + incompleteDownstreamRequest.Buildings.Add(new ProductionBuildingSnapshot(3, 50, 613, 1, + ProliferationMode.None)); + var incompleteDownstream = new FactoryBlackBoxAnalyzer(partialCatalog).Analyze(incompleteDownstreamRequest); + Check(incompleteDownstream.Diagnostics.Any(diagnostic => + diagnostic.Code == ProductionDiagnosticCode.MissingOperatingParameter), + "missing fractionator throughput leaves its known input demand unmodeled"); + Equal(3, incompleteDownstream.ItemFlows[1].SteadyStateExternalSupply.Value, + "an unresolved but known downstream input prevents underestimating its upstream supply"); + } + + private static void BlueprintDescriptionFormattingAndFields() + { + var labels = new BlueprintDescriptionLabels("工厂耗电", "物流耗电", "缺少:", "多余:", "未知", + "(已知部分)", "输入:", "输出:", "研究:"); + var joint = new FactoryBlackBoxAnalyzer(BlueprintCatalog()).Analyze(BlueprintRequest(3)); + var text = BlueprintDescriptionFormatter.Format(joint, TestItemTag, labels); + Check(text.Power == "工厂耗电 5kW", "absent logistics consumption is omitted"); + var warnings = "多余:" + TestItemTag(2) + " x60, " + TestItemTag(3) + " x60"; + Check(text.Input == TestItemTag(1) + " x2", + "input excludes warnings and reflects upstream throughput capped by downstream demand"); + Check(text.Output == TestItemTag(3) + " x90, " + TestItemTag(4) + " x1", + "coproduct appears once alongside the final product"); + Check(text.Warnings == warnings && text.Description == warnings + "\n输入:" + text.Input + + "\n输出:" + text.Output, + "excess items share one labeled line before input and output"); + Check(!text.Input.Contains(((char)10).ToString()) && !text.Output.Contains(((char)10).ToString()), + "each material line retains comma-separated entries without embedded breaks"); + + var shortage = BlueprintDescriptionFormatter.Format( + new FactoryBlackBoxAnalyzer(BlueprintCatalog()).Analyze(BlueprintRequest(1)), TestItemTag, labels); + Check(shortage.Description.StartsWith("缺少:" + TestItemTag(2) + " x60\n输入:") && + !shortage.Input.Contains("缺少"), + "shortage warnings are placed before inputs rather than inside them"); + + var warningOnlyReport = new ProductionReport(ProductionStatus.Complete, true, true, + new[] + { + new ProductionItemFlow(52, 2, 3, 0, 0, 0, 0, 1, + false, false, 0, Array.Empty(), Array.Empty(), 1, 0, 0), + new ProductionItemFlow(53, 1, 3, 0, 0, 0, 0, 2, + false, false, 0, Array.Empty(), Array.Empty(), 2, 0, 0), + new ProductionItemFlow(54, 3, 0, 0, 0, 0, 3, 0, + false, true, 3, Array.Empty(), Array.Empty(), 0, 3, 0) + }, + Array.Empty(), Array.Empty(), + new ProductionPower(0, 0, 0, 0, 0, 0, ProductionPowerScope.SelectedFacilities), + new ProductionPowerBreakdown(0, 0, true, true)); + var warningOnly = BlueprintDescriptionFormatter.Format(warningOnlyReport, TestItemTag, labels); + var warningLines = "缺少:" + TestItemTag(52) + " x1, " + TestItemTag(53) + " x2" + + "\n多余:" + TestItemTag(54) + " x3"; + Check(warningOnly.Warnings == warningLines && warningOnly.Description == warningLines && + warningOnly.Input == "" && warningOnly.Output == "" && warningOnly.Research == "", + "missing and excess use separate aligned lines without repeating labels or adding empty lines"); + + var powerOnly = new ProductionReport(ProductionStatus.Complete, true, true, + Array.Empty(), Array.Empty(), + Array.Empty(), new ProductionPower(3100000000, 3100000000, 0, 0, 0, 0, + ProductionPowerScope.SelectedFacilities), + new ProductionPowerBreakdown(2500000000, 600000000, true, true)); + var large = BlueprintDescriptionFormatter.Format(powerOnly, TestItemTag, labels); + Check(large.Power == "工厂耗电 2.5GW | 物流耗电 600MW", + "gigawatt and megawatt display matches the native Chinese field example"); + Check(large.Input == "" && large.Output == "" && large.Description == "", + "empty material categories add no description lines"); + + var logisticsRequest = new FactoryBlackBoxRequest(); + logisticsRequest.Buildings.Add(new ProductionBuildingSnapshot(1, 30, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary { ["ChargePowerWatts"] = 600000000 })); + var logisticsOnly = BlueprintDescriptionFormatter.Format( + new FactoryBlackBoxAnalyzer(BlueprintCatalog()).Analyze(logisticsRequest), TestItemTag, labels); + Check(logisticsOnly.Power == "物流耗电 600MW" && logisticsOnly.Description == "", + "logistics-only blueprints do not show empty factory or material categories"); + logisticsRequest.Buildings[0] = new ProductionBuildingSnapshot(1, 30, 0, 1, ProliferationMode.None); + var unknownLogistics = BlueprintDescriptionFormatter.Format( + new FactoryBlackBoxAnalyzer(BlueprintCatalog()).Analyze(logisticsRequest), TestItemTag, labels); + Check(unknownLogistics.Power == "物流耗电 未知", + "unknown charging demand is not omitted as an absent building"); + + var request = BlueprintRequest(2); + request.Buildings.Add(new ProductionBuildingSnapshot(3, 30, 0, 1, ProliferationMode.None, + operatingParameters: new Dictionary { ["ChargePowerWatts"] = 600000000 })); + request.Buildings[0] = new ProductionBuildingSnapshot(1, 10, 999, 2, ProliferationMode.None); + var missingFactory = new FactoryBlackBoxAnalyzer(BlueprintCatalog()).Analyze(request); + var partial = BlueprintDescriptionFormatter.Format(missingFactory, TestItemTag, labels); + Check(partial.Power == "工厂耗电 未知 | 物流耗电 600MW", + "unknown factory demand cannot become zero or erase known logistics power"); + Check(partial.Input.Contains("(已知部分)"), + "known material inputs are explicitly identified as partial"); + + request = BlueprintRequest(3); + request.Buildings.Add(new ProductionBuildingSnapshot(3, 40, 0, 1, ProliferationMode.None)); + var partialProduction = new FactoryBlackBoxAnalyzer(BlueprintCatalog()).Analyze(request); + var knownText = BlueprintDescriptionFormatter.Format(partialProduction, TestItemTag, labels); + Check(knownText.Input.Contains("(已知部分)") && knownText.Output.Contains("(已知部分)") && + !knownText.Input.Contains("多余") && !knownText.Output.Contains(TestItemTag(3)), + "partial materials retain known rates without inferring excess or coproducts"); + Check(knownText.Input.Contains(TestItemTag(1) + " x2") && + !knownText.Input.Contains(TestItemTag(1) + " x3"), + "partial descriptions cap known material inputs at downstream throughput"); + + request = new FactoryBlackBoxRequest(); + request.Buildings.Add(new ProductionBuildingSnapshot(3, 40, 0, 1, ProliferationMode.None)); + var noMaterial = new FactoryBlackBoxAnalyzer(BlueprintCatalog()).Analyze(request); + partial = BlueprintDescriptionFormatter.Format(noMaterial, TestItemTag, labels); + Check(partial.Input == "" && partial.Output == "" && partial.Description == "", + "unknown materials without known entries do not create empty lines"); + Check(partial.Power == "工厂耗电 4kW", + "the miner's independent power remains available without its resource context"); + + var failed = false; + try + { + BlueprintDescriptionFormatter.Format(ProductionReport.Failure(new ProductionDiagnostic( + ProductionDiagnosticCode.DataNotReady, "Data is not ready.")), TestItemTag, labels); + } + catch (InvalidOperationException) + { + failed = true; + } + + Check(failed, "unavailable catalog cannot be formatted as a complete zero report"); + + var fractional = new ProductionReport(ProductionStatus.Complete, true, true, + new[] + { + new ProductionItemFlow(42, 0.125, 0, 0, 0, 0, 0.125, 0, + true, false, 0, Array.Empty(), Array.Empty()), + new ProductionItemFlow(43, 1.2, 0, 0, 0, 0, 1.2, 0, + true, false, 0, Array.Empty(), Array.Empty()) + }, Array.Empty(), Array.Empty(), + new ProductionPower(0, 0, 0, 0, 0, 0, ProductionPowerScope.SelectedFacilities), + new ProductionPowerBreakdown(0, 0, true, true)); + var rounded = BlueprintDescriptionFormatter.Format(fractional, TestItemTag, labels); + Check(rounded.Output == TestItemTag(42) + " x0.125, " + TestItemTag(43) + " x1.2", + "display rounding retains small nonzero rates and omits unnecessary trailing zeros"); + Check(rounded.Power == "" && rounded.Input == "" && + rounded.Description == "输出:" + rounded.Output, + "no consumers means no power field and an output-only report has one line"); + + var inputOnlyReport = new ProductionReport(ProductionStatus.Complete, true, true, + new[] { new ProductionItemFlow(51, 0, 3, 0, 0, 0, 0, 3, + false, false, 0, Array.Empty(), Array.Empty()) }, + Array.Empty(), Array.Empty(), + new ProductionPower(0, 0, 0, 0, 0, 0, ProductionPowerScope.SelectedFacilities), + new ProductionPowerBreakdown(0, 0, true, true)); + var inputOnly = BlueprintDescriptionFormatter.Format(inputOnlyReport, TestItemTag, labels); + Check(inputOnly.Output == "" && inputOnly.Description == "输入:" + inputOnly.Input, + "an input-only report omits the empty output line"); + + var longReport = new ProductionReport(ProductionStatus.Complete, true, true, + Enumerable.Range(1000, 140).Select(itemId => new ProductionItemFlow(itemId, 1.2, 0, 0, 0, 0, 1.2, 0, + true, false, 0, Array.Empty(), Array.Empty())), + Array.Empty(), Array.Empty(), + new ProductionPower(0, 0, 0, 0, 0, 0, ProductionPowerScope.SelectedFacilities), + new ProductionPowerBreakdown(0, 0, true, true)); + var longText = BlueprintDescriptionFormatter.Format(longReport, TestItemTag, labels); + Check(longText.Description.Length > BlueprintDescriptionText.MaximumDescriptionLength && + !longText.Description.Contains("\n") && longText.Description.Contains(TestItemTag(1139)), + "long material lines are not truncated and can be refused at the native description limit"); + TestNativeFields(); + } + + private static void TestNativeFields() + { + var firstFields = TestBlueprintFields("2.5GW"); + var result = BlueprintDescriptionFields.TryUpdate("Other:unchanged;", firstFields, 20, + EscapeNativeField, UnescapeNativeField, out var generated); + Check(result == BlueprintFieldUpdateResult.Updated && generated == "Other:unchanged;Power:2.5GW;", + "only the power field is appended while unrelated fields remain intact"); + + var escapedFields = TestBlueprintFields("2.5GW:250; " + (char)92 + "extra"); + result = BlueprintDescriptionFields.TryUpdate("", escapedFields, 20, + EscapeNativeField, UnescapeNativeField, out var escaped); + var escapedPower = escaped.Split(';')[0]; + Check(result == BlueprintFieldUpdateResult.Updated && + UnescapeNativeField(escapedPower.Substring(escapedPower.IndexOf(':') + 1)) == escapedFields[0].Value, + "native backslash, semicolon, and colon escaping still round-trips power fields"); + + result = BlueprintDescriptionFields.TryUpdate(generated, + TestBlueprintFields("3GW"), 20, + EscapeNativeField, UnescapeNativeField, out var repeated); + Check(result == BlueprintFieldUpdateResult.Updated && repeated == "Other:unchanged;Power:3GW;", + "repeated generation updates the power field without appending duplicates"); + + result = BlueprintDescriptionFields.TryUpdate( + "Note:keep;Input (per minute):manual;Output (per minute):manual;Power:old;", firstFields, 20, + EscapeNativeField, UnescapeNativeField, out var preserved); + Check(result == BlueprintFieldUpdateResult.Updated && + preserved == "Note:keep;Input (per minute):manual;Output (per minute):manual;Power:2.5GW;", + "only the power field is updated; input and output custom fields remain untouched"); + + var partialExisting = "Unrelated:hand edited;Input:manual;"; + result = BlueprintDescriptionFields.TryUpdate(partialExisting, + TestBlueprintFields("100MW"), 20, + EscapeNativeField, UnescapeNativeField, out var updated); + Check(result == BlueprintFieldUpdateResult.Updated && + updated == "Unrelated:hand edited;Input:manual;Power:100MW;", + "a custom input field remains unchanged when power is appended"); + + var chineseFields = new[] + { + new BlueprintDescriptionField("耗电", "新功率", "Power", "耗电") + }; + result = BlueprintDescriptionFields.TryUpdate("Power:old;输入:manual;Output (per minute):manual;", + chineseFields, 3, EscapeNativeField, UnescapeNativeField, out var translated); + Check(result == BlueprintFieldUpdateResult.Updated && + translated == "耗电:新功率;输入:manual;Output (per minute):manual;", + "English and Chinese power titles match while other localized fields remain unchanged"); + + var duplicateNames = "Power:old;耗电:old;Note:Power Input Output;输入(每分钟):manual;Output:manual;"; + result = BlueprintDescriptionFields.TryUpdate(duplicateNames, + TestBlueprintFields("new"), 5, EscapeNativeField, UnescapeNativeField, + out var keptDuplicates); + Check(result == BlueprintFieldUpdateResult.Updated && + keptDuplicates == "Power:new;Note:Power Input Output;输入(每分钟):manual;Output:manual;", + "duplicate power slots are merged without modifying other titled fields"); + + var noPowerFields = TestBlueprintFields(null); + result = BlueprintDescriptionFields.TryUpdate("Other:keep;Power:old;耗电:old;输入:manual;Output:manual;", + noPowerFields, 20, EscapeNativeField, UnescapeNativeField, out var removed); + Check(result == BlueprintFieldUpdateResult.Updated && removed == "Other:keep;输入:manual;Output:manual;", + "a blueprint without consumers removes only stale power fields"); + result = BlueprintDescriptionFields.TryUpdate("", noPowerFields, 20, + EscapeNativeField, UnescapeNativeField, out var empty); + Check(result == BlueprintFieldUpdateResult.Updated && empty == "", + "empty power and material categories do not create any custom fields"); + + var full = string.Concat(Enumerable.Range(0, 20).Select(index => "Custom" + index + ":keep;")); + result = BlueprintDescriptionFields.TryUpdate(full, firstFields, 20, + EscapeNativeField, UnescapeNativeField, out var rejected); + Check(result == BlueprintFieldUpdateResult.CapacityExceeded && rejected == full, + "a missing power field at native capacity causes an all-or-nothing refusal"); + result = BlueprintDescriptionFields.TryUpdate(full, noPowerFields, 20, + EscapeNativeField, UnescapeNativeField, out updated); + Check(result == BlueprintFieldUpdateResult.Updated && updated == full, + "description-only generation needs no custom-field slot even at native capacity"); + var onePresent = "Power:old;" + string.Concat(Enumerable.Range(0, 19) + .Select(index => "Custom" + index + ":keep;")); + result = BlueprintDescriptionFields.TryUpdate(onePresent, firstFields, 20, + EscapeNativeField, UnescapeNativeField, out updated); + Check(result == BlueprintFieldUpdateResult.Updated && + updated == "Power:2.5GW;" + onePresent.Substring("Power:old;".Length), + "existing power fields can be updated at the native field limit"); + var otherFieldsAtCapacity = "Input:manual;Output:manual;" + string.Concat(Enumerable.Range(0, 18) + .Select(index => "Custom" + index + ":keep;")); + result = BlueprintDescriptionFields.TryUpdate(otherFieldsAtCapacity, firstFields, 20, + EscapeNativeField, UnescapeNativeField, out rejected); + Check(result == BlueprintFieldUpdateResult.CapacityExceeded && rejected == otherFieldsAtCapacity, + "other input and output fields cannot be removed to make room for power"); + + result = BlueprintDescriptionFields.TryUpdate("Unterminated:old", firstFields, 20, + EscapeNativeField, UnescapeNativeField, out rejected); + Check(result == BlueprintFieldUpdateResult.InvalidFields && rejected == "Unterminated:old", + "invalid native serialization is rejected without changing existing text"); + foreach (var malformed in new[] { "MissingDelimiter;", "Too:many:delimiters;", "Valid:value;;" }) + { + Check(!BlueprintDescriptionFields.IsNativeFormatValid(malformed), + "malformed native fields are detected before the inspector collects pending edits"); + result = BlueprintDescriptionFields.TryUpdate(malformed, firstFields, 20, + EscapeNativeField, UnescapeNativeField, out rejected); + Check(result == BlueprintFieldUpdateResult.InvalidFields && rejected == malformed, + "malformed native fields cannot be partially replaced or silently discarded"); + } + } + + private static BlueprintDescriptionField[] TestBlueprintFields(string power) + { + return new[] { new BlueprintDescriptionField("Power", power, "耗电") }; + } + + private static string EscapeNativeField(string value) + { + var serialized = new System.Text.StringBuilder(); + foreach (var character in value) + { + if (character == (char)92) serialized.Append((char)92).Append((char)92); + else if (character == ';') serialized.Append((char)92).Append('b'); + else if (character == ':') serialized.Append((char)92).Append('c'); + else serialized.Append(character); + } + + return serialized.ToString(); + } + + private static string UnescapeNativeField(string value) + { + var text = new System.Text.StringBuilder(); + for (var index = 0; index < value.Length; index++) + { + if (value[index] != (char)92 || index + 1 >= value.Length) + { + text.Append(value[index]); + continue; + } + + index++; + switch (value[index]) + { + case 'b': text.Append(';'); break; + case 'c': text.Append(':'); break; + case (char)92: text.Append((char)92); break; + default: text.Append((char)92).Append(value[index]); break; + } + } + + return text.ToString(); + } + + private static string TestItemTag(int itemId) + { + return ((char)92).ToString() + "item" + itemId + "-;"; + } + + private static FactoryBlackBoxRequest BlueprintRequest(int upstreamBuildings) + { + var request = new FactoryBlackBoxRequest(); + request.Buildings.Add(new ProductionBuildingSnapshot(1, 10, 610, upstreamBuildings, + ProliferationMode.None)); + request.Buildings.Add(new ProductionBuildingSnapshot(2, 20, 611, 1, ProliferationMode.None)); + return request; + } + + private static ProductionCatalog BlueprintCatalog() + { + return new ProductionCatalog(new[] + { + new ProductionItem(1, 0, true, false, 0, 0), + new ProductionItem(2, 610, false, false, 0, 0), + new ProductionItem(3, 610, false, false, 0, 0), + new ProductionItem(4, 611, false, false, 0, 0), + new ProductionItem(5, 621, false, false, 0, 0), + new ProductionItem(6, 622, false, false, 0, 0), + new ProductionItem(7, 0, false, false, 4, 60) + }, new[] + { + Recipe(610, new[] { (1, 1.0) }, new[] { (2, 60.0), (3, 60.0) }), + Recipe(611, new[] { (2, 120.0), (3, 30.0) }, new[] { (4, 1.0) }), + Recipe(612, new[] { (1, 1.0) }, new[] { (3, 60.0) }), + Recipe(620, new[] { (1, 1.0), (2, 1.0) }, new[] { (2, 1.0), (3, 60.0) }), + Recipe(621, new[] { (5, 1.0) }, new[] { (6, 1.0) }), + Recipe(622, new[] { (6, 1.0) }, new[] { (5, 1.0) }) + }, new[] + { + new ProductionBuilding(10, ProductionRecipeCategory.Assemble, 1, 1000, 100), + new ProductionBuilding(20, ProductionRecipeCategory.Assemble, 1, 2000, 200), + new ProductionBuilding(30, ProductionRecipeCategory.None, 0, 600000000, 0, + ProductionBuildingKind.Logistics), + new ProductionBuilding(31, ProductionRecipeCategory.None, 0, 900, 50, + ProductionBuildingKind.Auxiliary), + new ProductionBuilding(32, ProductionRecipeCategory.None, 0, 200, 10, + ProductionBuildingKind.Auxiliary), + new ProductionBuilding(40, ProductionRecipeCategory.None, 0, 4000, 200, + ProductionBuildingKind.Miner, minerKind: ProductionMinerKind.Vein, miningPeriodTicks: 60000) + }, new[] { 0.0, 0.25, 0.5, 0.75, 1.0 }, + new[] { 0.0, 0.125, 0.2, 0.225, 0.25 }, + new[] { 1.0, 1.3, 1.7, 2.1, 2.5 }); } private static ProductionPlanRequest Request(params (int id, double rate)[] targets)