diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..0032683a43a77b0ef1eb307413afcf044514de2b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,14 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +assets/snapkitty/art/civilization.jpg filter=lfs diff=lfs merge=lfs -text +assets/snapkitty/art/kitten.jpg filter=lfs diff=lfs merge=lfs -text +assets/snapkitty/art/kitten.png filter=lfs diff=lfs merge=lfs -text +assets/snapkitty/art/snap-os.jpg filter=lfs diff=lfs merge=lfs -text +assets/snapkitty/art/suited-man.jpg filter=lfs diff=lfs merge=lfs -text +assets/snapkitty/art/suited-man.png filter=lfs diff=lfs merge=lfs -text +assets/snapkitty/web/preview_composite.png filter=lfs diff=lfs merge=lfs -text +unify/game/assets/textures/snapkitty/civilization.qoi filter=lfs diff=lfs merge=lfs -text +unify/game/assets/textures/snapkitty/kitten.qoi filter=lfs diff=lfs merge=lfs -text +unify/game/assets/textures/snapkitty/snap-os.qoi filter=lfs diff=lfs merge=lfs -text +unify/game/assets/textures/snapkitty/suited-man.qoi filter=lfs diff=lfs merge=lfs -text diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..97b800fc6314e8d4849e858791fd524d0443e274 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,93 @@ +name: Repoverse core + +on: + push: + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: '8.0.x' + - run: dotnet build -warnaserror + - run: dotnet test --no-build + - name: Exercise the authenticated world sidecar + run: python3 tools/test-sidecar.py + - uses: actions/checkout@v4 + with: + repository: SNAPKITTYWEST/BOBS-Many-Voxel-Worlds + path: sample + fetch-depth: 0 # local ingest reads commit history + - name: Generate a world from the sample monorepo + run: | + dotnet run --project src/Repoverse.Cli --no-build -- ingest-local sample --owner SNAPKITTYWEST --subprojects --out out/snapshot.json + dotnet run --project src/Repoverse.Cli --no-build -- generate --snapshot out/snapshot.json --out out/manifest.json + dotnet run --project src/Repoverse.Cli --no-build -- stats --manifest out/manifest.json + + unified-engine: + runs-on: ubuntu-latest + defaults: + run: + working-directory: unified-engine + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + - run: npm ci + - run: npm test + + unify: + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: unify + steps: + - uses: actions/checkout@v4 + - run: sudo apt-get update && sudo apt-get install -y ninja-build libsdl2-dev + - run: cmake -S . -B build -G Ninja + - run: cmake --build build + - run: ctest --test-dir build --output-on-failure + - name: SDL backend smoke run + run: SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy ./build/unify_game --frames 240 --screenshot title.png + - uses: actions/upload-artifact@v4 + with: + name: unify-playtest-screenshots + path: | + unify/build/*.png + unify/build/snapkitty-evidence/*.png + + unify-sanitizers: + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: unify + steps: + - uses: actions/checkout@v4 + - run: sudo apt-get update && sudo apt-get install -y ninja-build + - run: > + cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug + -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer" + -DCMAKE_C_FLAGS="-fsanitize=address,undefined" + -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" + - run: cmake --build build + - run: ctest --test-dir build --output-on-failure + env: + UBSAN_OPTIONS: halt_on_error=1:print_stacktrace=1 + + unify-windows-mingw: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - name: Build and test SDL game + shell: pwsh + run: ./tools/Build-Snapkitty.ps1 + - name: Package playable game + run: python tools/package-snapkitty.py + - uses: actions/upload-artifact@v4 + with: + name: Snapkitty-Windows + path: out/Snapkitty-Windows.zip diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..05c7989ca6c32741f929f875e5aed65fe7adf2bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +bin/ +obj/ +*.user +.vs/ +TestResults/ + +# Generated by the CLI (§66): regenerate, never hand-edit. +out/ +preview/world-mesh.json + +# unified-engine (Node) +node_modules/ + +# Unreal generated host artifacts +unreal/Repoverse/Plugins/ +unreal/Repoverse/Unify/ +unreal/Repoverse/Binaries/ +unreal/Repoverse/Intermediate/ +unreal/Repoverse/Saved/ +unreal/Repoverse/DerivedDataCache/ +unreal/Repoverse/Content/ diff --git a/HANDOFF.md b/HANDOFF.md new file mode 100644 index 0000000000000000000000000000000000000000..3babb65bc56cdb8825980cfff6bc9741ef64dedf --- /dev/null +++ b/HANDOFF.md @@ -0,0 +1,212 @@ +# Repoverse handoff + +**From:** the cloud session that built the C# core (Master Directive, Part I) +**To:** whoever builds the engine side and the back end locally (Rider, Unreal, Swift, CAD) +**State at handoff:** `dotnet build -warnaserror` is clean and all 72 tests pass. The pipeline has run end to end on real +data (the 15 sub-projects of `SNAPKITTYWEST/BOBS-Many-Voxel-Worlds`). Nothing has run inside Unreal, Swift or CAD +tooling yet. The Parts II and III directive text has not been received. + +--- + +## 1. What exists + +Read `README.md` for the full table. In one line: **GitHub or local git → `CanonicalRepository` → classifier → +deterministic `WorldManifest` → procedural chunks (32³, 16-bit voxels) → greedy-meshed quads**, plus snapshot +diff events, a fixed-step clock, versioned saves and `repoverse://` URIs. + +| Path | Responsibility | +|---|---| +| `src/Repoverse.Core/Model/` | Canonical GitHub facts; `Derived` + `Provenance` for everything inferred | +| `src/Repoverse.Core/Ingestion/` | `GitHubIngest` (REST, ETag cache, rate limits), `LocalGitIngest`, `SnapshotStore` (offline merge) | +| `src/Repoverse.Core/Generation/` | `Seed`, `Classifier`, `Overrides`, `RoomGraph`, `ManifestBuilder`, `WorldManifest` | +| `src/Repoverse.Core/Voxels/` | `Voxel`/`Chunk`, `BuildingRasterizer`, `WorldGenerator`, `WorldEdits`, `ChunkStreamer`, `GreedyMesher` | +| `src/Repoverse.Core/Simulation/` | `WorldEvents` + `SnapshotDiff`, `SimulationClock` | +| `src/Repoverse.Core/Persistence/` | `SaveGame` (schema 2, v1 migration) | +| `src/Repoverse.Core/WorldConstants.cs` | Every tunable dimension; change numbers here only | +| `src/Repoverse.Cli/` | `ingest-local`, `ingest-github`, `generate`, `stats`, `export-mesh`, `diff` | +| `preview/index.html` | Three.js viewer for `export-mesh` output. A debugging aid, not the game | +| `tests/` | 72 behaviour tests; run `dotnet test` before and after every change to the core | + +--- + +## 2. Contracts the back end must honour + +The **C# types are the source of truth**. The JSON below is what they serialise to (`Json.Options`: camelCase, +enums as camelCase strings, nulls omitted). If you need a field, add it in C# and bump the schema version. +Don't patch the JSON. + +### 2.1 World manifest (`generate` → `manifest.json`, schema 1) + +```jsonc +{ + "schemaVersion": 1, "generator": "repoverse-gen/1", "worldSeed": "000000005aa4c177", + "snapshots": { "snapkittywest/guppy": "git:" }, // repo key → snapshot id it was built from + "buildings": [{ + "repo": "SNAPKITTYWEST/guppy", // display form; identity is the lower-cased key + "category": { "value": "compiler", "why": { "rule": "classifier:rules", "evidence": "mentions-compiler (score 5)" } }, + "district": { "value": "kernel", "why": { ... } }, + "archetype": { "value": "foundry", "why": { ... } }, + "material": "metal", + "plot": { "district": "kernel", "slot": 0 }, // sticky across regenerations (pass --previous) + "footprint": { "x": 257, "z": 254, "width": 14, "depth": 19 }, // voxel units, ground plane + "floors": 1, "roomsPerSide": 2, "roomDepth": 6, "height": 7, + "activity": { "value": "low", "why": { ... } }, // dormant | low | moderate | high + "construction": { "value": "unreleased", "why": { ... } }, // unreleased | prerelease | released | archived + "landmark": false, "population": 1, "seed": "d17a3db530f2e546", + "interior": { + "rooms": [{ "id": 3, "name": "examples", "purpose": "workshop", "floor": 0, "directories": ["examples"], + "fileCount": 3, "artifacts": [{ "path": "examples/grover_2qubit.py", "kind": "sourceTerminal", + "sizeBytes": 4083, "language": "Python" }] }], + "doors": [{ "a": 0, "b": 1 }] + } + }], + "dependencies": [{ "from": "owner/a", "to": "owner/b" }] +} +``` + +**Rule:** Unreal actors are built *from* this and never written back into it (§5). The same snapshot, seed and +previous manifest must always produce byte-identical JSON; `GenerationTests` enforces this. + +### 2.2 Voxels and chunks + +- `Voxel` is a `ushort`: bits 0–7 `BlockType`, bits 8–11 `MaterialFamily`, bits 12–15 state (activity level for + walls, floors and roofs). `MeshKey = packed & 0x0FFF`, and one material/draw group per key. +- A chunk is 32×32×32, indexed as `(y * 32 + z) * 32 + x`. Chunk Y layers run from 0 to `WorldGenerator.MaxChunkY` + (currently 2). +- World units are **1 voxel = 1 unit**. Pick one Unreal scale and put it in one place. Suggested: 1 voxel = 50 cm, + a 6-voxel storey = 3 m. +- Axes: **Y is up** in the core. Unreal is Z-up, so map core (x, y, z) → UE (x, z, y) and flip winding, or + mirror one axis. Do it in exactly one conversion function. +- `GreedyMesher.Build(chunk, neighbourSampler)` → `Quad(axis, positive, layer, u, v, width, height, meshKey)`. + `GreedyMesher.Corners()` returns counter-clockwise world-space corners (core handedness). Pass a + neighbour sampler, or chunk-border faces will not be culled. +- Interactive things are **not voxels**. `BuildingRasterizer.Objects(building)` yields `WorldObject` + (id, repo, x, y, z, kind, sourcePath, roomId, actions). Spawn these as actors or instances. +- `BuildingRasterizer.Plan(building)` gives each room's voxel rectangle and floor Y. Use it for cutaway, + floor isolation and room highlighting. + +### 2.3 Other formats + +| Format | Where | Notes | +|---|---|---| +| Snapshot | `Ingestion/SnapshotStore.cs` | schema 1; last-known-good; written atomically | +| Save | `Persistence/SaveGame.cs` | schema 2; player + edits + tick only; add migrations to `Migrations` | +| Events | `Simulation/WorldEvents.cs` | typed records; `SnapshotDiff.Diff(before, after)` produces them | +| URI | `RepoverseUri.cs` | `repoverse://owner/repo/path#L12`, `?room=N`, `@x,y,z` | +| Mesh export | `Cli/Program.cs` `export-mesh` | **debug format only**: enum names here are PascalCase, unlike the manifest. Don't build the engine on it; use §3.1 | + +--- + +## 3. What to build next, in order + +Order follows the directive's vertical-slice rule (§55–57): get one district walkable end to end before scaling. + +### P0: finish the Part I vertical slice + +**3.1 C# ↔ Unreal bridge (decide first; everything else depends on it)** +The core is .NET 8 and Unreal is C++. The options, in my recommended order: + +1. **Sidecar process (recommended to start).** Run the core as a local server. An Unreal C++ plugin talks to it + over a named pipe or localhost TCP with length-prefixed binary messages. It's the easiest to debug + (both sides test alone), the core stays engine-free, and the repo already uses this pattern + (`voxel/server/QuantumVoxelServer.cs` in BOBS-Many-Voxel-Worlds). Minimum messages: `LoadManifest`, + `SetFocus(x,z)` → stream `ChunkMesh`/`ChunkUnloaded`, `GetObjects(buildingKey)`, `ApplyEdit`, `Save`/`Load`, + `Events` (push). +2. **Embed .NET in Unreal via `hostfxr`.** In-process with no IPC cost, but you own the hosting and threading. +3. **UnrealSharp or a similar plugin.** Quickest to write gameplay in C#, but it's a third-party dependency on + your engine version. + +*Done when:* Unreal shows the chunks around a focus point, updates as the focus moves, and memory stays flat +while travelling (mirror `VoxelTests.Streaming_memory_is_bounded_by_radius_while_travelling`). + +**3.2 Unreal chunk rendering (C++)** +- Build one mesh section per `MeshKey` from `Quad`s. Use `RealtimeMeshComponent` or + `UProceduralMeshComponent`, and do not spawn one actor per voxel (§14). +- Collision comes from the same quads (complex-as-simple is fine to start). +- Map `MaterialFamily` × `BlockType` to material instances. Windows are translucent. +- *Done when:* the 15-building district renders at target frame rate, and `stat unit` and draw calls are logged + (§44). + +**3.3 Player, interaction, camera modes** +- First/third-person walk with collision. Enter through the east-wall door (`Plan().Entrance`) and climb the + ladder shaft between floors. +- Interaction comes from `WorldObject.Actions` (the object advertises its verbs; the player code doesn't + hard-code them, §52). +- Camera modes World, Architectural Orbit (roof hide via `BlockType.Roof`, floor isolation via + `Plan().Rooms[].FloorY`), Code and City Overview. Selection is one `repoverse://` URI shared by all modes (§73). +- *Done when:* you can walk the whole §57 success path: enter building → pick room → pick file → Code + Mode → back outside → travel → quit → reload → same state. + +**3.4 Source inspection** +- Fetch file contents on demand: from the GitHub contents API, via `GitHubIngest`'s cache pattern, or from a + local clone. Page large files (§38). Nothing is fetched at manifest time. + +**3.5 Save/load wiring** +- On quit, `SaveGame.Capture(manifest, player, edits, clock.Tick)`; on boot, `Read` then `RestoreEdits`. Player + position and mode must come back exactly. + +**3.6 Dependency extraction** (core, C#) +- Fill `CanonicalRepository.DependsOn` by parsing `Cargo.toml`, `package.json`, `*.csproj`, `go.mod`, + `pyproject.toml`/`requirements.txt` and `.gitmodules`, matched against repos in the world. Edges then flow + into the manifest automatically, with a test for each format. + +### P1: control plane and navigation + +- **Swift control plane (§33–34).** An `AppState` holding selection, camera, overlays, simulation state and + graph filters, bridged to the engine. It controls intent only and must never copy world data. Every toggle + in §34 must change real filter state (add a test per toggle). +- **CSS design tokens (§35).** Spacing, radii, blur, type scale, status colours, focus, hover, selected, + disabled and stale states. Pair each colour with a shape or icon (§70). Use it for any HTML/UMG-web overlays. +- **Graph Mode (§21).** Draw `dependencies` edges between buildings, filterable by category and depth. +- **Search, command palette, world map, bookmarks, fast travel (§48–50, §74–75).** The data is already there: + manifest buildings plus artifacts plus `RepoverseUri`. +- **Live sync loop.** Periodic `ingest-github`, then `SnapshotDiff`, then events drive visuals (§26, §92): + release → illumination, archived → archive state, new files → rebuild that building's chunks only. + +### P2: later + +- CAD import pipeline, offline only (§24): DWG/DXF/IFC → cleaned mesh + metadata → packaged asset, + referenced from `Overrides` (`landmark`, custom archetype). +- Audio, accessibility pass, and diagnostics overlay (§61, §69–70). +- Parts II and III (agents, simulation, 388-repo scale, packaging), once the directive text is available. + +--- + +## 4. Known gaps in the core (fix before scaling to 388 repos) + +| Gap | Where | Impact | +|---|---|---| +| **District overflow throws.** Each district holds 144 plots, and a 145th repo in one district fails the whole build | `ManifestBuilder.Build` | Likely to hit at 388 repos if the classifier skews. Needs §85 expansion (a new ring or an overflow district) | +| `DependsOn` never populated | ingesters | Graph Mode has no data (see 3.6) | +| Contributors capped at 100 (1 page); recent commits capped at 300 (3 pages) | `GitHubIngest` | Fine for activity levels; wrong as absolute counts | +| `.v` counts as both Coq and Verilog | `Classifier` | Ties break by enum order; provenance shows it. Use overrides | +| One floor plan (a corridor spine) for every archetype | `BuildingRasterizer` | Buildings read alike; archetype shells are future work | +| Headers are added on every `GitHubIngest` construction | `GitHubIngest` ctor | Duplicate headers if one `HttpClient` is reused. Give each ingest its own client, or move the headers onto the request | +| Local ingest treats git tags as releases, whole-repo only | `LocalGitIngest` | Sub-project buildings always show `unreleased` (scaffolding) | +| Classifier is keyword rules | `Classifier` | Fine for a slice. An AI classifier must follow §82 (cached, versioned, overridable, never blocking) | + +--- + +## 5. Setup + +```bash +# .NET 8 SDK + git +dotnet build -warnaserror && dotnet test +dotnet run --project src/Repoverse.Cli -- ingest-local --owner SNAPKITTYWEST --subprojects --out out/snapshot.json +dotnet run --project src/Repoverse.Cli -- generate --snapshot out/snapshot.json --out out/manifest.json +dotnet run --project src/Repoverse.Cli -- stats --manifest out/manifest.json +GITHUB_TOKEN= dotnet run --project src/Repoverse.Cli -- ingest-github SNAPKITTYWEST --out out/snapshot.json +``` + +Keep the token in the environment or the OS keychain, never in files (§41). `GitHubIngest.Redact` scrubs +tokens from error text. + +## 6. Decisions you need to make + +1. **Bridge:** sidecar, hostfxr or UnrealSharp (3.1). I recommend the sidecar. +2. **Unreal version and mesh component:** RealtimeMesh plugin or built-in ProceduralMesh. +3. **Voxel scale in Unreal:** 50 cm is suggested. +4. **Swift's target platform:** macOS only, or an iPad companion over the network. This decides whether Swift + talks to the engine in-process or over the same sidecar protocol. +5. **Scope of the first live ingest:** all 349 public repos plus private ones, or a curated list via + `ingest-github --limit` / overrides. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..baef65a2521df7f40c3fa685c0c739ab1afa7e12 --- /dev/null +++ b/README.md @@ -0,0 +1,17 @@ +--- +tags: +- snapkitty +- october-2026-drop +- csharp +- c++ +- c +- lua +- javascript +- voxel +- game +- visualization +- community +--- + +> Mirrored from [https://github.com/SNAPKITTYWEST/repoverse](https://github.com/SNAPKITTYWEST/repoverse) at commit `90d5c60`. Part of the **SnapKitty October 2026 main drop**. + diff --git a/Repoverse.sln b/Repoverse.sln new file mode 100644 index 0000000000000000000000000000000000000000..8493fc7db97c46a78f9880b58d8130ca5d5f0ebc --- /dev/null +++ b/Repoverse.sln @@ -0,0 +1,50 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{196A873E-0AA4-4B28-B58D-D2936643B90D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repoverse.Core", "src\Repoverse.Core\Repoverse.Core.csproj", "{FB897333-4192-456C-A1EA-B3B741592B1F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repoverse.Cli", "src\Repoverse.Cli\Repoverse.Cli.csproj", "{A7AECCC2-1FB7-4326-8410-A4673DAAC665}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{5F82D87A-4CE3-468B-9DFD-AC07CB8E0F7F}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repoverse.Core.Tests", "tests\Repoverse.Core.Tests\Repoverse.Core.Tests.csproj", "{72CB5AFA-688D-4237-A5D7-40BC49B555B0}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Repoverse.Sidecar", "src\Repoverse.Sidecar\Repoverse.Sidecar.csproj", "{0AB89BF5-CB58-4F06-9753-77D84414244B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FB897333-4192-456C-A1EA-B3B741592B1F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FB897333-4192-456C-A1EA-B3B741592B1F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FB897333-4192-456C-A1EA-B3B741592B1F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FB897333-4192-456C-A1EA-B3B741592B1F}.Release|Any CPU.Build.0 = Release|Any CPU + {A7AECCC2-1FB7-4326-8410-A4673DAAC665}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A7AECCC2-1FB7-4326-8410-A4673DAAC665}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A7AECCC2-1FB7-4326-8410-A4673DAAC665}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A7AECCC2-1FB7-4326-8410-A4673DAAC665}.Release|Any CPU.Build.0 = Release|Any CPU + {72CB5AFA-688D-4237-A5D7-40BC49B555B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {72CB5AFA-688D-4237-A5D7-40BC49B555B0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {72CB5AFA-688D-4237-A5D7-40BC49B555B0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {72CB5AFA-688D-4237-A5D7-40BC49B555B0}.Release|Any CPU.Build.0 = Release|Any CPU + {0AB89BF5-CB58-4F06-9753-77D84414244B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0AB89BF5-CB58-4F06-9753-77D84414244B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0AB89BF5-CB58-4F06-9753-77D84414244B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0AB89BF5-CB58-4F06-9753-77D84414244B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {FB897333-4192-456C-A1EA-B3B741592B1F} = {196A873E-0AA4-4B28-B58D-D2936643B90D} + {A7AECCC2-1FB7-4326-8410-A4673DAAC665} = {196A873E-0AA4-4B28-B58D-D2936643B90D} + {72CB5AFA-688D-4237-A5D7-40BC49B555B0} = {5F82D87A-4CE3-468B-9DFD-AC07CB8E0F7F} + {0AB89BF5-CB58-4F06-9753-77D84414244B} = {196A873E-0AA4-4B28-B58D-D2936643B90D} + EndGlobalSection +EndGlobal diff --git a/assets/snapkitty/LICENSE b/assets/snapkitty/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..be3f7b28e564e7dd05eaf59d64adba1a4065ac0e --- /dev/null +++ b/assets/snapkitty/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/assets/snapkitty/SOURCE_README.md b/assets/snapkitty/SOURCE_README.md new file mode 100644 index 0000000000000000000000000000000000000000..82da211c53edfee056550ee2ec0b816f40a6a851 --- /dev/null +++ b/assets/snapkitty/SOURCE_README.md @@ -0,0 +1,55 @@ +# SNAPKITTY: Bifrost Runner — 2D game + +**Play it live:** https://ahmadaliparr.github.io/snapkitty-2d/ + +Built from your four art pieces: the hoodie kitten (player), the suited +Architect (NPC), the SNAP-OS dashboard (HUD language), and the +Snapkitty civilization poster (world backdrop). + +## Play it now — `index.html` + +A playable 2D platformer prototype of the full game design. Open in any +browser, no build step. + +- **Move:** A/D or arrows · **Jump:** Space/W (coyote time included) +- **E:** talk to the Architect at checkpoints · **R:** restart after winning +- Seal all **8 Bifrost event cubes**, then reach the **Bifrost terminal** +- Gaps respawn you; HUD tracks sealed events + ledger integrity + +Verified: `node --check` clean, headless DOM-stubbed run of the full +game loop (boot, run, jump, all 8 pickups, NPC dialogue open/close, +win banner, reset) — all OK. Layout composited against the real art +and visually inspected. + +## Build it for real — `UnrealProject/` (C# / UnrealSharp) + +Unreal Engine 5.5+ project using **C# via UnrealSharp** + Paper2D: + +- `Snapkitty2D.uproject` — module `Snapkitty2D`, depends on + `Paper2D`, `EnhancedInput`, `UnrealSharpCore` +- `Source/Snapkitty2D/`: + - `SnapkittyPlayer.cs` — plane-locked 2D character controller, + run/jump, flipbook animation states (idle/run/jump) + - `ArchitectNPC.cs` — dialogue NPC, talk radius, briefing lines + - `BifrostPickup.cs` — bobbing/spinning collectible event cube + - `SnapkittyGameMode.cs` — sealed-event counter, win condition, + Blueprint events for UI/fanfare + - `SnapkittyHUD.cs` — SNAP-OS styled HUD bindings (event counter, + integrity bar, timed dialogue box) +- `Config/DefaultEngine.ini` — 2D-oriented defaults + +Open the `.uproject` in UE5, import `art/` as Paper2D sprites, subclass +the C# classes in Blueprints, build `L_BifrostRunner`. + +## Art — `art/` + +| file | role | +|---|---| +| `kitten.png` | player sprite (background-removed cutout) | +| `suited-man.png` | Architect NPC sprite (background-removed cutout) | +| `civilization.jpg` | parallax world backdrop | +| `snap-os.jpg` | HUD/title-screen reference | +| `*.jpg` originals | kept as fallback sources | + +(Cutouts produced with `rembg`; the web prototype auto-falls back to +the `.jpg` originals if a `.png` is missing.) diff --git a/assets/snapkitty/art/civilization.jpg b/assets/snapkitty/art/civilization.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d3a58de36afcbca25a46b46b3e84e8a221b3fc82 --- /dev/null +++ b/assets/snapkitty/art/civilization.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:560114843cdde8834771b08aaf5130190c215bcf56771420fda33b3a69055d0d +size 605588 diff --git a/assets/snapkitty/art/kitten.jpg b/assets/snapkitty/art/kitten.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b0b009546af3ba86114c345fbc0236ce0902b9eb --- /dev/null +++ b/assets/snapkitty/art/kitten.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49ca2191fda8c44aab8dc852a63bebe3af805deefdbba0f2cd45be7edc0907c5 +size 316701 diff --git a/assets/snapkitty/art/kitten.png b/assets/snapkitty/art/kitten.png new file mode 100644 index 0000000000000000000000000000000000000000..9b937da8ebd5325bdab9441344dbc873acd27d62 --- /dev/null +++ b/assets/snapkitty/art/kitten.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f52ec70ff5fbfd6c9fd09c9cdb39d3c263c5d4301b91a4ced483011ca1df45f3 +size 1016545 diff --git a/assets/snapkitty/art/snap-os.jpg b/assets/snapkitty/art/snap-os.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1529fcef1e22019e717865edd27fad85e9939175 --- /dev/null +++ b/assets/snapkitty/art/snap-os.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a37710ee48448b03a978f084996549c27eafdf820d46703621e7d84a4d57e4b2 +size 307687 diff --git a/assets/snapkitty/art/suited-man.jpg b/assets/snapkitty/art/suited-man.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ad0ee71e12a8feeb30c6ef6cd2523167ec5a0cf8 --- /dev/null +++ b/assets/snapkitty/art/suited-man.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b72a3df0b2aae60010d3f30ef8722d659c0282f3ffd1e6a4fddc0241889c5404 +size 347109 diff --git a/assets/snapkitty/art/suited-man.png b/assets/snapkitty/art/suited-man.png new file mode 100644 index 0000000000000000000000000000000000000000..1c54dae3ee633339d2a0c51c2f121bc3f34060d4 --- /dev/null +++ b/assets/snapkitty/art/suited-man.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dcadcf72892ec067a74e1655b009b70e5c8b5f3d9192f7aef5c7eccc038342b2 +size 979481 diff --git a/assets/snapkitty/runtime-manifest.json b/assets/snapkitty/runtime-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..36412bc15957e91a789b2314f5ac97b62b53e6a0 --- /dev/null +++ b/assets/snapkitty/runtime-manifest.json @@ -0,0 +1,34 @@ +[ + { + "source": "assets/snapkitty/art/kitten.png", + "runtime": "unify/game/assets/textures/snapkitty/kitten.qoi", + "sha256": "f52ec70ff5fbfd6c9fd09c9cdb39d3c263c5d4301b91a4ced483011ca1df45f3", + "qoiSha256": "994a3f728f87a01958a7cc9e777e3a9fe397f43dfc389ad9dcae256c6aa8ec51", + "width": 1320, + "height": 1320 + }, + { + "source": "assets/snapkitty/art/suited-man.png", + "runtime": "unify/game/assets/textures/snapkitty/suited-man.qoi", + "sha256": "dcadcf72892ec067a74e1655b009b70e5c8b5f3d9192f7aef5c7eccc038342b2", + "qoiSha256": "2052e2b6e328ad1507a6a90fd2137856a34f0fd5a755a0b479535bb7e653b0ff", + "width": 1320, + "height": 1320 + }, + { + "source": "assets/snapkitty/art/civilization.jpg", + "runtime": "unify/game/assets/textures/snapkitty/civilization.qoi", + "sha256": "560114843cdde8834771b08aaf5130190c215bcf56771420fda33b3a69055d0d", + "qoiSha256": "1b4464a6040bb3795084ae76d1819b118ea767649f32eb4116081fcc95650eb5", + "width": 1320, + "height": 880 + }, + { + "source": "assets/snapkitty/art/snap-os.jpg", + "runtime": "unify/game/assets/textures/snapkitty/snap-os.qoi", + "sha256": "a37710ee48448b03a978f084996549c27eafdf820d46703621e7d84a4d57e4b2", + "qoiSha256": "3c3b05598b2dbbd1ba0d8f2cd63fad22f1cd24ad3aeb83e53635bea68877c787", + "width": 1320, + "height": 880 + } +] diff --git a/assets/snapkitty/source-manifest.json b/assets/snapkitty/source-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..402d8b706d1280ee63c6058929f817d5388f6d01 --- /dev/null +++ b/assets/snapkitty/source-manifest.json @@ -0,0 +1,118 @@ +{ + "repository": "https://github.com/SNAPKITTYWEST/snapkitty-2d", + "commit": "2a9314984723affc01aafcd31c4d2a6858dd16ca", + "files": [ + { + "source": "art/civilization.jpg", + "path": "art/civilization.jpg", + "bytes": 605588, + "sha256": "560114843cdde8834771b08aaf5130190c215bcf56771420fda33b3a69055d0d", + "git_blob": "6e0069394259333ede3d0a7cb64ec04d8dc51d15", + "width": 1320, + "height": 880, + "mode": "RGB", + "transparent": false + }, + { + "source": "art/kitten.jpg", + "path": "art/kitten.jpg", + "bytes": 316701, + "sha256": "49ca2191fda8c44aab8dc852a63bebe3af805deefdbba0f2cd45be7edc0907c5", + "git_blob": "332282b974640cf96f599267adc4fbfc6521c9a8", + "width": 1320, + "height": 1320, + "mode": "RGB", + "transparent": false + }, + { + "source": "art/kitten.png", + "path": "art/kitten.png", + "bytes": 1016545, + "sha256": "f52ec70ff5fbfd6c9fd09c9cdb39d3c263c5d4301b91a4ced483011ca1df45f3", + "git_blob": "e8e764c4e059c8fa81ed78335396b8361d922e5a", + "width": 1320, + "height": 1320, + "mode": "RGBA", + "transparent": true + }, + { + "source": "art/snap-os.jpg", + "path": "art/snap-os.jpg", + "bytes": 307687, + "sha256": "a37710ee48448b03a978f084996549c27eafdf820d46703621e7d84a4d57e4b2", + "git_blob": "d0bc5717d7b9babcf65bffff2ad8813b191c6923", + "width": 1320, + "height": 880, + "mode": "RGB", + "transparent": false + }, + { + "source": "art/suited-man.jpg", + "path": "art/suited-man.jpg", + "bytes": 347109, + "sha256": "b72a3df0b2aae60010d3f30ef8722d659c0282f3ffd1e6a4fddc0241889c5404", + "git_blob": "6d31688381dc93bb533f35e0e60f9db7ba564d36", + "width": 1320, + "height": 1320, + "mode": "RGB", + "transparent": false + }, + { + "source": "art/suited-man.png", + "path": "art/suited-man.png", + "bytes": 979481, + "sha256": "dcadcf72892ec067a74e1655b009b70e5c8b5f3d9192f7aef5c7eccc038342b2", + "git_blob": "731074d01595784c6568c3418131eda3f0287380", + "width": 1320, + "height": 1320, + "mode": "RGBA", + "transparent": true + }, + { + "source": "web/preview_composite.png", + "path": "web/preview_composite.png", + "bytes": 708880, + "sha256": "f661f75012d47bc0a551f01a90cfd38d777bb605175ef531dfff013c7b459a67", + "git_blob": "202494492ad9bb81b311bdaf3e3489583493a157", + "width": 960, + "height": 540, + "mode": "RGB", + "transparent": false + }, + { + "source": "LICENSE", + "path": "reference/LICENSE", + "bytes": 34523, + "sha256": "0d96a4ff68ad6d4b6f1f30f713b18d5184912ba8dd389f86aa7710db079abcb0", + "git_blob": "be3f7b28e564e7dd05eaf59d64adba1a4065ac0e" + }, + { + "source": "README.md", + "path": "reference/README.md", + "bytes": 2296, + "sha256": "3ac8607a0398e15c310b17b57f0b13c548190e5d69af1992075ac9b20554ed30", + "git_blob": "82da211c53edfee056550ee2ec0b816f40a6a851" + }, + { + "source": "UnrealProject/README.md", + "path": "reference/UnrealProject/README.md", + "bytes": 1538, + "sha256": "ef8cfab3d0793bd2439deb5b96b208c5528043cdebfcf28cf9372897a846d52b", + "git_blob": "4aae26523f1b196e2e07cf93e331643ae2f53e81" + }, + { + "source": "UnrealProject/Source/Snapkitty2D/SnapkittyHUD.cs", + "path": "reference/UnrealProject/Source/Snapkitty2D/SnapkittyHUD.cs", + "bytes": 2487, + "sha256": "3c975334862a6b09a119e11a3a445d51acbb0fcb5c28a0b57ea222899261ed26", + "git_blob": "ba93d33510521fd217be03576f9fe2d33a455dd2" + }, + { + "source": "index.html", + "path": "reference/index.html", + "bytes": 13777, + "sha256": "373db3983f31f9379ae8224da526eab3f16fddf89168ba5229277c6a90a60bc4", + "git_blob": "efd4e254fdd11d06c0c63d8054e9dccda812af9c" + } + ] +} diff --git a/assets/snapkitty/web/preview_composite.png b/assets/snapkitty/web/preview_composite.png new file mode 100644 index 0000000000000000000000000000000000000000..b725688162f43dbda11d661488fe393e737a2fa2 --- /dev/null +++ b/assets/snapkitty/web/preview_composite.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f661f75012d47bc0a551f01a90cfd38d777bb605175ef531dfff013c7b459a67 +size 708880 diff --git a/docs/REPOVERSE-3D.md b/docs/REPOVERSE-3D.md new file mode 100644 index 0000000000000000000000000000000000000000..274f0dff24efcda58d1702d064a77fa658121c2d --- /dev/null +++ b/docs/REPOVERSE-3D.md @@ -0,0 +1,93 @@ +# Repoverse 3D district + +The C# world generator now has an authenticated, loopback-only HTTP sidecar and +an Unreal client in the existing Repoverse module. The original 2D GameMode +remains the default; the 3D launcher selects RepoverseWorldMode explicitly. + +## Build and run + +Requires .NET 8 SDK, Unreal Engine 5.4 or newer, and the matching Visual Studio +C++ toolchain. From the repository root in PowerShell: + + ./tools/Start-Repoverse3D.ps1 -EngineRoot 'D:/Epic/UE_5.6' + +Use your actual installation path. This example is not an installed-engine claim. +The script ingests this Git checkout, creates the authoritative manifest, builds +Unify and the Unreal host, starts a local sidecar with a fresh session token, +waits for its health endpoint, and launches the 3D GameMode. On editor exit it +stops only the sidecar process it started. Logs and the save are in out/world3d. +Use -SourceRoot to explore another local Git checkout, or -SkipBuild after a +successful build. The default launcher creates a world for one repository; +multiple buildings can be served from an existing multi-repository manifest. + +## Controls implemented in the Unreal client + +- WASD/arrows move, mouse looks, Space jumps, Shift runs. +- Near a ladder, hold Space to climb or Ctrl to descend. +- E inspects a nearby source terminal. PgUp/PgDn page source; Esc closes it. +- Tab/Shift+Tab travel between manifest repositories. +- 1 returns to walking, 2 orbits the selected destination, 3 opens its overview. +- F5 saves, F9 restores. Esc outside source view saves successfully before quitting. + +Movement waits for nearby terrain to load. Meshes and collision use the same +C# greedy quads. The coordinate conversion is centralized: one voxel is 50 cm, +core (x,y,z) becomes Unreal (x,z,y), and triangle winding reverses once. +Ladder mesh sections do not collide. Materials are generated by create-map.py; +no new artwork is required. Windows currently use an opaque blue material. + +## Service contract, version 1 + +All requests require X-Repoverse-Token. The service binds 127.0.0.1 only and +rejects Origin-bearing requests. A single renderer owns a service session; +requests execute serially. This is not a multiplayer server. + +| Route | Behavior | +| --- | --- | +| POST /v1/session | Reset renderer residency; return player, destinations and artifact objects | +| POST /v1/focus | Accept x/z in core units; return at most four chunk meshes plus unload IDs | +| POST /v1/save | Accept PlayerState; atomically save player and voxel edits | +| POST /v1/load | Restore matching world snapshot; invalidate resident meshes | +| POST /v1/edit | Apply a packed voxel edit and invalidate neighboring faces | +| GET /v1/source | Read 32 lines of a manifest artifact from the explicitly mapped local checkout | +| GET /v1/health | Report protocol version and resident chunk count | + +The stream radius is one chunk with one chunk of unload hysteresis. Source reads +are capped at 2 MiB, reject links/path traversal, and never execute repository +code. Local source contents reflect the current working copy, not a historical +Git blob. Other repositories require their own source mapping; remote source +fetching is not implemented. Save restoration rejects a different world seed, +generator, or snapshot. API edits are available; an in-game build tool is not. + +## Verification and remaining work + +The C# solution builds with warnings as errors. Unit tests cover bounded +residency, unload/reload, edit persistence, boundary remeshing, outward triangle +winding, passable ladders, source paging and source restrictions. Run: + + dotnet test Repoverse.sln + python tools/test-sidecar.py + +The second command runs a real sidecar process against a manifest generated +from this checkout, including auth, HTTP streaming, save/load and source reads. + +**The new Unreal client has not been compiled or played in Unreal.** An Unreal +installation was not found in this session. This is an integration awaiting +engine validation, not a finished or packaged 3D game. Required editor checks: +compile with UBT; walk into the building; collide with walls; climb all floors; +inspect a file; orbit; travel; save; quit; restart and restore; disconnect the +service; exit PIE. Measure frame time and mesh/collision upload costs. + +Remaining beyond this vertical slice: rendered dependency graph, architectural +roof/floor cutaways, remote source retrieval, multi-repository source mappings, +search/bookmarks, live synchronization, complete camera persistence, transparent +windows, CAD, Swift control plane, and the absent Parts II/III directive. + +## Twin-O-Matic builder + +Export a build from the matching Twin-O-Matic browser app, then pass its JSON path to the launcher with `-BuildPlan`. The launcher sends the plan to authenticated `POST /v1/build` before opening Unreal. This leaves browser-origin requests blocked. No generated script is executed. + +Version 1 plans carry `id`, `actor`, `units: "voxel"`, integer `origin` (Y-up), and `operations` with shape names and arguments. Boxes, spheres, cylinders, cones and XY-plane tori are supported. The entire plan is validated/rasterized before edits apply. Limits: 128 operations, 262144 candidate samples, 32768 resulting voxels, 16 builder identities per world. Smaller-than-voxel features may vanish; colors quantize to existing material families. Lights/particles are preview-only. Imported blocks can replace existing terrain, so select an empty construction area using the plan origin. + +The builder body follows its latest completed build position; this is a representation of accepted build commands, not an autonomous Unreal-hosted language model. F5 stores builder identity and edits; F9 and reconnect restore them. Existing schema-2 saves default to no builders. + +Verification: 88 C# tests, real local HTTP build/save/load/reconnect, and a build downloaded by the Twin browser test and submitted to this service. Unreal client changes still require compilation and a real playtest with an installed engine and the user's supplied assets. diff --git a/docs/SNAPKITTY-GAME.md b/docs/SNAPKITTY-GAME.md new file mode 100644 index 0000000000000000000000000000000000000000..161b88f8e00fbcb55b48dfe48925901fb113adc9 --- /dev/null +++ b/docs/SNAPKITTY-GAME.md @@ -0,0 +1,86 @@ +# Repoverse / SNAPKITTY game + +## Play the Windows build + +The native game opens the SNAPKITTY menu. Enter or Space starts Bifrost Runner. +A/D or arrows move, Space/W jumps, E talks near the Architect, F5 saves, F9 +restores the disk save (including after restarting), and Escape returns to the menu. +F9 on the title screen continues the saved game. I opens the about panel. R opens the +repository browser; Left/Right selects a repository and Escape returns. + +Build from the repository root with PowerShell: + + ./tools/Build-Snapkitty.ps1 -Play + +After building, run python tools/package-snapkitty.py to create +out/Snapkitty-Windows.zip. Extract it and double-click Play.cmd. +The package includes runtime assets, original artwork, notices and checksums. + +Requires CMake, MinGW GCC/G++, and network access for the first SDL2 download. +The script pins SDL 2.32.10 and verifies its SHA-256. The runtime has no network +dependency. Generated sprites and audio remain part of the existing Unify build. + +## What is shared + +The title, repository browser, gameplay, physics, WASM compute, saves and artwork +are shared Unify Lua/assets. The SDL backend provides a desktop window. Unreal +provides a Canvas renderer, input and audio through the existing Unify backend. +This is a native 2D game hosted inside Unreal, not a new browser simulation. + +The existing demo remains available with --scene title. The new default is +snapkitty, which opens snapkitty_level. The player uses the original kitten +cutout; motion uses the existing run/jump state machine and procedural squash, +not invented sprite-sheet frames. The Architect is an interactive NPC near the +start. Event pickups, obstacles, moving platforms, the finish trigger and +save/restore use the existing platformer systems. + +## Repoverse data bridge + +The C# core remains the authority for world generation. Export a snapshot and +manifest using the existing CLI, then generate the read-only repository scene: + + dotnet run --project src/Repoverse.Cli -- ingest-local . --owner SNAPKITTYWEST --out out/snapshot.json + dotnet run --project src/Repoverse.Cli -- generate --snapshot out/snapshot.json --out out/manifest.json + python tools/export-unify-world.py out/manifest.json + +The exporter accepts schema 1 and encodes text as Lua string bytes, never as +executable source. It does not modify the manifest or run repository code. +The checked-in menu data is a snapshot of this repository, not live GitHub data. +The browser shows category, district, activity, construction, rooms and seed. +It is not yet the streamed 3D voxel district described in HANDOFF.md. + +## Unreal project + +See unreal/README.md. The project enables the UnifyUnreal plugin, assigns the +Unify GameMode, creates a host automatically, and stages ordinary files as +NonUFS assets because the engine opens them through its file loader. + +## Artwork and provenance + +Originals and the upstream AGPL license are under assets/snapkitty. Four QOI +runtime copies were converted losslessly, with pixel equality checked. +The source and runtime SHA-256 hashes are in runtime-manifest.json. +No original was recolored, resized or overwritten; scene tint is applied at +runtime for readability. Both original JPGs and transparent PNGs are retained. +The upstream source commit is recorded in source-manifest.json. This does not +replace the licensing terms of unrelated Repoverse code. + +Regenerate texture files with python tools/import-snapkitty.py (Pillow required). +The checked-in QOI files make Pillow unnecessary for ordinary game builds. + +## Validation + +CTest runs the engine suite, the original demo playthrough and the SNAPKITTY +playthrough. The latter exercises the actual game rather than a mock scene. +An additional engine test covers the about panel, repository scene, play +transition, original textures and Architect interaction. Screenshots are +written under unify/build-game/snapkitty-evidence. + +The Unreal Editor is not installed in the inspected locations on this machine. +Its C++ integration therefore still needs compilation and a PIE check with the +user's engine version. SDL/headless results do not establish Unreal compilation. + +## 3D district integration + +See [REPOVERSE-3D.md](REPOVERSE-3D.md) for the new C# sidecar, Unreal client, +launcher and the remaining Unreal compilation/playtest boundary. diff --git a/preview/index.html b/preview/index.html new file mode 100644 index 0000000000000000000000000000000000000000..f952b550e8ae8116bfa15683d63717d7c632cf1a --- /dev/null +++ b/preview/index.html @@ -0,0 +1,166 @@ + + + + + +Repoverse Preview + + + + + +
+

Repoverse · generator preview

+
loading world-mesh.json…
+
+ + +
+
drag to orbit · scroll to zoom · click a building
+
+
+ + + diff --git a/src/Repoverse.Cli/Program.cs b/src/Repoverse.Cli/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..8c5fd1885b2e25921de187774bb412334eb93b2d --- /dev/null +++ b/src/Repoverse.Cli/Program.cs @@ -0,0 +1,208 @@ +using System.Diagnostics; +using System.Text.Json; +using Repoverse.Core; +using Repoverse.Core.Generation; +using Repoverse.Core.Ingestion; +using Repoverse.Core.Simulation; +using Repoverse.Core.Voxels; + +// repoverse [options]. Each command reads/writes plain JSON so stages can be run, +// inspected and diffed independently: snapshot → manifest → chunks/meshes. + +var cmd = args.FirstOrDefault(); +var opts = ParseOptions(args.Skip(1).ToArray()); +try +{ + return cmd switch + { + "ingest-local" => IngestLocal(opts), + "ingest-github" => await IngestGitHub(opts), + "generate" => Generate(opts), + "stats" => await Stats(opts), + "export-mesh" => ExportMesh(opts), + "diff" => Diff(opts), + _ => Usage(), + }; +} +catch (Exception e) when (e is IOException or InvalidDataException or FormatException or ArgumentException or InvalidOperationException or JsonException) +{ + Console.Error.WriteLine($"error: {GitHubIngest.Redact(e.Message)}"); + return 1; +} + +static int Usage() +{ + Console.Error.WriteLine(""" + usage: + repoverse ingest-local [--owner NAME] [--subprojects] --out snapshot.json + repoverse ingest-github [--limit N] [--forks] [--cache DIR] --out snapshot.json (token: $GITHUB_TOKEN) + repoverse generate --snapshot snapshot.json --out manifest.json [--seed N] [--overrides FILE] [--previous manifest.json] + repoverse stats --manifest manifest.json + repoverse export-mesh --manifest manifest.json --out world-mesh.json + repoverse diff --before snapshot.json --after snapshot.json + """); + return 2; +} + +static int IngestLocal(Dictionary o) +{ + var dir = Required(o, "_0"); + var owner = o.GetValueOrDefault("owner", "local"); + var repos = LocalGitIngest.Ingest(dir, owner, o.ContainsKey("subprojects")); + var snap = new Snapshot { TakenAt = DateTimeOffset.UtcNow, Source = $"git:{Path.GetFullPath(dir)}", Repositories = repos }; + SnapshotStore.Save(Required(o, "out"), snap); + Console.WriteLine($"[GITHUB] ingested {repos.Count} repositories from {dir}"); + return 0; +} + +static async Task IngestGitHub(Dictionary o) +{ + var owner = Required(o, "_0"); + var outPath = Required(o, "out"); + var cache = o.GetValueOrDefault("cache", Path.Combine(Path.GetTempPath(), "repoverse-cache")); + var token = Environment.GetEnvironmentVariable("GITHUB_TOKEN"); + var ingest = new GitHubIngest(new HttpClient(), cache, token); + var result = await ingest.IngestOwnerAsync(owner, o.ContainsKey("forks"), o.TryGetValue("limit", out var l) ? int.Parse(l) : null); + + var merged = SnapshotStore.Merge(SnapshotStore.Load(outPath), result, $"github:{owner}", DateTimeOffset.UtcNow); + if (merged.Snapshot.Repositories.Count > 0) SnapshotStore.Save(outPath, merged.Snapshot); + foreach (var f in result.Failures) Console.Error.WriteLine($"[GITHUB] failed {f.Repo}: {f.Reason}"); + Console.WriteLine($"[GITHUB] {result.Repositories.Count} fresh, {merged.Stale.Count} stale, {result.Failures.Count} failed; " + + $"{ingest.RequestsSent} requests ({ingest.NotModified} not modified){(result.RateLimited ? "; RATE LIMITED" : "")}"); + return merged.Snapshot.Repositories.Count > 0 ? 0 : 1; +} + +static int Generate(Dictionary o) +{ + var snap = SnapshotStore.Load(Required(o, "snapshot")) ?? throw new IOException("snapshot not found"); + var seed = new Seed(o.TryGetValue("seed", out var s) ? ulong.Parse(s) : 0x5AA4C177UL); + var overrides = o.TryGetValue("overrides", out var ov) ? Overrides.Load(ov) : null; + var previous = o.TryGetValue("previous", out var pv) && File.Exists(pv) ? ReadManifest(pv) : null; + + var sw = Stopwatch.StartNew(); + var manifest = ManifestBuilder.Build(snap.Repositories, seed, overrides, previous); + File.WriteAllText(Required(o, "out"), JsonSerializer.Serialize(manifest, Json.Options)); + Console.WriteLine($"[MANIFEST] {manifest.Buildings.Count} buildings, {manifest.Dependencies.Count} dependency edges in {sw.ElapsedMilliseconds} ms (seed {manifest.WorldSeed})"); + Console.WriteLine($"{"repository",-44} {"category",-22} {"district",-18} {"archetype",-13} {"floors",6} {"rooms",6}"); + foreach (var b in manifest.Buildings) + Console.WriteLine($"{b.Repo.Key,-44} {b.Category.Value,-22} {b.District.Value,-18} {b.Archetype.Value,-13} {b.Floors,6} {b.Interior.Rooms.Count(BuildingRasterizer.IsWorkRoom),6} ← {b.Category.Why}"); + return 0; +} + +static async Task Stats(Dictionary o) +{ + var manifest = ReadManifest(Required(o, "manifest")); + var gen = new WorldGenerator(manifest); + var chunks = ChunksForBuildings(manifest).ToList(); + + var sw = Stopwatch.StartNew(); + var generated = chunks.AsParallel().Select(c => gen.Generate(c)).ToList(); + var genTime = sw.Elapsed; + var byCoord = generated.ToDictionary(c => c.Coord); + Voxel? Sample(int x, int y, int z) => byCoord.TryGetValue(ChunkCoord.FromVoxel(x, y, z), out var ch) + ? ch[x - ch.Coord.OriginX, y - ch.Coord.OriginY, z - ch.Coord.OriginZ] : null; + + sw.Restart(); + var meshes = generated.AsParallel().Select(c => GreedyMesher.Build(c, Sample)).ToList(); + var meshTime = sw.Elapsed; + int faces = meshes.Sum(m => m.VisibleFaces), quads = meshes.Sum(m => m.Quads.Count); + int objects = manifest.Buildings.Sum(b => BuildingRasterizer.Objects(b).Count()); + + Console.WriteLine($"[VOXEL] {generated.Count} chunks, {generated.Sum(c => (long)c.NonAirCount):N0} solid voxels, {generated.Count * 64} KiB voxel memory"); + Console.WriteLine($"[VOXEL] generate {genTime.TotalMilliseconds:F0} ms total, {genTime.TotalMilliseconds / generated.Count:F2} ms/chunk (parallel)"); + Console.WriteLine($"[VOXEL] mesh {meshTime.TotalMilliseconds:F0} ms; {faces:N0} visible faces → {quads:N0} quads ({quads * 2:N0} tris), {100.0 * quads / Math.Max(1, faces):F1}% of naive"); + Console.WriteLine($"[VOXEL] draw groups: max {meshes.Max(m => m.MaterialGroups)} per chunk, {meshes.Sum(m => m.MaterialGroups)} total"); + Console.WriteLine($"[WORLDGEN] {objects} interactive objects (entities, not voxels)"); + + var streamer = new ChunkStreamer(gen, new WorldEdits(), radius: 4); + var b0 = manifest.Buildings[0]; + sw.Restart(); + await streamer.SettleAsync(b0.Footprint.X, b0.Footprint.Z); + Console.WriteLine($"[STREAMING] radius 4 around {b0.Repo}: {streamer.Loaded.Count} chunks resident in {sw.ElapsedMilliseconds} ms"); + return 0; +} + +static int ExportMesh(Dictionary o) +{ + var manifest = ReadManifest(Required(o, "manifest")); + var gen = new WorldGenerator(manifest); + var chunks = ChunksForBuildings(manifest).AsParallel().Select(c => gen.Generate(c)).ToDictionary(c => c.Coord); + Voxel? Sample(int x, int y, int z) => chunks.TryGetValue(ChunkCoord.FromVoxel(x, y, z), out var ch) + ? ch[x - ch.Coord.OriginX, y - ch.Coord.OriginY, z - ch.Coord.OriginZ] : null; + + // Flat arrays per mesh key keep the file small and map 1:1 onto GPU buffers. + var groups = new Dictionary Pos, List Normal)>(); + foreach (var mesh in chunks.Values.AsParallel().Select(c => GreedyMesher.Build(c, Sample)).ToList()) + foreach (var q in mesh.Quads) + { + if (!groups.TryGetValue(q.MeshKey, out var g)) groups[q.MeshKey] = g = ([], []); + foreach (var (x, y, z) in GreedyMesher.Corners(mesh.Coord, q)) { g.Pos.Add(x); g.Pos.Add(y); g.Pos.Add(z); } + g.Normal.Add((q.Axis + 1) * (q.Positive ? 1 : -1)); + } + + var export = new + { + manifest.WorldSeed, + Groups = groups.OrderBy(kv => kv.Key).Select(kv => new + { + Block = ((BlockType)(kv.Key & 0xFF)).ToString(), + Material = ((Repoverse.Core.Model.MaterialFamily)(kv.Key >> 8 & 0xF)).ToString(), + Positions = kv.Value.Pos, + Normals = kv.Value.Normal, + }), + Buildings = manifest.Buildings.Select(b => new + { + Repo = b.Repo.Key, b.Description, Category = b.Category.Value.ToString(), CategoryWhy = b.Category.Why.ToString(), + District = b.District.Value.ToString(), Archetype = b.Archetype.Value.ToString(), b.Floors, + Activity = b.Activity.Value.ToString(), Construction = b.Construction.Value.ToString(), + b.Footprint.X, b.Footprint.Z, b.Footprint.Width, b.Footprint.Depth, b.Height, + Rooms = b.Interior.Rooms.Where(BuildingRasterizer.IsWorkRoom).Select(r => new { r.Name, Purpose = r.Purpose.ToString(), r.Floor, r.FileCount }), + }), + Objects = manifest.Buildings.SelectMany(BuildingRasterizer.Objects) + .Select(w => new { w.X, w.Y, w.Z, Kind = w.Kind.ToString(), Uri = new RepoverseUri { Repo = w.Repo, Path = w.SourcePath }.ToString() }), + Dependencies = manifest.Dependencies.Select(d => new[] { d.From.Key, d.To.Key }), + }; + File.WriteAllText(Required(o, "out"), JsonSerializer.Serialize(export, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })); + Console.WriteLine($"[VOXEL] exported {groups.Values.Sum(g => g.Normal.Count):N0} quads in {groups.Count} material groups"); + return 0; +} + +static int Diff(Dictionary o) +{ + var before = SnapshotStore.Load(Required(o, "before")) ?? throw new IOException("before snapshot not found"); + var after = SnapshotStore.Load(Required(o, "after")) ?? throw new IOException("after snapshot not found"); + foreach (var e in SnapshotDiff.Diff(before.Repositories, after.Repositories)) Console.WriteLine(e); + return 0; +} + +static IEnumerable ChunksForBuildings(WorldManifest m) +{ + var set = new HashSet(); + foreach (var b in m.Buildings) + { + var lo = ChunkCoord.FromVoxel(b.Footprint.X - WorldConstants.RoadWidth, 0, b.Footprint.Z - WorldConstants.RoadWidth); + var hi = ChunkCoord.FromVoxel(b.Footprint.MaxX + WorldConstants.RoadWidth, WorldConstants.GroundLevel + b.Height, b.Footprint.MaxZ + WorldConstants.RoadWidth); + for (int x = lo.X; x <= hi.X; x++) for (int y = 0; y <= hi.Y; y++) for (int z = lo.Z; z <= hi.Z; z++) + set.Add(new ChunkCoord(x, y, z)); + } + return set.OrderBy(c => c.X).ThenBy(c => c.Z).ThenBy(c => c.Y); +} + +static WorldManifest ReadManifest(string path) => + JsonSerializer.Deserialize(File.ReadAllText(path), Json.Options) ?? throw new InvalidDataException($"{path} is empty"); + +static string Required(Dictionary o, string key) => + o.TryGetValue(key, out var v) ? v : throw new ArgumentException(key.StartsWith('_') ? "missing positional argument" : $"missing --{key}"); + +static Dictionary ParseOptions(string[] a) +{ + var o = new Dictionary(); + int pos = 0; + for (int i = 0; i < a.Length; i++) + { + if (!a[i].StartsWith("--")) { o[$"_{pos++}"] = a[i]; continue; } + var key = a[i][2..]; + o[key] = i + 1 < a.Length && !a[i + 1].StartsWith("--") ? a[++i] : "true"; + } + return o; +} diff --git a/src/Repoverse.Cli/Repoverse.Cli.csproj b/src/Repoverse.Cli/Repoverse.Cli.csproj new file mode 100644 index 0000000000000000000000000000000000000000..f381c0ff3cb0aa852bd1558426a1a3446c99b0fc --- /dev/null +++ b/src/Repoverse.Cli/Repoverse.Cli.csproj @@ -0,0 +1,14 @@ + + + + + + + + Exe + net8.0 + enable + enable + + + diff --git a/src/Repoverse.Core/Bridge/BuilderPlan.cs b/src/Repoverse.Core/Bridge/BuilderPlan.cs new file mode 100644 index 0000000000000000000000000000000000000000..a391ea3598866819de5ae1da8eaf397990beb47b --- /dev/null +++ b/src/Repoverse.Core/Bridge/BuilderPlan.cs @@ -0,0 +1,69 @@ +using System.Text.Json; +using System.Text.RegularExpressions; +using Repoverse.Core.Model; +using Repoverse.Core.Voxels; +namespace Repoverse.Core.Bridge; + +public sealed record BuildOrigin(int X,int Y,int Z); +public sealed record BuildOperation(string Name,JsonElement Args); +public sealed record BuilderPlan(int SchemaVersion,string Id,string Actor,string Units,BuildOrigin Origin,BuildOperation[] Operations); +public sealed record BuilderState(string Actor,string PlanId,double X,double Y,double Z,int Voxels); +public readonly record struct BuildVoxel(int X,int Y,int Z,ushort Packed); + +/// Data-only Twin builder contract. Validate and rasterize completely before editing the world. +public static class BuilderRasterizer +{ + public const int MaxVoxels=32768; + public static IReadOnlyList Rasterize(BuilderPlan plan) + { + if(plan.SchemaVersion!=1 || plan.Units!="voxel" || string.IsNullOrWhiteSpace(plan.Id) || plan.Id.Length>128 || string.IsNullOrWhiteSpace(plan.Actor) || plan.Actor.Length>64 + || plan.Origin is null || plan.Operations is null || plan.Operations.Length is <1 or >128)throw new ArgumentException("Invalid builder plan."); + if(Math.Abs((long)plan.Origin.X)>1_000_000 || Math.Abs((long)plan.Origin.Z)>1_000_000)throw new ArgumentException("Invalid build origin."); + var result=new Dictionary<(int,int,int),BuildVoxel>();long candidates=0; + foreach(var operation in plan.Operations) + { + if(operation is null || operation.Args.ValueKind!=JsonValueKind.Object)throw new ArgumentException("Invalid build operation."); + var a=operation.Args; + double N(string key,double fallback,double min,double max) { + double v=fallback; + if(a.TryGetProperty(key,out var p) && (p.ValueKind!=JsonValueKind.Number || !p.TryGetDouble(out v)))throw new ArgumentException("Invalid "+key); + if(!double.IsFinite(v)||vmax)throw new ArgumentException("Invalid "+key);return v; + } + double cx=plan.Origin.X+N("x",0,-256,256), cy=plan.Origin.Y+N("y",1,-256,256), cz=plan.Origin.Z+N("z",0,-256,256); + double rx,ry,rz,r=0,tube=0,h=0; + switch(operation.Name) { + case "add_box":rx=N("width",1,.02,64)/2;ry=N("height",1,.02,64)/2;rz=N("depth",1,.02,64)/2;break; + case "add_sphere":rx=ry=rz=r=N("radius",.7,.02,64);break; + case "add_cylinder":rx=rz=r=N("radius",.5,.02,64);ry=(h=N("height",2,.02,64))/2;break; + case "add_cone":rx=rz=r=N("radius",.6,.02,64);ry=(h=N("height",1.5,.02,64))/2;break; + case "add_torus":r=N("radius",1,.02,64);tube=N("tube",.3,.02,64);if(tube>r)throw new ArgumentException("Invalid torus tube");rx=ry=r+tube;rz=tube;break; + default:throw new ArgumentException("Unsupported build shape: "+operation.Name); + } + // Sample voxel centers in the same Y-up coordinates as the preview. Torus lies in XY. + int xmin=(int)Math.Ceiling(cx-rx-.5),xmax=(int)Math.Floor(cx+rx-.5),ymin=(int)Math.Ceiling(cy-ry-.5),ymax=(int)Math.Floor(cy+ry-.5),zmin=(int)Math.Ceiling(cz-rz-.5),zmax=(int)Math.Floor(cz+rz-.5); + if(cx-rx < -1_000_000 || cx+rx>1_000_000 || cz-rz < -1_000_000 || cz+rz>1_000_000 || cy-ry<1 || cy+ry>(WorldGenerator.MaxChunkY+1)*WorldConstants.ChunkSize)throw new ArgumentException("Build exceeds world bounds."); + candidates+=(long)Math.Max(0,xmax-xmin+1)*Math.Max(0,ymax-ymin+1)*Math.Max(0,zmax-zmin+1); + if(candidates>262144)throw new ArgumentException("Build sampling budget exceeded."); + var color=a.TryGetProperty("color",out var c)?(c.ValueKind==JsonValueKind.String?c.GetString():null):"#5ad1c4"; + if(color is null || !Regex.IsMatch(color,"^#[0-9a-fA-F]{6}$"))throw new ArgumentException("Invalid build color."); + // Quantize to the existing ten material families; save schema retains packed voxel materials. + int red=Convert.ToInt32(color.Substring(1,2),16),green=Convert.ToInt32(color.Substring(3,2),16),blue=Convert.ToInt32(color.Substring(5,2),16); + var material=red>green&&red>blue?MaterialFamily.Ceramic:green>red&&green>blue?MaterialFamily.Wood:blue>red?MaterialFamily.Glass:MaterialFamily.Concrete; + ushort packed=new Voxel(BlockType.Wall,material).Packed; + for(int x=xmin;x<=xmax;x++)for(int y=ymin;y<=ymax;y++)for(int z=zmin;z<=zmax;z++) { + double dx=x+.5-cx,dy=y+.5-cy,dz=z+.5-cz; + bool inside=operation.Name switch { + "add_sphere"=>dx*dx+dy*dy+dz*dz<=r*r, + "add_cylinder"=>dx*dx+dz*dz<=r*r, + "add_cone"=>dx*dx+dz*dz<=Math.Pow(r*(.5-dy/h),2), + "add_torus"=>Math.Pow(Math.Sqrt(dx*dx+dy*dy)-r,2)+dz*dz<=tube*tube, + _=>true + }; + if(!inside)continue;result[(x,y,z)]=new(x,y,z,packed); + if(result.Count>MaxVoxels)throw new ArgumentException("Build voxel budget exceeded."); + } + } + if(result.Count==0)throw new ArgumentException("Shapes are too small for this voxel grid. Increase their size."); + return result.Values.ToArray(); + } +} diff --git a/src/Repoverse.Core/Bridge/LocalSourceReader.cs b/src/Repoverse.Core/Bridge/LocalSourceReader.cs new file mode 100644 index 0000000000000000000000000000000000000000..463c92fa1fe58f9cda79c901f97f5ff7d7d81b24 --- /dev/null +++ b/src/Repoverse.Core/Bridge/LocalSourceReader.cs @@ -0,0 +1,32 @@ +using Repoverse.Core.Generation; + +namespace Repoverse.Core.Bridge; + +public sealed record SourcePage(string Path, int Offset, string[] Lines, bool HasMore); +/// Read-only, bounded source pages for artifacts in one explicitly mapped local repository. +public sealed class LocalSourceReader(WorldManifest manifest, string repo, string sourceRoot) +{ + private readonly string _root = Path.GetFullPath(sourceRoot); + private readonly HashSet _allowed = manifest.Buildings.Where(b => b.Repo.Key == repo.ToLowerInvariant()) + .SelectMany(b => b.Interior.Rooms).SelectMany(r => r.Artifacts).Select(a => a.Path).ToHashSet(StringComparer.Ordinal); + public SourcePage Read(string requestedRepo, string relative, int offset) + { + if (!requestedRepo.Equals(repo,StringComparison.OrdinalIgnoreCase) || !_allowed.Contains(relative)) + throw new ArgumentException("Source is not an artifact in the mapped repository."); + if (offset is < 0 or > 100_000 || Path.IsPathRooted(relative)) throw new ArgumentException("Invalid source page."); + var parts = relative.Replace('\\','/').Split('/'); + if (parts.Any(p => p is "" or "." or ".." || p.Contains(':'))) throw new ArgumentException("Invalid source path."); + // Reject links/junctions at every component, including the configured root. + var target = _root; + if ((File.GetAttributes(target) & FileAttributes.ReparsePoint) != 0) throw new ArgumentException("Linked source roots are unsupported."); + foreach (var part in parts) { + target = Path.Combine(target,part); + if ((File.GetAttributes(target) & FileAttributes.ReparsePoint) != 0) throw new ArgumentException("Linked source paths are unsupported."); + } + if (new FileInfo(target).Length > 2*1024*1024) throw new ArgumentException("Source exceeds the 2 MiB inspection limit."); + var text = File.ReadAllText(target); + if (text.Contains('\0')) throw new ArgumentException("Binary artifact; open it in its native application."); + var lines = text.Replace("\r\n","\n").Split('\n'); + return new(relative,offset,lines.Skip(offset).Take(32).Select(s => s.Length>240 ? s[..240]+"..." : s).ToArray(),offset+32 Sections); +public sealed record StreamPacket(IReadOnlyList Unloaded, IReadOnlyList Chunks, int Remaining, int Resident); +public sealed record Destination(string Repo, string Description, double X, double Y, double Z, + int Floors, int LadderX, int LadderZ, IReadOnlyList Rooms); + +/// Single-client, serialized bridge session. Core Y-up units remain authoritative. +public sealed class WorldSession +{ + private readonly WorldGenerator _generator; + private readonly Dictionary _chunks = new(); + private readonly HashSet _dirty = new(); + private readonly int _radius; + public WorldManifest Manifest { get; } + public WorldEdits Edits { get; } = new(); + public PlayerState Player { get; private set; } + public long Tick { get; private set; } + public IReadOnlyList Builders => _builders.Values.ToArray(); + private readonly Dictionary _builders = new(StringComparer.Ordinal); + public IReadOnlyList Destinations { get; } + public int Resident => _chunks.Count; + + public WorldSession(WorldManifest manifest, int radius = 1) + { + if (manifest.SchemaVersion != WorldManifest.CurrentSchema) throw new InvalidDataException("Unsupported manifest schema."); + if (radius is < 0 or > 3) throw new ArgumentOutOfRangeException(nameof(radius)); + Manifest = manifest; _radius = radius; _generator = new(manifest); + Destinations = manifest.Buildings.Select(b => { + var p = BuildingRasterizer.Plan(b); + return new Destination(b.Repo.Key, b.Description, p.Entrance.X + 3.5, + p.Entrance.Y + 1.5, p.Entrance.Z + .5, b.Floors, p.LadderX, p.CorridorZ + 1, p.Rooms); + }).ToArray(); + var start = Destinations.FirstOrDefault(); + Player = new PlayerState { X = start?.X ?? 10, Y = start?.Y ?? 11, Z = start?.Z ?? 10, Yaw = 180 }; + } + + public static void Validate(PlayerState p) + { + if (!double.IsFinite(p.X) || !double.IsFinite(p.Y) || !double.IsFinite(p.Z) || !double.IsFinite(p.Yaw) + || Math.Abs(p.X) > 1_000_000 || Math.Abs(p.Z) > 1_000_000 || p.Y < -100 || p.Y > 10_000 + || !Enum.IsDefined(p.Mode)) throw new ArgumentException("Invalid player state."); + } + + public void SetPlayer(PlayerState player) { Validate(player); Player = player; } + + private static IEnumerable Neighbours(ChunkCoord c) + { + yield return c; + yield return c with { X = c.X - 1 }; yield return c with { X = c.X + 1 }; + yield return c with { Y = c.Y - 1 }; yield return c with { Y = c.Y + 1 }; + yield return c with { Z = c.Z - 1 }; yield return c with { Z = c.Z + 1 }; + } + private static int Distance(ChunkCoord a, ChunkCoord b) => Math.Max(Math.Abs(a.X-b.X), Math.Abs(a.Z-b.Z)); + + /// Bounded generation and upload, nearest first. Unloads are sent before replacement meshes. + public StreamPacket Focus(double x, double z, int budget = 4) + { + Validate(Player with { X = x, Z = z }); + if (budget is < 1 or > 16) throw new ArgumentOutOfRangeException(nameof(budget)); + var center = ChunkCoord.FromVoxel((int)Math.Floor(x), WorldConstants.GroundLevel, (int)Math.Floor(z)); + var unloaded = new List(); + foreach (var c in _chunks.Keys.Where(c => Distance(c, center) > _radius + 1).ToArray()) + { + _chunks.Remove(c); _dirty.Remove(c); unloaded.Add(c.ToString()); + foreach (var n in Neighbours(c)) if (_chunks.ContainsKey(n)) _dirty.Add(n); + } + var wanted = new List(); + for (int dx = -_radius; dx <= _radius; dx++) + for (int dz = -_radius; dz <= _radius; dz++) + for (int y = 0; y <= WorldGenerator.MaxChunkY; y++) + wanted.Add(new(center.X + dx, y, center.Z + dz)); + wanted = wanted.OrderBy(c => Distance(c, center)).ThenBy(c => c.Y).ThenBy(c => c.X).ThenBy(c => c.Z).ToList(); + foreach (var c in wanted.Where(c => !_chunks.ContainsKey(c)).Take(budget)) + { + _chunks[c] = _generator.Generate(c, Edits); + foreach (var n in Neighbours(c)) if (_chunks.ContainsKey(n)) _dirty.Add(n); + } + var result = new List(); + foreach (var c in _dirty.OrderBy(c => Distance(c, center)).ThenBy(c => c.Y).ThenBy(c => c.X).ThenBy(c => c.Z).Take(budget).ToArray()) + { + result.Add(Encode(GreedyMesher.Build(_chunks[c], Sample))); + _dirty.Remove(c); + } + Tick++; + return new(unloaded, result, wanted.Count(c => !_chunks.ContainsKey(c)) + _dirty.Count, _chunks.Count); + } + public Voxel? Sample(int x, int y, int z) => _chunks.TryGetValue(ChunkCoord.FromVoxel(x,y,z), out var c) + ? c[x-c.Coord.OriginX, y-c.Coord.OriginY, z-c.Coord.OriginZ] : null; + + public static MeshPacket Encode(ChunkMesh mesh) + { + var sections = new List(); + foreach (var group in mesh.Quads.GroupBy(q => q.MeshKey).OrderBy(g => g.Key)) + { + var vertices = new List(); var indices = new List(); + foreach (var q in group) + { + int i = vertices.Count; + vertices.AddRange(GreedyMesher.Corners(mesh.Coord, q).Select(v => new[] {v.X,v.Y,v.Z})); + indices.AddRange([i,i+1,i+2,i,i+2,i+3]); + } + sections.Add(new(group.Key, !new Voxel(group.Key).IsPassable, vertices.ToArray(), indices.ToArray())); + } + return new(mesh.Coord.ToString(), sections); + } + public IReadOnlyList Objects() => Manifest.Buildings.SelectMany(BuildingRasterizer.Objects).ToArray(); + public void Edit(int x, int y, int z, ushort packed) + { + if (y < 1 || y > WorldGenerator.MaxChunkY * WorldConstants.ChunkSize + 31 || Math.Abs((long)x)>1_000_000 || Math.Abs((long)z)>1_000_000 + || !Enum.IsDefined(new Voxel(packed).Type)) throw new ArgumentException("Invalid voxel edit."); + Edits.Set(x,y,z,new Voxel(packed)); + var c = ChunkCoord.FromVoxel(x,y,z); + if (_chunks.ContainsKey(c)) _chunks[c] = _generator.Generate(c,Edits); + foreach (var n in Neighbours(c)) if (_chunks.ContainsKey(n)) _dirty.Add(n); + } + public BuilderState Build(BuilderPlan plan) + { + var voxels=BuilderRasterizer.Rasterize(plan); + if(!_builders.ContainsKey(plan.Actor) && _builders.Count>=16)throw new ArgumentException("Builder actor limit reached."); + var changed=new HashSet(); + foreach(var v in voxels){Edits.Set(v.X,v.Y,v.Z,new Voxel(v.Packed));changed.Add(ChunkCoord.FromVoxel(v.X,v.Y,v.Z));} + foreach(var c in changed){if(_chunks.ContainsKey(c))_chunks[c]=_generator.Generate(c,Edits);foreach(var n in Neighbours(c))if(_chunks.ContainsKey(n))_dirty.Add(n);} + var last=voxels[^1];var state=new BuilderState(plan.Actor,plan.Id,last.X+.5,last.Y+1,last.Z+.5,voxels.Count);_builders[plan.Actor]=state;return state; + } + public SaveGame Capture() => SaveGame.Capture(Manifest, Player, Edits, Tick) with {Builders=Builders}; + public void Restore(SaveGame save) + { + if (save.WorldSeed != Manifest.WorldSeed || save.Generator != Manifest.Generator + || save.Snapshots.Count != Manifest.Snapshots.Count || save.Snapshots.Any(s => !Manifest.Snapshots.TryGetValue(s.Key,out var v) || v != s.Value)) + throw new InvalidDataException("Save belongs to a different world snapshot."); + Validate(save.Player); + // Validate in a temporary store before changing the live session. + var restored = new WorldEdits(); save.RestoreEdits(restored); + if(save.Builders.Count>16 || save.Builders.Any(b=>string.IsNullOrWhiteSpace(b.Actor)||b.Actor.Length>64||!double.IsFinite(b.X)||!double.IsFinite(b.Y)||!double.IsFinite(b.Z)) || save.Builders.Select(b=>b.Actor).Distinct().Count()!=save.Builders.Count)throw new InvalidDataException("Invalid saved builders."); + Edits.Load(restored.Snapshot()); Player = save.Player; Tick = save.SimulationTick; + _builders.Clear();foreach(var b in save.Builders)_builders.Add(b.Actor,b); + foreach (var c in _chunks.Keys.ToArray()) { _chunks[c] = _generator.Generate(c,Edits); _dirty.Add(c); } + } +} diff --git a/src/Repoverse.Core/Generation/Classifier.cs b/src/Repoverse.Core/Generation/Classifier.cs new file mode 100644 index 0000000000000000000000000000000000000000..f3daa67032da641877a2fe05ed5a184712d027fc --- /dev/null +++ b/src/Repoverse.Core/Generation/Classifier.cs @@ -0,0 +1,124 @@ +using Repoverse.Core.Model; + +namespace Repoverse.Core.Generation; + +/// +/// Deterministic, rule-based semantic classification. Each rule contributes weighted +/// evidence; the highest total wins and the winning evidence becomes the provenance. +/// Purpose signals (topics, description, file layout) outweigh language (§80). +/// +public static class Classifier +{ + /// A rule returns how many independent signals matched; weight applies per signal, capped at 3. + private sealed record Rule(SemanticCategory Category, int Weight, string Name, Func Match); + + /// + /// Counts keywords present as whole words in name, description and topics. Text and keywords are + /// both reduced to space-separated alphanumeric tokens, so "Guppy-to-IR" matches "ir" and + /// "multi-agent" matches "multi agent". A trailing '*' makes a keyword a word prefix. + /// + private static int Mentions(CanonicalRepository r, params string[] words) + { + var text = Tokens($"{r.Id.Name} {r.Description} {string.Join(' ', r.Topics)}"); + return words.Count(w => w.EndsWith('*') + ? text.Contains(Tokens(w[..^1]).TrimEnd(), StringComparison.Ordinal) + : text.Contains(Tokens(w), StringComparison.Ordinal)); + } + + private static string Tokens(string s) => " " + TokenSplit.Replace(s.ToLowerInvariant(), " ").Trim() + " "; + private static readonly System.Text.RegularExpressions.Regex TokenSplit = new("[^a-z0-9]+"); + + private static int One(bool b) => b ? 1 : 0; + + private static bool HasFile(CanonicalRepository r, Func pred) => + r.Tree.Any(e => e.Kind == TreeEntryKind.File && pred(e.Path.ToLowerInvariant())); + + private static bool HasExt(CanonicalRepository r, params string[] exts) => + HasFile(r, p => exts.Any(x => p.EndsWith(x, StringComparison.Ordinal))); + + private static bool Lang(CanonicalRepository r, params string[] langs) => + r.PrimaryLanguage is { } l && langs.Contains(l, StringComparer.OrdinalIgnoreCase); + + private static readonly Rule[] Rules = + [ + new(SemanticCategory.FormalVerification, 6, "proof-sources", r => One(HasExt(r, ".lean", ".v", ".agda", ".idr", ".thy", ".tla"))), + new(SemanticCategory.FormalVerification, 4, "mentions-proof", r => Mentions(r, "proof*", "verified", "formal", "theorem*", "lean4", "coq")), + new(SemanticCategory.Compiler, 5, "mentions-compiler", r => Mentions(r, "compiler", "codegen", "llvm", "parser", "interpreter", "wasm", "ir", "lowering")), + new(SemanticCategory.Compiler, 3, "grammar-files", r => One(HasExt(r, ".g4", ".y", ".lalrpop", ".ll"))), + new(SemanticCategory.OperatingSystem, 6, "mentions-os", r => Mentions(r, "kernel", "microkernel", "operating system", "bootloader", "hypervisor")), + new(SemanticCategory.OperatingSystem, 3, "linker-script", r => One(HasExt(r, ".ld", ".lds"))), + new(SemanticCategory.CryptographicCore, 6, "mentions-crypto", r => Mentions(r, "crypto", "cipher", "signature", "ed25519", "zk", "zero-knowledge", "encryption")), + new(SemanticCategory.Financial, 6, "mentions-finance", r => Mentions(r, "finance", "trading", "ledger", "payment", "bank", "exchange", "portfolio")), + new(SemanticCategory.Quantum, 6, "mentions-quantum", r => Mentions(r, "quantum", "qubit", "qiskit", "qir", "circuit")), + new(SemanticCategory.Hardware, 6, "hdl-sources", r => One(HasExt(r, ".v", ".sv", ".vhd", ".vhdl", ".kicad_pcb", ".sch"))), + new(SemanticCategory.Hardware, 4, "mentions-hardware", r => Mentions(r, "fpga", "firmware", "embedded", "pcb", "risc-v", "microcontroller")), + new(SemanticCategory.Training, 6, "mentions-training", r => Mentions(r, "dataset", "corpus", "training", "fine-tune", "finetune")), + new(SemanticCategory.AgentSystem, 5, "mentions-agent", r => Mentions(r, "agent*", "multi-agent", "autonomous", "llm", "mcp")), + new(SemanticCategory.Simulation, 5, "mentions-simulation", r => Mentions(r, "simulat*", "voxel", "physics", "game")), + new(SemanticCategory.Database, 6, "mentions-database", r => Mentions(r, "database", "storage engine", "sql", "kv store")), + new(SemanticCategory.Networking, 5, "mentions-network", r => Mentions(r, "network", "protocol", "http", "rpc", "proxy", "p2p")), + new(SemanticCategory.WebInterface, 4, "mentions-web", r => Mentions(r, "frontend", "website", "dashboard", "ui", "react", "web app")), + new(SemanticCategory.WebInterface, 3, "web-language", r => One(Lang(r, "TypeScript", "JavaScript", "HTML", "CSS", "Vue", "Svelte"))), + new(SemanticCategory.Documentation, 4, "docs-only", r => One(r.Tree.Count > 0 && r.Tree.Where(e => e.Kind == TreeEntryKind.File) + .All(e => e.Path.EndsWith(".md", StringComparison.OrdinalIgnoreCase) || e.Path.EndsWith(".txt", StringComparison.OrdinalIgnoreCase) || e.Path.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)))), + new(SemanticCategory.SystemsInfrastructure, 3, "systems-language", r => One(Lang(r, "Rust", "C", "C++", "Zig", "Go", "Assembly"))), + new(SemanticCategory.SystemsInfrastructure, 4, "mentions-infra", r => Mentions(r, "infrastructure", "deploy", "orchestrat*", "ci/cd", "terraform", "runtime")), + ]; + + public static Derived Classify(CanonicalRepository repo, Overrides? overrides = null) + { + if (overrides?.Category(repo.Id) is { } forced) + return new(forced, Provenance.Override(overrides.Source)); + + var scores = new Dictionary Evidence)>(); + foreach (var rule in Rules) + { + var hits = Math.Min(3, rule.Match(repo)); + if (hits == 0) continue; + if (!scores.TryGetValue(rule.Category, out var s)) s = (0, []); + s.Evidence.Add(hits > 1 ? $"{rule.Name}x{hits}" : rule.Name); + scores[rule.Category] = (s.Score + rule.Weight * hits, s.Evidence); + } + + if (scores.Count == 0) + return new(SemanticCategory.Experimental, new("classifier:fallback", "no rule matched")); + + // Ties break on enum order so the result never depends on dictionary iteration. + var best = scores.OrderByDescending(kv => kv.Value.Score).ThenBy(kv => (int)kv.Key).First(); + return new(best.Key, new("classifier:rules", $"{string.Join('+', best.Value.Evidence)} (score {best.Value.Score})")); + } + + public static District DistrictFor(SemanticCategory c, bool archived) => archived ? District.Archive : c switch + { + SemanticCategory.OperatingSystem or SemanticCategory.Compiler => District.Kernel, + SemanticCategory.SystemsInfrastructure or SemanticCategory.Networking => District.Infrastructure, + SemanticCategory.CryptographicCore => District.Security, + SemanticCategory.FormalVerification => District.FormalMethods, + SemanticCategory.Financial => District.Financial, + SemanticCategory.Quantum => District.QuantumResearch, + SemanticCategory.Hardware => District.HardwareIndustrial, + SemanticCategory.Training => District.Training, + SemanticCategory.AgentSystem => District.Agent, + SemanticCategory.Simulation => District.Ai, + SemanticCategory.Database => District.Data, + SemanticCategory.WebInterface => District.WebInterface, + SemanticCategory.Documentation => District.Archive, + _ => District.Experimental, + }; + + public static BuildingArchetype ArchetypeFor(SemanticCategory c) => c switch + { + SemanticCategory.Compiler => BuildingArchetype.Foundry, + SemanticCategory.OperatingSystem or SemanticCategory.SystemsInfrastructure => BuildingArchetype.ControlTower, + SemanticCategory.CryptographicCore => BuildingArchetype.Vault, + SemanticCategory.FormalVerification => BuildingArchetype.ProofChamber, + SemanticCategory.Financial => BuildingArchetype.Exchange, + SemanticCategory.Quantum or SemanticCategory.Hardware or SemanticCategory.Simulation => BuildingArchetype.Laboratory, + SemanticCategory.Training or SemanticCategory.Documentation => BuildingArchetype.Library, + SemanticCategory.WebInterface => BuildingArchetype.Studio, + SemanticCategory.Database => BuildingArchetype.Warehouse, + SemanticCategory.Networking => BuildingArchetype.Relay, + SemanticCategory.AgentSystem => BuildingArchetype.Commons, + _ => BuildingArchetype.Workshop, + }; +} diff --git a/src/Repoverse.Core/Generation/ManifestBuilder.cs b/src/Repoverse.Core/Generation/ManifestBuilder.cs new file mode 100644 index 0000000000000000000000000000000000000000..9e5cf6c4ee2b8eecac0c6e84d9c764b81facdc79 --- /dev/null +++ b/src/Repoverse.Core/Generation/ManifestBuilder.cs @@ -0,0 +1,179 @@ +using Repoverse.Core.Model; +using static Repoverse.Core.WorldConstants; + +namespace Repoverse.Core.Generation; + +/// +/// Canonical repositories → world manifest. Pure and deterministic: same snapshot, +/// seed, overrides and previous manifest give an equal manifest (§59). +/// +public static class ManifestBuilder +{ + private const int RoomWidth = 6; + + /// Plot slots of a district ordered outward from its centre, so districts grow as compact blobs. + private static readonly (int Col, int Row)[] SpiralSlots = Enumerable.Range(0, DistrictSide * DistrictSide) + .Select(i => (Col: i % DistrictSide, Row: i / DistrictSide)) + .OrderBy(s => Math.Max(Math.Abs(s.Col * 2 + 1 - DistrictSide), Math.Abs(s.Row * 2 + 1 - DistrictSide))) + .ThenBy(s => Math.Atan2(s.Row * 2 + 1 - DistrictSide, s.Col * 2 + 1 - DistrictSide)) + .ToArray(); + + public static (int X, int Z) DistrictOrigin(District d) + { + var i = (int)d; + const int stride = DistrictSpan + 2 * PlotSize; // avenue between districts + return (i % DistrictGridColumns * stride, i / DistrictGridColumns * stride); + } + + public static (int X, int Z) PlotOrigin(PlotAddress plot) + { + var (ox, oz) = DistrictOrigin(plot.District); + var (col, row) = SpiralSlots[plot.Slot]; + return (ox + col * PlotSize, oz + row * PlotSize); + } + + public static WorldManifest Build( + IReadOnlyList repos, + Seed worldSeed, + Overrides? overrides = null, + WorldManifest? previous = null) + { + overrides ??= Overrides.Empty; + var ordered = repos.OrderBy(r => r.Id.Key, StringComparer.Ordinal).ToList(); + var dup = ordered.GroupBy(r => r.Id.Key).FirstOrDefault(g => g.Count() > 1); + if (dup != null) throw new ArgumentException($"Repository '{dup.Key}' appears twice in the snapshot."); + + var classified = ordered.Select(r => + { + var category = Classifier.Classify(r, overrides); + var district = overrides.District(r.Id) is { } d + ? new Derived(d, Provenance.Override(overrides.Source)) + : new Derived(Classifier.DistrictFor(category.Value, r.Archived), + new("district-from-category", r.Archived ? "archived" : category.Value.ToString())); + return (Repo: r, Category: category, District: district); + }).ToList(); + + // Sticky placement (§7, §85): a repo keeps its plot while it stays in the same district; + // newcomers take the innermost free slot in id order. + var taken = new Dictionary>(); + var slotOf = new Dictionary(); + foreach (var c in classified) + { + var old = previous?.Find(c.Repo.Id); + if (old == null || old.Plot.District != c.District.Value) continue; + if (!taken.TryGetValue(old.Plot.District, out var set)) taken[old.Plot.District] = set = []; + if (set.Add(old.Plot.Slot)) slotOf[c.Repo.Id.Key] = old.Plot; + } + foreach (var c in classified) + { + if (slotOf.ContainsKey(c.Repo.Id.Key)) continue; + if (!taken.TryGetValue(c.District.Value, out var set)) taken[c.District.Value] = set = []; + var slot = Enumerable.Range(0, SpiralSlots.Length).FirstOrDefault(s => !set.Contains(s), -1); + if (slot < 0) throw new InvalidOperationException($"District {c.District.Value} is full ({SpiralSlots.Length} plots)."); + set.Add(slot); + slotOf[c.Repo.Id.Key] = new PlotAddress(c.District.Value, slot); + } + + var inWorld = ordered.Select(r => r.Id.Key).ToHashSet(); + var buildings = classified.Select(c => Transform(c.Repo, c.Category, c.District, slotOf[c.Repo.Id.Key], worldSeed, overrides)).ToList(); + var edges = ordered + .SelectMany(r => r.DependsOn.Where(d => inWorld.Contains(d.Key) && d.Key != r.Id.Key).Select(d => new DependencyEdge(r.Id, d))) + .DistinctBy(e => (e.From.Key, e.To.Key)) + .OrderBy(e => e.From.Key, StringComparer.Ordinal).ThenBy(e => e.To.Key, StringComparer.Ordinal) + .ToList(); + + return new WorldManifest + { + WorldSeed = worldSeed.ToString(), + Snapshots = ordered.ToDictionary(r => r.Id.Key, r => r.SnapshotId), + Buildings = buildings, + Dependencies = edges, + }; + } + + /// + /// Repository → building (§9). Floors follow module structure (room count), depth follows + /// code volume, activity follows recent commits, construction follows releases — not size → height. + /// + public static BuildingDefinition Transform( + CanonicalRepository repo, + Derived category, + Derived district, + PlotAddress plot, + Seed worldSeed, + Overrides overrides) + { + var seed = worldSeed.Derive("repo:" + repo.Id.Key); + var archetype = overrides.Archetype(repo.Id) is { } a + ? new Derived(a, Provenance.Override(overrides.Source)) + : new Derived(Classifier.ArchetypeFor(category.Value), new("archetype-from-category", category.Value.ToString())); + bool landmark = overrides.Landmark(repo.Id); + + // Count prospective rooms first to size the floor plate, then build the real graph with that width. + var probe = RoomGraphBuilder.Build(repo, int.MaxValue); + int workRooms = probe.Rooms.Count(r => r.Purpose is not (RoomPurpose.Lobby or RoomPurpose.Corridor or RoomPurpose.Stairwell)); + int maxPerSide = (MaxFootprint - 2) / RoomWidth; + int perSide = Math.Clamp((int)Math.Ceiling(Math.Sqrt(Math.Max(1, workRooms))), 1, maxPerSide); + if (landmark) perSide = maxPerSide; + var interior = RoomGraphBuilder.Build(repo, perSide * 2); + int floors = Math.Min(MaxFloors, interior.Rooms.Count(r => r.Purpose == RoomPurpose.Corridor)); + + long codeBytes = repo.Languages.Values.Sum(); + if (codeBytes == 0) codeBytes = repo.Tree.Where(e => e.Kind == TreeEntryKind.File).Sum(e => e.SizeBytes); + int roomDepth = Math.Clamp(3 + (int)Math.Log2(Math.Max(1, codeBytes / 4096.0) + 1), 4, 10); + + int width = Math.Clamp(2 + perSide * RoomWidth, MinFootprint, MaxFootprint); + int depth = Math.Clamp(2 * roomDepth + 7, MinFootprint, MaxFootprint); + var (px, pz) = PlotOrigin(plot); + var footprint = new Footprint(px + (PlotSize - width) / 2, pz + (PlotSize - depth) / 2, width, depth); + + var activity = repo.CommitsLast90Days switch + { + 0 => ActivityLevel.Dormant, + < 10 => ActivityLevel.Low, + < 50 => ActivityLevel.Moderate, + _ => ActivityLevel.High, + }; + var construction = repo.Archived ? ConstructionState.Archived + : repo.Releases.Any(r => !r.Prerelease) ? ConstructionState.Released + : repo.Releases.Count > 0 ? ConstructionState.Prerelease + : ConstructionState.Unreleased; + + return new BuildingDefinition + { + Repo = repo.Id, + Description = repo.Description ?? "", + Category = category, + District = district, + Archetype = archetype, + Material = MaterialFor(archetype.Value), + Plot = plot, + Footprint = footprint, + Floors = floors, + RoomsPerSide = perSide, + RoomDepth = roomDepth, + Activity = new(activity, new("commits-in-window", $"{repo.CommitsLast90Days} commits / {ActivityWindowDays}d")), + Construction = new(construction, new("release-state", repo.Archived ? "archived" : $"{repo.Releases.Count} releases")), + Landmark = landmark, + Population = Math.Clamp(repo.Contributors, 1, perSide * 2 * floors), + Seed = seed.ToString(), + Interior = interior, + }; + } + + public static MaterialFamily MaterialFor(BuildingArchetype a) => a switch + { + BuildingArchetype.Foundry => MaterialFamily.Metal, + BuildingArchetype.ControlTower => MaterialFamily.Concrete, + BuildingArchetype.Vault => MaterialFamily.Security, + BuildingArchetype.ProofChamber => MaterialFamily.Stone, + BuildingArchetype.Exchange => MaterialFamily.Glass, + BuildingArchetype.Laboratory => MaterialFamily.Laboratory, + BuildingArchetype.Library => MaterialFamily.Archive, + BuildingArchetype.Studio => MaterialFamily.Glass, + BuildingArchetype.Warehouse => MaterialFamily.Concrete, + BuildingArchetype.Relay => MaterialFamily.Electronics, + BuildingArchetype.Commons => MaterialFamily.Wood, + _ => MaterialFamily.Wood, + }; +} diff --git a/src/Repoverse.Core/Generation/Overrides.cs b/src/Repoverse.Core/Generation/Overrides.cs new file mode 100644 index 0000000000000000000000000000000000000000..f3c5056c301813fd825a3429ef75d073ffcde7ec --- /dev/null +++ b/src/Repoverse.Core/Generation/Overrides.cs @@ -0,0 +1,62 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using Repoverse.Core.Model; + +namespace Repoverse.Core.Generation; + +/// +/// Hand-authored world design (§83). Overrides augment procedural output; any repo +/// not listed is generated normally. +/// +public sealed class Overrides +{ + public sealed record Entry + { + public SemanticCategory? Category { get; init; } + public District? District { get; init; } + public BuildingArchetype? Archetype { get; init; } + public bool Landmark { get; init; } + } + + private readonly Dictionary _entries; + public string Source { get; } + + public Overrides(IReadOnlyDictionary entries, string source) + { + _entries = entries.ToDictionary(kv => kv.Key.ToLowerInvariant(), kv => kv.Value); + Source = source; + } + + public static Overrides Empty { get; } = new(new Dictionary(), "(none)"); + + public static Overrides Load(string path) + { + var entries = JsonSerializer.Deserialize>(File.ReadAllText(path), Json.Options) + ?? throw new InvalidDataException($"Override file '{path}' is empty."); + return new Overrides(entries, Path.GetFileName(path)); + } + + private Entry? Get(RepoId id) => _entries.GetValueOrDefault(id.Key); + public SemanticCategory? Category(RepoId id) => Get(id)?.Category; + public District? District(RepoId id) => Get(id)?.District; + public BuildingArchetype? Archetype(RepoId id) => Get(id)?.Archetype; + public bool Landmark(RepoId id) => Get(id)?.Landmark ?? false; +} + +/// Shared serializer settings: enums as strings so manifests stay human-readable and diffable. +public static class Json +{ + public static JsonSerializerOptions Options { get; } = new() + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase), new RepoIdConverter() }, + }; + + private sealed class RepoIdConverter : JsonConverter + { + public override RepoId Read(ref Utf8JsonReader reader, Type t, JsonSerializerOptions o) => RepoId.Parse(reader.GetString()!); + public override void Write(Utf8JsonWriter writer, RepoId value, JsonSerializerOptions o) => writer.WriteStringValue($"{value.Owner}/{value.Name}"); + } +} diff --git a/src/Repoverse.Core/Generation/RoomGraph.cs b/src/Repoverse.Core/Generation/RoomGraph.cs new file mode 100644 index 0000000000000000000000000000000000000000..07e450177a0aac8408f7fd27b5109a25e9e21556 --- /dev/null +++ b/src/Repoverse.Core/Generation/RoomGraph.cs @@ -0,0 +1,197 @@ +using Repoverse.Core.Model; + +namespace Repoverse.Core.Generation; + +public enum RoomPurpose { Lobby, Corridor, Stairwell, Workshop, InspectionLab, Archive, ProofVault, Assembly, Storage, Toolroom, Commons } + +/// Software concept a world object stands for (§53). +public enum ArtifactKind { SourceTerminal, TestBench, ProofVault, ArchiveShelf, BuildStation, DataRack, ConfigPanel, AssetCrate, NotebookDesk, HardwareBench } + +public sealed record Artifact(string Path, ArtifactKind Kind, long SizeBytes, string Language); + +public sealed record Room +{ + public required int Id { get; init; } + public required string Name { get; init; } + public required RoomPurpose Purpose { get; init; } + public required int Floor { get; init; } + /// Repository directories this room represents; several when small dirs were merged. + public IReadOnlyList Directories { get; init; } = []; + public int FileCount { get; init; } + public IReadOnlyList Artifacts { get; init; } = []; +} + +public sealed record Door(int A, int B); + +/// Logical interior (§88): rooms and their connections, before any geometry exists. +public sealed record RoomGraph(IReadOnlyList Rooms, IReadOnlyList Doors) +{ + public int EntranceId => Rooms.First(r => r.Purpose == RoomPurpose.Lobby).Id; + + /// Rooms not reachable from the entrance. Empty for a valid graph (§89). + public IReadOnlyList Unreachable() + { + var adj = Rooms.ToDictionary(r => r.Id, _ => new List()); + foreach (var d in Doors) { adj[d.A].Add(d.B); adj[d.B].Add(d.A); } + var seen = new HashSet { EntranceId }; + var queue = new Queue(seen); + while (queue.Count > 0) + foreach (var n in adj[queue.Dequeue()]) + if (seen.Add(n)) queue.Enqueue(n); + return Rooms.Where(r => !seen.Contains(r.Id)).ToList(); + } +} + +public static class RoomGraphBuilder +{ + public static bool IsIgnored(string path) + { + foreach (var segment in path.Split('/')) + if (WorldConstants.IgnoredDirectories.Contains(segment, StringComparer.OrdinalIgnoreCase)) + return true; + return false; + } + + public static RoomPurpose PurposeFor(string directory) + { + var d = directory.ToLowerInvariant(); + var leaf = d[(d.LastIndexOf('/') + 1)..]; + return leaf switch + { + "test" or "tests" or "spec" or "specs" or "__tests__" or "testing" => RoomPurpose.InspectionLab, + "doc" or "docs" or "documentation" or "papers" or "notes" => RoomPurpose.Archive, + "proof" or "proofs" or "formal" or "theories" or "verification" => RoomPurpose.ProofVault, + ".github" or "ci" or ".circleci" or "workflows" or "deploy" => RoomPurpose.Assembly, + "assets" or "data" or "fixtures" or "demo" or "screenshots" or "resources" => RoomPurpose.Storage, + "scripts" or "tools" or "bin" or "cmd" => RoomPurpose.Toolroom, + _ => RoomPurpose.Workshop, + }; + } + + public static ArtifactKind KindFor(string path) + { + var p = path.ToLowerInvariant(); + var name = p[(p.LastIndexOf('/') + 1)..]; + if (name.Contains("test") || name.Contains("spec") || p.Split('/')[..^1].Any(d => d is "test" or "tests" or "spec" or "specs" or "__tests__")) + return ArtifactKind.TestBench; + if (name is "makefile" or "cargo.toml" or "package.json" or "cmakelists.txt" or "dockerfile" or "project.toml" + || name.EndsWith(".csproj") || name.EndsWith(".cabal") || name.EndsWith(".sln") || p.Contains(".github/workflows/")) + return ArtifactKind.BuildStation; + var ext = Path.GetExtension(name); + return ext switch + { + ".lean" or ".v" or ".agda" or ".idr" or ".thy" or ".tla" => ArtifactKind.ProofVault, + ".md" or ".rst" or ".txt" or ".pdf" or ".tex" => ArtifactKind.ArchiveShelf, + ".json" or ".csv" or ".parquet" or ".sqlite" or ".db" or ".vox" => ArtifactKind.DataRack, + ".toml" or ".yaml" or ".yml" or ".ini" or ".cfg" or ".lock" => ArtifactKind.ConfigPanel, + ".png" or ".jpg" or ".svg" or ".zip" or ".wav" or ".glb" => ArtifactKind.AssetCrate, + ".ipynb" => ArtifactKind.NotebookDesk, + ".sv" or ".vhd" or ".vhdl" or ".metal" or ".asm" or ".s" => ArtifactKind.HardwareBench, + _ => ArtifactKind.SourceTerminal, + }; + } + + public static string LanguageFor(string path) => Path.GetExtension(path).ToLowerInvariant() switch + { + ".cs" => "C#", ".rs" => "Rust", ".py" => "Python", ".hs" => "Haskell", ".jl" => "Julia", + ".js" or ".mjs" or ".cjs" => "JavaScript", ".ts" or ".tsx" => "TypeScript", ".swift" => "Swift", + ".c" or ".h" => "C", ".cpp" or ".cc" or ".hpp" => "C++", ".go" => "Go", ".lean" => "Lean", + ".asm" or ".s" => "Assembly", ".metal" => "Metal", ".m" => "Objective-C", ".pl" => "Prolog", + ".html" => "HTML", ".css" => "CSS", ".md" => "Markdown", ".json" => "JSON", ".toml" => "TOML", + ".yml" or ".yaml" => "YAML", ".idr" => "Idris", ".zig" => "Zig", ".java" => "Java", ".kt" => "Kotlin", + _ => "Other", + }; + + /// + /// Groups the tree into rooms by top-level directory (then second level for large ones), + /// merges tiny directories into a Commons room, and lays rooms out over floors joined + /// by a stairwell. Every room hangs off its floor's corridor, so the graph is connected + /// by construction; verifies it. + /// + public static RoomGraph Build(CanonicalRepository repo, int roomsPerFloor) + { + var files = repo.Tree + .Where(e => e.Kind == TreeEntryKind.File && !IsIgnored(e.Path)) + .OrderBy(e => e.Path, StringComparer.Ordinal) + .ToList(); + + // Bucket by top-level directory; split big buckets one level deeper. + var buckets = new SortedDictionary>(StringComparer.Ordinal); + void Add(string key, TreeEntry e) + { + if (!buckets.TryGetValue(key, out var list)) buckets[key] = list = []; + list.Add(e); + } + var byTop = files.GroupBy(f => f.Path.Contains('/') ? f.Path[..f.Path.IndexOf('/')] : ""); + foreach (var group in byTop) + { + var items = group.ToList(); + bool split = group.Key != "" && items.Count > WorldConstants.MaxArtifactsPerRoom; + foreach (var e in items) + { + if (!split) { Add(group.Key, e); continue; } + var rest = e.Path[(group.Key.Length + 1)..]; + Add(rest.Contains('/') ? $"{group.Key}/{rest[..rest.IndexOf('/')]}" : group.Key, e); + } + } + + var roomDirs = new List<(string Name, List Dirs, List Files)>(); + var commons = (Name: "Commons", Dirs: new List(), Files: new List()); + foreach (var (dir, list) in buckets) + { + if (dir == "" || list.Count < WorldConstants.MinFilesForOwnRoom) { commons.Dirs.Add(dir == "" ? "/" : dir); commons.Files.AddRange(list); } + else roomDirs.Add((dir, [dir], list)); + } + // Semantic compression: keep the biggest rooms, fold the tail into Commons. + var budget = WorldConstants.MaxRoomsPerBuilding - 1; + foreach (var extra in roomDirs.OrderByDescending(r => r.Files.Count).ThenBy(r => r.Name, StringComparer.Ordinal).Skip(budget).ToList()) + { + roomDirs.Remove(extra); + commons.Dirs.AddRange(extra.Dirs); + commons.Files.AddRange(extra.Files); + } + if (commons.Files.Count > 0) roomDirs.Add(commons); + + var rooms = new List(); + var doors = new List(); + int nextId = 0; + var lobby = new Room { Id = nextId++, Name = "Lobby", Purpose = RoomPurpose.Lobby, Floor = 0 }; + rooms.Add(lobby); + + int floors = Math.Max(1, (int)Math.Ceiling(roomDirs.Count / (double)roomsPerFloor)); + int prevStair = -1; + for (int f = 0; f < floors; f++) + { + var corridor = new Room { Id = nextId++, Name = $"Corridor {f}", Purpose = RoomPurpose.Corridor, Floor = f }; + var stair = new Room { Id = nextId++, Name = $"Stairwell {f}", Purpose = RoomPurpose.Stairwell, Floor = f }; + rooms.Add(corridor); rooms.Add(stair); + doors.Add(new Door(corridor.Id, stair.Id)); + if (f == 0) doors.Add(new Door(lobby.Id, corridor.Id)); + if (prevStair >= 0) doors.Add(new Door(prevStair, stair.Id)); + prevStair = stair.Id; + + foreach (var (name, dirs, list) in roomDirs.Skip(f * roomsPerFloor).Take(roomsPerFloor)) + { + var room = new Room + { + Id = nextId++, + Name = name, + Purpose = name == "Commons" ? RoomPurpose.Commons : PurposeFor(name), + Floor = f, + Directories = dirs, + FileCount = list.Count, + Artifacts = list + .OrderByDescending(e => KindFor(e.Path) == ArtifactKind.BuildStation) + .ThenByDescending(e => e.SizeBytes) + .ThenBy(e => e.Path, StringComparer.Ordinal) + .Take(WorldConstants.MaxArtifactsPerRoom) + .Select(e => new Artifact(e.Path, KindFor(e.Path), e.SizeBytes, LanguageFor(e.Path))) + .ToList(), + }; + rooms.Add(room); + doors.Add(new Door(corridor.Id, room.Id)); + } + } + return new RoomGraph(rooms, doors); + } +} diff --git a/src/Repoverse.Core/Generation/Seed.cs b/src/Repoverse.Core/Generation/Seed.cs new file mode 100644 index 0000000000000000000000000000000000000000..95cf499bdf8598eaf7184e535c3fecedb614d08c --- /dev/null +++ b/src/Repoverse.Core/Generation/Seed.cs @@ -0,0 +1,54 @@ +using System.Text; + +namespace Repoverse.Core.Generation; + +/// +/// Deterministic seed derivation (§8). string.GetHashCode is randomized per process, +/// so seeds use FNV-1a over UTF-8 followed by a SplitMix64 finalizer. +/// +public readonly record struct Seed(ulong Value) +{ + public Seed Derive(string scope) + { + var h = 14695981039346656037UL ^ Value; + foreach (var b in Encoding.UTF8.GetBytes(scope)) + { + h ^= b; + h *= 1099511628211UL; + } + return new Seed(Mix(h)); + } + + public SeededRandom Random() => new(Value); + + internal static ulong Mix(ulong z) + { + z += 0x9E3779B97F4A7C15UL; + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL; + return z ^ (z >> 31); + } + + public override string ToString() => Value.ToString("x16"); +} + +/// SplitMix64 stream. Same seed → same sequence on every platform and runtime. +public sealed class SeededRandom(ulong state) +{ + private ulong _state = state; + + public ulong NextULong() + { + _state += 0x9E3779B97F4A7C15UL; + return Seed.Mix(_state - 0x9E3779B97F4A7C15UL); + } + + /// Uniform integer in [min, maxExclusive). + public int Next(int min, int maxExclusive) + { + if (maxExclusive <= min) return min; + return min + (int)(NextULong() % (ulong)(maxExclusive - min)); + } + + public T Pick(IReadOnlyList items) => items[Next(0, items.Count)]; +} diff --git a/src/Repoverse.Core/Generation/WorldManifest.cs b/src/Repoverse.Core/Generation/WorldManifest.cs new file mode 100644 index 0000000000000000000000000000000000000000..de6bd1f24aa6340fbdb4cc7decf4d07b0bb77222 --- /dev/null +++ b/src/Repoverse.Core/Generation/WorldManifest.cs @@ -0,0 +1,57 @@ +using Repoverse.Core.Model; + +namespace Repoverse.Core.Generation; + +public enum ActivityLevel { Dormant, Low, Moderate, High } +public enum ConstructionState { Unreleased, Prerelease, Released, Archived } + +public readonly record struct PlotAddress(District District, int Slot); + +/// Voxel-space rectangle on the ground plane; Y is implied by . +public readonly record struct Footprint(int X, int Z, int Width, int Depth) +{ + public int MaxX => X + Width - 1; + public int MaxZ => Z + Depth - 1; +} + +/// What the world generator needs to build one repository's structure (§7, §9). +public sealed record BuildingDefinition +{ + public required RepoId Repo { get; init; } + public required string Description { get; init; } + public required Derived Category { get; init; } + public required Derived District { get; init; } + public required Derived Archetype { get; init; } + public required MaterialFamily Material { get; init; } + public required PlotAddress Plot { get; init; } + public required Footprint Footprint { get; init; } + public required int Floors { get; init; } + public required int RoomsPerSide { get; init; } + public required int RoomDepth { get; init; } + public required Derived Activity { get; init; } + public required Derived Construction { get; init; } + public required bool Landmark { get; init; } + /// Agent seats reserved for Part II's simulation, from contributor count. + public required int Population { get; init; } + public required string Seed { get; init; } + public required RoomGraph Interior { get; init; } + public int Height => Floors * WorldConstants.FloorHeight + 1; +} + +public sealed record DependencyEdge(RepoId From, RepoId To); + +public sealed record WorldManifest +{ + public const int CurrentSchema = 1; + public const string GeneratorVersion = "repoverse-gen/1"; + + public int SchemaVersion { get; init; } = CurrentSchema; + public string Generator { get; init; } = GeneratorVersion; + public required string WorldSeed { get; init; } + /// repo key → snapshot id each building was generated from. + public required IReadOnlyDictionary Snapshots { get; init; } + public required IReadOnlyList Buildings { get; init; } + public required IReadOnlyList Dependencies { get; init; } + + public BuildingDefinition? Find(RepoId id) => Buildings.FirstOrDefault(b => b.Repo.Key == id.Key); +} diff --git a/src/Repoverse.Core/Ingestion/GitHubIngest.cs b/src/Repoverse.Core/Ingestion/GitHubIngest.cs new file mode 100644 index 0000000000000000000000000000000000000000..01705831d4aafb74ee9a88a57b6c9d818e4d7b71 --- /dev/null +++ b/src/Repoverse.Core/Ingestion/GitHubIngest.cs @@ -0,0 +1,212 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Repoverse.Core.Model; + +namespace Repoverse.Core.Ingestion; + +public sealed class RateLimitedException(DateTimeOffset resetsAt) : Exception($"GitHub rate limit reached; resets at {resetsAt:u}.") +{ + public DateTimeOffset ResetsAt { get; } = resetsAt; +} + +public sealed record IngestFailure(string Repo, string Reason); + +public sealed record IngestResult(IReadOnlyList Repositories, IReadOnlyList Failures, bool RateLimited); + +/// +/// The only place Repoverse talks to GitHub (§25). Responses are cached on disk with their +/// ETag and re-requested conditionally, so unchanged data costs no rate-limit budget. +/// A repo that fails to ingest is reported and skipped; it never aborts the whole run. +/// +public sealed class GitHubIngest +{ + private readonly HttpClient _http; + private readonly string _cacheDir; + private readonly TimeProvider _clock; + + /// Read from the environment or a secret store by the caller; never persisted (§41). + public GitHubIngest(HttpClient http, string cacheDir, string? token, TimeProvider? clock = null) + { + _http = http; + _cacheDir = cacheDir; + _clock = clock ?? TimeProvider.System; + Directory.CreateDirectory(cacheDir); + _http.BaseAddress ??= new Uri("https://api.github.com/"); + _http.DefaultRequestHeaders.UserAgent.TryParseAdd("repoverse/1"); + _http.DefaultRequestHeaders.Accept.ParseAdd("application/vnd.github+json"); + if (!string.IsNullOrEmpty(token)) + _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + } + + public int RequestsSent { get; private set; } + public int NotModified { get; private set; } + + public async Task IngestOwnerAsync(string owner, bool includeForks = false, int? limit = null, CancellationToken ct = default) + { + List listing; + try + { + // /users/{owner}/repos works for both users and organisations. + listing = await GetPagedAsync($"users/{Uri.EscapeDataString(owner)}/repos?per_page=100&type=owner&sort=full_name", ct); + } + catch (RateLimitedException) + { + return new IngestResult([], [new IngestFailure(owner, "rate limited while listing repositories")], true); + } + + var repos = new List(); + var failures = new List(); + foreach (var r in listing.Where(r => includeForks || !r.GetProperty("fork").GetBoolean()).Take(limit ?? int.MaxValue)) + { + var fullName = r.GetProperty("full_name").GetString()!; + try + { + repos.Add(await IngestRepoAsync(r, ct)); + } + catch (RateLimitedException e) + { + failures.Add(new IngestFailure(fullName, e.Message)); + return new IngestResult(repos, failures, true); + } + catch (Exception e) when (e is HttpRequestException or JsonException or KeyNotFoundException or InvalidOperationException) + { + failures.Add(new IngestFailure(fullName, Redact(e.Message))); + } + } + return new IngestResult(repos, failures, false); + } + + private async Task IngestRepoAsync(JsonElement r, CancellationToken ct) + { + var id = RepoId.Parse(r.GetProperty("full_name").GetString()!); + var path = $"repos/{Uri.EscapeDataString(id.Owner)}/{Uri.EscapeDataString(id.Name)}"; + var branch = r.TryGetProperty("default_branch", out var db) && db.ValueKind == JsonValueKind.String ? db.GetString()! : "main"; + var since = _clock.GetUtcNow().AddDays(-WorldConstants.ActivityWindowDays).ToString("yyyy-MM-ddTHH:mm:ssZ"); + + var languages = (await GetAsync($"{path}/languages", ct)) is { ValueKind: JsonValueKind.Object } langs + ? langs.EnumerateObject().ToDictionary(p => p.Name, p => p.Value.GetInt64()) + : new Dictionary(); + + var tree = new List(); + // Empty repositories answer 409 here; treat as an empty tree. + if (await GetAsync($"{path}/git/trees/{Uri.EscapeDataString(branch)}?recursive=1", ct, allowStatus: HttpStatusCode.Conflict) is { ValueKind: JsonValueKind.Object } t + && t.TryGetProperty("tree", out var entries)) + { + foreach (var e in entries.EnumerateArray()) + { + var type = e.GetProperty("type").GetString(); + if (type is not ("blob" or "tree")) continue; // submodules ("commit") are dependencies, not rooms + tree.Add(new TreeEntry(e.GetProperty("path").GetString()!, + type == "tree" ? TreeEntryKind.Directory : TreeEntryKind.File, + e.TryGetProperty("size", out var s) ? s.GetInt64() : 0)); + } + } + + var releases = (await GetPagedAsync($"{path}/releases?per_page=100", ct, maxPages: 1)) + .Where(x => x.TryGetProperty("published_at", out var p) && p.ValueKind == JsonValueKind.String) + .Select(x => new Release(x.GetProperty("tag_name").GetString()!, x.GetProperty("published_at").GetDateTimeOffset(), x.GetProperty("prerelease").GetBoolean())) + .ToList(); + var commits = await GetPagedAsync($"{path}/commits?since={since}&per_page=100", ct, maxPages: 3, allowStatus: HttpStatusCode.Conflict); + var pulls = await GetPagedAsync($"{path}/pulls?state=open&per_page=100", ct, maxPages: 3); + var contributors = await GetPagedAsync($"{path}/contributors?per_page=100", ct, maxPages: 1, allowStatus: HttpStatusCode.NoContent); + + var pushed = r.TryGetProperty("pushed_at", out var pa) && pa.ValueKind == JsonValueKind.String ? pa.GetDateTimeOffset() : default; + return new CanonicalRepository + { + Id = id, + Description = r.TryGetProperty("description", out var d) && d.ValueKind == JsonValueKind.String ? d.GetString() : null, + PrimaryLanguage = r.TryGetProperty("language", out var l) && l.ValueKind == JsonValueKind.String ? l.GetString() : null, + Languages = languages, + Topics = r.TryGetProperty("topics", out var tp) ? tp.EnumerateArray().Select(x => x.GetString()!).ToList() : [], + SizeKb = r.GetProperty("size").GetInt64(), + Archived = r.GetProperty("archived").GetBoolean(), + Fork = r.GetProperty("fork").GetBoolean(), + DefaultBranch = branch, + CreatedAt = r.GetProperty("created_at").GetDateTimeOffset(), + PushedAt = pushed, + License = r.TryGetProperty("license", out var li) && li.ValueKind == JsonValueKind.Object ? li.GetProperty("spdx_id").GetString() : null, + // GitHub's open_issues_count includes PRs. + OpenIssues = Math.Max(0, r.GetProperty("open_issues_count").GetInt32() - pulls.Count), + OpenPullRequests = pulls.Count, + Contributors = contributors.Count, + CommitsLast90Days = commits.Count, + Releases = releases, + Tree = tree, + SnapshotId = $"{pushed:O}", + }; + } + + /// Follows rel="next" Link headers up to . + private async Task> GetPagedAsync(string url, CancellationToken ct, int maxPages = 50, HttpStatusCode? allowStatus = null) + { + var items = new List(); + string? next = url; + for (int page = 0; next != null && page < maxPages; page++) + { + var (json, link) = await SendAsync(next, ct, allowStatus); + if (json is { ValueKind: JsonValueKind.Array } arr) items.AddRange(arr.EnumerateArray()); + next = NextLink(link); + } + return items; + } + + private async Task GetAsync(string url, CancellationToken ct, HttpStatusCode? allowStatus = null) => + (await SendAsync(url, ct, allowStatus)).Json; + + private async Task<(JsonElement? Json, string? Link)> SendAsync(string url, CancellationToken ct, HttpStatusCode? allowStatus) + { + var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(url)))[..32]; + var bodyPath = Path.Combine(_cacheDir, key + ".json"); + var metaPath = Path.Combine(_cacheDir, key + ".meta"); + string[] meta = File.Exists(metaPath) ? await File.ReadAllLinesAsync(metaPath, ct) : []; + + using var req = new HttpRequestMessage(HttpMethod.Get, url); + if (meta.Length > 0 && meta[0].Length > 0 && File.Exists(bodyPath)) + req.Headers.TryAddWithoutValidation("If-None-Match", meta[0]); + + RequestsSent++; + using var res = await _http.SendAsync(req, ct); + if (res.StatusCode == HttpStatusCode.NotModified) + { + NotModified++; + return (Parse(await File.ReadAllTextAsync(bodyPath, ct)), meta.Length > 1 ? meta[1] : null); + } + if (res.StatusCode is HttpStatusCode.Forbidden or HttpStatusCode.TooManyRequests + && res.Headers.TryGetValues("x-ratelimit-remaining", out var rem) && rem.FirstOrDefault() == "0") + { + var reset = res.Headers.TryGetValues("x-ratelimit-reset", out var rs) && long.TryParse(rs.FirstOrDefault(), out var epoch) + ? DateTimeOffset.FromUnixTimeSeconds(epoch) : _clock.GetUtcNow().AddHours(1); + throw new RateLimitedException(reset); + } + if (allowStatus == res.StatusCode) return (null, null); + if (!res.IsSuccessStatusCode) + throw new HttpRequestException($"GET {url} → {(int)res.StatusCode} {res.ReasonPhrase}", null, res.StatusCode); + + var body = await res.Content.ReadAsStringAsync(ct); + var link = res.Headers.TryGetValues("Link", out var lv) ? string.Join(",", lv) : null; + await File.WriteAllTextAsync(bodyPath, body, ct); + await File.WriteAllLinesAsync(metaPath, [res.Headers.ETag?.ToString() ?? "", link ?? ""], ct); + return (Parse(body), link); + } + + private static JsonElement? Parse(string body) => string.IsNullOrWhiteSpace(body) ? null : JsonDocument.Parse(body).RootElement.Clone(); + + public static string? NextLink(string? link) + { + if (link == null) return null; + foreach (var part in link.Split(',')) + { + var bits = part.Split(';'); + if (bits.Length > 1 && bits[1..].Any(b => b.Trim() == "rel=\"next\"")) + return bits[0].Trim().TrimStart('<').TrimEnd('>'); + } + return null; + } + + /// Strips anything token-shaped from text that may end up in logs (§41). + public static string Redact(string text) => + System.Text.RegularExpressions.Regex.Replace(text, @"(gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|Bearer\s+\S+)", "[REDACTED]"); +} diff --git a/src/Repoverse.Core/Ingestion/LocalGitIngest.cs b/src/Repoverse.Core/Ingestion/LocalGitIngest.cs new file mode 100644 index 0000000000000000000000000000000000000000..c824b2f5ba1006d0b7d64a92e6c446e477aa3168 --- /dev/null +++ b/src/Repoverse.Core/Ingestion/LocalGitIngest.cs @@ -0,0 +1,113 @@ +using System.Diagnostics; +using Repoverse.Core.Generation; +using Repoverse.Core.Model; + +namespace Repoverse.Core.Ingestion; + +/// +/// Builds canonical repositories from a local git checkout, with no network. With +/// subprojects each top-level directory becomes its own repository, which turns +/// a monorepo into a multi-building district. +/// +public static class LocalGitIngest +{ + public static IReadOnlyList Ingest(string repoPath, string owner, bool subprojects) + { + var files = Git(repoPath, "ls-files", "-z").Split('\0', StringSplitOptions.RemoveEmptyEntries); + var head = Git(repoPath, "rev-parse", "HEAD").Trim(); + var since = $"--since={WorldConstants.ActivityWindowDays}.days"; + var tags = Git(repoPath, "for-each-ref", "--format=%(refname:short)|%(creatordate:iso-strict)", "refs/tags") + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Select(l => l.Split('|')) + .Select(p => new Release(p[0], DateTimeOffset.Parse(p[1]), p[0].Contains('-'))) + .ToList(); + + CanonicalRepository Make(string name, string prefix, IEnumerable paths) + { + var list = paths.ToList(); + var tree = new List(); + var dirs = new SortedSet(StringComparer.Ordinal); + foreach (var p in list) + { + var rel = p[prefix.Length..]; + var full = Path.Combine(repoPath, p); + tree.Add(new TreeEntry(rel, TreeEntryKind.File, File.Exists(full) ? new FileInfo(full).Length : 0)); + for (int i = rel.IndexOf('/'); i > 0; i = rel.IndexOf('/', i + 1)) dirs.Add(rel[..i]); + } + tree.AddRange(dirs.Select(d => new TreeEntry(d, TreeEntryKind.Directory, 0))); + + var languages = tree.Where(e => e.Kind == TreeEntryKind.File && !RoomGraphBuilder.IsIgnored(e.Path)) + .GroupBy(e => RoomGraphBuilder.LanguageFor(e.Path)) + .Where(g => g.Key is not ("Other" or "Markdown" or "JSON" or "TOML" or "YAML")) + .ToDictionary(g => g.Key, g => g.Sum(e => e.SizeBytes)); + var scope = prefix.Length == 0 ? "." : prefix.TrimEnd('/'); + var authors = Git(repoPath, "log", "--format=%ae", "--", scope).Split('\n', StringSplitOptions.RemoveEmptyEntries).Distinct().Count(); + var recent = Git(repoPath, "rev-list", "--count", since, "HEAD", "--", scope).Trim(); + var dates = Git(repoPath, "log", "--format=%cI", "--", scope).Split('\n', StringSplitOptions.RemoveEmptyEntries); + + return new CanonicalRepository + { + Id = new RepoId(owner, name), + Description = ReadmeSummary(repoPath, prefix, list), + PrimaryLanguage = languages.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key).Select(kv => kv.Key).FirstOrDefault(), + Languages = languages, + SizeKb = tree.Sum(e => e.SizeBytes) / 1024, + CreatedAt = dates.Length > 0 ? DateTimeOffset.Parse(dates[^1]) : default, + PushedAt = dates.Length > 0 ? DateTimeOffset.Parse(dates[0]) : default, + Contributors = authors, + CommitsLast90Days = int.TryParse(recent, out var n) ? n : 0, + Releases = prefix.Length == 0 ? tags : [], + Tree = tree, + SnapshotId = $"git:{head}", + }; + } + + if (!subprojects) + return [Make(new DirectoryInfo(repoPath).Name, "", files)]; + + return files.Where(f => f.Contains('/')) + .GroupBy(f => f[..f.IndexOf('/')]) + .Where(g => !g.Key.StartsWith('.')) + .OrderBy(g => g.Key, StringComparer.Ordinal) + .Select(g => Make(g.Key, g.Key + "/", g)) + .ToList(); + } + + private static string? ReadmeSummary(string root, string prefix, List files) + { + var readme = files.FirstOrDefault(f => string.Equals(f[prefix.Length..], "README.md", StringComparison.OrdinalIgnoreCase)) + ?? files.FirstOrDefault(f => f.EndsWith(".md", StringComparison.OrdinalIgnoreCase) && !f[prefix.Length..].Contains('/')); + if (readme == null) return null; + string? prose = null; + foreach (var line in File.ReadLines(Path.Combine(root, readme)).Take(60)) + { + var t = line.Trim().TrimStart('#', ' ', '*', '>').Trim(); + // Agent reports open with "KEY: value" headers; TASK/MISSION/DESCRIPTION carry the purpose. + var meta = MetadataLine.Match(t); + if (meta.Success) + { + if (meta.Groups[1].Value is "TASK" or "MISSION" or "DESCRIPTION" or "SUMMARY") return Clip(meta.Groups[2].Value); + continue; + } + if (prose == null && t.Length > 3 && !t.StartsWith("![") && !t.StartsWith('<') && !t.StartsWith("---") && !t.StartsWith("```")) + prose = t; + } + return prose == null ? null : Clip(prose); + } + + private static readonly System.Text.RegularExpressions.Regex MetadataLine = new(@"^([A-Z][A-Z_]+):\s*(.*)$"); + + private static string Clip(string s) => s.Length > 160 ? s[..160] : s; + + private static string Git(string dir, params string[] args) + { + var psi = new ProcessStartInfo("git") { WorkingDirectory = dir, RedirectStandardOutput = true, RedirectStandardError = true }; + foreach (var a in args) psi.ArgumentList.Add(a); + using var p = Process.Start(psi) ?? throw new InvalidOperationException("git is not available."); + var output = p.StandardOutput.ReadToEnd(); + var err = p.StandardError.ReadToEnd(); + p.WaitForExit(); + if (p.ExitCode != 0) throw new InvalidOperationException($"git {string.Join(' ', args)} failed: {err.Trim()}"); + return output; + } +} diff --git a/src/Repoverse.Core/Ingestion/SnapshotStore.cs b/src/Repoverse.Core/Ingestion/SnapshotStore.cs new file mode 100644 index 0000000000000000000000000000000000000000..e4b76b99751c8738edcc02eeb4d911a008bbf5ae --- /dev/null +++ b/src/Repoverse.Core/Ingestion/SnapshotStore.cs @@ -0,0 +1,63 @@ +using System.Text.Json; +using Repoverse.Core.Generation; +using Repoverse.Core.Model; + +namespace Repoverse.Core.Ingestion; + +public sealed record Snapshot +{ + public const int CurrentSchema = 1; + public int SchemaVersion { get; init; } = CurrentSchema; + public required DateTimeOffset TakenAt { get; init; } + public required string Source { get; init; } + public required IReadOnlyList Repositories { get; init; } + public IReadOnlyList Failures { get; init; } = []; +} + +/// +/// Last-known-good canonical state (§27). A refresh is merged per repository: repos that +/// failed this time keep their previous record and are reported stale, and an empty or +/// wholly failed refresh never replaces a populated snapshot. +/// +public static class SnapshotStore +{ + public static Snapshot? Load(string path) => + File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path), Json.Options) : null; + + public static void Save(string path, Snapshot snapshot) + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!); + var tmp = path + ".tmp"; + File.WriteAllText(tmp, JsonSerializer.Serialize(snapshot, Json.Options)); + File.Move(tmp, path, overwrite: true); // atomic replace: a crash never leaves half a snapshot + } + + public sealed record MergeResult(Snapshot Snapshot, IReadOnlyList Stale, bool KeptPrevious); + + public static MergeResult Merge(Snapshot? previous, IngestResult fresh, string source, DateTimeOffset now) + { + if (previous != null && fresh.Repositories.Count == 0) + return new MergeResult(previous with { Failures = fresh.Failures }, previous.Repositories.Select(r => r.Id.Key).ToList(), true); + + var failed = fresh.Failures.Select(f => f.Repo.ToLowerInvariant()).ToHashSet(); + var byKey = fresh.Repositories.ToDictionary(r => r.Id.Key); + var stale = new List(); + if (previous != null) + foreach (var old in previous.Repositories) + // Keep old records for repos that failed or were not reached (e.g. rate limit mid-run). + if (!byKey.ContainsKey(old.Id.Key) && (failed.Contains(old.Id.Key) || fresh.RateLimited)) + { + byKey[old.Id.Key] = old; + stale.Add(old.Id.Key); + } + + var merged = new Snapshot + { + TakenAt = now, + Source = source, + Repositories = byKey.Values.OrderBy(r => r.Id.Key, StringComparer.Ordinal).ToList(), + Failures = fresh.Failures, + }; + return new MergeResult(merged, stale, false); + } +} diff --git a/src/Repoverse.Core/Model/CanonicalRepository.cs b/src/Repoverse.Core/Model/CanonicalRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..2beadc99811300a51f8977049d2105ee9b077ad0 --- /dev/null +++ b/src/Repoverse.Core/Model/CanonicalRepository.cs @@ -0,0 +1,53 @@ +namespace Repoverse.Core.Model; + +/// Stable internal identity for a repository: lower-cased "owner/name". +public readonly record struct RepoId(string Owner, string Name) +{ + public string Key => $"{Owner.ToLowerInvariant()}/{Name.ToLowerInvariant()}"; + public override string ToString() => Key; + + public static RepoId Parse(string fullName) + { + var slash = fullName.IndexOf('/'); + if (slash <= 0 || slash == fullName.Length - 1) + throw new FormatException($"Expected 'owner/name', got '{fullName}'."); + return new RepoId(fullName[..slash], fullName[(slash + 1)..]); + } +} + +public enum TreeEntryKind { File, Directory } + +public sealed record TreeEntry(string Path, TreeEntryKind Kind, long SizeBytes); + +public sealed record Release(string Tag, DateTimeOffset PublishedAt, bool Prerelease); + +/// +/// GitHub-sourced facts about a repository. Nothing in here is inferred by Repoverse; +/// derived values live in with provenance. +/// +public sealed record CanonicalRepository +{ + public required RepoId Id { get; init; } + public string? Description { get; init; } + public string? PrimaryLanguage { get; init; } + /// Bytes of code per language, as reported by GitHub's languages endpoint. + public IReadOnlyDictionary Languages { get; init; } = new Dictionary(); + public IReadOnlyList Topics { get; init; } = []; + public long SizeKb { get; init; } + public bool Archived { get; init; } + public bool Fork { get; init; } + public string DefaultBranch { get; init; } = "main"; + public DateTimeOffset CreatedAt { get; init; } + public DateTimeOffset PushedAt { get; init; } + public string? License { get; init; } + public int OpenIssues { get; init; } + public int OpenPullRequests { get; init; } + public int Contributors { get; init; } + public int CommitsLast90Days { get; init; } + public IReadOnlyList Releases { get; init; } = []; + public IReadOnlyList Tree { get; init; } = []; + /// Other repos in the world this one depends on (from manifests / submodules). + public IReadOnlyList DependsOn { get; init; } = []; + /// Opaque version marker of the snapshot this record came from (e.g. pushed_at + ETag). + public string SnapshotId { get; init; } = ""; +} diff --git a/src/Repoverse.Core/Model/Derived.cs b/src/Repoverse.Core/Model/Derived.cs new file mode 100644 index 0000000000000000000000000000000000000000..1911a8e312f8e822a66518a51b040a2ef37fd4a2 --- /dev/null +++ b/src/Repoverse.Core/Model/Derived.cs @@ -0,0 +1,66 @@ +namespace Repoverse.Core.Model; + +/// Why a derived value has the value it has (§28). +public sealed record Provenance(string Rule, string Evidence) +{ + public static Provenance Override(string file) => new("manual-override", file); + public override string ToString() => $"{Rule}: {Evidence}"; +} + +public sealed record Derived(T Value, Provenance Why); + +public enum SemanticCategory +{ + SystemsInfrastructure, + OperatingSystem, + Compiler, + CryptographicCore, + FormalVerification, + Financial, + Simulation, + Hardware, + Quantum, + Training, + AgentSystem, + Database, + Networking, + WebInterface, + Documentation, + Experimental, +} + +public enum District +{ + Kernel, + Ai, + Financial, + FormalMethods, + HardwareIndustrial, + QuantumResearch, + Agent, + WebInterface, + Data, + Security, + Archive, + Experimental, + Infrastructure, + Training, +} + +public enum BuildingArchetype +{ + Foundry, // compilers, runtimes: transformation machinery + ControlTower, // OS / kernel / infrastructure + Vault, // crypto, security + ProofChamber, // formal methods + Exchange, // finance + Laboratory, // quantum, hardware, simulation + Library, // docs, training corpora + Studio, // web / interface + Warehouse, // databases + Relay, // networking + Commons, // agent systems + Workshop, // small / experimental +} + +public enum MaterialFamily { Stone, Concrete, Glass, Metal, Wood, Ceramic, Electronics, Laboratory, Archive, Security } diff --git a/src/Repoverse.Core/Persistence/SaveGame.cs b/src/Repoverse.Core/Persistence/SaveGame.cs new file mode 100644 index 0000000000000000000000000000000000000000..715d937e2869ca5cb4cd383de5508af279fb6ddd --- /dev/null +++ b/src/Repoverse.Core/Persistence/SaveGame.cs @@ -0,0 +1,96 @@ +using Repoverse.Core.Bridge; +using System.Text.Json; +using System.Text.Json.Nodes; +using Repoverse.Core.Generation; +using Repoverse.Core.Voxels; + +namespace Repoverse.Core.Persistence; + +public enum ViewMode { World, Code, Graph, Build, Cad, Audit, Agent } + +public sealed record Bookmark(string Label, string Uri); + +public sealed record PlayerState +{ + public double X { get; init; } + public double Y { get; init; } + public double Z { get; init; } + public double Yaw { get; init; } + public ViewMode Mode { get; init; } = ViewMode.World; + /// repoverse:// URI of the current selection, if any. + public string? Selection { get; init; } + public IReadOnlyList Bookmarks { get; init; } = []; +} + +public sealed record ChunkEdits(string Chunk, IReadOnlyDictionary Voxels); + +/// +/// Versioned save (§42, §43). Holds player state and user modifications only; +/// canonical and generated state are rebuilt from the snapshot and manifest. +/// +public sealed record SaveGame +{ + public const int CurrentSchema = 2; + + public int SchemaVersion { get; init; } = CurrentSchema; + public required string WorldSeed { get; init; } + public required string Generator { get; init; } + public required IReadOnlyDictionary Snapshots { get; init; } + public required PlayerState Player { get; init; } + public IReadOnlyList Edits { get; init; } = []; + public long SimulationTick { get; init; } + public IReadOnlyList Builders { get; init; } = []; + + public static SaveGame Capture(WorldManifest manifest, PlayerState player, WorldEdits edits, long tick) => new() + { + WorldSeed = manifest.WorldSeed, + Generator = manifest.Generator, + Snapshots = manifest.Snapshots, + Player = player, + Edits = edits.Snapshot().OrderBy(kv => kv.Key.ToString(), StringComparer.Ordinal) + .Select(kv => new ChunkEdits(kv.Key.ToString(), kv.Value)).ToList(), + SimulationTick = tick, + }; + + public void RestoreEdits(WorldEdits edits) => edits.Load(Edits.ToDictionary( + e => { var p = e.Chunk.Split(','); return new ChunkCoord(int.Parse(p[0]), int.Parse(p[1]), int.Parse(p[2])); }, + e => e.Voxels)); + + public static void Write(string path, SaveGame save) + { + var tmp = path + ".tmp"; + File.WriteAllText(tmp, JsonSerializer.Serialize(save, Json.Options)); + File.Move(tmp, path, overwrite: true); + } + + public static SaveGame Read(string path) => Parse(File.ReadAllText(path)); + + public static SaveGame Parse(string json) + { + var node = JsonNode.Parse(json)?.AsObject() ?? throw new InvalidDataException("Save file is empty."); + var version = node["schemaVersion"]?.GetValue() ?? 1; + if (version > CurrentSchema) + throw new InvalidDataException($"Save schema {version} is newer than this build supports ({CurrentSchema})."); + for (; version < CurrentSchema; version++) Migrations[version](node); + node["schemaVersion"] = CurrentSchema; + return node.Deserialize(Json.Options) ?? throw new InvalidDataException("Save file could not be read."); + } + + /// Migration from schema N to N+1, applied in order. + private static readonly Dictionary> Migrations = new() + { + // v1 kept "seed" and "cameraMode" and had no bookmarks or edits. + [1] = n => + { + if (n["seed"] is { } seed) { n.Remove("seed"); n["worldSeed"] = seed.GetValue(); } + n["generator"] ??= "repoverse-gen/0"; + n["snapshots"] ??= new JsonObject(); + if (n["player"] is JsonObject p) + { + if (p["cameraMode"] is { } mode) { p.Remove("cameraMode"); p["mode"] = mode.GetValue(); } + p["bookmarks"] ??= new JsonArray(); + } + n["edits"] ??= new JsonArray(); + }, + }; +} diff --git a/src/Repoverse.Core/Repoverse.Core.csproj b/src/Repoverse.Core/Repoverse.Core.csproj new file mode 100644 index 0000000000000000000000000000000000000000..fa71b7ae6a34999a3f96c40d9a0b870b311d11dd --- /dev/null +++ b/src/Repoverse.Core/Repoverse.Core.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/src/Repoverse.Core/RepoverseUri.cs b/src/Repoverse.Core/RepoverseUri.cs new file mode 100644 index 0000000000000000000000000000000000000000..ab16682765dc032198b2f9c7389c908d34d0ee53 --- /dev/null +++ b/src/Repoverse.Core/RepoverseUri.cs @@ -0,0 +1,78 @@ +using Repoverse.Core.Model; + +namespace Repoverse.Core; + +/// +/// Deep link into the world (§76). Grammar, version 1: +/// +/// repoverse://{owner}/{repo}[/{path}][#L{line}] +/// repoverse://{owner}/{repo}?room={id} +/// repoverse://@{x},{y},{z} +/// +/// Path segments are percent-encoded; the repo part matches GitHub's owner/name. +/// +public sealed record RepoverseUri +{ + public const string Scheme = "repoverse"; + + public RepoId? Repo { get; init; } + public string? Path { get; init; } + public int? Line { get; init; } + public int? Room { get; init; } + public (int X, int Y, int Z)? Location { get; init; } + + public static RepoverseUri Parse(string text) + { + const string prefix = Scheme + "://"; + if (!text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + throw new FormatException($"Not a {Scheme} URI: '{text}'."); + var rest = text[prefix.Length..]; + + if (rest.StartsWith('@')) + { + var p = rest[1..].Split(','); + if (p.Length != 3) throw new FormatException("Location must be @x,y,z."); + return new RepoverseUri { Location = (int.Parse(p[0]), int.Parse(p[1]), int.Parse(p[2])) }; + } + + int? line = null, room = null; + var hash = rest.IndexOf('#'); + if (hash >= 0) + { + var frag = rest[(hash + 1)..]; + if (!frag.StartsWith('L') || !int.TryParse(frag[1..], out var l)) throw new FormatException($"Bad fragment '#{frag}'."); + line = l; + rest = rest[..hash]; + } + var q = rest.IndexOf('?'); + if (q >= 0) + { + foreach (var kv in rest[(q + 1)..].Split('&')) + if (kv.StartsWith("room=") && int.TryParse(kv[5..], out var r)) room = r; + else throw new FormatException($"Unknown query '{kv}'."); + rest = rest[..q]; + } + + var parts = rest.Split('/', 3); + if (parts.Length < 2 || parts[0].Length == 0 || parts[1].Length == 0) throw new FormatException("Expected owner/repo."); + var path = parts.Length == 3 && parts[2].Length > 0 + ? string.Join('/', parts[2].Split('/').Select(Uri.UnescapeDataString)) + : null; + return new RepoverseUri { Repo = new RepoId(Uri.UnescapeDataString(parts[0]), Uri.UnescapeDataString(parts[1])), Path = path, Line = line, Room = room }; + } + + public override string ToString() + { + if (Location is var (x, y, z)) return $"{Scheme}://@{x},{y},{z}"; + var s = $"{Scheme}://{Uri.EscapeDataString(Repo!.Value.Owner)}/{Uri.EscapeDataString(Repo.Value.Name)}"; + if (Path != null) s += "/" + string.Join('/', Path.Split('/').Select(Uri.EscapeDataString)); + if (Room != null) s += $"?room={Room}"; + if (Line != null) s += $"#L{Line}"; + return s; + } + + /// External reference back to GitHub (§77); internal identity stays the RepoId. + public string? GitHubUrl(string branch = "HEAD") => Repo is not { } r ? null + : Path == null ? $"https://github.com/{r.Owner}/{r.Name}" + : $"https://github.com/{r.Owner}/{r.Name}/blob/{branch}/{Path}{(Line is { } l ? $"#L{l}" : "")}"; +} diff --git a/src/Repoverse.Core/Simulation/SimulationClock.cs b/src/Repoverse.Core/Simulation/SimulationClock.cs new file mode 100644 index 0000000000000000000000000000000000000000..dd01d226366bdc76160d644256a380ba3002201b --- /dev/null +++ b/src/Repoverse.Core/Simulation/SimulationClock.cs @@ -0,0 +1,58 @@ +namespace Repoverse.Core.Simulation; + +/// +/// Fixed-step simulation time, decoupled from render frames (§31). The host calls +/// with real frame time; the clock runs zero or more fixed ticks +/// scaled by , and fires scheduled actions in tick order. +/// +public sealed class SimulationClock(double ticksPerSecond = WorldConstants.SimulationTicksPerSecond, int maxTicksPerAdvance = 16) +{ + private readonly PriorityQueue<(long Tick, long Seq, Action Action), (long, long)> _scheduled = new(); + private double _accumulator; + private long _seq; + + public long Tick { get; private set; } + public double Speed { get; set; } = 1.0; + public bool Paused { get; set; } + public TimeSpan TickLength => TimeSpan.FromSeconds(1 / ticksPerSecond); + public TimeSpan SimulatedTime => TickLength * Tick; + + /// Raised once per fixed tick, after that tick's scheduled actions. + public event Action? Ticked; + + public void Schedule(long ticksFromNow, Action action) + { + ArgumentOutOfRangeException.ThrowIfNegative(ticksFromNow); + var at = Tick + ticksFromNow; + _scheduled.Enqueue((at, _seq, action), (at, _seq++)); + } + + /// Number of ticks run. + public int Advance(TimeSpan realElapsed) + { + if (Paused || Speed <= 0) return 0; + _accumulator += realElapsed.TotalSeconds * Speed * ticksPerSecond; + int ran = 0; + while (_accumulator >= 1 && ran < maxTicksPerAdvance) + { + _accumulator -= 1; + Step(); + ran++; + } + // Spiral-of-death guard: drop backlog rather than stall the frame. + if (ran == maxTicksPerAdvance) _accumulator = Math.Min(_accumulator, 1); + return ran; + } + + /// Runs exactly one tick regardless of pause; used for deterministic stepping. + public void Step() + { + Tick++; + while (_scheduled.TryPeek(out var item, out _) && item.Tick <= Tick) + { + _scheduled.Dequeue(); + item.Action(); + } + Ticked?.Invoke(Tick); + } +} diff --git a/src/Repoverse.Core/Simulation/WorldEvents.cs b/src/Repoverse.Core/Simulation/WorldEvents.cs new file mode 100644 index 0000000000000000000000000000000000000000..1d8a96a00f7c8493b2c3ce1883ce1b5ac546650a --- /dev/null +++ b/src/Repoverse.Core/Simulation/WorldEvents.cs @@ -0,0 +1,52 @@ +using Repoverse.Core.Model; + +namespace Repoverse.Core.Simulation; + +/// Typed world events (§32). Each carries the data needed to visualise it. +public abstract record WorldEvent(RepoId Repo); + +public sealed record RepositoryAdded(RepoId Repo) : WorldEvent(Repo); +public sealed record RepositoryRemoved(RepoId Repo) : WorldEvent(Repo); +public sealed record RepositoryArchived(RepoId Repo) : WorldEvent(Repo); +public sealed record RepositoryUnarchived(RepoId Repo) : WorldEvent(Repo); +public sealed record ReleasePublished(RepoId Repo, string Tag, bool Prerelease) : WorldEvent(Repo); +public sealed record IssuesChanged(RepoId Repo, int Before, int After) : WorldEvent(Repo); +public sealed record PullRequestsChanged(RepoId Repo, int Before, int After) : WorldEvent(Repo); +public sealed record ActivityChanged(RepoId Repo, int CommitsBefore, int CommitsAfter) : WorldEvent(Repo); +public sealed record StructureChanged(RepoId Repo, int FilesAdded, int FilesRemoved) : WorldEvent(Repo); + +/// Turns two canonical snapshots into the events that justify world changes (§26). +public static class SnapshotDiff +{ + public static IReadOnlyList Diff(IReadOnlyList before, IReadOnlyList after) + { + var old = before.ToDictionary(r => r.Id.Key); + var now = after.ToDictionary(r => r.Id.Key); + var events = new List(); + + foreach (var key in old.Keys.Union(now.Keys).OrderBy(k => k, StringComparer.Ordinal)) + { + old.TryGetValue(key, out var a); + now.TryGetValue(key, out var b); + if (a == null) { events.Add(new RepositoryAdded(b!.Id)); continue; } + if (b == null) { events.Add(new RepositoryRemoved(a.Id)); continue; } + + if (!a.Archived && b.Archived) events.Add(new RepositoryArchived(b.Id)); + if (a.Archived && !b.Archived) events.Add(new RepositoryUnarchived(b.Id)); + + var oldTags = a.Releases.Select(r => r.Tag).ToHashSet(); + foreach (var r in b.Releases.Where(r => !oldTags.Contains(r.Tag)).OrderBy(r => r.PublishedAt)) + events.Add(new ReleasePublished(b.Id, r.Tag, r.Prerelease)); + + if (a.OpenIssues != b.OpenIssues) events.Add(new IssuesChanged(b.Id, a.OpenIssues, b.OpenIssues)); + if (a.OpenPullRequests != b.OpenPullRequests) events.Add(new PullRequestsChanged(b.Id, a.OpenPullRequests, b.OpenPullRequests)); + if (a.CommitsLast90Days != b.CommitsLast90Days) events.Add(new ActivityChanged(b.Id, a.CommitsLast90Days, b.CommitsLast90Days)); + + var aFiles = a.Tree.Where(e => e.Kind == TreeEntryKind.File).Select(e => e.Path).ToHashSet(); + var bFiles = b.Tree.Where(e => e.Kind == TreeEntryKind.File).Select(e => e.Path).ToHashSet(); + int added = bFiles.Count(f => !aFiles.Contains(f)), removed = aFiles.Count(f => !bFiles.Contains(f)); + if (added + removed > 0) events.Add(new StructureChanged(b.Id, added, removed)); + } + return events; + } +} diff --git a/src/Repoverse.Core/Voxels/BuildingRasterizer.cs b/src/Repoverse.Core/Voxels/BuildingRasterizer.cs new file mode 100644 index 0000000000000000000000000000000000000000..3f06c6b15b2fe9b9634549899805c7f492306496 --- /dev/null +++ b/src/Repoverse.Core/Voxels/BuildingRasterizer.cs @@ -0,0 +1,167 @@ +using Repoverse.Core.Generation; +using Repoverse.Core.Model; +using static Repoverse.Core.WorldConstants; + +namespace Repoverse.Core.Voxels; + +/// An interactive object placed in the world, kept out of bulk voxel data (§12, §91). +public sealed record WorldObject( + string Id, + RepoId Repo, + int X, int Y, int Z, + ArtifactKind Kind, + string SourcePath, + int RoomId, + IReadOnlyList Actions); + +/// Where each room of a building ended up in voxel space, for navigation checks and cutaway. +public sealed record RoomPlacement(int RoomId, int Floor, int MinX, int MinZ, int MaxX, int MaxZ, int FloorY); + +/// +/// Turns a into voxels. Floor plan per storey: +/// a 3-wide corridor along X through the middle, rooms on both sides separated by +/// partitions, a door from every room to the corridor, a ladder shaft at the west end +/// of the corridor and the entrance on the east wall. +/// +/// z=D-1 ┌──────────┬──────────┐ +/// │ room │ room │ +/// ├───door───┴───door───┤ +/// │L corridor ⌂ entrance (floor 0) +/// ├───door───┬───door───┤ +/// │ room │ room │ +/// z=0 └──────────┴──────────┘ +/// +public static class BuildingRasterizer +{ + public delegate void Setter(int x, int y, int z, Voxel v); + + public sealed record Layout(IReadOnlyList Rooms, int CorridorZ, int LadderX, (int X, int Y, int Z) Entrance); + + public static Layout Plan(BuildingDefinition b) + { + var f = b.Footprint; + int cz = f.Z + b.RoomDepth + 2; // first corridor row + int slot = (f.Width - 2) / b.RoomsPerSide; + var rooms = new List(); + var byFloor = b.Interior.Rooms.Where(IsWorkRoom).GroupBy(r => r.Floor); + foreach (var floor in byFloor) + { + if (floor.Key >= b.Floors) continue; + int y = GroundLevel + floor.Key * FloorHeight; + int i = 0; + foreach (var room in floor) + { + int side = i % 2, col = i / 2; + int x0 = f.X + 1 + col * slot; + int x1 = col == b.RoomsPerSide - 1 ? f.MaxX - 1 : x0 + slot - 2; + var (z0, z1) = side == 0 ? (f.Z + 1, cz - 2) : (cz + 4, f.MaxZ - 1); + rooms.Add(new RoomPlacement(room.Id, floor.Key, x0, z0, x1, z1, y)); + i++; + } + } + return new Layout(rooms, cz, f.X + 1, (f.MaxX, GroundLevel + 1, cz + 1)); + } + + public static bool IsWorkRoom(Room r) => r.Purpose is not (RoomPurpose.Lobby or RoomPurpose.Corridor or RoomPurpose.Stairwell); + + public static void Rasterize(BuildingDefinition b, Setter set) + { + var f = b.Footprint; + var layout = Plan(b); + var m = b.Material; + int cz = layout.CorridorZ; + int top = GroundLevel + b.Floors * FloorHeight; + bool scaffold = b.Construction.Value == ConstructionState.Unreleased; + byte state = (byte)b.Activity.Value; + + // Foundation one voxel wider than the footprint. + for (int x = f.X - 1; x <= f.MaxX + 1; x++) + for (int z = f.Z - 1; z <= f.MaxZ + 1; z++) + set(x, GroundLevel - 1, z, new Voxel(BlockType.Foundation, MaterialFamily.Stone)); + + for (int floor = 0; floor < b.Floors; floor++) + { + int y0 = GroundLevel + floor * FloorHeight; + for (int x = f.X; x <= f.MaxX; x++) + for (int z = f.Z; z <= f.MaxZ; z++) + { + bool shaft = x == layout.LadderX && z == cz + 1; + set(x, y0, z, shaft && floor > 0 ? Voxel.Air : new Voxel(BlockType.Floor, m, state)); + bool edge = x == f.X || x == f.MaxX || z == f.Z || z == f.MaxZ; + for (int y = y0 + 1; y < y0 + FloorHeight; y++) + { + if (edge) + { + bool window = (y - y0) is 2 or 3 && (x + z) % 3 != 0 && !IsCorner(f, x, z); + set(x, y, z, new Voxel(window ? BlockType.Window : BlockType.Wall, m, state)); + } + else if (z == cz - 1 || z == cz + 3) + set(x, y, z, new Voxel(BlockType.Partition, m)); // corridor walls; doors carved below + else if (shaft) + set(x, y, z, new Voxel(BlockType.Ladder, MaterialFamily.Metal)); + } + } + + foreach (var room in layout.Rooms.Where(r => r.Floor == floor)) + { + // East partition between neighbouring rooms. + if (room.MaxX + 1 < f.MaxX) + for (int z = room.MinZ; z <= room.MaxZ; z++) + for (int y = y0 + 1; y < y0 + FloorHeight; y++) + set(room.MaxX + 1, y, z, new Voxel(BlockType.Partition, m)); + // Door into the corridor, centred on the room. + int dx = (room.MinX + room.MaxX) / 2; + int dz = room.MinZ < cz ? cz - 1 : cz + 3; + for (int y = y0 + 1; y <= y0 + DoorHeight; y++) + set(dx, y, dz, Voxel.Air); + } + // Ladder shaft continues through the ceiling of every storey but the top one. + if (floor < b.Floors - 1) + set(layout.LadderX, y0 + FloorHeight, cz + 1, Voxel.Air); + } + + // Entrance on the east wall at the corridor. + for (int y = GroundLevel + 1; y <= GroundLevel + DoorHeight; y++) + for (int z = cz; z <= cz + 2; z++) + set(f.MaxX, y, z, Voxel.Air); + + for (int x = f.X; x <= f.MaxX; x++) + for (int z = f.Z; z <= f.MaxZ; z++) + set(x, top, z, new Voxel(BlockType.Roof, m, state)); + + if (scaffold) // unreleased work reads as a construction site (§26) + for (int y = GroundLevel; y <= top; y += 2) + for (int x = f.X - 1; x <= f.MaxX + 1; x += 4) + set(x, y, f.Z - 1, new Voxel(BlockType.Scaffold, MaterialFamily.Metal)); + } + + private static bool IsCorner(Footprint f, int x, int z) => (x == f.X || x == f.MaxX) && (z == f.Z || z == f.MaxZ); + + /// Places each room's leading artifacts along its back wall as interactive objects. + public static IEnumerable Objects(BuildingDefinition b) + { + var layout = Plan(b); + var rooms = b.Interior.Rooms.ToDictionary(r => r.Id); + foreach (var p in layout.Rooms) + { + var room = rooms[p.RoomId]; + bool south = p.MinZ < layout.CorridorZ; + int z = south ? p.MinZ : p.MaxZ; + int x = p.MinX; + foreach (var a in room.Artifacts) + { + if (x > p.MaxX) break; + yield return new WorldObject($"{b.Repo.Key}:{a.Path}", b.Repo, x, p.FloorY + 1, z, a.Kind, a.Path, room.Id, ActionsFor(a.Kind)); + x++; + } + } + } + + public static IReadOnlyList ActionsFor(ArtifactKind k) => k switch + { + ArtifactKind.TestBench => ["inspect", "view-history", "test"], + ArtifactKind.BuildStation => ["inspect", "view-history", "build"], + ArtifactKind.ProofVault => ["inspect", "view-history", "verify"], + _ => ["inspect", "view-history", "open"], + }; +} diff --git a/src/Repoverse.Core/Voxels/ChunkStreamer.cs b/src/Repoverse.Core/Voxels/ChunkStreamer.cs new file mode 100644 index 0000000000000000000000000000000000000000..f66cf0e34695eee919f5c2ebd16c9fd8b4b053e1 --- /dev/null +++ b/src/Repoverse.Core/Voxels/ChunkStreamer.cs @@ -0,0 +1,96 @@ +using static Repoverse.Core.WorldConstants; + +namespace Repoverse.Core.Voxels; + +/// +/// Keeps the chunks around a focus point resident (§11, §13). Each +/// starts generation for the nearest missing chunks on the thread pool (bounded by +/// maxInFlight), collects finished ones, and unloads chunks beyond radius + hysteresis, +/// cancelling their pending work. Memory is bounded by the radius, not by world size. +/// +public sealed class ChunkStreamer(WorldGenerator generator, WorldEdits edits, int radius = StreamRadiusChunks, int maxInFlight = 8) +{ + private readonly Dictionary _loaded = new(); + private readonly Dictionary Task, CancellationTokenSource Cts)> _pending = new(); + private readonly object _statsGate = new(); + + public IReadOnlyDictionary Loaded => _loaded; + public int InFlight => _pending.Count; + public long ChunksGenerated { get; private set; } + public TimeSpan TotalGenerationTime { get; private set; } + + public sealed record Tick(int Started, int Completed, int Unloaded, int Cancelled); + + public Tick Update(int focusX, int focusZ) + { + var center = ChunkCoord.FromVoxel(focusX, GroundLevel, focusZ); + int completed = 0, unloaded = 0, cancelled = 0, started = 0; + + foreach (var (c, p) in _pending.Where(kv => kv.Value.Task.IsCompleted).ToList()) + { + _pending.Remove(c); + p.Cts.Dispose(); + if (p.Task.IsCompletedSuccessfully) { _loaded[c] = p.Task.Result; completed++; } + } + + int keep = radius + StreamHysteresisChunks; + foreach (var c in _loaded.Keys.Where(c => HorizontalDistance(c, center) > keep).ToList()) + { + _loaded.Remove(c); + unloaded++; + } + foreach (var (c, p) in _pending.Where(kv => HorizontalDistance(kv.Key, center) > keep).ToList()) + { + p.Cts.Cancel(); + _pending.Remove(c); + cancelled++; + } + + foreach (var c in Wanted(center)) + { + if (_pending.Count >= maxInFlight) break; + if (_loaded.ContainsKey(c) || _pending.ContainsKey(c)) continue; + var cts = new CancellationTokenSource(); + var token = cts.Token; + _pending[c] = (Task.Run(() => + { + var start = System.Diagnostics.Stopwatch.GetTimestamp(); + var chunk = generator.Generate(c, edits, token); + lock (_statsGate) { ChunksGenerated++; TotalGenerationTime += System.Diagnostics.Stopwatch.GetElapsedTime(start); } + return chunk; + }, token), cts); + started++; + } + return new Tick(started, completed, unloaded, cancelled); + } + + /// Runs updates until everything wanted around the focus is resident. + public async Task SettleAsync(int focusX, int focusZ, CancellationToken ct = default) + { + while (true) + { + Update(focusX, focusZ); + if (_pending.Count == 0) return; + await Task.WhenAny(_pending.Values.Select(p => p.Task)).WaitAsync(ct); + } + } + + /// Chunks within the radius, nearest first (§13 prioritisation). + public IEnumerable Wanted(ChunkCoord center) + { + var list = new List(); + for (int dx = -radius; dx <= radius; dx++) + for (int dz = -radius; dz <= radius; dz++) + for (int y = 0; y <= WorldGenerator.MaxChunkY; y++) + list.Add(new ChunkCoord(center.X + dx, y, center.Z + dz)); + return list.OrderBy(c => HorizontalDistance(c, center)).ThenBy(c => Math.Abs(c.Y - center.Y)).ThenBy(c => c.X).ThenBy(c => c.Z); + } + + private static int HorizontalDistance(ChunkCoord a, ChunkCoord b) => Math.Max(Math.Abs(a.X - b.X), Math.Abs(a.Z - b.Z)); + + /// World-space voxel lookup across loaded chunks; null when the chunk is not resident. + public Voxel? Sample(int x, int y, int z) => + _loaded.TryGetValue(ChunkCoord.FromVoxel(x, y, z), out var chunk) + ? chunk[x - chunk.Coord.OriginX, y - chunk.Coord.OriginY, z - chunk.Coord.OriginZ] + : null; +} diff --git a/src/Repoverse.Core/Voxels/GreedyMesher.cs b/src/Repoverse.Core/Voxels/GreedyMesher.cs new file mode 100644 index 0000000000000000000000000000000000000000..e2f8161f9bdaa3629ea1c709f526f75fea97fda8 --- /dev/null +++ b/src/Repoverse.Core/Voxels/GreedyMesher.cs @@ -0,0 +1,116 @@ +using System.Diagnostics; +using static Repoverse.Core.WorldConstants; + +namespace Repoverse.Core.Voxels; + +/// +/// An axis-aligned face rectangle. is the normal axis (0=X,1=Y,2=Z), +/// its direction; (U,V) span the other two axes in cyclic order. +/// Coordinates are chunk-local voxel corners. +/// +public readonly record struct Quad(int Axis, bool Positive, int Layer, int U, int V, int Width, int Height, ushort MeshKey); + +public sealed record ChunkMesh(ChunkCoord Coord, IReadOnlyList Quads, int VisibleFaces, TimeSpan BuildTime) +{ + public int Triangles => Quads.Count * 2; + /// One draw call per distinct material key (§14). + public int MaterialGroups => Quads.Select(q => q.MeshKey).Distinct().Count(); +} + +/// +/// Greedy meshing (§14): emits only faces between a visible voxel and a non-opaque +/// neighbour, then merges coplanar faces with the same material key into maximal rectangles. +/// Faces between identical see-through blocks (window next to window) are culled. +/// +public static class GreedyMesher +{ + private const int S = ChunkSize; + + /// World-space sampler for voxels outside the chunk; null result = not loaded, treated as air. + public static ChunkMesh Build(Chunk chunk, Func? neighbour = null) + { + var sw = Stopwatch.StartNew(); + var quads = new List(); + int faces = 0; + if (chunk.IsEmpty) return new ChunkMesh(chunk.Coord, quads, 0, sw.Elapsed); + + var mask = new ushort[S * S]; + Span pos = stackalloc int[3]; + Span npos = stackalloc int[3]; + + for (int axis = 0; axis < 3; axis++) + { + int u = (axis + 1) % 3, v = (axis + 2) % 3; + foreach (var positive in new[] { false, true }) + { + for (int layer = 0; layer < S; layer++) + { + // Build the face mask for this slice. 0 = no face; otherwise MeshKey + 1. + for (int j = 0; j < S; j++) + for (int i = 0; i < S; i++) + { + pos[axis] = layer; pos[u] = i; pos[v] = j; + var here = chunk[pos[0], pos[1], pos[2]]; + ushort m = 0; + if (!here.IsAir) + { + npos[0] = pos[0]; npos[1] = pos[1]; npos[2] = pos[2]; + npos[axis] += positive ? 1 : -1; + var there = Sample(chunk, npos, neighbour); + if (!there.IsOpaque && there.Type != here.Type) { m = (ushort)(here.MeshKey + 1); faces++; } + } + mask[j * S + i] = m; + } + + // Merge the mask into maximal rectangles. + for (int j = 0; j < S; j++) + for (int i = 0; i < S;) + { + var m = mask[j * S + i]; + if (m == 0) { i++; continue; } + int w = 1; + while (i + w < S && mask[j * S + i + w] == m) w++; + int h = 1; + for (; j + h < S; h++) + { + bool rowOk = true; + for (int k = 0; k < w && rowOk; k++) rowOk = mask[(j + h) * S + i + k] == m; + if (!rowOk) break; + } + for (int dy = 0; dy < h; dy++) + for (int dx = 0; dx < w; dx++) + mask[(j + dy) * S + i + dx] = 0; + quads.Add(new Quad(axis, positive, layer + (positive ? 1 : 0), i, j, w, h, (ushort)(m - 1))); + i += w; + } + } + } + } + return new ChunkMesh(chunk.Coord, quads, faces, sw.Elapsed); + } + + private static Voxel Sample(Chunk chunk, ReadOnlySpan p, Func? neighbour) + { + if ((uint)p[0] < S && (uint)p[1] < S && (uint)p[2] < S) return chunk[p[0], p[1], p[2]]; + if (neighbour == null) return Voxel.Air; + return neighbour(chunk.Coord.OriginX + p[0], chunk.Coord.OriginY + p[1], chunk.Coord.OriginZ + p[2]) ?? Voxel.Air; + } + + /// Quad corners in world space, counter-clockwise when viewed from the face normal. + public static (float X, float Y, float Z)[] Corners(ChunkCoord c, Quad q) + { + int u = (q.Axis + 1) % 3, v = (q.Axis + 2) % 3; + var o = new[] { c.OriginX, c.OriginY, c.OriginZ }; + (float, float, float) At(int du, int dv) + { + var p = new float[3]; + p[q.Axis] = o[q.Axis] + q.Layer; + p[u] = o[u] + q.U + du; + p[v] = o[v] + q.V + dv; + return (p[0], p[1], p[2]); + } + var quad = new[] { At(0, 0), At(q.Width, 0), At(q.Width, q.Height), At(0, q.Height) }; + if (!q.Positive) Array.Reverse(quad); + return quad; + } +} diff --git a/src/Repoverse.Core/Voxels/Voxel.cs b/src/Repoverse.Core/Voxels/Voxel.cs new file mode 100644 index 0000000000000000000000000000000000000000..c2bed89e93d87998d84fb9cad6b523bc35dba814 --- /dev/null +++ b/src/Repoverse.Core/Voxels/Voxel.cs @@ -0,0 +1,94 @@ +using Repoverse.Core.Model; + +namespace Repoverse.Core.Voxels; + +/// Structural role of a voxel. Interactive things are entities, not blocks (§12). +public enum BlockType : byte +{ + Air = 0, + Bedrock, + Soil, + Grass, + Road, + Sidewalk, + Foundation, + Wall, + Floor, + Roof, + Window, + Partition, + Ladder, + Scaffold, +} + +/// +/// 16-bit packed voxel: 8 bits block type, 4 bits material family, 4 bits state. +/// A 32³ chunk is 64 KiB. +/// +public readonly record struct Voxel(ushort Packed) +{ + public static readonly Voxel Air = default; + + public Voxel(BlockType type, MaterialFamily material = MaterialFamily.Concrete, byte state = 0) + : this((ushort)((byte)type | ((int)material & 0xF) << 8 | (state & 0xF) << 12)) { } + + public BlockType Type => (BlockType)(Packed & 0xFF); + public MaterialFamily Material => (MaterialFamily)((Packed >> 8) & 0xF); + public byte State => (byte)(Packed >> 12); + + public bool IsAir => Type == BlockType.Air; + /// Blocks the player/agents can move through. + public bool IsPassable => Type is BlockType.Air or BlockType.Ladder; + /// Hides faces of neighbours. Windows and ladders are see-through. + public bool IsOpaque => Type is not (BlockType.Air or BlockType.Window or BlockType.Ladder or BlockType.Scaffold); + + /// Key used to batch faces into one draw call (§14 material groups). + public ushort MeshKey => (ushort)(Packed & 0x0FFF); +} + +public readonly record struct ChunkCoord(int X, int Y, int Z) +{ + public static ChunkCoord FromVoxel(int x, int y, int z) => + new(FloorDiv(x), FloorDiv(y), FloorDiv(z)); + + public static int FloorDiv(int v) => v >= 0 ? v / WorldConstants.ChunkSize : (v + 1) / WorldConstants.ChunkSize - 1; + + public int OriginX => X * WorldConstants.ChunkSize; + public int OriginY => Y * WorldConstants.ChunkSize; + public int OriginZ => Z * WorldConstants.ChunkSize; + + public int ChebyshevDistance(ChunkCoord o) => Math.Max(Math.Abs(X - o.X), Math.Max(Math.Abs(Y - o.Y), Math.Abs(Z - o.Z))); + + public override string ToString() => $"{X},{Y},{Z}"; +} + +public sealed class Chunk +{ + private const int S = WorldConstants.ChunkSize; + private readonly ushort[] _voxels = new ushort[WorldConstants.ChunkVolume]; + + public Chunk(ChunkCoord coord) => Coord = coord; + + public ChunkCoord Coord { get; } + public int NonAirCount { get; private set; } + public bool IsEmpty => NonAirCount == 0; + + public static int Index(int x, int y, int z) => (y * S + z) * S + x; + + public Voxel this[int x, int y, int z] + { + get => new(_voxels[Index(x, y, z)]); + set + { + var i = Index(x, y, z); + var was = _voxels[i] & 0xFF; + var now = value.Packed & 0xFF; + if (was == 0 && now != 0) NonAirCount++; + else if (was != 0 && now == 0) NonAirCount--; + _voxels[i] = value.Packed; + } + } + + public Voxel GetIndex(int i) => new(_voxels[i]); + public ReadOnlySpan Raw => _voxels; +} diff --git a/src/Repoverse.Core/Voxels/WorldGenerator.cs b/src/Repoverse.Core/Voxels/WorldGenerator.cs new file mode 100644 index 0000000000000000000000000000000000000000..c7595556eb4312f09a6ec0c9fc5fe331de0956e8 --- /dev/null +++ b/src/Repoverse.Core/Voxels/WorldGenerator.cs @@ -0,0 +1,151 @@ +using Repoverse.Core.Generation; +using Repoverse.Core.Model; +using static Repoverse.Core.WorldConstants; + +namespace Repoverse.Core.Voxels; + +/// +/// Procedural base state for any chunk, derived only from the manifest (§11): terrain, +/// district road grid and buildings. Player edits are layered on top by . +/// +public sealed class WorldGenerator +{ + private readonly Dictionary<(int, int), BuildingDefinition> _byPlotCell = new(); + + public WorldGenerator(WorldManifest manifest) + { + Manifest = manifest; + foreach (var b in manifest.Buildings) + _byPlotCell[(Math.DivRem(b.Footprint.X, PlotSize).Quotient, Math.DivRem(b.Footprint.Z, PlotSize).Quotient)] = b; + } + + public WorldManifest Manifest { get; } + + /// Top chunk layer that can contain anything. + public static int MaxChunkY => ChunkCoord.FloorDiv(GroundLevel + MaxFloors * FloorHeight + 1); + + public Chunk Generate(ChunkCoord c, WorldEdits? edits = null, CancellationToken ct = default) + { + var chunk = new Chunk(c); + if (c.Y < 0 || c.Y > MaxChunkY) return chunk; + + for (int z = 0; z < ChunkSize; z++) + for (int x = 0; x < ChunkSize; x++) + { + int wx = c.OriginX + x, wz = c.OriginZ + z; + var surface = Surface(wx, wz); + for (int y = 0; y < ChunkSize; y++) + { + int wy = c.OriginY + y; + if (wy >= GroundLevel) break; + chunk[x, y, z] = wy == 0 ? new Voxel(BlockType.Bedrock, MaterialFamily.Stone) + : wy < GroundLevel - 1 ? new Voxel(BlockType.Soil, MaterialFamily.Stone) + : surface; + } + } + ct.ThrowIfCancellationRequested(); + + foreach (var b in BuildingsTouching(c)) + { + BuildingRasterizer.Rasterize(b, (x, y, z, v) => + { + int lx = x - c.OriginX, ly = y - c.OriginY, lz = z - c.OriginZ; + if ((uint)lx < ChunkSize && (uint)ly < ChunkSize && (uint)lz < ChunkSize) + chunk[lx, ly, lz] = v; + }); + ct.ThrowIfCancellationRequested(); + } + + edits?.ApplyTo(chunk); + return chunk; + } + + public IEnumerable BuildingsTouching(ChunkCoord c) + { + int x0 = Math.DivRem(c.OriginX - PlotSize, PlotSize).Quotient, x1 = Math.DivRem(c.OriginX + ChunkSize + PlotSize, PlotSize).Quotient; + int z0 = Math.DivRem(c.OriginZ - PlotSize, PlotSize).Quotient, z1 = Math.DivRem(c.OriginZ + ChunkSize + PlotSize, PlotSize).Quotient; + for (int px = x0; px <= x1; px++) + for (int pz = z0; pz <= z1; pz++) + if (_byPlotCell.TryGetValue((px, pz), out var b) && Overlaps(b, c)) + yield return b; + } + + private static bool Overlaps(BuildingDefinition b, ChunkCoord c) + { + // Rasterized extent: footprint plus one voxel of foundation/scaffold, ground-1 to roof. + int minY = GroundLevel - 1, maxY = GroundLevel + b.Floors * FloorHeight; + return b.Footprint.X - 1 < c.OriginX + ChunkSize && b.Footprint.MaxX + 1 >= c.OriginX + && b.Footprint.Z - 1 < c.OriginZ + ChunkSize && b.Footprint.MaxZ + 1 >= c.OriginZ + && minY < c.OriginY + ChunkSize && maxY >= c.OriginY; + } + + /// Ground block: roads ring every plot inside a district, grass elsewhere. + public static Voxel Surface(int wx, int wz) + { + const int stride = DistrictSpan + 2 * PlotSize; + int dx = Mod(wx, stride), dz = Mod(wz, stride); + if (dx >= DistrictSpan || dz >= DistrictSpan) + { + // Avenue between districts with a central road. + int ax = dx - DistrictSpan, az = dz - DistrictSpan; + bool onRoad = (dx >= DistrictSpan && Math.Abs(ax - PlotSize) < RoadWidth) || (dz >= DistrictSpan && Math.Abs(az - PlotSize) < RoadWidth); + return onRoad ? new Voxel(BlockType.Road, MaterialFamily.Concrete) : new Voxel(BlockType.Grass, MaterialFamily.Wood); + } + int px = dx % PlotSize, pz = dz % PlotSize; + int half = RoadWidth / 2; + bool road = px < half || px >= PlotSize - half || pz < half || pz >= PlotSize - half; + bool walk = !road && (px < RoadWidth || px >= PlotSize - RoadWidth || pz < RoadWidth || pz >= PlotSize - RoadWidth); + return road ? new Voxel(BlockType.Road, MaterialFamily.Concrete) + : walk ? new Voxel(BlockType.Sidewalk, MaterialFamily.Stone) + : new Voxel(BlockType.Grass, MaterialFamily.Wood); + } + + private static int Mod(int a, int m) => ((a % m) + m) % m; +} + +/// Persistent user modifications, stored separately from procedural state (§11, §22). +public sealed class WorldEdits +{ + private readonly Dictionary> _edits = new(); + private readonly object _gate = new(); + + public void Set(int x, int y, int z, Voxel v) + { + var c = ChunkCoord.FromVoxel(x, y, z); + lock (_gate) + { + if (!_edits.TryGetValue(c, out var map)) _edits[c] = map = new(); + map[Chunk.Index(x - c.OriginX, y - c.OriginY, z - c.OriginZ)] = v.Packed; + } + } + + public void ApplyTo(Chunk chunk) + { + lock (_gate) + { + if (!_edits.TryGetValue(chunk.Coord, out var map)) return; + foreach (var (i, packed) in map) + { + int x = i % ChunkSize, z = i / ChunkSize % ChunkSize, y = i / (ChunkSize * ChunkSize); + chunk[x, y, z] = new Voxel(packed); + } + } + } + + public int Count { get { lock (_gate) return _edits.Values.Sum(m => m.Count); } } + + public IReadOnlyDictionary> Snapshot() + { + lock (_gate) + return _edits.ToDictionary(kv => kv.Key, kv => (IReadOnlyDictionary)new Dictionary(kv.Value)); + } + + public void Load(IReadOnlyDictionary> data) + { + lock (_gate) + { + _edits.Clear(); + foreach (var (c, map) in data) _edits[c] = new Dictionary(map); + } + } +} diff --git a/src/Repoverse.Core/WorldConstants.cs b/src/Repoverse.Core/WorldConstants.cs new file mode 100644 index 0000000000000000000000000000000000000000..59d9049ff8e3bd197b5d67c20488e41b2dd0529e --- /dev/null +++ b/src/Repoverse.Core/WorldConstants.cs @@ -0,0 +1,42 @@ +namespace Repoverse.Core; + +/// All tunable world dimensions in one place (§64). Units are voxels unless stated. +public static class WorldConstants +{ + public const int ChunkSize = 32; + public const int ChunkVolume = ChunkSize * ChunkSize * ChunkSize; + + /// One building plot plus its surrounding road. + public const int PlotSize = 48; + public const int RoadWidth = 6; + public const int MaxFootprint = PlotSize - 2 * RoadWidth; // 36 + public const int MinFootprint = 10; + + /// Plots per district side; a district holds DistrictSide² buildings before overflow. + public const int DistrictSide = 12; + public const int DistrictSpan = DistrictSide * PlotSize; + public const int DistrictGridColumns = 4; + + public const int GroundLevel = 8; + public const int FloorHeight = 6; // 1 slab + 5 air + public const int MaxFloors = 12; + public const int CorridorWidth = 3; + public const int DoorHeight = 3; + + /// Directories with fewer files merge into a shared room (§78 semantic compression). + public const int MinFilesForOwnRoom = 2; + public const int MaxRoomsPerBuilding = 48; + public const int MaxArtifactsPerRoom = 24; + + public const int ActivityWindowDays = 90; + public const int StreamRadiusChunks = 6; + public const int StreamHysteresisChunks = 2; + + public const double SimulationTicksPerSecond = 10; + + public static readonly string[] IgnoredDirectories = + [ + "node_modules", "target", "bin", "obj", "build", "dist", "out", ".git", ".idea", ".vs", + "__pycache__", ".venv", "venv", "vendor", ".gradle", ".next", ".cache", "coverage", + ]; +} diff --git a/src/Repoverse.Sidecar/Program.cs b/src/Repoverse.Sidecar/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..7fcab969f73739b343c5096527fcdc719665fb17 --- /dev/null +++ b/src/Repoverse.Sidecar/Program.cs @@ -0,0 +1,67 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Repoverse.Core.Bridge; +using Repoverse.Core.Generation; +using Repoverse.Core.Persistence; + +// Local-only service. One Unreal client owns a session; reconnect starts a new stream. +var builder = WebApplication.CreateBuilder(args); +string Required(string name) => builder.Configuration[name] ?? throw new ArgumentException($"--{name} is required"); +var manifest = JsonSerializer.Deserialize(File.ReadAllText(Required("manifest")), Repoverse.Core.Generation.Json.Options) + ?? throw new InvalidDataException("Empty manifest"); +var token = Required("token"); +if (token.Length < 32) throw new ArgumentException("Use a random token of at least 32 characters."); +var tokenHash = SHA256.HashData(Encoding.UTF8.GetBytes(token)); +int port = int.Parse(builder.Configuration["port"] ?? "38473"); +if (port is < 1024 or > 65535) throw new ArgumentException("Invalid port"); +builder.WebHost.UseUrls($"http://127.0.0.1:{port}"); +builder.WebHost.ConfigureKestrel(k => k.Limits.MaxRequestBodySize = 64 * 1024); +builder.Services.ConfigureHttpJsonOptions(o => { + o.SerializerOptions.PropertyNamingPolicy = Repoverse.Core.Generation.Json.Options.PropertyNamingPolicy; + foreach (var c in Repoverse.Core.Generation.Json.Options.Converters) o.SerializerOptions.Converters.Add(c); +}); +var app = builder.Build(); +var gate = new SemaphoreSlim(1,1); +var session = new WorldSession(manifest); +var savePath = Path.GetFullPath(builder.Configuration["save"] ?? "repoverse-save.json"); +var sourceRoot = builder.Configuration["source-root"]; +var sourceRepo = builder.Configuration["source-repo"]; +var sources = sourceRoot == null || sourceRepo == null ? null : new LocalSourceReader(manifest, sourceRepo, sourceRoot); +app.Use(async (context,next) => { + // No CORS: web pages cannot use this service. Authenticate even read-only requests. + var supplied = SHA256.HashData(Encoding.UTF8.GetBytes(context.Request.Headers["X-Repoverse-Token"].ToString())); + if (context.Request.Headers.ContainsKey("Origin") || !CryptographicOperations.FixedTimeEquals(tokenHash,supplied)) { + context.Response.StatusCode=403; return; + } + await gate.WaitAsync(context.RequestAborted); + try { await next(context); } + catch (Exception e) when (e is ArgumentException or InvalidDataException or JsonException or FormatException or IOException) { + context.Response.StatusCode=400; + await context.Response.WriteAsJsonAsync(new { error=e.Message }); + } + finally { gate.Release(); } +}); +app.MapPost("/v1/session", () => { + var player = session.Player; + var saved = session.Capture(); + session = new WorldSession(manifest); session.Restore(saved); + return new { schemaVersion=1, worldSeed=manifest.WorldSeed, player, destinations=session.Destinations, objects=session.Objects(), builders=session.Builders }; +}); +app.MapPost("/v1/focus", (FocusRequest r) => {var p=session.Focus(r.X,r.Z);return new {p.Unloaded,p.Chunks,p.Remaining,p.Resident,builders=session.Builders};}); +app.MapPost("/v1/build", (BuilderPlan plan) => session.Build(plan)); +app.MapPost("/v1/save", (PlayerState player) => { + session.SetPlayer(player); + Directory.CreateDirectory(Path.GetDirectoryName(savePath)!); + SaveGame.Write(savePath,session.Capture()); + return new { saved=true }; +}); +app.MapPost("/v1/load", () => { session.Restore(SaveGame.Read(savePath)); return session.Player; }); +app.MapPost("/v1/edit", (EditRequest r) => {session.Edit(r.X,r.Y,r.Z,r.Packed);return new { edited=true };}); +app.MapGet("/v1/source", (string repo, string path, int offset = 0) => sources is null + ? Results.BadRequest(new { error="Local source inspection is not configured. Use --source-root and --source-repo." }) + : Results.Ok(sources.Read(repo,path,offset))); +app.MapGet("/v1/health", () => new { schemaVersion=1, resident=session.Resident }); +await app.RunAsync(); +record FocusRequest(double X,double Z); +record EditRequest(int X,int Y,int Z,ushort Packed); diff --git a/src/Repoverse.Sidecar/Repoverse.Sidecar.csproj b/src/Repoverse.Sidecar/Repoverse.Sidecar.csproj new file mode 100644 index 0000000000000000000000000000000000000000..a8045810e9344fb228b0d4a798711a357576a0d4 --- /dev/null +++ b/src/Repoverse.Sidecar/Repoverse.Sidecar.csproj @@ -0,0 +1,4 @@ + + net8.0enableenable + + diff --git a/tests/Repoverse.Core.Tests/BridgeTests.cs b/tests/Repoverse.Core.Tests/BridgeTests.cs new file mode 100644 index 0000000000000000000000000000000000000000..a47d0582b510e723ab29d3f841d6ccaba30bde1f --- /dev/null +++ b/tests/Repoverse.Core.Tests/BridgeTests.cs @@ -0,0 +1,90 @@ +using Repoverse.Core.Bridge; +using Repoverse.Core.Generation; +using Repoverse.Core.Persistence; +using Repoverse.Core.Voxels; + +namespace Repoverse.Core.Tests; + +public class BridgeTests +{ + private static WorldSession Session(int radius = 0) => new(ManifestBuilder.Build(TestRepos.Slice(),new Seed(42)),radius); + private static List Settle(WorldSession s,double x,double z) + { + var meshes=new List(); + for(int i=0;i<100;i++) { + var p=s.Focus(x,z); meshes.AddRange(p.Chunks); + if(p.Remaining==0)return meshes; + } + throw new Exception("Stream did not settle"); + } + [Fact] public void Streaming_is_bounded_and_unloads_old_meshes() + { + var s=Session(); var first=Settle(s,0,0); + Assert.NotEmpty(first); + Assert.Equal(WorldGenerator.MaxChunkY+1,s.Resident); + var moved=s.Focus(1000,1000); + Assert.Equal(first.Select(m=>m.Id).Distinct().Order(),moved.Unloaded.Order()); + for(int i=0;i<20;i++) { + Settle(s,i*500,i*500); + Assert.InRange(s.Resident,1,WorldGenerator.MaxChunkY+1); + } + } + [Fact] public void Edits_remesh_and_survive_unload_and_save_restore() + { + var s=Session();Settle(s,0,0); + s.Edit(2,15,2,new Voxel(BlockType.Wall).Packed); + Assert.NotEmpty(s.Focus(0,0).Chunks); + s.SetPlayer(new PlayerState {X=2,Y=16,Z=2,Selection="repoverse://snapkitty/site"}); + var saved=s.Capture(); + Settle(s,2000,2000);Settle(s,0,0); + Assert.Equal(BlockType.Wall,s.Sample(2,15,2)!.Value.Type); + var restored=Session();restored.Restore(saved);Settle(restored,0,0); + Assert.Equal(saved.Player,restored.Player); + Assert.Equal(BlockType.Wall,restored.Sample(2,15,2)!.Value.Type); + Assert.Throws(()=>restored.Restore(saved with {WorldSeed="other"})); + } + [Fact] public void Mesh_packets_have_outward_core_winding_and_passable_ladders() + { + var c=new Chunk(new(0,0,0));c[1,1,1]=new Voxel(BlockType.Wall);c[4,1,1]=new Voxel(BlockType.Ladder); + var packet=WorldSession.Encode(GreedyMesher.Build(c)); + Assert.Contains(packet.Sections,s=>!s.Collision && (s.Key&255)==(int)BlockType.Ladder); + var wall=packet.Sections.Single(s=>(s.Key&255)==(int)BlockType.Wall); + Assert.Equal(24,wall.Vertices.Length);Assert.Equal(36,wall.Indices.Length); + for(int i=0;i0); + } + } + [Fact] public void Adjacent_arrivals_remesh_boundaries() + { + var s=Session(1); var seen=new Dictionary(); + for(int i=0;i<100;i++) { + var p=s.Focus(0,0,1); + foreach(var c in p.Chunks)seen[c.Id]=seen.GetValueOrDefault(c.Id)+1; + if(p.Remaining==0)break; + } + Assert.Contains(seen.Values,n=>n>1); + Assert.Equal(9*(WorldGenerator.MaxChunkY+1),s.Resident); + } + [Fact] public void Invalid_coordinates_are_rejected() + { + var s=Session();Assert.Throws(()=>s.Focus(double.NaN,0)); + Assert.Throws(()=>s.SetPlayer(new PlayerState{Y=double.PositiveInfinity})); + Assert.Throws(()=>s.Edit(0,0,0,0)); + } + [Fact] public void Source_is_paged_and_restricted_to_manifest_artifacts() + { + var dir=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString());Directory.CreateDirectory(dir); + try { + var manifest=ManifestBuilder.Build([TestRepos.Make("source",files:["README.md","../escape.txt"])],new Seed(1)); + File.WriteAllLines(Path.Combine(dir,"README.md"),Enumerable.Range(0,80).Select(i=>$"line {i}")); + var source=new LocalSourceReader(manifest,"snapkitty/source",dir); + var page=source.Read("snapkitty/source","README.md",32); + Assert.Equal("line 32",page.Lines[0]);Assert.Equal(32,page.Lines.Length);Assert.True(page.HasMore); + Assert.Throws(()=>source.Read("someone/else","README.md",0)); + Assert.Throws(()=>source.Read("snapkitty/source",".git/config",0)); + Assert.Throws(()=>source.Read("snapkitty/source","../escape.txt",0)); + } finally {Directory.Delete(dir,true);} + } +} diff --git a/tests/Repoverse.Core.Tests/BuilderTests.cs b/tests/Repoverse.Core.Tests/BuilderTests.cs new file mode 100644 index 0000000000000000000000000000000000000000..e35e026d84f8077b8e8e23d3f1de09b6a799454a --- /dev/null +++ b/tests/Repoverse.Core.Tests/BuilderTests.cs @@ -0,0 +1,15 @@ +using System.Text.Json; +using Repoverse.Core.Bridge; +using Repoverse.Core.Generation; +using Repoverse.Core.Persistence; +namespace Repoverse.Core.Tests; +public class BuilderTests { + static BuilderPlan Plan(string operations)=>JsonSerializer.Deserialize("{\"schemaVersion\":1,\"id\":\"test\",\"actor\":\"twin-builder\",\"units\":\"voxel\",\"origin\":{\"x\":0,\"y\":9,\"z\":0},\"operations\":"+operations+"}",Repoverse.Core.Generation.Json.Options)!; + static WorldSession Session()=>new(ManifestBuilder.Build(TestRepos.Slice(),new Seed(42)),0); + [Fact] public void Build_survives_save_and_reconnect(){var s=Session();var p=Plan("[{\"name\":\"add_box\",\"args\":{\"width\":2,\"height\":2,\"depth\":2,\"y\":1}}]");var b=s.Build(p);Assert.Equal(8,b.Voxels);var saved=SaveGame.Parse(JsonSerializer.Serialize(s.Capture(),Repoverse.Core.Generation.Json.Options));var restored=Session();restored.Restore(saved);Assert.Equal(b,Assert.Single(restored.Builders));Assert.Equal(s.Capture().Edits.Count,restored.Capture().Edits.Count);restored.Focus(0,0);Assert.False(restored.Sample(0,9,0)!.Value.IsAir);} + [Fact] public void Invalid_later_operation_does_not_partially_edit(){var s=Session();Assert.Throws(()=>s.Build(Plan("[{\"name\":\"add_box\",\"args\":{}},{\"name\":\"eval\",\"args\":{}}]")));Assert.Empty(s.Capture().Edits);Assert.Empty(s.Builders);} + [Theory] [InlineData("add_sphere")] [InlineData("add_cylinder")] [InlineData("add_cone")] [InlineData("add_torus")] + public void Solid_shapes_rasterize(string shape){var p=Plan("[{\"name\":\""+shape+"\",\"args\":{\"radius\":3,\"tube\":1,\"height\":4,\"y\":5}}]");Assert.NotEmpty(BuilderRasterizer.Rasterize(p));} + [Theory] [InlineData("{\"width\":\"bad\"}")] [InlineData("{\"color\":12}")] [InlineData("{\"width\":64,\"height\":64,\"depth\":64,\"y\":40}")] [InlineData("{\"y\":-20}")] + public void Invalid_or_oversized_builds_rejected(string args){Assert.Throws(()=>BuilderRasterizer.Rasterize(Plan("[{\"name\":\"add_box\",\"args\":"+args+"}]")));} +} diff --git a/tests/Repoverse.Core.Tests/GenerationTests.cs b/tests/Repoverse.Core.Tests/GenerationTests.cs new file mode 100644 index 0000000000000000000000000000000000000000..1d9ebf7f39068af8e3fe5ce48164b626756e2603 --- /dev/null +++ b/tests/Repoverse.Core.Tests/GenerationTests.cs @@ -0,0 +1,138 @@ +using System.Text.Json; +using Repoverse.Core.Generation; +using Repoverse.Core.Model; + +namespace Repoverse.Core.Tests; + +public class GenerationTests +{ + private static readonly Seed WorldSeed = new(42); + + [Fact] + public void Same_inputs_produce_identical_manifest_json() + { + var a = JsonSerializer.Serialize(ManifestBuilder.Build(TestRepos.Slice(), WorldSeed), Json.Options); + var b = JsonSerializer.Serialize(ManifestBuilder.Build(TestRepos.Slice().Reverse().ToList(), WorldSeed), Json.Options); + Assert.Equal(a, b); + } + + [Fact] + public void Different_world_seed_changes_building_seeds_but_not_layout() + { + var a = ManifestBuilder.Build(TestRepos.Slice(), WorldSeed); + var b = ManifestBuilder.Build(TestRepos.Slice(), new Seed(43)); + Assert.All(a.Buildings.Zip(b.Buildings), p => + { + Assert.NotEqual(p.First.Seed, p.Second.Seed); + Assert.Equal(p.First.Footprint, p.Second.Footprint); + }); + } + + [Theory] + [InlineData("ortho32", SemanticCategory.OperatingSystem, District.Kernel)] + [InlineData("fpga-lab", SemanticCategory.Hardware, District.HardwareIndustrial)] + [InlineData("tiny-llm", SemanticCategory.AgentSystem, District.Agent)] + [InlineData("proofs", SemanticCategory.FormalVerification, District.FormalMethods)] + [InlineData("ledger", SemanticCategory.Financial, District.Financial)] + [InlineData("site", SemanticCategory.WebInterface, District.WebInterface)] + [InlineData("corpus", SemanticCategory.Training, District.Training)] + [InlineData("deployer", SemanticCategory.SystemsInfrastructure, District.Infrastructure)] + [InlineData("wasmc", SemanticCategory.Compiler, District.Kernel)] + [InlineData("scratch", SemanticCategory.Experimental, District.Experimental)] + public void Slice_repositories_classify_into_distinct_districts(string name, SemanticCategory category, District district) + { + var b = ManifestBuilder.Build(TestRepos.Slice(), WorldSeed).Buildings.Single(x => x.Repo.Name == name); + Assert.Equal(category, b.Category.Value); + Assert.Equal(district, b.District.Value); + Assert.False(string.IsNullOrEmpty(b.Category.Why.Evidence)); + } + + [Fact] + public void Purpose_outweighs_language() + { + // §80: a Rust web server is a network system, not a foundry. + var repo = TestRepos.Make("api-gw", "HTTP proxy and RPC gateway", "Rust"); + Assert.Equal(SemanticCategory.Networking, Classifier.Classify(repo).Value); + } + + [Theory] + [InlineData("Guppy-to-IR translation with linear type enforcement", SemanticCategory.Compiler)] + [InlineData("A firmware build", SemanticCategory.Hardware)] + [InlineData("Quick fixes for the build", SemanticCategory.Experimental)] // "ui" inside "build"/"quick" is not a word + [InlineData("Theorems about schedulers", SemanticCategory.FormalVerification)] + public void Keywords_match_whole_words(string description, SemanticCategory expected) => + Assert.Equal(expected, Classifier.Classify(TestRepos.Make("x", description, files: ["a.bin"])).Value); + + [Fact] + public void Archived_repositories_move_to_the_archive_district() + { + var repos = new[] { TestRepos.Make("old-kernel", "kernel", "C", archived: true) }; + var b = ManifestBuilder.Build(repos, WorldSeed).Buildings[0]; + Assert.Equal(District.Archive, b.District.Value); + Assert.Equal(ConstructionState.Archived, b.Construction.Value); + } + + [Fact] + public void Overrides_win_and_are_recorded_as_provenance() + { + var overrides = new Overrides(new Dictionary + { + ["snapkitty/scratch"] = new() { Category = SemanticCategory.Quantum, Landmark = true }, + }, "overrides.json"); + var b = ManifestBuilder.Build(TestRepos.Slice(), WorldSeed, overrides).Buildings.Single(x => x.Repo.Name == "scratch"); + Assert.Equal(SemanticCategory.Quantum, b.Category.Value); + Assert.Equal("manual-override", b.Category.Why.Rule); + Assert.True(b.Landmark); + } + + [Fact] + public void Existing_buildings_keep_their_plots_when_repositories_are_added() + { + var first = ManifestBuilder.Build(TestRepos.Slice(), WorldSeed); + // "aaa-kernel" sorts first and would take slot 0 of the Kernel district in a fresh build. + var grown = TestRepos.Slice().Append(TestRepos.Make("aaa-kernel", "kernel hypervisor", "C")).ToList(); + var second = ManifestBuilder.Build(grown, WorldSeed, previous: first); + + foreach (var b in first.Buildings) + Assert.Equal(b.Footprint, second.Find(b.Repo)!.Footprint); + var newcomer = second.Buildings.Single(b => b.Repo.Name == "aaa-kernel"); + Assert.DoesNotContain(first.Buildings, b => b.Plot == newcomer.Plot); + } + + [Fact] + public void Buildings_never_overlap() + { + var repos = Enumerable.Range(0, 60).Select(i => TestRepos.Make($"k{i:00}", "kernel", "C")).ToList(); + var m = ManifestBuilder.Build(repos, WorldSeed); + var fps = m.Buildings.Select(b => b.Footprint).ToList(); + for (int i = 0; i < fps.Count; i++) + for (int j = i + 1; j < fps.Count; j++) + Assert.False(fps[i].X <= fps[j].MaxX && fps[j].X <= fps[i].MaxX && fps[i].Z <= fps[j].MaxZ && fps[j].Z <= fps[i].MaxZ, + $"{m.Buildings[i].Repo} overlaps {m.Buildings[j].Repo}"); + } + + [Fact] + public void Floors_follow_module_structure_not_raw_size() + { + var flat = TestRepos.Make("flat", "tool", "Go", Enumerable.Range(0, 40).Select(i => $"f{i}.go")); + var modular = TestRepos.Make("modular", "tool", "Go", Enumerable.Range(0, 40).Select(i => $"m{i % 20}/f{i}.go")); + var m = ManifestBuilder.Build([flat, modular], WorldSeed); + Assert.True(m.Find(modular.Id)!.Interior.Rooms.Count > m.Find(flat.Id)!.Interior.Rooms.Count); + } + + [Fact] + public void Dependencies_only_link_repositories_in_the_world() + { + var a = TestRepos.Make("a", dependsOn: [new RepoId("snapkitty", "b"), new RepoId("elsewhere", "x")]); + var b = TestRepos.Make("b"); + var edge = Assert.Single(ManifestBuilder.Build([a, b], WorldSeed).Dependencies); + Assert.Equal(("snapkitty/a", "snapkitty/b"), (edge.From.Key, edge.To.Key)); + } + + [Fact] + public void Duplicate_repositories_are_rejected() + { + var r = TestRepos.Make("dup"); + Assert.Throws(() => ManifestBuilder.Build([r, r], WorldSeed)); + } +} diff --git a/tests/Repoverse.Core.Tests/IngestionTests.cs b/tests/Repoverse.Core.Tests/IngestionTests.cs new file mode 100644 index 0000000000000000000000000000000000000000..aa9fd0ae3781f38c7a4982a14460507bd83a23eb --- /dev/null +++ b/tests/Repoverse.Core.Tests/IngestionTests.cs @@ -0,0 +1,190 @@ +using System.Net; +using System.Text; +using Repoverse.Core.Ingestion; + +namespace Repoverse.Core.Tests; + +public class IngestionTests : IDisposable +{ + private readonly string _cache = Path.Combine(Path.GetTempPath(), "repoverse-test-" + Guid.NewGuid().ToString("N")); + public void Dispose() { if (Directory.Exists(_cache)) Directory.Delete(_cache, true); } + + /// Scripted GitHub: routes by path prefix, supports ETags and a rate-limit switch. + private sealed class FakeGitHub : HttpMessageHandler + { + public readonly Dictionary> Routes = new(); + public readonly List Seen = []; + public bool RateLimited; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + var path = request.RequestUri!.PathAndQuery; + Seen.Add(path); + if (RateLimited) + { + var r = new HttpResponseMessage(HttpStatusCode.Forbidden); + r.Headers.Add("x-ratelimit-remaining", "0"); + r.Headers.Add("x-ratelimit-reset", "2000000000"); + return Task.FromResult(r); + } + var route = Routes.Where(kv => path.StartsWith(kv.Key)).OrderByDescending(kv => kv.Key.Length).Select(kv => kv.Value).FirstOrDefault(); + return Task.FromResult(route?.Invoke(request) ?? new HttpResponseMessage(HttpStatusCode.NotFound)); + } + } + + private static HttpResponseMessage Json(string body, string? etag = null, string? link = null) + { + var r = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; + if (etag != null) r.Headers.ETag = new System.Net.Http.Headers.EntityTagHeaderValue(etag); + if (link != null) r.Headers.Add("Link", link); + return r; + } + + private static string RepoJson(string name, bool fork = false) => $$""" + {"full_name":"snapkitty/{{name}}","description":"{{name}} compiler","language":"Rust","topics":["wasm"], + "size":120,"archived":false,"fork":{{(fork ? "true" : "false")}},"default_branch":"main", + "created_at":"2024-01-01T00:00:00Z","pushed_at":"2026-09-01T00:00:00Z","license":{"spdx_id":"MIT"},"open_issues_count":3} + """; + + private FakeGitHub Standard() + { + var gh = new FakeGitHub(); + gh.Routes["/users/snapkitty/repos?per_page=100"] = _ => Json($"[{RepoJson("alpha")},{RepoJson("forked", fork: true)}]", + link: "; rel=\"next\", ; rel=\"last\""); + gh.Routes["/users/snapkitty/repos?page=2"] = _ => Json($"[{RepoJson("beta")}]"); + foreach (var n in new[] { "alpha", "beta" }) + { + gh.Routes[$"/repos/snapkitty/{n}/languages"] = _ => Json("""{"Rust":9000,"Shell":100}"""); + gh.Routes[$"/repos/snapkitty/{n}/git/trees/"] = _ => Json("""{"tree":[{"path":"src","type":"tree"},{"path":"src/lower.rs","type":"blob","size":900},{"path":"vendor/x","type":"commit"}]}"""); + gh.Routes[$"/repos/snapkitty/{n}/releases"] = _ => Json("""[{"tag_name":"v1.0.0","published_at":"2026-08-01T00:00:00Z","prerelease":false},{"tag_name":"draft","published_at":null,"prerelease":false}]"""); + gh.Routes[$"/repos/snapkitty/{n}/commits"] = _ => Json("""[{},{},{},{}]"""); + gh.Routes[$"/repos/snapkitty/{n}/pulls"] = _ => Json("""[{}]"""); + gh.Routes[$"/repos/snapkitty/{n}/contributors"] = _ => Json("""[{},{}]"""); + } + return gh; + } + + [Fact] + public async Task Ingests_all_pages_skips_forks_and_maps_fields() + { + var gh = Standard(); + var ingest = new GitHubIngest(new HttpClient(gh), _cache, token: null); + var result = await ingest.IngestOwnerAsync("snapkitty"); + + Assert.Empty(result.Failures); + Assert.Equal(["alpha", "beta"], result.Repositories.Select(r => r.Id.Name)); + var a = result.Repositories[0]; + Assert.Equal(9000, a.Languages["Rust"]); + Assert.Equal(2, a.OpenIssues); // 3 minus 1 open PR + Assert.Equal(1, a.OpenPullRequests); + Assert.Equal(4, a.CommitsLast90Days); + Assert.Equal(2, a.Contributors); + Assert.Equal("MIT", a.License); + Assert.Single(a.Releases); // unpublished draft ignored + Assert.Equal(2, a.Tree.Count); // submodule entry excluded + } + + [Fact] + public async Task One_failing_repository_does_not_stop_the_rest() + { + var gh = Standard(); + gh.Routes["/repos/snapkitty/alpha/languages"] = _ => new HttpResponseMessage(HttpStatusCode.InternalServerError); + var result = await new GitHubIngest(new HttpClient(gh), _cache, null).IngestOwnerAsync("snapkitty"); + Assert.Equal("snapkitty/alpha", Assert.Single(result.Failures).Repo); + Assert.Equal("beta", Assert.Single(result.Repositories).Id.Name); + } + + [Fact] + public async Task Empty_repository_yields_an_empty_tree() + { + var gh = Standard(); + gh.Routes["/repos/snapkitty/alpha/git/trees/"] = _ => new HttpResponseMessage(HttpStatusCode.Conflict); + var result = await new GitHubIngest(new HttpClient(gh), _cache, null).IngestOwnerAsync("snapkitty"); + Assert.Empty(result.Failures); + Assert.Empty(result.Repositories[0].Tree); + } + + [Fact] + public async Task Unchanged_resources_are_served_from_cache_via_etag() + { + var gh = Standard(); + int full = 0; + gh.Routes["/repos/snapkitty/alpha/languages"] = req => + { + if (req.Headers.IfNoneMatch.Any(t => t.Tag == "\"v1\"")) return new HttpResponseMessage(HttpStatusCode.NotModified); + full++; + return Json("""{"Rust":1234}""", etag: "\"v1\""); + }; + var first = new GitHubIngest(new HttpClient(gh), _cache, null); + await first.IngestOwnerAsync("snapkitty"); + var second = new GitHubIngest(new HttpClient(gh), _cache, null); + var result = await second.IngestOwnerAsync("snapkitty"); + + Assert.Equal(1, full); + Assert.True(second.NotModified >= 1); + Assert.Equal(1234, result.Repositories[0].Languages["Rust"]); + } + + [Fact] + public async Task Rate_limit_is_reported_not_thrown() + { + var gh = Standard(); + gh.RateLimited = true; + var result = await new GitHubIngest(new HttpClient(gh), _cache, null).IngestOwnerAsync("snapkitty"); + Assert.True(result.RateLimited); + Assert.Empty(result.Repositories); + } + + [Fact] + public async Task Offline_refresh_keeps_last_good_snapshot() + { + var gh = Standard(); + var good = await new GitHubIngest(new HttpClient(gh), _cache, null).IngestOwnerAsync("snapkitty"); + var saved = SnapshotStore.Merge(null, good, "test", DateTimeOffset.UnixEpoch).Snapshot; + + gh.RateLimited = true; + var bad = await new GitHubIngest(new HttpClient(gh), _cache + "-2", null).IngestOwnerAsync("snapkitty"); + var merged = SnapshotStore.Merge(saved, bad, "test", DateTimeOffset.UnixEpoch.AddDays(1)); + + Assert.True(merged.KeptPrevious); + Assert.Equal(2, merged.Snapshot.Repositories.Count); + Assert.Equal(2, merged.Stale.Count); + } + + [Fact] + public void Partial_refresh_keeps_failed_repositories_as_stale() + { + var prev = new Snapshot { TakenAt = default, Source = "t", Repositories = [TestRepos.Make("a"), TestRepos.Make("b")] }; + var fresh = new IngestResult([TestRepos.Make("a", commits: 99)], [new IngestFailure("snapkitty/b", "500")], false); + var merged = SnapshotStore.Merge(prev, fresh, "t", default); + Assert.Equal(99, merged.Snapshot.Repositories.Single(r => r.Id.Name == "a").CommitsLast90Days); + Assert.Equal(["snapkitty/b"], merged.Stale); + } + + [Fact] + public void Deleted_repositories_drop_out_on_a_clean_refresh() + { + var prev = new Snapshot { TakenAt = default, Source = "t", Repositories = [TestRepos.Make("a"), TestRepos.Make("gone")] }; + var merged = SnapshotStore.Merge(prev, new IngestResult([TestRepos.Make("a")], [], false), "t", default); + Assert.Equal(["a"], merged.Snapshot.Repositories.Select(r => r.Id.Name)); + } + + [Fact] + public async Task Token_is_sent_but_redacted_from_errors() + { + var gh = Standard(); + string? auth = null; + gh.Routes["/repos/snapkitty/alpha/languages"] = req => { auth = req.Headers.Authorization?.ToString(); return Json("{}"); }; + await new GitHubIngest(new HttpClient(gh), _cache, "ghp_abcdefghijklmnopqrstuvwxyz0123").IngestOwnerAsync("snapkitty"); + Assert.Equal("Bearer ghp_abcdefghijklmnopqrstuvwxyz0123", auth); + Assert.Equal("failed with [REDACTED] here", GitHubIngest.Redact("failed with ghp_abcdefghijklmnopqrstuvwxyz0123 here")); + } + + [Fact] + public void Link_header_parsing_finds_next() + { + Assert.Equal("https://x/p2", GitHubIngest.NextLink("; rel=\"next\", ; rel=\"last\"")); + Assert.Null(GitHubIngest.NextLink("; rel=\"prev\"")); + Assert.Null(GitHubIngest.NextLink(null)); + } +} diff --git a/tests/Repoverse.Core.Tests/InteriorTests.cs b/tests/Repoverse.Core.Tests/InteriorTests.cs new file mode 100644 index 0000000000000000000000000000000000000000..35702826196cc9d7cfc4f96bbd714f0df655cb9f --- /dev/null +++ b/tests/Repoverse.Core.Tests/InteriorTests.cs @@ -0,0 +1,111 @@ +using Repoverse.Core.Generation; +using Repoverse.Core.Voxels; +using static Repoverse.Core.WorldConstants; + +namespace Repoverse.Core.Tests; + +public class InteriorTests +{ + [Fact] + public void Ignored_directories_never_become_rooms() + { + var files = new[] { "src/a.js", "src/b.js" } + .Concat(Enumerable.Range(0, 5000).Select(i => $"node_modules/pkg{i}/index.js")) + .Concat(["target/debug/app", "build/out.o"]); + var graph = RoomGraphBuilder.Build(TestRepos.Make("web", files: files), 6); + Assert.DoesNotContain(graph.Rooms, r => r.Directories.Any(d => d.StartsWith("node_modules") || d.StartsWith("target") || d.StartsWith("build"))); + Assert.Contains(graph.Rooms, r => r.Name == "src"); + } + + [Fact] + public void Huge_repositories_are_compressed_to_the_room_budget() + { + var files = Enumerable.Range(0, 200).SelectMany(d => Enumerable.Range(0, 3).Select(f => $"pkg{d:000}/file{f}.c")); + var graph = RoomGraphBuilder.Build(TestRepos.Make("mono", files: files), 10); + var work = graph.Rooms.Where(BuildingRasterizer.IsWorkRoom).ToList(); + Assert.True(work.Count <= MaxRoomsPerBuilding); + Assert.Equal(600, work.Sum(r => r.FileCount)); // nothing lost, only folded into Commons + Assert.Contains(work, r => r.Name == "Commons"); + } + + [Fact] + public void Room_purpose_comes_from_directory_meaning() + { + var graph = RoomGraphBuilder.Build(TestRepos.Make("r", files: ["tests/a.py", "tests/b.py", "docs/x.md", "docs/y.md", "proofs/p.lean", "proofs/q.lean"]), 6); + Assert.Equal(RoomPurpose.InspectionLab, graph.Rooms.Single(r => r.Name == "tests").Purpose); + Assert.Equal(RoomPurpose.Archive, graph.Rooms.Single(r => r.Name == "docs").Purpose); + Assert.Equal(RoomPurpose.ProofVault, graph.Rooms.Single(r => r.Name == "proofs").Purpose); + } + + [Fact] + public void Every_room_graph_in_the_slice_is_connected() + { + foreach (var b in ManifestBuilder.Build(TestRepos.Slice(), new Seed(1)).Buildings) + Assert.Empty(b.Interior.Unreachable()); + } + + /// + /// §89 against real geometry: flood-fill walkable air from the entrance (2 voxels of + /// headroom, one-step climbs, ladders vertical) and require every room to be reached. + /// + [Theory] + [InlineData(4)] + [InlineData(40)] + [InlineData(120)] + public void Every_rasterized_room_is_reachable_on_foot(int directories) + { + var files = Enumerable.Range(0, directories).SelectMany(d => new[] { $"m{d:000}/a.rs", $"m{d:000}/b.rs" }); + var b = ManifestBuilder.Build([TestRepos.Make("walk", "kernel", "Rust", files)], new Seed(7)).Buildings[0]; + + var grid = new Dictionary<(int, int, int), Voxel>(); + BuildingRasterizer.Rasterize(b, (x, y, z, v) => grid[(x, y, z)] = v); + Voxel At(int x, int y, int z) => grid.TryGetValue((x, y, z), out var v) ? v : Voxel.Air; + bool Standable(int x, int y, int z) => At(x, y, z).IsPassable && At(x, y + 1, z).IsPassable && (!At(x, y - 1, z).IsPassable || At(x, y, z).Type == BlockType.Ladder || At(x, y - 1, z).Type == BlockType.Ladder); + + var layout = BuildingRasterizer.Plan(b); + var f = b.Footprint; + var start = layout.Entrance; + var seen = new HashSet<(int, int, int)> { start }; + var queue = new Queue<(int X, int Y, int Z)>(seen); + while (queue.Count > 0) + { + var (x, y, z) = queue.Dequeue(); + foreach (var (dx, dz) in new[] { (1, 0), (-1, 0), (0, 1), (0, -1) }) + foreach (var dy in new[] { 0, 1, -1 }) + { + var n = (x + dx, y + dy, z + dz); + if (n.Item1 < f.X || n.Item1 > f.MaxX || n.Item3 < f.Z || n.Item3 > f.MaxZ) continue; + if (Standable(n.Item1, n.Item2, n.Item3) && seen.Add(n)) queue.Enqueue(n); + } + if (At(x, y, z).Type == BlockType.Ladder || At(x, y + 1, z).Type == BlockType.Ladder || At(x, y - 1, z).Type == BlockType.Ladder) + foreach (var dy in new[] { 1, -1 }) + { + var n = (x, y + dy, z); + if (At(n.Item1, n.Item2, n.Item3).IsPassable && seen.Add(n)) queue.Enqueue(n); + } + } + + Assert.NotEmpty(layout.Rooms); + Assert.Equal(b.Interior.Rooms.Count(BuildingRasterizer.IsWorkRoom), layout.Rooms.Count); + foreach (var room in layout.Rooms) + { + var c = ((room.MinX + room.MaxX) / 2, room.FloorY + 1, (room.MinZ + room.MaxZ) / 2); + Assert.True(seen.Contains(c), $"room {room.RoomId} on floor {room.Floor} is sealed"); + } + } + + [Fact] + public void Artifacts_become_interactive_objects_inside_their_rooms() + { + var b = ManifestBuilder.Build(TestRepos.Slice(), new Seed(1)).Buildings.Single(x => x.Repo.Name == "wasmc"); + var objects = BuildingRasterizer.Objects(b).ToList(); + var placements = BuildingRasterizer.Plan(b).Rooms.ToDictionary(r => r.RoomId); + Assert.Contains(objects, o => o.SourcePath == "tests/lower.rs" && o.Kind == ArtifactKind.TestBench && o.Actions.Contains("test")); + Assert.All(objects, o => + { + var p = placements[o.RoomId]; + Assert.InRange(o.X, p.MinX, p.MaxX); + Assert.InRange(o.Z, p.MinZ, p.MaxZ); + }); + } +} diff --git a/tests/Repoverse.Core.Tests/Repoverse.Core.Tests.csproj b/tests/Repoverse.Core.Tests/Repoverse.Core.Tests.csproj new file mode 100644 index 0000000000000000000000000000000000000000..9800673491fc1bb4d14ef9dd909fe94c72c854ce --- /dev/null +++ b/tests/Repoverse.Core.Tests/Repoverse.Core.Tests.csproj @@ -0,0 +1,27 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + + + + + + + + + + + diff --git a/tests/Repoverse.Core.Tests/StateTests.cs b/tests/Repoverse.Core.Tests/StateTests.cs new file mode 100644 index 0000000000000000000000000000000000000000..94c3788b60ffc06de2409925db3d6fe6a198cc34 --- /dev/null +++ b/tests/Repoverse.Core.Tests/StateTests.cs @@ -0,0 +1,124 @@ +using Repoverse.Core.Generation; +using Repoverse.Core.Model; +using Repoverse.Core.Persistence; +using Repoverse.Core.Simulation; +using Repoverse.Core.Voxels; + +namespace Repoverse.Core.Tests; + +public class StateTests +{ + [Fact] + public void Save_round_trips_player_state_and_edits() + { + var manifest = ManifestBuilder.Build(TestRepos.Slice(), new Seed(3)); + var edits = new WorldEdits(); + edits.Set(-5, 12, 40, new Voxel(BlockType.Wall, MaterialFamily.Wood)); + var player = new PlayerState { X = 1.5, Z = -3, Mode = ViewMode.Code, Selection = "repoverse://snapkitty/wasmc/src/lower.rs#L10", Bookmarks = [new("home", "repoverse://@0,9,0")] }; + var path = Path.GetTempFileName(); + try + { + SaveGame.Write(path, SaveGame.Capture(manifest, player, edits, tick: 77)); + var loaded = SaveGame.Read(path); + var restored = new WorldEdits(); + loaded.RestoreEdits(restored); + + Assert.Equal(player.Selection, loaded.Player.Selection); + Assert.Equal(ViewMode.Code, loaded.Player.Mode); + Assert.Equal(77, loaded.SimulationTick); + Assert.Equal(manifest.WorldSeed, loaded.WorldSeed); + var chunk = new Chunk(ChunkCoord.FromVoxel(-5, 12, 40)); + restored.ApplyTo(chunk); + Assert.Equal(MaterialFamily.Wood, chunk[-5 - chunk.Coord.OriginX, 12, 40 - chunk.Coord.OriginZ].Material); + } + finally { File.Delete(path); } + } + + [Fact] + public void Version_1_saves_migrate() + { + const string v1 = """{"schemaVersion":1,"seed":"000000000000002a","player":{"x":4,"y":9,"z":2,"cameraMode":"graph"},"simulationTick":5}"""; + var save = SaveGame.Parse(v1); + Assert.Equal(SaveGame.CurrentSchema, save.SchemaVersion); + Assert.Equal("000000000000002a", save.WorldSeed); + Assert.Equal(ViewMode.Graph, save.Player.Mode); + Assert.Empty(save.Edits); + } + + [Fact] + public void Saves_from_a_newer_build_are_refused() + { + Assert.Throws(() => SaveGame.Parse("""{"schemaVersion":99}""")); + } + + [Theory] + [InlineData("repoverse://snapkitty/wasmc")] + [InlineData("repoverse://snapkitty/wasmc/src/lower.rs#L42")] + [InlineData("repoverse://snapkitty/wasmc/dir%20with%20space/a.rs")] + [InlineData("repoverse://snapkitty/wasmc?room=3")] + [InlineData("repoverse://@-10,9,200")] + public void Uris_round_trip(string text) => Assert.Equal(text, RepoverseUri.Parse(text).ToString()); + + [Fact] + public void Uri_maps_back_to_github() + { + var uri = RepoverseUri.Parse("repoverse://snapkitty/wasmc/src/lower.rs#L42"); + Assert.Equal("https://github.com/snapkitty/wasmc/blob/main/src/lower.rs#L42", uri.GitHubUrl("main")); + Assert.Equal("src/lower.rs", uri.Path); + } + + [Theory] + [InlineData("http://x/y")] + [InlineData("repoverse://onlyowner")] + [InlineData("repoverse://a/b#nope")] + public void Malformed_uris_are_rejected(string text) => Assert.Throws(() => RepoverseUri.Parse(text)); + + [Fact] + public void Clock_runs_fixed_ticks_independent_of_frame_rate() + { + var clock = new SimulationClock(ticksPerSecond: 10); + int ticks = 0; + clock.Ticked += _ => ticks++; + for (int frame = 0; frame < 120; frame++) clock.Advance(TimeSpan.FromSeconds(1 / 120.0)); // one second at 120 FPS + Assert.InRange(ticks, 9, 10); + + clock.Speed = 4; + clock.Advance(TimeSpan.FromSeconds(1)); + Assert.InRange(ticks, 9 + 16, 10 + 16); // capped at maxTicksPerAdvance + + clock.Paused = true; + Assert.Equal(0, clock.Advance(TimeSpan.FromSeconds(5))); + } + + [Fact] + public void Scheduled_actions_fire_in_tick_then_insertion_order() + { + var clock = new SimulationClock(); + var log = new List(); + clock.Schedule(2, () => log.Add("b")); + clock.Schedule(1, () => log.Add("a")); + clock.Schedule(2, () => log.Add("c")); + for (int i = 0; i < 3; i++) clock.Step(); + Assert.Equal(["a", "b", "c"], log); + } + + [Fact] + public void Snapshot_diff_emits_typed_events() + { + var before = new[] { TestRepos.Make("a", commits: 1), TestRepos.Make("gone") }; + var after = new[] + { + TestRepos.Make("a", commits: 30, archived: true, releases: [new Release("v2", DateTimeOffset.UnixEpoch, false)], + files: ["README.md", "src/main.rs", "src/new.rs"]), + TestRepos.Make("new"), + }; + var events = SnapshotDiff.Diff(before, after); + Assert.Contains(events, e => e is RepositoryArchived { Repo.Name: "a" }); + Assert.Contains(events, e => e is ReleasePublished { Tag: "v2" }); + Assert.Contains(events, e => e is ActivityChanged { CommitsBefore: 1, CommitsAfter: 30 }); + Assert.Contains(events, e => e is StructureChanged { FilesAdded: 1, FilesRemoved: 3 }); + Assert.Contains(events, e => e is RepositoryAdded { Repo.Name: "new" }); + Assert.Contains(events, e => e is RepositoryRemoved { Repo.Name: "gone" }); + Assert.Empty(SnapshotDiff.Diff(before, before)); + } +} diff --git a/tests/Repoverse.Core.Tests/TestRepos.cs b/tests/Repoverse.Core.Tests/TestRepos.cs new file mode 100644 index 0000000000000000000000000000000000000000..8a738a1f2f52995076d2dcc7bd6495dd148258a0 --- /dev/null +++ b/tests/Repoverse.Core.Tests/TestRepos.cs @@ -0,0 +1,45 @@ +using Repoverse.Core.Model; + +namespace Repoverse.Core.Tests; + +internal static class TestRepos +{ + public static CanonicalRepository Make(string name, string? description = null, string? language = null, + IEnumerable? files = null, int commits = 5, bool archived = false, IReadOnlyList? releases = null, + IReadOnlyList? topics = null, IReadOnlyList? dependsOn = null, int contributors = 3) + { + var tree = (files ?? ["README.md", "src/main.rs", "src/lib.rs", "tests/basic.rs", "Cargo.toml"]) + .Select(p => new TreeEntry(p, TreeEntryKind.File, 2000 + p.Length * 37)) + .ToList(); + return new CanonicalRepository + { + Id = new RepoId("snapkitty", name), + Description = description, + PrimaryLanguage = language, + Languages = language == null ? new Dictionary() : new Dictionary { [language] = tree.Sum(t => t.SizeBytes) }, + Topics = topics ?? [], + CommitsLast90Days = commits, + Archived = archived, + Releases = releases ?? [], + Tree = tree, + DependsOn = dependsOn ?? [], + Contributors = contributors, + SnapshotId = "test", + }; + } + + /// The ten-category slice from §56. + public static IReadOnlyList Slice() => + [ + Make("ortho32", "Microkernel operating system", "Rust", ["kernel/boot.rs", "kernel/mm.rs", "kernel/sched.rs", "linker.ld", "Cargo.toml"]), + Make("fpga-lab", "FPGA firmware for a RISC-V core", "SystemVerilog", ["rtl/core.sv", "rtl/alu.sv", "sim/tb.sv", "Makefile"]), + Make("tiny-llm", "Agent framework for autonomous LLM tools", "Python", ["agent/loop.py", "agent/tools.py", "tests/test_loop.py", "pyproject.toml"]), + Make("proofs", "Formal proofs of the scheduler", "Lean", ["Proofs/Sched.lean", "Proofs/Mem.lean", "lakefile.lean"]), + Make("ledger", "Double-entry ledger and payment engine", "Go", ["ledger/post.go", "ledger/account.go", "api/http.go", "go.mod"]), + Make("site", "Marketing website frontend", "TypeScript", ["src/App.tsx", "src/index.tsx", "public/index.html", "package.json"]), + Make("corpus", "Training dataset and corpus tooling", "Python", ["data/shard0.json", "data/shard1.json", "scripts/clean.py", "README.md"]), + Make("deployer", "Infrastructure deploy orchestration", "Go", ["cmd/deploy/main.go", "deploy/k8s.yaml", ".github/workflows/ci.yml"]), + Make("wasmc", "Compiler from a kernel IR to wasm", "Rust", ["src/lower.rs", "src/parser.rs", "src/ir.rs", "tests/lower.rs", "Cargo.toml"]), + Make("scratch", "misc experiments", null, ["a.txt", "b.bin"]), + ]; +} diff --git a/tests/Repoverse.Core.Tests/VoxelTests.cs b/tests/Repoverse.Core.Tests/VoxelTests.cs new file mode 100644 index 0000000000000000000000000000000000000000..bb066af5b08e43563e1e4ded49ef43e67ce7b116 --- /dev/null +++ b/tests/Repoverse.Core.Tests/VoxelTests.cs @@ -0,0 +1,126 @@ +using Repoverse.Core.Generation; +using Repoverse.Core.Model; +using Repoverse.Core.Voxels; +using static Repoverse.Core.WorldConstants; + +namespace Repoverse.Core.Tests; + +public class VoxelTests +{ + [Fact] + public void Voxel_packs_type_material_and_state() + { + var v = new Voxel(BlockType.Window, MaterialFamily.Glass, 3); + Assert.Equal(BlockType.Window, v.Type); + Assert.Equal(MaterialFamily.Glass, v.Material); + Assert.Equal(3, v.State); + Assert.False(v.IsOpaque); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(31, 0)] + [InlineData(32, 1)] + [InlineData(-1, -1)] + [InlineData(-32, -1)] + [InlineData(-33, -2)] + public void Chunk_coordinates_floor_toward_negative_infinity(int voxel, int chunk) => + Assert.Equal(chunk, ChunkCoord.FloorDiv(voxel)); + + [Fact] + public void Solid_box_meshes_to_six_quads() + { + var chunk = new Chunk(new ChunkCoord(0, 0, 0)); + for (int x = 4; x < 12; x++) for (int y = 4; y < 9; y++) for (int z = 4; z < 20; z++) + chunk[x, y, z] = new Voxel(BlockType.Wall); + var mesh = GreedyMesher.Build(chunk); + Assert.Equal(6, mesh.Quads.Count); + Assert.Equal(2 * (8 * 5 + 8 * 16 + 5 * 16), mesh.VisibleFaces); + } + + [Fact] + public void Greedy_quads_cover_exactly_the_visible_faces() + { + var rng = new SeededRandom(99); + var chunk = new Chunk(new ChunkCoord(0, 0, 0)); + BlockType[] types = [BlockType.Air, BlockType.Air, BlockType.Wall, BlockType.Floor, BlockType.Window]; + for (int i = 0; i < ChunkVolume; i++) + chunk[i % ChunkSize, i / (ChunkSize * ChunkSize), i / ChunkSize % ChunkSize] = new Voxel(rng.Pick(types)); + var mesh = GreedyMesher.Build(chunk); + Assert.Equal(mesh.VisibleFaces, mesh.Quads.Sum(q => q.Width * q.Height)); + Assert.True(mesh.Quads.Count < mesh.VisibleFaces); + } + + [Fact] + public void Faces_against_a_loaded_solid_neighbour_are_culled() + { + var chunk = new Chunk(new ChunkCoord(0, 0, 0)); + for (int y = 0; y < ChunkSize; y++) for (int z = 0; z < ChunkSize; z++) chunk[ChunkSize - 1, y, z] = new Voxel(BlockType.Wall); + var open = GreedyMesher.Build(chunk); + var closed = GreedyMesher.Build(chunk, (x, _, _) => x >= ChunkSize ? new Voxel(BlockType.Wall) : null); + Assert.Equal(open.VisibleFaces - ChunkSize * ChunkSize, closed.VisibleFaces); + } + + [Fact] + public void Generated_chunks_are_deterministic_and_contain_buildings() + { + var manifest = ManifestBuilder.Build(TestRepos.Slice(), new Seed(5)); + var b = manifest.Buildings[0]; + var c = ChunkCoord.FromVoxel(b.Footprint.X + 2, GroundLevel + 1, b.Footprint.Z + 2); + var gen = new WorldGenerator(manifest); + var one = gen.Generate(c); + var two = new WorldGenerator(manifest).Generate(c); + Assert.True(one.Raw.SequenceEqual(two.Raw)); + var local = one[b.Footprint.X + 2 - c.OriginX, GroundLevel - c.OriginY, b.Footprint.Z + 2 - c.OriginZ]; + Assert.Equal(BlockType.Floor, local.Type); + } + + [Fact] + public void Chunks_outside_the_world_height_are_empty() + { + var gen = new WorldGenerator(ManifestBuilder.Build(TestRepos.Slice(), new Seed(5))); + Assert.True(gen.Generate(new ChunkCoord(0, -1, 0)).IsEmpty); + Assert.True(gen.Generate(new ChunkCoord(0, WorldGenerator.MaxChunkY + 1, 0)).IsEmpty); + } + + [Fact] + public async Task Streaming_memory_is_bounded_by_radius_while_travelling() + { + var manifest = ManifestBuilder.Build(TestRepos.Slice(), new Seed(5)); + var streamer = new ChunkStreamer(new WorldGenerator(manifest), new WorldEdits(), radius: 2); + int layers = WorldGenerator.MaxChunkY + 1; + int maxResident = (2 * (2 + StreamHysteresisChunks) + 1) * (2 * (2 + StreamHysteresisChunks) + 1) * layers; + + for (int step = 0; step < 12; step++) + { + await streamer.SettleAsync(step * 3 * ChunkSize, 100); + Assert.InRange(streamer.Loaded.Count, 1, maxResident); + } + Assert.Equal(0, streamer.InFlight); + } + + [Fact] + public async Task Player_edits_survive_chunk_unload_and_reload() + { + var manifest = ManifestBuilder.Build(TestRepos.Slice(), new Seed(5)); + var edits = new WorldEdits(); + var streamer = new ChunkStreamer(new WorldGenerator(manifest), edits, radius: 1); + edits.Set(5, GroundLevel + 3, 5, new Voxel(BlockType.Wall, MaterialFamily.Wood)); + + await streamer.SettleAsync(0, 0); + Assert.Equal(BlockType.Wall, streamer.Sample(5, GroundLevel + 3, 5)!.Value.Type); + await streamer.SettleAsync(50 * ChunkSize, 0); + Assert.Null(streamer.Sample(5, GroundLevel + 3, 5)); + await streamer.SettleAsync(0, 0); + Assert.Equal(MaterialFamily.Wood, streamer.Sample(5, GroundLevel + 3, 5)!.Value.Material); + } + + [Fact] + public void Generation_honours_cancellation() + { + var gen = new WorldGenerator(ManifestBuilder.Build(TestRepos.Slice(), new Seed(5))); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + Assert.Throws(() => gen.Generate(new ChunkCoord(0, 0, 0), ct: cts.Token)); + } +} diff --git a/tools/Build-Snapkitty.ps1 b/tools/Build-Snapkitty.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..3f414275669051f70c0a5a37cb66dbaf8e9cb408 --- /dev/null +++ b/tools/Build-Snapkitty.ps1 @@ -0,0 +1,22 @@ +param([switch]$Play) +$ErrorActionPreference = 'Stop' +$RepoRoot = Split-Path $PSScriptRoot -Parent +$BuildRoot = Join-Path $RepoRoot 'unify\build-game' +$VendorRoot = Join-Path $BuildRoot 'vendor' +New-Item -ItemType Directory -Force -Path $VendorRoot | Out-Null +$Archive = Join-Path $VendorRoot 'SDL2-devel-2.32.10-mingw.zip' +if (!(Test-Path -LiteralPath $Archive)) { + Invoke-WebRequest 'https://github.com/libsdl-org/SDL/releases/download/release-2.32.10/SDL2-devel-2.32.10-mingw.zip' -OutFile $Archive +} +$Expected = 'F15CFF5FCA62EC9381A016EF1D42A95C638CD72D2F226BA5781C76FE43DBD1AC' +if ((Get-FileHash -LiteralPath $Archive -Algorithm SHA256).Hash -ne $Expected) { throw 'SDL archive checksum mismatch' } +$SdlRoot = Join-Path $VendorRoot 'sdl2\SDL2-2.32.10\x86_64-w64-mingw32' +if (!(Test-Path -LiteralPath $SdlRoot)) { Expand-Archive -LiteralPath $Archive -DestinationPath (Join-Path $VendorRoot 'sdl2') } +& cmake -S (Join-Path $RepoRoot 'unify') -B $BuildRoot -G 'MinGW Makefiles' -DCMAKE_BUILD_TYPE=Release "-DSDL2_DIR=$SdlRoot/lib/cmake/SDL2" +if ($LASTEXITCODE) { throw 'Configure failed' } +& cmake --build $BuildRoot -j 6 +if ($LASTEXITCODE) { throw 'Build failed' } +Copy-Item -LiteralPath (Join-Path $SdlRoot 'bin\SDL2.dll') -Destination (Join-Path $BuildRoot 'SDL2.dll') -Force +& ctest --test-dir $BuildRoot --output-on-failure +if ($LASTEXITCODE) { throw 'Game checks failed' } +if ($Play) { & (Join-Path $BuildRoot 'unify_game.exe') } diff --git a/tools/Start-Repoverse3D.ps1 b/tools/Start-Repoverse3D.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..1027c5e18a09cf4d28be42d6e4734e87c9cafef3 --- /dev/null +++ b/tools/Start-Repoverse3D.ps1 @@ -0,0 +1,59 @@ +param( + [Parameter(Mandatory=$true)][string]$EngineRoot, + [string]$SourceRoot, + [string]$Owner = 'SNAPKITTYWEST', + [int]$Port = 38473, + [string]$BuildPlan, + [switch]$SkipBuild +) +$ErrorActionPreference = 'Stop' +$RepoRoot = Split-Path $PSScriptRoot -Parent +if (!$SourceRoot) { $SourceRoot = $RepoRoot } +$SourceRoot = (Resolve-Path -LiteralPath $SourceRoot).Path +$Editor = Join-Path $EngineRoot 'Engine\Binaries\Win64\UnrealEditor.exe' +if (!(Test-Path -LiteralPath $Editor)) { throw "Unreal Editor not found: $Editor" } +$Dotnet = Join-Path $env:USERPROFILE '.dotnet\dotnet.exe' +if (!(Test-Path -LiteralPath $Dotnet)) { $Dotnet = (Get-Command dotnet).Source } +$WorldDir = Join-Path $RepoRoot 'out\world3d' +New-Item -ItemType Directory -Force -Path $WorldDir | Out-Null +if (!$SkipBuild) { + & $Dotnet build (Join-Path $RepoRoot 'Repoverse.sln') -warnaserror + if ($LASTEXITCODE) { throw 'Core build failed' } + & (Join-Path $RepoRoot 'unreal\Prepare-Unreal.ps1') -EngineRoot $EngineRoot +} +$Cli = Join-Path $RepoRoot 'src\Repoverse.Cli\bin\Debug\net8.0\Repoverse.Cli.dll' +$Snapshot = Join-Path $WorldDir 'snapshot.json' +$Manifest = Join-Path $WorldDir 'manifest.json' +& $Dotnet $Cli ingest-local $SourceRoot --owner $Owner --out $Snapshot +if ($LASTEXITCODE) { throw 'Local ingestion failed' } +& $Dotnet $Cli generate --snapshot $Snapshot --out $Manifest +if ($LASTEXITCODE) { throw 'World generation failed' } +$Data = Get-Content -LiteralPath $Manifest -Raw | ConvertFrom-Json +$Repo = $Data.buildings[0].repo +$Token = [Guid]::NewGuid().ToString('N') + [Guid]::NewGuid().ToString('N') +$Sidecar = Join-Path $RepoRoot 'src\Repoverse.Sidecar\bin\Debug\net8.0\Repoverse.Sidecar.dll' +$Save = Join-Path $WorldDir 'save.json' +# ArgumentList is a command-line string on Windows; quote every path with spaces. +$ServiceArgs = @(('"'+$Sidecar+'"'), '--manifest', ('"'+$Manifest+'"'), '--token', $Token, '--port', $Port, '--save', ('"'+$Save+'"'), '--source-root', ('"'+$SourceRoot+'"'), '--source-repo', $Repo) +$Service = Start-Process -FilePath $Dotnet -ArgumentList $ServiceArgs -PassThru -WindowStyle Hidden -RedirectStandardOutput (Join-Path $WorldDir 'service.log') -RedirectStandardError (Join-Path $WorldDir 'service-error.log') +try { + $Ready = $false + for ($i=0; $i -lt 100; $i++) { + if ($Service.HasExited) { throw 'World service exited; inspect out/world3d/service-error.log' } + try { $null = Invoke-RestMethod "http://127.0.0.1:$Port/v1/health" -Headers @{'X-Repoverse-Token'=$Token}; $Ready=$true; break } catch { Start-Sleep -Milliseconds 100 } + } + if (!$Ready) { throw 'World service did not become ready' } + if ($BuildPlan) { + $BuildFile = Get-Item -LiteralPath $BuildPlan + if ($BuildFile.Length -gt 65536) { throw 'Build plan exceeds 64 KiB' } + $Body = Get-Content -LiteralPath $BuildFile.FullName -Raw + $Receipt = Invoke-RestMethod "http://127.0.0.1:$Port/v1/build" -Method Post -ContentType 'application/json' -Body $Body -Headers @{'X-Repoverse-Token'=$Token} + Write-Host "Builder $($Receipt.actor) placed $($Receipt.voxels) voxels. F5 saves the build." + } + $Project = Join-Path $RepoRoot 'unreal\Repoverse\Repoverse.uproject' + $GameArgs = @(('"'+$Project+'"'), '/Game/Maps/Repoverse?game=/Script/Repoverse.RepoverseWorldMode', '-game', "-RepoverseToken=$Token", "-RepoversePort=$Port", '-windowed', '-ResX=1440', '-ResY=900') + $Game = Start-Process -FilePath $Editor -ArgumentList $GameArgs -PassThru -Wait + if ($Game.ExitCode) { throw "Unreal exited with code $($Game.ExitCode)" } +} finally { + if (!$Service.HasExited) { Stop-Process -Id $Service.Id } +} diff --git a/tools/export-unify-world.py b/tools/export-unify-world.py new file mode 100644 index 0000000000000000000000000000000000000000..e630742df0ecf4a18964b4b3d9ef2b0be945c9c8 --- /dev/null +++ b/tools/export-unify-world.py @@ -0,0 +1,29 @@ +"""Export a read-only Unify menu from the authoritative C# manifest; no world-schema mutation.""" +import argparse +import json +from pathlib import Path +def lua_string(value): + # Encode bytes, not executable Lua. Fixed-width decimal escapes avoid delimiter injection. + return '"' + ''.join(chr(92) + format(b, '03d') for b in str(value).encode('utf-8')) + '"' +def export(manifest): + if manifest.get("schemaVersion") != 1: + raise ValueError("Expected WorldManifest schemaVersion 1") + rows=[] + for b in manifest["buildings"]: + floors=b["floors"] + if type(floors) is not int or floors < 1: raise ValueError("Invalid floor count") + fields={k:b[k]["value"] for k in ("district","category","activity","construction")} + fields.update(repo=b["repo"],seed=b["seed"]) + text=",".join(k+"="+lua_string(v) for k,v in fields.items()) + rows.append("{"+text+",floors="+str(floors)+",rooms="+str(len(b["interior"]["rooms"]))+"}") + return "{"+",".join(rows)+"}" +if __name__=="__main__": + parser=argparse.ArgumentParser() + parser.add_argument("manifest",type=Path) + parser.add_argument("--out",type=Path,default=Path("unify/game/assets/scenes/repositories.lua")) + args=parser.parse_args() + template=Path(__file__).parent.joinpath("templates/repositories.lua").read_text() + generated=template.replace("@BUILDINGS@",export(json.loads(args.manifest.read_text(encoding="utf-8")))) + args.out.parent.mkdir(parents=True,exist_ok=True) + args.out.write_text(generated,encoding="utf-8",newline="\n") + print("Wrote",args.out) diff --git a/tools/import-snapkitty.py b/tools/import-snapkitty.py new file mode 100644 index 0000000000000000000000000000000000000000..02403ad9f31c968187d169acdd1c6611e59d1b03 --- /dev/null +++ b/tools/import-snapkitty.py @@ -0,0 +1,19 @@ +"""Rebuild lossless QOI runtime copies from the preserved original artwork (requires Pillow).""" +from pathlib import Path +from PIL import Image +import hashlib +import json +root=Path(__file__).resolve().parents[1] +original=root/"assets/snapkitty" +manifest=json.loads((original/"runtime-manifest.json").read_text()) +for entry in manifest: + src=root/entry["source"] + if hashlib.sha256(src.read_bytes()).hexdigest()!=entry["sha256"]: + raise ValueError("Source changed: "+str(src)) + image=Image.open(src).convert("RGBA") + output=root/entry["runtime"] + output.parent.mkdir(parents=True,exist_ok=True) + image.save(output,format="QOI") + with Image.open(output) as check: + assert image.tobytes()==check.convert("RGBA").tobytes() +print("Four pixel-identical QOI textures prepared. Original images preserved.") diff --git a/tools/package-snapkitty.py b/tools/package-snapkitty.py new file mode 100644 index 0000000000000000000000000000000000000000..54c444b0f11b4c77f7a524dd0eea6317a0bfd2fa --- /dev/null +++ b/tools/package-snapkitty.py @@ -0,0 +1,37 @@ +"""Package the verified native build without machine-specific asset paths.""" +from pathlib import Path +import hashlib +import shutil +import zipfile +import argparse + +root = Path(__file__).resolve().parents[1] +build = root / "unify/build-game" +parser = argparse.ArgumentParser() +parser.add_argument("--output", default="out/Snapkitty-Windows") +args = parser.parse_args() +out = (root / args.output).resolve() +if out.exists(): + raise SystemExit("Package directory already exists; choose a fresh output before packaging.") +required = [build / "unify_game.exe", build / "SDL2.dll"] +for item in required: + if not item.is_file(): + raise SystemExit(f"Missing build artifact: {item}") +out.mkdir(parents=True) +for item in required: + shutil.copy2(item, out / item.name) +shutil.copytree(root / "unify/game/assets", out / "assets", ignore=shutil.ignore_patterns("*.usav")) +shutil.copytree(root / "assets/snapkitty", out / "source-artwork") +shutil.copy2(build / "vendor/sdl2/SDL2-2.32.10/LICENSE.txt", out / "SDL2-LICENSE.txt") +shutil.copytree(root / "unify/third_party/lua/doc", out / "licenses/lua") +shutil.copy2(root / "docs/SNAPKITTY-GAME.md", out / "README.md") +(out / "Play.cmd").write_text('@echo off\ncd /d "%~dp0"\nunify_game.exe --assets "%~dp0assets"\n', encoding="ascii") +files = sorted(p for p in out.rglob("*") if p.is_file()) +(out / "SHA256SUMS.txt").write_text("".join(hashlib.sha256(p.read_bytes()).hexdigest() + " " + p.relative_to(out).as_posix() + "\n" for p in files), encoding="utf-8") +archive = out.with_suffix(".zip") +with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as z: + for p in sorted(out.rglob("*")): + if p.is_file(): + z.write(p, p.relative_to(out.parent)) +print(archive) +print(hashlib.sha256(archive.read_bytes()).hexdigest()) diff --git a/tools/templates/repositories.lua b/tools/templates/repositories.lua new file mode 100644 index 0000000000000000000000000000000000000000..579b5b086e5207467c2d8fdd1611945ffd90c473 --- /dev/null +++ b/tools/templates/repositories.lua @@ -0,0 +1,36 @@ +-- Read-only presentation of the C# WorldManifest. Generated data never writes back to the core. +local buildings = @BUILDINGS@ +local S = {} +function S:init() + input:bind("next", "right", "d") + input:bind("prev", "left", "a") + input:bind("play", "enter") + input:bind("back", "escape") +end +function S:load() self.state={selected=1}; camera:set(0,0,32) end +function S:update(dt) + if input:is_pressed("next") and #buildings>0 then self.state.selected=self.state.selected % #buildings + 1 end + if input:is_pressed("prev") and #buildings>0 then self.state.selected=(self.state.selected-2) % #buildings + 1 end + if input:is_pressed("back") then scene.transition("snapkitty") end + if input:is_pressed("play") then scene.transition("snapkitty_level") end +end +function S:render() + local w,h=ui:screen() + ui:image("textures/snapkitty/snap-os",0,0,w,h) + ui:rect(0,0,w,h,5,9,20,230) + ui:text("REPOVERSE / REPOSITORIES",24,22,2.3,120,230,250) + local b=buildings[self.state.selected] + if b then + ui:text(b.repo:sub(1,48),24,70,1.8,230,220,255) + ui:text("DISTRICT "..b.district.." / "..b.category,24,112,1.4,200,210,230) + ui:text("ACTIVITY "..b.activity.." / "..b.construction,24,141,1.3,180,220,200) + ui:text(b.floors.." FLOORS / "..b.rooms.." ROOMS",24,171,1.5,240,210,145) + ui:text("SEED "..b.seed,24,204,1.2,165,185,205) + ui:text(self.state.selected.." / "..#buildings.." - LEFT / RIGHT TO BROWSE",24,254,1.3,195,210,240) + else + ui:text("NO WORLD MANIFEST IMPORTED",24,94,2,230,210,150) + ui:text("RUN tools/export-unify-world.py WITH A MANIFEST",24,139,1.2,210,220,240) + end + ui:text("ENTER PLAY BIFROST RUNNER ESC MENU",24,h-35,1.3,210,230,250) +end +return S diff --git a/tools/test-sidecar.py b/tools/test-sidecar.py new file mode 100644 index 0000000000000000000000000000000000000000..f9bbc718fe4a34389a665d04f521b98be5fc1f82 --- /dev/null +++ b/tools/test-sidecar.py @@ -0,0 +1,86 @@ +"""Exercise the real HTTP bridge against a CLI-generated local world. Standard library only.""" +import argparse +import json +import secrets +import socket +import subprocess +import tempfile +import time +import urllib.error +import urllib.request +from pathlib import Path + +p = argparse.ArgumentParser() +p.add_argument('--dotnet', default='dotnet') +p.add_argument('--build-plan', help='Optional real Twin-O-Matic export to exercise') +a = p.parse_args() +root = Path(__file__).resolve().parents[1] +cli = root / 'src/Repoverse.Cli/bin/Debug/net8.0/Repoverse.Cli.dll' +service = root / 'src/Repoverse.Sidecar/bin/Debug/net8.0/Repoverse.Sidecar.dll' +with tempfile.TemporaryDirectory(prefix='repoverse-http-') as temp: + work = Path(temp) + subprocess.run([a.dotnet, str(cli), 'ingest-local', str(root), '--owner', 'SNAPKITTYWEST', '--out', str(work/'snapshot.json')], check=True) + subprocess.run([a.dotnet, str(cli), 'generate', '--snapshot', str(work/'snapshot.json'), '--out', str(work/'manifest.json')], check=True) + with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + token = secrets.token_hex(32) + args = [a.dotnet, str(service), '--manifest', str(work/'manifest.json'), '--token', token, + '--port', str(port), '--save', str(work/'save.json'), '--source-root', str(root), '--source-repo', 'snapkittywest/repoverse'] + with (work/'service.log').open('w') as log: + child = subprocess.Popen(args, stdout=log, stderr=log) + try: + def request(route, data=None, auth=token, origin=None): + headers = {'X-Repoverse-Token': auth} + if origin: headers['Origin'] = origin + if data is not None: headers['Content-Type'] = 'application/json' + req = urllib.request.Request(f'http://127.0.0.1:{port}'+route, data=None if data is None else json.dumps(data).encode(), headers=headers) + try: + with urllib.request.urlopen(req, timeout=15) as response: + return response.status, json.load(response) + except urllib.error.HTTPError as e: + return e.code, e.read().decode() + for _ in range(100): + if child.poll() is not None: raise RuntimeError((work/'service.log').read_text()) + try: + if request('/v1/health')[0] == 200: break + except urllib.error.URLError: time.sleep(.1) + else: raise RuntimeError('Sidecar did not start') + assert request('/v1/health', auth='bad')[0] == 403 + assert request('/v1/health', origin='https://example.com')[0] == 403 + status, session = request('/v1/session', {}) + assert status == 200 and session['schemaVersion'] == 1 and session['destinations'] + player = session['player'] + resident_ids = set() + for _ in range(100): + status, packet = request('/v1/focus', {'x': player['x'], 'z': player['z']}) + assert status == 200 and len(packet['chunks']) <= 4 + resident_ids.difference_update(packet['unloaded']) + resident_ids.update(c['id'] for c in packet['chunks']) + if packet['remaining'] == 0: break + else: raise AssertionError('Focus did not settle') + assert resident_ids + plan = json.loads(Path(a.build_plan).read_text()) if a.build_plan else { + 'schemaVersion': 1, 'id': 'http-builder', 'actor': 'twin-builder', 'units': 'voxel', + 'origin': {'x': 0, 'y': 9, 'z': 0}, + 'operations': [{'name': 'add_box', 'args': {'width': 2, 'height': 2, 'depth': 2, 'y': 1, 'color': '#5ad1c4'}}]} + status, receipt = request('/v1/build', plan) + assert status == 200 and receipt['voxels'] > 0, receipt + assert request('/v1/build', {**plan, 'operations': plan['operations'] + [{'name': 'eval', 'args': {}}]})[0] == 400 + assert request('/v1/focus', {'x': player['x'], 'z': player['z']})[1]['builders'] == [receipt] + player['selection'] = 'repoverse://snapkittywest/repoverse/README.md' + assert request('/v1/save', player)[0] == 200 + assert request('/v1/load', {})[1] == player + assert json.loads((work/'save.json').read_text())['builders'] == [receipt] + status, source = request('/v1/source?repo=snapkittywest%2Frepoverse&path=README.md&offset=0') + assert status == 200 and source['lines'], source + assert request('/v1/source?repo=snapkittywest%2Frepoverse&path=.git%2Fconfig&offset=0')[0] == 400 + assert request('/v1/focus', {'x': 1e20, 'z': 0})[0] == 400 + # A newly connected renderer must receive the world again. + assert request('/v1/session', {})[1]['builders'] == [receipt] + assert request('/v1/focus', {'x': player['x'], 'z': player['z']})[1]['chunks'] + print('PASS: authentication, browser isolation, real mesh stream, save/load, source paging, invalid requests, builder placement/persistence, reconnect') + finally: + child.terminate() + try: child.wait(timeout=5) + except subprocess.TimeoutExpired: child.kill(); child.wait() diff --git a/unified-engine/kernel/ast/ast.js b/unified-engine/kernel/ast/ast.js new file mode 100644 index 0000000000000000000000000000000000000000..0faf8e2cbc296776e99ad377b63d0870acbf56d6 --- /dev/null +++ b/unified-engine/kernel/ast/ast.js @@ -0,0 +1,17 @@ +/** + * Kernel AST. Deliberately small: expressions, statements, and a function + * signature with typed parameters. No types are inferred here. + * + * TypeRef { kind: 'scalar' | 'buffer', scalar, isConst } + * Expr { kind, ... } kinds: int float bool var builtin index unary + * binary assign call cast + * (float carries `single`: true for an `f` suffix) + * Stmt { kind, ... } kinds: decl assign if while for break continue + * return expr block + * Param { name, type } + * KernelAst { name, returnType, params, body, isGlobal } + * + * The shapes are documented rather than declared as types because the project + * runs as plain ESM JavaScript with no TypeScript toolchain. + */ +export {}; diff --git a/unified-engine/kernel/compiler/compile.js b/unified-engine/kernel/compiler/compile.js new file mode 100644 index 0000000000000000000000000000000000000000..909e5fd4f78dc82c4844107213bebb437fcd1f05 --- /dev/null +++ b/unified-engine/kernel/compiler/compile.js @@ -0,0 +1,14 @@ +/** + * The full kernel pipeline: source -> AST -> IR -> wasm bytes. + */ + +import { parse } from './parser.js'; +import { lower } from '../ir/lowering.js'; +import { emitModule } from '../../wasm/modules/codegen.js'; + +export function compile(source) { + const ast = parse(source); + const ir = lower(ast); + const bytes = emitModule(ir); + return { ast, ir, bytes }; +} diff --git a/unified-engine/kernel/compiler/lexer.js b/unified-engine/kernel/compiler/lexer.js new file mode 100644 index 0000000000000000000000000000000000000000..1f6ada98672a564b9e2ab313d1c4de42bf3cf17b --- /dev/null +++ b/unified-engine/kernel/compiler/lexer.js @@ -0,0 +1,167 @@ +/** + * Lexer for the CUDA-like kernel language. + * + * Emits a token stream with source offsets so parser and lowering errors can point + * at a line. Whitespace and comments are skipped; nothing is evaluated here. + */ + +export const TokenType = { + IDENT: 'ident', + KEYWORD: 'keyword', + INT: 'int', + FLOAT: 'float', + PUNCT: 'punct', + EOF: 'eof', +}; + +const KEYWORDS = new Set([ + '__global__', + '__device__', + '__shared__', + 'void', + 'int', + 'uint', + 'float', + 'double', + 'const', + 'return', + 'if', + 'else', + 'while', + 'for', + 'break', + 'continue', + 'true', + 'false', +]); + +/** Multi-character operators are matched before single-character ones. */ +const PUNCTUATORS = [ + '&&', '||', '==', '!=', '<=', '>=', '<<', '>>', '+=', '-=', '*=', '/=', '%=', + '++', '--', '->', + '{', '}', '(', ')', '[', ']', ';', ',', '<', '>', '=', '+', '-', '*', '/', '%', '!', '&', '|', '^', '~', '.', +]; + +export class LexError extends Error { + constructor(message, line, column) { + super(`${message} (line ${line}, column ${column})`); + this.name = 'LexError'; + this.line = line; + this.column = column; + } +} + +const isDigit = (c) => c >= '0' && c <= '9'; +const isIdentStart = (c) => /[A-Za-z_]/.test(c); +const isIdentPart = (c) => /[A-Za-z0-9_]/.test(c); + +export function tokenize(source) { + const tokens = []; + let i = 0; + let line = 1; + let lineStart = 0; + + const column = (offset) => offset - lineStart + 1; + + while (i < source.length) { + const c = source[i]; + + if (c === '\n') { + i += 1; + line += 1; + lineStart = i; + continue; + } + if (c === ' ' || c === '\t' || c === '\r') { + i += 1; + continue; + } + // Comments run to end of line. + if (c === '/' && source[i + 1] === '/') { + while (i < source.length && source[i] !== '\n') i += 1; + continue; + } + if (c === '/' && source[i + 1] === '*') { + const startLine = line; + const startColumn = column(i); + i += 2; + for (;;) { + if (i >= source.length) throw new LexError('Unterminated block comment', startLine, startColumn); + if (source[i] === '\n') { + line += 1; + i += 1; + lineStart = i; + continue; + } + if (source[i] === '*' && source[i + 1] === '/') { + i += 2; + break; + } + i += 1; + } + continue; + } + + // Identifiers, keywords and __global__-style qualifiers. + if (isIdentStart(c)) { + const start = i; + while (i < source.length && isIdentPart(source[i])) i += 1; + const value = source.slice(start, i); + tokens.push({ + type: KEYWORDS.has(value) ? TokenType.KEYWORD : TokenType.IDENT, + value, + line, + column: column(start), + offset: start, + }); + continue; + } + + // Numbers: decimal and 0x hex, with optional fractional part and f suffix. + if (isDigit(c) || (c === '.' && isDigit(source[i + 1]))) { + const start = i; + let isFloat = false; + if (c === '0' && (source[i + 1] === 'x' || source[i + 1] === 'X')) { + i += 2; + while (i < source.length && /[0-9a-fA-F]/.test(source[i])) i += 1; + } else { + while (i < source.length && isDigit(source[i])) i += 1; + if (source[i] === '.') { + isFloat = true; + i += 1; + while (i < source.length && isDigit(source[i])) i += 1; + } + if (source[i] === 'e' || source[i] === 'E') { + isFloat = true; + i += 1; + if (source[i] === '+' || source[i] === '-') i += 1; + while (i < source.length && isDigit(source[i])) i += 1; + } + } + if (source[i] === 'f' || source[i] === 'F') { + isFloat = true; + i += 1; + } + const text = source.slice(start, i); + if (i < source.length && isIdentStart(source[i])) { + throw new LexError(`Malformed numeric literal '${text}${source[i]}'`, line, column(start)); + } + tokens.push({ type: isFloat ? TokenType.FLOAT : TokenType.INT, value: text, line, column: column(start), offset: start }); + continue; + } + + // Punctuators, longest match first. + const punct = PUNCTUATORS.find((p) => source.startsWith(p, i)); + if (punct) { + const start = i; + i += punct.length; + tokens.push({ type: TokenType.PUNCT, value: punct, line, column: column(start), offset: start }); + continue; + } + + throw new LexError(`Unexpected character '${c}'`, line, column(i)); + } + + tokens.push({ type: TokenType.EOF, value: '', line, column: column(i), offset: i }); + return tokens; +} diff --git a/unified-engine/kernel/compiler/parser.js b/unified-engine/kernel/compiler/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..f513650159d7768251d450640231a1cb00622c3c --- /dev/null +++ b/unified-engine/kernel/compiler/parser.js @@ -0,0 +1,332 @@ +/** + * Recursive-descent parser for the CUDA-like kernel language. + * Produces the AST in ../ast/ast.js. Every failure raises ParseError with a line. + */ + +import { tokenize, TokenType } from './lexer.js'; + +export class ParseError extends Error { + constructor(message, line) { + super(`${message} (line ${line})`); + this.name = 'ParseError'; + this.line = line; + } +} + +const SCALARS = new Set(['int', 'uint', 'float', 'double', 'void']); +const BUILTINS = new Set([ + 'blockIdx', 'blockDim', 'threadIdx', 'gridDim', + 'global_id', 'local_id', 'block_id', 'global_id_x', 'local_id_x', +]); + +/** Binary operator precedence, higher binds tighter. Follows C. */ +const PRECEDENCE = { + '||': 1, '&&': 2, + '|': 3, '^': 4, '&': 5, + '==': 6, '!=': 6, + '<': 7, '>': 7, '<=': 7, '>=': 7, + '<<': 8, '>>': 8, + '+': 9, '-': 9, + '*': 10, '/': 10, '%': 10, +}; + +const ASSIGN_OPS = new Set(['=', '+=', '-=', '*=', '/=', '%=']); + +/** Maps CUDA-style builtins onto the backend-neutral IR names. */ +const BUILTIN_MEMBERS = { + blockIdx: { x: 'block_id_x', y: 'block_id_y', z: 'block_id_z' }, + blockDim: { x: 'block_dim_x', y: 'block_dim_y', z: 'block_dim_z' }, + threadIdx: { x: 'local_id_x', y: 'local_id_y', z: 'local_id_z' }, + gridDim: { x: 'grid_dim_x', y: 'grid_dim_y', z: 'grid_dim_z' }, +}; + +export function parse(source) { + const tokens = tokenize(source); + let pos = 0; + + const peek = (offset = 0) => tokens[Math.min(pos + offset, tokens.length - 1)]; + const at = (value, type = TokenType.PUNCT) => peek().type === type && peek().value === value; + const atKeyword = (value) => peek().type === TokenType.KEYWORD && peek().value === value; + const next = () => tokens[pos++]; + const expect = (value) => { + if (!at(value)) throw new ParseError(`Expected '${value}' but found '${peek().value}'`, peek().line); + return next(); + }; + const atScalar = () => peek().type === TokenType.KEYWORD && SCALARS.has(peek().value) && peek().value !== 'void'; + const expectIdent = () => { + if (peek().type !== TokenType.IDENT) throw new ParseError(`Expected an identifier but found '${peek().value}'`, peek().line); + return next().value; + }; + + // ---- parameter type: `const float* A` or `int N` ---- + function parseParamType() { + const isConst = atKeyword('const'); + if (isConst) next(); + const typeToken = next(); + if (typeToken.type !== TokenType.KEYWORD || !SCALARS.has(typeToken.value)) { + throw new ParseError(`'${typeToken.value}' is not a supported parameter type`, typeToken.line); + } + const scalar = typeToken.value; + let isBuffer = false; + if (at('*')) { + next(); + isBuffer = true; + } + return { kind: isBuffer ? 'buffer' : 'scalar', scalar, isConst }; + } + + function parseParams() { + expect('('); + const params = []; + if (at(')')) { + next(); + return params; + } + for (;;) { + const type = parseParamType(); + const name = expectIdent(); + params.push({ name, type }); + if (at(',')) { + next(); + if (at(')')) break; + continue; + } + break; + } + expect(')'); + return params; + } + + // ---- primary expressions ---- + function parsePrimary() { + const token = peek(); + + if (at('(')) { + next(); + const inner = parseExpr(); + expect(')'); + return inner; + } + if (token.type === TokenType.INT) { + next(); + const value = token.value.startsWith('0x') || token.value.startsWith('0X') + ? parseInt(token.value, 16) + : parseInt(token.value, 10); + return { kind: 'int', value }; + } + if (token.type === TokenType.FLOAT) { + next(); + // As in C, an unsuffixed literal is a double and `f` makes it a float. + const single = /[fF]$/.test(token.value); + return { kind: 'float', value: Number.parseFloat(token.value), single }; + } + // Functional cast: int(x), float(x). + if (atScalar() && peek(1).type === TokenType.PUNCT && peek(1).value === '(') { + const to = next().value; + next(); + const inner = parseExpr(); + expect(')'); + return { kind: 'cast', to, operand: inner }; + } + if (atKeyword('true')) { + next(); + return { kind: 'bool', value: true }; + } + if (atKeyword('false')) { + next(); + return { kind: 'bool', value: false }; + } + if (token.type === TokenType.IDENT) { + next(); + if (BUILTINS.has(token.value)) return { kind: 'builtin', name: token.value }; + if (at('(')) throw new ParseError(`Unknown function '${token.value}'`, token.line); + return { kind: 'var', name: token.value }; + } + throw new ParseError(`Unexpected '${token.value}' in expression`, token.line); + } + + function parsePostfix() { + let left = parsePrimary(); + for (;;) { + if (at('[')) { + next(); + const index = parseExpr(); + expect(']'); + left = { kind: 'index', base: left, index }; + continue; + } + if (at('.') && left.kind === 'builtin') { + next(); + const member = expectIdent(); + const mapped = BUILTIN_MEMBERS[left.name]; + if (!mapped || !(member in mapped)) { + throw new ParseError(`'${left.name}' has no member '${member}'`, peek().line); + } + left = { kind: 'call', callee: mapped[member], args: [] }; + continue; + } + if (at('++') || at('--')) { + const op = next().value; + left = { kind: 'assign', op: op === '++' ? '+=' : '-=', target: left, value: { kind: 'int', value: 1 } }; + continue; + } + break; + } + return left; + } + + function parseUnary() { + if (at('!') || at('-') || at('~')) { + const op = next().value; + return { kind: 'unary', op, operand: parseUnary() }; + } + // C-style cast: (float)x. + if (at('(') && peek(1).type === TokenType.KEYWORD && SCALARS.has(peek(1).value) && peek(1).value !== 'void' + && peek(2).type === TokenType.PUNCT && peek(2).value === ')') { + next(); + const to = next().value; + next(); + return { kind: 'cast', to, operand: parseUnary() }; + } + return parsePostfix(); + } + + function parseBinary(minPrecedence) { + let left = parseUnary(); + for (;;) { + const token = peek(); + if (token.type !== TokenType.PUNCT) break; + const precedence = PRECEDENCE[token.value]; + if (precedence === undefined || precedence < minPrecedence) break; + next(); + const right = parseBinary(precedence + 1); + left = { kind: 'binary', op: token.value, left, right }; + } + return left; + } + + function parseExpr() { + const left = parseBinary(1); + if (ASSIGN_OPS.has(peek().value) && peek().type === TokenType.PUNCT) { + const op = next().value; + const value = parseExpr(); + return { kind: 'assign', op, target: left, value }; + } + return left; + } + + // ---- statements ---- + function parseBlock() { + expect('{'); + const body = []; + while (!at('}')) { + if (peek().type === TokenType.EOF) throw new ParseError("Unterminated block: expected '}'", peek().line); + body.push(parseStmt()); + } + expect('}'); + return body; + } + + function parseStmt() { + if (at('{')) return { kind: 'block', body: parseBlock() }; + + if (atKeyword('if')) { + next(); + expect('('); + const cond = parseExpr(); + expect(')'); + // A braceless body is valid CUDA and is used by the reference kernel, so a single + // statement is accepted and wrapped rather than rejected. + const then = at('{') ? parseBlock() : [parseStmt()]; + let otherwise = []; + if (atKeyword('else')) { + next(); + otherwise = at('{') ? parseBlock() : [parseStmt()]; + } + return { kind: 'if', cond, then, otherwise }; + } + + if (atKeyword('while')) { + next(); + expect('('); + const cond = parseExpr(); + expect(')'); + const body = at('{') ? parseBlock() : [parseStmt()]; + return { kind: 'while', cond, body }; + } + + if (atKeyword('for')) { + next(); + expect('('); + let init = null; + if (at(';')) next(); + else init = parseSimpleStmt(); + const cond = at(';') ? null : parseExpr(); + expect(';'); + const step = at(')') ? null : parseExpr(); + expect(')'); + const body = at('{') ? parseBlock() : [parseStmt()]; + return { kind: 'for', init, cond, step, body }; + } + + if (atKeyword('break') || atKeyword('continue')) { + const kind = next().value; + expect(';'); + return { kind }; + } + + if (atKeyword('return')) { + next(); + if (at(';')) { + next(); + return { kind: 'return', value: null }; + } + const value = parseExpr(); + expect(';'); + return { kind: 'return', value }; + } + + return parseSimpleStmt(); + } + + /** A declaration or expression statement, including its ';'. Also the init clause of `for`. */ + function parseSimpleStmt() { + // Local scalar declaration: int i = 0; (a functional cast like int(x) is an expression) + if (atScalar() && !(peek(1).type === TokenType.PUNCT && peek(1).value === '(')) { + const type = next().value; + const name = expectIdent(); + let init = null; + if (at('=')) { + next(); + init = parseExpr(); + } + expect(';'); + return { kind: 'decl', name, type, init }; + } + + const expr = parseExpr(); + expect(';'); + // An assignment statement keeps the assign node itself, matching the Stmt kinds in ast.js. + if (expr.kind === 'assign') return expr; + return { kind: 'expr', value: expr }; + } + + // ---- top level: a single __global__ kernel ---- + if (!atKeyword('__global__')) { + throw new ParseError(`A kernel must be declared __global__ (found '${peek().value}')`, peek().line); + } + next(); + const returnToken = next(); + if (returnToken.type !== TokenType.KEYWORD || !SCALARS.has(returnToken.value)) { + throw new ParseError(`'${returnToken.value}' is not a supported return type`, returnToken.line); + } + const returnType = returnToken.value; + const name = expectIdent(); + const params = parseParams(); + const body = parseBlock(); + + if (peek().type !== TokenType.EOF) { + throw new ParseError(`Unexpected trailing input '${peek().value}'`, peek().line); + } + return { name, returnType, params, body, isGlobal: true }; +} diff --git a/unified-engine/kernel/ir/ir.js b/unified-engine/kernel/ir/ir.js new file mode 100644 index 0000000000000000000000000000000000000000..c8262819a334420c64086fcefcbab6e631888110 --- /dev/null +++ b/unified-engine/kernel/ir/ir.js @@ -0,0 +1,117 @@ +/** + * Kernel IR. Backend-neutral intermediate representation. + * + * Values are virtual registers: every instruction that produces a result writes a + * fresh `out` value `{ id, type }` exactly once. Named variables (parameters and + * locals) are read and written with LOAD / STORE. + * + * Control flow is structured rather than a label/jump graph, so a backend such as + * WebAssembly can emit it directly: + * + * IF { cond, then: Instr[], otherwise: Instr[] } + * LOOP { head: Instr[], cond: Value | null, body: Instr[], step: Instr[] } + * Evaluates `head` then `cond` before each iteration and exits when it is + * false. CONTINUE jumps to `step`; BREAK leaves the innermost loop. + */ +export const Op = { + CONST: 'const', LOAD: 'load', STORE: 'store', + ADD: 'add', SUB: 'sub', MUL: 'mul', DIV: 'div', REM: 'rem', + BIT_AND: 'bit_and', BIT_OR: 'bit_or', BIT_XOR: 'bit_xor', SHL: 'shl', SHR: 'shr', + CMP_LT: 'cmp_lt', CMP_GT: 'cmp_gt', CMP_LE: 'cmp_le', + CMP_GE: 'cmp_ge', CMP_EQ: 'cmp_eq', CMP_NE: 'cmp_ne', + NOT: 'not', NEG: 'neg', BIT_NOT: 'bit_not', CONVERT: 'convert', + BUILTIN: 'builtin', + BUFFER_LOAD: 'buffer_load', BUFFER_STORE: 'buffer_store', + IF: 'if', LOOP: 'loop', BREAK: 'break', CONTINUE: 'continue', RET: 'ret', +}; + +/** `bool` is the 0/1 result of a comparison; backends store it like an i32. */ +export const Type = { I32: 'i32', U32: 'u32', F32: 'f32', F64: 'f64', BOOL: 'bool' }; + +/** Source scalar names to IR types. */ +export const SCALAR_TYPES = { int: Type.I32, uint: Type.U32, float: Type.F32, double: Type.F64 }; + +/** Thread-indexing builtins a kernel may read. */ +export const Builtin = { + GLOBAL_ID_X: 'global_id_x', + LOCAL_ID_X: 'local_id_x', + BLOCK_ID_X: 'block_id_x', + BLOCK_DIM_X: 'block_dim_x', + GRID_DIM_X: 'grid_dim_x', +}; + +export const isFloat = (type) => type === Type.F32 || type === Type.F64; + +export function makeIdCounter() { + let next = 0; + return { next: () => next++ }; +} + +export function value(id, type) { + return { id, type }; +} + +export function instr(op, fields = {}, out = null) { + return { op, ...fields, out }; +} + +/** + * params: [{ name, kind: 'scalar' | 'buffer', type, isConst }] + * locals: [{ name, type }] (names are unique; shadowed source names are renamed) + * builtins: Builtin names the body reads + */ +export function kernel(name, returnType, params, locals, body, builtins) { + return { name, returnType, params, locals, body, builtins }; +} + +/** Renders IR as indented text for debugging and snapshot-style tests. */ +export function printIr(k) { + const lines = []; + const params = k.params.map((p) => `${p.kind === 'buffer' ? `${p.type}*` : p.type} ${p.name}`).join(', '); + lines.push(`kernel ${k.name}(${params}) -> ${k.returnType ?? 'void'}`); + for (const local of k.locals) lines.push(` local ${local.type} ${local.name}`); + const v = (x) => `%${x.id}`; + const walk = (body, depth) => { + const pad = ' '.repeat(depth); + for (const ins of body) { + const lhs = ins.out ? `${v(ins.out)}:${ins.out.type} = ` : ''; + switch (ins.op) { + case Op.CONST: lines.push(`${pad}${lhs}const ${ins.imm}`); break; + case Op.LOAD: lines.push(`${pad}${lhs}load ${ins.name}`); break; + case Op.STORE: lines.push(`${pad}store ${ins.name}, ${v(ins.value)}`); break; + case Op.BUILTIN: lines.push(`${pad}${lhs}builtin ${ins.name}`); break; + case Op.CONVERT: lines.push(`${pad}${lhs}convert ${v(ins.value)}`); break; + case Op.BUFFER_LOAD: lines.push(`${pad}${lhs}buffer_load ${ins.buffer}[${v(ins.index)}]`); break; + case Op.BUFFER_STORE: lines.push(`${pad}buffer_store ${ins.buffer}[${v(ins.index)}], ${v(ins.value)}`); break; + case Op.IF: + lines.push(`${pad}if ${v(ins.cond)}`); + walk(ins.then, depth + 1); + if (ins.otherwise.length) { + lines.push(`${pad}else`); + walk(ins.otherwise, depth + 1); + } + lines.push(`${pad}end`); + break; + case Op.LOOP: + lines.push(`${pad}loop`); + walk(ins.head, depth + 1); + if (ins.cond) lines.push(`${pad} while ${v(ins.cond)}`); + walk(ins.body, depth + 1); + if (ins.step.length) { + lines.push(`${pad} step`); + walk(ins.step, depth + 1); + } + lines.push(`${pad}end`); + break; + case Op.RET: lines.push(`${pad}ret${ins.value ? ` ${v(ins.value)}` : ''}`); break; + case Op.BREAK: case Op.CONTINUE: lines.push(`${pad}${ins.op}`); break; + default: { + const args = ins.operand ? [ins.operand] : [ins.left, ins.right]; + lines.push(`${pad}${lhs}${ins.op} ${args.map(v).join(', ')}`); + } + } + } + }; + walk(k.body, 1); + return lines.join('\n'); +} diff --git a/unified-engine/kernel/ir/lowering.js b/unified-engine/kernel/ir/lowering.js new file mode 100644 index 0000000000000000000000000000000000000000..28d0f55231bbc6744f346a9cadb9116916f37225 --- /dev/null +++ b/unified-engine/kernel/ir/lowering.js @@ -0,0 +1,372 @@ +/** + * AST -> IR lowering. + * + * Resolves names against C block scopes, assigns every expression a type using C's + * usual arithmetic conversions, inserts explicit CONVERTs, and turns && / || into + * short-circuit control flow. Every failure raises LowerError; the IR it returns is + * fully typed so a backend never has to infer anything. + */ + +import { + Op, Type, SCALAR_TYPES, Builtin, isFloat, + makeIdCounter, value, instr, kernel, +} from './ir.js'; + +export class LowerError extends Error { + constructor(message) { + super(message); + this.name = 'LowerError'; + } +} + +const ARITHMETIC = { '+': Op.ADD, '-': Op.SUB, '*': Op.MUL, '/': Op.DIV, '%': Op.REM }; +const BITWISE = { '&': Op.BIT_AND, '|': Op.BIT_OR, '^': Op.BIT_XOR }; +const SHIFTS = { '<<': Op.SHL, '>>': Op.SHR }; +const COMPARISONS = { + '<': Op.CMP_LT, '>': Op.CMP_GT, '<=': Op.CMP_LE, + '>=': Op.CMP_GE, '==': Op.CMP_EQ, '!=': Op.CMP_NE, +}; + +/** Builtins the lowering can read. Only the x dimension is launched today. */ +const SUPPORTED_BUILTINS = new Set(Object.values(Builtin)); + +/** Integer promotion: bool arithmetic happens in int. */ +const promote = (type) => (type === Type.BOOL ? Type.I32 : type); + +/** C's usual arithmetic conversions, restricted to the supported scalars. */ +function commonType(a, b) { + const pa = promote(a); + const pb = promote(b); + for (const type of [Type.F64, Type.F32, Type.U32]) { + if (pa === type || pb === type) return type; + } + return Type.I32; +} + +function scalarType(name) { + const type = SCALAR_TYPES[name]; + if (!type) throw new LowerError(`'${name}' is not a supported value type`); + return type; +} + +export function lower(ast) { + const ids = makeIdCounter(); + const isVoid = ast.returnType === 'void'; + const returnType = isVoid ? null : scalarType(ast.returnType); + + const params = []; + const usedNames = new Set(); + const paramScope = new Map(); + for (const p of ast.params) { + if (usedNames.has(p.name)) throw new LowerError(`Duplicate parameter '${p.name}'`); + usedNames.add(p.name); + const param = { name: p.name, kind: p.type.kind, type: scalarType(p.type.scalar), isConst: p.type.isConst }; + params.push(param); + paramScope.set(p.name, param); + } + + const locals = []; + const builtins = new Set(); + const scopes = [paramScope]; + let out = []; + let loopDepth = 0; + + // ---- helpers ---- + const fresh = (type) => value(ids.next(), type); + const emit = (ins) => { + out.push(ins); + return ins.out; + }; + /** Runs `fn` with a fresh instruction list and returns what it emitted. */ + const collect = (fn) => { + const saved = out; + out = []; + try { + fn(); + return out; + } finally { + out = saved; + } + }; + const scoped = (fn) => { + scopes.push(new Map()); + try { + return fn(); + } finally { + scopes.pop(); + } + }; + + function declareLocal(sourceName, type) { + let name = sourceName; + for (let n = 1; usedNames.has(name); n += 1) name = `${sourceName}.${n}`; + usedNames.add(name); + const local = { name, kind: 'scalar', type, isConst: false }; + locals.push({ name, type }); + return local; + } + + function lookup(name) { + for (let i = scopes.length - 1; i >= 0; i -= 1) { + const binding = scopes[i].get(name); + if (binding) return binding; + } + throw new LowerError(`Unknown variable '${name}'`); + } + + const constant = (type, imm) => emit(instr(Op.CONST, { imm }, fresh(type))); + + function convert(val, to) { + if (val.type === to) return val; + if (to === Type.BOOL) return toBool(val); + return emit(instr(Op.CONVERT, { value: val }, fresh(to))); + } + + function toBool(val) { + if (val.type === Type.BOOL) return val; + const zero = constant(val.type, 0); + return emit(instr(Op.CMP_NE, { left: val, right: zero }, fresh(Type.BOOL))); + } + + function requireInteger(val, what) { + if (isFloat(val.type)) throw new LowerError(`${what} requires integer operands`); + } + + function readBuiltin(name) { + if (!SUPPORTED_BUILTINS.has(name)) { + throw new LowerError(`Builtin '${name}' is not supported; only the x dimension is available`); + } + if (!isVoid) throw new LowerError(`Builtin '${name}' is only available in void kernels`); + builtins.add(name); + return emit(instr(Op.BUILTIN, { name }, fresh(Type.I32))); + } + + function bufferBinding(expr) { + if (expr.kind !== 'var') throw new LowerError('Only a buffer parameter can be indexed'); + const binding = lookup(expr.name); + if (binding.kind !== 'buffer') throw new LowerError(`'${expr.name}' is not a buffer`); + return binding; + } + + function lowerIndex(expr) { + const index = lowerExpr(expr); + requireInteger(index, 'A buffer index'); + return convert(index, Type.I32); + } + + /** Applies a binary operator to two already-lowered values. */ + function binaryOp(op, left, right) { + if (op in ARITHMETIC) { + const type = commonType(left.type, right.type); + if (op === '%' && isFloat(type)) throw new LowerError("'%' requires integer operands"); + const l = convert(left, type); + const r = convert(right, type); + return emit(instr(ARITHMETIC[op], { left: l, right: r }, fresh(type))); + } + if (op in BITWISE) { + requireInteger(left, `'${op}'`); + requireInteger(right, `'${op}'`); + const type = commonType(left.type, right.type); + return emit(instr(BITWISE[op], { left: convert(left, type), right: convert(right, type) }, fresh(type))); + } + if (op in SHIFTS) { + requireInteger(left, `'${op}'`); + requireInteger(right, `'${op}'`); + // The result has the promoted type of the left operand, not the common type. + const type = promote(left.type); + return emit(instr(SHIFTS[op], { left: convert(left, type), right: convert(right, type) }, fresh(type))); + } + if (op in COMPARISONS) { + const type = commonType(left.type, right.type); + const l = convert(left, type); + const r = convert(right, type); + return emit(instr(COMPARISONS[op], { left: l, right: r }, fresh(Type.BOOL))); + } + throw new LowerError(`Unsupported operator '${op}'`); + } + + /** a && b / a || b: the right side runs only when it can change the result. */ + function shortCircuit(expr) { + const result = declareLocal('$sc', Type.BOOL); + const left = toBool(lowerExpr(expr.left)); + emit(instr(Op.STORE, { name: result.name, value: left })); + const evalRight = collect(() => { + const right = toBool(lowerExpr(expr.right)); + emit(instr(Op.STORE, { name: result.name, value: right })); + }); + const isAnd = expr.op === '&&'; + emit(instr(Op.IF, { cond: left, then: isAnd ? evalRight : [], otherwise: isAnd ? [] : evalRight })); + return emit(instr(Op.LOAD, { name: result.name }, fresh(Type.BOOL))); + } + + function lowerAssign(expr) { + const compound = expr.op === '=' ? null : expr.op.slice(0, -1); + + if (expr.target.kind === 'var') { + const binding = lookup(expr.target.name); + if (binding.kind === 'buffer') throw new LowerError(`Cannot assign to buffer '${expr.target.name}'`); + if (binding.isConst) throw new LowerError(`Cannot assign to const '${expr.target.name}'`); + let result = lowerExpr(expr.value); + if (compound) { + const current = emit(instr(Op.LOAD, { name: binding.name }, fresh(binding.type))); + result = binaryOp(compound, current, result); + } + result = convert(result, binding.type); + emit(instr(Op.STORE, { name: binding.name, value: result })); + return result; + } + + if (expr.target.kind === 'index') { + const binding = bufferBinding(expr.target.base); + if (binding.isConst) throw new LowerError(`Cannot write to const buffer '${binding.name}'`); + const index = lowerIndex(expr.target.index); + let result = lowerExpr(expr.value); + if (compound) { + const current = emit(instr(Op.BUFFER_LOAD, { buffer: binding.name, index }, fresh(binding.type))); + result = binaryOp(compound, current, result); + } + result = convert(result, binding.type); + emit(instr(Op.BUFFER_STORE, { buffer: binding.name, index, value: result })); + return result; + } + + throw new LowerError('The left side of an assignment must be a variable or a buffer element'); + } + + function lowerExpr(expr) { + switch (expr.kind) { + case 'int': { + if (expr.value <= 0x7fffffff) return constant(Type.I32, expr.value); + if (expr.value <= 0xffffffff) return constant(Type.U32, expr.value); + throw new LowerError(`Integer literal ${expr.value} does not fit in 32 bits`); + } + case 'float': + return constant(expr.single ? Type.F32 : Type.F64, expr.value); + case 'bool': + return constant(Type.BOOL, expr.value ? 1 : 0); + case 'var': { + const binding = lookup(expr.name); + if (binding.kind === 'buffer') throw new LowerError(`Buffer '${expr.name}' must be indexed`); + return emit(instr(Op.LOAD, { name: binding.name }, fresh(binding.type))); + } + case 'builtin': + return readBuiltin(expr.name); + case 'call': + // The parser maps member builtins such as threadIdx.x onto call nodes. + if (expr.args.length !== 0) throw new LowerError(`Unknown function '${expr.callee}'`); + return readBuiltin(expr.callee); + case 'index': { + const binding = bufferBinding(expr.base); + const index = lowerIndex(expr.index); + return emit(instr(Op.BUFFER_LOAD, { buffer: binding.name, index }, fresh(binding.type))); + } + case 'unary': { + const operand = lowerExpr(expr.operand); + if (expr.op === '!') { + return emit(instr(Op.NOT, { operand: toBool(operand) }, fresh(Type.BOOL))); + } + if (expr.op === '-') { + const type = promote(operand.type); + return emit(instr(Op.NEG, { operand: convert(operand, type) }, fresh(type))); + } + if (expr.op === '~') { + requireInteger(operand, "'~'"); + const type = promote(operand.type); + return emit(instr(Op.BIT_NOT, { operand: convert(operand, type) }, fresh(type))); + } + throw new LowerError(`Unsupported unary operator '${expr.op}'`); + } + case 'binary': + if (expr.op === '&&' || expr.op === '||') return shortCircuit(expr); + return binaryOp(expr.op, lowerExpr(expr.left), lowerExpr(expr.right)); + case 'assign': + return lowerAssign(expr); + case 'cast': + return convert(lowerExpr(expr.operand), scalarType(expr.to)); + default: + throw new LowerError(`Unsupported expression '${expr.kind}'`); + } + } + + function lowerLoopBody(stmts) { + loopDepth += 1; + try { + return collect(() => scoped(() => lowerStmts(stmts))); + } finally { + loopDepth -= 1; + } + } + + function lowerStmt(stmt) { + switch (stmt.kind) { + case 'decl': { + const type = scalarType(stmt.type); + if (scopes.at(-1).has(stmt.name)) throw new LowerError(`'${stmt.name}' is already declared in this scope`); + // Evaluated before the name is in scope, so `int x = x;` reads an outer x. + // Without an initializer the local is zeroed so loop iterations stay deterministic. + const init = stmt.init ? convert(lowerExpr(stmt.init), type) : constant(type, 0); + const local = declareLocal(stmt.name, type); + scopes.at(-1).set(stmt.name, local); + emit(instr(Op.STORE, { name: local.name, value: init })); + return; + } + case 'assign': + lowerAssign(stmt); + return; + case 'expr': + lowerExpr(stmt.value); + return; + case 'block': + scoped(() => lowerStmts(stmt.body)); + return; + case 'if': { + const cond = toBool(lowerExpr(stmt.cond)); + const then = collect(() => scoped(() => lowerStmts(stmt.then))); + const otherwise = collect(() => scoped(() => lowerStmts(stmt.otherwise))); + emit(instr(Op.IF, { cond, then, otherwise })); + return; + } + case 'while': { + let cond = null; + const head = collect(() => { cond = toBool(lowerExpr(stmt.cond)); }); + const body = lowerLoopBody(stmt.body); + emit(instr(Op.LOOP, { head, cond, body, step: [] })); + return; + } + case 'for': + scoped(() => { + if (stmt.init) lowerStmt(stmt.init); + let cond = null; + const head = collect(() => { if (stmt.cond) cond = toBool(lowerExpr(stmt.cond)); }); + const body = lowerLoopBody(stmt.body); + const step = collect(() => { if (stmt.step) lowerExpr(stmt.step); }); + emit(instr(Op.LOOP, { head, cond, body, step })); + }); + return; + case 'break': + case 'continue': + if (loopDepth === 0) throw new LowerError(`'${stmt.kind}' outside of a loop`); + emit(instr(stmt.kind === 'break' ? Op.BREAK : Op.CONTINUE)); + return; + case 'return': { + if (isVoid) { + if (stmt.value) throw new LowerError('A void kernel cannot return a value'); + emit(instr(Op.RET, { value: null })); + return; + } + if (!stmt.value) throw new LowerError(`Kernel '${ast.name}' must return a ${ast.returnType}`); + emit(instr(Op.RET, { value: convert(lowerExpr(stmt.value), returnType) })); + return; + } + default: + throw new LowerError(`Unsupported statement '${stmt.kind}'`); + } + } + + function lowerStmts(stmts) { + for (const stmt of stmts) lowerStmt(stmt); + } + + const body = collect(() => scoped(() => lowerStmts(ast.body))); + return kernel(ast.name, returnType, params, locals, body, [...builtins]); +} diff --git a/unified-engine/package-lock.json b/unified-engine/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..a70294bed0895ed85efb0ea7b881d1fec2f9f0ac --- /dev/null +++ b/unified-engine/package-lock.json @@ -0,0 +1,50 @@ +{ + "name": "unified-engine", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "unified-engine", + "version": "0.1.0", + "dependencies": { + "fengari": "0.1.5" + } + }, + "node_modules/fengari": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/fengari/-/fengari-0.1.5.tgz", + "integrity": "sha512-0DS4Nn4rV8qyFlQCpKK8brT61EUtswynrpfFTcgLErcilBIBskSMQ86fO2WVuybr14ywyKdRjv91FiRZwnEuvQ==", + "license": "MIT", + "dependencies": { + "readline-sync": "^1.4.10", + "sprintf-js": "^1.1.3", + "tmp": "^0.2.5" + } + }, + "node_modules/readline-sync": { + "version": "1.4.10", + "resolved": "https://registry.npmjs.org/readline-sync/-/readline-sync-1.4.10.tgz", + "integrity": "sha512-gNva8/6UAe8QYepIQH/jQ2qn91Qj0B9sYjMBBs3QOB8F2CXcKgLxQaJRP76sWVRQt+QU+8fAkCbCvjjMFu7Ycw==", + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/sprintf-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", + "license": "BSD-3-Clause" + }, + "node_modules/tmp": { + "version": "0.2.7", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz", + "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==", + "license": "MIT", + "engines": { + "node": ">=14.14" + } + } + } +} diff --git a/unified-engine/package.json b/unified-engine/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5c09bece0de2830e1b8e3fe662c0f106bceefb6a --- /dev/null +++ b/unified-engine/package.json @@ -0,0 +1,19 @@ +{ + "name": "unified-engine", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "2D-first engine with a deterministic Lua orchestration backend and a real WASM-compiled compute kernel pipeline.", + "scripts": { + "test": "node --test \"tests/*.js\"", + "test:kernel": "node --test \"tests/test-kernel-*.js\"", + "test:wasm": "node --test \"tests/test-wasm-*.js\"", + "test:lua": "node --test tests/lua/", + "build:kernel": "node scripts/build-kernels.mjs", + "demo": "node examples/demo.mjs", + "demo:headless": "node examples/demo.mjs --headless" + }, + "dependencies": { + "fengari": "0.1.5" + } +} diff --git a/unified-engine/tests/test-kernel-frontend.js b/unified-engine/tests/test-kernel-frontend.js new file mode 100644 index 0000000000000000000000000000000000000000..0ed0adceafacdeac0af78bdfa7d6c1d83800e15b --- /dev/null +++ b/unified-engine/tests/test-kernel-frontend.js @@ -0,0 +1,162 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { tokenize, TokenType, LexError } from '../kernel/compiler/lexer.js'; +import { parse, ParseError } from '../kernel/compiler/parser.js'; + +const VECTOR_ADD = ` +__global__ +void vector_add(const float* A, const float* B, float* C, int N) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < N) + C[i] = A[i] + B[i]; +} +`; + +test('lexer: emits keywords, identifiers, numbers and punctuation', () => { + const tokens = tokenize('int i = 42;'); + assert.equal(tokens[0].type, TokenType.KEYWORD); + assert.equal(tokens[0].value, 'int'); + assert.equal(tokens[1].type, TokenType.IDENT); + assert.equal(tokens[3].type, TokenType.INT); + assert.equal(tokens[3].value, '42'); + assert.equal(tokens.at(-1).type, TokenType.EOF); +}); + +test('lexer: distinguishes float from int literals', () => { + assert.equal(tokenize('1.5')[0].type, TokenType.FLOAT); + assert.equal(tokenize('1')[0].type, TokenType.INT); + assert.equal(tokenize('2.5f')[0].type, TokenType.FLOAT); + assert.equal(tokenize('1e3')[0].type, TokenType.FLOAT); +}); + +test('lexer: parses hex literals', () => { + const token = tokenize('0x1F')[0]; + assert.equal(token.type, TokenType.INT); + assert.equal(parseInt(token.value, 16), 31); +}); + +test('lexer: skips line and block comments', () => { + const tokens = tokenize('int /* mid */ i; // trailing\n'); + assert.equal(tokens.filter((t) => t.type === TokenType.IDENT).length, 1); +}); + +test('lexer: tracks line numbers across newlines', () => { + const tokens = tokenize('int a;\nint b;\nint c;'); + assert.equal(tokens[0].line, 1); + const cToken = tokens.find((t) => t.value === 'c'); + assert.equal(cToken.line, 3); +}); + +test('lexer: prefers the longest punctuator', () => { + const values = tokenize('a += b').map((t) => t.value); + assert.ok(values.includes('+=')); + assert.ok(!values.includes('+=') === false); + const shift = tokenize('a << b').map((t) => t.value); + assert.ok(shift.includes('<<')); +}); + +test('lexer: rejects an unterminated block comment', () => { + assert.throws(() => tokenize('int a; /* never closed'), LexError); +}); + +test('lexer: rejects an unknown character', () => { + assert.throws(() => tokenize('int a = $;'), LexError); +}); + +test('parser: produces the expected kernel signature', () => { + const ast = parse(VECTOR_ADD); + assert.equal(ast.name, 'vector_add'); + assert.equal(ast.returnType, 'void'); + assert.equal(ast.isGlobal, true); + assert.equal(ast.params.length, 4); + assert.deepEqual(ast.params.map((p) => p.name), ['A', 'B', 'C', 'N']); + assert.deepEqual(ast.params.map((p) => p.type.kind), ['buffer', 'buffer', 'buffer', 'scalar']); + assert.equal(ast.params[0].type.isConst, true); + assert.equal(ast.params[2].type.isConst, false); +}); + +test('parser: lowers thread indexing to global_id_x', () => { + const ast = parse(VECTOR_ADD); + const [decl] = ast.body; + assert.equal(decl.kind, 'decl'); + assert.equal(decl.name, 'i'); + // i = blockIdx.x * blockDim.x + threadIdx.x + const add = decl.init; + assert.equal(add.kind, 'binary'); + assert.equal(add.op, '+'); + const mul = add.left; + assert.equal(mul.kind, 'binary'); + assert.equal(mul.op, '*'); + assert.equal(mul.left.callee, 'block_id_x'); + assert.equal(mul.right.callee, 'block_dim_x'); + assert.equal(add.right.callee, 'local_id_x'); +}); + +test('parser: keeps the guarded assignment as an if statement', () => { + const ast = parse(VECTOR_ADD); + const branch = ast.body[1]; + assert.equal(branch.kind, 'if'); + assert.equal(branch.cond.op, '<'); + const assign = branch.then[0]; + assert.equal(assign.kind, 'assign'); + assert.equal(assign.target.kind, 'index'); + assert.equal(assign.value.kind, 'binary'); + assert.equal(assign.value.op, '+'); +}); + +test('parser: accepts explicit casts and unary operators', () => { + const ast = parse('__global__ int f(int a) { return -int(a) * 2; }'); + // Unary minus binds tighter than '*', as in C: (-int(a)) * 2. + const ret = ast.body[0].value; + assert.equal(ret.kind, 'binary'); + assert.equal(ret.op, '*'); + assert.equal(ret.left.kind, 'unary'); + assert.equal(ret.left.operand.kind, 'cast'); + assert.equal(ret.left.operand.to, 'int'); +}); + +test('parser: accepts C-style casts', () => { + const ast = parse('__global__ float f(int a) { return (float)a / 2.0f; }'); + const ret = ast.body[0].value; + assert.equal(ret.op, '/'); + assert.equal(ret.left.kind, 'cast'); + assert.equal(ret.left.to, 'float'); + assert.equal(ret.right.single, true); +}); + +test('parser: follows C precedence for bitwise and shift operators', () => { + const ast = parse('__global__ int f(int a) { return a & 1 << 2 | 3; }'); + const ret = ast.body[0].value; + assert.equal(ret.op, '|'); + assert.equal(ret.left.op, '&'); + assert.equal(ret.left.right.op, '<<'); +}); + +test('parser: parses for loops with break and continue', () => { + const ast = parse('__global__ void f(int n) { for (int i = 0; i < n; i += 1) { if (i == 2) continue; break; } }'); + const loop = ast.body[0]; + assert.equal(loop.kind, 'for'); + assert.equal(loop.init.kind, 'decl'); + assert.equal(loop.cond.op, '<'); + assert.equal(loop.step.kind, 'assign'); + assert.equal(loop.body[0].then[0].kind, 'continue'); + assert.equal(loop.body[1].kind, 'break'); +}); + +test('parser: rejects a kernel without __global__', () => { + assert.throws(() => parse('void f() { }'), ParseError); +}); + +test('parser: rejects an unsupported parameter type', () => { + assert.throws(() => parse('__global__ void f(double2 v) { }'), ParseError); +}); + +test('parser: rejects trailing input after the kernel', () => { + assert.throws(() => parse(VECTOR_ADD + '\nint extra;'), ParseError); +}); + +test('parser: rejects an unterminated body', () => { + assert.throws(() => parse('__global__ void f() { int i = 0;'), ParseError); +}); diff --git a/unified-engine/tests/test-kernel-lowering.js b/unified-engine/tests/test-kernel-lowering.js new file mode 100644 index 0000000000000000000000000000000000000000..998bce97203e7cc68941de4b22139d41291a2c2c --- /dev/null +++ b/unified-engine/tests/test-kernel-lowering.js @@ -0,0 +1,102 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { parse } from '../kernel/compiler/parser.js'; +import { lower, LowerError } from '../kernel/ir/lowering.js'; +import { Op, Type, printIr } from '../kernel/ir/ir.js'; + +const lowerSource = (source) => lower(parse(source)); + +/** Every instruction in a body, including nested control flow. */ +function flatten(body) { + return body.flatMap((ins) => [ + ins, + ...flatten(ins.then ?? []), ...flatten(ins.otherwise ?? []), + ...flatten(ins.head ?? []), ...flatten(ins.body ?? []), ...flatten(ins.step ?? []), + ]); +} + +const VECTOR_ADD = ` +__global__ void vector_add(const float* A, const float* B, float* C, int N) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < N) + C[i] = A[i] + B[i]; +}`; + +test('lowering: vector_add has typed params, a guarded store and the builtins it reads', () => { + const ir = lowerSource(VECTOR_ADD); + assert.equal(ir.returnType, null); + assert.deepEqual(ir.params.map((p) => [p.name, p.kind, p.type]), [ + ['A', 'buffer', Type.F32], ['B', 'buffer', Type.F32], ['C', 'buffer', Type.F32], ['N', 'scalar', Type.I32], + ]); + assert.deepEqual(ir.builtins.sort(), ['block_dim_x', 'block_id_x', 'local_id_x']); + const branch = ir.body.find((ins) => ins.op === Op.IF); + assert.ok(branch); + const store = branch.then.find((ins) => ins.op === Op.BUFFER_STORE); + assert.equal(store.buffer, 'C'); + assert.equal(store.value.type, Type.F32); +}); + +test('lowering: every value id is defined exactly once', () => { + const ir = lowerSource(VECTOR_ADD); + const ids = flatten(ir.body).filter((ins) => ins.out).map((ins) => ins.out.id); + assert.equal(new Set(ids).size, ids.length); +}); + +test('lowering: applies the usual arithmetic conversions', () => { + const ir = lowerSource('__global__ float f(int a, float b) { return a * b; }'); + const mul = flatten(ir.body).find((ins) => ins.op === Op.MUL); + assert.equal(mul.out.type, Type.F32); + assert.equal(mul.left.type, Type.F32, 'the int operand is converted to float'); +}); + +test('lowering: an unsuffixed float literal is a double', () => { + const ir = lowerSource('__global__ float f(float x) { return x * 0.5; }'); + const mul = flatten(ir.body).find((ins) => ins.op === Op.MUL); + assert.equal(mul.out.type, Type.F64); +}); + +test('lowering: a shift keeps the type of its left operand', () => { + const ir = lowerSource('__global__ uint f(uint a, int b) { return a >> b; }'); + const shr = flatten(ir.body).find((ins) => ins.op === Op.SHR); + assert.equal(shr.out.type, Type.U32); +}); + +test('lowering: && short-circuits through a conditional', () => { + const ir = lowerSource('__global__ int f(const int* A, int i, int n) { return i < n && A[i] > 0; }'); + const branch = ir.body.find((ins) => ins.op === Op.IF); + assert.ok(branch.then.some((ins) => ins.op === Op.BUFFER_LOAD), 'A[i] is only read when i < n'); + assert.ok(!ir.body.some((ins) => ins.op === Op.BUFFER_LOAD)); +}); + +test('lowering: renames shadowed locals', () => { + const ir = lowerSource('__global__ int f() { int x = 1; { int x = 2; } return x; }'); + assert.deepEqual(ir.locals.map((l) => l.name), ['x', 'x.1']); + const ret = ir.body.at(-1); + const load = flatten(ir.body).find((ins) => ins.out === ret.value); + assert.equal(load.name, 'x'); +}); + +test('lowering: printIr renders the kernel', () => { + const text = printIr(lowerSource(VECTOR_ADD)); + assert.match(text, /^kernel vector_add\(f32\* A, f32\* B, f32\* C, i32 N\) -> void/); + assert.match(text, /buffer_store C\[%\d+\], %\d+/); +}); + +for (const [label, source, pattern] of [ + ['an unknown variable', '__global__ void f() { x = 1; }', /Unknown variable 'x'/], + ['a write to a const buffer', '__global__ void f(const int* A) { A[0] = 1; }', /const buffer 'A'/], + ['assigning a buffer', '__global__ void f(int* A, int* B) { A = B; }', /assign to buffer/], + ['a buffer used as a value', '__global__ int f(int* A) { return A; }', /must be indexed/], + ['a float index', '__global__ void f(int* A) { A[1.0f] = 1; }', /index requires integer/], + ['float %', '__global__ float f(float a) { return a % 2.0f; }', /'%' requires integer/], + ['break outside a loop', '__global__ void f() { break; }', /outside of a loop/], + ['a redeclaration', '__global__ void f() { int a = 1; int a = 2; }', /already declared/], + ['a value from a void kernel', '__global__ void f() { return 1; }', /cannot return a value/], + ['a missing return value', '__global__ int f() { return; }', /must return/], + ['builtins in a value kernel', '__global__ int f() { return threadIdx.x; }', /only available in void kernels/], + ['the y dimension', '__global__ void f(int* A) { A[0] = threadIdx.y; }', /only the x dimension/], +]) { + test(`lowering: rejects ${label}`, () => { + assert.throws(() => lowerSource(source), (error) => error instanceof LowerError && pattern.test(error.message)); + }); +} diff --git a/unified-engine/tests/test-wasm-runtime.js b/unified-engine/tests/test-wasm-runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..d358171e684ae17c4c1e7d31b7ab3d0737996127 --- /dev/null +++ b/unified-engine/tests/test-wasm-runtime.js @@ -0,0 +1,218 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { compile } from '../kernel/compiler/compile.js'; +import { KernelRuntime, RuntimeError } from '../wasm/runtime/runtime.js'; + +const VECTOR_ADD = ` +__global__ +void vector_add(const float* A, const float* B, float* C, int N) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < N) + C[i] = A[i] + B[i]; +} +`; + +/** Loads a value-returning kernel and returns a plain function. */ +async function scalarKernel(source) { + const kernel = await new KernelRuntime().load(source); + return (...args) => kernel.call(...args); +} + +test('wasm: compiled modules pass WebAssembly validation', () => { + assert.ok(WebAssembly.validate(compile(VECTOR_ADD).bytes)); + assert.ok(WebAssembly.validate(compile('__global__ double f(double x) { while (x > 1.0) x = x / 2.0; return x; }').bytes)); +}); + +test('wasm: vector_add computes C = A + B and respects the N guard', async () => { + const runtime = new KernelRuntime(); + const kernel = await runtime.load(VECTOR_ADD); + const n = 1000; + const a = Float32Array.from({ length: n }, (_, i) => i * 0.5); + const b = Float32Array.from({ length: n }, (_, i) => 1000 - i); + const A = runtime.upload(a); + const B = runtime.upload(b); + // One spare element past N proves threads beyond the guard do not write. + const C = runtime.alloc('f32', n + 1); + const block = 256; + kernel.launch({ grid: Math.ceil(n / block), block }, A, B, C, n); + const c = C.read(); + for (let i = 0; i < n; i += 1) assert.equal(c[i], Math.fround(a[i] + b[i])); + assert.equal(c[n], 0); +}); + +test('wasm: global_id_x covers every thread exactly once', async () => { + const runtime = new KernelRuntime(); + const kernel = await runtime.load('__global__ void count(int* hits) { hits[global_id_x] += 1; }'); + const hits = runtime.alloc('i32', 3 * 7); + kernel.launch({ grid: 3, block: 7 }, hits); + assert.deepEqual([...hits.read()], new Array(21).fill(1)); +}); + +test('wasm: integer arithmetic wraps and divides like C', async () => { + const f = await scalarKernel('__global__ int f(int a, int b) { return a / b * 1000 + a % b; }'); + assert.equal(f(7, 2), 3001); + assert.equal(f(-7, 2), -3001, 'division truncates toward zero'); + const wrap = await scalarKernel('__global__ int f(int a) { return a + 1; }'); + assert.equal(wrap(0x7fffffff), -0x80000000); +}); + +test('wasm: unsigned values use unsigned division, comparison and shifts', async () => { + const f = await scalarKernel('__global__ uint f(uint a) { return a / 2; }'); + assert.equal(f(0xfffffffe), 0x7fffffff); + const shr = await scalarKernel('__global__ uint f(uint a) { return a >> 28; }'); + assert.equal(shr(0xf0000000), 0xf); + const lt = await scalarKernel('__global__ int f(uint a, uint b) { return a < b; }'); + assert.equal(lt(1, 0x80000000), 1); +}); + +test('wasm: signed right shift is arithmetic', async () => { + const f = await scalarKernel('__global__ int f(int a) { return a >> 1; }'); + assert.equal(f(-8), -4); +}); + +test('wasm: casts truncate toward zero and saturate instead of trapping', async () => { + const f = await scalarKernel('__global__ int f(float x) { return (int)x; }'); + assert.equal(f(2.9), 2); + assert.equal(f(-2.9), -2); + assert.equal(f(1e20), 0x7fffffff); + assert.equal(f(Number.NaN), 0); + const g = await scalarKernel('__global__ float f(int a, int b) { return float(a) / b; }'); + assert.equal(g(1, 4), 0.25); +}); + +test('wasm: && and || short-circuit so an out-of-range read never happens', async () => { + const runtime = new KernelRuntime(); + const kernel = await runtime.load(` + __global__ void f(const int* A, int* out, int n) { + int i = global_id_x; + out[i] = (i < n && A[i] > 0) || i == 0; + }`); + const A = runtime.upload(Int32Array.from([0, 5, -1, 7])); + const out = runtime.alloc('i32', 6); + kernel.launch({ grid: 1, block: 6 }, A, out, 4); + assert.deepEqual([...out.read()], [1, 1, 0, 1, 0, 0]); +}); + +test('wasm: for loops honour break, continue and scoped locals', async () => { + const f = await scalarKernel(` + __global__ int f(int n) { + int sum = 0; + for (int i = 0; i < n; i += 1) { + if (i == 7) break; + if (i % 2 == 0) continue; + int i2 = i * i; + sum += i2; + } + return sum; + }`); + assert.equal(f(100), 1 + 9 + 25); + assert.equal(f(4), 1 + 9); + assert.equal(f(0), 0); +}); + +test('wasm: while loops and early returns', async () => { + const f = await scalarKernel(` + __global__ int collatz(int n) { + int steps = 0; + while (n != 1) { + if (steps > 1000) return -1; + if (n % 2 == 0) n = n / 2; else n = 3 * n + 1; + steps += 1; + } + return steps; + }`); + assert.equal(f(1), 0); + assert.equal(f(27), 111); +}); + +test('wasm: doubles keep full precision', async () => { + const f = await scalarKernel('__global__ double f(double a, double b) { return a + b; }'); + assert.equal(f(0.1, 0.2), 0.1 + 0.2); +}); + +test('wasm: a game particle step integrates and bounces off the floor', async () => { + const runtime = new KernelRuntime(); + const step = await runtime.load(` + __global__ void step(float* posY, float* velY, int count, float dt, float gravity) { + int i = global_id_x; + if (i >= count) return; + float v = velY[i] - gravity * dt; + float y = posY[i] + v * dt; + if (y < 0.0f) { + y = -y; + v = -v * 0.5f; + } + posY[i] = y; + velY[i] = v; + }`); + const count = 5; + const posY = runtime.upload(Float32Array.from([10, 5, 0.01, 2, 0])); + const velY = runtime.upload(Float32Array.from([0, 1, -2, 0, 0])); + const dt = 0.016; + const gravity = 9.8; + + // Reference implementation in JS with the same f32 rounding. + const y = Float32Array.from(posY.read()); + const v = Float32Array.from(velY.read()); + const f = Math.fround; + for (let frame = 0; frame < 120; frame += 1) { + step.launch({ grid: 1, block: 8 }, posY, velY, count, dt, gravity); + for (let i = 0; i < count; i += 1) { + let nv = f(v[i] - f(f(gravity) * f(dt))); + let ny = f(y[i] + f(nv * f(dt))); + if (ny < 0) { + ny = -ny; + nv = f(-nv * 0.5); + } + y[i] = ny; + v[i] = nv; + } + } + assert.deepEqual([...posY.read()], [...y]); + assert.deepEqual([...velY.read()], [...v]); + assert.ok([...posY.read()].every((p) => p >= 0), 'nothing falls through the floor'); +}); + +test('runtime: kernels loaded into one runtime share device buffers', async () => { + const runtime = new KernelRuntime(); + const fill = await runtime.load('__global__ void fill(int* A, int v) { A[global_id_x] = v; }'); + const double = await runtime.load('__global__ void twice(int* A) { A[global_id_x] *= 2; }'); + const A = runtime.alloc('i32', 4); + fill.launch({ grid: 1, block: 4 }, A, 21); + double.launch({ grid: 1, block: 4 }, A); + assert.deepEqual([...A.read()], [42, 42, 42, 42]); +}); + +test('runtime: grows memory for large buffers', async () => { + const runtime = new KernelRuntime({ initialPages: 1 }); + const kernel = await runtime.load('__global__ void iota(uint* A) { A[global_id_x] = global_id_x; }'); + const n = 100000; + const A = runtime.alloc('u32', n); + kernel.launch({ grid: n / 1000, block: 1000 }, A); + const out = A.read(); + assert.equal(out[0], 0); + assert.equal(out[n - 1], n - 1); +}); + +test('runtime: rejects mismatched launch arguments', async () => { + const runtime = new KernelRuntime(); + const kernel = await runtime.load(VECTOR_ADD); + const f = runtime.alloc('f32', 4); + const i = runtime.alloc('i32', 4); + const grid = { grid: 1, block: 4 }; + assert.throws(() => kernel.launch(grid, f, f, f), RuntimeError); + assert.throws(() => kernel.launch(grid, f, f, i, 4), /must be a f32 buffer/); + assert.throws(() => kernel.launch(grid, f, f, f, 4.5), /must be a i32/); + assert.throws(() => kernel.launch({ grid: -1, block: 4 }, f, f, f, 4), /Invalid grid/); + assert.throws(() => kernel.call(f, f, f, 4), /use launch/); + const other = new KernelRuntime().alloc('f32', 4); + assert.throws(() => kernel.launch(grid, f, f, other, 4), /different runtime/); + runtime.reset(); + assert.throws(() => kernel.launch(grid, f, f, f, 4), /freed by reset/); +}); + +test('runtime: load() rejects a kernel that does not compile', async () => { + await assert.rejects(new KernelRuntime().load('__global__ void f() { x = 1; }'), /Unknown variable/); +}); diff --git a/unified-engine/wasm/abi/abi.js b/unified-engine/wasm/abi/abi.js new file mode 100644 index 0000000000000000000000000000000000000000..8de21ac7672c7fba609a795a18f4382afaead82c --- /dev/null +++ b/unified-engine/wasm/abi/abi.js @@ -0,0 +1,37 @@ +/** + * The contract between compiled kernel modules and the host runtime. + * + * Memory: every module imports one linear memory as `env.memory`, owned by the + * host. A buffer parameter is passed as an i32 byte offset into that memory. + * + * Void kernels: the module exports `(...params, grid_dim_x, block_dim_x)`, + * which runs the body once per thread, block by block, in ascending thread order. + * The body itself is an internal function taking `...params` followed by + * THREAD_PARAMS. + * + * Non-void kernels: the body is exported directly as `(...params)` and may + * not read thread builtins. + */ + +import { Type } from '../../kernel/ir/ir.js'; + +export const MEMORY_IMPORT = { module: 'env', name: 'memory' }; + +/** Appended, in this order, to the kernel parameters of the internal body function. */ +export const THREAD_PARAMS = ['block_id_x', 'local_id_x', 'block_dim_x', 'grid_dim_x']; + +/** Appended, in this order, to the kernel parameters of an exported void kernel. */ +export const LAUNCH_PARAMS = ['grid_dim_x', 'block_dim_x']; + +/** Buffer element layout. `log2` is the shift from element index to byte offset. */ +export const ELEMENT = { + [Type.I32]: { bytes: 4, log2: 2, array: Int32Array }, + [Type.U32]: { bytes: 4, log2: 2, array: Uint32Array }, + [Type.F32]: { bytes: 4, log2: 2, array: Float32Array }, + [Type.F64]: { bytes: 8, log2: 3, array: Float64Array }, +}; + +/** The IR element type stored by a typed array, or undefined if it is not supported. */ +export function elementTypeOf(array) { + return Object.keys(ELEMENT).find((type) => array instanceof ELEMENT[type].array); +} diff --git a/unified-engine/wasm/modules/codegen.js b/unified-engine/wasm/modules/codegen.js new file mode 100644 index 0000000000000000000000000000000000000000..ffa5f4946c91fbd369e651fc7f1afbe5aa7f0881 --- /dev/null +++ b/unified-engine/wasm/modules/codegen.js @@ -0,0 +1,331 @@ +/** + * Kernel IR -> WebAssembly binary. + * + * Every IR virtual register becomes a typed wasm local, which keeps the stack + * discipline trivial: each instruction pushes its operands with local.get and + * stores its result with local.set. Structured IR control flow maps directly onto + * wasm block / loop / if. The module layout follows ../abi/abi.js. + */ + +import { Op, Type, Builtin, isFloat } from '../../kernel/ir/ir.js'; +import { MEMORY_IMPORT, THREAD_PARAMS, LAUNCH_PARAMS, ELEMENT } from '../abi/abi.js'; +import { + ValType, BLOCK_EMPTY, Section, ExternalKind, OpCode, SatOpCode, MAGIC_AND_VERSION, + uleb, sleb, f32, f64, name, vec, section, funcType, funcBody, +} from './encoder.js'; + +export class CodegenError extends Error { + constructor(message) { + super(message); + this.name = 'CodegenError'; + } +} + +const VAL_TYPE = { + [Type.I32]: ValType.I32, [Type.U32]: ValType.I32, [Type.BOOL]: ValType.I32, + [Type.F32]: ValType.F32, [Type.F64]: ValType.F64, +}; + +/** The wasm instruction family an IR type computes in: i32 (signed), u32, f32 or f64. */ +const family = (type) => (type === Type.BOOL ? Type.I32 : type); + +const ARITH = { + [Op.ADD]: { i32: 'i32_add', u32: 'i32_add', f32: 'f32_add', f64: 'f64_add' }, + [Op.SUB]: { i32: 'i32_sub', u32: 'i32_sub', f32: 'f32_sub', f64: 'f64_sub' }, + [Op.MUL]: { i32: 'i32_mul', u32: 'i32_mul', f32: 'f32_mul', f64: 'f64_mul' }, + [Op.DIV]: { i32: 'i32_div_s', u32: 'i32_div_u', f32: 'f32_div', f64: 'f64_div' }, + [Op.REM]: { i32: 'i32_rem_s', u32: 'i32_rem_u' }, + [Op.BIT_AND]: { i32: 'i32_and', u32: 'i32_and' }, + [Op.BIT_OR]: { i32: 'i32_or', u32: 'i32_or' }, + [Op.BIT_XOR]: { i32: 'i32_xor', u32: 'i32_xor' }, + [Op.SHL]: { i32: 'i32_shl', u32: 'i32_shl' }, + [Op.SHR]: { i32: 'i32_shr_s', u32: 'i32_shr_u' }, + [Op.CMP_LT]: { i32: 'i32_lt_s', u32: 'i32_lt_u', f32: 'f32_lt', f64: 'f64_lt' }, + [Op.CMP_GT]: { i32: 'i32_gt_s', u32: 'i32_gt_u', f32: 'f32_gt', f64: 'f64_gt' }, + [Op.CMP_LE]: { i32: 'i32_le_s', u32: 'i32_le_u', f32: 'f32_le', f64: 'f64_le' }, + [Op.CMP_GE]: { i32: 'i32_ge_s', u32: 'i32_ge_u', f32: 'f32_ge', f64: 'f64_ge' }, + [Op.CMP_EQ]: { i32: 'i32_eq', u32: 'i32_eq', f32: 'f32_eq', f64: 'f64_eq' }, + [Op.CMP_NE]: { i32: 'i32_ne', u32: 'i32_ne', f32: 'f32_ne', f64: 'f64_ne' }, +}; + +/** CONVERT opcodes keyed by `${from}>${to}`; an empty list is a reinterpretation. */ +const CONVERSIONS = { + 'i32>u32': [], 'u32>i32': [], 'bool>i32': [], 'bool>u32': [], + 'i32>f32': ['f32_convert_i32_s'], 'u32>f32': ['f32_convert_i32_u'], 'bool>f32': ['f32_convert_i32_s'], + 'i32>f64': ['f64_convert_i32_s'], 'u32>f64': ['f64_convert_i32_u'], 'bool>f64': ['f64_convert_i32_s'], + 'f32>f64': ['f64_promote_f32'], 'f64>f32': ['f32_demote_f64'], + 'f32>i32': [{ sat: 'i32_trunc_sat_f32_s' }], 'f32>u32': [{ sat: 'i32_trunc_sat_f32_u' }], + 'f64>i32': [{ sat: 'i32_trunc_sat_f64_s' }], 'f64>u32': [{ sat: 'i32_trunc_sat_f64_u' }], +}; + +const LOAD = { i32: 'i32_load', u32: 'i32_load', f32: 'f32_load', f64: 'f64_load' }; +const STORE = { i32: 'i32_store', u32: 'i32_store', f32: 'f32_store', f64: 'f64_store' }; + +/** Emits the body function of a kernel. Returns { params, results, locals, code }. */ +function emitBody(ir) { + const isVoid = ir.returnType === null; + const code = []; + const localIndex = new Map(); + const params = []; + const locals = []; + + for (const p of ir.params) { + localIndex.set(p.name, params.length); + params.push(p.kind === 'buffer' ? ValType.I32 : VAL_TYPE[p.type]); + } + if (isVoid) { + for (const t of THREAD_PARAMS) { + localIndex.set(`@${t}`, params.length); + params.push(ValType.I32); + } + } + const addLocal = (key, valType) => { + localIndex.set(key, params.length + locals.length); + locals.push(valType); + }; + for (const local of ir.locals) addLocal(local.name, VAL_TYPE[local.type]); + + const vreg = (val) => { + const key = `%${val.id}`; + if (!localIndex.has(key)) addLocal(key, VAL_TYPE[val.type]); + return localIndex.get(key); + }; + const buffers = new Map(ir.params.filter((p) => p.kind === 'buffer').map((p) => [p.name, p])); + + const op = (mnemonic) => code.push(OpCode[mnemonic]); + const get = (val) => code.push(OpCode.local_get, ...uleb(vreg(val))); + const set = (val) => code.push(OpCode.local_set, ...uleb(vreg(val))); + const getNamed = (key) => code.push(OpCode.local_get, ...uleb(localIndex.get(key))); + const setNamed = (key) => code.push(OpCode.local_set, ...uleb(localIndex.get(key))); + + function pushConst(type, imm) { + if (type === Type.F32) code.push(OpCode.f32_const, ...f32(imm)); + else if (type === Type.F64) code.push(OpCode.f64_const, ...f64(imm)); + else code.push(OpCode.i32_const, ...sleb(imm)); + } + + /** Pushes the byte address of buffer[index]. */ + function address(bufferName, index) { + const buffer = buffers.get(bufferName); + getNamed(buffer.name); + get(index); + code.push(OpCode.i32_const, ...sleb(ELEMENT[buffer.type].log2)); + op('i32_shl'); + op('i32_add'); + return buffer; + } + + /** Memory immediate: alignment hint (log2 bytes) and a zero offset. */ + const memarg = (type) => code.push(...uleb(ELEMENT[type].log2), ...uleb(0)); + + // Control stack of labels so BREAK / CONTINUE can compute branch depths. + const labels = []; + const depthOf = (kind) => { + for (let i = labels.length - 1; i >= 0; i -= 1) { + if (labels[i] === kind) return labels.length - 1 - i; + } + throw new CodegenError(`'${kind}' has no enclosing loop`); + }; + const open = (opcode, label) => { + code.push(opcode, BLOCK_EMPTY); + labels.push(label); + }; + const close = () => { + op('end'); + labels.pop(); + }; + + function emitInstr(ins) { + switch (ins.op) { + case Op.CONST: + pushConst(ins.out.type, ins.imm); + set(ins.out); + return; + case Op.LOAD: + getNamed(ins.name); + set(ins.out); + return; + case Op.STORE: + get(ins.value); + setNamed(ins.name); + return; + case Op.BUILTIN: + if (ins.name === Builtin.GLOBAL_ID_X) { + getNamed('@block_id_x'); + getNamed('@block_dim_x'); + op('i32_mul'); + getNamed('@local_id_x'); + op('i32_add'); + } else { + getNamed(`@${ins.name}`); + } + set(ins.out); + return; + case Op.NOT: + get(ins.operand); + op('i32_eqz'); + set(ins.out); + return; + case Op.NEG: + if (isFloat(ins.out.type)) { + get(ins.operand); + op(ins.out.type === Type.F32 ? 'f32_neg' : 'f64_neg'); + } else { + code.push(OpCode.i32_const, 0); + get(ins.operand); + op('i32_sub'); + } + set(ins.out); + return; + case Op.BIT_NOT: + get(ins.operand); + code.push(OpCode.i32_const, ...sleb(-1)); + op('i32_xor'); + set(ins.out); + return; + case Op.CONVERT: { + const steps = CONVERSIONS[`${ins.value.type}>${ins.out.type}`]; + if (!steps) throw new CodegenError(`No conversion from ${ins.value.type} to ${ins.out.type}`); + get(ins.value); + for (const step of steps) { + if (typeof step === 'string') op(step); + else code.push(0xfc, ...uleb(SatOpCode[step.sat])); + } + set(ins.out); + return; + } + case Op.BUFFER_LOAD: { + const buffer = address(ins.buffer, ins.index); + op(LOAD[buffer.type]); + memarg(buffer.type); + set(ins.out); + return; + } + case Op.BUFFER_STORE: { + const buffer = address(ins.buffer, ins.index); + get(ins.value); + op(STORE[buffer.type]); + memarg(buffer.type); + return; + } + case Op.IF: + get(ins.cond); + open(OpCode.if, 'if'); + emitList(ins.then); + if (ins.otherwise.length) { + op('else'); + emitList(ins.otherwise); + } + close(); + return; + case Op.LOOP: + // block $break { loop $top { head; br_if $break (!cond); block $continue { body } step; br $top } } + open(OpCode.block, 'break'); + open(OpCode.loop, 'top'); + emitList(ins.head); + if (ins.cond) { + get(ins.cond); + op('i32_eqz'); + code.push(OpCode.br_if, ...uleb(depthOf('break'))); + } + open(OpCode.block, 'continue'); + emitList(ins.body); + close(); + emitList(ins.step); + code.push(OpCode.br, ...uleb(depthOf('top'))); + close(); + close(); + return; + case Op.BREAK: + code.push(OpCode.br, ...uleb(depthOf('break'))); + return; + case Op.CONTINUE: + code.push(OpCode.br, ...uleb(depthOf('continue'))); + return; + case Op.RET: + if (ins.value) get(ins.value); + op('return'); + return; + default: { + const table = ARITH[ins.op]; + if (!table) throw new CodegenError(`Unsupported IR op '${ins.op}'`); + const mnemonic = table[family(ins.left.type)]; + if (!mnemonic) throw new CodegenError(`'${ins.op}' is not defined for ${ins.left.type}`); + get(ins.left); + get(ins.right); + op(mnemonic); + set(ins.out); + } + } + } + + function emitList(list) { + for (const ins of list) emitInstr(ins); + } + + emitList(ir.body); + // A value-returning body must not fall off the end; wasm validation needs the stack typed. + if (!isVoid) op('unreachable'); + + return { params, results: isVoid ? [] : [VAL_TYPE[ir.returnType]], locals, code }; +} + +/** + * The exported launcher for a void kernel: loops over blocks then threads and calls + * the body (function `bodyIndex`) once per thread. + */ +function emitLauncher(ir, bodyIndex) { + const n = ir.params.length; + const params = [ + ...ir.params.map((p) => (p.kind === 'buffer' ? ValType.I32 : VAL_TYPE[p.type])), + ...LAUNCH_PARAMS.map(() => ValType.I32), + ]; + const grid = n; + const blockDim = n + 1; + const block = n + 2; + const thread = n + 3; + const get = (i) => [OpCode.local_get, ...uleb(i)]; + const set = (i) => [OpCode.local_set, ...uleb(i)]; + const increment = (i) => [...get(i), OpCode.i32_const, 1, OpCode.i32_add, ...set(i)]; + + const call = []; + for (let i = 0; i < n; i += 1) call.push(...get(i)); + // THREAD_PARAMS order: block_id_x, local_id_x, block_dim_x, grid_dim_x + call.push(...get(block), ...get(thread), ...get(blockDim), ...get(grid), OpCode.call, ...uleb(bodyIndex)); + + const code = [ + OpCode.block, BLOCK_EMPTY, OpCode.loop, BLOCK_EMPTY, + ...get(block), ...get(grid), OpCode.i32_ge_u, OpCode.br_if, 1, + OpCode.i32_const, 0, ...set(thread), + OpCode.block, BLOCK_EMPTY, OpCode.loop, BLOCK_EMPTY, + ...get(thread), ...get(blockDim), OpCode.i32_ge_u, OpCode.br_if, 1, + ...call, + ...increment(thread), + OpCode.br, 0, + OpCode.end, OpCode.end, + ...increment(block), + OpCode.br, 0, + OpCode.end, OpCode.end, + ]; + return { params, results: [], locals: [ValType.I32, ValType.I32], code }; +} + +/** Compiles one kernel's IR to a complete wasm module. */ +export function emitModule(ir) { + const body = emitBody(ir); + const functions = [body]; + if (ir.returnType === null) functions.push(emitLauncher(ir, 0)); + const exported = functions.length - 1; + + const bytes = [ + ...MAGIC_AND_VERSION, + ...section(Section.TYPE, vec(functions.map((f) => funcType(f.params, f.results)))), + ...section(Section.IMPORT, vec([[ + ...name(MEMORY_IMPORT.module), ...name(MEMORY_IMPORT.name), ExternalKind.MEMORY, 0x00, ...uleb(0), + ]])), + ...section(Section.FUNCTION, vec(functions.map((_, i) => uleb(i)))), + ...section(Section.EXPORT, vec([[...name(ir.name), ExternalKind.FUNC, ...uleb(exported)]])), + ...section(Section.CODE, vec(functions.map((f) => funcBody(f.locals, f.code)))), + ]; + return new Uint8Array(bytes); +} diff --git a/unified-engine/wasm/modules/encoder.js b/unified-engine/wasm/modules/encoder.js new file mode 100644 index 0000000000000000000000000000000000000000..9b64a75d70eeca258241fa4b24d7c638c89eeaed --- /dev/null +++ b/unified-engine/wasm/modules/encoder.js @@ -0,0 +1,105 @@ +/** + * WebAssembly binary encoding primitives: LEB128 integers, IEEE floats, vectors + * and sections, plus the opcodes the kernel backend emits. Nothing here knows + * about kernels. + */ + +export const ValType = { I32: 0x7f, I64: 0x7e, F32: 0x7d, F64: 0x7c }; +export const BLOCK_EMPTY = 0x40; +export const Section = { TYPE: 1, IMPORT: 2, FUNCTION: 3, EXPORT: 7, CODE: 10 }; +export const ExternalKind = { FUNC: 0x00, MEMORY: 0x02 }; + +export const OpCode = { + unreachable: 0x00, block: 0x02, loop: 0x03, if: 0x04, else: 0x05, end: 0x0b, + br: 0x0c, br_if: 0x0d, return: 0x0f, call: 0x10, + local_get: 0x20, local_set: 0x21, + i32_load: 0x28, f32_load: 0x2a, f64_load: 0x2b, + i32_store: 0x36, f32_store: 0x38, f64_store: 0x39, + i32_const: 0x41, f32_const: 0x43, f64_const: 0x44, + i32_eqz: 0x45, i32_eq: 0x46, i32_ne: 0x47, + i32_lt_s: 0x48, i32_lt_u: 0x49, i32_gt_s: 0x4a, i32_gt_u: 0x4b, + i32_le_s: 0x4c, i32_le_u: 0x4d, i32_ge_s: 0x4e, i32_ge_u: 0x4f, + f32_eq: 0x5b, f32_ne: 0x5c, f32_lt: 0x5d, f32_gt: 0x5e, f32_le: 0x5f, f32_ge: 0x60, + f64_eq: 0x61, f64_ne: 0x62, f64_lt: 0x63, f64_gt: 0x64, f64_le: 0x65, f64_ge: 0x66, + i32_add: 0x6a, i32_sub: 0x6b, i32_mul: 0x6c, i32_div_s: 0x6d, i32_div_u: 0x6e, + i32_rem_s: 0x6f, i32_rem_u: 0x70, i32_and: 0x71, i32_or: 0x72, i32_xor: 0x73, + i32_shl: 0x74, i32_shr_s: 0x75, i32_shr_u: 0x76, + f32_neg: 0x8c, f32_add: 0x92, f32_sub: 0x93, f32_mul: 0x94, f32_div: 0x95, + f64_neg: 0x9a, f64_add: 0xa0, f64_sub: 0xa1, f64_mul: 0xa2, f64_div: 0xa3, + f32_convert_i32_s: 0xb2, f32_convert_i32_u: 0xb3, f32_demote_f64: 0xb6, + f64_convert_i32_s: 0xb7, f64_convert_i32_u: 0xb8, f64_promote_f32: 0xbb, +}; + +/** Saturating float-to-int truncations, 0xFC-prefixed. They never trap on NaN or overflow. */ +export const SatOpCode = { + i32_trunc_sat_f32_s: 0x00, i32_trunc_sat_f32_u: 0x01, + i32_trunc_sat_f64_s: 0x02, i32_trunc_sat_f64_u: 0x03, +}; + +export function uleb(n) { + const bytes = []; + let v = n >>> 0; + do { + let byte = v & 0x7f; + v >>>= 7; + if (v !== 0) byte |= 0x80; + bytes.push(byte); + } while (v !== 0); + return bytes; +} + +/** Signed LEB128 of a 32-bit integer. */ +export function sleb(n) { + const bytes = []; + let v = n | 0; + for (;;) { + const byte = v & 0x7f; + v >>= 7; + const done = (v === 0 && (byte & 0x40) === 0) || (v === -1 && (byte & 0x40) !== 0); + bytes.push(done ? byte : byte | 0x80); + if (done) return bytes; + } +} + +export function f32(n) { + const view = new DataView(new ArrayBuffer(4)); + view.setFloat32(0, n, true); + return [...new Uint8Array(view.buffer)]; +} + +export function f64(n) { + const view = new DataView(new ArrayBuffer(8)); + view.setFloat64(0, n, true); + return [...new Uint8Array(view.buffer)]; +} + +export function name(text) { + const bytes = [...new TextEncoder().encode(text)]; + return [...uleb(bytes.length), ...bytes]; +} + +/** A length-prefixed vector of already-encoded items. */ +export function vec(items) { + return [...uleb(items.length), ...items.flat()]; +} + +export function section(id, bytes) { + return [id, ...uleb(bytes.length), ...bytes]; +} + +export function funcType(params, results) { + return [0x60, ...vec(params.map((p) => [p])), ...vec(results.map((r) => [r]))]; +} + +/** A function body: local declarations run-length encoded by type, then code. */ +export function funcBody(localTypes, code) { + const runs = []; + for (const type of localTypes) { + if (runs.length && runs.at(-1).type === type) runs.at(-1).count += 1; + else runs.push({ type, count: 1 }); + } + const body = [...vec(runs.map((r) => [...uleb(r.count), r.type])), ...code, OpCode.end]; + return [...uleb(body.length), ...body]; +} + +export const MAGIC_AND_VERSION = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]; diff --git a/unified-engine/wasm/runtime/runtime.js b/unified-engine/wasm/runtime/runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..26e60279f95ac84d610bf8c67996aab97406fceb --- /dev/null +++ b/unified-engine/wasm/runtime/runtime.js @@ -0,0 +1,169 @@ +/** + * Host runtime for compiled kernels. + * + * Owns one WebAssembly.Memory shared by every kernel it loads, hands out typed + * device buffers from it with a bump allocator, and validates arguments before a + * launch so a type mismatch fails in JavaScript instead of corrupting memory. + */ + +import { compile } from '../../kernel/compiler/compile.js'; +import { Type } from '../../kernel/ir/ir.js'; +import { MEMORY_IMPORT, ELEMENT, elementTypeOf } from '../abi/abi.js'; + +const PAGE_BYTES = 65536; +const MAX_I32 = 0x7fffffff; +/** Offset 0 is never handed out, so a zero pointer is always a bug. */ +const HEAP_BASE = 16; + +export class RuntimeError extends Error { + constructor(message) { + super(message); + this.name = 'RuntimeError'; + } +} + +export class DeviceBuffer { + constructor(runtime, ptr, length, type) { + this.runtime = runtime; + this.ptr = ptr; + this.length = length; + this.type = type; + this.generation = runtime.generation; + } + + get byteLength() { + return this.length * ELEMENT[this.type].bytes; + } + + /** A live view over device memory. Invalidated when memory grows; prefer read(). */ + view() { + this.runtime.checkBuffer(this); + return new ELEMENT[this.type].array(this.runtime.memory.buffer, this.ptr, this.length); + } + + read() { + return this.view().slice(); + } + + write(data) { + if (data.length !== this.length) { + throw new RuntimeError(`Expected ${this.length} elements but got ${data.length}`); + } + this.view().set(data); + } +} + +export class KernelRuntime { + constructor({ initialPages = 1, maximumPages = 16384 } = {}) { + this.memory = new WebAssembly.Memory({ initial: initialPages, maximum: maximumPages }); + this.top = HEAP_BASE; + this.generation = 0; + } + + /** Allocates `length` elements of IR type `type` ('i32', 'u32', 'f32', 'f64'), zeroed. */ + alloc(type, length) { + const element = ELEMENT[type]; + if (!element) throw new RuntimeError(`Unsupported buffer type '${type}'`); + if (!Number.isInteger(length) || length < 0) throw new RuntimeError(`Invalid buffer length ${length}`); + const ptr = Math.ceil(this.top / 8) * 8; + const end = ptr + length * element.bytes; + if (end > MAX_I32) throw new RuntimeError('Out of device memory'); + const needed = Math.ceil(end / PAGE_BYTES) - this.memory.buffer.byteLength / PAGE_BYTES; + if (needed > 0) { + try { + this.memory.grow(needed); + } catch { + throw new RuntimeError('Out of device memory'); + } + } + this.top = end; + const buffer = new DeviceBuffer(this, ptr, length, type); + // Memory is reused after reset(), so clear it rather than trusting it is zero. + new Uint8Array(this.memory.buffer, ptr, buffer.byteLength).fill(0); + return buffer; + } + + /** Allocates a buffer matching a typed array and copies it in. */ + upload(array) { + const type = elementTypeOf(array); + if (!type) throw new RuntimeError(`Unsupported array type ${array?.constructor?.name}`); + const buffer = this.alloc(type, array.length); + buffer.write(array); + return buffer; + } + + /** Frees every buffer. Existing DeviceBuffers become invalid. */ + reset() { + this.top = HEAP_BASE; + this.generation += 1; + } + + checkBuffer(buffer) { + if (buffer.runtime !== this) throw new RuntimeError('Buffer belongs to a different runtime'); + if (buffer.generation !== this.generation) throw new RuntimeError('Buffer was freed by reset()'); + } + + /** Compiles kernel source and instantiates it against this runtime's memory. */ + async load(source) { + const { ir, bytes } = compile(source); + const imports = { [MEMORY_IMPORT.module]: { [MEMORY_IMPORT.name]: this.memory } }; + const { instance } = await WebAssembly.instantiate(bytes, imports); + return new Kernel(this, ir, bytes, instance.exports[ir.name]); + } +} + +export class Kernel { + constructor(runtime, ir, bytes, fn) { + this.runtime = runtime; + this.ir = ir; + this.bytes = bytes; + this.fn = fn; + } + + get name() { + return this.ir.name; + } + + /** Runs a void kernel on grid × block threads: launch({ grid, block }, ...args). */ + launch({ grid, block }, ...args) { + if (this.ir.returnType !== null) throw new RuntimeError(`'${this.name}' returns a value; use call()`); + for (const [label, n] of [['grid', grid], ['block', block]]) { + if (!Number.isInteger(n) || n < 0 || n > MAX_I32) throw new RuntimeError(`Invalid ${label} size ${n}`); + } + if (grid * block > Number.MAX_SAFE_INTEGER) throw new RuntimeError('Launch is too large'); + this.fn(...this.marshal(args), grid, block); + } + + /** Calls a value-returning kernel once and returns its result. */ + call(...args) { + if (this.ir.returnType === null) throw new RuntimeError(`'${this.name}' is a void kernel; use launch()`); + const result = this.fn(...this.marshal(args)); + return this.ir.returnType === Type.U32 ? result >>> 0 : result; + } + + marshal(args) { + const { params } = this.ir; + if (args.length !== params.length) { + throw new RuntimeError(`'${this.name}' takes ${params.length} arguments but got ${args.length}`); + } + return params.map((param, i) => { + const arg = args[i]; + if (param.kind === 'buffer') { + if (!(arg instanceof DeviceBuffer)) throw new RuntimeError(`Argument '${param.name}' must be a DeviceBuffer`); + this.runtime.checkBuffer(arg); + if (arg.type !== param.type) { + throw new RuntimeError(`Argument '${param.name}' must be a ${param.type} buffer, not ${arg.type}`); + } + return arg.ptr; + } + if (typeof arg !== 'number') throw new RuntimeError(`Argument '${param.name}' must be a number`); + if (param.type === Type.I32 || param.type === Type.U32) { + const [min, max] = param.type === Type.I32 ? [-0x80000000, MAX_I32] : [0, 0xffffffff]; + if (!Number.isInteger(arg) || arg < min || arg > max) { + throw new RuntimeError(`Argument '${param.name}' must be a ${param.type} but got ${arg}`); + } + } + return arg; + }); + } +} diff --git a/unify/.gitignore b/unify/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..590d4b2bef118587b27227af201b6b19bf59e94a --- /dev/null +++ b/unify/.gitignore @@ -0,0 +1,12 @@ +build*/ +# Generated by unify_assetgen during the build +game/assets/textures/*.qoi +game/assets/textures/*.atlas +game/assets/audio/ +game/assets/music/ +game/assets/saves/*.usav +*.tmp + +!game/assets/textures/snapkitty/ +!game/assets/textures/snapkitty/*.qoi +!game/assets/textures/snapkitty/*.atlas diff --git a/unify/CMakeLists.txt b/unify/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5dc5c137125a475a1f8cb3942e7f206ee50f5b92 --- /dev/null +++ b/unify/CMakeLists.txt @@ -0,0 +1,104 @@ +cmake_minimum_required(VERSION 3.16) +project(unify LANGUAGES C CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE RelWithDebInfo) +endif() + +# Deterministic floating point: no fused multiply-add contraction, no fast-math. +# The same binary must produce bit-identical simulation results run to run. +if(MSVC) + set(UNIFY_FP_FLAGS /fp:strict /EHsc) + set(UNIFY_WARN_FLAGS /W4 /wd4100) + set(UNIFY_QUIET_FLAGS /w) + set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreadedDLL) +else() + set(UNIFY_FP_FLAGS -ffp-contract=off -fno-fast-math) + set(UNIFY_WARN_FLAGS -Wall -Wextra -Wno-unused-parameter) + set(UNIFY_QUIET_FLAGS -w) +endif() +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +# MinGW: link the C++ runtime statically so executables don't pick up a mismatched libstdc++ from PATH. +if(MINGW) + add_link_options(-static) +endif() + +# ---- Lua 5.4 (vendored, unmodified) ----------------------------------------------------- +file(GLOB LUA_SOURCES third_party/lua/src/*.c) +# Compiled as C++: Lua errors then use C++ exceptions instead of longjmp. +set_source_files_properties(${LUA_SOURCES} PROPERTIES LANGUAGE CXX) +add_library(lua STATIC ${LUA_SOURCES}) +target_include_directories(lua PUBLIC third_party/lua/src) +if(WIN32) + target_compile_definitions(lua PRIVATE LUA_USE_WINDOWS) +else() + target_compile_definitions(lua PRIVATE LUA_USE_POSIX) +endif() +target_compile_options(lua PRIVATE ${UNIFY_QUIET_FLAGS} ${UNIFY_FP_FLAGS}) + +# ---- Engine core (no platform dependencies) --------------------------------------------- +file(GLOB_RECURSE UNIFY_ENGINE_SOURCES engine/*.cpp) +add_library(unify_engine STATIC ${UNIFY_ENGINE_SOURCES}) +target_include_directories(unify_engine PUBLIC engine) +target_link_libraries(unify_engine PUBLIC lua) +target_compile_options(unify_engine PRIVATE ${UNIFY_WARN_FLAGS} ${UNIFY_FP_FLAGS}) +option(UNIFY_NO_GLOBAL_NEW "Do not replace global operator new (for hosts like Unreal that own it)" OFF) +if(UNIFY_NO_GLOBAL_NEW) + target_compile_definitions(unify_engine PUBLIC UNIFY_NO_GLOBAL_NEW=1) +endif() +find_package(Threads REQUIRED) +target_link_libraries(unify_engine PUBLIC Threads::Threads) + +# ---- Backends ----------------------------------------------------------------------------- +find_package(SDL2 QUIET) +if(SDL2_FOUND) + add_library(unify_sdl STATIC backends/sdl/sdl_backend.cpp) + target_include_directories(unify_sdl PUBLIC backends ${SDL2_INCLUDE_DIRS}) + target_link_libraries(unify_sdl PUBLIC unify_engine SDL2::SDL2) + message(STATUS "UNIFY: SDL2 backend enabled") +else() + message(STATUS "UNIFY: SDL2 not found; building headless only") +endif() + +# ---- Demo game ---------------------------------------------------------------------------- +set(UNIFY_GAME_ASSETS ${PROJECT_SOURCE_DIR}/game/assets) +add_executable(unify_assetgen tools/assetgen.cpp) +target_link_libraries(unify_assetgen PRIVATE unify_engine) +# Binary assets (sprites, SFX, music) are generated, not committed. +add_custom_command( + OUTPUT ${UNIFY_GAME_ASSETS}/textures/sprites.qoi ${UNIFY_GAME_ASSETS}/music/theme.wav + COMMAND unify_assetgen ${UNIFY_GAME_ASSETS} + DEPENDS unify_assetgen + COMMENT "Generating game assets") +add_custom_target(unify_assets ALL DEPENDS ${UNIFY_GAME_ASSETS}/textures/sprites.qoi ${UNIFY_GAME_ASSETS}/music/theme.wav) + +add_executable(unify_game game/main.cpp) +target_link_libraries(unify_game PRIVATE unify_engine) +target_compile_definitions(unify_game PRIVATE UNIFY_DEFAULT_ASSETS="${UNIFY_GAME_ASSETS}") +if(SDL2_FOUND) + target_link_libraries(unify_game PRIVATE unify_sdl) + target_compile_definitions(unify_game PRIVATE UNIFY_HAS_SDL=1) +endif() +add_dependencies(unify_game unify_assets) + +add_executable(unify_playtest tools/playtest.cpp) +target_link_libraries(unify_playtest PRIVATE unify_engine) +add_dependencies(unify_playtest unify_assets) + +# ---- Tests -------------------------------------------------------------------------------- +file(GLOB UNIFY_TEST_SOURCES tests/*.cpp) +add_executable(unify_tests ${UNIFY_TEST_SOURCES}) +target_link_libraries(unify_tests PRIVATE unify_engine) +target_compile_options(unify_tests PRIVATE ${UNIFY_FP_FLAGS}) +enable_testing() +target_compile_definitions(unify_tests PRIVATE UNIFY_GAME_ASSETS="${UNIFY_GAME_ASSETS}") +add_dependencies(unify_tests unify_assets) +add_test(NAME unify_tests COMMAND unify_tests WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}) +add_test(NAME unify_playtest COMMAND unify_playtest ${UNIFY_GAME_ASSETS} ${CMAKE_BINARY_DIR}) + +file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/snapkitty-evidence) +add_test(NAME snapkitty_playtest COMMAND unify_playtest ${UNIFY_GAME_ASSETS} ${CMAKE_BINARY_DIR}/snapkitty-evidence --snapkitty) diff --git a/unify/README.md b/unify/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f5a367738c378f622de69e48325bcab2712f50da --- /dev/null +++ b/unify/README.md @@ -0,0 +1,167 @@ +# UNIFY + +UNIFY is a 2D game engine runtime written in C++17, with Lua gameplay, a CUDA-like kernel compiler that +targets its own WASM runtime, and interchangeable platform backends. `game/` holds a small platformer +built on it, which proves the runtime end to end. + +``` +UNIFY where +├── renderer engine/render RenderDevice, Renderer2D (sort + batch), camera, atlas, QOI/PNG, bitmap font +├── physics engine/physics rigid bodies, SAP broadphase, SAT/clip manifolds, sequential impulses, CCD, islands +├── audio engine/audio mixer, buses, voices, WAV decoder, streaming ring buffer, device thread +├── input engine/input timestamped event queue → per-tick InputFrame, actions/axes, buffering +├── animation engine/animation sprite clips, keyframe tracks, loop/once/ping-pong, crossfade blending +├── scene engine/runtime scene stack with per-scene resource ownership, prefabs, transitions +├── ECS engine/ecs generational entities, sparse-set component pools +├── Lua engine/script Lua 5.4 VM: own allocator + budget, engine-scheduled GC, sandbox +├── memory / GC engine/memory Frame/Pool/Object/Asset/Buffer allocators, pool-backed STL allocator +├── assets engine/assets registry, ref-counted handles, cache, loaders +├── serialization engine/serialization tagged, versioned binary sections +├── save states engine/runtime save_state / load_state / snapshot / restore / state_hash +├── networking-ready state engine/net rollback buffer: snapshots + input log, rewind & resimulate +├── WASM runtime engine/wasm binary decoder, interpreter, shared linear memory, buffers +├── kernel compiler engine/kernel CUDA-like source → AST → IR → constant folding → WASM +└── Unreal backend backends/unreal UE5 plugin implementing unify::Backend (not compiled here, see Status) +``` + +## Build and run + +Requires CMake ≥ 3.16, a C++17 compiler, and optionally SDL2 (`libsdl2-dev`) for the windowed backend. + +```bash +cmake -S . -B build -G Ninja +cmake --build build # also generates the game's sprites, SFX and music (unify_assetgen) +ctest --test-dir build # 58 unit/integration tests + the definition-of-done playtest +./build/unify_game # SDL2 window: arrows/AD move, Space jump, F5 save, F9 load, Esc menu +./build/unify_game --headless --frames 600 --screenshot out.png +./build/unify_playtest game/assets out/ # scripted playthrough with verification + screenshots +``` + +## The engine loop + +Every real-time frame runs these stages. The playtest prints this order from the engine's own trace. + +``` +INPUT → INPUT BUFFER → FIXED SIMULATION → PHYSICS → GAMEPLAY / LUA → ANIMATION → AUDIO → RENDER PREPARATION → RENDER → PRESENT + └─────────────────── zero or more fixed 60 Hz ticks ──────────────────┘ +``` + +There are five separate clocks: + +| Clock | Where | Used for | +|---|---|---| +| Wall / input clock | `Backend::now_ns()` | timestamping OS events, deciding when ticks are due | +| Simulation | `SimClock` (integer ticks) | all gameplay, physics and animation. Seconds are derived from ticks, never accumulated | +| Render | `RenderClock` | interpolation factor between the last two sim states | +| Audio | `Mixer::frames_rendered()` | advanced by the audio device thread, independent of frame rate | +| Input | event timestamps | an event is consumed by the tick whose window contains it | + +A tick is due when `origin + (tick+1)·1e9/rate ≤ now`. After `max_ticks_per_frame`, a stall drops time +rather than spiralling. Rendering interpolates transforms, so 30, 60 and 144 FPS all run the same +60 ticks per second (tested). + +**Input buffering.** OS events are queued with timestamps. Each tick drains the events stamped before +its end and folds them into an `InputFrame`: `pressed`, `released`, `repeated`, `held`, axes and pointer. +A press and release that both land between two ticks still reads as *pressed* in the next tick; the +playtest checks this with a 3 ms tap. `input:buffered("jump", n)` gives gameplay a press window. + +## Determinism, save states, networking + +- One seeded RNG (xoshiro128**) is the only random source. Lua's `math.random` is rebound to it. + Lua has no `os` or `io`, so no wall-clock reads. +- The build uses `-ffp-contract=off -fno-fast-math`, and every container that affects the simulation + iterates in a deterministic order. +- **Save state** = tagged binary sections: `HEAD` (magic, version, engine, tick rate), `TIME` (tick, + timers), `RNG`, `SCEN` (scene stack, owned assets by name, buffers, kernels), `ECS` (entity pool and + component pools in dense order), `PHYS` (bodies, *and contact impulses for warm starting*), `ANIM`, + `INPT`, `CAMR`, `COMP` (live WASM buffers and kernel sources), `LUA` (the `game` table plus each scene's + `state`), and `AUDI` (voices by asset name and position). There are no raw pointers; handles and names + only. Unknown sections are skippable, and newer versions are refused. +- `save_state()` / `load_state()` from Lua are applied at the tick boundary. `snapshot()` / `restore()` + are the in-memory forms, and `save_to_file()` writes atomically. +- **Round trip:** restore reproduces the saved `state_hash()` exactly, in the same engine or a fresh one. + Replaying the recorded input from a restored state reproduces the original continuation bit for bit. +- `engine/net/rollback.h` keeps periodic snapshots plus the input log. `correct(tick, frame)` rewinds and + re-simulates. A test proves that a late-corrected timeline equals the true one. + +## Lua API + +Scenes are Lua files returning a table with `init`, `load`, `update(dt)`, `render`, `on_contact(a, b, +kind, nx, ny, impulse)`, `on_timer(name)`, `on_saved`, `on_loaded` and `unload`. UNIFY owns the lifecycle. + +```lua +entity:set_position(x, y) entity:set_velocity(x, y) entity:set_animation("run", blend) +physics:apply_force(entity, x, y) physics:raycast(x1, y1, x2, y2, mask, ignore) physics:add_static_box(...) +audio:play("audio/jump") audio:stream("music/theme") audio:stop(id, fade) audio:set_bus_volume("music", v) +input:is_pressed("jump") input:is_held("left") input:buffered("jump", ticks) input:axis("move") +world:spawn("prefabs/player", x, y) world:find(name) camera:set(x, y, zoom) ui:text(...) -- ui only in render() +timer.after(sec, name) scene.transition("level") animation.define{...} map.load("maps/level1") +buffer.create(n) buffer.upload(b, t) buffer.download(b) kernel.compile(src) kernel.load(k) kernel.dispatch(k, grid, block, ...) +save_state([slot]) load_state([slot]) gc_step() gc_budget(kb) gc_pause() gc_resume() gc_collect() +``` + +Lua only ever holds handles: entities, buffers and kernels are userdata that wrap a generational handle, +checked on every call. A destroyed entity raises `stale entity handle` instead of touching freed memory. +Lua memory comes from its own allocator with a hard cap (the default is 64 MB). The collector is stopped, +and the engine runs one budgeted incremental step per tick, plus a full collection only on scene loads. + +## Kernel compiler and WASM runtime + +```c +__global__ void vadd(const float* A, const float* B, float* C, int n) { + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) C[i] = A[i] + B[i]; +} +``` + +**Source → AST.** A lexer and recursive-descent parser handle `int`/`float`, pointers, `if`/`for`/`while`, +`break`/`continue`, casts, `sqrtf`/`fabsf`/`fminf`/`fmaxf`/`min`/`max`, and `threadIdx`/`blockIdx`/`blockDim`/`gridDim`. + +**AST → IR.** A typed, name-resolved, structured IR with explicit conversions, printed by `print_ir`. +Constant folding and dead-branch elimination run on it. + +**IR → WASM.** Each module imports `env.memory` and exports the kernel plus `__dispatch(grid, block, ...)`, +which loops over the whole grid inside WASM. + +**Runtime.** It decodes and validates the binary, builds block side tables, and interprets i32/i64/f32/f64. +Out-of-bounds access, divide by zero, stack overflow and fuel exhaustion are *traps*, returned as errors. +All kernels share one linear memory, and buffers are ranges handed out by `BufferAllocator`. + +The demo runs `vadd` on the title screen and integrates the sparkle particles with a second kernel. + +## Backends + +| Backend | Render | Audio | Input | Status | +|---|---|---|---|---| +| Headless | software device, offscreen | null device thread (real time) | programmatic / replay | built and tested | +| SDL2 (native) | software device → SDL texture, integer scaling | SDL audio callback | keyboard, mouse, game controller, touch | built; smoke-tested with SDL's dummy drivers | +| Unreal | `FCanvasTriangleItem` per batch, transient `UTexture2D` | `USynthComponent` | `AnyKey` bindings | **source only, not compiled** (no UE toolchain in CI) | + +The renderer is a `RenderDevice` interface. The engine ships a software rasterizer as its reference +device, and a GPU device would plug in at the same interface. + +## Verification + +- `unify_tests`: 58 tests covering every physics edge case in the spec (tunneling, bullets, resting + contacts, stacking, penetration, zero and infinite mass, tiny and huge bodies, coincident centres, + parallel edges, corner, edge and multi contacts, triggers, sleep and wake, filtering, NaN containment, + exact save/restore). They also cover input buffering, the mixer, streaming and loop points, the audio + device thread, renderer batching, blending, scissor and rotation, animation modes and blending, the + allocators, handles, RNG, the kernel pipeline, WASM traps, scene-transition leak checks, determinism + across engines, fresh-engine restore, Lua sandboxing, the handle and memory caps, GC scheduling, + **zero heap allocations per steady-state tick**, stage order, frame-rate independence, and rollback. +- `unify_playtest`: the definition of done, from BOOT to CONTINUE PLAYING, on the real game with + scripted input. Each stage is verified from engine state (hashes, counts, clips, voices) and + screenshots are written. +- The whole suite and the playtest are clean under AddressSanitizer and UndefinedBehaviorSanitizer. + +## Not included / known limits + +- The **WASM *platform* backend** (compiling UNIFY itself to WebAssembly for browsers) is not built. It + needs Emscripten, which isn't available here. The engine core has no platform dependencies, so it is + a backend-sized job. UNIFY's WASM *runtime* for kernels is fully built. +- **Unreal backend**: see the table above. +- **Compilers**: builds with GCC and Clang, and with MinGW-w64 GCC on Windows (runtime linked statically). + MSVC is not supported: the code uses `__builtin_clz` and `__uint128_t`. +- Audio decodes PCM16 WAV only. Physics has no joints. Scissor rectangles are not applied on the Unreal + backend. The software renderer is the only render device. diff --git a/unify/backends/sdl/sdl_backend.cpp b/unify/backends/sdl/sdl_backend.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c59626dfb2bcf6064b29ba181fda9e1e4862684e --- /dev/null +++ b/unify/backends/sdl/sdl_backend.cpp @@ -0,0 +1,192 @@ +#include "sdl_backend.h" +#include "core/core.h" +#include + +namespace unify { + +// ------------------------------------------------------------------------------ audio + +void SdlAudioDevice::callback(void* user, uint8_t* stream, int len) { + auto* self = static_cast(user); + self->mixer_->render(reinterpret_cast(stream), uint32_t(len / int(sizeof(float) * 2))); +} + +bool SdlAudioDevice::start(Mixer& mixer) { + mixer_ = &mixer; + SDL_AudioSpec want{}, have{}; + want.freq = int(mixer.device_rate()); + want.format = AUDIO_F32SYS; + want.channels = 2; + want.samples = 512; + want.callback = &SdlAudioDevice::callback; + want.userdata = this; + device_ = SDL_OpenAudioDevice(nullptr, 0, &want, &have, 0); + if (!device_) { UNIFY_LOG_WARN("AUDIO", "SDL audio unavailable: %s", SDL_GetError()); return false; } + SDL_PauseAudioDevice(device_, 0); + UNIFY_LOG_INFO("AUDIO", "SDL audio: %d Hz, %d-frame buffer", have.freq, have.samples); + return true; +} + +void SdlAudioDevice::stop() { + if (device_) { SDL_CloseAudioDevice(device_); device_ = 0; } +} + +// ------------------------------------------------------------------------------ backend + +AudioDevice& SdlBackend::audio_device() { return audio_ok_ ? static_cast(audio_) : null_audio_; } + +bool SdlBackend::init(const EngineConfig& config, std::string& error) { + SDL_SetMainReady(); + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER) != 0) { error = SDL_GetError(); return false; } + if (SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) { + UNIFY_LOG_WARN("AUDIO", "SDL audio subsystem failed (%s); using the null device", SDL_GetError()); + audio_ok_ = false; + } else { + // Probe the device now so the engine starts the right one. + SDL_AudioSpec want{}, have{}; + want.freq = 44100; want.format = AUDIO_F32SYS; want.channels = 2; want.samples = 512; + want.callback = [](void*, uint8_t* s, int n) { SDL_memset(s, 0, size_t(n)); }; + SDL_AudioDeviceID probe = SDL_OpenAudioDevice(nullptr, 0, &want, &have, 0); + if (!probe) { audio_ok_ = false; UNIFY_LOG_WARN("AUDIO", "no audio device (%s); using the null device", SDL_GetError()); } + else SDL_CloseAudioDevice(probe); + } + width_ = config.width; + height_ = config.height; + window_ = SDL_CreateWindow(config.title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width_ * 2, height_ * 2, + SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); + if (!window_) { error = SDL_GetError(); return false; } + renderer_ = SDL_CreateRenderer(window_, -1, SDL_RENDERER_PRESENTVSYNC); + if (!renderer_) renderer_ = SDL_CreateRenderer(window_, -1, SDL_RENDERER_SOFTWARE); + if (!renderer_) { error = SDL_GetError(); return false; } + SDL_RenderSetLogicalSize(renderer_, width_, height_); // integer-scaled pixel art, letterboxed + SDL_RenderSetIntegerScale(renderer_, SDL_TRUE); + texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, width_, height_); + if (!texture_) { error = SDL_GetError(); return false; } + for (int i = 0; i < SDL_NumJoysticks(); i++) + if (SDL_IsGameController(i)) { pad_ = SDL_GameControllerOpen(i); break; } + perf_freq_ = SDL_GetPerformanceFrequency(); + perf_start_ = SDL_GetPerformanceCounter(); + initialized_ = true; + UNIFY_LOG_INFO("BOOT", "SDL %s video driver, window %dx%d", SDL_GetCurrentVideoDriver(), width_ * 2, height_ * 2); + return true; +} + +uint64_t SdlBackend::now_ns() { + uint64_t t = SDL_GetPerformanceCounter() - perf_start_; + return uint64_t((__uint128_t(t) * 1000000000u) / perf_freq_); +} + +static uint16_t map_key(SDL_Keycode k) { + switch (k) { + case SDLK_SPACE: return key::Space; + case SDLK_LEFT: return key::Left; + case SDLK_RIGHT: return key::Right; + case SDLK_UP: return key::Up; + case SDLK_DOWN: return key::Down; + case SDLK_RETURN: return key::Enter; + case SDLK_ESCAPE: return key::Escape; + case SDLK_F1: return key::F1; + case SDLK_F2: return key::F2; + case SDLK_F3: return key::F3; + case SDLK_F5: return key::F5; + case SDLK_F9: return key::F9; + case SDLK_LSHIFT: return key::LShift; + default: return (k >= 'a' && k <= 'z') ? uint16_t(k) : 0; + } +} +static uint16_t map_pad(uint8_t b) { + switch (b) { + case SDL_CONTROLLER_BUTTON_A: return key::PadA; + case SDL_CONTROLLER_BUTTON_B: return key::PadB; + case SDL_CONTROLLER_BUTTON_X: return key::PadX; + case SDL_CONTROLLER_BUTTON_Y: return key::PadY; + case SDL_CONTROLLER_BUTTON_START: return key::PadStart; + case SDL_CONTROLLER_BUTTON_BACK: return key::PadBack; + case SDL_CONTROLLER_BUTTON_DPAD_LEFT: return key::PadLeft; + case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: return key::PadRight; + case SDL_CONTROLLER_BUTTON_DPAD_UP: return key::PadUp; + case SDL_CONTROLLER_BUTTON_DPAD_DOWN: return key::PadDown; + default: return 0; + } +} + +void SdlBackend::poll(InputSystem& input, bool& quit) { + SDL_Event ev; + while (SDL_PollEvent(&ev)) { + InputEvent e; + e.timestamp_ns = now_ns(); // stamped on arrival: decides which simulation tick consumes it + switch (ev.type) { + case SDL_QUIT: quit = true; break; + case SDL_KEYDOWN: case SDL_KEYUP: + e.device = InputDevice::Keyboard; + e.code = map_key(ev.key.keysym.sym); + if (!e.code) break; + e.type = ev.type == SDL_KEYUP ? InputEventType::ButtonUp : ev.key.repeat ? InputEventType::ButtonRepeat : InputEventType::ButtonDown; + input.push(e); + break; + case SDL_MOUSEMOTION: { + float lx, ly; + SDL_RenderWindowToLogical(renderer_, ev.motion.x, ev.motion.y, &lx, &ly); + e.device = InputDevice::Mouse; e.type = InputEventType::PointerMove; e.value = lx; e.value2 = ly; + input.push(e); + break; + } + case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: + e.device = InputDevice::Mouse; + e.type = ev.type == SDL_MOUSEBUTTONDOWN ? InputEventType::ButtonDown : InputEventType::ButtonUp; + e.code = ev.button.button == SDL_BUTTON_LEFT ? key::MouseLeft : ev.button.button == SDL_BUTTON_RIGHT ? key::MouseRight : key::MouseMiddle; + input.push(e); + break; + case SDL_CONTROLLERBUTTONDOWN: case SDL_CONTROLLERBUTTONUP: + e.device = InputDevice::Gamepad; + e.type = ev.type == SDL_CONTROLLERBUTTONDOWN ? InputEventType::ButtonDown : InputEventType::ButtonUp; + e.code = map_pad(ev.cbutton.button); + if (e.code) input.push(e); + break; + case SDL_CONTROLLERAXISMOTION: + if (ev.caxis.axis == SDL_CONTROLLER_AXIS_LEFTX || ev.caxis.axis == SDL_CONTROLLER_AXIS_LEFTY) { + e.device = InputDevice::Gamepad; e.type = InputEventType::Axis; + e.code = ev.caxis.axis == SDL_CONTROLLER_AXIS_LEFTX ? key::PadAxisLeftX : key::PadAxisLeftY; + e.value = ev.caxis.value / 32767.0f; + input.push(e); + } + break; + case SDL_CONTROLLERDEVICEADDED: + if (!pad_) pad_ = SDL_GameControllerOpen(ev.cdevice.which); + break; + case SDL_FINGERDOWN: case SDL_FINGERUP: case SDL_FINGERMOTION: + e.device = InputDevice::Touch; + e.type = InputEventType::PointerMove; e.value = ev.tfinger.x * float(width_); e.value2 = ev.tfinger.y * float(height_); + input.push(e); + if (ev.type != SDL_FINGERMOTION) { + e.type = ev.type == SDL_FINGERDOWN ? InputEventType::ButtonDown : InputEventType::ButtonUp; + e.code = key::Touch0; + input.push(e); + } + break; + default: break; + } + } +} + +void SdlBackend::present(const RenderTarget& frame) { + SDL_UpdateTexture(texture_, nullptr, frame.color.pixels.data(), frame.width() * 4); + SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 255); + SDL_RenderClear(renderer_); + SDL_RenderCopy(renderer_, texture_, nullptr, nullptr); + SDL_RenderPresent(renderer_); +} + +void SdlBackend::shutdown() { + if (!initialized_) return; + audio_.stop(); + null_audio_.stop(); + if (pad_) SDL_GameControllerClose(pad_); + if (texture_) SDL_DestroyTexture(texture_); + if (renderer_) SDL_DestroyRenderer(renderer_); + if (window_) SDL_DestroyWindow(window_); + SDL_Quit(); + initialized_ = false; +} + +} // namespace unify diff --git a/unify/backends/sdl/sdl_backend.h b/unify/backends/sdl/sdl_backend.h new file mode 100644 index 0000000000000000000000000000000000000000..0e1591b7f64ab6d09b528b0afa6afaa6d0b96d5c --- /dev/null +++ b/unify/backends/sdl/sdl_backend.h @@ -0,0 +1,52 @@ +#pragma once +#include "runtime/backend.h" + +struct SDL_Window; +struct SDL_Renderer; +struct SDL_Texture; +struct _SDL_GameController; + +namespace unify { + +/// Hardware audio through SDL: the mixer runs inside SDL's audio callback thread. +class SdlAudioDevice : public AudioDevice { +public: + ~SdlAudioDevice() override { stop(); } + bool start(Mixer& mixer) override; + void stop() override; + const char* name() const override { return "sdl"; } +private: + static void callback(void* user, uint8_t* stream, int len); + uint32_t device_ = 0; + Mixer* mixer_ = nullptr; +}; + +/// Native desktop backend: SDL2 window + presentation of the software-rendered frame, +/// SDL audio, and keyboard/mouse/gamepad/touch input. +class SdlBackend : public Backend { +public: + ~SdlBackend() override { shutdown(); } + const char* name() const override { return "sdl2"; } + bool init(const EngineConfig& config, std::string& error) override; + RenderDevice& render_device() override { return device_; } + AudioDevice& audio_device() override; + void poll(InputSystem& input, bool& quit) override; + void present(const RenderTarget& frame) override; + uint64_t now_ns() override; + void shutdown() override; + +private: + SoftwareRenderDevice device_; + SdlAudioDevice audio_; + NullAudioDevice null_audio_; + bool audio_ok_ = true; + SDL_Window* window_ = nullptr; + SDL_Renderer* renderer_ = nullptr; + SDL_Texture* texture_ = nullptr; + _SDL_GameController* pad_ = nullptr; + int width_ = 0, height_ = 0; + uint64_t perf_freq_ = 1, perf_start_ = 0; + bool initialized_ = false; +}; + +} // namespace unify diff --git a/unify/backends/unreal/README.md b/unify/backends/unreal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c7c235c27634c268f167fbcf5d47bcc98c9416be --- /dev/null +++ b/unify/backends/unreal/README.md @@ -0,0 +1,30 @@ +For the ready-to-configure Repoverse host project and automated setup, see +[unreal/README.md](../../../unreal/README.md). The manual backend notes follow. + +# UNIFY Unreal backend + +An Unreal Engine 5 plugin that runs UNIFY games inside Unreal. It implements `unify::Backend`, the same +interface as the SDL2 and headless backends: + +| UNIFY | Unreal | +|---|---| +| `RenderDevice::create_texture` | transient `UTexture2D` (nearest filtering) | +| `RenderDevice::draw(Batch)` | one `FCanvasTriangleItem` per UNIFY batch, drawn in `AUnifyHUD::DrawHUD` | +| `AudioDevice` | `UUnifySynthComponent::OnGenerateAudio` runs UNIFY's mixer on the audio render thread | +| `Backend::poll` | `AnyKey` press/release bindings, stamped with `FPlatformTime` into UNIFY's input buffer | +| `Backend::now_ns` | `FPlatformTime::Cycles64` | + +Gameplay stays in UNIFY Lua scripts. Scripts never see an Unreal type, and the same `game/assets` +folder runs unchanged on SDL2, headless and Unreal. + +## Status + +This source is written against the UE5 API but **has not been compiled**: UNIFY's CI has no Unreal +toolchain. Expect small API fixes on first build, for example `UTexture2D` field access differs between +UE 5.x minor versions. Scissor rectangles are recorded but not yet applied as canvas clip rects. + +## Use + +1. Build UNIFY with CMake. Set `UNIFY_ROOT` / `UNIFY_BUILD` for `UnifyUnreal.Build.cs`. +2. Copy this folder to `/Plugins/UnifyUnreal` and copy `game/assets` to `/Unify/assets`. +3. Place an `AUnifyHost` actor in a level, and set the GameMode's HUD class to `AUnifyHUD`. diff --git a/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyGameMode.cpp b/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyGameMode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d84b9d088d3a52f092fa9d2e8a0f10e04848239 --- /dev/null +++ b/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyGameMode.cpp @@ -0,0 +1,22 @@ +#include "UnifyGameMode.h" +#include "UnifyHost.h" +#include "Engine/World.h" +#include "EngineUtils.h" +#include "GameFramework/PlayerController.h" +AUnifyGameMode::AUnifyGameMode() +{ + HUDClass = AUnifyHUD::StaticClass(); + DefaultPawnClass = nullptr; +} +void AUnifyGameMode::StartPlay() +{ + Super::StartPlay(); + bool Found = false; + for (TActorIterator It(GetWorld()); It; ++It) { Found = true; break; } + if (!Found) GetWorld()->SpawnActor(); + if (APlayerController* PC = GetWorld()->GetFirstPlayerController()) + { + PC->SetInputMode(FInputModeGameOnly()); + PC->bShowMouseCursor = false; + } +} diff --git a/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyHost.cpp b/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyHost.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2832b051120cb1e053287321a50d660a1fa95fd1 --- /dev/null +++ b/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyHost.cpp @@ -0,0 +1,85 @@ +// STATUS: written against the UE5 API; not compiled in UNIFY's CI. See UnifyUnrealBackend.h. +#include "UnifyHost.h" +#include "UnifyUnrealBackend.h" +#include "EngineUtils.h" +#include "Components/InputComponent.h" +#include "GameFramework/PlayerController.h" +#include "Misc/Paths.h" +#include "runtime/engine.h" + +AUnifyHost::AUnifyHost() +{ + PrimaryActorTick.bCanEverTick = true; + Synth = CreateDefaultSubobject(TEXT("UnifyAudio")); + RootComponent = Synth; +} + +AUnifyHost::~AUnifyHost() = default; + +void AUnifyHost::BeginPlay() +{ + Super::BeginPlay(); + Backend = std::make_unique(); + Backend->Synth = Synth; + + unify::EngineConfig Config; + Config.asset_root = TCHAR_TO_UTF8(*FPaths::Combine(FPaths::ProjectDir(), AssetRoot)); + Config.boot_scene = TCHAR_TO_UTF8(*BootScene); + Engine = std::make_unique(*Backend, Config); + std::string Error; + if (!Engine->boot(Error)) + { + UE_LOG(LogTemp, Error, TEXT("UNIFY boot failed: %s"), UTF8_TO_TCHAR(Error.c_str())); + Engine.reset(); + return; + } + + // Route every key through UNIFY's input buffer. UNIFY, not Unreal, decides what a key means. + if (APlayerController* PC = GetWorld()->GetFirstPlayerController()) + { + EnableInput(PC); + FInputKeyBinding Down(FInputChord(EKeys::AnyKey), IE_Pressed); + Down.KeyDelegate.GetDelegateWithKeyForManualSet().BindUObject(this, &AUnifyHost::HandleKeyDown); + InputComponent->KeyBindings.Add(Down); + FInputKeyBinding Up(FInputChord(EKeys::AnyKey), IE_Released); + Up.KeyDelegate.GetDelegateWithKeyForManualSet().BindUObject(this, &AUnifyHost::HandleKeyUp); + InputComponent->KeyBindings.Add(Up); + } +} + +void AUnifyHost::HandleKeyDown(FKey Key) { if (Backend) Backend->QueueKey(Key, true, false); } +void AUnifyHost::HandleKeyUp(FKey Key) { if (Backend) Backend->QueueKey(Key, false, false); } + +void AUnifyHost::Tick(float DeltaSeconds) +{ + Super::Tick(DeltaSeconds); + // One UNIFY frame per Unreal frame: UNIFY runs its own fixed-step simulation inside it, + // independent of Unreal's variable DeltaSeconds. + if (Engine && !Engine->quit_requested()) Engine->frame(); +} + +void AUnifyHost::DrawToCanvas(UCanvas* Canvas) +{ + if (Engine) Backend->Device.FlushToCanvas(Canvas, float(Engine->config().width), float(Engine->config().height)); +} + +void AUnifyHost::EndPlay(const EEndPlayReason::Type Reason) +{ + Engine.reset(); + if (Backend) Backend->shutdown(); + Backend.reset(); + Super::EndPlay(Reason); +} + +void AUnifyHost::AddReferencedObjects(UObject* This, FReferenceCollector& Collector) +{ + AUnifyHost* Self = CastChecked(This); + if (Self->Backend) Self->Backend->Device.AddReferencedObjects(Collector); + Super::AddReferencedObjects(This, Collector); +} + +void AUnifyHUD::DrawHUD() +{ + Super::DrawHUD(); + for (TActorIterator It(GetWorld()); It; ++It) It->DrawToCanvas(Canvas); +} diff --git a/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyUnrealBackend.cpp b/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyUnrealBackend.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8e2aa7bb09d12ee1600afd072f019861fd97987a --- /dev/null +++ b/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyUnrealBackend.cpp @@ -0,0 +1,271 @@ +// STATUS: written against the UE5 API; not compiled in UNIFY's CI. See UnifyUnrealBackend.h. +#include "UnifyUnrealBackend.h" +#include "Engine/Canvas.h" +#include "Engine/Texture2D.h" +#include "CanvasItem.h" +#include "HAL/PlatformTime.h" +#include "InputCoreTypes.h" +#include "Misc/ScopeLock.h" + +// ---------------------------------------------------------------------------------- render device + +static UTexture2D* MakeTexture(const unify::Image& Image) +{ + UTexture2D* Tex = UTexture2D::CreateTransient(Image.width, Image.height, PF_R8G8B8A8); + Tex->Filter = TF_Nearest; // pixel art + Tex->SRGB = true; + Tex->CompressionSettings = TC_EditorIcon; + Tex->UpdateResource(); + const int32 Bytes = Image.width * Image.height * 4; + uint8* Copy = static_cast(FMemory::Malloc(Bytes)); + FMemory::Memcpy(Copy, Image.pixels.data(), Bytes); + auto* Region = new FUpdateTextureRegion2D(0, 0, 0, 0, Image.width, Image.height); + Tex->UpdateTextureRegions(0, 1, Region, Image.width * 4, 4, Copy, + [](uint8* Data, const FUpdateTextureRegion2D* R) { FMemory::Free(Data); delete R; }); + return Tex; +} + +unify::TextureHandle FUnifyUnrealRenderDevice::create_texture(const unify::Image& Image) +{ + unify::TextureHandle H = Handles.allocate(); + const int32 Slot = int32(H.index()); + if (Slot >= Textures.Num()) { Textures.SetNum(Slot + 1); Sizes.SetNum(Slot + 1); } + Textures[Slot] = MakeTexture(Image); + Sizes[Slot] = FIntPoint(Image.width, Image.height); + return H; +} + +bool FUnifyUnrealRenderDevice::update_texture(unify::TextureHandle H, const unify::Image& Image) +{ + if (!Handles.valid(H)) return false; + Textures[int32(H.index())] = MakeTexture(Image); + Sizes[int32(H.index())] = FIntPoint(Image.width, Image.height); + return true; +} + +bool FUnifyUnrealRenderDevice::destroy_texture(unify::TextureHandle H) +{ + if (!Handles.valid(H)) return false; + Textures[int32(H.index())] = nullptr; // released to Unreal's GC + return Handles.release(H); +} + +bool FUnifyUnrealRenderDevice::texture_size(unify::TextureHandle H, int& W, int& Hh) const +{ + if (!Handles.valid(H)) return false; + W = Sizes[int32(H.index())].X; + Hh = Sizes[int32(H.index())].Y; + return true; +} + +void FUnifyUnrealRenderDevice::begin(unify::RenderTarget&, unify::Color Clear) +{ + Frame.Reset(); + ClearColor = FLinearColor(FColor(Clear.r, Clear.g, Clear.b, Clear.a)); + if (!White) White = MakeTexture(unify::Image(1, 1, {255, 255, 255, 255})); +} + +void FUnifyUnrealRenderDevice::draw(const unify::Batch& Batch) +{ + FRecordedBatch& Out = Frame.AddDefaulted_GetRef(); + UTexture2D* Tex = White; + FIntPoint Size(1, 1); + unify::TextureHandle H{Batch.texture}; + if (Batch.texture && Handles.valid(H)) { Tex = Textures[int32(H.index())]; Size = Sizes[int32(H.index())]; } + Out.Texture = Tex; + Out.Scissor = Batch.scissor; + switch (Batch.material.blend) + { + case unify::BlendMode::Opaque: Out.Blend = SE_BLEND_Opaque; break; + case unify::BlendMode::Additive: Out.Blend = SE_BLEND_Additive; break; + case unify::BlendMode::Multiply: Out.Blend = SE_BLEND_Modulate; break; + default: Out.Blend = SE_BLEND_Translucent; break; + } + Out.Tris.Reserve(Batch.quad_count * 2); + for (uint32 Q = 0; Q < Batch.quad_count; ++Q) + { + const unify::Vertex* V = Batch.vertices + Q * 4; + auto Vert = [&](const unify::Vertex& X, FVector2D& Pos, FVector2D& UV, FLinearColor& Col) + { + Pos = FVector2D(X.x, X.y); + UV = FVector2D(X.u / Size.X, X.v / Size.Y); // UNIFY UVs are texels; Unreal wants 0..1 + Col = FLinearColor(FColor(X.color.r, X.color.g, X.color.b, X.color.a)); + }; + static const int32 QuadTris[2][3] = {{0, 1, 2}, {0, 2, 3}}; + for (const int32* Tri : QuadTris) + { + FCanvasUVTri T; + Vert(V[Tri[0]], T.V0_Pos, T.V0_UV, T.V0_Color); + Vert(V[Tri[1]], T.V1_Pos, T.V1_UV, T.V1_Color); + Vert(V[Tri[2]], T.V2_Pos, T.V2_UV, T.V2_Color); + Out.Tris.Add(T); + } + } +} + +void FUnifyUnrealRenderDevice::FlushToCanvas(UCanvas* Canvas, float LogicalWidth, float LogicalHeight) +{ + if (!Canvas) return; + const float Scale = FMath::Min(Canvas->ClipX / LogicalWidth, Canvas->ClipY / LogicalHeight); + const FVector2D Offset((Canvas->ClipX - LogicalWidth * Scale) * 0.5f, (Canvas->ClipY - LogicalHeight * Scale) * 0.5f); + FCanvasTileItem Background(Offset, FVector2D(LogicalWidth * Scale, LogicalHeight * Scale), ClearColor); + Canvas->DrawItem(Background); + for (FRecordedBatch& B : Frame) + { + TArray Scaled = B.Tris; + for (FCanvasUVTri& T : Scaled) + { + T.V0_Pos = Offset + T.V0_Pos * Scale; + T.V1_Pos = Offset + T.V1_Pos * Scale; + T.V2_Pos = Offset + T.V2_Pos * Scale; + } + // Scissor rectangles are recorded (B.Scissor) but not yet applied on this backend. + FCanvasTriangleItem Item(Scaled, B.Texture->GetResource()); + Item.BlendMode = B.Blend; + Canvas->DrawItem(Item); + } +} + +void FUnifyUnrealRenderDevice::AddReferencedObjects(FReferenceCollector& Collector) +{ + Collector.AddReferencedObjects(Textures); + Collector.AddReferencedObject(White); +} + +// ---------------------------------------------------------------------------------- audio + +bool UUnifySynthComponent::Init(int32& SampleRate) +{ + NumChannels = 2; + SampleRate = Mixer ? int32(Mixer->device_rate()) : 44100; + return true; +} + +int32 UUnifySynthComponent::OnGenerateAudio(float* OutAudio, int32 NumSamples) +{ + // Audio render thread: UNIFY's mixer is designed to be driven from exactly this kind of thread. + FScopeLock Lock(&MixerLock); + if (Mixer) Mixer->render(OutAudio, uint32(NumSamples / 2)); + else FMemory::Memzero(OutAudio, NumSamples * sizeof(float)); + return NumSamples; +} + +bool FUnifyUnrealAudioDevice::start(unify::Mixer& Mixer) +{ + if (!Synth) return false; + { FScopeLock Lock(&Synth->MixerLock); Synth->Mixer = &Mixer; } + Synth->Start(); + return true; +} + +void FUnifyUnrealAudioDevice::stop() +{ + if (Synth) { + { FScopeLock Lock(&Synth->MixerLock); Synth->Mixer = nullptr; } + Synth->Stop(); + } +} + +// ---------------------------------------------------------------------------------- backend + +bool FUnifyUnrealBackend::init(const unify::EngineConfig&, std::string& Error) +{ + if (!Synth) { Error = "UUnifySynthComponent missing (AUnifyHost creates it)"; return false; } + return true; +} + +uint64_t FUnifyUnrealBackend::now_ns() +{ + return uint64_t(double(FPlatformTime::Cycles64()) * FPlatformTime::GetSecondsPerCycle64() * 1e9); +} + +static uint16 MapKey(const FKey& Key) +{ + using namespace unify; + if (Key == EKeys::SpaceBar) return key::Space; + if (Key == EKeys::Left) return key::Left; + if (Key == EKeys::Right) return key::Right; + if (Key == EKeys::Up) return key::Up; + if (Key == EKeys::Down) return key::Down; + if (Key == EKeys::Enter) return key::Enter; + if (Key == EKeys::Escape) return key::Escape; + if (Key == EKeys::F5) return key::F5; + if (Key == EKeys::F9) return key::F9; + if (Key == EKeys::A) return key::A; + if (Key == EKeys::D) return key::D; + if (Key == EKeys::W) return key::W; + if (Key == EKeys::S) return key::S; + if (Key == EKeys::E) return key::E; + if (Key == EKeys::I) return key::I; + if (Key == EKeys::R) return key::R; + if (Key == EKeys::LeftMouseButton) return key::MouseLeft; + if (Key == EKeys::Gamepad_FaceButton_Bottom) return key::PadA; + if (Key == EKeys::Gamepad_FaceButton_Right) return key::PadB; + if (Key == EKeys::Gamepad_Special_Right) return key::PadStart; + if (Key == EKeys::Gamepad_DPad_Left) return key::PadLeft; + if (Key == EKeys::Gamepad_DPad_Right) return key::PadRight; + if (Key == EKeys::Gamepad_LeftX) return key::PadAxisLeftX; + if (Key == EKeys::Gamepad_LeftY) return key::PadAxisLeftY; + return 0; +} + +void FUnifyUnrealBackend::QueueKey(const FKey& Key, bool bDown, bool bRepeat) +{ + const uint16 Code = MapKey(Key); + if (!Code) return; + unify::InputEvent E; + E.timestamp_ns = now_ns(); + E.device = Key.IsGamepadKey() ? unify::InputDevice::Gamepad : Key.IsMouseButton() ? unify::InputDevice::Mouse : unify::InputDevice::Keyboard; + E.type = !bDown ? unify::InputEventType::ButtonUp : bRepeat ? unify::InputEventType::ButtonRepeat : unify::InputEventType::ButtonDown; + E.code = Code; + FScopeLock Lock(&PendingLock); + Pending.Add(E); +} + +void FUnifyUnrealBackend::QueueAxis(const FKey& Key, float Value) +{ + const uint16 Code = MapKey(Key); + if (!Code) return; + unify::InputEvent E; + E.timestamp_ns = now_ns(); + E.device = unify::InputDevice::Gamepad; + E.type = unify::InputEventType::Axis; + E.code = Code; + E.value = Value; + FScopeLock Lock(&PendingLock); + Pending.Add(E); +} + +void FUnifyUnrealBackend::QueuePointer(float X, float Y) +{ + unify::InputEvent E; + E.timestamp_ns = now_ns(); + E.device = unify::InputDevice::Mouse; + E.type = unify::InputEventType::PointerMove; + E.value = X; + E.value2 = Y; + FScopeLock Lock(&PendingLock); + Pending.Add(E); +} + +void FUnifyUnrealBackend::poll(unify::InputSystem& Input, bool& Quit) +{ + TArray Events; + { + FScopeLock Lock(&PendingLock); + Events = MoveTemp(Pending); + } + for (const unify::InputEvent& E : Events) Input.push(E); + Quit = Quit || bQuitRequested; +} + +void FUnifyUnrealBackend::present(const unify::RenderTarget&) +{ + // Batches were recorded by FUnifyUnrealRenderDevice::draw(); AUnifyHUD::DrawHUD flushes + // them onto the canvas in Unreal's own draw pass. +} + +void FUnifyUnrealBackend::shutdown() +{ + Audio.stop(); +} diff --git a/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyUnrealModule.cpp b/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyUnrealModule.cpp new file mode 100644 index 0000000000000000000000000000000000000000..80027bb38fd1cab7682b8ace1d655345fa3514e9 --- /dev/null +++ b/unify/backends/unreal/Source/UnifyUnreal/Private/UnifyUnrealModule.cpp @@ -0,0 +1,2 @@ +#include "Modules/ModuleManager.h" +IMPLEMENT_MODULE(FDefaultModuleImpl, UnifyUnreal) diff --git a/unify/backends/unreal/Source/UnifyUnreal/Public/UnifyGameMode.h b/unify/backends/unreal/Source/UnifyUnreal/Public/UnifyGameMode.h new file mode 100644 index 0000000000000000000000000000000000000000..36657b4506761a11970a7fe72c3abd5b9ba705b6 --- /dev/null +++ b/unify/backends/unreal/Source/UnifyUnreal/Public/UnifyGameMode.h @@ -0,0 +1,12 @@ +#pragma once +#include "CoreMinimal.h" +#include "GameFramework/GameModeBase.h" +#include "UnifyGameMode.generated.h" +UCLASS() +class UNIFYUNREAL_API AUnifyGameMode : public AGameModeBase +{ + GENERATED_BODY() +public: + AUnifyGameMode(); + virtual void StartPlay() override; +}; diff --git a/unify/backends/unreal/Source/UnifyUnreal/Public/UnifyHost.h b/unify/backends/unreal/Source/UnifyUnreal/Public/UnifyHost.h new file mode 100644 index 0000000000000000000000000000000000000000..ae55e902fc08156eced72dc61f2c48b23f1aeae4 --- /dev/null +++ b/unify/backends/unreal/Source/UnifyUnreal/Public/UnifyHost.h @@ -0,0 +1,47 @@ +// Hosts a unify::Engine inside an Unreal level. Drop AUnifyHost into a map (or spawn it from a +// GameMode) and set AUnifyHUD as the HUD class. STATUS: see UnifyUnrealBackend.h. +#pragma once + +#include "CoreMinimal.h" +#include "GameFramework/Actor.h" +#include "GameFramework/HUD.h" +#include +#include "UnifyHost.generated.h" + +class FUnifyUnrealBackend; +namespace unify { class Engine; } + +UCLASS() +class UNIFYUNREAL_API AUnifyHost : public AActor +{ + GENERATED_BODY() +public: + AUnifyHost(); + virtual ~AUnifyHost() override; + virtual void BeginPlay() override; + virtual void EndPlay(const EEndPlayReason::Type Reason) override; + virtual void Tick(float DeltaSeconds) override; + static void AddReferencedObjects(UObject* This, FReferenceCollector& Collector); + + /// UNIFY asset root (scenes/, prefabs/, textures/ ...), relative to the project directory. + UPROPERTY(EditAnywhere, Category = "UNIFY") FString AssetRoot = TEXT("Unify/assets"); + UPROPERTY(EditAnywhere, Category = "UNIFY") FString BootScene = TEXT("snapkitty"); + + void DrawToCanvas(UCanvas* Canvas); + +private: + void HandleKeyDown(FKey Key); + void HandleKeyUp(FKey Key); + + UPROPERTY() TObjectPtr Synth; + std::unique_ptr Backend; + std::unique_ptr Engine; +}; + +UCLASS() +class UNIFYUNREAL_API AUnifyHUD : public AHUD +{ + GENERATED_BODY() +public: + virtual void DrawHUD() override; +}; diff --git a/unify/backends/unreal/Source/UnifyUnreal/Public/UnifyUnrealBackend.h b/unify/backends/unreal/Source/UnifyUnreal/Public/UnifyUnrealBackend.h new file mode 100644 index 0000000000000000000000000000000000000000..c31fc52975fdf96f220efba51b729328aac5209c --- /dev/null +++ b/unify/backends/unreal/Source/UnifyUnreal/Public/UnifyUnrealBackend.h @@ -0,0 +1,97 @@ +// UNIFY -> Unreal backend. +// +// STATUS: written against the UE5 API; not compiled in UNIFY's CI (no Unreal toolchain there). +// The interface it implements (unify::Backend) is the same one the SDL2 and headless backends +// implement and that CI exercises. +#pragma once + +#include "CoreMinimal.h" +#include "CanvasItem.h" +#include "Components/SynthComponent.h" +#include "runtime/backend.h" +#include "UnifyUnrealBackend.generated.h" + +class UTexture2D; +class UCanvas; + +/// UNIFY RenderDevice on Unreal: textures are transient UTexture2Ds; each UNIFY batch becomes one +/// FCanvasTriangleItem (so UNIFY's batching carries through to Unreal draw calls). Batches are +/// recorded during Engine::render() and replayed onto the HUD canvas by FlushToCanvas(). +class UNIFYUNREAL_API FUnifyUnrealRenderDevice : public unify::RenderDevice +{ +public: + unify::TextureHandle create_texture(const unify::Image& Image) override; + bool update_texture(unify::TextureHandle H, const unify::Image& Image) override; + bool destroy_texture(unify::TextureHandle H) override; + bool texture_size(unify::TextureHandle H, int& W, int& Hh) const override; + void begin(unify::RenderTarget& Target, unify::Color Clear) override; + void draw(const unify::Batch& Batch) override; + void end() override {} + uint32_t live_textures() const override { return Handles.alive(); } + + /// Draws the recorded frame, scaled to the canvas with integer pixel scaling. + void FlushToCanvas(UCanvas* Canvas, float LogicalWidth, float LogicalHeight); + void AddReferencedObjects(FReferenceCollector& Collector); + +private: + struct FRecordedBatch { UTexture2D* Texture; ESimpleElementBlendMode Blend; TArray Tris; unify::RectI Scissor; }; + unify::HandlePool Handles; + TArray> Textures; // indexed by handle slot; strong refs so GC keeps them + TArray Sizes; + TArray Frame; + FLinearColor ClearColor = FLinearColor::Black; + TObjectPtr White; +}; + +/// Audio: the UNIFY mixer renders directly inside Unreal's audio render thread. +UCLASS(ClassGroup = (UNIFY), meta = (BlueprintSpawnableComponent)) +class UNIFYUNREAL_API UUnifySynthComponent : public USynthComponent +{ + GENERATED_BODY() +public: + FCriticalSection MixerLock; + unify::Mixer* Mixer = nullptr; +protected: + virtual bool Init(int32& SampleRate) override; + virtual int32 OnGenerateAudio(float* OutAudio, int32 NumSamples) override; +}; + +class FUnifyUnrealAudioDevice : public unify::AudioDevice +{ +public: + explicit FUnifyUnrealAudioDevice(UUnifySynthComponent*& InSynth) : Synth(InSynth) {} + bool start(unify::Mixer& Mixer) override; + void stop() override; + const char* name() const override { return "unreal"; } +private: + UUnifySynthComponent*& Synth; +}; + +/// The backend object handed to unify::Engine. +class UNIFYUNREAL_API FUnifyUnrealBackend : public unify::Backend +{ +public: + FUnifyUnrealBackend() : Audio(Synth) {} + const char* name() const override { return "unreal"; } + bool init(const unify::EngineConfig& Config, std::string& Error) override; + unify::RenderDevice& render_device() override { return Device; } + unify::AudioDevice& audio_device() override { return Audio; } + void poll(unify::InputSystem& Input, bool& Quit) override; + void present(const unify::RenderTarget& Frame) override; + uint64_t now_ns() override; + void shutdown() override; + + /// Called from Unreal input callbacks (game thread); events are stamped on arrival. + void QueueKey(const FKey& Key, bool bDown, bool bRepeat); + void QueueAxis(const FKey& Key, float Value); + void QueuePointer(float X, float Y); + + FUnifyUnrealRenderDevice Device; + UUnifySynthComponent* Synth = nullptr; + bool bQuitRequested = false; + +private: + FUnifyUnrealAudioDevice Audio; + TArray Pending; + FCriticalSection PendingLock; +}; diff --git a/unify/backends/unreal/Source/UnifyUnreal/UnifyUnreal.Build.cs b/unify/backends/unreal/Source/UnifyUnreal/UnifyUnreal.Build.cs new file mode 100644 index 0000000000000000000000000000000000000000..48292680f9c773159c9cbda8171db51bcb0b2ee2 --- /dev/null +++ b/unify/backends/unreal/Source/UnifyUnreal/UnifyUnreal.Build.cs @@ -0,0 +1,38 @@ +using System; +using System.IO; +using UnrealBuildTool; +public class UnifyUnreal : ModuleRules +{ + public UnifyUnreal(ReadOnlyTargetRules Target) : base(Target) + { + PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; + CppStandard = CppStandardVersion.Cpp17; + bEnableExceptions = true; + bUseRTTI = true; + PublicDependencyModuleNames.AddRange(new[] { + "Core", "CoreUObject", "Engine", "InputCore", "AudioMixer", "SlateCore", "RenderCore", "RHI" + }); + string Root = Environment.GetEnvironmentVariable("UNIFY_ROOT"); + string Build = Environment.GetEnvironmentVariable("UNIFY_BUILD"); + if (String.IsNullOrEmpty(Root) || String.IsNullOrEmpty(Build)) + throw new BuildException("Run unreal/Prepare-Unreal.ps1 in this shell to set UNIFY_ROOT and UNIFY_BUILD."); + PublicIncludePaths.Add(Path.Combine(Root, "engine")); + PublicIncludePaths.Add(Path.Combine(Root, "third_party/lua/src")); + string Prefix = Target.Platform == UnrealTargetPlatform.Win64 ? "" : "lib"; + string Ext = Target.Platform == UnrealTargetPlatform.Win64 ? ".lib" : ".a"; + foreach (string Name in new[] {"unify_engine", "lua"}) + { + string Library = Path.Combine(Build, Prefix + Name + Ext); + if (!File.Exists(Library)) + throw new BuildException("Missing UNIFY library: " + Library); + PublicAdditionalLibraries.Add(Library); + } + PublicDefinitions.Add("UNIFY_UNREAL=1"); + PublicDefinitions.Add("UNIFY_NO_GLOBAL_NEW=1"); + string Assets = Path.Combine(Target.ProjectFile.Directory.FullName, "Unify", "assets"); + if (Directory.Exists(Assets)) + foreach (string FilePath in Directory.GetFiles(Assets, "*", SearchOption.AllDirectories)) + if (!FilePath.EndsWith(".usav")) + RuntimeDependencies.Add(FilePath, StagedFileType.NonUFS); + } +} diff --git a/unify/backends/unreal/UnifyUnreal.uplugin b/unify/backends/unreal/UnifyUnreal.uplugin new file mode 100644 index 0000000000000000000000000000000000000000..2935f256f8e8fdfff5e7ec17810398087a480f89 --- /dev/null +++ b/unify/backends/unreal/UnifyUnreal.uplugin @@ -0,0 +1,12 @@ +{ + "FileVersion": 3, + "Version": 1, + "VersionName": "1.0", + "FriendlyName": "UNIFY Unreal Backend", + "Description": "Runs UNIFY games inside Unreal Engine. Gameplay stays in UNIFY/Lua; Unreal provides rendering, audio and input.", + "Category": "Runtime", + "CanContainContent": false, + "Modules": [ + { "Name": "UnifyUnreal", "Type": "Runtime", "LoadingPhase": "Default" } + ] +} diff --git a/unify/engine/animation/animation.cpp b/unify/engine/animation/animation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1bcc3561938825d52ec486533afe01991556be4 --- /dev/null +++ b/unify/engine/animation/animation.cpp @@ -0,0 +1,169 @@ +#include "animation.h" +#include "../serialization/stream.h" +#include +#include + +namespace unify { + +float Track::sample(float t) const { + if (keys.empty()) return 0; + if (t <= keys.front().time) return keys.front().value; + if (t >= keys.back().time) return keys.back().value; + auto it = std::upper_bound(keys.begin(), keys.end(), t, [](float x, const Keyframe& k) { return x < k.time; }); + const Keyframe& b = *it; + const Keyframe& a = *(it - 1); + float span = b.time - a.time; + return span > 0 ? a.value + (b.value - a.value) * ((t - a.time) / span) : b.value; +} + +float AnimationClip::length() const { + float frames_len = 0; + for (auto& f : frames) frames_len += f.duration; + float track_len = 0; + for (auto& t : tracks) if (!t.keys.empty()) track_len = std::max(track_len, t.keys.back().time); + return std::max(frames_len, track_len); +} + +void AnimationSystem::add_clip(AnimationClip c) { clips_[c.name] = std::move(c); } +const AnimationClip* AnimationSystem::clip(const std::string& name) const { + auto it = clips_.find(name); + return it == clips_.end() ? nullptr : &it->second; +} + +uint32_t AnimationSystem::create_player(const std::string& clip) { + uint32_t id; + if (!free_.empty()) { id = free_.back(); free_.pop_back(); } + else { id = uint32_t(players_.size()); players_.emplace_back(); live_.push_back(0); } + players_[id] = AnimationPlayer{}; + players_[id].clip = clip; + live_[id] = 1; + return id + 1; // 0 means "no player" +} +bool AnimationSystem::destroy_player(uint32_t id) { + if (id == 0 || id > players_.size() || !live_[id - 1]) return false; + live_[id - 1] = 0; + free_.push_back(id - 1); + return true; +} +AnimationPlayer* AnimationSystem::player(uint32_t id) { + return (id == 0 || id > players_.size() || !live_[id - 1]) ? nullptr : &players_[id - 1]; +} +size_t AnimationSystem::live_players() const { return size_t(std::count(live_.begin(), live_.end(), 1)); } + +void AnimationSystem::play(uint32_t id, const std::string& name, float blend_seconds, bool restart) { + AnimationPlayer* p = player(id); + if (!p) return; + if (p->clip == name && !restart) return; + if (blend_seconds > 0) { + p->from_clip = p->clip; + p->from_time = p->time; + p->blend = 0; + p->blend_duration = blend_seconds; + } else { + p->from_clip.clear(); + p->blend = 1; + } + p->clip = name; + p->time = 0; + p->finished = false; +} + +// Maps an unbounded play time into clip time according to the play mode. +float AnimationSystem::wrap(const AnimationClip& c, float t, bool* finished) { + float len = c.length(); + if (len <= 0) return 0; + switch (c.mode) { + case PlayMode::Once: + if (t >= len) { if (finished) *finished = true; return len; } + return t; + case PlayMode::Loop: return std::fmod(t, len); + case PlayMode::PingPong: { + float m = std::fmod(t, 2 * len); + return m <= len ? m : 2 * len - m; + } + } + return t; +} + +void AnimationSystem::advance(float dt) { + for (size_t i = 0; i < players_.size(); i++) { + if (!live_[i]) continue; + AnimationPlayer& p = players_[i]; + const AnimationClip* c = clip(p.clip); + if (!c) continue; + if (!p.finished) { + p.time += dt * p.speed; + if (c->mode == PlayMode::Once && p.time >= c->length()) { p.time = c->length(); p.finished = true; } + // Keep loop time bounded so float precision does not degrade over long sessions. + if (c->mode == PlayMode::Loop && c->length() > 0) p.time = std::fmod(p.time, c->length()); + if (c->mode == PlayMode::PingPong && c->length() > 0) p.time = std::fmod(p.time, 2 * c->length()); + } + if (p.blend < 1) { + p.from_time += dt * p.speed; + p.blend = p.blend_duration > 0 ? std::min(1.0f, p.blend + dt / p.blend_duration) : 1.0f; + if (p.blend >= 1) p.from_clip.clear(); + } + } +} + +uint32_t AnimationSystem::sprite_region(uint32_t id) const { + const AnimationPlayer* p = const_cast(this)->player(id); + if (!p) return 0; + const AnimationClip* c = clip(p->clip); + if (!c || c->frames.empty()) return 0; + float t = wrap(*c, p->time, nullptr); + float acc = 0; + for (auto& f : c->frames) { + acc += f.duration; + if (t < acc) return f.region; + } + return c->frames.back().region; +} + +float AnimationSystem::value(uint32_t id, const std::string& property, float fallback) const { + const AnimationPlayer* p = const_cast(this)->player(id); + if (!p) return fallback; + auto sample = [&](const std::string& name, float time, bool& found) { + const AnimationClip* c = clip(name); + if (!c) return fallback; + for (auto& tr : c->tracks) + if (tr.property == property) { found = true; return tr.sample(wrap(*c, time, nullptr)); } + return fallback; + }; + bool found_to = false, found_from = false; + float to = sample(p->clip, p->time, found_to); + if (p->blend >= 1 || p->from_clip.empty()) return to; + float from = sample(p->from_clip, p->from_time, found_from); + if (!found_to && !found_from) return fallback; + return from + (to - from) * p->blend; +} + +void AnimationSystem::serialize(BinaryWriter& w) const { + w.u32(uint32_t(players_.size())); + for (size_t i = 0; i < players_.size(); i++) { + w.u8(live_[i]); + if (!live_[i]) continue; + const AnimationPlayer& p = players_[i]; + w.str(p.clip); w.f32(p.time); w.f32(p.speed); w.boolean(p.finished); + w.str(p.from_clip); w.f32(p.from_time); w.f32(p.blend); w.f32(p.blend_duration); + } + w.u32(uint32_t(free_.size())); + for (uint32_t f : free_) w.u32(f); +} + +void AnimationSystem::deserialize(BinaryReader& r) { + uint32_t n = r.u32(); + players_.assign(n, AnimationPlayer{}); + live_.assign(n, 0); + for (uint32_t i = 0; i < n; i++) { + live_[i] = r.u8(); + if (!live_[i]) continue; + AnimationPlayer& p = players_[i]; + p.clip = r.str(); p.time = r.f32(); p.speed = r.f32(); p.finished = r.boolean(); + p.from_clip = r.str(); p.from_time = r.f32(); p.blend = r.f32(); p.blend_duration = r.f32(); + } + free_.resize(r.u32()); + for (auto& f : free_) f = r.u32(); +} + +} // namespace unify diff --git a/unify/engine/animation/animation.h b/unify/engine/animation/animation.h new file mode 100644 index 0000000000000000000000000000000000000000..e8a62d93dcd7daf9da60f6113764276abf4e3fbb --- /dev/null +++ b/unify/engine/animation/animation.h @@ -0,0 +1,77 @@ +#pragma once +#include +#include +#include +#include + +namespace unify { +class BinaryWriter; +class BinaryReader; + +enum class PlayMode : uint8_t { Once, Loop, PingPong }; + +struct Keyframe { float time; float value; }; + +/// Linear-interpolated float track (e.g. "scale_y", "rotation", "alpha"). +struct Track { + std::string property; + std::vector keys; // sorted by time + float sample(float t) const; +}; + +/// Sprite frame: atlas region index shown for `duration` seconds. +struct SpriteFrame { uint32_t region; float duration; }; + +struct AnimationClip { + std::string name; + PlayMode mode = PlayMode::Loop; + std::vector frames; // sprite animation (may be empty) + std::vector tracks; // timeline properties (may be empty) + float length() const; // max of frame total and last key time +}; + +/// Plays one clip at a time with optional crossfade from the previous clip. +/// Time is advanced only by the simulation (fixed dt), never by render frames. +struct AnimationPlayer { + std::string clip; + float time = 0; + float speed = 1; + bool finished = false; + // Crossfade state: the previous clip keeps advancing while its weight falls to 0. + std::string from_clip; + float from_time = 0; + float blend = 1; // weight of `clip` (1 = no blend in progress) + float blend_duration = 0; +}; + +class AnimationSystem { +public: + void add_clip(AnimationClip clip); + const AnimationClip* clip(const std::string& name) const; + + uint32_t create_player(const std::string& clip); + bool destroy_player(uint32_t id); + AnimationPlayer* player(uint32_t id); + /// Switches clip. With blend_seconds > 0 track values crossfade from the current clip. + void play(uint32_t id, const std::string& clip, float blend_seconds = 0, bool restart = false); + void advance(float dt); + + /// Current sprite region for the player (from the active clip's frame at its time). + uint32_t sprite_region(uint32_t id) const; + /// Blended track value; returns `fallback` if neither clip animates the property. + float value(uint32_t id, const std::string& property, float fallback) const; + + size_t live_players() const; + void serialize(BinaryWriter& w) const; + void deserialize(BinaryReader& r); + void clear_players() { players_.clear(); free_.clear(); } + +private: + static float wrap(const AnimationClip& c, float t, bool* finished); + std::map clips_; + std::vector players_; + std::vector live_; + std::vector free_; +}; + +} // namespace unify diff --git a/unify/engine/assets/assets.cpp b/unify/engine/assets/assets.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c95dee9744e4095cccbb0d8a62c9a02e7f724a09 --- /dev/null +++ b/unify/engine/assets/assets.cpp @@ -0,0 +1,212 @@ +#include "assets.h" +#include "../core/core.h" +#include +#include +#include + +namespace unify { + +const char* asset_type_name(AssetType t) { + switch (t) { + case AssetType::Texture: return "texture"; + case AssetType::Audio: return "audio"; + case AssetType::Music: return "music"; + case AssetType::Script: return "script"; + case AssetType::Prefab: return "prefab"; + case AssetType::Map: return "map"; + case AssetType::Kernel: return "kernel"; + case AssetType::Material: return "material"; + case AssetType::Font: return "font"; + case AssetType::SaveData: return "save"; + } + return "?"; +} + +bool read_file(const std::string& path, std::vector& out) { + FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) return false; + out.clear(); + uint8_t buf[65536]; + size_t n; + while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) out.insert(out.end(), buf, buf + n); + std::fclose(f); + return true; +} + +bool write_file(const std::string& path, const std::vector& data) { + std::string tmp = path + ".tmp"; + FILE* f = std::fopen(tmp.c_str(), "wb"); + if (!f) return false; + bool ok = std::fwrite(data.data(), 1, data.size(), f) == data.size(); + ok = std::fclose(f) == 0 && ok; + return ok && std::rename(tmp.c_str(), path.c_str()) == 0; // atomic replace: no torn save files +} + +AssetManager::AssetManager(RenderDevice& device, std::string root, size_t budget) : device_(device), root_(std::move(root)), alloc_(budget) {} + +AssetManager::~AssetManager() { + for (uint32_t i = 0; i < handles_.capacity(); i++) + if (AssetHandle h = handles_.at(i)) free_payload(records_[i]); +} + +std::string AssetManager::path_for(AssetType type, const std::string& name) const { + static const std::map ext = { + {AssetType::Texture, ".qoi"}, {AssetType::Audio, ".wav"}, {AssetType::Music, ".wav"}, {AssetType::Script, ".lua"}, + {AssetType::Prefab, ".lua"}, {AssetType::Map, ".map"}, {AssetType::Kernel, ".cu"}, {AssetType::Material, ".mat"}, + {AssetType::Font, ""}, {AssetType::SaveData, ".usav"}}; + return root_ + "/" + name + ext.at(type); +} + +AssetHandle AssetManager::find(const std::string& name) const { + auto it = by_name_.find(name); + return it == by_name_.end() ? AssetHandle{} : it->second; +} + +AssetHandle AssetManager::load(AssetType type, const std::string& name) { + auto it = by_name_.find(name); + if (it != by_name_.end() && handles_.valid(it->second)) { + AssetRecord& r = records_[it->second.index()]; + if (r.type != type) { UNIFY_LOG_ERROR("ASSETS", "'%s' already loaded as %s", name.c_str(), asset_type_name(r.type)); return {}; } + r.refs++; + return it->second; // cached: no duplicate load + } + AssetRecord rec; + rec.name = name; + rec.type = type; + rec.path = path_for(type, name); + rec.refs = 1; + if (!load_payload(rec)) { + UNIFY_LOG_ERROR("ASSETS", "failed to load %s '%s' (%s)", asset_type_name(type), name.c_str(), rec.path.c_str()); + return {}; + } + AssetHandle h = handles_.allocate(); + if (h.index() >= records_.size()) records_.resize(h.index() + 1); + records_[h.index()] = std::move(rec); + by_name_[name] = h; + return h; +} + +bool AssetManager::acquire(AssetHandle h) { + if (!valid(h)) return false; + records_[h.index()].refs++; + return true; +} + +bool AssetManager::release(AssetHandle h) { + if (!valid(h)) return false; + AssetRecord& r = records_[h.index()]; + if (--r.refs > 0) return true; + free_payload(r); + by_name_.erase(r.name); + r = AssetRecord{}; + handles_.release(h); + return true; +} + +static bool parse_map(const std::string& text, TileMap& m) { + std::istringstream in(text); + std::string line; + while (std::getline(in, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.rfind("//", 0) == 0) continue; // comment ('#' is a tile character) + if (line.rfind("tile_size ", 0) == 0) { m.tile_size = std::stof(line.substr(10)); continue; } + m.rows.push_back(line); + m.width = std::max(m.width, int(line.size())); + } + for (auto& r : m.rows) r.resize(size_t(m.width), ' '); + m.height = int(m.rows.size()); + return m.height > 0; +} + +bool AssetManager::load_payload(AssetRecord& r) { + switch (r.type) { + case AssetType::Texture: { + Image img; + if (!load_image(r.path, img)) return false; + r.texture.texture = device_.create_texture(img); + r.texture.width = img.width; + r.texture.height = img.height; + r.texture.atlas.regions.push_back({"", {0, 0, img.width, img.height}}); + // Optional atlas sidecar: "name x y w h" per line. + std::vector meta; + std::string atlas_path = r.path.substr(0, r.path.size() - 4) + ".atlas"; + if (read_file(atlas_path, meta)) { + std::istringstream in(std::string(meta.begin(), meta.end())); + AtlasRegion reg; + while (in >> reg.name >> reg.rect.x >> reg.rect.y >> reg.rect.w >> reg.rect.h) r.texture.atlas.regions.push_back(reg); + } + r.bytes = img.pixels.size(); + return bool(r.texture.texture); + } + case AssetType::Audio: { + r.clip = std::make_shared(); + r.clip->name = r.name; + if (!r.clip->load_wav(r.path)) return false; + r.bytes = r.clip->samples.size() * sizeof(float); + return true; + } + case AssetType::Music: { + // Streamed: validate the header only. Nothing but the header is read here. + WavDecoder probe; + if (!probe.open(r.path)) return false; + r.bytes = 0; + return true; + } + case AssetType::Font: return true; + case AssetType::Script: case AssetType::Prefab: case AssetType::Map: case AssetType::Kernel: case AssetType::Material: case AssetType::SaveData: { + std::vector data; + if (!read_file(r.path, data)) return false; + r.blob = alloc_.allocate(data.size() + 1, asset_type_name(r.type)); + if (!r.blob) { UNIFY_LOG_ERROR("ASSETS", "asset budget exhausted loading '%s'", r.name.c_str()); return false; } + std::memcpy(r.blob, data.data(), data.size()); + r.blob[data.size()] = 0; + r.text.assign(reinterpret_cast(r.blob), data.size()); + r.bytes = data.size() + 1; + if (r.type == AssetType::Map && !parse_map(r.text, r.map)) return false; + if (r.type == AssetType::Material) { + std::istringstream in(r.text); + std::string key; + while (in >> key) { + if (key == "blend") { + std::string v; in >> v; + r.material.blend = v == "additive" ? BlendMode::Additive : v == "multiply" ? BlendMode::Multiply : v == "opaque" ? BlendMode::Opaque : BlendMode::Alpha; + } else if (key == "tint") { + int cr, cg, cb, ca; in >> cr >> cg >> cb >> ca; + r.material.tint = {uint8_t(cr), uint8_t(cg), uint8_t(cb), uint8_t(ca)}; + } + } + } + return true; + } + } + return false; +} + +void AssetManager::free_payload(AssetRecord& r) { + if (r.type == AssetType::Texture && r.texture.texture) device_.destroy_texture(r.texture.texture); + if (r.blob) { alloc_.free(r.blob); r.blob = nullptr; } + r.clip.reset(); +} + +std::shared_ptr AssetManager::open_stream(AssetHandle h) { + const AssetRecord* r = get(h); + if (!r || r->type != AssetType::Music) return nullptr; + auto s = std::make_shared(); + s->name = r->name; + if (!s->open(r->path)) return nullptr; + return s; +} + +size_t AssetManager::resident_bytes() const { + size_t n = 0; + for (uint32_t i = 0; i < handles_.capacity(); i++) if (handles_.at(i)) n += records_[i].bytes; + return n; +} + +std::vector AssetManager::loaded_names() const { + std::vector out; + for (auto& kv : by_name_) out.push_back(kv.first); + return out; +} + +} // namespace unify diff --git a/unify/engine/assets/assets.h b/unify/engine/assets/assets.h new file mode 100644 index 0000000000000000000000000000000000000000..e264d59466a0d67603ff94cff1eb2ef54c7a4649 --- /dev/null +++ b/unify/engine/assets/assets.h @@ -0,0 +1,87 @@ +#pragma once +#include +#include +#include +#include +#include "../core/handle.h" +#include "../memory/memory.h" +#include "../render/render.h" +#include "../audio/audio.h" + +namespace unify { + +enum class AssetType : uint8_t { Texture, Audio, Music, Script, Prefab, Map, Kernel, Material, Font, SaveData }; +const char* asset_type_name(AssetType t); + +/// Tile map: rows of characters, bottom row last. Legend is interpreted by gameplay. +struct TileMap { + int width = 0, height = 0; + float tile_size = 1; + std::vector rows; // rows[0] = top + char at(int x, int y_from_bottom) const { + int r = height - 1 - y_from_bottom; + if (x < 0 || x >= width || r < 0 || r >= height) return ' '; + return rows[size_t(r)][size_t(x)]; + } +}; + +/// Material definition ("shader" asset for the 2D pipeline): blend mode + tint. +struct MaterialDef { BlendMode blend = BlendMode::Alpha; Color tint; }; + +struct TextureAsset { TextureHandle texture; Atlas atlas; int width = 0, height = 0; }; + +struct AssetRecord { + std::string name; // logical name, e.g. "textures/sprites" + std::string path; // file path + AssetType type; + uint32_t refs = 0; + size_t bytes = 0; // resident bytes attributed to this asset + // Payloads (only the one matching `type` is set). + TextureAsset texture; + std::shared_ptr clip; + std::string text; // script / prefab / kernel source + TileMap map; + MaterialDef material; + uint8_t* blob = nullptr; // AssetAllocator-owned copy of the file bytes (text assets) +}; + +/// Registry + cache + loaders. Assets are referenced by AssetHandle and ref-counted: +/// loading an already-resident asset returns the same handle (no duplication), and the +/// payload is freed when the last reference is released. +class AssetManager { +public: + AssetManager(RenderDevice& device, std::string root, size_t budget_bytes = 256u << 20); + ~AssetManager(); + + AssetHandle load(AssetType type, const std::string& name); + bool acquire(AssetHandle h); // add a reference + bool release(AssetHandle h); // drop a reference; unloads at zero + bool valid(AssetHandle h) const { return handles_.valid(h); } + const AssetRecord* get(AssetHandle h) const { return valid(h) ? &records_[h.index()] : nullptr; } + AssetHandle find(const std::string& name) const; + + /// Opens a new streaming source for a music asset (streams are per-playback, the file is not cached). + std::shared_ptr open_stream(AssetHandle music); + std::string path_for(AssetType type, const std::string& name) const; + const std::string& root() const { return root_; } + + uint32_t live() const { return handles_.alive(); } + size_t resident_bytes() const; + const AssetAllocator& allocator() const { return alloc_; } + std::vector loaded_names() const; + +private: + bool load_payload(AssetRecord& r); + void free_payload(AssetRecord& r); + RenderDevice& device_; + std::string root_; + AssetAllocator alloc_; + HandlePool handles_; + std::vector records_; + std::map by_name_; +}; + +bool read_file(const std::string& path, std::vector& out); +bool write_file(const std::string& path, const std::vector& data); + +} // namespace unify diff --git a/unify/engine/audio/audio.h b/unify/engine/audio/audio.h new file mode 100644 index 0000000000000000000000000000000000000000..e47282f87a20db2915be7051ca2d572dff5de878 --- /dev/null +++ b/unify/engine/audio/audio.h @@ -0,0 +1,214 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../core/handle.h" + +namespace unify { +class BinaryWriter; +class BinaryReader; + +// ------------------------------------------------------------------------------ decoding + +struct WavInfo { + uint16_t channels = 0; + uint32_t sample_rate = 0; + uint16_t bits = 0; + uint32_t frames = 0; + uint64_t data_offset = 0; + int64_t loop_start = -1, loop_end = -1; // from the RIFF 'smpl' chunk, in frames +}; + +/// Incremental PCM16 WAV decoder over a file. Reads a bounded number of frames at a +/// time; never loads the whole file. Used by streaming sources. +class WavDecoder { +public: + ~WavDecoder(); + bool open(const std::string& path); + /// Decodes up to `frames` frames into interleaved stereo float. Returns frames produced. + uint32_t read(float* stereo_out, uint32_t frames); + bool seek(uint32_t frame); + uint32_t position() const { return pos_; } + const WavInfo& info() const { return info_; } + bool at_end() const { return pos_ >= info_.frames; } +private: + FILE* file_ = nullptr; + WavInfo info_; + uint32_t pos_ = 0; + std::vector scratch_; +}; + +bool parse_wav_header(FILE* f, WavInfo& info); +/// Writes a PCM16 WAV (optionally with a 'smpl' loop) — used by the asset generator. +bool write_wav(const std::string& path, const std::vector& interleaved, uint16_t channels, uint32_t rate, int64_t loop_start = -1, int64_t loop_end = -1); + +// ------------------------------------------------------------------------------ assets + +/// Fully decoded short sound (SFX). Samples are stereo float at the clip's own rate. +struct AudioClip { + std::string name; + uint32_t sample_rate = 44100; + std::vector samples; // interleaved stereo + uint32_t loop_start = 0, loop_end = 0; // frames; loop_end 0 = whole clip + uint32_t frames() const { return uint32_t(samples.size() / 2); } + bool load_wav(const std::string& path); +}; + +/// Single-producer/single-consumer ring of stereo frames between the streamer thread +/// (decoder side) and the mixer (device side). Lock-free. +class StreamBuffer { +public: + explicit StreamBuffer(uint32_t capacity_frames) : buf_(size_t(capacity_frames) * 2), cap_(capacity_frames) {} + uint32_t available() const { return uint32_t(write_.load(std::memory_order_acquire) - read_.load(std::memory_order_acquire)); } + uint32_t space() const { return cap_ - available(); } + uint32_t capacity() const { return cap_; } + uint32_t write(const float* frames, uint32_t n); + uint32_t read(float* frames, uint32_t n); + void reset() { read_.store(0); write_.store(0); } +private: + std::vector buf_; + uint32_t cap_; + std::atomic read_{0}, write_{0}; +}; + +/// Long audio played from disk: decoder → stream buffer. Owns its decoder. +struct StreamingSource { + std::string name, path; + WavDecoder decoder; + StreamBuffer buffer{44100}; // ~1 s at 44.1 kHz + uint32_t loop_start = 0, loop_end = 0; + bool loop = false; + std::atomic finished{false}; // decoder reached the end (non-looping) + std::atomic underruns{0}; + std::atomic frames_consumed{0}; // frames the mixer has pulled (for save/seek) + std::mutex decoder_mutex; + bool open(const std::string& p); + /// Decodes into the buffer until it is at least half full (called by the streamer thread). + void refill(); + void seek(uint32_t frame); +}; + +// ------------------------------------------------------------------------------ mixer + +enum class Bus : uint8_t { Master = 0, Sfx = 1, Music = 2, Count = 3 }; +enum class VoiceState : uint8_t { Free, Playing, Paused }; + +struct PlayParams { + Bus bus = Bus::Sfx; + float volume = 1, pan = 0, pitch = 1; + bool loop = false; + float fade_in = 0; // seconds + double start = 0; // clip start position in frames (save-state restore) +}; + +/// Voice mixer. Game thread issues commands; the audio device thread calls render(). +/// Voice slots are preallocated: starting a sound never allocates on the audio thread. +class Mixer { +public: + explicit Mixer(uint32_t device_rate = 44100, uint32_t max_voices = 64); + + AudioHandle play(std::shared_ptr clip, const PlayParams& p = {}); + AudioHandle stream(std::shared_ptr src, const PlayParams& p = {}); + bool stop(AudioHandle h, float fade_out = 0); + bool pause(AudioHandle h); + bool resume(AudioHandle h); + bool set_volume(AudioHandle h, float v); + bool set_pan(AudioHandle h, float pan); + bool set_pitch(AudioHandle h, float pitch); + bool fade(AudioHandle h, float target, float seconds); + bool playing(AudioHandle h) const; + /// Voice still exists (playing or paused). + bool alive(AudioHandle h) const; + void set_bus_volume(Bus b, float v); + float bus_volume(Bus b) const; + void stop_all(); + + /// Mixes `frames` stereo frames into `out` (interleaved float, [-1,1]). Audio thread. + void render(float* out, uint32_t frames); + + uint32_t device_rate() const { return rate_; } + /// Audio clock: frames rendered by the device since start. + uint64_t frames_rendered() const { return rendered_.load(); } + double audio_time() const { return double(rendered_.load()) / rate_; } + uint32_t active_voices() const; + float peak() const { return peak_.load(); } + + /// Voices that reference streams, for the streamer thread. + void streams(std::vector>& out) const; + + // Save-state support: voices are persisted by asset name + playback position. + struct VoiceSnapshot { AudioHandle handle; std::string asset; bool is_stream; Bus bus; float volume, pan, pitch; bool loop; bool paused; double position; }; + std::vector snapshot() const; + +private: + struct Voice { + VoiceState state = VoiceState::Free; + uint8_t generation = 1; + std::shared_ptr clip; + std::shared_ptr stream; + Bus bus = Bus::Sfx; + float volume = 1, pan = 0, pitch = 1; + bool loop = false; + double position = 0; // clip frame position (fractional) + float gain = 1, gain_target = 1, gain_step = 0; // fade envelope + bool stop_after_fade = false; + float prev[2] = {0, 0}, next[2] = {0, 0}; // stream interpolation window + double frac = 1; // stream: fraction between prev and next + }; + Voice* find(AudioHandle h); + const Voice* find(AudioHandle h) const; + AudioHandle start(Voice*& v, const PlayParams& p); + + uint32_t rate_; + std::vector voices_; + float bus_volume_[int(Bus::Count)] = {1, 1, 1}; + mutable std::mutex mutex_; + std::atomic rendered_{0}; + std::atomic peak_{0}; +}; + +// ------------------------------------------------------------------------------ devices + +/// Output device abstraction. Backends provide real devices; the engine ships a null +/// device (real-time thread, no output) and an offline device (manual pull, for tests). +class AudioDevice { +public: + virtual ~AudioDevice() = default; + virtual bool start(Mixer& mixer) = 0; + virtual void stop() = 0; + virtual const char* name() const = 0; +}; + +/// Renders the mix on its own thread at real-time pace and discards it. Keeps audio time +/// advancing independently of rendering when no hardware device is present. +class NullAudioDevice : public AudioDevice { +public: + ~NullAudioDevice() override { stop(); } + bool start(Mixer& mixer) override; + void stop() override; + const char* name() const override { return "null"; } +private: + std::thread thread_; + std::atomic running_{false}; +}; + +/// Background decoder: keeps every active stream's buffer topped up. +class AudioStreamer { +public: + ~AudioStreamer() { stop(); } + void start(Mixer& mixer); + void stop(); + /// Synchronous refill (deterministic tests, or single-threaded platforms). + static void pump(Mixer& mixer); +private: + std::thread thread_; + std::atomic running_{false}; +}; + +} // namespace unify diff --git a/unify/engine/audio/mixer.cpp b/unify/engine/audio/mixer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d4abf92cf9ff866d8b85e32eec370a3494b82d4 --- /dev/null +++ b/unify/engine/audio/mixer.cpp @@ -0,0 +1,311 @@ +#include "audio.h" +#include "../core/core.h" +#include "../core/math.h" +#include +#include +#include + +namespace unify { + +// ------------------------------------------------------------------------------ stream buffer + +uint32_t StreamBuffer::write(const float* frames, uint32_t n) { + uint64_t w = write_.load(std::memory_order_relaxed), r = read_.load(std::memory_order_acquire); + n = std::min(n, cap_ - uint32_t(w - r)); + for (uint32_t i = 0; i < n; i++) { + size_t at = size_t((w + i) % cap_) * 2; + buf_[at] = frames[2 * i]; + buf_[at + 1] = frames[2 * i + 1]; + } + write_.store(w + n, std::memory_order_release); + return n; +} + +uint32_t StreamBuffer::read(float* frames, uint32_t n) { + uint64_t r = read_.load(std::memory_order_relaxed), w = write_.load(std::memory_order_acquire); + n = std::min(n, uint32_t(w - r)); + for (uint32_t i = 0; i < n; i++) { + size_t at = size_t((r + i) % cap_) * 2; + frames[2 * i] = buf_[at]; + frames[2 * i + 1] = buf_[at + 1]; + } + read_.store(r + n, std::memory_order_release); + return n; +} + +bool StreamingSource::open(const std::string& p) { + path = p; + if (!decoder.open(p)) return false; + const WavInfo& i = decoder.info(); + loop_start = i.loop_start >= 0 ? uint32_t(i.loop_start) : 0; + loop_end = i.loop_end > 0 ? uint32_t(i.loop_end) : i.frames; + return true; +} + +void StreamingSource::refill() { + std::lock_guard lock(decoder_mutex); + float chunk[2 * 2048]; + while (buffer.space() > buffer.capacity() / 2) { + uint32_t end = loop ? loop_end : decoder.info().frames; + uint32_t pos = decoder.position(); + if (pos >= end) { + if (!loop) { finished = true; return; } + decoder.seek(loop_start); // loop point: continue seamlessly from loop_start + continue; + } + uint32_t want = std::min({2048, end - pos, buffer.space()}); + uint32_t got = decoder.read(chunk, want); + if (got == 0) { finished = true; return; } + buffer.write(chunk, got); + } +} + +void StreamingSource::seek(uint32_t frame) { + std::lock_guard lock(decoder_mutex); + decoder.seek(frame); + buffer.reset(); + finished = false; +} + +// ------------------------------------------------------------------------------ mixer + +Mixer::Mixer(uint32_t device_rate, uint32_t max_voices) : rate_(device_rate), voices_(max_voices) {} + +Mixer::Voice* Mixer::find(AudioHandle h) { + if (h.is_null() || h.index() >= voices_.size()) return nullptr; + Voice& v = voices_[h.index()]; + return v.state != VoiceState::Free && v.generation == h.generation() ? &v : nullptr; +} +const Mixer::Voice* Mixer::find(AudioHandle h) const { return const_cast(this)->find(h); } + +AudioHandle Mixer::start(Voice*& out, const PlayParams& p) { + out = nullptr; + for (uint32_t i = 0; i < voices_.size(); i++) { + Voice& v = voices_[i]; + if (v.state != VoiceState::Free) continue; + uint8_t gen = v.generation; + v = Voice{}; + v.generation = gen; + v.state = VoiceState::Playing; + v.bus = p.bus; v.volume = p.volume; v.pan = clampf(p.pan, -1, 1); v.pitch = std::max(0.01f, p.pitch); v.loop = p.loop; + if (p.fade_in > 0) { v.gain = 0; v.gain_target = 1; v.gain_step = 1.0f / (p.fade_in * rate_); } + out = &v; + return AudioHandle::make(i, gen); + } + UNIFY_LOG_WARN("AUDIO", "voice limit (%zu) reached; sound dropped", voices_.size()); + return {}; +} + +AudioHandle Mixer::play(std::shared_ptr clip, const PlayParams& p) { + if (!clip || clip->frames() == 0) return {}; + std::lock_guard lock(mutex_); + Voice* v; + AudioHandle h = start(v, p); + if (v) { v->clip = std::move(clip); v->position = std::max(0.0, p.start); } + return h; +} + +AudioHandle Mixer::stream(std::shared_ptr src, const PlayParams& p) { + if (!src) return {}; + src->loop = p.loop; + src->refill(); // prime the buffer so playback starts without an underrun + std::lock_guard lock(mutex_); + Voice* v; + AudioHandle h = start(v, p); + if (v) { v->stream = std::move(src); v->frac = 1; } + return h; +} + + +bool Mixer::stop(AudioHandle h, float fade_out) { + std::lock_guard lock(mutex_); + Voice* v = find(h); + if (!v) return false; + if (fade_out > 0) { + v->gain_target = 0; + v->gain_step = v->gain / (fade_out * rate_); + v->stop_after_fade = true; + return true; + } + v->state = VoiceState::Free; + v->generation = uint8_t(v->generation + 1) ? uint8_t(v->generation + 1) : 1; + v->clip.reset(); + v->stream.reset(); + return true; +} +bool Mixer::pause(AudioHandle h) { std::lock_guard l(mutex_); Voice* v = find(h); if (!v) return false; v->state = VoiceState::Paused; return true; } +bool Mixer::resume(AudioHandle h) { std::lock_guard l(mutex_); Voice* v = find(h); if (!v) return false; v->state = VoiceState::Playing; return true; } +bool Mixer::set_volume(AudioHandle h, float x) { std::lock_guard l(mutex_); Voice* v = find(h); if (!v) return false; v->volume = std::max(0.0f, x); return true; } +bool Mixer::set_pan(AudioHandle h, float x) { std::lock_guard l(mutex_); Voice* v = find(h); if (!v) return false; v->pan = clampf(x, -1, 1); return true; } +bool Mixer::set_pitch(AudioHandle h, float x) { std::lock_guard l(mutex_); Voice* v = find(h); if (!v) return false; v->pitch = std::max(0.01f, x); return true; } +bool Mixer::fade(AudioHandle h, float target, float seconds) { + std::lock_guard l(mutex_); + Voice* v = find(h); + if (!v) return false; + v->gain_target = std::max(0.0f, target); + v->gain_step = seconds > 0 ? std::fabs(v->gain_target - v->gain) / (seconds * rate_) : 1e9f; + return true; +} +bool Mixer::alive(AudioHandle h) const { std::lock_guard l(mutex_); return find(h) != nullptr; } +bool Mixer::playing(AudioHandle h) const { std::lock_guard l(mutex_); const Voice* v = find(h); return v && v->state == VoiceState::Playing; } +void Mixer::set_bus_volume(Bus b, float v) { std::lock_guard l(mutex_); bus_volume_[int(b)] = std::max(0.0f, v); } +float Mixer::bus_volume(Bus b) const { std::lock_guard l(mutex_); return bus_volume_[int(b)]; } +void Mixer::stop_all() { + std::lock_guard l(mutex_); + for (auto& v : voices_) if (v.state != VoiceState::Free) { v.state = VoiceState::Free; v.generation = uint8_t(v.generation + 1) ? uint8_t(v.generation + 1) : 1; v.clip.reset(); v.stream.reset(); } +} +uint32_t Mixer::active_voices() const { + std::lock_guard l(mutex_); + uint32_t n = 0; + for (auto& v : voices_) n += v.state != VoiceState::Free; + return n; +} +void Mixer::streams(std::vector>& out) const { + out.clear(); + std::lock_guard l(mutex_); + for (auto& v : voices_) if (v.state != VoiceState::Free && v.stream) out.push_back(v.stream); +} + +void Mixer::render(float* out, uint32_t frames) { + std::fill(out, out + size_t(frames) * 2, 0.0f); + std::lock_guard lock(mutex_); + const float master = bus_volume_[int(Bus::Master)]; + for (Voice& v : voices_) { + if (v.state != VoiceState::Playing) continue; + const float bus = bus_volume_[int(v.bus)] * master; + // Constant-power pan. + const float angle = (v.pan + 1) * 0.25f * 3.14159265f; + const float pl = std::cos(angle) * 1.41421356f, pr = std::sin(angle) * 1.41421356f; + bool done = false; + for (uint32_t i = 0; i < frames && !done; i++) { + float l, r; + if (v.clip) { + const AudioClip& c = *v.clip; + uint32_t end = (v.loop && c.loop_end) ? c.loop_end : c.frames(); + uint32_t i0 = uint32_t(v.position); + if (i0 >= end) { + if (v.loop) { v.position = c.loop_start + (v.position - end); i0 = uint32_t(v.position); } + else { done = true; break; } + } + uint32_t i1 = i0 + 1 < end ? i0 + 1 : (v.loop ? c.loop_start : i0); + float t = float(v.position - i0); + l = lerp(c.samples[2 * i0], c.samples[2 * i1], t); + r = lerp(c.samples[2 * i0 + 1], c.samples[2 * i1 + 1], t); + v.position += double(v.pitch) * c.sample_rate / rate_; + } else { + StreamingSource& s = *v.stream; + double stepv = double(v.pitch) * s.decoder.info().sample_rate / rate_; + while (v.frac >= 1) { + float fr[2]; + if (s.buffer.read(fr, 1) == 0) { + if (s.finished) { done = true; break; } + s.underruns++; + fr[0] = v.next[0]; fr[1] = v.next[1]; // hold last sample; streamer will catch up + } else { + s.frames_consumed++; + } + v.prev[0] = v.next[0]; v.prev[1] = v.next[1]; + v.next[0] = fr[0]; v.next[1] = fr[1]; + v.frac -= 1; + } + if (done) break; + l = lerp(v.prev[0], v.next[0], float(v.frac)); + r = lerp(v.prev[1], v.next[1], float(v.frac)); + v.frac += stepv; + } + if (v.gain != v.gain_target) { + v.gain = v.gain < v.gain_target ? std::min(v.gain + v.gain_step, v.gain_target) : std::max(v.gain - v.gain_step, v.gain_target); + if (v.gain == 0 && v.stop_after_fade) { done = true; } + } + float g = v.volume * v.gain * bus; + out[2 * i] += l * g * pl; + out[2 * i + 1] += r * g * pr; + } + if (done) { + v.state = VoiceState::Free; + v.generation = uint8_t(v.generation + 1) ? uint8_t(v.generation + 1) : 1; + v.clip.reset(); + v.stream.reset(); + } + } + float pk = 0; + for (uint32_t i = 0; i < frames * 2; i++) { + out[i] = clampf(out[i], -1, 1); // hard limiter: never emit out-of-range samples + pk = std::max(pk, std::fabs(out[i])); + } + peak_.store(pk); + rendered_ += frames; +} + +std::vector Mixer::snapshot() const { + std::lock_guard l(mutex_); + std::vector out; + for (uint32_t i = 0; i < voices_.size(); i++) { + const Voice& v = voices_[i]; + if (v.state == VoiceState::Free) continue; + VoiceSnapshot s; + s.handle = AudioHandle::make(i, v.generation); + s.is_stream = bool(v.stream); + s.asset = v.clip ? v.clip->name : v.stream->name; + s.bus = v.bus; s.volume = v.volume; s.pan = v.pan; s.pitch = v.pitch; s.loop = v.loop; + s.paused = v.state == VoiceState::Paused; + s.position = v.clip ? v.position : double(v.stream->decoder.position()); + if (v.stream) { + // Decoder position runs ahead of playback by what is buffered; report what was heard. + uint64_t buffered = v.stream->buffer.available(); + double pos = s.position - double(buffered); + if (pos < 0) pos += v.stream->loop_end - v.stream->loop_start; + s.position = pos; + } + out.push_back(s); + } + return out; +} + +// ------------------------------------------------------------------------------ devices + +bool NullAudioDevice::start(Mixer& mixer) { + if (running_) return true; + running_ = true; + thread_ = std::thread([this, &mixer] { + const uint32_t block = 512; + std::vector buf(block * 2); + auto next = std::chrono::steady_clock::now(); + const auto period = std::chrono::nanoseconds(uint64_t(block) * 1000000000ull / mixer.device_rate()); + while (running_) { + mixer.render(buf.data(), block); + next += period; + std::this_thread::sleep_until(next); + } + }); + return true; +} +void NullAudioDevice::stop() { + running_ = false; + if (thread_.joinable()) thread_.join(); +} + +void AudioStreamer::pump(Mixer& mixer) { + std::vector> list; + mixer.streams(list); + for (auto& s : list) s->refill(); +} +void AudioStreamer::start(Mixer& mixer) { + if (running_) return; + running_ = true; + thread_ = std::thread([this, &mixer] { + std::vector> list; + while (running_) { + mixer.streams(list); + for (auto& s : list) s->refill(); + list.clear(); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + }); +} +void AudioStreamer::stop() { + running_ = false; + if (thread_.joinable()) thread_.join(); +} + +} // namespace unify diff --git a/unify/engine/audio/wav.cpp b/unify/engine/audio/wav.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b4673719a2277c4e6432ad862988fe911bf9aae8 --- /dev/null +++ b/unify/engine/audio/wav.cpp @@ -0,0 +1,111 @@ +#include "audio.h" +#include + +namespace unify { + +static uint32_t rd32(const uint8_t* p) { return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24; } +static uint16_t rd16(const uint8_t* p) { return uint16_t(p[0] | p[1] << 8); } + +bool parse_wav_header(FILE* f, WavInfo& info) { + uint8_t hdr[12]; + if (std::fread(hdr, 1, 12, f) != 12 || std::memcmp(hdr, "RIFF", 4) || std::memcmp(hdr + 8, "WAVE", 4)) return false; + bool have_fmt = false, have_data = false; + uint8_t ch[8]; + while (std::fread(ch, 1, 8, f) == 8) { + uint32_t size = rd32(ch + 4); + long body = std::ftell(f); + if (!std::memcmp(ch, "fmt ", 4)) { + uint8_t fmt[16]; + if (size < 16 || std::fread(fmt, 1, 16, f) != 16) return false; + if (rd16(fmt) != 1) return false; // PCM only + info.channels = rd16(fmt + 2); + info.sample_rate = rd32(fmt + 4); + info.bits = rd16(fmt + 14); + have_fmt = true; + } else if (!std::memcmp(ch, "data", 4)) { + info.data_offset = uint64_t(body); + if (have_fmt && info.channels) info.frames = size / (uint32_t(info.channels) * (info.bits / 8)); + have_data = true; + } else if (!std::memcmp(ch, "smpl", 4) && size >= 36 + 24) { + std::vector s(size); + if (std::fread(s.data(), 1, size, f) != size) return false; + if (rd32(&s[28]) > 0) { // num sample loops + info.loop_start = rd32(&s[36 + 8]); + info.loop_end = int64_t(rd32(&s[36 + 12])) + 1; // 'end' is inclusive in the spec + } + } + std::fseek(f, body + long(size + (size & 1)), SEEK_SET); + } + return have_fmt && have_data && info.bits == 16 && (info.channels == 1 || info.channels == 2); +} + +WavDecoder::~WavDecoder() { if (file_) std::fclose(file_); } + +bool WavDecoder::open(const std::string& path) { + if (file_) std::fclose(file_); + file_ = std::fopen(path.c_str(), "rb"); + if (!file_ || !parse_wav_header(file_, info_)) { if (file_) std::fclose(file_); file_ = nullptr; return false; } + return seek(0); +} + +bool WavDecoder::seek(uint32_t frame) { + if (!file_) return false; + if (frame > info_.frames) frame = info_.frames; + pos_ = frame; + return std::fseek(file_, long(info_.data_offset + uint64_t(frame) * info_.channels * 2), SEEK_SET) == 0; +} + +uint32_t WavDecoder::read(float* out, uint32_t frames) { + if (!file_) return 0; + uint32_t n = std::min(frames, info_.frames - pos_); + scratch_.resize(size_t(n) * info_.channels); + size_t got = std::fread(scratch_.data(), 2 * info_.channels, n, file_); + for (size_t i = 0; i < got; i++) { + if (info_.channels == 2) { + out[2 * i] = scratch_[2 * i] / 32768.0f; + out[2 * i + 1] = scratch_[2 * i + 1] / 32768.0f; + } else { + out[2 * i] = out[2 * i + 1] = scratch_[i] / 32768.0f; + } + } + pos_ += uint32_t(got); + return uint32_t(got); +} + +bool write_wav(const std::string& path, const std::vector& pcm, uint16_t channels, uint32_t rate, int64_t loop_start, int64_t loop_end) { + FILE* f = std::fopen(path.c_str(), "wb"); + if (!f) return false; + auto w32 = [&](uint32_t v) { uint8_t b[4] = {uint8_t(v), uint8_t(v >> 8), uint8_t(v >> 16), uint8_t(v >> 24)}; std::fwrite(b, 1, 4, f); }; + auto w16 = [&](uint16_t v) { uint8_t b[2] = {uint8_t(v), uint8_t(v >> 8)}; std::fwrite(b, 1, 2, f); }; + uint32_t data_bytes = uint32_t(pcm.size() * 2); + bool has_loop = loop_start >= 0 && loop_end > loop_start; + uint32_t smpl_size = has_loop ? 36 + 24 : 0; + std::fwrite("RIFF", 1, 4, f); + w32(4 + (8 + 16) + (8 + data_bytes) + (has_loop ? 8 + smpl_size : 0)); + std::fwrite("WAVE", 1, 4, f); + std::fwrite("fmt ", 1, 4, f); w32(16); + w16(1); w16(channels); w32(rate); w32(rate * channels * 2); w16(uint16_t(channels * 2)); w16(16); + if (has_loop) { + std::fwrite("smpl", 1, 4, f); w32(smpl_size); + for (int i = 0; i < 7; i++) w32(i == 2 ? 1000000000u / rate : 0); // manufacturer..SMPTE; [2]=sample period ns + w32(1); w32(0); // num loops, sampler data + w32(0); w32(0); w32(uint32_t(loop_start)); w32(uint32_t(loop_end - 1)); w32(0); w32(0); + } + std::fwrite("data", 1, 4, f); w32(data_bytes); + std::fwrite(pcm.data(), 2, pcm.size(), f); + return std::fclose(f) == 0; +} + +bool AudioClip::load_wav(const std::string& path) { + WavDecoder d; + if (!d.open(path)) return false; + sample_rate = d.info().sample_rate; + samples.resize(size_t(d.info().frames) * 2); + uint32_t got = d.read(samples.data(), d.info().frames); + samples.resize(size_t(got) * 2); + loop_start = d.info().loop_start >= 0 ? uint32_t(d.info().loop_start) : 0; + loop_end = d.info().loop_end > 0 ? uint32_t(d.info().loop_end) : 0; + return true; +} + +} // namespace unify diff --git a/unify/engine/core/core.cpp b/unify/engine/core/core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c47ef6a5bd4b411ca043894336f27357847eac0e --- /dev/null +++ b/unify/engine/core/core.cpp @@ -0,0 +1,29 @@ +#include "core.h" +#include +#include + +namespace unify { + +uint64_t wall_clock_ns() { + static const auto start = std::chrono::steady_clock::now(); + return uint64_t(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()); +} + +static LogLevel g_min_level = LogLevel::Info; +static std::mutex g_log_mutex; + +void set_log_level(LogLevel min_level) { g_min_level = min_level; } + +void log_message(LogLevel level, const char* category, const char* fmt, ...) { + if (level < g_min_level) return; + static const char* names[] = {"DEBUG", "INFO", "WARN", "ERROR"}; + char buf[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buf, sizeof buf, fmt, args); + va_end(args); + std::lock_guard lock(g_log_mutex); + std::fprintf(level >= LogLevel::Warn ? stderr : stdout, "[%s] [%s] %s\n", names[int(level)], category, buf); +} + +} // namespace unify diff --git a/unify/engine/core/core.h b/unify/engine/core/core.h new file mode 100644 index 0000000000000000000000000000000000000000..cd5b0c1e2b95d1cea815cc0517d0ffa42182d101 --- /dev/null +++ b/unify/engine/core/core.h @@ -0,0 +1,103 @@ +#pragma once +#include +#include +#include +#include + +namespace unify { + +// --------------------------------------------------------------------------------------- +// Deterministic RNG. The ONLY random source simulation code may use (engine, physics, Lua). +// xoshiro128** — 128-bit state, fully serializable, identical output on every platform. +// --------------------------------------------------------------------------------------- +class Rng { +public: + explicit Rng(uint64_t seed = 0x5eed) { reseed(seed); } + void reseed(uint64_t seed) { + // SplitMix64 expands the seed so nearby seeds give unrelated streams. + for (int i = 0; i < 4; i += 2) { + seed += 0x9E3779B97F4A7C15ull; + uint64_t z = seed; + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + z ^= z >> 31; + s_[i] = uint32_t(z); + s_[i + 1] = uint32_t(z >> 32); + } + if ((s_[0] | s_[1] | s_[2] | s_[3]) == 0) s_[0] = 1; + } + uint32_t next_u32() { + uint32_t result = rotl(s_[1] * 5, 7) * 9; + uint32_t t = s_[1] << 9; + s_[2] ^= s_[0]; s_[3] ^= s_[1]; s_[1] ^= s_[2]; s_[0] ^= s_[3]; + s_[2] ^= t; s_[3] = rotl(s_[3], 11); + return result; + } + /// [0, 1) with 24 bits of precision: exactly representable in float, no rounding drift. + float next_float() { return float(next_u32() >> 8) * (1.0f / 16777216.0f); } + float range(float lo, float hi) { return lo + (hi - lo) * next_float(); } + int32_t range_int(int32_t lo, int32_t hi_inclusive) { + uint32_t span = uint32_t(hi_inclusive - lo) + 1; + return span == 0 ? int32_t(next_u32()) : lo + int32_t(next_u32() % span); + } + const uint32_t* state() const { return s_; } + void set_state(const uint32_t st[4]) { for (int i = 0; i < 4; i++) s_[i] = st[i]; } + +private: + static uint32_t rotl(uint32_t x, int k) { return (x << k) | (x >> (32 - k)); } + uint32_t s_[4]; +}; + +// --------------------------------------------------------------------------------------- +// Clocks. Five independent notions of time; only SimClock is visible to gameplay. +// --------------------------------------------------------------------------------------- + +/// Wall clock: platform monotonic time in nanoseconds. Nondeterministic; never read by simulation. +uint64_t wall_clock_ns(); + +/// Simulation time: an integer tick counter. Seconds are derived, never accumulated, +/// so there is no floating-point drift across long sessions or save/restore. +struct SimClock { + uint64_t tick = 0; + uint32_t ticks_per_second = 60; + double dt() const { return 1.0 / ticks_per_second; } + float dtf() const { return 1.0f / float(ticks_per_second); } + double seconds() const { return double(tick) / ticks_per_second; } + /// Input timestamps are nanoseconds since engine start on the input clock; tick N covers + /// the half-open interval [N*dt, (N+1)*dt). + uint64_t tick_end_ns(uint64_t t) const { return (t + 1) * 1000000000ull / ticks_per_second; } +}; + +/// Render time: wall time of the current frame plus the interpolation factor between the +/// previous and current simulation states. +struct RenderClock { + uint64_t frame = 0; + double seconds = 0; + float alpha = 0; // 0..1 blend between previous and current sim state + double frame_ms = 0; +}; + +// --------------------------------------------------------------------------------------- +// Logging +// --------------------------------------------------------------------------------------- +enum class LogLevel { Debug, Info, Warn, Error }; +void log_message(LogLevel level, const char* category, const char* fmt, ...) +#if defined(__GNUC__) + __attribute__((format(printf, 3, 4))) +#endif + ; +void set_log_level(LogLevel min_level); + +#define UNIFY_LOG_INFO(cat, ...) ::unify::log_message(::unify::LogLevel::Info, cat, __VA_ARGS__) +#define UNIFY_LOG_WARN(cat, ...) ::unify::log_message(::unify::LogLevel::Warn, cat, __VA_ARGS__) +#define UNIFY_LOG_ERROR(cat, ...) ::unify::log_message(::unify::LogLevel::Error, cat, __VA_ARGS__) +#define UNIFY_LOG_DEBUG(cat, ...) ::unify::log_message(::unify::LogLevel::Debug, cat, __VA_ARGS__) + +/// FNV-1a 64 over bytes; used for state hashes (determinism checks, rollback verification). +inline uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull) { + auto p = static_cast(data); + for (size_t i = 0; i < n; i++) { h ^= p[i]; h *= 1099511628211ull; } + return h; +} + +} // namespace unify diff --git a/unify/engine/core/handle.h b/unify/engine/core/handle.h new file mode 100644 index 0000000000000000000000000000000000000000..66ae5b2de5d26923b7bc6977f467196b7b91bb07 --- /dev/null +++ b/unify/engine/core/handle.h @@ -0,0 +1,110 @@ +#pragma once +#include +#include +#include +#include + +namespace unify { + +/// Generational handle: 24-bit slot index + 8-bit generation, packed in 32 bits. +/// Handles are what cross subsystem and script boundaries; raw pointers never do. +/// A handle whose generation no longer matches its slot is stale and fails validation. +template +struct Handle { + uint32_t bits = 0; // 0 == null (generation 0 is never issued) + static constexpr uint32_t kIndexBits = 24; + static constexpr uint32_t kIndexMask = (1u << kIndexBits) - 1; + + static Handle make(uint32_t index, uint8_t gen) { return Handle{(uint32_t(gen) << kIndexBits) | (index & kIndexMask)}; } + uint32_t index() const { return bits & kIndexMask; } + uint8_t generation() const { return uint8_t(bits >> kIndexBits); } + bool is_null() const { return bits == 0; } + explicit operator bool() const { return bits != 0; } + bool operator==(const Handle& o) const { return bits == o.bits; } + bool operator!=(const Handle& o) const { return bits != o.bits; } + bool operator<(const Handle& o) const { return bits < o.bits; } +}; + +struct EntityTag {}; +struct TextureTag {}; +struct AudioTag {}; +struct PhysicsBodyTag {}; +struct BufferTag {}; +struct KernelTag {}; +struct AssetTag {}; +struct ClipTag {}; + +using EntityHandle = Handle; +using TextureHandle = Handle; +using AudioHandle = Handle; // a playing voice +using PhysicsBodyHandle = Handle; +using BufferHandle = Handle; +using KernelHandle = Handle; +using AssetHandle = Handle; + +/// Issues and validates generational handles over a dense slot range with a free list. +/// Free order is LIFO and fully deterministic, so the same sequence of alloc/free calls +/// always yields the same handles (required for deterministic replay and save states). +template +class HandlePool { +public: + H allocate() { + uint32_t index; + if (!free_.empty()) { + index = free_.back(); + free_.pop_back(); + } else { + index = uint32_t(gens_.size()); + assert(index <= H::kIndexMask); + gens_.push_back(1); + live_.push_back(0); + } + live_[index] = 1; + alive_++; + return H::make(index, gens_[index]); + } + + bool valid(H h) const { + uint32_t i = h.index(); + return !h.is_null() && i < gens_.size() && live_[i] && gens_[i] == h.generation(); + } + + bool release(H h) { + if (!valid(h)) return false; + uint8_t& g = gens_[h.index()]; + g = uint8_t(g + 1); + if (g == 0) g = 1; // skip 0 so a recycled slot never re-issues null + live_[h.index()] = 0; + free_.push_back(h.index()); + alive_--; + return true; + } + + /// Handle currently occupying a slot (for iteration); null if the slot is free. + H at(uint32_t index) const { return index < gens_.size() && live_[index] ? H::make(index, gens_[index]) : H{}; } + + uint32_t alive() const { return alive_; } + uint32_t capacity() const { return uint32_t(gens_.size()); } + void reserve(size_t n) { gens_.reserve(n); free_.reserve(n); live_.reserve(n); } + + /// Raw state for save/restore: generations, liveness and free-list order. + struct State { std::vector gens; std::vector live; std::vector free; uint32_t alive = 0; }; + State save() const { return {gens_, live_, free_, alive_}; } + void load(const State& s) { gens_ = s.gens; live_ = s.live; free_ = s.free; alive_ = s.alive; } + void clear() { gens_.clear(); live_.clear(); free_.clear(); alive_ = 0; } + +private: + std::vector gens_; + std::vector live_; + std::vector free_; + uint32_t alive_ = 0; +}; + +} // namespace unify + +namespace std { +template +struct hash> { + size_t operator()(const unify::Handle& h) const noexcept { return std::hash()(h.bits); } +}; +} // namespace std diff --git a/unify/engine/core/math.h b/unify/engine/core/math.h new file mode 100644 index 0000000000000000000000000000000000000000..7cf1ac29174c390967a5cac9341931c2069eecf7 --- /dev/null +++ b/unify/engine/core/math.h @@ -0,0 +1,79 @@ +#pragma once +#include +#include +#include + +namespace unify { + +struct Vec2 { + float x = 0, y = 0; + constexpr Vec2() = default; + constexpr Vec2(float x_, float y_) : x(x_), y(y_) {} + Vec2 operator+(Vec2 o) const { return {x + o.x, y + o.y}; } + Vec2 operator-(Vec2 o) const { return {x - o.x, y - o.y}; } + Vec2 operator-() const { return {-x, -y}; } + Vec2 operator*(float s) const { return {x * s, y * s}; } + Vec2 operator/(float s) const { return {x / s, y / s}; } + Vec2& operator+=(Vec2 o) { x += o.x; y += o.y; return *this; } + Vec2& operator-=(Vec2 o) { x -= o.x; y -= o.y; return *this; } + Vec2& operator*=(float s) { x *= s; y *= s; return *this; } + bool operator==(Vec2 o) const { return x == o.x && y == o.y; } + bool operator!=(Vec2 o) const { return !(*this == o); } +}; +inline Vec2 operator*(float s, Vec2 v) { return {v.x * s, v.y * s}; } +inline float dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; } +inline float cross(Vec2 a, Vec2 b) { return a.x * b.y - a.y * b.x; } +inline Vec2 cross(Vec2 a, float s) { return {s * a.y, -s * a.x}; } +inline Vec2 cross(float s, Vec2 a) { return {-s * a.y, s * a.x}; } +inline float length_sq(Vec2 v) { return dot(v, v); } +inline float length(Vec2 v) { return std::sqrt(dot(v, v)); } +inline Vec2 perp(Vec2 v) { return {-v.y, v.x}; } +inline Vec2 normalize(Vec2 v) { + float l = length(v); + return l > 1e-12f ? v / l : Vec2{0, 0}; +} +inline Vec2 vmin(Vec2 a, Vec2 b) { return {std::min(a.x, b.x), std::min(a.y, b.y)}; } +inline Vec2 vmax(Vec2 a, Vec2 b) { return {std::max(a.x, b.x), std::max(a.y, b.y)}; } +inline bool finite(Vec2 v) { return std::isfinite(v.x) && std::isfinite(v.y); } +inline float lerp(float a, float b, float t) { return a + (b - a) * t; } +inline Vec2 lerp(Vec2 a, Vec2 b, float t) { return a + (b - a) * t; } +inline float clampf(float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); } + +/// 2D rotation stored as cos/sin so composing and inverting never calls trig. +struct Rot { + float c = 1, s = 0; + Rot() = default; + explicit Rot(float angle) : c(std::cos(angle)), s(std::sin(angle)) {} + float angle() const { return std::atan2(s, c); } + Vec2 apply(Vec2 v) const { return {c * v.x - s * v.y, s * v.x + c * v.y}; } + Vec2 apply_inv(Vec2 v) const { return {c * v.x + s * v.y, -s * v.x + c * v.y}; } +}; + +struct Transform { + Vec2 position; + float rotation = 0; // radians + Vec2 scale{1, 1}; + Vec2 apply(Vec2 local) const { + Rot r(rotation); + return position + r.apply({local.x * scale.x, local.y * scale.y}); + } +}; + +struct AABB { + Vec2 min, max; + bool overlaps(const AABB& o) const { + return !(max.x < o.min.x || o.max.x < min.x || max.y < o.min.y || o.max.y < min.y); + } + AABB merged(const AABB& o) const { return {vmin(min, o.min), vmax(max, o.max)}; } + AABB expanded(float r) const { return {{min.x - r, min.y - r}, {max.x + r, max.y + r}}; } + Vec2 center() const { return (min + max) * 0.5f; } + Vec2 extent() const { return (max - min) * 0.5f; } +}; + +struct Color { + uint8_t r = 255, g = 255, b = 255, a = 255; + static constexpr Color rgba(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255) { return Color{r, g, b, a}; } + bool operator==(const Color& o) const { return r == o.r && g == o.g && b == o.b && a == o.a; } +}; + +} // namespace unify diff --git a/unify/engine/ecs/ecs.h b/unify/engine/ecs/ecs.h new file mode 100644 index 0000000000000000000000000000000000000000..e56df1868d81af093826310b8b07e58613fa8357 --- /dev/null +++ b/unify/engine/ecs/ecs.h @@ -0,0 +1,155 @@ +#pragma once +#include +#include +#include +#include +#include "../core/handle.h" +#include "../core/math.h" + +namespace unify { + +/// Sparse-set component storage. Dense arrays give cache-friendly, deterministic +/// iteration (order depends only on the sequence of add/remove calls). +template +class ComponentPool { +public: + static constexpr uint32_t kNone = 0xFFFFFFFFu; + + T& add(EntityHandle e, T value = T{}) { + uint32_t i = e.index(); + if (i >= sparse_.size()) sparse_.resize(i + 1, kNone); + if (sparse_[i] != kNone) { dense_[sparse_[i]] = std::move(value); owners_[sparse_[i]] = e; return dense_[sparse_[i]]; } + sparse_[i] = uint32_t(dense_.size()); + dense_.push_back(std::move(value)); + owners_.push_back(e); + return dense_.back(); + } + bool remove(EntityHandle e) { + uint32_t i = e.index(); + if (i >= sparse_.size() || sparse_[i] == kNone || owners_[sparse_[i]] != e) return false; + uint32_t slot = sparse_[i]; + uint32_t last = uint32_t(dense_.size() - 1); + if (slot != last) { + dense_[slot] = std::move(dense_[last]); + owners_[slot] = owners_[last]; + sparse_[owners_[slot].index()] = slot; + } + dense_.pop_back(); + owners_.pop_back(); + sparse_[i] = kNone; + return true; + } + T* get(EntityHandle e) { + uint32_t i = e.index(); + if (i >= sparse_.size() || sparse_[i] == kNone || owners_[sparse_[i]] != e) return nullptr; + return &dense_[sparse_[i]]; + } + const T* get(EntityHandle e) const { return const_cast(this)->get(e); } + bool has(EntityHandle e) const { return get(e) != nullptr; } + size_t size() const { return dense_.size(); } + T& at(size_t i) { return dense_[i]; } + const T& at(size_t i) const { return dense_[i]; } + EntityHandle owner(size_t i) const { return owners_[i]; } + void clear() { dense_.clear(); owners_.clear(); sparse_.clear(); } + void reserve(size_t n) { dense_.reserve(n); owners_.reserve(n); sparse_.reserve(n); } + template void each(F&& f) { for (size_t i = 0; i < dense_.size(); i++) f(owners_[i], dense_[i]); } +private: + std::vector dense_; + std::vector owners_; + std::vector sparse_; +}; + +// ----- Engine components ------------------------------------------------------------- + +struct TransformC { + Transform current; + Transform previous; // last tick's pose, for render interpolation +}; + +struct SpriteC { + uint32_t texture = 0; // TextureHandle bits + uint32_t atlas_region = 0; // region index within the texture's atlas (0 = whole texture) + Vec2 size{16, 16}; // world units + Vec2 pivot{0.5f, 0.5f}; + Color tint{}; + int16_t layer = 0; + float depth = 0; + bool flip_x = false; + bool visible = true; +}; + +struct BodyC { uint32_t body = 0; }; // PhysicsBodyHandle bits +struct AnimatorC { uint32_t player = 0; }; // index into AnimationSystem players + +struct EntityInfo { + std::string name; + std::string prefab; + uint16_t scene = 0; // owning scene id; 0 = persistent across scene transitions + uint32_t tags = 0; +}; + +/// The entity/component database. Owns entity lifetime; subsystems (physics, animation, +/// audio) own their own data and are linked to entities by handle through components. +class World { +public: + World() { entities_.reserve(4096); } + + EntityHandle create(const std::string& name = {}, uint16_t scene = 0) { + EntityHandle e = entities_.allocate(); + if (e.index() >= info_.size()) info_.resize(e.index() + 1); + info_[e.index()] = EntityInfo{name, {}, scene, 0}; + transforms.add(e); + return e; + } + /// Destroys an entity and its engine components. Subsystem resources are released by + /// the on_destroy hooks (physics bodies, animation players, script refs) first. + bool destroy(EntityHandle e) { + if (!entities_.valid(e)) return false; + for (auto& hook : on_destroy_) hook(e); + transforms.remove(e); + sprites.remove(e); + bodies.remove(e); + animators.remove(e); + info_[e.index()] = {}; + entities_.release(e); + return true; + } + bool valid(EntityHandle e) const { return entities_.valid(e); } + EntityInfo* info(EntityHandle e) { return valid(e) ? &info_[e.index()] : nullptr; } + uint32_t alive() const { return entities_.alive(); } + uint32_t capacity() const { return entities_.capacity(); } + EntityHandle at(uint32_t index) const { return entities_.at(index); } + + EntityHandle find(const std::string& name) const { + for (uint32_t i = 0; i < entities_.capacity(); i++) { + EntityHandle e = entities_.at(i); + if (e && info_[i].name == name) return e; + } + return {}; + } + template void each_entity(F&& f) const { + for (uint32_t i = 0; i < entities_.capacity(); i++) if (EntityHandle e = entities_.at(i)) f(e); + } + + void add_destroy_hook(std::function hook) { on_destroy_.push_back(std::move(hook)); } + + ComponentPool transforms; + ComponentPool sprites; + ComponentPool bodies; + ComponentPool animators; + + // Save-state access. + HandlePool& entity_pool() { return entities_; } + std::vector& infos() { return info_; } + void clear() { + entities_.clear(); info_.clear(); + transforms.clear(); sprites.clear(); bodies.clear(); animators.clear(); + } + +private: + HandlePool entities_; + std::vector info_; + std::vector> on_destroy_; +}; + +} // namespace unify diff --git a/unify/engine/input/input.cpp b/unify/engine/input/input.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aaf46887fcf03b7c5a06e070f2c015e0a0245c52 --- /dev/null +++ b/unify/engine/input/input.cpp @@ -0,0 +1,148 @@ +#include "input.h" +#include "../serialization/stream.h" +#include + +namespace unify { + +static void insert_sorted(std::vector& v, uint16_t c) { + auto it = std::lower_bound(v.begin(), v.end(), c); + if (it == v.end() || *it != c) v.insert(it, c); +} +static void erase_sorted(std::vector& v, uint16_t c) { + auto it = std::lower_bound(v.begin(), v.end(), c); + if (it != v.end() && *it == c) v.erase(it); +} + +void InputSystem::push(const InputEvent& e) { + std::lock_guard lock(mutex_); + // Keep the queue ordered by timestamp even if devices report slightly out of order. + auto it = std::upper_bound(queue_.begin(), queue_.end(), e.timestamp_ns, + [](uint64_t t, const InputEvent& x) { return t < x.timestamp_ns; }); + queue_.insert(it, e); +} + +const InputFrame& InputSystem::consume_tick(uint64_t tick, uint64_t tick_end_ns) { + drained_.clear(); + { + std::lock_guard lock(mutex_); + size_t n = 0; + while (n < queue_.size() && queue_[n].timestamp_ns < tick_end_ns) n++; + drained_.insert(drained_.end(), queue_.begin(), queue_.begin() + long(n)); + queue_.erase(queue_.begin(), queue_.begin() + long(n)); + } + InputFrame& f = frame_; + f.tick = tick; + f.pressed.clear(); f.released.clear(); f.repeated.clear(); + for (const InputEvent& e : drained_) { + switch (e.type) { + case InputEventType::ButtonDown: + // A down while already down (lost up event) still counts as held, not a new press. + if (!std::binary_search(down_.begin(), down_.end(), e.code)) insert_sorted(f.pressed, e.code); + insert_sorted(down_, e.code); + break; + case InputEventType::ButtonUp: + if (std::binary_search(down_.begin(), down_.end(), e.code)) insert_sorted(f.released, e.code); + erase_sorted(down_, e.code); + break; + case InputEventType::ButtonRepeat: insert_sorted(f.repeated, e.code); break; + case InputEventType::Axis: axes_[e.code] = clampf(e.value, -1, 1); break; + case InputEventType::PointerMove: pointer_ = {e.value, e.value2}; break; + } + } + consumed_ += drained_.size(); + f.held = down_; + f.axes = axes_; + f.pointer = pointer_; + for (auto& kv : bindings_) + if (code_in(f.pressed, kv.first)) last_pressed_tick_[kv.first] = tick + 1; + if (recording_) recorded_.push_back(f); + return f; +} + +const InputFrame& InputSystem::apply_frame(const InputFrame& in) { + frame_ = in; + down_ = in.held; + axes_ = in.axes; + pointer_ = in.pointer; + for (auto& kv : bindings_) + if (code_in(frame_.pressed, kv.first)) last_pressed_tick_[kv.first] = in.tick + 1; + if (recording_) recorded_.push_back(frame_); + return frame_; +} + +void InputSystem::bind(const std::string& action, uint16_t code) { bindings_[action].push_back(code); } +void InputSystem::bind_axis(const std::string& action, uint16_t neg, uint16_t pos, uint16_t analog) { axis_bindings_[action] = {neg, pos, analog}; } + +bool InputSystem::code_in(const std::vector& list, const std::string& action) const { + auto it = bindings_.find(action); + if (it == bindings_.end()) return false; + for (uint16_t c : it->second) if (std::binary_search(list.begin(), list.end(), c)) return true; + return false; +} +bool InputSystem::is_pressed(const std::string& a) const { return code_in(frame_.pressed, a); } +bool InputSystem::is_held(const std::string& a) const { return code_in(frame_.held, a) || code_in(frame_.pressed, a); } +bool InputSystem::is_released(const std::string& a) const { return code_in(frame_.released, a); } +bool InputSystem::is_repeated(const std::string& a) const { return code_in(frame_.repeated, a); } + +float InputSystem::axis(const std::string& action) const { + auto it = axis_bindings_.find(action); + if (it == axis_bindings_.end()) return 0; + float v = 0; + if (std::binary_search(frame_.held.begin(), frame_.held.end(), it->second.neg)) v -= 1; + if (std::binary_search(frame_.held.begin(), frame_.held.end(), it->second.pos)) v += 1; + if (it->second.analog) { + auto a = frame_.axes.find(it->second.analog); + if (a != frame_.axes.end() && std::fabs(a->second) > 0.2f) v += a->second; // dead zone + } + return clampf(v, -1, 1); +} + +bool InputSystem::buffered(const std::string& action, uint32_t ticks) const { + auto it = last_pressed_tick_.find(action); + if (it == last_pressed_tick_.end() || it->second == 0) return false; + uint64_t pressed_tick = it->second - 1; + return frame_.tick - pressed_tick <= ticks; +} +void InputSystem::consume_buffered(const std::string& action) { last_pressed_tick_[action] = 0; } + +// ------------------------------------------------------------------------------ serialization + +static void write_codes(BinaryWriter& w, const std::vector& v) { w.u16(uint16_t(v.size())); for (auto c : v) w.u16(c); } +static std::vector read_codes(BinaryReader& r) { std::vector v(r.u16()); for (auto& c : v) c = r.u16(); return v; } + +void InputFrame::serialize(BinaryWriter& w) const { + w.u64(tick); + write_codes(w, pressed); write_codes(w, released); write_codes(w, repeated); write_codes(w, held); + w.u16(uint16_t(axes.size())); + for (auto& kv : axes) { w.u16(kv.first); w.f32(kv.second); } + w.vec2(pointer); +} +InputFrame InputFrame::deserialize(BinaryReader& r) { + InputFrame f; + f.tick = r.u64(); + f.pressed = read_codes(r); f.released = read_codes(r); f.repeated = read_codes(r); f.held = read_codes(r); + uint16_t n = r.u16(); + for (uint16_t i = 0; i < n; i++) { uint16_t c = r.u16(); f.axes[c] = r.f32(); } + f.pointer = r.vec2(); + return f; +} + +void InputSystem::serialize(BinaryWriter& w) const { + frame_.serialize(w); + write_codes(w, down_); + w.u16(uint16_t(last_pressed_tick_.size())); + for (auto& kv : last_pressed_tick_) { w.str(kv.first); w.u64(kv.second); } +} +void InputSystem::deserialize(BinaryReader& r) { + frame_ = InputFrame::deserialize(r); + down_ = read_codes(r); + axes_ = frame_.axes; + pointer_ = frame_.pointer; + last_pressed_tick_.clear(); + uint16_t n = r.u16(); + for (uint16_t i = 0; i < n; i++) { std::string a = r.str(); last_pressed_tick_[a] = r.u64(); } + std::lock_guard lock(mutex_); + queue_.clear(); // live events from before the restore belong to a timeline that no longer exists +} + +} // namespace unify diff --git a/unify/engine/input/input.h b/unify/engine/input/input.h new file mode 100644 index 0000000000000000000000000000000000000000..944be8a4b091fccc7525d4669053c2dd31b9e12f --- /dev/null +++ b/unify/engine/input/input.h @@ -0,0 +1,112 @@ +#pragma once +#include +#include +#include +#include +#include +#include "../core/math.h" + +namespace unify { +class BinaryWriter; +class BinaryReader; + +enum class InputDevice : uint8_t { Keyboard, Mouse, Gamepad, Touch }; +enum class InputEventType : uint8_t { ButtonDown, ButtonUp, ButtonRepeat, Axis, PointerMove }; + +/// Engine-level key/button codes (platform backends translate into these). +namespace key { +enum : uint16_t { + Unknown = 0, E = 'e', I = 'i', A = 'a', D = 'd', S = 's', W = 'w', R = 'r', P = 'p', + Space = 32, Escape = 27, Enter = 13, + Left = 256, Right, Up, Down, F5, F9, F1, F2, F3, LShift, + MouseLeft = 512, MouseRight, MouseMiddle, + PadA = 768, PadB, PadX, PadY, PadStart, PadBack, PadLeft, PadRight, PadUp, PadDown, + PadAxisLeftX = 1024, PadAxisLeftY, + Touch0 = 1280, +}; +} + +struct InputEvent { + uint64_t timestamp_ns = 0; // input clock (engine-relative ns); decides which tick consumes it + InputDevice device = InputDevice::Keyboard; + InputEventType type = InputEventType::ButtonDown; + uint16_t code = 0; + float value = 0; // axis value, or pointer x + float value2 = 0; // pointer y +}; + +/// Per-tick digested input: what gameplay reads. Serializable, so it can be recorded, +/// replayed, sent over a network, or stored in a save state. +struct InputFrame { + uint64_t tick = 0; + std::vector pressed; // went down during the tick (even if released in the same tick) + std::vector released; // went up during the tick + std::vector repeated; + std::vector held; // down at the end of the tick + std::map axes; + Vec2 pointer; + bool operator==(const InputFrame& o) const { + return tick == o.tick && pressed == o.pressed && released == o.released && repeated == o.repeated && held == o.held && axes == o.axes && pointer == o.pointer; + } + void serialize(BinaryWriter& w) const; + static InputFrame deserialize(BinaryReader& r); +}; + +/// OS thread → queue → timestamp → fixed-tick consumption → gameplay. +/// +/// Platform code calls push() (thread-safe) as events arrive. At each fixed tick the +/// scheduler calls consume_tick(tick_end_ns), which drains every event stamped before the +/// end of that tick and folds it into an InputFrame. Events stamped later stay queued for +/// the next tick, so a burst of fast frames or a long frame never drops or double-counts. +class InputSystem { +public: + void push(const InputEvent& e); + /// Builds the frame for `tick` from all queued events with timestamp < tick_end_ns. + const InputFrame& consume_tick(uint64_t tick, uint64_t tick_end_ns); + /// Replay / network path: use a recorded frame instead of live events. + const InputFrame& apply_frame(const InputFrame& f); + + // Action mapping ("jump" -> Space, W, PadA ...). + void bind(const std::string& action, uint16_t code); + void bind_axis(const std::string& action, uint16_t negative, uint16_t positive, uint16_t analog_axis = 0); + bool is_pressed(const std::string& action) const; + bool is_held(const std::string& action) const; + bool is_released(const std::string& action) const; + bool is_repeated(const std::string& action) const; + float axis(const std::string& action) const; + /// True if the action was pressed within the last `ticks` ticks and not yet consumed. + /// This is the gameplay-side buffer (e.g. jump pressed just before landing). + bool buffered(const std::string& action, uint32_t ticks) const; + void consume_buffered(const std::string& action); + Vec2 pointer() const { return frame_.pointer; } + + const InputFrame& frame() const { return frame_; } + size_t queued() const { std::lock_guard l(mutex_); return queue_.size(); } + uint64_t events_consumed() const { return consumed_; } + + // Recording for deterministic replay. + void set_recording(bool on) { recording_ = on; if (on) recorded_.clear(); } + const std::vector& recorded() const { return recorded_; } + + void serialize(BinaryWriter& w) const; + void deserialize(BinaryReader& r); + +private: + bool code_in(const std::vector& list, const std::string& action) const; + mutable std::mutex mutex_; + std::vector queue_; // guarded by mutex_ + std::vector drained_; // tick-local scratch (no per-tick allocation after warmup) + std::vector down_; // keys currently down (sorted) + std::map axes_; + Vec2 pointer_; + InputFrame frame_; + std::map> bindings_; + struct AxisBinding { uint16_t neg, pos, analog; }; + std::map axis_bindings_; + std::map last_pressed_tick_; // action -> tick+1 of last unconsumed press + uint64_t consumed_ = 0; + bool recording_ = false; + std::vector recorded_; +}; + +} // namespace unify diff --git a/unify/engine/kernel/backend.cpp b/unify/engine/kernel/backend.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06d40cc2dab40acf3b913d62f3a79102da901d21 --- /dev/null +++ b/unify/engine/kernel/backend.cpp @@ -0,0 +1,407 @@ +// IR optimisation (constant folding), IR printing, and WASM code generation. +#include "kernel.h" +#include "../wasm/wasm.h" +#include +#include +#include + +namespace unify::kernel { + +namespace { +float as_f(uint32_t b) { float f; std::memcpy(&f, &b, 4); return f; } +uint32_t fb(float f) { uint32_t b; std::memcpy(&b, &f, 4); return b; } + +// ---------------------------------------------------------------------------- folding +bool fold_expr(IRExprP& e, uint32_t& count) { + for (auto& a : e->args) fold_expr(a, count); + auto is_const = [](const IRExprP& x) { return x->kind == IRExpr::Const; }; + if (e->kind == IRExpr::Convert && is_const(e->args[0])) { + IRExpr& a = *e->args[0]; + uint32_t bits; + if (e->type == IRType::F32) bits = fb(float(int32_t(a.bits))); + else { + float f = as_f(a.bits); + if (!(f > -2147483648.0f && f < 2147483648.0f)) return false; // would trap at runtime; keep it + bits = uint32_t(int32_t(f)); + } + auto c = std::make_unique(); + c->kind = IRExpr::Const; c->type = e->type; c->bits = bits; + e = std::move(c); + count++; + return true; + } + if (e->kind == IRExpr::Binary && is_const(e->args[0]) && is_const(e->args[1])) { + const std::string& op = e->op; + IRType operand = e->args[0]->type; + uint32_t r = 0; + if (operand == IRType::I32) { + int32_t a = int32_t(e->args[0]->bits), b = int32_t(e->args[1]->bits); + if ((op == "/" || op == "%") && (b == 0 || (a == INT32_MIN && b == -1))) return false; // runtime trap semantics + if (op == "+") r = uint32_t(a) + uint32_t(b); + else if (op == "-") r = uint32_t(a) - uint32_t(b); + else if (op == "*") r = uint32_t(a) * uint32_t(b); + else if (op == "/") r = uint32_t(a / b); + else if (op == "%") r = uint32_t(a % b); + else if (op == "<") r = a < b; else if (op == "<=") r = a <= b; + else if (op == ">") r = a > b; else if (op == ">=") r = a >= b; + else if (op == "==") r = a == b; else if (op == "!=") r = a != b; + else if (op == "&&") r = (a != 0) & (b != 0); else if (op == "||") r = (a != 0) | (b != 0); + else return false; + } else { + float a = as_f(e->args[0]->bits), b = as_f(e->args[1]->bits); + if (op == "+") r = fb(a + b); else if (op == "-") r = fb(a - b); + else if (op == "*") r = fb(a * b); else if (op == "/") r = fb(a / b); + else if (op == "<") r = a < b; else if (op == "<=") r = a <= b; + else if (op == ">") r = a > b; else if (op == ">=") r = a >= b; + else if (op == "==") r = a == b; else if (op == "!=") r = a != b; + else return false; + } + auto c = std::make_unique(); + c->kind = IRExpr::Const; c->type = e->type; c->bits = r; + e = std::move(c); + count++; + return true; + } + if (e->kind == IRExpr::Unary && is_const(e->args[0])) { + uint32_t v = e->args[0]->bits, r; + if (e->op == "!") r = v == 0; + else if (e->type == IRType::I32) r = uint32_t(-int32_t(v)); + else r = fb(-as_f(v)); + auto c = std::make_unique(); + c->kind = IRExpr::Const; c->type = e->type; c->bits = r; + e = std::move(c); + count++; + return true; + } + return false; +} + +void fold_block(std::vector& body, uint32_t& count) { + std::vector out; + for (auto& s : body) { + if (s->value) fold_expr(s->value, count); + if (s->index) fold_expr(s->index, count); + if (s->cond) fold_expr(s->cond, count); + fold_block(s->then_body, count); + fold_block(s->else_body, count); + fold_block(s->body, count); + fold_block(s->step, count); + // Dead-branch elimination for constant conditions. + if (s->kind == IRStmt::If && s->cond->kind == IRExpr::Const) { + auto& taken = s->cond->bits ? s->then_body : s->else_body; + for (auto& t : taken) out.push_back(std::move(t)); + count++; + continue; + } + if (s->kind == IRStmt::Loop && s->cond->kind == IRExpr::Const && s->cond->bits == 0) { count++; continue; } + out.push_back(std::move(s)); + } + body = std::move(out); +} + +// ---------------------------------------------------------------------------- printing +const char* tn(IRType t) { return t == IRType::F32 ? "f32" : "i32"; } + +void print_expr(std::ostream& o, const IRExpr& e, const IRFunction& fn) { + auto local_name = [&](uint32_t i) -> std::string { + static const char* b[] = {"threadIdx.x", "blockIdx.x", "blockDim.x", "gridDim.x"}; + if (i < 4) return b[i]; + if (i < fn.param_types.size()) return "%p" + std::to_string(i - 4); + return "%" + fn.local_names[i - fn.param_types.size()]; + }; + switch (e.kind) { + case IRExpr::Const: if (e.type == IRType::F32) o << as_f(e.bits) << "f"; else o << int32_t(e.bits); break; + case IRExpr::Local: o << local_name(e.local); break; + case IRExpr::Load: o << "load." << tn(e.type) << " " << local_name(e.local) << "["; print_expr(o, *e.args[0], fn); o << "]"; break; + case IRExpr::Binary: o << "("; print_expr(o, *e.args[0], fn); o << " " << e.op << "." << tn(e.args[0]->type) << " "; print_expr(o, *e.args[1], fn); o << ")"; break; + case IRExpr::Unary: o << e.op << "("; print_expr(o, *e.args[0], fn); o << ")"; break; + case IRExpr::Convert: o << "convert." << tn(e.type) << "("; print_expr(o, *e.args[0], fn); o << ")"; break; + case IRExpr::Intrinsic: + o << e.op << "("; + for (size_t i = 0; i < e.args.size(); i++) { if (i) o << ", "; print_expr(o, *e.args[i], fn); } + o << ")"; + break; + } +} + +void print_block(std::ostream& o, const std::vector& body, const IRFunction& fn, int indent) { + std::string pad(size_t(indent) * 2, ' '); + for (auto& s : body) { + switch (s->kind) { + case IRStmt::SetLocal: { + IRExpr l; l.kind = IRExpr::Local; l.local = s->local; + o << pad; print_expr(o, l, fn); o << " = "; print_expr(o, *s->value, fn); o << "\n"; + break; + } + case IRStmt::Store: { + IRExpr l; l.kind = IRExpr::Local; l.local = s->local; + o << pad << "store." << tn(s->type) << " "; print_expr(o, l, fn); o << "["; print_expr(o, *s->index, fn); o << "] = "; + print_expr(o, *s->value, fn); o << "\n"; + break; + } + case IRStmt::If: + o << pad << "if "; print_expr(o, *s->cond, fn); o << " {\n"; + print_block(o, s->then_body, fn, indent + 1); + if (!s->else_body.empty()) { o << pad << "} else {\n"; print_block(o, s->else_body, fn, indent + 1); } + o << pad << "}\n"; + break; + case IRStmt::Loop: + o << pad << "loop while "; print_expr(o, *s->cond, fn); o << " {\n"; + print_block(o, s->body, fn, indent + 1); + if (!s->step.empty()) { o << pad << "} step {\n"; print_block(o, s->step, fn, indent + 1); } + o << pad << "}\n"; + break; + case IRStmt::Return: o << pad << "return\n"; break; + case IRStmt::Break: o << pad << "break\n"; break; + case IRStmt::Continue: o << pad << "continue\n"; break; + } + } +} + +// ---------------------------------------------------------------------------- WASM emission +using wasm::write_sleb; +using wasm::write_uleb; + +struct Emitter { + std::vector code; + // Branch depths: how many structured blocks deep we are relative to the innermost loop's + // break (outer block) and continue (inner block) targets. + std::vector break_depth, continue_depth; + uint32_t depth = 0; + + void op(uint8_t b) { code.push_back(b); } + void local_get(uint32_t i) { op(0x20); write_uleb(code, i); } + void local_set(uint32_t i) { op(0x21); write_uleb(code, i); } + void i32_const(int32_t v) { op(0x41); write_sleb(code, v); } + void f32_const(uint32_t bits) { op(0x43); for (int i = 0; i < 4; i++) code.push_back(uint8_t(bits >> (8 * i))); } + void begin(uint8_t kind) { op(kind); op(0x40); depth++; } + void end() { op(0x0B); depth--; } + + void address(uint32_t base_local, const IRExpr& index) { + local_get(base_local); + expr(index); + i32_const(4); + op(0x6C); // i32.mul + op(0x6A); // i32.add + } + + void expr(const IRExpr& e) { + bool f = e.kind == IRExpr::Binary ? e.args[0]->type == IRType::F32 : e.type == IRType::F32; + switch (e.kind) { + case IRExpr::Const: if (e.type == IRType::F32) f32_const(e.bits); else i32_const(int32_t(e.bits)); break; + case IRExpr::Local: local_get(e.local); break; + case IRExpr::Load: + address(e.local, *e.args[0]); + op(e.type == IRType::F32 ? 0x2A : 0x28); write_uleb(code, 2); write_uleb(code, 0); + break; + case IRExpr::Binary: { + expr(*e.args[0]); + expr(*e.args[1]); + const std::string& o = e.op; + if (o == "&&") { op(0x71); break; } + if (o == "||") { op(0x72); break; } + if (f) { + if (o == "+") op(0x92); else if (o == "-") op(0x93); else if (o == "*") op(0x94); else if (o == "/") op(0x95); + else if (o == "==") op(0x5B); else if (o == "!=") op(0x5C); else if (o == "<") op(0x5D); + else if (o == ">") op(0x5E); else if (o == "<=") op(0x5F); else if (o == ">=") op(0x60); + } else { + if (o == "+") op(0x6A); else if (o == "-") op(0x6B); else if (o == "*") op(0x6C); else if (o == "/") op(0x6D); + else if (o == "%") op(0x6F); else if (o == "==") op(0x46); else if (o == "!=") op(0x47); + else if (o == "<") op(0x48); else if (o == ">") op(0x4A); else if (o == "<=") op(0x4C); else if (o == ">=") op(0x4E); + } + break; + } + case IRExpr::Unary: + if (e.op == "!") { expr(*e.args[0]); op(0x45); } + else if (e.type == IRType::F32) { expr(*e.args[0]); op(0x8C); } + else { i32_const(0); expr(*e.args[0]); op(0x6B); } + break; + case IRExpr::Convert: + expr(*e.args[0]); + op(e.type == IRType::F32 ? 0xB2 : 0xA8); // f32.convert_i32_s / i32.trunc_f32_s + break; + case IRExpr::Intrinsic: { + const std::string& n = e.op; + if (e.type == IRType::I32 && (n == "min" || n == "max")) { + // select(a, b, a < b) for min; a > b for max. Operands are side-effect free. + expr(*e.args[0]); expr(*e.args[1]); + expr(*e.args[0]); expr(*e.args[1]); + op(n == "min" ? 0x48 : 0x4A); + op(0x1B); + break; + } + for (auto& a : e.args) expr(*a); + if (n == "sqrtf") op(0x91); else if (n == "fabsf") op(0x8B); else if (n == "floorf") op(0x8E); + else if (n == "ceilf") op(0x8D); else if (n == "fminf" || n == "min") op(0x96); else if (n == "fmaxf" || n == "max") op(0x97); + break; + } + } + } + + void stmts(const std::vector& body) { for (auto& s : body) stmt(*s); } + + void stmt(const IRStmt& s) { + switch (s.kind) { + case IRStmt::SetLocal: expr(*s.value); local_set(s.local); break; + case IRStmt::Store: + address(s.local, *s.index); + expr(*s.value); + op(s.type == IRType::F32 ? 0x38 : 0x36); write_uleb(code, 2); write_uleb(code, 0); + break; + case IRStmt::If: + expr(*s.cond); + begin(0x04); + stmts(s.then_body); + if (!s.else_body.empty()) { op(0x05); stmts(s.else_body); } + end(); + break; + case IRStmt::Loop: { + // block $break { loop $top { br_if $break !cond; block $continue { body } step; br $top } } + begin(0x02); + break_depth.push_back(depth); + begin(0x03); + uint32_t top = depth; + expr(*s.cond); + op(0x45); + op(0x0D); write_uleb(code, depth - break_depth.back()); + begin(0x02); + continue_depth.push_back(depth); + stmts(s.body); + continue_depth.pop_back(); + end(); + stmts(s.step); + op(0x0C); write_uleb(code, depth - top); + end(); + break_depth.pop_back(); + end(); + break; + } + case IRStmt::Return: op(0x0F); break; + case IRStmt::Break: op(0x0C); write_uleb(code, depth - break_depth.back()); break; + case IRStmt::Continue: op(0x0C); write_uleb(code, depth - continue_depth.back()); break; + } + } +}; + +void section(std::vector& out, uint8_t id, const std::vector& body) { + out.push_back(id); + write_uleb(out, body.size()); + out.insert(out.end(), body.begin(), body.end()); +} +void name(std::vector& out, const std::string& s) { + write_uleb(out, s.size()); + out.insert(out.end(), s.begin(), s.end()); +} +uint8_t vt(IRType t) { return t == IRType::F32 ? 0x7D : 0x7F; } +} // namespace + +uint32_t fold_constants(IRFunction& fn) { + uint32_t count = 0; + fold_block(fn.body, count); + return count; +} + +std::string print_ir(const IRFunction& fn) { + std::ostringstream o; + o << "kernel " << fn.name << "("; + for (size_t i = 4; i < fn.param_types.size(); i++) o << (i > 4 ? ", " : "") << "%p" << (i - 4) << ": " << tn(fn.param_types[i]); + o << ") {\n"; + for (size_t i = 0; i < fn.local_types.size(); i++) o << " local %" << fn.local_names[i] << ": " << tn(fn.local_types[i]) << "\n"; + print_block(o, fn.body, fn, 1); + o << "}\n"; + return o.str(); +} + +std::vector emit_wasm(const IRFunction& fn) { + std::vector m = {0x00, 'a', 's', 'm', 0x01, 0x00, 0x00, 0x00}; + const size_t user = fn.param_types.size() - 4; + + // Types: 0 = kernel(threadIdx, blockIdx, blockDim, gridDim, params...), 1 = dispatch(grid, block, params...) + std::vector types; + write_uleb(types, 2); + types.push_back(0x60); + write_uleb(types, fn.param_types.size()); + for (IRType t : fn.param_types) types.push_back(vt(t)); + write_uleb(types, 0); + types.push_back(0x60); + write_uleb(types, 2 + user); + types.push_back(0x7F); types.push_back(0x7F); + for (size_t i = 4; i < fn.param_types.size(); i++) types.push_back(vt(fn.param_types[i])); + write_uleb(types, 0); + section(m, 1, types); + + // Import the shared linear memory so every kernel sees the same buffers. + std::vector imports; + write_uleb(imports, 1); + name(imports, "env"); name(imports, "memory"); + imports.push_back(0x02); imports.push_back(0x00); write_uleb(imports, 1); + section(m, 2, imports); + + std::vector funcs; + write_uleb(funcs, 2); write_uleb(funcs, 0); write_uleb(funcs, 1); + section(m, 3, funcs); + + std::vector exports; + write_uleb(exports, 2); + name(exports, fn.name); exports.push_back(0x00); write_uleb(exports, 0); + name(exports, fn.name + "__dispatch"); exports.push_back(0x00); write_uleb(exports, 1); + section(m, 7, exports); + + std::vector code; + write_uleb(code, 2); + { // kernel body + Emitter e; + std::vector body; + write_uleb(body, fn.local_types.size()); + for (IRType t : fn.local_types) { write_uleb(body, 1); body.push_back(vt(t)); } + e.stmts(fn.body); + e.op(0x0B); + body.insert(body.end(), e.code.begin(), e.code.end()); + write_uleb(code, body.size()); + code.insert(code.end(), body.begin(), body.end()); + } + { // dispatch: for b in [0, grid) for t in [0, block) kernel(t, b, block, grid, params...) + Emitter e; + const uint32_t grid = 0, block = 1, b = uint32_t(2 + user), t = b + 1; + std::vector body; + write_uleb(body, 1); write_uleb(body, 2); body.push_back(0x7F); + e.i32_const(0); e.local_set(b); + e.begin(0x02); e.begin(0x03); + e.local_get(b); e.local_get(grid); e.op(0x4F); e.op(0x0D); write_uleb(e.code, 1); // br_if b >= grid (unsigned) + e.i32_const(0); e.local_set(t); + e.begin(0x02); e.begin(0x03); + e.local_get(t); e.local_get(block); e.op(0x4F); e.op(0x0D); write_uleb(e.code, 1); + e.local_get(t); e.local_get(b); e.local_get(block); e.local_get(grid); + for (uint32_t i = 0; i < user; i++) e.local_get(2 + i); + e.op(0x10); write_uleb(e.code, 0); + e.local_get(t); e.i32_const(1); e.op(0x6A); e.local_set(t); + e.op(0x0C); write_uleb(e.code, 0); + e.end(); e.end(); + e.local_get(b); e.i32_const(1); e.op(0x6A); e.local_set(b); + e.op(0x0C); write_uleb(e.code, 0); + e.end(); e.end(); + e.op(0x0B); + body.insert(body.end(), e.code.begin(), e.code.end()); + write_uleb(code, body.size()); + code.insert(code.end(), body.begin(), body.end()); + } + section(m, 10, code); + return m; +} + +CompiledKernel compile(const std::string& source) { + CompiledKernel out; + KernelAST ast; + if (!parse(source, ast, out.error)) return out; + IRFunction fn; + if (!lower(ast, fn, out.error)) return out; + out.folded_constants = fold_constants(fn); + out.name = fn.name; + for (auto& p : ast.params) out.params.push_back({p.type, p.name}); + out.ir_text = print_ir(fn); + out.wasm = emit_wasm(fn); + out.ok = true; + return out; +} + +} // namespace unify::kernel diff --git a/unify/engine/kernel/kernel.h b/unify/engine/kernel/kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..0485d6e0d19a136a7db512430dfab8a541a80753 --- /dev/null +++ b/unify/engine/kernel/kernel.h @@ -0,0 +1,97 @@ +#pragma once +#include +#include +#include +#include + +namespace unify::kernel { + +// ============================================================================ AST +enum class Type : uint8_t { Void, Int, Float, IntPtr, FloatPtr }; +const char* type_name(Type t); + +struct Expr; +using ExprP = std::unique_ptr; +struct Expr { + enum Kind { IntLit, FloatLit, Var, Index, Binary, Unary, Cast, Call } kind; + int line = 0; + int32_t ival = 0; + float fval = 0; + std::string name; // Var / Call name / operator spelling + Type cast_to = Type::Void; + std::vector args; // operands / call arguments / [base, index] +}; + +struct Stmt; +using StmtP = std::unique_ptr; +struct Stmt { + enum Kind { Decl, Assign, If, For, While, Block, Return, Break, Continue } kind; + int line = 0; + Type decl_type = Type::Void; + std::string name; // Decl name; Assign operator ("=", "+=", ...) + ExprP target, value, cond; + StmtP init, step, then_s, else_s, body; + std::vector stmts; +}; + +struct Param { Type type; std::string name; }; +struct KernelAST { std::string name; std::vector params; StmtP body; }; + +// ============================================================================ IR +// Typed, name-resolved, structured IR. Every value is i32 or f32; pointers are i32 byte +// offsets into the shared linear memory. Implicit conversions are explicit nodes here. +enum class IRType : uint8_t { I32, F32 }; + +struct IRExpr; +using IRExprP = std::unique_ptr; +struct IRExpr { + enum Kind { Const, Local, Load, Binary, Unary, Convert, Intrinsic } kind; + IRType type = IRType::I32; + uint32_t bits = 0; // Const payload (i32 value or f32 bits) + uint32_t local = 0; // Local index / Load base pointer local + std::string op; // Binary/Unary/Intrinsic operator + std::vector args; +}; + +struct IRStmt; +using IRStmtP = std::unique_ptr; +struct IRStmt { + enum Kind { SetLocal, Store, If, Loop, Return, Break, Continue } kind; + uint32_t local = 0; // SetLocal target / Store base pointer local + IRType type = IRType::I32; + IRExprP value, index, cond; + std::vector then_body, else_body, body, step; +}; + +struct IRFunction { + std::string name; + std::vector param_types; // builtins (4 x i32) followed by user params + std::vector local_types; // declared locals after params + std::vector local_names; + std::vector body; +}; + +// ============================================================================ API +struct KernelParam { Type type; std::string name; }; + +struct CompiledKernel { + bool ok = false; + std::string error; // "line N: message" on failure + std::string name; + std::vector params; // user-visible parameters (excluding builtins) + std::vector wasm; // binary module: imports env.memory, exports name and name__dispatch + std::string ir_text; // human-readable IR, for inspection and tests + uint32_t folded_constants = 0; // optimisation statistic +}; + +/// Full pipeline: source → AST → IR → optimise → WASM. +CompiledKernel compile(const std::string& source); + +// Individual stages (exposed for tests and tooling). +bool parse(const std::string& source, KernelAST& out, std::string& error); +bool lower(const KernelAST& ast, IRFunction& out, std::string& error); +uint32_t fold_constants(IRFunction& fn); +std::string print_ir(const IRFunction& fn); +std::vector emit_wasm(const IRFunction& fn); + +} // namespace unify::kernel diff --git a/unify/engine/kernel/lower.cpp b/unify/engine/kernel/lower.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ab82905e2f589641e82456360927ce6750ec97c --- /dev/null +++ b/unify/engine/kernel/lower.cpp @@ -0,0 +1,335 @@ +// AST → IR: name resolution, type checking, implicit conversions, control-flow lowering. +#include "kernel.h" +#include +#include + +namespace unify::kernel { + +namespace { +const char* kBuiltins[] = {"threadIdx.x", "blockIdx.x", "blockDim.x", "gridDim.x"}; + +uint32_t fbits(float f) { uint32_t b; std::memcpy(&b, &f, 4); return b; } + +class Lowerer { +public: + std::string err; + + bool run(const KernelAST& ast, IRFunction& fn) { + fn_ = &fn; + fn.name = ast.name; + scopes_.emplace_back(); + for (const char* b : kBuiltins) { declare_param(b, Type::Int); } + for (auto& p : ast.params) { + if (p.type == Type::Void) return fail(0, "parameter '" + p.name + "' cannot be void"); + if (lookup(p.name)) return fail(0, "duplicate parameter '" + p.name + "'"); + declare_param(p.name, p.type); + } + return stmt(*ast.body, fn.body); + } + +private: + struct Sym { uint32_t local; Type type; }; + + bool fail(int line, const std::string& m) { if (err.empty()) err = "line " + std::to_string(line) + ": " + m; return false; } + static IRType ir(Type t) { return t == Type::Float ? IRType::F32 : IRType::I32; } + + void declare_param(const std::string& name, Type t) { + uint32_t idx = uint32_t(fn_->param_types.size()); + fn_->param_types.push_back(ir(t)); + scopes_.back()[name] = {idx, t}; + param_count_++; + } + uint32_t declare_local(const std::string& name, Type t) { + uint32_t idx = param_count_ + uint32_t(fn_->local_types.size()); + fn_->local_types.push_back(ir(t)); + fn_->local_names.push_back(name); + scopes_.back()[name] = {idx, t}; + return idx; + } + const Sym* lookup(const std::string& name) const { + for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) { + auto f = it->find(name); + if (f != it->end()) return &f->second; + } + return nullptr; + } + + static IRExprP convert(IRExprP e, IRType to) { + if (e->type == to) return e; + auto c = std::make_unique(); + c->kind = IRExpr::Convert; + c->type = to; + c->args.push_back(std::move(e)); + return c; + } + static IRExprP konst_i(int32_t v) { auto e = std::make_unique(); e->kind = IRExpr::Const; e->type = IRType::I32; e->bits = uint32_t(v); return e; } + // Normalises a scalar to an i32 truth value (0/1). + static IRExprP truthy(IRExprP e) { + auto c = std::make_unique(); + c->kind = IRExpr::Binary; c->type = IRType::I32; c->op = "!="; + IRExprP zero = std::make_unique(); + zero->kind = IRExpr::Const; zero->type = e->type; zero->bits = 0; + c->args.push_back(std::move(e)); + c->args.push_back(std::move(zero)); + return c; + } + + // Returns the lowered expression and its source-level type. + IRExprP expr(const Expr& e, Type& t) { + switch (e.kind) { + case Expr::IntLit: t = Type::Int; return konst_i(e.ival); + case Expr::FloatLit: { + t = Type::Float; + auto c = std::make_unique(); + c->kind = IRExpr::Const; c->type = IRType::F32; c->bits = fbits(e.fval); + return c; + } + case Expr::Var: { + const Sym* s = lookup(e.name); + if (!s) { fail(e.line, "undeclared identifier '" + e.name + "'"); return nullptr; } + t = s->type; + auto l = std::make_unique(); + l->kind = IRExpr::Local; l->type = ir(s->type); l->local = s->local; + return l; + } + case Expr::Index: { + const Expr& base = *e.args[0]; + if (base.kind != Expr::Var) { fail(e.line, "only named pointers can be indexed"); return nullptr; } + const Sym* s = lookup(base.name); + if (!s) { fail(e.line, "undeclared identifier '" + base.name + "'"); return nullptr; } + if (s->type != Type::IntPtr && s->type != Type::FloatPtr) { fail(e.line, "'" + base.name + "' is not a pointer"); return nullptr; } + Type it; + IRExprP idx = expr(*e.args[1], it); + if (!idx) return nullptr; + if (it != Type::Int) { fail(e.line, "array index must be int"); return nullptr; } + t = s->type == Type::FloatPtr ? Type::Float : Type::Int; + auto l = std::make_unique(); + l->kind = IRExpr::Load; l->type = ir(t); l->local = s->local; + l->args.push_back(std::move(idx)); + return l; + } + case Expr::Cast: { + Type it; + IRExprP x = expr(*e.args[0], it); + if (!x) return nullptr; + if (it == Type::IntPtr || it == Type::FloatPtr) { fail(e.line, "cannot cast a pointer"); return nullptr; } + t = e.cast_to; + return convert(std::move(x), ir(t)); + } + case Expr::Unary: { + Type it; + IRExprP x = expr(*e.args[0], it); + if (!x) return nullptr; + if (it == Type::IntPtr || it == Type::FloatPtr) { fail(e.line, "invalid operand to unary " + e.name); return nullptr; } + auto u = std::make_unique(); + u->kind = IRExpr::Unary; u->op = e.name; + if (e.name == "!") { t = Type::Int; u->type = IRType::I32; u->args.push_back(truthy(std::move(x))); } + else { t = it; u->type = x->type; u->args.push_back(std::move(x)); } + return u; + } + case Expr::Binary: { + Type lt, rt; + IRExprP a = expr(*e.args[0], lt); + IRExprP b = a ? expr(*e.args[1], rt) : nullptr; + if (!a || !b) return nullptr; + if (lt == Type::IntPtr || lt == Type::FloatPtr || rt == Type::IntPtr || rt == Type::FloatPtr) { + fail(e.line, "pointer arithmetic is not supported; index the pointer instead"); + return nullptr; + } + const std::string& op = e.name; + auto bin = std::make_unique(); + bin->kind = IRExpr::Binary; bin->op = op; + if (op == "&&" || op == "||") { + t = Type::Int; bin->type = IRType::I32; + bin->args.push_back(truthy(std::move(a))); + bin->args.push_back(truthy(std::move(b))); + return bin; + } + // Usual arithmetic conversion: int op float -> float. + IRType operand = (lt == Type::Float || rt == Type::Float) ? IRType::F32 : IRType::I32; + if (op == "%" && operand == IRType::F32) { fail(e.line, "'%' requires int operands"); return nullptr; } + bin->args.push_back(convert(std::move(a), operand)); + bin->args.push_back(convert(std::move(b), operand)); + bool cmp = op == "<" || op == "<=" || op == ">" || op == ">=" || op == "==" || op == "!="; + bin->type = cmp ? IRType::I32 : operand; + t = cmp ? Type::Int : (operand == IRType::F32 ? Type::Float : Type::Int); + return bin; + } + case Expr::Call: { + static const std::map intrinsics = { + {"sqrtf", 1}, {"fabsf", 1}, {"floorf", 1}, {"ceilf", 1}, {"fminf", 2}, {"fmaxf", 2}, {"min", 2}, {"max", 2}}; + auto it = intrinsics.find(e.name); + if (it == intrinsics.end()) { fail(e.line, "unknown function '" + e.name + "'"); return nullptr; } + if (int(e.args.size()) != it->second) { fail(e.line, "'" + e.name + "' takes " + std::to_string(it->second) + " argument(s)"); return nullptr; } + auto call = std::make_unique(); + call->kind = IRExpr::Intrinsic; call->op = e.name; + bool integer = e.name == "min" || e.name == "max"; + IRType want = IRType::F32; + if (integer) { + // min/max follow their operands' type. + want = IRType::I32; + for (auto& a : e.args) { Type at; IRExprP x = expr(*a, at); if (!x) return nullptr; if (at == Type::Float) want = IRType::F32; } + } + for (auto& a : e.args) { + Type at; + IRExprP x = expr(*a, at); + if (!x) return nullptr; + call->args.push_back(convert(std::move(x), want)); + } + call->type = want; + t = want == IRType::F32 ? Type::Float : Type::Int; + return call; + } + } + return nullptr; + } + + bool stmt(const Stmt& s, std::vector& out) { + switch (s.kind) { + case Stmt::Block: { + scopes_.emplace_back(); + for (auto& x : s.stmts) if (!stmt(*x, out)) return false; + scopes_.pop_back(); + return true; + } + case Stmt::Decl: { + if (s.decl_type == Type::IntPtr || s.decl_type == Type::FloatPtr) return fail(s.line, "local pointers are not supported"); + if (scopes_.back().count(s.name)) return fail(s.line, "redeclaration of '" + s.name + "'"); + IRExprP init; + if (s.value) { + Type vt; + init = expr(*s.value, vt); + if (!init) return false; + init = convert(std::move(init), ir(s.decl_type)); + } else { + init = konst_i(0); + init->type = ir(s.decl_type); // zero-initialise: 0 bits are 0 for both i32 and f32 + } + uint32_t idx = declare_local(s.name, s.decl_type); + auto st = std::make_unique(); + st->kind = IRStmt::SetLocal; st->local = idx; st->type = ir(s.decl_type); st->value = std::move(init); + out.push_back(std::move(st)); + return true; + } + case Stmt::Assign: { + Type vt; + IRExprP value = expr(*s.value, vt); + if (!value) return false; + const Expr& tgt = *s.target; + std::string op = s.name; + if (tgt.kind == Expr::Var) { + const Sym* sym = lookup(tgt.name); + if (!sym) return fail(s.line, "undeclared identifier '" + tgt.name + "'"); + if (sym->local < 4) return fail(s.line, "cannot assign to builtin '" + tgt.name + "'"); + if (sym->type == Type::IntPtr || sym->type == Type::FloatPtr) return fail(s.line, "cannot reassign a pointer parameter"); + IRType ty = ir(sym->type); + if (op != "=") { + Type dummy; + IRExprP cur = expr(tgt, dummy); + auto bin = std::make_unique(); + bin->kind = IRExpr::Binary; bin->op = op.substr(0, 1); + IRType operand = (ty == IRType::F32 || vt == Type::Float) ? IRType::F32 : IRType::I32; + bin->type = operand; + bin->args.push_back(convert(std::move(cur), operand)); + bin->args.push_back(convert(std::move(value), operand)); + value = std::move(bin); + } + auto st = std::make_unique(); + st->kind = IRStmt::SetLocal; st->local = sym->local; st->type = ty; st->value = convert(std::move(value), ty); + out.push_back(std::move(st)); + return true; + } + if (tgt.kind == Expr::Index) { + Type et; + IRExprP load = expr(tgt, et); // validates pointer + index + if (!load) return false; + IRType ty = load->type; + uint32_t base = load->local; + if (op != "=") { + auto bin = std::make_unique(); + bin->kind = IRExpr::Binary; bin->op = op.substr(0, 1); + IRType operand = (ty == IRType::F32 || vt == Type::Float) ? IRType::F32 : IRType::I32; + bin->type = operand; + Type dummy; + IRExprP cur = expr(tgt, dummy); + bin->args.push_back(convert(std::move(cur), operand)); + bin->args.push_back(convert(std::move(value), operand)); + value = std::move(bin); + } + auto st = std::make_unique(); + st->kind = IRStmt::Store; st->local = base; st->type = ty; + st->index = std::move(load->args[0]); + st->value = convert(std::move(value), ty); + out.push_back(std::move(st)); + return true; + } + return fail(s.line, "left side of assignment is not assignable"); + } + case Stmt::If: { + Type ct; + IRExprP c = expr(*s.cond, ct); + if (!c) return false; + auto st = std::make_unique(); + st->kind = IRStmt::If; + st->cond = c->type == IRType::I32 ? std::move(c) : truthy(std::move(c)); + scopes_.emplace_back(); + if (!stmt(*s.then_s, st->then_body)) return false; + scopes_.pop_back(); + if (s.else_s) { + scopes_.emplace_back(); + if (!stmt(*s.else_s, st->else_body)) return false; + scopes_.pop_back(); + } + out.push_back(std::move(st)); + return true; + } + case Stmt::For: + case Stmt::While: { + scopes_.emplace_back(); + if (s.init && !stmt(*s.init, out)) return false; + auto st = std::make_unique(); + st->kind = IRStmt::Loop; + if (s.cond) { + Type ct; + IRExprP c = expr(*s.cond, ct); + if (!c) return false; + st->cond = c->type == IRType::I32 ? std::move(c) : truthy(std::move(c)); + } else { + st->cond = konst_i(1); + } + loop_depth_++; + if (!stmt(*s.body, st->body)) return false; + loop_depth_--; + if (s.step && !stmt(*s.step, st->step)) return false; + scopes_.pop_back(); + out.push_back(std::move(st)); + return true; + } + case Stmt::Return: { auto st = std::make_unique(); st->kind = IRStmt::Return; out.push_back(std::move(st)); return true; } + case Stmt::Break: + case Stmt::Continue: { + if (loop_depth_ == 0) return fail(s.line, std::string(s.kind == Stmt::Break ? "break" : "continue") + " outside a loop"); + auto st = std::make_unique(); + st->kind = s.kind == Stmt::Break ? IRStmt::Break : IRStmt::Continue; + out.push_back(std::move(st)); + return true; + } + } + return fail(s.line, "unsupported statement"); + } + + IRFunction* fn_ = nullptr; + std::vector> scopes_; + uint32_t param_count_ = 0; + int loop_depth_ = 0; +}; +} // namespace + +bool lower(const KernelAST& ast, IRFunction& out, std::string& error) { + out = IRFunction{}; + Lowerer l; + if (!l.run(ast, out)) { error = l.err; return false; } + return true; +} + +} // namespace unify::kernel diff --git a/unify/engine/kernel/parser.cpp b/unify/engine/kernel/parser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36fdb8f71adf0423f3c855074b7711ef1b8cdd9f --- /dev/null +++ b/unify/engine/kernel/parser.cpp @@ -0,0 +1,339 @@ +// Kernel language front end: lexer + recursive-descent parser → AST. +// +// __global__ void vadd(const float* A, const float* B, float* C, int n) { +// int i = blockIdx.x * blockDim.x + threadIdx.x; +// if (i < n) C[i] = A[i] + B[i]; +// } +#include "kernel.h" +#include +#include + +namespace unify::kernel { + +const char* type_name(Type t) { + switch (t) { + case Type::Void: return "void"; + case Type::Int: return "int"; + case Type::Float: return "float"; + case Type::IntPtr: return "int*"; + case Type::FloatPtr: return "float*"; + } + return "?"; +} + +namespace { +struct Token { + enum Kind { Ident, Int, Float, Punct, End } kind; + std::string text; + int line; +}; + +bool lex(const std::string& s, std::vector& out, std::string& err) { + int line = 1; + size_t i = 0; + static const char* two[] = {"<=", ">=", "==", "!=", "&&", "||", "+=", "-=", "*=", "/=", "++", "--"}; + while (i < s.size()) { + char c = s[i]; + if (c == '\n') { line++; i++; continue; } + if (std::isspace(uint8_t(c))) { i++; continue; } + if (c == '/' && i + 1 < s.size() && s[i + 1] == '/') { while (i < s.size() && s[i] != '\n') i++; continue; } + if (c == '/' && i + 1 < s.size() && s[i + 1] == '*') { + i += 2; + while (i + 1 < s.size() && !(s[i] == '*' && s[i + 1] == '/')) { if (s[i] == '\n') line++; i++; } + i += 2; + continue; + } + if (std::isalpha(uint8_t(c)) || c == '_') { + size_t j = i; + while (j < s.size() && (std::isalnum(uint8_t(s[j])) || s[j] == '_')) j++; + out.push_back({Token::Ident, s.substr(i, j - i), line}); + i = j; + continue; + } + if (std::isdigit(uint8_t(c)) || (c == '.' && i + 1 < s.size() && std::isdigit(uint8_t(s[i + 1])))) { + size_t j = i; + bool is_float = false; + while (j < s.size() && (std::isdigit(uint8_t(s[j])) || s[j] == '.' || s[j] == 'e' || s[j] == 'E' || + ((s[j] == '-' || s[j] == '+') && (s[j - 1] == 'e' || s[j - 1] == 'E')))) { + if (s[j] == '.' || s[j] == 'e' || s[j] == 'E') is_float = true; + j++; + } + std::string num = s.substr(i, j - i); + if (j < s.size() && (s[j] == 'f' || s[j] == 'F')) { is_float = true; j++; } + out.push_back({is_float ? Token::Float : Token::Int, num, line}); + i = j; + continue; + } + bool matched = false; + for (const char* t : two) + if (s.compare(i, 2, t) == 0) { out.push_back({Token::Punct, t, line}); i += 2; matched = true; break; } + if (matched) continue; + if (std::string("+-*/%<>=!(){}[];,.&").find(c) != std::string::npos) { + out.push_back({Token::Punct, std::string(1, c), line}); + i++; + continue; + } + err = "line " + std::to_string(line) + ": unexpected character '" + std::string(1, c) + "'"; + return false; + } + out.push_back({Token::End, "", line}); + return true; +} + +class Parser { +public: + explicit Parser(std::vector t) : t_(std::move(t)) {} + std::string err; + + bool kernel(KernelAST& k) { + while (peek("__global__") || peek("extern") || peek("\"C\"")) next(); + if (!expect("void")) return false; + if (!ident(k.name)) return false; + if (!expect("(")) return false; + if (!peek(")")) { + do { + Param p; + if (!type(p.type)) return false; + if (!ident(p.name)) return false; + k.params.push_back(p); + } while (accept(",")); + } + if (!expect(")")) return false; + k.body = block(); + if (!k.body) return false; + if (t_[pos_].kind != Token::End) return fail("unexpected tokens after kernel body"); + return true; + } + +private: + const Token& cur() const { return t_[pos_]; } + void next() { if (t_[pos_].kind != Token::End) pos_++; } + bool peek(const char* s) const { return cur().text == s && cur().kind != Token::End; } + bool accept(const char* s) { if (peek(s)) { next(); return true; } return false; } + bool fail(const std::string& m) { if (err.empty()) err = "line " + std::to_string(cur().line) + ": " + m; return false; } + bool expect(const char* s) { if (accept(s)) return true; return fail(std::string("expected '") + s + "' but found '" + cur().text + "'"); } + bool ident(std::string& out) { + if (cur().kind != Token::Ident) return fail("expected identifier but found '" + cur().text + "'"); + out = cur().text; + next(); + return true; + } + bool is_type_start() const { return peek("int") || peek("float") || peek("const") || peek("unsigned"); } + bool type(Type& t) { + accept("const"); + if (accept("int")) t = Type::Int; + else if (accept("float")) t = Type::Float; + else return fail("expected a type (int or float) but found '" + cur().text + "'"); + if (accept("*")) t = t == Type::Int ? Type::IntPtr : Type::FloatPtr; + accept("const"); + accept("__restrict__"); + return true; + } + + StmtP block() { + auto s = std::make_unique(); + s->kind = Stmt::Block; + s->line = cur().line; + if (!expect("{")) return nullptr; + while (!peek("}")) { + if (cur().kind == Token::End) { fail("unterminated block"); return nullptr; } + StmtP st = statement(); + if (!st) return nullptr; + s->stmts.push_back(std::move(st)); + } + next(); + return s; + } + + StmtP simple_statement() { // declaration or assignment, no trailing ';' + auto s = std::make_unique(); + s->line = cur().line; + if (is_type_start()) { + s->kind = Stmt::Decl; + if (!type(s->decl_type) || !ident(s->name)) return nullptr; + if (accept("=")) { s->value = expr(); if (!s->value) return nullptr; } + return s; + } + s->kind = Stmt::Assign; + s->target = postfix(); + if (!s->target) return nullptr; + if (accept("++") || accept("--")) { + std::string op = t_[pos_ - 1].text == "++" ? "+=" : "-="; + s->name = op; + auto one = std::make_unique(); + one->kind = Expr::IntLit; one->ival = 1; one->line = s->line; + s->value = std::move(one); + return s; + } + for (const char* op : {"=", "+=", "-=", "*=", "/="}) + if (accept(op)) { s->name = op; s->value = expr(); return s->value ? std::move(s) : nullptr; } + fail("expected an assignment"); + return nullptr; + } + + StmtP statement() { + int line = cur().line; + if (peek("{")) return block(); + if (accept("if")) { + auto s = std::make_unique(); + s->kind = Stmt::If; s->line = line; + if (!expect("(")) return nullptr; + s->cond = expr(); + if (!s->cond || !expect(")")) return nullptr; + s->then_s = statement(); + if (!s->then_s) return nullptr; + if (accept("else")) { s->else_s = statement(); if (!s->else_s) return nullptr; } + return s; + } + if (accept("for")) { + auto s = std::make_unique(); + s->kind = Stmt::For; s->line = line; + if (!expect("(")) return nullptr; + if (!peek(";")) { s->init = simple_statement(); if (!s->init) return nullptr; } + if (!expect(";")) return nullptr; + if (!peek(";")) { s->cond = expr(); if (!s->cond) return nullptr; } + if (!expect(";")) return nullptr; + if (!peek(")")) { s->step = simple_statement(); if (!s->step) return nullptr; } + if (!expect(")")) return nullptr; + s->body = statement(); + return s->body ? std::move(s) : nullptr; + } + if (accept("while")) { + auto s = std::make_unique(); + s->kind = Stmt::While; s->line = line; + if (!expect("(")) return nullptr; + s->cond = expr(); + if (!s->cond || !expect(")")) return nullptr; + s->body = statement(); + return s->body ? std::move(s) : nullptr; + } + for (auto [kw, kind] : {std::pair{"return", Stmt::Return}, {"break", Stmt::Break}, {"continue", Stmt::Continue}}) { + if (accept(kw)) { + auto s = std::make_unique(); + s->kind = kind; s->line = line; + return expect(";") ? std::move(s) : nullptr; + } + } + StmtP s = simple_statement(); + if (!s || !expect(";")) return nullptr; + return s; + } + + // Precedence climbing: || && ==,!= <,<=,>,>= +,- *,/,% + ExprP expr() { return binary(0); } + int prec(const std::string& op) const { + if (op == "||") return 1; + if (op == "&&") return 2; + if (op == "==" || op == "!=") return 3; + if (op == "<" || op == "<=" || op == ">" || op == ">=") return 4; + if (op == "+" || op == "-") return 5; + if (op == "*" || op == "/" || op == "%") return 6; + return -1; + } + ExprP binary(int min_prec) { + ExprP lhs = unary(); + if (!lhs) return nullptr; + while (cur().kind == Token::Punct && prec(cur().text) > min_prec) { + std::string op = cur().text; + int line = cur().line; + next(); + ExprP rhs = binary(prec(op)); + if (!rhs) return nullptr; + auto e = std::make_unique(); + e->kind = Expr::Binary; e->name = op; e->line = line; + e->args.push_back(std::move(lhs)); + e->args.push_back(std::move(rhs)); + lhs = std::move(e); + } + return lhs; + } + ExprP unary() { + int line = cur().line; + if (accept("-") || accept("!")) { + auto e = std::make_unique(); + e->kind = Expr::Unary; e->name = t_[pos_ - 1].text; e->line = line; + ExprP x = unary(); + if (!x) return nullptr; + e->args.push_back(std::move(x)); + return e; + } + // Cast: "(" type ")" unary + if (peek("(") && (t_[pos_ + 1].text == "int" || t_[pos_ + 1].text == "float")) { + next(); + Type t; + if (!type(t) || !expect(")")) return nullptr; + auto e = std::make_unique(); + e->kind = Expr::Cast; e->cast_to = t; e->line = line; + ExprP x = unary(); + if (!x) return nullptr; + e->args.push_back(std::move(x)); + return e; + } + return postfix(); + } + ExprP postfix() { + ExprP e = primary(); + if (!e) return nullptr; + while (true) { + int line = cur().line; + if (accept("[")) { + auto ix = std::make_unique(); + ix->kind = Expr::Index; ix->line = line; + ix->args.push_back(std::move(e)); + ExprP idx = expr(); + if (!idx || !expect("]")) return nullptr; + ix->args.push_back(std::move(idx)); + e = std::move(ix); + } else if (accept(".")) { + // Only builtin member access (threadIdx.x etc.) exists in this language. + std::string field; + if (!ident(field)) return nullptr; + if (e->kind != Expr::Var) { fail("member access is only valid on builtins"); return nullptr; } + e->name += "." + field; + } else { + return e; + } + } + } + ExprP primary() { + auto e = std::make_unique(); + e->line = cur().line; + if (cur().kind == Token::Int) { e->kind = Expr::IntLit; e->ival = int32_t(std::strtol(cur().text.c_str(), nullptr, 0)); next(); return e; } + if (cur().kind == Token::Float) { e->kind = Expr::FloatLit; e->fval = std::strtof(cur().text.c_str(), nullptr); next(); return e; } + if (cur().kind == Token::Ident) { + e->name = cur().text; + next(); + if (accept("(")) { + e->kind = Expr::Call; + if (!peek(")")) { + do { ExprP a = expr(); if (!a) return nullptr; e->args.push_back(std::move(a)); } while (accept(",")); + } + if (!expect(")")) return nullptr; + return e; + } + e->kind = Expr::Var; + return e; + } + if (accept("(")) { + ExprP inner = expr(); + if (!inner || !expect(")")) return nullptr; + return inner; + } + fail("expected an expression but found '" + cur().text + "'"); + return nullptr; + } + + std::vector t_; + size_t pos_ = 0; +}; +} // namespace + +bool parse(const std::string& source, KernelAST& out, std::string& error) { + std::vector tokens; + if (!lex(source, tokens, error)) return false; + Parser p(std::move(tokens)); + if (!p.kernel(out)) { error = p.err; return false; } + return true; +} + +} // namespace unify::kernel diff --git a/unify/engine/memory/memory.cpp b/unify/engine/memory/memory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c251b3e031e50a985b70631d08972692be4f48d --- /dev/null +++ b/unify/engine/memory/memory.cpp @@ -0,0 +1,29 @@ +#include "memory.h" +#include + +namespace unify { +std::atomic HeapStats::allocations{0}; +std::atomic HeapStats::bytes{0}; +} // namespace unify + +#ifndef UNIFY_NO_GLOBAL_NEW +// Global allocation counting. Cheap (one relaxed atomic add) and always on, so the +// "no per-tick heap allocation" property can be measured in any build. +void* operator new(size_t size) { + unify::HeapStats::allocations.fetch_add(1, std::memory_order_relaxed); + unify::HeapStats::bytes.fetch_add(size, std::memory_order_relaxed); + if (void* p = std::malloc(size ? size : 1)) return p; + throw std::bad_alloc(); +} +void* operator new[](size_t size) { return operator new(size); } +void* operator new(size_t size, const std::nothrow_t&) noexcept { + unify::HeapStats::allocations.fetch_add(1, std::memory_order_relaxed); + unify::HeapStats::bytes.fetch_add(size, std::memory_order_relaxed); + return std::malloc(size ? size : 1); +} +void* operator new[](size_t size, const std::nothrow_t& t) noexcept { return operator new(size, t); } +void operator delete(void* p) noexcept { std::free(p); } +void operator delete[](void* p) noexcept { std::free(p); } +void operator delete(void* p, size_t) noexcept { std::free(p); } +void operator delete[](void* p, size_t) noexcept { std::free(p); } +#endif // UNIFY_NO_GLOBAL_NEW (hosts such as Unreal own operator new; counting is then disabled) diff --git a/unify/engine/memory/memory.h b/unify/engine/memory/memory.h new file mode 100644 index 0000000000000000000000000000000000000000..d718f47328962213a0ae289b8b06daafdbf226bc --- /dev/null +++ b/unify/engine/memory/memory.h @@ -0,0 +1,240 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace unify { + +inline size_t align_up(size_t v, size_t a) { return (v + a - 1) & ~(a - 1); } + +/// Process-wide count of global operator new calls. Lets tests assert that the +/// steady-state simulation tick performs no heap allocation. +struct HeapStats { + static std::atomic allocations; + static std::atomic bytes; +}; + +// --------------------------------------------------------------------------------------- +/// Linear per-frame scratch memory. Reset once per frame; allocation is a pointer bump. +/// Overflow is a hard failure reported via nullptr + counter, never a silent heap fallback. +class FrameAllocator { +public: + explicit FrameAllocator(size_t capacity) : buffer_(capacity) {} + void* allocate(size_t size, size_t align = alignof(std::max_align_t)) { + // Align the address, not the offset: the buffer itself is only malloc-aligned. + uintptr_t base = reinterpret_cast(buffer_.data()); + size_t start = size_t(align_up(base + offset_, align) - base); + if (start + size > buffer_.size()) { overflows_++; return nullptr; } + offset_ = start + size; + if (offset_ > high_water_) high_water_ = offset_; + return buffer_.data() + start; + } + template T* alloc_array(size_t n) { + void* p = allocate(sizeof(T) * n, alignof(T)); + return p ? new (p) T[n]() : nullptr; + } + void reset() { offset_ = 0; } + size_t used() const { return offset_; } + size_t capacity() const { return buffer_.size(); } + size_t high_water() const { return high_water_; } + uint64_t overflows() const { return overflows_; } +private: + std::vector buffer_; + size_t offset_ = 0, high_water_ = 0; + uint64_t overflows_ = 0; +}; + +// --------------------------------------------------------------------------------------- +/// Fixed-size block allocator over pre-reserved pages; O(1) alloc/free via intrusive free list. +class PoolAllocator { +public: + PoolAllocator(size_t block_size, size_t blocks_per_page) + : block_(align_up(std::max(block_size, sizeof(void*)), alignof(std::max_align_t))), per_page_(blocks_per_page) {} + ~PoolAllocator() { for (auto* p : pages_) ::operator delete(p); } + PoolAllocator(const PoolAllocator&) = delete; + PoolAllocator& operator=(const PoolAllocator&) = delete; + + void* allocate() { + if (!free_) grow(); + void* p = free_; + free_ = *static_cast(free_); + in_use_++; + return p; + } + void free(void* p) { + if (!p) return; + *static_cast(p) = free_; + free_ = p; + in_use_--; + } + size_t in_use() const { return in_use_; } + size_t capacity() const { return pages_.size() * per_page_; } + size_t block_size() const { return block_; } + void reserve_blocks(size_t n) { while (capacity() < n) grow(); } +private: + void grow() { + auto* page = static_cast(::operator new(block_ * per_page_)); + pages_.push_back(page); + for (size_t i = per_page_; i-- > 0;) { + void* b = page + i * block_; + *static_cast(b) = free_; + free_ = b; + } + } + size_t block_, per_page_; + std::vector pages_; + void* free_ = nullptr; + size_t in_use_ = 0; +}; + +/// Typed object pool on top of PoolAllocator. Constructs in place; destroy() runs the destructor. +template +class ObjectPool { +public: + explicit ObjectPool(size_t per_page = 256) : pool_(sizeof(T), per_page) {} + template T* create(Args&&... args) { return new (pool_.allocate()) T(std::forward(args)...); } + void destroy(T* obj) { if (obj) { obj->~T(); pool_.free(obj); } } + size_t live() const { return pool_.in_use(); } + void reserve(size_t n) { pool_.reserve_blocks(n); } +private: + PoolAllocator pool_; +}; + +/// STL allocator over a per-type PoolAllocator. Node-based containers (std::map contacts) +/// recycle nodes through the pool instead of hitting the heap on every insert/erase. +template +class PoolStdAllocator { +public: + using value_type = T; + PoolStdAllocator() noexcept = default; + template PoolStdAllocator(const PoolStdAllocator&) noexcept {} + T* allocate(size_t n) { + if (n == 1) return static_cast(pool().allocate()); + return static_cast(::operator new(n * sizeof(T))); + } + void deallocate(T* p, size_t n) noexcept { + if (n == 1) pool().free(p); + else ::operator delete(p); + } + static PoolAllocator& pool() { static PoolAllocator p(sizeof(T), 512); return p; } + template bool operator==(const PoolStdAllocator&) const noexcept { return true; } + template bool operator!=(const PoolStdAllocator&) const noexcept { return false; } +}; + +// --------------------------------------------------------------------------------------- +/// Accounts asset memory per category against a budget. Asset loaders allocate through it +/// so leaks after scene unload are observable (bytes return to baseline). +class AssetAllocator { +public: + explicit AssetAllocator(size_t budget) : budget_(budget) {} + uint8_t* allocate(size_t bytes, const char* category) { + if (used_ + bytes > budget_) { failures_++; return nullptr; } + auto* p = static_cast(::operator new(bytes, std::nothrow)); + if (!p) { failures_++; return nullptr; } + used_ += bytes; + by_category_[category] += bytes; + sizes_[p] = {bytes, category}; + return p; + } + void free(uint8_t* p) { + auto it = sizes_.find(p); + if (it == sizes_.end()) return; + used_ -= it->second.first; + by_category_[it->second.second] -= it->second.first; + sizes_.erase(it); + ::operator delete(p); + } + size_t used() const { return used_; } + size_t budget() const { return budget_; } + uint64_t failures() const { return failures_; } + size_t used_by(const std::string& category) const { + auto it = by_category_.find(category); + return it == by_category_.end() ? 0 : it->second; + } + size_t live_allocations() const { return sizes_.size(); } +private: + size_t budget_, used_ = 0; + uint64_t failures_ = 0; + std::map by_category_; + std::map> sizes_; +}; + +// --------------------------------------------------------------------------------------- +/// Sub-allocates ranges of an externally owned linear memory (e.g. a WASM instance's memory). +/// First-fit over an ordered free list with coalescing. Offsets, not pointers, are returned, +/// because the backing memory may grow and move. +class BufferAllocator { +public: + explicit BufferAllocator(uint32_t base = 0, uint32_t size = 0) { reset(base, size); } + void reset(uint32_t base, uint32_t size) { + free_.clear(); + used_.clear(); + if (size) free_[base] = size; + base_ = base; + end_ = base + size; + } + /// Extends the managed range (after the backing memory grew). + void extend(uint32_t new_end) { + if (new_end <= end_) return; + insert_free(end_, new_end - end_); + end_ = new_end; + } + static constexpr uint32_t kFail = 0xFFFFFFFFu; + uint32_t allocate(uint32_t size, uint32_t align = 16) { + if (size == 0) size = 1; + for (auto it = free_.begin(); it != free_.end(); ++it) { + uint32_t start = uint32_t(align_up(it->first, align)); + uint32_t pad = start - it->first; + if (it->second < pad + size) continue; + uint32_t block_start = it->first, block_size = it->second; + free_.erase(it); + if (pad) free_[block_start] = pad; + uint32_t tail = block_size - pad - size; + if (tail) free_[start + size] = tail; + used_[start] = size; + return start; + } + return kFail; + } + bool free(uint32_t offset) { + auto it = used_.find(offset); + if (it == used_.end()) return false; + uint32_t size = it->second; + used_.erase(it); + insert_free(offset, size); + return true; + } + uint32_t size_of(uint32_t offset) const { auto it = used_.find(offset); return it == used_.end() ? 0 : it->second; } + size_t live() const { return used_.size(); } + uint32_t bytes_used() const { uint32_t n = 0; for (auto& kv : used_) n += kv.second; return n; } + uint32_t largest_free() const { uint32_t m = 0; for (auto& kv : free_) m = std::max(m, kv.second); return m; } + const std::map& used_ranges() const { return used_; } + void restore(const std::map& used, uint32_t base, uint32_t end) { + reset(base, end - base); + free_.clear(); + used_ = used; + uint32_t cursor = base; + for (auto& kv : used_) { if (kv.first > cursor) free_[cursor] = kv.first - cursor; cursor = kv.first + kv.second; } + if (cursor < end) free_[cursor] = end - cursor; + } +private: + void insert_free(uint32_t offset, uint32_t size) { + auto next = free_.lower_bound(offset); + if (next != free_.end() && offset + size == next->first) { size += next->second; next = free_.erase(next); } + if (next != free_.begin()) { + auto prev = std::prev(next); + if (prev->first + prev->second == offset) { prev->second += size; return; } + } + free_[offset] = size; + } + std::map free_, used_; + uint32_t base_ = 0, end_ = 0; +}; + +} // namespace unify diff --git a/unify/engine/net/rollback.cpp b/unify/engine/net/rollback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eeeaa2b8935497ee9f44cd1aafdf4ffaa21579e4 --- /dev/null +++ b/unify/engine/net/rollback.cpp @@ -0,0 +1,45 @@ +#include "rollback.h" +#include "../runtime/engine.h" + +namespace unify { + +void RollbackBuffer::advance(Engine& engine) { + uint64_t tick = engine.sim_clock().tick; + if (tick % interval_ == 0) snaps_.push_back({tick, engine.save_state(false)}); + engine.tick(); + log_.push_back(engine.input().frame()); + // Bound history: drop snapshots (and the input they cover) older than the window. + while (!snaps_.empty() && tick - snaps_.front().tick > max_ticks_ && snaps_.size() > 1) snaps_.pop_front(); + while (!log_.empty() && !snaps_.empty() && log_.front().tick < snaps_.front().tick) log_.pop_front(); +} + +bool RollbackBuffer::rewind_and_resimulate(Engine& engine, uint64_t tick, std::string& error) { + uint64_t now = engine.sim_clock().tick; + const Snap* base = nullptr; + for (const Snap& s : snaps_) if (s.tick <= tick) base = &s; + if (!base) { error = "tick is older than the rollback window"; return false; } + if (!engine.load_state(base->state, error)) return false; + for (const InputFrame& f : log_) { + if (f.tick < base->tick) continue; + if (f.tick >= now) break; + if (f.tick % interval_ == 0) { // refresh snapshots along the corrected timeline + for (Snap& s : snaps_) if (s.tick == f.tick) s.state = engine.save_state(false); + } + engine.replay_tick(f); + resimulated_++; + } + return engine.sim_clock().tick == now || (error = "resimulation ended at the wrong tick", false); +} + +bool RollbackBuffer::correct(Engine& engine, uint64_t tick, const InputFrame& frame, std::string& error) { + for (InputFrame& f : log_) { + if (f.tick != tick) continue; + f = frame; + f.tick = tick; + return rewind_and_resimulate(engine, tick, error); + } + error = "no recorded input for that tick"; + return false; +} + +} // namespace unify diff --git a/unify/engine/net/rollback.h b/unify/engine/net/rollback.h new file mode 100644 index 0000000000000000000000000000000000000000..08d89379fd512707a52bb53a6e2c500b5eac1d3f --- /dev/null +++ b/unify/engine/net/rollback.h @@ -0,0 +1,41 @@ +#pragma once +#include +#include +#include +#include +#include "../input/input.h" + +namespace unify { +class Engine; + +/// Networking-ready state model: periodic snapshots + the exact per-tick input log. +/// +/// Because a UNIFY simulation is a pure function of (state, input frame), a peer that learns +/// late that the input for some past tick was different can rewind to the nearest snapshot at +/// or before that tick, substitute the corrected frame, and re-simulate to the present. This is +/// the core of rollback netcode; lockstep peers instead compare state_hash() per tick. +class RollbackBuffer { +public: + explicit RollbackBuffer(uint32_t snapshot_interval = 10, uint32_t max_history_ticks = 600) + : interval_(snapshot_interval), max_ticks_(max_history_ticks) {} + + /// Runs one live tick through the engine and records it (snapshotting every interval). + void advance(Engine& engine); + /// Replaces the input for `tick` and re-simulates up to the current tick. + bool correct(Engine& engine, uint64_t tick, const InputFrame& frame, std::string& error); + /// Re-simulates from the snapshot at or before `tick` using the recorded frames. + bool rewind_and_resimulate(Engine& engine, uint64_t tick, std::string& error); + + size_t snapshots() const { return snaps_.size(); } + const std::deque& log() const { return log_; } + uint64_t resimulated_ticks() const { return resimulated_; } + +private: + struct Snap { uint64_t tick; std::vector state; }; + uint32_t interval_, max_ticks_; + std::deque snaps_; + std::deque log_; // log_[i].tick is consecutive + uint64_t resimulated_ = 0; +}; + +} // namespace unify diff --git a/unify/engine/physics/physics.h b/unify/engine/physics/physics.h new file mode 100644 index 0000000000000000000000000000000000000000..bdab1f1cd0392cc9f2bf3f3260f3debe52e9745b --- /dev/null +++ b/unify/engine/physics/physics.h @@ -0,0 +1,213 @@ +#pragma once +#include +#include +#include +#include +#include "../core/math.h" +#include "../core/handle.h" +#include "../memory/memory.h" + +namespace unify { +class BinaryWriter; +class BinaryReader; + +namespace phys { +constexpr float kLinearSlop = 0.005f; // allowed penetration (m); keeps contacts warm +constexpr float kAngularSlop = 2.0f / 180.0f * 3.14159265f; +constexpr float kPolygonRadius = 2.0f * kLinearSlop; +constexpr float kMaxLinearCorrection = 0.2f; +constexpr float kBaumgarte = 0.2f; +constexpr float kVelocityThreshold = 1.0f; // below this closing speed, no bounce +constexpr float kTimeToSleep = 0.5f; +constexpr float kLinearSleepTolerance = 0.01f; +constexpr float kAngularSleepTolerance = 2.0f / 180.0f * 3.14159265f; +constexpr int kMaxPolygonVertices = 8; +constexpr float kMaxTranslation = 50.0f; // per step clamp against numeric explosions +} // namespace phys + +enum class ShapeType : uint8_t { Circle, AABB, Box, Polygon }; +enum class BodyType : uint8_t { Static, Kinematic, Dynamic }; + +struct Shape { + ShapeType type = ShapeType::Circle; + float radius = 0.5f; // circle radius; polygon skin (kPolygonRadius) + int count = 0; // polygon vertex count + Vec2 vertices[phys::kMaxPolygonVertices]; // body-local, CCW, centroid at origin + Vec2 normals[phys::kMaxPolygonVertices]; + + static Shape circle(float radius); + static Shape aabb(float half_w, float half_h); // axis-aligned: body rotation is locked + static Shape box(float half_w, float half_h); // oriented box: rotates freely + /// Convex hull of the given points (≤ 8), recentred on its centroid. Returns the offset + /// that was subtracted so callers can shift the body position to keep world placement. + static Shape polygon(const Vec2* points, int n, Vec2* centroid_out = nullptr); + float area() const; + float inertia_per_mass() const; // rotational inertia about the centroid divided by mass + AABB bounds(Vec2 position, const Rot& rot) const; + float max_extent() const; // distance from centroid to furthest point (for CCD bounds) + float min_extent() const; // smallest half-width (for "fast body" detection) +}; + +struct BodyDef { + BodyType type = BodyType::Dynamic; + Shape shape = Shape::circle(0.5f); + Vec2 position; + float angle = 0; + Vec2 velocity; + float angular_velocity = 0; + float density = 1.0f; // mass = density * area unless mass > 0 + float mass = 0; // explicit mass; <=0 means derive from density; INFINITY = immovable + float friction = 0.6f; + float restitution = 0.0f; + float gravity_scale = 1.0f; + float linear_damping = 0.0f; + float angular_damping = 0.01f; + bool fixed_rotation = false; + bool bullet = false; // always use continuous collision + bool sensor = false; // trigger: overlap events only, no collision response + bool can_sleep = true; + uint32_t category = 1; + uint32_t mask = 0xFFFFFFFFu; + uint32_t user = 0; // owning EntityHandle bits +}; + +struct Body { + BodyType type = BodyType::Dynamic; + Shape shape; + Vec2 position; + float angle = 0; + Rot rot; + Vec2 velocity; + float angular_velocity = 0; + Vec2 force; + float torque = 0; + float mass = 0, inv_mass = 0, inertia = 0, inv_inertia = 0; + float friction = 0.6f, restitution = 0, gravity_scale = 1; + float linear_damping = 0, angular_damping = 0; + bool fixed_rotation = false, bullet = false, sensor = false, can_sleep = true; + bool awake = true; + float sleep_time = 0; + uint32_t category = 1, mask = 0xFFFFFFFFu; + uint32_t user = 0; + AABB aabb; + // Pre-step pose, for CCD sweeps and failure rollback. + Vec2 position0; float angle0 = 0; Vec2 velocity0; float angular_velocity0 = 0; +}; + +struct ManifoldPoint { + Vec2 local_point; // meaning depends on manifold type (Box2D convention) + float normal_impulse = 0; + float tangent_impulse = 0; + uint32_t id = 0; // feature key for warm starting +}; + +struct Manifold { + enum Type : uint8_t { Circles, FaceA, FaceB } type = Circles; + Vec2 local_normal; + Vec2 local_point; + ManifoldPoint points[2]; + int count = 0; +}; + +struct WorldManifold { Vec2 normal; Vec2 points[2]; float separations[2]; }; + +enum class ContactEventType : uint8_t { Begin, Persist, End, TriggerBegin, TriggerEnd }; + +struct ContactEvent { + ContactEventType type; + PhysicsBodyHandle a, b; + uint32_t user_a = 0, user_b = 0; + Vec2 normal; // from a to b + Vec2 point; + float impulse = 0; +}; + +struct RayHit { PhysicsBodyHandle body; Vec2 point; Vec2 normal; float fraction = 1; }; + +struct PhysicsStats { + uint32_t bodies = 0, awake = 0, pairs = 0, contacts = 0, touching = 0, ccd_hits = 0, failures = 0; +}; + +class PhysicsWorld { +public: + PhysicsWorld(); + + PhysicsBodyHandle create_body(const BodyDef& def); + bool destroy_body(PhysicsBodyHandle h); + bool valid(PhysicsBodyHandle h) const { return handles_.valid(h); } + Body* get(PhysicsBodyHandle h) { return valid(h) ? &bodies_[h.index()] : nullptr; } + const Body* get(PhysicsBodyHandle h) const { return valid(h) ? &bodies_[h.index()] : nullptr; } + + void apply_force(PhysicsBodyHandle h, Vec2 f); + void apply_impulse(PhysicsBodyHandle h, Vec2 impulse); + void set_velocity(PhysicsBodyHandle h, Vec2 v); + void set_transform(PhysicsBodyHandle h, Vec2 position, float angle); + void wake(PhysicsBodyHandle h); + + void step(float dt); + + const std::vector& events() const { return events_; } + bool raycast(Vec2 from, Vec2 to, uint32_t mask, RayHit& out, PhysicsBodyHandle ignore = {}) const; + /// All bodies whose shape overlaps the given AABB (broad test), in handle order. + void query_aabb(const AABB& box, std::vector& out) const; + + Vec2 gravity{0, -20.0f}; + int velocity_iterations = 8; + int position_iterations = 3; + PhysicsStats stats; + + uint32_t body_count() const { return handles_.alive(); } + PhysicsBodyHandle handle_at(uint32_t index) const { return handles_.at(index); } + + void serialize(BinaryWriter& w) const; + void deserialize(BinaryReader& r); + void clear(); + +private: + struct Contact { + PhysicsBodyHandle a, b; + Manifold manifold; + bool touching = false; + bool sensor = false; + bool seen = false; // refreshed this step + float friction = 0, restitution = 0; + }; + struct VelocityPoint { Vec2 ra, rb; float normal_mass, tangent_mass, velocity_bias; }; + struct VelocityConstraint { Contact* c; Vec2 normal; VelocityPoint p[2]; int count; }; + + void update_aabbs(); + void broadphase(); + void narrowphase(Contact& c); + void solve(float dt); + void continuous(float dt); + void update_sleep(float dt); + void guard_failures(); + void set_mass(Body& b, const BodyDef& def); + static uint64_t pair_key(PhysicsBodyHandle a, PhysicsBodyHandle b) { + uint32_t x = a.bits, y = b.bits; + if (x > y) std::swap(x, y); + return (uint64_t(x) << 32) | y; + } + + HandlePool handles_; + std::vector bodies_; + std::vector order_; // SAP order (body slot indices), kept sorted by aabb.min.x + // Ordered => deterministic solver order. Nodes come from a pool: no heap traffic per contact. + std::map, PoolStdAllocator>> contacts_; + std::vector events_; + std::vector constraints_; + std::vector island_parent_; + std::vector island_min_; + std::vector was_touching_; +}; + +// Narrowphase and distance primitives (exposed for tests). +void collide(const Body& a, const Body& b, Manifold& m); +WorldManifold world_manifold(const Manifold& m, const Body& a, const Body& b); +/// GJK distance between two posed shapes, including their radii. Returns separation (<0 = overlap +/// is reported as 0) and closest points. +/// Distance between core shapes (vertices / circle centres) without radii; used by CCD. +float shape_core_distance(const Shape& sa, Vec2 pa, const Rot& ra, const Shape& sb, Vec2 pb, const Rot& rb); +float shape_distance(const Shape& sa, Vec2 pa, const Rot& ra, const Shape& sb, Vec2 pb, const Rot& rb, Vec2* point_a = nullptr, Vec2* point_b = nullptr); + +} // namespace unify diff --git a/unify/engine/physics/shapes.cpp b/unify/engine/physics/shapes.cpp new file mode 100644 index 0000000000000000000000000000000000000000..95614bbd1b7e598ac0baef31296a69a8dc6d0c58 --- /dev/null +++ b/unify/engine/physics/shapes.cpp @@ -0,0 +1,485 @@ +// Shape construction, mass properties, narrowphase manifolds and GJK distance. +// The manifold/solver conventions follow the well-known Box2D v2 formulation +// (reference face + clipping, local manifold points for the position solver). +#include "physics.h" +#include + +namespace unify { +using namespace phys; + +// ------------------------------------------------------------------------------ shapes + +Shape Shape::circle(float radius) { + Shape s; + s.type = ShapeType::Circle; + s.radius = std::max(radius, 0.25f * kLinearSlop); + return s; +} + +static void box_vertices(Shape& s, float hw, float hh) { + s.count = 4; + s.vertices[0] = {-hw, -hh}; s.vertices[1] = {hw, -hh}; s.vertices[2] = {hw, hh}; s.vertices[3] = {-hw, hh}; + s.normals[0] = {0, -1}; s.normals[1] = {1, 0}; s.normals[2] = {0, 1}; s.normals[3] = {-1, 0}; + s.radius = kPolygonRadius; +} + +Shape Shape::aabb(float hw, float hh) { + Shape s; + s.type = ShapeType::AABB; + box_vertices(s, std::max(hw, kLinearSlop), std::max(hh, kLinearSlop)); + return s; +} + +Shape Shape::box(float hw, float hh) { + Shape s; + s.type = ShapeType::Box; + box_vertices(s, std::max(hw, kLinearSlop), std::max(hh, kLinearSlop)); + return s; +} + +Shape Shape::polygon(const Vec2* points, int n, Vec2* centroid_out) { + // Weld near-duplicate points, then gift-wrap the convex hull (counter-clockwise). + Vec2 ps[kMaxPolygonVertices]; + int m = 0; + for (int i = 0; i < n && m < kMaxPolygonVertices; i++) { + bool unique = true; + for (int j = 0; j < m; j++) if (length_sq(points[i] - ps[j]) < 0.25f * kLinearSlop * kLinearSlop) { unique = false; break; } + if (unique) ps[m++] = points[i]; + } + if (m < 3) return Shape::box(0.5f, 0.5f); + + int i0 = 0; + for (int i = 1; i < m; i++) + if (ps[i].x > ps[i0].x || (ps[i].x == ps[i0].x && ps[i].y < ps[i0].y)) i0 = i; + int hull[kMaxPolygonVertices]; + int hn = 0, ih = i0; + for (;;) { + hull[hn] = ih; + int ie = 0; + for (int j = 1; j < m; j++) { + if (ie == ih) { ie = j; continue; } + Vec2 r = ps[ie] - ps[hull[hn]], v = ps[j] - ps[hull[hn]]; + float c = cross(r, v); + if (c < 0 || (c == 0 && length_sq(v) > length_sq(r))) ie = j; + } + hn++; + ih = ie; + if (ie == i0 || hn == kMaxPolygonVertices) break; + } + if (hn < 3) return Shape::box(0.5f, 0.5f); + + Shape s; + s.type = ShapeType::Polygon; + s.count = hn; + for (int i = 0; i < hn; i++) s.vertices[i] = ps[hull[i]]; + + // Centroid by triangle fan. + Vec2 c{0, 0}; + float area = 0; + Vec2 ref = s.vertices[0]; + for (int i = 1; i + 1 < hn; i++) { + Vec2 e1 = s.vertices[i] - ref, e2 = s.vertices[i + 1] - ref; + float a = 0.5f * cross(e1, e2); + area += a; + c += a * (1.0f / 3.0f) * (ref + s.vertices[i] + ref + s.vertices[i + 1] - ref); + } + c = area > 1e-12f ? c * (1.0f / area) : ref; + for (int i = 0; i < hn; i++) s.vertices[i] -= c; + for (int i = 0; i < hn; i++) { + Vec2 e = s.vertices[(i + 1) % hn] - s.vertices[i]; + s.normals[i] = normalize(Vec2{e.y, -e.x}); + } + s.radius = kPolygonRadius; + if (centroid_out) *centroid_out = c; + return s; +} + +float Shape::area() const { + if (type == ShapeType::Circle) return 3.14159265f * radius * radius; + float a = 0; + for (int i = 1; i + 1 < count; i++) a += 0.5f * cross(vertices[i] - vertices[0], vertices[i + 1] - vertices[0]); + return a; +} + +float Shape::inertia_per_mass() const { + if (type == ShapeType::Circle) return 0.5f * radius * radius; + // Sum of triangle (origin, v_i, v_i+1) inertias about the origin (= centroid), per unit density. + float inertia = 0, area_sum = 0; + for (int i = 0; i < count; i++) { + Vec2 e1 = vertices[i], e2 = vertices[(i + 1) % count]; + float d = cross(e1, e2); + area_sum += 0.5f * d; + inertia += (d / 12.0f) * (dot(e1, e1) + dot(e1, e2) + dot(e2, e2)); + } + return area_sum > 0 ? inertia / area_sum : 0; +} + +AABB Shape::bounds(Vec2 p, const Rot& r) const { + if (type == ShapeType::Circle) return {{p.x - radius, p.y - radius}, {p.x + radius, p.y + radius}}; + Vec2 lo = p + r.apply(vertices[0]), hi = lo; + for (int i = 1; i < count; i++) { Vec2 v = p + r.apply(vertices[i]); lo = vmin(lo, v); hi = vmax(hi, v); } + return AABB{lo, hi}.expanded(radius); +} + +float Shape::max_extent() const { + if (type == ShapeType::Circle) return radius; + float m = 0; + for (int i = 0; i < count; i++) m = std::max(m, length(vertices[i])); + return m + radius; +} + +float Shape::min_extent() const { + if (type == ShapeType::Circle) return radius; + float m = FLT_MAX; + for (int i = 0; i < count; i++) m = std::min(m, -dot(normals[i], vertices[i]) * -1.0f); + return m + radius; +} + +// ------------------------------------------------------------------------------ narrowphase + +namespace { +struct Xf { Vec2 p; Rot q; }; +Vec2 mul(const Xf& x, Vec2 v) { return x.p + x.q.apply(v); } +Vec2 mul_t(const Xf& x, Vec2 v) { return x.q.apply_inv(v - x.p); } +Xf xf_of(const Body& b) { return {b.position, b.rot}; } + +struct ClipVertex { Vec2 v; uint32_t id; }; +uint32_t feature(uint8_t ia, uint8_t ib, uint8_t ta, uint8_t tb) { return uint32_t(ia) | uint32_t(ib) << 8 | uint32_t(ta) << 16 | uint32_t(tb) << 24; } +constexpr uint8_t kVertex = 0, kFace = 1; + +int clip_segment(ClipVertex out[2], const ClipVertex in[2], Vec2 normal, float offset, uint8_t vertex_index_a) { + int n = 0; + float d0 = dot(normal, in[0].v) - offset; + float d1 = dot(normal, in[1].v) - offset; + if (d0 <= 0) out[n++] = in[0]; + if (d1 <= 0) out[n++] = in[1]; + if (d0 * d1 < 0) { + float t = d0 / (d0 - d1); + out[n].v = in[0].v + t * (in[1].v - in[0].v); + out[n].id = feature(vertex_index_a, uint8_t(in[0].id >> 8), kVertex, kFace); + n++; + } + return n; +} + +float max_separation(int* edge, const Shape& p1, const Xf& x1, const Shape& p2, const Xf& x2) { + // Express p1 in p2's frame. + Rot q{}; + q.c = x2.q.c * x1.q.c + x2.q.s * x1.q.s; + q.s = x2.q.c * x1.q.s - x2.q.s * x1.q.c; + Vec2 t = x2.q.apply_inv(x1.p - x2.p); + int best = 0; + float max_sep = -FLT_MAX; + for (int i = 0; i < p1.count; i++) { + Vec2 n = q.apply(p1.normals[i]); + Vec2 v1 = q.apply(p1.vertices[i]) + t; + float si = FLT_MAX; + for (int j = 0; j < p2.count; j++) si = std::min(si, dot(n, p2.vertices[j] - v1)); + if (si > max_sep) { max_sep = si; best = i; } + } + *edge = best; + return max_sep; +} + +void collide_polygons(Manifold& m, const Shape& A, const Xf& xa, const Shape& B, const Xf& xb) { + m.count = 0; + float total_radius = A.radius + B.radius; + int edge_a, edge_b; + float sep_a = max_separation(&edge_a, A, xa, B, xb); + if (sep_a > total_radius) return; + float sep_b = max_separation(&edge_b, B, xb, A, xa); + if (sep_b > total_radius) return; + + // Prefer A's face unless B's is clearly better. The tolerance makes the choice stable + // for parallel edges, so resting boxes do not flip reference faces every step. + const Shape *p1, *p2; + Xf x1, x2; + int edge1; + uint8_t flip; + const float tol = 0.1f * kLinearSlop; + if (sep_b > sep_a + tol) { + p1 = &B; p2 = &A; x1 = xb; x2 = xa; edge1 = edge_b; m.type = Manifold::FaceB; flip = 1; + } else { + p1 = &A; p2 = &B; x1 = xa; x2 = xb; edge1 = edge_a; m.type = Manifold::FaceA; flip = 0; + } + + // Incident edge: the edge of p2 most anti-parallel to the reference normal. + Vec2 n1 = x2.q.apply_inv(x1.q.apply(p1->normals[edge1])); + int inc = 0; + float min_dot = FLT_MAX; + for (int i = 0; i < p2->count; i++) { + float d = dot(n1, p2->normals[i]); + if (d < min_dot) { min_dot = d; inc = i; } + } + int inc2 = (inc + 1) % p2->count; + ClipVertex incident[2] = { + {mul(x2, p2->vertices[inc]), feature(uint8_t(edge1), uint8_t(inc), kFace, kVertex)}, + {mul(x2, p2->vertices[inc2]), feature(uint8_t(edge1), uint8_t(inc2), kFace, kVertex)}, + }; + + int i11 = edge1, i12 = (edge1 + 1) % p1->count; + Vec2 v11 = p1->vertices[i11], v12 = p1->vertices[i12]; + Vec2 local_tangent = normalize(v12 - v11); + Vec2 local_normal = cross(local_tangent, 1.0f); + Vec2 plane_point = 0.5f * (v11 + v12); + Vec2 tangent = x1.q.apply(local_tangent); + Vec2 normal = cross(tangent, 1.0f); + v11 = mul(x1, v11); + v12 = mul(x1, v12); + float front = dot(normal, v11); + float side1 = -dot(tangent, v11) + total_radius; + float side2 = dot(tangent, v12) + total_radius; + + ClipVertex c1[2], c2[2]; + if (clip_segment(c1, incident, -tangent, side1, uint8_t(i11)) < 2) return; + if (clip_segment(c2, c1, tangent, side2, uint8_t(i12)) < 2) return; + + m.local_normal = local_normal; + m.local_point = plane_point; + int n = 0; + for (int i = 0; i < 2; i++) { + float separation = dot(normal, c2[i].v) - front; + if (separation <= total_radius) { + ManifoldPoint& mp = m.points[n]; + mp.local_point = mul_t(x2, c2[i].v); + uint32_t id = c2[i].id; + if (flip) { // swap A/B feature roles so ids stay consistent regardless of reference choice + uint8_t ia = uint8_t(id), ib = uint8_t(id >> 8), ta = uint8_t(id >> 16), tb = uint8_t(id >> 24); + id = feature(ib, ia, tb, ta); + } + mp.id = id; + n++; + } + } + m.count = n; +} + +void collide_polygon_circle(Manifold& m, const Shape& poly, const Xf& xa, const Shape& circle, const Xf& xb) { + m.count = 0; + Vec2 c_local = mul_t(xa, xb.p); + float radius = poly.radius + circle.radius; + int normal_index = 0; + float separation = -FLT_MAX; + for (int i = 0; i < poly.count; i++) { + float s = dot(poly.normals[i], c_local - poly.vertices[i]); + if (s > radius) return; + if (s > separation) { separation = s; normal_index = i; } + } + Vec2 v1 = poly.vertices[normal_index], v2 = poly.vertices[(normal_index + 1) % poly.count]; + m.type = Manifold::FaceA; + m.points[0].local_point = {0, 0}; + m.points[0].id = 0; + if (separation < FLT_EPSILON) { // centre inside the polygon: push out along the nearest face + m.count = 1; + m.local_normal = poly.normals[normal_index]; + m.local_point = 0.5f * (v1 + v2); + return; + } + float u1 = dot(c_local - v1, v2 - v1); + float u2 = dot(c_local - v2, v1 - v2); + if (u1 <= 0) { // vertex region v1 (corner contact) + if (length_sq(c_local - v1) > radius * radius) return; + m.local_normal = normalize(c_local - v1); + m.local_point = v1; + } else if (u2 <= 0) { // vertex region v2 + if (length_sq(c_local - v2) > radius * radius) return; + m.local_normal = normalize(c_local - v2); + m.local_point = v2; + } else { // face region (edge contact) + Vec2 face_center = 0.5f * (v1 + v2); + if (dot(c_local - face_center, poly.normals[normal_index]) > radius) return; + m.local_normal = poly.normals[normal_index]; + m.local_point = face_center; + } + m.count = 1; +} + +void collide_circles(Manifold& m, const Xf& xa, float ra, const Xf& xb, float rb) { + m.count = 0; + float r = ra + rb; + if (length_sq(xb.p - xa.p) > r * r) return; + m.type = Manifold::Circles; + m.local_point = {0, 0}; + m.local_normal = {0, 0}; + m.points[0].local_point = {0, 0}; + m.points[0].id = 0; + m.count = 1; +} +} // namespace + +void collide(const Body& a, const Body& b, Manifold& m) { + Xf xa = xf_of(a), xb = xf_of(b); + bool ca = a.shape.type == ShapeType::Circle, cb = b.shape.type == ShapeType::Circle; + if (ca && cb) collide_circles(m, xa, a.shape.radius, xb, b.shape.radius); + else if (!ca && cb) collide_polygon_circle(m, a.shape, xa, b.shape, xb); + else if (!ca && !cb) collide_polygons(m, a.shape, xa, b.shape, xb); + else m.count = 0; // circle-vs-polygon is always stored polygon-first by the world +} + +// Coincident centres have no defined direction; use a fixed, deterministic one (up). +static Vec2 safe_direction(Vec2 d) { + return length_sq(d) > FLT_EPSILON * FLT_EPSILON ? normalize(d) : Vec2{0, 1}; +} + +WorldManifold world_manifold(const Manifold& m, const Body& a, const Body& b) { + WorldManifold wm{}; + Xf xa = xf_of(a), xb = xf_of(b); + float ra = a.shape.radius, rb = b.shape.radius; + if (m.count == 0) return wm; + switch (m.type) { + case Manifold::Circles: { + Vec2 pa = mul(xa, m.local_point), pb = mul(xb, m.points[0].local_point); + wm.normal = safe_direction(pb - pa); + Vec2 ca = pa + ra * wm.normal, cb = pb - rb * wm.normal; + wm.points[0] = 0.5f * (ca + cb); + wm.separations[0] = dot(cb - ca, wm.normal); + break; + } + case Manifold::FaceA: { + wm.normal = xa.q.apply(m.local_normal); + Vec2 plane = mul(xa, m.local_point); + for (int i = 0; i < m.count; i++) { + Vec2 clip = mul(xb, m.points[i].local_point); + Vec2 ca = clip + (ra - dot(clip - plane, wm.normal)) * wm.normal; + Vec2 cb = clip - rb * wm.normal; + wm.points[i] = 0.5f * (ca + cb); + wm.separations[i] = dot(cb - ca, wm.normal); + } + break; + } + case Manifold::FaceB: { + wm.normal = xb.q.apply(m.local_normal); + Vec2 plane = mul(xb, m.local_point); + for (int i = 0; i < m.count; i++) { + Vec2 clip = mul(xa, m.points[i].local_point); + Vec2 cb = clip + (rb - dot(clip - plane, wm.normal)) * wm.normal; + Vec2 ca = clip - ra * wm.normal; + wm.points[i] = 0.5f * (ca + cb); + wm.separations[i] = dot(ca - cb, wm.normal); + } + wm.normal = -wm.normal; + break; + } + } + return wm; +} + +// ------------------------------------------------------------------------------ GJK distance + +namespace { +struct Proxy { + Vec2 v[kMaxPolygonVertices]; + int count; + float radius; + int support(Vec2 d) const { + int best = 0; + float bv = dot(v[0], d); + for (int i = 1; i < count; i++) { float x = dot(v[i], d); if (x > bv) { bv = x; best = i; } } + return best; + } +}; +Proxy make_proxy(const Shape& s, Vec2 p, const Rot& r) { + Proxy px{}; + if (s.type == ShapeType::Circle) { px.count = 1; px.v[0] = p; px.radius = s.radius; return px; } + px.count = s.count; + for (int i = 0; i < s.count; i++) px.v[i] = p + r.apply(s.vertices[i]); + px.radius = s.radius; + return px; +} +struct SimplexVertex { Vec2 wa, wb, w; float a; int ia, ib; }; +struct Simplex { + SimplexVertex v[3]; + int count; + void solve2() { + Vec2 w1 = v[0].w, w2 = v[1].w, e12 = w2 - w1; + float d12_2 = -dot(w1, e12); + if (d12_2 <= 0) { v[0].a = 1; count = 1; return; } + float d12_1 = dot(w2, e12); + if (d12_1 <= 0) { v[1].a = 1; count = 1; v[0] = v[1]; return; } + float inv = 1.0f / (d12_1 + d12_2); + v[0].a = d12_1 * inv; v[1].a = d12_2 * inv; count = 2; + } + void solve3() { + Vec2 w1 = v[0].w, w2 = v[1].w, w3 = v[2].w; + Vec2 e12 = w2 - w1; float d12_1 = dot(w2, e12), d12_2 = -dot(w1, e12); + Vec2 e13 = w3 - w1; float d13_1 = dot(w3, e13), d13_2 = -dot(w1, e13); + Vec2 e23 = w3 - w2; float d23_1 = dot(w3, e23), d23_2 = -dot(w2, e23); + float n123 = cross(e12, e13); + float d123_1 = n123 * cross(w2, w3), d123_2 = n123 * cross(w3, w1), d123_3 = n123 * cross(w1, w2); + if (d12_2 <= 0 && d13_2 <= 0) { v[0].a = 1; count = 1; return; } + if (d12_1 > 0 && d12_2 > 0 && d123_3 <= 0) { float i = 1 / (d12_1 + d12_2); v[0].a = d12_1 * i; v[1].a = d12_2 * i; count = 2; return; } + if (d13_1 > 0 && d13_2 > 0 && d123_2 <= 0) { float i = 1 / (d13_1 + d13_2); v[0].a = d13_1 * i; v[2].a = d13_2 * i; count = 2; v[1] = v[2]; return; } + if (d12_1 <= 0 && d23_2 <= 0) { v[1].a = 1; count = 1; v[0] = v[1]; return; } + if (d13_1 <= 0 && d23_1 <= 0) { v[2].a = 1; count = 1; v[0] = v[2]; return; } + if (d23_1 > 0 && d23_2 > 0 && d123_1 <= 0) { float i = 1 / (d23_1 + d23_2); v[1].a = d23_1 * i; v[2].a = d23_2 * i; count = 2; v[0] = v[2]; return; } + float i = 1 / (d123_1 + d123_2 + d123_3); + v[0].a = d123_1 * i; v[1].a = d123_2 * i; v[2].a = d123_3 * i; count = 3; + } + Vec2 search_direction() const { + if (count == 1) return -v[0].w; + Vec2 e12 = v[1].w - v[0].w; + return cross(e12, -v[0].w) > 0 ? cross(1.0f, e12) : cross(e12, 1.0f); + } +}; +} // namespace + +// Distance between the core shapes (polygon vertices / circle centre), ignoring radii. +static float core_distance(const Proxy& A, const Proxy& B, Vec2& ca, Vec2& cb); + +float shape_core_distance(const Shape& sa, Vec2 pa, const Rot& ra, const Shape& sb, Vec2 pb, const Rot& rb) { + Proxy A = make_proxy(sa, pa, ra), B = make_proxy(sb, pb, rb); + Vec2 ca, cb; + return core_distance(A, B, ca, cb); +} + +float shape_distance(const Shape& sa, Vec2 pa, const Rot& ra, const Shape& sb, Vec2 pb, const Rot& rb, Vec2* out_a, Vec2* out_b) { + Proxy A = make_proxy(sa, pa, ra), B = make_proxy(sb, pb, rb); + Vec2 ca, cb; + float dist = core_distance(A, B, ca, cb); + float radii = A.radius + B.radius; + if (dist > radii && dist > FLT_EPSILON) { + Vec2 n = (cb - ca) / dist; + ca += A.radius * n; + cb -= B.radius * n; + dist -= radii; + } else { + Vec2 mid = 0.5f * (ca + cb); + ca = cb = mid; + dist = 0; + } + if (out_a) *out_a = ca; + if (out_b) *out_b = cb; + return dist; +} + +static float core_distance(const Proxy& A, const Proxy& B, Vec2& ca, Vec2& cb) { + Simplex s{}; + s.count = 1; + s.v[0] = {A.v[0], B.v[0], B.v[0] - A.v[0], 1, 0, 0}; + int save_a[3], save_b[3]; + for (int iter = 0; iter < 32; iter++) { + int save_count = s.count; + for (int i = 0; i < save_count; i++) { save_a[i] = s.v[i].ia; save_b[i] = s.v[i].ib; } + if (s.count == 2) s.solve2(); + else if (s.count == 3) s.solve3(); + if (s.count == 3) break; // origin inside: shapes overlap + Vec2 d = s.search_direction(); + if (length_sq(d) < FLT_EPSILON * FLT_EPSILON) break; + SimplexVertex& nv = s.v[s.count]; + nv.ia = A.support(-d); + nv.ib = B.support(d); + nv.wa = A.v[nv.ia]; + nv.wb = B.v[nv.ib]; + nv.w = nv.wb - nv.wa; + bool duplicate = false; + for (int i = 0; i < save_count; i++) if (nv.ia == save_a[i] && nv.ib == save_b[i]) { duplicate = true; break; } + if (duplicate) break; + s.count++; + } + if (s.count == 1) { ca = s.v[0].wa; cb = s.v[0].wb; } + else if (s.count == 2) { ca = s.v[0].a * s.v[0].wa + s.v[1].a * s.v[1].wa; cb = s.v[0].a * s.v[0].wb + s.v[1].a * s.v[1].wb; } + else { ca = s.v[0].a * s.v[0].wa + s.v[1].a * s.v[1].wa + s.v[2].a * s.v[2].wa; cb = ca; } + return length(cb - ca); +} + +} // namespace unify diff --git a/unify/engine/physics/world.cpp b/unify/engine/physics/world.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4063b60564dabf2d72a14ca59cede9e4d0404812 --- /dev/null +++ b/unify/engine/physics/world.cpp @@ -0,0 +1,692 @@ +#include "physics.h" +#include "../core/core.h" +#include "../serialization/stream.h" +#include + +namespace unify { +using namespace phys; + +PhysicsWorld::PhysicsWorld() { + bodies_.reserve(1024); + order_.reserve(1024); + events_.reserve(512); + constraints_.reserve(512); +} + +void PhysicsWorld::set_mass(Body& b, const BodyDef& def) { + b.mass = b.inv_mass = b.inertia = b.inv_inertia = 0; + if (b.type != BodyType::Dynamic) return; + float m; + if (std::isinf(def.mass)) { // "infinite mass": immovable dynamic body + b.mass = INFINITY; + return; + } else if (def.mass > 0 && std::isfinite(def.mass)) { + m = def.mass; + } else { + m = def.density * b.shape.area(); + } + if (!(m > 0) || !std::isfinite(m)) { // zero/negative/NaN mass: fall back to unit mass, never divide by 0 + UNIFY_LOG_WARN("PHYSICS", "body has non-positive mass (%g); using 1.0", double(m)); + m = 1.0f; + } + b.mass = m; + b.inv_mass = 1.0f / m; + b.inertia = m * b.shape.inertia_per_mass(); + bool rotation_locked = b.fixed_rotation || b.shape.type == ShapeType::AABB; + b.inv_inertia = (rotation_locked || b.inertia <= 0) ? 0.0f : 1.0f / b.inertia; +} + +PhysicsBodyHandle PhysicsWorld::create_body(const BodyDef& def) { + PhysicsBodyHandle h = handles_.allocate(); + if (h.index() >= bodies_.size()) bodies_.resize(h.index() + 1); + Body& b = bodies_[h.index()]; + b = Body{}; + b.type = def.type; + b.shape = def.shape; + b.position = def.position; + b.angle = def.shape.type == ShapeType::AABB ? 0.0f : def.angle; + b.rot = Rot(b.angle); + b.velocity = def.velocity; + b.angular_velocity = def.angular_velocity; + b.friction = def.friction; + b.restitution = def.restitution; + b.gravity_scale = def.gravity_scale; + b.linear_damping = def.linear_damping; + b.angular_damping = def.angular_damping; + b.fixed_rotation = def.fixed_rotation || def.shape.type == ShapeType::AABB; + b.bullet = def.bullet; + b.sensor = def.sensor; + b.can_sleep = def.can_sleep; + b.category = def.category; + b.mask = def.mask; + b.user = def.user; + b.awake = def.type != BodyType::Static; + set_mass(b, def); + if (b.fixed_rotation) b.angular_velocity = 0; + b.aabb = b.shape.bounds(b.position, b.rot); + b.position0 = b.position; + b.angle0 = b.angle; + // Insert into SAP order at the right place so the order stays sorted and deterministic. + auto it = order_.begin(); + while (it != order_.end() && bodies_[*it].aabb.min.x <= b.aabb.min.x) ++it; + order_.insert(it, h.index()); + return h; +} + +bool PhysicsWorld::destroy_body(PhysicsBodyHandle h) { + if (!handles_.valid(h)) return false; + // End any contacts so gameplay sees matching End events. + for (auto it = contacts_.begin(); it != contacts_.end();) { + if (it->second.a == h || it->second.b == h) { + if (it->second.touching) { + const Body& ba = bodies_[it->second.a.index()]; + const Body& bb = bodies_[it->second.b.index()]; + events_.push_back({it->second.sensor ? ContactEventType::TriggerEnd : ContactEventType::End, + it->second.a, it->second.b, ba.user, bb.user, {}, {}, 0}); + // Wake the survivor so it does not float where the destroyed body was. + PhysicsBodyHandle other = it->second.a == h ? it->second.b : it->second.a; + if (bodies_[other.index()].type == BodyType::Dynamic) { bodies_[other.index()].awake = true; bodies_[other.index()].sleep_time = 0; } + } + it = contacts_.erase(it); + } else { + ++it; + } + } + for (size_t i = 0; i < order_.size(); i++) if (order_[i] == h.index()) { order_.erase(order_.begin() + long(i)); break; } + handles_.release(h); + return true; +} + +void PhysicsWorld::wake(PhysicsBodyHandle h) { + if (Body* b = get(h)) if (b->type != BodyType::Static) { b->awake = true; b->sleep_time = 0; } +} +void PhysicsWorld::apply_force(PhysicsBodyHandle h, Vec2 f) { + Body* b = get(h); + if (!b || b->type != BodyType::Dynamic || !finite(f)) return; + b->force += f; + wake(h); +} +void PhysicsWorld::apply_impulse(PhysicsBodyHandle h, Vec2 impulse) { + Body* b = get(h); + if (!b || b->type != BodyType::Dynamic || !finite(impulse)) return; + b->velocity += b->inv_mass * impulse; + wake(h); +} +void PhysicsWorld::set_velocity(PhysicsBodyHandle h, Vec2 v) { + Body* b = get(h); + if (!b || b->type == BodyType::Static || !finite(v)) return; + b->velocity = v; + if (length_sq(v) > 0) wake(h); +} +void PhysicsWorld::set_transform(PhysicsBodyHandle h, Vec2 p, float angle) { + Body* b = get(h); + if (!b || !finite(p) || !std::isfinite(angle)) return; + b->position = p; + b->angle = b->fixed_rotation ? b->angle : angle; + b->rot = Rot(b->angle); + b->aabb = b->shape.bounds(b->position, b->rot); + wake(h); +} + +// ------------------------------------------------------------------------------ step + +void PhysicsWorld::update_aabbs() { + for (uint32_t i : order_) { + Body& b = bodies_[i]; + b.aabb = b.shape.bounds(b.position, b.rot); + } + // Insertion sort: O(n) for the nearly-sorted order that frame coherence produces, + // and stable, so equal keys keep a deterministic order. + for (size_t i = 1; i < order_.size(); i++) { + uint32_t key = order_[i]; + float x = bodies_[key].aabb.min.x; + size_t j = i; + while (j > 0 && bodies_[order_[j - 1]].aabb.min.x > x) { order_[j] = order_[j - 1]; j--; } + order_[j] = key; + } +} + +static bool should_collide(const Body& a, const Body& b) { + if ((a.category & b.mask) == 0 || (b.category & a.mask) == 0) return false; + if (a.type != BodyType::Dynamic && b.type != BodyType::Dynamic) return a.sensor || b.sensor ? (a.type == BodyType::Kinematic || b.type == BodyType::Kinematic) : false; + return true; +} + +void PhysicsWorld::broadphase() { + for (auto& kv : contacts_) kv.second.seen = false; + stats.pairs = 0; + for (size_t i = 0; i < order_.size(); i++) { + const Body& a = bodies_[order_[i]]; + for (size_t j = i + 1; j < order_.size(); j++) { + const Body& b = bodies_[order_[j]]; + if (b.aabb.min.x > a.aabb.max.x) break; + if (a.aabb.max.y < b.aabb.min.y || b.aabb.max.y < a.aabb.min.y) continue; + if (!should_collide(a, b)) continue; + bool active_a = a.awake && a.type != BodyType::Static; + bool active_b = b.awake && b.type != BodyType::Static; + PhysicsBodyHandle ha = handles_.at(order_[i]), hb = handles_.at(order_[j]); + uint64_t key = pair_key(ha, hb); + auto it = contacts_.find(key); + if (!active_a && !active_b) { // both resting/static: keep the cached contact as-is + if (it != contacts_.end()) it->second.seen = true; + continue; + } + stats.pairs++; + if (it == contacts_.end()) { + Contact c; + // Polygon-vs-circle manifolds are defined polygon-first. + bool swap = a.shape.type == ShapeType::Circle && b.shape.type != ShapeType::Circle; + c.a = swap ? hb : ha; + c.b = swap ? ha : hb; + c.sensor = a.sensor || b.sensor; + c.friction = std::sqrt(a.friction * b.friction); + c.restitution = std::max(a.restitution, b.restitution); + it = contacts_.emplace(key, c).first; + } + it->second.seen = true; + narrowphase(it->second); + } + } +} + +void PhysicsWorld::narrowphase(Contact& c) { + Manifold old = c.manifold; + collide(bodies_[c.a.index()], bodies_[c.b.index()], c.manifold); + // Warm start: carry impulses across steps for points with the same feature id. + for (int i = 0; i < c.manifold.count; i++) { + ManifoldPoint& p = c.manifold.points[i]; + p.normal_impulse = p.tangent_impulse = 0; + for (int j = 0; j < old.count; j++) + if (old.points[j].id == p.id) { p.normal_impulse = old.points[j].normal_impulse; p.tangent_impulse = old.points[j].tangent_impulse; break; } + } +} + +void PhysicsWorld::solve(float dt) { + constraints_.clear(); + for (auto& kv : contacts_) { + Contact& c = kv.second; + if (c.sensor || c.manifold.count == 0) continue; + Body& a = bodies_[c.a.index()]; + Body& b = bodies_[c.b.index()]; + if (!(a.awake && a.type == BodyType::Dynamic) && !(b.awake && b.type == BodyType::Dynamic)) continue; + WorldManifold wm = world_manifold(c.manifold, a, b); + VelocityConstraint vc{}; + vc.c = &c; + vc.normal = wm.normal; + vc.count = c.manifold.count; + Vec2 tangent = cross(wm.normal, 1.0f); + for (int i = 0; i < vc.count; i++) { + VelocityPoint& p = vc.p[i]; + p.ra = wm.points[i] - a.position; + p.rb = wm.points[i] - b.position; + float rna = cross(p.ra, wm.normal), rnb = cross(p.rb, wm.normal); + float kn = a.inv_mass + b.inv_mass + a.inv_inertia * rna * rna + b.inv_inertia * rnb * rnb; + p.normal_mass = kn > 0 ? 1.0f / kn : 0; + float rta = cross(p.ra, tangent), rtb = cross(p.rb, tangent); + float kt = a.inv_mass + b.inv_mass + a.inv_inertia * rta * rta + b.inv_inertia * rtb * rtb; + p.tangent_mass = kt > 0 ? 1.0f / kt : 0; + Vec2 dv = b.velocity + cross(b.angular_velocity, p.rb) - a.velocity - cross(a.angular_velocity, p.ra); + float vrel = dot(wm.normal, dv); + p.velocity_bias = vrel < -kVelocityThreshold ? -c.restitution * vrel : 0; + } + constraints_.push_back(vc); + } + + // Warm start. + for (auto& vc : constraints_) { + Body& a = bodies_[vc.c->a.index()]; + Body& b = bodies_[vc.c->b.index()]; + Vec2 tangent = cross(vc.normal, 1.0f); + for (int i = 0; i < vc.count; i++) { + const ManifoldPoint& mp = vc.c->manifold.points[i]; + Vec2 P = mp.normal_impulse * vc.normal + mp.tangent_impulse * tangent; + a.velocity -= a.inv_mass * P; a.angular_velocity -= a.inv_inertia * cross(vc.p[i].ra, P); + b.velocity += b.inv_mass * P; b.angular_velocity += b.inv_inertia * cross(vc.p[i].rb, P); + } + } + + for (int it = 0; it < velocity_iterations; it++) { + for (auto& vc : constraints_) { + Body& a = bodies_[vc.c->a.index()]; + Body& b = bodies_[vc.c->b.index()]; + Vec2 tangent = cross(vc.normal, 1.0f); + float friction = vc.c->friction; + // Friction first so the normal (non-penetration) solve has the last word. + for (int i = 0; i < vc.count; i++) { + VelocityPoint& p = vc.p[i]; + ManifoldPoint& mp = vc.c->manifold.points[i]; + Vec2 dv = b.velocity + cross(b.angular_velocity, p.rb) - a.velocity - cross(a.angular_velocity, p.ra); + float lambda = p.tangent_mass * -dot(dv, tangent); + float max_f = friction * mp.normal_impulse; + float next = clampf(mp.tangent_impulse + lambda, -max_f, max_f); + lambda = next - mp.tangent_impulse; + mp.tangent_impulse = next; + Vec2 P = lambda * tangent; + a.velocity -= a.inv_mass * P; a.angular_velocity -= a.inv_inertia * cross(p.ra, P); + b.velocity += b.inv_mass * P; b.angular_velocity += b.inv_inertia * cross(p.rb, P); + } + for (int i = 0; i < vc.count; i++) { + VelocityPoint& p = vc.p[i]; + ManifoldPoint& mp = vc.c->manifold.points[i]; + Vec2 dv = b.velocity + cross(b.angular_velocity, p.rb) - a.velocity - cross(a.angular_velocity, p.ra); + float vn = dot(dv, vc.normal); + float lambda = -p.normal_mass * (vn - p.velocity_bias); + float next = std::max(mp.normal_impulse + lambda, 0.0f); + lambda = next - mp.normal_impulse; + mp.normal_impulse = next; + Vec2 P = lambda * vc.normal; + a.velocity -= a.inv_mass * P; a.angular_velocity -= a.inv_inertia * cross(p.ra, P); + b.velocity += b.inv_mass * P; b.angular_velocity += b.inv_inertia * cross(p.rb, P); + } + } + } + + // Integrate positions (dynamic and kinematic), clamping absurd translations. + for (uint32_t i : order_) { + Body& b = bodies_[i]; + if (b.type == BodyType::Static || !b.awake) continue; + Vec2 move = dt * b.velocity; + float ls = length_sq(move); + if (ls > kMaxTranslation * kMaxTranslation) b.velocity *= kMaxTranslation / std::sqrt(ls); + b.position += dt * b.velocity; + if (!b.fixed_rotation) { b.angle += dt * b.angular_velocity; b.rot = Rot(b.angle); } + } + + // Position solver: push resolving penetration directly (no energy added to velocities). + for (int it = 0; it < position_iterations; it++) { + float min_sep = 0; + for (auto& vc : constraints_) { + Contact& c = *vc.c; + Body& a = bodies_[c.a.index()]; + Body& b = bodies_[c.b.index()]; + const Manifold& m = c.manifold; + float ma = a.inv_mass, mb = b.inv_mass, ia = a.inv_inertia, ib = b.inv_inertia; + for (int j = 0; j < m.count; j++) { + Vec2 normal, point; + float sep; + float ra = a.shape.radius, rb = b.shape.radius; + if (m.type == Manifold::Circles) { + Vec2 pa = a.position + a.rot.apply(m.local_point), pb = b.position + b.rot.apply(m.points[0].local_point); + Vec2 d = pb - pa; + normal = length_sq(d) > FLT_EPSILON * FLT_EPSILON ? normalize(d) : Vec2{0, 1}; + point = 0.5f * (pa + pb); + sep = dot(d, normal) - ra - rb; + } else if (m.type == Manifold::FaceA) { + normal = a.rot.apply(m.local_normal); + Vec2 plane = a.position + a.rot.apply(m.local_point); + Vec2 clip = b.position + b.rot.apply(m.points[j].local_point); + sep = dot(clip - plane, normal) - ra - rb; + point = clip; + } else { + normal = b.rot.apply(m.local_normal); + Vec2 plane = b.position + b.rot.apply(m.local_point); + Vec2 clip = a.position + a.rot.apply(m.points[j].local_point); + sep = dot(clip - plane, normal) - ra - rb; + point = clip; + normal = -normal; + } + Vec2 rA = point - a.position, rB = point - b.position; + min_sep = std::min(min_sep, sep); + float C = clampf(kBaumgarte * (sep + kLinearSlop), -kMaxLinearCorrection, 0.0f); + float rna = cross(rA, normal), rnb = cross(rB, normal); + float K = ma + mb + ia * rna * rna + ib * rnb * rnb; + float impulse = K > 0 ? -C / K : 0; + Vec2 P = impulse * normal; + a.position -= ma * P; + b.position += mb * P; + if (ia > 0) { a.angle -= ia * cross(rA, P); a.rot = Rot(a.angle); } + if (ib > 0) { b.angle += ib * cross(rB, P); b.rot = Rot(b.angle); } + } + } + if (min_sep >= -3.0f * kLinearSlop) break; + } +} + +// Continuous collision: conservative advancement along each fast body's sweep against +// static/kinematic geometry (and everything, for bullets). Stops the body at first touch. +void PhysicsWorld::continuous(float) { + for (uint32_t i : order_) { + Body& b = bodies_[i]; + if (b.type != BodyType::Dynamic || !b.awake || b.sensor) continue; + Vec2 motion = b.position - b.position0; + float travel = length(motion) + std::fabs(b.angle - b.angle0) * b.shape.max_extent(); + if (!b.bullet && travel < 0.5f * b.shape.min_extent()) continue; + + Rot r0(b.angle0); + // Swept bounds from the pre-step pose to the integrated pose (b.aabb is still pre-step here). + AABB swept = b.shape.bounds(b.position0, r0).merged(b.shape.bounds(b.position, b.rot)); + float toi = 1.0f; + for (uint32_t k : order_) { + if (k == i) continue; + const Body& o = bodies_[k]; + if (o.sensor || !should_collide(b, o)) continue; + if (o.type == BodyType::Dynamic && !b.bullet) continue; + AABB oswept = o.shape.bounds(o.position0, Rot(o.angle0)).merged(o.shape.bounds(o.position, o.rot)); + if (!swept.overlaps(oswept)) continue; + + // Measured on core shapes: stop where the skins overlap by ~3 slop, so the next + // step's narrowphase is guaranteed a manifold and the solver removes the approach. + const float target = std::max(kLinearSlop, b.shape.radius + o.shape.radius - 3.0f * kLinearSlop); + const float tolerance = 0.25f * kLinearSlop; + float d0 = shape_core_distance(b.shape, b.position0, r0, o.shape, o.position0, Rot(o.angle0)); + if (d0 <= target + tolerance) continue; // already touching at the start: discrete contacts handle it + float bound = length(motion - (o.position - o.position0)) + std::fabs(b.angle - b.angle0) * b.shape.max_extent() + + std::fabs(o.angle - o.angle0) * o.shape.max_extent(); + if (bound < 1e-9f) continue; + float t = 0; + for (int iter = 0; iter < 32; iter++) { + Vec2 pb = lerp(b.position0, b.position, t), po = lerp(o.position0, o.position, t); + float d = shape_core_distance(b.shape, pb, Rot(lerp(b.angle0, b.angle, t)), o.shape, po, Rot(lerp(o.angle0, o.angle, t))); + if (d <= target + tolerance) break; + t += (d - target) / bound; + if (t >= toi) break; + } + if (t < toi) toi = t; + } + if (toi < 1.0f) { + b.position = lerp(b.position0, b.position, toi); + b.angle = lerp(b.angle0, b.angle, toi); + b.rot = Rot(b.angle); + b.aabb = b.shape.bounds(b.position, b.rot); + stats.ccd_hits++; + } + } +} + +void PhysicsWorld::update_sleep(float dt) { + const float lin2 = kLinearSleepTolerance * kLinearSleepTolerance; + const float ang2 = kAngularSleepTolerance * kAngularSleepTolerance; + island_parent_.resize(bodies_.size()); + for (uint32_t i = 0; i < bodies_.size(); i++) island_parent_[i] = i; + auto find = [&](uint32_t x) { while (island_parent_[x] != x) { island_parent_[x] = island_parent_[island_parent_[x]]; x = island_parent_[x]; } return x; }; + + for (uint32_t i : order_) { + Body& b = bodies_[i]; + if (b.type != BodyType::Dynamic || !b.awake) continue; + if (!b.can_sleep || length_sq(b.velocity) > lin2 || b.angular_velocity * b.angular_velocity > ang2) b.sleep_time = 0; + else b.sleep_time += dt; + } + for (auto& kv : contacts_) { + const Contact& c = kv.second; + if (!c.touching || c.sensor) continue; + Body& a = bodies_[c.a.index()]; + Body& b = bodies_[c.b.index()]; + // A moving kinematic body keeps whatever it touches awake. + if (a.type == BodyType::Kinematic && length_sq(a.velocity) > 0) b.sleep_time = 0; + if (b.type == BodyType::Kinematic && length_sq(b.velocity) > 0) a.sleep_time = 0; + if (a.type == BodyType::Dynamic && b.type == BodyType::Dynamic) { + uint32_t ra = find(c.a.index()), rb = find(c.b.index()); + if (ra != rb) island_parent_[std::max(ra, rb)] = std::min(ra, rb); + } + } + std::vector& min_sleep = island_min_; + min_sleep.assign(bodies_.size(), FLT_MAX); + for (uint32_t i : order_) { + const Body& b = bodies_[i]; + if (b.type != BodyType::Dynamic) continue; + float t = b.awake ? b.sleep_time : kTimeToSleep; // sleeping members count as ready + uint32_t r = find(i); + min_sleep[r] = std::min(min_sleep[r], t); + } + for (uint32_t i : order_) { + Body& b = bodies_[i]; + if (b.type != BodyType::Dynamic) continue; + if (min_sleep[find(i)] >= kTimeToSleep) { + if (b.awake) { b.awake = false; b.velocity = {}; b.angular_velocity = 0; } + } else if (!b.awake) { + b.awake = true; + b.sleep_time = 0; + } + } +} + +void PhysicsWorld::guard_failures() { + for (uint32_t i : order_) { + Body& b = bodies_[i]; + if (finite(b.position) && std::isfinite(b.angle) && finite(b.velocity) && std::isfinite(b.angular_velocity)) continue; + // Numeric failure (e.g. degenerate input). Roll the body back rather than letting NaN + // propagate into transforms, contacts and the ECS. + UNIFY_LOG_ERROR("PHYSICS", "non-finite state on body %u; rolled back", i); + b.position = b.position0; b.angle = b.angle0; b.rot = Rot(b.angle); + b.velocity = {}; b.angular_velocity = 0; + b.force = {}; b.torque = 0; + stats.failures++; + for (auto& kv : contacts_) + if (kv.second.a.index() == i || kv.second.b.index() == i) + for (int k = 0; k < kv.second.manifold.count; k++) kv.second.manifold.points[k].normal_impulse = kv.second.manifold.points[k].tangent_impulse = 0; + } +} + +void PhysicsWorld::step(float dt) { + events_.clear(); + if (!(dt > 0)) return; + stats.ccd_hits = 0; + + for (uint32_t i : order_) { + Body& b = bodies_[i]; + b.position0 = b.position; b.angle0 = b.angle; + b.velocity0 = b.velocity; b.angular_velocity0 = b.angular_velocity; + if (b.type != BodyType::Dynamic || !b.awake) continue; + b.velocity += dt * (b.gravity_scale * gravity + b.inv_mass * b.force); + b.angular_velocity += dt * b.inv_inertia * b.torque; + b.velocity *= 1.0f / (1.0f + dt * b.linear_damping); + b.angular_velocity *= 1.0f / (1.0f + dt * b.angular_damping); + } + + update_aabbs(); + broadphase(); + + // Touching state before the solve, so impulses from this step accompany the events. + std::vector& was = was_touching_; + was.clear(); + for (auto& kv : contacts_) was.push_back(kv.second.touching ? 1 : 0); + { + for (auto& kv : contacts_) { + Contact& c = kv.second; + if (c.seen) { + const Body& a = bodies_[c.a.index()]; + const Body& b = bodies_[c.b.index()]; + bool active = (a.awake && a.type != BodyType::Static) || (b.awake && b.type != BodyType::Static); + if (active) c.touching = c.manifold.count > 0; + } else { + c.touching = false; + } + } + } + + solve(dt); + continuous(dt); + guard_failures(); + update_sleep(dt); + + for (uint32_t i : order_) { bodies_[i].force = {}; bodies_[i].torque = 0; } + + // Events in deterministic (pair-key) order; drop contacts whose AABBs no longer overlap. + size_t k = 0; + stats.contacts = stats.touching = 0; + for (auto it = contacts_.begin(); it != contacts_.end(); k++) { + Contact& c = it->second; + bool before = was[k] != 0; + const Body& a = bodies_[c.a.index()]; + const Body& b = bodies_[c.b.index()]; + ContactEvent ev{}; + ev.a = c.a; ev.b = c.b; ev.user_a = a.user; ev.user_b = b.user; + if (c.touching) { + WorldManifold wm = world_manifold(c.manifold, a, b); + ev.normal = wm.normal; + ev.point = wm.points[0]; + for (int i = 0; i < c.manifold.count; i++) ev.impulse += c.manifold.points[i].normal_impulse; + } + bool asleep = !(a.awake && a.type != BodyType::Static) && !(b.awake && b.type != BodyType::Static); + if (c.touching && !before) { ev.type = c.sensor ? ContactEventType::TriggerBegin : ContactEventType::Begin; events_.push_back(ev); } + else if (!c.touching && before) { ev.type = c.sensor ? ContactEventType::TriggerEnd : ContactEventType::End; events_.push_back(ev); } + else if (c.touching && !c.sensor && !asleep) { ev.type = ContactEventType::Persist; events_.push_back(ev); } + if (!c.seen) { it = contacts_.erase(it); continue; } + stats.contacts++; + if (c.touching) stats.touching++; + ++it; + } + + stats.bodies = handles_.alive(); + stats.awake = 0; + for (uint32_t i : order_) if (bodies_[i].awake && bodies_[i].type == BodyType::Dynamic) stats.awake++; +} + +// ------------------------------------------------------------------------------ queries + +static bool ray_shape(const Body& b, Vec2 p1, Vec2 p2, float& fraction, Vec2& normal) { + Vec2 d = p2 - p1; + if (b.shape.type == ShapeType::Circle) { + Vec2 s = p1 - b.position; + float r = b.shape.radius; + float bb = dot(s, d), cc = dot(s, s) - r * r, rr = dot(d, d); + float sigma = bb * bb - rr * cc; + if (sigma < 0 || rr < FLT_EPSILON) return false; + float a = -(bb + std::sqrt(sigma)); + if (a < 0 || a > rr) return false; + fraction = a / rr; + normal = normalize(s + fraction * d); + return true; + } + Vec2 lp1 = b.rot.apply_inv(p1 - b.position), lp2 = b.rot.apply_inv(p2 - b.position), ld = lp2 - lp1; + float lower = 0, upper = 1; + int index = -1; + for (int i = 0; i < b.shape.count; i++) { + // Expand faces by the polygon skin so rays hit where contacts happen. + float num = dot(b.shape.normals[i], b.shape.vertices[i] - lp1) + b.shape.radius; + float den = dot(b.shape.normals[i], ld); + if (den == 0) { if (num < 0) return false; continue; } + if (den < 0 && num < lower * den) { lower = num / den; index = i; } + else if (den > 0 && num < upper * den) { upper = num / den; } + if (upper < lower) return false; + } + if (index < 0) return false; + fraction = lower; + normal = b.rot.apply(b.shape.normals[index]); + return true; +} + +bool PhysicsWorld::raycast(Vec2 from, Vec2 to, uint32_t mask, RayHit& out, PhysicsBodyHandle ignore) const { + bool hit = false; + out.fraction = 1; + for (uint32_t i : order_) { + const Body& b = bodies_[i]; + PhysicsBodyHandle h = handles_.at(i); + if (h == ignore || b.sensor || (b.category & mask) == 0) continue; + float f; Vec2 n; + if (ray_shape(b, from, to, f, n) && f < out.fraction) { + out = {h, from + f * (to - from), n, f}; + hit = true; + } + } + return hit; +} + +void PhysicsWorld::query_aabb(const AABB& box, std::vector& out) const { + out.clear(); + for (uint32_t i : order_) if (bodies_[i].aabb.overlaps(box)) out.push_back(handles_.at(i)); + std::sort(out.begin(), out.end()); +} + +// ------------------------------------------------------------------------------ save state + +static void write_shape(BinaryWriter& w, const Shape& s) { + w.u8(uint8_t(s.type)); w.f32(s.radius); w.u8(uint8_t(s.count)); + for (int i = 0; i < s.count; i++) { w.vec2(s.vertices[i]); w.vec2(s.normals[i]); } +} +static Shape read_shape(BinaryReader& r) { + Shape s; + s.type = ShapeType(r.u8()); s.radius = r.f32(); s.count = r.u8(); + if (s.count > kMaxPolygonVertices) throw SerializationError("polygon vertex count out of range"); + for (int i = 0; i < s.count; i++) { s.vertices[i] = r.vec2(); s.normals[i] = r.vec2(); } + return s; +} + +void PhysicsWorld::serialize(BinaryWriter& w) const { + auto hs = handles_.save(); + w.u32(uint32_t(hs.gens.size())); + for (size_t i = 0; i < hs.gens.size(); i++) { w.u8(hs.gens[i]); w.u8(hs.live[i]); } + w.u32(uint32_t(hs.free.size())); + for (uint32_t f : hs.free) w.u32(f); + w.vec2(gravity); + w.u32(uint32_t(order_.size())); + for (uint32_t i : order_) { + const Body& b = bodies_[i]; + w.u32(i); + w.u8(uint8_t(b.type)); write_shape(w, b.shape); + w.vec2(b.position); w.f32(b.angle); w.vec2(b.velocity); w.f32(b.angular_velocity); + w.vec2(b.force); w.f32(b.torque); + w.f32(b.mass); w.f32(b.inv_mass); w.f32(b.inertia); w.f32(b.inv_inertia); + w.f32(b.friction); w.f32(b.restitution); w.f32(b.gravity_scale); w.f32(b.linear_damping); w.f32(b.angular_damping); + w.u8(uint8_t(b.fixed_rotation | b.bullet << 1 | b.sensor << 2 | b.can_sleep << 3 | b.awake << 4)); + w.f32(b.sleep_time); w.u32(b.category); w.u32(b.mask); w.u32(b.user); + } + // Contacts carry warm-starting impulses; without them a restored world diverges. + w.u32(uint32_t(contacts_.size())); + for (auto& kv : contacts_) { + const Contact& c = kv.second; + w.u64(kv.first); w.u32(c.a.bits); w.u32(c.b.bits); + w.u8(uint8_t(c.touching | c.sensor << 1)); w.f32(c.friction); w.f32(c.restitution); + const Manifold& m = c.manifold; + w.u8(uint8_t(m.type)); w.vec2(m.local_normal); w.vec2(m.local_point); w.u8(uint8_t(m.count)); + for (int i = 0; i < m.count; i++) { w.vec2(m.points[i].local_point); w.f32(m.points[i].normal_impulse); w.f32(m.points[i].tangent_impulse); w.u32(m.points[i].id); } + } +} + +void PhysicsWorld::deserialize(BinaryReader& r) { + clear(); + HandlePool::State hs; + uint32_t n = r.u32(); + hs.gens.resize(n); hs.live.resize(n); + for (uint32_t i = 0; i < n; i++) { hs.gens[i] = r.u8(); hs.live[i] = r.u8(); if (hs.live[i]) hs.alive++; } + uint32_t nf = r.u32(); + hs.free.resize(nf); + for (auto& f : hs.free) f = r.u32(); + handles_.load(hs); + bodies_.assign(n, Body{}); + gravity = r.vec2(); + uint32_t count = r.u32(); + for (uint32_t k = 0; k < count; k++) { + uint32_t i = r.u32(); + if (i >= n) throw SerializationError("body index out of range"); + Body& b = bodies_[i]; + b.type = BodyType(r.u8()); b.shape = read_shape(r); + b.position = r.vec2(); b.angle = r.f32(); b.velocity = r.vec2(); b.angular_velocity = r.f32(); + b.force = r.vec2(); b.torque = r.f32(); + b.mass = r.f32(); b.inv_mass = r.f32(); b.inertia = r.f32(); b.inv_inertia = r.f32(); + b.friction = r.f32(); b.restitution = r.f32(); b.gravity_scale = r.f32(); b.linear_damping = r.f32(); b.angular_damping = r.f32(); + uint8_t f = r.u8(); + b.fixed_rotation = f & 1; b.bullet = f & 2; b.sensor = f & 4; b.can_sleep = f & 8; b.awake = f & 16; + b.sleep_time = r.f32(); b.category = r.u32(); b.mask = r.u32(); b.user = r.u32(); + b.rot = Rot(b.angle); + b.aabb = b.shape.bounds(b.position, b.rot); + b.position0 = b.position; b.angle0 = b.angle; + order_.push_back(i); + } + uint32_t nc = r.u32(); + for (uint32_t k = 0; k < nc; k++) { + uint64_t key = r.u64(); + Contact c; + c.a.bits = r.u32(); c.b.bits = r.u32(); + uint8_t f = r.u8(); c.touching = f & 1; c.sensor = f & 2; + c.friction = r.f32(); c.restitution = r.f32(); + Manifold& m = c.manifold; + m.type = Manifold::Type(r.u8()); m.local_normal = r.vec2(); m.local_point = r.vec2(); m.count = r.u8(); + if (m.count > 2) throw SerializationError("manifold point count out of range"); + for (int i = 0; i < m.count; i++) { m.points[i].local_point = r.vec2(); m.points[i].normal_impulse = r.f32(); m.points[i].tangent_impulse = r.f32(); m.points[i].id = r.u32(); } + if (!handles_.valid(c.a) || !handles_.valid(c.b)) throw SerializationError("contact references a dead body"); + contacts_.emplace(key, c); + } +} + +void PhysicsWorld::clear() { + handles_.clear(); + bodies_.clear(); + order_.clear(); + contacts_.clear(); + events_.clear(); + constraints_.clear(); + stats = {}; +} + +} // namespace unify diff --git a/unify/engine/render/image.cpp b/unify/engine/render/image.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ca6f714994e1fdcaa8b2412538a4c22c1fe8ed3c --- /dev/null +++ b/unify/engine/render/image.cpp @@ -0,0 +1,193 @@ +// QOI ("Quite OK Image") codec for texture assets, and an uncompressed PNG writer for screenshots. +#include "render.h" +#include +#include + +namespace unify { + +static uint32_t qoi_hash(const uint8_t* p) { return (p[0] * 3u + p[1] * 5u + p[2] * 7u + p[3] * 11u) % 64u; } + +bool decode_qoi(const std::vector& d, Image& out) { + if (d.size() < 22 || std::memcmp(d.data(), "qoif", 4)) return false; + auto be32 = [&](size_t o) { return uint32_t(d[o]) << 24 | uint32_t(d[o + 1]) << 16 | uint32_t(d[o + 2]) << 8 | d[o + 3]; }; + uint32_t w = be32(4), h = be32(8); + if (w == 0 || h == 0 || w > 16384 || h > 16384) return false; + out = Image(int(w), int(h)); + uint8_t index[64 * 4] = {}; + uint8_t px[4] = {0, 0, 0, 255}; + size_t p = 14, end = d.size() - 8; + int run = 0; + for (size_t i = 0; i < size_t(w) * h; i++) { + if (run > 0) { run--; } + else if (p < end) { + uint8_t b = d[p++]; + if (b == 0xFE) { px[0] = d[p]; px[1] = d[p + 1]; px[2] = d[p + 2]; p += 3; } + else if (b == 0xFF) { std::memcpy(px, &d[p], 4); p += 4; } + else if ((b & 0xC0) == 0x00) { std::memcpy(px, &index[(b & 0x3F) * 4], 4); } + else if ((b & 0xC0) == 0x40) { px[0] += ((b >> 4) & 3) - 2; px[1] += ((b >> 2) & 3) - 2; px[2] += (b & 3) - 2; } + else if ((b & 0xC0) == 0x80) { + uint8_t b2 = d[p++]; + int vg = (b & 0x3F) - 32; + px[0] += uint8_t(vg - 8 + ((b2 >> 4) & 0xF)); + px[1] += uint8_t(vg); + px[2] += uint8_t(vg - 8 + (b2 & 0xF)); + } else { run = b & 0x3F; } + std::memcpy(&index[qoi_hash(px) * 4], px, 4); + } + std::memcpy(&out.pixels[i * 4], px, 4); + } + return true; +} + +std::vector encode_qoi(const Image& img) { + std::vector o; + auto be32 = [&](uint32_t v) { for (int i = 3; i >= 0; i--) o.push_back(uint8_t(v >> (8 * i))); }; + o.insert(o.end(), {'q', 'o', 'i', 'f'}); + be32(uint32_t(img.width)); be32(uint32_t(img.height)); + o.push_back(4); o.push_back(0); + uint8_t index[64 * 4] = {}; + uint8_t prev[4] = {0, 0, 0, 255}; + int run = 0; + size_t n = size_t(img.width) * img.height; + for (size_t i = 0; i < n; i++) { + const uint8_t* px = &img.pixels[i * 4]; + if (!std::memcmp(px, prev, 4)) { + if (++run == 62 || i == n - 1) { o.push_back(uint8_t(0xC0 | (run - 1))); run = 0; } + continue; + } + if (run) { o.push_back(uint8_t(0xC0 | (run - 1))); run = 0; } + uint32_t h = qoi_hash(px); + if (!std::memcmp(&index[h * 4], px, 4)) { o.push_back(uint8_t(h)); } + else { + std::memcpy(&index[h * 4], px, 4); + if (px[3] == prev[3]) { + int8_t vr = int8_t(px[0] - prev[0]), vg = int8_t(px[1] - prev[1]), vb = int8_t(px[2] - prev[2]); + int8_t vgr = int8_t(vr - vg), vgb = int8_t(vb - vg); + if (vr > -3 && vr < 2 && vg > -3 && vg < 2 && vb > -3 && vb < 2) o.push_back(uint8_t(0x40 | (vr + 2) << 4 | (vg + 2) << 2 | (vb + 2))); + else if (vgr > -9 && vgr < 8 && vg > -33 && vg < 32 && vgb > -9 && vgb < 8) { o.push_back(uint8_t(0x80 | (vg + 32))); o.push_back(uint8_t((vgr + 8) << 4 | (vgb + 8))); } + else { o.push_back(0xFE); o.push_back(px[0]); o.push_back(px[1]); o.push_back(px[2]); } + } else { o.push_back(0xFF); o.insert(o.end(), px, px + 4); } + } + std::memcpy(prev, px, 4); + } + o.insert(o.end(), {0, 0, 0, 0, 0, 0, 0, 1}); + return o; +} + +bool load_image(const std::string& path, Image& out) { + FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) return false; + std::vector data; + uint8_t buf[65536]; + size_t n; + while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) data.insert(data.end(), buf, buf + n); + std::fclose(f); + return decode_qoi(data, out); +} + +static uint32_t crc_table[256]; +static void init_crc() { + for (uint32_t n = 0; n < 256; n++) { uint32_t c = n; for (int k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320u ^ (c >> 1) : c >> 1; crc_table[n] = c; } +} +static uint32_t crc(const uint8_t* p, size_t n, uint32_t c = 0xFFFFFFFFu) { for (size_t i = 0; i < n; i++) c = crc_table[(c ^ p[i]) & 0xFF] ^ (c >> 8); return c; } + +bool write_png(const std::string& path, const Image& img) { + if (!crc_table[1]) init_crc(); + // Raw scanlines (filter 0) in stored (uncompressed) deflate blocks inside a zlib stream. + std::vector raw; + for (int y = 0; y < img.height; y++) { raw.push_back(0); raw.insert(raw.end(), img.at(0, y), img.at(0, y) + img.width * 4); } + std::vector z = {0x78, 0x01}; + uint32_t a = 1, b = 0; + for (uint8_t v : raw) { a = (a + v) % 65521; b = (b + a) % 65521; } + for (size_t off = 0; off < raw.size() || off == 0; off += 65535) { + size_t len = std::min(65535, raw.size() - off); + z.push_back(off + len >= raw.size() ? 1 : 0); + z.push_back(uint8_t(len)); z.push_back(uint8_t(len >> 8)); + z.push_back(uint8_t(~len)); z.push_back(uint8_t(~len >> 8)); + z.insert(z.end(), raw.begin() + long(off), raw.begin() + long(off + len)); + if (raw.empty()) break; + } + uint32_t adler = b << 16 | a; + for (int i = 3; i >= 0; i--) z.push_back(uint8_t(adler >> (8 * i))); + + FILE* f = std::fopen(path.c_str(), "wb"); + if (!f) return false; + auto chunk = [&](const char* type, const std::vector& data) { + uint8_t len[4] = {uint8_t(data.size() >> 24), uint8_t(data.size() >> 16), uint8_t(data.size() >> 8), uint8_t(data.size())}; + std::fwrite(len, 1, 4, f); + std::fwrite(type, 1, 4, f); + if (!data.empty()) std::fwrite(data.data(), 1, data.size(), f); + uint32_t c = crc(reinterpret_cast(type), 4); + c = crc(data.data(), data.size(), c) ^ 0xFFFFFFFFu; + uint8_t cb[4] = {uint8_t(c >> 24), uint8_t(c >> 16), uint8_t(c >> 8), uint8_t(c)}; + std::fwrite(cb, 1, 4, f); + }; + const uint8_t sig[8] = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'}; + std::fwrite(sig, 1, 8, f); + std::vector ihdr = {uint8_t(img.width >> 24), uint8_t(img.width >> 16), uint8_t(img.width >> 8), uint8_t(img.width), + uint8_t(img.height >> 24), uint8_t(img.height >> 16), uint8_t(img.height >> 8), uint8_t(img.height), 8, 6, 0, 0, 0}; + chunk("IHDR", ihdr); + chunk("IDAT", z); + chunk("IEND", {}); + return std::fclose(f) == 0; +} + +// ------------------------------------------------------------------------------ bitmap font + +// Classic 5x7 font, ASCII 32..126, column-major, bit 0 = top row. +static const uint8_t kFont5x7[95][5] = { + {0x00,0x00,0x00,0x00,0x00},{0x00,0x00,0x5F,0x00,0x00},{0x00,0x07,0x00,0x07,0x00},{0x14,0x7F,0x14,0x7F,0x14}, + {0x24,0x2A,0x7F,0x2A,0x12},{0x23,0x13,0x08,0x64,0x62},{0x36,0x49,0x55,0x22,0x50},{0x00,0x05,0x03,0x00,0x00}, + {0x00,0x1C,0x22,0x41,0x00},{0x00,0x41,0x22,0x1C,0x00},{0x08,0x2A,0x1C,0x2A,0x08},{0x08,0x08,0x3E,0x08,0x08}, + {0x00,0x50,0x30,0x00,0x00},{0x08,0x08,0x08,0x08,0x08},{0x00,0x60,0x60,0x00,0x00},{0x20,0x10,0x08,0x04,0x02}, + {0x3E,0x51,0x49,0x45,0x3E},{0x00,0x42,0x7F,0x40,0x00},{0x42,0x61,0x51,0x49,0x46},{0x21,0x41,0x45,0x4B,0x31}, + {0x18,0x14,0x12,0x7F,0x10},{0x27,0x45,0x45,0x45,0x39},{0x3C,0x4A,0x49,0x49,0x30},{0x01,0x71,0x09,0x05,0x03}, + {0x36,0x49,0x49,0x49,0x36},{0x06,0x49,0x49,0x29,0x1E},{0x00,0x36,0x36,0x00,0x00},{0x00,0x56,0x36,0x00,0x00}, + {0x08,0x14,0x22,0x41,0x00},{0x14,0x14,0x14,0x14,0x14},{0x00,0x41,0x22,0x14,0x08},{0x02,0x01,0x51,0x09,0x06}, + {0x32,0x49,0x79,0x41,0x3E},{0x7E,0x11,0x11,0x11,0x7E},{0x7F,0x49,0x49,0x49,0x36},{0x3E,0x41,0x41,0x41,0x22}, + {0x7F,0x41,0x41,0x22,0x1C},{0x7F,0x49,0x49,0x49,0x41},{0x7F,0x09,0x09,0x01,0x01},{0x3E,0x41,0x41,0x51,0x32}, + {0x7F,0x08,0x08,0x08,0x7F},{0x00,0x41,0x7F,0x41,0x00},{0x20,0x40,0x41,0x3F,0x01},{0x7F,0x08,0x14,0x22,0x41}, + {0x7F,0x40,0x40,0x40,0x40},{0x7F,0x02,0x04,0x02,0x7F},{0x7F,0x04,0x08,0x10,0x7F},{0x3E,0x41,0x41,0x41,0x3E}, + {0x7F,0x09,0x09,0x09,0x06},{0x3E,0x41,0x51,0x21,0x5E},{0x7F,0x09,0x19,0x29,0x46},{0x46,0x49,0x49,0x49,0x31}, + {0x01,0x01,0x7F,0x01,0x01},{0x3F,0x40,0x40,0x40,0x3F},{0x1F,0x20,0x40,0x20,0x1F},{0x7F,0x20,0x18,0x20,0x7F}, + {0x63,0x14,0x08,0x14,0x63},{0x03,0x04,0x78,0x04,0x03},{0x61,0x51,0x49,0x45,0x43},{0x00,0x00,0x7F,0x41,0x41}, + {0x02,0x04,0x08,0x10,0x20},{0x41,0x41,0x7F,0x00,0x00},{0x04,0x02,0x01,0x02,0x04},{0x40,0x40,0x40,0x40,0x40}, + {0x00,0x01,0x02,0x04,0x00},{0x20,0x54,0x54,0x54,0x78},{0x7F,0x48,0x44,0x44,0x38},{0x38,0x44,0x44,0x44,0x20}, + {0x38,0x44,0x44,0x48,0x7F},{0x38,0x54,0x54,0x54,0x18},{0x08,0x7E,0x09,0x01,0x02},{0x08,0x14,0x54,0x54,0x3C}, + {0x7F,0x08,0x04,0x04,0x78},{0x00,0x44,0x7D,0x40,0x00},{0x20,0x40,0x44,0x3D,0x00},{0x00,0x7F,0x10,0x28,0x44}, + {0x00,0x41,0x7F,0x40,0x00},{0x7C,0x04,0x18,0x04,0x78},{0x7C,0x08,0x04,0x04,0x78},{0x38,0x44,0x44,0x44,0x38}, + {0x7C,0x14,0x14,0x14,0x08},{0x08,0x14,0x14,0x18,0x7C},{0x7C,0x08,0x04,0x04,0x08},{0x48,0x54,0x54,0x54,0x20}, + {0x04,0x3F,0x44,0x40,0x20},{0x3C,0x40,0x40,0x20,0x7C},{0x1C,0x20,0x40,0x20,0x1C},{0x3C,0x40,0x30,0x40,0x3C}, + {0x44,0x28,0x10,0x28,0x44},{0x0C,0x50,0x50,0x50,0x3C},{0x44,0x64,0x54,0x4C,0x44},{0x00,0x08,0x36,0x41,0x00}, + {0x00,0x00,0x7F,0x00,0x00},{0x00,0x41,0x36,0x08,0x00},{0x08,0x08,0x2A,0x1C,0x08}, +}; + +BitmapFont BitmapFont::build() { + BitmapFont f; + f.image = Image(16 * 6, 6 * 8); + for (int c = 0; c < 95; c++) { + int cx = (c % 16) * 6, cy = (c / 16) * 8; + for (int col = 0; col < 5; col++) + for (int row = 0; row < 7; row++) + if (kFont5x7[c][col] >> row & 1) { + uint8_t* p = f.image.at(cx + col, cy + row); + p[0] = p[1] = p[2] = p[3] = 255; + } + } + return f; +} + +RectF BitmapFont::glyph(char c) const { + int i = (c < 32 || c > 126) ? '?' - 32 : c - 32; + return {float((i % 16) * 6), float((i / 16) * 8), 6, 8}; +} + +void BitmapFont::draw(Renderer2D& r, const std::string& text, Vec2 pos, float scale, Color color, int16_t layer) const { + float x = pos.x; + for (char c : text) { + if (c != ' ') r.screen_rect(texture, glyph(c), {x, pos.y, 6 * scale, 8 * scale}, color, layer); + x += 6 * scale; + } +} + +} // namespace unify diff --git a/unify/engine/render/render.h b/unify/engine/render/render.h new file mode 100644 index 0000000000000000000000000000000000000000..ff5d6750c61f6d6b58a815d8ceff31edd8437947 --- /dev/null +++ b/unify/engine/render/render.h @@ -0,0 +1,173 @@ +#pragma once +#include +#include +#include +#include "../core/math.h" +#include "../core/handle.h" + +namespace unify { + +struct RectI { int x = 0, y = 0, w = 0, h = 0; bool empty() const { return w <= 0 || h <= 0; } }; +struct RectF { float x = 0, y = 0, w = 0, h = 0; }; + +/// CPU-side RGBA8 image. Also the storage of the software render target. +struct Image { + int width = 0, height = 0; + std::vector pixels; // RGBA, row-major, top row first + Image() = default; + Image(int w, int h, Color fill = {0, 0, 0, 0}) : width(w), height(h), pixels(size_t(w) * h * 4) { + for (size_t i = 0; i < pixels.size(); i += 4) { pixels[i] = fill.r; pixels[i + 1] = fill.g; pixels[i + 2] = fill.b; pixels[i + 3] = fill.a; } + } + uint8_t* at(int x, int y) { return &pixels[(size_t(y) * width + x) * 4]; } + const uint8_t* at(int x, int y) const { return &pixels[(size_t(y) * width + x) * 4]; } +}; + +bool decode_qoi(const std::vector& data, Image& out); +std::vector encode_qoi(const Image& img); +bool write_png(const std::string& path, const Image& img); // uncompressed deflate, for screenshots +bool load_image(const std::string& path, Image& out); // .qoi + +enum class BlendMode : uint8_t { Opaque, Alpha, Additive, Multiply }; + +struct Material { + BlendMode blend = BlendMode::Alpha; + bool operator==(const Material& o) const { return blend == o.blend; } +}; + +/// Texture atlas: named sub-rectangles of one texture, packed with a shelf packer. +struct AtlasRegion { std::string name; RectI rect; }; +struct Atlas { + std::vector regions; // region 0 is the whole texture + int find(const std::string& name) const { + for (size_t i = 0; i < regions.size(); i++) if (regions[i].name == name) return int(i); + return -1; + } +}; +/// Packs images into one atlas image; returns false if they do not fit. +bool pack_atlas(const std::vector>& items, int size, Image& out, Atlas& atlas, int padding = 1); + +struct Camera { + Vec2 position; // world point at the viewport centre + float zoom = 32; // pixels per world unit + float rotation = 0; +}; + +struct Viewport { RectI rect; }; + +/// A render target: a colour buffer the device draws into. +struct RenderTarget { + Image color; + RenderTarget() = default; + RenderTarget(int w, int h) : color(w, h, {0, 0, 0, 255}) {} + int width() const { return color.width; } + int height() const { return color.height; } +}; + +/// One queued draw. Everything is resolved to target pixels by the Renderer2D before +/// reaching the device, so devices only rasterize textured quads. +struct RenderCommand { + uint32_t texture = 0; // TextureHandle bits (0 = white) + RectF src; // texel rectangle + Vec2 corners[4]; // screen-space, CCW from bottom-left of the sprite + Color tint; + int16_t layer = 0; + float depth = 0; // within a layer: larger draws later (in front) + Material material; + RectI scissor; // empty = full viewport + uint32_t sequence = 0; // submission order: final tie-breaker, keeps sort stable +}; + +struct Vertex { float x, y, u, v; Color color; }; + +/// A run of commands sharing texture, material and scissor: one device draw call. +struct Batch { + uint32_t texture = 0; + Material material; + RectI scissor; + const Vertex* vertices = nullptr; // 4 per quad + uint32_t quad_count = 0; +}; + +/// Abstract GPU-or-CPU device. Backends implement this (software, SDL, Unreal). +class RenderDevice { +public: + virtual ~RenderDevice() = default; + virtual TextureHandle create_texture(const Image& image) = 0; + virtual bool update_texture(TextureHandle h, const Image& image) = 0; + virtual bool destroy_texture(TextureHandle h) = 0; + virtual bool texture_size(TextureHandle h, int& w, int& h_out) const = 0; + virtual void begin(RenderTarget& target, Color clear) = 0; + virtual void draw(const Batch& batch) = 0; + virtual void end() = 0; + virtual uint32_t live_textures() const = 0; +}; + +/// Reference device: rasterizes batches into the target's colour buffer on the CPU. +class SoftwareRenderDevice : public RenderDevice { +public: + TextureHandle create_texture(const Image& image) override; + bool update_texture(TextureHandle h, const Image& image) override; + bool destroy_texture(TextureHandle h) override; + bool texture_size(TextureHandle h, int& w, int& h_out) const override; + void begin(RenderTarget& target, Color clear) override; + void draw(const Batch& batch) override; + void end() override {} + uint32_t live_textures() const override { return handles_.alive(); } +private: + void raster_triangle(const Vertex& a, const Vertex& b, const Vertex& c, const Image* tex, BlendMode blend, const RectI& clip); + HandlePool handles_; + std::vector textures_; + RenderTarget* target_ = nullptr; + Image white_{1, 1, {255, 255, 255, 255}}; +}; + +struct RenderStats { uint32_t commands = 0, batches = 0, quads = 0; }; + +/// Collects commands for a frame, sorts and batches them, and submits to a device. +class Renderer2D { +public: + explicit Renderer2D(RenderDevice& device) : device_(device) { commands_.reserve(4096); vertices_.reserve(4096 * 4); } + + void begin(RenderTarget& target, const Camera& camera, const Viewport& vp, Color clear = {20, 22, 30, 255}); + /// World-space sprite: centre position, size in world units, rotation. + void sprite(uint32_t texture, RectF src, Vec2 pos, Vec2 size, float rotation, Color tint, int16_t layer, float depth, + BlendMode blend = BlendMode::Alpha, bool flip_x = false, Vec2 pivot = {0.5f, 0.5f}); + /// Screen-space rectangle (UI): pixels, origin top-left. + void screen_rect(uint32_t texture, RectF src, RectF dst, Color tint, int16_t layer, BlendMode blend = BlendMode::Alpha); + void fill_screen_rect(RectF dst, Color c, int16_t layer) { screen_rect(0, {0, 0, 1, 1}, dst, c, layer); } + void set_scissor(RectI r) { scissor_ = r; } + void clear_scissor() { scissor_ = {}; } + void end(); + + Vec2 world_to_screen(Vec2 w) const; + Vec2 screen_to_world(Vec2 s) const; + const RenderStats& stats() const { return stats_; } + /// Stats of the last completed frame (valid while a new frame is being built). + const RenderStats& last_frame_stats() const { return last_stats_; } + RenderDevice& device() { return device_; } + +private: + RenderDevice& device_; + RenderTarget* target_ = nullptr; + Camera camera_; + Viewport viewport_; + Color clear_; + RectI scissor_; + std::vector commands_; + std::vector vertices_; + uint32_t sequence_ = 0; + RenderStats stats_, last_stats_; +}; + +/// Bitmap font (5x7 glyphs baked into an atlas-ready image, 6x8 cells). +struct BitmapFont { + Image image; // 16x6 grid of 6x8 cells for ASCII 32..127 + uint32_t texture = 0; + static BitmapFont build(); + RectF glyph(char c) const; + /// Draws text at a screen position (top-left), scale = pixels per font pixel. + void draw(Renderer2D& r, const std::string& text, Vec2 pos, float scale, Color color, int16_t layer) const; + float width(const std::string& text, float scale) const { return float(text.size()) * 6 * scale; } +}; + +} // namespace unify diff --git a/unify/engine/render/renderer.cpp b/unify/engine/render/renderer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d515b44fd1886e637c2428c1137b3a8d392043ee --- /dev/null +++ b/unify/engine/render/renderer.cpp @@ -0,0 +1,239 @@ +#include "render.h" +#include +#include + +namespace unify { + +// ------------------------------------------------------------------------------ software device + +TextureHandle SoftwareRenderDevice::create_texture(const Image& image) { + TextureHandle h = handles_.allocate(); + if (h.index() >= textures_.size()) textures_.resize(h.index() + 1); + textures_[h.index()] = image; + return h; +} +bool SoftwareRenderDevice::update_texture(TextureHandle h, const Image& image) { + if (!handles_.valid(h)) return false; + textures_[h.index()] = image; + return true; +} +bool SoftwareRenderDevice::destroy_texture(TextureHandle h) { + if (!handles_.valid(h)) return false; + textures_[h.index()] = Image{}; + return handles_.release(h); +} +bool SoftwareRenderDevice::texture_size(TextureHandle h, int& w, int& hh) const { + if (!handles_.valid(h)) return false; + w = textures_[h.index()].width; + hh = textures_[h.index()].height; + return true; +} + +void SoftwareRenderDevice::begin(RenderTarget& target, Color clear) { + target_ = ⌖ + auto& px = target.color.pixels; + for (size_t i = 0; i < px.size(); i += 4) { px[i] = clear.r; px[i + 1] = clear.g; px[i + 2] = clear.b; px[i + 3] = clear.a; } +} + +static inline uint8_t mul8(int a, int b) { return uint8_t((a * b + 127) / 255); } + +void SoftwareRenderDevice::raster_triangle(const Vertex& a, const Vertex& b, const Vertex& c, const Image* tex, BlendMode blend, const RectI& clip) { + Image& dst = target_->color; + float area = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); + if (std::fabs(area) < 1e-6f) return; + int minx = std::max(clip.x, int(std::floor(std::min({a.x, b.x, c.x})))); + int maxx = std::min(clip.x + clip.w - 1, int(std::ceil(std::max({a.x, b.x, c.x})))); + int miny = std::max(clip.y, int(std::floor(std::min({a.y, b.y, c.y})))); + int maxy = std::min(clip.y + clip.h - 1, int(std::ceil(std::max({a.y, b.y, c.y})))); + if (minx > maxx || miny > maxy) return; + float inv = 1.0f / area; + const int tw = tex->width, th = tex->height; + for (int y = miny; y <= maxy; y++) { + float py = y + 0.5f; + for (int x = minx; x <= maxx; x++) { + float px = x + 0.5f; + // Barycentric weights; the top-left rule is approximated by >= 0 on shared edges. + float w0 = ((b.x - px) * (c.y - py) - (b.y - py) * (c.x - px)) * inv; + float w1 = ((c.x - px) * (a.y - py) - (c.y - py) * (a.x - px)) * inv; + float w2 = 1.0f - w0 - w1; + if (w0 < 0 || w1 < 0 || w2 < 0) continue; + float u = w0 * a.u + w1 * b.u + w2 * c.u; + float v = w0 * a.v + w1 * b.v + w2 * c.v; + int tx = std::clamp(int(std::floor(u)), 0, tw - 1); + int ty = std::clamp(int(std::floor(v)), 0, th - 1); + const uint8_t* s = tex->at(tx, ty); + int sr = mul8(s[0], a.color.r), sg = mul8(s[1], a.color.g), sb = mul8(s[2], a.color.b), sa = mul8(s[3], a.color.a); + uint8_t* d = dst.at(x, y); + switch (blend) { + case BlendMode::Opaque: d[0] = uint8_t(sr); d[1] = uint8_t(sg); d[2] = uint8_t(sb); d[3] = 255; break; + case BlendMode::Alpha: + if (sa == 0) break; + d[0] = uint8_t((sr * sa + d[0] * (255 - sa) + 127) / 255); + d[1] = uint8_t((sg * sa + d[1] * (255 - sa) + 127) / 255); + d[2] = uint8_t((sb * sa + d[2] * (255 - sa) + 127) / 255); + d[3] = uint8_t(std::min(255, sa + d[3] * (255 - sa) / 255)); + break; + case BlendMode::Additive: + d[0] = uint8_t(std::min(255, d[0] + sr * sa / 255)); + d[1] = uint8_t(std::min(255, d[1] + sg * sa / 255)); + d[2] = uint8_t(std::min(255, d[2] + sb * sa / 255)); + break; + case BlendMode::Multiply: + d[0] = mul8(d[0], sr); d[1] = mul8(d[1], sg); d[2] = mul8(d[2], sb); + break; + } + } + } +} + +void SoftwareRenderDevice::draw(const Batch& batch) { + if (!target_) return; + const Image* tex = &white_; + if (batch.texture) { + TextureHandle h{batch.texture}; + if (handles_.valid(h) && textures_[h.index()].width > 0) tex = &textures_[h.index()]; + } + RectI clip = batch.scissor.empty() ? RectI{0, 0, target_->width(), target_->height()} : batch.scissor; + clip.x = std::max(clip.x, 0); + clip.y = std::max(clip.y, 0); + clip.w = std::min(clip.w, target_->width() - clip.x); + clip.h = std::min(clip.h, target_->height() - clip.y); + if (clip.empty()) return; + for (uint32_t q = 0; q < batch.quad_count; q++) { + const Vertex* v = batch.vertices + q * 4; + raster_triangle(v[0], v[1], v[2], tex, batch.material.blend, clip); + raster_triangle(v[0], v[2], v[3], tex, batch.material.blend, clip); + } +} + +// ------------------------------------------------------------------------------ Renderer2D + +void Renderer2D::begin(RenderTarget& target, const Camera& camera, const Viewport& vp, Color clear) { + target_ = ⌖ + camera_ = camera; + viewport_ = vp.rect.empty() ? Viewport{{0, 0, target.width(), target.height()}} : vp; + clear_ = clear; + commands_.clear(); + sequence_ = 0; + scissor_ = {}; + stats_ = {}; +} + +Vec2 Renderer2D::world_to_screen(Vec2 w) const { + Vec2 d = Rot(-camera_.rotation).apply(w - camera_.position) * camera_.zoom; + return {viewport_.rect.x + viewport_.rect.w * 0.5f + d.x, viewport_.rect.y + viewport_.rect.h * 0.5f - d.y}; // y up -> y down +} +Vec2 Renderer2D::screen_to_world(Vec2 s) const { + Vec2 d{s.x - (viewport_.rect.x + viewport_.rect.w * 0.5f), -(s.y - (viewport_.rect.y + viewport_.rect.h * 0.5f))}; + return camera_.position + Rot(camera_.rotation).apply(d / camera_.zoom); +} + +void Renderer2D::sprite(uint32_t texture, RectF src, Vec2 pos, Vec2 size, float rotation, Color tint, int16_t layer, float depth, + BlendMode blend, bool flip_x, Vec2 pivot) { + RenderCommand c; + c.texture = texture; + c.src = src; + if (flip_x) { c.src.x += c.src.w; c.src.w = -c.src.w; } + Rot r(rotation); + Vec2 local[4] = {{-pivot.x * size.x, -pivot.y * size.y}, {(1 - pivot.x) * size.x, -pivot.y * size.y}, + {(1 - pivot.x) * size.x, (1 - pivot.y) * size.y}, {-pivot.x * size.x, (1 - pivot.y) * size.y}}; + AABB bounds{{1e30f, 1e30f}, {-1e30f, -1e30f}}; + for (int i = 0; i < 4; i++) { + c.corners[i] = world_to_screen(pos + r.apply(local[i])); + bounds.min = vmin(bounds.min, c.corners[i]); + bounds.max = vmax(bounds.max, c.corners[i]); + } + // Cull off-screen sprites before they cost a sort slot. + const RectI& vr = viewport_.rect; + if (bounds.max.x < vr.x || bounds.min.x > vr.x + vr.w || bounds.max.y < vr.y || bounds.min.y > vr.y + vr.h) return; + c.tint = tint; c.layer = layer; c.depth = depth; c.material.blend = blend; + c.scissor = scissor_.empty() ? vr : scissor_; + c.sequence = sequence_++; + commands_.push_back(c); +} + +void Renderer2D::screen_rect(uint32_t texture, RectF src, RectF dst, Color tint, int16_t layer, BlendMode blend) { + RenderCommand c; + c.texture = texture; + c.src = src; + c.corners[0] = {dst.x, dst.y + dst.h}; + c.corners[1] = {dst.x + dst.w, dst.y + dst.h}; + c.corners[2] = {dst.x + dst.w, dst.y}; + c.corners[3] = {dst.x, dst.y}; + c.tint = tint; c.layer = layer; c.depth = 0; c.material.blend = blend; + c.scissor = scissor_; + c.sequence = sequence_++; + commands_.push_back(c); +} + +void Renderer2D::end() { + if (!target_) return; + // Sort: layer, then depth, then keep batchable state together, then submission order. + // Depth decides visibility, so state-grouping only happens among equal depths. + std::sort(commands_.begin(), commands_.end(), [](const RenderCommand& a, const RenderCommand& b) { + if (a.layer != b.layer) return a.layer < b.layer; + if (a.depth != b.depth) return a.depth < b.depth; + if (a.material.blend != b.material.blend) return a.material.blend < b.material.blend; + if (a.texture != b.texture) return a.texture < b.texture; + return a.sequence < b.sequence; + }); + vertices_.clear(); + for (const RenderCommand& c : commands_) { + // Quad vertex order: bottom-left, bottom-right, top-right, top-left (source v is top-down). + float u0 = c.src.x, u1 = c.src.x + c.src.w, v0 = c.src.y + c.src.h, v1 = c.src.y; + vertices_.push_back({c.corners[0].x, c.corners[0].y, u0, v0, c.tint}); + vertices_.push_back({c.corners[1].x, c.corners[1].y, u1, v0, c.tint}); + vertices_.push_back({c.corners[2].x, c.corners[2].y, u1, v1, c.tint}); + vertices_.push_back({c.corners[3].x, c.corners[3].y, u0, v1, c.tint}); + } + device_.begin(*target_, clear_); + size_t i = 0; + while (i < commands_.size()) { + size_t j = i + 1; + auto same = [&](const RenderCommand& a, const RenderCommand& b) { + return a.texture == b.texture && a.material == b.material && a.scissor.x == b.scissor.x && a.scissor.y == b.scissor.y && + a.scissor.w == b.scissor.w && a.scissor.h == b.scissor.h; + }; + while (j < commands_.size() && same(commands_[i], commands_[j])) j++; + Batch b; + b.texture = commands_[i].texture; + b.material = commands_[i].material; + b.scissor = commands_[i].scissor; + b.vertices = &vertices_[i * 4]; + b.quad_count = uint32_t(j - i); + device_.draw(b); + stats_.batches++; + i = j; + } + device_.end(); + stats_.commands = stats_.quads = uint32_t(commands_.size()); + last_stats_ = stats_; +} + +// ------------------------------------------------------------------------------ atlas + +bool pack_atlas(const std::vector>& items, int size, Image& out, Atlas& atlas, int padding) { + out = Image(size, size); + atlas.regions.clear(); + atlas.regions.push_back({"", {0, 0, size, size}}); + // Shelf packing, tallest first (stable for equal heights so output is deterministic). + std::vector order(items.size()); + for (size_t i = 0; i < order.size(); i++) order[i] = i; + std::stable_sort(order.begin(), order.end(), [&](size_t a, size_t b) { return items[a].second->height > items[b].second->height; }); + std::vector placed(items.size()); + int x = padding, y = padding, shelf = 0; + for (size_t k : order) { + const Image& im = *items[k].second; + if (x + im.width + padding > size) { x = padding; y += shelf + padding; shelf = 0; } + if (y + im.height + padding > size) return false; + placed[k] = {x, y, im.width, im.height}; + for (int row = 0; row < im.height; row++) + std::copy(im.at(0, row), im.at(0, row) + im.width * 4, out.at(x, y + row)); + x += im.width + padding; + shelf = std::max(shelf, im.height); + } + for (size_t i = 0; i < items.size(); i++) atlas.regions.push_back({items[i].first, placed[i]}); + return true; +} + +} // namespace unify diff --git a/unify/engine/runtime/backend.h b/unify/engine/runtime/backend.h new file mode 100644 index 0000000000000000000000000000000000000000..0f5c8918988bd90c865550a5b1217f8013bddc0e --- /dev/null +++ b/unify/engine/runtime/backend.h @@ -0,0 +1,69 @@ +#pragma once +#include +#include +#include "../render/render.h" +#include "../audio/audio.h" +#include "../input/input.h" + +namespace unify { + +struct EngineConfig { + std::string title = "UNIFY"; + int width = 640, height = 360; + uint32_t tick_rate = 60; + uint64_t seed = 1; + std::string asset_root = "assets"; + std::string boot_scene = "title"; + size_t lua_memory_limit = 64u << 20; + int lua_gc_budget_kb = 32; + int max_ticks_per_frame = 8; // beyond this the sim drops time instead of spiralling +}; + +/// Platform backend. UNIFY talks to the platform only through this interface; gameplay +/// never sees it. Implementations: Headless (engine), SDL2 (backends/sdl), Unreal +/// (backends/unreal). A backend supplies a render device, an audio device, input events +/// stamped on its clock, and presentation of finished frames. +class Backend { +public: + virtual ~Backend() = default; + virtual const char* name() const = 0; + virtual bool init(const EngineConfig& config, std::string& error) = 0; + virtual RenderDevice& render_device() = 0; + virtual AudioDevice& audio_device() = 0; + /// Pushes pending OS events into `input`, timestamped with now_ns(). Sets quit on close. + virtual void poll(InputSystem& input, bool& quit) = 0; + virtual void present(const RenderTarget& frame) = 0; + /// Monotonic platform clock (the input clock). Nondeterministic; never visible to gameplay. + virtual uint64_t now_ns() = 0; + virtual void shutdown() = 0; +}; + +/// Offscreen backend: software rendering, null audio device, programmatic input and a +/// controllable clock. Used for tests, CI, replays and servers. +class HeadlessBackend : public Backend { +public: + const char* name() const override { return "headless"; } + bool init(const EngineConfig&, std::string&) override { return true; } + RenderDevice& render_device() override { return device_; } + AudioDevice& audio_device() override { return audio_; } + void poll(InputSystem&, bool& quit) override { quit = quit_; } + void present(const RenderTarget& frame) override { last_frame_ = frame.color; presented_++; } + uint64_t now_ns() override { return clock_ns_; } + void shutdown() override { audio_.stop(); } + + void advance_clock(uint64_t ns) { clock_ns_ += ns; } + void set_clock(uint64_t ns) { clock_ns_ = ns; } + void request_quit() { quit_ = true; } + const Image& last_frame() const { return last_frame_; } + uint64_t presented() const { return presented_; } + +private: + SoftwareRenderDevice device_; + NullAudioDevice audio_; + uint64_t clock_ns_ = 0; + bool quit_ = false; + Image last_frame_; + uint64_t presented_ = 0; +}; + +} // namespace unify diff --git a/unify/engine/runtime/bindings.cpp b/unify/engine/runtime/bindings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d0d9cf205e7b8e29bcf04bfc4b9f59781731e90 --- /dev/null +++ b/unify/engine/runtime/bindings.cpp @@ -0,0 +1,606 @@ +// The UNIFY Lua API. Gameplay scripts reach the engine only through these functions. +// Objects cross the boundary as handles (entity, buffer, kernel, voice ids) and every +// call validates its handle; Lua never receives an engine pointer. +#include "engine.h" +#include +#include +#include +#include + +namespace unify { + +namespace { + +Engine& E(lua_State* L) { return *static_cast(lua_touserdata(L, lua_upvalueindex(1))); } + +EntityHandle check_entity(lua_State* L, int idx) { + auto* p = static_cast(luaL_checkudata(L, idx, kEntityMeta)); + EntityHandle e{*p}; + if (!E(L).world().valid(e)) luaL_error(L, "stale entity handle (entity was destroyed)"); + return e; +} +void push_entity(lua_State* L, EntityHandle e) { + if (!e) { lua_pushnil(L); return; } + *static_cast(lua_newuserdatauv(L, sizeof(uint32_t), 0)) = e.bits; + luaL_setmetatable(L, kEntityMeta); +} +PhysicsBodyHandle body_of(lua_State* L, EntityHandle e) { + BodyC* b = E(L).world().bodies.get(e); + return b ? PhysicsBodyHandle{b->body} : PhysicsBodyHandle{}; +} +float num(lua_State* L, int i) { return float(luaL_checknumber(L, i)); } +float opt(lua_State* L, int i, float d) { return float(luaL_optnumber(L, i, d)); } + +// Ensures the active scene holds a reference to an asset (so unloading the scene frees it). +AssetHandle scene_asset(lua_State* L, AssetType type, const std::string& name) { + Engine& e = E(L); + AssetHandle h = e.assets().find(name); + Scene* s = e.current_scene(); + if (!h) { + h = e.assets().load(type, name); + if (!h) luaL_error(L, "%s asset '%s' could not be loaded", asset_type_name(type), name.c_str()); + if (s) s->assets.push_back(h); else e.assets().acquire(h); + } else if (s && std::find(s->assets.begin(), s->assets.end(), h) == s->assets.end()) { + e.assets().acquire(h); + s->assets.push_back(h); + } + return h; +} + +// ------------------------------------------------------------------------------ entity +int ent_set_position(lua_State* L) { + EntityHandle e = check_entity(L, 1); + Vec2 p{num(L, 2), num(L, 3)}; + TransformC* t = E(L).world().transforms.get(e); + t->current.position = p; + if (lua_toboolean(L, 4)) t->previous.position = p; // teleport: no interpolation smear + if (PhysicsBodyHandle b = body_of(L, e)) E(L).physics().set_transform(b, p, t->current.rotation); + return 0; +} +int ent_position(lua_State* L) { + EntityHandle e = check_entity(L, 1); + Vec2 p = E(L).world().transforms.get(e)->current.position; + lua_pushnumber(L, p.x); lua_pushnumber(L, p.y); + return 2; +} +int ent_set_velocity(lua_State* L) { + EntityHandle e = check_entity(L, 1); + PhysicsBodyHandle b = body_of(L, e); + if (!b) return luaL_error(L, "entity has no physics body"); + E(L).physics().set_velocity(b, {num(L, 2), num(L, 3)}); + return 0; +} +int ent_velocity(lua_State* L) { + EntityHandle e = check_entity(L, 1); + const Body* b = E(L).physics().get(body_of(L, e)); + lua_pushnumber(L, b ? b->velocity.x : 0); + lua_pushnumber(L, b ? b->velocity.y : 0); + return 2; +} +int ent_apply_impulse(lua_State* L) { + EntityHandle e = check_entity(L, 1); + E(L).physics().apply_impulse(body_of(L, e), {num(L, 2), num(L, 3)}); + return 0; +} +int ent_set_rotation(lua_State* L) { + EntityHandle e = check_entity(L, 1); + TransformC* t = E(L).world().transforms.get(e); + t->current.rotation = num(L, 2); + if (PhysicsBodyHandle b = body_of(L, e)) E(L).physics().set_transform(b, t->current.position, t->current.rotation); + return 0; +} +int ent_rotation(lua_State* L) { lua_pushnumber(L, E(L).world().transforms.get(check_entity(L, 1))->current.rotation); return 1; } +int ent_set_animation(lua_State* L) { + EntityHandle e = check_entity(L, 1); + AnimatorC* a = E(L).world().animators.get(e); + const char* clip = luaL_checkstring(L, 2); + if (!E(L).animation().clip(clip)) return luaL_error(L, "unknown animation '%s'", clip); + if (!a) a = &E(L).world().animators.add(e, AnimatorC{E(L).animation().create_player(clip)}); + E(L).animation().play(a->player, clip, opt(L, 3, 0), lua_toboolean(L, 4)); + return 0; +} +int ent_animation(lua_State* L) { + AnimatorC* a = E(L).world().animators.get(check_entity(L, 1)); + AnimationPlayer* p = a ? E(L).animation().player(a->player) : nullptr; + if (!p) { lua_pushnil(L); return 1; } + lua_pushstring(L, p->clip.c_str()); + lua_pushboolean(L, p->finished); + return 2; +} +SpriteC& sprite_of(lua_State* L, EntityHandle e) { + SpriteC* s = E(L).world().sprites.get(e); + if (!s) luaL_error(L, "entity has no sprite"); + return *s; +} +int ent_set_flip(lua_State* L) { sprite_of(L, check_entity(L, 1)).flip_x = lua_toboolean(L, 2); return 0; } +int ent_set_visible(lua_State* L) { sprite_of(L, check_entity(L, 1)).visible = lua_toboolean(L, 2); return 0; } +int ent_set_tint(lua_State* L) { + SpriteC& s = sprite_of(L, check_entity(L, 1)); + s.tint = {uint8_t(luaL_checkinteger(L, 2)), uint8_t(luaL_checkinteger(L, 3)), uint8_t(luaL_checkinteger(L, 4)), uint8_t(luaL_optinteger(L, 5, 255))}; + return 0; +} +int ent_name(lua_State* L) { lua_pushstring(L, E(L).world().info(check_entity(L, 1))->name.c_str()); return 1; } +int ent_valid(lua_State* L) { + auto* p = static_cast(luaL_checkudata(L, 1, kEntityMeta)); + lua_pushboolean(L, E(L).world().valid(EntityHandle{*p})); + return 1; +} +int ent_id(lua_State* L) { lua_pushinteger(L, check_entity(L, 1).bits); return 1; } +int ent_destroy(lua_State* L) { E(L).destroy_entity(check_entity(L, 1)); return 0; } +int ent_eq(lua_State* L) { + auto* a = static_cast(luaL_checkudata(L, 1, kEntityMeta)); + auto* b = static_cast(luaL_checkudata(L, 2, kEntityMeta)); + lua_pushboolean(L, *a == *b); + return 1; +} +int ent_tostring(lua_State* L) { + auto* p = static_cast(luaL_checkudata(L, 1, kEntityMeta)); + EntityHandle e{*p}; + const EntityInfo* in = E(L).world().info(e); + lua_pushfstring(L, "Entity(%d:%d %s)", int(e.index()), int(e.generation()), in ? in->name.c_str() : ""); + return 1; +} + +// ------------------------------------------------------------------------------ world +int world_spawn(lua_State* L) { + std::string err; + EntityHandle e = E(L).instantiate(luaL_checkstring(L, 2), {num(L, 3), num(L, 4)}, lua_toboolean(L, 5), err); + if (!e) return luaL_error(L, "spawn failed: %s", err.c_str()); + push_entity(L, e); + return 1; +} +int world_destroy(lua_State* L) { lua_pushboolean(L, E(L).destroy_entity(check_entity(L, 2))); return 1; } +int world_find(lua_State* L) { push_entity(L, E(L).world().find(luaL_checkstring(L, 2))); return 1; } +int world_count(lua_State* L) { lua_pushinteger(L, E(L).world().alive()); return 1; } + +// ------------------------------------------------------------------------------ physics +int phys_apply_force(lua_State* L) { + PhysicsBodyHandle b = body_of(L, check_entity(L, 2)); + if (!b) return luaL_error(L, "entity has no physics body"); + E(L).physics().apply_force(b, {num(L, 3), num(L, 4)}); + return 0; +} +int phys_apply_impulse(lua_State* L) { E(L).physics().apply_impulse(body_of(L, check_entity(L, 2)), {num(L, 3), num(L, 4)}); return 0; } +int phys_raycast(lua_State* L) { + uint32_t mask = uint32_t(luaL_optinteger(L, 6, 0xFFFF)); + PhysicsBodyHandle ignore; + if (lua_isuserdata(L, 7)) ignore = body_of(L, check_entity(L, 7)); + RayHit hit; + if (!E(L).physics().raycast({num(L, 2), num(L, 3)}, {num(L, 4), num(L, 5)}, mask, hit, ignore)) { lua_pushboolean(L, 0); return 1; } + lua_pushboolean(L, 1); + lua_pushnumber(L, hit.point.x); lua_pushnumber(L, hit.point.y); + lua_pushnumber(L, hit.normal.x); lua_pushnumber(L, hit.normal.y); + const Body* b = E(L).physics().get(hit.body); + push_entity(L, b && E(L).world().valid(EntityHandle{b->user}) ? EntityHandle{b->user} : EntityHandle{}); + return 6; +} +int phys_set_gravity(lua_State* L) { E(L).physics().gravity = {num(L, 2), num(L, 3)}; return 0; } +int phys_add_static_box(lua_State* L) { + // Static collision without a sprite (e.g. merged tile runs). Owned by the active scene. + Engine& e = E(L); + Scene* s = e.current_scene(); + EntityHandle ent = e.world().create("static", s ? s->id : 0); + Vec2 c{num(L, 2), num(L, 3)}; + e.world().transforms.get(ent)->current.position = c; + e.world().transforms.get(ent)->previous.position = c; + BodyDef d; + d.type = BodyType::Static; + d.shape = Shape::aabb(num(L, 4) / 2, num(L, 5) / 2); + d.position = c; + d.friction = opt(L, 7, 0.8f); + d.category = uint32_t(luaL_optinteger(L, 6, 1)); + d.user = ent.bits; + e.world().bodies.add(ent, BodyC{e.physics().create_body(d).bits}); + push_entity(L, ent); + return 1; +} +int phys_is_awake(lua_State* L) { + const Body* b = E(L).physics().get(body_of(L, check_entity(L, 2))); + lua_pushboolean(L, b && b->awake); + return 1; +} + +// ------------------------------------------------------------------------------ audio +int audio_play(lua_State* L) { + Engine& e = E(L); + AssetHandle h = scene_asset(L, AssetType::Audio, luaL_checkstring(L, 2)); + PlayParams p; + p.bus = Bus::Sfx; p.volume = opt(L, 3, 1); p.pan = opt(L, 4, 0); p.pitch = opt(L, 5, 1); + AudioHandle v = e.mixer().play(e.assets().get(h)->clip, p); + if (v && e.current_scene()) e.current_scene()->voices.push_back(v); + lua_pushinteger(L, v.bits); + return 1; +} +int audio_stream(lua_State* L) { + Engine& e = E(L); + AssetHandle h = scene_asset(L, AssetType::Music, luaL_checkstring(L, 2)); + auto src = e.assets().open_stream(h); + if (!src) return luaL_error(L, "could not open stream '%s'", luaL_checkstring(L, 2)); + PlayParams p; + p.bus = Bus::Music; p.volume = opt(L, 3, 1); + p.loop = lua_isnoneornil(L, 4) ? true : lua_toboolean(L, 4); + p.fade_in = opt(L, 5, 0); + AudioHandle v = e.mixer().stream(src, p); + if (v && e.current_scene()) e.current_scene()->voices.push_back(v); + lua_pushinteger(L, v.bits); + return 1; +} +AudioHandle voice(lua_State* L, int i) { return AudioHandle{uint32_t(luaL_checkinteger(L, i))}; } +int audio_stop(lua_State* L) { lua_pushboolean(L, E(L).mixer().stop(voice(L, 2), opt(L, 3, 0))); return 1; } +int audio_pause(lua_State* L) { lua_pushboolean(L, E(L).mixer().pause(voice(L, 2))); return 1; } +int audio_resume(lua_State* L) { lua_pushboolean(L, E(L).mixer().resume(voice(L, 2))); return 1; } +int audio_fade(lua_State* L) { lua_pushboolean(L, E(L).mixer().fade(voice(L, 2), num(L, 3), num(L, 4))); return 1; } +int audio_playing(lua_State* L) { lua_pushboolean(L, E(L).mixer().playing(voice(L, 2))); return 1; } +int audio_set_bus_volume(lua_State* L) { + std::string bus = luaL_checkstring(L, 2); + Bus b = bus == "music" ? Bus::Music : bus == "sfx" ? Bus::Sfx : Bus::Master; + E(L).mixer().set_bus_volume(b, num(L, 3)); + return 0; +} + +// ------------------------------------------------------------------------------ input +int in_pressed(lua_State* L) { lua_pushboolean(L, E(L).input().is_pressed(luaL_checkstring(L, 2))); return 1; } +int in_held(lua_State* L) { lua_pushboolean(L, E(L).input().is_held(luaL_checkstring(L, 2))); return 1; } +int in_released(lua_State* L) { lua_pushboolean(L, E(L).input().is_released(luaL_checkstring(L, 2))); return 1; } +int in_axis(lua_State* L) { lua_pushnumber(L, E(L).input().axis(luaL_checkstring(L, 2))); return 1; } +int in_buffered(lua_State* L) { lua_pushboolean(L, E(L).input().buffered(luaL_checkstring(L, 2), uint32_t(luaL_optinteger(L, 3, 6)))); return 1; } +int in_consume(lua_State* L) { E(L).input().consume_buffered(luaL_checkstring(L, 2)); return 0; } +int in_pointer(lua_State* L) { Vec2 p = E(L).input().pointer(); lua_pushnumber(L, p.x); lua_pushnumber(L, p.y); return 2; } +uint16_t key_code(const std::string& n) { + static const std::map keys = { + {"space", key::Space}, {"left", key::Left}, {"right", key::Right}, {"up", key::Up}, {"down", key::Down}, + {"e", key::E}, {"i", key::I}, {"a", key::A}, {"d", key::D}, {"w", key::W}, {"s", key::S}, {"r", key::R}, {"p", key::P}, + {"enter", key::Enter}, {"escape", key::Escape}, {"f1", key::F1}, {"f2", key::F2}, {"f3", key::F3}, + {"f5", key::F5}, {"f9", key::F9}, {"shift", key::LShift}, {"mouse_left", key::MouseLeft}, + {"pad_a", key::PadA}, {"pad_b", key::PadB}, {"pad_x", key::PadX}, {"pad_y", key::PadY}, {"pad_start", key::PadStart}, + {"pad_left", key::PadLeft}, {"pad_right", key::PadRight}, {"pad_up", key::PadUp}, {"pad_down", key::PadDown}, + {"pad_left_x", key::PadAxisLeftX}, {"pad_left_y", key::PadAxisLeftY}, {"touch", key::Touch0}}; + auto it = keys.find(n); + return it == keys.end() ? 0 : it->second; +} +int in_bind(lua_State* L) { + const char* action = luaL_checkstring(L, 2); + for (int i = 3; i <= lua_gettop(L); i++) { + uint16_t c = key_code(luaL_checkstring(L, i)); + if (!c) return luaL_error(L, "unknown key '%s'", lua_tostring(L, i)); + E(L).input().bind(action, c); + } + return 0; +} +int in_bind_axis(lua_State* L) { + uint16_t neg = key_code(luaL_checkstring(L, 3)), pos = key_code(luaL_checkstring(L, 4)); + uint16_t analog = lua_isstring(L, 5) ? key_code(lua_tostring(L, 5)) : 0; + if (!neg || !pos) return luaL_error(L, "unknown key in axis binding"); + E(L).input().bind_axis(luaL_checkstring(L, 2), neg, pos, analog); + return 0; +} + +// ------------------------------------------------------------------------------ camera / ui +int cam_set(lua_State* L) { + Camera& c = E(L).camera(); + c.position = {num(L, 2), num(L, 3)}; + if (!lua_isnoneornil(L, 4)) c.zoom = num(L, 4); + return 0; +} +int cam_get(lua_State* L) { + const Camera& c = E(L).camera(); + lua_pushnumber(L, c.position.x); lua_pushnumber(L, c.position.y); lua_pushnumber(L, c.zoom); + return 3; +} +void require_render(lua_State* L) { + if (!E(L).in_render_phase()) luaL_error(L, "ui calls are only valid inside render()"); +} +Color color_args(lua_State* L, int i) { + return {uint8_t(luaL_optinteger(L, i, 255)), uint8_t(luaL_optinteger(L, i + 1, 255)), uint8_t(luaL_optinteger(L, i + 2, 255)), uint8_t(luaL_optinteger(L, i + 3, 255))}; +} +int ui_text(lua_State* L) { + require_render(L); + E(L).font().draw(E(L).renderer(), luaL_checkstring(L, 2), {num(L, 3), num(L, 4)}, opt(L, 5, 2), color_args(L, 6), 1000); + return 0; +} +int ui_rect(lua_State* L) { + require_render(L); + E(L).renderer().fill_screen_rect({num(L, 2), num(L, 3), num(L, 4), num(L, 5)}, color_args(L, 6), 999); + return 0; +} +int ui_image(lua_State* L) { + require_render(L); + const char* name = luaL_checkstring(L, 2); + const TextureAsset* tex = E(L).texture(name); + if (!tex) return luaL_error(L, "image '%s' could not be loaded", name); + E(L).renderer().screen_rect(tex->texture.bits, {0, 0, float(tex->width), float(tex->height)}, + {num(L, 3), num(L, 4), num(L, 5), num(L, 6)}, color_args(L, 7), int16_t(luaL_optinteger(L, 11, 998))); + return 0; +} +int ui_width(lua_State* L) { lua_pushnumber(L, E(L).font().width(luaL_checkstring(L, 2), opt(L, 3, 2))); return 1; } +int ui_screen(lua_State* L) { lua_pushinteger(L, E(L).config().width); lua_pushinteger(L, E(L).config().height); return 2; } + +// ------------------------------------------------------------------------------ timer / scene / engine +int timer_after(lua_State* L) { E(L).add_timer(luaL_checknumber(L, 1), false, luaL_checkstring(L, 2)); return 0; } +int timer_every(lua_State* L) { E(L).add_timer(luaL_checknumber(L, 1), true, luaL_checkstring(L, 2)); return 0; } +int scene_transition(lua_State* L) { + // Deferred to the end of the gameplay stage: never tear down a scene from inside its own callback. + E(L).request_transition(luaL_checkstring(L, 1)); + return 0; +} +int scene_state(lua_State* L) { + // The active scene's persistent state table (read-only inspection for tools and tests). + const Scene* s = E(L).active_scene(); + if (!s || s->lua_ref < 0) { lua_pushnil(L); return 1; } + lua_rawgeti(L, LUA_REGISTRYINDEX, s->lua_ref); + lua_getfield(L, -1, "state"); + return 1; +} +int scene_current(lua_State* L) { const Scene* s = E(L).active_scene(); lua_pushstring(L, s ? s->name.c_str() : ""); return 1; } +int engine_tick(lua_State* L) { lua_pushinteger(L, lua_Integer(E(L).sim_clock().tick)); return 1; } +int engine_time(lua_State* L) { lua_pushnumber(L, E(L).sim_clock().seconds()); return 1; } +int engine_quit(lua_State* L) { E(L).request_quit(); return 0; } +int engine_hash(lua_State* L) { + char buf[20]; + std::snprintf(buf, sizeof buf, "%016llx", static_cast(E(L).state_hash())); + lua_pushstring(L, buf); + return 1; +} +int engine_stats(lua_State* L) { + Engine& e = E(L); + lua_createtable(L, 0, 6); + lua_pushinteger(L, e.world().alive()); lua_setfield(L, -2, "entities"); + lua_pushinteger(L, e.physics().stats.awake); lua_setfield(L, -2, "awake_bodies"); + lua_pushinteger(L, lua_Integer(e.lua().bytes())); lua_setfield(L, -2, "lua_bytes"); + lua_pushinteger(L, e.mixer().active_voices()); lua_setfield(L, -2, "voices"); + lua_pushinteger(L, e.renderer().last_frame_stats().batches); lua_setfield(L, -2, "batches"); + lua_pushnumber(L, e.render_clock().frame_ms); lua_setfield(L, -2, "frame_ms"); + return 1; +} +int log_fn(lua_State* L) { + std::string out; + for (int i = 1; i <= lua_gettop(L); i++) { if (i > 1) out += " "; out += luaL_tolstring(L, i, nullptr); lua_pop(L, 1); } + E(L).script_log(out); + return 0; +} +int save_state_fn(lua_State* L) { E(L).request_save(luaL_optstring(L, 1, "")); lua_pushboolean(L, 1); return 1; } +int load_state_fn(lua_State* L) { E(L).request_load(luaL_optstring(L, 1, "")); lua_pushboolean(L, 1); return 1; } + +// ------------------------------------------------------------------------------ gc +int gc_step(lua_State* L) { E(L).lua().gc_step(); return 0; } +int gc_budget(lua_State* L) { if (!lua_isnoneornil(L, 1)) E(L).lua().gc_budget(int(luaL_checkinteger(L, 1))); lua_pushinteger(L, E(L).lua().gc_budget_kb()); return 1; } +int gc_pause(lua_State* L) { E(L).lua().gc_pause(); return 0; } +int gc_resume(lua_State* L) { E(L).lua().gc_resume(); return 0; } +int gc_collect(lua_State* L) { E(L).lua().gc_collect(); return 0; } +int gc_bytes(lua_State* L) { lua_pushinteger(L, lua_Integer(E(L).lua().bytes())); return 1; } + +// ------------------------------------------------------------------------------ animation / map +int anim_define(lua_State* L) { + luaL_checktype(L, 1, LUA_TTABLE); + AnimationClip c; + lua_getfield(L, 1, "name"); c.name = luaL_checkstring(L, -1); lua_pop(L, 1); + lua_getfield(L, 1, "mode"); + std::string mode = lua_isstring(L, -1) ? lua_tostring(L, -1) : "loop"; + lua_pop(L, 1); + c.mode = mode == "once" ? PlayMode::Once : mode == "pingpong" ? PlayMode::PingPong : PlayMode::Loop; + lua_getfield(L, 1, "texture"); + const TextureAsset* tex = lua_isstring(L, -1) ? E(L).texture(lua_tostring(L, -1)) : nullptr; + lua_pop(L, 1); + lua_getfield(L, 1, "frames"); + if (lua_istable(L, -1)) { + if (!tex) return luaL_error(L, "animation '%s' has frames but no texture", c.name.c_str()); + for (int i = 1; i <= int(lua_rawlen(L, -1)); i++) { + lua_rawgeti(L, -1, i); + lua_rawgeti(L, -1, 1); lua_rawgeti(L, -2, 2); + const char* region = luaL_checkstring(L, -2); + int r = tex->atlas.find(region); + if (r < 0) return luaL_error(L, "animation '%s': unknown atlas region '%s'", c.name.c_str(), region); + c.frames.push_back({uint32_t(r), float(luaL_checknumber(L, -1))}); + lua_pop(L, 3); + } + } + lua_pop(L, 1); + lua_getfield(L, 1, "tracks"); + if (lua_istable(L, -1)) { + lua_pushnil(L); + while (lua_next(L, -2)) { + Track t; + t.property = luaL_checkstring(L, -2); + for (int i = 1; i <= int(lua_rawlen(L, -1)); i++) { + lua_rawgeti(L, -1, i); + lua_rawgeti(L, -1, 1); lua_rawgeti(L, -2, 2); + t.keys.push_back({float(luaL_checknumber(L, -2)), float(luaL_checknumber(L, -1))}); + lua_pop(L, 3); + } + std::sort(t.keys.begin(), t.keys.end(), [](const Keyframe& a, const Keyframe& b) { return a.time < b.time; }); + c.tracks.push_back(t); + lua_pop(L, 1); + } + } + lua_pop(L, 1); + E(L).animation().add_clip(c); + return 0; +} +int map_load(lua_State* L) { + AssetHandle h = scene_asset(L, AssetType::Map, luaL_checkstring(L, 1)); + const TileMap& m = E(L).assets().get(h)->map; + lua_createtable(L, 0, 4); + lua_pushinteger(L, m.width); lua_setfield(L, -2, "width"); + lua_pushinteger(L, m.height); lua_setfield(L, -2, "height"); + lua_pushnumber(L, m.tile_size); lua_setfield(L, -2, "tile_size"); + lua_createtable(L, m.height, 0); + for (int i = 0; i < m.height; i++) { lua_pushstring(L, m.rows[size_t(i)].c_str()); lua_rawseti(L, -2, i + 1); } + lua_setfield(L, -2, "rows"); + return 1; +} + +// ------------------------------------------------------------------------------ buffer / kernel +LuaBuffer* check_buffer(lua_State* L, int i) { + auto* b = static_cast(luaL_checkudata(L, i, kBufferMeta)); + if (!E(L).compute().buffer_valid(BufferHandle{b->bits})) luaL_error(L, "stale buffer handle"); + return b; +} +int buffer_create(lua_State* L) { + lua_Integer n = luaL_checkinteger(L, 1); + if (n <= 0 || n > (1 << 24)) return luaL_error(L, "buffer size out of range"); + bool is_int = std::strcmp(luaL_optstring(L, 2, "float"), "int") == 0; + BufferHandle h = E(L).compute().buffer_create(uint32_t(n) * 4); + if (!h) return luaL_error(L, "out of kernel memory"); + if (Scene* s = E(L).current_scene()) s->buffers.push_back(h); + auto* b = static_cast(lua_newuserdatauv(L, sizeof(LuaBuffer), 0)); + *b = {h.bits, is_int}; + luaL_setmetatable(L, kBufferMeta); + return 1; +} +int buffer_upload(lua_State* L) { + LuaBuffer* b = check_buffer(L, 1); + luaL_checktype(L, 2, LUA_TTABLE); + uint32_t offset = uint32_t(luaL_optinteger(L, 3, 0)); + uint32_t n = uint32_t(lua_rawlen(L, 2)); + uint32_t cap = E(L).compute().buffer_size(BufferHandle{b->bits}) / 4; + if (offset + n > cap) return luaL_error(L, "upload of %d elements at %d overflows buffer of %d", int(n), int(offset), int(cap)); + std::vector tmp(n); + for (uint32_t i = 0; i < n; i++) { + lua_rawgeti(L, 2, lua_Integer(i) + 1); + if (b->is_int) { int32_t v = int32_t(lua_tointeger(L, -1)); std::memcpy(&tmp[i], &v, 4); } + else { float v = float(lua_tonumber(L, -1)); std::memcpy(&tmp[i], &v, 4); } + lua_pop(L, 1); + } + E(L).compute().buffer_upload(BufferHandle{b->bits}, tmp.data(), n * 4, offset * 4); + return 0; +} +int buffer_download(lua_State* L) { + LuaBuffer* b = check_buffer(L, 1); + uint32_t cap = E(L).compute().buffer_size(BufferHandle{b->bits}) / 4; + uint32_t n = uint32_t(luaL_optinteger(L, 2, cap)); + if (n > cap) n = cap; + std::vector tmp(n); + E(L).compute().buffer_download(BufferHandle{b->bits}, tmp.data(), n * 4); + lua_createtable(L, int(n), 0); + for (uint32_t i = 0; i < n; i++) { + if (b->is_int) { int32_t v; std::memcpy(&v, &tmp[i], 4); lua_pushinteger(L, v); } + else { float v; std::memcpy(&v, &tmp[i], 4); lua_pushnumber(L, v); } + lua_rawseti(L, -2, lua_Integer(i) + 1); + } + return 1; +} +int buffer_destroy(lua_State* L) { + LuaBuffer* b = check_buffer(L, 1); + E(L).compute().buffer_destroy(BufferHandle{b->bits}); + if (Scene* s = E(L).current_scene()) s->buffers.erase(std::remove(s->buffers.begin(), s->buffers.end(), BufferHandle{b->bits}), s->buffers.end()); + return 0; +} +int buffer_size(lua_State* L) { lua_pushinteger(L, E(L).compute().buffer_size(BufferHandle{check_buffer(L, 1)->bits}) / 4); return 1; } + +int kernel_compile(lua_State* L) { + std::string src = luaL_checkstring(L, 1); + if (src.find("__global__") == std::string::npos) { // an asset name, e.g. "kernels/particles" + AssetHandle h = scene_asset(L, AssetType::Kernel, src); + src = E(L).assets().get(h)->text; + } + kernel::CompiledKernel k = E(L).compute().compile(src); + lua_createtable(L, 0, 6); + lua_pushboolean(L, k.ok); lua_setfield(L, -2, "ok"); + lua_pushstring(L, k.error.c_str()); lua_setfield(L, -2, "error"); + lua_pushstring(L, k.name.c_str()); lua_setfield(L, -2, "name"); + lua_pushstring(L, k.ir_text.c_str()); lua_setfield(L, -2, "ir"); + lua_pushinteger(L, lua_Integer(k.wasm.size())); lua_setfield(L, -2, "wasm_bytes"); + lua_pushstring(L, src.c_str()); lua_setfield(L, -2, "source"); + return 1; +} +int kernel_load(lua_State* L) { + luaL_checktype(L, 1, LUA_TTABLE); + lua_getfield(L, 1, "source"); + std::string src = luaL_checkstring(L, -1); + lua_pop(L, 1); + std::string err; + KernelHandle h = E(L).compute().compile_and_load(src, err); + if (!h) return luaL_error(L, "kernel load failed: %s", err.c_str()); + if (Scene* s = E(L).current_scene()) s->kernels.push_back(h); + *static_cast(lua_newuserdatauv(L, sizeof(uint32_t), 0)) = h.bits; + luaL_setmetatable(L, kKernelMeta); + return 1; +} +int kernel_dispatch(lua_State* L) { + KernelHandle k{*static_cast(luaL_checkudata(L, 1, kKernelMeta))}; + if (!E(L).compute().kernel_valid(k)) return luaL_error(L, "stale kernel handle"); + uint32_t grid = uint32_t(luaL_checkinteger(L, 2)), block = uint32_t(luaL_checkinteger(L, 3)); + std::vector args; + for (int i = 4; i <= lua_gettop(L); i++) { + if (luaL_testudata(L, i, kBufferMeta)) args.push_back(KernelArg::buf(BufferHandle{check_buffer(L, i)->bits})); + else if (lua_isinteger(L, i)) args.push_back(KernelArg::integer(int32_t(lua_tointeger(L, i)))); + else args.push_back(KernelArg::real(float(luaL_checknumber(L, i)))); + } + DispatchResult r = E(L).compute().dispatch(k, grid, block, args); + if (!r.ok) return luaL_error(L, "kernel dispatch failed: %s", r.error.c_str()); + lua_pushinteger(L, lua_Integer(r.instructions)); + return 1; +} + +void make_lib(lua_State* L, Engine& e, const char* global, const luaL_Reg* fns) { + lua_newtable(L); + lua_pushlightuserdata(L, &e); + luaL_setfuncs(L, fns, 1); + lua_setglobal(L, global); +} +} // namespace + +void register_bindings(Engine& engine) { + lua_State* L = engine.lua().L(); + + luaL_newmetatable(L, kEntityMeta); + static const luaL_Reg entity_methods[] = { + {"set_position", ent_set_position}, {"position", ent_position}, {"set_velocity", ent_set_velocity}, {"velocity", ent_velocity}, + {"apply_impulse", ent_apply_impulse}, {"set_rotation", ent_set_rotation}, {"rotation", ent_rotation}, + {"set_animation", ent_set_animation}, {"animation", ent_animation}, {"set_flip", ent_set_flip}, {"set_visible", ent_set_visible}, + {"set_tint", ent_set_tint}, {"name", ent_name}, {"valid", ent_valid}, {"id", ent_id}, {"destroy", ent_destroy}, {nullptr, nullptr}}; + lua_newtable(L); + lua_pushlightuserdata(L, &engine); + luaL_setfuncs(L, entity_methods, 1); + lua_setfield(L, -2, "__index"); + lua_pushlightuserdata(L, &engine); lua_pushcclosure(L, ent_eq, 1); lua_setfield(L, -2, "__eq"); + lua_pushlightuserdata(L, &engine); lua_pushcclosure(L, ent_tostring, 1); lua_setfield(L, -2, "__tostring"); + lua_pop(L, 1); + luaL_newmetatable(L, kBufferMeta); lua_pop(L, 1); + luaL_newmetatable(L, kKernelMeta); lua_pop(L, 1); + + static const luaL_Reg world_fns[] = {{"spawn", world_spawn}, {"destroy", world_destroy}, {"find", world_find}, {"count", world_count}, {nullptr, nullptr}}; + static const luaL_Reg physics_fns[] = {{"apply_force", phys_apply_force}, {"apply_impulse", phys_apply_impulse}, {"raycast", phys_raycast}, + {"set_gravity", phys_set_gravity}, {"add_static_box", phys_add_static_box}, {"is_awake", phys_is_awake}, {nullptr, nullptr}}; + static const luaL_Reg audio_fns[] = {{"play", audio_play}, {"stream", audio_stream}, {"stop", audio_stop}, {"pause", audio_pause}, {"resume", audio_resume}, + {"fade", audio_fade}, {"playing", audio_playing}, {"set_bus_volume", audio_set_bus_volume}, {nullptr, nullptr}}; + static const luaL_Reg input_fns[] = {{"is_pressed", in_pressed}, {"is_held", in_held}, {"is_released", in_released}, {"axis", in_axis}, + {"buffered", in_buffered}, {"consume", in_consume}, {"pointer", in_pointer}, {"bind", in_bind}, {"bind_axis", in_bind_axis}, {nullptr, nullptr}}; + static const luaL_Reg camera_fns[] = {{"set", cam_set}, {"get", cam_get}, {nullptr, nullptr}}; + static const luaL_Reg ui_fns[] = {{"text", ui_text}, {"image", ui_image}, {"rect", ui_rect}, {"width", ui_width}, {"screen", ui_screen}, {nullptr, nullptr}}; + static const luaL_Reg timer_fns[] = {{"after", timer_after}, {"every", timer_every}, {nullptr, nullptr}}; + static const luaL_Reg scene_fns[] = {{"transition", scene_transition}, {"current", scene_current}, {"state", scene_state}, {nullptr, nullptr}}; + static const luaL_Reg engine_fns[] = {{"tick", engine_tick}, {"time", engine_time}, {"quit", engine_quit}, {"state_hash", engine_hash}, {"stats", engine_stats}, {nullptr, nullptr}}; + static const luaL_Reg gc_fns[] = {{"step", gc_step}, {"budget", gc_budget}, {"pause", gc_pause}, {"resume", gc_resume}, {"collect", gc_collect}, {"bytes", gc_bytes}, {nullptr, nullptr}}; + static const luaL_Reg anim_fns[] = {{"define", anim_define}, {nullptr, nullptr}}; + static const luaL_Reg map_fns[] = {{"load", map_load}, {nullptr, nullptr}}; + static const luaL_Reg buffer_fns[] = {{"create", buffer_create}, {"upload", buffer_upload}, {"download", buffer_download}, {"destroy", buffer_destroy}, {"size", buffer_size}, {nullptr, nullptr}}; + static const luaL_Reg kernel_fns[] = {{"compile", kernel_compile}, {"load", kernel_load}, {"dispatch", kernel_dispatch}, {nullptr, nullptr}}; + make_lib(L, engine, "world", world_fns); + make_lib(L, engine, "physics", physics_fns); + make_lib(L, engine, "audio", audio_fns); + make_lib(L, engine, "input", input_fns); + make_lib(L, engine, "camera", camera_fns); + make_lib(L, engine, "ui", ui_fns); + make_lib(L, engine, "timer", timer_fns); + make_lib(L, engine, "scene", scene_fns); + make_lib(L, engine, "engine", engine_fns); + make_lib(L, engine, "gc", gc_fns); + make_lib(L, engine, "animation", anim_fns); + make_lib(L, engine, "map", map_fns); + make_lib(L, engine, "buffer", buffer_fns); + make_lib(L, engine, "kernel", kernel_fns); + // gc_step() etc. also as globals, matching the engine-level API names. + for (auto* r = gc_fns; r->name; r++) { + lua_pushlightuserdata(L, &engine); + lua_pushcclosure(L, r->func, 1); + lua_setglobal(L, (std::string("gc_") + r->name).c_str()); + } + lua_pushlightuserdata(L, &engine); lua_pushcclosure(L, log_fn, 1); lua_setglobal(L, "log"); + lua_pushlightuserdata(L, &engine); lua_pushcclosure(L, save_state_fn, 1); lua_setglobal(L, "save_state"); + lua_pushlightuserdata(L, &engine); lua_pushcclosure(L, load_state_fn, 1); lua_setglobal(L, "load_state"); + lua_newtable(L); + lua_setglobal(L, "game"); // persistent gameplay state, serialized in save states +} + +} // namespace unify diff --git a/unify/engine/runtime/engine.cpp b/unify/engine/runtime/engine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea085d0102dfdce41d7227395b4a346af4d82eca --- /dev/null +++ b/unify/engine/runtime/engine.cpp @@ -0,0 +1,834 @@ +#include "engine.h" +#include "../serialization/stream.h" +#include +#include +#include +#include +#include + +namespace unify { + +const char* stage_name(Stage s) { + static const char* names[] = {"INPUT", "INPUT BUFFER", "FIXED SIMULATION", "PHYSICS", "GAMEPLAY / LUA", "ANIMATION", "AUDIO", "RENDER PREPARATION", "RENDER", "PRESENT"}; + return s < Stage::Count ? names[size_t(s)] : "?"; +} + +Engine::Engine(Backend& backend, EngineConfig config) + : backend_(backend), config_(std::move(config)), mixer_(44100, 64), target_(config_.width, config_.height), rng_(config_.seed) { + sim_.ticks_per_second = config_.tick_rate; + assets_ = std::make_unique(backend_.render_device(), config_.asset_root); + renderer_ = std::make_unique(backend_.render_device()); + lua_ = std::make_unique(config_.lua_memory_limit); + lua_->gc_budget(config_.lua_gc_budget_kb); + // Entity destruction releases the subsystem resources it owns. + world_.add_destroy_hook([this](EntityHandle e) { + if (BodyC* b = world_.bodies.get(e)) physics_.destroy_body(PhysicsBodyHandle{b->body}); + if (AnimatorC* a = world_.animators.get(e)) anim_.destroy_player(a->player); + if (SpriteC* s = world_.sprites.get(e)) (void)s; // textures are owned by scenes, not entities + }); + physics_.gravity = {0, -30}; + trace_.reserve(64); + events_scratch_.reserve(512); +} + +Engine::~Engine() { + streamer_.stop(); + backend_.audio_device().stop(); + mixer_.stop_all(); + while (!scenes_.empty()) { unload_scene(scenes_.back()); scenes_.pop_back(); } +} + +bool Engine::boot(std::string& error) { + if (!backend_.init(config_, error)) return false; + font_ = BitmapFont::build(); + font_.texture = backend_.render_device().create_texture(font_.image).bits; + if (!backend_.audio_device().start(mixer_)) UNIFY_LOG_WARN("AUDIO", "audio device '%s' failed to start; continuing silent", backend_.audio_device().name()); + streamer_.start(mixer_); + lua_->sandbox(&rng_); + register_bindings(*this); + UNIFY_LOG_INFO("BOOT", "%s on %s backend, %dx%d, %u Hz simulation", kEngineVersion, backend_.name(), config_.width, config_.height, config_.tick_rate); + if (!transition(config_.boot_scene, error)) return false; + sim_origin_ns_ = backend_.now_ns(); + booted_ = true; + return true; +} + +void Engine::script_log(const std::string& s) { + script_log_.push_back(s); + if (script_log_.size() > 256) script_log_.erase(script_log_.begin()); + UNIFY_LOG_INFO("LUA", "%s", s.c_str()); +} + +void Engine::report_script_error(const std::string& where) { + std::string msg = where + ": " + lua_->last_error(); + script_log("ERROR " + msg); + UNIFY_LOG_ERROR("LUA", "%s", msg.c_str()); +} + +// ------------------------------------------------------------------------------ scheduler + +void Engine::frame() { + auto t0 = std::chrono::steady_clock::now(); + trace_.clear(); + mark(Stage::Input); + backend_.poll(input_, quit_); + const uint64_t now = backend_.now_ns(); + const uint64_t dt_ns = 1000000000ull / sim_.ticks_per_second; + uint32_t ran = 0; + while (sim_origin_ns_ + (sim_.tick + 1) * 1000000000ull / sim_.ticks_per_second <= now && ran < uint32_t(config_.max_ticks_per_frame) && !quit_) { + tick(); + ran++; + } + if (ran == uint32_t(config_.max_ticks_per_frame)) { + // Too far behind (breakpoint, stall): drop the backlog instead of spiralling. + sim_origin_ns_ = now - sim_.tick * 1000000000ull / sim_.ticks_per_second; + } + stats_.ticks_this_frame = ran; + uint64_t tick_start = sim_origin_ns_ + sim_.tick * 1000000000ull / sim_.ticks_per_second; + float alpha = now > tick_start ? clampf(float(double(now - tick_start) / double(dt_ns)), 0, 1) : 0; + render(alpha); + render_clock_.frame_ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); +} + +int Engine::run() { + while (!quit_) frame(); + return 0; +} + +void Engine::tick_impl(const InputFrame* replay) { + if (!trace_.empty() && trace_.back() == Stage::Present) trace_.clear(); + uint64_t heap0 = HeapStats::allocations.load(); + auto stage_start = std::chrono::steady_clock::now(); + auto lap = [&](Stage s) { + auto t = std::chrono::steady_clock::now(); + stats_.stage_ms[size_t(s)] = std::chrono::duration(t - stage_start).count(); + stage_start = t; + }; + const float dt = sim_.dtf(); + + mark(Stage::InputBuffer); + if (replay) input_.apply_frame(*replay); + else input_.consume_tick(sim_.tick, sim_origin_ns_ + sim_.tick_end_ns(sim_.tick)); + lap(Stage::InputBuffer); + + mark(Stage::FixedSimulation); + for (size_t i = 0; i < world_.transforms.size(); i++) world_.transforms.at(i).previous = world_.transforms.at(i).current; + lap(Stage::FixedSimulation); + + mark(Stage::Physics); + physics_.step(dt); + sync_transforms_from_physics(); + lap(Stage::Physics); + + mark(Stage::Gameplay); + dispatch_physics_events(); + fire_timers(); + lua_pushnumber(lua_->L(), dt); + if (!call_scene("update", 1)) report_script_error("scene update"); + if (!pending_transition_.empty()) { + std::string target = pending_transition_, err; + pending_transition_.clear(); + if (!transition(target, err)) UNIFY_LOG_ERROR("SCENE", "transition to '%s' failed: %s", target.c_str(), err.c_str()); + } + lua_->gc_step(); // bounded incremental GC every tick: no unpredictable full-collection stalls + lap(Stage::Gameplay); + + mark(Stage::Animation); + anim_.advance(dt); + lap(Stage::Animation); + + mark(Stage::Audio); + for (auto& s : scenes_) // forget voices that finished on the audio thread + s.voices.erase(std::remove_if(s.voices.begin(), s.voices.end(), [&](AudioHandle h) { return !mixer_.alive(h); }), s.voices.end()); + lap(Stage::Audio); + + sim_.tick++; + stats_.heap_allocs_last_tick = HeapStats::allocations.load() - heap0; + stats_.lua_bytes = lua_->bytes(); + process_pending_state_ops(); +} + +void Engine::render(float alpha) { + auto t0 = std::chrono::steady_clock::now(); + mark(Stage::RenderPrep); + render_clock_.alpha = alpha; + render_clock_.frame++; + render_clock_.seconds = double(backend_.now_ns()) * 1e-9; + frame_alloc_.reset(); + renderer_->begin(target_, camera_, {}); + for (size_t i = 0; i < world_.sprites.size(); i++) { + const SpriteC& s = world_.sprites.at(i); + if (!s.visible) continue; + EntityHandle e = world_.sprites.owner(i); + const TransformC* t = world_.transforms.get(e); + if (!t) continue; + // Interpolate between the last two simulation states: smooth at any frame rate. + Vec2 pos = lerp(t->previous.position, t->current.position, alpha); + float rot = t->previous.rotation + (t->current.rotation - t->previous.rotation) * alpha; + const AssetRecord* tex = assets_->get(AssetHandle{s.texture}); + uint32_t region = s.atlas_region; + Vec2 size = s.size; + Color tint = s.tint; + if (const AnimatorC* a = world_.animators.get(e)) { + if (uint32_t r = anim_.sprite_region(a->player)) region = r; + size.x *= anim_.value(a->player, "scale_x", 1); + size.y *= anim_.value(a->player, "scale_y", 1); + rot += anim_.value(a->player, "rotation", 0); + tint.a = uint8_t(clampf(float(tint.a) * anim_.value(a->player, "alpha", 1), 0, 255)); + } + RectF src{0, 0, 1, 1}; + uint32_t device_tex = 0; + if (tex && tex->type == AssetType::Texture) { + device_tex = tex->texture.texture.bits; + const auto& regs = tex->texture.atlas.regions; + RectI rr = regs[region < regs.size() ? region : 0].rect; + src = {float(rr.x), float(rr.y), float(rr.w), float(rr.h)}; + } + renderer_->sprite(device_tex, src, pos, size, rot, tint, s.layer, s.depth, BlendMode::Alpha, s.flip_x, s.pivot); + } + rendering_ = true; // ui:* calls are only valid here + if (!call_scene("render")) report_script_error("scene render"); + rendering_ = false; + stats_.stage_ms[size_t(Stage::RenderPrep)] = std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + + mark(Stage::Render); + auto t1 = std::chrono::steady_clock::now(); + renderer_->end(); + stats_.stage_ms[size_t(Stage::Render)] = std::chrono::duration(std::chrono::steady_clock::now() - t1).count(); + + mark(Stage::Present); + backend_.present(target_); +} + +void Engine::sync_transforms_from_physics() { + for (size_t i = 0; i < world_.bodies.size(); i++) { + EntityHandle e = world_.bodies.owner(i); + const Body* b = physics_.get(PhysicsBodyHandle{world_.bodies.at(i).body}); + TransformC* t = world_.transforms.get(e); + if (!b || !t) continue; + // Physics has already contained its own failures; only finite poses reach the ECS. + if (!finite(b->position) || !std::isfinite(b->angle)) continue; + t->current.position = b->position; + t->current.rotation = b->angle; + } +} + +static void push_entity(lua_State* L, uint32_t bits) { + if (!bits) { lua_pushnil(L); return; } + *static_cast(lua_newuserdatauv(L, sizeof(uint32_t), 0)) = bits; + luaL_setmetatable(L, kEntityMeta); +} + +void Engine::dispatch_physics_events() { + static const char* names[] = {"begin", "persist", "end", "trigger_begin", "trigger_end"}; + // Copy first: gameplay may destroy bodies from inside a callback, which appends End + // events to the physics event list and would invalidate a live iterator. + events_scratch_ = physics_.events(); + for (const ContactEvent& ev : events_scratch_) { + if (ev.type == ContactEventType::Persist) continue; // high-volume; gameplay polls contacts via raycasts instead + lua_State* L = lua_->L(); + push_entity(L, world_.valid(EntityHandle{ev.user_a}) ? ev.user_a : 0); + push_entity(L, world_.valid(EntityHandle{ev.user_b}) ? ev.user_b : 0); + lua_pushstring(L, names[int(ev.type)]); + lua_pushnumber(L, ev.normal.x); + lua_pushnumber(L, ev.normal.y); + lua_pushnumber(L, ev.impulse); + if (!call_scene("on_contact", 6)) report_script_error("scene on_contact"); + } +} + +void Engine::add_timer(double seconds, bool repeat, const std::string& name) { + uint64_t ticks = std::max(1, uint64_t(seconds * sim_.ticks_per_second + 0.5)); + timers_.push_back({sim_.tick + ticks, repeat ? ticks : 0, name, current_scene() ? current_scene()->id : uint16_t(0)}); +} + +void Engine::fire_timers() { + for (size_t i = 0; i < timers_.size();) { + Timer& t = timers_[i]; + if (t.fire_tick > sim_.tick) { i++; continue; } + std::string name = t.name; + if (t.interval_ticks) { t.fire_tick += t.interval_ticks; i++; } + else timers_.erase(timers_.begin() + long(i)); + lua_pushstring(lua_->L(), name.c_str()); + if (!call_scene("on_timer", 1)) report_script_error("scene on_timer"); + } +} + +// ------------------------------------------------------------------------------ scenes + +bool Engine::call_scene(const char* fn, int nargs) { + lua_State* L = lua_->L(); + Scene* s = current_scene(); + if (!s || s->lua_ref < 0) { lua_pop(L, nargs); return true; } + lua_rawgeti(L, LUA_REGISTRYINDEX, s->lua_ref); + lua_getfield(L, -1, fn); + if (!lua_isfunction(L, -1)) { lua_pop(L, 2 + nargs); return true; } + lua_insert(L, -(nargs + 2)); // fn below args + lua_insert(L, -(nargs + 1)); // scene table as first arg (method call) + if (lua_pcall(L, nargs + 1, 0, 0) != LUA_OK) { + const char* msg = lua_tostring(L, -1); + lua_->set_error(msg ? msg : "(non-string error)"); + lua_pop(L, 1); + return false; + } + return true; +} + +bool Engine::load_scene_script(Scene& s, std::string& error) { + s.script = assets_->load(AssetType::Script, "scenes/" + s.name); + if (!s.script) { error = "scene script 'scenes/" + s.name + "' not found"; return false; } + const AssetRecord* rec = assets_->get(s.script); + if (!lua_->run(rec->text, rec->path, 1)) { error = lua_->last_error(); return false; } + lua_State* L = lua_->L(); + if (!lua_istable(L, -1)) { lua_pop(L, 1); error = "scene script must return a table"; return false; } + lua_pushstring(L, s.name.c_str()); + lua_setfield(L, -2, "name"); + s.lua_ref = luaL_ref(L, LUA_REGISTRYINDEX); + return true; +} + +void Engine::unload_scene(Scene& s) { + // Entities owned by this scene (persistent ones have scene 0 and survive). + std::vector doomed; + world_.each_entity([&](EntityHandle e) { if (world_.info(e)->scene == s.id) doomed.push_back(e); }); + for (EntityHandle e : doomed) world_.destroy(e); + for (AudioHandle v : s.voices) mixer_.stop(v); + for (BufferHandle b : s.buffers) compute_.buffer_destroy(b); + for (KernelHandle k : s.kernels) compute_.unload(k); + for (AssetHandle a : s.assets) assets_->release(a); + if (s.script) assets_->release(s.script); + if (s.lua_ref >= 0) luaL_unref(lua_->L(), LUA_REGISTRYINDEX, s.lua_ref); + timers_.erase(std::remove_if(timers_.begin(), timers_.end(), [&](const Timer& t) { return t.scene == s.id; }), timers_.end()); + s = Scene{}; +} + +bool Engine::transition(const std::string& name, std::string& error) { + if (!scenes_.empty()) { + call_scene("unload"); + unload_scene(scenes_.back()); + scenes_.pop_back(); + } + return push_scene(name, error); +} + +bool Engine::push_scene(const std::string& name, std::string& error) { + Scene s; + s.id = next_scene_id_++; + s.name = name; + s.voices.reserve(64); // playing a sound never grows this list mid-tick + scenes_.push_back(s); + if (!load_scene_script(scenes_.back(), error)) { unload_scene(scenes_.back()); scenes_.pop_back(); return false; } + lua_->gc_collect(); // scene loads are the one place a full collection is allowed + // init(): code-level setup (bindings, animation clips); also runs after a restore. + // load(): creates the scene's world content; skipped on restore (the save provides it). + if (!call_scene("init") || !call_scene("load")) { + // A scene that fails to load is removed completely: no half-built world is left running. + error = lua_->last_error(); + report_script_error("scene load"); + unload_scene(scenes_.back()); + scenes_.pop_back(); + return false; + } + UNIFY_LOG_INFO("SCENE", "loaded '%s' (id %u)", name.c_str(), scenes_.back().id); + return true; +} + +bool Engine::pop_scene(std::string& error) { + if (scenes_.size() <= 1) { error = "cannot pop the last scene"; return false; } + call_scene("unload"); + unload_scene(scenes_.back()); + scenes_.pop_back(); + return true; +} + +ResourceCounts Engine::resources() const { + uint32_t refs = 0; + for (auto& s : scenes_) refs += s.lua_ref >= 0; + return {world_.alive(), physics_.body_count(), uint32_t(const_cast(anim_).live_players()), mixer_.active_voices(), + compute_.live_buffers(), compute_.live_kernels(), assets_->live(), const_cast(backend_).render_device().live_textures(), refs}; +} + +// ------------------------------------------------------------------------------ prefabs + +const TextureAsset* Engine::texture(const std::string& name) { + AssetHandle h = assets_->find(name); + Scene* s = current_scene(); + if (!h) { + h = assets_->load(AssetType::Texture, name); + if (!h) return nullptr; + if (s) s->assets.push_back(h); else assets_->acquire(h); + } else if (s && std::find(s->assets.begin(), s->assets.end(), h) == s->assets.end()) { + assets_->acquire(h); + s->assets.push_back(h); + } + return &assets_->get(h)->texture; +} + +static float field_num(lua_State* L, int t, const char* k, float def) { + lua_getfield(L, t, k); + float v = lua_isnumber(L, -1) ? float(lua_tonumber(L, -1)) : def; + lua_pop(L, 1); + return v; +} +static std::string field_str(lua_State* L, int t, const char* k, const std::string& def = {}) { + lua_getfield(L, t, k); + std::string v = lua_isstring(L, -1) ? lua_tostring(L, -1) : def; + lua_pop(L, 1); + return v; +} +static bool field_bool(lua_State* L, int t, const char* k, bool def) { + lua_getfield(L, t, k); + bool v = lua_isboolean(L, -1) ? lua_toboolean(L, -1) : def; + lua_pop(L, 1); + return v; +} + +const PrefabDef* Engine::prefab(const std::string& name, std::string& error) { + auto it = prefabs_.find(name); + if (it != prefabs_.end()) return &it->second; + AssetHandle h = assets_->load(AssetType::Prefab, name); + if (!h) { error = "prefab '" + name + "' not found"; return nullptr; } + std::string text = assets_->get(h)->text, path = assets_->get(h)->path; + assets_->release(h); // parsed into a PrefabDef; the source text is not kept + if (!lua_->run(text, path, 1)) { error = lua_->last_error(); return nullptr; } + lua_State* L = lua_->L(); + int t = lua_gettop(L); + if (!lua_istable(L, t)) { lua_pop(L, 1); error = "prefab must return a table"; return nullptr; } + PrefabDef d; + d.name = field_str(L, t, "name", name); + d.animation = field_str(L, t, "animation"); + d.tags = uint32_t(field_num(L, t, "tags", 0)); + lua_getfield(L, t, "sprite"); + if (lua_istable(L, -1)) { + int st = lua_gettop(L); + d.has_sprite = true; + d.texture = field_str(L, st, "texture"); + d.region = field_str(L, st, "region"); + d.sprite_size = {field_num(L, st, "w", 1), field_num(L, st, "h", 1)}; + d.layer = int16_t(field_num(L, st, "layer", 0)); + d.depth = field_num(L, st, "depth", 0); + lua_getfield(L, st, "tint"); + if (lua_istable(L, -1)) { + int tt = lua_gettop(L); + d.tint = {uint8_t(field_num(L, tt, "r", 255)), uint8_t(field_num(L, tt, "g", 255)), uint8_t(field_num(L, tt, "b", 255)), uint8_t(field_num(L, tt, "a", 255))}; + } + lua_pop(L, 1); + } + lua_pop(L, 1); + lua_getfield(L, t, "body"); + if (lua_istable(L, -1)) { + int bt = lua_gettop(L); + d.has_body = true; + BodyDef& b = d.body; + std::string type = field_str(L, bt, "type", "dynamic"); + b.type = type == "static" ? BodyType::Static : type == "kinematic" ? BodyType::Kinematic : BodyType::Dynamic; + std::string shape = field_str(L, bt, "shape", "aabb"); + float w = field_num(L, bt, "w", 1), hh = field_num(L, bt, "h", 1); + if (shape == "circle") b.shape = Shape::circle(field_num(L, bt, "r", 0.5f)); + else if (shape == "box") b.shape = Shape::box(w / 2, hh / 2); + else if (shape == "polygon") { + Vec2 pts[phys::kMaxPolygonVertices]; + int n = 0; + lua_getfield(L, bt, "points"); + if (lua_istable(L, -1)) { + for (int i = 1; i <= int(lua_rawlen(L, -1)) && n < phys::kMaxPolygonVertices; i++) { + lua_rawgeti(L, -1, i); + int pt = lua_gettop(L); + lua_rawgeti(L, pt, 1); lua_rawgeti(L, pt, 2); + pts[n++] = {float(lua_tonumber(L, -2)), float(lua_tonumber(L, -1))}; + lua_pop(L, 3); + } + } + lua_pop(L, 1); + b.shape = Shape::polygon(pts, n); + } else b.shape = Shape::aabb(w / 2, hh / 2); + b.density = field_num(L, bt, "density", 1); + b.mass = field_num(L, bt, "mass", 0); + b.friction = field_num(L, bt, "friction", 0.6f); + b.restitution = field_num(L, bt, "restitution", 0); + b.gravity_scale = field_num(L, bt, "gravity_scale", 1); + b.linear_damping = field_num(L, bt, "linear_damping", 0); + b.fixed_rotation = field_bool(L, bt, "fixed_rotation", false); + b.bullet = field_bool(L, bt, "bullet", false); + b.sensor = field_bool(L, bt, "sensor", false); + b.can_sleep = field_bool(L, bt, "can_sleep", true); + b.category = uint32_t(field_num(L, bt, "category", 1)); + b.mask = uint32_t(field_num(L, bt, "mask", 65535)); + } + lua_pop(L, 2); + return &(prefabs_[name] = d); +} + +EntityHandle Engine::instantiate(const std::string& name, Vec2 pos, bool persistent, std::string& error) { + const PrefabDef* d = prefab(name, error); + if (!d) return {}; + Scene* s = current_scene(); + EntityHandle e = world_.create(d->name, persistent || !s ? 0 : s->id); + world_.info(e)->prefab = name; + world_.info(e)->tags = d->tags; + TransformC* t = world_.transforms.get(e); + t->current.position = t->previous.position = pos; + if (d->has_sprite) { + SpriteC sp; + if (!d->texture.empty()) { + const TextureAsset* tex = texture(d->texture); + if (!tex) { world_.destroy(e); error = "texture '" + d->texture + "' not found"; return {}; } + sp.texture = assets_->find(d->texture).bits; + int r = d->region.empty() ? 0 : tex->atlas.find(d->region); + sp.atlas_region = r < 0 ? 0 : uint32_t(r); + } + sp.size = d->sprite_size; sp.layer = d->layer; sp.depth = d->depth; sp.tint = d->tint; + world_.sprites.add(e, sp); + } + if (d->has_body) { + BodyDef b = d->body; + b.position = pos; + b.user = e.bits; + world_.bodies.add(e, BodyC{physics_.create_body(b).bits}); + } + if (!d->animation.empty()) world_.animators.add(e, AnimatorC{anim_.create_player(d->animation)}); + return e; +} + +bool Engine::destroy_entity(EntityHandle e) { return world_.destroy(e); } + +// ------------------------------------------------------------------------------ input injection + +uint64_t Engine::next_tick_input_ns() const { + return sim_origin_ns_ + uint64_t(sim_.tick) * 1000000000ull / sim_.ticks_per_second + 1; +} + +void Engine::inject(uint16_t code, bool down) { + InputEvent e; + e.timestamp_ns = next_tick_input_ns(); + e.type = down ? InputEventType::ButtonDown : InputEventType::ButtonUp; + e.code = code; + input_.push(e); +} + +// ------------------------------------------------------------------------------ save states + +namespace { +void write_color(BinaryWriter& w, Color c) { w.u8(c.r); w.u8(c.g); w.u8(c.b); w.u8(c.a); } +Color read_color(BinaryReader& r) { Color c; c.r = r.u8(); c.g = r.u8(); c.b = r.u8(); c.a = r.u8(); return c; } +void write_transform(BinaryWriter& w, const Transform& t) { w.vec2(t.position); w.f32(t.rotation); w.vec2(t.scale); } +Transform read_transform(BinaryReader& r) { Transform t; t.position = r.vec2(); t.rotation = r.f32(); t.scale = r.vec2(); return t; } +} // namespace + +std::vector Engine::save_state(bool include_audio) { + BinaryWriter w; + lua_State* L = lua_->L(); + size_t sec; + + sec = w.begin_section("HEAD"); + w.str("UNIFY-SAVE"); w.u32(kSaveVersion); w.str(kEngineVersion); w.u32(sim_.ticks_per_second); w.u64(config_.seed); + w.end_section(sec); + + sec = w.begin_section("TIME"); + w.u64(sim_.tick); + w.u32(uint32_t(timers_.size())); + for (auto& t : timers_) { w.u64(t.fire_tick); w.u64(t.interval_ticks); w.str(t.name); w.u16(t.scene); } + w.end_section(sec); + + sec = w.begin_section("RNG "); + for (int i = 0; i < 4; i++) w.u32(rng_.state()[i]); + w.end_section(sec); + + sec = w.begin_section("SCEN"); + w.u16(next_scene_id_); + w.u32(uint32_t(scenes_.size())); + for (auto& s : scenes_) { + w.u16(s.id); w.str(s.name); + w.u32(uint32_t(s.assets.size())); + for (AssetHandle a : s.assets) { const AssetRecord* r = assets_->get(a); w.u8(uint8_t(r->type)); w.str(r->name); } + w.u32(uint32_t(s.buffers.size())); for (auto b : s.buffers) w.u32(b.bits); + w.u32(uint32_t(s.kernels.size())); for (auto k : s.kernels) w.u32(k.bits); + } + w.end_section(sec); + + sec = w.begin_section("ECS "); + { + auto es = world_.entity_pool().save(); + w.u32(uint32_t(es.gens.size())); + for (size_t i = 0; i < es.gens.size(); i++) { + w.u8(es.gens[i]); w.u8(es.live[i]); + if (es.live[i]) { const EntityInfo& in = world_.infos()[i]; w.str(in.name); w.str(in.prefab); w.u16(in.scene); w.u32(in.tags); } + } + w.u32(uint32_t(es.free.size())); + for (auto f : es.free) w.u32(f); + // Component pools in dense order (their order is part of the deterministic state). + w.u32(uint32_t(world_.transforms.size())); + for (size_t i = 0; i < world_.transforms.size(); i++) { + w.u32(world_.transforms.owner(i).bits); + write_transform(w, world_.transforms.at(i).current); + write_transform(w, world_.transforms.at(i).previous); + } + w.u32(uint32_t(world_.sprites.size())); + for (size_t i = 0; i < world_.sprites.size(); i++) { + const SpriteC& s = world_.sprites.at(i); + w.u32(world_.sprites.owner(i).bits); + const AssetRecord* tex = assets_->get(AssetHandle{s.texture}); + w.str(tex ? tex->name : ""); // assets by name: handles are not stable across runs + w.u32(s.atlas_region); w.vec2(s.size); w.vec2(s.pivot); write_color(w, s.tint); + w.u16(uint16_t(s.layer)); w.f32(s.depth); w.boolean(s.flip_x); w.boolean(s.visible); + } + w.u32(uint32_t(world_.bodies.size())); + for (size_t i = 0; i < world_.bodies.size(); i++) { w.u32(world_.bodies.owner(i).bits); w.u32(world_.bodies.at(i).body); } + w.u32(uint32_t(world_.animators.size())); + for (size_t i = 0; i < world_.animators.size(); i++) { w.u32(world_.animators.owner(i).bits); w.u32(world_.animators.at(i).player); } + } + w.end_section(sec); + + sec = w.begin_section("PHYS"); physics_.serialize(w); w.end_section(sec); + sec = w.begin_section("ANIM"); anim_.serialize(w); w.end_section(sec); + sec = w.begin_section("INPT"); input_.serialize(w); w.end_section(sec); + sec = w.begin_section("CAMR"); w.vec2(camera_.position); w.f32(camera_.zoom); w.f32(camera_.rotation); w.end_section(sec); + sec = w.begin_section("COMP"); compute_.serialize(w); w.end_section(sec); + + // Lua: the global `game` table plus each scene's `state` field. Functions are code, not state: + // they come back from the scene scripts themselves. + sec = w.begin_section("LUA "); + { + std::string err; + lua_getglobal(L, "game"); + if (!lua_->serialize_value(-1, w, err)) UNIFY_LOG_ERROR("SAVE", "game table: %s", err.c_str()); + lua_pop(L, 1); + w.u32(uint32_t(scenes_.size())); + for (auto& s : scenes_) { + lua_rawgeti(L, LUA_REGISTRYINDEX, s.lua_ref); + lua_getfield(L, -1, "state"); + if (!lua_->serialize_value(-1, w, err)) UNIFY_LOG_ERROR("SAVE", "scene '%s' state: %s", s.name.c_str(), err.c_str()); + lua_pop(L, 2); + } + } + w.end_section(sec); + + if (include_audio) { + sec = w.begin_section("AUDI"); + auto voices = mixer_.snapshot(); + w.u32(uint32_t(voices.size())); + for (auto& v : voices) { + uint16_t owner = 0; + for (auto& s : scenes_) if (std::find(s.voices.begin(), s.voices.end(), v.handle) != s.voices.end()) owner = s.id; + w.str(v.asset); w.boolean(v.is_stream); w.u8(uint8_t(v.bus)); w.f32(v.volume); w.f32(v.pan); w.f32(v.pitch); + w.boolean(v.loop); w.boolean(v.paused); w.f64(v.position); w.u16(owner); + } + w.f32(mixer_.bus_volume(Bus::Master)); w.f32(mixer_.bus_volume(Bus::Sfx)); w.f32(mixer_.bus_volume(Bus::Music)); + w.end_section(sec); + } + return w.take(); +} + +bool Engine::load_state(const std::vector& bytes, std::string& error) { + std::map sections; + try { + BinaryReader all(bytes); + char tag[5]; + BinaryReader body(nullptr, 0); + while (all.next_section(tag, body)) sections.emplace(tag, body); + for (const char* need : {"HEAD", "TIME", "RNG ", "SCEN", "ECS ", "PHYS", "ANIM", "INPT", "CAMR", "COMP", "LUA "}) + if (!sections.count(need)) { error = std::string("save state is missing section ") + need; return false; } + BinaryReader& head = sections.at("HEAD"); + if (head.str() != "UNIFY-SAVE") { error = "not a UNIFY save state"; return false; } + uint32_t version = head.u32(); + if (version > kSaveVersion) { error = "save state version " + std::to_string(version) + " is newer than this engine"; return false; } + head.str(); + if (head.u32() != sim_.ticks_per_second) { error = "save state was recorded at a different tick rate"; return false; } + } catch (const SerializationError& e) { + error = std::string("corrupt save state: ") + e.what(); + return false; + } + + lua_State* L = lua_->L(); + try { + // Keep every currently loaded asset alive across the swap so unchanged assets keep + // their handles and are not reloaded from disk. + std::vector keep; + for (auto& s : scenes_) for (auto a : s.assets) { assets_->acquire(a); keep.push_back(a); } + + // Tear down the live world completely; the saved one replaces it. + mixer_.stop_all(); + for (auto& s : scenes_) { + s.voices.clear(); s.buffers.clear(); s.kernels.clear(); // compute state is replaced wholesale below + } + world_.clear(); + physics_.clear(); + while (!scenes_.empty()) { unload_scene(scenes_.back()); scenes_.pop_back(); } + + BinaryReader& time = sections.at("TIME"); + sim_.tick = time.u64(); + std::vector saved_timers; + uint32_t nt = time.u32(); + for (uint32_t i = 0; i < nt; i++) { Timer t; t.fire_tick = time.u64(); t.interval_ticks = time.u64(); t.name = time.str(); t.scene = time.u16(); saved_timers.push_back(t); } + + BinaryReader& rng = sections.at("RNG "); + uint32_t st[4]; + for (auto& x : st) x = rng.u32(); + rng_.set_state(st); + + std::string cerr; + if (!compute_.deserialize(sections.at("COMP"), cerr)) { error = cerr; return false; } + + BinaryReader& sc = sections.at("SCEN"); + next_scene_id_ = sc.u16(); + uint32_t ns = sc.u32(); + for (uint32_t i = 0; i < ns; i++) { + Scene s; + s.id = sc.u16(); + s.name = sc.str(); + s.voices.reserve(64); + scenes_.push_back(s); + Scene& live = scenes_.back(); + if (!load_scene_script(live, error)) return false; + // Restore the scene's asset list before init(), so init() finds its assets already + // owned instead of appending duplicates (which would change the saved state). + uint32_t na = sc.u32(); + for (uint32_t k = 0; k < na; k++) { + AssetType type = AssetType(sc.u8()); + std::string name = sc.str(); + AssetHandle h = assets_->load(type, name); + if (!h) { error = "asset '" + name + "' from the save state could not be loaded"; return false; } + live.assets.push_back(h); + } + if (!call_scene("init")) { error = "scene init: " + lua_->last_error(); return false; } + uint32_t nb = sc.u32(); for (uint32_t k = 0; k < nb; k++) live.buffers.push_back(BufferHandle{sc.u32()}); + uint32_t nk = sc.u32(); for (uint32_t k = 0; k < nk; k++) live.kernels.push_back(KernelHandle{sc.u32()}); + } + for (auto a : keep) assets_->release(a); + timers_ = saved_timers; + + BinaryReader& ecs = sections.at("ECS "); + { + HandlePool::State es; + uint32_t n = ecs.u32(); + es.gens.resize(n); es.live.resize(n); + world_.infos().assign(n, EntityInfo{}); + for (uint32_t i = 0; i < n; i++) { + es.gens[i] = ecs.u8(); es.live[i] = ecs.u8(); + if (!es.live[i]) continue; + es.alive++; + EntityInfo& in = world_.infos()[i]; + in.name = ecs.str(); in.prefab = ecs.str(); in.scene = ecs.u16(); in.tags = ecs.u32(); + } + es.free.resize(ecs.u32()); + for (auto& f : es.free) f = ecs.u32(); + world_.entity_pool().load(es); + uint32_t nt2 = ecs.u32(); + for (uint32_t i = 0; i < nt2; i++) { + EntityHandle e{ecs.u32()}; + TransformC t; t.current = read_transform(ecs); t.previous = read_transform(ecs); + world_.transforms.add(e, t); + } + uint32_t nsp = ecs.u32(); + for (uint32_t i = 0; i < nsp; i++) { + EntityHandle e{ecs.u32()}; + SpriteC s; + std::string tex = ecs.str(); + s.texture = tex.empty() ? 0 : assets_->find(tex).bits; + s.atlas_region = ecs.u32(); s.size = ecs.vec2(); s.pivot = ecs.vec2(); s.tint = read_color(ecs); + s.layer = int16_t(ecs.u16()); s.depth = ecs.f32(); s.flip_x = ecs.boolean(); s.visible = ecs.boolean(); + world_.sprites.add(e, s); + } + uint32_t nb = ecs.u32(); + for (uint32_t i = 0; i < nb; i++) { EntityHandle e{ecs.u32()}; world_.bodies.add(e, BodyC{ecs.u32()}); } + uint32_t na = ecs.u32(); + for (uint32_t i = 0; i < na; i++) { EntityHandle e{ecs.u32()}; world_.animators.add(e, AnimatorC{ecs.u32()}); } + } + + physics_.deserialize(sections.at("PHYS")); + anim_.deserialize(sections.at("ANIM")); + input_.deserialize(sections.at("INPT")); + BinaryReader& cam = sections.at("CAMR"); + camera_.position = cam.vec2(); camera_.zoom = cam.f32(); camera_.rotation = cam.f32(); + + BinaryReader& lr = sections.at("LUA "); + std::string lerr; + if (!lua_->deserialize_value(lr, lerr)) { error = "game table: " + lerr; return false; } + lua_setglobal(L, "game"); + uint32_t nls = lr.u32(); + for (uint32_t i = 0; i < nls && i < scenes_.size(); i++) { + lua_rawgeti(L, LUA_REGISTRYINDEX, scenes_[i].lua_ref); + if (!lua_->deserialize_value(lr, lerr)) { lua_pop(L, 1); error = "scene state: " + lerr; return false; } + lua_setfield(L, -2, "state"); + lua_pop(L, 1); + } + + if (sections.count("AUDI")) { + BinaryReader& au = sections.at("AUDI"); + uint32_t nv = au.u32(); + for (uint32_t i = 0; i < nv; i++) { + std::string asset = au.str(); + bool is_stream = au.boolean(); + PlayParams p; + p.bus = Bus(au.u8()); p.volume = au.f32(); p.pan = au.f32(); p.pitch = au.f32(); p.loop = au.boolean(); + bool paused = au.boolean(); + double pos = au.f64(); + uint16_t owner = au.u16(); + AudioHandle h; + if (is_stream) { + auto src = assets_->open_stream(assets_->find(asset)); + if (src) { src->seek(uint32_t(std::max(0.0, pos))); h = mixer_.stream(src, p); } + } else if (const AssetRecord* r = assets_->get(assets_->find(asset))) { + p.start = pos; + h = mixer_.play(r->clip, p); + } + if (h && paused) mixer_.pause(h); + for (auto& s : scenes_) if (s.id == owner && h) s.voices.push_back(h); + } + mixer_.set_bus_volume(Bus::Master, au.f32()); mixer_.set_bus_volume(Bus::Sfx, au.f32()); mixer_.set_bus_volume(Bus::Music, au.f32()); + } + } catch (const SerializationError& e) { + error = std::string("corrupt save state: ") + e.what(); + return false; + } + // Real time continues from the restored tick. + // Same exact formula as tick boundaries (SimClock::tick_end_ns); a truncated per-tick + // duration here would drift input windows by up to a tick after restoring late in a session. + sim_origin_ns_ = backend_.now_ns() - sim_.tick * 1000000000ull / sim_.ticks_per_second; + lua_->gc_collect(); + return true; +} + +uint64_t Engine::state_hash() { + std::vector s = save_state(false); + return fnv1a(s.data(), s.size()); +} + +bool Engine::save_to_file(const std::string& slot, std::string& error) { + std::string path = assets_->path_for(AssetType::SaveData, "saves/" + slot); + if (!write_file(path, save_state())) { error = "could not write " + path; return false; } + return true; +} + +bool Engine::load_from_file(const std::string& slot, std::string& error) { + std::vector data; + std::string path = assets_->path_for(AssetType::SaveData, "saves/" + slot); + if (!read_file(path, data)) { error = "no save at " + path; return false; } + return load_state(data, error); +} + +void Engine::process_pending_state_ops() { + // Requests made during the tick run here, at the tick boundary, in request order: + // state is never captured or replaced halfway through a simulation step. + std::vector> ops; + ops.swap(pending_ops_); + for (auto& [is_save, slot] : ops) { + std::string err; + if (is_save) { + bool ok = true; + if (slot.empty()) quick_slot_ = save_state(); + else if (!(ok = save_to_file(slot, err))) UNIFY_LOG_ERROR("SAVE", "%s", err.c_str()); + lua_pushboolean(lua_->L(), ok); + lua_pushstring(lua_->L(), slot.c_str()); + if (!call_scene("on_saved", 2)) report_script_error("scene on_saved"); + } else { + bool ok = slot.empty() ? (!quick_slot_.empty() && load_state(quick_slot_, err)) : load_from_file(slot, err); + if (!ok) UNIFY_LOG_ERROR("SAVE", "load failed: %s", err.empty() ? "no quick save" : err.c_str()); + lua_pushboolean(lua_->L(), ok); + lua_pushstring(lua_->L(), slot.c_str()); + if (!call_scene("on_loaded", 2)) report_script_error("scene on_loaded"); + } + } +} + +} // namespace unify diff --git a/unify/engine/runtime/engine.h b/unify/engine/runtime/engine.h new file mode 100644 index 0000000000000000000000000000000000000000..2b39e219aac38d1ab2cc56215c4ec5978e1091fe --- /dev/null +++ b/unify/engine/runtime/engine.h @@ -0,0 +1,200 @@ +#pragma once +#include +#include +#include +#include +#include "backend.h" +#include "../core/core.h" +#include "../ecs/ecs.h" +#include "../physics/physics.h" +#include "../animation/animation.h" +#include "../assets/assets.h" +#include "../script/lua_vm.h" +#include "../wasm/compute.h" +#include "../memory/memory.h" + +namespace unify { + +/// Scheduler stages, in execution order. Recorded per tick/frame for tracing and tests. +enum class Stage : uint8_t { Input, InputBuffer, FixedSimulation, Physics, Gameplay, Animation, Audio, RenderPrep, Render, Present, Count }; +const char* stage_name(Stage s); + +struct PrefabDef { + std::string name; + bool has_sprite = false; + std::string texture, region; + Vec2 sprite_size{1, 1}; + int16_t layer = 0; + float depth = 0; + Color tint; + bool has_body = false; + BodyDef body; + std::string animation; // initial clip + uint32_t tags = 0; +}; + +struct Timer { uint64_t fire_tick; uint64_t interval_ticks; std::string name; uint16_t scene; }; + +/// A loaded scene: its script table and every resource it owns. Unloading a scene frees +/// all of it, which is what makes transitions leak-free. +struct Scene { + uint16_t id = 0; + std::string name; + int lua_ref = -1; // registry ref to the table returned by the scene script + AssetHandle script; + std::vector assets; + std::vector voices; + std::vector buffers; + std::vector kernels; +}; + +struct ResourceCounts { + uint32_t entities, bodies, anim_players, voices, buffers, kernels, assets, textures, lua_refs; + bool operator==(const ResourceCounts& o) const { + return entities == o.entities && bodies == o.bodies && anim_players == o.anim_players && voices == o.voices && buffers == o.buffers && + kernels == o.kernels && assets == o.assets && textures == o.textures && lua_refs == o.lua_refs; + } +}; + +struct FrameStats { + uint32_t ticks_this_frame = 0; + double stage_ms[size_t(Stage::Count)] = {}; + uint64_t heap_allocs_last_tick = 0; + size_t lua_bytes = 0; +}; + +class Engine { +public: + static constexpr uint32_t kSaveVersion = 1; + static constexpr const char* kEngineVersion = "UNIFY 1.0"; + + Engine(Backend& backend, EngineConfig config); + ~Engine(); + + /// BOOT → LOAD ASSETS → CREATE WORLD: starts devices, Lua, and the boot scene. + bool boot(std::string& error); + /// One real-time frame: poll input, run due fixed ticks, render, present. + void frame(); + /// One fixed simulation tick (INPUT BUFFER → FIXED SIM → PHYSICS → GAMEPLAY → ANIMATION → AUDIO). + void tick() { tick_impl(nullptr); } + /// Runs one tick using a recorded/networked InputFrame instead of live input. This is + /// the replay / rollback path: same state + same frames = same result. + void replay_tick(const InputFrame& frame) { tick_impl(&frame); } + /// RENDER PREP → RENDER → PRESENT with interpolation factor alpha. + void render(float alpha); + /// Runs until the backend or gameplay requests quit. + int run(); + bool quit_requested() const { return quit_; } + void request_quit() { quit_ = true; } + + // ---- save states -------------------------------------------------------------------- + std::vector save_state(bool include_audio = true); + bool load_state(const std::vector& bytes, std::string& error); + std::vector snapshot() { return save_state(); } + bool restore(const std::vector& s, std::string& e) { return load_state(s, e); } + bool save_to_file(const std::string& slot, std::string& error); + bool load_from_file(const std::string& slot, std::string& error); + /// Hash of all deterministic simulation state (excludes audio playback, which runs on + /// its own clock). Equal hashes = equal simulations: the lockstep/rollback check. + uint64_t state_hash(); + + // ---- scenes / entities ---------------------------------------------------------------- + bool transition(const std::string& scene, std::string& error); + bool push_scene(const std::string& scene, std::string& error); + bool pop_scene(std::string& error); + const Scene* active_scene() const { return scenes_.empty() ? nullptr : &scenes_.back(); } + EntityHandle instantiate(const std::string& prefab, Vec2 position, bool persistent, std::string& error); + bool destroy_entity(EntityHandle e); + ResourceCounts resources() const; + + // ---- input injection (headless / replay) ---------------------------------------------- + /// Queues a button event that lands inside the next simulation tick's input window. + void inject(uint16_t code, bool down); + uint64_t next_tick_input_ns() const; + + // ---- subsystems ------------------------------------------------------------------------- + World& world() { return world_; } + PhysicsWorld& physics() { return physics_; } + AnimationSystem& animation() { return anim_; } + InputSystem& input() { return input_; } + Mixer& mixer() { return mixer_; } + AssetManager& assets() { return *assets_; } + ComputeRuntime& compute() { return compute_; } + LuaVM& lua() { return *lua_; } + Renderer2D& renderer() { return *renderer_; } + Camera& camera() { return camera_; } + Rng& rng() { return rng_; } + const SimClock& sim_clock() const { return sim_; } + const RenderClock& render_clock() const { return render_clock_; } + RenderTarget& target() { return target_; } + Backend& backend() { return backend_; } + const EngineConfig& config() const { return config_; } + const FrameStats& stats() const { return stats_; } + const std::vector& trace() const { return trace_; } + const std::vector& log_lines() const { return script_log_; } + const PrefabDef* prefab(const std::string& name, std::string& error); + + // Used by bindings. + bool in_render_phase() const { return rendering_; } + void add_timer(double seconds, bool repeat, const std::string& name); + void request_transition(const std::string& scene) { pending_transition_ = scene; } + void request_save(const std::string& slot) { pending_ops_.push_back({true, slot}); } + void request_load(const std::string& slot) { pending_ops_.push_back({false, slot}); } + std::vector& quick_slot() { return quick_slot_; } + void script_log(const std::string& s); + Scene* current_scene() { return scenes_.empty() ? nullptr : &scenes_.back(); } + const BitmapFont& font() const { return font_; } + const TextureAsset* texture(const std::string& name); + void report_script_error(const std::string& where); + +private: + void tick_impl(const InputFrame* replay); + bool load_scene_script(Scene& s, std::string& error); + void unload_scene(Scene& s); + bool call_scene(const char* fn, int nargs = 0); + void sync_transforms_from_physics(); + void dispatch_physics_events(); + void fire_timers(); + void process_pending_state_ops(); + void mark(Stage s) { if (trace_.size() >= 64) trace_.clear(); trace_.push_back(s); } + + Backend& backend_; + EngineConfig config_; + World world_; + PhysicsWorld physics_; + AnimationSystem anim_; + InputSystem input_; + Mixer mixer_; + AudioStreamer streamer_; + std::unique_ptr assets_; + ComputeRuntime compute_; + std::unique_ptr lua_; + std::unique_ptr renderer_; + RenderTarget target_; + Camera camera_; + BitmapFont font_; + Rng rng_; + SimClock sim_; + RenderClock render_clock_; + FrameAllocator frame_alloc_{1u << 20}; + uint64_t sim_origin_ns_ = 0; // input-clock time at which tick 0 began + std::vector scenes_; + uint16_t next_scene_id_ = 1; + std::vector timers_; + std::map prefabs_; + std::map texture_cache_; + std::vector events_scratch_; + std::vector trace_; + FrameStats stats_; + std::vector script_log_; + std::vector quick_slot_; + std::vector> pending_ops_; // (is_save, slot); "" = quick slot + bool quit_ = false, booted_ = false, rendering_ = false; + std::string pending_transition_; +}; + +/// Registers the UNIFY Lua API (entity, world, physics, audio, input, camera, ui, timer, +/// scene, buffer, kernel, gc, save_state/load_state) into the engine's Lua state. +void register_bindings(Engine& engine); + +} // namespace unify diff --git a/unify/engine/script/lua_vm.cpp b/unify/engine/script/lua_vm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a59dbd7af507c8522285fa95311dad994d890055 --- /dev/null +++ b/unify/engine/script/lua_vm.cpp @@ -0,0 +1,216 @@ +#include "lua_vm.h" +#include "../core/core.h" +#include "../serialization/stream.h" +#include +#include +#include +// Lua is compiled as C++ (see CMakeLists.txt) so script errors unwind with exceptions, +// which runs destructors in binding code instead of longjmp-ing over them. +#include "lua.h" +#include "lauxlib.h" +#include "lualib.h" + +namespace unify { + +const char* const kEntityMeta = "unify.Entity"; +const char* const kBufferMeta = "unify.Buffer"; +const char* const kKernelMeta = "unify.Kernel"; + +void* LuaVM::alloc(void* ud, void* ptr, size_t osize, size_t nsize) { + auto* vm = static_cast(ud); + if (ptr == nullptr) osize = 0; // osize encodes the object type when ptr is NULL + if (nsize == 0) { + vm->used_ -= osize; + std::free(ptr); + return nullptr; + } + if (vm->used_ - osize + nsize > vm->limit_) { vm->failures_++; return nullptr; } // Lua raises "not enough memory" + void* p = std::realloc(ptr, nsize); + if (!p) { vm->failures_++; return nullptr; } + vm->used_ = vm->used_ - osize + nsize; + if (vm->used_ > vm->peak_) vm->peak_ = vm->used_; + return p; +} + +LuaVM::LuaVM(size_t memory_limit) : limit_(memory_limit) { + L_ = lua_newstate(&LuaVM::alloc, this); + luaL_openlibs(L_); + // The engine owns collection timing: stop the automatic collector and use + // incremental steps scheduled once per tick with a fixed budget. + lua_gc(L_, LUA_GCINC, 0, 0, 0); + lua_gc(L_, LUA_GCSTOP); +} + +LuaVM::~LuaVM() { if (L_) lua_close(L_); } + +static int deterministic_random(lua_State* L) { + Rng* rng = static_cast(lua_touserdata(L, lua_upvalueindex(1))); + int n = lua_gettop(L); + if (n == 0) { lua_pushnumber(L, double(rng->next_float())); return 1; } + lua_Integer lo = 1, hi; + if (n == 1) hi = luaL_checkinteger(L, 1); + else { lo = luaL_checkinteger(L, 1); hi = luaL_checkinteger(L, 2); } + luaL_argcheck(L, lo <= hi, n, "interval is empty"); + lua_pushinteger(L, rng->range_int(int32_t(lo), int32_t(hi))); + return 1; +} + +void LuaVM::sandbox(Rng* rng) { + // Nondeterministic or unsafe services are not reachable from gameplay code. + for (const char* g : {"os", "io", "debug", "dofile", "loadfile", "require", "package", "collectgarbage"}) { + lua_pushnil(L_); + lua_setglobal(L_, g); + } + lua_getglobal(L_, "math"); + lua_pushlightuserdata(L_, rng); + lua_pushcclosure(L_, deterministic_random, 1); + lua_setfield(L_, -2, "random"); + lua_pushnil(L_); + lua_setfield(L_, -2, "randomseed"); + lua_pop(L_, 1); +} + +bool LuaVM::run(const std::string& code, const std::string& chunk_name, int results) { + if (luaL_loadbuffer(L_, code.data(), code.size(), ("@" + chunk_name).c_str()) != LUA_OK) { + error_ = lua_tostring(L_, -1); + lua_pop(L_, 1); + return false; + } + if (lua_pcall(L_, 0, results, 0) != LUA_OK) { + error_ = lua_tostring(L_, -1); + lua_pop(L_, 1); + return false; + } + return true; +} + +bool LuaVM::call_global(const char* name, int nargs, int nresults) { + lua_getglobal(L_, name); + if (!lua_isfunction(L_, -1)) { lua_pop(L_, 1 + nargs); return true; } + if (nargs) lua_insert(L_, -(nargs + 1)); + if (lua_pcall(L_, nargs, nresults, 0) != LUA_OK) { + error_ = lua_tostring(L_, -1); + lua_pop(L_, 1); + return false; + } + return true; +} + +void LuaVM::gc_step() { if (!paused_) lua_gc(L_, LUA_GCSTEP, budget_kb_); } +void LuaVM::gc_budget(int kb) { budget_kb_ = kb < 1 ? 1 : kb; } +void LuaVM::gc_pause() { paused_ = true; } +void LuaVM::gc_resume() { paused_ = false; } +void LuaVM::gc_collect() { lua_gc(L_, LUA_GCCOLLECT); lua_gc(L_, LUA_GCSTOP); } + +// ------------------------------------------------------------------------------ serialization +// Tags: 0 nil, 1 false, 2 true, 3 integer, 4 float, 5 string, 6 table, 7 entity, 8 buffer, 9 kernel. +// Handles serialize as handle bits; the owning subsystems restore the same handles. +static bool write_value(lua_State* L, int idx, BinaryWriter& w, std::string& err, int depth) { + if (depth > 64) { err = "table nesting too deep (cycle?)"; return false; } + idx = lua_absindex(L, idx); + switch (lua_type(L, idx)) { + case LUA_TNIL: w.u8(0); return true; + case LUA_TBOOLEAN: w.u8(lua_toboolean(L, idx) ? 2 : 1); return true; + case LUA_TNUMBER: + if (lua_isinteger(L, idx)) { w.u8(3); w.u64(uint64_t(lua_tointeger(L, idx))); } + else { w.u8(4); w.f64(lua_tonumber(L, idx)); } + return true; + case LUA_TSTRING: { size_t n; const char* s = lua_tolstring(L, idx, &n); w.u8(5); w.str(std::string(s, n)); return true; } + case LUA_TUSERDATA: + if (luaL_testudata(L, idx, kEntityMeta)) { w.u8(7); w.u32(*static_cast(lua_touserdata(L, idx))); return true; } + if (luaL_testudata(L, idx, kBufferMeta)) { auto* b = static_cast(lua_touserdata(L, idx)); w.u8(8); w.u32(b->bits); w.boolean(b->is_int); return true; } + if (luaL_testudata(L, idx, kKernelMeta)) { w.u8(9); w.u32(*static_cast(lua_touserdata(L, idx))); return true; } + err = "cannot serialize userdata"; + return false; + case LUA_TTABLE: { + // Deterministic key order: collect keys, sort (numbers before strings). + struct Key { bool is_num; lua_Integer i; double d; bool is_int; std::string s; }; + std::vector keys; + lua_pushnil(L); + while (lua_next(L, idx)) { + lua_pop(L, 1); + Key k{}; + if (lua_type(L, -1) == LUA_TNUMBER) { k.is_num = true; k.is_int = lua_isinteger(L, -1); k.i = lua_tointeger(L, -1); k.d = lua_tonumber(L, -1); } + else if (lua_type(L, -1) == LUA_TSTRING) { k.s = lua_tostring(L, -1); } + else { lua_pop(L, 1); err = "table keys must be numbers or strings"; return false; } + keys.push_back(k); + } + std::sort(keys.begin(), keys.end(), [](const Key& a, const Key& b) { + if (a.is_num != b.is_num) return a.is_num; + if (a.is_num) return a.d < b.d; + return a.s < b.s; + }); + w.u8(6); + w.u32(uint32_t(keys.size())); + for (auto& k : keys) { + if (k.is_num) { if (k.is_int) lua_pushinteger(L, k.i); else lua_pushnumber(L, k.d); } + else lua_pushlstring(L, k.s.data(), k.s.size()); + if (!write_value(L, -1, w, err, depth + 1)) { lua_pop(L, 1); return false; } + lua_gettable(L, idx); + bool ok = write_value(L, -1, w, err, depth + 1); + lua_pop(L, 1); + if (!ok) return false; + } + return true; + } + default: + err = std::string("cannot serialize a ") + lua_typename(L, lua_type(L, idx)); + return false; + } +} + +static bool read_value(lua_State* L, BinaryReader& r, std::string& err, int depth) { + if (depth > 64) { err = "table nesting too deep"; return false; } + luaL_checkstack(L, 4, "deserialize"); + switch (r.u8()) { + case 0: lua_pushnil(L); return true; + case 1: lua_pushboolean(L, 0); return true; + case 2: lua_pushboolean(L, 1); return true; + case 3: lua_pushinteger(L, lua_Integer(r.u64())); return true; + case 4: lua_pushnumber(L, r.f64()); return true; + case 5: { std::string s = r.str(); lua_pushlstring(L, s.data(), s.size()); return true; } + case 7: { + auto* p = static_cast(lua_newuserdatauv(L, sizeof(uint32_t), 0)); + *p = r.u32(); + luaL_setmetatable(L, kEntityMeta); + return true; + } + case 8: { + auto* b = static_cast(lua_newuserdatauv(L, sizeof(LuaBuffer), 0)); + b->bits = r.u32(); + b->is_int = r.boolean(); + luaL_setmetatable(L, kBufferMeta); + return true; + } + case 9: { + *static_cast(lua_newuserdatauv(L, sizeof(uint32_t), 0)) = r.u32(); + luaL_setmetatable(L, kKernelMeta); + return true; + } + case 6: { + uint32_t n = r.u32(); + lua_createtable(L, 0, int(n)); + for (uint32_t i = 0; i < n; i++) { + if (!read_value(L, r, err, depth + 1)) return false; + if (!read_value(L, r, err, depth + 1)) return false; + lua_settable(L, -3); + } + return true; + } + default: err = "corrupt Lua value tag"; return false; + } +} + +bool LuaVM::serialize_value(int index, BinaryWriter& w, std::string& error) { return write_value(L_, index, w, error, 0); } +bool LuaVM::deserialize_value(BinaryReader& r, std::string& error) { + int top = lua_gettop(L_); + try { + if (read_value(L_, r, error, 0)) return true; + } catch (const SerializationError& e) { + error = e.what(); + } + lua_settop(L_, top); + return false; +} + +} // namespace unify diff --git a/unify/engine/script/lua_vm.h b/unify/engine/script/lua_vm.h new file mode 100644 index 0000000000000000000000000000000000000000..68d487e1c0a312f3787c1a5bead425a6dde6a383 --- /dev/null +++ b/unify/engine/script/lua_vm.h @@ -0,0 +1,68 @@ +#pragma once +#include +#include +#include +#include + +struct lua_State; + +namespace unify { +class BinaryWriter; +class BinaryReader; +class Rng; + +/// Owns a Lua 5.4 state whose memory is accounted and capped separately from the engine +/// heap, and whose garbage collector runs only when the engine schedules it. +class LuaVM { +public: + explicit LuaVM(size_t memory_limit = 64u << 20); + ~LuaVM(); + LuaVM(const LuaVM&) = delete; + LuaVM& operator=(const LuaVM&) = delete; + + lua_State* L() const { return L_; } + + /// Deterministic sandbox: math.random uses the engine RNG; os/io/debug/loadfile are removed. + void sandbox(Rng* rng); + bool run(const std::string& code, const std::string& chunk_name, int results = 0); + const std::string& last_error() const { return error_; } + void set_error(std::string e) { error_ = std::move(e); } + /// Calls global (or table-field) function `name` if present. Returns false on Lua error. + bool call_global(const char* name, int nargs = 0, int nresults = 0); + + // ---- GC scheduling ------------------------------------------------------------------ + void gc_step(); // runs one budgeted incremental step (unless paused) + void gc_budget(int kb_per_step); // work per gc_step, in KB of allocation debt + void gc_pause(); // no collection at all until gc_resume() + void gc_resume(); + void gc_collect(); // full collection (e.g. during a loading screen) + int gc_budget_kb() const { return budget_kb_; } + bool gc_paused() const { return paused_; } + + size_t bytes() const { return used_; } + size_t peak_bytes() const { return peak_; } + size_t limit() const { return limit_; } + uint64_t allocation_failures() const { return failures_; } + + /// Serializes a Lua value (nil/bool/number/string/table; no functions or cycles). + /// Entity userdata are written as handles via the supplied tag. + bool serialize_value(int index, BinaryWriter& w, std::string& error); + bool deserialize_value(BinaryReader& r, std::string& error); + +private: + static void* alloc(void* ud, void* ptr, size_t osize, size_t nsize); + lua_State* L_ = nullptr; + size_t used_ = 0, peak_ = 0, limit_; + uint64_t failures_ = 0; + int budget_kb_ = 64; + bool paused_ = false; + std::string error_; +}; + +/// Name of the metatable used for entity userdata (holds an EntityHandle's bits only). +extern const char* const kEntityMeta; +extern const char* const kBufferMeta; // userdata: LuaBuffer +extern const char* const kKernelMeta; // userdata: uint32_t KernelHandle bits +struct LuaBuffer { uint32_t bits; bool is_int; }; + +} // namespace unify diff --git a/unify/engine/serialization/stream.h b/unify/engine/serialization/stream.h new file mode 100644 index 0000000000000000000000000000000000000000..ba84d018553f29833b3db7350f20c8bd8295e0d9 --- /dev/null +++ b/unify/engine/serialization/stream.h @@ -0,0 +1,81 @@ +#pragma once +#include +#include +#include +#include +#include +#include "../core/math.h" + +namespace unify { + +/// Little-endian binary writer. Floats are written as their IEEE-754 bit patterns, +/// so a round trip is bit-exact (required for deterministic save states). +class BinaryWriter { +public: + void u8(uint8_t v) { buf_.push_back(v); } + void u16(uint16_t v) { for (int i = 0; i < 2; i++) buf_.push_back(uint8_t(v >> (8 * i))); } + void u32(uint32_t v) { for (int i = 0; i < 4; i++) buf_.push_back(uint8_t(v >> (8 * i))); } + void u64(uint64_t v) { for (int i = 0; i < 8; i++) buf_.push_back(uint8_t(v >> (8 * i))); } + void i32(int32_t v) { u32(uint32_t(v)); } + void f32(float v) { uint32_t b; std::memcpy(&b, &v, 4); u32(b); } + void f64(double v) { uint64_t b; std::memcpy(&b, &v, 8); u64(b); } + void boolean(bool v) { u8(v ? 1 : 0); } + void vec2(Vec2 v) { f32(v.x); f32(v.y); } + void str(const std::string& s) { u32(uint32_t(s.size())); bytes(s.data(), s.size()); } + void bytes(const void* p, size_t n) { auto b = static_cast(p); buf_.insert(buf_.end(), b, b + n); } + void blob(const std::vector& v) { u32(uint32_t(v.size())); bytes(v.data(), v.size()); } + + /// Tagged, length-prefixed section. Readers can skip sections they do not understand, + /// which is what lets the save format evolve without breaking old files. + size_t begin_section(const char tag[4]) { bytes(tag, 4); size_t at = buf_.size(); u32(0); return at; } + void end_section(size_t at) { + uint32_t len = uint32_t(buf_.size() - at - 4); + for (int i = 0; i < 4; i++) buf_[at + i] = uint8_t(len >> (8 * i)); + } + + const std::vector& data() const { return buf_; } + std::vector take() { return std::move(buf_); } + size_t size() const { return buf_.size(); } +private: + std::vector buf_; +}; + +struct SerializationError : std::runtime_error { using std::runtime_error::runtime_error; }; + +class BinaryReader { +public: + BinaryReader(const uint8_t* data, size_t size) : p_(data), end_(data + size) {} + explicit BinaryReader(const std::vector& v) : BinaryReader(v.data(), v.size()) {} + uint8_t u8() { need(1); return *p_++; } + uint16_t u16() { need(2); uint16_t v = uint16_t(p_[0] | (p_[1] << 8)); p_ += 2; return v; } + uint32_t u32() { need(4); uint32_t v = 0; for (int i = 0; i < 4; i++) v |= uint32_t(p_[i]) << (8 * i); p_ += 4; return v; } + uint64_t u64() { need(8); uint64_t v = 0; for (int i = 0; i < 8; i++) v |= uint64_t(p_[i]) << (8 * i); p_ += 8; return v; } + int32_t i32() { return int32_t(u32()); } + float f32() { uint32_t b = u32(); float v; std::memcpy(&v, &b, 4); return v; } + double f64() { uint64_t b = u64(); double v; std::memcpy(&v, &b, 8); return v; } + bool boolean() { return u8() != 0; } + Vec2 vec2() { float x = f32(); return {x, f32()}; } + std::string str() { uint32_t n = u32(); need(n); std::string s(reinterpret_cast(p_), n); p_ += n; return s; } + void bytes(void* out, size_t n) { need(n); std::memcpy(out, p_, n); p_ += n; } + std::vector blob() { uint32_t n = u32(); need(n); std::vector v(p_, p_ + n); p_ += n; return v; } + + /// Reads the next section header. Returns a reader limited to the section body. + bool next_section(char tag[5], BinaryReader& body) { + if (p_ == end_) return false; + need(8); + std::memcpy(tag, p_, 4); tag[4] = 0; p_ += 4; + uint32_t len = u32(); + need(len); + body = BinaryReader(p_, len); + p_ += len; + return true; + } + bool at_end() const { return p_ == end_; } + size_t remaining() const { return size_t(end_ - p_); } +private: + void need(size_t n) const { if (size_t(end_ - p_) < n) throw SerializationError("unexpected end of data"); } + const uint8_t* p_; + const uint8_t* end_; +}; + +} // namespace unify diff --git a/unify/engine/wasm/compute.cpp b/unify/engine/wasm/compute.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9fbe43889237d59effb603bf998110e3e841de40 --- /dev/null +++ b/unify/engine/wasm/compute.cpp @@ -0,0 +1,191 @@ +#include "compute.h" +#include "../core/core.h" +#include "../serialization/stream.h" +#include + +namespace unify { + +ComputeRuntime::ComputeRuntime(uint32_t initial_pages, uint32_t max_pages) : memory_(std::make_shared()) { + memory_->max_pages = max_pages; + memory_->bytes.assign(size_t(initial_pages) * wasm::Memory::kPage, 0); + alloc_.reset(kReserved, uint32_t(memory_->bytes.size()) - kReserved); +} + +bool ComputeRuntime::grow_to_fit(uint32_t bytes) { + uint32_t need_pages = (bytes + wasm::Memory::kPage - 1) / wasm::Memory::kPage + 1; + if (memory_->grow(need_pages) < 0) return false; + alloc_.extend(uint32_t(memory_->bytes.size())); + return true; +} + +BufferHandle ComputeRuntime::buffer_create(uint32_t bytes) { + uint32_t off = alloc_.allocate(bytes, 16); + if (off == BufferAllocator::kFail) { + if (!grow_to_fit(bytes)) { UNIFY_LOG_ERROR("COMPUTE", "out of kernel memory (%u bytes requested)", bytes); return {}; } + off = alloc_.allocate(bytes, 16); + if (off == BufferAllocator::kFail) return {}; + } + std::memset(memory_->bytes.data() + off, 0, bytes); + BufferHandle h = buffers_.allocate(); + if (h.index() >= buf_.size()) buf_.resize(h.index() + 1); + buf_[h.index()] = {off, bytes}; + return h; +} + +bool ComputeRuntime::buffer_destroy(BufferHandle h) { + if (!buffers_.valid(h)) return false; + alloc_.free(buf_[h.index()].offset); + buf_[h.index()] = {}; + return buffers_.release(h); +} + +bool ComputeRuntime::buffer_upload(BufferHandle h, const void* data, uint32_t bytes, uint32_t offset) { + if (!buffers_.valid(h)) return false; + const Buf& b = buf_[h.index()]; + if (uint64_t(offset) + bytes > b.size) return false; + std::memcpy(memory_->bytes.data() + b.offset + offset, data, bytes); + return true; +} + +bool ComputeRuntime::buffer_download(BufferHandle h, void* out, uint32_t bytes, uint32_t offset) const { + if (!buffers_.valid(h)) return false; + const Buf& b = buf_[h.index()]; + if (uint64_t(offset) + bytes > b.size) return false; + std::memcpy(out, memory_->bytes.data() + b.offset + offset, bytes); + return true; +} + +uint32_t ComputeRuntime::buffer_size(BufferHandle h) const { return buffers_.valid(h) ? buf_[h.index()].size : 0; } + +KernelHandle ComputeRuntime::load(const kernel::CompiledKernel& k, const std::string& source, std::string& error) { + if (!k.ok) { error = k.error; return {}; } + auto module = std::make_shared(); + if (!wasm::decode(k.wasm, *module, error)) return {}; + auto inst = std::make_shared(); + if (!inst->instantiate(module, memory_, {}, error)) return {}; + KernelHandle h = kernels_.allocate(); + if (h.index() >= kern_.size()) kern_.resize(h.index() + 1); + kern_[h.index()] = {source, k, inst}; + return h; +} + +KernelHandle ComputeRuntime::compile_and_load(const std::string& source, std::string& error) { + kernel::CompiledKernel k = compile(source); + if (!k.ok) { error = k.error; return {}; } + return load(k, source, error); +} + +bool ComputeRuntime::unload(KernelHandle h) { + if (!kernels_.valid(h)) return false; + kern_[h.index()] = {}; + return kernels_.release(h); +} + +const kernel::CompiledKernel* ComputeRuntime::kernel_info(KernelHandle h) const { + return kernels_.valid(h) ? &kern_[h.index()].compiled : nullptr; +} + +DispatchResult ComputeRuntime::dispatch(KernelHandle h, uint32_t grid, uint32_t block, const std::vector& args) { + DispatchResult r; + if (!kernels_.valid(h)) { r.ok = false; r.error = "invalid kernel handle"; return r; } + Kern& k = kern_[h.index()]; + const auto& params = k.compiled.params; + if (args.size() != params.size()) { + r.ok = false; + r.error = k.compiled.name + " expects " + std::to_string(params.size()) + " arguments, got " + std::to_string(args.size()); + return r; + } + std::vector wargs = {wasm::Value::i32(int32_t(grid)), wasm::Value::i32(int32_t(block))}; + for (size_t i = 0; i < args.size(); i++) { + const KernelArg& a = args[i]; + kernel::Type t = params[i].type; + bool is_ptr = t == kernel::Type::IntPtr || t == kernel::Type::FloatPtr; + if (is_ptr) { + if (a.kind != KernelArg::Buffer || !buffers_.valid(BufferHandle{a.buffer})) { + r.ok = false; r.error = "argument '" + params[i].name + "' must be a valid buffer"; return r; + } + wargs.push_back(wasm::Value::i32(int32_t(buf_[BufferHandle{a.buffer}.index()].offset))); + } else if (t == kernel::Type::Int) { + wargs.push_back(wasm::Value::i32(a.kind == KernelArg::Float ? int32_t(a.f) : a.i)); + } else { + wargs.push_back(wasm::Value::f32(a.kind == KernelArg::Int ? float(a.i) : a.f)); + } + } + wasm::ExecResult x = k.instance->call(k.compiled.name + "__dispatch", wargs); + r.ok = x.ok; + r.error = x.trap; + r.instructions = x.instructions; + return r; +} + +void ComputeRuntime::serialize(BinaryWriter& w) const { + w.u32(memory_->pages()); + auto bs = buffers_.save(); + w.u32(uint32_t(bs.gens.size())); + for (size_t i = 0; i < bs.gens.size(); i++) { + w.u8(bs.gens[i]); w.u8(bs.live[i]); + if (bs.live[i]) { + const Buf& b = buf_[i]; + w.u32(b.offset); w.u32(b.size); + w.bytes(memory_->bytes.data() + b.offset, b.size); // only live buffer contents, not the whole memory + } + } + w.u32(uint32_t(bs.free.size())); + for (uint32_t f : bs.free) w.u32(f); + auto ks = kernels_.save(); + w.u32(uint32_t(ks.gens.size())); + for (size_t i = 0; i < ks.gens.size(); i++) { + w.u8(ks.gens[i]); w.u8(ks.live[i]); + if (ks.live[i]) w.str(kern_[i].source); // kernels are rebuilt from source on load + } + w.u32(uint32_t(ks.free.size())); + for (uint32_t f : ks.free) w.u32(f); +} + +bool ComputeRuntime::deserialize(BinaryReader& r, std::string& error) { + uint32_t pages = r.u32(); + memory_->bytes.assign(size_t(pages) * wasm::Memory::kPage, 0); + HandlePool::State bs; + uint32_t n = r.u32(); + bs.gens.resize(n); bs.live.resize(n); + buf_.assign(n, Buf{}); + std::map used; + for (uint32_t i = 0; i < n; i++) { + bs.gens[i] = r.u8(); bs.live[i] = r.u8(); + if (!bs.live[i]) continue; + bs.alive++; + Buf b{r.u32(), r.u32()}; + if (uint64_t(b.offset) + b.size > memory_->bytes.size()) { error = "buffer out of range in save state"; return false; } + r.bytes(memory_->bytes.data() + b.offset, b.size); + buf_[i] = b; + used[b.offset] = b.size; + } + bs.free.resize(r.u32()); + for (auto& f : bs.free) f = r.u32(); + buffers_.load(bs); + alloc_.restore(used, kReserved, uint32_t(memory_->bytes.size())); + + HandlePool::State ks; + uint32_t nk = r.u32(); + ks.gens.resize(nk); ks.live.resize(nk); + kern_.assign(nk, Kern{}); + for (uint32_t i = 0; i < nk; i++) { + ks.gens[i] = r.u8(); ks.live[i] = r.u8(); + if (!ks.live[i]) continue; + ks.alive++; + std::string src = r.str(); + kernel::CompiledKernel k = compile(src); + if (!k.ok) { error = "kernel failed to recompile: " + k.error; return false; } + auto module = std::make_shared(); + if (!wasm::decode(k.wasm, *module, error)) return false; + auto inst = std::make_shared(); + if (!inst->instantiate(module, memory_, {}, error)) return false; + kern_[i] = {src, k, inst}; + } + ks.free.resize(r.u32()); + for (auto& f : ks.free) f = r.u32(); + kernels_.load(ks); + return true; +} + +} // namespace unify diff --git a/unify/engine/wasm/compute.h b/unify/engine/wasm/compute.h new file mode 100644 index 0000000000000000000000000000000000000000..1e827ec0c31d0aac09b7a3271112ff4cb6fd25a9 --- /dev/null +++ b/unify/engine/wasm/compute.h @@ -0,0 +1,73 @@ +#pragma once +#include +#include +#include +#include "wasm.h" +#include "../core/handle.h" +#include "../memory/memory.h" +#include "../kernel/kernel.h" + +namespace unify { +class BinaryWriter; +class BinaryReader; + +/// A kernel argument: a buffer handle (passed to WASM as its byte offset) or a scalar. +struct KernelArg { + enum Kind { Buffer, Int, Float } kind; + uint32_t buffer = 0; // BufferHandle bits + int32_t i = 0; + float f = 0; + static KernelArg buf(BufferHandle h) { return {Buffer, h.bits, 0, 0}; } + static KernelArg integer(int32_t v) { return {Int, 0, v, 0}; } + static KernelArg real(float v) { return {Float, 0, 0, v}; } +}; + +struct DispatchResult { bool ok = true; std::string error; uint64_t instructions = 0; }; + +/// Owns the WASM linear memory shared by all kernels, the buffers inside it, and the +/// loaded kernel instances. All access is through validated handles. +class ComputeRuntime { +public: + explicit ComputeRuntime(uint32_t initial_pages = 16, uint32_t max_pages = 1024); + + // buffer.create / upload / download + BufferHandle buffer_create(uint32_t bytes); + bool buffer_destroy(BufferHandle h); + bool buffer_upload(BufferHandle h, const void* data, uint32_t bytes, uint32_t offset = 0); + bool buffer_download(BufferHandle h, void* out, uint32_t bytes, uint32_t offset = 0) const; + uint32_t buffer_size(BufferHandle h) const; + bool buffer_valid(BufferHandle h) const { return buffers_.valid(h); } + + // kernel.compile / load / dispatch + kernel::CompiledKernel compile(const std::string& source) const { return kernel::compile(source); } + /// Loads a compiled kernel (source is kept so save states can rebuild it). + KernelHandle load(const kernel::CompiledKernel& k, const std::string& source, std::string& error); + KernelHandle compile_and_load(const std::string& source, std::string& error); + bool unload(KernelHandle h); + DispatchResult dispatch(KernelHandle h, uint32_t grid, uint32_t block, const std::vector& args); + bool kernel_valid(KernelHandle h) const { return kernels_.valid(h); } + const kernel::CompiledKernel* kernel_info(KernelHandle h) const; + + uint32_t live_buffers() const { return buffers_.alive(); } + uint32_t live_kernels() const { return kernels_.alive(); } + uint32_t bytes_in_use() const { return alloc_.bytes_used(); } + uint32_t memory_pages() const { return memory_->pages(); } + + void serialize(BinaryWriter& w) const; + bool deserialize(BinaryReader& r, std::string& error); + +private: + struct Buf { uint32_t offset = 0, size = 0; }; + struct Kern { std::string source; kernel::CompiledKernel compiled; std::shared_ptr instance; }; + bool grow_to_fit(uint32_t bytes); + + std::shared_ptr memory_; + BufferAllocator alloc_; + HandlePool buffers_; + std::vector buf_; + HandlePool kernels_; + std::vector kern_; + static constexpr uint32_t kReserved = 16; // offset 0 is never handed out, so 0 never looks like a valid buffer +}; + +} // namespace unify diff --git a/unify/engine/wasm/decode.cpp b/unify/engine/wasm/decode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b7ecc3bd33829d040638c3fddb36c69a66e56f4 --- /dev/null +++ b/unify/engine/wasm/decode.cpp @@ -0,0 +1,268 @@ +#include "wasm.h" +#include + +namespace unify::wasm { + +Value Value::f32(float v) { uint32_t b; std::memcpy(&b, &v, 4); return {ValType::F32, b}; } +Value Value::f64(double v) { uint64_t b; std::memcpy(&b, &v, 8); return {ValType::F64, b}; } +float Value::as_f32() const { uint32_t b = uint32_t(bits); float v; std::memcpy(&v, &b, 4); return v; } +double Value::as_f64() const { double v; std::memcpy(&v, &bits, 8); return v; } + +void write_uleb(std::vector& out, uint64_t v) { + do { uint8_t b = v & 0x7F; v >>= 7; if (v) b |= 0x80; out.push_back(b); } while (v); +} +void write_sleb(std::vector& out, int64_t v) { + bool more = true; + while (more) { + uint8_t b = v & 0x7F; + v >>= 7; + if ((v == 0 && !(b & 0x40)) || (v == -1 && (b & 0x40))) more = false; else b |= 0x80; + out.push_back(b); + } +} + +namespace { +struct Reader { + const uint8_t* p; + const uint8_t* end; + std::string err; + bool ok() const { return err.empty(); } + bool need(size_t n) { if (size_t(end - p) < n) { if (err.empty()) err = "unexpected end of module"; return false; } return true; } + uint8_t u8() { return need(1) ? *p++ : 0; } + uint64_t uleb(int max_bits = 32) { + uint64_t r = 0; int shift = 0; + for (;;) { + if (!need(1)) return 0; + uint8_t b = *p++; + r |= uint64_t(b & 0x7F) << shift; + shift += 7; + if (!(b & 0x80)) break; + if (shift >= max_bits + 7) { err = "LEB128 too long"; return 0; } + } + return r; + } + int64_t sleb(int bits) { + int64_t r = 0; int shift = 0; uint8_t b; + do { + if (!need(1)) return 0; + b = *p++; + r |= int64_t(b & 0x7F) << shift; + shift += 7; + if (shift > bits + 7) { err = "LEB128 too long"; return 0; } + } while (b & 0x80); + if (shift < 64 && (b & 0x40)) r |= -(int64_t(1) << shift); + return r; + } + std::string name() { uint64_t n = uleb(); if (!need(n)) return {}; std::string s(reinterpret_cast(p), n); p += n; return s; } + ValType valtype() { + uint8_t t = u8(); + if (t != 0x7F && t != 0x7E && t != 0x7D && t != 0x7C) { err = "unsupported value type"; return ValType::I32; } + return ValType(t); + } +}; + +// Evaluates a constant initializer expression (i32/i64/f32/f64.const ... end). +Value const_expr(Reader& r) { + Value v; + uint8_t op = r.u8(); + switch (op) { + case 0x41: v = Value::i32(int32_t(r.sleb(32))); break; + case 0x42: v = Value::i64(r.sleb(64)); break; + case 0x43: { if (r.need(4)) { float f; std::memcpy(&f, r.p, 4); r.p += 4; v = Value::f32(f); } break; } + case 0x44: { if (r.need(8)) { double d; std::memcpy(&d, r.p, 8); r.p += 8; v = Value::f64(d); } break; } + default: r.err = "unsupported constant expression"; + } + if (r.u8() != 0x0B) r.err = "constant expression not terminated"; + return v; +} + +// Skips one instruction's immediates. Returns false for unknown opcodes. +bool skip_immediates(Reader& r, uint8_t op) { + switch (op) { + case 0x02: case 0x03: case 0x04: { // blocktype: 0x40, valtype, or s33 type index + uint8_t b = *r.p; + if (b == 0x40 || b == 0x7F || b == 0x7E || b == 0x7D || b == 0x7C) r.p++; else r.sleb(33); + return true; + } + case 0x0C: case 0x0D: case 0x10: case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: r.uleb(); return true; + case 0x0E: { uint64_t n = r.uleb(); for (uint64_t i = 0; i <= n; i++) r.uleb(); return true; } + case 0x11: r.uleb(); r.uleb(); return true; + case 0x3F: case 0x40: r.u8(); return true; + case 0x41: r.sleb(32); return true; + case 0x42: r.sleb(64); return true; + case 0x43: r.need(4); r.p += 4; return true; + case 0x44: r.need(8); r.p += 8; return true; + default: + if (op >= 0x28 && op <= 0x3E) { r.uleb(); r.uleb(); return true; } // memarg + if (op == 0x00 || op == 0x01 || op == 0x05 || op == 0x0B || op == 0x0F || op == 0x1A || op == 0x1B) return true; + if (op >= 0x45 && op <= 0xC4) return true; // numeric, no immediates + if (op == 0xFC) { r.uleb(); return true; } // saturating truncation prefix + return false; + } +} + +// Builds block -> end / if -> else maps so branches jump in O(log n) without rescanning. +bool index_blocks(Function& f, std::string& err) { + Reader r{f.code.data(), f.code.data() + f.code.size(), {}}; + std::vector open; + while (r.p < r.end && r.ok()) { + uint32_t at = uint32_t(r.p - f.code.data()); + uint8_t op = r.u8(); + if (op == 0x02 || op == 0x03 || op == 0x04) open.push_back(at); + if (op == 0x05) { + if (open.empty()) { err = "else without if"; return false; } + f.else_of[open.back()] = at; + } + if (op == 0x0B) { + if (open.empty()) { + if (r.p != r.end) { err = "code after function end"; return false; } + return true; + } + f.end_of[open.back()] = at; + open.pop_back(); + } + if (!skip_immediates(r, op)) { err = "unsupported opcode 0x" + std::to_string(op); return false; } + } + if (!r.ok()) { err = r.err; return false; } + err = "function body missing end"; + return false; +} +} // namespace + +bool decode(const std::vector& bytes, Module& m, std::string& error) { + m = Module{}; + Reader r{bytes.data(), bytes.data() + bytes.size(), {}}; + static const uint8_t magic[8] = {0x00, 'a', 's', 'm', 0x01, 0x00, 0x00, 0x00}; + if (bytes.size() < 8 || std::memcmp(bytes.data(), magic, 8)) { error = "not a WASM v1 module"; return false; } + r.p += 8; + std::vector func_types; + uint8_t last_id = 0; + while (r.p < r.end && r.ok()) { + uint8_t id = r.u8(); + uint64_t size = r.uleb(); + if (!r.need(size)) break; + Reader s{r.p, r.p + size, {}}; + r.p += size; + if (id != 0) { + if (id < last_id) { error = "sections out of order"; return false; } + last_id = id; + } + switch (id) { + case 0: break; // custom + case 1: { // type + uint64_t n = s.uleb(); + for (uint64_t i = 0; i < n && s.ok(); i++) { + if (s.u8() != 0x60) { s.err = "expected func type"; break; } + FuncType t; + uint64_t np = s.uleb(); for (uint64_t k = 0; k < np; k++) t.params.push_back(s.valtype()); + uint64_t nr = s.uleb(); for (uint64_t k = 0; k < nr; k++) t.results.push_back(s.valtype()); + if (t.results.size() > 1) { s.err = "multi-value results unsupported"; break; } + m.types.push_back(t); + } + break; + } + case 2: { // import + uint64_t n = s.uleb(); + for (uint64_t i = 0; i < n && s.ok(); i++) { + Import im; + im.module = s.name(); im.name = s.name(); im.kind = s.u8(); + if (im.kind == 0) { im.type_index = uint32_t(s.uleb()); m.imported_funcs++; } + else if (im.kind == 2) { + uint8_t flags = s.u8(); + im.min_pages = uint32_t(s.uleb()); + if (flags & 1) { im.max_pages = uint32_t(s.uleb()); im.has_max = true; } + m.has_memory = m.memory_imported = true; + m.memory_min = im.min_pages; m.memory_max = im.max_pages; m.memory_has_max = im.has_max; + } else { s.err = "only function and memory imports are supported"; } + m.imports.push_back(im); + } + break; + } + case 3: { uint64_t n = s.uleb(); for (uint64_t i = 0; i < n; i++) func_types.push_back(uint32_t(s.uleb())); break; } + case 4: { // table + uint64_t n = s.uleb(); + for (uint64_t i = 0; i < n; i++) { s.u8(); uint8_t f = s.u8(); s.uleb(); if (f & 1) s.uleb(); } + break; + } + case 5: { // memory + if (s.uleb() != 1) { s.err = "exactly one memory supported"; break; } + uint8_t flags = s.u8(); + m.memory_min = uint32_t(s.uleb()); + if (flags & 1) { m.memory_max = uint32_t(s.uleb()); m.memory_has_max = true; } + m.has_memory = true; + break; + } + case 6: { // global + uint64_t n = s.uleb(); + for (uint64_t i = 0; i < n && s.ok(); i++) { Global g; g.type = s.valtype(); g.mut = s.u8() != 0; g.init = const_expr(s); m.globals.push_back(g); } + break; + } + case 7: { // export + uint64_t n = s.uleb(); + for (uint64_t i = 0; i < n; i++) { Export e; e.name = s.name(); e.kind = s.u8(); e.index = uint32_t(s.uleb()); m.exports.push_back(e); } + break; + } + case 8: s.uleb(); break; // start (ignored: kernels have none) + case 9: { // elem (active, table 0, funcref indices) + uint64_t n = s.uleb(); + for (uint64_t i = 0; i < n && s.ok(); i++) { + if (s.uleb() != 0) { s.err = "unsupported element segment"; break; } + Value off = const_expr(s); + uint64_t k = s.uleb(); + uint32_t base = uint32_t(off.as_i32()); + if (m.table.size() < base + k) m.table.resize(base + k, 0xFFFFFFFFu); + for (uint64_t j = 0; j < k; j++) m.table[base + j] = uint32_t(s.uleb()); + } + break; + } + case 10: { // code + uint64_t n = s.uleb(); + if (n != func_types.size()) { s.err = "function/code count mismatch"; break; } + for (uint64_t i = 0; i < n && s.ok(); i++) { + uint64_t body_size = s.uleb(); + if (!s.need(body_size)) break; + Reader b{s.p, s.p + body_size, {}}; + s.p += body_size; + Function f; + f.type_index = func_types[i]; + uint64_t groups = b.uleb(); + for (uint64_t g = 0; g < groups && b.ok(); g++) { + uint64_t count = b.uleb(); + if (count > 50000) { b.err = "too many locals"; break; } + ValType t = b.valtype(); + for (uint64_t k = 0; k < count; k++) f.locals.push_back(t); + } + if (!b.ok()) { s.err = b.err; break; } + f.code.assign(b.p, b.end); + std::string e; + if (!index_blocks(f, e)) { s.err = "function " + std::to_string(i) + ": " + e; break; } + m.functions.push_back(std::move(f)); + } + break; + } + case 11: { // data (active, memory 0) + uint64_t n = s.uleb(); + for (uint64_t i = 0; i < n && s.ok(); i++) { + if (s.uleb() != 0) { s.err = "unsupported data segment"; break; } + DataSegment d; + d.offset = uint32_t(const_expr(s).as_i32()); + uint64_t len = s.uleb(); + if (!s.need(len)) break; + d.bytes.assign(s.p, s.p + len); + s.p += len; + m.data.push_back(std::move(d)); + } + break; + } + case 12: s.uleb(); break; // data count + default: error = "unknown section " + std::to_string(id); return false; + } + if (!s.ok()) { error = s.err; return false; } + } + if (!r.ok()) { error = r.err; return false; } + for (auto& f : m.functions) if (f.type_index >= m.types.size()) { error = "function type index out of range"; return false; } + for (auto& im : m.imports) if (im.kind == 0 && im.type_index >= m.types.size()) { error = "import type index out of range"; return false; } + return true; +} + +} // namespace unify::wasm diff --git a/unify/engine/wasm/exec.cpp b/unify/engine/wasm/exec.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d4aa1c5e463c3e33fd543bbf7af0d2f294ca160 --- /dev/null +++ b/unify/engine/wasm/exec.cpp @@ -0,0 +1,345 @@ +// WebAssembly interpreter. Executes decoded modules directly from their bytecode using +// precomputed block side tables. Every failure mode is a trap returned to the caller. +#include "wasm.h" +#include +#include +#include + +namespace unify::wasm { + +namespace { +// Portable integer bit operations for GCC, Clang and MSVC. +inline uint32_t leading_zeros(uint32_t x) { uint32_t n=32; for (;x;x>>=1) --n; return n; } +inline uint32_t trailing_zeros(uint32_t x) { if (!x) return 32; uint32_t n=0; while (!(x&1)) {++n;x>>=1;} return n; } +inline uint32_t population(uint32_t x) { uint32_t n=0; while (x) {x&=x-1;++n;} return n; } +inline uint32_t f2b(float f) { uint32_t b; std::memcpy(&b, &f, 4); return b; } +inline float b2f(uint64_t b) { uint32_t x = uint32_t(b); float f; std::memcpy(&f, &x, 4); return f; } +inline uint64_t d2b(double d) { uint64_t b; std::memcpy(&b, &d, 8); return b; } +inline double b2d(uint64_t b) { double d; std::memcpy(&d, &b, 8); return d; } + +struct Code { + const uint8_t* base; + const uint8_t* p; + uint32_t pos() const { return uint32_t(p - base); } + uint64_t uleb() { uint64_t r = 0; int s = 0; uint8_t b; do { b = *p++; r |= uint64_t(b & 0x7F) << s; s += 7; } while (b & 0x80); return r; } + int64_t sleb() { int64_t r = 0; int s = 0; uint8_t b; do { b = *p++; r |= int64_t(b & 0x7F) << s; s += 7; } while (b & 0x80); if (s < 64 && (b & 0x40)) r |= -(int64_t(1) << s); return r; } +}; + +template F wasm_min(F a, F b) { + if (std::isnan(a) || std::isnan(b)) return std::numeric_limits::quiet_NaN(); + if (a == b) return std::signbit(a) ? a : b; // min(-0, +0) = -0 + return a < b ? a : b; +} +template F wasm_max(F a, F b) { + if (std::isnan(a) || std::isnan(b)) return std::numeric_limits::quiet_NaN(); + if (a == b) return std::signbit(a) ? b : a; + return a > b ? a : b; +} + +struct Label { uint32_t cont; uint32_t height; uint32_t arity; bool loop; }; +} // namespace + +const FuncType& Instance::type_of(uint32_t idx) const { + if (idx < module_->imported_funcs) { + uint32_t k = 0; + for (auto& im : module_->imports) if (im.kind == 0 && k++ == idx) return module_->types[im.type_index]; + } + return module_->types[module_->functions[idx - module_->imported_funcs].type_index]; +} + +bool Instance::instantiate(std::shared_ptr module, std::shared_ptr shared_memory, + const std::map& host_funcs, std::string& error) { + module_ = std::move(module); + host_.clear(); + for (auto& im : module_->imports) { + if (im.kind != 0) continue; + auto it = host_funcs.find(im.module + "." + im.name); + if (it == host_funcs.end()) { error = "unresolved import " + im.module + "." + im.name; return false; } + host_.push_back(it->second); + } + if (module_->memory_imported) { + if (!shared_memory) { error = "module imports a memory but none was provided"; return false; } + if (shared_memory->pages() < module_->memory_min) { error = "provided memory is smaller than the import minimum"; return false; } + memory_ = shared_memory; + } else if (module_->has_memory) { + memory_ = std::make_shared(); + memory_->max_pages = module_->memory_has_max ? module_->memory_max : 65536; + memory_->bytes.assign(size_t(module_->memory_min) * Memory::kPage, 0); + } + for (auto& d : module_->data) { + if (!memory_ || uint64_t(d.offset) + d.bytes.size() > memory_->bytes.size()) { error = "data segment out of bounds"; return false; } + std::memcpy(memory_->bytes.data() + d.offset, d.bytes.data(), d.bytes.size()); + } + globals_.clear(); + for (auto& g : module_->globals) globals_.push_back(g.init); + return true; +} + +bool Instance::has_export(const std::string& name) const { + for (auto& e : module_->exports) if (e.kind == 0 && e.name == name) return true; + return false; +} + +ExecResult Instance::call(const std::string& name, const std::vector& args) { + for (auto& e : module_->exports) + if (e.kind == 0 && e.name == name) return call_index(e.index, args); + ExecResult r; + r.ok = false; + r.trap = "no exported function '" + name + "'"; + return r; +} + +ExecResult Instance::call_index(uint32_t idx, const std::vector& args) { + ExecResult r; + uint32_t total = module_->imported_funcs + uint32_t(module_->functions.size()); + if (idx >= total) { r.ok = false; r.trap = "function index out of range"; return r; } + const FuncType& t = type_of(idx); + if (args.size() != t.params.size()) { r.ok = false; r.trap = "argument count mismatch"; return r; } + for (size_t i = 0; i < args.size(); i++) + if (args[i].type != t.params[i]) { r.ok = false; r.trap = "argument " + std::to_string(i) + " has the wrong type"; return r; } + std::vector stack; + stack.reserve(1024); + for (auto& a : args) stack.push_back(a.bits); + r.ok = run(idx, stack, r.trap, r.instructions, 0); + if (r.ok) for (size_t i = 0; i < t.results.size(); i++) r.results.push_back({t.results[i], stack[stack.size() - t.results.size() + i]}); + return r; +} + +bool Instance::run(uint32_t idx, std::vector& stack, std::string& trap, uint64_t& executed, uint32_t depth) { + if (depth > max_call_depth) { trap = "call stack exhausted"; return false; } + const FuncType& ft = type_of(idx); + if (idx < module_->imported_funcs) { + std::vector args(ft.params.size()), results; + for (size_t i = ft.params.size(); i-- > 0;) { args[i] = {ft.params[i], stack.back()}; stack.pop_back(); } + if (!host_[idx](args, results, trap)) return false; + if (results.size() != ft.results.size()) { trap = "host function returned wrong result count"; return false; } + for (auto& v : results) stack.push_back(v.bits); + return true; + } + const Function& fn = module_->functions[idx - module_->imported_funcs]; + std::vector locals(ft.params.size() + fn.locals.size(), 0); + for (size_t i = ft.params.size(); i-- > 0;) { locals[i] = stack.back(); stack.pop_back(); } + const uint32_t base_height = uint32_t(stack.size()); + std::vector