mirror of
https://github.com/soarqin/DSP_Mods.git
synced 2026-11-22 18:19:02 +08:00
Compare commits
228
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
476c193aa2 | ||
|
|
307bb4740d | ||
|
|
8696a80a66 | ||
|
|
d4ba72abf4 | ||
|
|
bcc82e1056 | ||
|
|
d52bf1034a | ||
|
|
5fb8695348 | ||
|
|
99bcf7fa5f | ||
|
|
6ced106901 | ||
|
|
6a292e0816 | ||
|
|
6845b0c56f | ||
|
|
205cf55440 | ||
|
|
9fc2723bca | ||
|
|
12467b9345 | ||
|
|
b08eaf13b7 | ||
|
|
a4ac2efe4b | ||
|
|
e91ce4376b | ||
|
|
94a6833aae | ||
|
|
439b5053d8 | ||
|
|
a87a6455a5 | ||
|
|
d6e92292d3 | ||
|
|
1c5073c6ac | ||
|
|
d084f9cf75 | ||
|
|
60d54ac918 | ||
|
|
8a10fc909a | ||
|
|
0f640eb75b | ||
|
|
ac4210fe5d | ||
|
|
367a72b375 | ||
|
|
c0c4f51312 | ||
|
|
3e3e995d55 | ||
|
|
63a6a6ec6c | ||
|
|
f03d6c758e | ||
|
|
92e6511d91 | ||
|
|
e95c832e03 | ||
|
|
94254b8c28 | ||
|
|
ce9a4b73cd | ||
|
|
b5019abb62 | ||
|
|
d32b44e337 | ||
|
|
fe9c771230 | ||
|
|
b5cb9aefb9 | ||
|
|
3a840e7b2d | ||
|
|
b7564903d0 | ||
|
|
27c6a959ad | ||
|
|
7f9f0b62ae | ||
|
|
04a2fbb85a | ||
|
|
f5cb17dbd8 | ||
|
|
3a5676d737 | ||
|
|
2c601e3546 | ||
|
|
fa65236d5c | ||
|
|
7dd9830b48 | ||
|
|
75017476e3 | ||
|
|
1cbda9a1d6 | ||
|
|
82f6f53fa8 | ||
|
|
0604308d8a | ||
|
|
f91ccfcffb | ||
|
|
e74bd915a7 | ||
|
|
3f8e04f4a0 | ||
|
|
5ae85eb031 | ||
|
|
47c3c79d8c | ||
|
|
4b2f9c67dc | ||
|
|
87061d5235 | ||
|
|
574919f1f0 | ||
|
|
f611f2f9b3 | ||
|
|
0e09c17ea0 | ||
|
|
69d5a4b3ce | ||
|
|
53d558a9a4 | ||
|
|
a48ae5ad96 | ||
|
|
82365b3d16 | ||
|
|
010ec73c8d | ||
|
|
66ecebaca7 | ||
|
|
15c5bbdd72 | ||
|
|
6b03801681 | ||
|
|
db15c65961 | ||
|
|
ff7ce158cc | ||
|
|
ab1d20683d | ||
|
|
c2016909ff | ||
|
|
cca8b8594d | ||
|
|
647b130993 | ||
|
|
b74005282e | ||
|
|
76d9d9fa21 | ||
|
|
8d70ce8862 | ||
|
|
51fc080ff2 | ||
|
|
036243fd4a | ||
|
|
34c99701ca | ||
|
|
6e2b21a0a0 | ||
|
|
1939a9cf22 | ||
|
|
25b33144b8 | ||
|
|
a133fd9e14 | ||
|
|
7973cbe358 | ||
|
|
36426d034d | ||
|
|
4fb43c73b5 | ||
|
|
06c3532acc | ||
|
|
54c1700fcd | ||
|
|
6c7f9867d0 | ||
|
|
d843090622 | ||
|
|
439d74c817 | ||
|
|
ed916ebe7f | ||
|
|
f4b163fae9 | ||
|
|
8bfcee2a81 | ||
|
|
b5b2fee14e | ||
|
|
b6657c96c0 | ||
|
|
2dce3a7b93 | ||
|
|
eae4ba0376 | ||
|
|
06015d51d0 | ||
|
|
099f3ee35a | ||
|
|
39bdf06e88 | ||
|
|
87f08f3f8d | ||
|
|
f822c1a5c6 | ||
|
|
ce199374b4 | ||
|
|
dace35a691 | ||
|
|
f2abb7cc2c | ||
|
|
91259bbd17 | ||
|
|
cb7a965d12 | ||
|
|
bfe0787923 | ||
|
|
4ed33b2638 | ||
|
|
ee7ea6ec35 | ||
|
|
64f9aee06b | ||
|
|
cc783937e6 | ||
|
|
f1cfc5619f | ||
|
|
ffd8b91930 | ||
|
|
79dea142de | ||
|
|
c3f3c2e96e | ||
|
|
63aaceda6f | ||
|
|
33921e7177 | ||
|
|
7a8f4af31d | ||
|
|
44efbdbb4f | ||
|
|
b7180afff2 | ||
|
|
e5cb52c3f4 | ||
|
|
ca4244384c | ||
|
|
19629eae97 | ||
|
|
93e60cd4f0 | ||
|
|
be86aebf7c | ||
|
|
69b028d706 | ||
|
|
93c39e2133 | ||
|
|
a894c34987 | ||
|
|
d7f8dc55d4 | ||
|
|
2e6950afb3 | ||
|
|
a5b2bdedd4 | ||
|
|
a346778db9 | ||
|
|
109c6afd90 | ||
|
|
e2848b4f97 | ||
|
|
f69a90d452 | ||
|
|
e91271e137 | ||
|
|
524e2b62f0 | ||
|
|
2487a099c1 | ||
|
|
7e9f9ee1ce | ||
|
|
f7fc9aaab0 | ||
|
|
c823e72c67 | ||
|
|
669ce9f88c | ||
|
|
a9ad961bd3 | ||
|
|
d6b00b1b78 | ||
|
|
ad99b49bad | ||
|
|
5e501ea649 | ||
|
|
d98d87af48 | ||
|
|
6ab286bb0b | ||
|
|
6f33669163 | ||
|
|
91184ccc3a | ||
|
|
2e13206346 | ||
|
|
3e24461ef0 | ||
|
|
097a5c8e8a | ||
|
|
63fb13bf92 | ||
|
|
e758209d99 | ||
|
|
a5009496d5 | ||
|
|
29b30996e6 | ||
|
|
60d14c9401 | ||
|
|
f0ee1aaea9 | ||
|
|
358fd4cf23 | ||
|
|
80aa2f9b70 | ||
|
|
5914f02d09 | ||
|
|
d9d1e0108f | ||
|
|
2456280151 | ||
|
|
0d090ddfb0 | ||
|
|
39578559aa | ||
|
|
157c86112b | ||
|
|
d0c20693e3 | ||
|
|
8ae88f4b41 | ||
|
|
c1428f6aee | ||
|
|
260e419855 | ||
|
|
6e0484f035 | ||
|
|
6e4416389d | ||
|
|
71c0fe75db | ||
|
|
aa775bd05f | ||
|
|
9787636d08 | ||
|
|
256faeee19 | ||
|
|
78e86aeafe | ||
|
|
3156f0ffb5 | ||
|
|
2377f92589 | ||
|
|
788ed4275e | ||
|
|
ed8d7d61ff | ||
|
|
6eb9161af1 | ||
|
|
2201de2b1b | ||
|
|
b537ff22be | ||
|
|
0049629fd1 | ||
|
|
c339041824 | ||
|
|
0d7941387f | ||
|
|
f237789fa0 | ||
|
|
b2c04c1dff | ||
|
|
29ee32b11b | ||
|
|
3f7c384284 | ||
|
|
556493b2b6 | ||
|
|
269cc3b801 | ||
|
|
cacbfd6d5f | ||
|
|
45445f82a1 | ||
|
|
1a242af84e | ||
|
|
1467a6010d | ||
|
|
6f5b779d58 | ||
|
|
d8fa46d495 | ||
|
|
af3b46be11 | ||
|
|
96f160926c | ||
|
|
ee812bbc79 | ||
|
|
052c23d3b7 | ||
|
|
be9de43492 | ||
|
|
2dbf017a5e | ||
|
|
3c7744047c | ||
|
|
a9959a2f07 | ||
|
|
77f5803a24 | ||
|
|
e9bbcf5e2c | ||
|
|
a183485286 | ||
|
|
5a6cfb18c9 | ||
|
|
49226001be | ||
|
|
7c1e88f86d | ||
|
|
16429936a9 | ||
|
|
d711dd25ef | ||
|
|
e909b6d9d2 | ||
|
|
2a4008deac | ||
|
|
6b423225fe | ||
|
|
9d9a12c1af | ||
|
|
1d11ba90bd |
No files matched your search
@@ -0,0 +1,28 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
end_of_line = crlf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.{cs,vb}]
|
||||
# Suggestion-only so existing code does not break the build
|
||||
dotnet_style_qualification_for_field = false:suggestion
|
||||
dotnet_style_qualification_for_property = false:suggestion
|
||||
dotnet_style_qualification_for_method = false:suggestion
|
||||
dotnet_style_qualification_for_event = false:suggestion
|
||||
dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion
|
||||
dotnet_style_readonly_field = true:suggestion
|
||||
csharp_style_var_for_built_in_types = true:suggestion
|
||||
csharp_style_var_when_type_is_apparent = true:suggestion
|
||||
csharp_style_var_elsewhere = true:suggestion
|
||||
csharp_style_expression_bodied_methods = when_on_single_line:suggestion
|
||||
csharp_style_expression_bodied_properties = true:suggestion
|
||||
csharp_prefer_simple_default_expression = true:suggestion
|
||||
csharp_style_pattern_local_over_anonymous_function = true:suggestion
|
||||
@@ -0,0 +1,30 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master, refactor/*]
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: Restore
|
||||
run: dotnet restore DSP_Mods.sln
|
||||
|
||||
- name: Build Release
|
||||
run: dotnet build DSP_Mods.sln -c Release --no-restore
|
||||
|
||||
- name: Package main mods
|
||||
run: |
|
||||
dotnet build UXAssist/UXAssist.csproj -t:ZipMod -c Release --no-restore
|
||||
dotnet build CheatEnabler/CheatEnabler.csproj -t:ZipMod -c Release --no-restore
|
||||
dotnet build UniverseGenTweaks/UniverseGenTweaks.csproj -t:ZipMod -c Release --no-restore
|
||||
+17
@@ -4,9 +4,14 @@
|
||||
# Rider project files
|
||||
/.idea/
|
||||
|
||||
# VS Code project files
|
||||
/.vscode/
|
||||
|
||||
# C# generated folders
|
||||
bin/
|
||||
obj/
|
||||
*.dll
|
||||
!/AssemblyFromGame/*.dll
|
||||
|
||||
# C++ build folders
|
||||
build/
|
||||
@@ -15,3 +20,15 @@ build/
|
||||
/*/package/*.zip
|
||||
/*/package/patchers/
|
||||
/*/package/plugins/
|
||||
|
||||
# Agent files
|
||||
/.omo/
|
||||
/.worktrees/
|
||||
/.pi*/
|
||||
/.opencode/
|
||||
/.playwright*/
|
||||
/.codegraph/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -0,0 +1,86 @@
|
||||
# Agent Guidelines
|
||||
|
||||
## Rules
|
||||
|
||||
- Keep `AGENTS.md` concise: record important project standards, recurring pitfalls, and short durable architecture references. Add guidance only when useful for future work; omit details that can be read directly from code.
|
||||
- Keep investigation evidence, work history, completed plans, and implementation snapshots out of `AGENTS.md`. If work history needs to be retained, put it in a separate document and add only a brief link here.
|
||||
- Changelogs describe only user-visible changes relative to the previous release. Group changes by feature; omit implementation details, validation history, and fixes to defects introduced and corrected within the same version. Consolidate unreleased work into the feature's final behavior instead of listing its development iterations.
|
||||
- Unless the user explicitly requests a version bump, add changelog notes only to the latest existing version and do not change version numbers.
|
||||
- Write code comments and non-localized documentation in English. Keep English and Chinese sections of bilingual READMEs and changelogs synchronized; update README feature and usage descriptions when release changes affect them.
|
||||
- Inspect the original DSP game DLL, never the stripped publicized copy in `AssemblyFromGame/`, when method bodies are required. Locate DSP using the Steam registry and `steamapps/libraryfolders.vdf` as `UpdateGameDlls.ps1` does, then decompile `<game_root>/DSPGAME_Data/Managed/Assembly-CSharp.dll`.
|
||||
- Resolve in-game terminology from `<game_root>/Locale/`: `Names` contains keys, `1033` is English, and `2052` is Simplified Chinese.
|
||||
|
||||
## Project
|
||||
|
||||
- This repository contains independent BepInEx 5.x C# mods for Dyson Sphere Program. HarmonyLib patches game methods at runtime; `UXAssist` (User eXperience Assistant) is the shared library used directly by `CheatEnabler` and `UniverseGenTweaks`.
|
||||
- Projects target `net472` or `netstandard2.1` with SDK-style `.csproj` files. Compile-time game references live in `AssemblyFromGame/`.
|
||||
- `DustbinPreloader` and `LabOptPreloader` are Mono.Cecil preloaders; their main mods consume the injected fields without reflection.
|
||||
- LiveStreamAssist: [WebSocket architecture, transport migration, and validation](LiveStreamAssist/docs/WebSocketDesign.md). Overlay JS client: [LiveStreamAssist/js/README.md](LiveStreamAssist/js/README.md).
|
||||
- LiveStreamAssist JS clients keep `Client` as the JSON-RPC transport, `GameQuery` as the overlay data layer, and `GameText`/`GameIcons` offline from generated locale/proto dictionaries and extracted game icons. Do not have the offline layers call the WebSocket API. Edit `js/src/` and rebuild the bundle with `python LiveStreamAssist/js/scripts/pack_js.py`; refresh `js/generated/dsp-text.js` and `js/generated/dsp-icons.js` with `python LiveStreamAssist/js/scripts/generate_text.py` and `generate_icons.py` from a local DSP install. Run the JS and Python checks documented in `LiveStreamAssist/js/README.md`.
|
||||
|
||||
## Build
|
||||
|
||||
- `Directory.Build.props` supplies common frameworks, BepInEx packages, game references, warning policy, and the `UpdateGameDlls` dependency. `Directory.Build.targets` defines `ZipMod` and `CopyToParentPackage`. Exclude nested test-tool `bin` and `obj` artifacts from parent-mod item globs, including explicit `None` includes, while keeping test sources visible.
|
||||
- Normal validation: `dotnet build <project>/<project>.csproj -c Release --no-restore`. If NuGet assets are missing, run `dotnet restore <project>/<project>.csproj` before retrying the build.
|
||||
- Keep temporary verification projects under the mod's excluded root `obj/` directory. Remove abandoned generated outputs when their source project is gone so the SDK source glob cannot compile them into the mod.
|
||||
- Refresh game references explicitly with `dotnet build UpdateGameDlls/UpdateGameDlls.csproj`; the script publicizes installed DLLs in staging and compares generated content hashes so checkout timestamps cannot hide game updates. Missing DSP or the publicizer is a warning, not a build failure. If `assembly-publicizer` requires an unavailable .NET runtime, retry with process-local `DOTNET_ROLL_FORWARD=Major` rather than changing global runtime settings. Verify discovery warnings against the actual configured library directories and original managed DLLs; absence from the VDF `apps` list alone does not establish that DSP is uninstalled.
|
||||
- Package main mods with `dotnet build -t:ZipMod -c Release`; package preloaders with `dotnet build -t:CopyToParentPackage -c Release`. The mod `.csproj` `<Version>` is the single version source and packaging synchronizes `package/manifest.json`. Keep the latest English and Chinese changelog headings and notes aligned with `<Version>`; preserve existing unreleased notes and historical entries. Describe relevant triggers when documenting fixes to previously released behavior.
|
||||
- Treat warnings as errors except the intentional obsolete API warning `0618`; do not weaken this policy to hide new warnings.
|
||||
- Export Thunderstore package icons as 256x256 PNG files and verify their format and dimensions. For circular exports, apply an antialiased alpha mask to the approved artwork instead of regenerating it; preserve RGB pixels and make the exterior fully transparent. Convey the mod's function through familiar, conventionally oriented symbols rather than lettering. Preserve DSP motifs and consistent materials across related mod icons. During localized edits, preserve all unrequested geometry, placement and styling from the chosen reference; do not redesign surrounding structures to produce an overlap. Use clear foreground occlusion for intersecting forms without losing the main symbol's silhouette, and check contrast in 64x64 and 32x32 side-by-side previews. Keep unselected icon candidates under `artifacts/`, outside release package directories.
|
||||
|
||||
## 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 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.
|
||||
- Custom critical-warning text must participate in both `WarningSystem.hasCriticalWarning` and `WarningSystem.UpdateCriticalWarningText`; preserve native warnings and use one shared display priority.
|
||||
- `ModFeatureRegistry` discovers dependent-mod features during `Awake`; feature initialization is eager, while UXAssist alone drives the deferred start, input, update, and uninitialization lifecycle. Keep dispatchers internal and idempotent.
|
||||
- Apply config-controlled patches from their owning feature's `Start` and `SettingChanged` handlers. Shared lifecycle helpers must only manage always-on patches and must not override saved option states.
|
||||
- Proto-dependent features must tolerate calls before preload completes and retry via `UXAssist.Common.GameLogic.OnDataLoaded`. Mark changes applied only after capturing valid originals and successfully mutating the proto.
|
||||
- Architect-mode virtual stock applies only to player inventory and construction previews, including logistics bots, drones, and vessels. Keep cached package statistics consistent for inlined getters, preserve physical capacity and native ref/out contracts, and restore native statistics on disable.
|
||||
- Dispatch UXAssist shortcuts from the postfix of `VFInput.OnUpdate`, after DSP refreshes modifier and UI state. Keep typing/menu guards and per-frame registry guards; do not poll from an independent `Update()` or logic-tick callback.
|
||||
- Register localization keys through each project registration class and use `.Translate()` with keys. Do not add Chinese literals at call sites.
|
||||
- Prefer `UXAssist/Common/GameConstants` for item, tech, logistics, and Dyson sphere constants instead of inline literals.
|
||||
- Persist mod data through `IModCanSave` from DSPModSave.
|
||||
- Use `ModCompatHelper` for external plugin/type/member resolution and preserve legacy public type identities when refactoring reflection targets. Use `DysonSphereReflection` for DSPOptimizations-compatible Dyson sphere fields.
|
||||
- Use `nameof` for members exposed by the publicized compile-time game assemblies, even when the corresponding methods are private in the original game DLL; use string member names only when the publicized reference truly omits them.
|
||||
- Performance-sensitive Harmony transpilers must include the standard target/fallback header and use `TranspilerGuard` when a matcher can fail; returning original instructions is the fallback. Match named enum members and semantic calls or fields instead of hard-coded enum values or local-variable slots. Validate injected stack operand types and branch destinations, not just successful matching.
|
||||
- `PatchImpl<T>.Enable(true)` must remain fail-soft: log, unpatch, and leave the patch unset if Harmony application fails so config delegate chains remain consistent.
|
||||
- Overlay UI state must converge from actual game state on periodic updates, not depend only on one-shot event or patch callbacks. Treat replacement of a planet transport as a lifecycle boundary and clear its dependent overlays once. Station IDs are reusable indices, and a stable planet ID or factory reference does not imply stable transport ownership. Cloned controls must reset runtime state while retaining source styles; use `UXAssist.UI.Util.GetPreferredWidth` for dynamic text and `ResetButton` for cloned buttons. Preserve the source tip settings when resetting cloned help buttons so the game's native tips work; do not replace them with separate dialogs. Shared button sizing must use anchor-relative child positions so text and icons remain aligned after a button pivot changes.
|
||||
- Bulk planet resets must unregister entity markers through `DigitalSystem.RemoveMarkerComponent` before replacing entity pools or the digital system; `GalacticDigitalSystem` retains shared marker references across planets.
|
||||
- Logistics station overlays must refresh through the native UI lifecycle, independently of typing guards. Reconcile cached tips against live station/entity identities and recycle local tips when stations are removed.
|
||||
- Planet vein utilization counters belong before resource labels, not beside native icons or highlight controls. Keep resource labels in their native layout and preserve the counters' row-based vertical position when rows are reused.
|
||||
- UI-only options must preserve native progression, statistics, and event delivery. Suppress presentation handlers rather than bypassing authoritative game-state setters.
|
||||
- Expanded terraform brushes must raise both the input-size limit and the operation-local clamps in `PrepareFlattenPoints` and `PrepareRestorePoints`, with buffers sized before either preparation path runs.
|
||||
- Space-scene rendering suppression must require the native in-game hide-UI state and exclude menu demos and combat cutscenes. A hidden player model alone does not imply hidden scenery; use the same eligibility check for drawing and planet-simulator visibility.
|
||||
- LiveStreamAssist browser overlays must use single-flight polling and discard stale work after connection changes. Compound queries must reject mixed session IDs; cache only positive production indices so newly tracked items remain discoverable.
|
||||
- LiveStreamAssist production reads must schedule the native extra-info calculator for queried factories independently of the statistics UI. Deduplicate and throttle refreshes, let active native batches finish, and clear pending factory indices and deadlines at session boundaries.
|
||||
- LiveStreamAssist `ReflectionReader` caches bounded per-type member metadata and clears it during API uninitialization; do not cache mutable game values or arbitrary request results.
|
||||
|
||||
## Automation Architecture
|
||||
|
||||
### Auto-construct
|
||||
|
||||
- `AutoConstructEnabled` controls patch activation; `AutoConstructButtonEnabled` controls only button visibility. Never couple them.
|
||||
- Keep planning bounded and allocation-free. Follow native construction eligibility and planet-local surface movement semantics.
|
||||
- The planner owns only its generated `MoveTo` orders. Clear an active auto order before resetting planner state on disable or planet changes, without clearing user orders. Recovery detours must return control to the construction route.
|
||||
- Keep obstacle recovery at the current flight altitude. Validate lateral detour and escape waypoints against physics before issuing them, and retain recovery state to retry broader routes instead of treating an exhausted candidate list as success.
|
||||
- Let native flight control settle altitude after construction arrival; do not force a target altitude from auto-construct. The native non-gas flight baseline is 15f, while gas planets use a different lower bound.
|
||||
|
||||
### Auto-cruise
|
||||
|
||||
- `PlayerPatch.AutoNavigation` is the only auto-cruise implementation. Its Harmony patches follow `AutoCruiseEnabled`; use auto-cruise terminology in user-facing text rather than the game's native autopilot terminology. Keep persistent status and the current configured shortcut on the auto-cruise button, without a separate HUD label; fix its left edge so adaptive width grows rightward without overlapping the auto-construct button.
|
||||
- Use one navigation lifecycle path for target state and reusable obstacle data. Require a resolvable target, yield to `player.navigation.navigating`, and reject an active native autopilot before reporting that auto-cruise started.
|
||||
- Preserve native movement and braking conventions; manual warp input takes precedence.
|
||||
- Use `MySideSlider` consistently for auto-cruise numeric settings. Align slider starts to the widest localized row label and size tracks so their value labels sit nearby. Keep each slider and its value label on a shared vertical center with explicit anchors and pivots, without additional row offsets.
|
||||
|
||||
## Review Standard
|
||||
|
||||
- Fix root causes with minimal focused changes. Do not alter unrelated behavior, add copyright headers, commit changes, push branches, or create branches unless requested. Stage and commit only explicitly named task-related files, leaving unrelated working-tree changes untouched. Use normal pushes; do not rewrite remote history unless explicitly requested.
|
||||
- Before handoff, run the narrowest relevant build or test, then `git diff --check`. Mention unrelated pre-existing failures instead of changing them.
|
||||
- For game updates, also check Harmony target resolution and affected IL patterns against the original game DLL; compilation alone does not validate runtime patches.
|
||||
Binary file not shown.
Binary file not shown.
@@ -3,6 +3,44 @@
|
||||
|
||||
## Changlog
|
||||
|
||||
* 2.4.7
|
||||
* Extend `Unlock Tech with Key-Modifiers` with a downgrade mode.
|
||||
* Press `Caps Lock` to toggle downgrade mode. Modifier clicks lower tech levels and revert their bonuses and dependent tech levels; `Alt` returns the tech to locked.
|
||||
* The current mode is shown by a popup and warning banner. A help button in the tech tree explains the key combinations.
|
||||
* 2.4.6
|
||||
* `Architect mode`: Restore unlimited use of buildings, Logistics Bots, Logistics Drones, and Logistics Vessels, and increase the default displayed count from 100 to 999.
|
||||
* `Wind Turbines do global power coverage`: Fix a possible startup crash when enabled.
|
||||
* 2.4.5
|
||||
* Support Dyson Sphere Program 0.10.35.29057.
|
||||
* Update `Terraform anyway` for the separate foundation and Restore Terrain workflows. Preserve soil gains and prevent negative soil balances when resources are insufficient.
|
||||
* New button `Generate illegal dyson shells for all layers without nodes and shells`, which is used to extend dyson layers.
|
||||
* You must enable `IllegalDysonShellFunctionsEnabled` of `DysonSphere` section in config to see it.
|
||||
* `Finish build immediately`: Fix a crash when pasting a blueprint containing the first Planetary Shield Generator on a planet.
|
||||
* 2.4.4
|
||||
* `Finish build immediately`: Fix a possible crash.
|
||||
* 2.4.3
|
||||
* `Duplicate shells from that with highest production`: Fix crash on using with frameless shells.
|
||||
* `Keep max production shells and remove others`: Fix wrong behaviour when left count > 1.
|
||||
* `Quick absorb`: Fix ant issue that it is not working while `Skip absorption period` is enabled.
|
||||
* `Finish build immediately`: Fixed an issue where prebuilt buildings were not constructed immediately when the building quantity became sufficient.
|
||||
* New option for `Belt signal item generation`: `Use proliferators for raws/intermediates and finished products`
|
||||
* Following items use extra products: `Titanium Alloy`, `Prism`, `Frame Material`, `Proliferator Mk.II`, `Proliferator Mk.III`, `Magnetic Coil`, `Electric Motor`, `Electromagnetic Turbine`, `Super-magnetic Ring`, `Circuit Board`, `Thruster`, `Reinforced Thruster`, `Plasma Exciter`, `Particle Broadband`, `Graviton Lens`, `Quantum Chip`, `Annihilation Constraint Sphere`, `Deuteron Fuel Rod`, `Space Warper`, `Dyson Sphere Component`, `Small Carrier Rocket`, `Electromagnetic Matrix`, `Structure Matrix`, `Information Matrix`, `Gravity Matrix`, `Universe Matrix`
|
||||
* Following items does not use proliferators: `Casimir Crystal`, `Energy Matrix`
|
||||
* Other items use speed up production.
|
||||
* Fix some other minor bugs found by LLM AI.
|
||||
* 2.4.2
|
||||
* Fix critical bugs:
|
||||
* Dyson Power is not updated actively when `Skip bullet period` or `Skip absorption period` is enabled and no rocket is in fire.
|
||||
* Dyson Power is not updated actively on clicking `Complete Dyson Sphere Shells instantly` or `Remove all frames on Dyson Sphere`.
|
||||
* 2.4.1
|
||||
* New feature: `Remove all frames on Dyson Sphere`
|
||||
* Can save rockets with very little power generation impact.
|
||||
* Will keep nodes and shells and does not affect solar sails' absorption.
|
||||
* `Terraform without enough soil piles`: Working for blueprint paste and burying Dark Fog Core Driller now.
|
||||
* `Belt signal item generation`: Fix mod compatibility by resolving recursive recipes.
|
||||
* 2.4.0
|
||||
* Support game version 0.10.33
|
||||
* `Generate illegal dyson shell`: This function is open to all users now, enabling certain config entry is not needed any more.
|
||||
* 2.3.32
|
||||
* `Complete Dyson Sphere Shells instantly`: Fix a crash.
|
||||
* 2.3.31
|
||||
@@ -162,6 +200,44 @@
|
||||
|
||||
## 更新日志
|
||||
|
||||
* 2.4.7
|
||||
* `使用组合键点击解锁科技` 新增降级模式。
|
||||
* 按 `Caps Lock` 切换降级模式。按住组合键点击可降低科技等级,同时回退升级效果及后继科技等级;`Alt` 将科技回退到未解锁。
|
||||
* 弹窗和警告横幅显示当前模式,科技树中的帮助按钮提供组合键说明。
|
||||
* 2.4.6
|
||||
* `建筑师模式`:修复建筑、配送运输机、物流运输机和星际物流运输船无法无限使用的问题,默认显示数量由 100 提高至 999。
|
||||
* `风力涡轮机供电覆盖全球`:修复启用后可能导致启动崩溃的问题。
|
||||
* 2.4.5
|
||||
* 支持戴森球计划 0.10.35.29057。
|
||||
* 更新`强行改造地形`以适配独立地基和恢复地形的工作流程。在资源不足时保留沙土收益并防止负沙土平衡。
|
||||
* 新按钮 `为所有没有节点和壳的层级生成仙术戴森壳`,用于扩展新戴森壳层面的时候。
|
||||
* 你必须在设置文件里开启`DysonSphere`分类的`IllegalDysonShellFunctionsEnabled`才能看到它。
|
||||
* `立即完成建造`:修复在行星上粘贴包含首座行星护盾发生器的蓝图时可能崩溃的问题。
|
||||
* 2.4.4
|
||||
* `立即完成建造`: 修复一个可能的崩溃问题。
|
||||
* 2.4.3
|
||||
* `从发电量最高的壳复制戴森壳`:修复在无框壳体时可能崩溃的问题。
|
||||
* `保留发电量最高的戴森壳并移除其他戴森壳`:修复当剩余壳体数量大于1时的异常行为。
|
||||
* `快速吸收`:修复开启`跳过吸收阶段`时不生效的问题。
|
||||
* `立即完成建造`:修复建筑数量补足时,之前预建造状态的建筑未能立即完成的问题。
|
||||
* `传送带信号物品生成`新增选项:`原料/中间品和成品使用增产剂`
|
||||
* 以下物品会使用额外产出:`钛合金`、`棱镜`、`框架材料`、`增产剂 Mk.II`、`增产剂 Mk.III`、`磁线圈`、`电动机`、`电磁涡轮`、`超级磁场环`、`电路板`、`推进器`、`加力推进器`、`电浆激发器`、`粒子宽带`、`引力透镜`、`量子芯片`、`湮灭约束球`、`氘燃料棒`、`空间翘曲器`、`戴森球组件`、`小型运载火箭`、`电磁矩阵`、`结构矩阵`、`信息矩阵`、`引力矩阵`、`宇宙矩阵`
|
||||
* 以下物品不使用增产剂:`卡西米尔晶体`、`能量矩阵`
|
||||
* 其他物品使用加速生产
|
||||
* 修复一些由 LLM AI 发现的其他小问题。
|
||||
* 2.4.2
|
||||
* 修复了严重的系列BUG:
|
||||
* 在启用`跳过子弹阶段`或`跳过吸收阶段`并且没有火箭发射时,戴森球的发电量未实时更新
|
||||
* 点击`立即完成戴森壳建造`或`移除戴森球上的所有框架`时,戴森球的发电量未实时更新
|
||||
* 2.4.1
|
||||
* 新增功能:`移除戴森球上的所有框架`
|
||||
* 可以节省火箭,且几乎不影响发电效率
|
||||
* 会保留节点和壳面,不影响太阳帆的吸收
|
||||
* `沙土不够时依然可以整改地形`:现在支持蓝图粘贴和掩埋黑雾核心钻机
|
||||
* `传送带信号物品生成`:修复对递归配方的支持,兼容一些mod
|
||||
* 2.4.0
|
||||
* 支持游戏版本 0.10.33
|
||||
* `生成仙术戴森壳`:此功能现在对所有用户开放,不再需要启用特定的配置项。
|
||||
* 2.3.32
|
||||
* `立即完成戴森壳建造`:修复了一个崩溃问题
|
||||
* 2.3.31
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Reflection;
|
||||
using BepInEx;
|
||||
using BepInEx.Configuration;
|
||||
using CheatEnabler.Patches;
|
||||
using HarmonyLib;
|
||||
using CheatEnabler.Patches.Factory;
|
||||
using FactoryPatch = CheatEnabler.Patches.Factory.FactoryPatch;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
|
||||
namespace CheatEnabler;
|
||||
|
||||
@@ -16,11 +18,14 @@ public class CheatEnabler : BaseUnityPlugin
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
I18N.Init();
|
||||
|
||||
GamePatch.DevShortcutsEnabled = Config.Bind("General", "DevShortcuts", false, "Enable DevMode shortcuts");
|
||||
GamePatch.AbnormalDisablerEnabled = Config.Bind("General", "DisableAbnormalChecks", false,
|
||||
"disable all abnormal checks");
|
||||
GamePatch.UnlockTechEnabled = Config.Bind("General", "UnlockTech", false,
|
||||
"Unlock clicked tech by holding key-modifilers(Shift/Alt/Ctrl)");
|
||||
TechTweaksPatch.Enabled = Config.Bind("General", "UnlockTech", false,
|
||||
"Upgrade clicked tech by holding key modifiers (Shift/Alt/Ctrl), and downgrade it by holding the " +
|
||||
"same modifiers while downgrade mode is on (toggle it with Caps Lock)");
|
||||
FactoryPatch.ImmediateEnabled = Config.Bind("Build", "ImmediateBuild", false,
|
||||
"Build immediately");
|
||||
FactoryPatch.ArchitectModeEnabled = Config.Bind("Build", "Architect", false,
|
||||
@@ -39,6 +44,8 @@ public class CheatEnabler : BaseUnityPlugin
|
||||
"Belt signal count removals as comsumption in statistics");
|
||||
FactoryPatch.BeltSignalCountRecipeEnabled = Config.Bind("Build", "BeltSignalCountRecipe", false,
|
||||
"Belt signal count all raws and intermediates in statistics");
|
||||
FactoryPatch.BeltSignalUseProliferatorEnabled = Config.Bind("Build", "BeltSignalUseProliferator", false,
|
||||
"Belt signal count proliferators used for raws/intermediates and finished products");
|
||||
FactoryPatch.RemovePowerSpaceLimitEnabled = Config.Bind("Build", "RemovePowerDistanceLimit", false,
|
||||
"Remove distance limit for wind turbines and geothermals");
|
||||
FactoryPatch.BoostWindPowerEnabled = Config.Bind("Build", "BoostWindPower", false,
|
||||
@@ -51,8 +58,6 @@ public class CheatEnabler : BaseUnityPlugin
|
||||
"Boost geothermal power");
|
||||
FactoryPatch.WindTurbinesPowerGlobalCoverageEnabled = Config.Bind("Build", "PowerGlobalCoverage", false,
|
||||
"Global power coverage");
|
||||
FactoryPatch.GreaterPowerUsageInLogisticsEnabled = Config.Bind("Build", "GreaterPowerUsageInLogistics", false,
|
||||
"Increase maximum power usage in Logistic Stations and Advanced Mining Machines");
|
||||
FactoryPatch.ControlPanelRemoteLogisticsEnabled = Config.Bind("Build", "ControlPanelRemoteLogistics", false,
|
||||
"Retrieve/Place items from/to remote planets on logistics control panel");
|
||||
ResourcePatch.InfiniteResourceEnabled = Config.Bind("Planet", "AlwaysInfiniteResource", false,
|
||||
@@ -90,32 +95,19 @@ public class CheatEnabler : BaseUnityPlugin
|
||||
Functions.DysonSphereFunctions.IllegalDysonShellFunctionsEnabled = Config.Bind("DysonSphere", "IllegalDysonShellFunctions", false,
|
||||
"Enable illegal dyson shell functions");
|
||||
Functions.DysonSphereFunctions.ShellsCountForFunctions = Config.Bind("DysonSphere", "ShellsCountForFunctions", 2048,
|
||||
"Shells count for various functions");
|
||||
new ConfigDescription("Shells count for various functions", new AcceptableValueRange<int>(
|
||||
Functions.DysonSphereFunctions.MinShellsCountForFunctions,
|
||||
Functions.DysonSphereFunctions.MaxShellsCountForFunctions)));
|
||||
CombatPatch.MechaInvincibleEnabled = Config.Bind("Battle", "MechaInvincible", false,
|
||||
"Mecha and Drones/Fleets invincible");
|
||||
CombatPatch.BuildingsInvincibleEnabled = Config.Bind("Battle", "BuildingsInvincible", false,
|
||||
"Buildings invincible");
|
||||
Localization.Register();
|
||||
UIConfigWindow.Init();
|
||||
_patches = Util.GetTypesFiltered(Assembly.GetExecutingAssembly(),
|
||||
t => string.Equals(t.Namespace, "CheatEnabler.Patches", StringComparison.Ordinal) || string.Equals(t.Namespace, "CheatEnabler.Functions", StringComparison.Ordinal));
|
||||
_patches?.Do(type => type.GetMethod("Init")?.Invoke(null, null));
|
||||
}
|
||||
// Register features (Init runs eagerly here); UXAssist drives the deferred lifecycle and starts
|
||||
// this feature set immediately if its lifecycle has already begun.
|
||||
ModFeatureRegistry.Discover(Assembly.GetExecutingAssembly());
|
||||
|
||||
private Type[] _patches;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
_patches?.Do(type => type.GetMethod("Start")?.Invoke(null, null));
|
||||
I18N.Apply();
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
_patches?.Do(type => type.GetMethod("Uninit")?.Invoke(null, null));
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (VFInput.inputing) return;
|
||||
FactoryPatch.OnInputUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,45 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net472</TargetFramework>
|
||||
<BepInExPluginGuid>org.soardev.cheatenabler</BepInExPluginGuid>
|
||||
<Description>DSP MOD - CheatEnabler</Description>
|
||||
<Version>2.3.32</Version>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Version>2.4.7</Version>
|
||||
<PackageId>CheatEnabler</PackageId>
|
||||
<RootNamespace>CheatEnabler</RootNamespace>
|
||||
<RestoreAdditionalProjectSources>https://nuget.bepinex.dev/v3/index.json</RestoreAdditionalProjectSources>
|
||||
<PackHasChangelog>true</PackHasChangelog>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BepInEx.Core" Version="5.*" />
|
||||
<PackageReference Include="BepInEx.PluginInfoProps" Version="1.*" />
|
||||
<PackageReference Include="DysonSphereProgram.GameLibs" Version="0.10.32.*-r.*" />
|
||||
<PackageReference Include="UnityEngine.Modules" Version="2018.4.12" IncludeAssets="compile" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework.TrimEnd(`0123456789`))' == 'net'">
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
<ItemGroup>
|
||||
<Reference Include="Assembly-CSharp">
|
||||
<HintPath>..\AssemblyFromGame\Assembly-CSharp.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="UnityEngine.UI">
|
||||
<HintPath>..\AssemblyFromGame\UnityEngine.UI.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
-->
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\UXAssist\UXAssist.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Release'">
|
||||
<Exec Command="del /F /Q package\$(ProjectName)-$(Version).zip
powershell Compress-Archive -Force -DestinationPath 'package/$(ProjectName)-$(Version).zip' -Path '$(TargetPath)', package/icon.png, package/manifest.json, README.md, CHANGELOG.md" />
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using CheatEnabler;
|
||||
|
||||
namespace CheatEnabler.Functions.DysonSphere;
|
||||
|
||||
[ModFeature("DysonSphereResolver")]
|
||||
public static class DysonSphereResolver
|
||||
{
|
||||
public static (global::DysonSphere sphere, StarData star)? ResolveCurrent()
|
||||
{
|
||||
var star = GameMain.localStar;
|
||||
if (star == null) return null;
|
||||
var sphere = GameMain.data.dysonSpheres[star.index];
|
||||
if (sphere == null) return null;
|
||||
return (sphere, star);
|
||||
}
|
||||
|
||||
public static StarData ResolveEditorOrLocalStar()
|
||||
{
|
||||
var dysonEditor = UIRoot.instance?.uiGame?.dysonEditor;
|
||||
if (dysonEditor != null && dysonEditor.gameObject.activeSelf)
|
||||
{
|
||||
return dysonEditor.selection.viewStar;
|
||||
}
|
||||
var star = GameMain.localStar;
|
||||
if (star == null)
|
||||
{
|
||||
UIMessageBox.Show(Localization.CheatEnabler.Translate(), Localization.YouAreNotInAnySystem.Translate(), Localization.OK.Translate(), UIMessageBox.ERROR, null);
|
||||
}
|
||||
return star;
|
||||
}
|
||||
|
||||
public static (global::DysonSphere sphere, StarData star)? ResolveEditorOrLocalSphere(bool requireLayer = true)
|
||||
{
|
||||
var star = ResolveEditorOrLocalStar();
|
||||
if (star == null) return null;
|
||||
var sphere = GameMain.data?.dysonSpheres[star.index];
|
||||
if (sphere == null)
|
||||
{
|
||||
UIMessageBox.Show(Localization.CheatEnabler.Translate(), string.Format(Localization.ThereIsNoDysonSphereDataOn0.Translate(), star.displayName), Localization.OK.Translate(), UIMessageBox.ERROR, null);
|
||||
return null;
|
||||
}
|
||||
if (requireLayer && sphere.layerCount == 0)
|
||||
{
|
||||
UIMessageBox.Show(Localization.CheatEnabler.Translate(), string.Format(Localization.ThereIsNoDysonSphereShellOn0.Translate(), star.displayName), Localization.OK.Translate(), UIMessageBox.ERROR, null);
|
||||
return null;
|
||||
}
|
||||
return (sphere, star);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.GameConstants;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using UXAssist.Common.Utils;
|
||||
using CheatEnabler;
|
||||
|
||||
namespace CheatEnabler.Functions.DysonSphere;
|
||||
|
||||
[ModFeature("FrameRemovalFunctions")]
|
||||
public static class FrameRemovalFunctions
|
||||
{
|
||||
public static void RemoveAllFrames()
|
||||
{
|
||||
var resolved = DysonSphereResolver.ResolveEditorOrLocalSphere();
|
||||
if (resolved == null) return;
|
||||
var (dysonSphere, star) = resolved.Value;
|
||||
|
||||
UIMessageBox.Show(Localization.CheatEnabler.Translate(), string.Format(Localization.ThisWillRemoveAllFramesOn0AreYouSure.Translate(), star.displayName), Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () =>
|
||||
{
|
||||
foreach (var dysonSphereLayer in dysonSphere.layersIdBased)
|
||||
{
|
||||
if (dysonSphereLayer == null) continue;
|
||||
for (var i = dysonSphereLayer.nodeCursor - 1; i >= 0; i--)
|
||||
{
|
||||
var dysonNode = dysonSphereLayer.nodePool[i];
|
||||
if (dysonNode == null || dysonNode.id != i) continue;
|
||||
if (dysonNode.frames.Count > 0)
|
||||
dysonNode.frames.Clear();
|
||||
dysonNode.RecalcSpReq();
|
||||
}
|
||||
for (var i = dysonSphereLayer.shellCursor - 1; i >= 0; i--)
|
||||
{
|
||||
var dysonShell = dysonSphereLayer.shellPool[i];
|
||||
if (dysonShell == null || dysonShell.id != i) continue;
|
||||
if (dysonShell.frames.Count > 0)
|
||||
dysonShell.frames.Clear();
|
||||
}
|
||||
for (var i = dysonSphereLayer.frameCursor - 1; i >= 0; i--)
|
||||
{
|
||||
var dysonFrame = dysonSphereLayer.framePool[i];
|
||||
if (dysonFrame == null || dysonFrame.id != i) continue;
|
||||
dysonFrame.Free();
|
||||
dysonSphereLayer.framePool[i] = null;
|
||||
}
|
||||
dysonSphereLayer.frameCursor = 1;
|
||||
dysonSphereLayer.frameRecycleCursor = 0;
|
||||
dysonSphereLayer.SetFrameCapacity(DysonSphereConstants.DefaultLayerPoolCapacity);
|
||||
DysonSphereReflection.SetTotalFrameSP(dysonSphereLayer, 0);
|
||||
}
|
||||
dysonSphere.CheckAutoNodes();
|
||||
dysonSphere.PickAutoNode();
|
||||
dysonSphere.modelRenderer.RebuildModels();
|
||||
dysonSphere.needRecalculatePower = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,792 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using UnityEngine;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.GameConstants;
|
||||
|
||||
namespace CheatEnabler.Functions.DysonSphere;
|
||||
|
||||
public static class GeometryHelpers
|
||||
{
|
||||
const ulong rawNum0 = 0x3FED4D1BA3920BFAUL; // cosr
|
||||
const ulong rawNum1 = 0x3FD9B9832ADBFC16UL; // sinr
|
||||
const ulong rawNum2 = 0x3FE279A74590331DUL;
|
||||
const ulong rawNum3 = 0x3FEBB67AE8584CAAUL; // cos30
|
||||
private static readonly double factor0 = RawToDouble(rawNum0);
|
||||
private static readonly double factor1 = RawToDouble(rawNum1);
|
||||
private static readonly double factor2 = RawToDouble(rawNum2);
|
||||
private static readonly double factor3 = RawToDouble(rawNum3);
|
||||
public static readonly PrecalculatedTriangle[] PrecalculatedTriangles = [
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 6869, PosA = new Vector3() { x = RawToFloat(0x00000000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x45D66000U)}, PosB = new Vector3() { x = RawToFloat(0x2C88BEC4U), y = RawToFloat(0x00000000U), z = RawToFloat(0xC5D66000U)}, PosC = new Vector3() { x = RawToFloat(0xC5D66000U), y = RawToFloat(0x00000000U), z = RawToFloat(0xABB1589BU)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 13573, PosA = new Vector3() { x = RawToFloat(0x46540800U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2C87400AU)}, PosB = new Vector3() { x = RawToFloat(0x4652DEA6U), y = RawToFloat(0x00000000U), z = RawToFloat(0xC4B14E71U)}, PosC = new Vector3() { x = RawToFloat(0xC6540800U), y = RawToFloat(0x00000000U), z = RawToFloat(0xAC2F683EU)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 21257, PosA = new Vector3() { x = RawToFloat(0x46A60400U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2CD3CBAAU)}, PosB = new Vector3() { x = RawToFloat(0xC6070C9DU), y = RawToFloat(0x00000000U), z = RawToFloat(0xC697A9AEU)}, PosC = new Vector3() { x = RawToFloat(0xC6A60400U), y = RawToFloat(0x00000000U), z = RawToFloat(0xAC8956FFU)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 29718, PosA = new Vector3() { x = RawToFloat(0x469B4FBEU), y = RawToFloat(0x00000000U), z = RawToFloat(0x46AC7DAAU)}, PosB = new Vector3() { x = RawToFloat(0x46E81C00U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2D140EBCU)}, PosC = new Vector3() { x = RawToFloat(0xC6E81C00U), y = RawToFloat(0x00000000U), z = RawToFloat(0xACC0046AU)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 38834, PosA = new Vector3() { x = RawToFloat(0x4717AE00U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2D4181A3U)}, PosB = new Vector3() { x = RawToFloat(0x45FC49B0U), y = RawToFloat(0x00000000U), z = RawToFloat(0xC7145D79U)}, PosC = new Vector3() { x = RawToFloat(0xC717AE00U), y = RawToFloat(0x00000000U), z = RawToFloat(0xACFAF5D4U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 48523, PosA = new Vector3() { x = RawToFloat(0x473D8800U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2D71CBB9U)}, PosB = new Vector3() { x = RawToFloat(0xC73D8800U), y = RawToFloat(0x00000000U), z = RawToFloat(0xAD1CCB2AU)}, PosC = new Vector3() { x = RawToFloat(0xC72D2539U), y = RawToFloat(0x00000000U), z = RawToFloat(0x469A2DB9U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 58724, PosA = new Vector3() { x = RawToFloat(0x47656000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2D925038U)}, PosB = new Vector3() { x = RawToFloat(0xC7656000U), y = RawToFloat(0x00000000U), z = RawToFloat(0xAD3DC153U)}, PosC = new Vector3() { x = RawToFloat(0xC7518B63U), y = RawToFloat(0x00000000U), z = RawToFloat(0x46BA9727U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 69389, PosA = new Vector3() { x = RawToFloat(0x47878200U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2DACE001U)}, PosB = new Vector3() { x = RawToFloat(0xC7878200U), y = RawToFloat(0x00000000U), z = RawToFloat(0xAD603407U)}, PosC = new Vector3() { x = RawToFloat(0xC7078200U), y = RawToFloat(0x00000000U), z = RawToFloat(0x476AB4D7U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 80481, PosA = new Vector3() { x = RawToFloat(0x479D3000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2DC88874U)}, PosB = new Vector3() { x = RawToFloat(0xC79D3000U), y = RawToFloat(0x00000000U), z = RawToFloat(0xAD82095EU)}, PosC = new Vector3() { x = RawToFloat(0xC71D3000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x478820DDU)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 91970, PosA = new Vector3() { x = RawToFloat(0x47B2A01EU), y = RawToFloat(0x00000000U), z = RawToFloat(0x461631C0U)}, PosB = new Vector3() { x = RawToFloat(0x47B39C00U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2DE5234DU)}, PosC = new Vector3() { x = RawToFloat(0xC7B39C00U), y = RawToFloat(0x00000000U), z = RawToFloat(0xAD9495E6U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 103831, PosA = new Vector3() { x = RawToFloat(0x476E65BEU), y = RawToFloat(0x00000000U), z = RawToFloat(0x47A4101EU)}, PosB = new Vector3() { x = RawToFloat(0x47CACB00U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2E015B75U)}, PosC = new Vector3() { x = RawToFloat(0xC7CACB00U), y = RawToFloat(0x00000000U), z = RawToFloat(0xADA7C3C0U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 116040, PosA = new Vector3() { x = RawToFloat(0x47E29F00U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2E108E84U)}, PosB = new Vector3() { x = RawToFloat(0xC7E29F00U), y = RawToFloat(0x00000000U), z = RawToFloat(0xADBB7A19U)}, PosC = new Vector3() { x = RawToFloat(0xC70C0F3EU), y = RawToFloat(0x00000000U), z = RawToFloat(0x47D7878CU)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 128580, PosA = new Vector3() { x = RawToFloat(0x00000000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x47FB1D00U)}, PosB = new Vector3() { x = RawToFloat(0x47A80710U), y = RawToFloat(0x00000000U), z = RawToFloat(0x47BA9D10U)}, PosC = new Vector3() { x = RawToFloat(0x2EA02E04U), y = RawToFloat(0x00000000U), z = RawToFloat(0xC7FB1D00U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 141433, PosA = new Vector3() { x = RawToFloat(0x00000000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x480A1D80U)}, PosB = new Vector3() { x = RawToFloat(0x47A25D3CU), y = RawToFloat(0x00000000U), z = RawToFloat(0x47DF79A3U)}, PosC = new Vector3() { x = RawToFloat(0x2EB03393U), y = RawToFloat(0x00000000U), z = RawToFloat(0xC80A1D80U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 154586, PosA = new Vector3() { x = RawToFloat(0x00000000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x4816F500U)}, PosB = new Vector3() { x = RawToFloat(0x47B175ECU), y = RawToFloat(0x00000000U), z = RawToFloat(0x47F440EDU)}, PosC = new Vector3() { x = RawToFloat(0x2EC0959FU), y = RawToFloat(0x00000000U), z = RawToFloat(0xC816F500U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 168025, PosA = new Vector3() { x = RawToFloat(0x00000000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x48241500U)}, PosB = new Vector3() { x = RawToFloat(0x48241500U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2E51542AU)}, PosC = new Vector3() { x = RawToFloat(0xC8241500U), y = RawToFloat(0x00000000U), z = RawToFloat(0xAE07BD7FU)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 181738, PosA = new Vector3() { x = RawToFloat(0x00000000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x48317880U)}, PosB = new Vector3() { x = RawToFloat(0x48317880U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2E6268D3U)}, PosC = new Vector3() { x = RawToFloat(0xC8317880U), y = RawToFloat(0x00000000U), z = RawToFloat(0xAE12D0F8U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 195715, PosA = new Vector3() { x = RawToFloat(0x469FD288U), y = RawToFloat(0x00000000U), z = RawToFloat(0x483E1379U)}, PosB = new Vector3() { x = RawToFloat(0x483F1F80U), y = RawToFloat(0x00000000U), z = RawToFloat(0x2E73D398U)}, PosC = new Vector3() { x = RawToFloat(0xC83F1F80U), y = RawToFloat(0x00000000U), z = RawToFloat(0xAE1E1C47U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 209946, PosA = new Vector3() { x = RawToFloat(0x00000000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x484D0500U)}, PosB = new Vector3() { x = RawToFloat(0x48092F52U), y = RawToFloat(0x00000000U), z = RawToFloat(0x48185BF5U)}, PosC = new Vector3() { x = RawToFloat(0x2F02C70CU), y = RawToFloat(0x00000000U), z = RawToFloat(0xC84D0500U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 224422, PosA = new Vector3() { x = RawToFloat(0x00000000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x485B2900U)}, PosB = new Vector3() { x = RawToFloat(0x4812A593U), y = RawToFloat(0x00000000U), z = RawToFloat(0x4822DE24U)}, PosC = new Vector3() { x = RawToFloat(0x2F0BCC2BU), y = RawToFloat(0x00000000U), z = RawToFloat(0xC85B2900U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = 239136, PosA = new Vector3() { x = RawToFloat(0x00000000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x48698680U)}, PosB = new Vector3() { x = RawToFloat(0x481C424DU), y = RawToFloat(0x00000000U), z = RawToFloat(0x482D8B0EU)}, PosC = new Vector3() { x = RawToFloat(0x2F14F5F7U), y = RawToFloat(0x00000000U), z = RawToFloat(0xC8698680U)} },
|
||||
new PrecalculatedTriangle() { MaxOrbitRadius = DysonSphereConstants.MaxOrbitRadius, PosA = new Vector3() { x = RawToFloat(0x00000000U), y = RawToFloat(0x00000000U), z = RawToFloat(0x48742180U)}, PosB = new Vector3() { x = RawToFloat(0x48235AFEU), y = RawToFloat(0x00000000U), z = RawToFloat(0x48356CB1U)}, PosC = new Vector3() { x = RawToFloat(0x2F1BB9CEU), y = RawToFloat(0x00000000U), z = RawToFloat(0xC8742180U)} },
|
||||
];
|
||||
|
||||
public struct PrecalculatedTriangle
|
||||
{
|
||||
public int MaxOrbitRadius;
|
||||
public Vector3 PosA;
|
||||
public Vector3 PosB;
|
||||
public Vector3 PosC;
|
||||
}
|
||||
|
||||
private static double RawToDouble(ulong value)
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
return *(double*)&value;
|
||||
}
|
||||
}
|
||||
|
||||
private static float RawToFloat(uint value)
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
return *(float*)&value;
|
||||
}
|
||||
}
|
||||
|
||||
public static DysonNode QuickAddDysonNode(this DysonSphereLayer layer, int protoId, Vector3 pos)
|
||||
{
|
||||
int nodeId;
|
||||
if (layer.nodeRecycleCursor > 0)
|
||||
{
|
||||
int[] array = layer.nodeRecycle;
|
||||
int num = layer.nodeRecycleCursor - 1;
|
||||
layer.nodeRecycleCursor = num;
|
||||
nodeId = array[num];
|
||||
}
|
||||
else
|
||||
{
|
||||
int nodePoolIndex = layer.nodeCursor;
|
||||
layer.nodeCursor = nodePoolIndex + 1;
|
||||
nodeId = nodePoolIndex;
|
||||
if (nodeId == layer.nodeCapacity)
|
||||
{
|
||||
layer.SetNodeCapacity(layer.nodeCapacity * 2);
|
||||
}
|
||||
}
|
||||
DysonNode node = null;
|
||||
if (layer.nodePool[nodeId] == null)
|
||||
{
|
||||
node = new DysonNode();
|
||||
layer.nodePool[nodeId] = node;
|
||||
}
|
||||
else
|
||||
{
|
||||
node = layer.nodePool[nodeId];
|
||||
node.SetEmpty();
|
||||
}
|
||||
node.id = nodeId;
|
||||
node.protoId = protoId;
|
||||
node.layerId = layer.id;
|
||||
node.pos = pos;
|
||||
node.reserved = false;
|
||||
node.sp = 0;
|
||||
node.spMax = DysonNode.kSpPerNode;
|
||||
layer.dysonSphere.AddDysonNodeRData(node, true);
|
||||
return node;
|
||||
}
|
||||
public static DysonFrame QuickAddDysonFrame(this DysonSphereLayer layer, int protoId, DysonNode nodeA, DysonNode nodeB, bool euler)
|
||||
{
|
||||
int newId;
|
||||
if (layer.frameRecycleCursor > 0)
|
||||
{
|
||||
var array = layer.frameRecycle;
|
||||
var index = layer.frameRecycleCursor - 1;
|
||||
layer.frameRecycleCursor = index;
|
||||
newId = array[index];
|
||||
}
|
||||
else
|
||||
{
|
||||
var index = layer.frameCursor;
|
||||
layer.frameCursor = index + 1;
|
||||
newId = index;
|
||||
if (newId == layer.frameCapacity)
|
||||
{
|
||||
layer.SetFrameCapacity(layer.frameCapacity * 2);
|
||||
}
|
||||
}
|
||||
DysonFrame frame = layer.framePool[newId];
|
||||
if (frame == null)
|
||||
{
|
||||
frame = new DysonFrame();
|
||||
layer.framePool[newId] = frame;
|
||||
}
|
||||
else
|
||||
{
|
||||
frame = layer.framePool[newId];
|
||||
frame.SetEmpty();
|
||||
}
|
||||
frame.id = newId;
|
||||
frame.layerId = layer.id;
|
||||
frame.protoId = protoId + DysonSphereSegmentRenderer.nodeProtoCount;
|
||||
frame.reserved = false;
|
||||
frame.nodeA = nodeA;
|
||||
frame.nodeB = nodeB;
|
||||
frame.euler = euler;
|
||||
frame.spA = 0;
|
||||
frame.spB = 0;
|
||||
frame.spMax = frame.segCount * DysonFrame.kSpPerSeg;
|
||||
nodeA.frames.Add(frame);
|
||||
nodeB.frames.Add(frame);
|
||||
return frame;
|
||||
}
|
||||
private static readonly ThreadLocal<Dictionary<int, Vector3>> _vmap = new(() => new(16384));
|
||||
public static int CalculateTriangleVertCount(Vector3[] pos)
|
||||
{
|
||||
if (pos.Length != 3) return -1;
|
||||
VectorLF3[] polygon = [pos[0], pos[1], pos[2]];
|
||||
VectorLF3 sum = VectorLF3.zero;
|
||||
double num = 0.0;
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
float num2 = Vector3.Distance(pos[i], pos[(i + 1) % 3]);
|
||||
VectorLF3 vectorLF2 = ((VectorLF3)pos[i] + (VectorLF3)pos[(i + 1) % 3]) * 0.5;
|
||||
sum += vectorLF2 * num2;
|
||||
num += (double)num2;
|
||||
}
|
||||
var radius = Math.Round(polygon[0].magnitude * 10.0) / 10.0;
|
||||
for (int j = 0; j < polygon.Length; j++)
|
||||
{
|
||||
polygon[j] = polygon[j].normalized * radius;
|
||||
}
|
||||
var normalized = (sum / num).normalized;
|
||||
var center = normalized * radius;
|
||||
float num3 = 0f;
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
float num4 = Vector3.Distance(center, polygon[k]);
|
||||
if (num4 > num3)
|
||||
{
|
||||
num3 = num4;
|
||||
}
|
||||
}
|
||||
var gridScale = (int)(Math.Pow(radius / DysonSphereConstants.GridScaleBaseRadius, 0.75) + 0.5);
|
||||
gridScale = ((gridScale < 1) ? 1 : gridScale);
|
||||
var gridSize = gridScale * DysonSphereConstants.GridSizeBase;
|
||||
var gridSizeDouble = (double)gridSize;
|
||||
var cpPerVertex = gridScale * gridScale * DysonSphereConstants.CpPerVertexFactor;
|
||||
|
||||
var num5 = (int)((double)num3 / factor3 / gridSizeDouble + 2.5);
|
||||
var xaxis = VectorLF3.Cross(normalized, Vector3.up).normalized;
|
||||
if (xaxis.magnitude < 0.1)
|
||||
{
|
||||
xaxis = new VectorLF3(0f, 0f, 1f);
|
||||
}
|
||||
var yaxis = VectorLF3.Cross(xaxis, normalized).normalized;
|
||||
var raydir = xaxis * factor0 + yaxis * factor1;
|
||||
var w1axis = xaxis * (0.5 * gridSizeDouble) - yaxis * (factor3 * gridSizeDouble);
|
||||
var w2axis = xaxis * (0.5 * gridSizeDouble) + yaxis * (factor3 * gridSizeDouble);
|
||||
var w0axis = xaxis * gridSizeDouble;
|
||||
var t1axis = yaxis * (gridSizeDouble * factor2 * 0.5) - xaxis * (gridSizeDouble * 0.5);
|
||||
var t2axis = yaxis * (gridSizeDouble * factor2 * 0.5) + xaxis * (gridSizeDouble * 0.5);
|
||||
var t0axis = yaxis * (gridSizeDouble / factor3 * 0.5);
|
||||
var polyn = new VectorLF3[3];
|
||||
var polynu = new double[3];
|
||||
for (int l = 0; l < 3; l++)
|
||||
{
|
||||
Vector3 vector = polygon[l];
|
||||
Vector3 vector2 = polygon[(l + 1) % 3];
|
||||
polyn[l] = VectorLF3.Cross(vector, vector2).normalized;
|
||||
polynu[l] = polyn[l].x * raydir.x + polyn[l].y * raydir.y + polyn[l].z * raydir.z;
|
||||
}
|
||||
var vmap = _vmap.Value;
|
||||
vmap.Clear();
|
||||
double num7 = gridSizeDouble * 0.5;
|
||||
for (int m = -num5; m <= num5; m++)
|
||||
{
|
||||
for (int n = -num5; n <= num5; n++)
|
||||
{
|
||||
if (m - n <= num5 && m - n >= -num5)
|
||||
{
|
||||
VectorLF3 vectorLF3;
|
||||
vectorLF3.x = center.x + w0axis.x * m - w1axis.x * n;
|
||||
vectorLF3.y = center.y + w0axis.y * m - w1axis.y * n;
|
||||
vectorLF3.z = center.z + w0axis.z * m - w1axis.z * n;
|
||||
double num8 = radius / vectorLF3.magnitude;
|
||||
vectorLF3 *= num8;
|
||||
int num9 = 0;
|
||||
for (int num10 = 0; num10 < 3; num10++)
|
||||
{
|
||||
double num11 = -(polyn[num10].x * vectorLF3.x + polyn[num10].y * vectorLF3.y + polyn[num10].z * vectorLF3.z) / polynu[num10];
|
||||
if (num11 >= 0.0)
|
||||
{
|
||||
VectorLF3 normalized2 = new VectorLF3(vectorLF3.x + num11 * raydir.x, vectorLF3.y + num11 * raydir.y, vectorLF3.z + num11 * raydir.z).normalized;
|
||||
normalized2 *= radius;
|
||||
VectorLF3 vectorLF4 = polygon[num10] - normalized2;
|
||||
VectorLF3 vectorLF5 = polygon[(num10 + 1) % 3] - normalized2;
|
||||
double num12 = vectorLF4.x * vectorLF5.x + vectorLF4.y * vectorLF5.y + vectorLF4.z * vectorLF5.z;
|
||||
if (num12 < 0.0 || (num12 == 0.0 && vectorLF4.x == 0.0 && vectorLF4.y == 0.0 && vectorLF4.z == 0.0))
|
||||
{
|
||||
num9++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ((num9 & 1) == 1)
|
||||
{
|
||||
int num13 = DysonShell._get_key(m, n);
|
||||
vmap[num13] = vectorLF3;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int num14 = 0; num14 < 3; num14++)
|
||||
{
|
||||
VectorLF3 vectorLF6 = polygon[num14];
|
||||
VectorLF3 vectorLF7 = polyn[num14];
|
||||
VectorLF3 vectorLF8 = vectorLF3 - vectorLF6;
|
||||
double num15 = vectorLF7.x * vectorLF8.x + vectorLF7.y * vectorLF8.y + vectorLF7.z * vectorLF8.z;
|
||||
double num16 = Math.Abs(num15);
|
||||
if (num16 <= num7)
|
||||
{
|
||||
VectorLF3 vectorLF9 = polygon[(num14 + 1) % 3];
|
||||
VectorLF3 vectorLF10 = vectorLF3 - vectorLF7 * num15;
|
||||
VectorLF3 vectorLF11 = vectorLF9 - vectorLF6;
|
||||
double magnitude = vectorLF11.magnitude;
|
||||
VectorLF3 vectorLF12 = vectorLF11 / magnitude;
|
||||
VectorLF3 vectorLF13 = vectorLF10 - vectorLF6;
|
||||
double num17 = vectorLF12.x * vectorLF13.x + vectorLF12.y * vectorLF13.y + vectorLF12.z * vectorLF13.z;
|
||||
double num18;
|
||||
if (num17 < 0.0)
|
||||
{
|
||||
num18 = vectorLF8.magnitude;
|
||||
}
|
||||
else if (num17 > magnitude)
|
||||
{
|
||||
num18 = (vectorLF3 - vectorLF9).magnitude;
|
||||
}
|
||||
else
|
||||
{
|
||||
num18 = num16;
|
||||
}
|
||||
if (num18 <= num7)
|
||||
{
|
||||
int num19 = DysonShell._get_key(m, n);
|
||||
vmap[num19] = vectorLF3;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return vmap.Count;
|
||||
}
|
||||
public static bool GenerateCustomShellGeometry(this DysonShell shell)
|
||||
{
|
||||
VectorLF3 sum = VectorLF3.zero;
|
||||
double num = 0.0;
|
||||
for (int i = 0; i < shell.frames.Count; i++)
|
||||
{
|
||||
double num2 = Vector3.Distance(shell.frames[i].nodeA.pos, shell.frames[i].nodeB.pos);
|
||||
VectorLF3 vectorLF2 = ((VectorLF3)shell.frames[i].nodeA.pos + (VectorLF3)shell.frames[i].nodeB.pos) * 0.5;
|
||||
sum += vectorLF2 * num2;
|
||||
num += num2;
|
||||
}
|
||||
shell.radius = Math.Round(shell.polygon[0].magnitude * 10.0) / 10.0;
|
||||
for (int j = 0; j < shell.polygon.Count; j++)
|
||||
{
|
||||
shell.polygon[j] = shell.polygon[j].normalized * shell.radius;
|
||||
}
|
||||
var normalized = (sum / num).normalized;
|
||||
shell.center = normalized * shell.radius;
|
||||
float num3 = 0f;
|
||||
for (int k = 0; k < shell.polygon.Count; k++)
|
||||
{
|
||||
float num4 = Vector3.Distance(shell.center, shell.polygon[k]);
|
||||
if (num4 > num3)
|
||||
{
|
||||
num3 = num4;
|
||||
}
|
||||
}
|
||||
shell.gridScale = (int)(Math.Pow(shell.radius / DysonSphereConstants.GridScaleBaseRadius, 0.75) + 0.5);
|
||||
shell.gridScale = ((shell.gridScale < 1) ? 1 : shell.gridScale);
|
||||
shell.gridSize = shell.gridScale * DysonSphereConstants.GridSizeBase;
|
||||
var gridSizeDouble = (double)shell.gridSize;
|
||||
shell.cpPerVertex = shell.gridScale * shell.gridScale * DysonSphereConstants.CpPerVertexFactor;
|
||||
int num5 = (int)((double)num3 / factor3 / gridSizeDouble + 2.5);
|
||||
shell.xaxis = VectorLF3.Cross(normalized, Vector3.up).normalized;
|
||||
if (shell.xaxis.magnitude < 0.1)
|
||||
{
|
||||
shell.xaxis = new VectorLF3(0f, 0f, 1f);
|
||||
}
|
||||
shell.yaxis = VectorLF3.Cross(shell.xaxis, normalized).normalized;
|
||||
shell.raydir = shell.xaxis * factor0 + shell.yaxis * factor1;
|
||||
shell.w1axis = shell.xaxis * (0.5 * gridSizeDouble) - shell.yaxis * (factor3 * gridSizeDouble);
|
||||
shell.w2axis = shell.xaxis * (0.5 * gridSizeDouble) + shell.yaxis * (factor3 * gridSizeDouble);
|
||||
shell.w0axis = shell.xaxis * gridSizeDouble;
|
||||
shell.t1axis = shell.yaxis * (gridSizeDouble * factor2 * 0.5) - shell.xaxis * (gridSizeDouble * 0.5);
|
||||
shell.t2axis = shell.yaxis * (gridSizeDouble * factor2 * 0.5) + shell.xaxis * (gridSizeDouble * 0.5);
|
||||
shell.t0axis = shell.yaxis * (gridSizeDouble / factor3 * 0.5);
|
||||
int count = shell.polygon.Count;
|
||||
shell.polyn = new VectorLF3[count];
|
||||
shell.polynu = new double[count];
|
||||
for (int l = 0; l < count; l++)
|
||||
{
|
||||
shell.polyn[l] = VectorLF3.Cross(shell.polygon[l], shell.polygon[(l + 1) % count]).normalized;
|
||||
shell.polynu[l] = shell.polyn[l].x * shell.raydir.x + shell.polyn[l].y * shell.raydir.y + shell.polyn[l].z * shell.raydir.z;
|
||||
}
|
||||
DysonShell.s_vmap.Clear();
|
||||
DysonShell.s_outvmap.Clear();
|
||||
DysonShell.s_ivmap.Clear();
|
||||
double num7 = gridSizeDouble * 0.5;
|
||||
for (int m = -num5; m <= num5; m++)
|
||||
{
|
||||
for (int n = -num5; n <= num5; n++)
|
||||
{
|
||||
if (m - n <= num5 && m - n >= -num5)
|
||||
{
|
||||
VectorLF3 vectorLF3;
|
||||
vectorLF3.x = shell.center.x + shell.w0axis.x * m - shell.w1axis.x * n;
|
||||
vectorLF3.y = shell.center.y + shell.w0axis.y * m - shell.w1axis.y * n;
|
||||
vectorLF3.z = shell.center.z + shell.w0axis.z * m - shell.w1axis.z * n;
|
||||
double num8 = shell.radius / vectorLF3.magnitude;
|
||||
vectorLF3 *= num8;
|
||||
int num9 = 0;
|
||||
for (int num10 = 0; num10 < count; num10++)
|
||||
{
|
||||
double num11 = -(shell.polyn[num10].x * vectorLF3.x + shell.polyn[num10].y * vectorLF3.y + shell.polyn[num10].z * vectorLF3.z) / shell.polynu[num10];
|
||||
if (num11 >= 0.0)
|
||||
{
|
||||
VectorLF3 normalized2 = new VectorLF3(vectorLF3.x + num11 * shell.raydir.x, vectorLF3.y + num11 * shell.raydir.y, vectorLF3.z + num11 * shell.raydir.z).normalized;
|
||||
normalized2 *= shell.radius;
|
||||
VectorLF3 vectorLF4 = shell.polygon[num10] - normalized2;
|
||||
VectorLF3 vectorLF5 = shell.polygon[(num10 + 1) % count] - normalized2;
|
||||
double num12 = vectorLF4.x * vectorLF5.x + vectorLF4.y * vectorLF5.y + vectorLF4.z * vectorLF5.z;
|
||||
if (num12 < 0.0 || (num12 == 0.0 && vectorLF4.x == 0.0 && vectorLF4.y == 0.0 && vectorLF4.z == 0.0))
|
||||
{
|
||||
num9++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ((num9 & 1) == 1)
|
||||
{
|
||||
int num13 = DysonShell._get_key(m, n);
|
||||
DysonShell.s_vmap[num13] = vectorLF3;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int num14 = 0; num14 < count; num14++)
|
||||
{
|
||||
VectorLF3 vectorLF6 = shell.polygon[num14];
|
||||
VectorLF3 vectorLF7 = shell.polyn[num14];
|
||||
VectorLF3 vectorLF8 = vectorLF3 - vectorLF6;
|
||||
double num15 = vectorLF7.x * vectorLF8.x + vectorLF7.y * vectorLF8.y + vectorLF7.z * vectorLF8.z;
|
||||
double num16 = Math.Abs(num15);
|
||||
if (num16 <= num7)
|
||||
{
|
||||
VectorLF3 vectorLF9 = shell.polygon[(num14 + 1) % count];
|
||||
VectorLF3 vectorLF10 = vectorLF3 - vectorLF7 * num15;
|
||||
VectorLF3 vectorLF11 = vectorLF9 - vectorLF6;
|
||||
double magnitude = vectorLF11.magnitude;
|
||||
VectorLF3 vectorLF12 = vectorLF11 / magnitude;
|
||||
VectorLF3 vectorLF13 = vectorLF10 - vectorLF6;
|
||||
double num17 = vectorLF12.x * vectorLF13.x + vectorLF12.y * vectorLF13.y + vectorLF12.z * vectorLF13.z;
|
||||
double num18;
|
||||
if (num17 < 0.0)
|
||||
{
|
||||
num18 = vectorLF8.magnitude;
|
||||
}
|
||||
else if (num17 > magnitude)
|
||||
{
|
||||
num18 = (vectorLF3 - vectorLF9).magnitude;
|
||||
}
|
||||
else
|
||||
{
|
||||
num18 = num16;
|
||||
}
|
||||
if (num18 <= num7)
|
||||
{
|
||||
int num19 = DysonShell._get_key(m, n);
|
||||
DysonShell.s_vmap[num19] = vectorLF3;
|
||||
DysonShell.s_outvmap[num19] = vectorLF3;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
int count2 = DysonShell.s_vmap.Count;
|
||||
if (count2 > DysonSphereConstants.MaxShellVertices)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
shell.verts = new Vector3[count2];
|
||||
shell.uvs = new Vector2[count2];
|
||||
shell.uv2s = new Vector2[count2];
|
||||
shell.vkeys = new int[count2];
|
||||
shell._gen_points_topo_indices(count2);
|
||||
shell.vAdjs = new short[count2 * 6];
|
||||
for (int num20 = 0; num20 < shell.vAdjs.Length; num20++)
|
||||
{
|
||||
shell.vAdjs[num20] = -1;
|
||||
}
|
||||
int num21 = 0;
|
||||
foreach (KeyValuePair<int, Vector3> keyValuePair in DysonShell.s_vmap)
|
||||
{
|
||||
Vector3 value = keyValuePair.Value;
|
||||
DysonShell.s_ivmap[keyValuePair.Key] = num21;
|
||||
shell.verts[num21] = value;
|
||||
shell.uv2s[num21].x = DysonShell.s_outvmap.ContainsKey(keyValuePair.Key) ? 0 : 1;
|
||||
shell.vkeys[num21] = keyValuePair.Key;
|
||||
num21++;
|
||||
}
|
||||
foreach (KeyValuePair<int, int> keyValuePair2 in DysonShell.s_ivmap)
|
||||
{
|
||||
int key = keyValuePair2.Key;
|
||||
int num22 = DysonShell.s_ivmap[key];
|
||||
int num23 = key + 65536;
|
||||
int num24 = key - 1;
|
||||
int num25 = key - 65537;
|
||||
int num26 = key - 65536;
|
||||
int num27 = key + 1;
|
||||
int num28 = key + 65537;
|
||||
bool flag = DysonShell.s_ivmap.ContainsKey(num23);
|
||||
bool flag2 = DysonShell.s_ivmap.ContainsKey(num24);
|
||||
bool flag3 = DysonShell.s_ivmap.ContainsKey(num25);
|
||||
bool flag4 = DysonShell.s_ivmap.ContainsKey(num26);
|
||||
bool flag5 = DysonShell.s_ivmap.ContainsKey(num27);
|
||||
bool flag6 = DysonShell.s_ivmap.ContainsKey(num28);
|
||||
shell.vAdjs[num22 * 6] = (short)(flag ? DysonShell.s_ivmap[num23] : (-1));
|
||||
shell.vAdjs[num22 * 6 + 1] = (short)(flag2 ? DysonShell.s_ivmap[num24] : (-1));
|
||||
shell.vAdjs[num22 * 6 + 2] = (short)(flag3 ? DysonShell.s_ivmap[num25] : (-1));
|
||||
shell.vAdjs[num22 * 6 + 3] = (short)(flag4 ? DysonShell.s_ivmap[num26] : (-1));
|
||||
shell.vAdjs[num22 * 6 + 4] = (short)(flag5 ? DysonShell.s_ivmap[num27] : (-1));
|
||||
shell.vAdjs[num22 * 6 + 5] = (short)(flag6 ? DysonShell.s_ivmap[num28] : (-1));
|
||||
}
|
||||
int num29 = 0;
|
||||
int num30 = 0;
|
||||
for (int num31 = 0; num31 < count2; num31++)
|
||||
{
|
||||
double num32 = shell.radius * 2.0;
|
||||
int num33 = -1;
|
||||
VectorLF3 vectorLF14 = shell.verts[num31];
|
||||
for (int num34 = 0; num34 < count; num34++)
|
||||
{
|
||||
VectorLF3 vectorLF15 = shell.polygon[num34];
|
||||
VectorLF3 vectorLF16 = shell.polygon[(num34 + 1) % count];
|
||||
VectorLF3 vectorLF17 = shell.polyn[num34];
|
||||
VectorLF3 vectorLF18 = vectorLF14 - vectorLF15;
|
||||
double num35 = vectorLF17.x * vectorLF18.x + vectorLF17.y * vectorLF18.y + vectorLF17.z * vectorLF18.z;
|
||||
VectorLF3 vectorLF19 = vectorLF14 - vectorLF17 * num35;
|
||||
VectorLF3 vectorLF20 = vectorLF14 - vectorLF16;
|
||||
double num36 = vectorLF17.x * vectorLF20.x + vectorLF17.y * vectorLF20.y + vectorLF17.z * vectorLF20.z;
|
||||
VectorLF3 vectorLF21 = vectorLF16 - vectorLF15;
|
||||
double magnitude2 = vectorLF21.magnitude;
|
||||
VectorLF3 vectorLF22 = vectorLF21 / magnitude2;
|
||||
VectorLF3 vectorLF23 = vectorLF19 - vectorLF15;
|
||||
double num37 = vectorLF22.x * vectorLF23.x + vectorLF22.y * vectorLF23.y + vectorLF22.z * vectorLF23.z;
|
||||
double num38;
|
||||
if (num37 < 0.0)
|
||||
{
|
||||
num38 = (vectorLF14 - vectorLF15).magnitude;
|
||||
num38 -= Math.Abs(num35) * 0.001;
|
||||
}
|
||||
else if (num37 > magnitude2)
|
||||
{
|
||||
num38 = (vectorLF14 - vectorLF16).magnitude;
|
||||
num38 -= Math.Abs(num36) * 0.001;
|
||||
}
|
||||
else
|
||||
{
|
||||
num38 = Math.Abs(num35);
|
||||
num38 -= Math.Abs(num35) * 0.001;
|
||||
}
|
||||
if (num38 < num32)
|
||||
{
|
||||
num32 = num38;
|
||||
num33 = num34;
|
||||
}
|
||||
}
|
||||
shell.uv2s[num31].y = num33;
|
||||
if (num29 + num30 < 49 && shell._is_point_in_shell(vectorLF14))
|
||||
{
|
||||
double num39 = VectorLF3.Dot(vectorLF14 - shell.polygon[num33], shell.polyn[num33]);
|
||||
if (num39 > 0.1)
|
||||
{
|
||||
num29++;
|
||||
}
|
||||
else if (num39 < -0.1)
|
||||
{
|
||||
num30++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (num29 > num30)
|
||||
{
|
||||
shell.clockwise = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
shell.clockwise = false;
|
||||
}
|
||||
shell.vertAttr = new int[count2];
|
||||
shell.vertsq = new short[count2];
|
||||
shell.vertsqOffset = new int[shell.nodes.Count + 1];
|
||||
int count3 = shell.nodes.Count;
|
||||
int num40 = count3 / 2;
|
||||
for (int num41 = 0; num41 < count2; num41++)
|
||||
{
|
||||
Vector3 vector3 = shell.verts[num41];
|
||||
double num42 = double.MaxValue;
|
||||
int num43 = 0;
|
||||
int num44 = 0;
|
||||
int num45 = num41 + 479001600;
|
||||
for (int num46 = 0; num46 < count3; num46++)
|
||||
{
|
||||
int num47 = num45 % count3 - num46;
|
||||
if (num47 < 0)
|
||||
{
|
||||
num47 = -num47;
|
||||
}
|
||||
if (num47 > num40)
|
||||
{
|
||||
num47 = count3 - num47;
|
||||
}
|
||||
double num48 = (double)(vector3 - shell.nodes[num46].pos).sqrMagnitude;
|
||||
num48 += num47;
|
||||
if (num48 < num42)
|
||||
{
|
||||
num42 = num48;
|
||||
num43 = shell.nodes[num46].id;
|
||||
num44 = num46;
|
||||
}
|
||||
}
|
||||
shell.vertAttr[num41] = num43;
|
||||
shell.vertsqOffset[num44]++;
|
||||
}
|
||||
int num49 = 0;
|
||||
for (int num50 = 0; num50 < shell.vertsqOffset.Length; num50++)
|
||||
{
|
||||
num49 += shell.vertsqOffset[num50];
|
||||
}
|
||||
Assert.True(num49 == count2);
|
||||
for (int num51 = shell.vertsqOffset.Length - 1; num51 >= 0; num51--)
|
||||
{
|
||||
shell.vertsqOffset[num51] = num49;
|
||||
if (num51 > 0)
|
||||
{
|
||||
num49 -= shell.vertsqOffset[num51 - 1];
|
||||
}
|
||||
}
|
||||
Assert.Zero(num49);
|
||||
shell._openListPrepare();
|
||||
int num52 = shell.randSeed;
|
||||
int num53 = 0;
|
||||
while (num53 < count3)
|
||||
{
|
||||
Vector3 pos = shell.nodes[num53].pos;
|
||||
int num54 = shell.nodes[num53].id;
|
||||
float num55 = float.MaxValue;
|
||||
int num56 = -1;
|
||||
for (int num57 = 0; num57 < count2; num57++)
|
||||
{
|
||||
if (shell.vertAttr[num57] == num54 && (shell.vAdjs[num57 * 6] >= 0 || shell.vAdjs[num57 * 6 + 1] >= 0 || shell.vAdjs[num57 * 6 + 2] >= 0 || shell.vAdjs[num57 * 6 + 3] >= 0 || shell.vAdjs[num57 * 6 + 4] >= 0 || shell.vAdjs[num57 * 6 + 5] >= 0))
|
||||
{
|
||||
float sqrMagnitude = (shell.verts[num57] - pos).sqrMagnitude;
|
||||
if (sqrMagnitude < num55)
|
||||
{
|
||||
num55 = sqrMagnitude;
|
||||
num56 = num57;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (num56 >= 0)
|
||||
{
|
||||
shell._openListAdd(num56);
|
||||
}
|
||||
int num58 = shell.vertsqOffset[num53];
|
||||
int num59 = shell.vertsqOffset[num53 + 1] - shell.vertsqOffset[num53];
|
||||
double num60 = 0.0;
|
||||
for (; ; )
|
||||
{
|
||||
int num61 = shell._traverseRandomVertex(shell.nodes[num53].id, ref num52);
|
||||
if (num61 < 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
shell.vertsq[num58++] = (short)num61;
|
||||
num60 += 1.0;
|
||||
shell.uvs[num61].x = num53;
|
||||
shell.uvs[num61].y = (float)(num60 / num59);
|
||||
if (num58 == shell.vertsqOffset[num53 + 1])
|
||||
{
|
||||
goto Block_57;
|
||||
}
|
||||
}
|
||||
IL_1329:
|
||||
if (num58 < shell.vertsqOffset[num53 + 1])
|
||||
{
|
||||
for (int num62 = 0; num62 < count2; num62++)
|
||||
{
|
||||
if (shell.vertAttr[num62] == num54 && !shell._tmp_marked[num62])
|
||||
{
|
||||
shell.vertsq[num58++] = (short)num62;
|
||||
num60 += 1.0;
|
||||
shell.uvs[num62].x = num53;
|
||||
shell.uvs[num62].y = (float)(num60 / num59);
|
||||
}
|
||||
}
|
||||
}
|
||||
Assert.False(num58 > shell.vertsqOffset[num53 + 1]);
|
||||
Assert.False(num58 < shell.vertsqOffset[num53 + 1]);
|
||||
shell._openListClear();
|
||||
num53++;
|
||||
continue;
|
||||
Block_57:
|
||||
Assert.Zero(shell._tmp_openCount);
|
||||
goto IL_1329;
|
||||
}
|
||||
shell._openListFree();
|
||||
shell.vertexCount = count2;
|
||||
return true;
|
||||
}
|
||||
public static int QuickAddDysonShell(this DysonSphereLayer layer, int protoId, DysonNode[] nodes, DysonFrame[] frames, bool limit)
|
||||
{
|
||||
int shellId = 0;
|
||||
if (layer.shellRecycleCursor > 0)
|
||||
{
|
||||
int[] array = layer.shellRecycle;
|
||||
int index = layer.shellRecycleCursor - 1;
|
||||
layer.shellRecycleCursor = index;
|
||||
shellId = array[index];
|
||||
}
|
||||
else
|
||||
{
|
||||
int index = layer.shellCursor;
|
||||
layer.shellCursor = index + 1;
|
||||
shellId = index;
|
||||
if (shellId == layer.shellCapacity)
|
||||
{
|
||||
layer.SetShellCapacity(layer.shellCapacity * 2);
|
||||
}
|
||||
}
|
||||
var shell = layer.shellPool[shellId];
|
||||
if (shell == null)
|
||||
{
|
||||
shell = new DysonShell(layer);
|
||||
layer.shellPool[shellId] = shell;
|
||||
}
|
||||
else
|
||||
{
|
||||
shell.SetEmpty();
|
||||
}
|
||||
shell.id = shellId;
|
||||
shell.layerId = layer.id;
|
||||
shell.protoId = protoId;
|
||||
shell.randSeed = layer.id * DysonSphereConstants.ShellRandSeedMultiplier + shellId;
|
||||
for (int j = 0; j < nodes.Length; j++)
|
||||
{
|
||||
DysonNode dysonNode = nodes[j];
|
||||
DysonFrame dysonFrame = frames[j];
|
||||
List<Vector3> segments = dysonFrame.GetSegments();
|
||||
if (dysonNode == dysonFrame.nodeA)
|
||||
{
|
||||
for (int k = 0; k < segments.Count - 1; k++)
|
||||
{
|
||||
shell.polygon.Add(segments[k]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int l = segments.Count - 1; l >= 1; l--)
|
||||
{
|
||||
shell.polygon.Add(segments[l]);
|
||||
}
|
||||
}
|
||||
shell.nodeIndexMap[dysonNode.id] = shell.nodes.Count;
|
||||
shell.nodes.Add(dysonNode);
|
||||
shell.frames.Add(dysonFrame);
|
||||
}
|
||||
if (!shell.GenerateCustomShellGeometry() || (limit && DysonShell.s_vmap.Count < DysonSphereConstants.MinShellVertexThreshold))
|
||||
{
|
||||
CheatEnabler.Logger.LogDebug($"Stripped VertCount: {DysonShell.s_vmap.Count}");
|
||||
shell.Free();
|
||||
layer.shellPool[shellId] = null;
|
||||
int recycleIndex = layer.shellRecycleCursor;
|
||||
layer.shellRecycleCursor = recycleIndex + 1;
|
||||
layer.shellRecycle[recycleIndex] = shellId;
|
||||
return 0;
|
||||
}
|
||||
// CheatEnabler.Logger.LogDebug($"Shell {shellId} My VertCount: {DysonShell.s_vmap.Count}");
|
||||
// shell.GenerateGeometry();
|
||||
// CheatEnabler.Logger.LogDebug($"Shell {shellId} Orig VertCount: {DysonShell.s_vmap.Count}");
|
||||
// CheatEnabler.Logger.LogDebug($"Shell {shellId} Calc VertCount: {CalculateTriangleVertCount2([shell.nodes[0].pos, shell.nodes[1].pos, shell.nodes[2].pos])}");
|
||||
for (int j = 0; j < shell.nodes.Count; j++)
|
||||
{
|
||||
shell.nodes[j].shells.Add(shell);
|
||||
}
|
||||
shell.GenerateModelObjects();
|
||||
return shellId;
|
||||
}
|
||||
public static void QuickRemoveDysonNode(this DysonSphereLayer layer, int nodeId)
|
||||
{
|
||||
var node = layer.nodePool[nodeId];
|
||||
if (node == null || node.id != nodeId) return;
|
||||
var dysonSphere = layer.dysonSphere;
|
||||
dysonSphere.swarm.OnNodeRemove(layer.id, nodeId);
|
||||
dysonSphere.RemoveAutoNode(node);
|
||||
dysonSphere.RemoveNodeRocket(node);
|
||||
dysonSphere.RemoveDysonNodeRData(node);
|
||||
node.Free();
|
||||
layer.nodePool[nodeId] = null;
|
||||
int recycleIndex = layer.nodeRecycleCursor;
|
||||
layer.nodeRecycleCursor = recycleIndex + 1;
|
||||
layer.nodeRecycle[recycleIndex] = nodeId;
|
||||
}
|
||||
|
||||
public static void QuickRemoveDysonFrame(this DysonSphereLayer layer, int frameId)
|
||||
{
|
||||
var frame = layer.framePool[frameId];
|
||||
frame.nodeA.frames.Remove(frame);
|
||||
frame.nodeB.frames.Remove(frame);
|
||||
frame.Free();
|
||||
layer.framePool[frameId] = null;
|
||||
int recycleIndex = layer.frameRecycleCursor;
|
||||
layer.frameRecycleCursor = recycleIndex + 1;
|
||||
layer.frameRecycle[recycleIndex] = frameId;
|
||||
}
|
||||
public static int AlignUpToPowerOfTwo(int value)
|
||||
{
|
||||
value--;
|
||||
value |= value >> 1;
|
||||
value |= value >> 2;
|
||||
value |= value >> 4;
|
||||
value |= value >> 8;
|
||||
value |= value >> 16;
|
||||
return value + 1;
|
||||
}
|
||||
public class SupposedShell
|
||||
{
|
||||
public Vector3 posA;
|
||||
public Vector3 posB;
|
||||
public Vector3 posC;
|
||||
|
||||
public float area;
|
||||
public int vertCount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CheatEnabler.Functions;
|
||||
using static CheatEnabler.Functions.DysonSphere.GeometryHelpers;
|
||||
using UnityEngine;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.GameConstants;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using CheatEnabler;
|
||||
|
||||
namespace CheatEnabler.Functions.DysonSphere;
|
||||
|
||||
[ModFeature("IllegalShellFunctions")]
|
||||
public static class IllegalShellFunctions
|
||||
{
|
||||
private static void EnsureDysonShellMaps()
|
||||
{
|
||||
DysonShell.s_vmap ??= new Dictionary<int, Vector3>(16384);
|
||||
DysonShell.s_outvmap ??= new Dictionary<int, Vector3>(16384);
|
||||
DysonShell.s_ivmap ??= new Dictionary<int, int>(16384);
|
||||
}
|
||||
|
||||
private static void ResetLayerPools(DysonSphereLayer layer)
|
||||
{
|
||||
layer.nodePool = new DysonNode[DysonSphereConstants.DefaultLayerPoolCapacity];
|
||||
layer.nodeRecycle = new int[DysonSphereConstants.DefaultLayerPoolCapacity];
|
||||
layer.nodeRecycleCursor = 0;
|
||||
layer.nodeCapacity = DysonSphereConstants.DefaultLayerPoolCapacity;
|
||||
layer.nodeCursor = 1;
|
||||
layer.framePool = new DysonFrame[DysonSphereConstants.DefaultLayerPoolCapacity];
|
||||
layer.frameRecycle = new int[DysonSphereConstants.DefaultLayerPoolCapacity];
|
||||
layer.frameRecycleCursor = 0;
|
||||
layer.frameCapacity = DysonSphereConstants.DefaultLayerPoolCapacity;
|
||||
layer.frameCursor = 1;
|
||||
layer.shellPool = new DysonShell[DysonSphereConstants.DefaultLayerPoolCapacity];
|
||||
layer.shellRecycle = new int[DysonSphereConstants.DefaultLayerPoolCapacity];
|
||||
layer.shellRecycleCursor = 0;
|
||||
layer.shellCapacity = DysonSphereConstants.DefaultLayerPoolCapacity;
|
||||
layer.shellCursor = 1;
|
||||
}
|
||||
|
||||
private static void FinalizeDysonSphereChanges(global::DysonSphere sphere, DysonSphereLayer layer, bool notify = false, bool resetRenderMasks = false)
|
||||
{
|
||||
if (sphere == null) return;
|
||||
sphere.CheckAutoNodes();
|
||||
if (sphere.autoNodeCount <= 0) sphere.PickAutoNode();
|
||||
sphere.modelRenderer.RebuildModels();
|
||||
if (notify) GameMain.gameScenario?.NotifyOnPlanDysonShell();
|
||||
if (resetRenderMasks)
|
||||
{
|
||||
sphere.inEditorRenderMaskS = 0;
|
||||
sphere.inEditorRenderMaskL = 0;
|
||||
sphere.inGameRenderMaskS = 0;
|
||||
sphere.inGameRenderMaskL = 0;
|
||||
}
|
||||
}
|
||||
|
||||
public static void DuplicateShellsWithHighestProduction()
|
||||
{
|
||||
var resolved = DysonSphereResolver.ResolveEditorOrLocalSphere();
|
||||
if (resolved == null) return;
|
||||
var (dysonSphere, star) = resolved.Value;
|
||||
EnsureDysonShellMaps();
|
||||
DysonSphereLayer layer = null;
|
||||
var nodePos = new List<Vector3>();
|
||||
var isEuler = new List<bool>();
|
||||
DysonShell shell = null;
|
||||
for (var i = 1; i < dysonSphere.layersIdBased.Length; i++)
|
||||
{
|
||||
layer = dysonSphere.layersIdBased[i];
|
||||
if (layer == null || layer.id != i) continue;
|
||||
for (var j = 1; j < layer.shellCursor; j++)
|
||||
{
|
||||
shell = layer.shellPool[j];
|
||||
if (shell == null) continue;
|
||||
if (shell.id != j)
|
||||
{
|
||||
shell = null;
|
||||
continue;
|
||||
}
|
||||
nodePos.AddRange(shell.nodes.Select(node => node.pos));
|
||||
isEuler.AddRange(shell.frames.Select(frame => frame.euler));
|
||||
break;
|
||||
}
|
||||
if (nodePos.Count > 0) break;
|
||||
}
|
||||
if (nodePos.Count == 0)
|
||||
{
|
||||
UIMessageBox.Show(Localization.CheatEnabler.Translate(), string.Format(Localization.ThereIsNoDysonSphereShellOn0.Translate(), star.displayName), Localization.OK.Translate(), UIMessageBox.ERROR, null);
|
||||
return;
|
||||
}
|
||||
var currentShellCount = layer.shellCount;
|
||||
var keepCount = DysonSphereFunctions.ShellsCountForFunctions.Value;
|
||||
if (currentShellCount >= keepCount) return;
|
||||
CheatEnabler.Logger.LogDebug($"NodePositions: {nodePos[0]}, {nodePos[1]}, {nodePos[2]}");
|
||||
var nodeCount = nodePos.Count;
|
||||
DysonNode[] nodes = [.. shell.nodes];
|
||||
DysonFrame[] frames = [.. shell.frames];
|
||||
if (frames.Length == 0)
|
||||
{
|
||||
isEuler = new List<bool>(nodeCount);
|
||||
frames = new DysonFrame[nodeCount];
|
||||
for (var i = 0; i < nodeCount; i++)
|
||||
{
|
||||
isEuler.Add(false);
|
||||
frames[i] = layer.QuickAddDysonFrame(0, nodes[i], nodes[(i + 1) % nodeCount], false);
|
||||
}
|
||||
}
|
||||
var cpMax = new long[nodeCount];
|
||||
for (var i = 0; i < nodeCount; i++)
|
||||
{
|
||||
cpMax[i] = (shell.vertsqOffset[i + 1] - shell.vertsqOffset[i]) * shell.cpPerVertex;
|
||||
}
|
||||
long[] totalCpMax = [.. nodes.Select(node => node.totalCpMax)];
|
||||
var dirtyFrames = new HashSet<int>();
|
||||
for (var i = currentShellCount; i < keepCount; i++)
|
||||
{
|
||||
dirtyFrames.Clear();
|
||||
for (var j = 0; j < nodeCount; j++)
|
||||
{
|
||||
totalCpMax[j] += cpMax[j];
|
||||
if (totalCpMax[j] > DysonSphereConstants.TotalCpMaxCeiling)
|
||||
{
|
||||
totalCpMax[j] = cpMax[j];
|
||||
dirtyFrames.Add(j > 0 ? j - 1 : nodeCount - 1);
|
||||
dirtyFrames.Add(j);
|
||||
nodes[j] = layer.QuickAddDysonNode(0, nodePos[j]);
|
||||
}
|
||||
}
|
||||
foreach (var frameId in dirtyFrames)
|
||||
{
|
||||
frames[frameId] = layer.QuickAddDysonFrame(0, nodes[frameId], nodes[(frameId + 1) % nodeCount], isEuler[frameId]);
|
||||
}
|
||||
layer.QuickAddDysonShell(0, nodes, frames, false);
|
||||
}
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
node.RecalcSpReq();
|
||||
node.RecalcCpReq();
|
||||
}
|
||||
FinalizeDysonSphereChanges(dysonSphere, layer, true, true);
|
||||
}
|
||||
|
||||
public static void KeepMaxProductionShells()
|
||||
{
|
||||
var resolved = DysonSphereResolver.ResolveEditorOrLocalSphere();
|
||||
if (resolved == null) return;
|
||||
var (dysonSphere, star) = resolved.Value;
|
||||
int retainCount = DysonSphereFunctions.ShellsCountForFunctions.Value;
|
||||
for (var i = 1; i < dysonSphere.layersIdBased.Length; i++)
|
||||
{
|
||||
var layer = dysonSphere.layersIdBased[i];
|
||||
if (layer == null || layer.id != i) continue;
|
||||
var shells = layer.shellPool.Where(shell => shell != null).OrderByDescending(shell => shell.vertexCount).ToArray();
|
||||
if (shells.Length < 1) continue;
|
||||
for (var j = retainCount; j < shells.Length; j++)
|
||||
{
|
||||
var shell = shells[j];
|
||||
var id = shell.id;
|
||||
layer.shellPool[id] = null;
|
||||
for (var k = 0; k < shell.nodes.Count; k++)
|
||||
{
|
||||
shell.nodes[k].shells.Remove(shell);
|
||||
}
|
||||
shell.Free();
|
||||
shells[j] = null;
|
||||
}
|
||||
var poolCapacity = GeometryHelpers.AlignUpToPowerOfTwo(retainCount + 1);
|
||||
if (poolCapacity < DysonSphereConstants.DefaultLayerPoolCapacity) poolCapacity = DysonSphereConstants.DefaultLayerPoolCapacity;
|
||||
layer.shellPool = new DysonShell[poolCapacity];
|
||||
layer.shellRecycle = new int[poolCapacity];
|
||||
layer.shellRecycleCursor = 0;
|
||||
layer.shellCapacity = poolCapacity;
|
||||
layer.shellCursor = retainCount + 1;
|
||||
HashSet<int> retainNodes = [];
|
||||
HashSet<(int, int)> retainFrames = [];
|
||||
for (var j = 0; j < retainCount; j++)
|
||||
{
|
||||
var shell = shells[j];
|
||||
retainNodes.UnionWith(shell.nodes.Select(node => node.id));
|
||||
int shellId = j + 1;
|
||||
layer.shellPool[shellId] = shell;
|
||||
shell.id = shellId;
|
||||
for (var k = 0; k < shell.nodes.Count; k++)
|
||||
{
|
||||
var idA = shell.nodes[k].id;
|
||||
var idB = shell.nodes[(k + 1) % shell.nodes.Count].id;
|
||||
retainFrames.Add((idA, idB));
|
||||
retainFrames.Add((idB, idA));
|
||||
}
|
||||
}
|
||||
var nodes = layer.nodePool.Where(node => node != null && retainNodes.Contains(node.id)).ToArray();
|
||||
var frames = layer.framePool.Where(frame => frame != null && retainFrames.Contains((frame.nodeA.id, frame.nodeB.id))).ToArray();
|
||||
poolCapacity = GeometryHelpers.AlignUpToPowerOfTwo(frames.Length + 1);
|
||||
if (poolCapacity < DysonSphereConstants.DefaultLayerPoolCapacity) poolCapacity = DysonSphereConstants.DefaultLayerPoolCapacity;
|
||||
layer.framePool = new DysonFrame[poolCapacity];
|
||||
layer.frameRecycle = new int[poolCapacity];
|
||||
layer.frameRecycleCursor = 0;
|
||||
layer.frameCapacity = poolCapacity;
|
||||
layer.frameCursor = frames.Length + 1;
|
||||
for (var j = 0; j < frames.Length; j++)
|
||||
{
|
||||
int id = j + 1;
|
||||
layer.framePool[id] = frames[j];
|
||||
frames[j].id = id;
|
||||
}
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
if (node != null && node.id > 0)
|
||||
{
|
||||
dysonSphere.RemoveDysonNodeRData(node);
|
||||
}
|
||||
}
|
||||
poolCapacity = GeometryHelpers.AlignUpToPowerOfTwo(nodes.Length + 1);
|
||||
if (poolCapacity < DysonSphereConstants.DefaultLayerPoolCapacity) poolCapacity = DysonSphereConstants.DefaultLayerPoolCapacity;
|
||||
layer.nodePool = new DysonNode[poolCapacity];
|
||||
layer.nodeRecycle = new int[poolCapacity];
|
||||
layer.nodeRecycleCursor = 0;
|
||||
layer.nodeCapacity = poolCapacity;
|
||||
layer.nodeCursor = nodes.Length + 1;
|
||||
for (var j = 0; j < nodes.Length; j++)
|
||||
{
|
||||
int id = j + 1;
|
||||
layer.nodePool[id] = nodes[j];
|
||||
nodes[j].id = id;
|
||||
}
|
||||
for (var j = 1; j < layer.shellCursor; j++)
|
||||
{
|
||||
var shell = layer.shellPool[j];
|
||||
if (shell == null || shell.id != j) continue;
|
||||
shell.nodeIndexMap.Clear();
|
||||
for (var k = 0; k < shell.nodes.Count; k++)
|
||||
{
|
||||
shell.nodeIndexMap[shell.nodes[k].id] = k;
|
||||
}
|
||||
}
|
||||
for (var j = 1; j < layer.nodeCursor; j++)
|
||||
{
|
||||
var node = layer.nodePool[j];
|
||||
if (node == null || node.id != j) continue;
|
||||
dysonSphere.AddDysonNodeRData(node, true);
|
||||
node.RecalcSpReq();
|
||||
node.RecalcCpReq();
|
||||
}
|
||||
}
|
||||
FinalizeDysonSphereChanges(dysonSphere, null);
|
||||
}
|
||||
|
||||
public static void CreateIllegalDysonShellQuickly(int triangleCount)
|
||||
{
|
||||
var resolved = DysonSphereResolver.ResolveEditorOrLocalSphere(requireLayer: false);
|
||||
if (resolved == null) return;
|
||||
var (dysonSphere, _) = resolved.Value;
|
||||
|
||||
EnsureDysonShellMaps();
|
||||
|
||||
for (int i = 1; i <= 10; i++)
|
||||
{
|
||||
var layer = dysonSphere.layersIdBased[i];
|
||||
if (layer != null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var radius = dysonSphere.maxOrbitRadius;
|
||||
for (; radius > DysonSphereConstants.MinOrbitRadiusSearch; radius -= DysonSphereConstants.OrbitRadiusSearchStep)
|
||||
{
|
||||
if (dysonSphere.CheckLayerRadius(radius) == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
PrecalculatedTriangle triangle;
|
||||
try
|
||||
{
|
||||
triangle = GeometryHelpers.PrecalculatedTriangles.First(t => t.MaxOrbitRadius > radius);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
UIMessageBox.Show(Localization.CheatEnabler.Translate(), string.Format(Localization.NoPrecalculatedShellFoundForRadius0.Translate(), radius), Localization.OK.Translate(), UIMessageBox.ERROR, null);
|
||||
return;
|
||||
}
|
||||
layer = dysonSphere.AddLayerOnId(i, radius, Quaternion.Euler(0f, 0f, 0f), Mathf.Sqrt(dysonSphere.gravity / radius) / radius * DysonSphereConstants.RadiansToDegrees);
|
||||
if (layer == null) return;
|
||||
Vector3[] nodePos = [triangle.PosA.normalized * radius, triangle.PosB.normalized * radius, triangle.PosC.normalized * radius];
|
||||
DysonNode[] nodes = [layer.QuickAddDysonNode(0, nodePos[0]), layer.QuickAddDysonNode(0, nodePos[1]), layer.QuickAddDysonNode(0, nodePos[2])];
|
||||
DysonFrame[] frames = [layer.QuickAddDysonFrame(0, nodes[0], nodes[1], false), layer.QuickAddDysonFrame(0, nodes[1], nodes[2], false), layer.QuickAddDysonFrame(0, nodes[2], nodes[0], false)];
|
||||
var shellId = layer.QuickAddDysonShell(0, nodes, frames, false);
|
||||
if (shellId == 0) return;
|
||||
var shell = layer.shellPool[shellId];
|
||||
long[] cpMax = [.. nodes.Select(node => node.totalCpMax)];
|
||||
long[] totalCpMax = [.. cpMax];
|
||||
var dirtyFrames = new HashSet<int>();
|
||||
for (var j = 1; j < triangleCount; j++)
|
||||
{
|
||||
dirtyFrames.Clear();
|
||||
for (var k = 0; k < 3; k++)
|
||||
{
|
||||
totalCpMax[k] += cpMax[k];
|
||||
if (totalCpMax[k] > DysonSphereConstants.TotalCpMaxCeiling)
|
||||
{
|
||||
totalCpMax[k] = cpMax[k];
|
||||
dirtyFrames.Add(k > 0 ? k - 1 : 2);
|
||||
dirtyFrames.Add(k);
|
||||
nodes[k] = layer.QuickAddDysonNode(0, nodePos[k]);
|
||||
}
|
||||
}
|
||||
foreach (var frameId in dirtyFrames)
|
||||
{
|
||||
frames[frameId] = layer.QuickAddDysonFrame(0, nodes[frameId], nodes[(frameId + 1) % 3], false);
|
||||
}
|
||||
layer.QuickAddDysonShell(0, nodes, frames, false);
|
||||
}
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
node.RecalcSpReq();
|
||||
node.RecalcCpReq();
|
||||
}
|
||||
FinalizeDysonSphereChanges(dysonSphere, layer, true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool CreateIllegalDysonShellWithMaxOutputForLayer(DysonSphereLayer layer)
|
||||
{
|
||||
EnsureDysonShellMaps();
|
||||
var shellsChanged = false;
|
||||
var mutex = new object();
|
||||
var supposedShells = new List<SupposedShell>(DysonSphereConstants.MaxShellSearchCombinations);
|
||||
Vector3[] nodePos = new Vector3[DysonSphereConstants.MaxShellSearchNodeCount];
|
||||
for (var i = 0; i < DysonSphereConstants.MaxShellSearchNodeCount; i++)
|
||||
{
|
||||
nodePos[i] = new Vector3((float)Math.Sin(Math.PI * 2 * i / DysonSphereConstants.MaxShellSearchNodeCount), 0, (float)Math.Cos(Math.PI * 2 * i / DysonSphereConstants.MaxShellSearchNodeCount)) * layer.orbitRadius;
|
||||
}
|
||||
for (var i = 0; i < DysonSphereConstants.MaxShellSearchNodeCount - 2; i++)
|
||||
{
|
||||
for (var j = i + 1; j < DysonSphereConstants.MaxShellSearchNodeCount - 1; j++)
|
||||
{
|
||||
for (var k = j + 1; k < DysonSphereConstants.MaxShellSearchNodeCount; k++)
|
||||
{
|
||||
var area = Vector3.Cross(nodePos[j] - nodePos[i], nodePos[k] - nodePos[i]).sqrMagnitude;
|
||||
supposedShells.Add(new SupposedShell { posA = nodePos[i], posB = nodePos[j], posC = nodePos[k], area = area });
|
||||
}
|
||||
}
|
||||
}
|
||||
supposedShells.Sort((a, b) => b.area.CompareTo(a.area));
|
||||
CheatEnabler.Logger.LogDebug($"Finished Area Sort");
|
||||
var maxVertCount = -1;
|
||||
var maxJ = -1;
|
||||
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount - 1 };
|
||||
|
||||
var gridScale = (int)(Math.Pow(layer.orbitRadius / DysonSphereConstants.GridScaleBaseRadius, 0.75) + 0.5);
|
||||
gridScale = (gridScale < 1) ? 1 : gridScale;
|
||||
var cpPerVertex = gridScale * gridScale * DysonSphereConstants.CpPerVertexFactor;
|
||||
var barrier = DysonSphereConstants.TotalCpMaxCeiling / cpPerVertex;
|
||||
if (barrier > DysonSphereConstants.MaxShellVertices) barrier = DysonSphereConstants.MaxShellVertices;
|
||||
var truncValue = barrier / 1000 * 1000;
|
||||
CheatEnabler.Logger.LogDebug($"cpPerVertex: {cpPerVertex}, Barrier: {barrier}, TruncValue: {truncValue}");
|
||||
|
||||
Parallel.For(0, supposedShells.Count, options, (j, loopState) =>
|
||||
{
|
||||
var sshell = supposedShells[j];
|
||||
var vertCount = GeometryHelpers.CalculateTriangleVertCount([sshell.posA, sshell.posB, sshell.posC]);
|
||||
sshell.vertCount = vertCount <= barrier ? vertCount : -1;
|
||||
if (vertCount <= barrier)
|
||||
{
|
||||
lock (mutex)
|
||||
{
|
||||
if (loopState.ShouldExitCurrentIteration) return;
|
||||
if (vertCount > maxVertCount)
|
||||
{
|
||||
maxVertCount = vertCount;
|
||||
maxJ = j;
|
||||
if (maxVertCount >= truncValue)
|
||||
{
|
||||
CheatEnabler.Logger.LogDebug($"!!STOP!! Triangle {j}[{sshell.posA:F2} {sshell.posB:F2} {sshell.posC:F2}] has {vertCount} vertices");
|
||||
loopState.Stop();
|
||||
return;
|
||||
}
|
||||
CheatEnabler.Logger.LogDebug($"Triangle {j}[{sshell.posA:F2} {sshell.posB:F2} {sshell.posC:F2}] has {vertCount} vertices");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (maxJ >= 0)
|
||||
{
|
||||
ResetLayerPools(layer);
|
||||
foreach (var sshell in supposedShells.OrderByDescending(shell => shell.vertCount))
|
||||
{
|
||||
if (sshell.vertCount <= 0) break;
|
||||
|
||||
DysonNode[] newNodes = [layer.QuickAddDysonNode(0, sshell.posA), layer.QuickAddDysonNode(0, sshell.posB), layer.QuickAddDysonNode(0, sshell.posC)];
|
||||
DysonFrame[] newFrames = [layer.QuickAddDysonFrame(0, newNodes[0], newNodes[1], false), layer.QuickAddDysonFrame(0, newNodes[1], newNodes[2], false), layer.QuickAddDysonFrame(0, newNodes[2], newNodes[0], false)];
|
||||
if (layer.QuickAddDysonShell(0, newNodes, newFrames, false) == 0)
|
||||
{
|
||||
foreach (var frame in newFrames)
|
||||
{
|
||||
layer.QuickRemoveDysonFrame(frame.id);
|
||||
}
|
||||
foreach (var node in newNodes)
|
||||
{
|
||||
layer.QuickRemoveDysonNode(node.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
foreach (var node in newNodes)
|
||||
{
|
||||
node.RecalcSpReq();
|
||||
node.RecalcCpReq();
|
||||
}
|
||||
shellsChanged = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return shellsChanged;
|
||||
}
|
||||
|
||||
public static void CreateIllegalDysonShellWithMaxOutput()
|
||||
{
|
||||
var resolved = DysonSphereResolver.ResolveEditorOrLocalSphere(requireLayer: false);
|
||||
if (resolved == null) return;
|
||||
var (dysonSphere, star) = resolved.Value;
|
||||
UXAssist.Functions.DysonSphereFunctions.InitCurrentDysonLayer(star, 0);
|
||||
var layer = dysonSphere.layersIdBased[1];
|
||||
if (layer != null)
|
||||
{
|
||||
dysonSphere.RemoveLayer(1);
|
||||
}
|
||||
var maxOrbitRadius = Patches.DysonSpherePatch.UnlockMaxOrbitRadiusEnabled.Value ? Patches.DysonSpherePatch.UnlockMaxOrbitRadiusValue.Value : dysonSphere.maxOrbitRadius;
|
||||
layer = dysonSphere.AddLayerOnId(1, maxOrbitRadius, Quaternion.Euler(0f, 0f, 0f), Mathf.Sqrt(dysonSphere.gravity / maxOrbitRadius) / maxOrbitRadius * DysonSphereConstants.RadiansToDegrees);
|
||||
if (layer == null) return;
|
||||
|
||||
var shellsChanged = CreateIllegalDysonShellWithMaxOutputForLayer(layer);
|
||||
|
||||
FinalizeDysonSphereChanges(dysonSphere, layer, shellsChanged, true);
|
||||
}
|
||||
|
||||
public static void CreateIllegalDysonShellWithMaxOutputForAllLayers()
|
||||
{
|
||||
var resolved = DysonSphereResolver.ResolveEditorOrLocalSphere(requireLayer: false);
|
||||
if (resolved == null) return;
|
||||
var (dysonSphere, _) = resolved.Value;
|
||||
var shellsChanged = false;
|
||||
for (int i = dysonSphere.layersSorted.Length - 1; i >= 0; i--)
|
||||
{
|
||||
var layer = dysonSphere.layersSorted[i];
|
||||
if (layer == null) continue;
|
||||
shellsChanged = CreateIllegalDysonShellWithMaxOutputForLayer(layer) || shellsChanged;
|
||||
}
|
||||
|
||||
FinalizeDysonSphereChanges(dysonSphere, dysonSphere.layersSorted.FirstOrDefault(l => l != null), shellsChanged, true);
|
||||
}
|
||||
|
||||
public static void CreateIllegalDysonShellsSpecially()
|
||||
{
|
||||
var lastGridScale = 0;
|
||||
var radiusList = new List<int>();
|
||||
for (var r = DysonSphereConstants.MinOrbitRadiusSearch; r <= DysonSphereConstants.MaxOrbitRadius; r++)
|
||||
{
|
||||
var gridScale = (int)(Math.Pow(r / DysonSphereConstants.GridScaleBaseRadius, 0.75) + 0.5);
|
||||
gridScale = (gridScale < 1) ? 1 : gridScale;
|
||||
if (gridScale == lastGridScale) continue;
|
||||
lastGridScale = gridScale;
|
||||
radiusList.Add(r);
|
||||
CheatEnabler.Logger.LogDebug($"Grid Scale: {gridScale} from {r}");
|
||||
}
|
||||
radiusList.Add(DysonSphereConstants.MaxOrbitRadius);
|
||||
var resolved = DysonSphereResolver.ResolveEditorOrLocalSphere(requireLayer: false);
|
||||
if (resolved == null) return;
|
||||
var (dysonSphere, star) = resolved.Value;
|
||||
UXAssist.Functions.DysonSphereFunctions.InitCurrentDysonLayer(star, 0);
|
||||
|
||||
EnsureDysonShellMaps();
|
||||
var shellsChanged = false;
|
||||
var mutex = new object();
|
||||
|
||||
for (var idx = 1; idx <= 2; idx++)
|
||||
{
|
||||
Dictionary<(int, int), int> availableFrames = [];
|
||||
HashSet<int> unusedFrameIds = [];
|
||||
var layer = dysonSphere.layersIdBased[idx];
|
||||
if (layer != null)
|
||||
{
|
||||
dysonSphere.RemoveLayer(idx);
|
||||
}
|
||||
var orbitRadius = (radiusList[idx] - 1) / 10 * 10f;
|
||||
layer = dysonSphere.AddLayerOnId(idx, orbitRadius, Quaternion.Euler(0f, 0f, 0f), Mathf.Sqrt(dysonSphere.gravity / orbitRadius) / orbitRadius * DysonSphereConstants.RadiansToDegrees);
|
||||
if (layer == null) return;
|
||||
|
||||
var supposedShells = new List<SupposedShell>(DysonSphereConstants.MaxShellSearchCombinations);
|
||||
Vector3[] nodePos = new Vector3[DysonSphereConstants.MaxShellSearchNodeCount];
|
||||
for (var i = 0; i < DysonSphereConstants.MaxShellSearchNodeCount; i++)
|
||||
{
|
||||
nodePos[i] = new Vector3((float)Math.Sin(Math.PI * 2 * i / DysonSphereConstants.MaxShellSearchNodeCount), 0, (float)Math.Cos(Math.PI * 2 * i / DysonSphereConstants.MaxShellSearchNodeCount));
|
||||
}
|
||||
for (var i = 0; i < DysonSphereConstants.MaxShellSearchNodeCount - 2; i++)
|
||||
{
|
||||
for (var j = i + 1; j < DysonSphereConstants.MaxShellSearchNodeCount - 1; j++)
|
||||
{
|
||||
for (var k = j + 1; k < DysonSphereConstants.MaxShellSearchNodeCount; k++)
|
||||
{
|
||||
var area = Vector3.Cross(nodePos[j] - nodePos[i], nodePos[k] - nodePos[i]).sqrMagnitude;
|
||||
supposedShells.Add(new SupposedShell { posA = nodePos[i], posB = nodePos[j], posC = nodePos[k], area = area });
|
||||
}
|
||||
}
|
||||
}
|
||||
supposedShells.Sort((a, b) => b.area.CompareTo(a.area));
|
||||
|
||||
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount - 1 };
|
||||
|
||||
var gridScale = (int)(Math.Pow(orbitRadius / DysonSphereConstants.GridScaleBaseRadius, 0.75) + 0.5);
|
||||
gridScale = (gridScale < 1) ? 1 : gridScale;
|
||||
var cpPerVertex = gridScale * gridScale * DysonSphereConstants.CpPerVertexFactor;
|
||||
var barrier = DysonSphereConstants.TotalCpMaxCeiling / cpPerVertex;
|
||||
if (barrier > 30000) barrier = 30000;
|
||||
|
||||
Parallel.For(0, supposedShells.Count, options, (j, _) =>
|
||||
{
|
||||
var sshell = supposedShells[j];
|
||||
var vertCount = GeometryHelpers.CalculateTriangleVertCount([sshell.posA * orbitRadius, sshell.posB * orbitRadius, sshell.posC * orbitRadius]);
|
||||
if (vertCount > barrier)
|
||||
{
|
||||
sshell.vertCount = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
sshell.vertCount = vertCount;
|
||||
}
|
||||
});
|
||||
supposedShells.Sort((a, b) => b.vertCount.CompareTo(a.vertCount));
|
||||
for (var j = 0; j < supposedShells.Count && supposedShells[j].vertCount > 0; j++)
|
||||
{
|
||||
var sshell = supposedShells[j];
|
||||
CheatEnabler.Logger.LogDebug($"Checking Triangle {j}[{orbitRadius}] with {sshell.vertCount} vertices");
|
||||
var result = Parallel.For((radiusList[idx - 1] + 9) / 10, (radiusList[idx] + 9) / 10, options, (k, loopState) =>
|
||||
{
|
||||
var orbitRadius = k * 10f;
|
||||
var gridScale = (int)(Math.Pow(orbitRadius / DysonSphereConstants.GridScaleBaseRadius, 0.75) + 0.5);
|
||||
gridScale = (gridScale < 1) ? 1 : gridScale;
|
||||
var cpPerVertex = gridScale * gridScale * DysonSphereConstants.CpPerVertexFactor;
|
||||
var barrier = DysonSphereConstants.TotalCpMaxCeiling / cpPerVertex;
|
||||
if (barrier > 31000) barrier = 31000;
|
||||
if (loopState.ShouldExitCurrentIteration) return;
|
||||
var vertCount = GeometryHelpers.CalculateTriangleVertCount([sshell.posA * orbitRadius, sshell.posB * orbitRadius, sshell.posC * orbitRadius]);
|
||||
lock (mutex)
|
||||
{
|
||||
if (loopState.ShouldExitCurrentIteration) return;
|
||||
if (vertCount > barrier)
|
||||
{
|
||||
CheatEnabler.Logger.LogDebug($"EXCEEDED: Triangle {j}[{orbitRadius}] has {vertCount} vertices");
|
||||
loopState.Stop();
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!result.IsCompleted)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
ResetLayerPools(layer);
|
||||
DysonNode[] newNodes = [layer.QuickAddDysonNode(0, sshell.posA * orbitRadius), layer.QuickAddDysonNode(0, sshell.posB * orbitRadius), layer.QuickAddDysonNode(0, sshell.posC * orbitRadius)];
|
||||
DysonFrame[] newFrames = [layer.QuickAddDysonFrame(0, newNodes[0], newNodes[1], false), layer.QuickAddDysonFrame(0, newNodes[1], newNodes[2], false), layer.QuickAddDysonFrame(0, newNodes[2], newNodes[0], false)];
|
||||
layer.QuickAddDysonShell(0, newNodes, newFrames, false);
|
||||
foreach (var node in newNodes)
|
||||
{
|
||||
node.RecalcSpReq();
|
||||
node.RecalcCpReq();
|
||||
}
|
||||
shellsChanged = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
FinalizeDysonSphereChanges(dysonSphere, dysonSphere.layersIdBased[2], shellsChanged, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using UXAssist.Common.Utils;
|
||||
using CheatEnabler;
|
||||
|
||||
namespace CheatEnabler.Functions.DysonSphere;
|
||||
|
||||
[ModFeature("ShellCompletionFunctions")]
|
||||
public static class ShellCompletionFunctions
|
||||
{
|
||||
public static void CompleteShellsInstantly()
|
||||
{
|
||||
var resolved = DysonSphereResolver.ResolveEditorOrLocalSphere();
|
||||
if (resolved == null) return;
|
||||
var (dysonSphere, star) = resolved.Value;
|
||||
|
||||
UIMessageBox.Show(Localization.CheatEnabler.Translate(), string.Format(Localization.ThisWillCompleteAllDysonSphereShellsOn0InstantlyAreYouSure.Translate(), star.displayName), Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () =>
|
||||
{
|
||||
var rocketCount = 0L;
|
||||
var solarSailCount = 0L;
|
||||
foreach (var dysonSphereLayer in dysonSphere.layersIdBased)
|
||||
{
|
||||
if (dysonSphereLayer == null) continue;
|
||||
long totalNodeSp = 0;
|
||||
long totalFrameSp = 0;
|
||||
long totalCp = 0;
|
||||
for (var i = dysonSphereLayer.frameCursor - 1; i >= 0; i--)
|
||||
{
|
||||
var dysonFrame = dysonSphereLayer.framePool[i];
|
||||
if (dysonFrame == null || dysonFrame.id != i) continue;
|
||||
totalFrameSp += dysonFrame.spMax;
|
||||
var spMax = dysonFrame.spMax / 2;
|
||||
if (dysonFrame.spA < spMax)
|
||||
{
|
||||
rocketCount += spMax - dysonFrame.spA;
|
||||
dysonFrame.spA = spMax;
|
||||
dysonSphere.UpdateProgress(dysonFrame);
|
||||
}
|
||||
if (dysonFrame.spB < spMax)
|
||||
{
|
||||
rocketCount += spMax - dysonFrame.spB;
|
||||
dysonFrame.spB = spMax;
|
||||
dysonSphere.UpdateProgress(dysonFrame);
|
||||
}
|
||||
}
|
||||
for (var i = dysonSphereLayer.nodeCursor - 1; i >= 0; i--)
|
||||
{
|
||||
var dysonNode = dysonSphereLayer.nodePool[i];
|
||||
if (dysonNode == null || dysonNode.id != i) continue;
|
||||
dysonNode.spOrdered = 0;
|
||||
dysonNode._spReq = 0;
|
||||
totalNodeSp += dysonNode.spMax;
|
||||
var diff = dysonNode.spMax - dysonNode.sp;
|
||||
if (diff > 0)
|
||||
{
|
||||
rocketCount += diff;
|
||||
dysonNode.sp = dysonNode.spMax;
|
||||
dysonSphere.UpdateProgress(dysonNode);
|
||||
}
|
||||
dysonNode._cpReq = 0;
|
||||
dysonNode.cpOrdered = 0;
|
||||
foreach (var shell in dysonNode.shells)
|
||||
{
|
||||
var nodeIndex = shell.nodeIndexMap[dysonNode.id];
|
||||
var cpMax = (shell.vertsqOffset[nodeIndex + 1] - shell.vertsqOffset[nodeIndex]) * shell.cpPerVertex;
|
||||
totalCp += cpMax;
|
||||
diff = cpMax - shell.nodecps[nodeIndex];
|
||||
shell.nodecps[nodeIndex] = cpMax;
|
||||
shell.nodecps[shell.nodecps.Length - 1] += diff;
|
||||
solarSailCount += diff;
|
||||
if (DysonSphereReflection.HasTotalCP)
|
||||
{
|
||||
shell.SetMaterialDynamicVars();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DysonSphereReflection.SetTotalNodeSP(dysonSphereLayer, totalNodeSp);
|
||||
DysonSphereReflection.SetTotalFrameSP(dysonSphereLayer, totalFrameSp);
|
||||
DysonSphereReflection.SetTotalCP(dysonSphereLayer, totalCp);
|
||||
}
|
||||
dysonSphere.CheckAutoNodes();
|
||||
|
||||
var productRegister = dysonSphere.productRegister;
|
||||
if (productRegister != null)
|
||||
{
|
||||
lock (productRegister)
|
||||
{
|
||||
var count = rocketCount;
|
||||
while (count > 0x40000000L)
|
||||
{
|
||||
productRegister[ProductionStatistics.DYSON_STRUCTURE_ID] += 0x40000000;
|
||||
count -= 0x40000000;
|
||||
}
|
||||
if (count > 0L) productRegister[ProductionStatistics.DYSON_STRUCTURE_ID] += (int)count;
|
||||
count = solarSailCount;
|
||||
while (count > 0x40000000L)
|
||||
{
|
||||
productRegister[ProductionStatistics.SOLAR_SAIL_ID] += 0x40000000;
|
||||
productRegister[ProductionStatistics.DYSON_CELL_ID] += 0x40000000;
|
||||
count -= 0x40000000;
|
||||
}
|
||||
if (count > 0L)
|
||||
{
|
||||
productRegister[ProductionStatistics.SOLAR_SAIL_ID] += (int)count;
|
||||
productRegister[ProductionStatistics.DYSON_CELL_ID] += (int)count;
|
||||
}
|
||||
}
|
||||
}
|
||||
var consumeRegister = dysonSphere.consumeRegister;
|
||||
if (consumeRegister != null)
|
||||
{
|
||||
lock (consumeRegister)
|
||||
{
|
||||
var count = solarSailCount;
|
||||
while (count > 0x40000000L)
|
||||
{
|
||||
consumeRegister[ProductionStatistics.SOLAR_SAIL_ID] += 0x40000000;
|
||||
count -= 0x40000000;
|
||||
}
|
||||
if (count > 0L) consumeRegister[ProductionStatistics.SOLAR_SAIL_ID] += (int)count;
|
||||
}
|
||||
}
|
||||
dysonSphere.needRecalculatePower = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,9 @@
|
||||
using Random = UnityEngine.Random;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
|
||||
namespace CheatEnabler.Functions;
|
||||
|
||||
[ModFeature("PlanetFunctions")]
|
||||
public static class PlanetFunctions
|
||||
{
|
||||
public static void BuryAllVeins(bool bury)
|
||||
@@ -16,9 +19,15 @@ public static class PlanetFunctions
|
||||
{
|
||||
var pos = array[m].pos;
|
||||
var colliderId = array[m].colliderId;
|
||||
if (colliderId <= 0) continue;
|
||||
var chunkIdx = colliderId >> 20;
|
||||
var poolIdx = colliderId & 0xFFFFF;
|
||||
if (chunkIdx >= physics.colChunks.Length) continue;
|
||||
var chunk = physics.colChunks[chunkIdx];
|
||||
if (chunk == null || poolIdx >= chunk.colliderPool.Length) continue;
|
||||
var colliderData = physics.GetColliderData(colliderId);
|
||||
var vector = colliderData.pos.normalized * (height + 0.4f);
|
||||
physics.colChunks[colliderId >> 20].colliderPool[colliderId & 0xFFFFF].pos = vector;
|
||||
chunk.colliderPool[poolIdx].pos = vector;
|
||||
array[m].pos = pos.normalized * height;
|
||||
var quaternion = Maths.SphericalRotation(array[m].pos, Random.value * 360f);
|
||||
physics.SetPlanetPhysicsColliderDirty();
|
||||
|
||||
@@ -1,40 +1,23 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.GameConstants;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
|
||||
namespace CheatEnabler.Functions;
|
||||
|
||||
[ModFeature("PlayerFunctions")]
|
||||
public static class PlayerFunctions
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
I18N.Add("ClearAllMetadataConsumptionDetails",
|
||||
"""
|
||||
Metadata consumption records of all gamesaves are about to be cleared.
|
||||
You will gain following metadata back:
|
||||
""",
|
||||
"""
|
||||
所有存档的元数据消耗记录即将被清除,
|
||||
此操作将返还以下元数据:
|
||||
""");
|
||||
I18N.Add("ClearCurrentMetadataConsumptionDetails",
|
||||
"""
|
||||
Metadata consumption records of current gamesave are about to be cleared.
|
||||
You will gain following metadata back:
|
||||
""",
|
||||
"""
|
||||
当前存档的元数据消耗记录即将被清除,
|
||||
此操作将返还以下元数据:
|
||||
""");
|
||||
I18N.Add("NoMetadataConsumptionRecord",
|
||||
"No metadata consumption records found.",
|
||||
"未找到元数据消耗记录。");
|
||||
}
|
||||
}
|
||||
|
||||
public static void TeleportToOuterSpace()
|
||||
{
|
||||
var maxSqrDistance = 0.0;
|
||||
var starPosition = VectorLF3.zero;
|
||||
if (GameMain.galaxy == null) return;
|
||||
foreach (var star in GameMain.galaxy.stars)
|
||||
{
|
||||
var sqrDistance = star.position.sqrMagnitude;
|
||||
@@ -98,26 +81,26 @@ public static class PlayerFunctions
|
||||
var propertySystem = DSPGame.propertySystem;
|
||||
if (propertySystem == null) return;
|
||||
PurgePropertySystem(propertySystem);
|
||||
var itemCnt = new int[6];
|
||||
foreach (var cons in propertySystem.propertyDatas.SelectMany(data => data.totalConsumption.Where(cons => cons.id is >= 6001 and <= 6006)))
|
||||
var itemCnt = new int[ItemIds.Metaverse - ItemIds.HydrogenFuelRod + 1];
|
||||
foreach (var cons in propertySystem.propertyDatas.SelectMany(data => data.totalConsumption.Where(cons => cons.id is >= ItemIds.HydrogenFuelRod and <= ItemIds.Metaverse)))
|
||||
{
|
||||
itemCnt[cons.id - 6001] += cons.count;
|
||||
itemCnt[cons.id - ItemIds.HydrogenFuelRod] += cons.count;
|
||||
}
|
||||
|
||||
if (itemCnt.All(cnt => cnt == 0))
|
||||
{
|
||||
UIMessageBox.Show("Remove all metadata consumption records".Translate(), "NoMetadataConsumptionRecord".Translate(), "OK".Translate(), UIMessageBox.INFO);
|
||||
UIMessageBox.Show(Localization.RemoveAllMetadataConsumptionRecords.Translate(), Localization.NoMetadataConsumptionRecord.Translate(), Localization.OK.Translate(), UIMessageBox.INFO);
|
||||
return;
|
||||
}
|
||||
var msg = "ClearAllMetadataConsumptionDetails".Translate();
|
||||
for (var i = 0; i < 6; i++)
|
||||
var msg = Localization.ClearAllMetadataConsumptionDetails.Translate();
|
||||
for (var i = 0; i < itemCnt.Length; i++)
|
||||
{
|
||||
if (itemCnt[i] > 0)
|
||||
{
|
||||
msg += $"\n {LDB.items.Select(i + 6001).propertyName} x{itemCnt[i]}";
|
||||
msg += $"\n {LDB.items.Select(i + ItemIds.HydrogenFuelRod).propertyName} x{itemCnt[i]}";
|
||||
}
|
||||
}
|
||||
UIMessageBox.Show("Remove all metadata consumption records".Translate(), msg, "取消".Translate(), "确定".Translate(), UIMessageBox.QUESTION, null, () =>
|
||||
UIMessageBox.Show(Localization.RemoveAllMetadataConsumptionRecords.Translate(), msg, Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () =>
|
||||
{
|
||||
foreach (var data in propertySystem.propertyDatas)
|
||||
{
|
||||
@@ -138,41 +121,41 @@ public static class PlayerFunctions
|
||||
var propertySystem = DSPGame.propertySystem;
|
||||
if (propertySystem == null) return;
|
||||
PurgePropertySystem(propertySystem);
|
||||
var itemCnt = new int[6];
|
||||
var itemCnt = new int[ItemIds.Metaverse - ItemIds.HydrogenFuelRod + 1];
|
||||
var seedKey = DSPGame.GameDesc.seedKey64;
|
||||
var clusterPropertyData = propertySystem.propertyDatas.FirstOrDefault(cpd => cpd.seedKey == seedKey);
|
||||
if (clusterPropertyData == null)
|
||||
{
|
||||
UIMessageBox.Show("Remove metadata consumption record in current game".Translate(), "NoMetadataConsumptionRecord".Translate(), "OK".Translate(), UIMessageBox.INFO);
|
||||
UIMessageBox.Show(Localization.RemoveMetadataConsumptionRecordInCurrentGame.Translate(), Localization.NoMetadataConsumptionRecord.Translate(), Localization.OK.Translate(), UIMessageBox.INFO);
|
||||
return;
|
||||
}
|
||||
var currentGamePropertyData = GameMain.data.history.propertyData;
|
||||
foreach (var cons in currentGamePropertyData.totalConsumption.Where(cons => cons.id is >= 6001 and <= 6006))
|
||||
foreach (var cons in currentGamePropertyData.totalConsumption.Where(cons => cons.id is >= ItemIds.HydrogenFuelRod and <= ItemIds.Metaverse))
|
||||
{
|
||||
itemCnt[cons.id - 6001] += cons.count;
|
||||
itemCnt[cons.id - ItemIds.HydrogenFuelRod] += cons.count;
|
||||
}
|
||||
|
||||
if (itemCnt.All(cnt => cnt == 0))
|
||||
{
|
||||
UIMessageBox.Show("Remove metadata consumption record in current game".Translate(), "NoMetadataConsumptionRecord".Translate(), "OK".Translate(), UIMessageBox.INFO);
|
||||
UIMessageBox.Show(Localization.RemoveMetadataConsumptionRecordInCurrentGame.Translate(), Localization.NoMetadataConsumptionRecord.Translate(), Localization.OK.Translate(), UIMessageBox.INFO);
|
||||
return;
|
||||
}
|
||||
var msg = "ClearCurrentMetadataConsumptionDetails".Translate();
|
||||
for (var i = 0; i < 6; i++)
|
||||
var msg = Localization.ClearCurrentMetadataConsumptionDetails.Translate();
|
||||
for (var i = 0; i < itemCnt.Length; i++)
|
||||
{
|
||||
if (itemCnt[i] > 0)
|
||||
{
|
||||
msg += $"\n {LDB.items.Select(i + 6001).propertyName} x{itemCnt[i]}";
|
||||
msg += $"\n {LDB.items.Select(i + ItemIds.HydrogenFuelRod).propertyName} x{itemCnt[i]}";
|
||||
}
|
||||
}
|
||||
UIMessageBox.Show("Remove metadata consumption record in current game".Translate(), msg, "取消".Translate(), "确定".Translate(), UIMessageBox.QUESTION, null, () =>
|
||||
UIMessageBox.Show(Localization.RemoveMetadataConsumptionRecordInCurrentGame.Translate(), msg, Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () =>
|
||||
{
|
||||
for (var i = 0; i < clusterPropertyData.totalConsumption.Count; i++)
|
||||
{
|
||||
if (clusterPropertyData.totalConsumption[i].count == 0) continue;
|
||||
var id = clusterPropertyData.totalConsumption[i].id;
|
||||
if (id < 6001 || id > 6006) continue;
|
||||
var currentGameCount = itemCnt[id - 6001];
|
||||
if (id < ItemIds.HydrogenFuelRod || id > ItemIds.Metaverse) continue;
|
||||
var currentGameCount = itemCnt[id - ItemIds.HydrogenFuelRod];
|
||||
if (currentGameCount == 0) continue;
|
||||
var totalCount = clusterPropertyData.totalConsumption[i].count;
|
||||
clusterPropertyData.totalConsumption[i] = new IDCNT(id, totalCount > currentGameCount ? totalCount - currentGameCount : 0);
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
using UXAssist.Common;
|
||||
|
||||
namespace CheatEnabler;
|
||||
|
||||
public static class Localization
|
||||
{
|
||||
public const string CheatEnabler = "CheatEnabler";
|
||||
public const string YouAreNotInAnySystem = "You are not in any system.";
|
||||
public const string ThereIsNoDysonSphereShellOn0 = "There is no Dyson Sphere shell on \"{0}\".";
|
||||
public const string ThereIsNoDysonSphereDataOn0 = "There is no Dyson Sphere data on \"{0}\".";
|
||||
public const string ThisWillCompleteAllDysonSphereShellsOn0InstantlyAreYouSure = "This will complete all Dyson Sphere shells on \"{0}\". Are you sure?";
|
||||
public const string ThisWillRemoveAllFramesOn0AreYouSure = "This will remove all frames on \"{0}\". Are you sure?";
|
||||
public const string NoPrecalculatedShellFoundForRadius0 = "No precalculated shell found for radius {0}.";
|
||||
public const string ClearAllMetadataConsumptionDetails = "ClearAllMetadataConsumptionDetails";
|
||||
public const string ClearCurrentMetadataConsumptionDetails = "ClearCurrentMetadataConsumptionDetails";
|
||||
public const string NoMetadataConsumptionRecord = "NoMetadataConsumptionRecord";
|
||||
public const string KEYToggleNoCondition = "KEYToggleNoCondition";
|
||||
public const string KEYToggleNoCollision = "KEYToggleNoCollision";
|
||||
public const string NoConditionOn = "NoConditionOn";
|
||||
public const string NoConditionOff = "NoConditionOff";
|
||||
public const string NoCollisionOn = "NoCollisionOn";
|
||||
public const string NoCollisionOff = "NoCollisionOff";
|
||||
public const string BuildWithoutConditionIsEnabled = "Build without condition is enabled!";
|
||||
public const string NoCollisionIsEnabled = "No collision is enabled!";
|
||||
public const string Factory = "Factory";
|
||||
public const string Planet = "Planet";
|
||||
public const string MechaCombat = "Mecha/Combat";
|
||||
public const string Cancel = "Cancel";
|
||||
public const string OK = "OK";
|
||||
public const string BuryAllVeins = "Bury all veins";
|
||||
public const string RestoreBuriedVeins = "Restore buried veins";
|
||||
public const string ReformEntirePlanet = "Reform entire planet";
|
||||
public const string RevertPlanetTerrain = "Revert planet terrain";
|
||||
public const string EnableDevShortcuts = "Enable Dev Shortcuts";
|
||||
public const string DisableAbnormalChecks = "Disable Abnormal Checks";
|
||||
public const string Hotkey = "Hotkey";
|
||||
public const string UnlockTechWithKeyModifiers = "Unlock Tech with Key-Modifiers";
|
||||
public const string UnlockDowngradeTechWithKeyModifiers = "Quickly upgrade/downgrade tech with key-modifiers";
|
||||
public const string TechDowngradeModeOn = "Tech downgrade mode ON!";
|
||||
public const string TechDowngradeModeOff = "Tech downgrade mode OFF!";
|
||||
public const string TechDowngradeModeWarning = "!!Tech downgrade mode is ON!!";
|
||||
public const string TechModifierHelpBody = """
|
||||
Click a tech on the tree while holding:
|
||||
Shift: Tech level + 1
|
||||
Ctrl: Tech level + 10
|
||||
Ctrl + Shift: Tech level + 100
|
||||
Alt: Tech level to MAX
|
||||
|
||||
Note: all direct prerequisites will be unlocked as well.
|
||||
|
||||
Press Caps Lock to toggle Tech Downgrade Mode: the key-modifiers above then decrease tech levels and revert the corresponding upgrade values.
|
||||
Shift: Tech level - 1
|
||||
Ctrl: Tech level - 10
|
||||
Ctrl + Shift: Tech level - 100
|
||||
Alt: revert to locked (level 0)
|
||||
(Shift+Alt and Ctrl+Alt do nothing)
|
||||
|
||||
The features above come from the mod: CheatEnabler
|
||||
""";
|
||||
public const string PackageResizeSkippedOccupiedCells = "Package resize skipped: occupied cells would be removed";
|
||||
public const string TechDowngradeDeliveryOccupied = "Cannot downgrade tech: empty the delivery slots being removed and wait for deliveries to finish";
|
||||
public const string TechDowngradeDronesBusy = "Cannot downgrade tech: wait for construction drones to return";
|
||||
public const string TechDowngradeFleetsOccupied = "Cannot downgrade tech: recall and empty the fleets being removed";
|
||||
public const string TechDowngradeUnsupportedFunction = "Cannot downgrade tech: an unsupported tech function requires a mod update";
|
||||
public const string DevShortcuts = "Dev Shortcuts";
|
||||
public const string DevShortcutsTips = "Dev Shortcuts Tips";
|
||||
public const string UnlockTechWithKeyModifiersTips = "Unlock Tech with Key-Modifiers Tips";
|
||||
public const string RemoveAllMetadataConsumptionRecords = "Remove all metadata consumption records";
|
||||
public const string RemoveMetadataConsumptionRecordInCurrentGame = "Remove metadata consumption record in current game";
|
||||
public const string ClearMetadataFlagWhichBansAchievements = "Clear metadata flag which bans achievements";
|
||||
public const string AssignGamesaveToCurrentAccount = "Assign gamesave to current account";
|
||||
public const string FinishBuildImmediately = "Finish build immediately";
|
||||
public const string ArchitectMode = "Architect mode";
|
||||
public const string BuildWithoutCondition = "Build without condition";
|
||||
public const string NoCollision = "No collision";
|
||||
public const string BeltSignalGenerator = "Belt signal generator";
|
||||
public const string CountProliferatorsUsedForRawsIntermediatesAndFinishedProducts = "Count proliferators used for raws/intermediates and finished products";
|
||||
public const string CountProliferatorsUsedForRawsIntermediatesAndFinishedProductsTips = "Count proliferators used for raws/intermediates and finished products tips";
|
||||
public const string BeltSignalAltFormat = "Belt signal alt format";
|
||||
public const string BeltSignalAltFormatTips = "Belt signal alt format tips";
|
||||
public const string CountGenerationsAsProductionInStatistics = "Count generations as production in statistics";
|
||||
public const string CountRemovalsAsConsumptionInStatistics = "Count removals as consumption in statistics";
|
||||
public const string CountAllRawsAndIntermediatesInStatistics = "Count all raws and intermediates in statistics";
|
||||
public const string RemovePowerSpaceLimit = "Remove power space limit";
|
||||
public const string BoostWindPower = "Boost wind power";
|
||||
public const string BoostSolarPower = "Boost solar power";
|
||||
public const string BoostFuelPower = "Boost fuel power";
|
||||
public const string BoostFuelPower2 = "Boost fuel power 2";
|
||||
public const string WindTurbinesDoGlobalPowerCoverage = "Wind Turbines do global power coverage";
|
||||
public const string BoostGeothermalPower = "Boost geothermal power";
|
||||
public const string RetrievePlaceItemsFromToRemotePlanetsOnLogisticsControlPanel = "Retrieve/Place items from/to remote planets on logistics control panel";
|
||||
public const string InfiniteNaturalResources = "Infinite Natural Resources";
|
||||
public const string FastMining = "Fast Mining";
|
||||
public const string PumpAnywhere = "Pump Anywhere";
|
||||
public const string SkipBulletPeriod = "Skip bullet period";
|
||||
public const string FireAllBulletsAtOnce = "Fire all bullets at once";
|
||||
public const string SkipAbsorptionPeriod = "Skip absorption period";
|
||||
public const string QuickAbsorb = "Quick absorb";
|
||||
public const string EjectAnyway = "Eject anyway";
|
||||
public const string OverclockEjectors = "Overclock Ejectors";
|
||||
public const string OverclockSilos = "Overclock Silos";
|
||||
public const string UnlockDysonSphereMaxOrbitRadius = "Unlock Dyson Sphere max orbit radius";
|
||||
public const string CompleteDysonSphereShellsInstantly = "Complete Dyson Sphere shells instantly";
|
||||
public const string RemoveAllFramesOnDysonSphere = "Remove all frames on Dyson Sphere";
|
||||
public const string GenerateIllegalDysonShell = "Generate illegal dyson shell";
|
||||
public const string GenerateIllegalDysonShell2 = "Generate illegal dyson shell 2";
|
||||
public const string KeepMaxProductionShellsAndRemoveOthers = "Keep max production shells and remove others";
|
||||
public const string DuplicateShellsFromThatWithHighestProduction = "Duplicate shells from that with highest production";
|
||||
public const string GenerateIllegalDysonShellQuickly = "Generate illegal dyson shell quickly";
|
||||
public const string ShellsCount = "Shells count";
|
||||
public const string WARNINGThisOperationCanBeVerySlowContinue = "WARNING: This operation can be very slow, continue?";
|
||||
public const string WARNINGThisOperationIsDANGEROUSContinue = "WARNING: This operation is DANGEROUS, continue?";
|
||||
public const string TerraformWithoutEnoughSoilPiles = "Terraform without enough soil piles";
|
||||
public const string InstantHandCraft = "Instant hand-craft";
|
||||
public const string InstantTeleportLikeThatInSandboxMode = "Instant teleport (like that in Sandbox mode)";
|
||||
public const string MechaAndDronesFleetsInvicible = "Mecha and Drones/Fleets invicible";
|
||||
public const string BuildingsInvicible = "Buildings invicible";
|
||||
public const string EnableWarpWithoutSpaceWarpers = "Enable warp without space warpers";
|
||||
public const string TeleportToOuterSpace = "Teleport to outer space";
|
||||
public const string TeleportToSelectedAstronomical = "Teleport to selected astronomical";
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
I18N.Add(CheatEnabler, "CheatEnabler", "作弊器");
|
||||
I18N.Add(YouAreNotInAnySystem, "You are not in any system.", "你不在任何星系中");
|
||||
I18N.Add(ThereIsNoDysonSphereShellOn0, "There is no Dyson Sphere shell on \"{0}\".", "“{0}”上没有可建造的戴森壳");
|
||||
I18N.Add(ThereIsNoDysonSphereDataOn0, "There is no Dyson Sphere data on \"{0}\".", "“{0}”上没有戴森球数据");
|
||||
I18N.Add(ThisWillCompleteAllDysonSphereShellsOn0InstantlyAreYouSure, "This will complete all Dyson Sphere shells on \"{0}\". Are you sure?", "这将完成“{0}”上的所有戴森壳。你确定吗?");
|
||||
I18N.Add(ThisWillRemoveAllFramesOn0AreYouSure, "This will remove all frames on \"{0}\". Are you sure?", "这将移除“{0}”上的所有框架。你确定吗?");
|
||||
I18N.Add(NoPrecalculatedShellFoundForRadius0, "No precalculated shell found for radius {0}.", "没有找到适合半径 {0} 的预计算壳面");
|
||||
I18N.Add(ClearAllMetadataConsumptionDetails, """
|
||||
|
||||
Metadata consumption records of all gamesaves are about to be cleared.
|
||||
You will gain following metadata back:
|
||||
|
||||
""", """
|
||||
|
||||
所有存档的元数据消耗记录即将被清除,
|
||||
此操作将返还以下元数据:
|
||||
|
||||
""");
|
||||
I18N.Add(ClearCurrentMetadataConsumptionDetails, """
|
||||
|
||||
Metadata consumption records of current gamesave are about to be cleared.
|
||||
You will gain following metadata back:
|
||||
|
||||
""", """
|
||||
|
||||
当前存档的元数据消耗记录即将被清除,
|
||||
此操作将返还以下元数据:
|
||||
|
||||
""");
|
||||
I18N.Add(NoMetadataConsumptionRecord, "No metadata consumption records found.", "未找到元数据消耗记录。");
|
||||
I18N.Add(KEYToggleNoCondition, "[CE] Toggle No Condition Build", "[CE] 切换无条件建造");
|
||||
I18N.Add(KEYToggleNoCollision, "[CE] Toggle No Collision", "[CE] 切换无碰撞");
|
||||
I18N.Add(NoConditionOn, "No condition build is enabled!", "无条件建造已开启");
|
||||
I18N.Add(NoConditionOff, "No condition build is disabled!", "无条件建造已关闭");
|
||||
I18N.Add(NoCollisionOn, "No collision is enabled!", "无碰撞已开启");
|
||||
I18N.Add(NoCollisionOff, "No collision is disabled!", "无碰撞已关闭");
|
||||
I18N.Add(BuildWithoutConditionIsEnabled, "!!Build without condition is enabled!!", "!!无条件建造已开启!!");
|
||||
I18N.Add(NoCollisionIsEnabled, "!!No collision is enabled!!", "!!无碰撞已开启!!");
|
||||
I18N.Add(Factory, "Factory", "工厂");
|
||||
I18N.Add(Planet, "Planet", "行星");
|
||||
I18N.Add(MechaCombat, "Mecha/Combat", "机甲/战斗");
|
||||
I18N.Add(Cancel, "Cancel", "取消");
|
||||
I18N.Add(OK, "OK", "确定");
|
||||
I18N.Add(BuryAllVeins, "Bury all veins", "掩埋所有矿脉");
|
||||
I18N.Add(RestoreBuriedVeins, "Restore buried veins", "还原所有矿脉");
|
||||
I18N.Add(ReformEntirePlanet, "Reform entire planet", "铺满星球地基");
|
||||
I18N.Add(RevertPlanetTerrain, "Revert planet terrain", "还原星球地形");
|
||||
I18N.Add(EnableDevShortcuts, "Enable Dev Shortcuts", "开发模式快捷键");
|
||||
I18N.Add(DisableAbnormalChecks, "Disable Abnormal Checks", "关闭数据异常检查");
|
||||
I18N.Add(Hotkey, "Hotkey", "快捷键");
|
||||
I18N.Add(UnlockTechWithKeyModifiers, "Unlock Tech with Key-Modifiers", "使用组合键点击解锁科技");
|
||||
I18N.Add(UnlockDowngradeTechWithKeyModifiers, "Quickly upgrade/downgrade tech with key-modifiers", "使用组合键快速升降级科技");
|
||||
I18N.Add(TechDowngradeModeOn, "Tech downgrade mode ON!", "科技降级模式已开启!");
|
||||
I18N.Add(TechDowngradeModeOff, "Tech downgrade mode OFF!", "科技降级模式已关闭!");
|
||||
I18N.Add(TechDowngradeModeWarning, "!!Tech downgrade mode is ON!!", "!!科技降级模式已开启!!");
|
||||
I18N.Add(TechModifierHelpBody, """
|
||||
Click a tech on the tree while holding:
|
||||
Shift: Tech level + 1
|
||||
Ctrl: Tech level + 10
|
||||
Ctrl + Shift: Tech level + 100
|
||||
Alt: Tech level to MAX
|
||||
|
||||
Note: all direct prerequisites will be unlocked as well.
|
||||
|
||||
Press Caps Lock to toggle Tech Downgrade Mode: the key-modifiers above then decrease tech levels and revert the corresponding upgrade values.
|
||||
Shift: Tech level - 1
|
||||
Ctrl: Tech level - 10
|
||||
Ctrl + Shift: Tech level - 100
|
||||
Alt: revert to locked (level 0)
|
||||
(Shift+Alt and Ctrl+Alt do nothing)
|
||||
|
||||
The features above come from the mod: CheatEnabler
|
||||
""", """
|
||||
按住以下组合键点击科技树:
|
||||
Shift:科技等级 +1
|
||||
Ctrl:科技等级 +10
|
||||
Ctrl + Shift:科技等级 +100
|
||||
Alt:科技等级升到最大
|
||||
|
||||
注意:所有直接前置科技也会被解锁。
|
||||
|
||||
按 Caps Lock 开启/关闭科技降级模式:开启后上述组合键变为降低科技等级,并回退对应升级数值。
|
||||
Shift:科技等级 -1
|
||||
Ctrl:科技等级 -10
|
||||
Ctrl + Shift:科技等级 -100
|
||||
Alt:直接回退到未解锁(0 级,锁定)
|
||||
(Shift+Alt 与 Ctrl+Alt 无效果)
|
||||
|
||||
以上功能来源于MOD:CheatEnabler
|
||||
""");
|
||||
I18N.Add(PackageResizeSkippedOccupiedCells,
|
||||
"Cannot downgrade tech: empty the inventory cells being removed and retry",
|
||||
"无法降级科技:请先清空缩容将移除的机舱格子,再重试");
|
||||
I18N.Add(TechDowngradeDeliveryOccupied, TechDowngradeDeliveryOccupied,
|
||||
"无法降级科技:请先清空缩容将移除的物流清单格子,并等待配送完成");
|
||||
I18N.Add(TechDowngradeDronesBusy, TechDowngradeDronesBusy,
|
||||
"无法降级科技:请等待建设无人机返回");
|
||||
I18N.Add(TechDowngradeFleetsOccupied, TechDowngradeFleetsOccupied,
|
||||
"无法降级科技:请先召回并清空缩容将移除的编队");
|
||||
I18N.Add(TechDowngradeUnsupportedFunction, TechDowngradeUnsupportedFunction,
|
||||
"无法降级科技:存在尚未支持的科技效果,请更新 MOD 后重试");
|
||||
I18N.Add(DevShortcuts, "Dev Shortcuts", "开发模式快捷键");
|
||||
I18N.Add(DevShortcutsTips, """
|
||||
Caution: Some function may trigger abnormal check!
|
||||
Numpad 1: Gets all items and extends bag.
|
||||
Numpad 2: Boosts walk speed, gathering speed and mecha energy restoration.
|
||||
Numpad 3: Fills planet with foundations and bury all veins.
|
||||
Numpad 4: +1 construction drone.
|
||||
Numpad 5: Upgrades drone engine tech to full.
|
||||
Numpad 6: Unlocks researching tech.
|
||||
Numpad 7: Unlocks Drive Engine 1.
|
||||
Numpad 8: Unlocks Drive Engine 2 and maximize energy.
|
||||
Numpad 9: Unlocks ability to warp.
|
||||
Numpad 0: No costs for Logistic Storages' output.
|
||||
LCtrl + T: Unlocks all techs (not upgrades).
|
||||
LCtrl + Q: Adds 10000 to every metadata.
|
||||
LCtrl + W: Enters Sandbox Mode.
|
||||
LCtrl + Shift + W: Leaves Sandbox Mode.
|
||||
Numpad *: Proliferates items on hand.
|
||||
Numpad /: Removes proliferations from items on hand.
|
||||
PageDown: Remembers Pose of game camera.
|
||||
PageUp: Locks game camera using remembered Pose.
|
||||
""", """
|
||||
警告:某些功能可能触发异常检查!
|
||||
小键盘1:获得所有物品并扩展背包
|
||||
小键盘2:加快行走速度及采集速度,加快能量恢复速度
|
||||
小键盘3:将地基铺设整个星球并掩埋所有矿物
|
||||
小键盘4:建设机器人 +1
|
||||
小键盘5:建设机器人满级
|
||||
小键盘6:解锁当前科技
|
||||
小键盘7:解锁驱动技术I
|
||||
小键盘8:解锁驱动技术II 最大化能量
|
||||
小键盘9:机甲曲速解锁
|
||||
小键盘0:物流站通过传送带出物品无消耗
|
||||
左Ctrl + T:解锁所有非升级科技
|
||||
左Ctrl + Q:增加各项元数据10000点
|
||||
左Ctrl + W:进入沙盒模式
|
||||
左Ctrl + Shift + W:离开沙盒模式
|
||||
小键盘乘号 *:给手上物品喷涂增产剂
|
||||
小键盘除号 /:清除手上物品的增产剂
|
||||
PageDown:记录摄像机当前的Pose
|
||||
PageUp:用记录的Pose锁定摄像机
|
||||
""");
|
||||
I18N.Add(UnlockTechWithKeyModifiersTips, """
|
||||
Click tech on tree while holding:
|
||||
Shift: Tech level + 1
|
||||
Ctrl: Tech level + 10
|
||||
Ctrl + Shift: Tech level + 100
|
||||
Alt: Tech level to MAX
|
||||
|
||||
Note: all direct prerequisites will be unlocked as well.
|
||||
""", """
|
||||
按住以下组合键点击科技树:
|
||||
Shift:科技等级+1
|
||||
Ctrl:科技等级+10
|
||||
Ctrl+Shift:科技等级+100
|
||||
Alt:科技等级升到最大
|
||||
|
||||
注意:所有直接前置科技也会被解锁
|
||||
""");
|
||||
I18N.Add(RemoveAllMetadataConsumptionRecords, "Remove all metadata consumption records", "移除所有元数据消耗记录");
|
||||
I18N.Add(RemoveMetadataConsumptionRecordInCurrentGame, "Remove metadata consumption record in current game", "移除当前存档的元数据消耗记录");
|
||||
I18N.Add(ClearMetadataFlagWhichBansAchievements, "Clear metadata flag which bans achievements in current game", "解除当前存档因使用元数据导致的成就限制");
|
||||
I18N.Add(AssignGamesaveToCurrentAccount, "Assign gamesave to current account", "将游戏存档绑定给当前账号");
|
||||
I18N.Add(FinishBuildImmediately, "Finish build immediately", "建造秒完成");
|
||||
I18N.Add(ArchitectMode, "Architect mode", "建筑师模式");
|
||||
I18N.Add(BuildWithoutCondition, "Build without condition check", "无条件建造");
|
||||
I18N.Add(NoCollision, "No collision", "无碰撞");
|
||||
I18N.Add(BeltSignalGenerator, "Belt signal generator", "传送带信号物品生成");
|
||||
I18N.Add(CountProliferatorsUsedForRawsIntermediatesAndFinishedProducts, "Use proliferators for raws/intermediates and finished products", "原料、中间产物以及成品使用增产剂");
|
||||
I18N.Add(CountProliferatorsUsedForRawsIntermediatesAndFinishedProductsTips, """
|
||||
Following items use extra products: Titanium Alloy, Prism, Frame Material, Proliferator Mk.II, Proliferator Mk.III, Magnetic Coil, Electric Motor, Electromagnetic Turbine, Super-magnetic Ring, Circuit Board, Thruster, Reinforced Thruster, Plasma Exciter, Particle Broadband, Graviton Lens, Quantum Chip, Annihilation Constraint Sphere, Deuteron Fuel Rod, Space Warper, Dyson Sphere Component, Small Carrier Rocket, Electromagnetic Matrix, Structure Matrix, Information Matrix, Gravity Matrix, Universe Matrix
|
||||
Following items does not use proliferators: Casimir Crystal, Energy Matrix
|
||||
Other items use speed up production.
|
||||
""", """
|
||||
以下物品使用额外产出: 钛合金, 棱镜, 框架材料, 增产剂 Mk.II, 增产剂 Mk.III, 磁线圈, 电动机, 电磁涡轮, 超级磁场环, 电路板, 推进器, 加力推进器, 电浆激发器, 粒子宽带, 引力透镜, 量子芯片, 湮灭约束球, 氘核燃料棒, 空间翘曲器, 戴森球组件, 小型运载火箭, 电磁矩阵, 结构矩阵, 信息矩阵, 引力矩阵, 宇宙矩阵
|
||||
以下物品不使用增产剂: 卡西米尔晶体, 能量矩阵
|
||||
其他物品使用加速生产
|
||||
""");
|
||||
I18N.Add(BeltSignalAltFormat, "Belt signal alt format", "传送带信号替换格式");
|
||||
I18N.Add(BeltSignalAltFormatTips, """
|
||||
Belt signal number format alternative format:
|
||||
AAAABC by default
|
||||
BCAAAA as alternative
|
||||
AAAA=generation speed in minutes, B=proliferate points, C=stack count
|
||||
""", """
|
||||
传送带信号物品生成数量格式:
|
||||
默认为AAAABC
|
||||
勾选替换为BCAAAA
|
||||
AAAA=生成速度,B=增产点数,C=堆叠数量
|
||||
""");
|
||||
I18N.Add(CountGenerationsAsProductionInStatistics, "Count generations as production in statistics", "统计信息里将生成计算为产物");
|
||||
I18N.Add(CountRemovalsAsConsumptionInStatistics, "Count removals as consumption in statistics", "统计信息里将移除计算为消耗");
|
||||
I18N.Add(CountAllRawsAndIntermediatesInStatistics, "Count all raw materials in statistics", "统计信息里计算所有原料和中间产物");
|
||||
I18N.Add(RemovePowerSpaceLimit, "Remove space limit for winds and geothermals", "移除风力发电和地热发电的间距限制");
|
||||
I18N.Add(BoostWindPower, "Boost wind power(x100,000)", "提升风力发电(x100,000)");
|
||||
I18N.Add(BoostSolarPower, "Boost solar power(x100,000)", "提升太阳能发电(x100,000)");
|
||||
I18N.Add(BoostFuelPower, "Boost fuel power(x50,000)", "提升燃料发电(x50,000)");
|
||||
I18N.Add(BoostFuelPower2, "(x20,000 for deuteron, x10,000 for antimatter)", "(氘核燃料棒x20,000,反物质燃料棒x10,000)");
|
||||
I18N.Add(WindTurbinesDoGlobalPowerCoverage, "Wind Turbines do global power coverage", "风力涡轮机供电覆盖全球");
|
||||
I18N.Add(BoostGeothermalPower, "Boost geothermal power(x50,000)", "提升地热发电(x50,000)");
|
||||
I18N.Add(RetrievePlaceItemsFromToRemotePlanetsOnLogisticsControlPanel, "Retrieve/Place items from/to remote planets on logistics control panel", "在物流总控面板上可以从非本地行星取放物品");
|
||||
I18N.Add(InfiniteNaturalResources, "Infinite natural resources", "自然资源采集不消耗");
|
||||
I18N.Add(FastMining, "Fast mining", "高速采集");
|
||||
I18N.Add(PumpAnywhere, "Pump anywhere", "平地抽水");
|
||||
I18N.Add(SkipBulletPeriod, "Skip bullet period", "跳过子弹阶段");
|
||||
I18N.Add(FireAllBulletsAtOnce, "Fire all bullets at once", "一次弹射所有太阳帆");
|
||||
I18N.Add(SkipAbsorptionPeriod, "Skip absorption period", "跳过吸收阶段");
|
||||
I18N.Add(QuickAbsorb, "Quick absorb", "快速吸收");
|
||||
I18N.Add(EjectAnyway, "Eject anyway", "全球弹射");
|
||||
I18N.Add(OverclockEjectors, "Overclock Ejectors (10x)", "高速弹射器(10倍射速)");
|
||||
I18N.Add(OverclockSilos, "Overclock Silos (10x)", "高速发射井(10倍射速)");
|
||||
I18N.Add(UnlockDysonSphereMaxOrbitRadius, "Unlock Dyson Sphere max orbit radius", "解锁戴森球最大轨道半径");
|
||||
I18N.Add(CompleteDysonSphereShellsInstantly, "Complete Dyson Sphere shells instantly", "立即完成戴森壳建造");
|
||||
I18N.Add(RemoveAllFramesOnDysonSphere, "Remove all frames on Dyson Sphere", "移除戴森球上的所有框架");
|
||||
I18N.Add(GenerateIllegalDysonShell, "Generate an illegal dyson shell (!!1st shell layer will be replaced!!)", "生成单层仙术戴森壳(!!会先删除第一层戴森壳!!)");
|
||||
I18N.Add(GenerateIllegalDysonShell2, "Generate illegal dyson shells for all layers without nodes and shells", "为所有没有节点和壳的层级生成仙术戴森壳");
|
||||
I18N.Add(KeepMaxProductionShellsAndRemoveOthers, "Keep max production shells and remove others", "保留发电量最高的戴森壳并移除其他戴森壳");
|
||||
I18N.Add(DuplicateShellsFromThatWithHighestProduction, "Duplicate shells from that with highest production", "从发电量最高的壳复制戴森壳");
|
||||
I18N.Add(GenerateIllegalDysonShellQuickly, "Generate illegal dyson shell quickly", "快速生成仙术戴森壳");
|
||||
I18N.Add(ShellsCount, "Shells count", "壳面数量");
|
||||
I18N.Add(WARNINGThisOperationCanBeVerySlowContinue, "WARNING: This operation can be very slow, continue?", "警告:此操作可能非常慢,继续吗?");
|
||||
I18N.Add(WARNINGThisOperationIsDANGEROUSContinue, "WARNING: This operation is DANGEROUS, continue?", "警告:此操作非常危险,继续吗?");
|
||||
I18N.Add(TerraformWithoutEnoughSoilPiles, "Terraform without enough soil piles", "沙土不够时依然可以整改地形");
|
||||
I18N.Add(InstantHandCraft, "Instant hand-craft", "快速手动制造");
|
||||
I18N.Add(InstantTeleportLikeThatInSandboxMode, "Instant teleport (like that in Sandbox mode)", "快速传送(和沙盒模式一样)");
|
||||
I18N.Add(MechaAndDronesFleetsInvicible, "Mecha and Drones/Fleets invicible", "机甲和战斗无人机无敌");
|
||||
I18N.Add(BuildingsInvicible, "Buildings invincible", "建筑无敌");
|
||||
I18N.Add(EnableWarpWithoutSpaceWarpers, "Enable warp without space warpers", "无需空间翘曲器即可曲速飞行");
|
||||
I18N.Add(TeleportToOuterSpace, "Teleport to outer space", "传送到外太空");
|
||||
I18N.Add(TeleportToSelectedAstronomical, "Teleport to selected astronomical", "传送到选中的天体");
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,11 @@ using System.Reflection.Emit;
|
||||
using BepInEx.Configuration;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
|
||||
namespace CheatEnabler.Patches;
|
||||
|
||||
[ModFeature("Combat")]
|
||||
public static class CombatPatch
|
||||
{
|
||||
public static ConfigEntry<bool> MechaInvincibleEnabled;
|
||||
@@ -32,6 +34,9 @@ public static class CombatPatch
|
||||
|
||||
private class MechaInvincible : PatchImpl<MechaInvincible>
|
||||
{
|
||||
// Harmony transpiler: Player_get_invincible_Transpiler
|
||||
// Target: Player.invincible (getter)
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(Player), nameof(Player.invincible), MethodType.Getter)]
|
||||
private static IEnumerable<CodeInstruction> Player_get_invincible_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -43,7 +48,9 @@ public static class CombatPatch
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
// Harmony transpiler: SkillSystem_DamageObject_Transpiler
|
||||
// Target: SkillSystem.DamageGroundObjectByLocalCaster, SkillSystem.DamageGroundObjectByRemoteCaster, SkillSystem.DamageObject
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByLocalCaster))]
|
||||
[HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByRemoteCaster))]
|
||||
@@ -67,6 +74,9 @@ public static class CombatPatch
|
||||
|
||||
private class BuildingsInvincible : PatchImpl<BuildingsInvincible>
|
||||
{
|
||||
// Harmony transpiler: SkillSystem_DamageObject_Transpiler
|
||||
// Target: SkillSystem.DamageGroundObjectByLocalCaster, SkillSystem.DamageGroundObjectByRemoteCaster
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByLocalCaster))]
|
||||
[HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByRemoteCaster))]
|
||||
|
||||
@@ -4,10 +4,12 @@ using System.Reflection.Emit;
|
||||
using BepInEx.Configuration;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
using GameLogic = UXAssist.Common.GameLogic;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using GameLogicProc = UXAssist.Common.GameLogic;
|
||||
|
||||
namespace CheatEnabler.Patches;
|
||||
|
||||
[ModFeature("DysonSphere")]
|
||||
public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
{
|
||||
public static ConfigEntry<bool> SkipBulletEnabled;
|
||||
@@ -65,7 +67,9 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
// {
|
||||
// CheatEnabler.Logger.LogDebug($"[DysonShell.ImportFromBlueprint] vertCount={__instance.vertexCount}, cpPerVertex={__instance.cpPerVertex}, cpMax={__instance.cellPointMax}");
|
||||
// }
|
||||
|
||||
// Harmony transpiler: DysonNode_OrderConstructCp_Transpiler
|
||||
// Target: DysonNode.OrderConstructCp
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(DysonNode), nameof(DysonNode.OrderConstructCp))]
|
||||
private static IEnumerable<CodeInstruction> DysonNode_OrderConstructCp_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -80,7 +84,9 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
// Harmony transpiler: DysonSwarm_AbsorbSail_Transpiler
|
||||
// Target: DysonSwarm.AbsorbSail
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(DysonSwarm), nameof(DysonSwarm.AbsorbSail))]
|
||||
private static IEnumerable<CodeInstruction> DysonSwarm_AbsorbSail_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -134,12 +140,12 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
{
|
||||
UpdateSailLifeTime();
|
||||
UpdateSailsCacheForThisGame();
|
||||
GameLogic.OnGameBegin += GameMain_Begin_Postfix;
|
||||
GameLogicProc.OnGameBegin += OnGameBegin;
|
||||
}
|
||||
|
||||
protected override void OnDisable()
|
||||
{
|
||||
GameLogic.OnGameBegin -= GameMain_Begin_Postfix;
|
||||
GameLogicProc.OnGameBegin -= OnGameBegin;
|
||||
}
|
||||
|
||||
private static void UpdateSailLifeTime()
|
||||
@@ -172,7 +178,7 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
_sailsCacheCapacity[index] = capacity;
|
||||
}
|
||||
|
||||
private static void GameMain_Begin_Postfix()
|
||||
private static void OnGameBegin()
|
||||
{
|
||||
UpdateSailsCacheForThisGame();
|
||||
UpdateSailLifeTime();
|
||||
@@ -187,7 +193,9 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
UpdateSailLifeTime();
|
||||
}
|
||||
}
|
||||
|
||||
// Harmony transpiler: EjectorComponent_InternalUpdate_Transpiler
|
||||
// Target: EjectorComponent.InternalUpdate
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(EjectorComponent), nameof(EjectorComponent.InternalUpdate))]
|
||||
private static IEnumerable<CodeInstruction> EjectorComponent_InternalUpdate_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -296,7 +304,7 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(DysonSwarm), "GameTick")]
|
||||
[HarmonyPatch(typeof(DysonSwarm), nameof(DysonSwarm.GameTick))]
|
||||
public static void DysonSwarm_GameTick_Prefix(DysonSwarm __instance, long time)
|
||||
{
|
||||
var index = __instance.starData.index;
|
||||
@@ -337,6 +345,7 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
sphereProductRegister[ProductionStatistics.SOLAR_SAIL_ID] += len;
|
||||
sphereConsumeRegister[ProductionStatistics.SOLAR_SAIL_ID] += len;
|
||||
sphereProductRegister[ProductionStatistics.DYSON_CELL_ID] += len;
|
||||
__instance.dysonSphere.needRecalculatePower = true;
|
||||
return;
|
||||
}
|
||||
idx--;
|
||||
@@ -350,6 +359,7 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
sphereProductRegister[ProductionStatistics.SOLAR_SAIL_ID] += absorbCnt;
|
||||
sphereConsumeRegister[ProductionStatistics.SOLAR_SAIL_ID] += absorbCnt;
|
||||
sphereProductRegister[ProductionStatistics.DYSON_CELL_ID] += absorbCnt;
|
||||
__instance.dysonSphere.needRecalculatePower = true;
|
||||
}
|
||||
}
|
||||
for (; idx >= 0; idx--)
|
||||
@@ -363,14 +373,16 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
{
|
||||
protected override void OnEnable()
|
||||
{
|
||||
_instantAbsorb = QuickAbsorbEnabled.Value;
|
||||
_instantAbsorb = QuickAbsorbEnabled.Value && QuickAbsorbPatch.GetHarmony() != null;
|
||||
}
|
||||
|
||||
protected override void OnDisable()
|
||||
{
|
||||
_instantAbsorb = false;
|
||||
_instantAbsorb = QuickAbsorbEnabled.Value && QuickAbsorbPatch.GetHarmony() != null;
|
||||
}
|
||||
|
||||
// Harmony transpiler: DysonSwarm_AbsorbSail_Transpiler2
|
||||
// Target: DysonSwarm.AbsorbSail
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(DysonSwarm), nameof(DysonSwarm.AbsorbSail))]
|
||||
private static IEnumerable<CodeInstruction> DysonSwarm_AbsorbSail_Transpiler2(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -380,30 +392,20 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(ExpiryOrder), nameof(ExpiryOrder.index)))
|
||||
).Advance(1).RemoveInstructions(matcher.Length - matcher.Pos).Insert(
|
||||
// if (node.ConstructCp() != null)
|
||||
// {
|
||||
// this.dysonSphere.productRegister[ProductionStatistics.DYSON_CELL_ID]++;
|
||||
// }
|
||||
new CodeInstruction(OpCodes.Ldarg_1),
|
||||
new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(DysonNode), nameof(DysonNode.ConstructCp))),
|
||||
new CodeInstruction(OpCodes.Brfalse_S, label1),
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(DysonSwarm), nameof(DysonSwarm.dysonSphere))),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(DysonSphere), nameof(DysonSphere.productRegister))),
|
||||
new CodeInstruction(OpCodes.Ldc_I4, ProductionStatistics.DYSON_CELL_ID),
|
||||
new CodeInstruction(OpCodes.Ldelema, typeof(int)),
|
||||
new CodeInstruction(OpCodes.Dup),
|
||||
new CodeInstruction(OpCodes.Ldind_I4),
|
||||
new CodeInstruction(OpCodes.Ldc_I4_1),
|
||||
new CodeInstruction(OpCodes.Add),
|
||||
new CodeInstruction(OpCodes.Stind_I4),
|
||||
|
||||
// this.RemoveSolarSail(index);
|
||||
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(label1),
|
||||
new CodeInstruction(OpCodes.Ldarg_1),
|
||||
new CodeInstruction(OpCodes.Ldloc_1),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(DysonSwarm), nameof(DysonSwarm.RemoveSolarSail))),
|
||||
|
||||
// return false;
|
||||
Transpilers.EmitDelegate((DysonSwarm swarm, DysonNode node, int index) =>
|
||||
{
|
||||
if (node.ConstructCp() != null)
|
||||
{
|
||||
swarm.dysonSphere.productRegister[ProductionStatistics.DYSON_CELL_ID]++;
|
||||
swarm.dysonSphere.needRecalculatePower = true;
|
||||
}
|
||||
swarm.RemoveSolarSail(index);
|
||||
}),
|
||||
// return true;
|
||||
// to avoid conflict with QuickAbsorbPatch
|
||||
new CodeInstruction(OpCodes.Ldc_I4_1),
|
||||
new CodeInstruction(OpCodes.Ret)
|
||||
);
|
||||
@@ -415,14 +417,16 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
{
|
||||
protected override void OnEnable()
|
||||
{
|
||||
_instantAbsorb = SkipAbsorbEnabled.Value;
|
||||
_instantAbsorb = SkipAbsorbEnabled.Value && SkipAbsorbPatch.GetHarmony() != null;
|
||||
}
|
||||
|
||||
protected override void OnDisable()
|
||||
{
|
||||
_instantAbsorb = false;
|
||||
_instantAbsorb = SkipAbsorbEnabled.Value && SkipAbsorbPatch.GetHarmony() != null;
|
||||
}
|
||||
|
||||
// Harmony transpiler: DysonSphereLayer_GameTick_Transpiler
|
||||
// Target: DysonSphereLayer.GameTick
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(DysonSphereLayer), nameof(DysonSphereLayer.GameTick))]
|
||||
private static IEnumerable<CodeInstruction> DysonSphereLayer_GameTick_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -464,6 +468,9 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
|
||||
private class EjectAnywayPatch : PatchImpl<EjectAnywayPatch>
|
||||
{
|
||||
// Harmony transpiler: EjectorComponent_InternalUpdate_Transpiler
|
||||
// Target: EjectorComponent.InternalUpdate
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(EjectorComponent), nameof(EjectorComponent.InternalUpdate))]
|
||||
private static IEnumerable<CodeInstruction> EjectorComponent_InternalUpdate_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -494,6 +501,9 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
|
||||
private class OverclockEjector : PatchImpl<OverclockEjector>
|
||||
{
|
||||
// Harmony transpiler: EjectComponent_InternalUpdate_Transpiler
|
||||
// Target: EjectorComponent.InternalUpdate
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(EjectorComponent), nameof(EjectorComponent.InternalUpdate))]
|
||||
private static IEnumerable<CodeInstruction> EjectComponent_InternalUpdate_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -516,7 +526,9 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
matcher.Start().Advance(pos).RemoveInstructions(end - pos);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
// Harmony transpiler: UIEjectAndSiloWindow__OnUpdate_Transpiler
|
||||
// Target: UIEjectorWindow._OnUpdate
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UIEjectorWindow), nameof(UIEjectorWindow._OnUpdate))]
|
||||
private static IEnumerable<CodeInstruction> UIEjectAndSiloWindow__OnUpdate_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -547,6 +559,9 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
|
||||
private class OverclockSilo : PatchImpl<OverclockSilo>
|
||||
{
|
||||
// Harmony transpiler: SiloComponent_InternalUpdate_Transpiler
|
||||
// Target: SiloComponent.InternalUpdate
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(SiloComponent), nameof(SiloComponent.InternalUpdate))]
|
||||
private static IEnumerable<CodeInstruction> SiloComponent_InternalUpdate_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -569,7 +584,9 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
matcher.Start().Advance(pos).RemoveInstructions(end - pos);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
// Harmony transpiler: UIEjectAndSiloWindow__OnUpdate_Transpiler
|
||||
// Target: UISiloWindow._OnUpdate
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UISiloWindow), nameof(UISiloWindow._OnUpdate))]
|
||||
private static IEnumerable<CodeInstruction> UIEjectAndSiloWindow__OnUpdate_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -618,7 +635,9 @@ public class DysonSpherePatch : PatchImpl<DysonSpherePatch>
|
||||
if (dysonEditor == null || !dysonEditor.gameObject.activeSelf) return;
|
||||
dysonEditor.selection?.onViewStarChange?.Invoke();
|
||||
}
|
||||
|
||||
// Harmony transpiler: MaxOrbitRadiusPatch_Transpiler
|
||||
// Target: DysonSphere.CheckLayerRadius, DysonSphere.CheckSwarmRadius, DysonSphere.QueryLayerRadius, DysonSphere.QuerySwarmRadius, UIDEAddLayerDialogue.OnViewStarChange, UIDEAddSwarmDialogue.OnViewStarChange, UIDysonEditor.OnViewStarChange, UIDESwarmOrbitInfo._OnInit, UIDysonOrbitPreview.UpdateAscNodeGizmos
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(DysonSphere), nameof(DysonSphere.CheckLayerRadius))]
|
||||
[HarmonyPatch(typeof(DysonSphere), nameof(DysonSphere.CheckSwarmRadius))]
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
using System;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.GameConstants;
|
||||
|
||||
namespace CheatEnabler.Patches.Factory;
|
||||
|
||||
[PatchSetCallbackFlag(PatchCallbackFlag.CallOnDisableAfterUnpatch)]
|
||||
internal class ArchitectMode : PatchImpl<ArchitectMode>
|
||||
{
|
||||
private const int DefaultItemCount = 999;
|
||||
private static readonly AccessTools.FieldRef<BuildTool, StorageComponent> BuildToolPackage =
|
||||
AccessTools.FieldRefAccess<BuildTool, StorageComponent>(nameof(BuildTool.tmpPackage));
|
||||
|
||||
protected override void OnEnable()
|
||||
{
|
||||
RefreshPackageStatistics();
|
||||
var factory = GameMain.mainPlayer?.factory;
|
||||
if (factory?.planet?.data != null)
|
||||
{
|
||||
global::CheatEnabler.Patches.FactoryPatch.ArrivePlanet(factory);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnDisable()
|
||||
{
|
||||
RefreshPackageStatistics();
|
||||
}
|
||||
|
||||
private static void RefreshPackageStatistics()
|
||||
{
|
||||
var player = GameMain.mainPlayer;
|
||||
if (player?.package == null) return;
|
||||
player.packageUtility?.statistics?.Count(player.package);
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(PackageStatistics), nameof(PackageStatistics.Count))]
|
||||
private static void CountPackageItemsPatch(PackageStatistics __instance)
|
||||
{
|
||||
if (__instance != GameMain.mainPlayer?.packageUtility?.statistics) return;
|
||||
var items = LDB.items?.dataArray;
|
||||
if (items == null) return;
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (item == null || !IsArchitectItem(item.ID)) continue;
|
||||
var count = __instance.itemBundle.GetCount(item.ID);
|
||||
if (count < DefaultItemCount) __instance.itemBundle.Add(item.ID, DefaultItemCount - count, 0);
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(StorageComponent), nameof(StorageComponent.TakeTailItems), [typeof(int), typeof(int), typeof(int), typeof(bool)],
|
||||
[ArgumentType.Ref, ArgumentType.Ref, ArgumentType.Out, ArgumentType.Normal])]
|
||||
public static bool TakeTailItemsPatch(StorageComponent __instance, int itemId, int count, ref int inc)
|
||||
{
|
||||
if (count <= 0 || !IsPlayerStorage(__instance) || !IsArchitectItem(itemId)) return true;
|
||||
inc = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(StorageComponent), nameof(StorageComponent.TakeTailItems), [typeof(int), typeof(int), typeof(int[]), typeof(int), typeof(bool)],
|
||||
[ArgumentType.Ref, ArgumentType.Ref, ArgumentType.Normal, ArgumentType.Out, ArgumentType.Normal])]
|
||||
private static bool TakeTailItemsWithNeedsPatch(StorageComponent __instance, int itemId, int count, int[] needs, ref int inc, ref bool __result)
|
||||
{
|
||||
if (needs == null || Array.IndexOf(needs, itemId) < 0) return true;
|
||||
if (TakeTailItemsPatch(__instance, itemId, count, ref inc)) return true;
|
||||
__result = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(PlayerPackageUtility), nameof(PlayerPackageUtility.TryTakeItemFromAllPackages))]
|
||||
private static bool TryTakeItemFromAllPackagesPatch(PlayerPackageUtility __instance, int itemId, int count, ref int inc)
|
||||
{
|
||||
if (__instance.player == null || __instance.player != GameMain.mainPlayer || count <= 0 || !IsArchitectItem(itemId)) return true;
|
||||
inc = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(PlayerPackageUtility), nameof(PlayerPackageUtility.TakeItemFromAllPackages))]
|
||||
private static bool TakeItemFromAllPackagesPatch(PlayerPackageUtility __instance, int itemId, int count, ref int inc)
|
||||
{
|
||||
return TryTakeItemFromAllPackagesPatch(__instance, itemId, count, ref inc);
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(StorageComponent), nameof(StorageComponent.GetItemCount), typeof(int))]
|
||||
public static void GetItemCountPatch(StorageComponent __instance, int itemId, ref int __result)
|
||||
{
|
||||
if (__result >= DefaultItemCount || !IsPlayerStorage(__instance) || !IsArchitectItem(itemId)) return;
|
||||
__result = DefaultItemCount;
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(StorageComponent), nameof(StorageComponent.GetItemCount), [typeof(int), typeof(int)],
|
||||
[ArgumentType.Normal, ArgumentType.Out])]
|
||||
private static void GetItemCountWithIncPatch(StorageComponent __instance, int itemId, ref int __result)
|
||||
{
|
||||
GetItemCountPatch(__instance, itemId, ref __result);
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(PlayerPackageUtility), nameof(PlayerPackageUtility.GetPackageItemCount))]
|
||||
private static void GetPackageItemCountPatch(PlayerPackageUtility __instance, int itemId, ref int __result)
|
||||
{
|
||||
if (__instance.player == null || __instance.player != GameMain.mainPlayer || __result >= DefaultItemCount || !IsArchitectItem(itemId)) return;
|
||||
__result = DefaultItemCount;
|
||||
}
|
||||
|
||||
private static bool IsPlayerStorage(StorageComponent storage)
|
||||
{
|
||||
var player = GameMain.mainPlayer;
|
||||
if (storage == null || player == null) return false;
|
||||
if (storage == player.package) return true;
|
||||
var buildTools = player.controller?.actionBuild?.tools;
|
||||
if (buildTools == null) return false;
|
||||
foreach (var buildTool in buildTools)
|
||||
{
|
||||
if (buildTool != null && storage == BuildToolPackage(buildTool)) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsArchitectItem(int itemId)
|
||||
{
|
||||
if (itemId <= 0) return false;
|
||||
if (itemId is ItemIds.LogisticsBot or ItemIds.LogisticsDrone or ItemIds.LogisticsVessel) return true;
|
||||
var item = LDB.items?.Select(itemId);
|
||||
return item != null && (item.Type == EItemType.Logistics || item.CanBuild);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,639 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using UXAssist.Production;
|
||||
using GameLogicProc = UXAssist.Common.GameLogic;
|
||||
|
||||
namespace CheatEnabler.Patches.Factory;
|
||||
|
||||
[ModFeature("BeltSignalGenerator")]
|
||||
internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
|
||||
{
|
||||
private static Dictionary<int, BeltSignal>[] _signalBelts;
|
||||
private static Dictionary<long, int> _portalFrom;
|
||||
private static Dictionary<int, HashSet<long>> _portalTo;
|
||||
private static int _signalBeltsCapacity;
|
||||
private static bool _initialized;
|
||||
private static ProductionCatalog _sourceCatalog;
|
||||
private static ProductionItem _preferredProliferator;
|
||||
private static readonly Dictionary<(int itemId, bool proliferated, bool sprayed),
|
||||
IReadOnlyList<BeltSignalSourceRate>> SourceCache = [];
|
||||
private static readonly HashSet<(int itemId, bool proliferated, bool sprayed)> FailedSources = [];
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
GameLogicProc.OnGameEnd += ResetState;
|
||||
ProductionCatalogService.Changed += OnProductionCatalogChanged;
|
||||
}
|
||||
|
||||
public static void Uninit()
|
||||
{
|
||||
GameLogicProc.OnGameEnd -= ResetState;
|
||||
ProductionCatalogService.Changed -= OnProductionCatalogChanged;
|
||||
}
|
||||
|
||||
private static void ResetState()
|
||||
{
|
||||
_initialized = false;
|
||||
_signalBelts = null;
|
||||
_portalFrom = null;
|
||||
_portalTo = null;
|
||||
_signalBeltsCapacity = 0;
|
||||
ClearSourceCache();
|
||||
}
|
||||
|
||||
private static void ClearSourceCache()
|
||||
{
|
||||
_sourceCatalog = null;
|
||||
_preferredProliferator = null;
|
||||
SourceCache.Clear();
|
||||
FailedSources.Clear();
|
||||
}
|
||||
|
||||
private class BeltSignal
|
||||
{
|
||||
public int SignalId;
|
||||
public int SpeedLimit;
|
||||
public byte Stack;
|
||||
public byte Inc;
|
||||
public int Progress;
|
||||
public BeltSignalSourceStats SourceStats;
|
||||
}
|
||||
|
||||
protected override void OnEnable()
|
||||
{
|
||||
InitSignalBelts();
|
||||
GameLogicProc.OnGameBegin += OnGameBegin;
|
||||
}
|
||||
|
||||
protected override void OnDisable()
|
||||
{
|
||||
GameLogicProc.OnGameBegin -= OnGameBegin;
|
||||
_initialized = false;
|
||||
_signalBelts = null;
|
||||
_signalBeltsCapacity = 0;
|
||||
ClearSourceCache();
|
||||
}
|
||||
|
||||
internal static void OnAltFormatChanged()
|
||||
{
|
||||
if (_signalBelts == null) return;
|
||||
var factories = GameMain.data?.factories;
|
||||
if (factories == null) return;
|
||||
var factoryCount = GameMain.data.factoryCount;
|
||||
var altFormat = FactoryPatch.BeltSignalNumberAltFormat.Value;
|
||||
for (var i = Math.Min(_signalBelts.Length, factoryCount) - 1; i >= 0; i--)
|
||||
{
|
||||
var factory = factories[i];
|
||||
var cargoTraffic = factory?.cargoTraffic;
|
||||
if (cargoTraffic == null) continue;
|
||||
var entitySignPool = factory.entitySignPool;
|
||||
if (entitySignPool == null) continue;
|
||||
var belts = _signalBelts[i];
|
||||
if (belts == null) continue;
|
||||
foreach (var pair in belts)
|
||||
{
|
||||
var beltId = pair.Key;
|
||||
ref var belt = ref cargoTraffic.beltPool[beltId];
|
||||
if (belt.id != beltId) continue;
|
||||
ref var signal = ref entitySignPool[belt.entityId];
|
||||
if (signal.iconId0 < 1000) continue;
|
||||
var signalBelt = pair.Value;
|
||||
var inc = signalBelt.Inc / signalBelt.Stack;
|
||||
if (altFormat)
|
||||
signal.count0 = signalBelt.SpeedLimit + signalBelt.Stack * 10000 + inc * 100000;
|
||||
else
|
||||
signal.count0 = signalBelt.SpeedLimit * 100 + signalBelt.Stack + inc * 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void OnUseProliferatorChanged()
|
||||
{
|
||||
ClearSourceCache();
|
||||
RefreshSourceStats(true);
|
||||
}
|
||||
|
||||
private static void OnProductionCatalogChanged()
|
||||
{
|
||||
ClearSourceCache();
|
||||
RefreshSourceStats(false);
|
||||
}
|
||||
|
||||
private static void RefreshSourceStats(bool resetGenerationProgress)
|
||||
{
|
||||
if (_signalBelts == null) return;
|
||||
if (ProductionCatalogService.Current == null)
|
||||
{
|
||||
foreach (var belts in _signalBelts)
|
||||
{
|
||||
if (belts == null) continue;
|
||||
foreach (var belt in belts.Values)
|
||||
{
|
||||
belt.SourceStats = null;
|
||||
if (resetGenerationProgress) belt.Progress = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var factories = GameMain.data?.factories;
|
||||
if (factories == null) return;
|
||||
var factoryCount = GameMain.data.factoryCount;
|
||||
for (var i = Math.Min(_signalBelts.Length, factoryCount) - 1; i >= 0; i--)
|
||||
{
|
||||
var factory = factories[i];
|
||||
var cargoTraffic = factory?.cargoTraffic;
|
||||
if (cargoTraffic == null) continue;
|
||||
var entitySignPool = factory.entitySignPool;
|
||||
if (entitySignPool == null) continue;
|
||||
var belts = _signalBelts[i];
|
||||
if (belts == null) continue;
|
||||
foreach (var pair in belts)
|
||||
{
|
||||
var beltId = pair.Key;
|
||||
ref var belt = ref cargoTraffic.beltPool[beltId];
|
||||
if (belt.id != beltId) continue;
|
||||
var signalBelt = pair.Value;
|
||||
if (resetGenerationProgress) signalBelt.Progress = 0;
|
||||
signalBelt.SourceStats = null;
|
||||
AddSourcesToBeltSignal(signalBelt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void InitSignalBelts()
|
||||
{
|
||||
if (DSPGame.IsMenuDemo) return;
|
||||
_signalBelts = new Dictionary<int, BeltSignal>[64];
|
||||
_signalBeltsCapacity = 64;
|
||||
_portalFrom = [];
|
||||
_portalTo = [];
|
||||
|
||||
var factories = GameMain.data?.factories;
|
||||
if (factories == null) return;
|
||||
foreach (var factory in factories)
|
||||
{
|
||||
var entitySignPool = factory?.entitySignPool;
|
||||
if (entitySignPool == null) continue;
|
||||
var cargoTraffic = factory.cargoTraffic;
|
||||
var beltPool = cargoTraffic.beltPool;
|
||||
for (var i = cargoTraffic.beltCursor - 1; i > 0; i--)
|
||||
{
|
||||
if (beltPool[i].id != i) continue;
|
||||
ref var signal = ref entitySignPool[beltPool[i].entityId];
|
||||
var signalId = signal.iconId0;
|
||||
if (signalId == 0U) continue;
|
||||
var number = Mathf.RoundToInt(signal.count0);
|
||||
switch (signalId)
|
||||
{
|
||||
case 404:
|
||||
SetSignalBelt(factory.index, i, (int)signalId, 0);
|
||||
continue;
|
||||
case 600:
|
||||
case >= 1000 and < 20000:
|
||||
if (number > 0)
|
||||
SetSignalBelt(factory.index, i, (int)signalId, number);
|
||||
continue;
|
||||
case >= 601 and <= 609:
|
||||
if (number > 0)
|
||||
SetSignalBeltPortalTo(factory.index, i, number);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
private static Dictionary<int, BeltSignal> GetOrCreateSignalBelts(int index)
|
||||
{
|
||||
Dictionary<int, BeltSignal> obj;
|
||||
if (index < 0) return null;
|
||||
if (index >= _signalBeltsCapacity)
|
||||
{
|
||||
var newCapacity = _signalBeltsCapacity * 2;
|
||||
var newSignalBelts = new Dictionary<int, BeltSignal>[newCapacity];
|
||||
Array.Copy(_signalBelts, newSignalBelts, _signalBeltsCapacity);
|
||||
_signalBelts = newSignalBelts;
|
||||
_signalBeltsCapacity = newCapacity;
|
||||
}
|
||||
else
|
||||
{
|
||||
obj = _signalBelts[index];
|
||||
if (obj != null) return obj;
|
||||
}
|
||||
|
||||
obj = [];
|
||||
_signalBelts[index] = obj;
|
||||
return obj;
|
||||
}
|
||||
|
||||
private static Dictionary<int, BeltSignal> GetSignalBelts(int index)
|
||||
{
|
||||
return index >= 0 && index < _signalBeltsCapacity ? _signalBelts[index] : null;
|
||||
}
|
||||
|
||||
private static void SetSignalBelt(int factory, int beltId, int signalId, int number)
|
||||
{
|
||||
int stack;
|
||||
int inc;
|
||||
int speedLimit;
|
||||
if (signalId >= 1000)
|
||||
{
|
||||
if (!FactoryPatch.BeltSignalNumberAltFormat.Value)
|
||||
{
|
||||
stack = Mathf.Clamp(number % 10, 1, 4);
|
||||
inc = number / 10 % 10 * stack;
|
||||
speedLimit = number / 100;
|
||||
}
|
||||
else
|
||||
{
|
||||
stack = Mathf.Clamp(number / 10000 % 10, 1, 4);
|
||||
inc = number / 100000 % 10 * stack;
|
||||
speedLimit = number % 10000;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
stack = 0;
|
||||
inc = 0;
|
||||
speedLimit = number;
|
||||
}
|
||||
|
||||
if (speedLimit > 3600) speedLimit = 3600;
|
||||
|
||||
var signalBelts = GetOrCreateSignalBelts(factory);
|
||||
if (signalBelts.TryGetValue(beltId, out var oldBeltSignal))
|
||||
{
|
||||
if (oldBeltSignal.SignalId == signalId && oldBeltSignal.SpeedLimit == speedLimit &&
|
||||
oldBeltSignal.Stack == stack && oldBeltSignal.Inc == inc)
|
||||
{
|
||||
if (!ReferenceEquals(_sourceCatalog, ProductionCatalogService.Current))
|
||||
AddSourcesToBeltSignal(oldBeltSignal);
|
||||
return;
|
||||
}
|
||||
oldBeltSignal.SpeedLimit = speedLimit;
|
||||
oldBeltSignal.Stack = (byte)stack;
|
||||
oldBeltSignal.Inc = (byte)inc;
|
||||
oldBeltSignal.Progress = 0;
|
||||
oldBeltSignal.SignalId = signalId;
|
||||
oldBeltSignal.SourceStats = null;
|
||||
AddSourcesToBeltSignal(oldBeltSignal);
|
||||
return;
|
||||
}
|
||||
|
||||
var beltSignal = new BeltSignal
|
||||
{
|
||||
SignalId = signalId,
|
||||
SpeedLimit = speedLimit,
|
||||
Stack = (byte)stack,
|
||||
Inc = (byte)inc
|
||||
};
|
||||
AddSourcesToBeltSignal(beltSignal);
|
||||
signalBelts[beltId] = beltSignal;
|
||||
}
|
||||
|
||||
private static void AddSourcesToBeltSignal(BeltSignal beltSignal)
|
||||
{
|
||||
beltSignal.SourceStats = null;
|
||||
var itemId = beltSignal.SignalId;
|
||||
if (itemId < 1000 || beltSignal.Stack == 0) return;
|
||||
var catalog = ProductionCatalogService.Current;
|
||||
if (!ReferenceEquals(_sourceCatalog, catalog))
|
||||
{
|
||||
ClearSourceCache();
|
||||
_sourceCatalog = catalog;
|
||||
_preferredProliferator = BeltSignalSourcePreset.SelectProliferator(catalog);
|
||||
}
|
||||
|
||||
var proliferated = FactoryPatch.BeltSignalUseProliferatorEnabled.Value;
|
||||
var sprayed = proliferated && _preferredProliferator != null &&
|
||||
beltSignal.Inc / beltSignal.Stack >= _preferredProliferator.ProliferationLevel;
|
||||
var key = (itemId, proliferated, sprayed);
|
||||
if (catalog == null)
|
||||
{
|
||||
LogSourceFailure(key, "Production data is not loaded.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (FailedSources.Contains(key)) return;
|
||||
if (!SourceCache.TryGetValue(key, out var rates))
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = BeltSignalSourcePreset.Create(catalog, itemId, proliferated, sprayed);
|
||||
var report = new ProductionPlanner(catalog).Calculate(request);
|
||||
if (!report.MaterialComplete)
|
||||
{
|
||||
LogSourceFailure(key, string.Join("; ", report.Diagnostics.Select(diagnostic => diagnostic.Message)));
|
||||
return;
|
||||
}
|
||||
|
||||
rates = BeltSignalSourceStats.FromReport(report, itemId);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
LogSourceFailure(key, exception.ToString());
|
||||
return;
|
||||
}
|
||||
|
||||
SourceCache[key] = rates;
|
||||
}
|
||||
|
||||
if (rates.Count > 0) beltSignal.SourceStats = new BeltSignalSourceStats(rates);
|
||||
}
|
||||
|
||||
private static void LogSourceFailure((int itemId, bool proliferated, bool sprayed) key, string reason)
|
||||
{
|
||||
if (FailedSources.Add(key))
|
||||
CheatEnabler.Logger.LogWarning(
|
||||
$"Belt signal upstream statistics for item {key.itemId} are suspended: {reason}");
|
||||
}
|
||||
|
||||
private static void SetSignalBeltPortalTo(int factory, int beltId, int number)
|
||||
{
|
||||
var v = ((long)factory << 32) | (uint)beltId;
|
||||
_portalFrom[v] = number;
|
||||
if (!_portalTo.TryGetValue(number, out var set))
|
||||
{
|
||||
set = [];
|
||||
_portalTo[number] = set;
|
||||
}
|
||||
|
||||
set.Add(v);
|
||||
}
|
||||
|
||||
private static void RemoveSignalBelt(int factory, int beltId)
|
||||
{
|
||||
GetSignalBelts(factory)?.Remove(beltId);
|
||||
}
|
||||
|
||||
private static void RemovePlanetSignalBelts(int factory)
|
||||
{
|
||||
GetSignalBelts(factory)?.Clear();
|
||||
}
|
||||
|
||||
private static void RemoveSignalBeltPortalEnd(int factory, int beltId)
|
||||
{
|
||||
var v = ((long)factory << 32) | (uint)beltId;
|
||||
if (!_portalFrom.TryGetValue(v, out var number)) return;
|
||||
_portalFrom.Remove(v);
|
||||
if (!_portalTo.TryGetValue(number, out var set)) return;
|
||||
set.Remove(v);
|
||||
}
|
||||
|
||||
private static void OnGameBegin()
|
||||
{
|
||||
if (DSPGame.IsMenuDemo) return;
|
||||
if (FactoryPatch.BeltSignalGeneratorEnabled.Value) InitSignalBelts();
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(DigitalSystem), MethodType.Constructor, typeof(PlanetData))]
|
||||
private static void DigitalSystem_Constructor_Postfix(PlanetData _planet)
|
||||
{
|
||||
if (!FactoryPatch.BeltSignalGeneratorEnabled.Value) return;
|
||||
var player = GameMain.mainPlayer;
|
||||
if (player == null) return;
|
||||
var factory = _planet?.factory;
|
||||
if (factory == null) return;
|
||||
RemovePlanetSignalBelts(factory.index);
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.RemoveBeltComponent))]
|
||||
public static void CargoTraffic_RemoveBeltComponent_Prefix(int id)
|
||||
{
|
||||
if (!_initialized) return;
|
||||
var planet = GameMain.localPlanet;
|
||||
if (planet == null) return;
|
||||
RemoveSignalBeltPortalEnd(planet.factoryIndex, id);
|
||||
RemoveSignalBelt(planet.factoryIndex, id);
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.SetBeltSignalIcon))]
|
||||
public static void CargoTraffic_SetBeltSignalIcon_Postfix(CargoTraffic __instance, int signalId, int entityId)
|
||||
{
|
||||
if (!_initialized) return;
|
||||
var planet = GameMain.localPlanet;
|
||||
if (planet == null) return;
|
||||
var factory = __instance.factory;
|
||||
int number;
|
||||
var needAdd = false;
|
||||
switch (signalId)
|
||||
{
|
||||
case 404:
|
||||
number = 0;
|
||||
needAdd = true;
|
||||
break;
|
||||
case 600:
|
||||
case >= 1000 and < 20000:
|
||||
number = Mathf.RoundToInt(factory.entitySignPool[entityId].count0);
|
||||
if (number > 0)
|
||||
needAdd = true;
|
||||
break;
|
||||
case >= 601 and <= 609:
|
||||
number = Mathf.RoundToInt(factory.entitySignPool[entityId].count0);
|
||||
var factoryIndex = planet.factoryIndex;
|
||||
var beltId = factory.entityPool[entityId].beltId;
|
||||
if (number > 0)
|
||||
SetSignalBeltPortalTo(factoryIndex, beltId, number);
|
||||
RemoveSignalBelt(factoryIndex, beltId);
|
||||
return;
|
||||
default:
|
||||
number = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
{
|
||||
var factoryIndex = planet.factoryIndex;
|
||||
var beltId = factory.entityPool[entityId].beltId;
|
||||
if (needAdd)
|
||||
{
|
||||
SetSignalBelt(factoryIndex, beltId, signalId, number);
|
||||
}
|
||||
else
|
||||
{
|
||||
RemoveSignalBelt(factoryIndex, beltId);
|
||||
}
|
||||
|
||||
RemoveSignalBeltPortalEnd(factoryIndex, beltId);
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.SetBeltSignalNumber))]
|
||||
public static void CargoTraffic_SetBeltSignalNumber_Postfix(CargoTraffic __instance, float number, int entityId)
|
||||
{
|
||||
if (!_initialized) return;
|
||||
var planet = GameMain.localPlanet;
|
||||
if (planet == null) return;
|
||||
var factory = __instance.factory;
|
||||
var entitySignPool = factory.entitySignPool;
|
||||
uint signalId;
|
||||
if (entitySignPool[entityId].iconType == 0U || (signalId = entitySignPool[entityId].iconId0) == 0U) return;
|
||||
switch (signalId)
|
||||
{
|
||||
case 404:
|
||||
return;
|
||||
case 600:
|
||||
case >= 1000 and < 20000:
|
||||
break;
|
||||
case >= 601 and <= 609:
|
||||
var factoryIndex = planet.factoryIndex;
|
||||
var beltId = factory.entityPool[entityId].beltId;
|
||||
RemoveSignalBeltPortalEnd(factoryIndex, beltId);
|
||||
SetSignalBeltPortalTo(factoryIndex, beltId, Mathf.RoundToInt(number));
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
{
|
||||
var factoryIndex = planet.factoryIndex;
|
||||
var beltId = factory.entityPool[entityId].beltId;
|
||||
var n = Mathf.RoundToInt(number);
|
||||
if (n == 0)
|
||||
{
|
||||
RemoveSignalBelt(factoryIndex, beltId);
|
||||
}
|
||||
else
|
||||
{
|
||||
SetSignalBelt(factoryIndex, beltId, (int)signalId, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ProcessBeltSignals()
|
||||
{
|
||||
if (!_initialized) return;
|
||||
var data = GameMain.data;
|
||||
var factories = data?.factories;
|
||||
if (factories == null) return;
|
||||
DeepProfiler.BeginSample(DPEntry.Belt);
|
||||
for (var index = data.factoryCount - 1; index >= 0; index--)
|
||||
{
|
||||
var factory = factories[index];
|
||||
if (factory == null) continue;
|
||||
var belts = GetSignalBelts(index);
|
||||
if (belts == null || belts.Count == 0) continue;
|
||||
var factoryProductionStat = GameMain.statistics.production.factoryStatPool[index];
|
||||
var productRegister = factoryProductionStat.productRegister;
|
||||
var consumeRegister = factoryProductionStat.consumeRegister;
|
||||
var countRecipe = FactoryPatch.BeltSignalCountRecipeEnabled.Value;
|
||||
var cargoTraffic = factory.cargoTraffic;
|
||||
var beltCount = cargoTraffic.beltCursor;
|
||||
List<int> beltsToRemove = null;
|
||||
foreach (var pair in belts)
|
||||
{
|
||||
if (pair.Key >= beltCount)
|
||||
{
|
||||
if (beltsToRemove == null)
|
||||
beltsToRemove = [pair.Key];
|
||||
else
|
||||
beltsToRemove.Add(pair.Key);
|
||||
continue;
|
||||
}
|
||||
var beltSignal = pair.Value;
|
||||
var signalId = beltSignal.SignalId;
|
||||
switch (signalId)
|
||||
{
|
||||
case 404:
|
||||
{
|
||||
var beltId = pair.Key;
|
||||
ref var belt = ref cargoTraffic.beltPool[beltId];
|
||||
var cargoPath = cargoTraffic.GetCargoPath(belt.segPathId);
|
||||
if (cargoPath == null) continue;
|
||||
int itemId;
|
||||
if ((itemId = cargoPath.TryPickItem(belt.segIndex + belt.segPivotOffset - 5, 12, out var stack, out _)) > 0)
|
||||
{
|
||||
if (FactoryPatch.BeltSignalCountRemEnabled.Value) consumeRegister[itemId] += stack;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
case 600:
|
||||
{
|
||||
if (!_portalTo.TryGetValue(beltSignal.SpeedLimit, out var set)) continue;
|
||||
var beltId = pair.Key;
|
||||
ref var belt = ref cargoTraffic.beltPool[beltId];
|
||||
var cargoPath = cargoTraffic.GetCargoPath(belt.segPathId);
|
||||
if (cargoPath == null) continue;
|
||||
var segIndex = belt.segIndex + belt.segPivotOffset;
|
||||
if (!cargoPath.GetCargoAtIndex(segIndex, out var cargo, out var cargoId, out var _)) break;
|
||||
var itemId = cargo.item;
|
||||
var cargoPool = cargoPath.cargoContainer.cargoPool;
|
||||
var inc = cargoPool[cargoId].inc;
|
||||
var stack = cargoPool[cargoId].stack;
|
||||
foreach (var n in set)
|
||||
{
|
||||
var cargoTraffic1 = factories[(int)(n >> 32)].cargoTraffic;
|
||||
ref var belt1 = ref cargoTraffic1.beltPool[(int)(n & 0x7FFFFFFF)];
|
||||
cargoPath = cargoTraffic1.GetCargoPath(belt1.segPathId);
|
||||
if (cargoPath == null) continue;
|
||||
if (!cargoPath.TryInsertItem(belt1.segIndex + belt1.segPivotOffset, itemId, stack, inc)) continue;
|
||||
cargoPath.TryPickItem(segIndex - 5, 12, out var stack1, out var inc1);
|
||||
if (inc1 != inc || stack1 != stack)
|
||||
cargoPath.TryPickItem(segIndex - 5, 12, out _, out _);
|
||||
break;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
case >= 1000 and < 20000:
|
||||
{
|
||||
var hasSpeedLimit = beltSignal.SpeedLimit > 0;
|
||||
if (hasSpeedLimit)
|
||||
{
|
||||
beltSignal.Progress += beltSignal.SpeedLimit;
|
||||
switch (beltSignal.Progress)
|
||||
{
|
||||
case < 3600:
|
||||
continue;
|
||||
case > 18000:
|
||||
beltSignal.Progress = 14400;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var beltId = pair.Key;
|
||||
ref var belt = ref cargoTraffic.beltPool[beltId];
|
||||
var cargoPath = cargoTraffic.GetCargoPath(belt.segPathId);
|
||||
if (cargoPath == null) continue;
|
||||
var stack = beltSignal.Stack;
|
||||
var inc = beltSignal.Inc;
|
||||
if (!cargoPath.TryInsertItem(belt.segIndex + belt.segPivotOffset, signalId, stack, inc)) continue;
|
||||
if (hasSpeedLimit) beltSignal.Progress -= 3600;
|
||||
if (FactoryPatch.BeltSignalCountGenEnabled.Value) productRegister[signalId] += stack;
|
||||
if (!countRecipe) continue;
|
||||
beltSignal.SourceStats?.Apply(stack, productRegister, consumeRegister);
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (beltsToRemove == null) continue;
|
||||
foreach (var beltId in beltsToRemove)
|
||||
{
|
||||
belts.Remove(beltId);
|
||||
}
|
||||
}
|
||||
|
||||
DeepProfiler.EndSample(DPEntry.Belt);
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(GameLogic), nameof(GameLogic.OnFactoryFrameBegin))]
|
||||
public static void GameLogic_OnFactoryFrameBegin_Postfix()
|
||||
{
|
||||
ProcessBeltSignals();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UXAssist.Common.GameConstants;
|
||||
using UXAssist.Production;
|
||||
|
||||
namespace CheatEnabler.Patches.Factory;
|
||||
|
||||
internal readonly struct BeltSignalSourceRate
|
||||
{
|
||||
public int ItemId { get; }
|
||||
public double ProductionPerItem { get; }
|
||||
public double ConsumptionPerItem { get; }
|
||||
|
||||
public BeltSignalSourceRate(int itemId, double productionPerItem, double consumptionPerItem)
|
||||
{
|
||||
ItemId = itemId;
|
||||
ProductionPerItem = productionPerItem;
|
||||
ConsumptionPerItem = consumptionPerItem;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class BeltSignalSourceStats
|
||||
{
|
||||
private readonly double[] _productionProgress;
|
||||
private readonly double[] _consumptionProgress;
|
||||
|
||||
public IReadOnlyList<BeltSignalSourceRate> Rates { get; }
|
||||
|
||||
public BeltSignalSourceStats(IReadOnlyList<BeltSignalSourceRate> rates)
|
||||
{
|
||||
Rates = rates;
|
||||
_productionProgress = new double[rates.Count];
|
||||
_consumptionProgress = new double[rates.Count];
|
||||
}
|
||||
|
||||
public static IReadOnlyList<BeltSignalSourceRate> FromReport(ProductionReport report, int targetItemId)
|
||||
{
|
||||
if (report == null || !report.MaterialComplete)
|
||||
throw new InvalidOperationException("A complete material report is required for belt statistics.");
|
||||
|
||||
var rates = new List<BeltSignalSourceRate>();
|
||||
foreach (var flow in report.ItemFlows.Values.OrderBy(flow => flow.ItemId))
|
||||
{
|
||||
var produced = flow.GrossProduction + flow.ExternalImports -
|
||||
(flow.ItemId == targetItemId ? flow.Delivered : 0);
|
||||
var consumed = flow.GrossConsumption;
|
||||
if (!ValidRate(produced) || !ValidRate(consumed))
|
||||
throw new InvalidOperationException("The production report contains an invalid belt statistics rate.");
|
||||
if (produced > 0 || consumed > 0)
|
||||
rates.Add(new BeltSignalSourceRate(flow.ItemId, Math.Max(0, produced), consumed));
|
||||
}
|
||||
|
||||
return Array.AsReadOnly(rates.ToArray());
|
||||
}
|
||||
|
||||
public void Apply(int stack, int[] productRegister, int[] consumeRegister)
|
||||
{
|
||||
for (var index = 0; index < Rates.Count; index++)
|
||||
{
|
||||
var rate = Rates[index];
|
||||
Accumulate(rate.ProductionPerItem, stack, ref _productionProgress[index],
|
||||
productRegister, rate.ItemId);
|
||||
Accumulate(rate.ConsumptionPerItem, stack, ref _consumptionProgress[index],
|
||||
consumeRegister, rate.ItemId);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool ValidRate(double rate)
|
||||
{
|
||||
return rate >= -1e-7 && rate < int.MaxValue / 4.0 &&
|
||||
!double.IsNaN(rate) && !double.IsInfinity(rate);
|
||||
}
|
||||
|
||||
private static void Accumulate(double rate, int stack, ref double progress, int[] register, int itemId)
|
||||
{
|
||||
if (rate <= 0) return;
|
||||
var total = progress + rate * stack;
|
||||
if (total <= 0)
|
||||
{
|
||||
progress = total;
|
||||
return;
|
||||
}
|
||||
|
||||
var count = (int)Math.Ceiling(total);
|
||||
register[itemId] += count;
|
||||
progress = total - count;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class BeltSignalSourcePreset
|
||||
{
|
||||
public static ProductionItem SelectProliferator(ProductionCatalog catalog)
|
||||
{
|
||||
return catalog?.Items.Values.Where(item => item.ProliferationLevel > 0 && item.SpraysPerItem > 0)
|
||||
.OrderByDescending(item => item.ProliferationLevel)
|
||||
.ThenByDescending(item => item.SpraysPerItem)
|
||||
.ThenBy(item => item.Id).FirstOrDefault();
|
||||
}
|
||||
|
||||
public static ProductionPlanRequest Create(ProductionCatalog catalog, int itemId,
|
||||
bool useProliferator, bool sprayDeliveredItem)
|
||||
{
|
||||
var request = new ProductionPlanRequest
|
||||
{
|
||||
ProliferationEnabled = useProliferator,
|
||||
ProliferatorItemId = useProliferator ? SelectProliferator(catalog)?.Id ?? 0 : 0,
|
||||
SelfSprayProliferator = useProliferator
|
||||
};
|
||||
request.Targets.Add(new ProductionTarget(itemId, 1));
|
||||
foreach (var externalItemId in ItemIds.ExtraOreItemIds)
|
||||
{
|
||||
if (catalog.Items.ContainsKey(externalItemId)) request.ExternalMaterials.Add(externalItemId);
|
||||
}
|
||||
|
||||
if (!useProliferator) return request;
|
||||
if (sprayDeliveredItem) request.SprayDeliveredItems.Add(itemId);
|
||||
foreach (var item in catalog.Items.Values)
|
||||
{
|
||||
if (!catalog.Recipes.TryGetValue(item.DefaultRecipeId, out var recipe) ||
|
||||
!recipe.Outputs.ContainsKey(item.Id) || recipe.Inputs.Count == 0) continue;
|
||||
request.ProliferationModeByItem[item.Id] = ItemIds.NoProliferationItemIds.Contains(item.Id)
|
||||
? ProliferationMode.None
|
||||
: ItemIds.ExtraProliferationItemIds.Contains(item.Id) && recipe.Productive
|
||||
? ProliferationMode.ExtraProducts : ProliferationMode.Speedup;
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection.Emit;
|
||||
using BepInEx.Configuration;
|
||||
using CommonAPI.Systems;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using UXAssist.Common.Patching;
|
||||
using GameLogicProc = UXAssist.Common.GameLogic;
|
||||
|
||||
namespace CheatEnabler.Patches.Factory;
|
||||
|
||||
[ModFeature("CheatFactory", Order = 10)]
|
||||
public class FactoryPatch : PatchImpl<FactoryPatch>
|
||||
{
|
||||
public static ConfigEntry<bool> ImmediateEnabled;
|
||||
public static ConfigEntry<bool> ArchitectModeEnabled;
|
||||
public static ConfigEntry<bool> NoConditionEnabled;
|
||||
public static ConfigEntry<bool> NoCollisionEnabled;
|
||||
public static ConfigEntry<bool> BeltSignalGeneratorEnabled;
|
||||
public static ConfigEntry<bool> BeltSignalNumberAltFormat;
|
||||
public static ConfigEntry<bool> BeltSignalCountGenEnabled;
|
||||
public static ConfigEntry<bool> BeltSignalCountRemEnabled;
|
||||
public static ConfigEntry<bool> BeltSignalCountRecipeEnabled;
|
||||
public static ConfigEntry<bool> BeltSignalUseProliferatorEnabled;
|
||||
public static ConfigEntry<bool> RemovePowerSpaceLimitEnabled;
|
||||
public static ConfigEntry<bool> BoostWindPowerEnabled;
|
||||
public static ConfigEntry<bool> BoostSolarPowerEnabled;
|
||||
public static ConfigEntry<bool> BoostFuelPowerEnabled;
|
||||
public static ConfigEntry<bool> BoostGeothermalPowerEnabled;
|
||||
public static ConfigEntry<bool> WindTurbinesPowerGlobalCoverageEnabled;
|
||||
public static ConfigEntry<bool> ControlPanelRemoteLogisticsEnabled;
|
||||
|
||||
private static PressKeyBind _noConditionKey;
|
||||
private static PressKeyBind _noCollisionKey;
|
||||
internal static HashSet<int> BeltIds;
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
_noConditionKey = KeyBindings.RegisterKeyBinding(new BuiltinKey
|
||||
{
|
||||
key = new CombineKey(0, 0, ECombineKeyAction.OnceClick, true),
|
||||
conflictGroup = KeyBindConflict.MOVEMENT | KeyBindConflict.FLYING | KeyBindConflict.SAILING | KeyBindConflict.BUILD_MODE_1 | KeyBindConflict.KEYBOARD_KEYBIND,
|
||||
name = "ToggleNoCondition",
|
||||
canOverride = true
|
||||
}
|
||||
);
|
||||
_noCollisionKey = KeyBindings.RegisterKeyBinding(new BuiltinKey
|
||||
{
|
||||
key = new CombineKey(0, 0, ECombineKeyAction.OnceClick, true),
|
||||
conflictGroup = KeyBindConflict.MOVEMENT | KeyBindConflict.FLYING | KeyBindConflict.SAILING | KeyBindConflict.BUILD_MODE_1 | KeyBindConflict.KEYBOARD_KEYBIND,
|
||||
name = "ToggleNoCollision",
|
||||
canOverride = true
|
||||
}
|
||||
);
|
||||
ImmediateEnabled.SettingChanged += (_, _) => ImmediateBuild.Enable(ImmediateEnabled.Value);
|
||||
ArchitectModeEnabled.SettingChanged += (_, _) => ArchitectMode.Enable(ArchitectModeEnabled.Value);
|
||||
NoConditionEnabled.SettingChanged += (_, _) => NoConditionBuild.Enable(NoConditionEnabled.Value);
|
||||
NoCollisionEnabled.SettingChanged += (_, _) => NoCollisionValueChanged();
|
||||
BeltSignalGeneratorEnabled.SettingChanged += (_, _) => BeltSignalGenerator.Enable(BeltSignalGeneratorEnabled.Value);
|
||||
BeltSignalNumberAltFormat.SettingChanged += (_, _) => BeltSignalGenerator.OnAltFormatChanged();
|
||||
BeltSignalUseProliferatorEnabled.SettingChanged += (_, _) => BeltSignalGenerator.OnUseProliferatorChanged();
|
||||
RemovePowerSpaceLimitEnabled.SettingChanged += (_, _) => RemovePowerSpaceLimit.Enable(RemovePowerSpaceLimitEnabled.Value);
|
||||
BoostWindPowerEnabled.SettingChanged += (_, _) => BoostWindPower.Enable(BoostWindPowerEnabled.Value);
|
||||
BoostSolarPowerEnabled.SettingChanged += (_, _) => BoostSolarPower.Enable(BoostSolarPowerEnabled.Value);
|
||||
BoostFuelPowerEnabled.SettingChanged += (_, _) => BoostFuelPower.Enable(BoostFuelPowerEnabled.Value);
|
||||
BoostGeothermalPowerEnabled.SettingChanged += (_, _) => BoostGeothermalPower.Enable(BoostGeothermalPowerEnabled.Value);
|
||||
WindTurbinesPowerGlobalCoverageEnabled.SettingChanged += (_, _) => WindTurbinesPowerGlobalCoverage.Enable(WindTurbinesPowerGlobalCoverageEnabled.Value);
|
||||
ControlPanelRemoteLogisticsEnabled.SettingChanged += (_, _) => ControlPanelRemoteLogistics.Enable(ControlPanelRemoteLogisticsEnabled.Value);
|
||||
}
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
ImmediateBuild.Enable(ImmediateEnabled.Value);
|
||||
ArchitectMode.Enable(ArchitectModeEnabled.Value);
|
||||
NoConditionBuild.Enable(NoConditionEnabled.Value);
|
||||
NoCollisionValueChanged();
|
||||
BeltSignalGenerator.Enable(BeltSignalGeneratorEnabled.Value);
|
||||
RemovePowerSpaceLimit.Enable(RemovePowerSpaceLimitEnabled.Value);
|
||||
BoostWindPower.Enable(BoostWindPowerEnabled.Value);
|
||||
BoostSolarPower.Enable(BoostSolarPowerEnabled.Value);
|
||||
BoostFuelPower.Enable(BoostFuelPowerEnabled.Value);
|
||||
BoostGeothermalPower.Enable(BoostGeothermalPowerEnabled.Value);
|
||||
WindTurbinesPowerGlobalCoverage.Enable(WindTurbinesPowerGlobalCoverageEnabled.Value);
|
||||
ControlPanelRemoteLogistics.Enable(ControlPanelRemoteLogisticsEnabled.Value);
|
||||
Enable(true);
|
||||
CargoTrafficPatch.Enable(true);
|
||||
GameLogicProc.OnGameBegin += OnGameBegin_For_ImmBuild;
|
||||
GameLogicProc.OnDataLoaded += OnDataLoaded;
|
||||
}
|
||||
|
||||
public static void Uninit()
|
||||
{
|
||||
GameLogicProc.OnDataLoaded -= OnDataLoaded;
|
||||
GameLogicProc.OnGameBegin -= OnGameBegin_For_ImmBuild;
|
||||
CargoTrafficPatch.Enable(false);
|
||||
Enable(false);
|
||||
ImmediateBuild.Enable(false);
|
||||
ArchitectMode.Enable(false);
|
||||
NoConditionBuild.Enable(false);
|
||||
BeltSignalGenerator.Enable(false);
|
||||
RemovePowerSpaceLimit.Enable(false);
|
||||
BoostWindPower.Enable(false);
|
||||
BoostSolarPower.Enable(false);
|
||||
BoostFuelPower.Enable(false);
|
||||
BoostGeothermalPower.Enable(false);
|
||||
WindTurbinesPowerGlobalCoverage.Enable(false);
|
||||
ControlPanelRemoteLogistics.Enable(false);
|
||||
}
|
||||
|
||||
private static void OnDataLoaded()
|
||||
{
|
||||
WindTurbinesPowerGlobalCoverage.Enable(WindTurbinesPowerGlobalCoverageEnabled.Value);
|
||||
BeltIds ??= [.. LDB.items.dataArray.Where(i => i.prefabDesc.isBelt).Select(i => i.ID)];
|
||||
}
|
||||
|
||||
public static void OnInputUpdate()
|
||||
{
|
||||
if (_noConditionKey.keyValue)
|
||||
{
|
||||
NoConditionEnabled.Value = !NoConditionEnabled.Value;
|
||||
if (!DSPGame.IsMenuDemo && GameMain.isRunning)
|
||||
{
|
||||
UIRoot.instance.uiGame.generalTips.InvokeRealtimeTipAhead((NoConditionEnabled.Value ? Localization.NoConditionOn : Localization.NoConditionOff).Translate());
|
||||
}
|
||||
}
|
||||
if (_noCollisionKey.keyValue)
|
||||
{
|
||||
NoCollisionEnabled.Value = !NoCollisionEnabled.Value;
|
||||
if (!DSPGame.IsMenuDemo && GameMain.isRunning)
|
||||
{
|
||||
UIRoot.instance.uiGame.generalTips.InvokeRealtimeTipAhead((NoCollisionEnabled.Value ? Localization.NoCollisionOn : Localization.NoCollisionOff).Translate());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void NoCollisionValueChanged()
|
||||
{
|
||||
var coll = ColliderPool.instance;
|
||||
if (coll == null) return;
|
||||
var obj = coll.gameObject;
|
||||
if (obj == null) return;
|
||||
obj.gameObject.SetActive(!NoCollisionEnabled.Value);
|
||||
GameMain.data?.warningSystem?.UpdateCriticalWarningText();
|
||||
}
|
||||
|
||||
public static void ArrivePlanet(PlanetFactory factory)
|
||||
{
|
||||
if (factory.prebuildCount <= 0) return;
|
||||
var imm = ImmediateEnabled.Value;
|
||||
var architect = ArchitectModeEnabled.Value;
|
||||
if ((!imm && !architect) || GameMain.gameScenario == null) return;
|
||||
var prebuilds = factory.prebuildPool;
|
||||
if (imm)
|
||||
{
|
||||
var player = GameMain.mainPlayer;
|
||||
for (var i = factory.prebuildCursor - 1; i > 0; i--)
|
||||
{
|
||||
ref var pb = ref prebuilds[i];
|
||||
if (pb.id != i || pb.isDestroyed) continue;
|
||||
if (pb.itemRequired > 0)
|
||||
{
|
||||
if (!architect) continue;
|
||||
pb.itemRequired = 0;
|
||||
}
|
||||
CargoTrafficPatch.InstantBuild(player, factory, i);
|
||||
}
|
||||
CargoTrafficPatch.TryEndBatchBuilding(factory);
|
||||
}
|
||||
else if (architect)
|
||||
{
|
||||
for (var i = factory.prebuildCursor - 1; i > 0; i--)
|
||||
{
|
||||
ref var pb = ref prebuilds[i];
|
||||
if (pb.id != i || pb.isDestroyed || pb.itemRequired == 0) continue;
|
||||
pb.itemRequired = 0;
|
||||
factory.AlterPrebuildModelState(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(PlanetData), nameof(PlanetData.NotifyFactoryLoaded))]
|
||||
private static void PlanetData_NotifyFactoryLoaded_Postfix(PlanetData __instance)
|
||||
{
|
||||
var main = GameMain.instance;
|
||||
if (main != null && main._running && __instance.factory?.planet?.data != null)
|
||||
{
|
||||
global::CheatEnabler.Patches.FactoryPatch.ArrivePlanet(__instance.factory);
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnGameBegin_For_ImmBuild()
|
||||
{
|
||||
if (DSPGame.IsMenuDemo) return;
|
||||
var factory = GameMain.mainPlayer?.factory;
|
||||
if (factory?.planet?.data != null)
|
||||
{
|
||||
global::CheatEnabler.Patches.FactoryPatch.ArrivePlanet(factory);
|
||||
}
|
||||
GameMain.data?.warningSystem?.UpdateCriticalWarningText();
|
||||
}
|
||||
|
||||
private static bool HasCustomCriticalWarning() =>
|
||||
Tech.DowngradeMode.IsOn || NoConditionEnabled?.Value == true || NoCollisionEnabled?.Value == true;
|
||||
|
||||
private static string GetCustomCriticalWarningText()
|
||||
{
|
||||
if (Tech.DowngradeMode.IsOn) return Localization.TechDowngradeModeWarning.Translate();
|
||||
if (NoConditionEnabled?.Value == true) return Localization.BuildWithoutConditionIsEnabled.Translate();
|
||||
if (NoCollisionEnabled?.Value == true) return Localization.NoCollisionIsEnabled.Translate();
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void ApplyCustomCriticalWarningText(WarningSystem warning)
|
||||
{
|
||||
string text = GetCustomCriticalWarningText();
|
||||
if (text != null) warning.criticalWarningTexts = text + "\r\n";
|
||||
}
|
||||
|
||||
// Harmony transpiler: WarningSystem_hasCriticalWarning_Transpiler
|
||||
// Target: WarningSystem.hasCriticalWarning (getter)
|
||||
// Fallback: TranspilerGuard returns original instructions and logs a warning.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(WarningSystem), nameof(WarningSystem.hasCriticalWarning), MethodType.Getter)]
|
||||
private static IEnumerable<CodeInstruction> WarningSystem_hasCriticalWarning_Transpiler(
|
||||
IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.End().MatchBack(false, new CodeMatch(OpCodes.Ret));
|
||||
if (matcher.IsInvalid)
|
||||
{
|
||||
return matcher.Finish(instructions, global::CheatEnabler.CheatEnabler.Logger,
|
||||
nameof(WarningSystem_hasCriticalWarning_Transpiler));
|
||||
}
|
||||
|
||||
var labels = matcher.Labels;
|
||||
matcher.Labels = new List<Label>();
|
||||
matcher.Insert(
|
||||
new CodeInstruction(OpCodes.Call,
|
||||
AccessTools.Method(typeof(FactoryPatch), nameof(HasCustomCriticalWarning))).WithLabels(labels),
|
||||
new CodeInstruction(OpCodes.Or));
|
||||
return matcher.Finish(instructions, global::CheatEnabler.CheatEnabler.Logger,
|
||||
nameof(WarningSystem_hasCriticalWarning_Transpiler));
|
||||
}
|
||||
|
||||
// Harmony transpiler: WarningSystem_UpdateCriticalWarningText_Transpiler
|
||||
// Target: WarningSystem.UpdateCriticalWarningText
|
||||
// Fallback: TranspilerGuard returns original instructions and logs a warning.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(WarningSystem), nameof(WarningSystem.UpdateCriticalWarningText))]
|
||||
private static IEnumerable<CodeInstruction> WarningSystem_UpdateCriticalWarningText_Transpiler(
|
||||
IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Ldstr, ""),
|
||||
new CodeMatch(OpCodes.Call,
|
||||
AccessTools.PropertySetter(typeof(WarningSystem), nameof(WarningSystem.criticalWarningTexts))));
|
||||
if (matcher.IsInvalid)
|
||||
{
|
||||
return matcher.Finish(instructions, global::CheatEnabler.CheatEnabler.Logger,
|
||||
nameof(WarningSystem_UpdateCriticalWarningText_Transpiler));
|
||||
}
|
||||
|
||||
matcher.Repeat(m =>
|
||||
{
|
||||
m.Advance(3).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Call,
|
||||
AccessTools.Method(typeof(FactoryPatch), nameof(ApplyCustomCriticalWarningText))));
|
||||
if (m.Opcode != OpCodes.Ret) return;
|
||||
|
||||
var label = generator.DefineLabel();
|
||||
m.InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldfld,
|
||||
AccessTools.Field(typeof(WarningSystem), nameof(WarningSystem.onCriticalWarningTextChanged))),
|
||||
new CodeInstruction(OpCodes.Brfalse, label),
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldfld,
|
||||
AccessTools.Field(typeof(WarningSystem), nameof(WarningSystem.onCriticalWarningTextChanged))),
|
||||
new CodeInstruction(OpCodes.Callvirt, AccessTools.Method(typeof(Action), nameof(Action.Invoke))));
|
||||
m.Labels.Add(label);
|
||||
});
|
||||
return matcher.Start().Finish(instructions, global::CheatEnabler.CheatEnabler.Logger,
|
||||
nameof(WarningSystem_UpdateCriticalWarningText_Transpiler));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection.Emit;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
|
||||
namespace CheatEnabler.Patches.Factory;
|
||||
|
||||
internal class CargoTrafficPatch : PatchImpl<CargoTrafficPatch>
|
||||
{
|
||||
private static bool _isBatchBuilding;
|
||||
private static bool _disableRefreshBatchesBuffers;
|
||||
private static bool _anyBelt;
|
||||
private static readonly HashSet<int> _alterBeltRendererIds = [];
|
||||
private static readonly HashSet<int> _alterPathRendererIds = [];
|
||||
private static readonly HashSet<int> _refreshPathUVIds = [];
|
||||
|
||||
public static bool IsBatchBuilding => _isBatchBuilding;
|
||||
|
||||
public static void StartBatchBuilding(PlanetFactory factory)
|
||||
{
|
||||
factory.BeginFlattenTerrain();
|
||||
factory.cargoTraffic._batch_buffer_no_refresh = true;
|
||||
PlanetFactory.batchBuild = true;
|
||||
_isBatchBuilding = true;
|
||||
_disableRefreshBatchesBuffers = true;
|
||||
_anyBelt = false;
|
||||
}
|
||||
|
||||
public static void EndBatchBuilding(PlanetFactory factory)
|
||||
{
|
||||
PlanetFactory.batchBuild = false;
|
||||
factory.cargoTraffic._batch_buffer_no_refresh = false;
|
||||
factory.EndFlattenTerrain();
|
||||
_isBatchBuilding = false;
|
||||
var cargoTraffic = factory.cargoTraffic;
|
||||
var entityPool = factory.entityPool;
|
||||
var colChunks = factory.planet.physics?.colChunks;
|
||||
foreach (var beltId in _alterBeltRendererIds)
|
||||
{
|
||||
cargoTraffic.AlterBeltRenderer(beltId, entityPool, colChunks, false);
|
||||
}
|
||||
foreach (var pathId in _alterPathRendererIds)
|
||||
{
|
||||
cargoTraffic.AlterPathRenderer(pathId, false);
|
||||
}
|
||||
foreach (var pathId in _refreshPathUVIds)
|
||||
{
|
||||
cargoTraffic.RefreshPathUV(pathId);
|
||||
}
|
||||
_alterBeltRendererIds.Clear();
|
||||
_alterPathRendererIds.Clear();
|
||||
_refreshPathUVIds.Clear();
|
||||
_disableRefreshBatchesBuffers = false;
|
||||
if (_anyBelt)
|
||||
{
|
||||
factory.cargoTraffic.RefreshBeltBatchesBuffers();
|
||||
factory.cargoTraffic.RefreshPathBatchesBuffers();
|
||||
}
|
||||
_anyBelt = false;
|
||||
factory.planet.physics?.raycastLogic?.NotifyBatchObjectRemove();
|
||||
factory.planet.audio?.SetPlanetAudioDirty();
|
||||
|
||||
var atField = factory.planetATField;
|
||||
var defenseSystem = factory.defenseSystem;
|
||||
if (atField != null && defenseSystem != null &&
|
||||
defenseSystem.fieldGenerators.count > 0 && atField.physicsArgs == null)
|
||||
{
|
||||
atField.UpdatePhysicsShape(updateGeneratorMatrix: true);
|
||||
}
|
||||
}
|
||||
|
||||
public static void TryEndBatchBuilding(PlanetFactory factory)
|
||||
{
|
||||
if (!_isBatchBuilding) return;
|
||||
EndBatchBuilding(factory);
|
||||
}
|
||||
|
||||
public static void InstantBuild(Player player, PlanetFactory factory, int id)
|
||||
{
|
||||
if (!_isBatchBuilding) StartBatchBuilding(factory);
|
||||
_anyBelt = _anyBelt || (FactoryPatch.BeltIds?.Contains(factory.prebuildPool[id].protoId) ?? false);
|
||||
factory.BuildFinally(player, id, false);
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPriority(Priority.First)]
|
||||
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.AlterBeltRenderer))]
|
||||
private static bool CargoTraffic_AlterBeltRenderer_Prefix(int beltId)
|
||||
{
|
||||
if (!_isBatchBuilding) return true;
|
||||
_alterBeltRendererIds.Add(beltId);
|
||||
return false;
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPriority(Priority.First)]
|
||||
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.AlterPathRenderer))]
|
||||
private static bool CargoTraffic_AlterPathRenderer_Prefix(int pathId)
|
||||
{
|
||||
if (!_isBatchBuilding) return true;
|
||||
_alterPathRendererIds.Add(pathId);
|
||||
return false;
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPriority(Priority.First)]
|
||||
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.RefreshPathUV))]
|
||||
private static bool CargoTraffic_RefreshPathUV_Prefix(int pathId)
|
||||
{
|
||||
if (!_isBatchBuilding) return true;
|
||||
_refreshPathUVIds.Add(pathId);
|
||||
return false;
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPriority(Priority.First)]
|
||||
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.RefreshBeltBatchesBuffers))]
|
||||
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.RefreshPathBatchesBuffers))]
|
||||
private static bool CargoTraffic_RefreshBeltBatchesBuffers_Prefix()
|
||||
{
|
||||
return !_disableRefreshBatchesBuffers;
|
||||
}
|
||||
}
|
||||
|
||||
internal class ImmediateBuild : PatchImpl<ImmediateBuild>
|
||||
{
|
||||
protected override void OnEnable()
|
||||
{
|
||||
var factory = GameMain.mainPlayer?.factory;
|
||||
if (factory?.planet?.data != null)
|
||||
{
|
||||
global::CheatEnabler.Patches.FactoryPatch.ArrivePlanet(factory);
|
||||
}
|
||||
}
|
||||
// Harmony transpiler: Transpiler
|
||||
// Target: BuildTool_Addon.CreatePrebuilds, BuildTool_BlueprintPaste.CreatePrebuilds, BuildTool_Click.CreatePrebuilds, BuildTool_Inserter.CreatePrebuilds, BuildTool_Path.CreatePrebuilds
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(BuildTool_Addon), nameof(BuildTool_Addon.CreatePrebuilds))]
|
||||
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_BlueprintPaste.CreatePrebuilds))]
|
||||
[HarmonyPatch(typeof(BuildTool_Click), nameof(BuildTool_Click.CreatePrebuilds))]
|
||||
[HarmonyPatch(typeof(BuildTool_Inserter), nameof(BuildTool_Inserter.CreatePrebuilds))]
|
||||
[HarmonyPatch(typeof(BuildTool_Path), nameof(BuildTool_Path.CreatePrebuilds))]
|
||||
private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.End().MatchBack(false,
|
||||
new CodeMatch(OpCodes.Ret)
|
||||
);
|
||||
if (matcher.IsInvalid)
|
||||
{
|
||||
CheatEnabler.Logger.LogWarning($"Failed to patch CreatePrebuilds");
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
matcher.Advance(-1);
|
||||
if (matcher.Opcode != OpCodes.Nop && (matcher.Opcode != OpCodes.Call || !matcher.Instruction.OperandIs(AccessTools.Method(typeof(System.GC), nameof(System.GC.Collect)))))
|
||||
{
|
||||
CheatEnabler.Logger.LogWarning($"Failed to patch CreatePrebuilds: last instruction is not `Nop` or `Call GC.Collect()`: {matcher.Instruction}");
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
var labels = matcher.Labels;
|
||||
matcher.Labels = [];
|
||||
matcher.Insert(
|
||||
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels),
|
||||
new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(BuildTool), nameof(BuildTool.factory))),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(global::CheatEnabler.Patches.FactoryPatch), nameof(global::CheatEnabler.Patches.FactoryPatch.ArrivePlanet)))
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(GameLogic), nameof(GameLogic.FactoryConstructionSystemGameTick))]
|
||||
private static void GameLogic_FactoryConstructionSystemGameTick_Prefix(GameLogic __instance)
|
||||
{
|
||||
var time = __instance.timei;
|
||||
if (time % 6 != 0) return;
|
||||
var planet = GameMain.localPlanet;
|
||||
if (planet == null || !planet.factoryLoaded) return;
|
||||
var factory = planet.factory;
|
||||
if (factory == null || factory.prebuildCount <= 0) return;
|
||||
var player = GameMain.mainPlayer;
|
||||
if (player == null) return;
|
||||
var total = factory.prebuildCursor - 1;
|
||||
var stepCount = total switch
|
||||
{
|
||||
< 256 => 1,
|
||||
< 2048 => 3,
|
||||
< 16384 => 10,
|
||||
_ => 20,
|
||||
};
|
||||
var step = (int)(time / 6 % stepCount);
|
||||
var start = 1 + total * step / stepCount;
|
||||
var end = 1 + total * (step + 1) / stepCount;
|
||||
for (var i = start; i < end; i++)
|
||||
{
|
||||
ref var prebuild = ref factory.prebuildPool[i];
|
||||
if (prebuild.id != i || prebuild.isDestroyed) continue;
|
||||
if (prebuild.itemRequired > 0)
|
||||
{
|
||||
int itemId = prebuild.protoId;
|
||||
int count = prebuild.itemRequired;
|
||||
player.package.TakeTailItems(ref itemId, ref count, out var _, false);
|
||||
if (count > 0)
|
||||
{
|
||||
prebuild.itemRequired -= count;
|
||||
if (prebuild.itemRequired <= 0)
|
||||
{
|
||||
CargoTrafficPatch.InstantBuild(player, factory, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (CargoTrafficPatch.IsBatchBuilding)
|
||||
{
|
||||
for (var i = start - 1; i > 0; i--)
|
||||
{
|
||||
ref var prebuild = ref factory.prebuildPool[i];
|
||||
if (prebuild.id != i || prebuild.isDestroyed) continue;
|
||||
if (prebuild.itemRequired > 0)
|
||||
{
|
||||
int itemId = prebuild.protoId;
|
||||
int count = prebuild.itemRequired;
|
||||
player.package.TakeTailItems(ref itemId, ref count, out var _, false);
|
||||
if (count > 0)
|
||||
{
|
||||
prebuild.itemRequired -= count;
|
||||
if (prebuild.itemRequired <= 0)
|
||||
{
|
||||
CargoTrafficPatch.InstantBuild(player, factory, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var i = end; i <= total; i++)
|
||||
{
|
||||
ref var prebuild = ref factory.prebuildPool[i];
|
||||
if (prebuild.id != i || prebuild.isDestroyed) continue;
|
||||
if (prebuild.itemRequired > 0)
|
||||
{
|
||||
int itemId = prebuild.protoId;
|
||||
int count = prebuild.itemRequired;
|
||||
player.package.TakeTailItems(ref itemId, ref count, out var _, false);
|
||||
if (count > 0)
|
||||
{
|
||||
prebuild.itemRequired -= count;
|
||||
if (prebuild.itemRequired <= 0)
|
||||
{
|
||||
CargoTrafficPatch.InstantBuild(player, factory, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
CargoTrafficPatch.EndBatchBuilding(factory);
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(UXAssist.Functions.PlanetFunctions), nameof(UXAssist.Functions.PlanetFunctions.BuildOrbitalCollectors))]
|
||||
private static void UXAssist_PlanetFunctions_BuildOrbitalCollectors_Postfix()
|
||||
{
|
||||
var factory = GameMain.mainPlayer?.factory;
|
||||
if (factory?.planet?.data != null)
|
||||
{
|
||||
global::CheatEnabler.Patches.FactoryPatch.ArrivePlanet(factory);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection.Emit;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
|
||||
namespace CheatEnabler.Patches.Factory;
|
||||
|
||||
internal class ControlPanelRemoteLogistics : PatchImpl<ControlPanelRemoteLogistics>
|
||||
{
|
||||
// Harmony transpiler: UIControlPanelDispenserInspector_OnItemIconMouseDown_Transpiler
|
||||
// Target: UIControlPanelDispenserInspector.OnItemIconMouseDown, UIControlPanelDispenserInspector.OnHoldupItemClick, UIControlPanelDispenserInspector.OnCourierIconClick
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UIControlPanelDispenserInspector), nameof(UIControlPanelDispenserInspector.OnItemIconMouseDown))]
|
||||
[HarmonyPatch(typeof(UIControlPanelDispenserInspector), nameof(UIControlPanelDispenserInspector.OnHoldupItemClick))]
|
||||
[HarmonyPatch(typeof(UIControlPanelDispenserInspector), nameof(UIControlPanelDispenserInspector.OnCourierIconClick))]
|
||||
private static IEnumerable<CodeInstruction> UIControlPanelDispenserInspector_OnItemIconMouseDown_Transpiler(IEnumerable<CodeInstruction> instructions)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions);
|
||||
Label? branch = null;
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(UIControlPanelDispenserInspector), nameof(UIControlPanelDispenserInspector.isLocal))),
|
||||
new CodeMatch(ci => ci.Branches(out branch))
|
||||
).Repeat(
|
||||
m =>
|
||||
{
|
||||
if (branch == null)
|
||||
{
|
||||
m.Advance(3);
|
||||
return;
|
||||
}
|
||||
var labels = m.Labels;
|
||||
m.RemoveInstructions(3).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Br, branch.Value).WithLabels(labels)
|
||||
);
|
||||
}
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
// Harmony transpiler: UIControlPanelStationInspector_OnShipIconClick_Transpiler
|
||||
// Target: UIControlPanelStationInspector.OnShipIconClick, UIControlPanelStationInspector.OnWarperIconClick, UIControlPanelStationInspector.OnDroneIconClick
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UIControlPanelStationInspector), nameof(UIControlPanelStationInspector.OnShipIconClick))]
|
||||
[HarmonyPatch(typeof(UIControlPanelStationInspector), nameof(UIControlPanelStationInspector.OnWarperIconClick))]
|
||||
[HarmonyPatch(typeof(UIControlPanelStationInspector), nameof(UIControlPanelStationInspector.OnDroneIconClick))]
|
||||
private static IEnumerable<CodeInstruction> UIControlPanelStationInspector_OnShipIconClick_Transpiler(IEnumerable<CodeInstruction> instructions)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions);
|
||||
Label? branch = null;
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(UIControlPanelStationInspector), nameof(UIControlPanelStationInspector.isLocal))),
|
||||
new CodeMatch(ci => ci.Branches(out branch))
|
||||
).Repeat(
|
||||
m =>
|
||||
{
|
||||
if (branch == null)
|
||||
{
|
||||
m.Advance(3);
|
||||
return;
|
||||
}
|
||||
var labels = m.Labels;
|
||||
m.RemoveInstructions(3).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Br, branch.Value).WithLabels(labels)
|
||||
);
|
||||
}
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
// Harmony transpiler: UIControlPanelStationStorage_OnItemIconMouseDown_Transpiler
|
||||
// Target: UIControlPanelStationStorage.OnItemIconMouseDown
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UIControlPanelStationStorage), nameof(UIControlPanelStationStorage.OnItemIconMouseDown))]
|
||||
private static IEnumerable<CodeInstruction> UIControlPanelStationStorage_OnItemIconMouseDown_Transpiler(IEnumerable<CodeInstruction> instructions)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions);
|
||||
Label? branch = null;
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(UIControlPanelStationStorage), nameof(UIControlPanelStationStorage.isLocal))),
|
||||
new CodeMatch(ci => ci.Branches(out branch))
|
||||
).Repeat(
|
||||
m =>
|
||||
{
|
||||
if (branch == null)
|
||||
{
|
||||
m.Advance(3);
|
||||
return;
|
||||
}
|
||||
var labels = m.Labels;
|
||||
m.RemoveInstructions(3).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Br, branch.Value).WithLabels(labels)
|
||||
);
|
||||
}
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
// Harmony transpiler: UIControlPanelStationStorage_OnTakeBackButtonClick_Transpiler
|
||||
// Target: UIControlPanelStationStorage.OnTakeBackButtonClick
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UIControlPanelStationStorage), nameof(UIControlPanelStationStorage.OnTakeBackButtonClick))]
|
||||
private static IEnumerable<CodeInstruction> UIControlPanelStationStorage_OnTakeBackButtonClick_Transpiler(IEnumerable<CodeInstruction> instructions)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(UIControlPanelStationStorage), nameof(UIControlPanelStationStorage.isLocal))),
|
||||
new CodeMatch(ci => ci.Branches(out _))
|
||||
).Repeat(
|
||||
m =>
|
||||
{
|
||||
var labels = m.Labels;
|
||||
m.RemoveInstructions(3).Labels.AddRange(labels);
|
||||
}
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
// Harmony transpiler: UIControlPanelVeinCollectorPanel_OnProductIconClick_Transpiler
|
||||
// Target: UIControlPanelVeinCollectorPanel.OnProductIconClick
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UIControlPanelVeinCollectorPanel), nameof(UIControlPanelVeinCollectorPanel.OnProductIconClick))]
|
||||
private static IEnumerable<CodeInstruction> UIControlPanelVeinCollectorPanel_OnProductIconClick_Transpiler(IEnumerable<CodeInstruction> instructions)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions);
|
||||
Label? branch = null;
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(UIControlPanelVeinCollectorPanel), nameof(UIControlPanelVeinCollectorPanel.isLocal))),
|
||||
new CodeMatch(ci => ci.Branches(out branch))
|
||||
).Repeat(
|
||||
m =>
|
||||
{
|
||||
if (branch == null)
|
||||
{
|
||||
m.Advance(3);
|
||||
return;
|
||||
}
|
||||
var labels = m.Labels;
|
||||
m.RemoveInstructions(3).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Br, branch.Value).WithLabels(labels)
|
||||
);
|
||||
}
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection.Emit;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
|
||||
namespace CheatEnabler.Patches.Factory;
|
||||
|
||||
internal class NoConditionBuild : PatchImpl<NoConditionBuild>
|
||||
{
|
||||
protected override void OnEnable()
|
||||
{
|
||||
GameMain.data?.warningSystem?.UpdateCriticalWarningText();
|
||||
}
|
||||
|
||||
protected override void OnDisable()
|
||||
{
|
||||
GameMain.data?.warningSystem?.UpdateCriticalWarningText();
|
||||
}
|
||||
// Harmony transpiler: BuildTool_CheckBuildConditions_Transpiler
|
||||
// Target: BuildTool_Addon.CheckBuildConditions, BuildTool_Inserter.CheckBuildConditions
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler, HarmonyPriority(Priority.Last)]
|
||||
[HarmonyPatch(typeof(BuildTool_Addon), nameof(BuildTool_Addon.CheckBuildConditions))]
|
||||
[HarmonyPatch(typeof(BuildTool_Inserter), nameof(BuildTool_Inserter.CheckBuildConditions))]
|
||||
private static IEnumerable<CodeInstruction> BuildTool_CheckBuildConditions_Transpiler(IEnumerable<CodeInstruction> instructions)
|
||||
{
|
||||
yield return new CodeInstruction(OpCodes.Ldc_I4_1);
|
||||
yield return new CodeInstruction(OpCodes.Ret);
|
||||
}
|
||||
// Harmony transpiler: BuildTool_Path_CheckBuildConditions_Transpiler
|
||||
// Target: BuildTool_Path.CheckBuildConditions
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler, HarmonyPriority(Priority.First)]
|
||||
[HarmonyPatch(typeof(BuildTool_Path), nameof(BuildTool_Path.CheckBuildConditions))]
|
||||
private static IEnumerable<CodeInstruction> BuildTool_Path_CheckBuildConditions_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
var label1 = generator.DefineLabel();
|
||||
var label2 = generator.DefineLabel();
|
||||
matcher.Start().InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Br, label1)
|
||||
);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(BuildTool), nameof(BuildTool.buildPreviews))),
|
||||
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(List<BuildPreview>), nameof(List<BuildPreview>.Count))),
|
||||
new CodeMatch(ci => ci.IsStloc())
|
||||
);
|
||||
matcher.Labels.Add(label1);
|
||||
matcher.Advance(4).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Br, label2)
|
||||
);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(ci => ci.IsLdloc()),
|
||||
new CodeMatch(ci => ci.Branches(out _)),
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(BuildTool_Path), nameof(BuildTool_Path.waitForConfirm))),
|
||||
new CodeMatch(ci => ci.Branches(out _))
|
||||
);
|
||||
var operand = matcher.Operand;
|
||||
matcher.InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Ldc_I4_1).WithLabels(label2),
|
||||
new CodeInstruction(OpCodes.Stloc_S, operand)
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
// Harmony transpiler: BuildTool_Click_CheckBuildConditions_Transpiler
|
||||
// Target: BuildTool_BlueprintPaste.CheckBuildConditions, BuildTool_Click.CheckBuildConditions
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler, HarmonyPriority(Priority.Last)]
|
||||
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_BlueprintPaste.CheckBuildConditions))]
|
||||
[HarmonyPatch(typeof(BuildTool_Click), nameof(BuildTool_Click.CheckBuildConditions))]
|
||||
private static IEnumerable<CodeInstruction> BuildTool_Click_CheckBuildConditions_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
var label1 = generator.DefineLabel();
|
||||
matcher.Start().InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(NoConditionBuild), nameof(CheckForMiner))),
|
||||
new CodeInstruction(OpCodes.Brfalse_S, label1),
|
||||
new CodeInstruction(OpCodes.Ldc_I4_1),
|
||||
new CodeInstruction(OpCodes.Ret)
|
||||
);
|
||||
matcher.Labels.Add(label1);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
public static bool CheckForMiner(BuildTool tool)
|
||||
{
|
||||
var previews = tool.buildPreviews;
|
||||
foreach (var preview in previews)
|
||||
{
|
||||
var desc = preview?.item?.prefabDesc;
|
||||
if (desc == null) continue;
|
||||
if (desc.veinMiner || desc.oilMiner) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection.Emit;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.GameConstants;
|
||||
|
||||
namespace CheatEnabler.Patches.Factory;
|
||||
|
||||
internal class RemovePowerSpaceLimit : PatchImpl<RemovePowerSpaceLimit>
|
||||
{
|
||||
// Harmony transpiler: BuildTool_CheckBuildConditions_Transpiler
|
||||
// Target: BuildTool_Click.CheckBuildConditions, BuildTool_BlueprintPaste.CheckBuildConditions
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(BuildTool_Click), nameof(BuildTool_Click.CheckBuildConditions))]
|
||||
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_BlueprintPaste.CheckBuildConditions))]
|
||||
private static IEnumerable<CodeInstruction> BuildTool_CheckBuildConditions_Transpiler(IEnumerable<CodeInstruction> instructions)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions);
|
||||
matcher.Start().MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldc_R4, 110.25f)
|
||||
);
|
||||
if (matcher.IsValid)
|
||||
{
|
||||
matcher.Repeat(codeMatcher => codeMatcher.SetAndAdvance(
|
||||
OpCodes.Ldc_R4, 1f
|
||||
));
|
||||
}
|
||||
matcher.Start().MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldc_R4, 144f)
|
||||
);
|
||||
if (matcher.IsValid)
|
||||
{
|
||||
matcher.Repeat(codeMatcher => codeMatcher.SetAndAdvance(
|
||||
OpCodes.Ldc_R4, 1f
|
||||
));
|
||||
}
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
}
|
||||
|
||||
internal class BoostWindPower : PatchImpl<BoostWindPower>
|
||||
{
|
||||
// Harmony transpiler: PowerGeneratorComponent_EnergyCap_Wind_Transpiler
|
||||
// Target: PowerGeneratorComponent.EnergyCap_Wind
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.EnergyCap_Wind))]
|
||||
private static IEnumerable<CodeInstruction> PowerGeneratorComponent_EnergyCap_Wind_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.Start().RemoveInstructions(matcher.Length);
|
||||
matcher.Insert(
|
||||
// this.currentStrength = windStrength
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldarg_1),
|
||||
new CodeInstruction(OpCodes.Stfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.currentStrength))),
|
||||
// this.capacityCurrentTick = 500000000L
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 500000000L),
|
||||
new CodeInstruction(OpCodes.Stfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.capacityCurrentTick))),
|
||||
// return 500000000L
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 500000000L),
|
||||
new CodeInstruction(OpCodes.Ret)
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
}
|
||||
|
||||
internal class BoostSolarPower : PatchImpl<BoostSolarPower>
|
||||
{
|
||||
// Harmony transpiler: PowerGeneratorComponent_EnergyCap_PV_Transpiler
|
||||
// Target: PowerGeneratorComponent.EnergyCap_PV
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.EnergyCap_PV))]
|
||||
private static IEnumerable<CodeInstruction> PowerGeneratorComponent_EnergyCap_PV_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.Start().RemoveInstructions(matcher.Length).Insert(
|
||||
// this.currentStrength = lumino
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldarg_S, 4),
|
||||
new CodeInstruction(OpCodes.Stfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.currentStrength))),
|
||||
// this.capacityCurrentTick = 600000000L
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 600000000L),
|
||||
new CodeInstruction(OpCodes.Stfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.capacityCurrentTick))),
|
||||
// return 600000000L
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 600000000L),
|
||||
new CodeInstruction(OpCodes.Ret)
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
}
|
||||
|
||||
internal class BoostFuelPower : PatchImpl<BoostFuelPower>
|
||||
{
|
||||
// Harmony transpiler: PowerGeneratorComponent_EnergyCap_Fuel_Transpiler
|
||||
// Target: PowerGeneratorComponent.EnergyCap_Fuel
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.EnergyCap_Fuel))]
|
||||
private static IEnumerable<CodeInstruction> PowerGeneratorComponent_EnergyCap_Fuel_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
var label1 = generator.DefineLabel();
|
||||
var label2 = generator.DefineLabel();
|
||||
var label3 = generator.DefineLabel();
|
||||
matcher.Start().MatchForward(false,
|
||||
new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.capacityCurrentTick)))
|
||||
);
|
||||
var labels = matcher.Labels;
|
||||
matcher.Labels = [];
|
||||
matcher.Insert(
|
||||
// if (this.fuelMask == 4)
|
||||
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels),
|
||||
new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.fuelMask))),
|
||||
new CodeInstruction(OpCodes.Ldc_I4_4),
|
||||
new CodeInstruction(OpCodes.Bne_Un_S, label1),
|
||||
// multiplier = 10000L
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 10000L),
|
||||
new CodeInstruction(OpCodes.Br_S, label3),
|
||||
// else if (this.fuelMask == 2)
|
||||
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(label1),
|
||||
new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.fuelMask))),
|
||||
new CodeInstruction(OpCodes.Ldc_I4_2),
|
||||
new CodeInstruction(OpCodes.Bne_Un_S, label2),
|
||||
// multiplier = 20000L
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 20000L),
|
||||
new CodeInstruction(OpCodes.Br_S, label3),
|
||||
// else multiplier = 50000L
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 50000L).WithLabels(label2),
|
||||
// do multiplier before store to this.capacityCurrentTick
|
||||
new CodeInstruction(OpCodes.Mul).WithLabels(label3)
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
}
|
||||
|
||||
internal class BoostGeothermalPower : PatchImpl<BoostGeothermalPower>
|
||||
{
|
||||
// Harmony transpiler: PowerGeneratorComponent_EnergyCap_GTH_Transpiler
|
||||
// Target: PowerGeneratorComponent.EnergyCap_GTH
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.EnergyCap_GTH))]
|
||||
private static IEnumerable<CodeInstruction> PowerGeneratorComponent_EnergyCap_GTH_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.Start().RemoveInstructions(matcher.Length).Insert(
|
||||
// this.currentStrength = this.gthStrength
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.gthStrength))),
|
||||
new CodeInstruction(OpCodes.Stfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.currentStrength))),
|
||||
// this.capacityCurrentTick = 2000000000L
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 2000000000L),
|
||||
new CodeInstruction(OpCodes.Stfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.capacityCurrentTick))),
|
||||
// return 2000000000L
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 2000000000L),
|
||||
new CodeInstruction(OpCodes.Ret)
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
}
|
||||
|
||||
internal static class WindTurbinesPowerGlobalCoverage
|
||||
{
|
||||
private static bool _patched;
|
||||
private static PrefabDesc _prefabdesc;
|
||||
private static float _oldCoverRadius;
|
||||
private static float _oldConnectDistance;
|
||||
private const int WindTurbineId = ItemIds.WindTurbine;
|
||||
private const float WindTurbineNewCoverageDistance = 500f;
|
||||
|
||||
public static void Enable(bool enable)
|
||||
{
|
||||
if (enable)
|
||||
{
|
||||
if (_patched) return;
|
||||
var prefabDesc = LDB.items?.Select(WindTurbineId)?.prefabDesc;
|
||||
if (prefabDesc == null) return;
|
||||
_oldCoverRadius = prefabDesc.powerCoverRadius;
|
||||
_oldConnectDistance = prefabDesc.powerConnectDistance;
|
||||
prefabDesc.powerCoverRadius = WindTurbineNewCoverageDistance;
|
||||
prefabDesc.powerConnectDistance = WindTurbineNewCoverageDistance;
|
||||
_prefabdesc = prefabDesc;
|
||||
_patched = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!_patched) return;
|
||||
_prefabdesc.powerCoverRadius = _oldCoverRadius;
|
||||
_prefabdesc.powerConnectDistance = _oldConnectDistance;
|
||||
_patched = false;
|
||||
}
|
||||
|
||||
// Iterate all factories and update wind turbines power nodes
|
||||
var factories = GameMain.data?.factories;
|
||||
if (factories == null) return;
|
||||
foreach (var factory in factories)
|
||||
{
|
||||
var powerSystem = factory?.powerSystem;
|
||||
if (powerSystem == null) continue;
|
||||
for (var i = powerSystem.nodeCursor - 1; i >= 0; i--)
|
||||
{
|
||||
ref var node = ref powerSystem.nodePool[i];
|
||||
if (node.id != i) continue;
|
||||
ref var entity = ref factory.entityPool[node.entityId];
|
||||
if (entity.protoId != WindTurbineId) continue;
|
||||
// Disconnect from power system
|
||||
powerSystem.OnNodeRemoving(i);
|
||||
// Set new properties
|
||||
node.connectDistance = _prefabdesc.powerConnectDistance;
|
||||
node.coverRadius = _prefabdesc.powerCoverRadius;
|
||||
// Connect back to power system
|
||||
powerSystem.OnNodeAdded(i);
|
||||
}
|
||||
// Refresh power nodes rendering if factory is loaded
|
||||
if (factory.planet.factoryLoaded)
|
||||
{
|
||||
factory.planet.factoryModel.RefreshPowerNodes();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,12 @@
|
||||
namespace CheatEnabler.Patches;
|
||||
|
||||
/// <summary>
|
||||
/// Preserves the pre-refactor type and method identity used by mods that locate FactoryPatch through reflection.
|
||||
/// </summary>
|
||||
public static class FactoryPatch
|
||||
{
|
||||
public static void ArrivePlanet(PlanetFactory factory)
|
||||
{
|
||||
Factory.FactoryPatch.ArrivePlanet(factory);
|
||||
}
|
||||
}
|
||||
@@ -5,36 +5,43 @@ using BepInEx.Configuration;
|
||||
using HarmonyLib;
|
||||
using UnityEngine.Bindings;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using GameLogicProc = UXAssist.Common.GameLogic;
|
||||
|
||||
namespace CheatEnabler.Patches;
|
||||
|
||||
[ModFeature("Game")]
|
||||
public static class GamePatch
|
||||
{
|
||||
public static ConfigEntry<bool> DevShortcutsEnabled;
|
||||
public static ConfigEntry<bool> AbnormalDisablerEnabled;
|
||||
public static ConfigEntry<bool> UnlockTechEnabled;
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
DevShortcutsEnabled.SettingChanged += (_, _) => DevShortcuts.Enable(DevShortcutsEnabled.Value);
|
||||
AbnormalDisablerEnabled.SettingChanged += (_, _) => AbnormalDisabler.Enable(AbnormalDisablerEnabled.Value);
|
||||
UnlockTechEnabled.SettingChanged += (_, _) => UnlockTech.Enable(UnlockTechEnabled.Value);
|
||||
GameLogicProc.OnGameEnd += ResetState;
|
||||
}
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
DevShortcuts.Enable(DevShortcutsEnabled.Value);
|
||||
AbnormalDisabler.Enable(AbnormalDisablerEnabled.Value);
|
||||
UnlockTech.Enable(UnlockTechEnabled.Value);
|
||||
}
|
||||
|
||||
public static void Uninit()
|
||||
{
|
||||
UnlockTech.Enable(false);
|
||||
GameLogicProc.OnGameEnd -= ResetState;
|
||||
AbnormalDisabler.Enable(false);
|
||||
DevShortcuts.Enable(false);
|
||||
}
|
||||
|
||||
private static void ResetState()
|
||||
{
|
||||
AbnormalDisabler.ResetState();
|
||||
DevShortcuts.ResetState();
|
||||
}
|
||||
|
||||
public class AbnormalDisabler : PatchImpl<AbnormalDisabler>
|
||||
{
|
||||
private static Dictionary<int, AbnormalityDeterminator> _savedDeterminators;
|
||||
@@ -42,13 +49,14 @@ public static class GamePatch
|
||||
protected override void OnEnable()
|
||||
{
|
||||
if (_savedDeterminators == null) return;
|
||||
var abnormalLogic = GameMain.gameScenario.abnormalityLogic;
|
||||
var abnormalLogic = GameMain.gameScenario?.abnormalityLogic;
|
||||
if (abnormalLogic == null) return;
|
||||
foreach (var p in _savedDeterminators)
|
||||
{
|
||||
p.Value.OnUnregEvent();
|
||||
}
|
||||
|
||||
abnormalLogic.determinators = new Dictionary<int, AbnormalityDeterminator>();
|
||||
abnormalLogic.determinators = [];
|
||||
}
|
||||
|
||||
protected override void OnDisable()
|
||||
@@ -63,25 +71,30 @@ public static class GamePatch
|
||||
}
|
||||
}
|
||||
|
||||
internal static void ResetState()
|
||||
{
|
||||
_savedDeterminators = null;
|
||||
}
|
||||
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), "NotifyBeforeGameSave")]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), "NotifyOnAssemblerRecipePick")]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), "NotifyOnGameBegin")]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), "NotifyOnMechaForgeTaskComplete")]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), "NotifyOnUnlockTech")]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), "NotifyOnUseConsole")]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), nameof(AbnormalityLogic.NotifyBeforeGameSave))]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), nameof(AbnormalityLogic.NotifyOnAssemblerRecipePick))]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), nameof(AbnormalityLogic.NotifyOnGameBegin))]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), nameof(AbnormalityLogic.NotifyOnMechaForgeTaskComplete))]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), nameof(AbnormalityLogic.NotifyOnUnlockTech))]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), nameof(AbnormalityLogic.NotifyOnUseConsole))]
|
||||
private static bool DisableAbnormalLogic()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), "InitDeterminators")]
|
||||
[HarmonyPatch(typeof(AbnormalityLogic), nameof(AbnormalityLogic.InitDeterminators))]
|
||||
private static void DisableAbnormalDeterminators(AbnormalityLogic __instance)
|
||||
{
|
||||
_savedDeterminators = __instance.determinators;
|
||||
if (!AbnormalDisablerEnabled.Value) return;
|
||||
__instance.determinators = new Dictionary<int, AbnormalityDeterminator>();
|
||||
__instance.determinators = [];
|
||||
foreach (var p in _savedDeterminators)
|
||||
{
|
||||
p.Value.OnUnregEvent();
|
||||
@@ -103,6 +116,11 @@ public static class GamePatch
|
||||
if (_test != null) _test.active = false;
|
||||
}
|
||||
|
||||
internal static void ResetState()
|
||||
{
|
||||
_test = null;
|
||||
}
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(PlayerController), nameof(PlayerController.Init))]
|
||||
private static void PlayerController_Init_Postfix(PlayerController __instance)
|
||||
@@ -127,7 +145,9 @@ public static class GamePatch
|
||||
{
|
||||
__instance.Update();
|
||||
}
|
||||
|
||||
// Harmony transpiler: PlayerAction_Test_Update_Transpiler
|
||||
// Target: PlayerAction_Test.Update
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(PlayerAction_Test), nameof(PlayerAction_Test.Update))]
|
||||
private static IEnumerable<CodeInstruction> PlayerAction_Test_Update_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
@@ -140,7 +160,7 @@ public static class GamePatch
|
||||
var pos = matcher.Pos;
|
||||
/* Remove Shift+F4 part of the method */
|
||||
matcher.Start().RemoveInstructions(pos).MatchForward(false,
|
||||
new CodeMatch(OpCodes.Call, AccessTools.Method(typeof(GameMain), "get_sandboxToolsEnabled")),
|
||||
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(GameMain), nameof(GameMain.sandboxToolsEnabled))),
|
||||
new CodeMatch(OpCodes.Ldc_I4_0),
|
||||
new CodeMatch(OpCodes.Ceq)
|
||||
);
|
||||
@@ -160,7 +180,9 @@ public static class GamePatch
|
||||
matcher.Labels = labels;
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
// Harmony transpiler: GameCamera_Logic_Transpiler
|
||||
// Target: GameCamera.FrameLogic
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(GameCamera), nameof(GameCamera.FrameLogic))]
|
||||
private static IEnumerable<CodeInstruction> GameCamera_Logic_Transpiler(IEnumerable<CodeInstruction> instructions)
|
||||
@@ -187,125 +209,4 @@ public static class GamePatch
|
||||
}
|
||||
}
|
||||
|
||||
public class UnlockTech : PatchImpl<UnlockTech>
|
||||
{
|
||||
private static void UnlockTechRecursive(GameHistoryData history, [NotNull] TechProto techProto, int maxLevel = 10000)
|
||||
{
|
||||
var techStates = history.techStates;
|
||||
var techID = techProto.ID;
|
||||
if (techStates == null || !techStates.TryGetValue(techID, out var value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (value.unlocked)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var maxLvl = Math.Min(maxLevel < 0 ? value.curLevel - maxLevel - 1 : maxLevel, value.maxLevel);
|
||||
|
||||
foreach (var preid in techProto.PreTechs)
|
||||
{
|
||||
var preProto = LDB.techs.Select(preid);
|
||||
if (preProto != null)
|
||||
UnlockTechRecursive(history, preProto, techProto.PreTechsMax ? 10000 : -1);
|
||||
}
|
||||
|
||||
foreach (var preid in techProto.PreTechsImplicit)
|
||||
{
|
||||
var preProto = LDB.techs.Select(preid);
|
||||
if (preProto != null)
|
||||
UnlockTechRecursive(history, preProto, techProto.PreTechsMax ? 10000 : -1);
|
||||
}
|
||||
|
||||
if (value.curLevel < techProto.Level) value.curLevel = techProto.Level;
|
||||
while (value.curLevel <= maxLvl)
|
||||
{
|
||||
if (value.curLevel == 0)
|
||||
{
|
||||
foreach (var recipe in techProto.UnlockRecipes)
|
||||
{
|
||||
history.UnlockRecipe(recipe);
|
||||
}
|
||||
}
|
||||
|
||||
for (var j = 0; j < techProto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
history.UnlockTechFunction(techProto.UnlockFunctions[j], techProto.UnlockValues[j], value.curLevel);
|
||||
}
|
||||
|
||||
for (var k = 0; k < techProto.AddItems.Length; k++)
|
||||
{
|
||||
history.GainTechAwards(techProto.AddItems[k], techProto.AddItemCounts[k]);
|
||||
}
|
||||
|
||||
value.curLevel++;
|
||||
}
|
||||
|
||||
value.unlocked = maxLvl >= value.maxLevel;
|
||||
value.curLevel = value.unlocked ? maxLvl : maxLvl + 1;
|
||||
value.hashNeeded = techProto.GetHashNeeded(value.curLevel);
|
||||
value.hashUploaded = value.unlocked ? value.hashNeeded : 0;
|
||||
techStates[techID] = value;
|
||||
history.RegFeatureKey(1000100);
|
||||
history.NotifyTechUnlock(techID, maxLvl, true);
|
||||
}
|
||||
|
||||
private static void OnClickTech(UITechNode node)
|
||||
{
|
||||
var history = GameMain.history;
|
||||
if (VFInput.shift)
|
||||
{
|
||||
if (VFInput.alt) return;
|
||||
if (VFInput.control)
|
||||
UnlockTechRecursive(history, node.techProto, -100);
|
||||
else
|
||||
UnlockTechRecursive(history, node.techProto, -1);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (VFInput.control)
|
||||
{
|
||||
if (!VFInput.alt)
|
||||
UnlockTechRecursive(history, node.techProto, -10);
|
||||
else
|
||||
return;
|
||||
}
|
||||
else if (VFInput.alt)
|
||||
{
|
||||
UnlockTechRecursive(history, node.techProto);
|
||||
}
|
||||
else
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
history.VarifyTechQueue();
|
||||
if (history.currentTech != history.techQueue[0])
|
||||
{
|
||||
history.currentTech = history.techQueue[0];
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UITechNode), nameof(UITechNode.OnPointerDown))]
|
||||
private static IEnumerable<CodeInstruction> UITechNode_OnPointerDown_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UITechNode), nameof(UITechNode.tree))),
|
||||
new CodeMatch(OpCodes.Callvirt, AccessTools.Method(typeof(UITechTree), "get_selected"))
|
||||
);
|
||||
var labels = matcher.Labels;
|
||||
matcher.Labels = null;
|
||||
matcher.Insert(
|
||||
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(UnlockTech), nameof(UnlockTech.OnClickTech)))
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,12 @@ using System.Reflection.Emit;
|
||||
using BepInEx.Configuration;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using UXAssist.Common.Patching;
|
||||
|
||||
namespace CheatEnabler.Patches;
|
||||
|
||||
[ModFeature("Planet")]
|
||||
public static class PlanetPatch
|
||||
{
|
||||
public static ConfigEntry<bool> WaterPumpAnywhereEnabled;
|
||||
@@ -31,6 +35,9 @@ public static class PlanetPatch
|
||||
|
||||
private class WaterPumperPatch : PatchImpl<WaterPumperPatch>
|
||||
{
|
||||
// Harmony transpiler: BuildTool_CheckBuildConditions_Transpiler
|
||||
// Target: BuildTool_BlueprintPaste.CheckBuildConditions, BuildTool_Click.CheckBuildConditions
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_BlueprintPaste.CheckBuildConditions))]
|
||||
[HarmonyPatch(typeof(BuildTool_Click), nameof(BuildTool_Click.CheckBuildConditions))]
|
||||
@@ -53,27 +60,126 @@ public static class PlanetPatch
|
||||
|
||||
private class TerraformAnyway : PatchImpl<TerraformAnyway>
|
||||
{
|
||||
// Harmony transpiler: BuildTool_BlueprintPaste_DetermineReforms_Patch
|
||||
// Target: BuildTool_BlueprintPaste.DetermineReforms
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(BuildTool_Reform), nameof(BuildTool_Reform.ReformAction))]
|
||||
private static IEnumerable<CodeInstruction> BuildTool_Reform_ReformAction_Patch(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
[HarmonyPatch(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_BlueprintPaste.DetermineReforms))]
|
||||
private static IEnumerable<CodeInstruction> BuildTool_BlueprintPaste_DetermineReforms_Patch(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(BuildTool), nameof(BuildTool.player))),
|
||||
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.sandCount))),
|
||||
new CodeMatch(ci => ci.IsStloc())
|
||||
).Advance(4).MatchForward(false,
|
||||
new CodeMatch(ci => ci.IsLdloc()),
|
||||
new CodeMatch(ci => ci.IsLdloc()),
|
||||
new CodeMatch(OpCodes.Conv_I8),
|
||||
new CodeMatch(ci => ci.opcode == OpCodes.Bge || ci.opcode == OpCodes.Bge_S)
|
||||
);
|
||||
var labels = matcher.Labels;
|
||||
matcher.Labels = null;
|
||||
matcher.RemoveInstructions(3);
|
||||
matcher.Labels.AddRange(labels);
|
||||
matcher.Opcode = OpCodes.Br;
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
// Harmony transpiler: BuildTool_Reform_RemoveBasePit_Patch
|
||||
// Target: BuildTool_Reform.RemoveBasePit
|
||||
// Fallback: Checks CodeMatcher.IsInvalid/IsValid and returns original instructions on mismatch.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(BuildTool_Reform), nameof(BuildTool_Reform.RemoveBasePit))]
|
||||
private static IEnumerable<CodeInstruction> BuildTool_Reform_RemoveBasePit_Patch(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(BuildTool_Reform), nameof(BuildTool_Reform.circlePointCount))),
|
||||
new CodeMatch(ci => ci.opcode == OpCodes.Blt || ci.opcode == OpCodes.Blt_S)
|
||||
).RemoveInstructions(2).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Ldc_I4_0)
|
||||
).MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(BuildTool), nameof(BuildTool.player))),
|
||||
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.sandCount))),
|
||||
new CodeMatch(ci => ci.IsLdloc()),
|
||||
new CodeMatch(OpCodes.Conv_I8),
|
||||
new CodeMatch(OpCodes.Sub)
|
||||
).Advance(6).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 0L),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Math), nameof(Math.Max), [typeof(long), typeof(long)]))
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
// Harmony transpiler: UIRemoveBasePitButton_OnRemoveButtonClick_Patch
|
||||
// Target: UIRemoveBasePitButton.OnRemoveButtonClick, UIRemoveBasePitButton._OnUpdate
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UIRemoveBasePitButton), nameof(UIRemoveBasePitButton.OnRemoveButtonClick))]
|
||||
[HarmonyPatch(typeof(UIRemoveBasePitButton), nameof(UIRemoveBasePitButton._OnUpdate))]
|
||||
private static IEnumerable<CodeInstruction> UIRemoveBasePitButton_OnRemoveButtonClick_Patch(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIRemoveBasePitButton), nameof(UIRemoveBasePitButton.pointCount))),
|
||||
new CodeMatch(OpCodes.Sub),
|
||||
new CodeMatch(OpCodes.Ldc_I4_0),
|
||||
new CodeMatch(OpCodes.Clt)
|
||||
);
|
||||
if (matcher.IsValid)
|
||||
{
|
||||
matcher.RemoveInstructions(2).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Ldc_I4_0)
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
matcher.Start();
|
||||
}
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UIRemoveBasePitButton), nameof(UIRemoveBasePitButton.player))),
|
||||
new CodeMatch(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.sandCount))),
|
||||
new CodeMatch(ci => ci.IsLdloc()),
|
||||
new CodeMatch(OpCodes.Conv_I8),
|
||||
new CodeMatch(OpCodes.Sub)
|
||||
).Advance(6).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 0L),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Math), nameof(Math.Max), [typeof(long), typeof(long)]))
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
[HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(BuildTool_Reform), nameof(BuildTool_Reform.DoFlattenExecute))]
|
||||
[HarmonyPatch(typeof(BuildTool_Reform), nameof(BuildTool_Reform.DoRestoreExecute))]
|
||||
private static void BuildTool_Reform_Execute_Prefix(BuildTool_Reform __instance, ref int needSandCount)
|
||||
{
|
||||
var sandCount = __instance.player.sandCount;
|
||||
if (needSandCount > sandCount)
|
||||
needSandCount = (int)sandCount;
|
||||
}
|
||||
|
||||
// Harmony transpiler: BuildTool_Reform_DoFlattenExecute_Patch
|
||||
// Target: BuildTool_Reform.DoFlattenExecute
|
||||
// Fallback: TranspilerGuard returns original instructions when the foundation count check is not found.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(BuildTool_Reform), nameof(BuildTool_Reform.DoFlattenExecute))]
|
||||
private static IEnumerable<CodeInstruction> BuildTool_Reform_DoFlattenExecute_Patch(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(BuildTool_Reform), nameof(BuildTool_Reform.cursorPointCount))),
|
||||
new CodeMatch(ci => ci.opcode == OpCodes.Blt || ci.opcode == OpCodes.Blt_S)
|
||||
).RemoveInstructions(2).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Ldc_I4_0)
|
||||
).MatchForward(false,
|
||||
new CodeMatch(OpCodes.Callvirt, AccessTools.Method(typeof(Player), "get_sandCount"))
|
||||
).Advance(1).MatchForward(false,
|
||||
new CodeMatch(OpCodes.Conv_I8),
|
||||
new CodeMatch(OpCodes.Sub)
|
||||
).Advance(2).InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Ldc_I8, 0L),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Math), "Max", [typeof(long), typeof(long)]))
|
||||
);
|
||||
if (matcher.IsInvalid)
|
||||
return matcher.Finish(instructions, CheatEnabler.Logger, nameof(BuildTool_Reform_DoFlattenExecute_Patch));
|
||||
var labels = matcher.Labels;
|
||||
matcher.RemoveInstructions(2).Insert(new CodeInstruction(OpCodes.Ldc_I4_0).WithLabels(labels));
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@ using System.Reflection.Emit;
|
||||
using BepInEx.Configuration;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
|
||||
namespace CheatEnabler.Patches;
|
||||
|
||||
[ModFeature("Player")]
|
||||
public static class PlayerPatch
|
||||
{
|
||||
public static ConfigEntry<bool> InstantHandCraftEnabled;
|
||||
@@ -45,6 +47,9 @@ public static class PlayerPatch
|
||||
|
||||
private class InstantTeleport : PatchImpl<InstantTeleport>
|
||||
{
|
||||
// Harmony transpiler: UIGlobemap__OnUpdate_Transpiler
|
||||
// Target: UIGlobemap._OnUpdate, UIStarmap.DoRightClickFastTravel, UIStarmap.OnFastTravelButtonClick, UIStarmap.OnScreenClick, UIStarmap.SandboxRightClickFastTravelLogic, UIStarmap.StartFastTravelToPlanet, UIStarmap.StartFastTravelToUPosition, UIStarmap.UpdateCursorView, UIStarmap._OnUpdate
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UIGlobemap), nameof(UIGlobemap._OnUpdate))]
|
||||
[HarmonyPatch(typeof(UIStarmap), nameof(UIStarmap.DoRightClickFastTravel))]
|
||||
|
||||
@@ -3,9 +3,11 @@ using System.Reflection.Emit;
|
||||
using BepInEx.Configuration;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
|
||||
namespace CheatEnabler.Patches;
|
||||
|
||||
[ModFeature("Resource")]
|
||||
public static class ResourcePatch
|
||||
{
|
||||
public static ConfigEntry<bool> InfiniteResourceEnabled;
|
||||
@@ -31,10 +33,13 @@ public static class ResourcePatch
|
||||
|
||||
private class InfiniteResource : PatchImpl<InfiniteResource>
|
||||
{
|
||||
static private readonly float InfiniteResourceRate = 0f;
|
||||
// Harmony transpiler: Transpiler
|
||||
// Target: FactorySystem.GameTick, GameLogic._miner_parallel, PlanetTransport.GameTick, UIChartAstroResource.CalculateMaxAmount, UIChartVeinGroup.CalculateMaxAmount, UIControlPanelAdvancedMinerEntry._OnUpdate, UIControlPanelVeinCollectorPanel._OnUpdate, UIMinerWindow._OnUpdate, UIMiningUpgradeLabel.Update, UIVeinCollectorPanel._OnUpdate
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(FactorySystem), nameof(FactorySystem.GameTick), typeof(long), typeof(bool))]
|
||||
[HarmonyPatch(typeof(FactorySystem), nameof(FactorySystem.GameTick), typeof(long), typeof(bool), typeof(int), typeof(int), typeof(int))]
|
||||
[HarmonyPatch(typeof(ItemProto), nameof(ItemProto.GetPropValue))]
|
||||
[HarmonyPatch(typeof(GameLogic), nameof(GameLogic._miner_parallel))]
|
||||
[HarmonyPatch(typeof(PlanetTransport), nameof(PlanetTransport.GameTick))]
|
||||
[HarmonyPatch(typeof(UIChartAstroResource), nameof(UIChartAstroResource.CalculateMaxAmount))]
|
||||
[HarmonyPatch(typeof(UIChartVeinGroup), nameof(UIChartVeinGroup.CalculateMaxAmount))]
|
||||
@@ -42,18 +47,29 @@ public static class ResourcePatch
|
||||
[HarmonyPatch(typeof(UIControlPanelVeinCollectorPanel), nameof(UIControlPanelVeinCollectorPanel._OnUpdate))]
|
||||
[HarmonyPatch(typeof(UIMinerWindow), nameof(UIMinerWindow._OnUpdate))]
|
||||
[HarmonyPatch(typeof(UIMiningUpgradeLabel), nameof(UIMiningUpgradeLabel.Update))]
|
||||
[HarmonyPatch(typeof(UIStationStorage), nameof(UIStationStorage.RefreshValues))]
|
||||
[HarmonyPatch(typeof(UIVeinCollectorPanel), nameof(UIVeinCollectorPanel._OnUpdate))]
|
||||
private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(GameHistoryData), nameof(GameHistoryData.miningCostRate)))
|
||||
new CodeMatch(ci => (ci.opcode == OpCodes.Ldfld || ci.opcode == OpCodes.Ldflda) && ci.OperandIs(AccessTools.Field(typeof(GameHistoryData), nameof(GameHistoryData.miningCostRate))))
|
||||
).Repeat(codeMatcher =>
|
||||
codeMatcher.RemoveInstruction().InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Pop),
|
||||
new CodeInstruction(OpCodes.Ldc_R4, 0f)
|
||||
)
|
||||
{
|
||||
if (codeMatcher.Instruction.opcode == OpCodes.Ldfld)
|
||||
{
|
||||
codeMatcher.RemoveInstruction().InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Pop),
|
||||
new CodeInstruction(OpCodes.Ldc_R4, InfiniteResourceRate)
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
codeMatcher.RemoveInstruction().InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Pop),
|
||||
new CodeInstruction(OpCodes.Ldsflda, AccessTools.Field(typeof(InfiniteResource), nameof(InfiniteResourceRate)))
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
@@ -61,29 +77,53 @@ public static class ResourcePatch
|
||||
|
||||
private class FastMining : PatchImpl<FastMining>
|
||||
{
|
||||
static private readonly float FastMiningSpeed = 2400f;
|
||||
// Harmony transpiler: Transpiler
|
||||
// Target: AstroResourceStatPlan.AddPlanetResources, BuildingGizmo.Update, FactorySystem.GameTick, GameLogic._miner_parallel, ItemProto.GetPropValue, PlanetTransport.GameTick, ProductionExtraInfoCalculator.CalculateFactory, UIChartAstroResource.CalculateMaxAmount, UIChartVeinGroup.CalculateMaxAmount, UIControlPanelStationStorage.RefreshValues, UIControlPanelVeinCollectorPanel._OnUpdate, UIMinerWindow._OnUpdate, UIMiningUpgradeLabel.Update, UIPlanetDetail.OnPlanetDataSet, UIPlanetDetail.RefreshDynamicProperties, UIReferenceSpeedTip.AddEntryDataWithFactory, UIStarDetail.OnStarDataSet, UIStarDetail.RefreshDynamicProperties, UIStationStorage.RefreshValues, UIVeinCollectorPanel._OnUpdate
|
||||
// Fallback: None — patch will fail loudly if the target method body changes.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(FactorySystem), "GameTick", typeof(long), typeof(bool))]
|
||||
[HarmonyPatch(typeof(FactorySystem), "GameTick", typeof(long), typeof(bool), typeof(int), typeof(int), typeof(int))]
|
||||
[HarmonyPatch(typeof(ItemProto), "GetPropValue")]
|
||||
[HarmonyPatch(typeof(PlanetTransport), "GameTick")]
|
||||
[HarmonyPatch(typeof(UIMinerWindow), "_OnUpdate")]
|
||||
[HarmonyPatch(typeof(UIMiningUpgradeLabel), "Update")]
|
||||
[HarmonyPatch(typeof(UIPlanetDetail), "OnPlanetDataSet")]
|
||||
[HarmonyPatch(typeof(UIPlanetDetail), "RefreshDynamicProperties")]
|
||||
[HarmonyPatch(typeof(UIStarDetail), "OnStarDataSet")]
|
||||
[HarmonyPatch(typeof(UIStarDetail), "RefreshDynamicProperties")]
|
||||
[HarmonyPatch(typeof(UIStationStorage), "RefreshValues")]
|
||||
[HarmonyPatch(typeof(UIVeinCollectorPanel), "_OnUpdate")]
|
||||
[HarmonyPatch(typeof(AstroResourceStatPlan), nameof(AstroResourceStatPlan.AddPlanetResources))]
|
||||
[HarmonyPatch(typeof(BuildingGizmo), nameof(BuildingGizmo.Update))]
|
||||
[HarmonyPatch(typeof(FactorySystem), nameof(FactorySystem.GameTick), typeof(long), typeof(bool))]
|
||||
[HarmonyPatch(typeof(GameLogic), nameof(GameLogic._miner_parallel))]
|
||||
[HarmonyPatch(typeof(ItemProto), nameof(ItemProto.GetPropValue))]
|
||||
[HarmonyPatch(typeof(PlanetTransport), nameof(PlanetTransport.GameTick))]
|
||||
[HarmonyPatch(typeof(ProductionExtraInfoCalculator), nameof(ProductionExtraInfoCalculator.CalculateFactory))]
|
||||
[HarmonyPatch(typeof(UIChartAstroResource), nameof(UIChartAstroResource.CalculateMaxAmount))]
|
||||
[HarmonyPatch(typeof(UIChartVeinGroup), nameof(UIChartVeinGroup.CalculateMaxAmount))]
|
||||
[HarmonyPatch(typeof(UIControlPanelStationStorage), nameof(UIControlPanelStationStorage.RefreshValues))]
|
||||
[HarmonyPatch(typeof(UIControlPanelVeinCollectorPanel), nameof(UIControlPanelVeinCollectorPanel._OnUpdate))]
|
||||
[HarmonyPatch(typeof(UIMinerWindow), nameof(UIMinerWindow._OnUpdate))]
|
||||
[HarmonyPatch(typeof(UIMiningUpgradeLabel), nameof(UIMiningUpgradeLabel.Update))]
|
||||
[HarmonyPatch(typeof(UIPlanetDetail), nameof(UIPlanetDetail.OnPlanetDataSet))]
|
||||
[HarmonyPatch(typeof(UIPlanetDetail), nameof(UIPlanetDetail.RefreshDynamicProperties))]
|
||||
[HarmonyPatch(typeof(UIReferenceSpeedTip), nameof(UIReferenceSpeedTip.AddEntryDataWithFactory))]
|
||||
[HarmonyPatch(typeof(UIStarDetail), nameof(UIStarDetail.OnStarDataSet))]
|
||||
[HarmonyPatch(typeof(UIStarDetail), nameof(UIStarDetail.RefreshDynamicProperties))]
|
||||
[HarmonyPatch(typeof(UIStationStorage), nameof(UIStationStorage.RefreshValues))]
|
||||
[HarmonyPatch(typeof(UIVeinCollectorPanel), nameof(UIVeinCollectorPanel._OnUpdate))]
|
||||
private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(GameHistoryData), nameof(GameHistoryData.miningSpeedScale)))
|
||||
new CodeMatch(ci => (ci.opcode == OpCodes.Ldfld || ci.opcode == OpCodes.Ldflda) && ci.OperandIs(AccessTools.Field(typeof(GameHistoryData), nameof(GameHistoryData.miningSpeedScale))))
|
||||
).Repeat(codeMatcher =>
|
||||
codeMatcher.RemoveInstruction().InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Pop),
|
||||
new CodeInstruction(OpCodes.Ldc_R4, 2400f)
|
||||
)
|
||||
{
|
||||
if (codeMatcher.Instruction.opcode == OpCodes.Ldfld)
|
||||
{
|
||||
codeMatcher.RemoveInstruction().InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Pop),
|
||||
new CodeInstruction(OpCodes.Ldc_R4, FastMiningSpeed)
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
codeMatcher.RemoveInstruction().InsertAndAdvance(
|
||||
new CodeInstruction(OpCodes.Pop),
|
||||
new CodeInstruction(OpCodes.Ldsflda, AccessTools.Field(typeof(FastMining), nameof(FastMiningSpeed)))
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Session level downgrade mode, toggled with <c>Caps Lock</c>.
|
||||
///
|
||||
/// The flag is intentionally not persisted: it is a per-session switch, so a game restart always comes
|
||||
/// back in the normal (upgrade) mode. The click handler reads <see cref="IsOn"/> at click time, so
|
||||
/// whatever the mode is at that moment wins.
|
||||
///
|
||||
/// Toggling reports itself exactly like the other CheatEnabler toggles (no condition build / no
|
||||
/// collision) do: a realtime tip ahead popup, plus an entry in the critical warning banner. The banner
|
||||
/// entry outranks the other two so the mode cannot be missed while they are on as well.
|
||||
/// </summary>
|
||||
internal static class DowngradeMode
|
||||
{
|
||||
public static bool IsOn { get; private set; }
|
||||
|
||||
/// <summary>Per-frame <c>Caps Lock</c> poll; driven by the mod feature registry input hook.</summary>
|
||||
public static void Update()
|
||||
{
|
||||
if (TechTweaksPatch.Enabled == null || !TechTweaksPatch.Enabled.Value ||
|
||||
TechTweaksPatch.Impl.GetHarmony() == null || DSPGame.IsMenuDemo || !GameMain.isRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (Input.GetKeyDown(KeyCode.CapsLock))
|
||||
{
|
||||
Toggle();
|
||||
}
|
||||
}
|
||||
|
||||
public static void Toggle()
|
||||
{
|
||||
IsOn = !IsOn;
|
||||
|
||||
if (!DSPGame.IsMenuDemo && GameMain.isRunning)
|
||||
{
|
||||
UIRoot.instance.uiGame.generalTips.InvokeRealtimeTipAhead(
|
||||
(IsOn ? Localization.TechDowngradeModeOn : Localization.TechDowngradeModeOff).Translate());
|
||||
GameMain.data?.warningSystem?.UpdateCriticalWarningText();
|
||||
}
|
||||
}
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
if (!IsOn) return;
|
||||
IsOn = false;
|
||||
GameMain.data?.warningSystem?.UpdateCriticalWarningText();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Entry point injected into UITechNode.OnPointerDown, shared by upgrade and downgrade clicks.
|
||||
/// </summary>
|
||||
internal static class TechClickHandler
|
||||
{
|
||||
public static void OnClickTech(UITechNode node)
|
||||
{
|
||||
// The handler runs inside the game's own click path, so nothing may escape from here and break
|
||||
// the tech tree UI.
|
||||
try
|
||||
{
|
||||
HandleClick(node);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
TechLog.Warn($"click handling failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void HandleClick(UITechNode node)
|
||||
{
|
||||
if (node == null || TechTweaksPatch.Enabled == null || !TechTweaksPatch.Enabled.Value)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TechProto techProto = node.techProto;
|
||||
if (techProto == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
GameHistoryData history = GameMain.history;
|
||||
if (history == null || history.techStates == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!TechKeyCombo.TryDecode(out int steps))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (DowngradeMode.IsOn)
|
||||
{
|
||||
TechDowngrade.Run(history, techProto, steps);
|
||||
}
|
||||
else
|
||||
{
|
||||
TechUnlock.Run(history, techProto, steps);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Plans the complete dependency cascade before changing tech states or live game objects.
|
||||
/// A dependent loses all applied levels when its prerequisite can no longer be researched.
|
||||
/// </summary>
|
||||
internal static class TechDowngrade
|
||||
{
|
||||
internal const int DeliveryPackageRecipeId = 122;
|
||||
|
||||
// Values are the last applied levels after this click, rather than the next research levels.
|
||||
private static readonly Dictionary<int, int> Targets = new();
|
||||
private static readonly HashSet<int> DirtyFuncs = new();
|
||||
private static readonly HashSet<int> Recipes = new();
|
||||
private static bool _inserterDirty;
|
||||
|
||||
public static void Run(GameHistoryData history, TechProto techProto, int steps)
|
||||
{
|
||||
if (!TryGetLastAppliedLevel(history, techProto, out int lastApplied) || steps <= 0) return;
|
||||
|
||||
int target = steps == TechKeyCombo.LevelToMax
|
||||
? techProto.Level - 1
|
||||
: System.Math.Max(techProto.Level - 1, lastApplied - steps);
|
||||
Targets.Clear();
|
||||
DirtyFuncs.Clear();
|
||||
Recipes.Clear();
|
||||
_inserterDirty = false;
|
||||
Plan(history, techProto, target);
|
||||
|
||||
if (!TechFuncRevert.CanRevert(history, Targets)) return;
|
||||
|
||||
int localStorageBefore = history.localStationExtraStorage;
|
||||
int remoteStorageBefore = history.remoteStationExtraStorage;
|
||||
foreach (var pair in Targets)
|
||||
{
|
||||
Apply(history, LDB.techs.Select(pair.Key), pair.Value);
|
||||
}
|
||||
|
||||
// All states must be final before checking shared recipes or recomputing function values.
|
||||
foreach (int recipeId in Recipes)
|
||||
{
|
||||
if (IsRecipeGranted(history, recipeId)) continue;
|
||||
history.recipeUnlocked.Remove(recipeId);
|
||||
if (recipeId == DeliveryPackageRecipeId)
|
||||
{
|
||||
GameMain.mainPlayer.deliveryPackage.unlocked = false;
|
||||
GameMain.mainPlayer.deliveryPackage.NotifySizeChange();
|
||||
}
|
||||
}
|
||||
|
||||
foreach (int func in DirtyFuncs)
|
||||
{
|
||||
// Both functions share one package layout and must only resize it once.
|
||||
if (func == 38 && DirtyFuncs.Contains(5)) continue;
|
||||
TechFuncRevert.Recompute(history, func);
|
||||
}
|
||||
|
||||
TechFuncRevert.ReconcileStationStorage(history, localStorageBefore, remoteStorageBefore);
|
||||
if (_inserterDirty) history.gameData.OnInserterTechChange();
|
||||
|
||||
TechUnlock.FinishClick(history);
|
||||
RefreshOpenWindow();
|
||||
}
|
||||
|
||||
internal static void MarkDirty(int func) => DirtyFuncs.Add(func);
|
||||
internal static void MarkInserterDirty() => _inserterDirty = true;
|
||||
|
||||
/// <summary>Completed techs store the last applied level; other techs store the next level.</summary>
|
||||
internal static int GetLastAppliedLevel(TechState state) => state.unlocked ? state.curLevel : state.curLevel - 1;
|
||||
|
||||
internal static bool TryGetLastAppliedLevel(GameHistoryData history, TechProto proto, out int lastApplied)
|
||||
{
|
||||
lastApplied = 0;
|
||||
if (history?.techStates == null || proto == null ||
|
||||
!history.techStates.TryGetValue(proto.ID, out TechState state)) return false;
|
||||
|
||||
lastApplied = GetLastAppliedLevel(state);
|
||||
return lastApplied >= proto.Level;
|
||||
}
|
||||
|
||||
internal static bool HasAnyAppliedLevel(GameHistoryData history, TechProto proto) =>
|
||||
TryGetLastAppliedLevel(history, proto, out _);
|
||||
|
||||
private static void Plan(GameHistoryData history, TechProto proto, int target)
|
||||
{
|
||||
if (Targets.ContainsKey(proto.ID) || !history.techStates.TryGetValue(proto.ID, out TechState state)) return;
|
||||
Targets.Add(proto.ID, target);
|
||||
|
||||
foreach (TechProto post in LDB.techs.dataArray)
|
||||
{
|
||||
if (post == null || post.ID == proto.ID ||
|
||||
!(Contains(post.PreTechs, proto.ID) || Contains(post.PreTechsImplicit, proto.ID))) continue;
|
||||
|
||||
// Mirrors GameHistoryData.TechUnlocked(id, max). A partially researched dependent also
|
||||
// needs to be reset; its own unlocked flag does not describe its prerequisite's validity.
|
||||
if (state.unlocked && target >= state.curLevel && (!post.PreTechsMax || target == state.maxLevel)) continue;
|
||||
if (!history.techStates.TryGetValue(post.ID, out TechState postState)) continue;
|
||||
if (GetLastAppliedLevel(postState) < post.Level && postState.hashUploaded == 0) continue;
|
||||
Plan(history, post, post.Level - 1);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Apply(GameHistoryData history, TechProto proto, int target)
|
||||
{
|
||||
TechState state = history.techStates[proto.ID];
|
||||
for (int level = GetLastAppliedLevel(state); level > target; level--)
|
||||
{
|
||||
for (int j = 0; j < proto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
TechFuncRevert.Revert(history, proto.UnlockFunctions[j], proto.UnlockValues[j], level);
|
||||
}
|
||||
}
|
||||
|
||||
state.unlocked = target >= state.maxLevel;
|
||||
state.curLevel = state.unlocked ? state.maxLevel : target + 1;
|
||||
state.hashNeeded = proto.GetHashNeeded(state.curLevel);
|
||||
state.hashUploaded = state.unlocked ? state.hashNeeded : 0L;
|
||||
state.unlockTick = 0;
|
||||
history.techStates[proto.ID] = state;
|
||||
if (target < proto.Level)
|
||||
{
|
||||
foreach (int recipe in proto.UnlockRecipes) Recipes.Add(recipe);
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool Contains(int[] array, int value)
|
||||
{
|
||||
if (array == null) return false;
|
||||
foreach (int item in array)
|
||||
{
|
||||
if (item == value) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
internal static bool IsRecipeGranted(GameHistoryData history, int recipeId,
|
||||
IReadOnlyDictionary<int, int> targets = null)
|
||||
{
|
||||
if (Contains(Configs.freeMode.recipes, recipeId)) return true;
|
||||
foreach (TechProto proto in LDB.techs.dataArray)
|
||||
{
|
||||
if (proto == null || !Contains(proto.UnlockRecipes, recipeId)) continue;
|
||||
int last = targets != null && targets.TryGetValue(proto.ID, out int target)
|
||||
? target
|
||||
: history.techStates.TryGetValue(proto.ID, out TechState state) ? GetLastAppliedLevel(state) : proto.Level - 1;
|
||||
if (last >= proto.Level) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
internal static void RefreshOpenWindow()
|
||||
{
|
||||
UITechTree window = UIRoot.instance?.uiGame?.techTree;
|
||||
if (window == null || !window.active) return;
|
||||
|
||||
// Restore native layering for all nodes once, without emitting research-complete events
|
||||
// or promoting downgraded nodes through the upgrade-only SortUnlockedNode path.
|
||||
window.SortTechNodeOrderInGroup(window.graphGroup0);
|
||||
window.SortTechNodeOrderInGroup(window.graphGroup1);
|
||||
foreach (UITechNode node in window.nodes.Values)
|
||||
{
|
||||
node.UpdateInfoComplete();
|
||||
node.UpdateInfoDynamic(true);
|
||||
node.UpdateLayoutDynamic(true, true);
|
||||
node.UpdateConnDynamic();
|
||||
}
|
||||
|
||||
window.selected?.RefreshPreTechCheckboxes();
|
||||
window.ResetTipDelay();
|
||||
window.RefreshDataValueText();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,995 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech
|
||||
{
|
||||
/// <summary>
|
||||
/// Reverts the fields changed by GameHistoryData.UnlockTechFunction. Lossy, multiplicative,
|
||||
/// assignment and boolean functions are recomputed from native defaults and surviving levels.
|
||||
/// Package geometry and station limits are reconciled once per click; native unlock side effects
|
||||
/// must never be replayed across the whole tech tree.
|
||||
/// </summary>
|
||||
internal static class TechFuncRevert
|
||||
{
|
||||
// Base values hard-coded by GameHistoryData.SetForNewGame().
|
||||
private const int BaseInserterStackCountObsolete = 1;
|
||||
private const int BaseInserterStackInput = 2;
|
||||
private const int BaseInserterStackOutput = 1;
|
||||
private const int BaseStorageLevel = 2;
|
||||
private const int BaseLabLevel = 3;
|
||||
private const int BaseStationPilerLevel = 1;
|
||||
private const int BaseDysonNodeAbsorbInterval = 360;
|
||||
|
||||
/// <summary>Function ids already reported as having no known inverse (log-once guard).</summary>
|
||||
private static readonly HashSet<int> UnknownFuncsWarned = new HashSet<int>();
|
||||
|
||||
/// <summary>The game's own rounding of <c>double</c> tech values to <c>int</c>.</summary>
|
||||
internal static int ToInt(double value) => (int)(value > 0.0 ? value + 0.5 : value - 0.5);
|
||||
|
||||
/// <summary>Mirrors <c>Mathf.Round(x * 1000f) / 1000f</c> used by func 21.</summary>
|
||||
private static float Round3Mathf(float value) => Mathf.Round(value * 1000f) / 1000f;
|
||||
|
||||
/// <summary>Mirrors <c>(float)(int)(x * 1000.0 + 0.5) / 1000f</c> used by funcs 61-64, 67 and 71.</summary>
|
||||
private static float Round3Trunc(float value) => (float)(int)((double)value * 1000.0 + 0.5) / 1000f;
|
||||
|
||||
/// <summary>Mirrors <c>(double)(int)(x * 1000.0 + 0.5) / 1000.0</c> used by func 84.</summary>
|
||||
private static double Round3Trunc(double value) => (int)(value * 1000.0 + 0.5) / 1000.0;
|
||||
|
||||
/// <summary>Undo one already applied level of <paramref name="func"/>.</summary>
|
||||
public static void Revert(GameHistoryData history, int func, double value, int level)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
Mecha mecha = player != null ? player.mecha : null;
|
||||
int num = ToInt(value);
|
||||
|
||||
switch (func)
|
||||
{
|
||||
case 1:
|
||||
if (mecha != null)
|
||||
{
|
||||
ConstructionModuleComponent module = mecha.constructionModule;
|
||||
module.droneCount = Math.Max(0, module.droneCount - num);
|
||||
module.droneAliveCount = Math.Max(0, Math.Min(module.droneAliveCount - num, module.droneCount));
|
||||
module.droneIdleCount = Math.Max(0, Math.Min(module.droneIdleCount - num, module.droneCount));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 2:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.reactorPowerGen -= value;
|
||||
if (mecha.reactorPowerGen < 0.0)
|
||||
{
|
||||
mecha.reactorPowerGen = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 3:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.walkSpeed -= (float)value;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 4: // assignment: recomputed from the techs that still grant it
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 5: // package geometry: recomputed together with func 38
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 6:
|
||||
// coreEnergyCap is additive, coreLevel is an assignment of the tech level -> the
|
||||
// capacity is reverted here and the level is recomputed.
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.coreEnergyCap -= value;
|
||||
if (mecha.coreEnergyCap < 0.0)
|
||||
{
|
||||
mecha.coreEnergyCap = 0.0;
|
||||
}
|
||||
mecha.coreEnergy = Math.Min(mecha.coreEnergy, mecha.coreEnergyCap);
|
||||
}
|
||||
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 7:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.replicateSpeed -= (float)value;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 8: // one-way flag: recomputed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 9:
|
||||
history.constructionDroneMovement = Math.Max(0, history.constructionDroneMovement - num);
|
||||
break;
|
||||
|
||||
case 10:
|
||||
history.constructionDroneSpeed -= (float)value;
|
||||
break;
|
||||
|
||||
case 11:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.maxSailSpeed -= (float)value;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 12:
|
||||
history.solarSailLife -= (float)value;
|
||||
break;
|
||||
|
||||
case 13: // multiplicative: recomputed (no float drift)
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 14: // assignment: recomputed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
TechDowngrade.MarkInserterDirty();
|
||||
break;
|
||||
|
||||
case 15:
|
||||
history.logisticDroneSpeedScale -= (float)value;
|
||||
break;
|
||||
|
||||
case 16:
|
||||
history.logisticShipSpeedScale -= (float)value;
|
||||
break;
|
||||
|
||||
case 17: // one-way flag: recomputed, and existing warpers are never removed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 18:
|
||||
history.logisticDroneCarries = Math.Max(0, history.logisticDroneCarries - num);
|
||||
break;
|
||||
|
||||
case 19:
|
||||
history.logisticShipCarries = Math.Max(0, history.logisticShipCarries - num);
|
||||
break;
|
||||
|
||||
case 20: // multiplicative with a 0 clamp: recomputed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 21:
|
||||
history.miningSpeedScale = Round3Mathf(history.miningSpeedScale - (float)value);
|
||||
break;
|
||||
|
||||
case 22:
|
||||
history.techSpeed = Math.Max(1, history.techSpeed - num);
|
||||
break;
|
||||
|
||||
case 23: // assignment
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 24:
|
||||
history.storageLevel = Math.Max(BaseStorageLevel, history.storageLevel - num);
|
||||
break;
|
||||
|
||||
case 25:
|
||||
history.labLevel = Math.Max(BaseLabLevel, history.labLevel - num);
|
||||
break;
|
||||
|
||||
case 26:
|
||||
history.dysonNodeLatitude -= (float)value;
|
||||
break;
|
||||
|
||||
case 27:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.maxWarpSpeed -= (float)(value * 40000.0);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 28: // assignment
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 29:
|
||||
history.stationPilerLevel = Math.Max(BaseStationPilerLevel, history.stationPilerLevel - num);
|
||||
break;
|
||||
|
||||
case 30:
|
||||
// Existing station limits are rescaled once after all levels have been reverted.
|
||||
history.localStationExtraStorage = Math.Max(0, history.localStationExtraStorage - num);
|
||||
break;
|
||||
|
||||
case 31:
|
||||
history.remoteStationExtraStorage = Math.Max(0, history.remoteStationExtraStorage - num);
|
||||
break;
|
||||
|
||||
case 32:
|
||||
if (player != null && player.deliveryPackage != null)
|
||||
{
|
||||
player.deliveryPackage.colCount = Math.Max(0, player.deliveryPackage.colCount - num);
|
||||
player.deliveryPackage.NotifySizeChange();
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 33:
|
||||
if (player != null && player.deliveryPackage != null)
|
||||
{
|
||||
player.deliveryPackage.stackSizeMultiplier = Math.Max(1, player.deliveryPackage.stackSizeMultiplier - num);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 34:
|
||||
history.logisticCourierSpeedScale -= (float)value;
|
||||
break;
|
||||
|
||||
case 35:
|
||||
history.logisticCourierCarries = Math.Max(0, history.logisticCourierCarries - num);
|
||||
break;
|
||||
|
||||
case 36:
|
||||
history.dispenserDeliveryMaxAngle = Math.Max(0f, history.dispenserDeliveryMaxAngle - num);
|
||||
break;
|
||||
|
||||
case 37: // feature keys: recomputed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 38:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 39:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
TechDowngrade.MarkInserterDirty();
|
||||
break;
|
||||
|
||||
case 40:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
TechDowngrade.MarkInserterDirty();
|
||||
break;
|
||||
|
||||
case 41:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
TechDowngrade.MarkInserterDirty();
|
||||
break;
|
||||
|
||||
case 42:
|
||||
case 43:
|
||||
case 44:
|
||||
case 45:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 61:
|
||||
history.kineticDamageScale = Round3Trunc(history.kineticDamageScale - (float)value);
|
||||
break;
|
||||
|
||||
case 62:
|
||||
history.energyDamageScale = Round3Trunc(history.energyDamageScale - (float)value);
|
||||
break;
|
||||
|
||||
case 63:
|
||||
history.blastDamageScale = Round3Trunc(history.blastDamageScale - (float)value);
|
||||
break;
|
||||
|
||||
case 64:
|
||||
history.magneticDamageScale = Round3Trunc(history.magneticDamageScale - (float)value);
|
||||
break;
|
||||
|
||||
case 65:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.energyShieldRadius = Math.Max(0f, mecha.energyShieldRadius - (float)value);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 66:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.energyShieldCapacity = Math.Max(0L, mecha.energyShieldCapacity - num);
|
||||
mecha.energyShieldEnergy = Math.Min(mecha.energyShieldEnergy, mecha.energyShieldCapacity);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 67:
|
||||
history.combatDroneDamageRatio = Round3Trunc(history.combatDroneDamageRatio - (float)value);
|
||||
break;
|
||||
|
||||
case 68:
|
||||
history.combatDroneROFRatio -= (float)value;
|
||||
break;
|
||||
|
||||
case 69:
|
||||
history.combatDroneDurabilityRatio -= (float)value;
|
||||
break;
|
||||
|
||||
case 70:
|
||||
history.combatDroneSpeedRatio -= (float)value;
|
||||
history.combatShipSpeedRatio -= (float)value;
|
||||
break;
|
||||
|
||||
case 71:
|
||||
history.combatShipDamageRatio = Round3Trunc(history.combatShipDamageRatio - (float)value);
|
||||
break;
|
||||
|
||||
case 72:
|
||||
history.combatShipROFRatio -= (float)value;
|
||||
break;
|
||||
|
||||
case 73:
|
||||
history.combatShipDurabilityRatio -= (float)value;
|
||||
break;
|
||||
|
||||
case 74: // ratio driven value: recomputed
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 75: // one-way flag
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 76: // assignment
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 77:
|
||||
if (mecha != null && mecha.groundCombatModule != null)
|
||||
{
|
||||
mecha.groundCombatModule.fleetCount = Math.Max(0, mecha.groundCombatModule.fleetCount - (int)value);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 78:
|
||||
history.groundFleetPortCount = Math.Max(0, history.groundFleetPortCount - (int)value);
|
||||
break;
|
||||
|
||||
case 79:
|
||||
if (mecha != null && mecha.spaceCombatModule != null)
|
||||
{
|
||||
mecha.spaceCombatModule.fleetCount = Math.Max(0, mecha.spaceCombatModule.fleetCount - (int)value);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 80:
|
||||
history.spaceFleetPortCount = Math.Max(0, history.spaceFleetPortCount - (int)value);
|
||||
break;
|
||||
|
||||
case 81:
|
||||
if (mecha != null)
|
||||
{
|
||||
RescaleHp(mecha, () => mecha.hpMaxUpgrade = Math.Max(0, mecha.hpMaxUpgrade - num));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 82:
|
||||
case 83:
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 84:
|
||||
if (mecha != null)
|
||||
{
|
||||
RescaleHp(mecha, () =>
|
||||
history.globalHpEnhancement = (float)Round3Trunc(history.globalHpEnhancement - (float)value));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 85:
|
||||
history.enemyDropScale -= (float)value;
|
||||
break;
|
||||
|
||||
case 86: // one-way flag
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
case 99: // one-way flag
|
||||
TechDowngrade.MarkDirty(func);
|
||||
break;
|
||||
|
||||
default:
|
||||
// Unknown / newly added function id: warn instead of guessing. Only once per id -
|
||||
// a downgrade can walk thousands of levels and must not flood the log.
|
||||
if (UnknownFuncsWarned.Add(func))
|
||||
{
|
||||
TechLog.Warn($"revert: no inverse known for tech function {func} (value={value}, level={level}); " +
|
||||
"the field was left untouched. A game update may have added a new function.");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recomputes the functions that cannot be inverted step by step. Called once per downgrade
|
||||
/// click after every level has been reverted.
|
||||
/// </summary>
|
||||
public static void Recompute(GameHistoryData history, int func)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
Mecha mecha = player != null ? player.mecha : null;
|
||||
ModeConfig freeMode = Configs.freeMode;
|
||||
if (freeMode == null)
|
||||
{
|
||||
TechLog.Warn($"recompute of tech function {func} skipped: Configs.freeMode is not available");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (func)
|
||||
{
|
||||
case 5:
|
||||
case 38:
|
||||
ReconcilePackage(history);
|
||||
break;
|
||||
|
||||
case 4:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.thrusterLevel = Math.Max(freeMode.mechaThrusterLevel,
|
||||
PickMax(history, func, freeMode.mechaThrusterLevel));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 6:
|
||||
if (mecha != null)
|
||||
{
|
||||
// func 6 assigns `coreLevel = level` (the tech's own level), not the value.
|
||||
mecha.coreLevel = Math.Max(freeMode.mechaCoreLevel, PickMaxLevel(history, func));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 8:
|
||||
history.useIonLayer = IsGrantedByAnyTech(history, func) || freeMode.useIonLayer;
|
||||
break;
|
||||
|
||||
case 13:
|
||||
history.solarEnergyLossRate = freeMode.solarEnergyLossRate * ProductOfAppliedValues(history, func);
|
||||
break;
|
||||
|
||||
case 14:
|
||||
history.inserterStackCountObsolete = Math.Max(BaseInserterStackCountObsolete,
|
||||
PickMax(history, func, BaseInserterStackCountObsolete));
|
||||
break;
|
||||
|
||||
case 17:
|
||||
// Never revoke the warp capability from stations that already have warpers: only the
|
||||
// history flag is recalculated. `SetAllStationsMaxWarperCount` has no inverse that
|
||||
// would not destroy existing warpers.
|
||||
history.logisticShipWarpDrive = IsGrantedByAnyTech(history, func) || freeMode.logisticShipWarpDrive;
|
||||
break;
|
||||
|
||||
case 20:
|
||||
float costRate = freeMode.miningCostRate * ProductOfAppliedValues(history, func);
|
||||
// Mirrors the clamp inside GameHistoryData.UnlockTechFunction case 20.
|
||||
if (costRate < TechProto.MINING_COST_CRITICAL_POINT)
|
||||
{
|
||||
costRate = 0f;
|
||||
}
|
||||
|
||||
history.miningCostRate = costRate;
|
||||
break;
|
||||
|
||||
case 23:
|
||||
history.universeObserveLevel = Math.Max(freeMode.universeObserveLevel,
|
||||
PickMax(history, func, freeMode.universeObserveLevel));
|
||||
break;
|
||||
|
||||
case 28:
|
||||
history.blueprintLimit = Math.Max(freeMode.blueprintLimit,
|
||||
PickMax(history, func, freeMode.blueprintLimit));
|
||||
break;
|
||||
|
||||
case 37:
|
||||
RecomputeFeatureKeys(history);
|
||||
break;
|
||||
|
||||
case 39:
|
||||
history.inserterStackOutput = Math.Max(BaseInserterStackOutput,
|
||||
PickMax(history, func, BaseInserterStackOutput));
|
||||
break;
|
||||
|
||||
case 40:
|
||||
history.inserterBidirectional = IsGrantedByAnyTech(history, func);
|
||||
break;
|
||||
|
||||
case 41:
|
||||
history.inserterStackInput = Math.Max(BaseInserterStackInput,
|
||||
PickMax(history, func, BaseInserterStackInput));
|
||||
break;
|
||||
|
||||
case 42:
|
||||
history.beltVerticalConstruction = IsGrantedByAnyTech(history, func);
|
||||
break;
|
||||
|
||||
case 43:
|
||||
// A shorter absorption interval is the upgrade, so the smallest granted value wins.
|
||||
history.dysonNodeAbsorbInterval = PickMin(history, func, BaseDysonNodeAbsorbInterval);
|
||||
break;
|
||||
|
||||
case 44:
|
||||
history.bpReformLimit = PickMax(history, func, 0);
|
||||
break;
|
||||
|
||||
case 45:
|
||||
history.manualPlantVegetation = IsGrantedByAnyTech(history, func);
|
||||
break;
|
||||
|
||||
case 74:
|
||||
RecomputePlanetaryAtField(history, freeMode);
|
||||
break;
|
||||
|
||||
case 75:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.energyShieldUnlocked = IsGrantedByAnyTech(history, func) || freeMode.unlockEnergyShield;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 76:
|
||||
int speed = 0;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
speed = Math.Max(speed, (int)value));
|
||||
history.autoReconstructSpeed = speed;
|
||||
break;
|
||||
|
||||
case 82:
|
||||
case 83:
|
||||
RecomputeLaser(history, freeMode, mecha, func);
|
||||
break;
|
||||
|
||||
case 86:
|
||||
if (mecha != null)
|
||||
{
|
||||
mecha.energyShieldBurstUnlocked =
|
||||
IsGrantedByAnyTech(history, func) || freeMode.unlockEnergyShieldBurst;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 99:
|
||||
history.missionAccomplished = IsGrantedByAnyTech(history, func);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// func 74 keeps the field expressed as <c>base / ratio</c>; the ratio grows by <c>value</c> per
|
||||
/// level and is rounded to two decimals each time. Rebuilding it from <c>1 + sum(values)</c>
|
||||
/// reproduces exactly what the sequence of forward operations produced, because the rounding is
|
||||
/// a no-op for two-decimal increments.
|
||||
/// </summary>
|
||||
private static void RecomputePlanetaryAtField(GameHistoryData history, ModeConfig freeMode)
|
||||
{
|
||||
double ratio = 1.0;
|
||||
ForEachAppliedFunction(history, 74, (proto, lastApplied, value) =>
|
||||
ratio += value * (lastApplied - proto.Level + 1));
|
||||
ratio = Math.Round(ratio, 2);
|
||||
if (ratio <= 0.0)
|
||||
{
|
||||
ratio = 1.0;
|
||||
}
|
||||
|
||||
long rate = (long)((double)freeMode.planetaryATFieldEnergyRate / ratio + 0.5);
|
||||
history.planetaryATFieldEnergyRate = Math.Max(1L, rate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// func 37 registers <c>1600000 + value</c> as a feature key. A key is kept while any tech that
|
||||
/// grants it still has a level applied, and removed otherwise.
|
||||
/// </summary>
|
||||
private static void RecomputeFeatureKeys(GameHistoryData history)
|
||||
{
|
||||
var allKeys = new HashSet<int>();
|
||||
var stillGranted = new HashSet<int>();
|
||||
TechProto[] all = LDB.techs.dataArray;
|
||||
for (int i = 0; i < all.Length; i++)
|
||||
{
|
||||
TechProto proto = all[i];
|
||||
if (proto?.UnlockFunctions == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int j = 0; j < proto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
if (proto.UnlockFunctions[j] != 37)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int key = 1600000 + ToInt(proto.UnlockValues[j]);
|
||||
allKeys.Add(key);
|
||||
if (TechDowngrade.HasAnyAppliedLevel(history, proto))
|
||||
{
|
||||
stillGranted.Add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (int key in allKeys)
|
||||
{
|
||||
if (stillGranted.Contains(key))
|
||||
{
|
||||
history.RegFeatureKey(key);
|
||||
}
|
||||
else
|
||||
{
|
||||
history.UnregFeatureKey(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static float ProductOfAppliedValues(GameHistoryData history, int func)
|
||||
{
|
||||
float product = 1f;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
{
|
||||
int count = lastApplied - proto.Level + 1;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
product *= (float)value;
|
||||
}
|
||||
});
|
||||
return product;
|
||||
}
|
||||
|
||||
private static int PickMax(GameHistoryData history, int func, int fallback)
|
||||
{
|
||||
int best = fallback;
|
||||
bool found = false;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
{
|
||||
int candidate = ToInt(value);
|
||||
if (!found || candidate > best)
|
||||
{
|
||||
best = candidate;
|
||||
found = true;
|
||||
}
|
||||
});
|
||||
return found ? best : fallback;
|
||||
}
|
||||
|
||||
private static int PickMin(GameHistoryData history, int func, int fallback)
|
||||
{
|
||||
int best = fallback;
|
||||
bool found = false;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
{
|
||||
int candidate = ToInt(value);
|
||||
if (!found || candidate < best)
|
||||
{
|
||||
best = candidate;
|
||||
found = true;
|
||||
}
|
||||
});
|
||||
return found ? best : fallback;
|
||||
}
|
||||
|
||||
/// <summary>Largest "last applied level" among all techs granting <paramref name="func"/>.</summary>
|
||||
private static int PickMaxLevel(GameHistoryData history, int func)
|
||||
{
|
||||
int best = 0;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
{
|
||||
if (lastApplied > best)
|
||||
{
|
||||
best = lastApplied;
|
||||
}
|
||||
});
|
||||
return best;
|
||||
}
|
||||
|
||||
private static bool IsGrantedByAnyTech(GameHistoryData history, int func)
|
||||
{
|
||||
bool found = false;
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) => found = true);
|
||||
return found;
|
||||
}
|
||||
|
||||
internal static void ForEachAppliedFunction(GameHistoryData history, int func, Action<TechProto, int, double> visit,
|
||||
IReadOnlyDictionary<int, int> targets = null)
|
||||
{
|
||||
if (history.techStates == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TechProto[] all = LDB.techs.dataArray;
|
||||
for (int i = 0; i < all.Length; i++)
|
||||
{
|
||||
TechProto proto = all[i];
|
||||
if (proto?.UnlockFunctions == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int lastApplied;
|
||||
if (targets != null && targets.TryGetValue(proto.ID, out int target))
|
||||
{
|
||||
lastApplied = target;
|
||||
if (lastApplied < proto.Level) continue;
|
||||
}
|
||||
else if (!TechDowngrade.TryGetLastAppliedLevel(history, proto, out lastApplied))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int j = 0; j < proto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
if (proto.UnlockFunctions[j] == func)
|
||||
{
|
||||
visit(proto, lastApplied, proto.UnlockValues[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// func 81 and 84 keep the current HP ratio while <c>hpMaxApplied</c> changes.
|
||||
/// </summary>
|
||||
private static void RescaleHp(Mecha mecha, Action changeMaxUpgrade)
|
||||
{
|
||||
int maxApplied = mecha.hpMaxApplied;
|
||||
float ratio = maxApplied > 0 ? (float)mecha.hp / maxApplied : 1f;
|
||||
changeMaxUpgrade();
|
||||
maxApplied = mecha.hpMaxApplied;
|
||||
mecha.hp = (int)(maxApplied * ratio + 0.5f);
|
||||
if (mecha.hp > maxApplied)
|
||||
{
|
||||
mecha.hp = maxApplied;
|
||||
}
|
||||
|
||||
mecha.hp = Math.Max(0, mecha.hp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Both ranges use the factor computed from the local range. Damage and energy use native
|
||||
/// integer rounding on every level, so division cannot recover the previous values exactly.
|
||||
/// </summary>
|
||||
private static void RecomputeLaser(GameHistoryData history, ModeConfig config, Mecha mecha, int func)
|
||||
{
|
||||
if (mecha == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (func == 82)
|
||||
{
|
||||
mecha.laserLocalAttackRange = config.mechaLocalLaserAttackRange;
|
||||
mecha.laserSpaceAttackRange = config.mechaSpaceLaserAttackRange;
|
||||
}
|
||||
else
|
||||
{
|
||||
mecha.laserLocalDamage = config.mechaLocalLaserDamage;
|
||||
mecha.laserSpaceDamage = config.mechaSpaceLaserDamage;
|
||||
mecha.laserEnergyCapacity = config.mechaLaserEnergyCapacity;
|
||||
mecha.laserLocalEnergyCost = config.mechaLocalLaserEnergyCost;
|
||||
mecha.laserSpaceEnergyCost = config.mechaSpaceLaserEnergyCost;
|
||||
}
|
||||
|
||||
ForEachAppliedFunction(history, func, (proto, lastApplied, value) =>
|
||||
{
|
||||
for (int level = proto.Level; level <= lastApplied; level++)
|
||||
{
|
||||
if (func == 82)
|
||||
{
|
||||
float factor = 1f + (float)(value / mecha.laserLocalAttackRange);
|
||||
mecha.laserLocalAttackRange *= factor;
|
||||
mecha.laserSpaceAttackRange *= factor;
|
||||
}
|
||||
else
|
||||
{
|
||||
float factor = 1f + (float)ToInt(value) / mecha.laserLocalDamage;
|
||||
mecha.laserLocalDamage = (int)(mecha.laserLocalDamage * factor + 0.5f);
|
||||
mecha.laserSpaceDamage = (int)(mecha.laserSpaceDamage * factor + 0.5f);
|
||||
mecha.laserEnergyCapacity = (int)(mecha.laserEnergyCapacity * factor + 0.5f);
|
||||
mecha.laserLocalEnergyCost = (int)(mecha.laserLocalEnergyCost * factor + 0.5f);
|
||||
mecha.laserSpaceEnergyCost = (int)(mecha.laserSpaceEnergyCost * factor + 0.5f);
|
||||
}
|
||||
}
|
||||
});
|
||||
if (func == 83) mecha.laserEnergy = Math.Min(mecha.laserEnergy, mecha.laserEnergyCapacity);
|
||||
}
|
||||
|
||||
/// <summary>Rejects the whole cascade before any state changes if capacity would hide live contents.</summary>
|
||||
internal static bool CanRevert(GameHistoryData history, IReadOnlyDictionary<int, int> targets)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
if (Configs.freeMode == null || history.gameData == null || player?.mecha == null ||
|
||||
player.package?.grids == null || player.deliveryPackage?.grids == null)
|
||||
{
|
||||
TechLog.Warn("downgrade skipped: game data is not ready");
|
||||
return false;
|
||||
}
|
||||
|
||||
var removed = new Dictionary<int, int>();
|
||||
bool deliveryUnlockRemoved = false;
|
||||
foreach (var pair in targets)
|
||||
{
|
||||
TechProto proto = LDB.techs.Select(pair.Key);
|
||||
int count = TechDowngrade.GetLastAppliedLevel(history.techStates[pair.Key]) - pair.Value;
|
||||
deliveryUnlockRemoved |= pair.Value < proto.Level &&
|
||||
TechDowngrade.Contains(proto.UnlockRecipes, TechDowngrade.DeliveryPackageRecipeId);
|
||||
for (int j = 0; j < proto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
int func = proto.UnlockFunctions[j];
|
||||
if (!(func is >= 1 and <= 45 or >= 61 and <= 86 or 99))
|
||||
{
|
||||
TechLog.Warn($"downgrade skipped: unsupported tech function {func} in tech {proto.ID}");
|
||||
UIRealtimeTip.Popup(Localization.TechDowngradeUnsupportedFunction.Translate());
|
||||
return false;
|
||||
}
|
||||
|
||||
int value = func is >= 77 and <= 80 ? (int)proto.UnlockValues[j] : ToInt(proto.UnlockValues[j]);
|
||||
removed.TryGetValue(func, out int previous);
|
||||
removed[func] = previous + value * count;
|
||||
}
|
||||
}
|
||||
|
||||
int packageCols = player.GetPackageColumnCount();
|
||||
int packageRows = (player.package.size - 1) / packageCols + 1;
|
||||
bool resizePackage = removed.ContainsKey(5) || removed.ContainsKey(38);
|
||||
if (resizePackage)
|
||||
{
|
||||
GetPackageGeometry(history, targets, out packageCols, out packageRows);
|
||||
if (!CanResizePackage(player, packageCols, packageRows))
|
||||
{
|
||||
UIRealtimeTip.Popup(Localization.PackageResizeSkippedOccupiedCells.Translate());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
DeliveryPackage delivery = player.deliveryPackage;
|
||||
removed.TryGetValue(32, out int deliveryColsRemoved);
|
||||
int deliveryCols = Math.Max(0, delivery.colCount - deliveryColsRemoved);
|
||||
int deliveryRows = resizePackage ? Math.Min(DeliveryPackage.MAX_ROWCOUNT, packageRows) : delivery.rowCount;
|
||||
bool deliveryLocked = deliveryUnlockRemoved &&
|
||||
!TechDowngrade.IsRecipeGranted(history, TechDowngrade.DeliveryPackageRecipeId, targets);
|
||||
for (int i = 0; i < delivery.grids.Length; i++)
|
||||
{
|
||||
if (!delivery.IsGridActive(i) || (!deliveryLocked &&
|
||||
i / DeliveryPackage.MAX_COLCOUNT < deliveryRows &&
|
||||
DeliveryPackage.MAX_COLCOUNT - 1 - i % DeliveryPackage.MAX_COLCOUNT < deliveryCols)) continue;
|
||||
if (delivery.grids[i].count > 0 || delivery.grids[i].ordered != 0)
|
||||
{
|
||||
UIRealtimeTip.Popup(Localization.TechDowngradeDeliveryOccupied.Translate());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
removed.TryGetValue(1, out int dronesRemoved);
|
||||
if (dronesRemoved > player.mecha.constructionModule.droneIdleCount)
|
||||
{
|
||||
UIRealtimeTip.Popup(Localization.TechDowngradeDronesBusy.Translate());
|
||||
return false;
|
||||
}
|
||||
|
||||
removed.TryGetValue(77, out int groundFleetsRemoved);
|
||||
removed.TryGetValue(79, out int spaceFleetsRemoved);
|
||||
if (!CanRemoveFleets(player.mecha.groundCombatModule, groundFleetsRemoved) ||
|
||||
!CanRemoveFleets(player.mecha.spaceCombatModule, spaceFleetsRemoved))
|
||||
{
|
||||
UIRealtimeTip.Popup(Localization.TechDowngradeFleetsOccupied.Translate());
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool CanRemoveFleets(CombatModuleComponent module, int removed)
|
||||
{
|
||||
if (removed <= 0 || module?.moduleFleets == null) return true;
|
||||
int target = Math.Max(0, module.fleetCount - removed);
|
||||
for (int i = target; i < Math.Min(module.fleetCount, module.moduleFleets.Length); i++)
|
||||
{
|
||||
ModuleFleet fleet = module.moduleFleets[i];
|
||||
if (fleet.fleetId != 0) return false;
|
||||
if (fleet.fighters == null) continue;
|
||||
foreach (ModuleFighter fighter in fleet.fighters)
|
||||
{
|
||||
if (fighter.count > 0 || fighter.craftId != 0) return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static void ReconcileStationStorage(GameHistoryData history, int localBefore, int remoteBefore)
|
||||
{
|
||||
int localDelta = history.localStationExtraStorage - localBefore;
|
||||
int remoteDelta = history.remoteStationExtraStorage - remoteBefore;
|
||||
if (localDelta == 0 && remoteDelta == 0) return;
|
||||
GameData data = history.gameData;
|
||||
for (int i = 0; i < data.factoryCount; i++)
|
||||
{
|
||||
PlanetTransport transport = data.factories[i]?.transport;
|
||||
if (transport == null) continue;
|
||||
// Native scaling uses the already updated capacity and the signed change. Passing a
|
||||
// negative delta restores the configured station limits without removing stored items.
|
||||
if (localDelta != 0) transport.OnTechFunctionUnlocked(30, localDelta, 0);
|
||||
if (remoteDelta != 0) transport.OnTechFunctionUnlocked(31, remoteDelta, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static void GetPackageGeometry(GameHistoryData history, IReadOnlyDictionary<int, int> targets,
|
||||
out int columns, out int rows)
|
||||
{
|
||||
const int baseColumns = 10;
|
||||
int baseSize = Configs.freeMode.playerPackageSize;
|
||||
int columnCount = baseColumns;
|
||||
int rowCount = (baseSize - 1) / baseColumns + 1;
|
||||
ForEachAppliedFunction(history, 38, (proto, last, value) =>
|
||||
columnCount += ToInt(value) * (last - proto.Level + 1), targets);
|
||||
ForEachAppliedFunction(history, 5, (proto, last, value) =>
|
||||
rowCount += ToInt(value) * (last - proto.Level + 1), targets);
|
||||
columns = columnCount;
|
||||
rows = rowCount;
|
||||
}
|
||||
|
||||
private static bool CanResizePackage(Player player, int columns, int rows)
|
||||
{
|
||||
StorageComponent package = player.package;
|
||||
int oldColumns = player.GetPackageColumnCount();
|
||||
for (int i = 0; i < package.size; i++)
|
||||
{
|
||||
if (package.grids[i].itemId != 0 && (i / oldColumns >= rows || i % oldColumns >= columns))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Native SetSize cannot shrink columns safely. Preserve each retained cell's position and
|
||||
/// metadata; CanRevert has already checked every cell that the new layout would remove.
|
||||
/// </summary>
|
||||
private static void ReconcilePackage(GameHistoryData history)
|
||||
{
|
||||
Player player = GameMain.mainPlayer;
|
||||
GetPackageGeometry(history, null, out int targetCols, out int targetRows);
|
||||
int targetSize = targetRows * targetCols;
|
||||
StorageComponent package = player.package;
|
||||
int oldCols = player.GetPackageColumnCount();
|
||||
if (oldCols == targetCols && package.size == targetSize) return;
|
||||
|
||||
var newGrid = new StorageComponent.GRID[targetSize];
|
||||
for (int i = 0; i < package.size; i++)
|
||||
{
|
||||
int row = i / oldCols;
|
||||
int col = i % oldCols;
|
||||
if (row < targetRows && col < targetCols) newGrid[row * targetCols + col] = package.grids[i];
|
||||
}
|
||||
|
||||
player.packageColCount = targetCols;
|
||||
package.grids = newGrid;
|
||||
package.size = targetSize;
|
||||
package.SetBans(Math.Min(package.bans, targetSize));
|
||||
package.ResetOptimizationFlags();
|
||||
package.NotifyStorageChange();
|
||||
package.NotifyStorageSizeChange();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// The key-modifier semantics shared by the upgrade and the downgrade side.
|
||||
///
|
||||
/// Both directions use the same modifier mapping:
|
||||
///
|
||||
/// <list type="table">
|
||||
/// <item><term>Shift</term><description>+1 / -1</description></item>
|
||||
/// <item><term>Ctrl</term><description>+10 / -10</description></item>
|
||||
/// <item><term>Ctrl + Shift</term><description>+100 / -100</description></item>
|
||||
/// <item><term>Alt</term><description>to MAX / back to locked</description></item>
|
||||
/// <item><term>Shift + Alt, Ctrl + Alt</term><description>ignored</description></item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal static class TechKeyCombo
|
||||
{
|
||||
/// <summary>Sentinel for the "Alt" combination: apply or revert everything this click can.</summary>
|
||||
public const int LevelToMax = int.MaxValue;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the currently held modifiers.
|
||||
/// Returns false when the combination carries no meaning and the click must be left alone.
|
||||
/// </summary>
|
||||
public static bool TryDecode(out int steps)
|
||||
{
|
||||
steps = 0;
|
||||
|
||||
if (VFInput.shift)
|
||||
{
|
||||
if (VFInput.alt)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
steps = VFInput.control ? 100 : 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (VFInput.control)
|
||||
{
|
||||
if (VFInput.alt)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
steps = 10;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (VFInput.alt)
|
||||
{
|
||||
steps = LevelToMax;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Single funnel for the tech unlock / downgrade feature's log output.
|
||||
///
|
||||
/// Only real problems are reported: a Harmony target that no longer resolves, a tech function without
|
||||
/// a known inverse, or a refused package resize. Those are conditions the player or the maintainer
|
||||
/// needs to know about after a game update.
|
||||
/// </summary>
|
||||
internal static class TechLog
|
||||
{
|
||||
public static void Warn(string message)
|
||||
{
|
||||
CheatEnabler.Logger.LogWarning("[TechTweaks] " + message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UIUtil = UXAssist.UI.Util;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>Owns the cloned native help button, including its lifetime and localized tooltip.</summary>
|
||||
internal static class TechTreeUI
|
||||
{
|
||||
private static UITechTree _window;
|
||||
private static UIButton _helpButton;
|
||||
|
||||
public static void OnTechTreeOpened(UITechTree window)
|
||||
{
|
||||
if (window == null) return;
|
||||
if (_window != window) Reset();
|
||||
_window = window;
|
||||
if (_helpButton != null) return;
|
||||
|
||||
Transform source = UIRoot.instance?.galaxySelect?.sandboxToggle?.transform.parent?.Find("tip-button");
|
||||
if (source == null) return;
|
||||
|
||||
GameObject clone = Object.Instantiate(source.gameObject, window.transform, false);
|
||||
clone.name = "TechTweaks-HelpButton";
|
||||
_helpButton = clone.GetComponent<UIButton>();
|
||||
if (_helpButton == null)
|
||||
{
|
||||
Object.Destroy(clone);
|
||||
return;
|
||||
}
|
||||
|
||||
// Reset cloned runtime state while retaining the native tooltip prefab and timing.
|
||||
UIButton.TipSettings tipSettings = _helpButton.tips;
|
||||
_helpButton.button?.onClick.RemoveAllListeners();
|
||||
UIUtil.ResetButton(_helpButton);
|
||||
_helpButton.tips = tipSettings;
|
||||
_helpButton.tips.topLevel = true;
|
||||
_helpButton.tips.corner = 3;
|
||||
|
||||
var rect = (RectTransform)clone.transform;
|
||||
Text caption = window.tabButtonText0;
|
||||
if (caption != null)
|
||||
{
|
||||
RectTransform captionRect = caption.rectTransform;
|
||||
rect.SetParent(captionRect.parent, false);
|
||||
rect.anchorMin = captionRect.anchorMin;
|
||||
rect.anchorMax = captionRect.anchorMax;
|
||||
rect.pivot = captionRect.pivot;
|
||||
rect.anchoredPosition3D = captionRect.anchoredPosition3D -
|
||||
new Vector3(0f, captionRect.rect.height + 4f, 0f);
|
||||
}
|
||||
else
|
||||
{
|
||||
UIUtil.NormalizeRectWithBottomLeft(rect, 24f, 24f, window.transform);
|
||||
}
|
||||
|
||||
rect.localScale = Vector3.one;
|
||||
RefreshText();
|
||||
clone.SetActive(true);
|
||||
}
|
||||
|
||||
public static void RefreshText()
|
||||
{
|
||||
if (_helpButton == null) return;
|
||||
_helpButton.tips.tipTitle = Localization.UnlockDowngradeTechWithKeyModifiers.Translate();
|
||||
_helpButton.tips.tipText = Localization.TechModifierHelpBody.Translate();
|
||||
_helpButton.UpdateTip();
|
||||
}
|
||||
|
||||
public static void Reset()
|
||||
{
|
||||
if (_helpButton != null)
|
||||
{
|
||||
_helpButton.gameObject.SetActive(false);
|
||||
Object.Destroy(_helpButton.gameObject);
|
||||
}
|
||||
|
||||
_window = null;
|
||||
_helpButton = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
|
||||
namespace CheatEnabler.Patches.Tech;
|
||||
|
||||
/// <summary>
|
||||
/// Upgrade side - unlock techs by clicking them with a key-modifier held while downgrade mode is off.
|
||||
///
|
||||
/// <see cref="UnlockTechRecursive"/> preserves the previous modifier-click upgrade behavior. The
|
||||
/// prerequisites are unlocked
|
||||
/// recursively (<c>PreTechs</c> / <c>PreTechsImplicit</c>, driven by <c>PreTechsMax</c>), recipes are
|
||||
/// unlocked on level 0, every level calls <c>UnlockTechFunction</c>, tech awards are granted, the hash
|
||||
/// counters are maintained and <c>NotifyTechUnlock</c> plus <c>RegFeatureKey(1000100)</c> are fired.
|
||||
/// </summary>
|
||||
internal static class TechUnlock
|
||||
{
|
||||
public static void Run(GameHistoryData history, TechProto techProto, int steps)
|
||||
{
|
||||
// Mirrors the built-in maxLevel argument: "to MAX" passes the default, the other combinations
|
||||
// pass -(steps) so the loop advances exactly `steps` levels.
|
||||
int maxLevel = steps == TechKeyCombo.LevelToMax ? 10000 : -steps;
|
||||
|
||||
UnlockTechRecursive(history, techProto, maxLevel);
|
||||
|
||||
FinishClick(history);
|
||||
}
|
||||
|
||||
/// <summary>Same post-click queue fix-up the built-in feature performs.</summary>
|
||||
internal static void FinishClick(GameHistoryData history)
|
||||
{
|
||||
history.VerifyTechQueue();
|
||||
if (history.techQueue != null && history.techQueue.Length > 0 && history.currentTech != history.techQueue[0])
|
||||
{
|
||||
history.currentTech = history.techQueue[0];
|
||||
}
|
||||
}
|
||||
|
||||
private static void UnlockTechRecursive(GameHistoryData history, TechProto techProto, int maxLevel = 10000)
|
||||
{
|
||||
var techStates = history.techStates;
|
||||
int techID = techProto.ID;
|
||||
if (techStates == null || !techStates.TryGetValue(techID, out TechState value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (value.unlocked)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int maxLvl = Math.Min(maxLevel < 0 ? value.curLevel - maxLevel - 1 : maxLevel, value.maxLevel);
|
||||
|
||||
foreach (int preid in techProto.PreTechs)
|
||||
{
|
||||
TechProto preProto = LDB.techs.Select(preid);
|
||||
if (preProto != null)
|
||||
{
|
||||
UnlockTechRecursive(history, preProto, techProto.PreTechsMax ? 10000 : -1);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (int preid in techProto.PreTechsImplicit)
|
||||
{
|
||||
TechProto preProto = LDB.techs.Select(preid);
|
||||
if (preProto != null)
|
||||
{
|
||||
UnlockTechRecursive(history, preProto, techProto.PreTechsMax ? 10000 : -1);
|
||||
}
|
||||
}
|
||||
|
||||
if (value.curLevel < techProto.Level)
|
||||
{
|
||||
value.curLevel = techProto.Level;
|
||||
}
|
||||
|
||||
while (value.curLevel <= maxLvl)
|
||||
{
|
||||
if (value.curLevel == 0)
|
||||
{
|
||||
foreach (int recipe in techProto.UnlockRecipes)
|
||||
{
|
||||
history.UnlockRecipe(recipe);
|
||||
}
|
||||
}
|
||||
|
||||
for (int j = 0; j < techProto.UnlockFunctions.Length; j++)
|
||||
{
|
||||
history.UnlockTechFunction(techProto.UnlockFunctions[j], techProto.UnlockValues[j], value.curLevel);
|
||||
}
|
||||
|
||||
for (int k = 0; k < techProto.AddItems.Length; k++)
|
||||
{
|
||||
history.GainTechAwards(techProto.AddItems[k], techProto.AddItemCounts[k]);
|
||||
}
|
||||
|
||||
value.curLevel++;
|
||||
}
|
||||
|
||||
// No trace inside the loop above on purpose: a single Alt-click on an "infinite" tech applies
|
||||
// thousands of levels, and one log write per level makes the game freeze.
|
||||
value.unlocked = maxLvl >= value.maxLevel;
|
||||
value.curLevel = value.unlocked ? maxLvl : maxLvl + 1;
|
||||
value.hashNeeded = techProto.GetHashNeeded(value.curLevel);
|
||||
value.hashUploaded = value.unlocked ? value.hashNeeded : 0L;
|
||||
techStates[techID] = value;
|
||||
history.RegFeatureKey(1000100);
|
||||
history.NotifyTechUnlock(techID, maxLvl, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection.Emit;
|
||||
using BepInEx.Configuration;
|
||||
using CheatEnabler.Patches.Tech;
|
||||
using HarmonyLib;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using UXAssist.Common.Patching;
|
||||
using GameLogicProc = UXAssist.Common.GameLogic;
|
||||
|
||||
namespace CheatEnabler.Patches;
|
||||
|
||||
/// <summary>Owns the General/UnlockTech option, session input and tech tree patches.</summary>
|
||||
[ModFeature("TechTweaks")]
|
||||
public static class TechTweaksPatch
|
||||
{
|
||||
public static ConfigEntry<bool> Enabled;
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
Enabled.SettingChanged += OnSettingChanged;
|
||||
GameLogicProc.OnGameEnd += ResetState;
|
||||
}
|
||||
|
||||
public static void Start() => Impl.Enable(Enabled.Value);
|
||||
|
||||
public static void Uninit()
|
||||
{
|
||||
Enabled.SettingChanged -= OnSettingChanged;
|
||||
GameLogicProc.OnGameEnd -= ResetState;
|
||||
Impl.Enable(false);
|
||||
ResetState();
|
||||
}
|
||||
|
||||
private static void OnSettingChanged(object sender, EventArgs args) => Impl.Enable(Enabled.Value);
|
||||
|
||||
public static void OnInputUpdate() => DowngradeMode.Update();
|
||||
|
||||
private static void ResetState()
|
||||
{
|
||||
DowngradeMode.Reset();
|
||||
TechTreeUI.Reset();
|
||||
}
|
||||
|
||||
public sealed class Impl : PatchImpl<Impl>
|
||||
{
|
||||
protected override void OnEnable()
|
||||
{
|
||||
DowngradeMode.Reset();
|
||||
UITechTree window = UIRoot.instance?.uiGame?.techTree;
|
||||
if (window != null && window.active) UpdateHelpButton(window);
|
||||
}
|
||||
|
||||
protected override void OnDisable() => ResetState();
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(UITechTree), nameof(UITechTree._OnOpen))]
|
||||
private static void UITechTree_OnOpen_Postfix(UITechTree __instance) => UpdateHelpButton(__instance);
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(UITechTree), nameof(UITechTree.OnLanguageChange))]
|
||||
private static void UITechTree_OnLanguageChange_Postfix() => TechTreeUI.RefreshText();
|
||||
|
||||
[HarmonyPostfix]
|
||||
[HarmonyPatch(typeof(UITechTree), nameof(UITechTree._OnFree))]
|
||||
private static void UITechTree_OnFree_Postfix() => TechTreeUI.Reset();
|
||||
|
||||
private static void UpdateHelpButton(UITechTree window)
|
||||
{
|
||||
try
|
||||
{
|
||||
TechTreeUI.OnTechTreeOpened(window);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
TechTreeUI.Reset();
|
||||
CheatEnabler.Logger.LogWarning($"[TechTweaks] creating the tech tree help button failed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
// Harmony transpiler: UITechNode_OnPointerDown_Transpiler
|
||||
// Target: UITechNode.OnPointerDown
|
||||
// Fallback: TranspilerGuard returns original instructions and logs a warning.
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(UITechNode), nameof(UITechNode.OnPointerDown))]
|
||||
private static IEnumerable<CodeInstruction> UITechNode_OnPointerDown_Transpiler(
|
||||
IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
matcher.MatchForward(false,
|
||||
new CodeMatch(OpCodes.Ldarg_0),
|
||||
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(UITechNode), nameof(UITechNode.tree))),
|
||||
new CodeMatch(OpCodes.Callvirt,
|
||||
AccessTools.PropertyGetter(typeof(UITechTree), nameof(UITechTree.selected))));
|
||||
if (matcher.IsInvalid)
|
||||
{
|
||||
return matcher.Finish(instructions, CheatEnabler.Logger, nameof(UITechNode_OnPointerDown_Transpiler));
|
||||
}
|
||||
|
||||
var labels = matcher.Labels;
|
||||
matcher.Labels = new List<Label>();
|
||||
matcher.Insert(
|
||||
new CodeInstruction(OpCodes.Ldarg_0).WithLabels(labels),
|
||||
new CodeInstruction(OpCodes.Call,
|
||||
AccessTools.Method(typeof(TechClickHandler), nameof(TechClickHandler.OnClickTech))));
|
||||
|
||||
return matcher.Finish(instructions, CheatEnabler.Logger, nameof(UITechNode_OnPointerDown_Transpiler));
|
||||
}
|
||||
}
|
||||
}
|
||||
+56
-16
@@ -13,26 +13,36 @@
|
||||
* General:
|
||||
* Enable Dev Shortcuts (check config panel for usage)
|
||||
* Disable Abnormal Checks
|
||||
* Unlock techs with key-modifiers (Ctrl/Alt/Shift)
|
||||
* Quickly upgrade/downgrade tech with key-modifiers (click the tech tree while holding Ctrl/Alt/Shift)
|
||||
* Hold `Shift` / `Ctrl` / `Ctrl+Shift` to change the level by 1 / 10 / 100; `Alt` upgrades to the maximum or returns the tech to locked in downgrade mode.
|
||||
* `Caps Lock` toggles session downgrade mode, shown by a realtime tip and a critical warning banner. Leaving the game or disabling this feature resets the mode.
|
||||
* Upgrading unlocks required prerequisites. Downgrading reverts the corresponding bonuses and removes dependent upgrade levels and research progress when their prerequisites become unavailable.
|
||||
* A downgrade is refused if capacity reductions would hide inventory or delivery contents, pending deliveries or equipped/deployed fleets, or if too few construction drones are idle. Empty affected slots, recall and empty affected fleets, or wait for drones to return before retrying.
|
||||
* The `?` button in the tech tree shows the full key reference.
|
||||
* Remove all metadata consumption records
|
||||
* Remove metadata consumption record in current game
|
||||
* Clear metadata flag which bans achievements
|
||||
* Assign gamesave to currrnet account
|
||||
* Assign gamesave to current account
|
||||
* Factory:
|
||||
* Finish build immediately
|
||||
* Architect mode (Infinite buildings)
|
||||
* Completes pending buildings as soon as their required building items are available
|
||||
* Architect mode
|
||||
* Unlimited use of buildings, Logistics Bots, Logistics Drones and Interstellar Logistics Vessels
|
||||
* Construction and inventory availability checks show at least 999 of each supported item.
|
||||
* Build without condition
|
||||
* No collision
|
||||
* Belt signal item generation
|
||||
* Count generations as production in statistics
|
||||
* Count removals as consumption in statistics
|
||||
* Count all raws and intermediates in statistics
|
||||
* Count proliferators used for raw materials, intermediates and finished products
|
||||
* Input calculations use recipe-specific extra-product or speed-up bonuses. Casimir Crystals and Energy Matrices are excluded; the option's help tooltip lists the extra-product recipes.
|
||||
* Belt signal alt format
|
||||
* Increase maximum power usage in Logistic Stations and Advanced Mining Machines
|
||||
* Logistic Stations: Increased max charging power to 3GW(ILS) and 600MW(PLS) (10x of original)
|
||||
* Advanced Mining Machines: Increased max mining speed to 1000%
|
||||
* Retrieve/Place items from/to remote planets on logistics control panel
|
||||
* Remove space limit between wind turbines and solar panels
|
||||
* Remove spacing limits for Wind Turbines and Geothermal Power Stations
|
||||
* Wind Turbines do global power coverage
|
||||
* Boost power generations for kinds of power generators
|
||||
* Planet:
|
||||
@@ -40,19 +50,29 @@
|
||||
* Infinite Natural Resources
|
||||
* Fast Mining
|
||||
* Pump Anywhere
|
||||
* Terraform without enought soil piles
|
||||
* Terraform without enough soil piles
|
||||
* Supports foundation placement, Restore Terrain, blueprint foundations and burying Dark Fog Core Drillers
|
||||
* Soil gains still take effect, and insufficient soil does not leave a negative balance.
|
||||
* Reform the entire planet or revert all terrain reforms from the config panel
|
||||
* Instant teleport (like that in Sandbox mode)
|
||||
* Dyson Sphere:
|
||||
* Skip bullet period
|
||||
* Optionally fire all buffered Solar Sails at once
|
||||
* Skip absorption period
|
||||
* Quick absorb
|
||||
* Eject anyway
|
||||
* Overclock Ejectors and Silos (10x firing speed)
|
||||
* Unlock Dyson Sphere max orbit radius
|
||||
* Complete Dyson Sphere Shells instantly
|
||||
* Buttons for creating illegal Dyson Sphere Shells, you must enable `IllegalDysonShellFunctionsEnabled` of `DysonSphere` section in config to see them.
|
||||
* Generate an illegal dyson shell
|
||||
* Keep max production shells and remove others
|
||||
* Duplicate shells from that with highest production
|
||||
* Remove all frames on Dyson Sphere
|
||||
* Keeps nodes and shells, preserving Solar Sail absorption while reducing rocket use for frames
|
||||
* Generate illegal Dyson Sphere Shells
|
||||
* The default quick-generation button creates new layers with the selected shell count.
|
||||
* Enable `IllegalDysonShellFunctions` in the `DysonSphere` config section to access the advanced controls:
|
||||
* Generate an illegal Dyson shell
|
||||
* Generate illegal shells for all existing layers without nodes and shells
|
||||
* Keep the highest-production shells and remove the others
|
||||
* Duplicate the highest-production shells with a configurable shell count
|
||||
* Mecha/Combat:
|
||||
* Mecha and Drones/Fleets invicible
|
||||
* Buildings invicible
|
||||
@@ -87,26 +107,36 @@
|
||||
* 常规:
|
||||
* 启用开发模式快捷键(使用说明见设置面板)
|
||||
* 屏蔽异常检测
|
||||
* 使用组合键解锁科技(Ctrl/Alt/Shift)
|
||||
* 使用组合键快速升降级科技(按住 Ctrl/Alt/Shift 点击科技树)
|
||||
* 按住 `Shift` / `Ctrl` / `Ctrl+Shift` 可改变 1 / 10 / 100 级;`Alt` 升到最大等级,降级模式下则回退到未解锁。
|
||||
* `Caps Lock` 切换本次游戏中的降级模式,并通过实时弹窗和严重警告横幅提示。离开游戏或关闭此功能后,降级模式重置。
|
||||
* 升级时解锁所需前置科技;降级时回退对应升级效果,前置条件失效的后继科技也会失去已应用等级和研究进度。
|
||||
* 缩容会隐藏机舱或物流清单中的物品、未完成的配送、有战斗机或尚未召回的编队,或空闲建设无人机数量不足时,会拒绝整次降级。清空相关格子、召回并清空相关编队,或等待建设无人机返回后再重试。
|
||||
* 科技树界面的 `?` 按钮显示完整组合键说明。
|
||||
* 移除所有元数据消耗记录
|
||||
* 移除当前存档的元数据消耗记录
|
||||
* 解除当前存档因使用元数据导致的成就限制
|
||||
* 将游戏存档绑定给当前账号
|
||||
* 工厂:
|
||||
* 建造秒完成
|
||||
* 建筑师模式(无限建筑)
|
||||
* 所需建筑物品齐备后立即完成待建造建筑
|
||||
* 建筑师模式
|
||||
* 建筑、配送运输机、物流运输机和星际物流运输船可无限使用
|
||||
* 建造及库存可用数量检查中,每种受支持物品至少显示 999 个。
|
||||
* 无条件建造
|
||||
* 无碰撞
|
||||
* 传送带信号物品生成
|
||||
* 统计信息里将生成计算为产物
|
||||
* 统计信息里将移除计算为消耗
|
||||
* 统计面板中计算所有原材料和中间产物
|
||||
* 统计原料、中间产物和成品使用的增产剂
|
||||
* 计算原料需求时使用对应配方的额外产出或加速效果;卡西米尔晶体和能量矩阵不使用增产剂。此选项的帮助提示列出使用额外产出的配方。
|
||||
* 传送带信号替换格式
|
||||
* 提升物流塔和大型采矿机的最大功耗
|
||||
* 物流塔:将最大充电功率提高到3GW(星际物流塔)和600MW(行星物流塔)(原来的10倍)
|
||||
* 大型采矿机:将最大采矿速度提高到1000%
|
||||
* 在物流总控面板上可以从非本地行星取放物品
|
||||
* 风力发电机和太阳能板无间距限制
|
||||
* 移除风力涡轮机和地热发电站的间距限制
|
||||
* 风力涡轮机供电覆盖全球
|
||||
* 提升各种发电设备发电量
|
||||
* 行星:
|
||||
@@ -115,18 +145,28 @@
|
||||
* 高速采集
|
||||
* 平地抽水
|
||||
* 沙土不够时依然可以整改地形
|
||||
* 支持铺设地基、还原地形、蓝图地基和掩埋黑雾核心钻机
|
||||
* 沙土收益仍正常生效,沙土不足时不会扣成负数。
|
||||
* 可在配置面板铺满星球地基或还原全部地形
|
||||
* 快速传送(和沙盒模式一样)
|
||||
* 戴森球:
|
||||
* 跳过子弹阶段
|
||||
* 可选择一次弹射所有已缓存的太阳帆
|
||||
* 跳过吸收阶段
|
||||
* 快速吸收
|
||||
* 全球弹射
|
||||
* 高速弹射器和高速发射井(10 倍射速)
|
||||
* 解锁戴森球最大轨道半径
|
||||
* 立即完成戴森壳建造
|
||||
* 用于制作仙术戴森壳的按钮,你必须在设置文件里开启`DysonSphere`分类的`IllegalDysonShellFunctionsEnabled`才能看到它们
|
||||
* 生成单层仙术戴森壳
|
||||
* 保留发电量最高的戴森壳并移除其他戴森壳
|
||||
* 从发电量最高的壳复制戴森壳
|
||||
* 移除戴森球上的所有框架
|
||||
* 保留节点和戴森壳,太阳帆吸收仍正常进行,可减少框架使用的火箭。
|
||||
* 生成仙术戴森壳
|
||||
* 默认的快速生成按钮会按所选壳面数量创建新的戴森球层级。
|
||||
* 在配置文件的 `DysonSphere` 分类中启用 `IllegalDysonShellFunctions`,可使用以下高级操作:
|
||||
* 生成单层仙术戴森壳
|
||||
* 为所有尚无节点和戴森壳的现有层级生成仙术戴森壳
|
||||
* 保留发电量最高的戴森壳并移除其他戴森壳
|
||||
* 从发电量最高的壳复制戴森壳,可设置壳面数量
|
||||
* 机甲/战斗:
|
||||
* 机甲和战斗无人机无敌
|
||||
* 建筑无敌
|
||||
|
||||
+61
-112
@@ -1,6 +1,9 @@
|
||||
using CheatEnabler.Functions;
|
||||
using CheatEnabler.Patches;
|
||||
using CheatEnabler.Patches.Factory;
|
||||
using FactoryPatch = CheatEnabler.Patches.Factory.FactoryPatch;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
using UXAssist.UI;
|
||||
using UXAssist.Common;
|
||||
using System;
|
||||
@@ -16,74 +19,6 @@ public static class UIConfigWindow
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
I18N.Add("Factory", "Factory", "工厂");
|
||||
I18N.Add("Planet", "Planet", "行星");
|
||||
I18N.Add("Mecha/Combat", "Mecha/Combat", "机甲/战斗");
|
||||
I18N.Add("Enable Dev Shortcuts", "Enable Dev Shortcuts", "开发模式快捷键");
|
||||
I18N.Add("Disable Abnormal Checks", "Disable Abnormal Checks", "关闭数据异常检查");
|
||||
I18N.Add("Hotkey", "Hotkey", "快捷键");
|
||||
I18N.Add("Unlock Tech with Key-Modifiers", "Unlock Tech with Key-Modifiers", "使用组合键点击解锁科技");
|
||||
I18N.Add("Dev Shortcuts", "Dev Shortcuts", "开发模式快捷键");
|
||||
I18N.Add("Dev Shortcuts Tips",
|
||||
"Caution: Some function may trigger abnormal check!\nNumpad 1: Gets all items and extends bag.\nNumpad 2: Boosts walk speed, gathering speed and mecha energy restoration.\nNumpad 3: Fills planet with foundations and bury all veins.\nNumpad 4: +1 construction drone.\nNumpad 5: Upgrades drone engine tech to full.\nNumpad 6: Unlocks researching tech.\nNumpad 7: Unlocks Drive Engine 1.\nNumpad 8: Unlocks Drive Engine 2 and maximize energy.\nNumpad 9: Unlocks ability to warp.\nNumpad 0: No costs for Logistic Storages' output.\nLCtrl + T: Unlocks all techs (not upgrades).\nLCtrl + Q: Adds 10000 to every metadata.\nLCtrl + W: Enters Sandbox Mode.\nLCtrl + Shift + W: Leaves Sandbox Mode.\nNumpad *: Proliferates items on hand.\nNumpad /: Removes proliferations from items on hand.\nPageDown: Remembers Pose of game camera.\nPageUp: Locks game camera using remembered Pose.",
|
||||
"警告:某些功能可能触发异常检查!\n小键盘1:获得所有物品并扩展背包\n小键盘2:加快行走速度及采集速度,加快能量恢复速度\n小键盘3:将地基铺设整个星球并掩埋所有矿物\n小键盘4:建设机器人 +1\n小键盘5:建设机器人满级\n小键盘6:解锁当前科技\n小键盘7:解锁驱动技术I\n小键盘8:解锁驱动技术II 最大化能量\n小键盘9:机甲曲速解锁\n小键盘0:物流站通过传送带出物品无消耗\n左Ctrl + T:解锁所有非升级科技\n左Ctrl + Q:增加各项元数据10000点\n左Ctrl + W:进入沙盒模式\n左Ctrl + Shift + W:离开沙盒模式\n小键盘乘号 *:给手上物品喷涂增产剂\n小键盘除号 /:清除手上物品的增产剂\nPageDown:记录摄像机当前的Pose\nPageUp:用记录的Pose锁定摄像机");
|
||||
I18N.Add("Unlock Tech with Key-Modifiers Tips",
|
||||
"Click tech on tree while holding:\n Shift: Tech level + 1\n Ctrl: Tech level + 10\n Ctrl + Shift: Tech level + 100\n Alt: Tech level to MAX\n\nNote: all direct prerequisites will be unlocked as well.",
|
||||
"按住以下组合键点击科技树:\n Shift:科技等级+1\n Ctrl:科技等级+10\n Ctrl+Shift:科技等级+100\n Alt:科技等级升到最大\n\n注意:所有直接前置科技也会被解锁");
|
||||
I18N.Add("Remove all metadata consumption records", "Remove all metadata consumption records", "移除所有元数据消耗记录");
|
||||
I18N.Add("Remove metadata consumption record in current game", "Remove metadata consumption record in current game", "移除当前存档的元数据消耗记录");
|
||||
I18N.Add("Clear metadata flag which bans achievements", "Clear metadata flag which bans achievements in current game", "解除当前存档因使用元数据导致的成就限制");
|
||||
I18N.Add("Assign gamesave to current account", "Assign gamesave to current account", "将游戏存档绑定给当前账号");
|
||||
I18N.Add("Finish build immediately", "Finish build immediately", "建造秒完成");
|
||||
I18N.Add("Architect mode", "Architect mode", "建筑师模式");
|
||||
I18N.Add("Build without condition", "Build without condition check", "无条件建造");
|
||||
I18N.Add("No collision", "No collision", "无碰撞");
|
||||
I18N.Add("Belt signal generator", "Belt signal generator", "传送带信号物品生成");
|
||||
I18N.Add("Belt signal alt format", "Belt signal alt format", "传送带信号替换格式");
|
||||
I18N.Add("Belt signal alt format tips",
|
||||
"Belt signal number format alternative format:\n AAAABC by default\n BCAAAA as alternative\nAAAA=generation speed in minutes, B=proliferate points, C=stack count",
|
||||
"传送带信号物品生成数量格式:\n 默认为AAAABC\n 勾选替换为BCAAAA\nAAAA=生成速度,B=增产点数,C=堆叠数量");
|
||||
I18N.Add("Count generations as production in statistics", "Count generations as production in statistics", "统计信息里将生成计算为产物");
|
||||
I18N.Add("Count removals as consumption in statistics", "Count removals as consumption in statistics", "统计信息里将移除计算为消耗");
|
||||
I18N.Add("Count all raws and intermediates in statistics", "Count all raw materials in statistics", "统计信息里计算所有原料和中间产物");
|
||||
I18N.Add("Remove power space limit", "Remove space limit for winds and geothermals", "移除风力发电和地热发电的间距限制");
|
||||
I18N.Add("Boost wind power", "Boost wind power(x100,000)", "提升风力发电(x100,000)");
|
||||
I18N.Add("Boost solar power", "Boost solar power(x100,000)", "提升太阳能发电(x100,000)");
|
||||
I18N.Add("Boost fuel power", "Boost fuel power(x50,000)", "提升燃料发电(x50,000)");
|
||||
I18N.Add("Boost fuel power 2", "(x20,000 for deuteron, x10,000 for antimatter)", "(氘核燃料棒x20,000,反物质燃料棒x10,000)");
|
||||
I18N.Add("Wind Turbines do global power coverage", "Wind Turbines do global power coverage", "风力涡轮机供电覆盖全球");
|
||||
I18N.Add("Boost geothermal power", "Boost geothermal power(x50,000)", "提升地热发电(x50,000)");
|
||||
I18N.Add("Increase maximum power usage in Logistic Stations and Advanced Mining Machines", "Increase maximum power usage in Logistic Stations and Advanced Mining Machines",
|
||||
"提升物流塔和大型采矿机的最大功耗");
|
||||
I18N.Add("Retrieve/Place items from/to remote planets on logistics control panel", "Retrieve/Place items from/to remote planets on logistics control panel", "在物流总控面板上可以从非本地行星取放物品");
|
||||
I18N.Add("Infinite Natural Resources", "Infinite natural resources", "自然资源采集不消耗");
|
||||
I18N.Add("Fast Mining", "Fast mining", "高速采集");
|
||||
I18N.Add("Pump Anywhere", "Pump anywhere", "平地抽水");
|
||||
I18N.Add("Skip bullet period", "Skip bullet period", "跳过子弹阶段");
|
||||
I18N.Add("Fire all bullets at once", "Fire all bullets at once", "一次弹射所有太阳帆");
|
||||
I18N.Add("Skip absorption period", "Skip absorption period", "跳过吸收阶段");
|
||||
I18N.Add("Quick absorb", "Quick absorb", "快速吸收");
|
||||
I18N.Add("Eject anyway", "Eject anyway", "全球弹射");
|
||||
I18N.Add("Overclock Ejectors", "Overclock Ejectors (10x)", "高速弹射器(10倍射速)");
|
||||
I18N.Add("Overclock Silos", "Overclock Silos (10x)", "高速发射井(10倍射速)");
|
||||
I18N.Add("Unlock Dyson Sphere max orbit radius", "Unlock Dyson Sphere max orbit radius", "解锁戴森球最大轨道半径");
|
||||
I18N.Add("Complete Dyson Sphere shells instantly", "Complete Dyson Sphere shells instantly", "立即完成戴森壳建造");
|
||||
I18N.Add("Generate illegal dyson shell", "Generate an illegal dyson shell (!!All shells will be removed first!!)", "生成单层仙术戴森壳(!!会先删除全部的壳!!)");
|
||||
I18N.Add("Keep max production shells and remove others", "Keep max production shells and remove others", "保留发电量最高的戴森壳并移除其他戴森壳");
|
||||
I18N.Add("Duplicate shells from that with highest production", "Duplicate shells from that with highest production", "从发电量最高的壳复制戴森壳");
|
||||
I18N.Add("Generate illegal dyson shell quickly", "Generate illegal dyson shell quickly", "快速生成仙术戴森壳");
|
||||
I18N.Add("Shells count", "Shells count", "壳面数量");
|
||||
I18N.Add("WARNING: This operation can be very slow, continue?", "WARNING: This operation can be very slow, continue?", "警告:此操作可能非常慢,继续吗?");
|
||||
I18N.Add("WARNING: This operation is DANGEROUS, continue?", "WARNING: This operation is DANGEROUS, continue?", "警告:此操作非常危险,继续吗?");
|
||||
I18N.Add("Terraform without enough soil piles", "Terraform without enough soil piles", "沙土不够时依然可以整改地形");
|
||||
I18N.Add("Instant hand-craft", "Instant hand-craft", "快速手动制造");
|
||||
I18N.Add("Instant teleport (like that in Sandbox mode)", "Instant teleport (like that in Sandbox mode)", "快速传送(和沙盒模式一样)");
|
||||
I18N.Add("Mecha and Drones/Fleets invicible", "Mecha and Drones/Fleets invicible", "机甲和战斗无人机无敌");
|
||||
I18N.Add("Buildings invicible", "Buildings invincible", "建筑无敌");
|
||||
I18N.Add("Enable warp without space warpers", "Enable warp without space warpers", "无需空间翘曲器即可曲速飞行");
|
||||
I18N.Add("Teleport to outer space", "Teleport to outer space", "传送到外太空");
|
||||
I18N.Add("Teleport to selected astronomical", "Teleport to selected astronomical", "传送到选中的天体");
|
||||
I18N.Apply();
|
||||
MyConfigWindow.OnUICreated += CreateUI;
|
||||
MyConfigWindow.OnUpdateUI += UpdateUI;
|
||||
}
|
||||
@@ -108,34 +43,34 @@ public static class UIConfigWindow
|
||||
}
|
||||
}
|
||||
|
||||
class ShellsCountMapper : MyWindow.RangeValueMapper<int>
|
||||
private static InputField AddShellsCountInput(MyConfigWindow wnd, float x, float y, RectTransform parent, string objName)
|
||||
{
|
||||
public ShellsCountMapper() : base(1, 139)
|
||||
{
|
||||
}
|
||||
var config = DysonSphereFunctions.ShellsCountForFunctions;
|
||||
var count = Mathf.Clamp(config.Value, DysonSphereFunctions.MinShellsCountForFunctions, DysonSphereFunctions.MaxShellsCountForFunctions);
|
||||
if (config.Value != count) config.Value = count;
|
||||
|
||||
public override int ValueToIndex(int value)
|
||||
InputField input = null;
|
||||
input = wnd.AddInputField(x, y, parent, count.ToString(), 15, objName, onEditEnd: value =>
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
< 4 => value,
|
||||
< 64 => value / 4 + 3,
|
||||
< 256 => value / 16 + 15,
|
||||
< 4096 => value / 64 + 27,
|
||||
_ => value / 256 + 75,
|
||||
};
|
||||
}
|
||||
if (!int.TryParse(value, out var parsed)) parsed = config.Value;
|
||||
parsed = Mathf.Clamp(parsed, DysonSphereFunctions.MinShellsCountForFunctions, DysonSphereFunctions.MaxShellsCountForFunctions);
|
||||
config.Value = parsed;
|
||||
input.text = parsed.ToString();
|
||||
});
|
||||
input.contentType = InputField.ContentType.IntegerNumber;
|
||||
input.characterLimit = 5;
|
||||
|
||||
public override int IndexToValue(int index)
|
||||
config.SettingChanged += OnShellsCountChanged;
|
||||
wnd.OnFree += () => config.SettingChanged -= OnShellsCountChanged;
|
||||
return input;
|
||||
|
||||
void OnShellsCountChanged(object o, EventArgs e)
|
||||
{
|
||||
return index switch
|
||||
{
|
||||
< 4 => index,
|
||||
< 19 => (index - 3) * 4,
|
||||
< 31 => (index - 15) * 16,
|
||||
< 91 => (index - 27) * 64,
|
||||
_ => (index - 75) * 256,
|
||||
};
|
||||
var normalized = Mathf.Clamp(config.Value, DysonSphereFunctions.MinShellsCountForFunctions, DysonSphereFunctions.MaxShellsCountForFunctions);
|
||||
if (config.Value != normalized) config.Value = normalized;
|
||||
|
||||
var value = normalized.ToString();
|
||||
if (input.text != value) input.text = value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,10 +91,11 @@ public static class UIConfigWindow
|
||||
y += 30f;
|
||||
wnd.AddCheckBox(x, y, tab1, GamePatch.AbnormalDisablerEnabled, "Disable Abnormal Checks");
|
||||
y += 36f;
|
||||
cb = wnd.AddCheckBox(x, y, tab1, GamePatch.UnlockTechEnabled, "Unlock Tech with Key-Modifiers");
|
||||
cb = wnd.AddCheckBox(x, y, tab1, TechTweaksPatch.Enabled, Localization.UnlockDowngradeTechWithKeyModifiers);
|
||||
x += cb.Width + 5f;
|
||||
y += 6f;
|
||||
wnd.AddTipsButton2(x, y, tab1, "Unlock Tech with Key-Modifiers", "Unlock Tech with Key-Modifiers Tips", "unlock-tech-tips");
|
||||
wnd.AddTipsButton2(x, y, tab1, Localization.UnlockDowngradeTechWithKeyModifiers,
|
||||
Localization.TechModifierHelpBody, "unlock-tech-tips");
|
||||
x = 0f;
|
||||
y += 30f + 36f;
|
||||
wnd.AddButton(x, y, 400f, tab1, "Remove all metadata consumption records", 16, "button-remove-all-metadata-consumption", PlayerFunctions.RemoveAllMetadataConsumptions);
|
||||
@@ -191,13 +127,14 @@ public static class UIConfigWindow
|
||||
y += 26f;
|
||||
var cb3 = wnd.AddCheckBox(x, y, tab2, FactoryPatch.BeltSignalCountRecipeEnabled, "Count all raws and intermediates in statistics", 13);
|
||||
y += 26f;
|
||||
var cb4 = wnd.AddCheckBox(x, y, tab2, FactoryPatch.BeltSignalNumberAltFormat, "Belt signal alt format", 13);
|
||||
x += cb4.Width + 5f;
|
||||
var cb4 = wnd.AddCheckBox(x, y, tab2, FactoryPatch.BeltSignalUseProliferatorEnabled, "Count proliferators used for raws/intermediates and finished products", 13);
|
||||
y += 6f;
|
||||
var tip1 = wnd.AddTipsButton2(x, y, tab2, "Belt signal alt format", "Belt signal alt format tips", "belt-signal-alt-format-tips");
|
||||
var tip1 = wnd.AddTipsButton2(x + cb4.Width + 5f, y, tab2, "Count proliferators used for raws/intermediates and finished products", "Count proliferators used for raws/intermediates and finished products tips", "count-proliferators-used-for-raws-intermediates-and-finished-products-tips");
|
||||
y += 20f;
|
||||
var cb5 = wnd.AddCheckBox(x, y, tab2, FactoryPatch.BeltSignalNumberAltFormat, "Belt signal alt format", 13);
|
||||
y += 6f;
|
||||
var tip2 = wnd.AddTipsButton2(x + cb5.Width + 5f, y, tab2, "Belt signal alt format", "Belt signal alt format tips", "belt-signal-alt-format-tips");
|
||||
x = 0f;
|
||||
y += 30f;
|
||||
wnd.AddCheckBox(x, y, tab2, FactoryPatch.GreaterPowerUsageInLogisticsEnabled, "Increase maximum power usage in Logistic Stations and Advanced Mining Machines");
|
||||
y += 36f;
|
||||
wnd.AddCheckBox(x, y, tab2, FactoryPatch.ControlPanelRemoteLogisticsEnabled, "Retrieve/Place items from/to remote planets on logistics control panel");
|
||||
{
|
||||
@@ -211,7 +148,9 @@ public static class UIConfigWindow
|
||||
cb2.gameObject.SetActive(on);
|
||||
cb3.gameObject.SetActive(on);
|
||||
cb4.gameObject.SetActive(on);
|
||||
cb5.gameObject.SetActive(on);
|
||||
tip1.gameObject.SetActive(on);
|
||||
tip2.gameObject.SetActive(on);
|
||||
}
|
||||
}
|
||||
x = 350f;
|
||||
@@ -247,11 +186,11 @@ public static class UIConfigWindow
|
||||
wnd.AddCheckBox(x, y, tab3, PlayerPatch.InstantTeleportEnabled, "Instant teleport (like that in Sandbox mode)");
|
||||
x = 400f;
|
||||
y = 10f;
|
||||
wnd.AddButton(x, y, 200f, tab3, "矿物掩埋标题", 16, "button-bury-all", () => { PlanetFunctions.BuryAllVeins(true); });
|
||||
wnd.AddButton(x, y, 200f, tab3, "Bury all veins", 16, "button-bury-all", () => { PlanetFunctions.BuryAllVeins(true); });
|
||||
y += 36f;
|
||||
wnd.AddButton(x, y, 200f, tab3, "矿物还原标题", 16, "button-bury-restore-all", () => { PlanetFunctions.BuryAllVeins(false); });
|
||||
wnd.AddButton(x, y, 200f, tab3, "Restore buried veins", 16, "button-bury-restore-all", () => { PlanetFunctions.BuryAllVeins(false); });
|
||||
y += 36f;
|
||||
wnd.AddButton(x, y, 200f, tab3, "铺满地基提示", 16, "button-reform-all", () =>
|
||||
wnd.AddButton(x, y, 200f, tab3, "Reform entire planet", 16, "button-reform-all", () =>
|
||||
{
|
||||
var player = GameMain.mainPlayer;
|
||||
if (player == null) return;
|
||||
@@ -261,7 +200,7 @@ public static class UIConfigWindow
|
||||
GameMain.localPlanet.factory.PlanetReformAll(reformTool.brushType, reformTool.brushColor, reformTool.buryVeins);
|
||||
});
|
||||
y += 36f;
|
||||
wnd.AddButton(x, y, 200f, tab3, "还原地形提示", 16, "button-reform-revert-all", () =>
|
||||
wnd.AddButton(x, y, 200f, tab3, "Revert planet terrain", 16, "button-reform-revert-all", () =>
|
||||
{
|
||||
var factory = GameMain.localPlanet?.factory;
|
||||
if (factory == null) return;
|
||||
@@ -301,38 +240,46 @@ public static class UIConfigWindow
|
||||
x = 300f;
|
||||
y = 10f;
|
||||
wnd.AddButton(x, y, 300f, tab4, "Complete Dyson Sphere shells instantly", 16, "button-complete-dyson-sphere-shells-instantly", DysonSphereFunctions.CompleteShellsInstantly);
|
||||
y += 36f;
|
||||
wnd.AddButton(x, y, 300f, tab4, "Remove all frames on Dyson Sphere", 16, "button-remove-all-frames-on-dyson-sphere", DysonSphereFunctions.RemoveAllFrames);
|
||||
{
|
||||
y += 72f;
|
||||
var originalY = y;
|
||||
var btn1 = wnd.AddButton(x, y, 300f, tab4, "Generate illegal dyson shell", 16, "button-generate-illegal-dyson-shells", () =>
|
||||
var btn0 = wnd.AddButton(x, y, 300f, tab4, "Generate illegal dyson shell", 16, "button-generate-illegal-dyson-shells", () =>
|
||||
{
|
||||
UIMessageBox.Show("Generate illegal dyson shell".Translate(), "WARNING: This operation can be very slow, continue?".Translate(), "取消".Translate(), "确定".Translate(), UIMessageBox.WARNING, null,
|
||||
UIMessageBox.Show(Localization.GenerateIllegalDysonShell.Translate(), Localization.WARNINGThisOperationCanBeVerySlowContinue.Translate(), Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.WARNING, null,
|
||||
() => { DysonSphereFunctions.CreateIllegalDysonShellWithMaxOutput(); });
|
||||
});
|
||||
y += 36f;
|
||||
var btn1 = wnd.AddButton(x, y, 300f, tab4, "Generate illegal dyson shell 2", 16, "button-generate-illegal-dyson-shells", () =>
|
||||
{
|
||||
UIMessageBox.Show(Localization.GenerateIllegalDysonShell2.Translate(), Localization.WARNINGThisOperationCanBeVerySlowContinue.Translate(), Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.WARNING, null,
|
||||
() => { DysonSphereFunctions.CreateIllegalDysonShellWithMaxOutputForAllLayers(); });
|
||||
});
|
||||
y += 36f;
|
||||
var btn2 = wnd.AddButton(x, y, 300f, tab4, "Keep max production shells and remove others", 16, "button-keep-max-production-shells", () =>
|
||||
{
|
||||
UIMessageBox.Show("Keep max production shells and remove others".Translate(), "WARNING: This operation is DANGEROUS, continue?".Translate(), "取消".Translate(), "确定".Translate(), UIMessageBox.WARNING, null,
|
||||
UIMessageBox.Show(Localization.KeepMaxProductionShellsAndRemoveOthers.Translate(), Localization.WARNINGThisOperationIsDANGEROUSContinue.Translate(), Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.WARNING, null,
|
||||
() => { DysonSphereFunctions.KeepMaxProductionShells(); });
|
||||
});
|
||||
y += 36f;
|
||||
var btn3 = wnd.AddButton(x, y, 300f, tab4, "Duplicate shells from that with highest production", 16, "button-duplicate-shells-from-the-highest-production", () =>
|
||||
{
|
||||
UIMessageBox.Show("Duplicate shells from that with highest production".Translate(), "WARNING: This operation can be very slow, continue?".Translate(), "取消".Translate(), "确定".Translate(), UIMessageBox.WARNING, null,
|
||||
UIMessageBox.Show(Localization.DuplicateShellsFromThatWithHighestProduction.Translate(), Localization.WARNINGThisOperationCanBeVerySlowContinue.Translate(), Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.WARNING, null,
|
||||
() => { DysonSphereFunctions.DuplicateShellsWithHighestProduction(); });
|
||||
});
|
||||
y += 30f;
|
||||
var slider1 = wnd.AddSlider(x + 20f, y, tab4, DysonSphereFunctions.ShellsCountForFunctions, new ShellsCountMapper());
|
||||
var input1 = AddShellsCountInput(wnd, x + 20f, y, tab4, "input-shells-count-illegal");
|
||||
|
||||
y = originalY;
|
||||
var btn4 = wnd.AddButton(x, y, 300f, tab4, "Generate illegal dyson shell quickly", 16, "button-generate-illegal-dyson-shells-quickly", () =>
|
||||
{
|
||||
UIMessageBox.Show("Generate illegal dyson shell".Translate(), "WARNING: This operation can be very slow, continue?".Translate(), "取消".Translate(), "确定".Translate(), UIMessageBox.WARNING, null,
|
||||
UIMessageBox.Show(Localization.GenerateIllegalDysonShellQuickly.Translate(), Localization.WARNINGThisOperationCanBeVerySlowContinue.Translate(), Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.WARNING, null,
|
||||
() => { DysonSphereFunctions.CreateIllegalDysonShellQuickly(DysonSphereFunctions.ShellsCountForFunctions.Value); });
|
||||
});
|
||||
y += 30f;
|
||||
var txt2 = wnd.AddText2(x, y, tab4, "Shells count", 15, "text-shells-count");
|
||||
var slider2 = wnd.AddSlider(x + txt2.preferredWidth + 5f, y + 6f, tab4, DysonSphereFunctions.ShellsCountForFunctions, new ShellsCountMapper());
|
||||
var input2 = AddShellsCountInput(wnd, x + UXAssist.UI.Util.GetPreferredWidth(txt2) + 5f, y, tab4, "input-shells-count-quick");
|
||||
|
||||
Functions.DysonSphereFunctions.IllegalDysonShellFunctionsEnabled.SettingChanged += onIllegalDysonShellFunctionsChanged;
|
||||
wnd.OnFree += () => { Functions.DysonSphereFunctions.IllegalDysonShellFunctionsEnabled.SettingChanged -= onIllegalDysonShellFunctionsChanged; };
|
||||
@@ -340,14 +287,15 @@ public static class UIConfigWindow
|
||||
void onIllegalDysonShellFunctionsChanged(object o, EventArgs e)
|
||||
{
|
||||
var enabled = Functions.DysonSphereFunctions.IllegalDysonShellFunctionsEnabled.Value;
|
||||
btn0.gameObject.SetActive(enabled);
|
||||
btn1.gameObject.SetActive(enabled);
|
||||
btn2.gameObject.SetActive(enabled);
|
||||
btn3.gameObject.SetActive(enabled);
|
||||
slider1.gameObject.SetActive(enabled);
|
||||
input1.gameObject.SetActive(enabled);
|
||||
|
||||
btn4.gameObject.SetActive(!enabled);
|
||||
txt2.gameObject.SetActive(!enabled);
|
||||
slider2.gameObject.SetActive(!enabled);
|
||||
input2.gameObject.SetActive(!enabled);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,6 +321,7 @@ public static class UIConfigWindow
|
||||
|
||||
private static void UpdateButtons()
|
||||
{
|
||||
if (_resignGameBtn == null || _clearBanBtn == null) return;
|
||||
var data = GameMain.data;
|
||||
if (data == null) return;
|
||||
var resignEnabled = data.account != AccountData.me;
|
||||
@@ -389,4 +338,4 @@ public static class UIConfigWindow
|
||||
_clearBanBtn.gameObject.SetActive(banEnabled);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 57 KiB After Width: | Height: | Size: 68 KiB |
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"name": "CheatEnabler",
|
||||
"version_number": "2.3.32",
|
||||
"version_number": "2.4.7",
|
||||
"website_url": "https://github.com/soarqin/DSP_Mods/tree/master/CheatEnabler",
|
||||
"description": "Add various cheat functions while disabling abnormal determinants / 添加一些作弊功能,同时屏蔽异常检测",
|
||||
"dependencies": [
|
||||
"xiaoye97-BepInEx-5.4.17",
|
||||
"soarqin-UXAssist-1.2.0"
|
||||
"soarqin-UXAssist-1.4.0"
|
||||
]
|
||||
}
|
||||
+137
-15
@@ -19,76 +19,198 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OverclockEverything", "Over
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MechaDronesTweaks", "MechaDronesTweaks\MechaDronesTweaks.csproj", "{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LabOpt", "LabOpt\LabOpt.csproj", "{DD76B77C-68D8-4A4C-B98E-CBEECEDC49FB}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{F2D5EBE8-7D9D-4572-9A3E-4DD1114FD99F} = {F2D5EBE8-7D9D-4572-9A3E-4DD1114FD99F}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LabOptPreloader", "LabOptPreloader\LabOptPreloader.csproj", "{F2D5EBE8-7D9D-4572-9A3E-4DD1114FD99F}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DustbinPreloader", "DustbinPreloader\DustbinPreloader.csproj", "{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PoolOpt", "PoolOpt\PoolOpt.csproj", "{8BE61246-2C9D-4088-AA33-5AFF22C5046E}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UserCloak", "UserCloak\UserCloak.csproj", "{096D2E4B-D1CE-424D-9954-C36A23E9E279}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LuaScriptEngine", "LuaScriptEngine\LuaScriptEngine.csproj", "{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UpdateGameDlls", "UpdateGameDlls\UpdateGameDlls.csproj", "{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LiveStreamAssist", "LiveStreamAssist\LiveStreamAssist.csproj", "{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Release|x64.Build.0 = Release|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{9C048229-6A50-4642-BC5E-02CD39D3869A}.Release|x86.Build.0 = Release|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x64.Build.0 = Release|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x86.Build.0 = Release|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x64.Build.0 = Release|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x86.Build.0 = Release|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Release|x64.Build.0 = Release|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Release|x86.Build.0 = Release|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Release|x64.Build.0 = Release|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{931F0230-5941-4E49-AB19-66921AF14096}.Release|x86.Build.0 = Release|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Release|x64.Build.0 = Release|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{9534694E-14F0-4498-852D-BBB3FCA986CD}.Release|x86.Build.0 = Release|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Release|x64.Build.0 = Release|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{0168941C-EEA6-49CF-9A67-E829FE06CF9B}.Release|x86.Build.0 = Release|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{DD76B77C-68D8-4A4C-B98E-CBEECEDC49FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{DD76B77C-68D8-4A4C-B98E-CBEECEDC49FB}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{DD76B77C-68D8-4A4C-B98E-CBEECEDC49FB}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{DD76B77C-68D8-4A4C-B98E-CBEECEDC49FB}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F2D5EBE8-7D9D-4572-9A3E-4DD1114FD99F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F2D5EBE8-7D9D-4572-9A3E-4DD1114FD99F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F2D5EBE8-7D9D-4572-9A3E-4DD1114FD99F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F2D5EBE8-7D9D-4572-9A3E-4DD1114FD99F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Release|x64.Build.0 = Release|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{15B8BC2E-93E0-4454-8F8F-BF1FA8DC90F4}.Release|x86.Build.0 = Release|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B8EB3D8D-5613-42F0-9040-EAA11A38C6AC}.Release|x86.Build.0 = Release|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Release|x64.Build.0 = Release|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{8BE61246-2C9D-4088-AA33-5AFF22C5046E}.Release|x86.Build.0 = Release|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Release|x64.Build.0 = Release|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{096D2E4B-D1CE-424D-9954-C36A23E9E279}.Release|x86.Build.0 = Release|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Release|x64.Build.0 = Release|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{E9375F0E-26DC-4CEC-80DC-9C48F23340BC}.Release|x86.Build.0 = Release|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Release|x64.Build.0 = Release|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{6E73B301-7C7A-4EF4-B0FA-4C6B40F96653}.Release|x86.Build.0 = Release|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Release|x64.Build.0 = Release|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{0E6D6C44-00CF-4FE9-A475-1D898B4D1DAC}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
<!-- Common properties shared by all DSP mod projects -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net472</TargetFramework>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>disable</Nullable>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<!-- CS0618: expected from the legacy Util forwarding facade; suppress so new warnings fail the build. -->
|
||||
<NoWarn>0618</NoWarn>
|
||||
<AnalysisLevel>none</AnalysisLevel>
|
||||
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
|
||||
<DefaultItemExcludesInProjectFolder>$(DefaultItemExcludesInProjectFolder);tools/**/bin/**;tools/**/obj/**</DefaultItemExcludesInProjectFolder>
|
||||
<RestoreAdditionalProjectSources>https://nuget.bepinex.dev/v3/index.json</RestoreAdditionalProjectSources>
|
||||
<!-- Set to true in projects that include a CHANGELOG.md in the package -->
|
||||
<PackHasChangelog>false</PackHasChangelog>
|
||||
<!-- Set to true in projects that use the plugins/patchers layout (Dustbin, LabOpt) -->
|
||||
<PackUsePluginsLayout>false</PackUsePluginsLayout>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Common NuGet packages for all mods -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BepInEx.Core" Version="5.*" />
|
||||
<PackageReference Include="BepInEx.PluginInfoProps" Version="1.*" />
|
||||
<PackageReference Include="UnityEngine.Modules" Version="2022.3.62" IncludeAssets="compile" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Game DLL references (local copies in AssemblyFromGame/) -->
|
||||
<ItemGroup>
|
||||
<Reference Include="Assembly-CSharp">
|
||||
<HintPath>$(MSBuildThisFileDirectory)AssemblyFromGame\Assembly-CSharp.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="UnityEngine.UI">
|
||||
<HintPath>$(MSBuildThisFileDirectory)AssemblyFromGame\UnityEngine.UI.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<!-- .NET Framework reference assemblies (only needed when targeting net*) -->
|
||||
<ItemGroup Condition="'$(TargetFramework.TrimEnd(`0123456789`))' == 'net'">
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- All projects depend on UpdateGameDlls helper to ensure game DLLs are
|
||||
refreshed before any project resolves assembly references. -->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="$(MSBuildThisFileDirectory)UpdateGameDlls\UpdateGameDlls.csproj"
|
||||
ReferenceOutputAssembly="false"
|
||||
SkipGetTargetFrameworkProperties="true"
|
||||
Private="false" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,94 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project>
|
||||
|
||||
<!--
|
||||
ZipMod target: assembles a Thunderstore-ready zip under package/.
|
||||
Run explicitly with: dotnet build -t:ZipMod -c Release
|
||||
It does NOT run automatically on every build.
|
||||
|
||||
"Pack" is reserved by the .NET SDK for NuGet packaging, so this target
|
||||
uses the name "ZipMod" to avoid conflict.
|
||||
|
||||
Per-project customisation properties (set in the project's PropertyGroup):
|
||||
PackHasChangelog – set to 'true' to include CHANGELOG.md in the zip
|
||||
PackUsePluginsLayout – set to 'true' for the plugins/patchers folder layout
|
||||
(used by Dustbin and LabOpt)
|
||||
|
||||
Simple layout zips:
|
||||
<AssemblyName>.dll icon.png manifest.json README.md [CHANGELOG.md]
|
||||
plugins/patchers layout zips:
|
||||
plugins/ patchers/ icon.png manifest.json README.md [CHANGELOG.md]
|
||||
-->
|
||||
<Target Name="ZipMod" DependsOnTargets="Build" Condition="'$(PackPreloaderTargetDir)' == ''">
|
||||
<PropertyGroup>
|
||||
<_PackageDir>$(MSBuildProjectDirectory)\package</_PackageDir>
|
||||
<_StagingDir>$(MSBuildProjectDirectory)\obj\pack-staging</_StagingDir>
|
||||
<_ZipPath>$(_PackageDir)\$(ProjectName)-$(Version).zip</_ZipPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- Sync manifest.json version_number from .csproj $(Version) before packaging -->
|
||||
<Exec Condition="Exists('$(_PackageDir)\manifest.json')"
|
||||
Command="powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$f='$(_PackageDir)\manifest.json'; $c=[IO.File]::ReadAllText($f); $c=$c -replace '(\u0022version_number\u0022\s*:\s*\u0022)[^\u0022]*(\u0022)','${1}$(Version)${2}'; [IO.File]::WriteAllText($f,$c,[Text.UTF8Encoding]::new($true))"" />
|
||||
|
||||
<!-- ── plugins/patchers layout: copy DLL into package/plugins/ first ── -->
|
||||
<MakeDir Directories="$(_PackageDir)\plugins"
|
||||
Condition="'$(PackUsePluginsLayout)' == 'true'" />
|
||||
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(_PackageDir)\plugins"
|
||||
Condition="'$(PackUsePluginsLayout)' == 'true'" />
|
||||
|
||||
<!-- Collect loose root files (common to both layouts) -->
|
||||
<ItemGroup>
|
||||
<_PackRootFiles Include="$(_PackageDir)\icon.png" />
|
||||
<_PackRootFiles Include="$(_PackageDir)\manifest.json" />
|
||||
<_PackRootFiles Include="$(MSBuildProjectDirectory)\README.md" />
|
||||
<_PackRootFiles Include="$(MSBuildProjectDirectory)\CHANGELOG.md"
|
||||
Condition="'$(PackHasChangelog)' == 'true'" />
|
||||
<!-- Simple layout: also include the DLL itself at the root -->
|
||||
<_PackRootFiles Include="$(TargetPath)"
|
||||
Condition="'$(PackUsePluginsLayout)' != 'true'" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Prepare staging directory -->
|
||||
<RemoveDir Directories="$(_StagingDir)" />
|
||||
<MakeDir Directories="$(_StagingDir)" />
|
||||
|
||||
<!-- Copy loose root files into staging root -->
|
||||
<Copy SourceFiles="@(_PackRootFiles)" DestinationFolder="$(_StagingDir)" />
|
||||
|
||||
<!-- plugins/patchers layout: copy sub-folders into staging (preserve structure) -->
|
||||
<ItemGroup Condition="'$(PackUsePluginsLayout)' == 'true'">
|
||||
<_PluginFiles Include="$(_PackageDir)\plugins\**\*" />
|
||||
<_PatcherFiles Include="$(_PackageDir)\patchers\**\*" />
|
||||
</ItemGroup>
|
||||
<Copy SourceFiles="@(_PluginFiles)"
|
||||
DestinationFiles="@(_PluginFiles->'$(_StagingDir)\plugins\%(RecursiveDir)%(Filename)%(Extension)')"
|
||||
Condition="'$(PackUsePluginsLayout)' == 'true'" />
|
||||
<Copy SourceFiles="@(_PatcherFiles)"
|
||||
DestinationFiles="@(_PatcherFiles->'$(_StagingDir)\patchers\%(RecursiveDir)%(Filename)%(Extension)')"
|
||||
Condition="'$(PackUsePluginsLayout)' == 'true'" />
|
||||
|
||||
<!-- Delete previous zip if present -->
|
||||
<Delete Files="$(_ZipPath)" Condition="Exists('$(_ZipPath)')" />
|
||||
|
||||
<!-- Create zip using MSBuild ZipDirectory task – no shell, no quoting issues -->
|
||||
<ZipDirectory SourceDirectory="$(_StagingDir)" DestinationFile="$(_ZipPath)" />
|
||||
|
||||
<!-- Clean up staging directory -->
|
||||
<RemoveDir Directories="$(_StagingDir)" />
|
||||
|
||||
<Message Text="ZipMod: created $(_ZipPath)" Importance="high" />
|
||||
</Target>
|
||||
|
||||
<!-- ── Preloader helper target ────────────────────────────────────────────
|
||||
Preloader projects (DustbinPreloader, LabOptPreloader) call this to
|
||||
copy their output DLL into the sibling main mod's patchers/ folder.
|
||||
Set PackPreloaderTargetDir in the preloader's csproj, e.g.:
|
||||
<PackPreloaderTargetDir>..\Dustbin\package\patchers</PackPreloaderTargetDir>
|
||||
──────────────────────────────────────────────────────────────────────── -->
|
||||
<Target Name="CopyToParentPackage" DependsOnTargets="Build"
|
||||
Condition="'$(PackPreloaderTargetDir)' != ''">
|
||||
<MakeDir Directories="$(PackPreloaderTargetDir)" />
|
||||
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(PackPreloaderTargetDir)" />
|
||||
<Message Text="CopyToParentPackage: copied $(TargetFileName) to $(PackPreloaderTargetDir)" Importance="high" />
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -77,7 +77,7 @@ public static class BeltSignal
|
||||
SID = ""
|
||||
};
|
||||
p.name = p.Name.Translate();
|
||||
signals.dataArray = signals.dataArray.AddItem(p).ToArray();
|
||||
signals.dataArray = [.. signals.dataArray.AddItem(p)];
|
||||
signals.dataIndices[p.ID] = index;
|
||||
_initialized = true;
|
||||
}
|
||||
@@ -225,11 +225,11 @@ public static class BeltSignal
|
||||
int itemId;
|
||||
if ((itemId = cargoPath.TryPickItem(belt.segIndex + belt.segPivotOffset - 5, 12, out var stack, out _)) <= 0) continue;
|
||||
consumeRegister[itemId] += stack;
|
||||
Dustbin.CalcGetSands(itemId, stack);
|
||||
Dustbin.CalcGetSands(itemId, stack, 0);
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -58,7 +58,7 @@ public class Dustbin : BaseUnityPlugin, IModCanSave, IMultiplayerMod
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int CalcGetSands(int itemId, int count)
|
||||
public static int CalcGetSands(int itemId, int count, int inc)
|
||||
{
|
||||
var sandsPerItem = itemId <= 12000 ? Dustbin.SandsFactors[itemId] : 0;
|
||||
if (sandsPerItem <= 0) return count;
|
||||
|
||||
+3
-23
@@ -1,41 +1,21 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net472</TargetFramework>
|
||||
<BepInExPluginGuid>org.soardev.dustbin</BepInExPluginGuid>
|
||||
<Description>DSP MOD - Dustbin</Description>
|
||||
<Version>1.4.0</Version>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<PackageId>Dustbin</PackageId>
|
||||
<RootNamespace>Dustbin</RootNamespace>
|
||||
<RestoreAdditionalProjectSources>https://nuget.bepinex.dev/v3/index.json</RestoreAdditionalProjectSources>
|
||||
<PackHasChangelog>true</PackHasChangelog>
|
||||
<PackUsePluginsLayout>true</PackUsePluginsLayout>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BepInEx.Core" Version="5.*" />
|
||||
<PackageReference Include="BepInEx.PluginInfoProps" Version="1.*" />
|
||||
<PackageReference Include="DysonSphereProgram.GameLibs" Version="0.10.32.*-r.*" />
|
||||
<PackageReference Include="DysonSphereProgram.Modding.DSPModSave" Version="1.*" />
|
||||
<PackageReference Include="DysonSphereProgram.Modding.NebulaMultiplayerModApi" Version="2.0.0" />
|
||||
<PackageReference Include="UnityEngine.Modules" Version="2018.4.12" IncludeAssets="compile" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="assets/icon/signal-410.png" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework.TrimEnd(`0123456789`))' == 'net'">
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="Assembly-CSharp">
|
||||
<HintPath>GameAssembly\Assembly-CSharp.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Release'">
|
||||
<Exec Command="del /F /Q package\$(ProjectName)-$(Version).zip
IF NOT EXIST package\plugins (mkdir package\plugins)
copy /y $(TargetPath) package\plugins\
cd package
powershell Compress-Archive -Force -DestinationPath '$(ProjectName)-$(Version).zip' -Path patchers, plugins, icon.png, manifest.json, ../README.md, ../CHANGELOG.md" />
|
||||
</Target>
|
||||
</Project>
|
||||
+48
-8
@@ -148,25 +148,65 @@ public static class StoragePatch
|
||||
_lastStorageId = 0; // Refresh UI to reposition button on client side
|
||||
}
|
||||
|
||||
|
||||
[HarmonyTranspiler]
|
||||
[HarmonyPatch(typeof(StorageComponent), nameof(StorageComponent.AddItem), [typeof(int), typeof(int), typeof(int), typeof(int), typeof(bool)],
|
||||
[ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Normal, ArgumentType.Out, ArgumentType.Normal])]
|
||||
private static IEnumerable<CodeInstruction> StorageComponent_AddItem_HarmonyTranspiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
|
||||
{
|
||||
var matcher = new CodeMatcher(instructions, generator);
|
||||
var label1 = generator.DefineLabel();
|
||||
matcher.Start().MatchForward(false,
|
||||
new CodeMatch(OpCodes.Stind_I4)
|
||||
).Advance(1).InsertAndAdvance(
|
||||
var codes = new List<CodeInstruction>(instructions);
|
||||
var matcher = new CodeMatcher(codes, generator);
|
||||
|
||||
// 找到方法开始处
|
||||
// Find the beginning of the method
|
||||
matcher.Start();
|
||||
|
||||
// 定义标签用于跳转
|
||||
// Define label for jump
|
||||
var skipDustbinLogic = generator.DefineLabel();
|
||||
|
||||
// 在方法开始处插入安全检查
|
||||
// Insert safety checks at the beginning of the method
|
||||
matcher.InsertAndAdvance(
|
||||
// 安全检查:确保StorageComponent实例不为null
|
||||
// Safety check: Ensure StorageComponent instance is not null
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Brfalse, skipDustbinLogic),
|
||||
|
||||
// 检查是否是垃圾桶
|
||||
// Check if it's a dustbin
|
||||
new CodeInstruction(OpCodes.Ldarg_0),
|
||||
new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(StorageComponent), nameof(StorageComponent.IsDustbin))),
|
||||
new CodeInstruction(OpCodes.Brfalse, label1),
|
||||
new CodeInstruction(OpCodes.Brfalse, skipDustbinLogic),
|
||||
|
||||
// 检查count是否大于0
|
||||
// Check if count is greater than 0
|
||||
new CodeInstruction(OpCodes.Ldarg_2),
|
||||
new CodeInstruction(OpCodes.Ldc_I4_0),
|
||||
new CodeInstruction(OpCodes.Ble, skipDustbinLogic),
|
||||
|
||||
// 调用CalcGetSands处理物品销毁和沙子生成
|
||||
// Call CalcGetSands to handle item destruction and sand generation
|
||||
new CodeInstruction(OpCodes.Ldarg_1),
|
||||
new CodeInstruction(OpCodes.Ldarg_2),
|
||||
new CodeInstruction(OpCodes.Ldarg_3),
|
||||
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Dustbin), nameof(Dustbin.CalcGetSands))),
|
||||
new CodeInstruction(OpCodes.Ret)
|
||||
|
||||
// 设置remainInc为0(第5个参数,索引4)
|
||||
// Set remainInc to 0 (5th parameter, index 4)
|
||||
new CodeInstruction(OpCodes.Ldarg, 4),
|
||||
new CodeInstruction(OpCodes.Ldc_I4_0),
|
||||
new CodeInstruction(OpCodes.Stind_I4),
|
||||
|
||||
// 返回count表示成功销毁
|
||||
// Return count to indicate successful destruction
|
||||
new CodeInstruction(OpCodes.Ret),
|
||||
|
||||
// 跳过垃圾桶逻辑的标签
|
||||
// Label to skip dustbin logic
|
||||
new CodeInstruction(OpCodes.Nop).WithLabels(skipDustbinLogic)
|
||||
);
|
||||
matcher.Labels.Add(label1);
|
||||
|
||||
return matcher.InstructionEnumeration();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,28 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net472</TargetFramework>
|
||||
<AssemblyName>DustbinPreloader</AssemblyName>
|
||||
<Description>DSP MOD - Prealoder for Dustbin</Description>
|
||||
<Description>DSP MOD - Preloader for Dustbin</Description>
|
||||
<Version>1.3.1</Version>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<RestoreAdditionalProjectSources>https://nuget.bepinex.dev/v3/index.json</RestoreAdditionalProjectSources>
|
||||
<PackPreloaderTargetDir>..\Dustbin\package\patchers</PackPreloaderTargetDir>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BepInEx.Core" Version="5.*" />
|
||||
<PackageReference Include="BepInEx.PluginInfoProps" Version="1.*" />
|
||||
<PackageReference Include="DysonSphereProgram.GameLibs" Version="0.10.32.*-r.*" />
|
||||
<PackageReference Include="UnityEngine.Modules" Version="2018.4.12" IncludeAssets="compile" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework.TrimEnd(`0123456789`))' == 'net'">
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Release'">
|
||||
<Exec Command="IF NOT EXIST ..\Dustbin\package\patchers (mkdir ..\Dustbin\package\patchers)
copy /y $(TargetPath) ..\Dustbin\package\patchers\" />
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -152,7 +152,7 @@ public class HideTips : BaseUnityPlugin
|
||||
class HideMenuDemo
|
||||
{
|
||||
[HarmonyPriority(Priority.First), HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(DSPGame), "StartDemoGame", typeof(int))]
|
||||
[HarmonyPatch(typeof(DSPGame), nameof(DSPGame.StartDemoGame), typeof(int))]
|
||||
private static bool DSPGame_StartDemoGame_Prefix()
|
||||
{
|
||||
if (DSPGame.Game != null)
|
||||
@@ -188,7 +188,7 @@ class HideMenuDemo
|
||||
}
|
||||
|
||||
[HarmonyPriority(Priority.First), HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(VFPreload), "IsMenuDemoLoaded")]
|
||||
[HarmonyPatch(typeof(VFPreload), nameof(VFPreload.IsMenuDemoLoaded))]
|
||||
private static bool VFPreload_IsMenuDemoLoaded_Prefix(ref bool __result)
|
||||
{
|
||||
__result = true;
|
||||
@@ -196,18 +196,18 @@ class HideMenuDemo
|
||||
}
|
||||
|
||||
[HarmonyPriority(Priority.First), HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(DSPGame), "LateUpdate")]
|
||||
[HarmonyPatch(typeof(GameMain), "LateUpdate")]
|
||||
[HarmonyPatch(typeof(GameMain), "FixedUpdate")]
|
||||
[HarmonyPatch(typeof(GameMain), "Update")]
|
||||
[HarmonyPatch(typeof(GameCamera), "LateUpdate")]
|
||||
[HarmonyPatch(typeof(DSPGame), nameof(DSPGame.LateUpdate))]
|
||||
[HarmonyPatch(typeof(GameMain), nameof(GameMain.LateUpdate))]
|
||||
[HarmonyPatch(typeof(GameMain), nameof(GameMain.FixedUpdate))]
|
||||
[HarmonyPatch(typeof(GameMain), nameof(GameMain.Update))]
|
||||
[HarmonyPatch(typeof(GameCamera), nameof(GameCamera.LateUpdate))]
|
||||
private static bool DSPGame_LateUpdate_Prefix()
|
||||
{
|
||||
return !DSPGame.IsMenuDemo;
|
||||
}
|
||||
|
||||
[HarmonyPriority(Priority.First), HarmonyPrefix]
|
||||
[HarmonyPatch(typeof(GameMain), "Begin")]
|
||||
[HarmonyPatch(typeof(GameMain), nameof(GameMain.Begin))]
|
||||
private static bool GameMain_Begin_Prefix()
|
||||
{
|
||||
if (!DSPGame.IsMenuDemo) return true;
|
||||
|
||||
@@ -1,29 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net472</TargetFramework>
|
||||
<AssemblyName>HideTips</AssemblyName>
|
||||
<BepInExPluginGuid>org.soardev.hidetips</BepInExPluginGuid>
|
||||
<Description>DSP MOD - HideTips</Description>
|
||||
<Version>1.0.4</Version>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<RestoreAdditionalProjectSources>https://nuget.bepinex.dev/v3/index.json</RestoreAdditionalProjectSources>
|
||||
<PackHasChangelog>true</PackHasChangelog>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BepInEx.Core" Version="5.*" />
|
||||
<PackageReference Include="BepInEx.PluginInfoProps" Version="1.*" />
|
||||
<PackageReference Include="DysonSphereProgram.GameLibs" Version="0.10.32.*-r.*" />
|
||||
<PackageReference Include="UnityEngine.Modules" Version="2018.4.12" IncludeAssets="compile" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework.TrimEnd(`0123456789`))' == 'net'">
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Release'">
|
||||
<Exec Command="del /F /Q package\$(ProjectName)-$(Version).zip
powershell Compress-Archive -Force -DestinationPath 'package/$(ProjectName)-$(Version).zip' -Path '$(TargetPath)', package/icon.png, package/manifest.json, README.md" />
|
||||
</Target>
|
||||
</Project>
|
||||
+1
-20
@@ -1,29 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net472</TargetFramework>
|
||||
<AssemblyName>LabOpt</AssemblyName>
|
||||
<BepInExPluginGuid>org.soardev.labopt</BepInExPluginGuid>
|
||||
<Description>DSP MOD - LabOpt</Description>
|
||||
<Version>0.3.6</Version>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<RestoreAdditionalProjectSources>https://nuget.bepinex.dev/v3/index.json</RestoreAdditionalProjectSources>
|
||||
<PackUsePluginsLayout>true</PackUsePluginsLayout>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BepInEx.Core" Version="5.*" />
|
||||
<PackageReference Include="BepInEx.PluginInfoProps" Version="1.*" />
|
||||
<PackageReference Include="DysonSphereProgram.GameLibs" Version="0.10.32.*-r.*" />
|
||||
<PackageReference Include="UnityEngine.Modules" Version="2018.4.12" IncludeAssets="compile" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework.TrimEnd(`0123456789`))' == 'net'">
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Release'">
|
||||
<Exec Command="del /F /Q package\$(ProjectName)-$(Version).zip
IF NOT EXIST package\plugins (mkdir package\plugins)
copy /y $(TargetPath) package\plugins\
cd package
powershell Compress-Archive -Force -DestinationPath '$(ProjectName)-$(Version).zip' -Path patchers, plugins, icon.png, manifest.json, ../README.md" />
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -1,28 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net472</TargetFramework>
|
||||
<AssemblyName>LabOptPreloader</AssemblyName>
|
||||
<Description>DSP MOD - Prealoder for LabOpt</Description>
|
||||
<Description>DSP MOD - Preloader for LabOpt</Description>
|
||||
<Version>0.2.1</Version>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<RestoreAdditionalProjectSources>https://nuget.bepinex.dev/v3/index.json</RestoreAdditionalProjectSources>
|
||||
<PackPreloaderTargetDir>..\LabOpt\package\patchers</PackPreloaderTargetDir>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BepInEx.Core" Version="5.*" />
|
||||
<PackageReference Include="BepInEx.PluginInfoProps" Version="1.*" />
|
||||
<PackageReference Include="DysonSphereProgram.GameLibs" Version="0.10.32.*-r.*" />
|
||||
<PackageReference Include="UnityEngine.Modules" Version="2018.4.12" IncludeAssets="compile" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework.TrimEnd(`0123456789`))' == 'net'">
|
||||
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Release'">
|
||||
<Exec Command="IF NOT EXIST ..\LabOpt\package\patchers (mkdir ..\LabOpt\package\patchers)
copy /y $(TargetPath) ..\LabOpt\package\patchers\" />
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -0,0 +1,863 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace LiveStreamAssist.Api;
|
||||
|
||||
internal static class ApiLimits
|
||||
{
|
||||
public const string ApiVersion = "1.0.0";
|
||||
public const string Path = "/api/v1";
|
||||
public const int MaxConnections = 8;
|
||||
public const int MaxPendingRequestsPerConnection = 8;
|
||||
public const int MaxPendingRequests = 64;
|
||||
public const int MaxRequestBytes = 65536;
|
||||
public const int MaxResponseBytes = 262144;
|
||||
public const int MaxJsonDepth = 32;
|
||||
public const int MaxIdLength = 64;
|
||||
public const int MaxPathSegments = 16;
|
||||
public const int MaxSelectMembers = 32;
|
||||
public const int DefaultPageSize = 64;
|
||||
public const int MaxPageSize = 128;
|
||||
public const int RequestTimeoutMs = 5000;
|
||||
public const int MaxRequestsPerFrame = 8;
|
||||
public const int MainThreadBudgetMs = 2;
|
||||
public const int CloseGoingAway = 1001;
|
||||
public const int CloseProtocolError = 1002;
|
||||
public const int CloseUnsupportedData = 1003;
|
||||
public const int CloseInvalidPayload = 1007;
|
||||
public const int ClosePolicyViolation = 1008;
|
||||
public const int CloseMessageTooBig = 1009;
|
||||
public const int CloseTryAgainLater = 1013;
|
||||
}
|
||||
|
||||
internal sealed class ApiError
|
||||
{
|
||||
public int Code;
|
||||
public string Kind;
|
||||
public string Message;
|
||||
public int? SegmentIndex;
|
||||
public string Member;
|
||||
public string Root;
|
||||
|
||||
public ApiError WithPath(int? segmentIndex = null, string member = null, string root = null)
|
||||
{
|
||||
SegmentIndex = segmentIndex;
|
||||
Member = member;
|
||||
Root = root;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class ApiRequest
|
||||
{
|
||||
public string Id;
|
||||
public string Method;
|
||||
public JObject Params;
|
||||
}
|
||||
|
||||
internal enum DataMethod
|
||||
{
|
||||
Roots,
|
||||
Describe,
|
||||
Read
|
||||
}
|
||||
|
||||
internal struct ReadOptions
|
||||
{
|
||||
public bool HasSelect;
|
||||
public string[] Select;
|
||||
public bool HasOffset;
|
||||
public int Offset;
|
||||
public bool HasLimit;
|
||||
public int Limit;
|
||||
|
||||
public int EffectiveOffset => HasOffset ? Offset : 0;
|
||||
public int EffectiveLimit => HasLimit ? Limit : ApiLimits.DefaultPageSize;
|
||||
}
|
||||
|
||||
internal sealed class DataCall
|
||||
{
|
||||
public DataMethod Method;
|
||||
public string Root;
|
||||
public PathSeg[] Path;
|
||||
public ReadOptions Options;
|
||||
}
|
||||
|
||||
internal enum PathKind
|
||||
{
|
||||
Member,
|
||||
Index,
|
||||
Key
|
||||
}
|
||||
|
||||
internal readonly struct PathSeg
|
||||
{
|
||||
public readonly PathKind Kind;
|
||||
public readonly string Name;
|
||||
public readonly int Index;
|
||||
public readonly object Key;
|
||||
|
||||
public PathSeg(string name)
|
||||
{
|
||||
Kind = PathKind.Member;
|
||||
Name = name;
|
||||
Index = 0;
|
||||
Key = null;
|
||||
}
|
||||
|
||||
public PathSeg(int index)
|
||||
{
|
||||
Kind = PathKind.Index;
|
||||
Name = null;
|
||||
Index = index;
|
||||
Key = null;
|
||||
}
|
||||
|
||||
public PathSeg(object key)
|
||||
{
|
||||
Kind = PathKind.Key;
|
||||
Name = null;
|
||||
Index = 0;
|
||||
Key = key;
|
||||
}
|
||||
}
|
||||
|
||||
internal static class ApiErrors
|
||||
{
|
||||
public static ApiError ParseError() =>
|
||||
New(-32700, "PARSE_ERROR", "Malformed JSON.");
|
||||
|
||||
public static ApiError InvalidRequest(string message = "Invalid request.") =>
|
||||
New(-32600, "INVALID_REQUEST", message);
|
||||
|
||||
public static ApiError MethodNotFound() =>
|
||||
New(-32601, "METHOD_NOT_FOUND", "Unknown method.");
|
||||
|
||||
public static ApiError InvalidParams(string message = "Invalid parameters.") =>
|
||||
New(-32602, "INVALID_PARAMS", message);
|
||||
|
||||
public static ApiError InternalError() =>
|
||||
New(-32603, "INTERNAL_ERROR", "Unexpected server failure.");
|
||||
|
||||
public static ApiError GameNotReady() =>
|
||||
New(-32001, "GAME_NOT_READY", "Game data is unavailable.");
|
||||
|
||||
public static ApiError RootNotFound(string root) =>
|
||||
New(-32002, "ROOT_NOT_FOUND", "Unknown root.").WithPath(root: root);
|
||||
|
||||
public static ApiError RootUnavailable(string root) =>
|
||||
New(-32003, "ROOT_UNAVAILABLE", "Root is unavailable.").WithPath(root: root);
|
||||
|
||||
public static ApiError MemberNotFound(string member, int? segmentIndex = null) =>
|
||||
New(-32004, "MEMBER_NOT_FOUND", "Requested member does not exist.").WithPath(segmentIndex, member);
|
||||
|
||||
public static ApiError MemberNotAllowed(string member, int? segmentIndex = null) =>
|
||||
New(-32005, "MEMBER_NOT_ALLOWED", "Member is outside the read policy.").WithPath(segmentIndex, member);
|
||||
|
||||
public static ApiError NullPath(int segmentIndex) =>
|
||||
New(-32006, "NULL_PATH", "Null encountered before completing the path.").WithPath(segmentIndex);
|
||||
|
||||
public static ApiError IndexOutOfRange(int segmentIndex) =>
|
||||
New(-32007, "INDEX_OUT_OF_RANGE", "Element index is outside the current array or list.").WithPath(segmentIndex);
|
||||
|
||||
public static ApiError KeyNotFound(int segmentIndex) =>
|
||||
New(-32008, "KEY_NOT_FOUND", "Dictionary has no matching key.").WithPath(segmentIndex);
|
||||
|
||||
public static ApiError UnsupportedType(int? segmentIndex = null, string member = null) =>
|
||||
New(-32009, "UNSUPPORTED_TYPE", "Value type or traversal is unsupported.").WithPath(segmentIndex, member);
|
||||
|
||||
public static ApiError ReadFailed(int? segmentIndex = null, string member = null) =>
|
||||
New(-32010, "READ_FAILED", "A permitted read failed.").WithPath(segmentIndex, member);
|
||||
|
||||
public static ApiError LimitExceeded(string message = "A documented resource limit would be exceeded.") =>
|
||||
New(-32011, "LIMIT_EXCEEDED", message);
|
||||
|
||||
public static ApiError ServerBusy() =>
|
||||
New(-32012, "SERVER_BUSY", "Admission capacity is exhausted.");
|
||||
|
||||
public static ApiError RequestTimeout() =>
|
||||
New(-32013, "REQUEST_TIMEOUT", "Response production exceeded its deadline.");
|
||||
|
||||
public static ApiError SessionChanged() =>
|
||||
New(-32014, "SESSION_CHANGED", "Session changed after admission.");
|
||||
|
||||
public static ApiError UnsupportedValue() =>
|
||||
New(-32015, "UNSUPPORTED_VALUE", "Value cannot be represented under the scalar rules.");
|
||||
|
||||
static ApiError New(int code, string kind, string message) =>
|
||||
new ApiError { Code = code, Kind = kind, Message = message };
|
||||
}
|
||||
|
||||
internal static class ApiProtocol
|
||||
{
|
||||
public const string JsonRpc = "2.0";
|
||||
public const string MethodPing = "system.ping";
|
||||
public const string MethodInfo = "system.info";
|
||||
public const string MethodValidate = "system.validate";
|
||||
public const string MethodStats = "system.stats";
|
||||
public const string MethodRoots = "data.roots";
|
||||
public const string MethodDescribe = "data.describe";
|
||||
public const string MethodRead = "data.read";
|
||||
|
||||
static readonly HashSet<string> SystemMethods = new HashSet<string>(StringComparer.Ordinal)
|
||||
{
|
||||
MethodPing, MethodInfo, MethodValidate, MethodStats
|
||||
};
|
||||
|
||||
static readonly HashSet<string> DataMethods = new HashSet<string>(StringComparer.Ordinal)
|
||||
{
|
||||
MethodRoots, MethodDescribe, MethodRead
|
||||
};
|
||||
|
||||
static readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings
|
||||
{
|
||||
TypeNameHandling = TypeNameHandling.None,
|
||||
DateParseHandling = DateParseHandling.None,
|
||||
NullValueHandling = NullValueHandling.Include,
|
||||
Formatting = Formatting.None,
|
||||
MaxDepth = ApiLimits.MaxJsonDepth
|
||||
};
|
||||
|
||||
public static bool IsSystemMethod(string method) => SystemMethods.Contains(method);
|
||||
public static bool IsDataMethod(string method) => DataMethods.Contains(method);
|
||||
|
||||
public static bool TryParseMessage(string text, out ApiRequest request, out ApiError error, out object id)
|
||||
{
|
||||
request = null;
|
||||
error = null;
|
||||
id = null;
|
||||
JToken token;
|
||||
try
|
||||
{
|
||||
using (var sr = new StringReader(text))
|
||||
using (var reader = new JsonTextReader(sr))
|
||||
{
|
||||
reader.DateParseHandling = DateParseHandling.None;
|
||||
reader.MaxDepth = ApiLimits.MaxJsonDepth;
|
||||
var load = new JsonLoadSettings
|
||||
{
|
||||
DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error,
|
||||
LineInfoHandling = LineInfoHandling.Ignore
|
||||
};
|
||||
token = JToken.Load(reader, load);
|
||||
if (reader.Read() && reader.TokenType != JsonToken.None)
|
||||
{
|
||||
error = ApiErrors.ParseError();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
error = ApiErrors.ParseError();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (token is JArray)
|
||||
{
|
||||
error = ApiErrors.InvalidRequest("Batch requests are not supported.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!(token is JObject obj))
|
||||
{
|
||||
error = ApiErrors.InvalidRequest();
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var prop in obj.Properties())
|
||||
{
|
||||
if (prop.Name != "jsonrpc" && prop.Name != "id" && prop.Name != "method" && prop.Name != "params")
|
||||
{
|
||||
error = ApiErrors.InvalidRequest("Unknown envelope field.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
var jsonrpc = obj["jsonrpc"];
|
||||
if (jsonrpc == null || jsonrpc.Type != JTokenType.String || !string.Equals(jsonrpc.Value<string>(), JsonRpc, StringComparison.Ordinal))
|
||||
{
|
||||
error = ApiErrors.InvalidRequest("jsonrpc must be \"2.0\".");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!obj.TryGetValue("id", out var idToken) || idToken == null || idToken.Type == JTokenType.Null)
|
||||
{
|
||||
error = ApiErrors.InvalidRequest("id is required.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (idToken.Type != JTokenType.String)
|
||||
{
|
||||
error = ApiErrors.InvalidRequest("id must be a string.");
|
||||
return false;
|
||||
}
|
||||
|
||||
var idValue = idToken.Value<string>();
|
||||
if (string.IsNullOrEmpty(idValue))
|
||||
{
|
||||
error = ApiErrors.InvalidRequest("id must be nonempty.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (idValue.Length > ApiLimits.MaxIdLength)
|
||||
{
|
||||
error = ApiErrors.InvalidRequest("id exceeds maxIdLength.");
|
||||
return false;
|
||||
}
|
||||
|
||||
id = idValue;
|
||||
|
||||
if (!obj.TryGetValue("method", out var methodToken) || methodToken == null || methodToken.Type != JTokenType.String)
|
||||
{
|
||||
error = ApiErrors.InvalidRequest("method is required.");
|
||||
return false;
|
||||
}
|
||||
|
||||
var method = methodToken.Value<string>();
|
||||
if (string.IsNullOrEmpty(method))
|
||||
{
|
||||
error = ApiErrors.InvalidRequest("method is required.");
|
||||
return false;
|
||||
}
|
||||
|
||||
JObject parms;
|
||||
if (!obj.TryGetValue("params", out var paramsToken))
|
||||
parms = new JObject();
|
||||
else if (paramsToken is JObject p)
|
||||
parms = p;
|
||||
else
|
||||
{
|
||||
error = ApiErrors.InvalidParams("params must be an object.");
|
||||
return false;
|
||||
}
|
||||
|
||||
request = new ApiRequest { Id = idValue, Method = method, Params = parms };
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool TryParseDataCall(ApiRequest request, out DataCall call, out ApiError error)
|
||||
{
|
||||
call = null;
|
||||
error = null;
|
||||
switch (request.Method)
|
||||
{
|
||||
case MethodRoots:
|
||||
error = RejectUnknownParams(request.Params);
|
||||
if (error != null) return false;
|
||||
call = new DataCall { Method = DataMethod.Roots, Path = Array.Empty<PathSeg>() };
|
||||
return true;
|
||||
case MethodDescribe:
|
||||
return TryParseDescribe(request.Params, out call, out error);
|
||||
case MethodRead:
|
||||
return TryParseRead(request.Params, out call, out error);
|
||||
default:
|
||||
error = ApiErrors.MethodNotFound();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static object HandleSystem(string method, JObject parms, GameVersionSnapshot version, string modVersion)
|
||||
{
|
||||
switch (method)
|
||||
{
|
||||
case MethodPing:
|
||||
{
|
||||
var err = RejectUnknownParams(parms);
|
||||
if (err != null) return err;
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["serverTimeUtc"] = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture)
|
||||
};
|
||||
}
|
||||
case MethodInfo:
|
||||
{
|
||||
var err = RejectUnknownParams(parms);
|
||||
if (err != null) return err;
|
||||
return BuildInfo(version, modVersion);
|
||||
}
|
||||
case MethodValidate:
|
||||
return HandleValidate(parms);
|
||||
case MethodStats:
|
||||
{
|
||||
var err = RejectUnknownParams(parms);
|
||||
if (err != null) return err;
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["available"] = false,
|
||||
["metrics"] = null
|
||||
};
|
||||
}
|
||||
default:
|
||||
return ApiErrors.MethodNotFound();
|
||||
}
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> BuildInfo(GameVersionSnapshot version, string modVersion)
|
||||
{
|
||||
var ready = version != null && version.Ready;
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["apiVersion"] = ApiLimits.ApiVersion,
|
||||
["modVersion"] = modVersion ?? "",
|
||||
["gameVersionReady"] = ready,
|
||||
["gameVersion"] = ready ? version.GameVersion : null,
|
||||
["gameBuild"] = ready ? (object)version.GameBuild : null,
|
||||
["capabilities"] = new Dictionary<string, object>
|
||||
{
|
||||
["reflection.read"] = true,
|
||||
["reflection.describe"] = true,
|
||||
["api.stats"] = false,
|
||||
["subscriptions"] = false
|
||||
},
|
||||
["limits"] = new Dictionary<string, object>
|
||||
{
|
||||
["maxConnections"] = ApiLimits.MaxConnections,
|
||||
["maxPendingRequestsPerConnection"] = ApiLimits.MaxPendingRequestsPerConnection,
|
||||
["maxPendingRequests"] = ApiLimits.MaxPendingRequests,
|
||||
["maxRequestBytes"] = ApiLimits.MaxRequestBytes,
|
||||
["maxResponseBytes"] = ApiLimits.MaxResponseBytes,
|
||||
["maxJsonDepth"] = ApiLimits.MaxJsonDepth,
|
||||
["maxIdLength"] = ApiLimits.MaxIdLength,
|
||||
["maxPathSegments"] = ApiLimits.MaxPathSegments,
|
||||
["maxSelectMembers"] = ApiLimits.MaxSelectMembers,
|
||||
["defaultPageSize"] = ApiLimits.DefaultPageSize,
|
||||
["maxPageSize"] = ApiLimits.MaxPageSize,
|
||||
["requestTimeoutMs"] = ApiLimits.RequestTimeoutMs,
|
||||
["maxRequestsPerFrame"] = ApiLimits.MaxRequestsPerFrame,
|
||||
["mainThreadBudgetMs"] = ApiLimits.MainThreadBudgetMs
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static bool CapabilityEnabled(string name)
|
||||
{
|
||||
switch (name)
|
||||
{
|
||||
case "reflection.read":
|
||||
case "reflection.describe":
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] SerializeEnvelope(object id, object result, ApiError error)
|
||||
{
|
||||
var envelope = new Dictionary<string, object>
|
||||
{
|
||||
["jsonrpc"] = JsonRpc,
|
||||
["id"] = id
|
||||
};
|
||||
if (error != null)
|
||||
envelope["error"] = ErrorBody(error);
|
||||
else
|
||||
envelope["result"] = result;
|
||||
return SerializeBounded(envelope);
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> ErrorBody(ApiError error)
|
||||
{
|
||||
var data = new Dictionary<string, object> { ["kind"] = error.Kind };
|
||||
if (error.SegmentIndex.HasValue) data["segmentIndex"] = error.SegmentIndex.Value;
|
||||
if (error.Member != null) data["member"] = error.Member;
|
||||
if (error.Root != null) data["root"] = error.Root;
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["code"] = error.Code,
|
||||
["message"] = error.Message,
|
||||
["data"] = data
|
||||
};
|
||||
}
|
||||
|
||||
public static byte[] SerializeBounded(object value)
|
||||
{
|
||||
using (var bounded = new BoundedStream(ApiLimits.MaxResponseBytes))
|
||||
using (var writer = new StreamWriter(bounded, new UTF8Encoding(false), 1024, true))
|
||||
using (var json = new JsonTextWriter(writer))
|
||||
{
|
||||
json.Formatting = Formatting.None;
|
||||
JsonSerializer.Create(SerializerSettings).Serialize(json, value);
|
||||
json.Flush();
|
||||
writer.Flush();
|
||||
return bounded.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static ApiError RejectUnknownParams(JObject parms, params string[] allowed)
|
||||
{
|
||||
if (parms == null) return null;
|
||||
foreach (var prop in parms.Properties())
|
||||
{
|
||||
var known = false;
|
||||
for (var i = 0; i < allowed.Length; i++)
|
||||
{
|
||||
if (string.Equals(prop.Name, allowed[i], StringComparison.Ordinal))
|
||||
{
|
||||
known = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!known)
|
||||
return ApiErrors.InvalidParams("Unknown parameter '" + prop.Name + "'.");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
static object HandleValidate(JObject parms)
|
||||
{
|
||||
var err = RejectUnknownParams(parms, "apiMajor", "requiredCapabilities");
|
||||
if (err != null) return err;
|
||||
if (!parms.TryGetValue("apiMajor", out var majorToken) || majorToken == null || majorToken.Type == JTokenType.Null)
|
||||
return ApiErrors.InvalidParams("apiMajor is required.");
|
||||
if (!TryGetInt32(majorToken, out var apiMajor) || apiMajor < 1)
|
||||
return ApiErrors.InvalidParams("apiMajor must be a positive 32-bit integer.");
|
||||
|
||||
var missing = new List<string>();
|
||||
if (parms.TryGetValue("requiredCapabilities", out var capToken))
|
||||
{
|
||||
if (!(capToken is JArray arr))
|
||||
return ApiErrors.InvalidParams("requiredCapabilities must be an array.");
|
||||
if (arr.Count > 32)
|
||||
return ApiErrors.LimitExceeded("requiredCapabilities exceeds 32 entries.");
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var item in arr)
|
||||
{
|
||||
if (item == null || item.Type != JTokenType.String)
|
||||
return ApiErrors.InvalidParams("Capability names must be nonempty strings.");
|
||||
var name = item.Value<string>();
|
||||
if (string.IsNullOrEmpty(name))
|
||||
return ApiErrors.InvalidParams("Capability names must be nonempty strings.");
|
||||
if (!seen.Add(name))
|
||||
return ApiErrors.InvalidParams("requiredCapabilities must be distinct.");
|
||||
if (!CapabilityEnabled(name))
|
||||
missing.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
var majorOk = apiMajor == 1;
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["compatible"] = majorOk && missing.Count == 0,
|
||||
["apiVersion"] = ApiLimits.ApiVersion,
|
||||
["apiMajorCompatible"] = majorOk,
|
||||
["missingCapabilities"] = missing
|
||||
};
|
||||
}
|
||||
|
||||
static bool TryParseDescribe(JObject parms, out DataCall call, out ApiError error)
|
||||
{
|
||||
call = null;
|
||||
error = RejectUnknownParams(parms, "root", "path");
|
||||
if (error != null) return false;
|
||||
if (!TryParseRoot(parms, out var root, out error)) return false;
|
||||
if (!TryParsePath(parms, out var path, out error)) return false;
|
||||
call = new DataCall { Method = DataMethod.Describe, Root = root, Path = path };
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool TryParseRead(JObject parms, out DataCall call, out ApiError error)
|
||||
{
|
||||
call = null;
|
||||
error = RejectUnknownParams(parms, "root", "path", "select", "offset", "limit");
|
||||
if (error != null) return false;
|
||||
if (!TryParseRoot(parms, out var root, out error)) return false;
|
||||
if (!TryParsePath(parms, out var path, out error)) return false;
|
||||
var options = new ReadOptions();
|
||||
if (parms.TryGetValue("select", out var selectToken))
|
||||
{
|
||||
if (!(selectToken is JArray arr))
|
||||
{
|
||||
error = ApiErrors.InvalidParams("select must be an array of member names.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (arr.Count < 1)
|
||||
{
|
||||
error = ApiErrors.InvalidParams("select must contain at least one member.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (arr.Count > ApiLimits.MaxSelectMembers)
|
||||
{
|
||||
error = ApiErrors.LimitExceeded("select exceeds maxSelectMembers.");
|
||||
return false;
|
||||
}
|
||||
|
||||
var names = new string[arr.Count];
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
for (var i = 0; i < arr.Count; i++)
|
||||
{
|
||||
var item = arr[i];
|
||||
if (item == null || item.Type != JTokenType.String)
|
||||
{
|
||||
error = ApiErrors.InvalidParams("select members must be nonempty strings.");
|
||||
return false;
|
||||
}
|
||||
|
||||
var name = item.Value<string>();
|
||||
if (string.IsNullOrEmpty(name))
|
||||
{
|
||||
error = ApiErrors.InvalidParams("select members must be nonempty strings.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!seen.Add(name))
|
||||
{
|
||||
error = ApiErrors.InvalidParams("select members must be distinct.");
|
||||
return false;
|
||||
}
|
||||
|
||||
names[i] = name;
|
||||
}
|
||||
|
||||
options.HasSelect = true;
|
||||
options.Select = names;
|
||||
}
|
||||
|
||||
if (parms.TryGetValue("offset", out var offsetToken))
|
||||
{
|
||||
if (!TryGetInt32(offsetToken, out var offset) || offset < 0)
|
||||
{
|
||||
error = ApiErrors.InvalidParams("offset must be a nonnegative 32-bit integer.");
|
||||
return false;
|
||||
}
|
||||
|
||||
options.HasOffset = true;
|
||||
options.Offset = offset;
|
||||
}
|
||||
|
||||
if (parms.TryGetValue("limit", out var limitToken))
|
||||
{
|
||||
if (!TryGetInt32(limitToken, out var limit))
|
||||
{
|
||||
error = ApiErrors.InvalidParams("limit must be an integer.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (limit < 1)
|
||||
{
|
||||
error = ApiErrors.InvalidParams("limit must be at least 1.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (limit > ApiLimits.MaxPageSize)
|
||||
{
|
||||
error = ApiErrors.LimitExceeded("limit exceeds maxPageSize.");
|
||||
return false;
|
||||
}
|
||||
|
||||
options.HasLimit = true;
|
||||
options.Limit = limit;
|
||||
}
|
||||
|
||||
call = new DataCall { Method = DataMethod.Read, Root = root, Path = path, Options = options };
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool TryParseRoot(JObject parms, out string root, out ApiError error)
|
||||
{
|
||||
root = null;
|
||||
error = null;
|
||||
if (!parms.TryGetValue("root", out var token) || token == null || token.Type == JTokenType.Null)
|
||||
{
|
||||
error = ApiErrors.InvalidParams("root is required.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (token.Type != JTokenType.String)
|
||||
{
|
||||
error = ApiErrors.InvalidParams("root must be a string.");
|
||||
return false;
|
||||
}
|
||||
|
||||
root = token.Value<string>();
|
||||
if (string.IsNullOrEmpty(root))
|
||||
{
|
||||
error = ApiErrors.InvalidParams("root must be a nonempty string.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool TryParsePath(JObject parms, out PathSeg[] path, out ApiError error)
|
||||
{
|
||||
path = Array.Empty<PathSeg>();
|
||||
error = null;
|
||||
if (!parms.TryGetValue("path", out var token))
|
||||
return true;
|
||||
if (!(token is JArray arr))
|
||||
{
|
||||
error = ApiErrors.InvalidParams("path must be an array.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (arr.Count > ApiLimits.MaxPathSegments)
|
||||
{
|
||||
error = ApiErrors.LimitExceeded("path exceeds maxPathSegments.");
|
||||
return false;
|
||||
}
|
||||
|
||||
var segs = new PathSeg[arr.Count];
|
||||
for (var i = 0; i < arr.Count; i++)
|
||||
{
|
||||
if (!TryParseSegment(arr[i], out segs[i], out error))
|
||||
return false;
|
||||
}
|
||||
|
||||
path = segs;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool TryParseSegment(JToken token, out PathSeg seg, out ApiError error)
|
||||
{
|
||||
seg = default;
|
||||
error = null;
|
||||
if (token == null || token.Type == JTokenType.Null)
|
||||
{
|
||||
error = ApiErrors.InvalidParams("path segments cannot be null.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (token.Type == JTokenType.String)
|
||||
{
|
||||
var name = token.Value<string>();
|
||||
if (string.IsNullOrEmpty(name))
|
||||
{
|
||||
error = ApiErrors.InvalidParams("member names must be nonempty.");
|
||||
return false;
|
||||
}
|
||||
|
||||
seg = new PathSeg(name);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (token.Type == JTokenType.Integer)
|
||||
{
|
||||
if (!TryGetInt32(token, out var index) || index < 0)
|
||||
{
|
||||
error = ApiErrors.InvalidParams("indexes must be nonnegative 32-bit integers.");
|
||||
return false;
|
||||
}
|
||||
|
||||
seg = new PathSeg(index);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (token is JObject obj)
|
||||
{
|
||||
JProperty keyProp = null;
|
||||
foreach (var prop in obj.Properties())
|
||||
{
|
||||
if (!string.Equals(prop.Name, "key", StringComparison.Ordinal))
|
||||
{
|
||||
error = ApiErrors.InvalidParams("key segments may only contain 'key'.");
|
||||
return false;
|
||||
}
|
||||
|
||||
keyProp = prop;
|
||||
}
|
||||
|
||||
if (keyProp == null || keyProp.Value == null || keyProp.Value.Type == JTokenType.Null)
|
||||
{
|
||||
error = ApiErrors.InvalidParams("key is required.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (keyProp.Value.Type == JTokenType.String)
|
||||
{
|
||||
seg = new PathSeg((object)keyProp.Value.Value<string>());
|
||||
return true;
|
||||
}
|
||||
|
||||
if (keyProp.Value.Type == JTokenType.Integer && TryGetInt32(keyProp.Value, out var key))
|
||||
{
|
||||
seg = new PathSeg((object)key);
|
||||
return true;
|
||||
}
|
||||
|
||||
error = ApiErrors.InvalidParams("dictionary keys must be strings or 32-bit integers.");
|
||||
return false;
|
||||
}
|
||||
|
||||
error = ApiErrors.InvalidParams("unsupported path segment.");
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool TryGetInt32(JToken token, out int value)
|
||||
{
|
||||
value = 0;
|
||||
if (token == null || token.Type != JTokenType.Integer) return false;
|
||||
try
|
||||
{
|
||||
var n = token.Value<long>();
|
||||
if (n < int.MinValue || n > int.MaxValue) return false;
|
||||
value = (int)n;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static int ApiMajor => 1;
|
||||
}
|
||||
|
||||
internal sealed class BoundedStream : MemoryStream
|
||||
{
|
||||
readonly int _max;
|
||||
|
||||
public BoundedStream(int max) => _max = max;
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
if (Length + count > _max)
|
||||
throw new ResponseTooLargeException();
|
||||
base.Write(buffer, offset, count);
|
||||
}
|
||||
|
||||
public override void WriteByte(byte value)
|
||||
{
|
||||
if (Length + 1 > _max)
|
||||
throw new ResponseTooLargeException();
|
||||
base.WriteByte(value);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class ResponseTooLargeException : Exception;
|
||||
internal sealed class GameVersionSnapshot
|
||||
{
|
||||
public readonly bool Ready;
|
||||
public readonly string GameVersion;
|
||||
public readonly int GameBuild;
|
||||
|
||||
public GameVersionSnapshot(bool ready, string gameVersion, int gameBuild)
|
||||
{
|
||||
Ready = ready;
|
||||
GameVersion = gameVersion;
|
||||
GameBuild = gameBuild;
|
||||
}
|
||||
|
||||
public static readonly GameVersionSnapshot Empty = new GameVersionSnapshot(false, null, 0);
|
||||
}
|
||||
|
||||
internal sealed class SessionSnapshot
|
||||
{
|
||||
public readonly int Generation;
|
||||
public readonly string SessionId;
|
||||
|
||||
public SessionSnapshot(int generation, string sessionId)
|
||||
{
|
||||
Generation = generation;
|
||||
SessionId = sessionId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using UnityEngine;
|
||||
|
||||
namespace LiveStreamAssist.Api;
|
||||
|
||||
internal sealed class GameWork
|
||||
{
|
||||
public PendingRequest Pending;
|
||||
public DataCall Call;
|
||||
public int Generation;
|
||||
public long DeadlineMs;
|
||||
}
|
||||
|
||||
internal delegate object GameWorkExecutor(GameWork work);
|
||||
|
||||
internal sealed class MainThreadDispatcher
|
||||
{
|
||||
readonly SynchronizationContext _context;
|
||||
readonly object _token;
|
||||
readonly object _gate = new object();
|
||||
readonly Queue<GameWork> _queue = new Queue<GameWork>();
|
||||
readonly GameWorkExecutor _execute;
|
||||
readonly Func<long> _nowMs;
|
||||
readonly Func<int> _frameCount;
|
||||
readonly Timer _watchdog;
|
||||
GameWork _running;
|
||||
bool _pumpScheduled;
|
||||
bool _stopped;
|
||||
int _frame = -1;
|
||||
int _startedThisFrame;
|
||||
readonly Stopwatch _budget = new Stopwatch();
|
||||
|
||||
public MainThreadDispatcher(SynchronizationContext context, object token, GameWorkExecutor execute, Func<long> nowMs,
|
||||
Func<int> frameCount = null)
|
||||
{
|
||||
_context = context;
|
||||
_token = token;
|
||||
_execute = execute;
|
||||
_nowMs = nowMs;
|
||||
_frameCount = frameCount ?? (() => Time.frameCount);
|
||||
_watchdog = new Timer(_ => SweepTimeouts(), null, 250, 250);
|
||||
}
|
||||
|
||||
public bool TryEnqueue(GameWork work)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stopped || _queue.Count >= ApiLimits.MaxPendingRequests) return false;
|
||||
_queue.Enqueue(work);
|
||||
ScheduleLocked();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void CancelQueued(Func<GameWork, ApiError> reason)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var count = _queue.Count;
|
||||
while (count-- > 0)
|
||||
{
|
||||
var work = _queue.Dequeue();
|
||||
var error = reason(work);
|
||||
if (error == null)
|
||||
_queue.Enqueue(work);
|
||||
else
|
||||
work.Pending.TryComplete(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_stopped = true;
|
||||
_running?.Pending.TryComplete(ApiErrors.RequestTimeout());
|
||||
}
|
||||
|
||||
_watchdog.Dispose();
|
||||
CancelQueued(_ => ApiErrors.RequestTimeout());
|
||||
}
|
||||
|
||||
void SweepTimeouts()
|
||||
{
|
||||
var now = _nowMs();
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stopped) return;
|
||||
if (_running != null && now >= _running.DeadlineMs)
|
||||
_running.Pending.TryComplete(ApiErrors.RequestTimeout());
|
||||
var count = _queue.Count;
|
||||
while (count-- > 0)
|
||||
{
|
||||
var work = _queue.Dequeue();
|
||||
if (!work.Pending.IsActive)
|
||||
continue;
|
||||
if (now >= work.DeadlineMs)
|
||||
work.Pending.TryComplete(ApiErrors.RequestTimeout());
|
||||
else
|
||||
_queue.Enqueue(work);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ScheduleLocked()
|
||||
{
|
||||
if (_pumpScheduled || _stopped) return;
|
||||
_pumpScheduled = true;
|
||||
_context.Post(Pump, _token);
|
||||
}
|
||||
|
||||
void Pump(object state)
|
||||
{
|
||||
if (!ReferenceEquals(state, _token)) return;
|
||||
Drain();
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stopped || _queue.Count == 0)
|
||||
{
|
||||
_pumpScheduled = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_context.Post(Pump, _token);
|
||||
}
|
||||
|
||||
void Drain()
|
||||
{
|
||||
var frame = _frameCount();
|
||||
if (frame != _frame)
|
||||
{
|
||||
_frame = frame;
|
||||
_startedThisFrame = 0;
|
||||
_budget.Reset();
|
||||
}
|
||||
|
||||
while (_startedThisFrame < ApiLimits.MaxRequestsPerFrame)
|
||||
{
|
||||
if (_startedThisFrame > 0 && _budget.ElapsedMilliseconds >= ApiLimits.MainThreadBudgetMs)
|
||||
break;
|
||||
GameWork work;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stopped || _queue.Count == 0) return;
|
||||
work = _queue.Dequeue();
|
||||
_running = work;
|
||||
}
|
||||
|
||||
_startedThisFrame++;
|
||||
_budget.Start();
|
||||
try { Run(work); }
|
||||
finally
|
||||
{
|
||||
_budget.Stop();
|
||||
lock (_gate) _running = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Run(GameWork work)
|
||||
{
|
||||
if (!work.Pending.IsActive)
|
||||
return;
|
||||
var now = _nowMs();
|
||||
if (now >= work.DeadlineMs)
|
||||
{
|
||||
work.Pending.TryComplete(ApiErrors.RequestTimeout());
|
||||
return;
|
||||
}
|
||||
|
||||
object result;
|
||||
try
|
||||
{
|
||||
result = _execute(work);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogError($"API game-data request failed: {ex}");
|
||||
work.Pending.TryComplete(ApiErrors.InternalError());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!work.Pending.IsActive)
|
||||
return;
|
||||
if (_nowMs() >= work.DeadlineMs)
|
||||
{
|
||||
work.Pending.TryComplete(ApiErrors.RequestTimeout());
|
||||
return;
|
||||
}
|
||||
|
||||
if (result is ApiError err)
|
||||
work.Pending.TryComplete(err);
|
||||
else
|
||||
work.Pending.TryCompleteResult(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LiveStreamAssist.Api;
|
||||
|
||||
internal sealed class ProductionExtraInfoRefresh
|
||||
{
|
||||
const int RefreshIntervalMs = 2000;
|
||||
readonly Dictionary<int, long> _nextRefreshMs = new Dictionary<int, long>();
|
||||
readonly HashSet<int> _pendingFactories = new HashSet<int>();
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_nextRefreshMs.Clear();
|
||||
_pendingFactories.Clear();
|
||||
}
|
||||
|
||||
public void OnRead(DataCall call, int factoryCount, bool calculating, long nowMs, Action<int> addFactory)
|
||||
{
|
||||
var factoryIndex = GetFactoryIndex(call);
|
||||
if (factoryIndex < 0 || factoryIndex >= factoryCount) return;
|
||||
|
||||
if (!_nextRefreshMs.TryGetValue(factoryIndex, out var next) || nowMs >= next)
|
||||
_pendingFactories.Add(factoryIndex);
|
||||
|
||||
// Let the native batch finish before requeuing factories it has already processed.
|
||||
if (calculating) return;
|
||||
foreach (var index in _pendingFactories)
|
||||
{
|
||||
if (index >= factoryCount) continue;
|
||||
addFactory(index);
|
||||
_nextRefreshMs[index] = nowMs + RefreshIntervalMs;
|
||||
}
|
||||
_pendingFactories.Clear();
|
||||
}
|
||||
|
||||
static int GetFactoryIndex(DataCall call)
|
||||
{
|
||||
if (call.Method != DataMethod.Read || call.Path == null) return -1;
|
||||
var path = call.Path;
|
||||
var offset = 0;
|
||||
if (call.Root == "game")
|
||||
{
|
||||
if (path.Length == 0 || path[0].Kind != PathKind.Member || path[0].Name != "statistics")
|
||||
return -1;
|
||||
offset = 1;
|
||||
}
|
||||
else if (call.Root != "statistics")
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (path.Length < offset + 3 ||
|
||||
path[offset].Kind != PathKind.Member || path[offset].Name != "production" ||
|
||||
path[offset + 1].Kind != PathKind.Member || path[offset + 1].Name != "factoryStatPool" ||
|
||||
path[offset + 2].Kind != PathKind.Index)
|
||||
return -1;
|
||||
return path[offset + 2].Index;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,832 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace LiveStreamAssist.Api;
|
||||
|
||||
internal sealed class MemberInfoDto
|
||||
{
|
||||
public string Name;
|
||||
public string Type;
|
||||
public string Kind;
|
||||
}
|
||||
|
||||
internal sealed class CollectionInfoDto
|
||||
{
|
||||
public string Kind;
|
||||
public string ElementType;
|
||||
public string KeyType;
|
||||
public int? Count;
|
||||
}
|
||||
|
||||
internal sealed class WalkResult
|
||||
{
|
||||
public object Encoded;
|
||||
public string TypeName;
|
||||
public bool IsNull;
|
||||
public MemberInfoDto[] Members;
|
||||
public CollectionInfoDto Collection;
|
||||
public ApiError Error;
|
||||
}
|
||||
|
||||
internal sealed class ReflectionReader
|
||||
{
|
||||
const int MaxCache = 1024;
|
||||
static readonly Assembly GameAssembly = typeof(GameData).Assembly;
|
||||
static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, false);
|
||||
internal static Action<string> Warn;
|
||||
|
||||
readonly Dictionary<Type, CachedType> _cache = new Dictionary<Type, CachedType>();
|
||||
readonly HashSet<Assembly> _extraAssemblies;
|
||||
readonly object _cacheGate = new object();
|
||||
|
||||
public ReflectionReader(params Assembly[] extraAllowed)
|
||||
{
|
||||
if (extraAllowed != null && extraAllowed.Length > 0)
|
||||
_extraAssemblies = new HashSet<Assembly>(extraAllowed);
|
||||
}
|
||||
|
||||
public void ClearCache()
|
||||
{
|
||||
lock (_cacheGate) _cache.Clear();
|
||||
}
|
||||
|
||||
public WalkResult Describe(object root, Type declaredType, PathSeg[] path)
|
||||
{
|
||||
var walked = Walk(root, declaredType, path);
|
||||
if (walked.Error != null) return Fail(walked.Error);
|
||||
return DescribeTerminal(walked.Value, walked.DeclaredType, walked.RuntimeType);
|
||||
}
|
||||
|
||||
public WalkResult Read(object root, Type declaredType, PathSeg[] path, ReadOptions options)
|
||||
{
|
||||
var walked = Walk(root, declaredType, path);
|
||||
if (walked.Error != null) return Fail(walked.Error);
|
||||
return ReadTerminal(walked.Value, walked.DeclaredType, walked.RuntimeType, options);
|
||||
}
|
||||
|
||||
public WalkResult DescribeTerminal(object value, Type declaredType, Type runtimeType)
|
||||
{
|
||||
var typeName = TypeName(value == null ? declaredType : runtimeType ?? value.GetType());
|
||||
var result = new WalkResult
|
||||
{
|
||||
TypeName = typeName,
|
||||
IsNull = value == null,
|
||||
Members = Array.Empty<MemberInfoDto>(),
|
||||
Encoded = null
|
||||
};
|
||||
var effective = value == null ? declaredType : runtimeType ?? value.GetType();
|
||||
if (!IsAllowedType(effective))
|
||||
return Fail(ApiErrors.UnsupportedType());
|
||||
if (TryCollectionKind(effective, out var kind, out var elementType, out var keyType))
|
||||
{
|
||||
int? count = null;
|
||||
if (value != null)
|
||||
count = GetCount(value, effective);
|
||||
result.Collection = new CollectionInfoDto
|
||||
{
|
||||
Kind = kind,
|
||||
ElementType = TypeName(elementType),
|
||||
KeyType = keyType == null ? null : TypeName(keyType),
|
||||
Count = count
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
if (value != null && IsScalar(Unwrap(effective)))
|
||||
return result;
|
||||
|
||||
if (effective != null && IsAllowedType(effective) && !IsScalar(Unwrap(effective)))
|
||||
result.Members = GetExposedMembers(effective);
|
||||
return result;
|
||||
}
|
||||
|
||||
public WalkResult ReadTerminal(object value, Type declaredType, Type runtimeType, ReadOptions options)
|
||||
{
|
||||
var typeName = TypeName(value == null ? declaredType : runtimeType ?? value.GetType());
|
||||
if (value == null)
|
||||
{
|
||||
if (options.HasOffset || options.HasLimit)
|
||||
{
|
||||
var declared = declaredType;
|
||||
if (!TryCollectionKind(declared, out var nullKind, out _, out _) ||
|
||||
(!string.Equals(nullKind, "array", StringComparison.Ordinal) &&
|
||||
!string.Equals(nullKind, "list", StringComparison.Ordinal)))
|
||||
return Fail(ApiErrors.InvalidParams("offset and limit are valid only for array or list terminals."));
|
||||
}
|
||||
|
||||
return new WalkResult { TypeName = typeName, IsNull = true, Encoded = null };
|
||||
}
|
||||
|
||||
var actual = runtimeType ?? value.GetType();
|
||||
if (TryCollectionKind(actual, out var kind, out var elementType, out _))
|
||||
{
|
||||
if (string.Equals(kind, "dictionary", StringComparison.Ordinal))
|
||||
{
|
||||
if (options.HasSelect)
|
||||
return Fail(ApiErrors.InvalidParams("select is invalid for dictionary terminals."));
|
||||
if (options.HasOffset || options.HasLimit)
|
||||
return Fail(ApiErrors.InvalidParams("offset and limit are valid only for array or list terminals."));
|
||||
return Ok(typeName, CollectionSummary(kind, actual, GetCount(value, actual)));
|
||||
}
|
||||
|
||||
if (options.HasSelect && IsScalar(Unwrap(elementType)))
|
||||
return Fail(ApiErrors.InvalidParams("select is invalid for scalar collection elements."));
|
||||
if (options.HasSelect && TryCollectionKind(elementType, out _, out _, out _))
|
||||
return Fail(ApiErrors.InvalidParams("select is invalid for collection elements."));
|
||||
|
||||
var page = ReadPage(value, actual, options);
|
||||
if (page.Error != null) return page;
|
||||
page.TypeName = typeName;
|
||||
return page;
|
||||
}
|
||||
|
||||
if (options.HasOffset || options.HasLimit)
|
||||
return Fail(ApiErrors.InvalidParams("offset and limit are valid only for array or list terminals."));
|
||||
|
||||
if (IsScalar(Unwrap(actual)))
|
||||
{
|
||||
if (options.HasSelect)
|
||||
return Fail(ApiErrors.InvalidParams("select is invalid for scalar terminals."));
|
||||
if (!TryEncodeScalar(value, actual, out var encoded, out var err))
|
||||
return Fail(err);
|
||||
return Ok(typeName, encoded);
|
||||
}
|
||||
|
||||
if (!IsAllowedType(actual))
|
||||
return Fail(ApiErrors.UnsupportedType());
|
||||
|
||||
if (options.HasSelect)
|
||||
{
|
||||
var projected = Project(value, actual, options.Select);
|
||||
if (projected.Error != null) return projected;
|
||||
projected.TypeName = typeName;
|
||||
return projected;
|
||||
}
|
||||
|
||||
return Ok(typeName, ObjectSummary(actual));
|
||||
}
|
||||
|
||||
WalkStep Walk(object root, Type declaredType, PathSeg[] path)
|
||||
{
|
||||
var current = root;
|
||||
var declared = declaredType;
|
||||
var runtime = current == null ? null : current.GetType();
|
||||
if (path == null || path.Length == 0)
|
||||
return new WalkStep { Value = current, DeclaredType = declared, RuntimeType = runtime };
|
||||
|
||||
for (var i = 0; i < path.Length; i++)
|
||||
{
|
||||
if (current == null)
|
||||
return new WalkStep { Error = ApiErrors.NullPath(i) };
|
||||
runtime = current.GetType();
|
||||
if (!IsAllowedType(runtime))
|
||||
return new WalkStep { Error = ApiErrors.UnsupportedType(i) };
|
||||
var seg = path[i];
|
||||
if (seg.Kind == PathKind.Member)
|
||||
{
|
||||
var slot = FindMember(runtime, seg.Name);
|
||||
if (slot == null)
|
||||
return new WalkStep { Error = ApiErrors.MemberNotFound(seg.Name, i) };
|
||||
if (!slot.Allowed)
|
||||
return new WalkStep { Error = ApiErrors.MemberNotAllowed(seg.Name, i) };
|
||||
if (!TryGetMemberValue(current, slot, i, out current, out var err))
|
||||
return new WalkStep { Error = err };
|
||||
declared = slot.DeclaredType;
|
||||
runtime = current == null ? null : current.GetType();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (seg.Kind == PathKind.Index)
|
||||
{
|
||||
if (!TryCollectionKind(runtime, out var kind, out var elementType, out _) ||
|
||||
!string.Equals(kind, "array", StringComparison.Ordinal) &&
|
||||
!string.Equals(kind, "list", StringComparison.Ordinal))
|
||||
return new WalkStep { Error = ApiErrors.UnsupportedType(i) };
|
||||
if (!TryGetIndex(current, runtime, seg.Index, i, out current, out var err))
|
||||
return new WalkStep { Error = err };
|
||||
declared = elementType;
|
||||
runtime = current == null ? null : current.GetType();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!TryCollectionKind(runtime, out var dkind, out var valueType, out var keyType) ||
|
||||
!string.Equals(dkind, "dictionary", StringComparison.Ordinal))
|
||||
return new WalkStep { Error = ApiErrors.UnsupportedType(i) };
|
||||
if (!TryCoerceKey(seg.Key, keyType, out var key, out var keyErr))
|
||||
return new WalkStep { Error = keyErr ?? ApiErrors.InvalidParams("dictionary key type mismatch.") };
|
||||
if (!TryGetKey(current, key, i, out current, out var kerr))
|
||||
return new WalkStep { Error = kerr };
|
||||
declared = valueType;
|
||||
runtime = current == null ? null : current.GetType();
|
||||
}
|
||||
|
||||
return new WalkStep { Value = current, DeclaredType = declared, RuntimeType = current == null ? null : current.GetType() };
|
||||
}
|
||||
|
||||
WalkResult ReadPage(object collection, Type collectionType, ReadOptions options)
|
||||
{
|
||||
var total = GetCount(collection, collectionType);
|
||||
var offset = options.EffectiveOffset;
|
||||
var limit = options.EffectiveLimit;
|
||||
var items = new List<object>();
|
||||
if (offset < total)
|
||||
{
|
||||
var take = Math.Min(limit, total - offset);
|
||||
for (var i = 0; i < take; i++)
|
||||
{
|
||||
if (!TryGetIndex(collection, collectionType, offset + i, null, out var item, out var err))
|
||||
return Fail(err);
|
||||
if (item == null)
|
||||
{
|
||||
items.Add(null);
|
||||
continue;
|
||||
}
|
||||
|
||||
var itemType = item.GetType();
|
||||
if (options.HasSelect)
|
||||
{
|
||||
if (IsScalar(Unwrap(itemType)) || TryCollectionKind(itemType, out _, out _, out _))
|
||||
return Fail(ApiErrors.InvalidParams("select is invalid for scalar or collection elements."));
|
||||
var projected = Project(item, itemType, options.Select);
|
||||
if (projected.Error != null) return projected;
|
||||
items.Add(projected.Encoded);
|
||||
}
|
||||
else if (IsScalar(Unwrap(itemType)))
|
||||
{
|
||||
if (!TryEncodeScalar(item, itemType, out var encoded, out var encErr))
|
||||
return Fail(encErr);
|
||||
items.Add(encoded);
|
||||
}
|
||||
else if (TryCollectionKind(itemType, out var ikind, out _, out _))
|
||||
items.Add(CollectionSummary(ikind, itemType, GetCount(item, itemType)));
|
||||
else if (!IsAllowedType(itemType))
|
||||
return Fail(ApiErrors.UnsupportedType());
|
||||
else
|
||||
items.Add(ObjectSummary(itemType));
|
||||
}
|
||||
}
|
||||
|
||||
return new WalkResult
|
||||
{
|
||||
Encoded = new Dictionary<string, object>
|
||||
{
|
||||
["items"] = items,
|
||||
["offset"] = offset,
|
||||
["totalCount"] = total,
|
||||
["hasMore"] = offset + items.Count < total
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
WalkResult Project(object value, Type type, string[] select)
|
||||
{
|
||||
if (!IsAllowedType(type)) return Fail(ApiErrors.UnsupportedType());
|
||||
var map = new Dictionary<string, object>(select.Length);
|
||||
foreach (var name in select)
|
||||
{
|
||||
var slot = FindMember(type, name);
|
||||
if (slot == null) return Fail(ApiErrors.MemberNotFound(name));
|
||||
if (!slot.Allowed) return Fail(ApiErrors.MemberNotAllowed(name));
|
||||
if (!TryGetMemberValue(value, slot, null, out var memberValue, out var err))
|
||||
return Fail(err);
|
||||
if (memberValue == null)
|
||||
{
|
||||
map[name] = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
var mt = memberValue.GetType();
|
||||
if (IsScalar(Unwrap(mt)))
|
||||
{
|
||||
if (!TryEncodeScalar(memberValue, mt, out var encoded, out var encErr))
|
||||
return Fail(encErr);
|
||||
map[name] = encoded;
|
||||
}
|
||||
else if (TryCollectionKind(mt, out var kind, out _, out _))
|
||||
map[name] = CollectionSummary(kind, mt, GetCount(memberValue, mt));
|
||||
else if (!IsAllowedType(mt))
|
||||
return Fail(ApiErrors.UnsupportedType(member: name));
|
||||
else
|
||||
map[name] = ObjectSummary(mt);
|
||||
}
|
||||
|
||||
return new WalkResult { Encoded = map };
|
||||
}
|
||||
|
||||
bool TryGetMemberValue(object instance, MemberSlot slot, int? segmentIndex, out object value, out ApiError error)
|
||||
{
|
||||
value = null;
|
||||
error = null;
|
||||
try
|
||||
{
|
||||
if (slot.Field != null)
|
||||
{
|
||||
value = slot.Field.GetValue(instance);
|
||||
return true;
|
||||
}
|
||||
|
||||
value = slot.Property.GetValue(instance, null);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Warn?.Invoke($"API read failed at {slot.Name}: {ex}");
|
||||
error = ApiErrors.ReadFailed(segmentIndex, slot.Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool TryGetIndex(object collection, Type collectionType, int index, int? segmentIndex, out object value, out ApiError error)
|
||||
{
|
||||
value = null;
|
||||
error = null;
|
||||
var count = GetCount(collection, collectionType);
|
||||
if (index < 0 || index >= count)
|
||||
{
|
||||
error = ApiErrors.IndexOutOfRange(segmentIndex ?? 0);
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (collectionType.IsArray)
|
||||
{
|
||||
value = ((Array)collection).GetValue(index);
|
||||
return true;
|
||||
}
|
||||
|
||||
value = ((IList)collection)[index];
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Warn?.Invoke($"API index read failed: {ex}");
|
||||
error = ApiErrors.ReadFailed(segmentIndex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static bool TryGetKey(object collection, object key, int segmentIndex, out object value, out ApiError error)
|
||||
{
|
||||
value = null;
|
||||
error = null;
|
||||
try
|
||||
{
|
||||
var dict = (IDictionary)collection;
|
||||
if (!dict.Contains(key))
|
||||
{
|
||||
error = ApiErrors.KeyNotFound(segmentIndex);
|
||||
return false;
|
||||
}
|
||||
|
||||
value = dict[key];
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Warn?.Invoke($"API key read failed: {ex}");
|
||||
error = ApiErrors.ReadFailed(segmentIndex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static bool TryCoerceKey(object raw, Type keyType, out object key, out ApiError error)
|
||||
{
|
||||
key = null;
|
||||
error = null;
|
||||
if (keyType == typeof(int))
|
||||
{
|
||||
if (raw is int i)
|
||||
{
|
||||
key = i;
|
||||
return true;
|
||||
}
|
||||
|
||||
error = ApiErrors.InvalidParams("dictionary key type mismatch.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (keyType == typeof(string))
|
||||
{
|
||||
if (raw is string s)
|
||||
{
|
||||
key = s;
|
||||
return true;
|
||||
}
|
||||
|
||||
error = ApiErrors.InvalidParams("dictionary key type mismatch.");
|
||||
return false;
|
||||
}
|
||||
|
||||
error = ApiErrors.UnsupportedType();
|
||||
return false;
|
||||
}
|
||||
|
||||
static int GetCount(object collection, Type type)
|
||||
{
|
||||
if (type.IsArray) return ((Array)collection).Length;
|
||||
return ((ICollection)collection).Count;
|
||||
}
|
||||
|
||||
MemberSlot FindMember(Type type, string name)
|
||||
{
|
||||
var cached = GetCached(type);
|
||||
return cached.ByName.TryGetValue(name, out var slot) ? slot : null;
|
||||
}
|
||||
|
||||
MemberInfoDto[] GetExposedMembers(Type type)
|
||||
{
|
||||
return GetCached(type).Exposed;
|
||||
}
|
||||
|
||||
CachedType GetCached(Type type)
|
||||
{
|
||||
lock (_cacheGate)
|
||||
{
|
||||
if (_cache.TryGetValue(type, out var hit))
|
||||
return hit;
|
||||
}
|
||||
|
||||
var built = BuildMembers(type);
|
||||
lock (_cacheGate)
|
||||
{
|
||||
if (_cache.TryGetValue(type, out var hit))
|
||||
return hit;
|
||||
if (_cache.Count < MaxCache)
|
||||
_cache[type] = built;
|
||||
return built;
|
||||
}
|
||||
}
|
||||
|
||||
CachedType BuildMembers(Type type)
|
||||
{
|
||||
var byName = new Dictionary<string, MemberSlot>(StringComparer.Ordinal);
|
||||
if (!IsAllowedType(type) || IsScalar(Unwrap(type)) || TryCollectionKind(type, out _, out _, out _))
|
||||
return new CachedType { ByName = byName, Exposed = Array.Empty<MemberInfoDto>() };
|
||||
for (var t = type; t != null && t != typeof(object); t = t.BaseType)
|
||||
{
|
||||
if (!IsAllowedType(t) || TryCollectionKind(t, out _, out _, out _)) break;
|
||||
foreach (var field in t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly))
|
||||
{
|
||||
if (field.IsStatic || field.IsDefined(typeof(CompilerGeneratedAttribute), false) || field.Name.IndexOf('<') >= 0)
|
||||
continue;
|
||||
if (byName.ContainsKey(field.Name))
|
||||
continue;
|
||||
var ft = field.FieldType;
|
||||
byName[field.Name] = new MemberSlot
|
||||
{
|
||||
Name = field.Name,
|
||||
Kind = "field",
|
||||
DeclaredType = ft,
|
||||
Field = field,
|
||||
Allowed = IsAllowedType(ft)
|
||||
};
|
||||
}
|
||||
|
||||
foreach (var prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly))
|
||||
{
|
||||
if (prop.GetIndexParameters().Length != 0)
|
||||
continue;
|
||||
if (byName.ContainsKey(prop.Name))
|
||||
continue;
|
||||
var allowed = IsAllowedProperty(prop) && IsAllowedType(prop.PropertyType) && prop.CanRead && prop.GetGetMethod(true) != null;
|
||||
byName[prop.Name] = new MemberSlot
|
||||
{
|
||||
Name = prop.Name,
|
||||
Kind = "property",
|
||||
DeclaredType = prop.PropertyType,
|
||||
Property = prop,
|
||||
Allowed = allowed
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
var exposed = new List<MemberInfoDto>();
|
||||
foreach (var pair in byName)
|
||||
{
|
||||
if (!pair.Value.Allowed) continue;
|
||||
exposed.Add(new MemberInfoDto
|
||||
{
|
||||
Name = pair.Value.Name,
|
||||
Type = TypeName(pair.Value.DeclaredType),
|
||||
Kind = pair.Value.Kind
|
||||
});
|
||||
}
|
||||
|
||||
exposed.Sort((a, b) => string.CompareOrdinal(a.Name, b.Name));
|
||||
return new CachedType { ByName = byName, Exposed = exposed.ToArray() };
|
||||
}
|
||||
|
||||
static bool IsAllowedProperty(PropertyInfo prop)
|
||||
{
|
||||
if (prop.DeclaringType == typeof(GameHistoryData))
|
||||
return string.Equals(prop.Name, "currentTech", StringComparison.Ordinal);
|
||||
|
||||
if (prop.DeclaringType == typeof(GameDesc))
|
||||
return string.Equals(prop.Name, "clusterString", StringComparison.Ordinal);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool IsAllowedType(Type type)
|
||||
{
|
||||
if (type == null) return false;
|
||||
type = Unwrap(type);
|
||||
if (IsForbidden(type)) return false;
|
||||
if (IsScalar(type) || IsUnityStruct(type)) return true;
|
||||
if (type.IsArray) return IsSupportedArray(type);
|
||||
if (IsSupportedList(type) || IsSupportedDictionary(type)) return true;
|
||||
if (type.Assembly == GameAssembly) return true;
|
||||
if (_extraAssemblies != null && _extraAssemblies.Contains(type.Assembly)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool IsSupportedArray(Type type)
|
||||
{
|
||||
if (!type.IsArray || type.GetArrayRank() != 1) return false;
|
||||
var element = type.GetElementType();
|
||||
return element != null && type == element.MakeArrayType() && IsAllowedType(element);
|
||||
}
|
||||
|
||||
bool IsSupportedList(Type type)
|
||||
{
|
||||
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(List<>)) return false;
|
||||
return IsAllowedType(type.GetGenericArguments()[0]);
|
||||
}
|
||||
|
||||
bool IsSupportedDictionary(Type type)
|
||||
{
|
||||
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Dictionary<,>)) return false;
|
||||
var args = type.GetGenericArguments();
|
||||
if (args[0] != typeof(int) && args[0] != typeof(string)) return false;
|
||||
return IsAllowedType(args[1]);
|
||||
}
|
||||
|
||||
bool TryCollectionKind(Type type, out string kind, out Type elementType, out Type keyType)
|
||||
{
|
||||
kind = null;
|
||||
elementType = null;
|
||||
keyType = null;
|
||||
if (type == null) return false;
|
||||
type = Unwrap(type);
|
||||
if (IsSupportedArray(type))
|
||||
{
|
||||
kind = "array";
|
||||
elementType = type.GetElementType();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (IsSupportedList(type))
|
||||
{
|
||||
kind = "list";
|
||||
elementType = type.GetGenericArguments()[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
if (IsSupportedDictionary(type))
|
||||
{
|
||||
kind = "dictionary";
|
||||
var args = type.GetGenericArguments();
|
||||
keyType = args[0];
|
||||
elementType = args[1];
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool IsForbidden(Type t)
|
||||
{
|
||||
if (t.IsPointer || t.IsByRef || t.IsGenericParameter) return true;
|
||||
if (t == typeof(IntPtr) || t == typeof(UIntPtr) || t == typeof(TypedReference)) return true;
|
||||
if (typeof(Delegate).IsAssignableFrom(t)) return true;
|
||||
if (typeof(Type).IsAssignableFrom(t) || typeof(MemberInfo).IsAssignableFrom(t) ||
|
||||
typeof(Assembly).IsAssignableFrom(t) || typeof(Module).IsAssignableFrom(t))
|
||||
return true;
|
||||
if (typeof(System.IO.Stream).IsAssignableFrom(t) || typeof(System.IO.TextReader).IsAssignableFrom(t) ||
|
||||
typeof(System.IO.TextWriter).IsAssignableFrom(t))
|
||||
return true;
|
||||
if (typeof(Task).IsAssignableFrom(t) || typeof(Thread).IsAssignableFrom(t) || typeof(WaitHandle).IsAssignableFrom(t))
|
||||
return true;
|
||||
if (t == typeof(SpinLock) || t == typeof(Mutex) || t == typeof(Semaphore) || t == typeof(ReaderWriterLock) ||
|
||||
t == typeof(ReaderWriterLockSlim))
|
||||
return true;
|
||||
if (typeof(UnityEngine.Object).IsAssignableFrom(t)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool IsScalar(Type t)
|
||||
{
|
||||
if (t.IsEnum) return true;
|
||||
return t == typeof(bool) || t == typeof(string) || t == typeof(char) ||
|
||||
t == typeof(byte) || t == typeof(sbyte) || t == typeof(short) || t == typeof(ushort) ||
|
||||
t == typeof(int) || t == typeof(uint) || t == typeof(long) || t == typeof(ulong) ||
|
||||
t == typeof(float) || t == typeof(double) || t == typeof(decimal) ||
|
||||
t == typeof(DateTime) || t == typeof(DateTimeOffset) || t == typeof(Guid);
|
||||
}
|
||||
|
||||
static bool IsUnityStruct(Type t)
|
||||
{
|
||||
return t == typeof(Vector2) || t == typeof(Vector3) || t == typeof(Vector4) || t == typeof(Quaternion);
|
||||
}
|
||||
|
||||
static Type Unwrap(Type t)
|
||||
{
|
||||
return Nullable.GetUnderlyingType(t) ?? t;
|
||||
}
|
||||
|
||||
static bool TryEncodeScalar(object value, Type type, out object encoded, out ApiError error)
|
||||
{
|
||||
encoded = null;
|
||||
error = null;
|
||||
type = Unwrap(type);
|
||||
if (value == null)
|
||||
return true;
|
||||
if (type.IsEnum)
|
||||
{
|
||||
var name = Enum.GetName(type, value);
|
||||
encoded = new Dictionary<string, object>
|
||||
{
|
||||
["name"] = name,
|
||||
["value"] = Enum.Format(type, value, "D")
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(bool))
|
||||
{
|
||||
encoded = (bool)value;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(uint))
|
||||
{
|
||||
encoded = (uint)value;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(int) || type == typeof(byte) || type == typeof(sbyte) || type == typeof(short) ||
|
||||
type == typeof(ushort))
|
||||
{
|
||||
encoded = Convert.ToInt32(value, CultureInfo.InvariantCulture);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(string))
|
||||
{
|
||||
var s = (string)value;
|
||||
if (!CheckStringSize(s, out error)) return false;
|
||||
encoded = s;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(char))
|
||||
{
|
||||
encoded = ((char)value).ToString();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(long))
|
||||
{
|
||||
encoded = ((long)value).ToString(CultureInfo.InvariantCulture);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(ulong))
|
||||
{
|
||||
encoded = ((ulong)value).ToString(CultureInfo.InvariantCulture);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(decimal))
|
||||
{
|
||||
encoded = ((decimal)value).ToString(CultureInfo.InvariantCulture);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(float))
|
||||
{
|
||||
var f = (float)value;
|
||||
if (float.IsNaN(f) || float.IsInfinity(f))
|
||||
{
|
||||
error = ApiErrors.UnsupportedValue();
|
||||
return false;
|
||||
}
|
||||
|
||||
encoded = f;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(double))
|
||||
{
|
||||
var d = (double)value;
|
||||
if (double.IsNaN(d) || double.IsInfinity(d))
|
||||
{
|
||||
error = ApiErrors.UnsupportedValue();
|
||||
return false;
|
||||
}
|
||||
|
||||
encoded = d;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(DateTime))
|
||||
{
|
||||
encoded = ((DateTime)value).ToString("o", CultureInfo.InvariantCulture);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(DateTimeOffset))
|
||||
{
|
||||
encoded = ((DateTimeOffset)value).ToString("o", CultureInfo.InvariantCulture);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (type == typeof(Guid))
|
||||
{
|
||||
encoded = ((Guid)value).ToString("D");
|
||||
return true;
|
||||
}
|
||||
|
||||
error = ApiErrors.UnsupportedType();
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool CheckStringSize(string s, out ApiError error)
|
||||
{
|
||||
error = null;
|
||||
if (s == null) return true;
|
||||
if (s.Length > ApiLimits.MaxResponseBytes || Utf8.GetByteCount(s) > ApiLimits.MaxResponseBytes)
|
||||
{
|
||||
error = ApiErrors.LimitExceeded("String value exceeds maxResponseBytes.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static Dictionary<string, object> ObjectSummary(Type type)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["$kind"] = "object",
|
||||
["$type"] = TypeName(type)
|
||||
};
|
||||
}
|
||||
|
||||
static Dictionary<string, object> CollectionSummary(string kind, Type type, int count)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["$kind"] = kind,
|
||||
["$type"] = TypeName(type),
|
||||
["count"] = count
|
||||
};
|
||||
}
|
||||
|
||||
internal static string TypeName(Type type)
|
||||
{
|
||||
if (type == null) return null;
|
||||
type = Unwrap(type);
|
||||
if (type.IsArray && type.GetArrayRank() == 1)
|
||||
return TypeName(type.GetElementType()) + "[]";
|
||||
return type.FullName ?? type.Name;
|
||||
}
|
||||
|
||||
static WalkResult Fail(ApiError error) => new WalkResult { Error = error };
|
||||
|
||||
static WalkResult Ok(string typeName, object encoded) =>
|
||||
new WalkResult { TypeName = typeName, Encoded = encoded, IsNull = encoded == null };
|
||||
|
||||
sealed class MemberSlot
|
||||
{
|
||||
public string Name;
|
||||
public string Kind;
|
||||
public Type DeclaredType;
|
||||
public FieldInfo Field;
|
||||
public PropertyInfo Property;
|
||||
public bool Allowed;
|
||||
}
|
||||
|
||||
sealed class CachedType
|
||||
{
|
||||
public Dictionary<string, MemberSlot> ByName;
|
||||
public MemberInfoDto[] Exposed;
|
||||
}
|
||||
|
||||
struct WalkStep
|
||||
{
|
||||
public object Value;
|
||||
public Type DeclaredType;
|
||||
public Type RuntimeType;
|
||||
public ApiError Error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BepInEx.Configuration;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using GameLogicProc = UXAssist.Common.GameLogic;
|
||||
|
||||
namespace LiveStreamAssist.Api;
|
||||
|
||||
[ModFeature("WebSocketApi", Order = 51)]
|
||||
internal static class WebSocketApiFeature
|
||||
{
|
||||
internal static ConfigEntry<bool> Enabled;
|
||||
internal static ConfigEntry<string> ListenAddress;
|
||||
internal static ConfigEntry<int> Port;
|
||||
|
||||
static readonly string[] RootNames =
|
||||
{ "game", "player", "history", "statistics", "galaxy", "localPlanet", "localStar" };
|
||||
|
||||
static readonly Type[] RootTypes =
|
||||
{
|
||||
typeof(GameData), typeof(Player), typeof(GameHistoryData), typeof(GameStatData),
|
||||
typeof(GalaxyData), typeof(PlanetData), typeof(StarData)
|
||||
};
|
||||
|
||||
static readonly object Gate = new object();
|
||||
static readonly ProductionExtraInfoRefresh ProductionRefresh = new ProductionExtraInfoRefresh();
|
||||
static object _ownerToken;
|
||||
static WebSocketApiServer _server;
|
||||
static MainThreadDispatcher _dispatcher;
|
||||
static ReflectionReader _reader;
|
||||
static volatile GameVersionSnapshot _version = GameVersionSnapshot.Empty;
|
||||
static volatile SessionSnapshot _session = new SessionSnapshot(0, null);
|
||||
static bool _started;
|
||||
|
||||
public static void BindConfig(ConfigFile config)
|
||||
{
|
||||
Enabled = config.Bind("WebSocketApi", "Enabled", false,
|
||||
"Start the WebSocket API listener when the mod starts");
|
||||
ListenAddress = config.Bind("WebSocketApi", "ListenAddress", "127.0.0.1",
|
||||
"Bind address; use a specific LAN address or 0.0.0.0 for LAN access");
|
||||
Port = config.Bind("WebSocketApi", "Port", 18080,
|
||||
new ConfigDescription("Listening port", new AcceptableValueRange<int>(1, 65535)));
|
||||
}
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
_reader = new ReflectionReader();
|
||||
ProductionRefresh.Reset();
|
||||
ReflectionReader.Warn = msg => LiveStreamAssist.Logger.LogWarning(msg);
|
||||
_version = GameVersionSnapshot.Empty;
|
||||
_session = new SessionSnapshot(0, null);
|
||||
}
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
if (_started) return;
|
||||
if (Enabled == null || !Enabled.Value) return;
|
||||
var ctx = SynchronizationContext.Current;
|
||||
if (ctx == null || ctx.GetType().FullName != "UnityEngine.UnitySynchronizationContext")
|
||||
{
|
||||
LiveStreamAssist.Logger.LogError(
|
||||
"WebSocket API requires Unity's installed SynchronizationContext; startup aborted.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IPAddress.TryParse(ListenAddress.Value, out var address))
|
||||
{
|
||||
LiveStreamAssist.Logger.LogError($"WebSocket API listen address is invalid: {ListenAddress.Value}");
|
||||
return;
|
||||
}
|
||||
|
||||
var port = Port.Value;
|
||||
if (port < 1 || port > 65535)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogError($"WebSocket API port is invalid: {port}");
|
||||
return;
|
||||
}
|
||||
|
||||
var token = new object();
|
||||
WebSocketApiServer server = null;
|
||||
var dispatcher = new MainThreadDispatcher(ctx, token,
|
||||
work => ReferenceEquals(_ownerToken, token) ? ExecuteWork(work) : ApiErrors.SessionChanged(),
|
||||
() => server?.NowMs ?? 0);
|
||||
server = new WebSocketApiServer(address, port, PluginInfo.PLUGIN_VERSION, GetVersion, GetSession, dispatcher);
|
||||
GameLogicProc.OnDataLoaded += OnDataLoaded;
|
||||
GameLogicProc.OnGameBegin += OnGameBegin;
|
||||
GameLogicProc.OnGameEnd += OnGameEnd;
|
||||
lock (Gate)
|
||||
{
|
||||
_ownerToken = token;
|
||||
_dispatcher = dispatcher;
|
||||
_server = server;
|
||||
_started = true;
|
||||
}
|
||||
|
||||
if (VFPreload.done || VFPreload.dbDone)
|
||||
PublishVersion();
|
||||
if (IsGameReady())
|
||||
BeginSession();
|
||||
_ = StartServerAsync();
|
||||
|
||||
async Task StartServerAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await server.StartAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogError($"WebSocket API failed to start: {ex}");
|
||||
dispatcher.Stop();
|
||||
await server.StopAsync().ConfigureAwait(false);
|
||||
ctx.Post(_ =>
|
||||
{
|
||||
if (ReferenceEquals(_ownerToken, token)) Uninit();
|
||||
}, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Uninit()
|
||||
{
|
||||
WebSocketApiServer server;
|
||||
MainThreadDispatcher dispatcher;
|
||||
lock (Gate)
|
||||
{
|
||||
if (!_started && _server == null) return;
|
||||
_started = false;
|
||||
_ownerToken = new object();
|
||||
server = _server;
|
||||
dispatcher = _dispatcher;
|
||||
_server = null;
|
||||
_dispatcher = null;
|
||||
_session = new SessionSnapshot(_session.Generation + 1, null);
|
||||
}
|
||||
|
||||
GameLogicProc.OnDataLoaded -= OnDataLoaded;
|
||||
GameLogicProc.OnGameBegin -= OnGameBegin;
|
||||
GameLogicProc.OnGameEnd -= OnGameEnd;
|
||||
try { dispatcher?.Stop(); }
|
||||
catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"WebSocket API dispatcher stop failed: {ex.Message}"); }
|
||||
try { server?.Stop(); }
|
||||
catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"WebSocket API server stop failed: {ex.Message}"); }
|
||||
_reader?.ClearCache();
|
||||
ProductionRefresh.Reset();
|
||||
ReflectionReader.Warn = null;
|
||||
}
|
||||
|
||||
public static bool IsKnownRoot(string name)
|
||||
{
|
||||
for (var i = 0; i < RootNames.Length; i++)
|
||||
{
|
||||
if (string.Equals(RootNames[i], name, StringComparison.Ordinal))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static GameVersionSnapshot GetVersion() => _version;
|
||||
static SessionSnapshot GetSession() => _session;
|
||||
|
||||
static void OnDataLoaded() => PublishVersion();
|
||||
|
||||
static void PublishVersion()
|
||||
{
|
||||
var v = GameConfig.gameVersion;
|
||||
_version = new GameVersionSnapshot(true, v.ToString(), GameConfig.build);
|
||||
}
|
||||
|
||||
static void OnGameBegin()
|
||||
{
|
||||
if (IsGameReady())
|
||||
BeginSession();
|
||||
}
|
||||
|
||||
static void OnGameEnd()
|
||||
{
|
||||
EndSession();
|
||||
}
|
||||
|
||||
static void BeginSession()
|
||||
{
|
||||
ProductionRefresh.Reset();
|
||||
MainThreadDispatcher dispatcher;
|
||||
int oldGeneration;
|
||||
lock (Gate)
|
||||
{
|
||||
oldGeneration = _session.Generation;
|
||||
_session = new SessionSnapshot(oldGeneration + 1, Guid.NewGuid().ToString("D"));
|
||||
dispatcher = _dispatcher;
|
||||
}
|
||||
|
||||
dispatcher?.CancelQueued(work => work.Generation == _session.Generation ? null : ApiErrors.SessionChanged());
|
||||
}
|
||||
|
||||
static void EndSession()
|
||||
{
|
||||
ProductionRefresh.Reset();
|
||||
MainThreadDispatcher dispatcher;
|
||||
lock (Gate)
|
||||
{
|
||||
_session = new SessionSnapshot(_session.Generation + 1, null);
|
||||
dispatcher = _dispatcher;
|
||||
}
|
||||
|
||||
dispatcher?.CancelQueued(work => work.Generation == _session.Generation ? null : ApiErrors.SessionChanged());
|
||||
}
|
||||
|
||||
static bool IsGameReady()
|
||||
{
|
||||
return GameMain.data != null && GameMain.isRunning && !GameMain.isLoading && !DSPGame.IsMenuDemo;
|
||||
}
|
||||
|
||||
static object ResolveRoot(string name)
|
||||
{
|
||||
switch (name)
|
||||
{
|
||||
case "game": return GameMain.data;
|
||||
case "player": return GameMain.mainPlayer;
|
||||
case "history": return GameMain.history;
|
||||
case "statistics": return GameMain.statistics;
|
||||
case "galaxy": return GameMain.galaxy;
|
||||
case "localPlanet": return GameMain.localPlanet;
|
||||
case "localStar": return GameMain.localStar;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
static Type DeclaredRootType(string name)
|
||||
{
|
||||
for (var i = 0; i < RootNames.Length; i++)
|
||||
{
|
||||
if (string.Equals(RootNames[i], name, StringComparison.Ordinal))
|
||||
return RootTypes[i];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
static object ExecuteWork(GameWork work)
|
||||
{
|
||||
var session = _session;
|
||||
if (work.Generation != session.Generation)
|
||||
return ApiErrors.SessionChanged();
|
||||
var call = work.Call;
|
||||
if (call.Method == DataMethod.Roots)
|
||||
return BuildRoots(session);
|
||||
if (!IsGameReady())
|
||||
return ApiErrors.GameNotReady();
|
||||
if (session.SessionId == null)
|
||||
return ApiErrors.GameNotReady();
|
||||
var instance = ResolveRoot(call.Root);
|
||||
if (instance == null)
|
||||
return ApiErrors.RootUnavailable(call.Root);
|
||||
var declared = DeclaredRootType(call.Root);
|
||||
WalkResult walked;
|
||||
if (call.Method == DataMethod.Describe)
|
||||
walked = _reader.Describe(instance, declared, call.Path);
|
||||
else
|
||||
walked = _reader.Read(instance, declared, call.Path, call.Options);
|
||||
if (walked.Error != null)
|
||||
return walked.Error;
|
||||
if (_session.Generation != work.Generation)
|
||||
return ApiErrors.SessionChanged();
|
||||
if (call.Method == DataMethod.Read)
|
||||
{
|
||||
var production = GameMain.statistics?.production;
|
||||
var calculator = production?.extraInfoCalculator;
|
||||
if (calculator != null)
|
||||
{
|
||||
// Native GameTickCharts refreshes derived statistics without opening the statistics UI.
|
||||
ProductionRefresh.OnRead(call, GameMain.data.factoryCount, calculator.calculating,
|
||||
_server.NowMs, calculator.AddFactory);
|
||||
}
|
||||
}
|
||||
var tick = GameMain.gameTick.ToString(CultureInfo.InvariantCulture);
|
||||
if (call.Method == DataMethod.Describe)
|
||||
return BuildDescribe(walked, session.SessionId, tick);
|
||||
return BuildRead(walked, session.SessionId, tick);
|
||||
}
|
||||
|
||||
static Dictionary<string, object> BuildRoots(SessionSnapshot session)
|
||||
{
|
||||
var ready = IsGameReady() && session.SessionId != null;
|
||||
var roots = new List<object>(RootNames.Length);
|
||||
for (var i = 0; i < RootNames.Length; i++)
|
||||
{
|
||||
var available = ready && ResolveRoot(RootNames[i]) != null;
|
||||
roots.Add(new Dictionary<string, object>
|
||||
{
|
||||
["name"] = RootNames[i],
|
||||
["type"] = ReflectionReader.TypeName(RootTypes[i]),
|
||||
["available"] = available
|
||||
});
|
||||
}
|
||||
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["gameReady"] = ready,
|
||||
["sessionId"] = ready ? session.SessionId : null,
|
||||
["gameTick"] = ready ? GameMain.gameTick.ToString(CultureInfo.InvariantCulture) : null,
|
||||
["roots"] = roots
|
||||
};
|
||||
}
|
||||
|
||||
static Dictionary<string, object> BuildDescribe(WalkResult walked, string sessionId, string tick)
|
||||
{
|
||||
var members = new List<object>(walked.Members?.Length ?? 0);
|
||||
if (walked.Members != null)
|
||||
{
|
||||
foreach (var m in walked.Members)
|
||||
{
|
||||
members.Add(new Dictionary<string, object>
|
||||
{
|
||||
["name"] = m.Name,
|
||||
["type"] = m.Type,
|
||||
["kind"] = m.Kind
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
object collection = null;
|
||||
if (walked.Collection != null)
|
||||
{
|
||||
collection = new Dictionary<string, object>
|
||||
{
|
||||
["kind"] = walked.Collection.Kind,
|
||||
["elementType"] = walked.Collection.ElementType,
|
||||
["keyType"] = walked.Collection.KeyType,
|
||||
["count"] = walked.Collection.Count
|
||||
};
|
||||
}
|
||||
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["type"] = walked.TypeName,
|
||||
["isNull"] = walked.IsNull,
|
||||
["members"] = members,
|
||||
["collection"] = collection,
|
||||
["sessionId"] = sessionId,
|
||||
["gameTick"] = tick
|
||||
};
|
||||
}
|
||||
|
||||
static Dictionary<string, object> BuildRead(WalkResult walked, string sessionId, string tick)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["type"] = walked.TypeName,
|
||||
["value"] = walked.Encoded,
|
||||
["sessionId"] = sessionId,
|
||||
["gameTick"] = tick
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,803 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace LiveStreamAssist.Api;
|
||||
|
||||
internal sealed class ProducedResponse
|
||||
{
|
||||
public object Result;
|
||||
public ApiError Error;
|
||||
}
|
||||
|
||||
internal sealed class PendingRequest
|
||||
{
|
||||
int _done;
|
||||
public ApiConnection Connection;
|
||||
public string Id;
|
||||
readonly TaskCompletionSource<ProducedResponse> _tcs =
|
||||
new TaskCompletionSource<ProducedResponse>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public Task<ProducedResponse> Completion => _tcs.Task;
|
||||
public bool IsActive => Volatile.Read(ref _done) == 0 && Connection != null && Connection.IsOpen;
|
||||
|
||||
public bool TryComplete(ApiError error)
|
||||
{
|
||||
if (error == null || Interlocked.Exchange(ref _done, 1) != 0) return false;
|
||||
return _tcs.TrySetResult(new ProducedResponse { Error = error });
|
||||
}
|
||||
|
||||
public bool TryCompleteResult(object result)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _done, 1) != 0) return false;
|
||||
return _tcs.TrySetResult(new ProducedResponse { Result = result });
|
||||
}
|
||||
|
||||
public bool TryCancel()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _done, 1) != 0) return false;
|
||||
_tcs.TrySetCanceled();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class ApiConnection : IDisposable
|
||||
{
|
||||
readonly WebSocketApiServer _server;
|
||||
readonly object _gate = new object();
|
||||
readonly Dictionary<string, PendingRequest> _outstanding = new Dictionary<string, PendingRequest>(StringComparer.Ordinal);
|
||||
readonly Queue<SendItem> _sendQueue = new Queue<SendItem>();
|
||||
readonly SemaphoreSlim _sendSignal = new SemaphoreSlim(0);
|
||||
readonly SemaphoreSlim _sendGate = new SemaphoreSlim(1, 1);
|
||||
readonly CancellationTokenSource _cancellation = new CancellationTokenSource();
|
||||
WebSocket _socket;
|
||||
Task _closeTask;
|
||||
bool _closing;
|
||||
bool _closed;
|
||||
bool _sending;
|
||||
|
||||
public ApiConnection(WebSocketApiServer server)
|
||||
{
|
||||
_server = server;
|
||||
}
|
||||
|
||||
public void Attach(WebSocket socket)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_socket = socket;
|
||||
if (!_closed) return;
|
||||
}
|
||||
socket.Abort();
|
||||
}
|
||||
|
||||
public CancellationToken Cancellation => _cancellation.Token;
|
||||
|
||||
public Task CloseCompletion
|
||||
{
|
||||
get { lock (_gate) return _closeTask ?? Task.CompletedTask; }
|
||||
}
|
||||
|
||||
public bool IsOpen
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return !_closed && !_closing;
|
||||
}
|
||||
}
|
||||
|
||||
public PendingRequest TryAdmit(string id, out bool duplicate, out bool busy)
|
||||
{
|
||||
duplicate = false;
|
||||
busy = false;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_closed || _closing) return null;
|
||||
if (_outstanding.ContainsKey(id))
|
||||
{
|
||||
duplicate = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (_outstanding.Count >= ApiLimits.MaxPendingRequestsPerConnection || !_server.TryIncrementPending())
|
||||
{
|
||||
busy = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
var pending = new PendingRequest { Connection = this, Id = id };
|
||||
_outstanding[id] = pending;
|
||||
_ = DeliverAsync(pending);
|
||||
return pending;
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanSendBusy()
|
||||
{
|
||||
lock (_gate)
|
||||
return !_closed && !_closing && _sendQueue.Count + (_sending ? 1 : 0) < ApiLimits.MaxPendingRequestsPerConnection;
|
||||
}
|
||||
|
||||
public void EnqueueError(object id, ApiError error)
|
||||
{
|
||||
byte[] payload;
|
||||
try
|
||||
{
|
||||
payload = ApiProtocol.SerializeEnvelope(id, null, error);
|
||||
}
|
||||
catch (ResponseTooLargeException)
|
||||
{
|
||||
Close(ApiLimits.CloseTryAgainLater);
|
||||
return;
|
||||
}
|
||||
|
||||
EnqueueSend(new SendItem { Payload = payload, EnqueuedMs = _server.NowMs });
|
||||
}
|
||||
|
||||
public void Release(string id)
|
||||
{
|
||||
var released = false;
|
||||
lock (_gate)
|
||||
{
|
||||
if (id != null && _outstanding.Remove(id))
|
||||
{
|
||||
released = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (released) _server.DecrementPending();
|
||||
}
|
||||
|
||||
public void Close(int code) => _ = CloseAsync(code);
|
||||
|
||||
public Task CloseAsync(int code)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_closeTask != null) return _closeTask;
|
||||
if (_closed) return Task.CompletedTask;
|
||||
_closing = true;
|
||||
_sendQueue.Clear();
|
||||
_cancellation.CancelAfter(ApiLimits.RequestTimeoutMs);
|
||||
_sendSignal.Release();
|
||||
return _closeTask = Task.Run(SendCloseAsync);
|
||||
}
|
||||
|
||||
async Task SendCloseAsync()
|
||||
{
|
||||
var entered = false;
|
||||
try
|
||||
{
|
||||
await _sendGate.WaitAsync(Cancellation).ConfigureAwait(false);
|
||||
entered = true;
|
||||
var ws = _socket;
|
||||
if (ws == null)
|
||||
{
|
||||
NotifyDisconnected();
|
||||
return;
|
||||
}
|
||||
if (ws.State == WebSocketState.Open || ws.State == WebSocketState.CloseReceived)
|
||||
await ws.CloseOutputAsync((WebSocketCloseStatus)code, "", Cancellation).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogWarning($"API close failed: {ex.Message}");
|
||||
AbortSend(_socket);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (entered) _sendGate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void NotifyDisconnected()
|
||||
{
|
||||
PendingRequest[] pending;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_closed) return;
|
||||
_closed = true;
|
||||
pending = SnapshotPending();
|
||||
_outstanding.Clear();
|
||||
_sendQueue.Clear();
|
||||
}
|
||||
|
||||
_server.OnConnectionClosed(this);
|
||||
foreach (var item in pending)
|
||||
{
|
||||
item.TryCancel();
|
||||
_server.DecrementPending();
|
||||
}
|
||||
_cancellation.Cancel();
|
||||
}
|
||||
|
||||
public async Task RunSendLoop(WebSocket ws, CancellationToken ct)
|
||||
{
|
||||
using var disconnected = ct.Register(NotifyDisconnected);
|
||||
try
|
||||
{
|
||||
while (!Cancellation.IsCancellationRequested && IsOpen)
|
||||
{
|
||||
await _sendSignal.WaitAsync(Cancellation).ConfigureAwait(false);
|
||||
SendItem item;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_closed || _closing) return;
|
||||
if (_sendQueue.Count == 0) continue;
|
||||
item = _sendQueue.Dequeue();
|
||||
_sending = true;
|
||||
}
|
||||
|
||||
var remaining = ApiLimits.RequestTimeoutMs - (_server.NowMs - item.EnqueuedMs);
|
||||
if (remaining <= 0)
|
||||
{
|
||||
AbortSend(ws);
|
||||
return;
|
||||
}
|
||||
|
||||
using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(Cancellation))
|
||||
{
|
||||
timeout.CancelAfter((int)remaining);
|
||||
var entered = false;
|
||||
try
|
||||
{
|
||||
await _sendGate.WaitAsync(timeout.Token).ConfigureAwait(false);
|
||||
entered = true;
|
||||
if (!IsOpen) return;
|
||||
await ws.SendAsync(new ArraySegment<byte>(item.Payload), WebSocketMessageType.Text, true,
|
||||
timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogWarning($"API send failed: {ex.Message}");
|
||||
AbortSend(ws);
|
||||
return;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (entered) _sendGate.Release();
|
||||
lock (_gate) _sending = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (item.Id != null)
|
||||
Release(item.Id);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogWarning($"API send loop failed: {ex.Message}");
|
||||
AbortSend(ws);
|
||||
}
|
||||
}
|
||||
|
||||
async Task DeliverAsync(PendingRequest pending)
|
||||
{
|
||||
try
|
||||
{
|
||||
var produced = await pending.Completion.ConfigureAwait(false);
|
||||
if (!IsOpen) return;
|
||||
byte[] payload;
|
||||
try
|
||||
{
|
||||
payload = ApiProtocol.SerializeEnvelope(pending.Id, produced.Result, produced.Error);
|
||||
}
|
||||
catch (ResponseTooLargeException)
|
||||
{
|
||||
payload = ApiProtocol.SerializeEnvelope(pending.Id, null,
|
||||
ApiErrors.LimitExceeded("Response exceeds maxResponseBytes."));
|
||||
}
|
||||
|
||||
EnqueueSend(new SendItem { Payload = payload, Id = pending.Id, EnqueuedMs = _server.NowMs });
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogError($"API response serialization failed: {ex}");
|
||||
Close(ApiLimits.CloseTryAgainLater);
|
||||
}
|
||||
}
|
||||
|
||||
void EnqueueSend(SendItem item)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_closed || _closing) return;
|
||||
if (_sendQueue.Count + (_sending ? 1 : 0) < ApiLimits.MaxPendingRequestsPerConnection)
|
||||
{
|
||||
_sendQueue.Enqueue(item);
|
||||
_sendSignal.Release();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Close(ApiLimits.CloseTryAgainLater);
|
||||
}
|
||||
|
||||
void AbortSend(WebSocket ws)
|
||||
{
|
||||
try { ws?.Abort(); }
|
||||
catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"API abort failed: {ex.Message}"); }
|
||||
NotifyDisconnected();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
NotifyDisconnected();
|
||||
_cancellation.Dispose();
|
||||
_sendSignal.Dispose();
|
||||
_sendGate.Dispose();
|
||||
}
|
||||
|
||||
PendingRequest[] SnapshotPending()
|
||||
{
|
||||
var pending = new PendingRequest[_outstanding.Count];
|
||||
if (_outstanding.Count > 0)
|
||||
_outstanding.Values.CopyTo(pending, 0);
|
||||
return pending;
|
||||
}
|
||||
|
||||
struct SendItem
|
||||
{
|
||||
public byte[] Payload;
|
||||
public string Id;
|
||||
public long EnqueuedMs;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class WebSocketApiServer
|
||||
{
|
||||
static readonly UTF8Encoding Utf8Throw = new UTF8Encoding(false, true);
|
||||
readonly IPAddress _address;
|
||||
readonly int _port;
|
||||
readonly string _modVersion;
|
||||
readonly Func<GameVersionSnapshot> _version;
|
||||
readonly Func<SessionSnapshot> _session;
|
||||
readonly MainThreadDispatcher _dispatcher;
|
||||
readonly object _gate = new object();
|
||||
readonly List<ApiConnection> _connections = new List<ApiConnection>();
|
||||
readonly System.Diagnostics.Stopwatch _clock = System.Diagnostics.Stopwatch.StartNew();
|
||||
readonly CancellationTokenSource _cts = new CancellationTokenSource();
|
||||
IWebHost _host;
|
||||
Task _startTask;
|
||||
Task _stopTask;
|
||||
int _pending;
|
||||
bool _alive;
|
||||
bool _stopped;
|
||||
|
||||
public WebSocketApiServer(
|
||||
IPAddress address,
|
||||
int port,
|
||||
string modVersion,
|
||||
Func<GameVersionSnapshot> version,
|
||||
Func<SessionSnapshot> session,
|
||||
MainThreadDispatcher dispatcher)
|
||||
{
|
||||
_address = address;
|
||||
_port = port;
|
||||
_modVersion = modVersion;
|
||||
_version = version;
|
||||
_session = session;
|
||||
_dispatcher = dispatcher;
|
||||
}
|
||||
|
||||
public long NowMs => _clock.ElapsedMilliseconds;
|
||||
|
||||
public void Start() => StartAsync().GetAwaiter().GetResult();
|
||||
|
||||
public Task StartAsync()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stopped) return Task.CompletedTask;
|
||||
return _startTask ?? (_startTask = Task.Run(StartHostAsync));
|
||||
}
|
||||
}
|
||||
|
||||
async Task StartHostAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
_cts.Token.ThrowIfCancellationRequested();
|
||||
await StartHostCoreAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_ = StopAsync();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
async Task StartHostCoreAsync()
|
||||
{
|
||||
var host = new WebHostBuilder()
|
||||
.UseSetting(WebHostDefaults.PreventHostingStartupKey, "true")
|
||||
.UseContentRoot(Path.GetDirectoryName(typeof(WebSocketApiServer).Assembly.Location) ?? ".")
|
||||
.ConfigureLogging(logging => logging.ClearProviders().AddProvider(new HostLogger()))
|
||||
.UseKestrel(options =>
|
||||
{
|
||||
options.Listen(_address, _port);
|
||||
options.AddServerHeader = false;
|
||||
options.Limits.MaxConcurrentConnections = ApiLimits.MaxConnections + 2;
|
||||
options.Limits.MaxConcurrentUpgradedConnections = ApiLimits.MaxConnections;
|
||||
options.Limits.MaxRequestHeadersTotalSize = 16 * 1024;
|
||||
options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(5);
|
||||
options.Limits.MaxRequestBodySize = 1024;
|
||||
})
|
||||
.UseSockets()
|
||||
.Configure(app =>
|
||||
{
|
||||
app.UseWebSockets(new WebSocketOptions { ReceiveBufferSize = 4096 });
|
||||
app.Run(HandleHttp);
|
||||
})
|
||||
.Build();
|
||||
lock (_gate)
|
||||
{
|
||||
_host = host;
|
||||
_alive = !_stopped;
|
||||
}
|
||||
|
||||
await host.StartAsync(_cts.Token).ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stopped) return;
|
||||
}
|
||||
var displayed = _address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6
|
||||
? "[" + _address + "]" : _address.ToString();
|
||||
LiveStreamAssist.Logger.LogInfo($"WebSocket API listening on ws://{displayed}:{_port}{ApiLimits.Path}");
|
||||
}
|
||||
|
||||
public void Stop() => _ = StopAsync();
|
||||
|
||||
public Task StopAsync()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stopTask != null) return _stopTask;
|
||||
_stopped = true;
|
||||
_alive = false;
|
||||
var conns = _connections.ToArray();
|
||||
var startup = _startTask;
|
||||
return _stopTask = Task.Run(async () =>
|
||||
{
|
||||
try { _cts.Cancel(); }
|
||||
catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"API cancel failed: {ex.Message}"); }
|
||||
foreach (var conn in conns)
|
||||
conn.Close(ApiLimits.CloseGoingAway);
|
||||
if (startup != null)
|
||||
{
|
||||
try { await startup.ConfigureAwait(false); }
|
||||
catch (Exception) { /* Startup failures are reported by the feature owner. */ }
|
||||
}
|
||||
IWebHost host;
|
||||
lock (_gate)
|
||||
{
|
||||
host = _host;
|
||||
_host = null;
|
||||
}
|
||||
DisposeHost(host);
|
||||
_cts.Dispose();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryIncrementPending()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_alive || _pending >= ApiLimits.MaxPendingRequests) return false;
|
||||
_pending++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void DecrementPending()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_pending > 0) _pending--;
|
||||
}
|
||||
}
|
||||
|
||||
public void OnConnectionClosed(ApiConnection connection)
|
||||
{
|
||||
lock (_gate)
|
||||
_connections.Remove(connection);
|
||||
}
|
||||
|
||||
async Task HandleHttp(HttpContext context)
|
||||
{
|
||||
bool alive;
|
||||
lock (_gate) alive = _alive;
|
||||
if (!alive)
|
||||
{
|
||||
context.Response.StatusCode = 503;
|
||||
return;
|
||||
}
|
||||
|
||||
var path = context.Request.Path.Value ?? "";
|
||||
if (!string.Equals(path, ApiLimits.Path, StringComparison.Ordinal))
|
||||
{
|
||||
context.Response.StatusCode = 404;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!context.WebSockets.IsWebSocketRequest)
|
||||
{
|
||||
context.Response.StatusCode = 400;
|
||||
return;
|
||||
}
|
||||
|
||||
ApiConnection conn;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_alive || _connections.Count >= ApiLimits.MaxConnections)
|
||||
{
|
||||
context.Response.StatusCode = 503;
|
||||
return;
|
||||
}
|
||||
|
||||
conn = new ApiConnection(this);
|
||||
_connections.Add(conn);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
WebSocket ws;
|
||||
using (_cts.Token.Register(context.Abort))
|
||||
ws = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
|
||||
conn.Attach(ws);
|
||||
await RunConnection(ws, conn, context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
conn.NotifyDisconnected();
|
||||
await conn.CloseCompletion.ConfigureAwait(false);
|
||||
conn.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
async Task RunConnection(WebSocket ws, ApiConnection conn, CancellationToken aborted)
|
||||
{
|
||||
using (ws)
|
||||
{
|
||||
var send = conn.RunSendLoop(ws, aborted);
|
||||
try
|
||||
{
|
||||
await ReceiveLoop(ws, conn).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
catch (WebSocketException ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogWarning($"API websocket error: {ex.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogWarning($"API connection failed: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
conn.NotifyDisconnected();
|
||||
try { ws.Abort(); }
|
||||
catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"API abort failed: {ex.Message}"); }
|
||||
try { await send.ConfigureAwait(false); }
|
||||
catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"API send join failed: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async Task ReceiveLoop(WebSocket ws, ApiConnection conn)
|
||||
{
|
||||
var buffer = new byte[4096];
|
||||
var payload = new byte[ApiLimits.MaxRequestBytes];
|
||||
var used = 0;
|
||||
long? messageDeadlineMs = null;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(conn.Cancellation);
|
||||
while ((ws.State == WebSocketState.Open || ws.State == WebSocketState.CloseSent) && !conn.Cancellation.IsCancellationRequested)
|
||||
{
|
||||
var remaining = messageDeadlineMs.HasValue && conn.IsOpen ? messageDeadlineMs.Value - NowMs : Timeout.Infinite;
|
||||
if (messageDeadlineMs.HasValue && conn.IsOpen && remaining <= 0)
|
||||
{
|
||||
await conn.CloseAsync(ApiLimits.CloseTryAgainLater).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
timeout.CancelAfter((int)remaining);
|
||||
WebSocketReceiveResult result;
|
||||
try
|
||||
{
|
||||
result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.MessageType == WebSocketMessageType.Close)
|
||||
{
|
||||
var status = result.CloseStatus.GetValueOrDefault(WebSocketCloseStatus.NormalClosure);
|
||||
if (status == WebSocketCloseStatus.Empty) status = WebSocketCloseStatus.NormalClosure;
|
||||
await conn.CloseAsync((int)status).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!conn.IsOpen) continue;
|
||||
if (result.MessageType == WebSocketMessageType.Binary)
|
||||
{
|
||||
await conn.CloseAsync(ApiLimits.CloseUnsupportedData).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (messageDeadlineMs.HasValue && NowMs >= messageDeadlineMs.Value)
|
||||
{
|
||||
await conn.CloseAsync(ApiLimits.CloseTryAgainLater).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (used > ApiLimits.MaxRequestBytes - result.Count)
|
||||
{
|
||||
await conn.CloseAsync(ApiLimits.CloseMessageTooBig).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
Buffer.BlockCopy(buffer, 0, payload, used, result.Count);
|
||||
used += result.Count;
|
||||
if (!result.EndOfMessage)
|
||||
{
|
||||
if (!messageDeadlineMs.HasValue) messageDeadlineMs = NowMs + ApiLimits.RequestTimeoutMs;
|
||||
continue;
|
||||
}
|
||||
timeout.CancelAfter(Timeout.Infinite);
|
||||
|
||||
string text;
|
||||
try
|
||||
{
|
||||
text = used == 0 ? "" : Utf8Throw.GetString(payload, 0, used);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
await conn.CloseAsync(ApiLimits.CloseInvalidPayload).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
used = 0;
|
||||
messageDeadlineMs = null;
|
||||
HandleMessage(conn, text);
|
||||
}
|
||||
}
|
||||
|
||||
void HandleMessage(ApiConnection conn, string message)
|
||||
{
|
||||
if (!conn.IsOpen) return;
|
||||
var parsed = ApiProtocol.TryParseMessage(message, out var request, out var parseError, out var id);
|
||||
if (!parsed && !(id is string))
|
||||
{
|
||||
conn.EnqueueError(id, parseError);
|
||||
return;
|
||||
}
|
||||
|
||||
var requestId = parsed ? request.Id : (string)id;
|
||||
var admittedMs = NowMs;
|
||||
var pending = conn.TryAdmit(requestId, out var duplicate, out var busy);
|
||||
if (pending == null)
|
||||
{
|
||||
if (duplicate)
|
||||
{
|
||||
conn.Close(ApiLimits.ClosePolicyViolation);
|
||||
return;
|
||||
}
|
||||
|
||||
if (busy)
|
||||
{
|
||||
if (conn.CanSendBusy())
|
||||
conn.EnqueueError(requestId, ApiErrors.ServerBusy());
|
||||
else
|
||||
conn.Close(ApiLimits.CloseTryAgainLater);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!parsed)
|
||||
{
|
||||
pending.TryComplete(parseError);
|
||||
return;
|
||||
}
|
||||
if (!ApiProtocol.IsSystemMethod(request.Method) && !ApiProtocol.IsDataMethod(request.Method))
|
||||
{
|
||||
pending.TryComplete(ApiErrors.MethodNotFound());
|
||||
return;
|
||||
}
|
||||
|
||||
if (ApiProtocol.IsSystemMethod(request.Method))
|
||||
{
|
||||
var handled = ApiProtocol.HandleSystem(request.Method, request.Params, _version(), _modVersion);
|
||||
if (handled is ApiError sysErr)
|
||||
pending.TryComplete(sysErr);
|
||||
else
|
||||
pending.TryCompleteResult(handled);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ApiProtocol.TryParseDataCall(request, out var call, out var callErr))
|
||||
{
|
||||
pending.TryComplete(callErr);
|
||||
return;
|
||||
}
|
||||
|
||||
if (call.Method != DataMethod.Roots && !WebSocketApiFeature.IsKnownRoot(call.Root))
|
||||
{
|
||||
pending.TryComplete(ApiErrors.RootNotFound(call.Root));
|
||||
return;
|
||||
}
|
||||
|
||||
var session = _session();
|
||||
var work = new GameWork
|
||||
{
|
||||
Pending = pending,
|
||||
Call = call,
|
||||
Generation = session.Generation,
|
||||
DeadlineMs = admittedMs + ApiLimits.RequestTimeoutMs
|
||||
};
|
||||
if (!_dispatcher.TryEnqueue(work))
|
||||
pending.TryComplete(ApiErrors.ServerBusy());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogError($"API request handling failed: {ex}");
|
||||
pending.TryComplete(ApiErrors.InternalError());
|
||||
}
|
||||
}
|
||||
|
||||
static void DisposeHost(IWebHost host)
|
||||
{
|
||||
if (host == null) return;
|
||||
try
|
||||
{
|
||||
host.StopAsync(TimeSpan.FromMilliseconds(ApiLimits.RequestTimeoutMs)).GetAwaiter().GetResult();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogWarning($"WebSocket API host stop failed: {ex.Message}");
|
||||
}
|
||||
|
||||
try { host.Dispose(); }
|
||||
catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"WebSocket API host dispose failed: {ex.Message}"); }
|
||||
}
|
||||
|
||||
sealed class HostLogger : ILoggerProvider, ILogger
|
||||
{
|
||||
public ILogger CreateLogger(string categoryName) => this;
|
||||
public IDisposable BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
public bool IsEnabled(LogLevel level) => level >= LogLevel.Warning && level != LogLevel.None;
|
||||
public void Dispose() { }
|
||||
|
||||
public void Log<TState>(LogLevel level, EventId eventId, TState state, Exception exception,
|
||||
Func<TState, Exception, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(level)) return;
|
||||
var message = "WebSocket host: " + formatter(state, exception);
|
||||
if (exception != null) message += "\n" + exception;
|
||||
if (level >= LogLevel.Error) LiveStreamAssist.Logger.LogError(message);
|
||||
else LiveStreamAssist.Logger.LogWarning(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Reflection;
|
||||
using BepInEx;
|
||||
using CommonAPI.Systems;
|
||||
using LiveStreamAssist.Api;
|
||||
using UnityEngine;
|
||||
using UXAssist.Common;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using GameLogicProc = UXAssist.Common.GameLogic;
|
||||
|
||||
namespace LiveStreamAssist;
|
||||
|
||||
[BepInPlugin(PluginInfo.PLUGIN_GUID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)]
|
||||
[BepInDependency(UXAssist.PluginInfo.PLUGIN_GUID)]
|
||||
public class LiveStreamAssist : BaseUnityPlugin
|
||||
{
|
||||
public new static readonly BepInEx.Logging.ManualLogSource Logger =
|
||||
BepInEx.Logging.Logger.CreateLogSource(PluginInfo.PLUGIN_NAME);
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
I18N.Init();
|
||||
I18N.Add("KEYToggleLiveStreamAssist", "[LSA] Toggle live-stream statistics assist", "[LSA] \u5207\u6362\u76f4\u64ad\u7edf\u8ba1\u8f85\u52a9");
|
||||
WebSocketApiFeature.BindConfig(Config);
|
||||
ModFeatureRegistry.Discover(Assembly.GetExecutingAssembly());
|
||||
I18N.Apply();
|
||||
}
|
||||
}
|
||||
|
||||
[ModFeature("LiveStreamAssist", Order = 50)]
|
||||
internal static class LiveStreamAssistFeature
|
||||
{
|
||||
private const float MinIntervalSeconds = 15f;
|
||||
private const float MaxIntervalSeconds = 30f;
|
||||
private static PressKeyBind _toggleKey;
|
||||
private static bool _enabled;
|
||||
private static float _nextSwitchAt;
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
_toggleKey = KeyBindings.RegisterKeyBinding(new BuiltinKey
|
||||
{
|
||||
key = new CombineKey((int)KeyCode.F8, CombineKey.CTRL_COMB, ECombineKeyAction.OnceClick, false),
|
||||
conflictGroup = KeyBindConflict.MOVEMENT | KeyBindConflict.FLYING | KeyBindConflict.SAILING |
|
||||
KeyBindConflict.BUILD_MODE_1 | KeyBindConflict.UI | KeyBindConflict.KEYBOARD_KEYBIND,
|
||||
name = "ToggleLiveStreamAssist",
|
||||
canOverride = true
|
||||
});
|
||||
}
|
||||
|
||||
public static void Start()
|
||||
{
|
||||
GameLogicProc.OnGameEnd += Stop;
|
||||
}
|
||||
|
||||
public static void Uninit()
|
||||
{
|
||||
GameLogicProc.OnGameEnd -= Stop;
|
||||
Stop();
|
||||
}
|
||||
|
||||
public static void OnInputUpdate()
|
||||
{
|
||||
if (!_toggleKey.keyValue) return;
|
||||
|
||||
if (_enabled)
|
||||
{
|
||||
Stop();
|
||||
return;
|
||||
}
|
||||
|
||||
TryStart();
|
||||
}
|
||||
|
||||
public static void OnUpdate()
|
||||
{
|
||||
if (!_enabled) return;
|
||||
|
||||
var statWindow = GetStatWindow();
|
||||
if (statWindow == null || !statWindow.active)
|
||||
{
|
||||
Stop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (Time.unscaledTime < _nextSwitchAt) return;
|
||||
|
||||
var nextTab = statWindow.tabIndex == 1 ? 4 : 1;
|
||||
statWindow.OnTabButtonClick(nextTab);
|
||||
ScheduleNextSwitch();
|
||||
}
|
||||
|
||||
private static void TryStart()
|
||||
{
|
||||
var statWindow = GetStatWindow();
|
||||
if (statWindow == null || !GameMain.isRunning) return;
|
||||
|
||||
UIRoot.instance.uiGame.OpenProductionWindow();
|
||||
statWindow = GetStatWindow();
|
||||
if (statWindow == null || !statWindow.active) return;
|
||||
|
||||
statWindow.OnTabButtonClick(1);
|
||||
_enabled = true;
|
||||
ScheduleNextSwitch();
|
||||
}
|
||||
|
||||
private static UIStatisticsWindow GetStatWindow()
|
||||
{
|
||||
if (UIRoot.instance == null || UIRoot.instance.uiGame == null) return null;
|
||||
return UIRoot.instance.uiGame.statWindow;
|
||||
}
|
||||
|
||||
private static void ScheduleNextSwitch()
|
||||
{
|
||||
_nextSwitchAt = Time.unscaledTime + Random.Range(MinIntervalSeconds, MaxIntervalSeconds);
|
||||
}
|
||||
|
||||
private static void Stop()
|
||||
{
|
||||
_enabled = false;
|
||||
_nextSwitchAt = 0f;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<BepInExPluginGuid>org.soardev.livestreamassist</BepInExPluginGuid>
|
||||
<Description>DSP MOD - LiveStreamAssist</Description>
|
||||
<Version>1.0.0</Version>
|
||||
<PackageId>LiveStreamAssist</PackageId>
|
||||
<RootNamespace>LiveStreamAssist</RootNamespace>
|
||||
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\UXAssist\UXAssist.csproj" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.3.13" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.13" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.3.13" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Core" Version="2.3.13" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets" Version="2.3.13" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.3.13" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="System.Net.WebSockets.WebSocketProtocol" Version="5.1.3" />
|
||||
<Compile Remove="tools\**" />
|
||||
<None Include="tools\**" Exclude="tools\**\bin\**;tools\**\obj\**" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Connections.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Hosting.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Hosting.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Hosting.Server.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Http.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Http.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Http.Extensions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Http.Features.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Server.Kestrel.Core.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Server.Kestrel.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Server.Kestrel.Https.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.WebSockets.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.AspNetCore.WebUtilities.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Bcl.AsyncInterfaces.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Configuration.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Configuration.Binder.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Configuration.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Configuration.EnvironmentVariables.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Configuration.FileExtensions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.DependencyInjection.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.DependencyInjection.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Diagnostics.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.FileProviders.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.FileProviders.Physical.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.FileSystemGlobbing.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Hosting.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Logging.Abstractions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Logging.Debug.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Logging.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.ObjectPool.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Options.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Extensions.Primitives.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Microsoft.Net.Http.Headers.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)Newtonsoft.Json.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Buffers.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Collections.Immutable.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Diagnostics.DiagnosticSource.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.IO.Pipelines.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Memory.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Net.WebSockets.WebSocketProtocol.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Numerics.Vectors.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Reflection.Metadata.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Runtime.CompilerServices.Unsafe.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Security.Cryptography.Cng.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Text.Encodings.Web.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.Threading.Tasks.Extensions.dll" />
|
||||
<WebSocketRuntimeDll Include="$(TargetDir)System.ValueTuple.dll" />
|
||||
</ItemGroup>
|
||||
<Target Name="AddWebSocketRuntimeDependencies" BeforeTargets="ZipMod">
|
||||
<Error Condition="'%(WebSocketRuntimeDll.Identity)' != '' And !Exists('%(WebSocketRuntimeDll.Identity)')"
|
||||
Text="Missing WebSocket runtime dependency: %(WebSocketRuntimeDll.Identity)" />
|
||||
<ItemGroup>
|
||||
<_PackRootFiles Include="@(WebSocketRuntimeDll)" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -0,0 +1,4 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("ReflectionReaderCheck")]
|
||||
[assembly: InternalsVisibleTo("WebSocketTransportCheck")]
|
||||
@@ -0,0 +1,38 @@
|
||||
# LiveStreamAssist
|
||||
|
||||
Keeps the Dyson Sphere Program statistics window active during a live stream by switching between the Production Statistics and Dyson Sphere tabs at a random interval. Optionally exposes a local/LAN WebSocket API for read-only game data.
|
||||
|
||||
## Usage
|
||||
|
||||
- Press Ctrl+F8 to start or stop the assist. The key can be changed in the game's keyboard settings.
|
||||
- Starting the assist opens the statistics window and selects Production Statistics.
|
||||
- The mod switches between Production Statistics and Dyson Sphere every 15 to 30 seconds.
|
||||
- Closing the statistics window stops the assist automatically.
|
||||
|
||||
The mod requires UXAssist.
|
||||
|
||||
## WebSocket API
|
||||
|
||||
The in-tree listener uses in-process ASP.NET Core 2.3 Kestrel (managed sockets). Unity 2022/Mono and LAN acceptance remain pending. The design document below defines the remaining gates.
|
||||
|
||||
Disabled by default. In the BepInEx config file, set:
|
||||
|
||||
```text
|
||||
[WebSocketApi]
|
||||
Enabled = true
|
||||
ListenAddress = 127.0.0.1
|
||||
Port = 18080
|
||||
```
|
||||
|
||||
Then connect to `ws://<host>:18080/api/v1`. There is no authentication. Use a LAN bind address or `0.0.0.0` only on trusted networks. Configuration changes require a game restart.
|
||||
|
||||
Open the overlay examples in a browser or OBS Browser Source. Default URL is `ws://127.0.0.1:18080/api/v1`; override with `?ws=`.
|
||||
|
||||
- [examples/research-overlay.html](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/examples/research-overlay.html) shows the current research name, level, and hash progress.
|
||||
- [examples/stats-overlay.html](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/examples/stats-overlay.html) also shows item production/consumption per minute and Dyson sphere generation.
|
||||
- [examples/live-dashboard.html](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/examples/live-dashboard.html) is a Chinese live-stream panel driven by URL parameters: selected item rates in a game-style table, tech levels, current research, and Dyson sphere generation.
|
||||
|
||||
The overlays use the [JS client](js/README.md): `Client` for JSON-RPC, `GameQuery` for those reads, and `GameText`/`GameIcons` for offline localized names, DSP KMG formatting, and extracted game icons. Keep the `examples/` and `js/` directories side by side when copying an overlay. The offline data never calls the WebSocket API; regenerate `js/generated/dsp-text.js` and `js/generated/dsp-icons.js` from the repository root with `python LiveStreamAssist/js/scripts/generate_text.py` and `python LiveStreamAssist/js/scripts/generate_icons.py`.
|
||||
|
||||
- [WebSocket API reference](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketApi.md)
|
||||
- [WebSocket design and transport migration plan](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketDesign.md)
|
||||
@@ -0,0 +1,512 @@
|
||||
# LiveStreamAssist WebSocket API
|
||||
|
||||
Status: API `1.0.0` compatibility contract. The in-tree transport is in-process ASP.NET Core 2.3 Kestrel; Unity/LAN acceptance is still pending. Enable the listener with BepInEx setting `WebSocketApi.Enabled`; see the [design and transport migration plan](WebSocketDesign.md).
|
||||
|
||||
Audience: developers of live-stream overlays, OBS integrations, and other clients. Server architecture and implementation tasks are documented separately in the [design and transport migration plan](WebSocketDesign.md).
|
||||
|
||||
## Connection
|
||||
|
||||
```text
|
||||
ws://<host>:18080/api/v1
|
||||
```
|
||||
|
||||
The service supports local and LAN clients without authentication. No token, login request, or application-level handshake is required. The client sends requests after the WebSocket connection opens. Other URL paths are rejected and must not execute API requests.
|
||||
|
||||
The BepInEx configuration section is `WebSocketApi`:
|
||||
|
||||
| Setting | Type | Default | Meaning |
|
||||
| --- | --- | --- | --- |
|
||||
| `Enabled` | Boolean | `false` | Start the listener when the mod starts. |
|
||||
| `ListenAddress` | IP address string | `127.0.0.1` | Bind address; use a specific LAN address or `0.0.0.0` for LAN access. |
|
||||
| `Port` | Integer, 1 through 65535 | `18080` | Listening port. |
|
||||
|
||||
Configuration changes require a game restart in v1. The server remains available when leaving a save. Reflection reads require an active player game; menu-demo data is not exposed as a player game.
|
||||
|
||||
Suggested client sequence:
|
||||
|
||||
1. Call `system.info` to read versions, capabilities, and limits.
|
||||
2. Optionally call `system.validate` to check the client's requirements.
|
||||
3. Call `data.roots`, then use `data.describe` to discover readable members.
|
||||
4. Call `data.read` and schedule any subsequent polling in the client.
|
||||
|
||||
There are no subscriptions or unsolicited application messages. Normal WebSocket control frames, including ping/pong and close frames, are transport operations rather than application notifications.
|
||||
|
||||
## WebSocket interoperability
|
||||
|
||||
The required transport profile is [RFC 6455](https://www.rfc-editor.org/rfc/rfc6455) over HTTP/1.1 Upgrade, using WebSocket version `13`. It is intended to interoperate with current browsers, OBS browser sources, and standard WebSocket clients. The migration does not change the JSON-RPC contract or require a new client SDK.
|
||||
|
||||
- Client frames must be masked; server frames must not be masked. Invalid framing, reserved opcodes, and unnegotiated RSV bits are protocol errors (`1002`).
|
||||
- Fragmentation must preserve message boundaries and UTF-8 decoder state. Interleaved control frames do not restart or relax the complete-message byte limit.
|
||||
- Ping/pong and close handshakes follow RFC 6455. A pong responding to a ping carries the same payload. Invalid text or close-reason UTF-8 produces `1007`.
|
||||
- `permessage-deflate` and other extensions are not negotiated in v1. An extension offer can be declined while accepting an ordinary uncompressed WebSocket connection. HTTP/2 and HTTP/3 WebSocket transports are not advertised by this profile.
|
||||
- Invalid paths, invalid opening handshakes, and connection-capacity rejection may be rejected at the HTTP layer before upgrade. A client must not assume every unsuccessful connection produces a WebSocket close frame.
|
||||
|
||||
These are acceptance requirements for the transport. Passing desktop checks does not imply full conformance or Unity/LAN acceptance; see the linked implementation status.
|
||||
|
||||
## Message format
|
||||
|
||||
The API uses a restricted JSON-RPC 2.0 request/response format. It does not implement the full JSON-RPC feature set: batches and notification requests are deliberately rejected.
|
||||
|
||||
Each complete WebSocket text message contains one UTF-8 JSON object. Fragmentation is supported at the WebSocket transport layer; an individual frame is not necessarily a complete JSON message.
|
||||
|
||||
### Request
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "request-1",
|
||||
"method": "system.ping",
|
||||
"params": {}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Required | Rules |
|
||||
| --- | --- | --- |
|
||||
| `jsonrpc` | Yes | Exactly `"2.0"`. |
|
||||
| `id` | Yes | Nonempty string, at most 64 UTF-16 code units. Unique among outstanding requests on this connection. |
|
||||
| `method` | Yes | Case-sensitive method name from this reference. |
|
||||
| `params` | No | An object; omission is equivalent to `{}`. Positional parameter arrays are unsupported. |
|
||||
|
||||
Identifiers, root names, member names, and capability names use ordinal, case-sensitive comparison. Unknown method parameters are rejected rather than silently ignored. Duplicate JSON object property names are rejected with `PARSE_ERROR` and `id: null`. Clients must ignore additional response fields introduced by compatible API extensions.
|
||||
|
||||
Missing, null, numeric, or otherwise invalid IDs produce an invalid-request response with `id: null`. A message without an ID is not treated as a notification. A batch array produces one invalid-request response with `id: null`.
|
||||
|
||||
Reusing an outstanding ID closes the connection with code `1008` and cancels its outstanding requests, avoiding ambiguous responses. An ID may be reused after its previous response has completed, although monotonically increasing client IDs are simpler.
|
||||
|
||||
### Response
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "request-1",
|
||||
"result": {
|
||||
"serverTimeUtc": "2026-09-17T12:00:00.0000000Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A response contains exactly one of `result` or `error`. Responses may arrive out of request order; correlate them by `id`. An accepted request completes at most once. Disconnection or server shutdown can prevent delivery; the server does not replay requests after reconnection.
|
||||
|
||||
All timestamps and game values in examples are illustrative.
|
||||
|
||||
## Versions and capabilities
|
||||
|
||||
The following versions have different meanings:
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `jsonrpc` | Envelope format version, always `"2.0"`. |
|
||||
| `apiVersion` | API semantic version, initially `"1.0.0"`. The URL selects its major version. |
|
||||
| `modVersion` | Installed LiveStreamAssist plugin version. |
|
||||
| `gameVersion` | Running DSP version string, without the separate build number. |
|
||||
| `gameBuild` | Running DSP build number, as an integer. |
|
||||
|
||||
Breaking API changes require a new API major version. Compatible additions use a minor version; compatible fixes use a patch version. Raw game member names and types can change when DSP changes even if the API version does not. Discover members for the running game rather than assuming API compatibility also guarantees a particular reflection path.
|
||||
|
||||
The first release advertises these capability keys:
|
||||
|
||||
| Capability | Value | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `reflection.read` | `true` | `data.read` is implemented. |
|
||||
| `reflection.describe` | `true` | Root and member discovery are implemented. |
|
||||
| `api.stats` | `false` | API statistics are reserved but not collected or returned. |
|
||||
| `subscriptions` | `false` | Subscription and notification delivery are unsupported. |
|
||||
|
||||
Unknown capabilities are unavailable. A development build must not advertise a capability before it actually implements it.
|
||||
|
||||
## Limits
|
||||
|
||||
These are the initial v1 defaults. `system.info.limits` is the authoritative source for the connected server. Byte limits count UTF-8 payload bytes, excluding WebSocket framing. A KiB is 1024 bytes.
|
||||
|
||||
| `limits` field | Value | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `maxConnections` | 8 | Simultaneous connections. |
|
||||
| `maxPendingRequestsPerConnection` | 8 | Outstanding accepted requests on one connection. |
|
||||
| `maxPendingRequests` | 64 | Outstanding accepted requests across the server. |
|
||||
| `maxRequestBytes` | 65536 | Complete incoming message, including all fragments. |
|
||||
| `maxResponseBytes` | 262144 | Complete outgoing JSON response. |
|
||||
| `maxJsonDepth` | 32 | Maximum nesting of objects and arrays in a request. |
|
||||
| `maxIdLength` | 64 | Request ID length in UTF-16 code units. |
|
||||
| `maxPathSegments` | 16 | Segments in a reflection path. |
|
||||
| `maxSelectMembers` | 32 | Members in an explicit projection. |
|
||||
| `defaultPageSize` | 64 | Array/list page size when `limit` is omitted. |
|
||||
| `maxPageSize` | 128 | Maximum requested array/list page size. |
|
||||
| `requestTimeoutMs` | 5000 | Deadline for producing a response, measured from request admission. |
|
||||
| `maxRequestsPerFrame` | 8 | Maximum game-data requests started in one Unity frame. |
|
||||
| `mainThreadBudgetMs` | 2 | Soft main-thread scheduling budget per Unity frame. |
|
||||
|
||||
Outstanding requests include queued reads, executing reads, and responses waiting to be sent, including an active send. System methods also consume outstanding-request capacity, but do not consume the game-data execution budget. A saturated server returns `SERVER_BUSY` when it can deliver an error within the bounded send queue; otherwise it attempts to close the connection with `1013`. A stalled or broken transport is aborted if a close frame cannot be delivered within the send deadline.
|
||||
|
||||
The main-thread budget does not preempt a running read. Deadlines are independent of game ticks and pause state. A timed-out request cannot later produce a success response. If a response cannot be delivered to a stalled client within the bounded send deadline, the connection closes instead of retaining output indefinitely.
|
||||
|
||||
An oversized incoming message closes the connection with `1009`. A result that would exceed the response limit returns `LIMIT_EXCEEDED`; it is not silently truncated.
|
||||
|
||||
## Methods
|
||||
|
||||
### `system.ping`
|
||||
|
||||
Parameters: none.
|
||||
|
||||
Result: `{ "serverTimeUtc": "<UTC timestamp>" }`.
|
||||
|
||||
Tests application-level connectivity. It does not read game objects or wait for a game frame, so it can succeed while a game-data request times out during loading. UTC timestamps use ISO 8601 round-trip formatting with a `Z` suffix.
|
||||
|
||||
### `system.info`
|
||||
|
||||
Parameters: none.
|
||||
|
||||
Returns versions, capabilities, and the limits listed above. It is available without an open save.
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "info-1",
|
||||
"result": {
|
||||
"apiVersion": "1.0.0",
|
||||
"modVersion": "1.0.0",
|
||||
"gameVersionReady": false,
|
||||
"gameVersion": null,
|
||||
"gameBuild": null,
|
||||
"capabilities": {
|
||||
"reflection.read": true,
|
||||
"reflection.describe": true,
|
||||
"api.stats": false,
|
||||
"subscriptions": false
|
||||
},
|
||||
"limits": {
|
||||
"maxConnections": 8,
|
||||
"maxPendingRequestsPerConnection": 8,
|
||||
"maxPendingRequests": 64,
|
||||
"maxRequestBytes": 65536,
|
||||
"maxResponseBytes": 262144,
|
||||
"maxJsonDepth": 32,
|
||||
"maxIdLength": 64,
|
||||
"maxPathSegments": 16,
|
||||
"maxSelectMembers": 32,
|
||||
"defaultPageSize": 64,
|
||||
"maxPageSize": 128,
|
||||
"requestTimeoutMs": 5000,
|
||||
"maxRequestsPerFrame": 8,
|
||||
"mainThreadBudgetMs": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Before game initialization supplies version information, `gameVersionReady` is `false` and both game version fields are `null`. Once ready, `gameVersionReady` is `true`, `gameVersion` is a string, and `gameBuild` is an integer. Leaving a save does not clear this process-level version information.
|
||||
|
||||
### `system.validate`
|
||||
|
||||
| Parameter | Required | Default | Rules |
|
||||
| --- | --- | --- | --- |
|
||||
| `apiMajor` | Yes | None | Positive 32-bit integer. |
|
||||
| `requiredCapabilities` | No | `[]` | At most 32 distinct, nonempty capability-name strings. |
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "validate-1",
|
||||
"method": "system.validate",
|
||||
"params": {
|
||||
"apiMajor": 1,
|
||||
"requiredCapabilities": ["reflection.read", "api.stats"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "validate-1",
|
||||
"result": {
|
||||
"compatible": false,
|
||||
"apiVersion": "1.0.0",
|
||||
"apiMajorCompatible": true,
|
||||
"missingCapabilities": ["api.stats"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`compatible` is true only when the requested API major matches and every required capability is true. `missingCapabilities` preserves request order and includes unknown capability names. A major mismatch or unavailable capability is a successful validation result with `compatible: false`, not a protocol error.
|
||||
|
||||
This is not authentication, game-version certification, or reflection-path validation. Calling it does not negotiate connection state or gate later requests.
|
||||
|
||||
### `system.stats`
|
||||
|
||||
Parameters: none.
|
||||
|
||||
The v1 result is exactly:
|
||||
|
||||
```json
|
||||
{
|
||||
"available": false,
|
||||
"metrics": null
|
||||
}
|
||||
```
|
||||
|
||||
The method exists as a placeholder even though `api.stats` is false. It must not return fabricated zero counters. Future metrics will be specified separately before this capability becomes true.
|
||||
|
||||
### `data.roots`
|
||||
|
||||
Parameters: none.
|
||||
|
||||
Returns `gameReady`, `sessionId`, `gameTick`, and a `roots` array. Each root entry has `name`, `type`, and `available` fields. All root names are always listed.
|
||||
|
||||
| Root | Declared type | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `game` | `GameData` | Active player-game data. |
|
||||
| `player` | `Player` | Main player. |
|
||||
| `history` | `GameHistoryData` | Research and progression data. |
|
||||
| `statistics` | `GameStatData` | In-game statistics data, unrelated to `system.stats`. |
|
||||
| `galaxy` | `GalaxyData` | Current galaxy. |
|
||||
| `localPlanet` | `PlanetData` | Current local planet, if present. |
|
||||
| `localStar` | `StarData` | Current local star, if present. |
|
||||
|
||||
Without an active player game, `gameReady` is false, `sessionId` and `gameTick` are null, and every root is unavailable. A paused player game is ready. A local planet or star can be unavailable during space travel even while `gameReady` is true.
|
||||
|
||||
`sessionId` is an opaque identifier for one loaded/new game session. It changes when a different session starts, including reloading the same save. `gameTick` is a decimal string. Discovery requires a main-thread turn and can time out if the game loop is blocked.
|
||||
|
||||
### Reflection paths
|
||||
|
||||
`data.describe` and `data.read` share these parameters:
|
||||
|
||||
| Parameter | Required | Default | Rules |
|
||||
| --- | --- | --- | --- |
|
||||
| `root` | Yes | None | One registered root name. Arbitrary CLR type names are not roots. |
|
||||
| `path` | No | `[]` | At most 16 path segments; an empty path addresses the root itself. |
|
||||
|
||||
| Segment | Meaning | Example |
|
||||
| --- | --- | --- |
|
||||
| Nonempty string | Exact instance field or permitted property name. | `"currentTech"` |
|
||||
| Nonnegative 32-bit integer | Zero-based array/list index. | `0` |
|
||||
| Object containing only `key` | Exact dictionary-key lookup. | `{"key": 1001}` |
|
||||
|
||||
Strings are literal member names, not expressions: `"history.currentTech"` is not split at the dot. Wildcards, method calls, filters, arithmetic, and arbitrary indexer invocation are unsupported.
|
||||
|
||||
V1 supports one-dimensional zero-based arrays, concrete BCL `List<T>`, and concrete BCL `Dictionary<TKey, TValue>` with `Int32` or string keys. String keys are not converted to integers. Other collection implementations and arbitrary `IEnumerable` enumeration are unsupported.
|
||||
|
||||
Fields can be public or non-public instance fields on permitted game-data types. Static fields, compiler-generated backing fields, methods, setters, and indexer properties are not exposed. Property reads require an explicit server allowlist. The property allowlist contains `GameHistoryData.currentTech` and `GameDesc.clusterString`; other getters are not automatically allowed merely because they are public or have no setter.
|
||||
|
||||
Use `data.describe` to discover the permitted surface. If inheritance hides a name, the most-derived declaration wins. Field/property traversal through runtime infrastructure such as Unity native objects, delegates, reflection objects, streams, or synchronization objects is unsupported.
|
||||
|
||||
Reflected values use DSP's native units and member names. The API does not localize member names, convert values to UI display units, or calculate aggregate gameplay statistics.
|
||||
|
||||
Successful reads beneath `statistics.production.factoryStatPool[index]` (also reachable through `game.statistics`) request a refresh of that factory's native production extra info. The game calculates these derived caches in its normal chart ticks; no statistics window needs to be open. Requests are deduplicated and throttled to once per factory every two seconds, and work requested during an active batch is queued on a later production read after the batch finishes. Reads still return the current cached values: `refProductSpeed` and `refConsumeSpeed` can initially be zero or remain stale until that factory is processed. Descriptions do not request a refresh.
|
||||
|
||||
### `data.describe`
|
||||
|
||||
Parameters: `root` and optional `path` only.
|
||||
|
||||
Returns metadata for the addressed value:
|
||||
|
||||
| Result field | Meaning |
|
||||
| --- | --- |
|
||||
| `type` | Diagnostic CLR type name; runtime type when non-null, declared type when null. |
|
||||
| `isNull` | Whether the addressed value is null. |
|
||||
| `members` | Permitted members, sorted by ordinal name. Each has `name`, `type`, and `kind` (`field` or `property`). |
|
||||
| `collection` | Null for non-collections; otherwise `kind` (`array`, `list`, or `dictionary`), `elementType`, `keyType`, and `count`. |
|
||||
| `sessionId` | Session that supplied the metadata. |
|
||||
| `gameTick` | Sampling tick as a decimal string. |
|
||||
|
||||
For arrays/lists, `keyType` is null. For a null collection, `count` is null. Scalars and supported BCL containers have an empty `members` array; their framework internals are not exposed. A null terminal value can still be described using its declared type.
|
||||
|
||||
Resolving the explicit path can read permitted getters. Listing the target's members does not evaluate those members, their getters, or collection elements. Denied members are omitted. Type names are diagnostic metadata, not instructions to load CLR types in a client.
|
||||
|
||||
This method requires an active game and an available root. Passing through null before the final segment fails with `NULL_PATH`.
|
||||
|
||||
### `data.read`
|
||||
|
||||
Additional parameters:
|
||||
|
||||
| Parameter | Required | Default | Rules |
|
||||
| --- | --- | --- | --- |
|
||||
| `select` | No | Omitted | 1 through 32 distinct, nonempty immediate member names for an object projection or for each object in an array/list page. No nested selection syntax. |
|
||||
| `offset` | No | `0` | Nonnegative 32-bit integer; valid only when the terminal value is an array/list. |
|
||||
| `limit` | No | `64` | Integer from 1 through 128; valid only when the terminal value is an array/list. |
|
||||
|
||||
The result always contains `type`, `value`, `sessionId`, and `gameTick`. `type` follows the same rule as in `data.describe`. A read or projection fails as a whole if any requested member cannot be read; v1 has no partial-success envelope.
|
||||
|
||||
Terminal-value behavior:
|
||||
|
||||
| Terminal value | `value` representation |
|
||||
| --- | --- |
|
||||
| Null | JSON null; no further member/element reads occur. |
|
||||
| Scalar | Encoded scalar, as specified below. |
|
||||
| Object without `select` | A shallow object summary. |
|
||||
| Object with `select` | An object containing exactly the selected members. |
|
||||
| Array/list | A page object containing `items`, `offset`, `totalCount`, and `hasMore`. |
|
||||
| Supported dictionary | A shallow dictionary summary; read individual entries using a key path segment. |
|
||||
|
||||
`select` is invalid for non-null scalar and dictionary terminals. In a collection page it applies to each non-null object element; requesting it for scalar elements is invalid. Null elements remain null. `offset` or `limit` on a non-collection is invalid, including null values whose declared type is not an array/list. Parameters are validated even when the selected page is empty; member availability is checked on objects actually read.
|
||||
|
||||
Pages return up to `limit` items. `offset` at or beyond the current count returns an empty page, preserving the requested offset, with `hasMore: false`. A single-element path index at or beyond the count is instead `INDEX_OUT_OF_RANGE`. `totalCount` means the underlying container count, not the number of live entities in a DSP pool. No filtering, compaction, sorting, or zero-ID skipping is implied. Pages from different requests need not describe an unchanged collection.
|
||||
|
||||
Complex values inside a projection or page remain summaries unless they are the direct objects selected by the request. The server never recursively expands an entire object graph. Summary shapes are:
|
||||
|
||||
```json
|
||||
{
|
||||
"$kind": "object",
|
||||
"$type": "GameData"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"$kind": "array",
|
||||
"$type": "System.Int32[]",
|
||||
"count": 8
|
||||
}
|
||||
```
|
||||
|
||||
Collection summaries use `$kind` values `array`, `list`, or `dictionary` and include `count`. The dollar-prefixed keys belong to the wire representation, not to the reflected object's members. To expand a summarized value, issue another request whose path addresses that value.
|
||||
|
||||
Scalar encoding:
|
||||
|
||||
| CLR value | JSON encoding |
|
||||
| --- | --- |
|
||||
| Boolean, string | Boolean or string. |
|
||||
| Character | One-character string. |
|
||||
| Signed/unsigned integers up to 32 bits | Number. |
|
||||
| `Int64`, `UInt64` | Invariant decimal string, even when the value would fit JavaScript's safe-integer range. |
|
||||
| Finite `Single`, `Double` | Number. |
|
||||
| `Decimal` | Invariant decimal string. |
|
||||
| Enum | Object with `name` (declared name or null) and `value` (underlying integer as a decimal string). |
|
||||
| `DateTime`, `DateTimeOffset` | ISO 8601 round-trip string; preserve the source time-zone/Kind information. An unspecified `DateTime` has no implied UTC suffix. |
|
||||
| `Guid` | Standard hyphenated string. |
|
||||
|
||||
Non-finite floating-point values fail with `UNSUPPORTED_VALUE`. Unsupported runtime types fail with `UNSUPPORTED_TYPE`; the server does not serialize their internals or call arbitrary `ToString()` implementations. Plain game-data structs, including position structs defined by DSP, follow the object/projection rules. Unity `Vector2`, `Vector3`, `Vector4`, and `Quaternion` support their instance fields through the same rules; Unity objects such as components and textures do not.
|
||||
|
||||
#### Research read example
|
||||
|
||||
First read `history` at `["currentTech"]`; a value of zero means there is no current research. Use a nonzero returned ID as the dictionary key, rather than assuming the illustrative ID below is active:
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "research-1",
|
||||
"method": "data.read",
|
||||
"params": {
|
||||
"root": "history",
|
||||
"path": ["techStates", {"key": 1001}],
|
||||
"select": ["curLevel", "hashUploaded", "hashNeeded"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "research-1",
|
||||
"result": {
|
||||
"type": "TechState",
|
||||
"value": {
|
||||
"curLevel": 3,
|
||||
"hashUploaded": "12345678901234567",
|
||||
"hashNeeded": "22345678901234567"
|
||||
},
|
||||
"sessionId": "session-1",
|
||||
"gameTick": "6000"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Array read example
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "queue-1",
|
||||
"method": "data.read",
|
||||
"params": {
|
||||
"root": "history",
|
||||
"path": ["techQueue"],
|
||||
"offset": 0,
|
||||
"limit": 2
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "queue-1",
|
||||
"result": {
|
||||
"type": "System.Int32[]",
|
||||
"value": {
|
||||
"items": [1001, 1002],
|
||||
"offset": 0,
|
||||
"totalCount": 8,
|
||||
"hasMore": true
|
||||
},
|
||||
"sessionId": "session-1",
|
||||
"gameTick": "6000"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Game state and consistency
|
||||
|
||||
- Menu demos, loading, and the absence of a running player game make `data.read` and `data.describe` fail with `GAME_NOT_READY`. `data.roots` can still report unavailability.
|
||||
- An unavailable known root during an active game, such as `localPlanet` during space travel, produces `ROOT_UNAVAILABLE`. This differs from a null terminal member on an available root.
|
||||
- Every game-data request is associated with the session state in which it was admitted. A queued request cannot silently read a subsequently loaded save; a session transition invalidates it with `SESSION_CHANGED`.
|
||||
- Results are detached samples taken on the main thread. `gameTick` identifies sampling time; it is not a transactional snapshot ID. No cross-request or globally atomic game-world snapshot is promised.
|
||||
- A response sampled before a session transition may already be in transit. Clients should use `sessionId` and new discovery results to discard data belonging to a previous session.
|
||||
|
||||
## Errors and recovery
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "read-1",
|
||||
"error": {
|
||||
"code": -32001,
|
||||
"message": "Game data is unavailable.",
|
||||
"data": {
|
||||
"kind": "GAME_NOT_READY"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`message` is English diagnostic text, not a stable identifier. `error.data.kind` is stable. Error data may additionally contain `segmentIndex` (zero-based), `member`, or `root` to identify the failure. Stack traces, filesystem paths, and exception objects are not returned.
|
||||
|
||||
| Code | Kind | Meaning / client action |
|
||||
| --- | --- | --- |
|
||||
| `-32700` | `PARSE_ERROR` | Malformed JSON or duplicate object keys; response ID is null. Correct the message. |
|
||||
| `-32600` | `INVALID_REQUEST` | Invalid envelope, batch, or invalid/missing ID. Correct the request; ID is null if it cannot be reliably determined. |
|
||||
| `-32601` | `METHOD_NOT_FOUND` | Unknown method. Check API version and method spelling. |
|
||||
| `-32602` | `INVALID_PARAMS` | Wrong/missing/unknown parameter or invalid parameter combination. Correct the request. |
|
||||
| `-32603` | `INTERNAL_ERROR` | Unexpected server failure. Inspect server logs. |
|
||||
| `-32001` | `GAME_NOT_READY` | No ready player game. Poll root availability before retrying. |
|
||||
| `-32002` | `ROOT_NOT_FOUND` | Unknown root name. Rediscover roots. |
|
||||
| `-32003` | `ROOT_UNAVAILABLE` | Known root is absent in this game state. Wait for it to become available. |
|
||||
| `-32004` | `MEMBER_NOT_FOUND` | Requested member does not exist. Rediscover members for this game version. |
|
||||
| `-32005` | `MEMBER_NOT_ALLOWED` | Member exists but is outside the read policy. Choose an exposed member. |
|
||||
| `-32006` | `NULL_PATH` | Null encountered before completing the path. Query a shorter path or retry after state changes. |
|
||||
| `-32007` | `INDEX_OUT_OF_RANGE` | Element index is outside the current array/list. Refresh collection metadata. |
|
||||
| `-32008` | `KEY_NOT_FOUND` | Dictionary has no matching key. Refresh the source of the key. |
|
||||
| `-32009` | `UNSUPPORTED_TYPE` | Value type or traversal operation is unsupported. Use supported data members. |
|
||||
| `-32010` | `READ_FAILED` | A permitted read failed, including a getter exception. Inspect logs or rediscover the path. |
|
||||
| `-32011` | `LIMIT_EXCEEDED` | A documented resource limit would be exceeded. Reduce depth, projection, page size, or output size. |
|
||||
| `-32012` | `SERVER_BUSY` | Admission capacity is exhausted. Reduce concurrent requests and back off. |
|
||||
| `-32013` | `REQUEST_TIMEOUT` | Response production exceeded its deadline. Retry later with a new ID. |
|
||||
| `-32014` | `SESSION_CHANGED` | Session changed after admission. Rediscover roots and discard old-session work. |
|
||||
| `-32015` | `UNSUPPORTED_VALUE` | Value cannot be represented under the scalar rules. |
|
||||
|
||||
Malformed parameter types and negative indexes/offsets are `INVALID_PARAMS`. For otherwise well-formed method parameters, exceeding a documented positive maximum, such as path length or page size, is `LIMIT_EXCEEDED`. Envelope validity and transport limits follow their specific rules above. A well-formed but unknown root is `ROOT_NOT_FOUND` before game availability is evaluated. Path resolution then stops at its first failure.
|
||||
|
||||
Transport closure codes relevant to clients:
|
||||
|
||||
| Code | Meaning |
|
||||
| --- | --- |
|
||||
| `1001` | Server is stopping. |
|
||||
| `1002` | WebSocket framing or protocol violation. |
|
||||
| `1003` | Binary application message is unsupported. |
|
||||
| `1007` | Invalid UTF-8 payload. |
|
||||
| `1008` | Protocol violation such as reuse of an outstanding ID. |
|
||||
| `1009` | Incoming message is too large. |
|
||||
| `1013` | Overload or inability to drain a bounded send queue. |
|
||||
|
||||
Reserved status values such as `1005`, `1006`, and `1015` are not sent in close frames. A client may locally report `1006` when a transport is lost or aborted without a completed close handshake.
|
||||
|
||||
Do not retry invalid paths unchanged in a tight loop. Game-state errors can be retried after discovery; overload and timeouts require client-side backoff. Reconnection creates a new request-ID namespace but does not restore any requests from the old connection.
|
||||
@@ -0,0 +1,430 @@
|
||||
# LiveStreamAssist WebSocket Design and Transport Migration Plan
|
||||
|
||||
Status: **in-process Kestrel transport implemented; desktop regressions pass; Unity/LAN and full conformance acceptance pending**. Production code explicitly pins ASP.NET Core **2.3.13** hosting, HTTP, Kestrel Core, Sockets, and WebSockets, `System.Net.WebSockets.WebSocketProtocol` **5.1.3**, and Newtonsoft.Json **13.0.3**. Fleck is removed. The desktop probe verifies a fragmented echo round trip; production-code checks cover connection cleanup, admission, deadlines, shutdown, and loopback requests. DSP/Unity Mono, Autobahn, and LAN checks have not passed.
|
||||
|
||||
The next remaining work is an actual DSP run of the probe/mod, then M3 conformance. Keep the mod on `net472`. A standalone gateway is a last-resort fallback after concrete in-process failures, not the default design.
|
||||
|
||||
The [API reference](WebSocketApi.md) defines the client-visible contract. This document defines the scope, implementation constraints, source references, work order, and acceptance checks. Keep API usage documentation separate from implementation investigation and progress notes.
|
||||
|
||||
## Confirmed scope
|
||||
|
||||
The following decisions were confirmed with the user and must survive a session handoff:
|
||||
|
||||
- Support both local and LAN WebSocket clients.
|
||||
- Use **no authentication** in v1. The user explicitly chose this after LAN access was discussed. Do not add a shared token, login endpoint, accounts, or permissions workflow.
|
||||
- Provide read-only, client-initiated requests for in-game data, primarily through reflection.
|
||||
- Provide connectivity and API-compatibility validation. Here, validation does not mean identity authentication or a separate reflection-path-validation API.
|
||||
- Report the API version, mod version, running game version, and running game build.
|
||||
- Reserve API statistics through `system.stats`, returning `available: false` and `metrics: null`; advertise `api.stats: false`.
|
||||
- Do not implement subscriptions, application notifications, batch requests, game writes, arbitrary method invocation, or script evaluation.
|
||||
- Preserve the existing Ctrl+F8 statistics-window feature and its independent state.
|
||||
- The game uses Unity 2022. Standard-library APIs, selected NuGet assets, and the entire runtime dependency graph must work in its actual Mono player.
|
||||
- Prefer an in-process implementation. Consider a standalone gateway only when maintained, compatible in-process options cannot satisfy the compatibility and conformance gates.
|
||||
- Retire Fleck and its internal-handler workaround. Do not carry them forward as the normal transport or as an automatic runtime fallback.
|
||||
|
||||
Keep the implementation small: one listener, a fixed method switch, fixed root providers, a bounded main-thread dispatcher, and shallow result projection. Use only the hosting services required by Kestrel; do not refactor the mod's feature architecture into a dependency-injection framework. No MVC, SignalR, REST API, web dashboard, general-purpose reflection service, or custom WebSocket framing implementation is required.
|
||||
|
||||
The initial listener configuration and all wire limits are defined in [API connection settings](WebSocketApi.md#connection) and [API limits](WebSocketApi.md#limits). Keep those tables as the single documentation source for their values. Configuration is startup-only in v1; do not introduce live configuration reload as part of this work.
|
||||
|
||||
## Starting or resuming implementation
|
||||
|
||||
1. Read the repository `AGENTS.md`, this document, and the API reference before editing code.
|
||||
2. Inspect `git status` and the current diff. Treat existing changes as user work. Check whether some phases have already been implemented rather than assuming this document's initial status still describes the checkout.
|
||||
3. Read the source entry points in the next section. Preserve the host-owned feature lifecycle and existing keyboard handling.
|
||||
4. Recheck runtime-specific assumptions against the installed game's original assemblies if DSP or Unity has changed. Do not use stripped reference DLL method bodies as evidence.
|
||||
5. Complete the migration phases in dependency order. M0 must pass before adopting a replacement in production code. Mark checks complete only after running them; an unavailable DSP or LAN test is blocked, not passed and not proof that an in-process solution is impossible.
|
||||
6. If pausing between sessions, update this document's current status, remaining phase checks, selected dependency versions, and concrete blockers. Replace stale notes instead of appending a chronological transcript. Keep project-specific guidance here; `AGENTS.md` should contain only a link to this document.
|
||||
|
||||
The API reference is the source of truth for method names, message shapes, numeric error codes, null behavior, and capability names. Resolve any conflict with this plan before implementing it. The migration replaces transport and repairs its integration; it does not restart the reflection feature from scratch or expand the API scope. Do not preserve an implementation bug by weakening the documented contract.
|
||||
|
||||
## Transport decision and evidence
|
||||
|
||||
Research baseline: **2026-09-17**. The preferred candidate is the **serviced ASP.NET Core 2.3 package line for .NET Framework**, using Kestrel's managed socket transport and its WebSocket middleware in the game process. This is a package-based `netstandard2.0` route, not a requirement to load a modern .NET runtime into Unity.
|
||||
|
||||
Microsoft explicitly lists Kestrel, its socket transport, and WebSocket middleware in the [supported 2.3 package set][aspnet-support]. Its [servicing advisory][aspnet-advisory] distinguishes this line from unsupported ASP.NET Core 2.1/2.2 packages and from running old .NET Core runtimes. The reviewed [WebSockets 2.3.13][websockets-package] and [Sockets transport 2.3.13][sockets-package] packages publish `netstandard2.0` assets and September 2026 servicing releases. Recheck the latest supported patch when implementing; patch numbers need not be identical across all packages.
|
||||
|
||||
The [reviewed middleware source][middleware-source] obtains an opaque stream through Kestrel's `IHttpUpgradeFeature` and constructs the WebSocket through the protocol dependency. The [socket transport source][sockets-source] uses the managed socket transport. This avoids the game's unimplemented `HttpListenerContext.AcceptWebSocketAsync` path.
|
||||
|
||||
Important qualifications:
|
||||
|
||||
- Microsoft's support statement concerns ASP.NET Core on .NET Framework; it is **not a certification of Unity's Mono player**. M0 still requires an actual DSP run.
|
||||
- This is a serviced compatibility line, not the current ASP.NET Core feature line. The required standard is the [API's RFC 6455/HTTP/1.1 profile](WebSocketApi.md#websocket-interoperability), not a claim of HTTP/2, HTTP/3, compression, or future extension support.
|
||||
- The transitive [WebSocketProtocol package][protocol-package] labels its standalone factory API obsolete. Do not build a new handshake stack around that API. Use the maintained middleware's existing integration, review the exact resolved protocol package and advisories, and verify which concrete WebSocket implementation is loaded. A package's Microsoft ownership alone is not sufficient acceptance evidence.
|
||||
|
||||
### Candidate disposition
|
||||
|
||||
| Candidate | Disposition and evidence |
|
||||
| --- | --- |
|
||||
| ASP.NET Core 2.3 + managed Kestrel Sockets + WebSockets | First candidate for M0: serviced packages and a compatible declared API surface. Actual Mono loading, protocol behavior, and resource bounds remain to be tested. |
|
||||
| Fleck 1.2.0 | Retired by the user's requirement. The reviewed [repository head][fleck-source] is a 2021 core commit; do not imply the repository is formally archived. The retired handler wrapper did not enforce a message-level limit. |
|
||||
| TouchSocket.Http 4.3.x | Maintained and publishes compatible targets, but not an approved drop-in. The [reviewed 4.3.6 frame parser][touch-frame] allocates from the advertised payload length before an application callback; the [framework-target project][touch-project] also references `System.Web`. The [4.3.7 package][touch-package] is newer than the reviewed source snapshot. Reconsider only with matching released source and passing gates, without a private framing fork. |
|
||||
| SuperSocket.WebSocket.Server 2.1.0 | The [current package][supersocket-package] requires .NET 6 or later, so it is not a compatible in-process replacement for this `net472` mod. Do not select an old preview merely to obtain a different TFM. |
|
||||
| A separate supported .NET LTS gateway | Conditional fallback only; see [Fallback boundary](#fallback-boundary). It adds packaging, IPC, and process-lifetime responsibilities and must not be introduced just because game testing is unavailable. |
|
||||
|
||||
### Unity and dependency compatibility rules
|
||||
|
||||
The [Unity 2022.3 documentation][unity-profile] describes .NET Standard 2.1 and .NET Framework API compatibility profiles and explicitly excludes .NET Core-targeted managed plugins. The installed player, not a Unity Editor setting in a different project, is the runtime to validate.
|
||||
|
||||
1. Keep `LiveStreamAssist.csproj` and its UXAssist reference on the existing `net472` path. For the replacement, select actual `netstandard2.0` or compatible .NET Framework assets, including transitive dependencies. Unity's support for Standard 2.1 does not make a Standard-2.1-only package a valid SDK project reference from `net472`.
|
||||
2. Do not reference `net6.0`, `net8.0`, or `net10.0` implementation DLLs in the mod. Do not add a `Microsoft.AspNetCore.App` framework reference, switch to `Microsoft.NET.Sdk.Web`, or retarget shared mods to make an incompatible package restore.
|
||||
3. Package version and target framework are different facts. A dependency such as `System.IO.Pipelines` or `Microsoft.Extensions.Options` can have an 8.x version and still supply a compatible asset; inspect the selected asset path and its APIs instead of deciding from its version number.
|
||||
4. Inspect `project.assets.json`, resolved runtime copy items, assembly references, and the actual game load results. Pay particular attention to `System.Memory`, `System.Buffers`, `System.Threading.Tasks.Extensions`, `System.Runtime.CompilerServices.Unsafe`, `System.IO.Pipelines`, and `Microsoft.Extensions.*`, including conflicts with other installed mods.
|
||||
5. Never replace the game's `mscorlib`, `System`, `System.Core`, `netstandard`, Unity assemblies, or framework facades to make the host start. Do not ship reference assemblies from a package's `ref` directory. Conversely, do not discard every `System.*` DLL: reviewed package implementations such as `System.Net.WebSockets.WebSocketProtocol.dll` may be required runtime dependencies.
|
||||
6. Use the classic `WebHostBuilder`/`IWebHost` hosting surface and `WebSocket` array-segment/task APIs available to the selected target. Avoid APIs copied from modern examples, such as `WebApplication.CreateBuilder`, `Task.WaitAsync`, or memory-based WebSocket overloads absent from the compile/runtime surface. Use ordinary task cancellation/timeouts where necessary.
|
||||
7. A successful desktop .NET Framework build or console run is only an early check. `MissingMethodException`, `TypeLoadException`, `NotImplementedException`, or unsupported socket behavior in the actual player fails M0. Do not conceal such failures with warning suppression, private-reflection patches, or global assembly-resolution hooks.
|
||||
|
||||
Prospective direct dependencies are the supported 2.3.x hosting/Kestrel components, `Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets`, and `Microsoft.AspNetCore.WebSockets`, plus the existing Newtonsoft.Json dependency. Prefer explicit components if a convenience package brings unused transports. Select the latest compatible serviced protocol dependency as well; do not let a minimum transitive constraint silently pin an obsolete patch. Record and lock the exact approved graph after M0.
|
||||
|
||||
## Repository entry points
|
||||
|
||||
Paths in this table are relative to the repository root.
|
||||
|
||||
| File / symbol | Why it matters |
|
||||
| --- | --- |
|
||||
| `LiveStreamAssist/LiveStreamAssist.cs` / `LiveStreamAssist.Awake` | BepInEx plugin startup; performs localization setup and feature discovery. Bind API configuration before discovery. |
|
||||
| `LiveStreamAssist/LiveStreamAssist.cs` / `LiveStreamAssistFeature` | Existing feature, order 50; owns Ctrl+F8 and statistics-window switching. Its `_enabled` flag is not the server-enabled flag. |
|
||||
| `LiveStreamAssist/LiveStreamAssist.csproj` | Inherits `net472`, currently references UXAssist, and owns the mod version. Add only the server's required dependencies and project-scoped packaging customization here. |
|
||||
| `LiveStreamAssist/Api/WebSocketApiServer.cs` | Kestrel host, `ApiConnection`, and `PendingRequest`; owns transport lifetime, admission, bounded I/O, and host-error logging. |
|
||||
| `LiveStreamAssist/Api/MainThreadDispatcher.cs` | Current game-work queue and completion path; inspect physical queue bounds and timeout behavior as well as frame budgets. |
|
||||
| `LiveStreamAssist/Api/ApiProtocol.cs` | Reuse the JSON-RPC contract and system methods; review serializer concurrency and remove transport-specific raw-socket limits. |
|
||||
| `LiveStreamAssist/tools/ReflectionReaderCheck/` | Existing fixture runner. Preserve its coverage; it does not prove WebSocket conformance or game-runtime compatibility. |
|
||||
| `UXAssist/Common/ModFeatures/ModFeatureRegistry.cs` | Initializes discovered features eagerly. UXAssist alone drives `StartAll`, `UninitAll`, and update dispatchers. |
|
||||
| `UXAssist/UXAssist.cs` / `Update` | Skips feature updates while `VFInput.inputing` or `DSPGame.IsMenuDemo` is true. This is unsuitable as the sole server request pump. |
|
||||
| `UXAssist/Common/GameLogic.cs` | Supplies `OnDataLoaded`, `OnGameBegin`, and `OnGameEnd` callbacks. Use the fully qualified UXAssist type or the existing `GameLogicProc` alias to avoid DSP's own `GameLogic` type. |
|
||||
| `Directory.Build.props` | Shared BepInEx dependencies, Unity compile assets, original-game reference refresh dependency, and warning policy. |
|
||||
| `Directory.Build.targets` / `ZipMod` | Packages the main assembly and selected root files. It does not automatically package NuGet runtime dependencies. |
|
||||
| `UpdateGameDlls.ps1` | Documents Steam registry and `libraryfolders.vdf` discovery. Running it updates/publicizes compile references; read it for installation discovery rather than using its outputs for decompilation. |
|
||||
| `LuaScriptEngine/LuaState.cs` | Existing research/statistics access examples, not a reusable WebSocket server. LuaScriptEngine is not a dependency of this feature. |
|
||||
|
||||
### Verified original-runtime facts
|
||||
|
||||
These facts were checked while preparing the plan. They are implementation constraints, not a substitute for testing the selected library in DSP:
|
||||
|
||||
| Original assembly / symbol | Finding and consequence |
|
||||
| --- | --- |
|
||||
| `System.dll` / `System.Net.HttpListenerContext.AcceptWebSocketAsync` | The inspected overloads throw `NotImplementedException`. Do not select the framework `HttpListener` WebSocket server path on the basis of desktop .NET tests. |
|
||||
| `UnityEngine.CoreModule.dll` / `UnityEngine.UnitySynchronizationContext` | `Post` enqueues work; `Exec` copies queued work before running callbacks. Capture the installed main-thread context and post a bounded pump through it. |
|
||||
| `Assembly-CSharp.dll` / `GameConfig` | Supplies `gameVersion` and the separate `build` field. Read these from the running game. |
|
||||
| `Assembly-CSharp.dll` / global `Version` | DSP has its own `Version` struct. `ToString()` omits its `Build` field. Do not confuse this type with `System.Version` or assume an assembly version is the game version. |
|
||||
| `Assembly-CSharp.dll` / `GameMain` | Root getters return current `GameData` members. Menu demos can have allocated game data; checking only `GameMain.data != null` is insufficient. Pausing does not end a running game. |
|
||||
| `Assembly-CSharp.dll` / `VFPreload` | `InvokeOnLoadWorkEnded` runs before `done` becomes true. `done`/`dbDone` can be used to detect an already completed preload when starting late; do not require them to be true inside the load-work-ended callback itself. |
|
||||
| `Assembly-CSharp.dll` / `GameHistoryData.currentTech` | This is an auto-property with a public getter and private setter, not a public field. The getter only returns its backing value and is the initial allowed property. |
|
||||
| `Assembly-CSharp.dll` / `GameConfig` getters | Some apparently readable properties create directories. Public visibility or the absence of a public setter does not establish a side-effect-free getter. |
|
||||
|
||||
To reproduce inspection, locate Steam using the registry and parse `steamapps/libraryfolders.vdf` for app ID `1366540`, as `UpdateGameDlls.ps1` does. Resolve `<game_root>/DSPGAME_Data/Managed/` and decompile the installed original DLLs, for example:
|
||||
|
||||
```text
|
||||
ilspycmd --disable-updatecheck -t GameConfig <managed>/Assembly-CSharp.dll
|
||||
ilspycmd --disable-updatecheck -t Version <managed>/Assembly-CSharp.dll
|
||||
ilspycmd --disable-updatecheck -t GameMain <managed>/Assembly-CSharp.dll
|
||||
ilspycmd --disable-updatecheck -t GameHistoryData <managed>/Assembly-CSharp.dll
|
||||
ilspycmd --disable-updatecheck -t VFPreload <managed>/Assembly-CSharp.dll
|
||||
ilspycmd --disable-updatecheck -t UnityEngine.UnitySynchronizationContext <managed>/UnityEngine.CoreModule.dll
|
||||
ilspycmd --disable-updatecheck -t System.Net.HttpListenerContext <managed>/System.dll
|
||||
```
|
||||
|
||||
Replace placeholders and quote paths containing spaces. Do not depend on this session's temporary decompilation output or a hard-coded Steam drive letter. Do not commit game DLLs or decompiled game source.
|
||||
|
||||
### Transport integration invariants
|
||||
|
||||
Keep these rules when changing the transport. The desktop harness exercises the production classes with controlled work scheduling and sockets; it does not replace the Unity acceptance gate.
|
||||
|
||||
| Code path | Required behavior |
|
||||
| --- | --- |
|
||||
| `ReceiveLoop` | Bound complete-message payloads, preserve fragmentation state across empty fragments, and cancel stalled partial reads independently of the next receive completion. |
|
||||
| `ApiConnection.NotifyDisconnected` / `Dispose` | Cancel I/O and wake an idle sender, clear queued output, and release every admission exactly once. Overflow must use this cleanup path rather than setting the terminal flag early. |
|
||||
| `TryAdmit` / `DeliverAsync` / `RunSendLoop` | Retain IDs and admission slots through delivery. Include active sends in output capacity, and deduct queued time from the send deadline. Invalid requests with a reliable ID still participate in duplicate-ID checks. |
|
||||
| `CloseAsync` / `ReceiveLoop` | Serialize close output with application sends; leave peer-close reception to the single receive loop. Bound the handshake and abort stalled I/O. |
|
||||
| `MainThreadDispatcher` | Watch queued and executing work, bound the physical queue, and remove canceled entries. Completion continuations must not serialize inline in the game-work producer. |
|
||||
| `StartAsync` / `StopAsync` / `HandleHttp` | One startup/shutdown task per owner, no resurrection after stop, no disposal racing startup, and concrete connection reservations that can be canceled during upgrade. |
|
||||
| `WebSocketApiFeature` | Bind clocks and failure callbacks to their originating owner, publish immutable snapshots with cross-thread visibility, and invalidate only old-session work. |
|
||||
| `ApiProtocol` / `ReflectionReader` | Use per-operation serializers, reject explicitly null typed parameters, and apply runtime/declaration type boundaries consistently to reads, descriptions, and projections. |
|
||||
| `tools/Test-WebSocketApi.ps1` | Use per-operation deadlines, strict-mode-safe optional access, bounded reads, and cleanup after failed upgrades. Require an actual HTTP rejection rather than treating every connection failure as a passed route test. |
|
||||
|
||||
## Code organization
|
||||
|
||||
Use these responsibilities as the starting layout; keep small private helpers with their owner rather than creating an interface or service for each step.
|
||||
|
||||
| File | Responsibility after migration |
|
||||
| --- | --- |
|
||||
| `LiveStreamAssist/Api/WebSocketApiFeature.cs` | Preserve configuration, feature order 51, Unity-context capture, version publication, sessions, and root providers; coordinate asynchronous host lifetime. |
|
||||
| `LiveStreamAssist/Api/WebSocketApiServer.cs` | Private Kestrel host and `System.Net.WebSockets.WebSocket` connection loops, bounded admission, serialized sends, and cleanup. Keep framework-specific types here. |
|
||||
| `LiveStreamAssist/Api/ApiProtocol.cs` | DTOs, error constants, validation, fixed method dispatch, system methods, and the API version constant. |
|
||||
| `LiveStreamAssist/Api/ReflectionReader.cs` | Shared path resolution, allowed-member discovery, value projection, and detached result construction. |
|
||||
| `LiveStreamAssist/Api/MainThreadDispatcher.cs` | Physically bounded game-work queue, one scheduled pump, cancellation, and detached completion; no JSON serialization or socket work. |
|
||||
| `LiveStreamAssist/tools/Test-WebSocketApi.ps1` | Runnable WebSocket integration checks using PowerShell 7 and `System.Net.WebSockets.ClientWebSocket`. |
|
||||
| `LiveStreamAssist/tools/WebSocketTransportCheck/` | Desktop `net472` echo probe and production transport/dispatcher regression checks. Keep test-only echo behavior out of the production API. |
|
||||
|
||||
Bind the three API settings in plugin startup before `ModFeatureRegistry.Discover`. Use a separate `[ModFeature]` class for the server. Do not have LiveStreamAssist call registry dispatchers, add a second shared update driver, relax UXAssist's menu/typing guards, or attach server activation to Ctrl+F8.
|
||||
|
||||
Keep Newtonsoft.Json for the existing API encoding. Do not migrate the JSON contract to SignalR or a different serializer as part of replacing Fleck. No new general-purpose transport factory or public abstraction is needed; isolate the selected framework at the existing server boundary.
|
||||
|
||||
## Runtime design
|
||||
|
||||
### Lifecycle and metadata
|
||||
|
||||
- `Init`: prepare configuration references and non-network state. Keep initialization safe if the API is disabled.
|
||||
- `Start`: if enabled, capture `SynchronizationContext.Current` on Unity's main thread, initialize a server owner instance, subscribe to game lifecycle events, and start the listener without blocking the game loop. If the current context is null or is not Unity's installed context, fail startup with a useful log; a newly constructed generic `SynchronizationContext` is not a main-thread dispatcher.
|
||||
- Build/start the private `IWebHost` on a worker and observe its startup task. Initialize owner/admission state before requests can arrive. Use explicit configuration from the mod rather than process-global URL settings, console lifetime, or unrelated hosting-startup discovery. Do not call `Run()` or terminate the game process when the host stops.
|
||||
- Publish version data from `GameLogicProc.OnDataLoaded`. If starting after preload, use the original preload completion flags to populate it immediately. Publish an immutable snapshot; network callbacks never read `GameConfig` or Unity state directly. Preserve this snapshot across save changes.
|
||||
- Source `modVersion` from generated `PluginInfo.PLUGIN_VERSION`. Keep `apiVersion` independent, initially `1.0.0`. Use the explicit `System.Version` name if parsing the API version to avoid DSP's global `Version` type.
|
||||
- Subscribe to `OnGameBegin` and `OnGameEnd` for session transitions. Account for starting after a game has already begun.
|
||||
- `Uninit`: stop admitting work, invalidate the owner/session, cancel requests, unsubscribe events, close the listener, and close connections. Clear metadata caches owned by the server. Posted callbacks must check their old owner token so they cannot run against a restarted instance.
|
||||
- Startup errors, including an occupied port or invalid settings, disable only this server instance and are logged. Do not silently bind a different address/port or let an exception escape into other features' startup/shutdown.
|
||||
- Start/stop and cleanup must be idempotent. Never synchronously wait on a task whose completion needs the Unity thread during shutdown.
|
||||
- Bound and observe `StopAsync`; dispose the host off the Unity thread, including startup-failure paths. A stopped or superseded owner cannot resume startup and leave a listener behind. Keep lifecycle/event-state transitions coordinated with the existing main-thread feature owner.
|
||||
- Forward Kestrel warnings/errors to the mod logger so runtime failures before the API handler are visible. The host must not require process-global logging configuration.
|
||||
|
||||
### Kestrel connection and receive loop
|
||||
|
||||
- Explicitly select the managed socket transport and the configured IP endpoint. Do not use `HttpListener`, HTTP.sys, IIS integration, or Libuv. Use the supported WebSocket middleware for handshake validation and the opaque-stream upgrade; do not recreate handshake or frame parsing in mod code.
|
||||
- Restrict the route to `/api/v1` before upgrade. Return an HTTP rejection for other paths, invalid handshakes, or exhausted upgrade capacity. Bound ordinary HTTP connections, upgraded connections, request-header size, and header-read time using supported host options. A Kestrel HTTP request-body limit is not a WebSocket message limit.
|
||||
- Await the connection handler for the lifetime of the WebSocket so the HTTP request pipeline does not dispose the upgraded stream prematurely. Each connection owns one receive loop, one serialized application send loop, and cancellation linked to server shutdown and client disconnect.
|
||||
- Read through the target-compatible `ReceiveAsync(ArraySegment<byte>, CancellationToken)` API. Accumulate at most `maxRequestBytes`, checking before each append; deliver one complete text message only when `EndOfMessage` is true. Handle an empty message as a JSON parse failure, not as a disconnect. Give an incomplete message an operation deadline once it starts, while allowing an otherwise idle connection to remain open.
|
||||
- Let the maintained protocol implementation handle masking, RSV/opcode validation, fragmentation state, ping/pong, and close parsing. Use strict UTF-8 decoding for the bounded completed text. Do not install another private-handler hook or write a frame parser to compensate for failed conformance.
|
||||
- Keep compression/extensions disabled for the v1 profile. Preserve binary-message rejection (`1003`), invalid UTF-8 (`1007`), invalid framing (`1002`), oversized messages (`1009`), and application policy errors (`1008`) as distinct outcomes.
|
||||
- Await and observe sends. Apply a deadline covering both queued time and the active send; use a bounded close attempt followed by `Abort`/disposal if the peer cannot drain. Do not send reserved close status values, swallow a failed send and continue, or launch overlapping application sends.
|
||||
|
||||
### Root providers and readiness
|
||||
|
||||
Register these fixed mappings inside LiveStreamAssist:
|
||||
|
||||
| Root | Provider |
|
||||
| --- | --- |
|
||||
| `game` | `GameMain.data` |
|
||||
| `player` | `GameMain.mainPlayer` |
|
||||
| `history` | `GameMain.history` |
|
||||
| `statistics` | `GameMain.statistics` |
|
||||
| `galaxy` | `GameMain.galaxy` |
|
||||
| `localPlanet` | `GameMain.localPlanet` |
|
||||
| `localStar` | `GameMain.localStar` |
|
||||
|
||||
A player game is ready when `GameMain.data` exists, `GameMain.isRunning` is true, loading is false, and `DSPGame.IsMenuDemo` is false. Re-evaluate these conditions on the main thread at execution time. Do not reject an otherwise ready game because it is paused, a fullscreen UI is open, or text input is active.
|
||||
|
||||
Root discovery always lists the fixed catalog, using declared types when no instance is available. `data.read`/`data.describe` reject a not-ready game. A known root that returns null during a ready game is `ROOT_UNAVAILABLE`; null reached at the end of a member path is a successful null value.
|
||||
|
||||
Do not retain root instances, collection instances, or getter return objects in reflection caches. Resolve roots per request. Treat only the specified root set as remote entry points; exposing a client-supplied assembly/type name would bypass this boundary.
|
||||
|
||||
### Network-to-main-thread flow
|
||||
|
||||
```text
|
||||
WebSocket callback
|
||||
-> validate envelope, parameters, ID, size, and capacity
|
||||
-> system method: respond from immutable/process-only data
|
||||
-> game-data method: capture session generation and enqueue
|
||||
-> one Unity SynchronizationContext.Post pump
|
||||
-> recheck connection, deadline, session, and readiness
|
||||
-> resolve root/path and build detached result
|
||||
-> asynchronous completion signal only
|
||||
-> worker serializes within the output cap
|
||||
-> serialized send; release admission only after delivery/cancellation
|
||||
```
|
||||
|
||||
- Network receive, JSON parsing, serialization, and socket sends stay off the Unity thread. Avoid accidentally capturing Unity's context in network async continuations.
|
||||
- Only one pump callback may be scheduled per server owner at a time. Process work within the API's per-frame count and soft-time budget, then repost remaining work. Do not busy-wait, spin, or post one unbounded callback per request. Track the Unity frame for the budget if the context is pumped more than once in a frame.
|
||||
- Use a standard queue with a small lock or `ConcurrentQueue` with correct admission accounting. A custom scheduler or lock-free queue is unnecessary. If using task completions, run continuations asynchronously so response work does not execute inline in the pump.
|
||||
- A request owns one admission slot until response delivery or cancellation. Capacity includes outgoing responses. Serialize sends per connection, bound the send queue, and close slow consumers rather than retaining unlimited output.
|
||||
- Distinguish response production from terminal delivery: `admitted -> result/error produced -> response sent or connection canceled`. Keep the ID reserved through the last step. A task completion source with asynchronous continuations is sufficient; do not serialize or release the slot inside its main-thread producer.
|
||||
- Expiry is based on monotonic elapsed time, not `Time.time` or game ticks. A worker-enforced production deadline must fire even when Unity stops pumping. Check expiry before reading as well. Once timed out, work cannot later emit success. A deadline does not abort a getter halfway through; the read policy must keep getters short and bounded.
|
||||
- Reuse the documented timeout duration for a separate bounded send deadline beginning at response enqueue, including the active send. A send timeout closes/aborts the connection; it must not interleave a second error envelope into a partly transmitted response.
|
||||
- Connection cancellation removes or cheaply skips queued work and releases its slot exactly once. Session invalidation and production timeout instead produce the documented error; retain the ID and slot until that error is sent or the connection is canceled. Use one terminal cleanup path so competing outcomes cannot double-complete or leak admission counts.
|
||||
- Enforce a physical game-work queue bound even after canceled requests release network admission. A queue full of stale entries is not permission to allocate another unbounded queue or task list. Bound unslotted parse/busy-error responses as well.
|
||||
- The only mutable game references exist during main-thread execution. Return scalar values, strings, copied arrays/pages, and plain snapshot dictionaries/DTOs; never pass a live DSP object, boxed game struct with nested references, `MemberInfo`, or `UnityEngine.Object` to the background JSON serializer.
|
||||
|
||||
### Session transitions
|
||||
|
||||
Maintain an internal generation that changes at game-session boundaries and server stop, plus an opaque public `sessionId` for each ready player session. A GUID is sufficient for the public ID; it is not persisted and has no authentication meaning.
|
||||
|
||||
Publish the current admission generation as immutable/thread-safe state. Each admitted game-data request records it without carrying a game object across threads. Before executing and before completing an in-progress sample, compare it with current state. Cancel pending old-generation work with `SESSION_CHANGED` instead of resolving its path against a new save.
|
||||
|
||||
On game end, publish an unavailable session and invalidate pending work while keeping the listener and process-level version metadata alive. Game readiness checks still run when requests execute, covering state changes between callbacks. Already delivered/in-transit snapshots remain identified by their old `sessionId`; do not claim they can be recalled.
|
||||
|
||||
### Reflection and serialization policy
|
||||
|
||||
Use one resolver/member-policy path for `data.read`, `data.describe`, and projections. Fixing or restricting access must affect all three paths together.
|
||||
|
||||
1. Validate segment kinds and bounds before invoking reflection. Retain whether `select`, `offset`, and `limit` were explicitly supplied; array/list defaults must not cause ordinary scalar reads to fail parameter validation. No dotted-path parser, expression compiler, wildcard search, or arbitrary indexer binder is needed.
|
||||
2. Resolve instance fields with public and non-public visibility, walking declared members from the most-derived type toward base types. Skip static and compiler-generated fields. Apply type restrictions before traversing a value. A denied declaration does not fall back to a same-named base declaration.
|
||||
3. Permit ordinary data types defined in the game's `Assembly-CSharp` assembly, the API's scalar types, the specified concrete BCL containers, and the listed Unity value structs. Apply infrastructure exclusions before the assembly allowance: being a game-defined subclass of `UnityEngine.Object`, a stream, or another runtime-service type does not make it readable. Do not traverse native handles, pointer/by-ref fields, delegates, `Type`/reflection metadata, tasks/threads, locks, streams, or arbitrary external-plugin types.
|
||||
4. Generic getter access starts with this exact allowlist only:
|
||||
|
||||
| Declaring type | Property | Verified behavior |
|
||||
| --- | --- | --- |
|
||||
| `GameHistoryData` | `currentTech` | Public auto-property getter returning its backing value; private setter is not exposed. |
|
||||
| `GameDesc` | `clusterString` | Formats the current cluster seed/address from `galaxySeed`, `starCount`, resource mode, and combat difficulty fields without mutating game state. |
|
||||
|
||||
Additional properties require a concrete query need and inspection of the original getter and any called methods. Record the exact declaration and reason here and update the API reference before adding it. Do not allow every public getter, call a setter, or bypass a rejected getter through its compiler-generated backing field.
|
||||
|
||||
5. Use concrete BCL array/list/dictionary adapters for indexing and counts. Do not accept arbitrary `IList`, `IDictionary`, or `IEnumerable` implementations merely because they expose a familiar interface. No full dictionary enumeration, custom collection internals, or pool compaction is needed in v1.
|
||||
6. Keep projections shallow as specified by the API. Explicit paths may follow cyclic references within the path limit, but summaries terminate output traversal. No graph serializer, persistent object handles, reference registry, or general cycle-resolution framework is needed.
|
||||
7. Encode 64-bit values and other scalars before passing snapshots to JSON serialization. Use Newtonsoft.Json without automatic CLR type construction (`TypeNameHandling.None`); parse request DTO/token data only. Never use `SerializeObject` or `JToken.FromObject` on an arbitrary game object.
|
||||
8. Bound serialized output while producing it, not after creating an unlimited JSON string. Bound snapshot construction too: enforce projection/page limits and reject obviously oversized strings before copying/encoding them. Metadata discovery is shallow and must not execute listed getters.
|
||||
9. Cache successful type/member metadata, not requests or failed arbitrary path strings. Use a bounded cache (for example, at most 1024 entries, then stop adding entries) rather than a new eviction framework. Clear it on server uninitialization. `ReflectionReader` stores the resolved `FieldInfo`/`PropertyInfo` objects in this per-type cache; it must still read live member values for every request instead of caching mutable game state.
|
||||
|
||||
Catch reflection/getter failures at the request boundary and map them to the API errors. Retain diagnostic exceptions in local logs, not response bodies. System methods and generic game-data methods must share envelope/error handling; do not introduce parallel protocol implementations.
|
||||
|
||||
## Migration phases
|
||||
|
||||
Checkmarks describe the completed work below; stated desktop results do not close the separate Unity/LAN gates. Keep evidence for the tested package graph and actual game runtime with the current phase status.
|
||||
|
||||
### M0: prove the in-process compatibility path
|
||||
|
||||
- [x] Build a small `net472` probe with the latest serviced ASP.NET Core 2.3 hosting, managed socket transport, and WebSocket packages. The researched transport/middleware baseline is 2.3.13; resolve compatible current versions for the other components and the protocol dependency instead of assuming all version numbers match.
|
||||
- [x] Inspect and record the selected compile/runtime assets and transitive closure, including the concrete protocol assembly. Check advisories and the upstream support statement, not just the package title or a computed NuGet compatibility list.
|
||||
- [x] Prove that the probe uses managed Kestrel Sockets and the maintained middleware upgrade path, with no fallback to the game's `HttpListener` implementation, Libuv, HTTP.sys, or a hand-written handshake/parser.
|
||||
- [ ] Run the same candidate in actual DSP/Unity 2022 Mono. Record game/Unity versions, architecture, loaded assembly identities/locations, and the WebSocket implementation type. Test both a clean supported installation and coexistence with the normal mod set. **Blocked: DSP was not launched.**
|
||||
- [ ] Verify a real opening handshake, fragmented text with interleaved ping, exact ping/pong payload behavior, a bounded oversized input, and closing/releasing the listener. An advertised huge frame length must not trigger an allocation proportional to that length before the application can enforce its limit. **Desktop checks cover handshake, fragmented round trips, payload limits, and listener release. Interleaved ping/pong and huge advertised lengths remain unverified.**
|
||||
- [ ] Confirm an idle API, startup failure, and normal shutdown do not disturb Ctrl+F8 or the shared feature lifecycle. Verify a port already in use fails softly. **Blocked: DSP.**
|
||||
- [x] Record a go/no-go decision and the exact graph to adopt. If a compatible package asset is missing or an actual Mono API fails, record the concrete failing call/assembly rather than suppressing it.
|
||||
|
||||
Desktop probe (repository root):
|
||||
|
||||
```powershell
|
||||
dotnet build LiveStreamAssist/tools/WebSocketTransportCheck/WebSocketTransportCheck.csproj -c Release
|
||||
& LiveStreamAssist/tools/WebSocketTransportCheck/bin/Release/net472/WebSocketTransportCheck.exe
|
||||
& LiveStreamAssist/tools/WebSocketTransportCheck/bin/Release/net472/WebSocketTransportCheck.exe --regression
|
||||
```
|
||||
|
||||
Observed desktop identities: Kestrel.Core **2.3.13**, Transport.Sockets **2.3.13**, WebSockets middleware **2.3.13**, protocol type `System.Net.WebSockets.ManagedWebSocket` from `System.Net.WebSockets.WebSocketProtocol` **5.1.3**. Microsoft.Extensions.* **8.x** assets selected as `lib/net462`. Newtonsoft.Json **13.0.3**. No Libuv package. The harness references the production project, and all 34 transport/hosting package versions match its lock file. Unity/Mono adoption remains unconfirmed.
|
||||
|
||||
The desktop regression harness loads Unity type metadata but runs on the Windows CLR. Its test-only `App.config` binds `netstandard` to the desktop 2.0 facade; Unity's Mono 2.1 type forwarders are not interchangeable with CLR forwarders. This configuration and the copied test host/game assemblies are not mod package contents and do not establish Mono compatibility.
|
||||
|
||||
Exit condition: the candidate actually starts, exchanges bounded messages, and disposes under the game's runtime using the intended managed assemblies. Desktop-only tests or an unavailable DSP launch leave M0 blocked. Investigate supported in-process alternatives before crossing the fallback boundary.
|
||||
|
||||
### M1: replace the Fleck transport
|
||||
|
||||
- [x] Replace the listener and connection implementation at `WebSocketApiServer.cs` using the M0-approved graph. Keep framework-specific hosting types at this boundary.
|
||||
- [x] Implement explicit endpoint/path handling, bounded pre-upgrade and upgraded connection admission, and a correctly awaited WebSocket connection lifetime.
|
||||
- [x] Implement the single receive loop and bounded complete-message assembly using the standard WebSocket API. Remove all Fleck references, `BoundedHandler`, handler casts/reflection, and `MaxIncomingSocketBytes`.
|
||||
- [x] Coordinate asynchronous host startup/stop with the existing feature owner and cancellation token. Dispose partial startup instances and prevent late callbacks from resurrecting stopped state.
|
||||
- [x] Retain API version `1.0.0`, the existing configuration keys/defaults, seven methods, root providers, reflection policy, game-session identifiers, numeric encoding, and statistics placeholder. Do not add authentication or subscriptions.
|
||||
|
||||
Exit condition: the production request path no longer uses Fleck or a private frame implementation, and the original API requests work through the new host. This does not yet establish all race/resource guarantees.
|
||||
|
||||
### M2: repair completion, accounting, and deadlines
|
||||
|
||||
- [x] Separate detached result production from delivery. No Unity-thread completion path may serialize JSON or enter a socket send. Verify thread affinity rather than assuming an async method automatically moves work to another thread.
|
||||
- [x] Keep request IDs and per-connection/global slots until the response is sent or the connection is canceled. Test success, error, timeout, disconnect, and stop races for exactly-once slot release. **Desktop held-send, overflow, timeout, and disconnect checks pass; in-game transitions remain pending.**
|
||||
- [x] Enforce response-production deadlines on a worker while the Unity pump is intentionally blocked. Do not cancel the receive loop merely because one game-data request times out.
|
||||
- [x] Enforce queued and active-send deadlines, observe failed tasks, and bound close attempts before aborting failed transports. Include the active send in queue/memory accounting.
|
||||
- [x] Put a hard bound on the physical game-work queue and remove/prune canceled entries. Repeated timeouts while the game loop is stopped must not accumulate stale work without limit.
|
||||
- [x] Make response serialization safe under concurrency while preserving the byte cap and existing JSON encoding.
|
||||
- [x] Preserve session-generation checks and invalidate queued old-save work. Already produced/in-transit snapshots remain tagged with the sampling session; never claim they can be recalled.
|
||||
- [x] Retain and rerun the reflection fixture checks. Add focused deterministic checks for these transport-integration defects using held completions/fake work scheduling, not production-only debug endpoints. **Reflection fixtures and the production `--regression` harness pass.**
|
||||
|
||||
Exit condition: a blocked Unity frame does not block system methods or timeout responses; all queues remain bounded; slots and IDs survive until terminal delivery/cancellation; no late success follows a timeout.
|
||||
|
||||
### M3: conformance and game integration
|
||||
|
||||
- [ ] Run a pinned [Autobahn Testsuite][autobahn] configuration in `fuzzingclient` mode against a test-only echo host using the same approved transport packages and configuration path. Use its isolated toolchain image and record the image digest, case results, and justified exclusions. Do not expose an echo method on the production JSON-RPC endpoint. Probe `--echo` exists; Autobahn was not run.
|
||||
- [ ] Test opening-handshake validation separately: HTTP method/version, required Upgrade/Connection tokens, WebSocket version/key, invalid paths, capacity rejection, and oversized or stalled headers. Autobahn's documented opening-handshake coverage is incomplete.
|
||||
- [ ] Cover masking direction, RSV/reserved opcodes, continuation ordering, interleaved control frames, control-frame FIN/size rules, invalid length encodings, UTF-8 across fragments, close status/reason validation, and ping/pong payload equality.
|
||||
- [ ] Test application limits separately with the real v1 settings: exact boundary and boundary-plus-one payloads, byte-by-byte fragmentation, multiple messages in one socket read, interleaved pings, and huge advertised lengths. Do not mistake an Autobahn echo expectation for a requirement to accept application payloads above 64 KiB.
|
||||
- [ ] Use a raw-socket/fuzzing test tool for invalid frames; `ClientWebSocket` intentionally does not generate many malformed frame cases. Keep malformed-frame generation in test tooling, not production transport code.
|
||||
- [x] Repair the PowerShell smoke harness: per-operation cancellation, response-ID matching, optional-field checks under strict mode, buffer/socket cleanup, and HTTP handshake-rejection handling. Move duplicate-outstanding-ID checks to a held-request harness so a legitimately completed first request does not create a timing-dependent failure.
|
||||
- [ ] Run no-save and active-save API checks, then real-game pause/text-input, loading, space travel, save switch/reload, and Ctrl+F8 regressions. Run a LAN client from a second machine and a current browser/OBS browser source. **Blocked: DSP.**
|
||||
- [ ] Exercise multiple clients and slow/non-reading consumers, blocked game work, malformed input followed by valid input, port conflicts, repeated start/stop, and shutdown during startup/read/send.
|
||||
|
||||
Desktop production checks pass for fragmented JSON, binary/invalid-UTF-8/oversized rejection (`1003`/`1007`/`1009`), duplicate IDs (`1008`), shutdown (`1001`), blocked-pump timeout delivery, stalled fragments, occupied ports, and startup/stop races. Full framing conformance, multi-client stress, and actual game/LAN scenarios remain open.
|
||||
|
||||
Autobahn proves the covered transport behavior, not the reflection API or Unity scheduling. Compression/other unsupported extensions and application size limits must be accounted for explicitly. A partial run, waived core-protocol failure, or test against a different runtime/package build is not a full pass. Seek an upstream fix for a required protocol defect; do not reconstruct a private frame layer to turn the report green.
|
||||
|
||||
Exit condition: the applicable RFC 6455 cases and application/resource tests pass with recorded evidence, and the actual Unity/Mono plus LAN integration matrix passes. No unmeasured FPS, latency, or future-standard guarantee is implied.
|
||||
|
||||
### M4: packaging and maintained delivery
|
||||
|
||||
- [x] Replace the two-DLL Fleck packaging list with the audited runtime closure of the approved host, while retaining project-local packaging customization.
|
||||
- [x] Pin the approved package versions and record the resolved graph, selected TFMs, and source/support references. Use a project-local package lock and locked restore for repeatable validation once the graph is approved; do not change dependency policy for unrelated mods.
|
||||
- [x] Fail packaging when a required runtime dependency is absent. Do not silently drop mandatory files behind `Exists` conditions, copy the entire build output, or ship reference/game/framework assemblies.
|
||||
- [x] Verify the final assembly references and ZIP contain no Fleck dependency or leftover handler shim. Remove stale Fleck files only from LiveStreamAssist-owned staging/install locations; other mods may legitimately use their own copies.
|
||||
- [ ] Test the packaged mod on a clean installation containing the declared BepInEx/UXAssist dependencies, then with the ordinary mod set. Do not depend on a developer machine's shared .NET runtime or incidental plugin DLLs. **Blocked: DSP.**
|
||||
- [x] Update API/README status only after the documented gates pass. Record the approved graph, exact probe/conformance commands, runtime evidence, and any remaining blocker in this document. Keep `AGENTS.md` as a link only. **Status records remaining Unity/LAN blockers; do not treat this as a full gate pass.**
|
||||
- [ ] Run the narrow build/fixture/smoke checks and `git diff --check`; review the diff for unrelated changes. **Release builds, fixtures, desktop transport checks, and ZipMod pass. The PowerShell script parses successfully; its game/LAN run is still pending.**
|
||||
|
||||
Use the existing project-local `BeforeTargets="ZipMod"` extension point and `_PackRootFiles`, driven by an audited dependency list or filtered resolved-runtime items. Include required supporting implementations such as the approved protocol/buffer packages, while excluding game references, Unity/BepInEx assemblies, and UXAssist itself. Record why each packaged assembly is needed; a `System.*` filename alone neither includes nor excludes it.
|
||||
|
||||
### Maintenance policy
|
||||
|
||||
- Review upstream support, servicing releases, and package advisories before a mod release and when an advisory affects shipped dependencies. Old release dates alone do not prove abandonment, and frequent releases alone do not prove conformance.
|
||||
- Review updates within the supported compatibility line. Do not automatically upgrade package majors or switch to a `net6.0+` asset because it has a higher version number. Avoid floating transport versions in a released build.
|
||||
- For every runtime-dependency update, inspect the graph/TFM diff, run the transport/protocol regressions and Unity smoke tests, and retain the conformance configuration/results. Rerun the wider game/LAN matrix when runtime behavior or hosting changes.
|
||||
- Prefer upstream fixes and serviced packages over local protocol patches. Track a discovered defect with a minimal reproducer and regression case. If a necessary fix cannot be obtained on a supported compatible line, reopen the selection decision instead of permanently freezing an unmaintained fork.
|
||||
- Keep compiler/audit policy intact. Document an actual compatibility limitation rather than suppressing it to obtain a green build. This process reduces maintenance risk; it does not promise bug-free dependencies.
|
||||
|
||||
## Fallback boundary
|
||||
|
||||
The user requested in-process investigation first. A standalone gateway becomes an option only after recording concrete failures of the preferred route and reasonable maintained in-process alternatives: unavailable Mono APIs, an unresolvable assembly-identity conflict, required protocol defects without a supported fix, or loss of upstream support. Missing access to DSP, a failed search, or extra package DLLs is not such evidence.
|
||||
|
||||
If this boundary is reached, revise the architecture before implementation: a supported .NET LTS process can own Kestrel/WebSockets while the Unity `net472` mod continues to own reflection and main-thread snapshots. The public API should remain compatible. Specify bounded local IPC, connection/request routing, deadlines, session invalidation, startup failure, parent/child exit cleanup, packaging, and runtime servicing in that revision. Modern .NET assemblies must remain in the separate process, never loaded into Unity. Do not scaffold or ship this fallback alongside a working in-process host.
|
||||
|
||||
## Validation commands and acceptance matrix
|
||||
|
||||
Run commands from the repository root. These target the existing mod and tools; their inclusion does not mean the replacement or runtime checks have passed. When adding the M0 probe and M3 conformance harness, record their exact build/run commands, test configuration path, and pinned toolchain version here.
|
||||
|
||||
Before the integration commands, install the built mod and its required DLLs, set `WebSocketApi.Enabled` to true, and restart DSP. Run no-save checks at the main menu, then open a save for `-RequireGame`. For the LAN check, configure the actual LAN bind address or `0.0.0.0` before restarting and connect from the second machine to the server's real LAN address, not to `0.0.0.0`.
|
||||
|
||||
```powershell
|
||||
dotnet restore LiveStreamAssist/LiveStreamAssist.csproj --locked-mode
|
||||
dotnet build LiveStreamAssist/LiveStreamAssist.csproj -c Release --no-restore
|
||||
dotnet build LiveStreamAssist/tools/WebSocketTransportCheck/WebSocketTransportCheck.csproj -c Release
|
||||
& LiveStreamAssist/tools/WebSocketTransportCheck/bin/Release/net472/WebSocketTransportCheck.exe
|
||||
& LiveStreamAssist/tools/WebSocketTransportCheck/bin/Release/net472/WebSocketTransportCheck.exe --regression
|
||||
dotnet build LiveStreamAssist/tools/ReflectionReaderCheck/ReflectionReaderCheck.csproj -c Release
|
||||
& LiveStreamAssist/tools/ReflectionReaderCheck/bin/Release/net472/ReflectionReaderCheck.exe
|
||||
pwsh -NoProfile -File LiveStreamAssist/tools/Test-WebSocketApi.ps1 -ServerUri ws://127.0.0.1:18080/api/v1
|
||||
pwsh -NoProfile -File LiveStreamAssist/tools/Test-WebSocketApi.ps1 -ServerUri ws://127.0.0.1:18080/api/v1 -RequireGame
|
||||
dotnet build LiveStreamAssist/LiveStreamAssist.csproj -t:ZipMod -c Release --no-restore
|
||||
git diff --check
|
||||
```
|
||||
|
||||
The fixture tools copy Unity metadata/facades from the installed game; the transport harness also copies BepInEx for desktop type loading. These copies are test-only. Use locked restore for repeatable validation; dependency updates require an explicit graph review and lock update. The packaged ZIP contains 49 declared runtime dependencies plus the plugin, manifest, README, and icon. Neither tool binaries/configuration nor game/core-framework/host assemblies belong in it.
|
||||
|
||||
The smoke script must accept those parameters, require no WebSocket client package, close its sockets in cleanup, and exit nonzero when an assertion fails. `-RequireGame` fails clearly if a save is not ready; no-save mode skips only game-dependent assertions, not protocol/system checks. Repeat the relevant script from a second machine with the actual LAN address. A loopback-only run does not establish LAN acceptance.
|
||||
|
||||
Do not use game-mutating debug endpoints to make checks pass. If a particular research ID is needed, discover it from current research, the research queue, or known game data; do not assume the API example's `1001` is always active.
|
||||
|
||||
| Scenario | Required observation |
|
||||
| --- | --- |
|
||||
| Unity/Mono dependency loading | The reviewed runtime assets load from the intended locations without missing APIs, assembly conflicts, or framework replacement. |
|
||||
| Default configuration | API disabled, no listener, existing assist still works. |
|
||||
| Opening handshake / RFC 6455 | Valid clients connect; invalid handshakes and framing fail as specified; applicable conformance cases pass with recorded results. |
|
||||
| Preload / main menu | Ping works; version readiness is explicit; menu demo is not an available player root. |
|
||||
| Active save | Roots, metadata, research reads, projections, and pages are correct. |
|
||||
| Pause / text input | Data reads still complete through the Unity context. |
|
||||
| Space travel | Absent local roots produce `ROOT_UNAVAILABLE`, not a crash or false whole-game failure. |
|
||||
| Large integer fixture | `Int64`/`UInt64` values beyond JavaScript's safe range round-trip as decimal strings. |
|
||||
| Forbidden getter / infrastructure | Every resolver path enforces the same policy without invoking the denied code. |
|
||||
| Cyclic object fixture | Shallow summaries and bounded explicit paths terminate without recursive graph export. |
|
||||
| Save switch / reload | Old queued requests fail; new queries carry a new session identifier. |
|
||||
| Invalid / oversized input | Documented JSON error or WebSocket close; no unlimited fragment buffer. |
|
||||
| Fragmentation / control frames | Payload accounting survives interleaved pings and TCP chunking; huge declared lengths cannot force proportional allocation. |
|
||||
| Multiple clients / slow consumer | Bounded admission and output; normal clients recover after pressure is removed. |
|
||||
| Blocked Unity pump | System methods and production deadlines still work; stale game-work entries remain bounded. |
|
||||
| Active send / ID reuse | IDs and slots stay reserved through delivery; send failure or timeout aborts without a second response or leaked capacity. |
|
||||
| Timeout / disconnect / stop | No double completion, leaked slots, stale game references, or Unity-thread wait deadlock. |
|
||||
| Startup / shutdown races | Occupied-port failure is isolated; stopping during startup leaves no orphan listener or late owner callbacks. |
|
||||
| Clean installation | All required third-party DLLs resolve without an incidental mod installation. |
|
||||
| Existing statistics assist | Ctrl+F8 and automatic tab switching retain their behavior. |
|
||||
|
||||
Normal validation remains the narrow LiveStreamAssist build, with warnings treated as errors under the repository policy. Report unrelated pre-existing failures instead of changing other mods. API-only functionality does not require save-data persistence, a preloader, or changes to the UXAssist public API.
|
||||
|
||||
## Deferred work
|
||||
|
||||
`system.stats` deliberately stops at the placeholder. When statistics are requested, define a concrete schema before enabling `api.stats`; likely candidates are current connections, completed/failed requests, bytes sent/received, and durations in milliseconds since server start. V1 admission counters are resource controls, not an excuse to expose an undocumented metrics schema.
|
||||
|
||||
Subscriptions, writes, method invocation, authentication, additional root catalogs, aggregated gameplay endpoints, dictionary enumeration, and recursive object export require separate scope decisions. Do not implement extension scaffolding for them now.
|
||||
|
||||
[aspnet-support]: https://dotnet.microsoft.com/en-us/platform/support/policy/aspnet/2.3-packages
|
||||
[aspnet-advisory]: https://devblogs.microsoft.com/dotnet/servicing-release-advisory-aspnetcore-23/
|
||||
[websockets-package]: https://www.nuget.org/packages/Microsoft.AspNetCore.WebSockets/2.3.13
|
||||
[sockets-package]: https://www.nuget.org/packages/Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets/2.3.13
|
||||
[middleware-source]: https://github.com/dotnet/aspnetcore/blob/1db07eda0330bfc87e383d1d65a50e9f0d43c6e9/src/Middleware/WebSockets/src/WebSocketMiddleware.cs
|
||||
[sockets-source]: https://github.com/dotnet/aspnetcore/blob/1db07eda0330bfc87e383d1d65a50e9f0d43c6e9/src/Servers/Kestrel/Transport.Sockets/src/SocketTransportFactory.cs
|
||||
[protocol-package]: https://www.nuget.org/packages/System.Net.WebSockets.WebSocketProtocol
|
||||
[fleck-source]: https://github.com/statianzo/Fleck/commit/45672e0781974bb04dbad1b94320756a33c60a6d
|
||||
[touch-frame]: https://github.com/RRQM/TouchSocket/blob/bf377c2a1363576e8b0ecb0924e9718f0093f0dc/src/TouchSocket.Http/WebSockets/Common/WSDataFrame.cs
|
||||
[touch-project]: https://github.com/RRQM/TouchSocket/blob/bf377c2a1363576e8b0ecb0924e9718f0093f0dc/src/TouchSocket.Http/TouchSocket.Http.csproj
|
||||
[touch-package]: https://www.nuget.org/packages/TouchSocket.Http/4.3.7
|
||||
[supersocket-package]: https://www.nuget.org/packages/SuperSocket.WebSocket.Server/2.1.0
|
||||
[unity-profile]: https://docs.unity3d.com/2022.3/Documentation/Manual/dotnetProfileSupport.html
|
||||
[autobahn]: https://github.com/crossbario/autobahn-testsuite
|
||||
@@ -0,0 +1,346 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>直播数据面板</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
html, body { margin: 0; background: transparent; color: #eef3f8; font: 15px/1.5 "Segoe UI", "Microsoft YaHei", system-ui, sans-serif; }
|
||||
[hidden] { display: none; }
|
||||
.panel { display: flex; flex-direction: column; gap: 10px; width: max-content; min-width: 320px; max-width: 640px; }
|
||||
.card { padding: 10px 14px 12px; background: rgba(9, 14, 22, 0.78); border: 1px solid rgba(255, 255, 255, 0.07); border-radius: 10px; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.25); }
|
||||
h1 { display: flex; align-items: baseline; justify-content: space-between; margin: 0 0 8px; font-size: 12px; font-weight: 600; letter-spacing: 0.14em; color: #9db1c5; }
|
||||
h1 .unit { font-size: 11px; font-weight: 500; letter-spacing: normal; color: #6d8296; }
|
||||
table { border-collapse: collapse; }
|
||||
td { padding: 3px 0 3px 14px; white-space: nowrap; }
|
||||
td:first-child { padding-left: 0; }
|
||||
tr.material > td { border-top: 1px solid rgba(255, 255, 255, 0.06); }
|
||||
tr:first-child > td { border-top: 0; }
|
||||
.itemCell { padding-right: 10px; }
|
||||
.item { display: flex; align-items: center; gap: 8px; font-weight: 600; }
|
||||
.icon { width: 32px; height: 32px; border-radius: 5px; flex: none; }
|
||||
.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.lbl { margin-right: 6px; font-size: 12px; color: #7f93a6; }
|
||||
.val { font-weight: 600; }
|
||||
.val.prod { color: #71de8d; }
|
||||
.val.cons { color: #ff8a70; }
|
||||
.val.ref { color: #aebfce; font-weight: 500; }
|
||||
.tech { display: flex; align-items: center; gap: 8px; padding: 3px 0; }
|
||||
.tech .name { flex: 1; }
|
||||
.tech .level { font-weight: 600; font-variant-numeric: tabular-nums; color: #bfe3ff; }
|
||||
.tech .level.done { color: #71de8d; }
|
||||
.research { display: flex; align-items: center; gap: 10px; }
|
||||
.research .name { font-size: 17px; font-weight: 650; }
|
||||
.progressRow { display: flex; align-items: center; gap: 10px; margin-top: 8px; }
|
||||
.bar { flex: 1; height: 8px; overflow: hidden; border-radius: 4px; background: rgba(255, 255, 255, 0.12); }
|
||||
.bar > div { height: 100%; width: 0; border-radius: 4px; background: #58b7d8; }
|
||||
.pct { min-width: 56px; text-align: right; font-weight: 600; font-variant-numeric: tabular-nums; }
|
||||
.hash { margin-top: 4px; font-size: 12px; color: #7f93a6; font-variant-numeric: tabular-nums; }
|
||||
.bigValue { font-size: 22px; font-weight: 700; font-variant-numeric: tabular-nums; }
|
||||
.cluster { display: flex; align-items: baseline; gap: 8px; }
|
||||
.cluster .value { font-size: 16px; font-weight: 650; font-variant-numeric: tabular-nums; }
|
||||
.status { margin-top: 8px; font-size: 12px; color: #7f93a6; }
|
||||
.status.error { color: #ff8a70; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="panel" id="panel"></div>
|
||||
<div class="status" id="status">连接中…</div>
|
||||
<script src="../js/generated/dsp-text.js"></script>
|
||||
<script src="../js/generated/dsp-icons.js"></script>
|
||||
<script src="../js/livestream-assist.js"></script>
|
||||
<script>
|
||||
const params = new URLSearchParams(location.search);
|
||||
const statusEl = document.getElementById("status");
|
||||
const panel = document.getElementById("panel");
|
||||
const POLL_INTERVAL = 2000;
|
||||
const WINDOW_LABELS = { "1min": "每分钟", "10min": "10分钟", "1hour": "1小时", "10hour": "10小时", "100hour": "100小时", total: "累计" };
|
||||
const STATUS_TEXT = { connecting: "连接中…", connected: "已连接", disconnected: "已断开" };
|
||||
|
||||
let pollTimer;
|
||||
let pollGeneration = 0;
|
||||
let validatedInfo = null;
|
||||
|
||||
function el(tag, className, parent) {
|
||||
const element = document.createElement(tag);
|
||||
if (className) element.className = className;
|
||||
if (parent) parent.appendChild(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
function setIcon(img, url) {
|
||||
img.src = url || "";
|
||||
img.hidden = !url;
|
||||
}
|
||||
|
||||
function setStatus(message, isError) {
|
||||
statusEl.textContent = message;
|
||||
statusEl.classList.toggle("error", !!isError);
|
||||
}
|
||||
|
||||
function parseIdList(raw, label) {
|
||||
if (!raw) return [];
|
||||
const ids = [];
|
||||
for (const token of raw.split(/[,,\s]+/)) {
|
||||
if (!token) continue;
|
||||
const id = Number(token);
|
||||
if (!Number.isInteger(id) || id <= 0) throw new Error("无效的" + label + "ID: " + token);
|
||||
ids.push(id);
|
||||
}
|
||||
return Array.from(new Set(ids));
|
||||
}
|
||||
|
||||
function flagEnabled(name) {
|
||||
const value = params.get(name);
|
||||
return value == null || value === "" || !/^(0|false)$/i.test(value);
|
||||
}
|
||||
|
||||
function buildClusterSection() {
|
||||
const section = el("section", "card cluster", panel);
|
||||
const label = el("span", "lbl", section);
|
||||
label.textContent = "星区";
|
||||
const value = el("span", "value", section);
|
||||
value.id = "clusterString";
|
||||
value.textContent = "—";
|
||||
return { value };
|
||||
}
|
||||
|
||||
function buildItemsSection(itemIds, windowName) {
|
||||
const section = el("section", "card", panel);
|
||||
const title = el("h1", "", section);
|
||||
title.textContent = "材料生产 / 消耗";
|
||||
const unit = el("span", "unit", title);
|
||||
unit.textContent = WINDOW_LABELS[windowName] + (windowName === "total" ? "(个)" : "(个/分钟)");
|
||||
const table = el("table", "", section);
|
||||
const rows = {};
|
||||
for (const id of itemIds) {
|
||||
const prodRow = el("tr", "material", table);
|
||||
const itemCell = el("td", "itemCell", prodRow);
|
||||
itemCell.rowSpan = 2;
|
||||
const item = el("div", "item", itemCell);
|
||||
const img = el("img", "icon", item);
|
||||
img.alt = "";
|
||||
setIcon(img, icons.itemIcon(id));
|
||||
const name = el("span", "", item);
|
||||
name.textContent = text.itemName(id) || ("物品 " + id);
|
||||
const refRow = el("tr", "", table);
|
||||
function valueCell(row, label, valueClass) {
|
||||
const cell = el("td", "num", row);
|
||||
const lbl = el("span", "lbl", cell);
|
||||
lbl.textContent = label;
|
||||
const val = el("span", "val " + valueClass, cell);
|
||||
val.textContent = "—";
|
||||
return val;
|
||||
}
|
||||
rows[id] = {
|
||||
prod: valueCell(prodRow, "生产", "prod"),
|
||||
prodRef: valueCell(prodRow, "理论生产", "ref"),
|
||||
cons: valueCell(refRow, "消耗", "cons"),
|
||||
consRef: valueCell(refRow, "理论消耗", "ref")
|
||||
};
|
||||
rows[id].prod.id = "item-" + id + "-prod";
|
||||
rows[id].prodRef.id = "item-" + id + "-prodRef";
|
||||
rows[id].cons.id = "item-" + id + "-cons";
|
||||
rows[id].consRef.id = "item-" + id + "-consRef";
|
||||
}
|
||||
return { rows };
|
||||
}
|
||||
|
||||
function buildTechsSection(techIds) {
|
||||
const section = el("section", "card", panel);
|
||||
const title = el("h1", "", section);
|
||||
title.textContent = "科技等级";
|
||||
const rows = {};
|
||||
for (const id of techIds) {
|
||||
const row = el("div", "tech", section);
|
||||
const img = el("img", "icon", row);
|
||||
img.alt = "";
|
||||
setIcon(img, icons.techIcon(id));
|
||||
const name = el("span", "name", row);
|
||||
name.textContent = text.techName(id) || ("科技 " + id);
|
||||
const level = el("span", "level", row);
|
||||
level.id = "tech-" + id;
|
||||
level.textContent = "—";
|
||||
rows[id] = level;
|
||||
}
|
||||
return { rows };
|
||||
}
|
||||
|
||||
function buildResearchSection() {
|
||||
const section = el("section", "card", panel);
|
||||
const title = el("h1", "", section);
|
||||
title.textContent = "当前研究";
|
||||
const head = el("div", "research", section);
|
||||
const img = el("img", "icon", head);
|
||||
img.alt = "";
|
||||
const name = el("span", "name", head);
|
||||
name.id = "researchName";
|
||||
name.textContent = "—";
|
||||
const progressRow = el("div", "progressRow", section);
|
||||
const bar = el("div", "bar", progressRow);
|
||||
const fill = el("div", "", bar);
|
||||
const pct = el("span", "pct", progressRow);
|
||||
pct.id = "researchPct";
|
||||
const hash = el("div", "hash", section);
|
||||
hash.id = "researchHash";
|
||||
return { img, name, fill, pct, hash };
|
||||
}
|
||||
|
||||
function buildDysonSection() {
|
||||
const section = el("section", "card", panel);
|
||||
const title = el("h1", "", section);
|
||||
title.textContent = "戴森球发电量";
|
||||
const value = el("div", "bigValue", section);
|
||||
value.id = "dysonWatts";
|
||||
value.textContent = "—";
|
||||
return { value };
|
||||
}
|
||||
|
||||
const windowName = params.get("window") || "1min";
|
||||
const hasSectionParams = params.has("items") || params.has("techs") || params.has("research") || params.has("dyson");
|
||||
const showResearch = params.has("research") ? flagEnabled("research") : !hasSectionParams;
|
||||
const showDyson = params.has("dyson") ? flagEnabled("dyson") : !hasSectionParams;
|
||||
const sections = {};
|
||||
|
||||
let itemIds = [];
|
||||
let techIds = [];
|
||||
let text;
|
||||
let icons;
|
||||
let client;
|
||||
let query;
|
||||
let fatal = null;
|
||||
try {
|
||||
if (!Object.prototype.hasOwnProperty.call(LiveStreamAssist.RATE_WINDOWS, windowName)) {
|
||||
throw new Error("未知的统计窗口: " + windowName);
|
||||
}
|
||||
itemIds = parseIdList(params.get("items"), "材料");
|
||||
techIds = parseIdList(params.get("techs"), "科技");
|
||||
text = LiveStreamAssist.GameText.fromGenerated({ language: params.get("lang") || "zh-CN" });
|
||||
icons = LiveStreamAssist.GameIcons.fromGenerated();
|
||||
sections.cluster = buildClusterSection();
|
||||
if (itemIds.length) sections.items = buildItemsSection(itemIds, windowName);
|
||||
if (techIds.length) sections.techs = buildTechsSection(techIds);
|
||||
if (showResearch) sections.research = buildResearchSection();
|
||||
if (showDyson) sections.dyson = buildDysonSection();
|
||||
client = new LiveStreamAssist.Client({
|
||||
url: params.get("ws") || "ws://127.0.0.1:18080/api/v1",
|
||||
onStatus: function (status) { if (STATUS_TEXT[status]) setStatus(STATUS_TEXT[status]); }
|
||||
});
|
||||
query = new LiveStreamAssist.GameQuery(client);
|
||||
} catch (error) {
|
||||
fatal = error;
|
||||
setStatus("初始化失败: " + (error.message || error), true);
|
||||
}
|
||||
|
||||
function formatActual(value, perMinute) {
|
||||
return perMinute ? text.formatRate(value) : text.formatKmg(value);
|
||||
}
|
||||
|
||||
function renderCluster(cluster) {
|
||||
sections.cluster.value.textContent = cluster.clusterString || "—";
|
||||
}
|
||||
|
||||
function renderRates(rates) {
|
||||
for (const row of rates) {
|
||||
const cells = sections.items.rows[row.itemId];
|
||||
if (!cells) continue;
|
||||
cells.prod.textContent = formatActual(row.production, row.perMinute);
|
||||
cells.cons.textContent = formatActual(row.consumption, row.perMinute);
|
||||
cells.prodRef.textContent = text.formatRate(row.theoreticalProduction);
|
||||
cells.consRef.textContent = text.formatRate(row.theoreticalConsumption);
|
||||
}
|
||||
}
|
||||
|
||||
function renderTechs(states) {
|
||||
for (const state of states) {
|
||||
const level = sections.techs.rows[state.techId];
|
||||
if (!level) continue;
|
||||
if (state.maxLevel > 0) {
|
||||
level.textContent = state.curLevel + "/" + state.maxLevel;
|
||||
} else {
|
||||
level.textContent = state.unlocked ? "已解锁" : "未解锁";
|
||||
}
|
||||
level.classList.toggle("done", !!state.unlocked);
|
||||
}
|
||||
}
|
||||
|
||||
function renderResearch(research) {
|
||||
const section = sections.research;
|
||||
if (!research || !research.active) {
|
||||
section.img.hidden = true;
|
||||
section.name.textContent = "暂无进行中的研究";
|
||||
section.fill.style.width = "0%";
|
||||
section.pct.textContent = "";
|
||||
section.hash.textContent = "";
|
||||
return;
|
||||
}
|
||||
setIcon(section.img, icons.techIcon(research.techId));
|
||||
section.name.textContent = text.techDisplayName(research.techId, research.curLevel) || ("科技 " + research.techId);
|
||||
const percent = Math.max(0, Math.min(100, research.progressPercent || 0));
|
||||
section.fill.style.width = percent + "%";
|
||||
section.pct.textContent = percent.toFixed(1) + "%";
|
||||
section.hash.textContent = text.formatKmg(research.hashUploaded) + " / " + text.formatKmg(research.hashNeeded) + " 哈希";
|
||||
}
|
||||
|
||||
function renderDyson(dyson) {
|
||||
sections.dyson.value.textContent = text.formatPower(dyson.watts);
|
||||
}
|
||||
|
||||
function errorStatus(error) {
|
||||
if (error && error.kind === "GAME_NOT_READY") return "等待游戏就绪…";
|
||||
if (error && error.kind === "SESSION_CHANGED") return "存档已切换,正在重新同步…";
|
||||
return "错误: " + ((error && (error.kind || error.message)) || error);
|
||||
}
|
||||
|
||||
async function tick(generation) {
|
||||
const jobs = [];
|
||||
if (sections.cluster) jobs.push(query.getClusterString());
|
||||
if (sections.items) jobs.push(query.getItemRates(itemIds, { window: windowName }));
|
||||
if (sections.techs) jobs.push(Promise.all(techIds.map(id => query.getTechState(id))));
|
||||
if (sections.research) jobs.push(query.getCurrentResearch());
|
||||
if (sections.dyson) jobs.push(query.getDysonPower());
|
||||
const results = await Promise.allSettled(jobs);
|
||||
if (generation !== pollGeneration) return;
|
||||
const failed = results.find(result => result.status === "rejected");
|
||||
if (failed) throw failed.reason;
|
||||
let index = 0;
|
||||
if (sections.cluster) renderCluster(results[index++].value);
|
||||
if (sections.items) renderRates(results[index++].value);
|
||||
if (sections.techs) renderTechs(results[index++].value);
|
||||
if (sections.research) renderResearch(results[index++].value);
|
||||
if (sections.dyson) renderDyson(results[index++].value);
|
||||
}
|
||||
|
||||
async function poll(generation) {
|
||||
if (generation !== pollGeneration || fatal) return;
|
||||
try {
|
||||
await client.connect(client.url);
|
||||
if (generation !== pollGeneration) return;
|
||||
if (!client.infoSnapshot || validatedInfo !== client.infoSnapshot) {
|
||||
const info = await client.systemInfo();
|
||||
if (generation !== pollGeneration) return;
|
||||
await client.validate({ apiMajor: 1, requiredCapabilities: ["reflection.read"] });
|
||||
if (generation !== pollGeneration) return;
|
||||
validatedInfo = info;
|
||||
}
|
||||
await tick(generation);
|
||||
if (generation === pollGeneration) setStatus("已连接");
|
||||
} catch (error) {
|
||||
if (generation === pollGeneration) setStatus(errorStatus(error), true);
|
||||
} finally {
|
||||
if (generation === pollGeneration) pollTimer = setTimeout(function () { poll(generation); }, POLL_INTERVAL);
|
||||
}
|
||||
}
|
||||
|
||||
function stop() {
|
||||
pollGeneration += 1;
|
||||
clearTimeout(pollTimer);
|
||||
if (client) client.close();
|
||||
validatedInfo = null;
|
||||
}
|
||||
|
||||
addEventListener("pagehide", stop);
|
||||
if (!fatal) poll(pollGeneration);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,117 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>LiveStreamAssist research</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
html, body { margin: 0; background: transparent; font: 18px/1.4 system-ui, sans-serif; color: #f2f5f8; }
|
||||
.card {
|
||||
min-width: 320px; max-width: 420px; padding: 16px 18px;
|
||||
background: rgba(12, 18, 28, 0.72); border-radius: 10px;
|
||||
}
|
||||
.label { opacity: 0.65; font-size: 12px; letter-spacing: 0.08em; text-transform: uppercase; }
|
||||
.title { margin: 4px 0 10px; font-size: 22px; font-weight: 650; }
|
||||
.bar { height: 10px; background: #1d2a3c; border-radius: 999px; overflow: hidden; }
|
||||
.fill { height: 100%; width: 0; background: #3d9cff; }
|
||||
.meta { margin-top: 8px; font-variant-numeric: tabular-nums; font-size: 14px; opacity: 0.9; }
|
||||
.status { margin-top: 8px; font-size: 13px; opacity: 0.7; }
|
||||
input, select {
|
||||
width: 100%; margin: 0 0 8px; box-sizing: border-box; padding: 6px 8px;
|
||||
border: 0; border-radius: 6px; background: #1d2a3c; color: inherit;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<input id="url" value="ws://127.0.0.1:18080/api/v1">
|
||||
<select id="lang">
|
||||
<option value="1033">English</option>
|
||||
<option value="2052">简体中文</option>
|
||||
<option value="1036">Français</option>
|
||||
<option value="1031">Deutsch</option>
|
||||
<option value="1041">日本語</option>
|
||||
</select>
|
||||
<div class="label">Current research</div>
|
||||
<div class="title" id="title">Connecting…</div>
|
||||
<div class="bar"><div class="fill" id="fill"></div></div>
|
||||
<div class="meta" id="meta"></div>
|
||||
<div class="status" id="status"></div>
|
||||
</div>
|
||||
<script src="../js/generated/dsp-text.js"></script>
|
||||
<script src="../js/livestream-assist.js"></script>
|
||||
<script>
|
||||
const qs = new URLSearchParams(location.search);
|
||||
const urlInput = document.getElementById("url");
|
||||
const langInput = document.getElementById("lang");
|
||||
const titleEl = document.getElementById("title");
|
||||
const fillEl = document.getElementById("fill");
|
||||
const metaEl = document.getElementById("meta");
|
||||
const statusEl = document.getElementById("status");
|
||||
urlInput.value = qs.get("ws") || urlInput.value;
|
||||
|
||||
const text = LiveStreamAssist.GameText.fromGenerated({ language: qs.get("lang") || langInput.value });
|
||||
langInput.value = String(text.lcid);
|
||||
if (!langInput.value) { langInput.value = "1033"; text.setLanguage(1033); }
|
||||
const client = new LiveStreamAssist.Client({
|
||||
url: urlInput.value,
|
||||
onStatus: function (status) { statusEl.textContent = status; }
|
||||
});
|
||||
const query = new LiveStreamAssist.GameQuery(client);
|
||||
let pollTimer;
|
||||
let pollGeneration = 0;
|
||||
let validatedInfo = null;
|
||||
|
||||
langInput.onchange = function () { text.setLanguage(langInput.value); };
|
||||
|
||||
async function tick(generation) {
|
||||
const research = await query.getCurrentResearch();
|
||||
if (generation !== pollGeneration) return;
|
||||
if (!research.active) {
|
||||
titleEl.textContent = "No active research";
|
||||
fillEl.style.width = "0%";
|
||||
metaEl.textContent = "";
|
||||
return;
|
||||
}
|
||||
const percentage = research.progressPercent || 0;
|
||||
titleEl.textContent = text.techDisplayName(research.techId, research.curLevel) || ("Tech " + research.techId);
|
||||
fillEl.style.width = Math.max(0, Math.min(100, percentage)).toFixed(2) + "%";
|
||||
metaEl.textContent = text.formatKmg(research.hashUploaded) + " / " + text.formatKmg(research.hashNeeded) + " (" + percentage.toFixed(1) + "%)";
|
||||
}
|
||||
|
||||
async function poll(generation) {
|
||||
if (generation !== pollGeneration) return;
|
||||
try {
|
||||
await client.connect(urlInput.value);
|
||||
if (generation !== pollGeneration) return;
|
||||
if (!client.infoSnapshot || validatedInfo !== client.infoSnapshot) {
|
||||
const info = await client.systemInfo();
|
||||
if (generation !== pollGeneration) return;
|
||||
await client.validate({ apiMajor: 1, requiredCapabilities: ["reflection.read"] });
|
||||
if (generation !== pollGeneration) return;
|
||||
validatedInfo = info;
|
||||
}
|
||||
await tick(generation);
|
||||
if (generation === pollGeneration) statusEl.textContent = "connected";
|
||||
} catch (error) {
|
||||
if (generation === pollGeneration) statusEl.textContent = error.kind || error.message;
|
||||
} finally {
|
||||
if (generation === pollGeneration) pollTimer = setTimeout(function () { poll(generation); }, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
function stop() {
|
||||
pollGeneration += 1;
|
||||
clearTimeout(pollTimer);
|
||||
client.close();
|
||||
validatedInfo = null;
|
||||
}
|
||||
|
||||
function start() { stop(); poll(pollGeneration); }
|
||||
|
||||
urlInput.onchange = start;
|
||||
addEventListener("pagehide", stop);
|
||||
start();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,134 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>LiveStreamAssist stats</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
html, body { margin: 0; background: transparent; font: 16px/1.4 system-ui, sans-serif; color: #f2f5f8; }
|
||||
.card {
|
||||
min-width: 360px; max-width: 520px; padding: 16px 18px;
|
||||
background: rgba(12, 18, 28, 0.72); border-radius: 10px;
|
||||
}
|
||||
.row { display: flex; justify-content: space-between; gap: 12px; margin: 6px 0; font-variant-numeric: tabular-nums; }
|
||||
.label { opacity: 0.65; }
|
||||
h1 { margin: 0 0 8px; font-size: 13px; letter-spacing: 0.08em; text-transform: uppercase; opacity: 0.7; font-weight: 600; }
|
||||
h2 { margin: 14px 0 6px; font-size: 18px; font-weight: 650; }
|
||||
input, select {
|
||||
width: 100%; margin: 0 0 8px; box-sizing: border-box; padding: 6px 8px;
|
||||
border: 0; border-radius: 6px; background: #1d2a3c; color: inherit;
|
||||
}
|
||||
.status { margin-top: 10px; font-size: 13px; opacity: 0.7; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<input id="url" value="ws://127.0.0.1:18080/api/v1">
|
||||
<select id="lang">
|
||||
<option value="1033">English</option>
|
||||
<option value="2052">简体中文</option>
|
||||
<option value="1036">Français</option>
|
||||
<option value="1031">Deutsch</option>
|
||||
<option value="1041">日本語</option>
|
||||
</select>
|
||||
<input id="itemId" value="1101" title="Item ID">
|
||||
<h1>Item</h1>
|
||||
<h2 id="itemName">—</h2>
|
||||
<div class="row"><span class="label">Production / min</span><span id="prod">—</span></div>
|
||||
<div class="row"><span class="label">Theoretical / min</span><span id="prodRef">—</span></div>
|
||||
<div class="row"><span class="label">Consumption / min</span><span id="cons">—</span></div>
|
||||
<div class="row"><span class="label">Theoretical / min</span><span id="consRef">—</span></div>
|
||||
<h1>Research</h1>
|
||||
<h2 id="techName">—</h2>
|
||||
<div class="row"><span class="label">Progress</span><span id="techProg">—</span></div>
|
||||
<h1>Dyson sphere</h1>
|
||||
<div class="row"><span class="label">Generation</span><span id="dyson">—</span></div>
|
||||
<div class="status" id="status">Connecting</div>
|
||||
</div>
|
||||
<script src="../js/generated/dsp-text.js"></script>
|
||||
<script src="../js/livestream-assist.js"></script>
|
||||
<script>
|
||||
const qs = new URLSearchParams(location.search);
|
||||
const urlInput = document.getElementById("url");
|
||||
const langInput = document.getElementById("lang");
|
||||
const itemInput = document.getElementById("itemId");
|
||||
const statusEl = document.getElementById("status");
|
||||
urlInput.value = qs.get("ws") || urlInput.value;
|
||||
itemInput.value = qs.get("item") || itemInput.value;
|
||||
|
||||
const text = LiveStreamAssist.GameText.fromGenerated({ language: qs.get("lang") || langInput.value });
|
||||
langInput.value = String(text.lcid);
|
||||
if (!langInput.value) { langInput.value = "1033"; text.setLanguage(1033); }
|
||||
const client = new LiveStreamAssist.Client({
|
||||
url: urlInput.value,
|
||||
onStatus: function (status) { statusEl.textContent = status; }
|
||||
});
|
||||
const query = new LiveStreamAssist.GameQuery(client);
|
||||
let pollTimer;
|
||||
let pollGeneration = 0;
|
||||
let validatedInfo = null;
|
||||
|
||||
langInput.onchange = function () { text.setLanguage(langInput.value); };
|
||||
|
||||
async function tick(generation) {
|
||||
const itemId = parseInt(itemInput.value, 10) || 1101;
|
||||
const results = await Promise.allSettled([
|
||||
query.getItemRates(itemId),
|
||||
query.getCurrentResearch(),
|
||||
query.getDysonPower()
|
||||
]);
|
||||
if (generation !== pollGeneration) return;
|
||||
const failed = results.find(function (result) { return result.status === "rejected"; });
|
||||
if (failed) throw failed.reason;
|
||||
const [rates, research, dyson] = results.map(function (result) { return result.value; });
|
||||
document.getElementById("itemName").textContent = text.itemName(itemId) || ("Item " + itemId);
|
||||
document.getElementById("prod").textContent = text.formatRate(rates.production);
|
||||
document.getElementById("prodRef").textContent = text.formatRate(rates.theoreticalProduction);
|
||||
document.getElementById("cons").textContent = text.formatRate(rates.consumption);
|
||||
document.getElementById("consRef").textContent = text.formatRate(rates.theoreticalConsumption);
|
||||
if (!research.active) {
|
||||
document.getElementById("techName").textContent = "No active research";
|
||||
document.getElementById("techProg").textContent = "";
|
||||
} else {
|
||||
document.getElementById("techName").textContent = text.techDisplayName(research.techId, research.curLevel) || ("Tech " + research.techId);
|
||||
document.getElementById("techProg").textContent = (research.progressPercent || 0).toFixed(1) + "%";
|
||||
}
|
||||
document.getElementById("dyson").textContent = text.formatPower(dyson.watts);
|
||||
}
|
||||
|
||||
async function poll(generation) {
|
||||
if (generation !== pollGeneration) return;
|
||||
try {
|
||||
await client.connect(urlInput.value);
|
||||
if (generation !== pollGeneration) return;
|
||||
if (!client.infoSnapshot || validatedInfo !== client.infoSnapshot) {
|
||||
const info = await client.systemInfo();
|
||||
if (generation !== pollGeneration) return;
|
||||
await client.validate({ apiMajor: 1, requiredCapabilities: ["reflection.read"] });
|
||||
if (generation !== pollGeneration) return;
|
||||
validatedInfo = info;
|
||||
}
|
||||
await tick(generation);
|
||||
if (generation === pollGeneration) statusEl.textContent = "connected";
|
||||
} catch (error) {
|
||||
if (generation === pollGeneration) statusEl.textContent = error.kind || error.message;
|
||||
} finally {
|
||||
if (generation === pollGeneration) pollTimer = setTimeout(function () { poll(generation); }, 2000);
|
||||
}
|
||||
}
|
||||
|
||||
function stop() {
|
||||
pollGeneration += 1;
|
||||
clearTimeout(pollTimer);
|
||||
client.close();
|
||||
validatedInfo = null;
|
||||
}
|
||||
|
||||
function start() { stop(); poll(pollGeneration); }
|
||||
|
||||
urlInput.onchange = start;
|
||||
addEventListener("pagehide", stop);
|
||||
start();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,155 @@
|
||||
# LiveStreamAssist JS client
|
||||
|
||||
Browser helper for the [WebSocket API](../docs/WebSocketApi.md). It is intended for OBS Browser Sources and local overlay pages with BigInt and `Promise.allSettled` support. There is no npm build; load the packed script as a classic `<script>`.
|
||||
|
||||
The library has four layers:
|
||||
|
||||
| Layer | Script surface | WebSocket? | Role |
|
||||
| --- | --- | --- | --- |
|
||||
| Low-level client | `LiveStreamAssist.Client` | Yes | JSON-RPC 2.0 transport, method wrappers, pending-request limit |
|
||||
| High-level query | `LiveStreamAssist.GameQuery` | Yes | Common overlay reads: item rates, research, Dyson power |
|
||||
| Game text | `LiveStreamAssist.GameText` | No | ID to localized name, DSP KMG formatting |
|
||||
| Game icons | `LiveStreamAssist.GameIcons` | No | ID to icon data URL extracted from game textures |
|
||||
|
||||
`GameText` and `GameIcons` never send API requests. Names come from generated dictionaries converted from the game's `Locale/` files and prototype tables; icons come from textures extracted from a local install.
|
||||
|
||||
## Files
|
||||
|
||||
- `livestream-assist.js` — packed browser bundle
|
||||
- `generated/dsp-text.js` — generated locale/proto dictionary
|
||||
- `generated/dsp-icons.js` — generated item/tech icon data URLs
|
||||
- `src/` — layer sources concatenated by `scripts/pack_js.py`
|
||||
- `scripts/generate_text.py` — regenerate text data from a local DSP install
|
||||
- `scripts/generate_icons.py` — regenerate icon data from a local DSP install
|
||||
|
||||
## Overlay usage
|
||||
|
||||
```html
|
||||
<div id="research"></div>
|
||||
<div id="rates"></div>
|
||||
<div id="power"></div>
|
||||
<script src="../js/generated/dsp-text.js"></script>
|
||||
<script src="../js/livestream-assist.js"></script>
|
||||
<script>
|
||||
(async function () {
|
||||
const text = LiveStreamAssist.GameText.fromGenerated({ language: "en" });
|
||||
const client = new LiveStreamAssist.Client({ url: "ws://127.0.0.1:18080/api/v1" });
|
||||
const query = new LiveStreamAssist.GameQuery(client);
|
||||
|
||||
await client.systemInfo();
|
||||
await client.validate({ apiMajor: 1, requiredCapabilities: ["reflection.read"] });
|
||||
await query.waitUntilReady();
|
||||
|
||||
const research = await query.getCurrentResearch();
|
||||
const iron = await query.getItemRates(1101);
|
||||
const dyson = await query.getDysonPower();
|
||||
|
||||
document.getElementById("research").textContent = research.active
|
||||
? text.techDisplayName(research.techId, research.curLevel)
|
||||
: "No active research";
|
||||
document.getElementById("rates").textContent = text.itemName(1101) + " " + text.formatRate(iron.production) + " / min";
|
||||
document.getElementById("power").textContent = text.formatPower(dyson.watts);
|
||||
})().catch(function (error) { console.error(error); });
|
||||
</script>
|
||||
```
|
||||
|
||||
Examples:
|
||||
|
||||
- [research-overlay.html](../examples/research-overlay.html)
|
||||
- [stats-overlay.html](../examples/stats-overlay.html)
|
||||
- [live-dashboard.html](../examples/live-dashboard.html)
|
||||
|
||||
Keep `examples/` and `js/` side by side when copying these pages. The examples retry failed connections, wait for each polling cycle to finish before scheduling another, and discard stale results after connection changes. Use `?lang=en`, `?lang=zh-CN`, or an LCID such as `?lang=2052`; the stats example also accepts `?item=1101`.
|
||||
|
||||
The Chinese live-dashboard page shows only the sections selected by URL parameters and defaults to research plus Dyson power when none are given:
|
||||
|
||||
```text
|
||||
?items=1101,1203&techs=1001,1104&research=1&dyson=1&window=1min
|
||||
```
|
||||
|
||||
- `items` renders the game-style rate table: each material has two rows (production with its theoretical value, then consumption with its theoretical value) sharing one icon and name cell.
|
||||
- `techs` renders tech levels: `cur/max` for repeatable techs, 已解锁/未解锁 for one-time techs.
|
||||
- `research` renders the current tech with a progress bar and hash counters.
|
||||
- `dyson` renders total Dyson sphere power generation.
|
||||
- `window` selects the rate window (`1min` default, `10min`, `1hour`, `10hour`, `100hour`, `total`).
|
||||
|
||||
## Low-level client
|
||||
|
||||
`Client` speaks the documented JSON-RPC methods only: `system.ping`, `system.info` (`systemInfo()`), `system.validate`, `system.stats`, `data.roots`, `data.describe`, and `data.read`. Unknown parameters are omitted so the server does not reject the request.
|
||||
|
||||
- Request ids are `n-<n>` and are unique among outstanding calls.
|
||||
- At most `maxPending` requests are in flight (default 8, then `system.info.limits.maxPendingRequestsPerConnection`). An explicit caller limit remains an upper bound. Limits must be positive integers.
|
||||
- Responses are correlated by id and may arrive out of order.
|
||||
- `Int64`/`UInt64` values stay strings on the wire. `GameQuery` converts them where needed.
|
||||
- `LiveStreamAssist.key(id)` builds a dictionary path segment `{ key }`.
|
||||
- `connect(url)` replaces a connection when its URL changes. `close()` cancels connecting, pending, and queued work and stops reconnect timers. Call `connect()` explicitly to reopen a closed client; requests never replay across connections.
|
||||
|
||||
API errors throw `LiveStreamAssist.ApiError` with stable `kind` from `error.data.kind`.
|
||||
|
||||
## High-level queries
|
||||
|
||||
Compound queries reject with `SESSION_CHANGED` instead of combining reads from different saves. Retry the entire query. Reads within one session can still sample different game ticks; they are not atomic snapshots.
|
||||
|
||||
### Item production
|
||||
|
||||
`query.getItemRates(itemId, { window, scope })`
|
||||
|
||||
- `window`: `1min` (default), `10min`, `1hour`, `10hour`, `100hour`, `total`. The default 1-minute window matches the statistics panel's shortest rate view: `ProductStat.total[1]` production and `total[8]` consumption, already items/min.
|
||||
- `scope`: omitted/`'cluster'` sums every factory; `'localPlanet'` uses `localPlanet.factoryIndex`; `{ factoryIndex }` reads one factory.
|
||||
- Result fields: `production`, `consumption`, `theoreticalProduction`, `theoreticalConsumption`. Theoretical values are the game's `refProductSpeed` / `refConsumeSpeed` in items/min. The server queues queried factories for the native production extra-info calculator without requiring the statistics window or Ctrl+F8 assist. Refresh requests are deduplicated and limited to once per factory every two seconds; an active calculation batch finishes before more factories are queued. Initial polls can return zero, and later polls can return the previous values until the native batch reaches that factory.
|
||||
|
||||
Pass an array of positive integer item ids to share the factory scan; duplicates do not multiply totals. Only existing product indices are cached, so newly produced items become visible on later polls. An unbuilt local planet returns zero rates; an unavailable local planet during space travel still raises `ROOT_UNAVAILABLE`.
|
||||
|
||||
### Research
|
||||
|
||||
- `getTechState(techId)` reads `history.techStates[techId]`.
|
||||
- `getCurrentResearch()` reads `history.currentTech`, then that tech's state. `techId === 0` means no active research. `progressPercent` uses integer hash math, same as the sample overlay.
|
||||
|
||||
### Current cluster
|
||||
|
||||
- `getClusterString()` reads `game.gameDesc.clusterString`, the current Dyson Sphere Program star-cluster seed/address string.
|
||||
- The result is `{ clusterString, sessionId, gameTick }`; the string is sampled on the game thread and is not cached across sessions.
|
||||
|
||||
### Dyson power
|
||||
|
||||
`getDysonPower()` sums `game.dysonSpheres[i].energyGenCurrentTick` across non-null spheres, projecting energy fields in collection pages. `getDysonPower({ starIndex })` reads only that sphere. Watts are `joulesPerTick * 60` (DSP ticks per second). `originalWatts` is the pre-Dark-Fog-debuff figure. Star display names use `overrideName` or `name` because `displayName` is a getter and is not readable through the API. Empty results retain their session metadata.
|
||||
|
||||
## Game text
|
||||
|
||||
Load `generated/dsp-text.js` before the library, then `GameText.fromGenerated({ language: "zh-CN" })`. Language may be an LCID (`1033`, `2052`), `en`, `zh`, `fr`, `de`, or `ja`.
|
||||
|
||||
- `itemName`, `techName`, `recipeName`, `signalName`, `veinName`, and `name(kind, id)`
|
||||
- `translate(key)` for generated locale keys (missing entries return the key and explicit empty translations stay empty, matching DSP)
|
||||
- `techDisplayName(id, curLevel)` matches `TechState.currentTechString`: name, or name + `杠等级` + level
|
||||
- `formatKmg`, `formatPower`, `formatEnergy` match `StringBuilderUtility.WriteKMG` / `WriteKMGPower` / `WriteKMGEnergy`: values below 10000 stay raw, then k/M/G/T/P/E with three leading digits. Decimal separators follow the selected language (`小数点`).
|
||||
|
||||
## Game icons
|
||||
|
||||
Load `generated/dsp-icons.js` before the library, then `GameIcons.fromGenerated()`.
|
||||
|
||||
- `itemIcon(id)`, `techIcon(id)`, and `icon(kind, id)` return PNG data URLs extracted from the game's `Icons/ItemRecipe` and `Icons/Tech` textures, or `null` for unknown IDs.
|
||||
- The data file is around 3.5 MB because it embeds every item and tech icon; pages should keep referencing it from disk like the other generated data.
|
||||
|
||||
## Regenerating text and icon data
|
||||
|
||||
Requires a local DSP install plus `pip install -r LiveStreamAssist/js/scripts/requirements.txt`.
|
||||
|
||||
```text
|
||||
python LiveStreamAssist/js/scripts/generate_text.py --game-root "<DSP install>"
|
||||
python LiveStreamAssist/js/scripts/generate_icons.py --game-root "<DSP install>"
|
||||
python LiveStreamAssist/js/scripts/pack_js.py
|
||||
```
|
||||
|
||||
The generator locates Steam/DSP the same way `UpdateGameDlls.ps1` does when `--game-root` is omitted. It reads BOM-aware `Locale/` files in the header's stable page order and extracts prototype id/name maps from `resources.assets`. Missing item or tech tables abort generation before overwriting the dictionary. Edit `src/` and repack rather than editing `livestream-assist.js` directly.
|
||||
|
||||
## Validation
|
||||
|
||||
Run from the repository root. JavaScript checks use Node.js 20 or later and require no npm packages. Python checks use the standard library; locale integration checks run when DSP is installed.
|
||||
|
||||
```text
|
||||
python LiveStreamAssist/js/scripts/pack_js.py
|
||||
node --test LiveStreamAssist/js/scripts/test_client.js LiveStreamAssist/js/scripts/test_query.js LiveStreamAssist/js/scripts/test_text.js LiveStreamAssist/js/scripts/test_overlays.js LiveStreamAssist/js/scripts/test_dashboard.js
|
||||
python LiveStreamAssist/js/scripts/test_text.py
|
||||
```
|
||||
|
||||
These checks cover connection cancellation, queue limits, session changes, production caching, Dyson pagination, locale parsing, formatting, and overlay polling. They do not replace DSP/OBS or LAN acceptance testing.
|
||||
@@ -0,0 +1,2 @@
|
||||
/* Generated from a local Dyson Sphere Program install by generate_icons.py. Do not edit. */
|
||||
globalThis.LiveStreamAssistIconData = {"version":"1.0.0","icons":{"item":{"1000":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAACfElEQVR42u2cMU4DMRBFvydbBtFAQQRIaXIBjsIV4FScAYmrUEIBoiGKqEAUNJFpDMouibCzXu/MeL7kZuUknuc/49lA1nnvkUOXN88AgLWbgLPurs6zvh/lhCdBuddKNcEbYs1UG7zca3f71kApNW/omki1OS93LFQzvBwxUe3w+sYWXQO11LzcNZFqd17fWMng9YuZGMPzYbCGuLMGjlzzuotyXGsiMXVezDUWTiQB8FhDJMgSO4hNd9KIfZ6HQJGA1GXtQhIGjx1EEgiPFURauwk2hx0qbe3i8wORNAdf9BARDG/UVCbo0GgQG0XB+hL3zN1zgmpxirYaqGaDSGFwXiNAdamrNYWLbxgpdp/XAFBt6mpP4WIbSOY+c+CoG0mVuM+bAytKYV9TKpsDmQHkfvJ6c6C1MQZQeuPszYGWwgbQZADzqBG01hcAKwBvAD4BTAGcADgGcGYAd+sLwD2Ap871jzAeACzCOLAU/qtt8Lp6DMNq4Ja0fYqc+wjg1QC2tUqcvzSAbb0NDFw9wM/E+e+SAQ7xn1HTxPmHpdfJ3YEnifOPLIXbOk6cfyodYO40PgsNcowWAGaly4yERnoRAXGRAJr9rZxD3i8tDwBchHq4DK3KezgwjkLazkbIjkHvhXNDRIA067Geau+FWWtIgI5JjE4qQA4QnWQHjg2xyOc2hYPx2jaMlLmiuNubEVPLSwb3C3Di160LBX8zvBm0lwKty4vLH5W4tDzWSJfU7fUcdHs9NxJ7wgM2np216+ET2p8XmFrzNuG1UticmOa8rTXQIKbB23qIGMR4eK0a2FWtNfG/mhfdxpgT4zhQnxfXDi+qka4VYmzc30cF05B5ubOJAAAAAElFTkSuQmCC","1001":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAn2klEQVR42s2cd7xkR3Xnv1U39+3wcpqcpZFmRgkhFBACgQAvtlcE2eB1ALQmWQbvwmIZbBawRXCQMbBgmbVhMRgjwHitXYwRimAEQgjl0eTRzLzYr3PfWFX7R7/3Jo9GiaX6U5+6p+umOvfU75w6darEpW/+LIvJGIMQ4mdCG2PAmF6FEIePgejQPQDU5mu9asdj07nnAuBX+nDCkKTbXTq/b2wIgKybUin5HJm2f+/HPJN06//68CnrxaVv+szhBvwMyyUGnuSc1r7vA9BqNZcY6BdLYFkAaCHwS8UeU0OfTifFXfhWU7v2HNXIvlLhGTHxax9/50nrJIsS8rMtHWAYEEuSd0zZajVptZpHvWzcbgHghGGPbrUZnhgEIAxdAColn03nnMnQ6uGlbA+GPHbP3dSn5pbyY/fczei6VUv5sXvuxh4MT5iv+chNTyKBP/tkGWM8oHuiykXpe7oSeLKUGp70nFOlv3/3rx73n/3/o/tijDqKeQt19b134wUFbMc6CgOPlMAjMTButZcYGIbuCTHw2FRtdBishE+LgW/7zDf49Fv+4zEMPKLrGGMQhxH/uaWPYV40fR9e0MOqJE2xhEWpVD6qG/vFUk9ZdDpwhAQCSxLYaMXHYeCxqXzGWnY/tvtpMfElb3mUWz9z/eHXN8aw7ZW/8ZRuUp64uKcEFhovhHjKkmiO0LqqtZ1WdRYALyhQm5058nGOcLyXbjr33HuA6rFaeMWmVbQaneO0cLU+d8o2tKbmKY0NPO3u/JX3Xttj4NZX/PrTukFp/AXHCNLJweVYc2bJjFlgHkCnXsNxe4ogj+PF0144V2/99fi69ZvWnrGhmafZ57Gsm4AHTwsDs+4p2zC1+wBja5c/fUy8/k1Pn4EAaTdFON4SPbjqBVT3/ftx5Ynq53bdiRQ9JpaHRo+SQFQG8MczM/Xrxy+4mNXrV6DSDJ0n+L6H1vxt0u1eB7SfqR2oNFjy6SuWZ8bAKD8sUSpHWPbJpfAE9Ubl9I9NLHyMzuLf5ydR56bJPfvP3fiKV7HtF66iMzeHTiOSbkY59CgGDkkUTzWqzU8Cf/xM7cB6dZ6+wYGfPQMXmWi0RrreSc/RaXJcvcmzE0nge7M0vaFdb7B229m89S/+iEOdmEd3HyTA4ANSa7qdCNtAwbFo1Zo/bTU61wF3ngoDg9IAUWv+pO/4dOvtZ2rQ9Q2P0O1Ex3Tt1lH19dkZTJ4dRS8ybiFtkpb9N1G7eWkcp/h+wK//zm+xYbjMfLXG5ol+ZK7ZPTVPYElGhiokUYI0Br9c3FZtxndk7eifXcFbG634EIBtFY+Bw/S4/56N+mfEwDzOaGSHbTWhUozlImxniW7UaiekTZ7RnJsGeKtW5pMqz6Xjehw8NMO1v/krbNx6Ft/8yeOsKPj0OQ5eYDE7U6fR6XLmspWgDJPVGlmeExQckm7nF3NlXjhYCa8GbvtZjQieEQO1EbAgWQCGp0RLlat/MIbXgkHaFp12l+UTY1z2yis5UK9DrmgkKXGWkyQpw30FtMp5dNchBkoFcpUzX2tSKfqkTcmKFeN9s/umvrv7sd2XA3f+3DPQDWyy7GmNjVboNLkFY7YIIUEIhBDMzFZ52zt+i60XnMFX73uUscCj7HtEeU6eCertLrYUzEcxxmj6Cj5DlTJZHCNtiySKGF8+xMG9++4ojQ28CviX55qBEhE8Ax0e4Lj+cdko9WT5vwujtxggiiOMNiilCUtFznneOXQNKKUwuabkOiwrhoS2jTCglaZS9ukvBfSFBTYsG0FIAdqwa8cT2J7DBc/fytzOQ//b1vJ5tpY8p3nRnnML7lPXwJ0Gblg5riz2j/Ss/erUyS71jNZYjsPYYB/tVodatcGaNasoTYwxPdfgrJFBnqi36GYZY8UQpTRDpZA09Dg4V2O+0cYTkk6ry55dkzRmqvihQxTFjAz1k2c5Bx/e831Lcj7wwHPahZca/xSZ6IYVjrp+gVZZjuXYjC5fBsD0/v3HXjqXK0WhVORFV72YW2/5DnvqT3DZlS9kxdoJDh6axUIQODZRmjHfjfBtm/lGm7luB8+xidME1xI8OjnN3OQs7fkG64ZWEkcJD+55jE67iy21HZZK/9Y3OLAcyJ4zBi423vVD0mju9K82EYgA1+95N1w/JI07WE4PWrvtNoViEa11Dy8sG6NzgOVpnNI30I/jOjQbTRCC8y7YwlpbULctfjo7z0SlhBSCuVYHR0jiNKXVjujrL7B2bJA8SZCWoeBKYlsihaA2V+PAvoN4novtWMxPPjEytfORNwKffU4YeKTkpHHnqSuSBaYdef2iBBaKxSXGLTpUhON+UKj86narxZoNa/ACn6lDMwyNDXPets2EgBECCdTaHSrFkKLjIBEEBZ9VgUOcZRRsm3t37CePEpIoISj6CGGo1VpoBF7o43oetYMp81MHr3nOGHhU9zPRUx4LIzrHYeBxEqhygGts1/lYmiQrw4JPqVxi/ZkbqM5Ukbbk+Zc9n4GRIepAVykmKiUa3S7TzRYrikXmOhHaEszOt1k31I+UEiMFaZxQr7eo9JdQuSZNMtzABVdiYeMXyzh+sOy508KLWPYUmXcsBlqWdxQGAosSeLWQ8qee5/wDWq/0fY9ut8uGszZxyUteyI5HtmOUZu261ZjQZ2ezS5wpNgwNkGvFVK2BQJCpnN0Hp+h0uqwd6GewUuLM1eNoo1FZhi0FnmOjlCKNY6Jml6jVQdoOtuOMOK4XOq7Hs53lEpY9nbRwneuHKJUsYeGCBF7Wbbdvm9q/72uuJbcKIF1gbKvZ4ZwLz0UIwa7tO4m6EVmWMehb1DoRA76HMppqlLB6sEIpcDkwX0MYeMWWM8mMBgHjQwMkcYotBatWjhF3E5IoQiu15DKTlo2QVh+w7rlRIk+XeQt24JHYt1AOqiz/VNypX5N0WtiWBNdHOC6hbRO1OzhSce9dd7P9gYeIMkNhdBnFgQHGgGoQ4NsWDx6YZLxUYtPwAPVuRJIkrBnsY/XIEI9OzTAcuuQaBgoF9lrQaUXs2b4brVNGRkbISEjjHMt2kLaNSlPxnGnhp+2J6TRO9PdrMVxjjMZ2bBwvICj34VnQmGuSxR0c12Hfzt0kSYo7up6xTes5c8smFLC8WGC2G+O5LisHQubbXTppyoaREVYP9XGo0WSwGOIKyUDoEAhBuxMzPTVHt1mnf7Afx5LEqcYYhe16uF5AJ+oOPGcY+LSHcgUXrdSx+SpjFEqDtF36B0r4Imd26iDNThfheBhpI6RHODBOmuasXt7P2etWkAPagC0lA4UA37ZJlKYVJWwYG6avXGK60SRKEoq+SznwmJmdx7Isup0WQRDQ399HluYI2ZsxtWwHNwgxWr/caM2znZ+OBIol3wDglwKSTnJk/RW5MgS+x9BAiTTLmKs2SBRYfhkpDWG5jPTLRHGGaXRwgoBumhD5NkjwLIuiY1PrdLEFrB3qx7YsumlOkuZMJw3OXjnOt+/6MQ8+vBMHRRZrxleMY0sLlSlyleM4Ln4hoFDppzF98JeB//Zz1YWP0CaLB2dqIyph0GNeN1XMznfRwsEvlXBsm7BSJuzrB9fDTzXab/Lw4zPcfOuPeeULt1F2HCwEnuVgi5TRSonAstg7N89Uo0Wc5ly8aQ2Hpqt857YfkkUxRmrGV07guQ5ZkpFnOXGUMDRSpjk3xdzBfRRHxu/4ecFAcyQRteMjybe7jk1Y8Km2EhrdFNtxqRRDgjDACQqUCj65tMgcjyDwGPJCJvcf4p/+6S5GxwbYsnEFw47LcOijjabWjYlMSidNGSoXGSoEFFyH7YdmSKOYPIsZHB+hUi6SRgnSCJI0x7Ftup2UyX17STsthlau+8zPnRKJuylCyqMxVVrMt1OS3FAsFiiVQiz
Line truncated
|
||||
@@ -0,0 +1,2 @@
|
||||
/* Generated from a local Dyson Sphere Program install by generate_text.py. Do not edit. */
|
||||
globalThis.LiveStreamAssistTextData = {"version":"1.0.0","languages":{"2052":{"lcid":2052,"name":"简体中文","abbr":"zh-CN","abbr2":"zh","fallback":1033},"1033":{"lcid":1033,"name":"English","abbr":"en-US","abbr2":"en","fallback":2052},"1036":{"lcid":1036,"name":"Français","abbr":"fr-FR","abbr2":"fr","fallback":1033},"1031":{"lcid":1031,"name":"Deutsch","abbr":"de-DE","abbr2":"de","fallback":1033},"1041":{"lcid":1041,"name":"日本語","abbr":"ja-JA","abbr2":"ja","fallback":1033}},"ids":{"item":{"1001":"铁矿","1002":"铜矿","1003":"硅石","1004":"钛石","1005":"石矿","1006":"煤矿","1030":"木材","1031":"植物燃料","1011":"可燃冰","1012":"金伯利矿石","1013":"分形硅石","1014":"光栅石","1015":"刺笋结晶","1016":"单极磁石","1101":"铁块","1104":"铜块","1105":"高纯硅块","1106":"钛块","1108":"石材","1109":"高能石墨","1103":"钢材","1107":"钛合金","1110":"玻璃","1119":"钛化玻璃","1111":"棱镜","1112":"金刚石","1113":"晶格硅","1201":"齿轮","1102":"磁铁","1202":"磁线圈","1203":"电动机","1204":"电磁涡轮","1205":"超级磁场环","1206":"粒子容器","1127":"奇异物质","1301":"电路板","1303":"处理器","1305":"量子芯片","1302":"微晶元件","1304":"位面过滤器","1402":"粒子宽带","1401":"电浆激发器","1404":"光子合并器","1501":"太阳帆","1000":"水","1007":"原油","1114":"精炼油","1116":"硫酸","1120":"氢","1121":"重氢","1122":"反物质","1208":"临界光子","1801":"氢燃料棒","1802":"氘核燃料棒","1803":"反物质燃料棒","1804":"金色燃料棒","1115":"塑料","1123":"石墨烯","1124":"碳纳米管","1117":"有机晶体","1118":"钛晶石","1126":"卡西米尔晶体","1128":"燃烧单元","1129":"爆破单元","1130":"晶石爆破单元","1209":"引力透镜","1210":"空间翘曲器","1403":"湮灭约束球","1407":"动力引擎","1405":"推进器2","1406":"加力推进器","5003":"配送运输机","5001":"物流运输机","5002":"星际物流运输船","1125":"框架材料","1502":"戴森球组件","1503":"小型运载火箭","1131":"地基","1141":"增产剂 Mk.I","1142":"增产剂 Mk.II","1143":"增产剂 Mk.III","1601":"机枪弹箱","1602":"钛化弹箱","1603":"超合金弹箱","1604":"炮弹组","1605":"高爆炮弹组","1606":"晶石炮弹组","1607":"等离子胶囊","1608":"反物质胶囊","1609":"导弹组","1610":"超音速导弹组","1611":"引力导弹组","1612":"电磁干扰胶囊","1613":"电磁压制胶囊","5101":"地面战斗机-E型","5102":"地面战斗机-A型","5103":"地面战斗机-F型","5111":"太空战斗机-A型","5112":"太空战斗机-F型","5201":"存储单元","5202":"硅基神经元","5203":"物质重组器","5204":"负熵奇点","5205":"虚粒子","5206":"能量碎片","2001":"低速传送带","2002":"高速传送带","2003":"极速传送带","2011":"低速分拣器","2012":"高速分拣器","2013":"极速分拣器","2014":"集装分拣器","2020":"四向分流器","2040":"自动集装机","2030":"流速器","2313":"喷涂机","2107":"物流配送器","2101":"小型储物仓","2102":"大型储物仓","2106":"储液罐","2303":"制造台 Mk.I","2304":"制造台 Mk.II","2305":"制造台 Mk.III","2318":"制造台 Mk.IV","2201":"电力感应塔","2202":"无线输电塔","2212":"卫星配电站","2401":"激光灯塔","2203":"风力涡轮机","2204":"火力发电厂","2211":"微型聚变发电站","2213":"地热发电站","2301":"采矿机","2316":"大型采矿机","2306":"抽水站","2302":"电弧熔炉","2315":"位面熔炉","2319":"熔炉 Mk.III","2307":"原油萃取站","2308":"原油精炼厂","2309":"化工厂","2317":"化工厂 Mk.II","2314":"分馏塔","2205":"太阳能板","2206":"蓄电器","2207":"蓄电器(满)","2311":"电磁轨道弹射器","2208":"射线接收站","2312":"垂直发射井","2209":"能量枢纽","2310":"微型粒子对撞机","2210":"人造恒星","2103":"物流运输站","2104":"星际物流运输站","2105":"轨道采集器","2901":"矩阵研究站","2902":"矩阵研究站 Mk.II","3001":"高斯机枪塔","3002":"高频激光塔","3003":"聚爆加农炮","3004":"磁化电浆炮","3005":"导弹防御塔","3006":"干扰塔","3007":"信标","3008":"护盾发生器","3009":"战场分析基站","3010":"地面电浆炮","6001":"电磁矩阵","6002":"能量矩阵","6003":"结构矩阵","6004":"信息矩阵","6005":"引力矩阵","6006":"宇宙矩阵","1099":"沙土"},"tech":{"1":"T戴森球计划","1001":"T电磁学","1002":"T电磁矩阵","1101":"T高效电浆控制","1102":"T等离子萃取精炼","1103":"TX射线裂解","1104":"T重整精炼","1105":"T电弧激光","1111":"T能量矩阵","1112":"T氢燃料棒","1113":"T推进器","1114":"T加力推进器","1120":"T流体储存封装","1121":"T基础化工","1122":"T高分子化工","1123":"T高强度晶体","1124":"T结构矩阵","1125":"T卡西米尔晶体","1126":"T高强度玻璃","1131":"T应用型超导体","1132":"T高强度材料","1133":"T粒子可控技术","11Line truncated
|
||||
@@ -0,0 +1,884 @@
|
||||
/**
|
||||
* LiveStreamAssist browser client.
|
||||
* Client: JSON-RPC WebSocket wrapper.
|
||||
* GameQuery: production, research, and Dyson power helpers.
|
||||
* GameText: offline locale names and DSP KMG formatting.
|
||||
*/
|
||||
(function (root, factory) {
|
||||
var api = factory();
|
||||
if (typeof module === "object" && module.exports) module.exports = api;
|
||||
root.LiveStreamAssist = api;
|
||||
})(typeof globalThis !== "undefined" ? globalThis : this, function () {
|
||||
"use strict";
|
||||
var ns = {};
|
||||
var TICKS_PER_SECOND = 60;
|
||||
var THIN_SPACE = "\u2009";
|
||||
var DIGITS = "0123456789";
|
||||
var DEFAULT_URL = "ws://127.0.0.1:18080/api/v1";
|
||||
var RATE_WINDOWS = {
|
||||
"1min": { productionIndex: 1, consumptionIndex: 8, divisor: 1, perMinute: true, timeLevel: 0 },
|
||||
"10min": { productionIndex: 2, consumptionIndex: 9, divisor: 10, perMinute: true, timeLevel: 1 },
|
||||
"1hour": { productionIndex: 3, consumptionIndex: 10, divisor: 60, perMinute: true, timeLevel: 2 },
|
||||
"10hour": { productionIndex: 4, consumptionIndex: 11, divisor: 600, perMinute: true, timeLevel: 3 },
|
||||
"100hour": { productionIndex: 5, consumptionIndex: 12, divisor: 6000, perMinute: true, timeLevel: 4 },
|
||||
total: { productionIndex: 6, consumptionIndex: 13, divisor: 1, perMinute: false, timeLevel: 5 }
|
||||
};
|
||||
|
||||
function key(value) { return { key: value }; }
|
||||
|
||||
function toBigInt(value) {
|
||||
if (typeof value === "bigint") return value;
|
||||
if (typeof value === "number") return BigInt(Math.trunc(value));
|
||||
if (value == null || value === "") return 0n;
|
||||
return BigInt(String(value));
|
||||
}
|
||||
|
||||
function toNumber(value) {
|
||||
if (typeof value === "number") return value;
|
||||
if (typeof value === "bigint") {
|
||||
var n = Number(value);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
if (value == null || value === "") return 0;
|
||||
var parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function writeKmg(value, options) {
|
||||
options = options || {};
|
||||
var lastIndex = options.lastIndex == null ? 8 : options.lastIndex;
|
||||
var blank = !!options.blank;
|
||||
var blankChar = options.blankChar || THIN_SPACE;
|
||||
var fillChar = options.fillChar != null ? options.fillChar : " ";
|
||||
var decimal = options.decimal || ".";
|
||||
var kind = options.kind || "count";
|
||||
var buf = [];
|
||||
var i;
|
||||
for (i = 0; i <= lastIndex; i++) buf[i] = fillChar;
|
||||
var n = toBigInt(value);
|
||||
var sign = 0;
|
||||
if (n > 0n) sign = 1;
|
||||
else if (n < 0n) { sign = -1; n = -n; }
|
||||
var pos = lastIndex;
|
||||
if (kind === "power") buf[pos--] = "W";
|
||||
else if (kind === "energy") buf[pos--] = "J";
|
||||
var threshold = kind === "si1000" ? 1000n : 10000n;
|
||||
if (n < threshold) {
|
||||
if (blank) buf[pos--] = blankChar;
|
||||
while (n > 0n) {
|
||||
buf[pos--] = DIGITS[Number(n % 10n)];
|
||||
if (pos < 0) return buf.join("");
|
||||
n /= 10n;
|
||||
}
|
||||
} else {
|
||||
var suffix = fillChar;
|
||||
var scale = 1n;
|
||||
if (n < 1000000n) { suffix = "k"; scale = 1000n; }
|
||||
else if (n < 1000000000n) { suffix = "M"; scale = 1000000n; }
|
||||
else if (n < 1000000000000n) { suffix = "G"; scale = 1000000000n; }
|
||||
else if (n < 1000000000000000n) { suffix = "T"; scale = 1000000000000n; }
|
||||
else if (n < 1000000000000000000n) { suffix = "P"; scale = 1000000000000000n; }
|
||||
else { suffix = "E"; scale = 1000000000000000000n; }
|
||||
buf[pos--] = suffix;
|
||||
if (blank) buf[pos--] = blankChar;
|
||||
var acc = 1n;
|
||||
while (n >= 1000n) { n /= 10n; acc *= 10n; }
|
||||
while (n > 0n) {
|
||||
buf[pos--] = DIGITS[Number(n % 10n)];
|
||||
if (pos < 0) return buf.join("");
|
||||
n /= 10n;
|
||||
acc *= 10n;
|
||||
if (acc === scale) {
|
||||
buf[pos--] = decimal;
|
||||
if (pos < 0) return buf.join("");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sign === 0) buf[pos--] = "0";
|
||||
else if (sign < 0) buf[pos--] = "-";
|
||||
return buf.join("");
|
||||
}
|
||||
|
||||
function formatKmg(value, options) {
|
||||
options = options || {};
|
||||
var formatted = writeKmg(value, options);
|
||||
return options.trim === false ? formatted : formatted.replace(/^\s+|\s+$/g, "");
|
||||
}
|
||||
|
||||
ns.format = {
|
||||
kmg: function (value, options) { return formatKmg(value, Object.assign({ kind: "count" }, options)); },
|
||||
kmg1000: function (value, options) { return formatKmg(value, Object.assign({ kind: "si1000" }, options)); },
|
||||
power: function (value, options) { return formatKmg(value, Object.assign({ kind: "power" }, options)); },
|
||||
energy: function (value, options) { return formatKmg(value, Object.assign({ kind: "energy" }, options)); },
|
||||
write: writeKmg
|
||||
};
|
||||
ns.key = key;
|
||||
ns.DEFAULT_URL = DEFAULT_URL;
|
||||
ns.TICKS_PER_SECOND = TICKS_PER_SECOND;
|
||||
ns.RATE_WINDOWS = RATE_WINDOWS;
|
||||
function ApiError(init) {
|
||||
var message = (init && init.message) || "LiveStreamAssist API error";
|
||||
Error.call(this, message);
|
||||
this.name = "ApiError";
|
||||
this.message = message;
|
||||
this.code = init && init.code;
|
||||
this.kind = init && init.kind;
|
||||
this.id = init && init.id;
|
||||
this.data = (init && init.data) || null;
|
||||
if (typeof Error.captureStackTrace === "function") Error.captureStackTrace(this, ApiError);
|
||||
}
|
||||
ApiError.prototype = Object.create(Error.prototype);
|
||||
ApiError.prototype.constructor = ApiError;
|
||||
|
||||
function errorFromResponse(id, error) {
|
||||
var data = error && error.data;
|
||||
return new ApiError({
|
||||
id: id,
|
||||
code: error && error.code,
|
||||
message: error && error.message,
|
||||
kind: data && data.kind,
|
||||
data: data || null
|
||||
});
|
||||
}
|
||||
|
||||
function Client(options) {
|
||||
options = options || {};
|
||||
this.url = options.url || DEFAULT_URL;
|
||||
this.autoReconnect = options.autoReconnect !== false;
|
||||
this.requestTimeoutMs = options.requestTimeoutMs == null ? 8000 : options.requestTimeoutMs;
|
||||
this.maxPending = options.maxPending == null ? 8 : options.maxPending;
|
||||
if (!Number.isInteger(this.maxPending) || this.maxPending < 1) {
|
||||
throw new RangeError("maxPending must be a positive integer.");
|
||||
}
|
||||
if (!Number.isFinite(this.requestTimeoutMs) || this.requestTimeoutMs <= 0) {
|
||||
throw new RangeError("requestTimeoutMs must be positive and finite.");
|
||||
}
|
||||
this._configuredMaxPending = options.maxPending;
|
||||
this._ws = null;
|
||||
this._connectionUrl = null;
|
||||
this._seq = 0;
|
||||
this._pending = new Map();
|
||||
this._waiters = [];
|
||||
this._active = 0;
|
||||
this._backoff = 500;
|
||||
this._closed = false;
|
||||
this._connecting = null;
|
||||
this._rejectConnecting = null;
|
||||
this._reconnectTimer = null;
|
||||
this._socketGen = 0;
|
||||
this.infoSnapshot = null;
|
||||
this.onStatus = options.onStatus || null;
|
||||
}
|
||||
|
||||
Client.prototype._setStatus = function (status, detail) {
|
||||
if (typeof this.onStatus === "function") {
|
||||
try { this.onStatus(status, detail); } catch (error) {}
|
||||
}
|
||||
};
|
||||
|
||||
Client.prototype.connect = function (url) {
|
||||
if (url != null) this.url = url;
|
||||
if (this._connectionUrl != null && this._connectionUrl !== this.url) this.close();
|
||||
this._closed = false;
|
||||
if (this._ws && this._ws.readyState === 1) return Promise.resolve(this);
|
||||
if (this._connecting) return this._connecting;
|
||||
if (this._ws) this._disconnect(new ApiError({ kind: "DISCONNECTED", message: "Connection replaced." }));
|
||||
clearTimeout(this._reconnectTimer);
|
||||
this._reconnectTimer = null;
|
||||
var self = this;
|
||||
var generation = ++this._socketGen;
|
||||
var resolveConnection;
|
||||
var connection = new Promise(function (resolve, reject) {
|
||||
resolveConnection = resolve;
|
||||
self._rejectConnecting = reject;
|
||||
});
|
||||
this._connecting = connection;
|
||||
this._connectionUrl = this.url;
|
||||
this.infoSnapshot = null;
|
||||
this.maxPending = this._configuredMaxPending == null ? 8 : this._configuredMaxPending;
|
||||
var socket;
|
||||
try { socket = this._ws = new WebSocket(this.url); }
|
||||
catch (error) {
|
||||
this._disconnect(new ApiError({ kind: "CONNECT_FAILED", message: String(error.message || error) }));
|
||||
this._setStatus("disconnected");
|
||||
return connection;
|
||||
}
|
||||
socket.onopen = function () {
|
||||
if (generation !== self._socketGen) return;
|
||||
self._backoff = 500;
|
||||
self._connecting = null;
|
||||
self._rejectConnecting = null;
|
||||
resolveConnection(self);
|
||||
self._setStatus("connected", { url: self.url });
|
||||
};
|
||||
socket.onmessage = function (event) {
|
||||
if (generation === self._socketGen) self._onMessage(event.data);
|
||||
};
|
||||
socket.onerror = function () {};
|
||||
socket.onclose = function (event) {
|
||||
if (generation !== self._socketGen) return;
|
||||
self._disconnect(new ApiError({
|
||||
kind: self._connecting ? "CONNECT_FAILED" : "DISCONNECTED",
|
||||
message: "WebSocket disconnected.", data: { code: event.code }
|
||||
}));
|
||||
var reconnectGeneration = self._socketGen;
|
||||
self._setStatus("disconnected", { code: event.code });
|
||||
if (!self._closed && self.autoReconnect && reconnectGeneration === self._socketGen) {
|
||||
var delay = self._backoff;
|
||||
self._backoff = Math.min(self._backoff * 2, 8000);
|
||||
self._reconnectTimer = setTimeout(function () {
|
||||
if (!self._closed && reconnectGeneration === self._socketGen) self.connect().catch(function () {});
|
||||
}, delay);
|
||||
}
|
||||
};
|
||||
this._setStatus("connecting", { url: this.url });
|
||||
return connection;
|
||||
};
|
||||
|
||||
Client.prototype._disconnect = function (error) {
|
||||
this._socketGen += 1;
|
||||
clearTimeout(this._reconnectTimer);
|
||||
this._reconnectTimer = null;
|
||||
var socket = this._ws;
|
||||
this._ws = null;
|
||||
this._connectionUrl = null;
|
||||
this.infoSnapshot = null;
|
||||
if (this._rejectConnecting) this._rejectConnecting(error);
|
||||
this._rejectConnecting = null;
|
||||
this._connecting = null;
|
||||
this._failPending(error);
|
||||
if (socket) {
|
||||
socket.onopen = socket.onmessage = socket.onerror = socket.onclose = null;
|
||||
if (socket.readyState < 2) {
|
||||
try { socket.close(); } catch (closeError) {}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Client.prototype.close = function () {
|
||||
this._closed = true;
|
||||
this._disconnect(new ApiError({ kind: "DISCONNECTED", message: "Client closed." }));
|
||||
this._backoff = 500;
|
||||
this._setStatus("disconnected");
|
||||
};
|
||||
|
||||
Client.prototype._failPending = function (error) {
|
||||
this._pending.forEach(function (waiter) {
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.reject(error);
|
||||
});
|
||||
this._pending.clear();
|
||||
this._active = 0;
|
||||
var waiters = this._waiters.splice(0, this._waiters.length);
|
||||
waiters.forEach(function (waiter) { waiter.reject(error); });
|
||||
};
|
||||
|
||||
Client.prototype._settlePending = function (id, error, result) {
|
||||
var waiter = this._pending.get(id);
|
||||
if (!waiter) return;
|
||||
this._pending.delete(id);
|
||||
clearTimeout(waiter.timer);
|
||||
this._release(waiter.generation);
|
||||
if (error) waiter.reject(error);
|
||||
else waiter.resolve(result);
|
||||
};
|
||||
|
||||
Client.prototype._onMessage = function (raw) {
|
||||
var message;
|
||||
try { message = JSON.parse(raw); } catch (error) { return; }
|
||||
if (!message || message.id == null || message.jsonrpc !== "2.0") return;
|
||||
if (!message.error && !Object.prototype.hasOwnProperty.call(message, "result")) return;
|
||||
this._settlePending(message.id, message.error && errorFromResponse(message.id, message.error), message.result);
|
||||
};
|
||||
|
||||
Client.prototype._drainWaiters = function () {
|
||||
if (this._closed || !this._ws || this._ws.readyState !== 1) return;
|
||||
while (this._active < this.maxPending && this._waiters.length) {
|
||||
this._active += 1;
|
||||
this._waiters.shift().resolve();
|
||||
}
|
||||
};
|
||||
|
||||
Client.prototype._release = function (generation) {
|
||||
if (generation !== this._socketGen) return;
|
||||
this._active = Math.max(0, this._active - 1);
|
||||
this._drainWaiters();
|
||||
};
|
||||
|
||||
Client.prototype._acquire = function (generation) {
|
||||
if (this._closed || generation !== this._socketGen || !this._ws || this._ws.readyState !== 1) {
|
||||
return Promise.reject(new ApiError({ kind: "DISCONNECTED", message: "WebSocket is not open." }));
|
||||
}
|
||||
var self = this;
|
||||
return new Promise(function (resolve, reject) {
|
||||
self._waiters.push({ resolve: resolve, reject: reject });
|
||||
self._drainWaiters();
|
||||
});
|
||||
};
|
||||
|
||||
Client.prototype.request = function (method, params) {
|
||||
if (this._closed) return Promise.reject(new ApiError({ kind: "DISCONNECTED", message: "Client closed." }));
|
||||
var self = this;
|
||||
var connection = this.connect();
|
||||
var generation = this._socketGen;
|
||||
return connection.then(function () { return self._acquire(generation); }).then(function () {
|
||||
if (generation !== self._socketGen || !self._ws || self._ws.readyState !== 1) {
|
||||
self._release(generation);
|
||||
throw new ApiError({ kind: "DISCONNECTED", message: "WebSocket is not open." });
|
||||
}
|
||||
var id = "n-" + (++self._seq);
|
||||
var body = { jsonrpc: "2.0", id: id, method: method };
|
||||
if (params != null) body.params = params;
|
||||
return new Promise(function (resolve, reject) {
|
||||
var timer = setTimeout(function () {
|
||||
self._settlePending(id, new ApiError({ kind: "CLIENT_TIMEOUT", message: "Client request timed out.", id: id }));
|
||||
}, self.requestTimeoutMs);
|
||||
self._pending.set(id, { resolve: resolve, reject: reject, timer: timer, generation: generation });
|
||||
try { self._ws.send(JSON.stringify(body)); }
|
||||
catch (err) {
|
||||
self._settlePending(id, new ApiError({ kind: "DISCONNECTED", message: String(err && err.message || err), id: id }));
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
Client.prototype.ping = function () { return this.request("system.ping", {}); };
|
||||
Client.prototype.stats = function () { return this.request("system.stats", {}); };
|
||||
Client.prototype.roots = function () { return this.request("data.roots", {}); };
|
||||
|
||||
Client.prototype.systemInfo = function () {
|
||||
var self = this;
|
||||
var request = this.request("system.info", {});
|
||||
var generation = this._socketGen;
|
||||
return request.then(function (result) {
|
||||
if (generation !== self._socketGen) throw new ApiError({ kind: "DISCONNECTED", message: "Connection replaced." });
|
||||
self.infoSnapshot = result;
|
||||
var limit = result && result.limits && result.limits.maxPendingRequestsPerConnection;
|
||||
if (Number.isInteger(limit) && limit > 0) {
|
||||
self.maxPending = self._configuredMaxPending == null ? limit : Math.min(limit, self._configuredMaxPending);
|
||||
self._drainWaiters();
|
||||
}
|
||||
return result;
|
||||
});
|
||||
};
|
||||
|
||||
Client.prototype.validate = function (params) {
|
||||
params = params || {};
|
||||
var body = { apiMajor: params.apiMajor == null ? 1 : params.apiMajor };
|
||||
if (params.requiredCapabilities) body.requiredCapabilities = params.requiredCapabilities;
|
||||
return this.request("system.validate", body);
|
||||
};
|
||||
|
||||
Client.prototype.describe = function (params) {
|
||||
var body = { root: params.root };
|
||||
if (params.path) body.path = params.path;
|
||||
return this.request("data.describe", body);
|
||||
};
|
||||
|
||||
Client.prototype.read = function (params) {
|
||||
var body = { root: params.root };
|
||||
if (params.path) body.path = params.path;
|
||||
if (params.select) body.select = params.select;
|
||||
if (params.offset != null) body.offset = params.offset;
|
||||
if (params.limit != null) body.limit = params.limit;
|
||||
return this.request("data.read", body);
|
||||
};
|
||||
|
||||
Client.prototype.info = function () { return this.systemInfo(); };
|
||||
|
||||
ns.ApiError = ApiError;
|
||||
ns.Client = Client;
|
||||
function allReads(promises) {
|
||||
var failure = null;
|
||||
return Promise.all(promises.map(function (promise) {
|
||||
return promise.catch(function (error) { if (!failure) failure = error; });
|
||||
})).then(function (results) {
|
||||
if (failure) throw failure;
|
||||
return results;
|
||||
});
|
||||
}
|
||||
|
||||
function sessionChanged() {
|
||||
return new ApiError({ kind: "SESSION_CHANGED", message: "The game session changed during the query. Retry the query." });
|
||||
}
|
||||
|
||||
function decorateTech(techId, result) {
|
||||
var value = result.value || {};
|
||||
var uploaded = toBigInt(value.hashUploaded);
|
||||
var needed = toBigInt(value.hashNeeded);
|
||||
var percent = 0;
|
||||
if (needed > 0n) percent = Number((uploaded * 10000n) / needed) / 100;
|
||||
return {
|
||||
techId: techId,
|
||||
unlocked: !!value.unlocked,
|
||||
curLevel: value.curLevel || 0,
|
||||
maxLevel: value.maxLevel || 0,
|
||||
hashUploaded: String(value.hashUploaded || "0"),
|
||||
hashNeeded: String(value.hashNeeded || "0"),
|
||||
progress: percent / 100,
|
||||
progressPercent: percent,
|
||||
sessionId: result.sessionId,
|
||||
gameTick: result.gameTick
|
||||
};
|
||||
}
|
||||
|
||||
function GameQuery(client) {
|
||||
this.client = client;
|
||||
this._sessionId = null;
|
||||
this._sessionVersion = 0;
|
||||
this._indexCache = new Map();
|
||||
}
|
||||
|
||||
GameQuery.prototype._rememberSession = function (sessionId) {
|
||||
if (sessionId !== this._sessionId) {
|
||||
this._sessionId = sessionId;
|
||||
this._sessionVersion += 1;
|
||||
this._indexCache.clear();
|
||||
}
|
||||
};
|
||||
|
||||
GameQuery.prototype._assertSession = function (context) {
|
||||
if (context.sessionId !== this._sessionId) throw sessionChanged();
|
||||
};
|
||||
|
||||
GameQuery.prototype._read = function (params, context) {
|
||||
context = context || {};
|
||||
var self = this;
|
||||
var version = this._sessionVersion;
|
||||
return this.client.read(params).then(function (result) {
|
||||
if (version !== self._sessionVersion && result.sessionId !== self._sessionId) throw sessionChanged();
|
||||
self._rememberSession(result.sessionId);
|
||||
if (context.sessionId && context.sessionId !== result.sessionId) throw sessionChanged();
|
||||
context.sessionId = result.sessionId;
|
||||
context.gameTick = result.gameTick;
|
||||
return result;
|
||||
}).catch(function (err) {
|
||||
if (err && (err.kind === "SESSION_CHANGED" || err.kind === "GAME_NOT_READY")) {
|
||||
self._indexCache.clear();
|
||||
if (version === self._sessionVersion) self._rememberSession(null);
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype.waitUntilReady = function (options) {
|
||||
options = options || {};
|
||||
var interval = options.intervalMs == null ? 500 : options.intervalMs;
|
||||
var timeout = options.timeoutMs == null ? 30000 : options.timeoutMs;
|
||||
var self = this;
|
||||
var start = Date.now();
|
||||
function loop() {
|
||||
var version = self._sessionVersion;
|
||||
return self.client.roots().then(function (roots) {
|
||||
if (roots && roots.gameReady) {
|
||||
if (version !== self._sessionVersion && roots.sessionId !== self._sessionId) throw sessionChanged();
|
||||
self._rememberSession(roots.sessionId);
|
||||
return roots;
|
||||
}
|
||||
self._rememberSession(null);
|
||||
if (Date.now() - start >= timeout) {
|
||||
throw new ApiError({ kind: "GAME_NOT_READY", message: "Timed out waiting for a player game." });
|
||||
}
|
||||
return new Promise(function (resolve) { setTimeout(resolve, interval); }).then(loop);
|
||||
});
|
||||
}
|
||||
return loop();
|
||||
};
|
||||
|
||||
GameQuery.prototype._getTechState = function (techId, context) {
|
||||
var self = this;
|
||||
return this._read({
|
||||
root: "history",
|
||||
path: ["techStates", key(techId)],
|
||||
select: ["unlocked", "curLevel", "maxLevel", "hashUploaded", "hashNeeded"]
|
||||
}, context).then(function (result) {
|
||||
self._assertSession(context);
|
||||
return decorateTech(techId, result);
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype.getTechState = function (techId) {
|
||||
return this._getTechState(techId, {});
|
||||
};
|
||||
|
||||
GameQuery.prototype.getCurrentResearch = function () {
|
||||
var self = this;
|
||||
var context = {};
|
||||
return this._read({ root: "history", path: ["currentTech"] }, context).then(function (tech) {
|
||||
self._assertSession(context);
|
||||
var techId = tech.value || 0;
|
||||
if (!techId) return { techId: 0, active: false, sessionId: tech.sessionId, gameTick: tech.gameTick };
|
||||
return self._getTechState(techId, context).then(function (state) {
|
||||
self._assertSession(context);
|
||||
state.active = true;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype.getClusterString = function () {
|
||||
var self = this;
|
||||
var context = {};
|
||||
return this._read({ root: "game", path: ["gameDesc", "clusterString"] }, context).then(function (result) {
|
||||
self._assertSession(context);
|
||||
return {
|
||||
clusterString: result.value == null ? "" : String(result.value),
|
||||
sessionId: result.sessionId,
|
||||
gameTick: result.gameTick
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype._factoryIds = function (scope, context) {
|
||||
if (scope === "localPlanet") {
|
||||
return this._read({ root: "localPlanet", path: ["factoryIndex"] }, context).then(function (result) {
|
||||
return Number.isInteger(result.value) && result.value >= 0 ? [result.value] : [];
|
||||
});
|
||||
}
|
||||
var factoryIndex = scope && typeof scope === "object" ? scope.factoryIndex : null;
|
||||
if (factoryIndex != null) {
|
||||
if (!Number.isInteger(factoryIndex) || factoryIndex < 0) throw new RangeError("factoryIndex must be a nonnegative integer.");
|
||||
} else if (scope != null && scope !== "cluster") {
|
||||
throw new Error("Unknown production scope.");
|
||||
}
|
||||
return this._read({ root: "game", path: ["factoryCount"] }, context).then(function (result) {
|
||||
var ids = [];
|
||||
var count = result.value || 0;
|
||||
if (factoryIndex != null) return factoryIndex < count ? [factoryIndex] : [];
|
||||
for (var index = 0; index < count; index++) ids.push(index);
|
||||
return ids;
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype._productIndex = function (factoryIndex, itemId, context) {
|
||||
this._assertSession(context);
|
||||
var cacheKey = factoryIndex + ":" + itemId;
|
||||
if (this._indexCache.has(cacheKey)) return Promise.resolve(this._indexCache.get(cacheKey));
|
||||
var self = this;
|
||||
return this._read({
|
||||
root: "statistics",
|
||||
path: ["production", "factoryStatPool", factoryIndex, "productIndices", itemId]
|
||||
}, context).then(function (result) {
|
||||
self._assertSession(context);
|
||||
var index = result.value || 0;
|
||||
if (index > 0) self._indexCache.set(cacheKey, index);
|
||||
return index;
|
||||
}).catch(function (err) {
|
||||
if (err && (err.kind === "INDEX_OUT_OF_RANGE" || err.kind === "NULL_PATH")) {
|
||||
self._assertSession(context);
|
||||
return 0;
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype._readFactoryItem = function (factoryIndex, itemId, spec, context) {
|
||||
var self = this;
|
||||
var consumptionOffset = spec.consumptionIndex - spec.productionIndex;
|
||||
return this._productIndex(factoryIndex, itemId, context).then(function (poolIndex) {
|
||||
if (!poolIndex) {
|
||||
return { itemId: itemId, production: 0, consumption: 0, theoreticalProduction: 0, theoreticalConsumption: 0, hit: false };
|
||||
}
|
||||
return allReads([
|
||||
self._read({
|
||||
root: "statistics",
|
||||
path: ["production", "factoryStatPool", factoryIndex, "productPool", poolIndex, "total"],
|
||||
offset: spec.productionIndex,
|
||||
limit: consumptionOffset + 1
|
||||
}, context),
|
||||
self._read({
|
||||
root: "statistics",
|
||||
path: ["production", "factoryStatPool", factoryIndex, "productPool", poolIndex],
|
||||
select: ["refProductSpeed", "refConsumeSpeed"]
|
||||
}, context)
|
||||
]).then(function (pair) {
|
||||
self._assertSession(context);
|
||||
var totals = (pair[0].value && pair[0].value.items) || [];
|
||||
var refs = pair[1].value || {};
|
||||
var productionTotal = toNumber(totals[0]) || 0;
|
||||
var consumptionTotal = toNumber(totals[consumptionOffset]) || 0;
|
||||
return {
|
||||
itemId: itemId,
|
||||
production: spec.perMinute ? productionTotal / spec.divisor : productionTotal,
|
||||
consumption: spec.perMinute ? consumptionTotal / spec.divisor : consumptionTotal,
|
||||
theoreticalProduction: refs.refProductSpeed || 0,
|
||||
theoreticalConsumption: refs.refConsumeSpeed || 0,
|
||||
hit: true
|
||||
};
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype.getItemRates = function (itemId, options) {
|
||||
options = options || {};
|
||||
var windowName = options.window || "1min";
|
||||
var spec = RATE_WINDOWS[windowName];
|
||||
if (!Object.prototype.hasOwnProperty.call(RATE_WINDOWS, windowName)) throw new Error("Unknown production window: " + windowName);
|
||||
var ids = Array.isArray(itemId) ? itemId : [itemId];
|
||||
ids.forEach(function (id) {
|
||||
if (!Number.isInteger(id) || id <= 0) throw new RangeError("Item IDs must be positive integers.");
|
||||
});
|
||||
if (!ids.length) return Promise.resolve([]);
|
||||
var uniqueIds = Array.from(new Set(ids));
|
||||
var self = this;
|
||||
var context = {};
|
||||
return this._factoryIds(options.scope, context).then(function (factoryIds) {
|
||||
self._assertSession(context);
|
||||
var jobs = [];
|
||||
factoryIds.forEach(function (factoryIndex) {
|
||||
uniqueIds.forEach(function (id) { jobs.push(self._readFactoryItem(factoryIndex, id, spec, context)); });
|
||||
});
|
||||
return allReads(jobs);
|
||||
}).then(function (parts) {
|
||||
self._assertSession(context);
|
||||
var byItem = Object.create(null);
|
||||
uniqueIds.forEach(function (id) {
|
||||
byItem[id] = {
|
||||
itemId: id, window: windowName, perMinute: spec.perMinute,
|
||||
production: 0, consumption: 0, theoreticalProduction: 0, theoreticalConsumption: 0, factories: 0
|
||||
};
|
||||
});
|
||||
parts.forEach(function (part) {
|
||||
if (!part) return;
|
||||
var row = byItem[part.itemId];
|
||||
row.production += part.production;
|
||||
row.consumption += part.consumption;
|
||||
row.theoreticalProduction += part.theoreticalProduction;
|
||||
row.theoreticalConsumption += part.theoreticalConsumption;
|
||||
if (part.hit) row.factories++;
|
||||
});
|
||||
var list = ids.map(function (id) {
|
||||
var row = byItem[id];
|
||||
row.sessionId = context.sessionId;
|
||||
row.gameTick = context.gameTick;
|
||||
return row;
|
||||
});
|
||||
return Array.isArray(itemId) ? list : list[0];
|
||||
});
|
||||
};
|
||||
|
||||
var SPHERE_ENERGY_FIELDS = ["energyGenCurrentTick", "energyGenOriginalCurrentTick", "energyReqCurrentTick"];
|
||||
|
||||
GameQuery.prototype._readSphere = function (starIndex, energy, context) {
|
||||
var self = this;
|
||||
return this._read({
|
||||
root: "game",
|
||||
path: ["dysonSpheres", starIndex, "starData"],
|
||||
select: ["index", "id", "name", "overrideName"]
|
||||
}, context).then(function (result) {
|
||||
self._assertSession(context);
|
||||
var star = result.value || {};
|
||||
var joules = toBigInt(energy.energyGenCurrentTick);
|
||||
var original = toBigInt(energy.energyGenOriginalCurrentTick);
|
||||
var watts = joules * BigInt(TICKS_PER_SECOND);
|
||||
return {
|
||||
starIndex: starIndex,
|
||||
starId: star.id,
|
||||
name: star.overrideName || star.name || ("Star " + starIndex),
|
||||
joulesPerTick: joules.toString(),
|
||||
originalJoulesPerTick: original.toString(),
|
||||
watts: watts.toString(),
|
||||
originalWatts: (original * BigInt(TICKS_PER_SECOND)).toString(),
|
||||
wattsNumber: toNumber(watts),
|
||||
energyReqCurrentTick: energy.energyReqCurrentTick != null ? String(energy.energyReqCurrentTick) : "0",
|
||||
sessionId: context.sessionId,
|
||||
gameTick: context.gameTick
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype._collectSpheres = function (offset, spheres, context) {
|
||||
var self = this;
|
||||
var limits = this.client.infoSnapshot && this.client.infoSnapshot.limits;
|
||||
var pageSize = limits && limits.maxPageSize || 128;
|
||||
return this._read({
|
||||
root: "game", path: ["dysonSpheres"], select: SPHERE_ENERGY_FIELDS,
|
||||
offset: offset, limit: Math.min(128, pageSize)
|
||||
}, context).then(function (page) {
|
||||
self._assertSession(context);
|
||||
var items = (page.value && page.value.items) || [];
|
||||
var jobs = [];
|
||||
items.forEach(function (entry, itemIndex) {
|
||||
var index = (page.value.offset || 0) + itemIndex;
|
||||
if (!entry) return;
|
||||
jobs.push(self._readSphere(index, entry, context));
|
||||
});
|
||||
return allReads(jobs).then(function (batch) {
|
||||
Array.prototype.push.apply(spheres, batch);
|
||||
if (page.value && page.value.hasMore) {
|
||||
var nextOffset = (page.value.offset || 0) + items.length;
|
||||
if (nextOffset <= offset) throw new ApiError({ kind: "INVALID_RESPONSE", message: "Collection page made no progress." });
|
||||
return self._collectSpheres(nextOffset, spheres, context);
|
||||
}
|
||||
return spheres;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype.getDysonPower = function (options) {
|
||||
options = options || {};
|
||||
var self = this;
|
||||
var context = {};
|
||||
var request;
|
||||
if (options.starIndex == null) {
|
||||
request = this._collectSpheres(0, [], context);
|
||||
} else {
|
||||
if (!Number.isInteger(options.starIndex) || options.starIndex < 0) throw new RangeError("starIndex must be a nonnegative integer.");
|
||||
request = this._read({
|
||||
root: "game", path: ["dysonSpheres", options.starIndex], select: SPHERE_ENERGY_FIELDS
|
||||
}, context).then(function (result) {
|
||||
if (!result.value) return [];
|
||||
return self._readSphere(options.starIndex, result.value, context).then(function (sphere) { return [sphere]; });
|
||||
});
|
||||
}
|
||||
return request.then(function (spheres) {
|
||||
self._assertSession(context);
|
||||
var total = 0n;
|
||||
var original = 0n;
|
||||
spheres.forEach(function (sphere) {
|
||||
total += toBigInt(sphere.watts);
|
||||
original += toBigInt(sphere.originalWatts);
|
||||
});
|
||||
return {
|
||||
sphereCount: spheres.length,
|
||||
watts: total.toString(),
|
||||
originalWatts: original.toString(),
|
||||
wattsNumber: toNumber(total),
|
||||
joulesPerTick: (total / BigInt(TICKS_PER_SECOND)).toString(),
|
||||
spheres: spheres,
|
||||
sessionId: context.sessionId,
|
||||
gameTick: context.gameTick
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
ns.GameQuery = GameQuery;
|
||||
var LCID_ALIASES = {
|
||||
en: 1033, "en-us": 1033,
|
||||
zh: 2052, "zh-cn": 2052,
|
||||
fr: 1036, "fr-fr": 1036,
|
||||
de: 1031, "de-de": 1031,
|
||||
ja: 1041, "ja-jp": 1041, "ja-ja": 1041
|
||||
};
|
||||
|
||||
function normalizeLcid(language, languages) {
|
||||
if (language == null || language === "") return 1033;
|
||||
if (typeof language === "number") return language;
|
||||
var lower = String(language).toLowerCase();
|
||||
if (Object.prototype.hasOwnProperty.call(LCID_ALIASES, lower)) return LCID_ALIASES[lower];
|
||||
if (/^\d+$/.test(String(language))) return parseInt(language, 10);
|
||||
if (languages) {
|
||||
var ids = Object.keys(languages);
|
||||
for (var i = 0; i < ids.length; i++) {
|
||||
var meta = languages[ids[i]];
|
||||
if (!meta) continue;
|
||||
if (String(meta.abbr).toLowerCase() === lower || String(meta.abbr2).toLowerCase() === lower || String(meta.name).toLowerCase() === lower) {
|
||||
return parseInt(ids[i], 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
return 1033;
|
||||
}
|
||||
|
||||
function GameText(data, options) {
|
||||
options = options || {};
|
||||
this.data = data || { languages: {}, ids: {}, strings: {} };
|
||||
this.lcid = normalizeLcid(options.language, this.data.languages);
|
||||
}
|
||||
|
||||
GameText.fromGenerated = function (options) {
|
||||
var data = (typeof globalThis !== "undefined" && globalThis.LiveStreamAssistTextData) ||
|
||||
(typeof window !== "undefined" && window.LiveStreamAssistTextData) ||
|
||||
null;
|
||||
if (!data) throw new Error("LiveStreamAssistTextData is not loaded. Include generated/dsp-text.js first.");
|
||||
return new GameText(data, options);
|
||||
};
|
||||
|
||||
GameText.prototype.setLanguage = function (language) {
|
||||
this.lcid = normalizeLcid(language, this.data.languages);
|
||||
return this;
|
||||
};
|
||||
|
||||
GameText.prototype.translate = function (nameKey) {
|
||||
if (nameKey == null || nameKey === "") return "";
|
||||
var row = this.data.strings && this.data.strings[nameKey];
|
||||
if (!row) return String(nameKey);
|
||||
var lcid = String(this.lcid);
|
||||
if (row[lcid] != null) return row[lcid];
|
||||
return String(nameKey);
|
||||
};
|
||||
|
||||
GameText.prototype.nameKey = function (kind, id) {
|
||||
var table = this.data.ids && this.data.ids[kind];
|
||||
return table ? table[String(id)] || null : null;
|
||||
};
|
||||
|
||||
GameText.prototype.name = function (kind, id) {
|
||||
var nameKey = this.nameKey(kind, id);
|
||||
return nameKey ? this.translate(nameKey) : "";
|
||||
};
|
||||
|
||||
GameText.prototype.itemName = function (id) { return this.name("item", id); };
|
||||
GameText.prototype.techName = function (id) { return this.name("tech", id); };
|
||||
GameText.prototype.recipeName = function (id) { return this.name("recipe", id); };
|
||||
GameText.prototype.signalName = function (id) { return this.name("signal", id); };
|
||||
GameText.prototype.veinName = function (id) { return this.name("vein", id); };
|
||||
|
||||
GameText.prototype.techDisplayName = function (id, curLevel) {
|
||||
var name = this.techName(id);
|
||||
if (!name) return "";
|
||||
if (!curLevel) return name;
|
||||
return name + this.translate("杠等级") + curLevel;
|
||||
};
|
||||
|
||||
GameText.prototype.separators = function () {
|
||||
var thousand = this.translate("千分分隔符");
|
||||
var decimal = this.translate("小数点");
|
||||
return {
|
||||
thousand: thousand && thousand.length === 1 ? thousand : ",",
|
||||
decimal: decimal && decimal.length === 1 ? decimal : "."
|
||||
};
|
||||
};
|
||||
|
||||
GameText.prototype.formatKmg = function (value, options) {
|
||||
return formatKmg(value, Object.assign({ decimal: this.separators().decimal, kind: "count" }, options));
|
||||
};
|
||||
GameText.prototype.formatPower = function (value, options) {
|
||||
return formatKmg(value, Object.assign({ decimal: this.separators().decimal, kind: "power" }, options));
|
||||
};
|
||||
GameText.prototype.formatEnergy = function (value, options) {
|
||||
return formatKmg(value, Object.assign({ decimal: this.separators().decimal, kind: "energy" }, options));
|
||||
};
|
||||
GameText.prototype.formatRate = function (value) {
|
||||
var seps = this.separators();
|
||||
if (value >= 10000) return this.formatKmg(Math.round(value));
|
||||
if (value >= 1000) return value.toFixed(0);
|
||||
if (value >= 100) return value.toFixed(1).replace(".", seps.decimal);
|
||||
if (value > 0) return value.toFixed(2).replace(".", seps.decimal);
|
||||
return "0";
|
||||
};
|
||||
|
||||
ns.GameText = GameText;
|
||||
function GameIcons(data) {
|
||||
this.data = data || { icons: { item: {}, tech: {} } };
|
||||
}
|
||||
|
||||
GameIcons.fromGenerated = function () {
|
||||
var data = (typeof globalThis !== "undefined" && globalThis.LiveStreamAssistIconData) ||
|
||||
(typeof window !== "undefined" && window.LiveStreamAssistIconData) ||
|
||||
null;
|
||||
if (!data) throw new Error("LiveStreamAssistIconData is not loaded. Include generated/dsp-icons.js first.");
|
||||
return new GameIcons(data);
|
||||
};
|
||||
|
||||
GameIcons.prototype.icon = function (kind, id) {
|
||||
var table = this.data.icons && this.data.icons[kind];
|
||||
return table ? table[String(id)] || null : null;
|
||||
};
|
||||
|
||||
GameIcons.prototype.itemIcon = function (id) { return this.icon("item", id); };
|
||||
GameIcons.prototype.techIcon = function (id) { return this.icon("tech", id); };
|
||||
|
||||
ns.GameIcons = GameIcons;
|
||||
return ns;
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
from generate_text import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract DSP item and tech icons into LiveStreamAssist JS icon data."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from generate_text import DEFAULT_UNITY_VERSION, extract_proto_map, find_game_root
|
||||
|
||||
ICON_CLASSES = ("ItemProtoSet", "TechProtoSet")
|
||||
ICON_SIZE = 80
|
||||
TEXTURE_FILES = ("resources.assets", "sharedassets0.assets")
|
||||
|
||||
|
||||
def collect_icon_names(game_root: Path, unity_version: str) -> dict[str, dict[int, str]]:
|
||||
"""Map item and tech IDs to the texture name from their IconPath field."""
|
||||
names: dict[str, dict[int, str]] = {}
|
||||
for kind, protos in extract_proto_map(game_root, unity_version, ICON_CLASSES).items():
|
||||
mapping: dict[int, str] = {}
|
||||
for proto_id, proto in protos.items():
|
||||
icon_path = proto.get("IconPath")
|
||||
if not icon_path:
|
||||
continue
|
||||
mapping[proto_id] = icon_path.split("/")[-1]
|
||||
names[kind] = mapping
|
||||
return {kind: mapping for kind, mapping in names.items() if mapping}
|
||||
|
||||
|
||||
def load_icon_textures(data_dir: Path, names: set[str]) -> dict[str, object]:
|
||||
"""Load the named textures, preferring the standard square icon size."""
|
||||
import UnityPy
|
||||
|
||||
textures: dict[str, tuple[object, bool]] = {}
|
||||
for filename in TEXTURE_FILES:
|
||||
path = data_dir / filename
|
||||
if not path.is_file():
|
||||
continue
|
||||
env = UnityPy.load(str(path))
|
||||
for obj in env.objects:
|
||||
if getattr(obj.type, "name", str(obj.type)) != "Texture2D":
|
||||
continue
|
||||
try:
|
||||
data = obj.read()
|
||||
except Exception:
|
||||
continue
|
||||
if data.m_Name not in names:
|
||||
continue
|
||||
square = data.m_Width == ICON_SIZE and data.m_Height == ICON_SIZE
|
||||
existing = textures.get(data.m_Name)
|
||||
if existing is None or (square and not existing[1]):
|
||||
textures[data.m_Name] = (data, square)
|
||||
return {name: value[0] for name, value in textures.items()}
|
||||
|
||||
|
||||
def encode_icon(texture: object) -> str:
|
||||
try:
|
||||
image = texture.image
|
||||
except ImportError as exc:
|
||||
raise SystemExit(
|
||||
"Pillow is required to encode icons. Install LiveStreamAssist/js/scripts/requirements.txt."
|
||||
) from exc
|
||||
if image.mode != "RGBA":
|
||||
image = image.convert("RGBA")
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, "PNG", optimize=True)
|
||||
return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode("ascii")
|
||||
|
||||
|
||||
def build_payload(game_root: Path, unity_version: str) -> tuple[dict, list[str]]:
|
||||
names = collect_icon_names(game_root, unity_version)
|
||||
if not names.get("item") or not names.get("tech"):
|
||||
raise SystemExit("Prototype extraction did not produce item and tech icons; generated data was not written.")
|
||||
textures = load_icon_textures(game_root / "DSPGAME_Data", {name for mapping in names.values() for name in mapping.values()})
|
||||
icons: dict[str, dict[str, str]] = {}
|
||||
missing: list[str] = []
|
||||
for kind, mapping in names.items():
|
||||
icons[kind] = {}
|
||||
for proto_id, texture_name in sorted(mapping.items()):
|
||||
texture = textures.get(texture_name)
|
||||
if texture is None:
|
||||
missing.append(f"{kind} {proto_id} ({texture_name})")
|
||||
continue
|
||||
icons[kind][str(proto_id)] = encode_icon(texture)
|
||||
return {"version": "1.0.0", "icons": icons}, missing
|
||||
|
||||
|
||||
def emit_js(payload: dict) -> str:
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
return (
|
||||
"/* Generated from a local Dyson Sphere Program install by generate_icons.py. Do not edit. */\n"
|
||||
"globalThis.LiveStreamAssistIconData = "
|
||||
+ body
|
||||
+ ";\n"
|
||||
)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--game-root", help="DSP install directory containing DSPGAME_Data")
|
||||
parser.add_argument("--unity-version", default=DEFAULT_UNITY_VERSION)
|
||||
parser.add_argument(
|
||||
"--out",
|
||||
default=str(Path(__file__).resolve().parents[1] / "generated" / "dsp-icons.js"),
|
||||
help="Output JS path",
|
||||
)
|
||||
parser.add_argument("--json-out", help="Optional JSON output path")
|
||||
args = parser.parse_args(argv)
|
||||
game_root = find_game_root(args.game_root)
|
||||
if game_root is None:
|
||||
raise SystemExit("Dyson Sphere Program install not found. Pass --game-root.")
|
||||
payload, missing = build_payload(game_root, args.unity_version)
|
||||
for entry in missing:
|
||||
print(f"Warning: icon texture not found for {entry}", file=sys.stderr)
|
||||
out_path = Path(args.out)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(emit_js(payload), encoding="utf-8", newline="\n")
|
||||
if args.json_out:
|
||||
json_path = Path(args.json_out)
|
||||
json_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8", newline="\n")
|
||||
item_count = len(payload["icons"].get("item", {}))
|
||||
tech_count = len(payload["icons"].get("tech", {}))
|
||||
print(f"Wrote {out_path} (items={item_count}, techs={tech_count}, bytes={out_path.stat().st_size})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,398 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Convert DSP Locale files and prototype tables into LiveStreamAssist JS text data."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
DSP_APPID = "1366540"
|
||||
DEFAULT_UNITY_VERSION = "2022.3.7"
|
||||
KIND_FROM_SET = {
|
||||
"ItemProtoSet": "item",
|
||||
"TechProtoSet": "tech",
|
||||
"RecipeProtoSet": "recipe",
|
||||
"SignalProtoSet": "signal",
|
||||
"VeinProtoSet": "vein",
|
||||
"EnemyProtoSet": "enemy",
|
||||
"ModelProtoSet": "model",
|
||||
"ThemeProtoSet": "theme",
|
||||
"AchievementProtoSet": "achievement",
|
||||
"TutorialProtoSet": "tutorial",
|
||||
"MilestoneProtoSet": "milestone",
|
||||
"GoalProtoSet": "goal",
|
||||
"AudioProtoSet": "audio",
|
||||
"PromptProtoSet": "prompt",
|
||||
"AdvisorTipProtoSet": "advisorTip",
|
||||
"JournalPatternProtoSet": "journalPattern",
|
||||
"CosmicMessageProtoSet": "cosmicMessage",
|
||||
"DoodadProtoSet": "doodad",
|
||||
"AbnormalityProtoSet": "abnormality",
|
||||
"FleetProtoSet": "fleet",
|
||||
"CreationPartProtoSet": "creationPart",
|
||||
"EffectEmitterProtoSet": "effectEmitter",
|
||||
"MIDIProtoSet": "midi",
|
||||
"PlayerProtoSet": "player",
|
||||
"VegeProtoSet": "vege",
|
||||
}
|
||||
EXTRA_STRING_KEYS = ("千分分隔符", "小数点", "杠等级")
|
||||
|
||||
|
||||
def unescape_string(text: str) -> str:
|
||||
out = []
|
||||
i = 0
|
||||
while i < len(text):
|
||||
ch = text[i]
|
||||
if ch == "\\" and i + 1 < len(text):
|
||||
i += 1
|
||||
nxt = text[i]
|
||||
mapping = {"\\": "\\", "r": "\r", "n": "\n", "t": "\t", "v": "\v", "f": "\f"}
|
||||
if nxt in mapping:
|
||||
out.append(mapping[nxt])
|
||||
else:
|
||||
out.append("\\")
|
||||
out.append(nxt)
|
||||
else:
|
||||
out.append(ch)
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def first_field(line: str) -> str:
|
||||
tab = line.find("\t")
|
||||
raw = line if tab < 0 else line[:tab]
|
||||
return unescape_string(raw)
|
||||
|
||||
|
||||
def translation_field(line: str) -> str | None:
|
||||
tab1 = line.find(" ")
|
||||
if tab1 < 0:
|
||||
return None
|
||||
tab2 = line.find(" ", tab1 + 1)
|
||||
if tab2 < 0:
|
||||
return None
|
||||
tab3 = line.find(" ", tab2 + 1)
|
||||
if tab3 < 0:
|
||||
return None
|
||||
return unescape_string(line[tab3 + 1 :])
|
||||
|
||||
|
||||
def read_locale_text(path: Path) -> str:
|
||||
data = path.read_bytes()
|
||||
if data.startswith((b'\xff\xfe', b'\xfe\xff')):
|
||||
return data.decode('utf-16')
|
||||
if data.startswith(b'\xef\xbb\xbf'):
|
||||
return data.decode('utf-8-sig')
|
||||
try:
|
||||
return data.decode('utf-8')
|
||||
except UnicodeDecodeError:
|
||||
return data.decode('utf-16')
|
||||
|
||||
|
||||
def parse_header(header_path: Path) -> tuple[list[dict], list[str]]:
|
||||
text = read_locale_text(header_path)
|
||||
lines = text.splitlines()
|
||||
languages: list[dict] = []
|
||||
page_order: dict[str, int] = {}
|
||||
in_langs = False
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("Version="):
|
||||
in_langs = True
|
||||
continue
|
||||
if in_langs and stripped and "," in stripped and not stripped.startswith("[") and "=" not in stripped.split(",", 1)[0]:
|
||||
parts = stripped.split(",")
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
try:
|
||||
lcid = int(parts[0])
|
||||
except ValueError:
|
||||
continue
|
||||
if lcid <= 0 or any(lang["lcid"] == lcid for lang in languages):
|
||||
continue
|
||||
languages.append(
|
||||
{
|
||||
"lcid": lcid,
|
||||
"name": parts[1],
|
||||
"abbr": parts[2] if len(parts) > 2 else parts[1].lower(),
|
||||
"abbr2": parts[3] if len(parts) > 3 else (parts[2] if len(parts) > 2 else parts[1].lower()),
|
||||
"fallback": int(parts[4]) if len(parts) > 4 and parts[4].isdigit() else 0,
|
||||
}
|
||||
)
|
||||
continue
|
||||
if "=" in stripped:
|
||||
key, _, value = stripped.partition("=")
|
||||
key = key.strip()
|
||||
try:
|
||||
page_order[key] = int(value.strip())
|
||||
except ValueError:
|
||||
continue
|
||||
pages = sorted(page_order, key=page_order.get)
|
||||
return languages, [name + ".txt" for name in pages]
|
||||
|
||||
|
||||
def load_name_keys(names_dir: Path, pages: list[str]) -> list[str]:
|
||||
keys: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for page in pages:
|
||||
path = names_dir / page
|
||||
if not path.is_file():
|
||||
continue
|
||||
for line in read_locale_text(path).splitlines():
|
||||
if not line:
|
||||
continue
|
||||
key = first_field(line)
|
||||
if not key or key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
keys.append(key)
|
||||
return keys
|
||||
|
||||
|
||||
def load_language_strings(lang_dir: Path, pages: list[str], keys: list[str]) -> dict[str, str]:
|
||||
index = {key: i for i, key in enumerate(keys)}
|
||||
values: list[str | None] = [None] * len(keys)
|
||||
for page in pages:
|
||||
path = lang_dir / page
|
||||
if not path.is_file():
|
||||
continue
|
||||
for line in read_locale_text(path).splitlines():
|
||||
if not line:
|
||||
continue
|
||||
key = first_field(line)
|
||||
if key not in index:
|
||||
continue
|
||||
slot = index[key]
|
||||
if values[slot] is not None:
|
||||
continue
|
||||
translated = translation_field(line)
|
||||
if translated is None:
|
||||
continue
|
||||
values[slot] = translated
|
||||
result = {}
|
||||
for key, value in zip(keys, values):
|
||||
result[key] = key if value is None else value
|
||||
return result
|
||||
|
||||
|
||||
def steam_path() -> Path | None:
|
||||
if os.name != "nt":
|
||||
return None
|
||||
try:
|
||||
import winreg
|
||||
except ImportError:
|
||||
return None
|
||||
roots = [
|
||||
(winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"Software\Valve\Steam"),
|
||||
(winreg.HKEY_LOCAL_MACHINE, r"Software\Wow6432Node\Valve\Steam"),
|
||||
]
|
||||
for hive, key in roots:
|
||||
try:
|
||||
with winreg.OpenKey(hive, key) as handle:
|
||||
value, _ = winreg.QueryValueEx(handle, "SteamPath")
|
||||
except OSError:
|
||||
continue
|
||||
if value:
|
||||
path = Path(str(value))
|
||||
if path.exists():
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def parse_library_folders(vdf_text: str) -> list[Path]:
|
||||
block_re = re.compile(r'"(?:\d+)"\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}', re.S)
|
||||
path_re = re.compile(r'"path"\s+"([^"]+)"')
|
||||
app_re = re.compile(r'"' + DSP_APPID + r'"\s+"[^"]+"')
|
||||
paths = []
|
||||
for block in block_re.finditer(vdf_text):
|
||||
text = block.group(1)
|
||||
if not app_re.search(text):
|
||||
continue
|
||||
match = path_re.search(text)
|
||||
if not match:
|
||||
continue
|
||||
raw = match.group(1).replace("\\\\", "\\").replace("/", "\\")
|
||||
paths.append(Path(raw))
|
||||
return paths
|
||||
|
||||
|
||||
def find_game_root(explicit: str | None) -> Path | None:
|
||||
if explicit:
|
||||
path = Path(explicit)
|
||||
if (path / "DSPGAME_Data").is_dir():
|
||||
return path
|
||||
raise SystemExit(f"DSP game root not found at {path}")
|
||||
env = os.environ.get("DSP_ROOT") or os.environ.get("DSPGAME_ROOT")
|
||||
if env:
|
||||
path = Path(env)
|
||||
if (path / "DSPGAME_Data").is_dir():
|
||||
return path
|
||||
steam = steam_path()
|
||||
if steam is None:
|
||||
return None
|
||||
vdf = steam / "steamapps" / "libraryfolders.vdf"
|
||||
if not vdf.is_file():
|
||||
return None
|
||||
for library in parse_library_folders(vdf.read_text(encoding="utf-8", errors="ignore")):
|
||||
candidate = library / "steamapps" / "common" / "Dyson Sphere Program"
|
||||
if (candidate / "DSPGAME_Data").is_dir():
|
||||
return candidate
|
||||
fallback = steam / "steamapps" / "common" / "Dyson Sphere Program"
|
||||
if (fallback / "DSPGAME_Data").is_dir():
|
||||
return fallback
|
||||
return None
|
||||
|
||||
|
||||
def extract_proto_map(
|
||||
game_root: Path, unity_version: str, class_names: set[str] | None = None
|
||||
) -> dict[str, dict[int, dict]]:
|
||||
"""Extract prototype entries keyed by kind and ID, keeping the raw fields."""
|
||||
try:
|
||||
import UnityPy
|
||||
from UnityPy.helpers.TypeTreeGenerator import TypeTreeGenerator
|
||||
except ImportError as exc:
|
||||
raise SystemExit(
|
||||
"UnityPy and TypeTreeGeneratorAPI are required to extract prototype IDs. "
|
||||
"Install LiveStreamAssist/js/scripts/requirements.txt."
|
||||
) from exc
|
||||
|
||||
wanted = class_names or KIND_FROM_SET
|
||||
data_dir = game_root / "DSPGAME_Data"
|
||||
generator = TypeTreeGenerator(unity_version)
|
||||
generator.load_local_game(str(game_root))
|
||||
ggm = UnityPy.load(str(data_dir / "globalgamemanagers.assets"))
|
||||
script_ids = {}
|
||||
for obj in ggm.objects:
|
||||
if getattr(obj.type, "name", str(obj.type)) != "MonoScript":
|
||||
continue
|
||||
script = obj.read()
|
||||
class_name = getattr(script, "m_ClassName", "")
|
||||
if class_name in wanted:
|
||||
script_ids[obj.path_id] = class_name
|
||||
|
||||
resources = UnityPy.load(str(data_dir / "resources.assets"))
|
||||
nodes = {
|
||||
class_name: generator.get_nodes_up("Assembly-CSharp.dll", class_name)
|
||||
for class_name in wanted
|
||||
}
|
||||
protos: dict[str, dict[int, dict]] = {KIND_FROM_SET[cn]: {} for cn in wanted}
|
||||
for obj in resources.objects:
|
||||
if getattr(obj.type, "name", str(obj.type)) != "MonoBehaviour":
|
||||
continue
|
||||
try:
|
||||
peek = obj.read_typetree(check_read=False)
|
||||
except Exception:
|
||||
continue
|
||||
script = peek.get("m_Script") or {}
|
||||
class_name = script_ids.get(script.get("m_PathID"))
|
||||
if class_name is None:
|
||||
continue
|
||||
kind = KIND_FROM_SET[class_name]
|
||||
tree = obj.read_typetree(nodes[class_name], check_read=False)
|
||||
for proto in tree.get("dataArray") or []:
|
||||
proto_id = proto.get("ID")
|
||||
if not proto_id:
|
||||
continue
|
||||
protos[kind][int(proto_id)] = proto
|
||||
return {kind: mapping for kind, mapping in protos.items() if mapping}
|
||||
|
||||
|
||||
def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str, str]]:
|
||||
ids: dict[str, dict[str, str]] = {}
|
||||
for kind, protos in extract_proto_map(game_root, unity_version).items():
|
||||
mapping: dict[str, str] = {}
|
||||
for proto_id, proto in protos.items():
|
||||
name = proto.get("Name")
|
||||
if not name:
|
||||
continue
|
||||
mapping[str(proto_id)] = name
|
||||
ids[kind] = mapping
|
||||
return {kind: mapping for kind, mapping in ids.items() if mapping}
|
||||
|
||||
|
||||
def collect_needed_keys(all_keys: list[str], ids: dict[str, dict[str, str]]) -> list[str]:
|
||||
needed = set(EXTRA_STRING_KEYS)
|
||||
for mapping in ids.values():
|
||||
needed.update(mapping.values())
|
||||
ordered = [key for key in all_keys if key in needed]
|
||||
for key in EXTRA_STRING_KEYS:
|
||||
if key not in ordered:
|
||||
ordered.append(key)
|
||||
return ordered
|
||||
|
||||
|
||||
def build_payload(game_root: Path, unity_version: str) -> dict:
|
||||
locale_dir = game_root / "Locale"
|
||||
header = locale_dir / "Header.txt"
|
||||
if not header.is_file():
|
||||
raise SystemExit(f"Locale header not found: {header}")
|
||||
languages, pages = parse_header(header)
|
||||
keys = load_name_keys(locale_dir / "Names", pages)
|
||||
ids = extract_proto_ids(game_root, unity_version)
|
||||
if not ids.get("item") or not ids.get("tech"):
|
||||
raise SystemExit("Prototype extraction did not produce item and tech IDs; generated data was not written.")
|
||||
needed_keys = collect_needed_keys(keys, ids)
|
||||
strings: dict[str, dict[str, str]] = {key: {} for key in needed_keys}
|
||||
language_meta = {}
|
||||
for lang in languages:
|
||||
lang_dir = locale_dir / str(lang["lcid"])
|
||||
if not lang_dir.is_dir():
|
||||
continue
|
||||
table = load_language_strings(lang_dir, pages, keys)
|
||||
language_meta[str(lang["lcid"])] = lang
|
||||
for key in needed_keys:
|
||||
strings[key][str(lang["lcid"])] = table.get(key, key)
|
||||
return {
|
||||
"version": "1.0.0",
|
||||
"languages": language_meta,
|
||||
"ids": ids,
|
||||
"strings": strings,
|
||||
}
|
||||
|
||||
|
||||
def emit_js(payload: dict) -> str:
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
return (
|
||||
"/* Generated from a local Dyson Sphere Program install by generate_text.py. Do not edit. */\n"
|
||||
"globalThis.LiveStreamAssistTextData = "
|
||||
+ body
|
||||
+ ";\n"
|
||||
)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--game-root", help="DSP install directory containing DSPGAME_Data and Locale")
|
||||
parser.add_argument("--unity-version", default=DEFAULT_UNITY_VERSION)
|
||||
parser.add_argument(
|
||||
"--out",
|
||||
default=str(Path(__file__).resolve().parents[1] / "generated" / "dsp-text.js"),
|
||||
help="Output JS path",
|
||||
)
|
||||
parser.add_argument("--json-out", help="Optional JSON output path")
|
||||
args = parser.parse_args(argv)
|
||||
game_root = find_game_root(args.game_root)
|
||||
if game_root is None:
|
||||
raise SystemExit("Dyson Sphere Program install not found. Pass --game-root.")
|
||||
payload = build_payload(game_root, args.unity_version)
|
||||
out_path = Path(args.out)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(emit_js(payload), encoding="utf-8", newline="\n")
|
||||
if args.json_out:
|
||||
json_path = Path(args.json_out)
|
||||
json_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8", newline="\n")
|
||||
item_count = len(payload["ids"].get("item", {}))
|
||||
tech_count = len(payload["ids"].get("tech", {}))
|
||||
print(f"Wrote {out_path} (items={item_count}, techs={tech_count}, strings={len(payload['strings'])})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Reference implementation of DSP StringBuilderUtility KMG formatting."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
NUM = "0123456789"
|
||||
THIN_SPACE = "\u2009"
|
||||
|
||||
|
||||
def write_kmg(
|
||||
value,
|
||||
last_index: int = 8,
|
||||
blank: bool = False,
|
||||
blank_char: str = THIN_SPACE,
|
||||
fill_char: str = " ",
|
||||
decimal: str = ".",
|
||||
kind: str = "count",
|
||||
) -> str:
|
||||
buf = [fill_char] * (last_index + 1)
|
||||
n = int(value)
|
||||
sign = 0
|
||||
if n > 0:
|
||||
sign = 1
|
||||
elif n < 0:
|
||||
sign = -1
|
||||
n = -n
|
||||
pos = last_index
|
||||
if kind == "power":
|
||||
buf[pos] = "W"
|
||||
pos -= 1
|
||||
elif kind == "energy":
|
||||
buf[pos] = "J"
|
||||
pos -= 1
|
||||
threshold = 1000 if kind == "si1000" else 10000
|
||||
if n < threshold:
|
||||
if blank:
|
||||
buf[pos] = blank_char
|
||||
pos -= 1
|
||||
while n > 0:
|
||||
buf[pos] = NUM[n % 10]
|
||||
pos -= 1
|
||||
if pos < 0:
|
||||
return "".join(buf)
|
||||
n //= 10
|
||||
else:
|
||||
if n < 1_000_000:
|
||||
suffix, scale = "k", 1000
|
||||
elif n < 1_000_000_000:
|
||||
suffix, scale = "M", 1_000_000
|
||||
elif n < 1_000_000_000_000:
|
||||
suffix, scale = "G", 1_000_000_000
|
||||
elif n < 1_000_000_000_000_000:
|
||||
suffix, scale = "T", 1_000_000_000_000
|
||||
elif n < 1_000_000_000_000_000_000:
|
||||
suffix, scale = "P", 1_000_000_000_000_000
|
||||
else:
|
||||
suffix, scale = "E", 1_000_000_000_000_000_000
|
||||
buf[pos] = suffix
|
||||
pos -= 1
|
||||
if blank:
|
||||
buf[pos] = blank_char
|
||||
pos -= 1
|
||||
acc = 1
|
||||
while n >= 1000:
|
||||
n //= 10
|
||||
acc *= 10
|
||||
while n > 0:
|
||||
buf[pos] = NUM[n % 10]
|
||||
pos -= 1
|
||||
if pos < 0:
|
||||
return "".join(buf)
|
||||
n //= 10
|
||||
acc *= 10
|
||||
if acc == scale:
|
||||
buf[pos] = decimal
|
||||
pos -= 1
|
||||
if pos < 0:
|
||||
return "".join(buf)
|
||||
if sign == 0:
|
||||
buf[pos] = "0"
|
||||
pos -= 1
|
||||
elif sign < 0:
|
||||
buf[pos] = "-"
|
||||
pos -= 1
|
||||
return "".join(buf)
|
||||
|
||||
|
||||
def format_kmg(value, kind: str = "count", blank: bool = False, decimal: str = ".", trim: bool = True) -> str:
|
||||
raw = write_kmg(value, kind=kind, blank=blank, decimal=decimal)
|
||||
return raw.strip() if trim else raw
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SRC = ROOT / "src"
|
||||
OUT = ROOT / "livestream-assist.js"
|
||||
parts = [
|
||||
SRC / "header.js",
|
||||
SRC / "format.js",
|
||||
SRC / "client.js",
|
||||
SRC / "query.js",
|
||||
SRC / "text.js",
|
||||
SRC / "icons.js",
|
||||
SRC / "footer.js",
|
||||
]
|
||||
text = "".join(path.read_text(encoding="utf-8") for path in parts)
|
||||
if not text.endswith("\n"):
|
||||
text += "\n"
|
||||
OUT.write_text(text, encoding="utf-8", newline="\n")
|
||||
print(f"Wrote {OUT} ({OUT.stat().st_size} bytes)")
|
||||
@@ -0,0 +1,2 @@
|
||||
UnityPy>=1.20
|
||||
TypeTreeGeneratorAPI>=0.0.10
|
||||
@@ -0,0 +1,221 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
const { createHarness, observe, flush } = require("./test_helpers");
|
||||
|
||||
test("close cancels a connecting socket and permits an explicit reconnect", async () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const client = new api.Client();
|
||||
const first = observe(client.connect());
|
||||
client.close();
|
||||
await flush();
|
||||
assert.equal(first.status, "rejected");
|
||||
assert.equal(first.error.kind, "DISCONNECTED");
|
||||
assert.equal(sockets[0].readyState, 3);
|
||||
const second = observe(client.connect());
|
||||
assert.equal(sockets.length, 2);
|
||||
sockets[1].open();
|
||||
await flush();
|
||||
assert.equal(second.status, "fulfilled");
|
||||
assert.equal(client.autoReconnect, true);
|
||||
client.close();
|
||||
});
|
||||
|
||||
test("a malformed URL does not poison later connections", async () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const client = new api.Client({ url: "not a URL" });
|
||||
const failed = observe(client.connect());
|
||||
await flush();
|
||||
assert.equal(failed.status, "rejected");
|
||||
const retry = observe(client.connect("ws://localhost:18080/api/v1"));
|
||||
assert.equal(sockets.length, 1);
|
||||
sockets[0].open();
|
||||
await flush();
|
||||
assert.equal(retry.status, "fulfilled");
|
||||
client.close();
|
||||
});
|
||||
|
||||
test("connect with another URL replaces an open connection", async () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const client = new api.Client();
|
||||
const first = client.connect();
|
||||
sockets[0].open();
|
||||
await first;
|
||||
const second = observe(client.connect("ws://localhost:19090/api/v1"));
|
||||
assert.equal(sockets[0].readyState, 3);
|
||||
assert.equal(sockets.length, 2);
|
||||
sockets[1].open();
|
||||
await flush();
|
||||
assert.equal(second.status, "fulfilled");
|
||||
client.close();
|
||||
});
|
||||
|
||||
test("disconnect rejects sent and queued calls without leaking capacity", async () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const client = new api.Client({ maxPending: 1, autoReconnect: false });
|
||||
const requests = [observe(client.ping()), observe(client.ping()), observe(client.ping())];
|
||||
sockets[0].open();
|
||||
await flush();
|
||||
assert.equal(sockets[0].sent.length, 1);
|
||||
sockets[0].close(1006);
|
||||
await flush();
|
||||
for (const request of requests) {
|
||||
assert.equal(request.status, "rejected");
|
||||
assert.equal(request.error.kind, "DISCONNECTED");
|
||||
}
|
||||
assert.equal(client._active, 0);
|
||||
const retry = observe(client.ping());
|
||||
sockets[1].open();
|
||||
await flush();
|
||||
assert.equal(sockets[1].sent.length, 1);
|
||||
sockets[1].reply(sockets[1].sent[0], "fresh");
|
||||
await flush();
|
||||
assert.equal(retry.value, "fresh");
|
||||
client.close();
|
||||
});
|
||||
|
||||
test("requests do not implicitly reopen an explicitly closed client", async () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const client = new api.Client();
|
||||
client.close();
|
||||
const request = observe(client.ping());
|
||||
await flush();
|
||||
assert.equal(request.status, "rejected");
|
||||
assert.equal(request.error.kind, "DISCONNECTED");
|
||||
assert.equal(sockets.length, 0);
|
||||
});
|
||||
|
||||
test("responses correlate by id and preserve Int64 strings", async () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const client = new api.Client({ maxPending: 2 });
|
||||
const first = observe(client.ping());
|
||||
const second = observe(client.ping());
|
||||
sockets[0].open();
|
||||
await flush();
|
||||
sockets[0].reply(sockets[0].sent[1], "9223372036854775807");
|
||||
sockets[0].reply(sockets[0].sent[0], "first");
|
||||
await flush();
|
||||
assert.equal(first.value, "first");
|
||||
assert.equal(second.value, "9223372036854775807");
|
||||
assert.equal(client._active, 0);
|
||||
client.close();
|
||||
});
|
||||
|
||||
test("timeouts release the next queued call exactly once", async () => {
|
||||
const { api, sockets, clock } = createHarness();
|
||||
const client = new api.Client({ maxPending: 1, requestTimeoutMs: 50 });
|
||||
const first = observe(client.ping());
|
||||
const second = observe(client.ping());
|
||||
sockets[0].open();
|
||||
await flush();
|
||||
clock.advance(50);
|
||||
await flush();
|
||||
assert.equal(first.error.kind, "CLIENT_TIMEOUT");
|
||||
assert.equal(sockets[0].sent.length, 2);
|
||||
sockets[0].reply(sockets[0].sent[0], "late");
|
||||
sockets[0].reply(sockets[0].sent[1], "second");
|
||||
await flush();
|
||||
assert.equal(second.value, "second");
|
||||
assert.equal(client._active, 0);
|
||||
assert.equal(clock.size, 0);
|
||||
client.close();
|
||||
});
|
||||
|
||||
test("server limits respect a lower caller limit", async () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const client = new api.Client({ maxPending: 1 });
|
||||
const info = client.systemInfo();
|
||||
sockets[0].open();
|
||||
await flush();
|
||||
sockets[0].reply(sockets[0].sent[0], { limits: { maxPendingRequestsPerConnection: 8 } });
|
||||
await info;
|
||||
assert.equal(client.maxPending, 1);
|
||||
client.close();
|
||||
});
|
||||
|
||||
test("close cancels automatic reconnect timers", async () => {
|
||||
const { api, sockets, clock } = createHarness();
|
||||
const client = new api.Client();
|
||||
const connection = client.connect();
|
||||
sockets[0].open();
|
||||
await connection;
|
||||
sockets[0].close(1006);
|
||||
assert.equal(clock.size, 1);
|
||||
client.close();
|
||||
assert.equal(clock.size, 0);
|
||||
clock.advance(10000);
|
||||
assert.equal(sockets.length, 1);
|
||||
});
|
||||
|
||||
test("invalid request limits fail instead of hanging the queue", () => {
|
||||
const { api } = createHarness();
|
||||
for (const maxPending of [0, -1, NaN, 1.5]) {
|
||||
assert.throws(() => new api.Client({ maxPending }), { name: "RangeError" });
|
||||
}
|
||||
});
|
||||
|
||||
test("a slot released just before reconnect cannot send on the new socket", async () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const client = new api.Client({ maxPending: 1 });
|
||||
observe(client.ping());
|
||||
const queued = observe(client.ping());
|
||||
sockets[0].open();
|
||||
await flush();
|
||||
sockets[0].reply(sockets[0].sent[0], "complete");
|
||||
client.close();
|
||||
const connection = client.connect();
|
||||
sockets[1].open();
|
||||
await connection;
|
||||
const current = observe(client.ping());
|
||||
await flush();
|
||||
assert.equal(queued.error.kind, "DISCONNECTED");
|
||||
assert.equal(sockets[1].sent.length, 1);
|
||||
assert.equal(client._active, 1);
|
||||
sockets[1].reply(sockets[1].sent[0], "current");
|
||||
await flush();
|
||||
assert.equal(current.value, "current");
|
||||
assert.equal(client._active, 0);
|
||||
client.close();
|
||||
});
|
||||
|
||||
test("closing after open but before request continuations rejects old work", async () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const client = new api.Client();
|
||||
const old = observe(client.ping());
|
||||
sockets[0].open();
|
||||
client.close();
|
||||
const connection = client.connect();
|
||||
sockets[1].open();
|
||||
await connection;
|
||||
await flush();
|
||||
assert.equal(old.error.kind, "DISCONNECTED");
|
||||
assert.equal(sockets[1].sent.length, 0);
|
||||
client.close();
|
||||
});
|
||||
|
||||
test("status callback failures do not strand connections", async () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const client = new api.Client({ onStatus() { throw new Error("Consumer callback"); } });
|
||||
const connection = observe(client.connect());
|
||||
sockets[0].open();
|
||||
await flush();
|
||||
assert.equal(connection.status, "fulfilled");
|
||||
client.close();
|
||||
});
|
||||
|
||||
test("automatic reconnect recovers from an initial handshake failure", async () => {
|
||||
const { api, sockets, clock } = createHarness();
|
||||
const client = new api.Client();
|
||||
const initial = observe(client.connect());
|
||||
sockets[0].close(1006);
|
||||
await flush();
|
||||
assert.equal(initial.error.kind, "CONNECT_FAILED");
|
||||
clock.advance(500);
|
||||
assert.equal(sockets.length, 2);
|
||||
sockets[1].open();
|
||||
const request = observe(client.ping());
|
||||
await flush();
|
||||
sockets[1].reply(sockets[1].sent[0], "reconnected");
|
||||
await flush();
|
||||
assert.equal(request.value, "reconnected");
|
||||
client.close();
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const test = require("node:test");
|
||||
const vm = require("node:vm");
|
||||
const { ROOT, createHarness, flush } = require("./test_helpers");
|
||||
|
||||
const TEXT_DATA = {
|
||||
languages: { "2052": { lcid: 2052, name: "简体中文", abbr: "zh-CN", abbr2: "zh" } },
|
||||
ids: {
|
||||
item: { 1101: "铁矿名", 1203: "电动机名" },
|
||||
tech: { 1001: "电磁学名", 1002: "高效学名" }
|
||||
},
|
||||
strings: {
|
||||
铁矿名: { "2052": "铁矿石" },
|
||||
电动机名: { "2052": "电动机" },
|
||||
电磁学名: { "2052": "电磁学" },
|
||||
高效学名: { "2052": "高效采集" }
|
||||
}
|
||||
};
|
||||
|
||||
function createDocument() {
|
||||
const byId = new Map();
|
||||
const created = [];
|
||||
function makeElement(tag) {
|
||||
const element = {
|
||||
tagName: String(tag).toUpperCase(), children: [], parentNode: null,
|
||||
textContent: "", className: "", src: "", alt: "", hidden: false,
|
||||
rowSpan: 0, style: {},
|
||||
classList: {
|
||||
set: new Set(),
|
||||
add(token) { this.set.add(token); },
|
||||
remove(token) { this.set.delete(token); },
|
||||
toggle(token, force) {
|
||||
const next = force == null ? !this.set.has(token) : !!force;
|
||||
if (next) this.set.add(token); else this.set.delete(token);
|
||||
return next;
|
||||
},
|
||||
contains(token) { return this.set.has(token); }
|
||||
},
|
||||
appendChild(child) { child.parentNode = element; element.children.push(child); return child; },
|
||||
removeAttribute() {},
|
||||
setAttribute(name, value) { element[name] = value; }
|
||||
};
|
||||
Object.defineProperty(element, "id", {
|
||||
get() { return element._id || ""; },
|
||||
set(value) { element._id = value; if (value) byId.set(value, element); }
|
||||
});
|
||||
created.push(element);
|
||||
return element;
|
||||
}
|
||||
const body = makeElement("body");
|
||||
return { created, byId, document: { createElement: makeElement, getElementById: id => byId.get(id) || null, body } };
|
||||
}
|
||||
|
||||
function openDashboard(options = {}) {
|
||||
const { context, clock } = createHarness();
|
||||
const { created, byId, document } = createDocument();
|
||||
const calls = [];
|
||||
const clients = [];
|
||||
const events = new Map();
|
||||
const base = context.LiveStreamAssist;
|
||||
class FakeClient {
|
||||
constructor(settings) { this.url = settings.url; this.connections = []; clients.push(this); }
|
||||
connect(url) {
|
||||
if (url != null) this.url = url;
|
||||
this.connections.push(url);
|
||||
if (options.failFirst && this.connections.length === 1) return Promise.reject({ kind: "CONNECT_FAILED" });
|
||||
return Promise.resolve(this);
|
||||
}
|
||||
close() { this.infoSnapshot = null; }
|
||||
systemInfo() { this.infoSnapshot = {}; return Promise.resolve(this.infoSnapshot); }
|
||||
validate() { return Promise.resolve({}); }
|
||||
}
|
||||
class FakeQuery {
|
||||
getItemRates(ids, opts) {
|
||||
calls.push(["rates", ids.slice(), opts]);
|
||||
if (options.pendingRates) return options.pendingRates;
|
||||
return Promise.resolve(ids.map(id => ({
|
||||
itemId: id, perMinute: true, production: 3, consumption: 1,
|
||||
theoreticalProduction: 4, theoreticalConsumption: 2
|
||||
})));
|
||||
}
|
||||
getTechState(id) {
|
||||
calls.push(["tech", id]);
|
||||
const custom = options.techStates && options.techStates[id];
|
||||
return Promise.resolve(custom || { techId: id, unlocked: false, curLevel: 2, maxLevel: 10 });
|
||||
}
|
||||
getCurrentResearch() {
|
||||
calls.push(["research"]);
|
||||
return Promise.resolve(options.research || {
|
||||
active: true, techId: 1001, curLevel: 0, progressPercent: 42.5,
|
||||
hashUploaded: "12345", hashNeeded: "67890"
|
||||
});
|
||||
}
|
||||
getDysonPower() {
|
||||
calls.push(["dyson"]);
|
||||
return Promise.resolve({ watts: "60900000" });
|
||||
}
|
||||
}
|
||||
context.LiveStreamAssist = Object.assign({}, base, {
|
||||
Client: FakeClient,
|
||||
GameQuery: FakeQuery,
|
||||
GameText: { fromGenerated(settings) { return new base.GameText(TEXT_DATA, settings); } },
|
||||
GameIcons: {
|
||||
fromGenerated() {
|
||||
return { itemIcon: id => "icon-item-" + id, techIcon: id => "icon-tech-" + id };
|
||||
}
|
||||
}
|
||||
});
|
||||
for (const id of ["panel", "status"]) {
|
||||
const element = document.createElement("div");
|
||||
element.id = id;
|
||||
document.body.appendChild(element);
|
||||
}
|
||||
Object.assign(context, {
|
||||
location: { search: options.search || "" },
|
||||
URLSearchParams,
|
||||
document,
|
||||
console,
|
||||
addEventListener(name, callback) { events.set(name, callback); }
|
||||
});
|
||||
const html = fs.readFileSync(path.join(ROOT, "..", "examples", "live-dashboard.html"), "utf8");
|
||||
const scripts = [...html.matchAll(/<script(?:[^>]*)>([\s\S]*?)<\/script>/g)];
|
||||
vm.runInContext(scripts.map(match => match[1]).join("\n"), context, { filename: "live-dashboard.html" });
|
||||
return { clock, calls, clients, events, byId, created };
|
||||
}
|
||||
|
||||
test("live-dashboard renders the requested sections", async () => {
|
||||
const dashboard = openDashboard({ search: "?items=1101,1203&techs=1001,1002&research=1&dyson=1&lang=zh-CN" });
|
||||
await flush();
|
||||
assert.equal(dashboard.byId.get("item-1101-prod").textContent, "3.00");
|
||||
assert.equal(dashboard.byId.get("item-1101-prodRef").textContent, "4.00");
|
||||
assert.equal(dashboard.byId.get("item-1101-cons").textContent, "1.00");
|
||||
assert.equal(dashboard.byId.get("item-1101-consRef").textContent, "2.00");
|
||||
assert.equal(dashboard.byId.get("item-1203-prod").textContent, "3.00");
|
||||
assert.equal(dashboard.byId.get("tech-1001").textContent, "2/10");
|
||||
assert.equal(dashboard.byId.get("tech-1002").textContent, "2/10");
|
||||
assert.equal(dashboard.byId.get("researchName").textContent, "电磁学");
|
||||
assert.equal(dashboard.byId.get("researchPct").textContent, "42.5%");
|
||||
assert.equal(dashboard.byId.get("researchHash").textContent, "12.3k / 67.8k 哈希");
|
||||
assert.equal(dashboard.byId.get("dysonWatts").textContent, "60.9MW");
|
||||
assert.equal(dashboard.byId.get("status").textContent, "已连接");
|
||||
assert.ok(dashboard.created.some(element => element.tagName === "IMG" && element.src === "icon-item-1101"));
|
||||
assert.ok(dashboard.calls.some(([name, ids]) => name === "rates" && ids.join() === "1101,1203"));
|
||||
});
|
||||
|
||||
test("live-dashboard defaults to research and Dyson sections", async () => {
|
||||
const dashboard = openDashboard({});
|
||||
await flush();
|
||||
assert.equal(dashboard.byId.get("researchName").textContent, "电磁学");
|
||||
assert.equal(dashboard.byId.get("dysonWatts").textContent, "60.9MW");
|
||||
assert.ok(!dashboard.byId.has("item-1101-prod"));
|
||||
assert.ok(!dashboard.byId.has("tech-1001"));
|
||||
assert.ok(!dashboard.calls.some(([name]) => name === "rates" || name === "tech"));
|
||||
});
|
||||
|
||||
test("live-dashboard shows a repeatable and a one-time tech level", async () => {
|
||||
const dashboard = openDashboard({
|
||||
search: "?techs=1001,1002",
|
||||
techStates: {
|
||||
1001: { techId: 1001, unlocked: false, curLevel: 5, maxLevel: 20 },
|
||||
1002: { techId: 1002, unlocked: true, curLevel: 0, maxLevel: 0 }
|
||||
}
|
||||
});
|
||||
await flush();
|
||||
assert.equal(dashboard.byId.get("tech-1001").textContent, "5/20");
|
||||
assert.equal(dashboard.byId.get("tech-1002").textContent, "已解锁");
|
||||
});
|
||||
|
||||
test("live-dashboard resumes polling after the first connection fails", async () => {
|
||||
const dashboard = openDashboard({ search: "?items=1101", failFirst: true });
|
||||
await flush();
|
||||
assert.equal(dashboard.calls.length, 0);
|
||||
dashboard.clock.advance(2000);
|
||||
await flush();
|
||||
assert.equal(dashboard.byId.get("item-1101-prod").textContent, "3.00");
|
||||
assert.equal(dashboard.byId.get("status").textContent, "已连接");
|
||||
});
|
||||
|
||||
test("live-dashboard does not overlap slow polls", async () => {
|
||||
let finish;
|
||||
const pending = new Promise(resolve => { finish = resolve; });
|
||||
const dashboard = openDashboard({ search: "?items=1101", pendingRates: pending });
|
||||
await flush();
|
||||
dashboard.clock.advance(10000);
|
||||
await flush();
|
||||
assert.equal(dashboard.calls.length, 1);
|
||||
finish([{ itemId: 1101, perMinute: true, production: 6, consumption: 2, theoreticalProduction: 8, theoreticalConsumption: 4 }]);
|
||||
await flush();
|
||||
assert.equal(dashboard.byId.get("item-1101-prod").textContent, "6.00");
|
||||
dashboard.clock.advance(2000);
|
||||
await flush();
|
||||
assert.equal(dashboard.calls.length, 2);
|
||||
});
|
||||
|
||||
test("live-dashboard stops polling on pagehide", async () => {
|
||||
const dashboard = openDashboard({ search: "?research=1" });
|
||||
await flush();
|
||||
assert.equal(typeof dashboard.events.get("pagehide"), "function");
|
||||
dashboard.events.get("pagehide")();
|
||||
dashboard.clock.advance(20000);
|
||||
await flush();
|
||||
assert.equal(dashboard.calls.length, 1);
|
||||
assert.equal(dashboard.clock.size, 0);
|
||||
});
|
||||
|
||||
test("live-dashboard reports initialization errors without polling", async () => {
|
||||
for (const search of ["?window=5min&research=1", "?techs=abc", "?items=1101&techs=0"]) {
|
||||
const dashboard = openDashboard({ search });
|
||||
await flush();
|
||||
assert.match(dashboard.byId.get("status").textContent, /初始化失败/);
|
||||
assert.equal(dashboard.calls.length, 0);
|
||||
dashboard.clock.advance(10000);
|
||||
await flush();
|
||||
assert.equal(dashboard.calls.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("live-dashboard can disable the default sections explicitly", async () => {
|
||||
const dashboard = openDashboard({ search: "?research=0" });
|
||||
await flush();
|
||||
assert.ok(!dashboard.byId.has("researchName"));
|
||||
assert.ok(!dashboard.byId.has("dysonWatts"));
|
||||
assert.equal(dashboard.byId.get("status").textContent, "已连接");
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
|
||||
const ROOT = path.resolve(__dirname, "..");
|
||||
|
||||
function createHarness() {
|
||||
let now = 0;
|
||||
let sequence = 0;
|
||||
const timers = new Map();
|
||||
const sockets = [];
|
||||
const clock = {
|
||||
setTimeout(callback, delay) {
|
||||
const timerId = ++sequence;
|
||||
timers.set(timerId, { callback, due: now + delay });
|
||||
return timerId;
|
||||
},
|
||||
setInterval(callback, delay) {
|
||||
const timerId = ++sequence;
|
||||
timers.set(timerId, { callback, due: now + delay, interval: delay });
|
||||
return timerId;
|
||||
},
|
||||
clearTimeout(timerId) { timers.delete(timerId); },
|
||||
advance(duration) {
|
||||
const end = now + duration;
|
||||
while (true) {
|
||||
const next = [...timers.entries()].filter(([, timer]) => timer.due <= end)
|
||||
.sort((left, right) => left[1].due - right[1].due)[0];
|
||||
if (!next) break;
|
||||
timers.delete(next[0]);
|
||||
now = next[1].due;
|
||||
if (next[1].interval) timers.set(next[0], { ...next[1], due: now + next[1].interval });
|
||||
next[1].callback();
|
||||
}
|
||||
now = end;
|
||||
},
|
||||
get size() { return timers.size; }
|
||||
};
|
||||
|
||||
class FakeWebSocket {
|
||||
constructor(url) {
|
||||
if (!/^wss?:\/\//.test(url)) throw new SyntaxError("Invalid WebSocket URL");
|
||||
this.url = url;
|
||||
this.readyState = 0;
|
||||
this.sent = [];
|
||||
sockets.push(this);
|
||||
}
|
||||
open() { this.readyState = 1; if (this.onopen) this.onopen(); }
|
||||
close(code = 1000) {
|
||||
this.readyState = 3;
|
||||
if (this.onclose) this.onclose({ code });
|
||||
}
|
||||
send(body) {
|
||||
if (this.readyState !== 1) throw new Error("Socket is not open");
|
||||
this.sent.push(JSON.parse(body));
|
||||
}
|
||||
reply(request, result) {
|
||||
this.onmessage({ data: JSON.stringify({ jsonrpc: "2.0", id: request.id, result }) });
|
||||
}
|
||||
}
|
||||
|
||||
const context = vm.createContext({
|
||||
console, WebSocket: FakeWebSocket,
|
||||
setTimeout: clock.setTimeout, clearTimeout: clock.clearTimeout
|
||||
});
|
||||
vm.runInContext(fs.readFileSync(path.join(ROOT, "livestream-assist.js"), "utf8"), context);
|
||||
return { api: context.LiveStreamAssist, context, clock, sockets };
|
||||
}
|
||||
|
||||
function observe(promise) {
|
||||
const outcome = { status: "pending" };
|
||||
promise.then(
|
||||
value => Object.assign(outcome, { status: "fulfilled", value }),
|
||||
error => Object.assign(outcome, { status: "rejected", error })
|
||||
);
|
||||
return outcome;
|
||||
}
|
||||
|
||||
function flush() { return new Promise(resolve => setImmediate(resolve)); }
|
||||
|
||||
function createQuery(handler) {
|
||||
const { api } = createHarness();
|
||||
const calls = [];
|
||||
const client = {
|
||||
read(params) {
|
||||
calls.push(params);
|
||||
return Promise.resolve().then(() => handler(params));
|
||||
}
|
||||
};
|
||||
return { query: new api.GameQuery(client), calls, api };
|
||||
}
|
||||
|
||||
function result(value, sessionId = "save-a", gameTick = "100") {
|
||||
return { value, sessionId, gameTick };
|
||||
}
|
||||
|
||||
module.exports = { ROOT, createHarness, createQuery, observe, flush, result };
|
||||
@@ -0,0 +1,109 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const test = require("node:test");
|
||||
const vm = require("node:vm");
|
||||
const { ROOT, createHarness, flush } = require("./test_helpers");
|
||||
|
||||
function openOverlay(filename, options = {}) {
|
||||
const { context, clock, api } = createHarness();
|
||||
const elements = new Map();
|
||||
const events = new Map();
|
||||
const clients = [];
|
||||
let reads = 0;
|
||||
const html = fs.readFileSync(path.join(ROOT, "..", "examples", filename), "utf8");
|
||||
function element(id) {
|
||||
if (!elements.has(id)) elements.set(id, { value: "", textContent: "", style: {} });
|
||||
return elements.get(id);
|
||||
}
|
||||
for (const match of html.matchAll(/<input id="([^"]+)"[^>]*value="([^"]+)"/g)) element(match[1]).value = match[2];
|
||||
const languages = [...html.matchAll(/<option value="([^"]+)"/g)].map(match => match[1]);
|
||||
let language = languages[0];
|
||||
Object.defineProperty(element("lang"), "value", {
|
||||
get() { return language; },
|
||||
set(value) { language = languages.includes(String(value)) ? String(value) : ""; }
|
||||
});
|
||||
class Client {
|
||||
constructor(settings) { this.url = settings.url; this.settings = settings; this.connections = []; clients.push(this); }
|
||||
connect(url) {
|
||||
if (url != null) this.url = url;
|
||||
this.connections.push(this.url);
|
||||
if (options.failFirst && this.connections.length === 1) return Promise.reject({ kind: "CONNECT_FAILED" });
|
||||
return Promise.resolve(this);
|
||||
}
|
||||
close() { this.infoSnapshot = null; }
|
||||
systemInfo() { this.infoSnapshot = {}; return Promise.resolve(this.infoSnapshot); }
|
||||
validate() { return Promise.resolve({}); }
|
||||
}
|
||||
class GameQuery {
|
||||
getCurrentResearch() {
|
||||
reads += 1;
|
||||
return options.research ? options.research(reads) : Promise.resolve({ active: false });
|
||||
}
|
||||
getItemRates() { return Promise.resolve({ production: 1, consumption: 1, theoreticalProduction: 1, theoreticalConsumption: 1 }); }
|
||||
getDysonPower() { return Promise.resolve({ watts: "60" }); }
|
||||
}
|
||||
context.LiveStreamAssist = {
|
||||
Client, GameQuery,
|
||||
GameText: { fromGenerated(settings) { return new api.GameText({}, settings); } }
|
||||
};
|
||||
Object.assign(context, {
|
||||
location: { search: options.search || "" }, URLSearchParams,
|
||||
document: { getElementById: element },
|
||||
setInterval: clock.setInterval, clearInterval: clock.clearTimeout,
|
||||
addEventListener(name, callback) { events.set(name, callback); }
|
||||
});
|
||||
const scripts = [...html.matchAll(/<script(?:[^>]*)>([\s\S]*?)<\/script>/g)];
|
||||
vm.runInContext(scripts.map(match => match[1]).join("\n"), context, { filename });
|
||||
return { clock, element, events, clients, get reads() { return reads; } };
|
||||
}
|
||||
|
||||
for (const filename of ["research-overlay.html", "stats-overlay.html"]) {
|
||||
test(filename + " resumes polling after the first connection fails", async () => {
|
||||
const overlay = openOverlay(filename, { failFirst: true });
|
||||
await flush();
|
||||
assert.equal(overlay.reads, 0);
|
||||
overlay.clock.advance(2000);
|
||||
await flush();
|
||||
assert.equal(overlay.reads, 1);
|
||||
assert.equal(overlay.element("status").textContent, "connected");
|
||||
});
|
||||
|
||||
test(filename + " does not overlap slow polls", async () => {
|
||||
let finish;
|
||||
const pending = new Promise(resolve => { finish = resolve; });
|
||||
const overlay = openOverlay(filename, { research: () => pending });
|
||||
await flush();
|
||||
overlay.clock.advance(10000);
|
||||
await flush();
|
||||
assert.equal(overlay.reads, 1);
|
||||
finish({ active: false });
|
||||
await flush();
|
||||
});
|
||||
|
||||
test(filename + " ignores old results after a URL change", async () => {
|
||||
let finish;
|
||||
const pending = new Promise(resolve => { finish = resolve; });
|
||||
const current = { active: true, techId: 1002, curLevel: 1, hashUploaded: "1", hashNeeded: "2", progressPercent: 50 };
|
||||
const overlay = openOverlay(filename, { research: count => count === 1 ? pending : Promise.resolve(current) });
|
||||
await flush();
|
||||
overlay.element("url").value = "ws://localhost:19090/api/v1";
|
||||
assert.equal(typeof overlay.element("url").onchange, "function");
|
||||
overlay.element("url").onchange();
|
||||
await flush();
|
||||
finish({ ...current, techId: 1001 });
|
||||
await flush();
|
||||
const title = overlay.element(filename === "research-overlay.html" ? "title" : "techName");
|
||||
assert.equal(title.textContent, "Tech 1002");
|
||||
assert.equal(overlay.clients[0].connections.at(-1), "ws://localhost:19090/api/v1");
|
||||
});
|
||||
|
||||
test(filename + " accepts LCID query parameters and stops on pagehide", async () => {
|
||||
const overlay = openOverlay(filename, { search: "?lang=2052" });
|
||||
await flush();
|
||||
assert.equal(overlay.element("lang").value, "2052");
|
||||
assert.equal(typeof overlay.events.get("pagehide"), "function");
|
||||
overlay.events.get("pagehide")();
|
||||
assert.equal(overlay.clock.size, 0);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
const { createQuery, result, observe, flush } = require("./test_helpers");
|
||||
|
||||
function itemReader(params, poolIndex = 1, sessionId = "save-a") {
|
||||
const member = params.path[params.path.length - 1];
|
||||
if (member === "factoryCount") return result(1, sessionId);
|
||||
if (params.path.includes("productIndices")) return result(poolIndex, sessionId);
|
||||
if (member === "total") {
|
||||
const totals = Array(14).fill("0");
|
||||
totals[1] = "60";
|
||||
totals[8] = "20";
|
||||
return result({ items: totals.slice(params.offset || 0, (params.offset || 0) + params.limit) }, sessionId);
|
||||
}
|
||||
return result({ refProductSpeed: 120, refConsumeSpeed: 40 }, sessionId);
|
||||
}
|
||||
|
||||
test("a missing product is rediscovered when production starts", async () => {
|
||||
let poolIndex = 0;
|
||||
const { query } = createQuery(params => itemReader(params, poolIndex));
|
||||
assert.equal((await query.getItemRates(1101)).production, 0);
|
||||
poolIndex = 1;
|
||||
const rates = await query.getItemRates(1101);
|
||||
assert.equal(rates.production, 60);
|
||||
assert.equal(rates.consumption, 20);
|
||||
assert.equal(rates.theoreticalProduction, 120);
|
||||
});
|
||||
|
||||
test("duplicate item ids share reads without doubling totals", async () => {
|
||||
const { query, calls } = createQuery(itemReader);
|
||||
const rates = await query.getItemRates([1101, 1101]);
|
||||
assert.equal(rates.length, 2);
|
||||
assert.equal(rates[0].production, 60);
|
||||
assert.equal(rates[1].production, 60);
|
||||
assert.equal(calls.filter(params => params.path.includes("productIndices")).length, 1);
|
||||
});
|
||||
|
||||
test("unbuilt local planets return zero rates without negative indexes", async () => {
|
||||
const { query, calls } = createQuery(params => {
|
||||
if (params.root === "localPlanet") return result(-1);
|
||||
throw new Error("An unbuilt planet has no factory statistics");
|
||||
});
|
||||
const rates = await query.getItemRates(1101, { scope: "localPlanet" });
|
||||
assert.equal(rates.production, 0);
|
||||
assert.equal(rates.factories, 0);
|
||||
assert.equal(rates.sessionId, "save-a");
|
||||
assert.equal(calls.length, 1);
|
||||
});
|
||||
|
||||
test("empty production results retain session metadata", async () => {
|
||||
const { query } = createQuery(() => result(0));
|
||||
const rates = await query.getItemRates(1101);
|
||||
assert.equal(rates.sessionId, "save-a");
|
||||
assert.equal(rates.gameTick, "100");
|
||||
});
|
||||
|
||||
test("explicit factory scopes refresh cached indices after a save change", async () => {
|
||||
let sessionId = "save-a";
|
||||
let poolIndex = 1;
|
||||
const { query, calls } = createQuery(params => itemReader(params, poolIndex, sessionId));
|
||||
await query.getItemRates(1101, { scope: { factoryIndex: 0 } });
|
||||
await query.getItemRates(1101, { scope: { factoryIndex: 0 } });
|
||||
calls.length = 0;
|
||||
sessionId = "save-b";
|
||||
poolIndex = 2;
|
||||
await query.getItemRates(1101, { scope: { factoryIndex: 0 } });
|
||||
const productReads = calls.filter(params => params.path.includes("productPool"));
|
||||
assert.equal(productReads.length, 2);
|
||||
for (const params of productReads) assert.equal(params.path[4], 2);
|
||||
});
|
||||
|
||||
test("research from different saves is not combined", async () => {
|
||||
const { query } = createQuery(params => params.path[0] === "currentTech"
|
||||
? result(1001)
|
||||
: result({ hashUploaded: "50", hashNeeded: "100", curLevel: 1 }, "save-b"));
|
||||
await assert.rejects(query.getCurrentResearch(), { kind: "SESSION_CHANGED" });
|
||||
});
|
||||
|
||||
test("cluster string reads the active game description", async () => {
|
||||
const { query, calls } = createQuery(() => result("12345678-64-A10"));
|
||||
const cluster = await query.getClusterString();
|
||||
assert.equal(cluster.clusterString, "12345678-64-A10");
|
||||
assert.equal(cluster.sessionId, "save-a");
|
||||
assert.equal(calls[0].root, "game");
|
||||
assert.equal(calls[0].path.join("."), "gameDesc.clusterString");
|
||||
});
|
||||
|
||||
test("research progress keeps integer precision", async () => {
|
||||
const { query } = createQuery(() => result({
|
||||
hashUploaded: "9007199254740993", hashNeeded: "18014398509481986", curLevel: 1
|
||||
}));
|
||||
const research = await query.getTechState(1001);
|
||||
assert.equal(research.progressPercent, 50);
|
||||
assert.equal(research.hashUploaded, "9007199254740993");
|
||||
});
|
||||
|
||||
test("Dyson collection pages project energy instead of rereading each sphere", async () => {
|
||||
const energy = { energyGenCurrentTick: "100", energyGenOriginalCurrentTick: "200", energyReqCurrentTick: "5" };
|
||||
const { query, calls } = createQuery(params => {
|
||||
if (params.path.length === 1) {
|
||||
const entries = Array(130).fill(null);
|
||||
entries[0] = energy;
|
||||
entries[129] = energy;
|
||||
const offset = params.offset || 0;
|
||||
return result({ items: entries.slice(offset, offset + params.limit), offset, hasMore: offset + params.limit < entries.length });
|
||||
}
|
||||
if (params.path[2] === "starData") return result({ id: params.path[1] + 1, name: "Star" });
|
||||
return result(energy);
|
||||
});
|
||||
const power = await query.getDysonPower();
|
||||
assert.equal(power.watts, "12000");
|
||||
assert.equal(power.originalWatts, "24000");
|
||||
assert.equal(power.sphereCount, 2);
|
||||
assert.equal(calls.length, 4);
|
||||
for (const page of calls.filter(params => params.path.length === 1)) {
|
||||
assert.ok(page.select.includes("energyGenCurrentTick"));
|
||||
}
|
||||
});
|
||||
|
||||
test("a targeted Dyson query does not scan all stars", async () => {
|
||||
const { query, calls } = createQuery(params => {
|
||||
if (params.path.length === 1) return result({ items: [null, {}], offset: 0, hasMore: false });
|
||||
if (params.path[2] === "starData") return result({ id: 2, name: "Star" });
|
||||
return result({ energyGenCurrentTick: "9007199254740993", energyGenOriginalCurrentTick: "9007199254740993" });
|
||||
});
|
||||
const power = await query.getDysonPower({ starIndex: 1 });
|
||||
assert.equal(power.watts, "540431955284459580");
|
||||
assert.equal(calls.length, 2);
|
||||
assert.equal(calls[0].path[1], 1);
|
||||
});
|
||||
|
||||
test("star lookup failures are not reported as successful power reads", async () => {
|
||||
const { query } = createQuery(params => {
|
||||
if (params.path.length === 1) return result({ items: [{}], offset: 0, hasMore: false });
|
||||
if (params.path[2] === "starData") throw { kind: "SESSION_CHANGED" };
|
||||
return result({ energyGenCurrentTick: "100" });
|
||||
});
|
||||
await assert.rejects(query.getDysonPower(), { kind: "SESSION_CHANGED" });
|
||||
});
|
||||
|
||||
test("empty Dyson results retain session metadata", async () => {
|
||||
const { query } = createQuery(() => result({ items: [], offset: 0, hasMore: false }));
|
||||
const power = await query.getDysonPower();
|
||||
assert.equal(power.watts, "0");
|
||||
assert.equal(power.sessionId, "save-a");
|
||||
assert.equal(power.gameTick, "100");
|
||||
});
|
||||
|
||||
test("late responses cannot restore a previous session", async () => {
|
||||
let finish;
|
||||
const pending = new Promise(resolve => { finish = resolve; });
|
||||
const { query } = createQuery(params => params.path[0] === "techStates" ? pending : result(0, "save-b"));
|
||||
const old = observe(query.getTechState(1001));
|
||||
await flush();
|
||||
await query.getCurrentResearch();
|
||||
finish(result({ hashUploaded: "1", hashNeeded: "2" }, "save-a"));
|
||||
await flush();
|
||||
assert.equal(old.error.kind, "SESSION_CHANGED");
|
||||
assert.equal(query._sessionId, "save-b");
|
||||
});
|
||||
|
||||
test("failed queries wait for their other reads before settling", async () => {
|
||||
let finish;
|
||||
const pending = new Promise(resolve => { finish = resolve; });
|
||||
const { query } = createQuery(params => {
|
||||
if (params.path.at(-1) === "total") return pending;
|
||||
if (params.select) throw { kind: "SERVER_BUSY" };
|
||||
return itemReader(params);
|
||||
});
|
||||
const rates = observe(query.getItemRates(1101));
|
||||
await flush();
|
||||
assert.equal(rates.status, "pending");
|
||||
finish(result({ items: Array(8).fill("0") }));
|
||||
await flush();
|
||||
assert.equal(rates.error.kind, "SERVER_BUSY");
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const test = require("node:test");
|
||||
const vm = require("node:vm");
|
||||
const { ROOT, createHarness } = require("./test_helpers");
|
||||
|
||||
test("the packed script matches its sources", () => {
|
||||
const names = ["header", "format", "client", "query", "text", "icons", "footer"];
|
||||
const sources = names.map(name => fs.readFileSync(path.join(ROOT, "src", name + ".js"), "utf8").replace(/\r\n/g, "\n")).join("");
|
||||
const packed = fs.readFileSync(path.join(ROOT, "livestream-assist.js"), "utf8").replace(/\r\n/g, "\n");
|
||||
assert.ok(packed === sources, "The bundle is stale; run python LiveStreamAssist/js/scripts/pack_js.py.");
|
||||
});
|
||||
|
||||
test("empty and missing translations follow the game instead of English fallback", () => {
|
||||
const { api, sockets } = createHarness();
|
||||
const text = new api.GameText({
|
||||
languages: { 2052: { fallback: 1033 } },
|
||||
strings: { empty: { 2052: "", 1033: "English" }, missing: { 1033: "English" } }
|
||||
}, { language: 2052 });
|
||||
assert.equal(text.translate("empty"), "");
|
||||
assert.equal(text.translate("missing"), "missing");
|
||||
assert.equal(sockets.length, 0);
|
||||
});
|
||||
|
||||
test("language aliases are case insensitive without metadata", () => {
|
||||
const { api } = createHarness();
|
||||
const text = new api.GameText({}, { language: "ZH-CN" });
|
||||
assert.equal(text.lcid, 2052);
|
||||
text.setLanguage("JA-JA");
|
||||
assert.equal(text.lcid, 1041);
|
||||
});
|
||||
|
||||
test("JavaScript KMG formatting covers thresholds, signs and 64-bit values", () => {
|
||||
const { api } = createHarness();
|
||||
const cases = [
|
||||
[0, "count", "0"], [9999, "count", "9999"], [10000, "count", "10.0k"],
|
||||
[12345, "count", "12.3k"], [999999, "count", "999k"], [1000000, "count", "1.00M"],
|
||||
[-12345, "count", "-12.3k"], [12345, "power", "12.3kW"], [0, "power", "0W"],
|
||||
[12345, "energy", "12.3kJ"], [1000, "si1000", "1.00k"],
|
||||
["9223372036854775807", "power", "9.22EW"]
|
||||
];
|
||||
for (const [value, kind, expected] of cases) {
|
||||
assert.equal(api.format.write(value, { kind }).trim(), expected);
|
||||
}
|
||||
assert.equal(api.format.kmg(12345, { decimal: "," }), "12,3k");
|
||||
assert.ok(api.format.write(12345, { blank: true }).includes("\u2009k"));
|
||||
});
|
||||
|
||||
test("generated prototype names are available offline without locale BOMs", () => {
|
||||
const { api, context } = createHarness();
|
||||
vm.runInContext(fs.readFileSync(path.join(ROOT, "generated", "dsp-text.js"), "utf8"), context);
|
||||
const text = api.GameText.fromGenerated({ language: "en" });
|
||||
assert.equal(text.translate("\u94c1\u77ff"), "Iron Ore");
|
||||
assert.ok(Object.keys(text.data.strings).every(key => !key.startsWith("\ufeff")));
|
||||
});
|
||||
|
||||
test("README usage examples parse as classic scripts", () => {
|
||||
const readme = fs.readFileSync(path.join(ROOT, "README.md"), "utf8");
|
||||
for (const script of readme.matchAll(/^<script>([\s\S]*?)^<\/script>/gm)) {
|
||||
assert.doesNotThrow(() => new vm.Script(script[1]));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
|
||||
from generate_text import (
|
||||
build_payload,
|
||||
find_game_root,
|
||||
first_field,
|
||||
load_language_strings,
|
||||
load_name_keys,
|
||||
parse_header,
|
||||
read_locale_text,
|
||||
translation_field,
|
||||
unescape_string,
|
||||
)
|
||||
from kmg import THIN_SPACE, format_kmg, write_kmg
|
||||
|
||||
|
||||
def assert_eq(actual, expected, label: str) -> None:
|
||||
if actual != expected:
|
||||
raise SystemExit(f"{label}: expected {expected!r}, got {actual!r}")
|
||||
|
||||
|
||||
def test_unescape() -> None:
|
||||
assert_eq(unescape_string("plain"), "plain", "plain")
|
||||
assert_eq(unescape_string("a\\nb"), "a\nb", "newline")
|
||||
assert_eq(unescape_string("a\\tb"), "a\tb", "tab")
|
||||
assert_eq(unescape_string("c:\\\\x"), "c:\\x", "backslash")
|
||||
|
||||
|
||||
def test_header_and_locale() -> None:
|
||||
game = find_game_root(None)
|
||||
if game is None:
|
||||
print("skip locale tests: DSP not found")
|
||||
return
|
||||
languages, pages = parse_header(game / "Locale" / "Header.txt")
|
||||
lcids = {lang["lcid"] for lang in languages}
|
||||
if 1033 not in lcids or 2052 not in lcids:
|
||||
raise SystemExit(f"missing core languages: {lcids}")
|
||||
if "prototype.txt" not in pages:
|
||||
raise SystemExit("prototype.txt missing from page order")
|
||||
iron = None
|
||||
for line in read_locale_text(game / "Locale" / "1033" / "prototype.txt").splitlines():
|
||||
if first_field(line) == "铁矿":
|
||||
iron = translation_field(line)
|
||||
break
|
||||
assert_eq(iron, "Iron Ore", "iron ore en")
|
||||
|
||||
|
||||
def test_locale_bom_and_empty_translations() -> None:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
locale_dir = Path(directory)
|
||||
locale_file = locale_dir / "prototype.txt"
|
||||
source = "first\t\tPrototype\tTranslated\nempty\t\tPrototype\t\n"
|
||||
for encoding in ("utf-16", "utf-8-sig"):
|
||||
locale_file.write_text(source, encoding=encoding, newline="\n")
|
||||
assert_eq(read_locale_text(locale_file), source, f"decode {encoding}")
|
||||
keys = load_name_keys(locale_dir, ["prototype.txt"])
|
||||
assert_eq(keys, ["first", "empty"], f"keys {encoding}")
|
||||
values = load_language_strings(locale_dir, ["prototype.txt"], keys)
|
||||
assert_eq(values, {"first": "Translated", "empty": ""}, f"translations {encoding}")
|
||||
locale_file.write_bytes(b"\xfe\xff" + source.encode("utf-16-be"))
|
||||
assert_eq(read_locale_text(locale_file), source, "decode utf-16-be")
|
||||
|
||||
|
||||
def test_header_page_order() -> None:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
header = Path(directory) / "Header.txt"
|
||||
header.write_text(
|
||||
"[Localization Project]\nVersion=1.1\n1033,English,en-US,en,2052,0\n\n"
|
||||
"keys=0\ncustom=0\nbase=0\nprototype=-1\n",
|
||||
encoding="utf-16",
|
||||
)
|
||||
_, pages = parse_header(header)
|
||||
assert_eq(pages, ["prototype.txt", "keys.txt", "custom.txt", "base.txt"], "stable page order")
|
||||
|
||||
|
||||
def test_incomplete_prototypes_are_rejected() -> None:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
game = Path(directory)
|
||||
locale_dir = game / "Locale"
|
||||
locale_dir.mkdir()
|
||||
(locale_dir / "Header.txt").write_text(
|
||||
"Version=1.1\n1033,English,en-US,en,2052,0\n\nprototype=-1\n", encoding="utf-8"
|
||||
)
|
||||
with patch("generate_text.extract_proto_ids", return_value={}):
|
||||
try:
|
||||
build_payload(game, "2022.3.7")
|
||||
except SystemExit:
|
||||
return
|
||||
raise SystemExit("incomplete prototypes must not overwrite generated data")
|
||||
|
||||
|
||||
def test_kmg() -> None:
|
||||
cases = [
|
||||
(0, "count", "0"),
|
||||
(12, "count", "12"),
|
||||
(9999, "count", "9999"),
|
||||
(10000, "count", "10.0k"),
|
||||
(12345, "count", "12.3k"),
|
||||
(999999, "count", "999k"),
|
||||
(1000000, "count", "1.00M"),
|
||||
(1234567890, "count", "1.23G"),
|
||||
(-12345, "count", "-12.3k"),
|
||||
(12345, "power", "12.3kW"),
|
||||
(123, "power", "123W"),
|
||||
(0, "power", "0W"),
|
||||
(12345, "energy", "12.3kJ"),
|
||||
(999, "si1000", "999"),
|
||||
(1000, "si1000", "1.00k"),
|
||||
(1234, "si1000", "1.23k"),
|
||||
]
|
||||
for value, kind, expected in cases:
|
||||
assert_eq(format_kmg(value, kind=kind), expected, f"kmg {value} {kind}")
|
||||
raw = write_kmg(12345, blank=True)
|
||||
if THIN_SPACE + "k" not in raw:
|
||||
raise SystemExit(f"blank thin space missing: {raw!r}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
test_unescape()
|
||||
test_kmg()
|
||||
test_locale_bom_and_empty_translations()
|
||||
test_header_page_order()
|
||||
test_incomplete_prototypes_are_rejected()
|
||||
test_header_and_locale()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,272 @@
|
||||
function ApiError(init) {
|
||||
var message = (init && init.message) || "LiveStreamAssist API error";
|
||||
Error.call(this, message);
|
||||
this.name = "ApiError";
|
||||
this.message = message;
|
||||
this.code = init && init.code;
|
||||
this.kind = init && init.kind;
|
||||
this.id = init && init.id;
|
||||
this.data = (init && init.data) || null;
|
||||
if (typeof Error.captureStackTrace === "function") Error.captureStackTrace(this, ApiError);
|
||||
}
|
||||
ApiError.prototype = Object.create(Error.prototype);
|
||||
ApiError.prototype.constructor = ApiError;
|
||||
|
||||
function errorFromResponse(id, error) {
|
||||
var data = error && error.data;
|
||||
return new ApiError({
|
||||
id: id,
|
||||
code: error && error.code,
|
||||
message: error && error.message,
|
||||
kind: data && data.kind,
|
||||
data: data || null
|
||||
});
|
||||
}
|
||||
|
||||
function Client(options) {
|
||||
options = options || {};
|
||||
this.url = options.url || DEFAULT_URL;
|
||||
this.autoReconnect = options.autoReconnect !== false;
|
||||
this.requestTimeoutMs = options.requestTimeoutMs == null ? 8000 : options.requestTimeoutMs;
|
||||
this.maxPending = options.maxPending == null ? 8 : options.maxPending;
|
||||
if (!Number.isInteger(this.maxPending) || this.maxPending < 1) {
|
||||
throw new RangeError("maxPending must be a positive integer.");
|
||||
}
|
||||
if (!Number.isFinite(this.requestTimeoutMs) || this.requestTimeoutMs <= 0) {
|
||||
throw new RangeError("requestTimeoutMs must be positive and finite.");
|
||||
}
|
||||
this._configuredMaxPending = options.maxPending;
|
||||
this._ws = null;
|
||||
this._connectionUrl = null;
|
||||
this._seq = 0;
|
||||
this._pending = new Map();
|
||||
this._waiters = [];
|
||||
this._active = 0;
|
||||
this._backoff = 500;
|
||||
this._closed = false;
|
||||
this._connecting = null;
|
||||
this._rejectConnecting = null;
|
||||
this._reconnectTimer = null;
|
||||
this._socketGen = 0;
|
||||
this.infoSnapshot = null;
|
||||
this.onStatus = options.onStatus || null;
|
||||
}
|
||||
|
||||
Client.prototype._setStatus = function (status, detail) {
|
||||
if (typeof this.onStatus === "function") {
|
||||
try { this.onStatus(status, detail); } catch (error) {}
|
||||
}
|
||||
};
|
||||
|
||||
Client.prototype.connect = function (url) {
|
||||
if (url != null) this.url = url;
|
||||
if (this._connectionUrl != null && this._connectionUrl !== this.url) this.close();
|
||||
this._closed = false;
|
||||
if (this._ws && this._ws.readyState === 1) return Promise.resolve(this);
|
||||
if (this._connecting) return this._connecting;
|
||||
if (this._ws) this._disconnect(new ApiError({ kind: "DISCONNECTED", message: "Connection replaced." }));
|
||||
clearTimeout(this._reconnectTimer);
|
||||
this._reconnectTimer = null;
|
||||
var self = this;
|
||||
var generation = ++this._socketGen;
|
||||
var resolveConnection;
|
||||
var connection = new Promise(function (resolve, reject) {
|
||||
resolveConnection = resolve;
|
||||
self._rejectConnecting = reject;
|
||||
});
|
||||
this._connecting = connection;
|
||||
this._connectionUrl = this.url;
|
||||
this.infoSnapshot = null;
|
||||
this.maxPending = this._configuredMaxPending == null ? 8 : this._configuredMaxPending;
|
||||
var socket;
|
||||
try { socket = this._ws = new WebSocket(this.url); }
|
||||
catch (error) {
|
||||
this._disconnect(new ApiError({ kind: "CONNECT_FAILED", message: String(error.message || error) }));
|
||||
this._setStatus("disconnected");
|
||||
return connection;
|
||||
}
|
||||
socket.onopen = function () {
|
||||
if (generation !== self._socketGen) return;
|
||||
self._backoff = 500;
|
||||
self._connecting = null;
|
||||
self._rejectConnecting = null;
|
||||
resolveConnection(self);
|
||||
self._setStatus("connected", { url: self.url });
|
||||
};
|
||||
socket.onmessage = function (event) {
|
||||
if (generation === self._socketGen) self._onMessage(event.data);
|
||||
};
|
||||
socket.onerror = function () {};
|
||||
socket.onclose = function (event) {
|
||||
if (generation !== self._socketGen) return;
|
||||
self._disconnect(new ApiError({
|
||||
kind: self._connecting ? "CONNECT_FAILED" : "DISCONNECTED",
|
||||
message: "WebSocket disconnected.", data: { code: event.code }
|
||||
}));
|
||||
var reconnectGeneration = self._socketGen;
|
||||
self._setStatus("disconnected", { code: event.code });
|
||||
if (!self._closed && self.autoReconnect && reconnectGeneration === self._socketGen) {
|
||||
var delay = self._backoff;
|
||||
self._backoff = Math.min(self._backoff * 2, 8000);
|
||||
self._reconnectTimer = setTimeout(function () {
|
||||
if (!self._closed && reconnectGeneration === self._socketGen) self.connect().catch(function () {});
|
||||
}, delay);
|
||||
}
|
||||
};
|
||||
this._setStatus("connecting", { url: this.url });
|
||||
return connection;
|
||||
};
|
||||
|
||||
Client.prototype._disconnect = function (error) {
|
||||
this._socketGen += 1;
|
||||
clearTimeout(this._reconnectTimer);
|
||||
this._reconnectTimer = null;
|
||||
var socket = this._ws;
|
||||
this._ws = null;
|
||||
this._connectionUrl = null;
|
||||
this.infoSnapshot = null;
|
||||
if (this._rejectConnecting) this._rejectConnecting(error);
|
||||
this._rejectConnecting = null;
|
||||
this._connecting = null;
|
||||
this._failPending(error);
|
||||
if (socket) {
|
||||
socket.onopen = socket.onmessage = socket.onerror = socket.onclose = null;
|
||||
if (socket.readyState < 2) {
|
||||
try { socket.close(); } catch (closeError) {}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Client.prototype.close = function () {
|
||||
this._closed = true;
|
||||
this._disconnect(new ApiError({ kind: "DISCONNECTED", message: "Client closed." }));
|
||||
this._backoff = 500;
|
||||
this._setStatus("disconnected");
|
||||
};
|
||||
|
||||
Client.prototype._failPending = function (error) {
|
||||
this._pending.forEach(function (waiter) {
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.reject(error);
|
||||
});
|
||||
this._pending.clear();
|
||||
this._active = 0;
|
||||
var waiters = this._waiters.splice(0, this._waiters.length);
|
||||
waiters.forEach(function (waiter) { waiter.reject(error); });
|
||||
};
|
||||
|
||||
Client.prototype._settlePending = function (id, error, result) {
|
||||
var waiter = this._pending.get(id);
|
||||
if (!waiter) return;
|
||||
this._pending.delete(id);
|
||||
clearTimeout(waiter.timer);
|
||||
this._release(waiter.generation);
|
||||
if (error) waiter.reject(error);
|
||||
else waiter.resolve(result);
|
||||
};
|
||||
|
||||
Client.prototype._onMessage = function (raw) {
|
||||
var message;
|
||||
try { message = JSON.parse(raw); } catch (error) { return; }
|
||||
if (!message || message.id == null || message.jsonrpc !== "2.0") return;
|
||||
if (!message.error && !Object.prototype.hasOwnProperty.call(message, "result")) return;
|
||||
this._settlePending(message.id, message.error && errorFromResponse(message.id, message.error), message.result);
|
||||
};
|
||||
|
||||
Client.prototype._drainWaiters = function () {
|
||||
if (this._closed || !this._ws || this._ws.readyState !== 1) return;
|
||||
while (this._active < this.maxPending && this._waiters.length) {
|
||||
this._active += 1;
|
||||
this._waiters.shift().resolve();
|
||||
}
|
||||
};
|
||||
|
||||
Client.prototype._release = function (generation) {
|
||||
if (generation !== this._socketGen) return;
|
||||
this._active = Math.max(0, this._active - 1);
|
||||
this._drainWaiters();
|
||||
};
|
||||
|
||||
Client.prototype._acquire = function (generation) {
|
||||
if (this._closed || generation !== this._socketGen || !this._ws || this._ws.readyState !== 1) {
|
||||
return Promise.reject(new ApiError({ kind: "DISCONNECTED", message: "WebSocket is not open." }));
|
||||
}
|
||||
var self = this;
|
||||
return new Promise(function (resolve, reject) {
|
||||
self._waiters.push({ resolve: resolve, reject: reject });
|
||||
self._drainWaiters();
|
||||
});
|
||||
};
|
||||
|
||||
Client.prototype.request = function (method, params) {
|
||||
if (this._closed) return Promise.reject(new ApiError({ kind: "DISCONNECTED", message: "Client closed." }));
|
||||
var self = this;
|
||||
var connection = this.connect();
|
||||
var generation = this._socketGen;
|
||||
return connection.then(function () { return self._acquire(generation); }).then(function () {
|
||||
if (generation !== self._socketGen || !self._ws || self._ws.readyState !== 1) {
|
||||
self._release(generation);
|
||||
throw new ApiError({ kind: "DISCONNECTED", message: "WebSocket is not open." });
|
||||
}
|
||||
var id = "n-" + (++self._seq);
|
||||
var body = { jsonrpc: "2.0", id: id, method: method };
|
||||
if (params != null) body.params = params;
|
||||
return new Promise(function (resolve, reject) {
|
||||
var timer = setTimeout(function () {
|
||||
self._settlePending(id, new ApiError({ kind: "CLIENT_TIMEOUT", message: "Client request timed out.", id: id }));
|
||||
}, self.requestTimeoutMs);
|
||||
self._pending.set(id, { resolve: resolve, reject: reject, timer: timer, generation: generation });
|
||||
try { self._ws.send(JSON.stringify(body)); }
|
||||
catch (err) {
|
||||
self._settlePending(id, new ApiError({ kind: "DISCONNECTED", message: String(err && err.message || err), id: id }));
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
Client.prototype.ping = function () { return this.request("system.ping", {}); };
|
||||
Client.prototype.stats = function () { return this.request("system.stats", {}); };
|
||||
Client.prototype.roots = function () { return this.request("data.roots", {}); };
|
||||
|
||||
Client.prototype.systemInfo = function () {
|
||||
var self = this;
|
||||
var request = this.request("system.info", {});
|
||||
var generation = this._socketGen;
|
||||
return request.then(function (result) {
|
||||
if (generation !== self._socketGen) throw new ApiError({ kind: "DISCONNECTED", message: "Connection replaced." });
|
||||
self.infoSnapshot = result;
|
||||
var limit = result && result.limits && result.limits.maxPendingRequestsPerConnection;
|
||||
if (Number.isInteger(limit) && limit > 0) {
|
||||
self.maxPending = self._configuredMaxPending == null ? limit : Math.min(limit, self._configuredMaxPending);
|
||||
self._drainWaiters();
|
||||
}
|
||||
return result;
|
||||
});
|
||||
};
|
||||
|
||||
Client.prototype.validate = function (params) {
|
||||
params = params || {};
|
||||
var body = { apiMajor: params.apiMajor == null ? 1 : params.apiMajor };
|
||||
if (params.requiredCapabilities) body.requiredCapabilities = params.requiredCapabilities;
|
||||
return this.request("system.validate", body);
|
||||
};
|
||||
|
||||
Client.prototype.describe = function (params) {
|
||||
var body = { root: params.root };
|
||||
if (params.path) body.path = params.path;
|
||||
return this.request("data.describe", body);
|
||||
};
|
||||
|
||||
Client.prototype.read = function (params) {
|
||||
var body = { root: params.root };
|
||||
if (params.path) body.path = params.path;
|
||||
if (params.select) body.select = params.select;
|
||||
if (params.offset != null) body.offset = params.offset;
|
||||
if (params.limit != null) body.limit = params.limit;
|
||||
return this.request("data.read", body);
|
||||
};
|
||||
|
||||
Client.prototype.info = function () { return this.systemInfo(); };
|
||||
|
||||
ns.ApiError = ApiError;
|
||||
ns.Client = Client;
|
||||
@@ -0,0 +1,2 @@
|
||||
return ns;
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
var TICKS_PER_SECOND = 60;
|
||||
var THIN_SPACE = "\u2009";
|
||||
var DIGITS = "0123456789";
|
||||
var DEFAULT_URL = "ws://127.0.0.1:18080/api/v1";
|
||||
var RATE_WINDOWS = {
|
||||
"1min": { productionIndex: 1, consumptionIndex: 8, divisor: 1, perMinute: true, timeLevel: 0 },
|
||||
"10min": { productionIndex: 2, consumptionIndex: 9, divisor: 10, perMinute: true, timeLevel: 1 },
|
||||
"1hour": { productionIndex: 3, consumptionIndex: 10, divisor: 60, perMinute: true, timeLevel: 2 },
|
||||
"10hour": { productionIndex: 4, consumptionIndex: 11, divisor: 600, perMinute: true, timeLevel: 3 },
|
||||
"100hour": { productionIndex: 5, consumptionIndex: 12, divisor: 6000, perMinute: true, timeLevel: 4 },
|
||||
total: { productionIndex: 6, consumptionIndex: 13, divisor: 1, perMinute: false, timeLevel: 5 }
|
||||
};
|
||||
|
||||
function key(value) { return { key: value }; }
|
||||
|
||||
function toBigInt(value) {
|
||||
if (typeof value === "bigint") return value;
|
||||
if (typeof value === "number") return BigInt(Math.trunc(value));
|
||||
if (value == null || value === "") return 0n;
|
||||
return BigInt(String(value));
|
||||
}
|
||||
|
||||
function toNumber(value) {
|
||||
if (typeof value === "number") return value;
|
||||
if (typeof value === "bigint") {
|
||||
var n = Number(value);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
if (value == null || value === "") return 0;
|
||||
var parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function writeKmg(value, options) {
|
||||
options = options || {};
|
||||
var lastIndex = options.lastIndex == null ? 8 : options.lastIndex;
|
||||
var blank = !!options.blank;
|
||||
var blankChar = options.blankChar || THIN_SPACE;
|
||||
var fillChar = options.fillChar != null ? options.fillChar : " ";
|
||||
var decimal = options.decimal || ".";
|
||||
var kind = options.kind || "count";
|
||||
var buf = [];
|
||||
var i;
|
||||
for (i = 0; i <= lastIndex; i++) buf[i] = fillChar;
|
||||
var n = toBigInt(value);
|
||||
var sign = 0;
|
||||
if (n > 0n) sign = 1;
|
||||
else if (n < 0n) { sign = -1; n = -n; }
|
||||
var pos = lastIndex;
|
||||
if (kind === "power") buf[pos--] = "W";
|
||||
else if (kind === "energy") buf[pos--] = "J";
|
||||
var threshold = kind === "si1000" ? 1000n : 10000n;
|
||||
if (n < threshold) {
|
||||
if (blank) buf[pos--] = blankChar;
|
||||
while (n > 0n) {
|
||||
buf[pos--] = DIGITS[Number(n % 10n)];
|
||||
if (pos < 0) return buf.join("");
|
||||
n /= 10n;
|
||||
}
|
||||
} else {
|
||||
var suffix = fillChar;
|
||||
var scale = 1n;
|
||||
if (n < 1000000n) { suffix = "k"; scale = 1000n; }
|
||||
else if (n < 1000000000n) { suffix = "M"; scale = 1000000n; }
|
||||
else if (n < 1000000000000n) { suffix = "G"; scale = 1000000000n; }
|
||||
else if (n < 1000000000000000n) { suffix = "T"; scale = 1000000000000n; }
|
||||
else if (n < 1000000000000000000n) { suffix = "P"; scale = 1000000000000000n; }
|
||||
else { suffix = "E"; scale = 1000000000000000000n; }
|
||||
buf[pos--] = suffix;
|
||||
if (blank) buf[pos--] = blankChar;
|
||||
var acc = 1n;
|
||||
while (n >= 1000n) { n /= 10n; acc *= 10n; }
|
||||
while (n > 0n) {
|
||||
buf[pos--] = DIGITS[Number(n % 10n)];
|
||||
if (pos < 0) return buf.join("");
|
||||
n /= 10n;
|
||||
acc *= 10n;
|
||||
if (acc === scale) {
|
||||
buf[pos--] = decimal;
|
||||
if (pos < 0) return buf.join("");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sign === 0) buf[pos--] = "0";
|
||||
else if (sign < 0) buf[pos--] = "-";
|
||||
return buf.join("");
|
||||
}
|
||||
|
||||
function formatKmg(value, options) {
|
||||
options = options || {};
|
||||
var formatted = writeKmg(value, options);
|
||||
return options.trim === false ? formatted : formatted.replace(/^\s+|\s+$/g, "");
|
||||
}
|
||||
|
||||
ns.format = {
|
||||
kmg: function (value, options) { return formatKmg(value, Object.assign({ kind: "count" }, options)); },
|
||||
kmg1000: function (value, options) { return formatKmg(value, Object.assign({ kind: "si1000" }, options)); },
|
||||
power: function (value, options) { return formatKmg(value, Object.assign({ kind: "power" }, options)); },
|
||||
energy: function (value, options) { return formatKmg(value, Object.assign({ kind: "energy" }, options)); },
|
||||
write: writeKmg
|
||||
};
|
||||
ns.key = key;
|
||||
ns.DEFAULT_URL = DEFAULT_URL;
|
||||
ns.TICKS_PER_SECOND = TICKS_PER_SECOND;
|
||||
ns.RATE_WINDOWS = RATE_WINDOWS;
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* LiveStreamAssist browser client.
|
||||
* Client: JSON-RPC WebSocket wrapper.
|
||||
* GameQuery: production, research, and Dyson power helpers.
|
||||
* GameText: offline locale names and DSP KMG formatting.
|
||||
*/
|
||||
(function (root, factory) {
|
||||
var api = factory();
|
||||
if (typeof module === "object" && module.exports) module.exports = api;
|
||||
root.LiveStreamAssist = api;
|
||||
})(typeof globalThis !== "undefined" ? globalThis : this, function () {
|
||||
"use strict";
|
||||
var ns = {};
|
||||
@@ -0,0 +1,21 @@
|
||||
function GameIcons(data) {
|
||||
this.data = data || { icons: { item: {}, tech: {} } };
|
||||
}
|
||||
|
||||
GameIcons.fromGenerated = function () {
|
||||
var data = (typeof globalThis !== "undefined" && globalThis.LiveStreamAssistIconData) ||
|
||||
(typeof window !== "undefined" && window.LiveStreamAssistIconData) ||
|
||||
null;
|
||||
if (!data) throw new Error("LiveStreamAssistIconData is not loaded. Include generated/dsp-icons.js first.");
|
||||
return new GameIcons(data);
|
||||
};
|
||||
|
||||
GameIcons.prototype.icon = function (kind, id) {
|
||||
var table = this.data.icons && this.data.icons[kind];
|
||||
return table ? table[String(id)] || null : null;
|
||||
};
|
||||
|
||||
GameIcons.prototype.itemIcon = function (id) { return this.icon("item", id); };
|
||||
GameIcons.prototype.techIcon = function (id) { return this.icon("tech", id); };
|
||||
|
||||
ns.GameIcons = GameIcons;
|
||||
@@ -0,0 +1,365 @@
|
||||
function allReads(promises) {
|
||||
var failure = null;
|
||||
return Promise.all(promises.map(function (promise) {
|
||||
return promise.catch(function (error) { if (!failure) failure = error; });
|
||||
})).then(function (results) {
|
||||
if (failure) throw failure;
|
||||
return results;
|
||||
});
|
||||
}
|
||||
|
||||
function sessionChanged() {
|
||||
return new ApiError({ kind: "SESSION_CHANGED", message: "The game session changed during the query. Retry the query." });
|
||||
}
|
||||
|
||||
function decorateTech(techId, result) {
|
||||
var value = result.value || {};
|
||||
var uploaded = toBigInt(value.hashUploaded);
|
||||
var needed = toBigInt(value.hashNeeded);
|
||||
var percent = 0;
|
||||
if (needed > 0n) percent = Number((uploaded * 10000n) / needed) / 100;
|
||||
return {
|
||||
techId: techId,
|
||||
unlocked: !!value.unlocked,
|
||||
curLevel: value.curLevel || 0,
|
||||
maxLevel: value.maxLevel || 0,
|
||||
hashUploaded: String(value.hashUploaded || "0"),
|
||||
hashNeeded: String(value.hashNeeded || "0"),
|
||||
progress: percent / 100,
|
||||
progressPercent: percent,
|
||||
sessionId: result.sessionId,
|
||||
gameTick: result.gameTick
|
||||
};
|
||||
}
|
||||
|
||||
function GameQuery(client) {
|
||||
this.client = client;
|
||||
this._sessionId = null;
|
||||
this._sessionVersion = 0;
|
||||
this._indexCache = new Map();
|
||||
}
|
||||
|
||||
GameQuery.prototype._rememberSession = function (sessionId) {
|
||||
if (sessionId !== this._sessionId) {
|
||||
this._sessionId = sessionId;
|
||||
this._sessionVersion += 1;
|
||||
this._indexCache.clear();
|
||||
}
|
||||
};
|
||||
|
||||
GameQuery.prototype._assertSession = function (context) {
|
||||
if (context.sessionId !== this._sessionId) throw sessionChanged();
|
||||
};
|
||||
|
||||
GameQuery.prototype._read = function (params, context) {
|
||||
context = context || {};
|
||||
var self = this;
|
||||
var version = this._sessionVersion;
|
||||
return this.client.read(params).then(function (result) {
|
||||
if (version !== self._sessionVersion && result.sessionId !== self._sessionId) throw sessionChanged();
|
||||
self._rememberSession(result.sessionId);
|
||||
if (context.sessionId && context.sessionId !== result.sessionId) throw sessionChanged();
|
||||
context.sessionId = result.sessionId;
|
||||
context.gameTick = result.gameTick;
|
||||
return result;
|
||||
}).catch(function (err) {
|
||||
if (err && (err.kind === "SESSION_CHANGED" || err.kind === "GAME_NOT_READY")) {
|
||||
self._indexCache.clear();
|
||||
if (version === self._sessionVersion) self._rememberSession(null);
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype.waitUntilReady = function (options) {
|
||||
options = options || {};
|
||||
var interval = options.intervalMs == null ? 500 : options.intervalMs;
|
||||
var timeout = options.timeoutMs == null ? 30000 : options.timeoutMs;
|
||||
var self = this;
|
||||
var start = Date.now();
|
||||
function loop() {
|
||||
var version = self._sessionVersion;
|
||||
return self.client.roots().then(function (roots) {
|
||||
if (roots && roots.gameReady) {
|
||||
if (version !== self._sessionVersion && roots.sessionId !== self._sessionId) throw sessionChanged();
|
||||
self._rememberSession(roots.sessionId);
|
||||
return roots;
|
||||
}
|
||||
self._rememberSession(null);
|
||||
if (Date.now() - start >= timeout) {
|
||||
throw new ApiError({ kind: "GAME_NOT_READY", message: "Timed out waiting for a player game." });
|
||||
}
|
||||
return new Promise(function (resolve) { setTimeout(resolve, interval); }).then(loop);
|
||||
});
|
||||
}
|
||||
return loop();
|
||||
};
|
||||
|
||||
GameQuery.prototype._getTechState = function (techId, context) {
|
||||
var self = this;
|
||||
return this._read({
|
||||
root: "history",
|
||||
path: ["techStates", key(techId)],
|
||||
select: ["unlocked", "curLevel", "maxLevel", "hashUploaded", "hashNeeded"]
|
||||
}, context).then(function (result) {
|
||||
self._assertSession(context);
|
||||
return decorateTech(techId, result);
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype.getTechState = function (techId) {
|
||||
return this._getTechState(techId, {});
|
||||
};
|
||||
|
||||
GameQuery.prototype.getCurrentResearch = function () {
|
||||
var self = this;
|
||||
var context = {};
|
||||
return this._read({ root: "history", path: ["currentTech"] }, context).then(function (tech) {
|
||||
self._assertSession(context);
|
||||
var techId = tech.value || 0;
|
||||
if (!techId) return { techId: 0, active: false, sessionId: tech.sessionId, gameTick: tech.gameTick };
|
||||
return self._getTechState(techId, context).then(function (state) {
|
||||
self._assertSession(context);
|
||||
state.active = true;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype.getClusterString = function () {
|
||||
var self = this;
|
||||
var context = {};
|
||||
return this._read({ root: "game", path: ["gameDesc", "clusterString"] }, context).then(function (result) {
|
||||
self._assertSession(context);
|
||||
return {
|
||||
clusterString: result.value == null ? "" : String(result.value),
|
||||
sessionId: result.sessionId,
|
||||
gameTick: result.gameTick
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype._factoryIds = function (scope, context) {
|
||||
if (scope === "localPlanet") {
|
||||
return this._read({ root: "localPlanet", path: ["factoryIndex"] }, context).then(function (result) {
|
||||
return Number.isInteger(result.value) && result.value >= 0 ? [result.value] : [];
|
||||
});
|
||||
}
|
||||
var factoryIndex = scope && typeof scope === "object" ? scope.factoryIndex : null;
|
||||
if (factoryIndex != null) {
|
||||
if (!Number.isInteger(factoryIndex) || factoryIndex < 0) throw new RangeError("factoryIndex must be a nonnegative integer.");
|
||||
} else if (scope != null && scope !== "cluster") {
|
||||
throw new Error("Unknown production scope.");
|
||||
}
|
||||
return this._read({ root: "game", path: ["factoryCount"] }, context).then(function (result) {
|
||||
var ids = [];
|
||||
var count = result.value || 0;
|
||||
if (factoryIndex != null) return factoryIndex < count ? [factoryIndex] : [];
|
||||
for (var index = 0; index < count; index++) ids.push(index);
|
||||
return ids;
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype._productIndex = function (factoryIndex, itemId, context) {
|
||||
this._assertSession(context);
|
||||
var cacheKey = factoryIndex + ":" + itemId;
|
||||
if (this._indexCache.has(cacheKey)) return Promise.resolve(this._indexCache.get(cacheKey));
|
||||
var self = this;
|
||||
return this._read({
|
||||
root: "statistics",
|
||||
path: ["production", "factoryStatPool", factoryIndex, "productIndices", itemId]
|
||||
}, context).then(function (result) {
|
||||
self._assertSession(context);
|
||||
var index = result.value || 0;
|
||||
if (index > 0) self._indexCache.set(cacheKey, index);
|
||||
return index;
|
||||
}).catch(function (err) {
|
||||
if (err && (err.kind === "INDEX_OUT_OF_RANGE" || err.kind === "NULL_PATH")) {
|
||||
self._assertSession(context);
|
||||
return 0;
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype._readFactoryItem = function (factoryIndex, itemId, spec, context) {
|
||||
var self = this;
|
||||
var consumptionOffset = spec.consumptionIndex - spec.productionIndex;
|
||||
return this._productIndex(factoryIndex, itemId, context).then(function (poolIndex) {
|
||||
if (!poolIndex) {
|
||||
return { itemId: itemId, production: 0, consumption: 0, theoreticalProduction: 0, theoreticalConsumption: 0, hit: false };
|
||||
}
|
||||
return allReads([
|
||||
self._read({
|
||||
root: "statistics",
|
||||
path: ["production", "factoryStatPool", factoryIndex, "productPool", poolIndex, "total"],
|
||||
offset: spec.productionIndex,
|
||||
limit: consumptionOffset + 1
|
||||
}, context),
|
||||
self._read({
|
||||
root: "statistics",
|
||||
path: ["production", "factoryStatPool", factoryIndex, "productPool", poolIndex],
|
||||
select: ["refProductSpeed", "refConsumeSpeed"]
|
||||
}, context)
|
||||
]).then(function (pair) {
|
||||
self._assertSession(context);
|
||||
var totals = (pair[0].value && pair[0].value.items) || [];
|
||||
var refs = pair[1].value || {};
|
||||
var productionTotal = toNumber(totals[0]) || 0;
|
||||
var consumptionTotal = toNumber(totals[consumptionOffset]) || 0;
|
||||
return {
|
||||
itemId: itemId,
|
||||
production: spec.perMinute ? productionTotal / spec.divisor : productionTotal,
|
||||
consumption: spec.perMinute ? consumptionTotal / spec.divisor : consumptionTotal,
|
||||
theoreticalProduction: refs.refProductSpeed || 0,
|
||||
theoreticalConsumption: refs.refConsumeSpeed || 0,
|
||||
hit: true
|
||||
};
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype.getItemRates = function (itemId, options) {
|
||||
options = options || {};
|
||||
var windowName = options.window || "1min";
|
||||
var spec = RATE_WINDOWS[windowName];
|
||||
if (!Object.prototype.hasOwnProperty.call(RATE_WINDOWS, windowName)) throw new Error("Unknown production window: " + windowName);
|
||||
var ids = Array.isArray(itemId) ? itemId : [itemId];
|
||||
ids.forEach(function (id) {
|
||||
if (!Number.isInteger(id) || id <= 0) throw new RangeError("Item IDs must be positive integers.");
|
||||
});
|
||||
if (!ids.length) return Promise.resolve([]);
|
||||
var uniqueIds = Array.from(new Set(ids));
|
||||
var self = this;
|
||||
var context = {};
|
||||
return this._factoryIds(options.scope, context).then(function (factoryIds) {
|
||||
self._assertSession(context);
|
||||
var jobs = [];
|
||||
factoryIds.forEach(function (factoryIndex) {
|
||||
uniqueIds.forEach(function (id) { jobs.push(self._readFactoryItem(factoryIndex, id, spec, context)); });
|
||||
});
|
||||
return allReads(jobs);
|
||||
}).then(function (parts) {
|
||||
self._assertSession(context);
|
||||
var byItem = Object.create(null);
|
||||
uniqueIds.forEach(function (id) {
|
||||
byItem[id] = {
|
||||
itemId: id, window: windowName, perMinute: spec.perMinute,
|
||||
production: 0, consumption: 0, theoreticalProduction: 0, theoreticalConsumption: 0, factories: 0
|
||||
};
|
||||
});
|
||||
parts.forEach(function (part) {
|
||||
if (!part) return;
|
||||
var row = byItem[part.itemId];
|
||||
row.production += part.production;
|
||||
row.consumption += part.consumption;
|
||||
row.theoreticalProduction += part.theoreticalProduction;
|
||||
row.theoreticalConsumption += part.theoreticalConsumption;
|
||||
if (part.hit) row.factories++;
|
||||
});
|
||||
var list = ids.map(function (id) {
|
||||
var row = byItem[id];
|
||||
row.sessionId = context.sessionId;
|
||||
row.gameTick = context.gameTick;
|
||||
return row;
|
||||
});
|
||||
return Array.isArray(itemId) ? list : list[0];
|
||||
});
|
||||
};
|
||||
|
||||
var SPHERE_ENERGY_FIELDS = ["energyGenCurrentTick", "energyGenOriginalCurrentTick", "energyReqCurrentTick"];
|
||||
|
||||
GameQuery.prototype._readSphere = function (starIndex, energy, context) {
|
||||
var self = this;
|
||||
return this._read({
|
||||
root: "game",
|
||||
path: ["dysonSpheres", starIndex, "starData"],
|
||||
select: ["index", "id", "name", "overrideName"]
|
||||
}, context).then(function (result) {
|
||||
self._assertSession(context);
|
||||
var star = result.value || {};
|
||||
var joules = toBigInt(energy.energyGenCurrentTick);
|
||||
var original = toBigInt(energy.energyGenOriginalCurrentTick);
|
||||
var watts = joules * BigInt(TICKS_PER_SECOND);
|
||||
return {
|
||||
starIndex: starIndex,
|
||||
starId: star.id,
|
||||
name: star.overrideName || star.name || ("Star " + starIndex),
|
||||
joulesPerTick: joules.toString(),
|
||||
originalJoulesPerTick: original.toString(),
|
||||
watts: watts.toString(),
|
||||
originalWatts: (original * BigInt(TICKS_PER_SECOND)).toString(),
|
||||
wattsNumber: toNumber(watts),
|
||||
energyReqCurrentTick: energy.energyReqCurrentTick != null ? String(energy.energyReqCurrentTick) : "0",
|
||||
sessionId: context.sessionId,
|
||||
gameTick: context.gameTick
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype._collectSpheres = function (offset, spheres, context) {
|
||||
var self = this;
|
||||
var limits = this.client.infoSnapshot && this.client.infoSnapshot.limits;
|
||||
var pageSize = limits && limits.maxPageSize || 128;
|
||||
return this._read({
|
||||
root: "game", path: ["dysonSpheres"], select: SPHERE_ENERGY_FIELDS,
|
||||
offset: offset, limit: Math.min(128, pageSize)
|
||||
}, context).then(function (page) {
|
||||
self._assertSession(context);
|
||||
var items = (page.value && page.value.items) || [];
|
||||
var jobs = [];
|
||||
items.forEach(function (entry, itemIndex) {
|
||||
var index = (page.value.offset || 0) + itemIndex;
|
||||
if (!entry) return;
|
||||
jobs.push(self._readSphere(index, entry, context));
|
||||
});
|
||||
return allReads(jobs).then(function (batch) {
|
||||
Array.prototype.push.apply(spheres, batch);
|
||||
if (page.value && page.value.hasMore) {
|
||||
var nextOffset = (page.value.offset || 0) + items.length;
|
||||
if (nextOffset <= offset) throw new ApiError({ kind: "INVALID_RESPONSE", message: "Collection page made no progress." });
|
||||
return self._collectSpheres(nextOffset, spheres, context);
|
||||
}
|
||||
return spheres;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
GameQuery.prototype.getDysonPower = function (options) {
|
||||
options = options || {};
|
||||
var self = this;
|
||||
var context = {};
|
||||
var request;
|
||||
if (options.starIndex == null) {
|
||||
request = this._collectSpheres(0, [], context);
|
||||
} else {
|
||||
if (!Number.isInteger(options.starIndex) || options.starIndex < 0) throw new RangeError("starIndex must be a nonnegative integer.");
|
||||
request = this._read({
|
||||
root: "game", path: ["dysonSpheres", options.starIndex], select: SPHERE_ENERGY_FIELDS
|
||||
}, context).then(function (result) {
|
||||
if (!result.value) return [];
|
||||
return self._readSphere(options.starIndex, result.value, context).then(function (sphere) { return [sphere]; });
|
||||
});
|
||||
}
|
||||
return request.then(function (spheres) {
|
||||
self._assertSession(context);
|
||||
var total = 0n;
|
||||
var original = 0n;
|
||||
spheres.forEach(function (sphere) {
|
||||
total += toBigInt(sphere.watts);
|
||||
original += toBigInt(sphere.originalWatts);
|
||||
});
|
||||
return {
|
||||
sphereCount: spheres.length,
|
||||
watts: total.toString(),
|
||||
originalWatts: original.toString(),
|
||||
wattsNumber: toNumber(total),
|
||||
joulesPerTick: (total / BigInt(TICKS_PER_SECOND)).toString(),
|
||||
spheres: spheres,
|
||||
sessionId: context.sessionId,
|
||||
gameTick: context.gameTick
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
ns.GameQuery = GameQuery;
|
||||
@@ -0,0 +1,106 @@
|
||||
var LCID_ALIASES = {
|
||||
en: 1033, "en-us": 1033,
|
||||
zh: 2052, "zh-cn": 2052,
|
||||
fr: 1036, "fr-fr": 1036,
|
||||
de: 1031, "de-de": 1031,
|
||||
ja: 1041, "ja-jp": 1041, "ja-ja": 1041
|
||||
};
|
||||
|
||||
function normalizeLcid(language, languages) {
|
||||
if (language == null || language === "") return 1033;
|
||||
if (typeof language === "number") return language;
|
||||
var lower = String(language).toLowerCase();
|
||||
if (Object.prototype.hasOwnProperty.call(LCID_ALIASES, lower)) return LCID_ALIASES[lower];
|
||||
if (/^\d+$/.test(String(language))) return parseInt(language, 10);
|
||||
if (languages) {
|
||||
var ids = Object.keys(languages);
|
||||
for (var i = 0; i < ids.length; i++) {
|
||||
var meta = languages[ids[i]];
|
||||
if (!meta) continue;
|
||||
if (String(meta.abbr).toLowerCase() === lower || String(meta.abbr2).toLowerCase() === lower || String(meta.name).toLowerCase() === lower) {
|
||||
return parseInt(ids[i], 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
return 1033;
|
||||
}
|
||||
|
||||
function GameText(data, options) {
|
||||
options = options || {};
|
||||
this.data = data || { languages: {}, ids: {}, strings: {} };
|
||||
this.lcid = normalizeLcid(options.language, this.data.languages);
|
||||
}
|
||||
|
||||
GameText.fromGenerated = function (options) {
|
||||
var data = (typeof globalThis !== "undefined" && globalThis.LiveStreamAssistTextData) ||
|
||||
(typeof window !== "undefined" && window.LiveStreamAssistTextData) ||
|
||||
null;
|
||||
if (!data) throw new Error("LiveStreamAssistTextData is not loaded. Include generated/dsp-text.js first.");
|
||||
return new GameText(data, options);
|
||||
};
|
||||
|
||||
GameText.prototype.setLanguage = function (language) {
|
||||
this.lcid = normalizeLcid(language, this.data.languages);
|
||||
return this;
|
||||
};
|
||||
|
||||
GameText.prototype.translate = function (nameKey) {
|
||||
if (nameKey == null || nameKey === "") return "";
|
||||
var row = this.data.strings && this.data.strings[nameKey];
|
||||
if (!row) return String(nameKey);
|
||||
var lcid = String(this.lcid);
|
||||
if (row[lcid] != null) return row[lcid];
|
||||
return String(nameKey);
|
||||
};
|
||||
|
||||
GameText.prototype.nameKey = function (kind, id) {
|
||||
var table = this.data.ids && this.data.ids[kind];
|
||||
return table ? table[String(id)] || null : null;
|
||||
};
|
||||
|
||||
GameText.prototype.name = function (kind, id) {
|
||||
var nameKey = this.nameKey(kind, id);
|
||||
return nameKey ? this.translate(nameKey) : "";
|
||||
};
|
||||
|
||||
GameText.prototype.itemName = function (id) { return this.name("item", id); };
|
||||
GameText.prototype.techName = function (id) { return this.name("tech", id); };
|
||||
GameText.prototype.recipeName = function (id) { return this.name("recipe", id); };
|
||||
GameText.prototype.signalName = function (id) { return this.name("signal", id); };
|
||||
GameText.prototype.veinName = function (id) { return this.name("vein", id); };
|
||||
|
||||
GameText.prototype.techDisplayName = function (id, curLevel) {
|
||||
var name = this.techName(id);
|
||||
if (!name) return "";
|
||||
if (!curLevel) return name;
|
||||
return name + this.translate("杠等级") + curLevel;
|
||||
};
|
||||
|
||||
GameText.prototype.separators = function () {
|
||||
var thousand = this.translate("千分分隔符");
|
||||
var decimal = this.translate("小数点");
|
||||
return {
|
||||
thousand: thousand && thousand.length === 1 ? thousand : ",",
|
||||
decimal: decimal && decimal.length === 1 ? decimal : "."
|
||||
};
|
||||
};
|
||||
|
||||
GameText.prototype.formatKmg = function (value, options) {
|
||||
return formatKmg(value, Object.assign({ decimal: this.separators().decimal, kind: "count" }, options));
|
||||
};
|
||||
GameText.prototype.formatPower = function (value, options) {
|
||||
return formatKmg(value, Object.assign({ decimal: this.separators().decimal, kind: "power" }, options));
|
||||
};
|
||||
GameText.prototype.formatEnergy = function (value, options) {
|
||||
return formatKmg(value, Object.assign({ decimal: this.separators().decimal, kind: "energy" }, options));
|
||||
};
|
||||
GameText.prototype.formatRate = function (value) {
|
||||
var seps = this.separators();
|
||||
if (value >= 10000) return this.formatKmg(Math.round(value));
|
||||
if (value >= 1000) return value.toFixed(0);
|
||||
if (value >= 100) return value.toFixed(1).replace(".", seps.decimal);
|
||||
if (value > 0) return value.toFixed(2).replace(".", seps.decimal);
|
||||
return "0";
|
||||
};
|
||||
|
||||
ns.GameText = GameText;
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "LiveStreamAssist",
|
||||
"version_number": "1.0.0",
|
||||
"website_url": "https://github.com/soarqin/DSP_Mods/tree/master/LiveStreamAssist",
|
||||
"description": "Keep the statistics window active for live streams",
|
||||
"dependencies": [
|
||||
"xiaoye97-BepInEx-5.4.17",
|
||||
"soarqin-UXAssist-1.5.9"
|
||||
]
|
||||
}
|
||||
Loaded 100 of 267 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user