supervisor-simulator/specs/numerical_design_system.md
2026-01-17 20:59:45 +08:00

173 lines
7.6 KiB
Markdown

# Numerical Design & Balancing System (NDBS) - Implementation Guide
**Version:** 2.0
**Target Stack:** Python 3.14 (FastAPI, uv), Vue.js (Vite), C# (Godot .NET)
**Role:** AI Developer Guide
## 1. System Overview
The NDBS is a local web application enabling game designers to:
1. **Edit Game Data:** Modify JSON files in `resources/definitions/` (Traits, Archetypes, Items) via a GUI.
2. **Script Logic:** Write C# code for `RuleIds` (special game logic) in a browser-based IDE. The system auto-generates the corresponding `.cs` files in `scripts/Rules/Generated/`.
This guide is structured as a sequence of tasks for an AI agent to implement the system incrementally.
---
## 2. Architecture
The system is designed as a **Unified Web Service**. A single Python process handles both the API logic and serving the frontend interface.
1. **NDBS Service (Python/FastAPI):**
* **API Layer:** Handles data reading/writing and script generation (`/api/*`).
* **Static Layer:** Serves the compiled Vue.js application (`index.html`, `js/`, `css/`) from the `client/dist` directory.
2. **NDBS Web Client (Vue.js):**
* Developed as a standard SPA.
* Built into static files (`npm run build`) which are consumed by the Python service.
**Runtime Flow:**
User runs `python main.py` -> Browser opens `http://localhost:8000` -> Frontend loads -> Frontend calls `/api/...` -> Python modifies files.
```mermaid
graph TD
User[Designer] -->|Browser| Service[NDBS Python Service]
Service -->|Serve Static| Frontend[Vue.js UI]
Service -->|API| Logic[Business Logic]
Logic -->|Read/Write| JSON[JSON/TRES Definitions]
Logic -->|Generate| CSharp[C# Rule Scripts]
```
---
## 3. Implementation Phases
### Phase 1: Python Backend Foundation
**Goal:** Establish a FastAPI server that can read/write the game's JSON files.
**Step 1.1: Environment Setup**
* **Instruction:** Create `tools/ndbs/server/`. Initialize a Python environment using `uv`.
* Run `uv init --python 3.14` to set up the project.
* Run `uv add fastapi uvicorn pydantic` to install dependencies.
* **Code Requirement:** Create `tools/ndbs/server/main.py`.
* **Key Functionality:**
* Enable CORS (allow all origins for dev).
* Define a constant `PROJECT_ROOT` pointing to `../../../../`.
**Step 1.2: File System API**
* **Instruction:** Implement endpoints to list and read definitions.
* **Endpoints:**
* `GET /api/files/definitions`: Scans `resources/definitions/` and returns a list of `.json` AND `.tres` files.
* `GET /api/files/content`: Takes a `filename` query param.
* If `.json`: Returns parsed JSON.
* If `.tres`: Parses the `[resource]` section key-value pairs into a JSON object. Handles arrays (e.g., `Tags = [ "a", "b" ]`) and strings.
* `POST /api/files/content`: Takes `filename` and `content` (JSON body).
* If `.json`: Writes standard JSON.
* If `.tres`: Reads the original file, replaces the values in the `[resource]` section with new values from the JSON, and saves preserving the header/metadata.
**Step 1.3: Schema Inference (Dynamic Models)**
* **Instruction:** Since we don't have hardcoded Pydantic models for every file, create a utility that reads a file (JSON or TRES) and generates a generic "Schema" description (listing keys and value types) to help the frontend build forms dynamically.
**Step 1.4: Static Asset Serving (SPA Support)**
* **Instruction:** Configure FastAPI to serve the frontend.
* Mount the `client/dist` directory to `/` as static files.
* **Critical:** Implement a "Catch-All" route (after API routes) that returns `client/dist/index.html`. This ensures that Vue Router paths (e.g., `http://localhost:8000/editor/archetypes`) work when refreshed.
---
### Phase 2: Vue.js Frontend Foundation
**Goal:** A clean UI to browse files and edit JSON data.
**Step 2.1: Project Scaffolding**
* **Instruction:** Create `tools/ndbs/client` using Vite + Vue 3 (TypeScript). Install `axios`, `pinia`, and `naive-ui`.
**Step 2.2: File Explorer & Layout**
* **Instruction:** Create a standard "Sidebar + Main Content" layout.
* **Sidebar:** Fetches the list of files from `GET /api/files/definitions` and displays them as a menu.
* **Main Content:** A RouterView to show the editor.
**Step 2.3: Generic JSON Editor**
* **Instruction:** Create a component `JsonEditor.vue`.
* Fetch content using `GET /api/files/content`.
* Display the raw JSON in a textarea (Monaco Editor preferred later).
* Add a "Save" button that calls `POST /api/files/content`.
**Step 2.4: Build Integration**
* **Instruction:** Configure `vite.config.ts` to output to `../server/client_dist` (or just `dist` inside client, and server reads from there).
* Ensure the "Build" command produces the artifacts expected by Step 1.4.
---
### Phase 3: C# Rule Engine Integration (Godot Side)
**Goal:** Prepare the game code to dynamically load the scripts we will generate later.
**Step 3.1: Define the Interface**
* **Instruction:** Create `scripts/Core/Interfaces/IGameRule.cs`.
```csharp
namespace Core.Interfaces;
using Models;
public interface IGameRule {
string Id { get; }
// Example hooks - adjust based on GameSystems.cs analysis
void OnEvent(GameSession session, object gameEvent);
void ModifyStats(UnitModel unit, StatRequest request);
}
```
**Step 3.2: Rule Manager (The Loader)**
* **Instruction:** Create `scripts/Core/Systems/RuleManager.cs`.
* Use **Reflection** to find all classes implementing `IGameRule`.
* Store them in a `Dictionary<string, IGameRule>`.
* Provide a method `ExecuteRule(string ruleId, ...)` that looks up the rule and calls its methods.
**Step 3.3: Hook into Game Systems**
* **Instruction:** Modify `scripts/Core/GameSystems.cs` (specifically `SynergySystem` or `TaskSystem`).
* Find where `RuleIds` are iterated.
* Inject a call to `RuleManager.Instance.ExecuteRule(ruleId, ...)` inside those loops.
---
### Phase 4: Scriptable Rule Editor (Full Stack)
**Goal:** Allow creating new C# rules from the web UI.
**Step 4.1: Backend - Template Generator**
* **Instruction:** Add endpoint `POST /api/rules/create`.
* **Params:** `rule_id` (e.g., "grinder_stress_effect").
* **Action:**
1. Validate naming (alphanumeric).
2. Load a C# template string (Class name = `Rule_{CamelCaseId}`).
3. Write file to `scripts/Rules/Generated/Rule_{CamelCaseId}.cs`.
4. Return success.
**Step 4.2: Frontend - C# Editor**
* **Instruction:** Add a "Rules" section to the sidebar.
* List `.cs` files in `scripts/Rules/Generated/` (add backend endpoint for this).
* Integrate **Monaco Editor** (Vue wrapper) for syntax highlighting.
* Save button writes the C# content back to disk.
**Step 4.3: Compilation Trigger (Optional but Recommended)**
* **Instruction:** Add a "Verify" button.
* Backend endpoint `POST /api/build`.
* Runs `dotnet build` shell command.
* Returns stdout/stderr to the frontend console.
---
## 4. Technical Constraints & Conventions
### 4.1 File Paths
* **Server Root:** `tools/ndbs/server`
* **Game Root:** `../../` (Relative to server)
### 4.2 Coding Style
* **Python:** Type hints (Python 3.14), Pydantic models for request/response bodies. Use `uv` for dependency management.
* **Vue:** Composition API (`<script setup lang="ts">`), Scoped CSS.
* **C#:** Namespace `Rules.Generated` for all generated scripts.
### 4.3 Safety
* **No Overwrite:** When creating a new rule, fail if the file already exists.
* **Backup:** (Bonus) Before saving a JSON file, copy the old version to `tools/ndbs/backups/`.