From 945c20f9f8cec3da014364578acc98e14979344e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 2 Jul 2026 13:05:33 +0100 Subject: [PATCH] Wire shared CultUI debug surface file --- .../Client/aetheria-rts-contract.ts | 2 + Aetheria.Rts.Web/Client/app.ts | 17 + Aetheria.Rts.Web/Electron/main.ts | 202 +++++++++- Aetheria.Rts.Web/Electron/preload.cjs | 19 + Aetheria.Rts.Web/wwwroot/index.html | 4 + Aetheria.Rts.Web/wwwroot/styles.css | 56 +++ GameData/cultui-debug-surface.cultui | 116 ++++++ .../AetheriaEveFileSurfacePresenter.cs | 348 ++++++++++++++++++ .../AetheriaEveFileSurfacePresenter.cs.meta | 11 + .../Runtime/AetheriaEveRuntimeBootstrap.cs | 25 +- docs/aetheria-perfect-machine-map.md | 6 + 11 files changed, 801 insertions(+), 5 deletions(-) create mode 100644 GameData/cultui-debug-surface.cultui create mode 100644 Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveFileSurfacePresenter.cs create mode 100644 Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveFileSurfacePresenter.cs.meta diff --git a/Aetheria.Rts.Web/Client/aetheria-rts-contract.ts b/Aetheria.Rts.Web/Client/aetheria-rts-contract.ts index d03470ee8..136fa2185 100644 --- a/Aetheria.Rts.Web/Client/aetheria-rts-contract.ts +++ b/Aetheria.Rts.Web/Client/aetheria-rts-contract.ts @@ -346,6 +346,8 @@ export type AetheriaRtsApi = { surfaceCatalog(): Promise; surfaceCatalogIndex(): Promise; mainMenuSurface(request: AetheriaMenuSurfaceRequest): Promise; + debugSurface(): Promise; + watchDebugSurface(callback: (surface: AetheriaMenuSurfaceDocument) => void): () => void; windowControl(action: "minimize" | "maximize" | "close"): Promise; health(): Promise; }; diff --git a/Aetheria.Rts.Web/Client/app.ts b/Aetheria.Rts.Web/Client/app.ts index e2ec71d47..a516c602e 100644 --- a/Aetheria.Rts.Web/Client/app.ts +++ b/Aetheria.Rts.Web/Client/app.ts @@ -33,6 +33,7 @@ const frameDetails = requiredElement("#frame-details"); const starbridgeDetails = requiredElement("#starbridge-details"); const runtimeSurfaceDetails = requiredElement("#runtime-surface-details"); const controlledList = requiredElement("#controlled-list"); +const debugSurfaceHost = requiredElement("#debug-surface-host"); const ctx = requiredContext(canvas); let zoom = 1; @@ -134,6 +135,20 @@ function renderMainMenuSurface(surface: AetheriaMenuSurfaceDocument): void { wireWindowControls(); } +async function startDebugSurface(): Promise { + try { + renderDebugSurface(await window.aetheriaRts.debugSurface()); + window.aetheriaRts.watchDebugSurface(renderDebugSurface); + } catch (error) { + debugSurfaceHost.textContent = error instanceof Error ? error.message : "CultUI debug surface unavailable."; + } +} + +function renderDebugSurface(surface: AetheriaMenuSurfaceDocument): void { + installMenuFonts(surface); + debugSurfaceHost.replaceChildren(lowerMenuComponent(surface.surface.root, surface)); +} + function lowerMenuComponent( component: AetheriaMenuSurfaceComponent, surface: AetheriaMenuSurfaceDocument, @@ -175,6 +190,7 @@ function lowerMenuComponent( kind === "surface" ? "eve-surface" : "", kind === "column" ? "eve-column" : "", kind === "row" ? "eve-row" : "", + kind === "form" ? "eve-form" : "", ].filter(Boolean).join(" "); for (const child of component.children ?? []) { element.append(lowerMenuComponent(child, surface)); @@ -735,6 +751,7 @@ if (mainMenuMode) { void showMainMenu(); } else { updateZoomLabel(); + void startDebugSurface(); void refreshRuntimeSurfaces(); void refresh(); } diff --git a/Aetheria.Rts.Web/Electron/main.ts b/Aetheria.Rts.Web/Electron/main.ts index 592be32a4..ddc9423af 100644 --- a/Aetheria.Rts.Web/Electron/main.ts +++ b/Aetheria.Rts.Web/Electron/main.ts @@ -1,12 +1,16 @@ -import { app, BrowserWindow, ipcMain, shell } from "electron"; +import { app, BrowserWindow, ipcMain, shell, type WebContents } from "electron"; import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; -import { createWriteStream, existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { createWriteStream, existsSync, mkdirSync, readFileSync, watch, writeFileSync, type FSWatcher } from "node:fs"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { AetheriaCultMeshClient, } from "./aetheria-cultmesh.js"; +import type { + AetheriaMenuSurfaceComponent, + AetheriaMenuSurfaceDocument, +} from "./aetheria-cultmesh.js"; import { registerAetheriaRtsIpcHandlers } from "./aetheria-rts-generated-bindings.js"; const __dirname = dirname(fileURLToPath(import.meta.url)); @@ -15,6 +19,7 @@ const repoRoot = resolve(projectRoot, ".."); const logsRoot = resolve(projectRoot, "logs"); const runtimeRoot = resolve(process.env.AETHERIA_RTS_RUNTIME_ROOT ?? resolve(projectRoot, "runtime")); const runtimeStatePath = resolve(runtimeRoot, "aetheria-rts.cc"); +const debugSurfacePath = resolve(process.env.AETHERIA_CULTUI_DEBUG_SURFACE_PATH ?? resolve(repoRoot, "GameData", "cultui-debug-surface.cultui")); const daemonDll = resolve(repoRoot, "Aetheria.State.Daemon", "bin", "Debug", "net10.0", "Aetheria.State.Daemon.dll"); const rendererIndex = resolve(projectRoot, "wwwroot", "index.html"); const rtsCultMeshPort = Number.parseInt(process.env.AETHERIA_RTS_CULTMESH_PORT ?? "3076", 10); @@ -33,6 +38,44 @@ let daemonProcess: ChildProcessWithoutNullStreams | null = null; let mainWindow: BrowserWindow | null = null; let rtsClient: AetheriaCultMeshClient | null = null; let isQuitting = false; +let debugSurfaceWatcher: FSWatcher | null = null; +let debugSurfaceWatchTimer: NodeJS.Timeout | null = null; +const debugSurfaceSubscriptions = new Map(); + +type AetheriaFileSurfaceDocument = { + readonly schema?: string; + readonly providerId?: string; + readonly providerKind?: string; + readonly title?: string; + readonly version?: number; + readonly updatedAtUtc?: string; + readonly surface?: AetheriaFileSurfaceTree; + readonly commands?: readonly AetheriaFileCommand[]; +}; + +type AetheriaFileSurfaceTree = { + readonly id?: string; + readonly root?: AetheriaFileSurfaceComponent; + readonly styles?: readonly AetheriaFileStyleToken[]; +}; + +type AetheriaFileSurfaceComponent = { + readonly id?: string; + readonly kind?: string; + readonly props?: unknown; + readonly children?: readonly AetheriaFileSurfaceComponent[]; +}; + +type AetheriaFileStyleToken = { + readonly name?: string; + readonly value?: string; +}; + +type AetheriaFileCommand = { + readonly command?: string; + readonly label?: string; + readonly transport?: string; +}; app.whenReady().then(async () => { mainWindow = createWindow(); @@ -111,6 +154,7 @@ app.on("before-quit", () => { isQuitting = true; void rtsClient?.close(); stopChild(daemonProcess); + closeDebugSurfaceWatcher(); }); function createWindow(): BrowserWindow { @@ -304,6 +348,26 @@ function registerIpc(): void { })); ipcMain.handle("aetheria-rts:main-menu-surface", async (_event, request) => requireClient().mainMenuSurface(request)); + ipcMain.handle("aetheria-rts:debug-surface", () => readDebugSurface()); + ipcMain.handle("aetheria-rts:debug-surface-watch", (event, subscriptionId: string) => { + if (!subscriptionId) + throw new Error("Debug surface subscription id is required."); + + debugSurfaceSubscriptions.set(subscriptionId, event.sender); + event.sender.once("destroyed", () => { + debugSurfaceSubscriptions.delete(subscriptionId); + stopDebugSurfaceWatcherIfIdle(); + }); + ensureDebugSurfaceWatcher(); + event.sender.send("aetheria-rts:debug-surface-changed", { + subscriptionId, + surface: readDebugSurface(), + }); + }); + ipcMain.handle("aetheria-rts:debug-surface-watch-stop", (_event, subscriptionId: string) => { + debugSurfaceSubscriptions.delete(subscriptionId); + stopDebugSurfaceWatcherIfIdle(); + }); ipcMain.handle("aetheria-rts:window-control", (event, action: string) => { const window = BrowserWindow.fromWebContents(event.sender); if (!window) @@ -328,6 +392,140 @@ function registerIpc(): void { }); } +function readDebugSurface(): AetheriaMenuSurfaceDocument { + if (!existsSync(debugSurfacePath)) { + throw new Error(`CultUI debug surface file not found: ${debugSurfacePath}`); + } + + const document = JSON.parse(readFileSync(debugSurfacePath, "utf8")) as AetheriaFileSurfaceDocument; + return normalizeDebugSurface(document); +} + +function ensureDebugSurfaceWatcher(): void { + if (debugSurfaceWatcher) + return; + + debugSurfaceWatcher = watch(debugSurfacePath, { persistent: false }, () => { + if (debugSurfaceWatchTimer) + clearTimeout(debugSurfaceWatchTimer); + debugSurfaceWatchTimer = setTimeout(publishDebugSurfaceChange, 50); + }); + debugSurfaceWatcher.once("error", error => { + console.warn(`CultUI debug surface watcher failed for ${debugSurfacePath}:`, error); + closeDebugSurfaceWatcher(); + }); +} + +function publishDebugSurfaceChange(): void { + debugSurfaceWatchTimer = null; + let surface: AetheriaMenuSurfaceDocument; + try { + surface = readDebugSurface(); + } catch (error) { + console.warn(error instanceof Error ? error.message : String(error)); + return; + } + + for (const [subscriptionId, webContents] of debugSurfaceSubscriptions) { + if (webContents.isDestroyed()) { + debugSurfaceSubscriptions.delete(subscriptionId); + continue; + } + + webContents.send("aetheria-rts:debug-surface-changed", { subscriptionId, surface }); + } + stopDebugSurfaceWatcherIfIdle(); +} + +function stopDebugSurfaceWatcherIfIdle(): void { + if (debugSurfaceSubscriptions.size === 0) + closeDebugSurfaceWatcher(); +} + +function closeDebugSurfaceWatcher(): void { + if (debugSurfaceWatchTimer) { + clearTimeout(debugSurfaceWatchTimer); + debugSurfaceWatchTimer = null; + } + debugSurfaceWatcher?.close(); + debugSurfaceWatcher = null; +} + +function normalizeDebugSurface(document: AetheriaFileSurfaceDocument): AetheriaMenuSurfaceDocument { + const surfaceId = stringOr(document.surface?.id, "aetheria.debug.file_surface"); + return { + providerId: stringOr(document.providerId, "aetheria.debug"), + providerKind: stringOr(document.providerKind, "debug.file_surface"), + title: stringOr(document.title, "Aetheria Debug Surface"), + version: typeof document.version === "number" && Number.isFinite(document.version) + ? document.version + : Date.now(), + updatedAtUtc: stringOr(document.updatedAtUtc, new Date().toISOString()), + surface: { + id: surfaceId, + root: normalizeDebugComponent(document.surface?.root, `${surfaceId}.root`), + styles: Array.isArray(document.surface?.styles) + ? document.surface.styles.map(token => ({ + name: stringOr(token.name, ""), + value: stringOr(token.value, ""), + })) + : [], + }, + commands: Array.isArray(document.commands) + ? document.commands.map(command => ({ + command: stringOr(command.command, ""), + label: stringOr(command.label, command.command ?? ""), + transport: stringOr(command.transport, "debug-log"), + })) + : [], + }; +} + +function normalizeDebugComponent( + component: AetheriaFileSurfaceComponent | undefined, + fallbackId: string, +): AetheriaMenuSurfaceComponent { + if (!component) { + return { + id: fallbackId, + kind: "surface", + props: {}, + children: [], + }; + } + + return { + id: stringOr(component.id, fallbackId), + kind: stringOr(component.kind, "surface"), + props: normalizeDebugProps(component.props), + children: Array.isArray(component.children) + ? component.children.map((child, index) => normalizeDebugComponent(child, `${fallbackId}.${index}`)) + : [], + }; +} + +function normalizeDebugProps(props: unknown): Record { + if (Array.isArray(props)) { + return Object.fromEntries( + props + .map(prop => objectValue(prop)) + .filter(prop => prop && typeof prop.key === "string") + .map(prop => [String(prop!.key), stringOr(prop!.value, "")])); + } + + if (props != null && typeof props === "object") { + return Object.fromEntries( + Object.entries(props as Record) + .map(([key, value]) => [key, stringOr(value, "")])); + } + + return {}; +} + +function stringOr(value: unknown, fallback: string): string { + return typeof value === "string" ? value : fallback; +} + function parseEndpointList(value: string | undefined): string[] { if (!value) return []; diff --git a/Aetheria.Rts.Web/Electron/preload.cjs b/Aetheria.Rts.Web/Electron/preload.cjs index 8971356d2..0bf445335 100644 --- a/Aetheria.Rts.Web/Electron/preload.cjs +++ b/Aetheria.Rts.Web/Electron/preload.cjs @@ -21,6 +21,10 @@ const channels = { surfaceCatalog: "aetheria-rts:surface-catalog", surfaceCatalogIndex: "aetheria-rts:surface-catalog-index", mainMenuSurface: "aetheria-rts:main-menu-surface", + debugSurface: "aetheria-rts:debug-surface", + debugSurfaceWatch: "aetheria-rts:debug-surface-watch", + debugSurfaceWatchStop: "aetheria-rts:debug-surface-watch-stop", + debugSurfaceChanged: "aetheria-rts:debug-surface-changed", windowControl: "aetheria-rts:window-control", health: "aetheria-rts:health", }; @@ -54,6 +58,21 @@ contextBridge.exposeInMainWorld("aetheriaRts", { surfaceCatalog: () => ipcRenderer.invoke(channels.surfaceCatalog), surfaceCatalogIndex: () => ipcRenderer.invoke(channels.surfaceCatalogIndex), mainMenuSurface: request => ipcRenderer.invoke(channels.mainMenuSurface, request), + debugSurface: () => ipcRenderer.invoke(channels.debugSurface), + watchDebugSurface: callback => { + const subscriptionId = `debug-surface-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`; + const listener = (_event, message) => { + if (message?.subscriptionId === subscriptionId) { + callback(message.surface); + } + }; + ipcRenderer.on(channels.debugSurfaceChanged, listener); + void ipcRenderer.invoke(channels.debugSurfaceWatch, subscriptionId); + return () => { + ipcRenderer.off(channels.debugSurfaceChanged, listener); + void ipcRenderer.invoke(channels.debugSurfaceWatchStop, subscriptionId); + }; + }, windowControl: action => ipcRenderer.invoke(channels.windowControl, action), health: () => ipcRenderer.invoke(channels.health), }); diff --git a/Aetheria.Rts.Web/wwwroot/index.html b/Aetheria.Rts.Web/wwwroot/index.html index f7212320a..39e3fec0a 100644 --- a/Aetheria.Rts.Web/wwwroot/index.html +++ b/Aetheria.Rts.Web/wwwroot/index.html @@ -44,6 +44,10 @@

Runtime Surfaces

+
+

CultUI Debug

+
+
diff --git a/Aetheria.Rts.Web/wwwroot/styles.css b/Aetheria.Rts.Web/wwwroot/styles.css index 388fd45cc..a64035faa 100644 --- a/Aetheria.Rts.Web/wwwroot/styles.css +++ b/Aetheria.Rts.Web/wwwroot/styles.css @@ -307,6 +307,62 @@ dd { color: #91a4ad; } +.debug-surface-host { + min-width: 0; +} + +.debug-surface-host .eve-surface, +.debug-surface-host .eve-column, +.debug-surface-host .eve-form { + display: flex; + min-width: 0; + flex-direction: column; + gap: 8px; +} + +.debug-surface-host .eve-row { + display: flex; + min-width: 0; + flex-wrap: wrap; + gap: 8px; +} + +.debug-surface-host .eve-text-title { + color: #d8f7ff; + font-size: 16px; + font-weight: 700; +} + +.debug-surface-host .eve-text { + color: #b8c7cf; + font-size: 13px; + line-height: 1.35; +} + +.debug-surface-host .eve-metric { + display: grid; + grid-template-columns: 86px minmax(0, 1fr); + gap: 6px 8px; + font-size: 12px; +} + +.debug-surface-host .eve-metric dt { + color: #91a4ad; +} + +.debug-surface-host .eve-metric dd { + min-width: 0; + margin: 0; + overflow-wrap: anywhere; +} + +.debug-surface-host .eve-control-button { + min-width: 82px; + height: 28px; + border-radius: 4px; + font-size: 12px; +} + @media (max-width: 760px) { .shell { grid-template-columns: 1fr; diff --git a/GameData/cultui-debug-surface.cultui b/GameData/cultui-debug-surface.cultui new file mode 100644 index 000000000..6b03a5dd7 --- /dev/null +++ b/GameData/cultui-debug-surface.cultui @@ -0,0 +1,116 @@ +{ + "schema": "gamecult.eve.surface.authoring.v1", + "providerId": "aetheria.debug", + "providerKind": "debug.file_surface", + "title": "Aetheria Debug Surface", + "version": 1, + "updatedAtUtc": "2026-07-02T00:00:00.0000000Z", + "surface": { + "id": "aetheria.debug.file_surface", + "styles": [ + { + "name": "font.title.family", + "value": "Montserrat" + }, + { + "name": "font.body.family", + "value": "Ubuntu" + } + ], + "root": { + "id": "aetheria.debug.file_surface.root", + "kind": "surface", + "props": [], + "children": [ + { + "id": "aetheria.debug.file_surface.title", + "kind": "text.title", + "props": [ + { + "key": "value", + "value": "CULTUI DEBUG" + } + ], + "children": [] + }, + { + "id": "aetheria.debug.file_surface.note", + "kind": "text", + "props": [ + { + "key": "value", + "value": "This file owns the debug composition. Unity and Electron lower this same document and reload it when the file changes." + } + ], + "children": [] + }, + { + "id": "aetheria.debug.file_surface.metrics", + "kind": "form", + "props": [], + "children": [ + { + "id": "aetheria.debug.file_surface.owner", + "kind": "metric", + "props": [ + { + "key": "label", + "value": "Owner" + }, + { + "key": "value", + "value": "GameData/cultui-debug-surface.cultui" + } + ], + "children": [] + }, + { + "id": "aetheria.debug.file_surface.reload", + "kind": "metric", + "props": [ + { + "key": "label", + "value": "Reload" + }, + { + "key": "value", + "value": "file timestamp watch" + } + ], + "children": [] + } + ] + }, + { + "id": "aetheria.debug.file_surface.actions", + "kind": "row", + "props": [], + "children": [ + { + "id": "aetheria.debug.file_surface.ping", + "kind": "control.button", + "props": [ + { + "key": "label", + "value": "Ping" + }, + { + "key": "command", + "value": "aetheria.debug.ping" + } + ], + "children": [] + } + ] + } + ] + } + }, + "commands": [ + { + "command": "aetheria.debug.ping", + "label": "Ping", + "transport": "debug-log" + } + ] +} diff --git a/Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveFileSurfacePresenter.cs b/Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveFileSurfacePresenter.cs new file mode 100644 index 000000000..c09f98f18 --- /dev/null +++ b/Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveFileSurfacePresenter.cs @@ -0,0 +1,348 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; +using System.Text; +using GameCult.Eve.Surface; +using GameCult.Mesh; +using UnityEngine; +using UnityEngine.UIElements; + +#nullable enable + +namespace GameCult.Aetheria.EveRuntime +{ + [DisallowMultipleComponent] + [RequireComponent(typeof(UIDocument))] + public sealed class AetheriaEveFileSurfacePresenter : MonoBehaviour + { + public const string DebugSurfacePathEnvironmentVariable = "AETHERIA_CULTUI_DEBUG_SURFACE_PATH"; + public const string DefaultDebugSurfaceRelativePath = "GameData/cultui-debug-surface.cultui"; + + [SerializeField] + private string surfaceFilePath = ""; + + [SerializeField] + private bool mountOnEnable = true; + + [SerializeField] + private bool refreshInUpdate = true; + + [SerializeField] + private float refreshIntervalSeconds = 0.1f; + + private UIDocument? _document; + private string _mountedPath = ""; + private DateTime _mountedWriteTimeUtc = DateTime.MinValue; + private long _mountedLength = -1; + private float _nextRefreshTime; + + public string SurfaceFilePath + { + get => surfaceFilePath; + set => surfaceFilePath = value ?? ""; + } + + private void OnEnable() + { + if (mountOnEnable) + Mount(); + } + + private void Update() + { + if (!refreshInUpdate || Time.unscaledTime < _nextRefreshTime) + return; + + _nextRefreshTime = Time.unscaledTime + Mathf.Max(0.01f, refreshIntervalSeconds); + RefreshIfChanged(); + } + + public void Mount() + { + var path = ResolveSurfacePath(surfaceFilePath); + var document = ResolveDocument(); + if (!File.Exists(path)) + { + MountError(document, $"CultUI debug surface file not found: {path}"); + _mountedPath = ""; + return; + } + + try + { + var surface = AetheriaEveFileSurfaceDocuments.Read(path); + AetheriaEveUnitySurfaceHost.Render( + transform, + document, + "Aetheria CultUI File Surface", + surface, + request => Debug.Log( + $"CultUI debug file surface command preview: {request.ProviderId}/{request.SurfaceId}/{request.Operation.OperationId}"), + CreateChrome()); + CaptureMountedState(path); + } + catch (Exception ex) + { + MountError(document, $"Failed to read CultUI debug surface file: {ex.Message}"); + _mountedPath = ""; + } + } + + private void RefreshIfChanged() + { + var path = ResolveSurfacePath(surfaceFilePath); + if (!File.Exists(path)) + return; + + var info = new FileInfo(path); + if (string.Equals(_mountedPath, path, StringComparison.Ordinal) && + _mountedWriteTimeUtc == info.LastWriteTimeUtc && + _mountedLength == info.Length) + { + return; + } + + Mount(); + } + + private UIDocument ResolveDocument() + { + if (_document == null) + _document = GetComponent(); + return _document; + } + + private void CaptureMountedState(string path) + { + var info = new FileInfo(path); + _mountedPath = path; + _mountedWriteTimeUtc = info.LastWriteTimeUtc; + _mountedLength = info.Length; + } + + private static void MountError(UIDocument document, string message) + { + var root = document.rootVisualElement; + root.Clear(); + var label = new Label(message); + label.AddToClassList("aetheria-eve-runtime-error-label"); + root.Add(label); + Debug.LogWarning(message); + } + + public static string ResolveSurfacePath(string configuredPath) + { + var environmentPath = Environment.GetEnvironmentVariable(DebugSurfacePathEnvironmentVariable); + var path = string.IsNullOrWhiteSpace(configuredPath) ? environmentPath : configuredPath; + if (string.IsNullOrWhiteSpace(path)) + path = Path.Combine(ProjectRoot(), DefaultDebugSurfaceRelativePath); + if (Path.IsPathRooted(path)) + return Path.GetFullPath(path); + return Path.GetFullPath(Path.Combine(ProjectRoot(), path)); + } + + private static string ProjectRoot() + { + return Path.GetFullPath(Path.Combine(Application.dataPath, "..")); + } + + private static AetheriaEveUnitySurfaceChrome CreateChrome() + { + return new AetheriaEveUnitySurfaceChrome + { + UseShell = true, + RootAlignItems = Align.FlexEnd, + RootJustifyContent = Justify.FlexStart, + RootPaddingTop = 72f, + RootPaddingRight = 24f, + MaxWidth = 420f, + MinWidth = 360f, + BackgroundColor = new Color(0.05f, 0.07f, 0.09f, 0.94f), + BorderColor = new Color(0.35f, 0.64f, 0.74f, 0.82f) + }; + } + } + + public static class AetheriaEveFileSurfaceDocuments + { + public static EveSurfaceDocument Read(string path) + { + if (string.IsNullOrWhiteSpace(path)) + throw new ArgumentException("CultUI surface path is required.", nameof(path)); + + using var stream = File.OpenRead(path); + var serializer = new DataContractJsonSerializer( + typeof(FileSurfaceDocument), + new DataContractJsonSerializerSettings + { + UseSimpleDictionaryFormat = true + }); + var document = (FileSurfaceDocument?)serializer.ReadObject(stream) + ?? throw new InvalidDataException("CultUI surface file is empty."); + + return ToEveSurfaceDocument(document, path); + } + + private static EveSurfaceDocument ToEveSurfaceDocument(FileSurfaceDocument document, string path) + { + var surface = document.Surface; + var surfaceId = string.IsNullOrWhiteSpace(surface?.Id) + ? "aetheria.debug.file_surface" + : surface!.Id!; + var root = document.Surface?.Root == null + ? new EveSurfaceComponent( + surfaceId + ".root", + "surface", + new Dictionary(StringComparer.Ordinal), + Array.Empty()) + : ToComponent(document.Surface.Root); + var writeTime = File.GetLastWriteTimeUtc(path); + var providerId = string.IsNullOrWhiteSpace(document.ProviderId) ? "aetheria.debug" : document.ProviderId!; + var providerKind = string.IsNullOrWhiteSpace(document.ProviderKind) ? "debug.file_surface" : document.ProviderKind!; + var updatedAtUtc = string.IsNullOrWhiteSpace(document.UpdatedAtUtc) ? writeTime.ToString("O") : document.UpdatedAtUtc!; + return new EveSurfaceDocument( + providerId, + providerKind, + document.Title ?? "", + document.Version <= 0 ? writeTime.Ticks : document.Version, + updatedAtUtc, + new EveSurfaceTree( + surfaceId, + root, + (document.Surface?.Styles ?? Array.Empty()) + .Select(style => new EveStyleToken(style.Name ?? "", style.Value ?? "")) + .ToArray()), + (document.Commands ?? Array.Empty()) + .Where(command => !string.IsNullOrWhiteSpace(command.Command)) + .Select(command => new EveCommandTemplate(CultMesh.OperationBindingRecord( + command.Command ?? "", + command.Label ?? command.Command ?? "", + "", + nameof(CultMeshLocalityKind.Automatic), + command.Transport ?? "debug-log").ToBinding())) + .ToArray()); + } + + private static EveSurfaceComponent ToComponent(FileSurfaceComponent component) + { + return new EveSurfaceComponent( + component.Id ?? "", + component.Kind ?? "", + ToProps(component.Props), + (component.Children ?? Array.Empty()) + .Select(ToComponent) + .ToArray()); + } + + private static Dictionary ToProps(IReadOnlyList? props) + { + var result = new Dictionary(StringComparer.Ordinal); + if (props == null) + return result; + + foreach (var prop in props) + { + var key = prop.Key; + if (!string.IsNullOrWhiteSpace(key)) + result[key!] = prop.Value ?? ""; + } + + return result; + } + +#pragma warning disable 0649 + [DataContract] + private sealed class FileSurfaceDocument + { + [DataMember(Name = "schema")] + public string? Schema; + + [DataMember(Name = "providerId")] + public string? ProviderId; + + [DataMember(Name = "providerKind")] + public string? ProviderKind; + + [DataMember(Name = "title")] + public string? Title; + + [DataMember(Name = "version")] + public long Version; + + [DataMember(Name = "updatedAtUtc")] + public string? UpdatedAtUtc; + + [DataMember(Name = "surface")] + public FileSurfaceTree? Surface; + + [DataMember(Name = "commands")] + public FileCommand[]? Commands; + } + + [DataContract] + private sealed class FileSurfaceTree + { + [DataMember(Name = "id")] + public string? Id; + + [DataMember(Name = "root")] + public FileSurfaceComponent? Root; + + [DataMember(Name = "styles")] + public FileStyleToken[]? Styles; + } + + [DataContract] + private sealed class FileSurfaceComponent + { + [DataMember(Name = "id")] + public string? Id; + + [DataMember(Name = "kind")] + public string? Kind; + + [DataMember(Name = "props")] + public FileProp[]? Props; + + [DataMember(Name = "children")] + public FileSurfaceComponent[]? Children; + } + + [DataContract] + private sealed class FileProp + { + [DataMember(Name = "key")] + public string? Key; + + [DataMember(Name = "value")] + public string? Value; + } + + [DataContract] + private sealed class FileStyleToken + { + [DataMember(Name = "name")] + public string? Name; + + [DataMember(Name = "value")] + public string? Value; + } + + [DataContract] + private sealed class FileCommand + { + [DataMember(Name = "command")] + public string? Command; + + [DataMember(Name = "label")] + public string? Label; + + [DataMember(Name = "transport")] + public string? Transport; + } +#pragma warning restore 0649 + } +} diff --git a/Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveFileSurfacePresenter.cs.meta b/Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveFileSurfacePresenter.cs.meta new file mode 100644 index 000000000..e66302e9a --- /dev/null +++ b/Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveFileSurfacePresenter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 55fd8c7b47c94f2c9407eb5d59d8e17f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveRuntimeBootstrap.cs b/Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveRuntimeBootstrap.cs index 1a933680b..ed9203bc0 100644 --- a/Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveRuntimeBootstrap.cs +++ b/Packages/org.gamecult.aetheria.eve-runtime/Runtime/AetheriaEveRuntimeBootstrap.cs @@ -13,20 +13,33 @@ namespace GameCult.Aetheria.EveRuntime public const string DefaultSurfaceId = AetheriaRuntimeDaemonGameSurfaceBuilder.SurfaceId; public const string DisableEnvironmentVariable = "AETHERIA_DISABLE_EVE_RUNTIME_BOOTSTRAP"; public const string SurfaceEnvironmentVariable = "AETHERIA_EVE_SURFACE_ID"; + public const string FileSurfaceEnvironmentVariable = "AETHERIA_EVE_FILE_SURFACE_PATH"; public const string DisableCommandLineSwitch = "--aetheria-disable-eve-runtime-bootstrap"; [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] private static void MountDefaultSurface() { - if (IsDisabled() || UnityEngine.Object.FindObjectOfType() != null) + if (IsDisabled() || + UnityEngine.Object.FindAnyObjectByType() != null || + UnityEngine.Object.FindAnyObjectByType() != null) + { return; + } var host = new GameObject("Aetheria Eve Runtime Surface"); UnityEngine.Object.DontDestroyOnLoad(host); host.AddComponent(); - var presenter = host.AddComponent(); - presenter.SurfaceId = SurfaceId(); + var fileSurfacePath = FileSurfacePath(); + if (!string.IsNullOrWhiteSpace(fileSurfacePath)) + { + var presenter = host.AddComponent(); + presenter.SurfaceFilePath = fileSurfacePath; + return; + } + + var statePresenter = host.AddComponent(); + statePresenter.SurfaceId = SurfaceId(); } private static bool IsDisabled() @@ -50,5 +63,11 @@ namespace GameCult.Aetheria.EveRuntime var configured = Environment.GetEnvironmentVariable(SurfaceEnvironmentVariable); return string.IsNullOrWhiteSpace(configured) ? DefaultSurfaceId : configured; } + + private static string FileSurfacePath() + { + var configured = Environment.GetEnvironmentVariable(FileSurfaceEnvironmentVariable); + return string.IsNullOrWhiteSpace(configured) ? "" : configured; + } } } diff --git a/docs/aetheria-perfect-machine-map.md b/docs/aetheria-perfect-machine-map.md index c87853ac2..339f2c185 100644 --- a/docs/aetheria-perfect-machine-map.md +++ b/docs/aetheria-perfect-machine-map.md @@ -1480,6 +1480,12 @@ First Aetheria surfaces to publish: memory, lowers it through the shared Eve UI Toolkit path, and emits provider-builder code for menu work; it does not publish state, accept commands, or become a menu authority. + - Done: add a shared file-owned debug CultUI surface at + `GameData/cultui-debug-surface.cultui`. Unity can mount it through + `AETHERIA_EVE_FILE_SURFACE_PATH` / `AetheriaEveFileSurfacePresenter`; + Electron reads and watches the same file through IPC and lowers it in the + RTS side panel. The file owns only debug composition; daemon/provider + surfaces and command acceptance remain separate authorities. - Done: publish renderer-emitted Eve commands as typed `gamecult.eve.command.v1` records, separate from runtime state commits so only the daemon-owned provider bridge accepts commands it owns.