feat(livestreamassist): add Chinese live dashboard with game icons

- Add a URL-driven Chinese overlay page rendering item rate tables,
  tech levels, current research, and Dyson sphere power for streams.
- Add the offline GameIcons layer and generate_icons.py, which extracts
  every item and tech icon from a local DSP install into
  js/generated/dsp-icons.js.
- Reuse the proto extraction in generate_text.py and cover the new
  page with test_dashboard.js.
This commit is contained in:
soarqin committed 2026-09-20 03:44:27 +08:00
1 parent 63a6a6ec6c
commit 3e3e995d55
12 files changed
+787 -15

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@
- 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` offline from generated locale/proto dictionaries. Do not have `GameText` 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` with `python LiveStreamAssist/js/scripts/generate_text.py` from a local DSP install. Run the JS and Python checks documented in `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
+2 -1
View File
@@ -30,8 +30,9 @@ Open the overlay examples in a browser or OBS Browser Source. Default URL is `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` for localized names and DSP KMG formatting. Keep the `examples/` and `js/` directories side by side when copying an overlay. `GameText` does not call the WebSocket API; regenerate `js/generated/dsp-text.js` from the repository root with `python LiveStreamAssist/js/scripts/generate_text.py`.
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,327 @@
<!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; }
.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 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();
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 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.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.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>
+29 -5
View File
@@ -2,22 +2,25 @@
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 three layers:
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` never sends API requests. Names come from generated dictionaries converted from the game's `Locale/` files and prototype tables.
`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
@@ -54,8 +57,21 @@ 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. Both examples retry failed connections, wait for each polling cycle to finish before scheduling another, and discard old results when the URL changes. Use `?lang=en`, `?lang=zh-CN`, or an LCID such as `?lang=2052`; the stats example also accepts `?item=1101`.
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
@@ -102,12 +118,20 @@ Load `generated/dsp-text.js` before the library, then `GameText.fromGenerated({
- `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 (`小数点`).
## Regenerating text data
## 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
```
@@ -119,7 +143,7 @@ Run from the repository root. JavaScript checks use Node.js 20 or later and requ
```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
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
```
@@ -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,iVBOR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Q399HluYI2ZsxtWwHNwgxWr/caM2znZ+OBIol3wDglwKSTnJk/RW5MgS+x9BAiTTLmKs2SBRYfhkpDWG5jPTLRHGGaXRwgoBumhD5NkjwLIuiY1PrdLEFrB3qx7YsumlOkuZMJw3OXjnOt+/6MQ8+vBMHRRZrxleMY0sLlSlyleM4Ln4hoFDppzF98JeB//Zz1YWP0CaLB2dqIyph0GNeN1XMznfRwsEvlXBsm7BSJuzrB9fDTzXab/Lw4zPcfOuPeeULt1F2HCwEnuVgi5TRSonAstg7N89Uo0Wc5ly8aQ2Hpqt857YfkkUxRmrGV07guQ5ZkpFnOXGUMDRSpjk3xdzBfRRHxu/4ecFAcyQRteMjybe7jk1Y8Km2EhrdFNtxqRRDgjDACQqUCj65tMgcjyDwGPJCJvcf4p/+6S5GxwbYsnEFw47LcOijjabWjYlMSidNGSoXGSoEFFyH7YdmSKOYPIsZHB+hUi6SRgnSCJI0x7Ftup2UyX17STsthlau+8zPnRKJuylCyqMxVVrMt1OS3FAsFiiVQiz Line truncated
+21
View File
@@ -846,5 +846,26 @@
};
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,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())
+23 -7
View File
@@ -249,7 +249,10 @@ def find_game_root(explicit: str | None) -> Path | None:
return None
def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str, str]]:
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
@@ -259,6 +262,7 @@ def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str
"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))
@@ -269,15 +273,15 @@ def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str
continue
script = obj.read()
class_name = getattr(script, "m_ClassName", "")
if class_name in KIND_FROM_SET:
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 KIND_FROM_SET
for class_name in wanted
}
ids: dict[str, dict[str, str]] = {kind: {} for kind in KIND_FROM_SET.values()}
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
@@ -293,10 +297,22 @@ def extract_proto_ids(game_root: Path, unity_version: str) -> dict[str, dict[str
tree = obj.read_typetree(nodes[class_name], check_read=False)
for proto in tree.get("dataArray") or []:
proto_id = proto.get("ID")
name = proto.get("Name")
if not proto_id or not name:
if not proto_id:
continue
ids[kind][str(int(proto_id))] = name
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}
+1
View File
@@ -10,6 +10,7 @@ parts = [
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)
@@ -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, "已连接");
});
+1 -1
View File
@@ -6,7 +6,7 @@ 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", "footer"];
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.");
+21
View File
@@ -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;