diff --git a/AGENTS.md b/AGENTS.md index b86c2d6..5a8cb78 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,86 +1,44 @@ -# Aquarium Engine Instructions +# Epiphany Aquarium Instructions ## Purpose -Aquarium Engine is the native C# runtime for the Epiphany Aquarium client. It -owns the window, renderer, input loop, live-reload boundary, persistent client -state, and eventual diegetic UI machinery. +This repo is the Epiphany Aquarium client. It owns Epiphany-facing runtime +semantics, agent visuals, CultCache documents, CultNet interpretation, voice +surfaces, and client-authored render plans. -This repo is not the Epiphany harness. The visible frame belongs to Aquarium. +The native host and renderer live in the adjacent Fensalir repo: +`E:\Projects\Fensalir`. ## Operating Doctrine -- The renderer is the source of truth for visible world pixels. -- Keep the frame legible: explicit passes, explicit ownership, explicit state. -- Do not leave lies in the walls. When building engine systems meant to last, - refuse half-assed shortcuts, hidden compensators, mystery state, and - prototype-shaped production code. Prefer full-ass, research-backed, - steel-plated resilience with padded failure boundaries so users do not cut - themselves on sharp internals. -- This is game engine work: every millisecond counts. Do not spend runtime - casually on avoidable JSON churn, spaghetti state, redundant ray work, - unbounded full-resolution filters, or convenience abstractions that hide - performance costs. If a shortcut is temporary, mark it as scaffolding and cut - it before it becomes architecture. -- Before inventing renderer, simulation, storage, or post-processing machinery, - check standard literature, production talks, engine docs, or proven local - patterns. Build the durable machine, not a sequence of shy approximations that - accrete into Jenga. -- When a visual, physical, or simulation spec describes a continuous form, start - with continuous field math or a coherent parameterization that owns the form. - Do not assemble the thing from piecewise capsules, boxes, slabs, adapters, or - helper organs just because that is the shortest path to pixels. Piecewise - construction is allowed only when the form itself is piecewise or when a - measured constraint makes the continuous model impractical; document that cut - line and keep the compensator small. -- The camera target is the Grid center. Grid radius follows zoom distance. - Pitch, yaw, and screen projection do not resize the Grid. -- Body anchors are world-space simulation state. They do not ride with the Grid - visibility window. -- Lighting is diegetic. Self, field sources, and Aquarium-owned transport light - the scene; ambient convenience light is guilty until proven useful. -- Overlay UI and diegetic UI are different beasts. Overlay text can use - DirectWrite. Scene text should become renderer-owned MSDF/SDF billboards when - it belongs in the world. -- CultCache is the runtime memory organ. Camera state, reload state, renderer - knobs, UI state, body state, and future Epiphany connection state should be - typed Cult documents, not loose JSON or process-only folklore. -- CultNet is the communication surface for Epiphany agents. Add transport - deliberately and keep authority boundaries typed. +- Epiphany owns meaning; Fensalir owns the machine that displays and reloads it. +- Keep dependency direction one-way: this repo can reference Fensalir, but + Fensalir must not learn Epiphany nouns. +- Client render code should publish explicit contracts and shaders. Do not sneak + renderer policy, D3D12 plumbing, or host lifecycle code back into this repo. +- CultCache documents are typed client state, not loose JSON sidecars. +- CultNet surfaces are semantic input. Spatial placement, body projection, and + renderer budget belong to the client/runtime contract, not to chat folklore. +- If an engine capability is missing, add it in Fensalir and consume it here. + Do not build a small private engine because the real one is across the hall. ## Persistent State -- `state/map.yaml` is the canonical project map. -- `state/memory.json` is durable engine doctrine and taste. -- `state/evidence.jsonl` stores distilled lessons that should change future - behavior. +- `state/map.yaml` is the canonical client map. +- `state/memory.json` is durable Epiphany Aquarium doctrine and taste. +- `state/evidence.jsonl` stores lessons that should change future behavior. - `state/scratch.md` is disposable working context for the active slice. -Update these when the engine learns something durable. Delete stale guidance -instead of embalming it. +Update state when ownership, contracts, or client doctrine changes. ## Verification -Use focused checks: - ```powershell -dotnet build Aquarium.Engine.sln +dotnet build EpiphanyAquarium.sln .\scripts\dev-reload.ps1 -Headless -RetainSlots 4 ``` -For normal iteration: - -```powershell -.\scripts\dev-watch.ps1 -``` - -For shipping: - -```powershell -.\scripts\publish-win-x64.ps1 -Clean -Zip -``` - ## Style -Prefer small, intentional commits. Push completed work. Keep docs about the live -system; put old branch scars only in evidence when they alter future decisions. +Keep docs about the live system. Historical scars belong in evidence only when +they change future decisions. diff --git a/Aquarium.Engine.sln b/Aquarium.Engine.sln deleted file mode 100644 index 8b08f3f..0000000 --- a/Aquarium.Engine.sln +++ /dev/null @@ -1,322 +0,0 @@ - -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", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine.Contracts", "src\Aquarium.Engine.Contracts\Aquarium.Engine.Contracts.csproj", "{08D15A38-B6AB-459B-8BF9-3CCA8555A022}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine", "src\Aquarium.Engine\Aquarium.Engine.csproj", "{51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CultMath", "..\CultMath\src\CultMath\CultMath.csproj", "{0089E341-25F2-43FC-8FD9-CBD1AE646D91}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Epiphany", "src\Aquarium.Epiphany\Aquarium.Epiphany.csproj", "{33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Caching.MessagePack", "..\CultLib\src\GameCult.Caching.MessagePack\GameCult.Caching.MessagePack.csproj", "{A8EDAE19-805B-4B09-9566-BE63937CA1B9}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Caching", "..\CultLib\src\GameCult.Caching\GameCult.Caching.csproj", "{6E874823-17F8-453C-A077-4A101D425C84}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Logging", "..\CultLib\src\GameCult.Logging\GameCult.Logging.csproj", "{68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Caching.MessagePack.Analyzers", "..\CultLib\src\GameCult.Caching.MessagePack.Analyzers\GameCult.Caching.MessagePack.Analyzers.csproj", "{225265F1-8278-48D7-B271-BE8841D0C1CA}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Caching.MessagePack.Generator", "..\CultLib\src\GameCult.Caching.MessagePack.Generator\GameCult.Caching.MessagePack.Generator.csproj", "{435C602F-025E-4948-8285-E83E693DAA7B}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameCult.Networking", "..\CultLib\src\GameCult.Networking\GameCult.Networking.csproj", "{BDE44048-7BA1-45C0-A69C-F70E5188FFE1}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Sample.Minimal", "src\Aquarium.Sample.Minimal\Aquarium.Sample.Minimal.csproj", "{7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine.Tests", "tests\Aquarium.Engine.Tests\Aquarium.Engine.Tests.csproj", "{37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Epiphany.AgentPreview", "src\Aquarium.Epiphany.AgentPreview\Aquarium.Epiphany.AgentPreview.csproj", "{F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Zyphos", "src\Aquarium.Zyphos\Aquarium.Zyphos.csproj", "{801B1913-6AE1-4B8C-8030-4669AC4FE25E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine.Fractal", "src\Aquarium.Engine.Fractal\Aquarium.Engine.Fractal.csproj", "{FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine.Fractal.Tests", "tests\Aquarium.Engine.Fractal.Tests\Aquarium.Engine.Fractal.Tests.csproj", "{A9D41C48-7E78-4D75-A814-0C1500245EFC}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.LocalCast", "src\Aquarium.LocalCast\Aquarium.LocalCast.csproj", "{E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.LocalCast.Tests", "tests\Aquarium.LocalCast.Tests\Aquarium.LocalCast.Tests.csproj", "{E6560D72-B018-4E00-AEBD-C1B9419E0BC7}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{07C2787E-EAC7-C090-1BA3-A61EC2A24D84}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Fractal.Receipt", "tools\Aquarium.Fractal.Receipt\Aquarium.Fractal.Receipt.csproj", "{C0D1BFAC-B1B4-4350-92A7-D537AE382909}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Fensalir", "src\Aquarium.Fensalir\Aquarium.Fensalir.csproj", "{F9274D99-3CC6-42B6-9817-EC7F19663B1D}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Debug|Any CPU.Build.0 = Debug|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Debug|x64.ActiveCfg = Debug|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Debug|x64.Build.0 = Debug|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Debug|x86.ActiveCfg = Debug|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Debug|x86.Build.0 = Debug|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Release|Any CPU.ActiveCfg = Release|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Release|Any CPU.Build.0 = Release|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Release|x64.ActiveCfg = Release|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Release|x64.Build.0 = Release|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Release|x86.ActiveCfg = Release|Any CPU - {08D15A38-B6AB-459B-8BF9-3CCA8555A022}.Release|x86.Build.0 = Release|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Debug|x64.ActiveCfg = Debug|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Debug|x64.Build.0 = Debug|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Debug|x86.ActiveCfg = Debug|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Debug|x86.Build.0 = Debug|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Release|Any CPU.Build.0 = Release|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Release|x64.ActiveCfg = Release|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Release|x64.Build.0 = Release|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Release|x86.ActiveCfg = Release|Any CPU - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1}.Release|x86.Build.0 = Release|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Debug|x64.ActiveCfg = Debug|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Debug|x64.Build.0 = Debug|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Debug|x86.ActiveCfg = Debug|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Debug|x86.Build.0 = Debug|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Release|Any CPU.Build.0 = Release|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Release|x64.ActiveCfg = Release|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Release|x64.Build.0 = Release|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Release|x86.ActiveCfg = Release|Any CPU - {0089E341-25F2-43FC-8FD9-CBD1AE646D91}.Release|x86.Build.0 = Release|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|Any CPU.Build.0 = Debug|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|x64.ActiveCfg = Debug|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|x64.Build.0 = Debug|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|x86.ActiveCfg = Debug|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|x86.Build.0 = Debug|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|Any CPU.ActiveCfg = Release|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|Any CPU.Build.0 = Release|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|x64.ActiveCfg = Release|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|x64.Build.0 = Release|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|x86.ActiveCfg = Release|Any CPU - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|x86.Build.0 = Release|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Debug|x64.ActiveCfg = Debug|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Debug|x64.Build.0 = Debug|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Debug|x86.ActiveCfg = Debug|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Debug|x86.Build.0 = Debug|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Release|Any CPU.Build.0 = Release|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Release|x64.ActiveCfg = Release|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Release|x64.Build.0 = Release|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Release|x86.ActiveCfg = Release|Any CPU - {A8EDAE19-805B-4B09-9566-BE63937CA1B9}.Release|x86.Build.0 = Release|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Debug|x64.ActiveCfg = Debug|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Debug|x64.Build.0 = Debug|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Debug|x86.ActiveCfg = Debug|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Debug|x86.Build.0 = Debug|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Release|Any CPU.Build.0 = Release|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Release|x64.ActiveCfg = Release|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Release|x64.Build.0 = Release|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Release|x86.ActiveCfg = Release|Any CPU - {6E874823-17F8-453C-A077-4A101D425C84}.Release|x86.Build.0 = Release|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Debug|x64.ActiveCfg = Debug|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Debug|x64.Build.0 = Debug|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Debug|x86.ActiveCfg = Debug|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Debug|x86.Build.0 = Debug|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Release|Any CPU.Build.0 = Release|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Release|x64.ActiveCfg = Release|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Release|x64.Build.0 = Release|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Release|x86.ActiveCfg = Release|Any CPU - {68AF73A1-65FE-4BCE-BDF6-8CB3DF12033E}.Release|x86.Build.0 = Release|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Debug|x64.ActiveCfg = Debug|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Debug|x64.Build.0 = Debug|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Debug|x86.ActiveCfg = Debug|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Debug|x86.Build.0 = Debug|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Release|Any CPU.Build.0 = Release|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Release|x64.ActiveCfg = Release|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Release|x64.Build.0 = Release|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Release|x86.ActiveCfg = Release|Any CPU - {225265F1-8278-48D7-B271-BE8841D0C1CA}.Release|x86.Build.0 = Release|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Debug|x64.ActiveCfg = Debug|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Debug|x64.Build.0 = Debug|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Debug|x86.ActiveCfg = Debug|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Debug|x86.Build.0 = Debug|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Release|Any CPU.Build.0 = Release|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Release|x64.ActiveCfg = Release|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Release|x64.Build.0 = Release|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Release|x86.ActiveCfg = Release|Any CPU - {435C602F-025E-4948-8285-E83E693DAA7B}.Release|x86.Build.0 = Release|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Debug|x64.ActiveCfg = Debug|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Debug|x64.Build.0 = Debug|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Debug|x86.ActiveCfg = Debug|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Debug|x86.Build.0 = Debug|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Release|Any CPU.Build.0 = Release|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Release|x64.ActiveCfg = Release|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Release|x64.Build.0 = Release|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Release|x86.ActiveCfg = Release|Any CPU - {BDE44048-7BA1-45C0-A69C-F70E5188FFE1}.Release|x86.Build.0 = Release|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Debug|x64.ActiveCfg = Debug|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Debug|x64.Build.0 = Debug|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Debug|x86.ActiveCfg = Debug|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Debug|x86.Build.0 = Debug|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Release|Any CPU.Build.0 = Release|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Release|x64.ActiveCfg = Release|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Release|x64.Build.0 = Release|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Release|x86.ActiveCfg = Release|Any CPU - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA}.Release|x86.Build.0 = Release|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Debug|x64.ActiveCfg = Debug|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Debug|x64.Build.0 = Debug|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Debug|x86.ActiveCfg = Debug|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Debug|x86.Build.0 = Debug|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Release|Any CPU.Build.0 = Release|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Release|x64.ActiveCfg = Release|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Release|x64.Build.0 = Release|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Release|x86.ActiveCfg = Release|Any CPU - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB}.Release|x86.Build.0 = Release|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|x64.ActiveCfg = Debug|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|x64.Build.0 = Debug|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|x86.ActiveCfg = Debug|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|x86.Build.0 = Debug|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|Any CPU.Build.0 = Release|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|x64.ActiveCfg = Release|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|x64.Build.0 = Release|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|x86.ActiveCfg = Release|Any CPU - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|x86.Build.0 = Release|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Debug|x64.ActiveCfg = Debug|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Debug|x64.Build.0 = Debug|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Debug|x86.ActiveCfg = Debug|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Debug|x86.Build.0 = Debug|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Release|Any CPU.Build.0 = Release|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Release|x64.ActiveCfg = Release|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Release|x64.Build.0 = Release|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Release|x86.ActiveCfg = Release|Any CPU - {801B1913-6AE1-4B8C-8030-4669AC4FE25E}.Release|x86.Build.0 = Release|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Debug|x64.ActiveCfg = Debug|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Debug|x64.Build.0 = Debug|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Debug|x86.ActiveCfg = Debug|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Debug|x86.Build.0 = Debug|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Release|Any CPU.Build.0 = Release|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Release|x64.ActiveCfg = Release|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Release|x64.Build.0 = Release|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Release|x86.ActiveCfg = Release|Any CPU - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0}.Release|x86.Build.0 = Release|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Debug|x64.ActiveCfg = Debug|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Debug|x64.Build.0 = Debug|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Debug|x86.ActiveCfg = Debug|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Debug|x86.Build.0 = Debug|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Release|Any CPU.Build.0 = Release|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Release|x64.ActiveCfg = Release|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Release|x64.Build.0 = Release|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Release|x86.ActiveCfg = Release|Any CPU - {A9D41C48-7E78-4D75-A814-0C1500245EFC}.Release|x86.Build.0 = Release|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Debug|x64.ActiveCfg = Debug|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Debug|x64.Build.0 = Debug|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Debug|x86.ActiveCfg = Debug|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Debug|x86.Build.0 = Debug|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Release|Any CPU.Build.0 = Release|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Release|x64.ActiveCfg = Release|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Release|x64.Build.0 = Release|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Release|x86.ActiveCfg = Release|Any CPU - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F}.Release|x86.Build.0 = Release|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Debug|x64.ActiveCfg = Debug|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Debug|x64.Build.0 = Debug|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Debug|x86.ActiveCfg = Debug|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Debug|x86.Build.0 = Debug|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Release|Any CPU.Build.0 = Release|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Release|x64.ActiveCfg = Release|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Release|x64.Build.0 = Release|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Release|x86.ActiveCfg = Release|Any CPU - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7}.Release|x86.Build.0 = Release|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|x64.ActiveCfg = Debug|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|x64.Build.0 = Debug|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|x86.ActiveCfg = Debug|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Debug|x86.Build.0 = Debug|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|Any CPU.Build.0 = Release|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|x64.ActiveCfg = Release|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|x64.Build.0 = Release|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|x86.ActiveCfg = Release|Any CPU - {C0D1BFAC-B1B4-4350-92A7-D537AE382909}.Release|x86.Build.0 = Release|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Debug|x64.ActiveCfg = Debug|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Debug|x64.Build.0 = Debug|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Debug|x86.ActiveCfg = Debug|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Debug|x86.Build.0 = Debug|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|Any CPU.Build.0 = Release|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x64.ActiveCfg = Release|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x64.Build.0 = Release|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x86.ActiveCfg = Release|Any CPU - {F9274D99-3CC6-42B6-9817-EC7F19663B1D}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {08D15A38-B6AB-459B-8BF9-3CCA8555A022} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {51FE01D8-9EEF-46B2-8D8C-3307AC2221C1} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {7564E6C2-FF01-4B5B-8C2B-F9CD796858BA} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {37363FC6-5AA3-49B4-A3B1-E4AB2CC986EB} = {0AB3BF05-4346-4AA6-1389-037BE0695223} - {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {801B1913-6AE1-4B8C-8030-4669AC4FE25E} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {F9274D99-3CC6-42B6-9817-EC7F19663B1D} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {FF232A59-4E8D-4D56-A2C3-ACC02F5371D0} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {A9D41C48-7E78-4D75-A814-0C1500245EFC} = {0AB3BF05-4346-4AA6-1389-037BE0695223} - {E8C66A46-1F56-484D-8CDD-5C0A3FD84A5F} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {E6560D72-B018-4E00-AEBD-C1B9419E0BC7} = {0AB3BF05-4346-4AA6-1389-037BE0695223} - {C0D1BFAC-B1B4-4350-92A7-D537AE382909} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} - {F9274D99-3CC6-42B6-9817-EC7F19663B1D} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - EndGlobalSection -EndGlobal diff --git a/EpiphanyAquarium.sln b/EpiphanyAquarium.sln new file mode 100644 index 0000000..08ee32a --- /dev/null +++ b/EpiphanyAquarium.sln @@ -0,0 +1,54 @@ + +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", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Epiphany", "src\Aquarium.Epiphany\Aquarium.Epiphany.csproj", "{33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Epiphany.AgentPreview", "src\Aquarium.Epiphany.AgentPreview\Aquarium.Epiphany.AgentPreview.csproj", "{F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|Any CPU.Build.0 = Debug|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|x64.ActiveCfg = Debug|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|x64.Build.0 = Debug|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|x86.ActiveCfg = Debug|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Debug|x86.Build.0 = Debug|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|Any CPU.ActiveCfg = Release|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|Any CPU.Build.0 = Release|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|x64.ActiveCfg = Release|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|x64.Build.0 = Release|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|x86.ActiveCfg = Release|Any CPU + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65}.Release|x86.Build.0 = Release|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|x64.ActiveCfg = Debug|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|x64.Build.0 = Debug|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|x86.ActiveCfg = Debug|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Debug|x86.Build.0 = Debug|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|Any CPU.Build.0 = Release|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|x64.ActiveCfg = Release|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|x64.Build.0 = Release|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|x86.ActiveCfg = Release|Any CPU + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {33654E0D-B31A-4062-B6AC-C1CE4C1A1F65} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {F12A367A-8D8E-490D-B60E-3FDBEA3E07E2} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + EndGlobalSection +EndGlobal diff --git a/Fensalir-Icon.png b/Fensalir-Icon.png deleted file mode 100644 index 7d937f4..0000000 Binary files a/Fensalir-Icon.png and /dev/null differ diff --git a/README.md b/README.md index ff395c7..23c3c7c 100644 --- a/README.md +++ b/README.md @@ -1,248 +1,54 @@ -# Fensalir +# Epiphany Aquarium -

- Fensalir icon -

+Epiphany Aquarium is the Epiphany-owned client for the Fensalir native runtime. +This repo owns client semantics: agent bodies, camera intent, CultCache state, +CultNet interpretation, voice surfaces, and Epiphany-specific shaders. -Fensalir is the C# native rendering spine for Aquarium clients: windowing, -D3D12 rendering, input, reload, persistent state, debug UI, and packageable -engine machinery. - -Epiphany is the first serious client in this repo. It is not the engine's -identity. - -## Intent - -- Native C# host with a legible renderer spine and explicit ownership. -- Vortice/D3D12 backend with graphics API details contained inside the engine. -- `Aquarium.Engine.Contracts` as the client-facing boundary. -- `Aquarium.Epiphany` as the current Epiphany Aquarium client. -- `Aquarium.Sample.Minimal` as a small non-Epiphany boundary proof. -- DirectWrite/Direct2D overlay text after the scene pass for crisp debug and UI - typography. -- Diegetic scene/UI surfaces driven by client objects instead of admin chrome. -- CultCache for typed settings, persistent client state, and reload recovery. -- CultNet-ready runtime identity for clients that need Epiphany communication. -- Procedural audio and visual state treated as coupled signals. - -## Current Shape - -The engine opens a Win32 window, owns a D3D12 swapchain, compiles and hot-reloads -HLSL, allocates render targets, preserves last-good shader/runtime state across -failed reloads, hosts the debug overlay, and presents scene-linear HDR through -the current post stack. - -Client code is loaded behind `Aquarium.Engine.Contracts`, so a client can reload -while the engine host, window, renderer, and D3D device stay alive. Runtime state -is banked through CultCache MessagePack documents instead of loose JSON. - -`Aquarium.Epiphany` currently supplies the Grid-centered camera policy, Epiphany -agent SDF shaders, body placement, CultCache documents, and future CultNet -interpretation. Those are client semantics. The engine consumes them as generic -rendering and runtime data. +Fensalir owns the window, renderer, D3D12 backend, audio device path, hot reload, +debug chrome, contracts, fractal machinery, and engine demos. It lives next to +this repo at `E:\Projects\Fensalir`. ## Repository Shape -This repository intentionally contains both the reusable Aquarium engine and the -Epiphany client while the client API is still being carved into its final shape: +- `src/Aquarium.Epiphany`: the runtime loaded by the Fensalir host. +- `src/Aquarium.Epiphany.AgentPreview`: isolated Epiphany agent preview tool. +- `docs`: Epiphany/client boundary notes. +- `state`: repo memory, map, evidence, and scratch state for the client. +- `scripts`: thin wrappers that delegate host/watch/reload work to Fensalir. -- `src/Aquarium.Engine.Contracts`: Vortice-free client API and shared data - contracts. -- `src/Aquarium.Engine`: Win32 host, D3D12 backend, reload transport, debug UI, - audio host, and engine-owned assets. -- `src/Aquarium.Epiphany`: Epiphany Aquarium runtime, state interpretation, - render-plan configuration, and agent shaders. -- `src/Aquarium.Zyphos`: planetary-scale rendering demo client with its own - runtime, controls, scene state, and SDF planet shaders. -- `src/Aquarium.Sample.Minimal`: tiny non-Epiphany client that proves the host - can run something other than Epiphany. +The client references Fensalir source projects directly while the package +boundary is still young. Do not copy engine contracts back into this repo. -Splitting Aquarium and Epiphany into separate repos is plausible, but not owed -yet. The cut becomes clean when the contracts are stable enough that Epiphany can -move out without taking renderer policy, shader include plumbing, or reload -folklore with it. Until then, the repo split would mostly create paperwork and a -new place for confusion to hide. +## Build + +```powershell +dotnet build EpiphanyAquarium.sln +``` ## Run -Aquarium currently expects the sibling `CultMath` and `CultLib` repos at -`E:\Projects\CultMath` and `E:\Projects\CultLib`, or the equivalent -`..\..\..\CultMath` / `..\..\..\CultLib` paths from the engine project. - -Aquarium consumes `AquaSynth.Faust` from the repo-local `packages` NuGet feed, -not as a live project reference to `AquaSynth`. That package pulls -`AquaSynth.Core` transitively for the built-in patch editor. This keeps Aquarium -builds stable while synth work is in flight. To intentionally update that -boundary, pack a new synth version and bump the `Aquarium.Engine` package -reference: - -```powershell -.\scripts\update-synth-package.ps1 -``` - -```powershell -dotnet build Aquarium.Engine.sln -dotnet run --project src\Aquarium.Engine\Aquarium.Engine.csproj -- --client-assembly src\Aquarium.Epiphany\bin\Debug\net10.0\Aquarium.Epiphany.dll -``` - -Open or build `Aquarium.Engine.sln`. It is the single solution inventory for the -repo. - -`src\Aquarium.Sample.Minimal` is a tiny non-Epiphany client used to keep the -engine boundary honest. It references only `Aquarium.Engine.Contracts`, declares -an `AquariumRenderPlan`, and boots through the same host/client loader path. - -`src\Aquarium.Zyphos` is the first nontrivial non-Epiphany demo. It renders a -rotating spherical planet, procedural continents, atmospheric rim light, -night-side city glints, and an orbiting moon through the same host, renderer, -reload, UI, bloom, and SDF proxy machinery used by Epiphany. - -For iteration while an Aquarium window is already open, use the dev reload -runner instead of `dotnet run`: - ```powershell .\scripts\dev-reload.ps1 ``` -It builds an apphost executable into a fresh disposable slot under -`artifacts\dev-reload`, records the slot/PID in PowerShell CLIXML, and launches -the runtime with a MessagePack CultCache store at -`artifacts\dev-reload\cultcache\aquarium-client.msgpack`. -The previous script-owned process is stopped only after the replacement build -succeeds. This keeps MSBuild away from the locked normal `bin\Debug` output -while a live window is still open. +The wrapper calls `E:\Projects\Fensalir\scripts\dev-reload.ps1` with +`src\Aquarium.Epiphany\Aquarium.Epiphany.csproj` as the client project. -Run a different client project through the same slot machinery with -`-ClientProject`: +For a headless smoke: ```powershell -.\scripts\dev-reload.ps1 -ClientProject src\Aquarium.Zyphos\Aquarium.Zyphos.csproj +.\scripts\dev-reload.ps1 -Headless -RetainSlots 4 ``` -If the visible dev window was closed but the last slot is still present, reopen -it without rebuilding: - -```powershell -.\scripts\dev-reload.ps1 -Reopen -``` - -Visible and headless runs keep separate PID state and logs, so a headless smoke -does not replace the visible dev window. - -For automatic rebuild/restart on source changes, use the watcher: +For the watcher: ```powershell .\scripts\dev-watch.ps1 ``` -Watch a specific client project the same way: +## Boundary -```powershell -.\scripts\dev-watch.ps1 -ClientProject src\Aquarium.Zyphos\Aquarium.Zyphos.csproj -``` - -The watcher polls source files, waits for writes to settle, builds into a new -slot, and only replaces the running Aquarium after the new build succeeds. If a -build fails, the previous good process keeps running and that same broken source -fingerprint is not retried until files change again. -It also watches the recorded script-owned process. If the visible window is -closed or the recorded process dies, the watcher relaunches from a fresh slot on -the next poll instead of sitting there with its hands folded like this is fine. -To reopen a closed visible window from the last good slot without rebuilding, -run the watcher with: - -```powershell -.\scripts\dev-watch.ps1 -ReopenWhenClosed -``` - -Shader edits do not restart the process. The dev watcher fingerprints -`.hlsl`/`.hlsli` files under both the engine and selected client shader roots, -copies them into the running apphost slot, and lets the renderer rebuild the -active D3D12 pipelines from its current shader source root. A bad shader edit -leaves the previous working shaders bound and writes the compiler failure to -stderr. - -Epiphany client/runtime code is split into `Aquarium.Epiphany` behind -`Aquarium.Engine.Contracts`. The host loads that client DLL through a collectible -assembly load context, while `dev-watch.ps1` builds client-only changes into -`artifacts\dev-reload\live-slots` and updates `live-current.txt`. The running -host sees the pointer change, loads and starts the new runtime first, then -disposes the old one only after the replacement is valid. A bad client DLL leaves -the previous runtime alive and reports the reload failure to stderr. The watcher -waits for the host log to acknowledge the exact client DLL path before calling a -client reload successful; pointer updates without host acknowledgement are treated -as reload failures. Successful reloads rehydrate through CultCache without -restarting the window or D3D device. -Host, renderer, contract, project, script, and `src\Aquarium.Engine\Assets` -content changes still rebuild and restart the apphost. Runtime content belongs -to the process image; shader hot reload cannot make a running renderer discover -new files it never loaded. - -Runtime live state is a typed CultCache document, not a loose sidecar file. The -first document is `epiphany.aquarium.live_state`, currently banking camera -target, yaw, pitch, distance, time, and save generation every few frames so a -reload can rehydrate without pretending memory is vibes. - -Stop the script-owned Aquarium process: - -```powershell -.\scripts\dev-stop.ps1 -``` - -Headless smoke: - -```powershell -dotnet run --project src\Aquarium.Engine\Aquarium.Engine.csproj -- --headless --client-assembly src\Aquarium.Epiphany\bin\Debug\net10.0\Aquarium.Epiphany.dll -``` - -Headless reload smoke without touching the normal build output: - -```powershell -.\scripts\dev-reload.ps1 -Headless -``` - -Renderer/client boundary check: - -```powershell -.\scripts\verify-boundaries.ps1 -``` - -Headless watch smoke: - -```powershell -.\scripts\dev-watch.ps1 -Headless -``` - -Shipping publish: - -```powershell -.\scripts\publish-win-x64.ps1 -Clean -Zip -``` - -This writes a self-contained Windows build to -`artifacts\publish\win-x64`, verifies the executable, Epiphany client DLL, -contracts DLL, icon, bundled fonts, and shader source, then optionally creates -`artifacts\publish\EpiphanyAquariumEngine-win-x64.zip`. - -## Persistent State - -This repo carries its own Aquarium memory: - -- `state/map.yaml`: canonical project map and next actions. -- `state/memory.json`: durable taste, doctrine, renderer rules, and warnings. -- `state/evidence.jsonl`: compact lessons that should change future behavior. -- `state/scratch.md`: disposable working context for the current pass. - -Keep that state current when the engine learns something durable. Dead lessons -go out with the trash; the repo is not a scrapbook. - -## Docs - -- `docs/aquarium-engine-doctrine.md`: engine doctrine and invariants. -- `docs/engine-client-boundary.md`: Engine/Epiphany ownership split. -- `docs/epiphany-extraction-render-api-plan.md`: migration plan for the client - extraction and ergonomic render graph API. -- `docs/vortice-spine.md`: native host/renderer spine. -- `docs/hlsl-renderer.md`: current shader path. -- `docs/input.md`: camera and input contract. -- `docs/cult-runtime-surface.md`: CultCache/CultNet runtime surface. +Epiphany may depend on Fensalir contracts and renderer services. Fensalir must +not depend on Epiphany policy, role names, CultNet surfaces, or client layout. +If a change needs new engine authority, make it in `E:\Projects\Fensalir` first +and consume the resulting contract here. diff --git a/docs/aquarium-engine-doctrine.md b/docs/aquarium-engine-doctrine.md deleted file mode 100644 index adddd12..0000000 --- a/docs/aquarium-engine-doctrine.md +++ /dev/null @@ -1,58 +0,0 @@ -# Aquarium Engine Doctrine - -Aquarium is a native engine now. The job is not to wrap a dashboard in a nicer -skin; the job is to build a field machine that can host agents, state, sound, -and UI as living objects. - -## Frame Contract - -- One camera target sits on the global XY plane. -- That target is the Grid center. -- Grid radius is derived from camera zoom distance. -- Orbit changes yaw and pitch. Zoom changes distance. Pan moves the target. -- Body anchors remain in world space. -- The renderer may move the Grid visibility window, but world-space texture and - field domains must stay stable. - -## Renderer Contract - -- The visible world is shader-owned. -- Traditional geometry is scaffolding only when it helps the renderer stand up. -- Raymarched bodies and Grid terrain must shade from the same field story that - created their hits. -- Broad-phase structures may cull, bin, and skip, but they must remain - conservative. A culling primitive does not get to edit visible geometry. -- Planet-local detail is local to the body domain. Moving a body must move its - surface with it, not scroll the noise through the body. -- Grid texturing and weather sample world-space domains. -- HDR bloom spreads energy before tonemapping. ACES or its successor owns final - display compression. - -## Lighting Contract - -- Self is the first diegetic emitter. -- Surfaces should never be brighter than the light source unless the transport - story explicitly explains it. -- No ambient or global fill light in the default Aquarium path. -- The long-term lighting target is a field sampled by terrain, bodies, - atmospheres, particles, and diegetic UI. -- Debug modes must expose hit coverage, normals, depth, field occupancy, - lighting energy, and post-stack behavior before beauty work gets clever. - -## UI Contract - -- Debug overlay is allowed, but it is explicit chrome. -- Overlay text uses DirectWrite and stays out of the HDR scene unless a feature - intentionally projects it into the world. -- Diegetic labels and menus should anchor to world objects and unfold locally. -- Object-owned controls beat global panels. -- Crisp text, focus, keyboard input, and accessibility are real requirements, - not optional little manners. - -## State Contract - -- Runtime state is CultCache-backed and typed. -- Live reload must rehydrate from cache before pretending it survived. -- Shader reload may fail without killing the last good frame. -- Live assembly reload may fail without killing the last good runtime. -- Persistent state should be small, structured, and useful for future work. diff --git a/docs/cult-runtime-surface.md b/docs/cult-runtime-surface.md index af74e9e..e32a55d 100644 --- a/docs/cult-runtime-surface.md +++ b/docs/cult-runtime-surface.md @@ -8,7 +8,7 @@ Aquarium uses CultLib directly for runtime identity and reload recovery. it to a `CultCache`. The dev scripts pass: ```powershell ---cache E:\Projects\Aquarium-Engine\artifacts\dev-reload\cultcache\aquarium-client.msgpack +--cache E:\Projects\Fensalir\artifacts\dev-reload\cultcache\aquarium-client.msgpack ``` Direct runs can also use `--cache ` or `AQUARIUM_CULTCACHE_PATH`. diff --git a/docs/d3d12-best-practices-audit.md b/docs/d3d12-best-practices-audit.md deleted file mode 100644 index 6df6595..0000000 --- a/docs/d3d12-best-practices-audit.md +++ /dev/null @@ -1,60 +0,0 @@ -# D3D12 Best Practices Audit - -## Verdict - -The current D3D12 path is a solid foundation for Aquarium's focused client -renderer. It proves per-frame command allocators, fence-protected reuse, -shader-visible descriptors, persistent mapped constants, explicit render-target -state, brush-rendered Grid height, HDR/bloom presentation, temporal diagnostic -targets, async shader pipeline builds, and a narrow DirectWrite overlay bridge. - -## Good Current Decisions - -- Command allocators are per swapchain frame and waited on before reset. -- Shader-visible descriptor slots are not overwritten while in flight. -- Constant upload memory is persistently mapped, 256-byte aligned, and allocated - through a per-frame upload ring. -- Offscreen render target state is tracked and redundant transitions are - skipped. -- Backbuffer state flows through the same transition helper style instead of raw - assumed barriers. -- D3D12 objects are named, and command-list events mark the frame for - PIX/graphics diagnostics. -- Shader-visible descriptors are split into static and per-frame transient - arenas. Transient arenas reset only after the owning frame fence clears. -- D3D12 resources are registered by name, and capacity diagnostics report upload, - transient descriptor, static descriptor, and RTV usage. -- The height-field target is a proper brush pass into scalar `R16_Float`. -- Transparent event lanes are not preserved as dormant scaffolding. When Grid - linework, particles, glyph motes, or other coverage events return, they need a - live producer/consumer contract instead of alpha-blended final-frame hacks. -- HDR bloom is pre-tonemap, multi-level, and separable. -- The D3D11On12 bridge is overlay-only, keeping native hinted text without - mixing overlay UI into scene rendering. - -## Temporary Acceptable Debt - -- Committed resources are used directly. Replace with D3D12MA or placed-resource - suballocation before the renderer owns many textures/buffers. -- Descriptor arenas are simple bump allocators. Add free lists or descriptor - table paging only when real resource churn demands it. -- Static shader and RTV descriptor arenas rebuild wholesale on resize. This is - deliberately simple and correct for swapchain-dependent resources. -- Upload ring is per-frame and reset after fence wait. It is not yet a global - transient allocator with suballocation statistics or overflow diagnostics. -- Removed-pass scaffolding should stay out of the live frame. Runtime - volumetrics, medium/froxel targets, and medium history lanes are shelved. - -## Required Before Larger Renderer Work - -- Add GPU timestamp queries when frame cost starts mattering beyond CPU timing - diagnostics. -- Add descriptor-owner diagnostics beyond heap-level capacity summaries when - descriptor churn becomes hard to reason about. -- Keep future renderer systems tied to explicit live pass contracts before - adding new render targets or history lanes. - -## Rule - -Build the resource machine first, then move pixels through it. Dead experiments -belong to Git, not to the live frame graph. diff --git a/docs/d3d12-migration.md b/docs/d3d12-migration.md deleted file mode 100644 index 5921bc8..0000000 --- a/docs/d3d12-migration.md +++ /dev/null @@ -1,48 +0,0 @@ -# D3D12 Renderer - -D3D12 is the live renderer. The old D3D11 scene backend has been removed; the -only remaining D3D11 use is the narrow D3D11On12 bridge required for native -DirectWrite/Direct2D overlay text. - -## Current State - -- D3D12 owns the device, command queue, flip-discard swapchain, RTV heap, - per-backbuffer command allocators, command list, fence-backed present loop, - static and transient shader-visible descriptor arenas, upload buffers, - renderer-owned height-field, HDR scene, bloom, temporal diagnostic targets, - named objects, command-list events, and explicit tracked transitions. -- The height-field pass uploads Aquarium frame constants plus client-authored - brush data, renders a base field, then draws additive brush quads into a - 128x128 scalar `R16_Float` target. -- The fullscreen scene pass traces the background and height-field surface. - Epiphany bodies render afterward through client-declared SDF proxy pipelines - that share engine-owned proxy mechanics and write into the same scene targets. -- Presentation is scene-linear until the post pass. The scene renders to - `R16G16B16A16_Float`, a three-level bloom pyramid performs firefly-safe - downsample plus separable blur, and final presentation applies exposure, - bloom/veil, and ACES. -- The scene pass writes color/travel, field id/normal metadata, temporal - control, and event targets. The present shader writes ping-pong history and - exposes debug views for raw scene, history, control, identity, bloom, and - exposed luminance. -- DirectWrite and Direct2D remain for crisp overlay text through D3D11On12: - D3D12 renders the frame, then the overlay acquires the swapchain backbuffer, - draws debug UI, releases it to Present, and never participates in world - rendering. -- Shader and PSO creation runs off the main thread. Startup holds the splash - until the first pipeline set is ready. Runtime shader edits under the engine - or Epiphany shader roots are copied into the running apphost slot and trigger a - background rebuild; successful builds swap in after a GPU wait and failures - keep the previous pipeline set. -- Resize waits for the GPU, releases swapchain-dependent resources, rebuilds - descriptor arenas, and recreates backbuffer views plus dependent render - targets. - -## Invariants - -- `IAquariumRenderer` is the host boundary. The host should not learn renderer - internals as D3D12 grows teeth. -- D3D12 work must be validated by actual headless runs, not just compilation. -- Transparent-looking Grid output is an event lane, not canonical opaque depth. -- DirectWrite overlay text belongs behind the narrow D3D11On12 bridge. Do not - use it for diegetic/world text or let it leak into the scene graph. diff --git a/docs/engine-client-boundary.md b/docs/engine-client-boundary.md index ad3e54f..1686cd6 100644 --- a/docs/engine-client-boundary.md +++ b/docs/engine-client-boundary.md @@ -1,83 +1,23 @@ -# Engine And Client Boundary +# Fensalir Dependency Boundary -Aquarium Engine is not the Epiphany frontend client. +Epiphany Aquarium is a client of Fensalir. -`Aquarium.Engine` owns the native machinery: Win32 windowing, D3D12 device -state, swapchain presentation, resource lifetime, shader compilation, reload -transport, input translation, render target allocation, and future render graph -execution. +This repo owns: -`Aquarium.Engine.Contracts` owns the Vortice-free public boundary clients use to -describe runtime state, render intent, UI, audio patches, and persistent -settings. Contracts may name reusable engine concepts. They may not smuggle -Epiphany policy into the host under a nicer namespace. +- Epiphany agent/body semantics. +- Epiphany shader code. +- Client render-plan configuration. +- CultCache documents for Epiphany Aquarium state. +- CultNet interpretation and voice surfaces. -`Aquarium.Epiphany` owns the client meaning: CultCache runtime state, CultNet -interpretation, camera intent, cursor semantics, agent visual state, diegetic -layout rules, and the render graph configuration that turns Epiphany state into -world pixels. +`E:\Projects\Fensalir` owns: -`Aquarium.Sample.Minimal` exists as the tiny smoke test. `Aquarium.Zyphos` -exists as the first real non-Epiphany demo: a planetary client with its own -runtime, controls, scene state, and SDF shaders. If a feature cannot be -explained without Epiphany or Zyphos, it is not engine API yet. +- Native windowing and process host. +- D3D12 renderer, shader compilation, and render graph execution. +- Input translation, audio output, debug chrome, and live reload. +- `Aquarium.Engine.Contracts`. +- Reusable fractal, field, reservoir, and demo machinery. -## Hard Rules - -- Engine code may expose rendering abstractions. It may not know Epiphany roles, - sub-agent identities, CultNet surface semantics, or frontend-specific layout - policy. -- Epiphany code may configure cameras, render targets, shader passes, body - registries, and resource bindings through engine APIs. It may not reach into - D3D12 implementation details. -- Hot reload is transport. It is not architecture. The reload boundary exists so - the client can change without killing the device, not so client policy can - leak into the engine under a nicer hat. -- If a feature name includes `Self`, `Face`, `Imagination`, `Eyes`, `Body`, - `Hands`, `Soul`, `Life`, `CultNet`, or Epiphany state semantics, the default - home is `Aquarium.Epiphany` unless it is a data-only contract. -- If a feature owns descriptors, command lists, fences, barriers, render target - transitions, shader object lifetime, or swapchain presentation, the default - home is `Aquarium.Engine`. - -## Next Engine API Shape - -The next durable renderer cut should make the client configure a small set of -engine primitives: - -- Render targets: format, dimensions, history policy, clear policy, and exported - handles. -- Cameras: view/projection data, previous-frame data, jitter policy, and named - consumers. -- Shader passes: shader module, root bindings, target outputs, depth policy, - dispatch/draw shape, and reload identity. -- Scene resources: structured buffers, textures, samplers, body registries, and - light registries behind typed handles. -- Frame graph edges: explicit read/write dependencies so pass ordering is data, - not hidden renderer folklore. - -Do not build this by piling adapters around the current monolith. First expose -the smallest real engine abstraction that lets `Aquarium.Epiphany` describe one -pass without D3D12 details. Then move one client-owned concept through it. Then -repeat. - -## Repository Split Line - -Aquarium should eventually be usable without carrying the Epiphany client in the -same repository. That does not mean the repo should be split before the boundary -is mechanically clean. - -Keep both in this repo while the public contracts, graph declarations, shader -include layout, reload transport, and sample-client path are still changing -together. Split Epiphany out only when: - -- `Aquarium.Engine` and `Aquarium.Engine.Contracts` contain no Epiphany role, - CultNet-surface, Grid-policy, or agent-layout semantics. -- A non-Epiphany client can declare cameras, targets, shaders, UI, and - presentation without referencing `Aquarium.Epiphany`. -- Epiphany shaders, state documents, and visual grammar live entirely on the - client side of the contracts. -- The host can load an external client assembly without repo-local path lore. - -Until those are true, a repo split would not simplify ownership. It would just -make the same leak harder to see. +The dependency direction is one-way. If Epiphany needs new engine authority, +add that authority in Fensalir and consume it here through contracts. Do not +copy contracts, host scripts, or renderer helpers into this repo. diff --git a/docs/epiphany-extraction-render-api-plan.md b/docs/epiphany-extraction-render-api-plan.md deleted file mode 100644 index 208c460..0000000 --- a/docs/epiphany-extraction-render-api-plan.md +++ /dev/null @@ -1,666 +0,0 @@ -# Epiphany Extraction And Render API Plan - -Aquarium is the engine. Epiphany is one client app. - -The current solution has the first physical boundary in place: - -- `Aquarium.Engine` owns the host, D3D12 renderer, input loop, shader reload, - debug overlay, and client runtime loader. -- `Aquarium.Engine.Contracts` is the shared API surface between host and client. -- `Aquarium.Epiphany` owns the current runtime state, camera rig, CultCache - documents, and client factory. - -That split is real but shallow. The engine still carries Epiphany-shaped world -knowledge inside `D3D12Renderer`: fixed role counts, Self/cursor constants, -agent shader paths, body light setup, Grid brush generation, orbit fallback -motion, and the body visual buffer layout. The client can reload, but it cannot -yet describe what gets rendered. The renderer remains a monolith with a client -mask taped to the front. Rude, but accurate. - -## Design Target - -Client authors should be able to describe a frame in C# using named engine -abstractions: - -- render targets with formats, size policies, clears, history, and persistence -- cameras with projection, view, previous-frame state, jitter, and named use -- shaders with hot reload, includes, entry points, root bindings, and defaults -- passes that declare reads, writes, depth, viewport, draw shape, and diagnostics -- structured buffers, constants, textures, samplers, cubemaps, and body registries -- standard features such as bloom, tonemapping, overlay, IBL, resize handling, - shader reload, transient descriptors, barriers, and debug views - -Aquarium should make the ordinary path boring: - -```csharp -public sealed class EpiphanyClient : AquariumClient -{ - protected override void Configure(AquariumApp app) - { - var mainCamera = app.Cameras.Orbit("main") - .LookAtGrid() - .WithHistory(); - - var gridHeight = app.RenderTargets.Create("grid-height") - .FixedSize(128, 128) - .Format(RenderFormat.R16Float) - .Clear(0.0f); - - var scene = app.RenderTargets.Hdr("scene") - .MatchWindow() - .WithHistory(); - - app.Graph.Pass("grid-height") - .Fullscreen("Shaders/GridHeight.hlsl", "GridHeightPS") - .Write(gridHeight) - .BindFrame() - .Bind("GridBrushes", GridBrushes); - - app.Graph.Pass("scene") - .Fullscreen("Shaders/Scene.hlsl", "ScenePS") - .Read(gridHeight) - .Write(scene.Color, scene.Metadata, scene.Control) - .Depth(scene.Depth) - .UseCamera(mainCamera) - .Bind("BodyLights", BodyLights); - - app.Features.Bloom(scene.Color); - app.Features.Tonemap(scene.Color).Present(); - app.Features.DirectWriteOverlay(); - } -} -``` - -That is the level of API Aquarium should expose: explicit enough to be durable, -ergonomic enough that nobody has to learn descriptor heaps before rendering a -flower. Descriptor heaps are Aquarium's problem. If the client author asks for a -sharp object, the engine hands them a handle, not the knife factory. - -## Literature Anchor - -This plan follows the render graph pattern used in production engines: - -- Unity describes render graphs as high-level render-pass and resource - declarations that simplify pipeline configuration and let the system manage - resources efficiently: https://docs.unity.cn/Packages/com.unity.render-pipelines.core%4014.0/manual/render-graph-system.html -- Unreal's Rendering Dependency Graph defers execution until all passes are - gathered, then uses whole-frame knowledge for scheduling, barriers, memory, - async compute, and validation: - https://dev.epicgames.com/documentation/ru-ru/unreal-engine/rendering-dependency-graph?application_version=4.27 -- Frostbite's FrameGraph talk frames the same problem as a graph of passes and - resources that keeps rendering features modular without giving up efficiency: - https://www.gdcvault.com/play/1024612/FrameGraph-Extensible-RenderingArc -- Granite's Vulkan render graph writeup is useful implementation pressure: - declare reads and writes, validate, traverse dependencies, assign logical - resources to physical resources, generate barriers, alias compatible - transient targets, then execute: - https://themaister.net/blog/2017/08/15/render-graphs-and-vulkan-a-deep-dive/ - -The Aquarium version should start smaller than those engines. No async compute, -no memory aliasing, no multipass merging in the first cut. First: client-owned -declarations, engine-owned execution. - -## Current Coupling Inventory - -These are the seams to cut. - -### Shared Contracts - -`Aquarium.Engine.Contracts` currently exposes: - -- `IAquariumRuntime` -- `IAquariumRuntimeFactory` -- `AquariumRuntimeOptions` -- `AquariumFrame` -- `GraphicsSettings` -- `GridFrame` -- input state - -`AquariumFrame` is too specific. It assumes one Grid, one camera position, one -cursor, one time scalar, and a renderer that knows what those mean. - -### Host - -`AquariumHost` owns: - -- client assembly load and reload pointer -- window creation -- renderer construction -- debug input routing -- settings synchronization -- mouse projection onto the Grid plane - -The mouse projection is client policy. The engine may provide ray utilities, -but `ProjectMouseToGridPlane` belongs in the client or in a reusable camera -helper chosen by the client. - -### Renderer - -`D3D12Renderer` owns both engine machinery and Epiphany scene policy: - -- engine machinery: device, swapchain, fences, command list, descriptor arenas, - upload ring, shader compilation, render targets, overlays, resize, resource - transitions, pipeline state -- Epiphany policy: Grid height target, Self gravity brush, role agent count, - fixed agent body shader list, cursor hibiscus buffer slot, body lights, orbit - fallback positions, Grid placement math, agent state scalars, debug mode names - -The renderer should retain the machinery and lose the policy. - -### Shader Assets - -Engine shader assets currently include Epiphany bodies: - -- `D3D12SelfBody.hlsl` -- `D3D12FaceAgent.hlsl` -- `D3D12ImaginationAgent.hlsl` -- `D3D12EyesAgent.hlsl` -- `D3D12BodyAgent.hlsl` -- `D3D12HandsAgent.hlsl` -- `D3D12SoulAgent.hlsl` -- `D3D12LifeAgent.hlsl` -- `D3D12CursorBody.hlsl` -- `D3D12AgentCharacters.hlsli` - -Those should move under the Epiphany client shader root once the engine can load -client-declared shaders. Engine-owned includes should remain only when they are -generic: SDF primitives, body proxy mechanics, PBR lighting, fullscreen vertex -helpers, packing helpers, and graph binding conventions. - -## Target Project Shape - -First stable shape inside this repo: - -```text -src/ - Aquarium.Engine.Contracts/ public client-facing API - Aquarium.Engine/ host plus D3D12 backend implementation - Aquarium.Epiphany/ Epiphany client app/runtime -``` - -Longer-term package shape: - -```text -src/ - Aquarium.Engine.Abstractions/ public API, no Vortice dependency - Aquarium.Engine.D3D12/ D3D12 backend - Aquarium.Engine.Host/ default Win32 host executable - Aquarium.Epiphany/ client app, eventually movable out of repo -``` - -Do not split projects before the API shape earns it. Premature project shrapnel -is not architecture. It is paperwork with delusions. - -## Public API Model - -### Client Entry - -Replace `IAquariumRuntime.Frame` with a richer client lifecycle: - -```csharp -public interface IAquariumClient : IDisposable -{ - void Configure(AquariumAppBuilder app); - void Load(AquariumLoadContext load); - void Update(AquariumUpdateContext update); - void Render(AquariumRenderContext render); - void FlushState(); -} -``` - -`Configure` declares stable graph shape. `Update` mutates CPU state. `Render` -uploads per-frame data and selects dynamic pass instances. The engine compiles -and executes the graph. - -Keep a compatibility adapter from the old `IAquariumRuntime` while migrating, -then remove it when Epiphany is fully on the new lifecycle. - -### Handles - -Expose typed handles, not D3D12 objects: - -```csharp -public readonly record struct RenderTargetHandle(string Name); -public readonly record struct DepthTargetHandle(string Name); -public readonly record struct CameraHandle(string Name); -public readonly record struct ShaderHandle(string Name); -public readonly record struct BufferHandle(string Name) where T : unmanaged; -public readonly record struct TextureHandle(string Name); -public readonly record struct PassHandle(string Name); -``` - -Names are diagnostic identity. The engine maps them to physical resources. - -### Render Targets - -Render target declarations should cover the common case without ceremony: - -```csharp -app.RenderTargets.Create("scene") - .MatchWindow(scale: 1.0f) - .Format(RenderFormat.Rgba16Float) - .Clear(Color.Black) - .Sampled() - .History(frames: 2); - -app.RenderTargets.Create("grid-height") - .FixedSize(128, 128) - .Format(RenderFormat.R16Float) - .Clear(0.0f) - .Sampled(); -``` - -Engine responsibilities: - -- allocate and resize physical resources -- allocate RTV, DSV, SRV, UAV descriptors -- create transient descriptors per frame -- preserve history targets -- validate format and usage combinations -- transition states -- expose debug names and graph viewer data - -### Cameras - -The engine should provide camera math utilities and history storage. The client -chooses semantics: - -```csharp -var camera = app.Cameras.Perspective("main") - .Position(() => CameraRig.Position) - .LookAt(() => CameraRig.Target3) - .VerticalFovDegrees(58) - .NearFar(0.05f, 500.0f) - .WithPreviousFrame() - .WithMouseRays(); -``` - -Engine-owned: - -- view/projection matrices -- inverse matrices -- viewport transforms -- previous-frame storage -- jitter policy -- screen ray generation helpers - -Client-owned: - -- what the camera tracks -- Grid center -- orbit controls -- mouse-to-world projection policy - -### Shaders And Includes - -Shader declarations should hide D3DCompile details but expose the real contract: - -```csharp -var sceneShader = app.Shaders.Hlsl("scene") - .File("Shaders/Scene.hlsl") - .Vertex("FullscreenTriangleVS") - .Pixel("ScenePS") - .IncludeDirectory("Shaders/Includes") - .HotReload(); -``` - -Engine-owned features: - -- include expansion -- compile diagnostics -- previous-good shader retention -- pipeline rebuild in the background -- root binding validation -- standard include library - -Client-owned: - -- shader source files -- shader pass declarations -- object-specific SDFs and materials - -### Passes - -Passes should declare resource use explicitly: - -```csharp -app.Graph.Pass("bloom-prefilter") - .Fullscreen(sceneShader) - .Read("scene") - .Write("bloom-0") - .BindFrame() - .When(features => features.BloomEnabled); -``` - -Initial pass types: - -- fullscreen graphics pass -- proxy rectangle graphics pass -- instanced graphics pass -- compute pass -- copy/blit pass -- present pass -- overlay pass - -Initial graph compiler: - -- validate resource existence -- validate acyclic dependencies -- topologically sort by declared reads/writes -- emit D3D12 transitions -- allocate transient frame descriptors -- rebuild on graph, shader, target, or window changes - -Later graph compiler: - -- transient target aliasing -- pass culling -- async compute -- graph visualization -- queue scheduling - -## It-Just-Works Feature Layer - -The public API should include feature builders over the low-level graph. They -generate normal graph declarations, not secret renderer code. - -### Presentation - -```csharp -app.Features.Presentation("default") - .From(scene.Color) - .Exposure(settings.SceneExposure) - .Bloom(settings.Bloom) - .Tonemap(Tonemap.AcesFitted) - .Present(); -``` - -### Bloom - -```csharp -app.Features.Bloom(scene.Color) - .Levels(3) - .FireflySafe() - .PreTonemap(); -``` - -### IBL - -```csharp -app.Features.ImageBasedLighting("studio") - .Pmrem("Textures/studio2_pmrem.dds") - .Irradiance("Textures/studio2_irradiance.dds") - .BindAs("StudioIbl"); -``` - -### SDF Bodies - -```csharp -app.Features.SdfBodies("agents") - .Buffer("AgentVisuals", maxCount: 64) - .SharedInclude("Shaders/D3D12SdfProxy.hlsli") - .Role("Self", "Shaders/SelfBody.hlsl") - .Role("Imagination", "Shaders/ImaginationBody.hlsl") - .DepthAgainst(scene.Depth) - .Write(scene.Color, scene.Metadata, scene.Control); -``` - -The engine supplies proxy drawing, bounds, depth writes, common lighting, and -debug counters. The client supplies the body list and shaders. - -### Debug - -The debug layer should read graph metadata: - -- pass list and timing -- target dimensions, formats, and history state -- shader compile status -- descriptor arena usage -- upload ring usage -- selected resource visualizers -- graph validation warnings - -Debug views should be registered, not hardcoded: - -```csharp -app.Debug.Views - .Add("Final", scene.Color) - .Add("Bloom", bloom.Output) - .Add("Agent Steps", scene.Metadata.Channel("steps")); -``` - -## Migration Plan - -### Phase 0: Freeze The Boundary - -Goal: prevent new leaks while the old renderer still exists. - -Tasks: - -- Keep `docs/engine-client-boundary.md` authoritative. -- Add an architectural test or script check that `src/Aquarium.Engine` contains - no `Aquarium.Epiphany` references. -- Add a second check that engine shader names do not include Epiphany role names - once shaders move. -- Mark current fixed renderer path as legacy in docs, not as permanent API. - -Exit criteria: - -- Boundary checks run in local verification. -- New work has an obvious place to live. - -### Phase 1: Rename Contracts Into Abstractions - -Goal: turn `Aquarium.Engine.Contracts` into an actual engine API surface. - -Tasks: - -- Introduce `AquariumAppBuilder`, `AquariumClient`, graph handles, resource - descriptors, camera descriptors, shader descriptors, pass descriptors, and - feature descriptors. -- Keep old `IAquariumRuntime` beside the new API temporarily. -- Add XML docs or README examples for the common path. -- Keep all contracts Vortice-free. - -Exit criteria: - -- A tiny sample client can declare one target, one fullscreen shader, and a - presentation pass without referencing `Aquarium.Engine.Render` or Vortice. - -### Phase 2: Build The Minimal Graph Compiler Inside Engine - -Goal: execute client-declared resources and passes without replacing the whole -renderer at once. - -Tasks: - -- Add internal `RenderGraph`, `RenderGraphCompiler`, `CompiledRenderGraph`, and - `RenderGraphExecutor`. -- Map public descriptors to internal D3D12 resources. -- Support fullscreen graphics passes first. -- Support named render target reads and writes. -- Support one depth target. -- Generate transitions from declared pass use. -- Keep shader hot reload and previous-good pipeline behavior. -- Add graph validation errors with pass/resource names. - -Exit criteria: - -- Existing scene, bloom, and present path can be represented as graph passes, - even if some callbacks still call existing private methods. - -### Phase 3: Convert Presentation And Bloom To Features - -Goal: move generic post-processing out of bespoke renderer flow. - -Tasks: - -- Express HDR scene target, bloom pyramid, history targets, and present pass as - graph resources. -- Implement `app.Features.Bloom`. -- Implement `app.Features.Presentation`. -- Move render debug mode registration into graph/debug descriptors. -- Keep DirectWrite overlay as an engine feature. - -Exit criteria: - -- A non-Epiphany sample can render a color target, bloom it, tonemap it, and - present without defining Grid, agents, cursor, or CultNet. - -### Phase 4: Move Epiphany Shaders And Body Policy To Client - -Goal: remove role bodies and cursor semantics from engine source. - -Tasks: - -- Move role shader files and `D3D12AgentCharacters.hlsli` into - `src/Aquarium.Epiphany/Shaders`. -- Keep generic includes in engine: - - fullscreen helpers - - SDF primitives - - PBR lighting - - body proxy mechanics - - packing and frame constants -- Replace fixed `RoleAgentCount`, fixed shader path arrays, and fixed - `AgentVisualGpu` ownership with a client-declared SDF body feature. -- Move `BuildAgentVisualTable`, `BuildBodyLightTable`, `BuildGridHeightBrushes`, - orbit fallback positions, cursor radius, and Self constants into - `Aquarium.Epiphany`. -- Let Epiphany upload buffers by handle. - -Exit criteria: - -- `src/Aquarium.Engine` contains no role names, no cursor hibiscus, no Self - constants, no agent orbit fallback, and no Epiphany shader paths. - -### Phase 5: Move Grid Policy To Epiphany Or A Reusable Feature - -Goal: decide whether Grid is a generic Aquarium feature or Epiphany client -policy. - -Recommended split: - -- Engine feature: height-field target, brush rendering primitive, reflective - surface shader helper, debug visualization. -- Epiphany policy: Grid center, radius rule, Self gravity bowl, role gravity - wells, radial wave parameters, body placement rule. - -Tasks: - -- Expose `app.Features.HeightField`. -- Expose CPU helper for evaluating brush stacks when the client asks for it. -- Move current brush stack construction into Epiphany. -- Move mouse-to-Grid projection out of `AquariumHost`. - -Exit criteria: - -- A different client can choose no Grid, a different height field, or a static - render target without touching engine code. - -### Phase 6: Replace Frame Contract - -Goal: stop `AquariumFrame` from being the rendering protocol. - -Tasks: - -- Introduce `AquariumFrameContext` for time, window size, input, graph resource - access, frame constants, and upload helpers. -- Let clients define their own frame constants structs. -- Keep engine standard constants optional: - - resolution - - time - - camera matrices - - previous camera matrices - - presentation settings -- Provide `Frame.UploadConstant`, `Frame.UploadBuffer`, and - `Frame.SetGraphValue`. -- Remove renderer dependence on `AquariumFrame`. - -Exit criteria: - -- `IAquariumRenderer.Render` consumes a compiled graph frame, not an Epiphany - shaped frame record. - -### Phase 7: Split Host From Backend When Earned - -Goal: make Aquarium usable as an engine package, not only an executable. - -Tasks: - -- Split public abstractions from D3D12 backend if the contract has stabilized. -- Keep Win32 host as the default app host. -- Let clients choose hosted mode: - - engine-owned window - - headless - - later embedded/native handle mode -- Package shader include library and default features as engine assets. - -Exit criteria: - -- A fresh client can reference Aquarium abstractions, implement a client class, - run through the host, and declare render graph resources without copying - Epiphany code. - -## Order Of Attack - -Do not start by moving every file. That produces thrilling amounts of rubble. - -Recommended first implementation slice: - -1. Add public render target, shader, pass, camera, and feature descriptor types - to contracts. -2. Add a graph builder that can describe the current fixed pipeline without - executing it. -3. Add a debug dump of the declared graph. -4. Convert bloom and presentation to execute from graph declarations. -5. Convert body proxy draws to a client-declared body registry. -6. Move Epiphany shaders out of engine. -7. Move Grid and agent/cursor frame construction out of renderer. - -Each slice must preserve: - -- shader reload keeps last good pipelines -- failed client reload keeps previous client alive -- resize rebuilds all size-bound targets -- debug overlay remains readable -- headless smoke still completes -- engine source stays free of Epiphany references - -## Verification Gates - -Every migration pass should run: - -```powershell -dotnet build Aquarium.Engine.sln --no-restore -.\scripts\dev-reload.ps1 -Headless -RetainSlots 4 -.\scripts\verify-boundaries.ps1 -``` - -The final `rg` should shrink over time. At the end it should be empty except -for generic documentation comments if any survive, and they probably should not. - -## Non-Goals For The First Graph - -- no async compute -- no transient memory aliasing -- no general material system -- no visual node editor -- no automatic shader reflection dependency on day one -- no project split until the API stops moving under our feet -- no "compatibility mode" escape hatch that lets client code call D3D12 directly - -The first graph exists to establish ownership and data flow. Optimization comes -after the graph tells the truth. - -## Success Definition - -Aquarium is clean when: - -- Engine code can render a non-Epiphany sample client. -- Epiphany can add a render target, camera, shader, buffer, and pass without - editing `D3D12Renderer`. -- Epiphany shaders live with Epiphany. -- Engine shader includes are generic. -- Resource lifetime, descriptors, barriers, resize, hot reload, presentation, - and debug inspection are engine-owned. -- Client code describes intent. Engine code makes it work. diff --git a/docs/hlsl-renderer.md b/docs/hlsl-renderer.md deleted file mode 100644 index e7d4b0f..0000000 --- a/docs/hlsl-renderer.md +++ /dev/null @@ -1,117 +0,0 @@ -# HLSL Renderer - -Aquarium's visible world is currently a D3D12 HLSL renderer with a small, -explicit frame graph. - -## Current Path - -1. Engine-owned `D3D12HeightField.hlsl` renders a 128x128 scalar height-field - target from client-authored brush data. -2. Engine-owned `D3D12Scene.hlsl` traces the background and Grid into - scene-linear HDR targets. -3. Epiphany-owned body shaders each get their own proxy pipeline: - `D3D12FaceAgent.hlsl`, `D3D12ImaginationAgent.hlsl`, - `D3D12EyesAgent.hlsl`, `D3D12BodyAgent.hlsl`, `D3D12HandsAgent.hlsl`, - `D3D12SoulAgent.hlsl`, `D3D12LifeAgent.hlsl`, `D3D12SelfBody.hlsl`, and - `D3D12CursorBody.hlsl`. Shared proxy mechanics live in the engine includes - `D3D12SdfCommon.hlsli`, `D3D12SdfProxy.hlsli`, and `D3D12SdfMath.hlsli`. -4. Engine-owned `D3D12Post.hlsl` builds bloom, resolves diagnostics/history, applies - exposure and ACES, then presents. -5. `DirectWriteOverlay` draws crisp final-pixel debug UI after scene rendering. - -C# feeds explicit frame constants: resolution, time, Grid radius, camera -position, presentation controls, previous frame state, cursor anchors, and debug -mode. CultMath is the CPU-side math grammar. Vortice math stays at the graphics -API membrane. - -## Grid - -The Grid height target is centered on the camera target; body anchors remain in -world space. The target stores height in `.r` only. A future useful expansion is -packed gradients in `.g/.b` if normal cost becomes worth the extra bandwidth. - -Grid linework is derivative-aware in the final scene pass. Cartesian lines use -screen-space `fwidth` against their world-domain coordinate so minor and major -lines stay the same pixel width across zoom distances. Terrain isolines derive -from the Grid height field, while field lines quantize terrain gradient angle -and fade out on flat surfaces. - -The fullscreen scene pass owns environment and Grid only. Bodies are not folded -into that pass. After the Grid writes scene color and travel-derived depth, -each body gets its own proxy draw and shader pipeline. The shared proxy vertex -shader computes a conservative screen rectangle from the uploaded body center -and bound radius. The body-specific pixel shader raymarches only that object -and writes travel-derived depth so the Grid and nearer bodies arbitrate -visibility through the depth target. - -## Solids - -Epiphany uploads Self, Face, Imagination, Eyes, Body, Hands, Soul, Life, and the -cursor through the engine `AquariumSdfObject` buffer, including current center, -previous center, and state scalars. Aquarium owns the D3D12 upload, proxy draw, -depth, and presentation machinery; Epiphany owns which bodies exist, where they -are, and which shader files describe them. - -The cursor is a luminous three-lobed hibiscus SDF that lives on the XY plane: -its center is one cursor radius above XY, so its lower contact tip lands at -Grid z=0 instead of sampling the Grid height field. The previous MathWorld -teardrop formula remains in `D3D12SdfMath.hlsli` for later reuse. Agent visuals -carry their previous centers in the structured buffer for temporal reprojection. - -Lighting is currently direct and diegetic: Self is the emitter. No ambient fill -is allowed to quietly solve a bad light story. - -## Temporal Diagnostics - -The temporal resolver is documented in `docs/tsr-inspired-taa-spec.md`. The live -frame keeps color, metadata, and control history. Projection jitter uses a small -Halton sequence, and final presentation blends validated history. SDF object -highlights get a narrow hot-current history path so transient specular spikes -can be damped without relaxing travel, field, or normal validation. Bloom is -clamped at prefilter for unsupported single-pixel HDR spikes, then attenuated -when the resolved scene has damped a much hotter current sample, so transient -fireflies do not keep blooming through the current-frame bloom path. -Dormant event lanes are not preserved without a producer and pass contract. - -Debug modes: - -- `0` final -- `1` raw current scene -- `2` reprojected history sample -- `3` history age -- `4` history weight -- `5` coverage and step ratio -- `6` current field identity -- `7` bloom contribution -- `8` exposed luminance -- `9` agent identity -- `10` agent SDF step count - -`F1` cycles modes. Number keys select the first modes directly. Startup mode can -be set with `--render-debug` or `AQUARIUM_RENDER_DEBUG_MODE`. - -## HDR - -Presentation applies explicit exposure before display transformation and adds a -low-gain pre-tonemap bloom/veil pyramid. The bloom pass renders exposed -scene-linear HDR color into half-, quarter-, and eighth-resolution targets, uses -firefly-safe downsampling, blurs each level with separable horizontal/vertical -passes, then contributes gently before the ACES fit. This is not threshold glow. - -## Overlay Text - -Readable overlay text is handled by `DirectWriteOverlay`, using DirectWrite for -font layout/rasterization and Direct2D for final draw. D3D12 reaches that path -through D3D11On12 only after the scene frame is rendered. The bridge is -overlay-only. - -The debug controls live in `Render/Ui/DebugUi.cs`. The grammar is a native -version of CultLib's generator API: panels, sections, sliders, toggles, options, -and buttons are declared in code and bound to engine state with explicit read -and write delegates. The visual language is compact, flat, and allowed to have -taste. Frighteningly controversial, apparently. - -The overlay owns a private DirectWrite font collection built from bundled Google -Fonts files in `Assets/Fonts`: Montserrat for thin small-cap display text and -Ubuntu Sans for body/debug copy. Runtime must not depend on system-installed -fonts. diff --git a/docs/input.md b/docs/input.md deleted file mode 100644 index f1de5d5..0000000 --- a/docs/input.md +++ /dev/null @@ -1,21 +0,0 @@ -# Input - -Input is currently Win32-backed and intentionally small. - -## Flow - -- `Win32Window` translates window messages into `InputState`. -- `AquariumHost` begins each input frame, pumps messages, then updates runtime. -- `AquariumRuntime` passes input into `OrbitCameraRig`. -- The renderer receives the updated camera and Grid frame as constants. - -## Controls - -- Middle mouse drag: orbit camera around the Grid center. -- Mouse wheel: exponential zoom. -- Right mouse drag: pan along the Grid plane. -- `WASD`: pan along the Grid plane. - -The camera target remains the Grid center. Panning moves that shared target; -orbiting changes only yaw/pitch; zoom changes only camera distance and therefore -Grid radius. diff --git a/docs/perfect-machine-architecture.md b/docs/perfect-machine-architecture.md deleted file mode 100644 index 092ab2a..0000000 --- a/docs/perfect-machine-architecture.md +++ /dev/null @@ -1,683 +0,0 @@ -# Perfect Machine Architecture - -## Objective - -Build one real-time spatial evidence machine that can render and resolve: - -- fast 2D scalar-field splats on tileable surfaces; -- fast 3D scalar-field splats in object/world volumes; -- SDF/level-set surfaces for opaque solids; -- density/extinction fields for flames, smoke, fog, plasma, and uncertain - sensor volumes; -- 2D fields projected onto 3D domains such as cube-sphere planets and toroidal - station decks; -- camera/microphone sensor evidence from Mimir-style capture; -- cached structural probes emitted by IFS `.aquageo` grammars; -- stochastic updates that converge under CPU, GPU, RAM, and SSD budgets. - -The product requirement is not "infinite detail." It is a compact authored -description that can put detail where pixels can see it, keep enough evidence -alive to stabilize it, and refuse work that cannot justify its cost. - -## Research Spine - -This architecture is not invented from the floorboards: - -- ReSTIR DI and GI prove reservoir reuse as a real-time sampling strategy for - expensive candidates across time and screen space. -- GRIS generalizes reservoir resampling beyond direct light candidates through - target functions, correlated samples, domains, and shift mappings. -- EWA surface/volume splatting and 3D Gaussian splatting prove anisotropic - projected support as a practical rendering primitive. -- Geometry clipmaps and Nanite-style virtualized geometry prove that visible - projected error and resident summaries beat global leaf traversal. -- TSDF fusion/KinectFusion prove that streamed sensor samples can accumulate - into a coherent implicit spatial field. -- Instant-NGP's multiresolution hash encoding is a warning and inspiration: - stochastic evidence can be fast when the data layout is explicit and GPU - friendly, but Aquarium should preserve deterministic summaries and bounds as - safety authority. - -## Prime Invariants - -- Authored semantic domains are the source of truth. -- Backend packets are compiled output and may be deleted/rebuilt. -- Every domain, node, claim, probe, payload, page, and reservoir has a stable - key. -- Every reusable sample must name its target function and source PDF or state - why it is non-probabilistic structural evidence. -- Every LOD subtree has a conservative parent summary. -- Learned/stochastic priority may rank work; it may not own field safety, - visibility safety, or calibration safety. -- Missing children render through parent summaries. A frame does not wait for - SSD. -- TAA owns pixel history, not producer identity. -- Mimir sensor fusion and fractal rendering share the evidence machinery; they - do not share client policy. - -## System Pipeline - -```text -Authored intent or live sensor input --> Domain binding --> Evidence candidate generation --> Target evaluation --> Resampled importance reservoir --> Temporal reuse validation --> Spatial/domain reuse validation --> Occupancy graph update --> Residency/page scheduling --> Backend packet lowering --> 2D/3D/projected field splat passes --> Temporal resolve guide buffers --> Debug/evidence telemetry -``` - -The machine is allowed to have multiple candidate producers. The reservoir -contract makes them comparable without pretending they are the same thing. - -## Module Network - -```text -Aquarium.Engine.Contracts - Stable DTOs: domains, claims, nodes, summaries, probes, reservoir guides, - payload pages, backend packets, debug rows. - -Aquarium.Engine.Fractal - Pure CPU algorithms: domain math, grammar expansion, ownership trees, - summaries, scoring, reservoirs, occupancy graph updates, residency planning, - packet planning. - -Aquarium.Engine.SensorFusion - Future shared adapter layer: camera/audio feature candidates, calibration - confidence, raw retention lowerings, Mimir-facing packet contracts. - -Aquarium.Engine.Render - D3D12 resources, page tables, structured buffers, field splat passes, - surface/volume resolves, TAA guide buffers, debug visualization. - -Aquarium.Zyphos - World policy, cube-sphere/tile roots, planet grammar seeds, setting-safe - visuals. - -Aquarium.Epiphany - Agent/body policy, role grammar selection, semantic bindings. - -Mimir/LocalCast - Sensor capture, raw rolling retention, feature extraction, calibration facts. - It does not own resolved spatial evidence history. -``` - -## Data Model - -### Domain - -```text -DomainKey -ParentKey -Kind: solar/orbital/planet/cubeTile/torus/surface2d/object3d/volume3d/sensorRig -Frame -Projection -Bounds -Periodicity -Owner -``` - -Domains say where coordinates live and how they map to parent space. A domain is -allowed to be 2D, 3D, or 2D projected onto 3D. - -### Claim - -```text -ClaimKey -DomainKey -NodeKey -Layer: form/appearance/transport -Kind: height/sdf2d/sdf3d/density/extinction/material/phase/emission/light/feature/confidence -LocalFrame -Envelope -Payload -Tags -CostTier -Seed -``` - -Claims are authored or inferred statements about a field. They are not renderer -packets. - -### Field Layer Split - -The old shorthand was `SDF / PBR / Radiosity`. That naming was useful for the -first opaque-object path, but it is not the architecture. - -The durable split is: - -```text -Form -> what exists where -Appearance -> how it interacts locally with light, color, and material -Transport -> how energy moves through or from it -``` - -Opaque solids lower through level-set form: - -```text -phi(x) = signed distance -gradient(phi) = surface normal -surface exists near phi = 0 -``` - -Transparent media lower through density/extinction form: - -```text -rho(x) = density / extinction / confidence -gradient(rho) = direction of local density change -volume exists where rho contributes above threshold -``` - -Sensor fusion may begin as confidence density and sharpen into surface claims -when multi-view/acoustic evidence makes a stable boundary plausible. Fractal -terrain may begin as SDF/height surfaces. Flames stay participating fields: -their form is density/extinction, their appearance is emission/color/phase, and -their transport is emission/scattering reuse. - -Implementation note: current packet names still say SDF/PBR/radiosity in places -because the first GPU receipt was built for opaque splats. Treat those as -backend packet names, not the conceptual contract. - -### Probe - -```text -ProbeKey -DomainKey -LocalPosition -LocalNormalOrGradient -BoundRadius -PayloadHandle -TargetContribution -SourcePdf -Confidence -ObservedFrame -ObservedTime -ProducerKind -FieldLayer -FieldEncoding -``` - -A structural probe can come from an IFS grammar. A sensor probe can come from a -camera/audio feature. Both become candidates only after they have a target -function and validation rules. - -### Reservoir - -```text -SelectedSample -SelectedTarget -WeightSum -CandidateCount -ContributionWeight -ValidationMask -SampleAge -DomainKey -``` - -The reservoir owns resampling math. It does not own stable tracks, packet -lowering, or TAA history. - -### Occupancy Graph - -```text -NodeKey -DomainKey -Bounds -SummaryPayload -ChildPayload -MeanContribution -Variance -Confidence -SampleAge -ResidencyState -LastVisibleFrame -LastUpdateFrame -``` - -The occupancy graph is the shared heuristic memory of where useful field -evidence likely lives. It is structural enough for IFS trees and statistical -enough for sensor fusion. - -### Page - -```text -PageKey -PayloadKind -ByteRangeOrHandle -ResidentTier: gpu/ram/ssd/missing -EstimatedGpuCost -EstimatedRamBytes -EstimatedSsdBytes -LastUseFrame -``` - -Pages are storage decisions, not semantic identity. - -## Algorithms - -### 1. Domain Binding - -Every candidate is first bound to a domain path. Cube-sphere terrain binds to a -face/tile path. Torus surfaces bind to periodic `u/v` patches. Agent details -bind to object-local sheets, curves, or volumes. Sensor features bind to a -sensor rig frame and then to a calibrated world or object domain. - -Validation starts here. If two samples do not share a valid lineage or shift -mapping, they do not reuse each other. - -### 2. IFS Grammar Expansion - -The `.aquageo` DSL emits semantic claims and ownership nodes: - -```text -grammar -> domains -> claims -> ownership tree -> summaries -``` - -Expansion is deterministic by stable key and seed. Generated leaves do not all -need to be resident. The ownership tree must summarize itself before it earns -LOD rights. - -### 3. Sensor Candidate Lowering - -Camera and microphone producers retain raw capture ordering, calibration, and -provenance. Aquarium receives resolved candidate observations: - -```text -camera/audio feature -> calibrated local/world candidate -> target evaluator -``` - -Sensor adapters own modality interpretation. Aquarium owns spatial evidence -history after lowering. - -### 4. Target Evaluation - -Targets are comparable scalar contributions: - -- projected SDF/form error; -- density/extinction contribution; -- appearance delta over visible coverage; -- transport/radiance contribution; -- feature confidence times calibration confidence; -- expected pixel influence; -- expected information gain for an uncertain region. - -The source PDF is the probability by which the candidate was proposed. If the -candidate is deterministic structural evidence, it uses an explicit proposal -policy rather than a magical free sample. - -### 5. Reservoir Update - -Each reservoir stores one representative sample plus the weight mass of the -candidates it represents: - -```text -candidateWeight = target / sourcePdf -weightSum += candidateWeight -candidateCount += representedCount -select candidate with probability candidateWeight / weightSum -``` - -Final contribution weight follows the RIS/ReSTIR shape: - -```text -weightSum / (candidateCount * selectedTarget) -``` - -Temporal reuse and spatial/domain reuse are explicit passes, not side effects. - -### 6. Reuse Validation - -Temporal reuse validates: - -- camera motion/reprojection; -- previous/current domain lineage; -- disocclusion; -- field id/material class; -- local-frame error; -- conservative bounds; -- sample age and confidence. - -Spatial/domain reuse validates: - -- neighbor surface compatibility; -- tile adjacency or periodic wrap; -- cube-face seam mapping; -- torus seam mapping; -- object-local parent frame stability; -- sensor calibration agreement. - -GRIS-style shift mappings live here. A shift is an owned object with tests, not -a helper function hiding inside a shader. - -### 7. Occupancy Graph Update - -The occupancy graph receives selected reservoirs and sparse high-quality probes. -It updates node statistics under budget: - -```text -mean, variance, confidence, sampleAge, lastVisible, lastUpdated -``` - -Unvisited nodes decay. Stale uncertainty grows. Visible, uncertain, stale, and -near-threshold nodes retain nonzero exploration probability. - -### 8. Selected Cut And Residency - -A hierarchy cut is selected from summaries: - -```text -projected error -material delta -coverage -current reservoir confidence -estimated GPU cost -residency state -``` - -Children stream only when the cut justifies them. Parent summaries remain -renderable. Eviction favors low-score high-cost payloads and protects -near-threshold nodes from thrash. - -### 9. Backend Lowering - -The same semantic field can lower to: - -- 2D SDF tile pages; -- 2D height/material pages; -- 3D SDF splat packets; -- 3D density/extinction splat packets; -- transparent emission/scattering splat packets; -- 2D-projected-to-3D splat packets; -- sensor confidence volumes; -- debug overlays. - -The first renderer path should use compact-support anisotropic envelopes. They -borrow Gaussian splatting's covariance discipline without inheriting infinite -support as a default runtime tax. Surface and volume encodings may share the -same envelope math; they do not share resolve rules. - -### 10. TAA Guide Integration - -TAA consumes guide signals: - -- reservoir confidence; -- sample age; -- domain validity; -- temporal detail; -- invalidation reason; -- field id and motion. - -TAA does not own reservoirs. It only decides how much pixel history may survive. - -## Resource Tradeoffs - -### CPU - -CPU performs grammar expansion, coarse scoring, stochastic scheduling, page -requests, eviction decisions, and selected-cut planning. It must not rescore -every leaf or rebuild payload pages mid-frame. - -### RAM - -RAM keeps summaries, estimator state, hot/warm metadata, selected cuts, and -recent probes. It does not keep every generated child payload. - -### SSD - -SSD stores payload pages, summary pages, probe history, and optional training -datasets. SSD never blocks a frame; parent summaries render while requests are -pending. - -### GPU - -GPU evaluates selected packets, splats, SDF proxy passes, density/transparent -volume passes, compute scoring where profitable, page-table sampling, and debug -views. It must not walk the authored grammar tree. - -## Render Frame Flow - -```text -1. Gather visible domains and active sensor regions. -2. Load resident summaries and previous reservoirs. -3. Generate structural and sensor candidates under CPU budget. -4. Evaluate targets and source PDFs. -5. Update local reservoirs. -6. Validate temporal reuse. -7. Validate spatial/domain reuse. -8. Update occupancy graph statistics. -9. Select hierarchy cut under CPU/GPU/RAM/SSD budgets. -10. Queue missing pages; keep parent summaries active. -11. Lower selected evidence to 2D/3D/projected field splat packets. -12. Render surface and/or transparent field passes. -13. Resolve with TAA guide buffers. -14. Emit debug telemetry and evidence logs. -``` - -## Test Boundaries - -Pure unit seams: - -- projection round trips and seam continuity; -- domain lineage and shift mapping; -- DSL expansion determinism; -- ownership bounds; -- summary conservativeness; -- reservoir math; -- stochastic scheduler convergence; -- residency selection under fake stores. - -Mock boundaries: - -- `IFractalRandom`; -- `IFractalClock`; -- `IContributionProbe`; -- `IFractalPayloadStore`; -- `ISensorCandidateSource`; -- `IDomainShiftMap`; -- `ITaaGuideSink`; -- `IFractalDebugSink`. - -GPU parity: - -- envelope evaluator; -- projection evaluator; -- packet decoding; -- selected-cut fade; -- guide-buffer packing. - -Performance fixtures: - -- fixed camera path; -- fixed DSL world; -- fixed sensor trace; -- fixed budget profile for GTX 1070-class hardware; -- output CPU ms, GPU ms, payload count, page requests, selected cut size, - reservoir confidence, and convergence error. - -## Waterfall Implementation Phases - -### Phase A: Architecture Freeze - -Deliver this document, the public thesis article, updated memory, and a cut -line for the TAA guide-buffer fork. - -### Phase B: Explicit Reservoir Guide Layout - -Add a dedicated reservoir guide history target rather than packing previous -reservoir validity into existing control channels. Preserve current-control.w -as the current confidence lane. - -Guide schema: - -```text -x: reservoir confidence -y: reservoir sample age -z: domain validity -w: invalidation code -``` - -Current state: SDF and temporal Gaussian passes write a scene reservoir guide -MRT. Resolve reads current and previous guide textures, folds confidence and -domain validity into history validation, and writes a ping-ponged history -reservoir guide target. `history-control.w` remains pixel history age. - -### Phase C: Fractal Probe Pipeline - -Turn IFS node probes into typed reservoir candidates with renderer-facing camera -motion, disocclusion, material, and visibility validation. - -Current state: `FractalStructuralProbeGenerator` lowers an -`AquariumFractalSummary` into `FractalProbeSample` candidates with local center, -bound radius, projected target contribution, source PDF, material delta, and -payload handle. Renderer-facing temporal validation remains open. -`FractalStructuralProbeReservoir` builds a selected-cut reservoir from an -ownership tree, summaries, and projected pixels per world unit; Zyphos now -exposes that reservoir in its fractal render plan/debug dump. -`FractalProbeReuseValidator.ValidateTemporal` now names the renderer-facing -rejection reasons for camera motion, disocclusion, material mismatch, and -visibility before those checks are lowered to GPU reuse passes. - -### Phase D: Occupancy Graph - -Promote contribution state into the heuristic occupancy graph and add -confidence decay, stale uncertainty growth, and convergence telemetry. - -Current state: `FractalOccupancyGraph` now owns per-node contribution state, -last visible frame, last observed score, and update probability. The -contribution cache routes through this graph, and unobserved nodes decay -confidence while stale uncertainty grows. Residency planning now keeps resident -payloads by score-per-cost and emits eviction decisions for low-value expensive -payloads. Convergence telemetry and richer resource-tier residency fields remain -open. - -### Phase E: 2D Surface Field Tile Backend - -Build cached 2D SDF/height/material/confidence pages for cube-sphere and torus domains. -Use parent summaries while child pages stream. - -Current state: `AquariumFractalSurfacePageKey` and -`AquariumFractalSurfacePage` define renderer-agnostic page metadata for height, -2D signed-distance, material, and confidence pages. `FractalSurfacePagePlanner` -turns a selected IFS cut into stable page metadata, and the Zyphos render plan -now exposes height, 2D signed-distance, material, and confidence pages beside -its structural probe reservoir. `FractalSurfacePageResidencyPlanner` adds a -mockable page-store boundary with byte-budgeted resident, missing, requested, -and evicted page decisions. `FractalSurfacePageRasterizer` now lowers resident -pages to CPU height, 2D signed-distance support, material, and confidence -sample payloads using the same shaped brush envelope math as the live brush -compiler. The real page store, atlas, and D3D12 lowering remain open. - -### Phase F: 3D Form Field Splat Backend - -Build compact-support 3D form splat packets for object/volume domains. Opaque -solids use SDF/level-set packets; transparent media use density/extinction -packets. Keep distance safety conservative and LOD gated for solids, and keep -volume cost bounded by explicit extinction/support budgets. - -Current state: `FractalProbeSample` now carries explicit field layer and -encoding metadata. The same reservoir sample type can represent opaque -`Form/SignedDistance` and transparent `Form/Density` or `Form/Extinction` -evidence without creating a second cache. `AquariumFractalSdfSplat3D` and -`FractalSdfSplat3DCompiler` own the opaque SDF lowering path; -`AquariumFractalDensitySplat3D` and `FractalDensitySplat3DCompiler` own the -transparent density/extinction lowering path. Reuse rejects mismatched -encodings before lineage/local-shift reuse can smear density and SDF together. -The `.aquageo` DSL accepts `density` and `extinction` claims beside `height`, -and its `flame` recursive primitive now emits density claims instead of height -claims. Height brush lowering filters to height payloads, leaving transparent -Form claims for field lowering. Zyphos now exposes a first structural SDF splat -from its probe reservoir. D3D12 lowering and object/body recursive form -integration remain open. - -### Phase G: 2D-Projected-To-3D Field Backend - -Project 2D field pages onto 3D domains: cube-sphere planets, torus stations, -curved sheets, object-local surfaces, and transparent sheets/volumes when the -domain mapping supports them. - -Current state: `FractalProjectedSdfSplatCompiler` lowers resident -`SignedDistance2D` page payloads into compact 3D SDF splats through an explicit -`Vector2 -> Vector3` mapping and surface normal. Zyphos caches a first bounded -set of projected surface splats from its resident SDF pages using a flat local -mapping; real cube-sphere and torus mappings remain open. - -### Phase H: Mimir Adapter - -Add sensor candidate adapters after the fractal reservoir path proves the -contract. Camera/audio features become candidates; Aquarium owns resolved -evidence. Sensor fusion initially emits confidence/density form claims; only -coherent gradients and multi-view/acoustic agreement should promote them into -surface claims. - -### Phase I: GPU Reservoirs And Spatial Reuse - -Move hot reservoirs to GPU buffers, add spatial reuse across screen tiles and -domain neighbors, and keep CPU/GPU parity fixtures. - -Current state: `tools/Aquarium.Fractal.Receipt` is the first GPU-resident -receipt harness. It allocates an 80-byte packed SDF splat UAV plus three -separate 64-byte reservoir UAVs for SDF envelopes, PBR material envelopes, and -radiosity because that was the first opaque-object packet slice. Conceptually -those are the first Form, Appearance, and Transport reservoirs. The receipt -runs independent D3D12 compute passes for splat population, form/SDF reservoir -sampling, appearance/PBR reservoir sampling, and transport/radiosity reservoir -sampling; the three reservoir passes share only the stochastic update budget -vocabulary, not packet anatomy. On the local GTX 1070, the budgeted receipt -kept `2,000,000` splats and `2,000,000` reservoirs per layer resident, updated -`50,000` entries per reservoir layer per frame with two candidates per update, -and measured `4.471 ms/frame`, `223.7 FPS` equivalent over `120` frames. This -proves compute-side GPU residency and budgeted temporal convergence for the -layered cache; final shaded visibility still has to consume the same packed -buffers. Next packet evolution should add density/extinction Form rows and -participating-medium Appearance/Transport rows instead of forcing flames through -opaque SDF/PBR semantics. - -### Phase J: Learned Priority Gate - -Only after telemetry exists, train or calibrate a predictor for update/residency -priority. Delete it if it does not beat the heuristic on held-out camera/sensor -traces. - -## Cut Lines - -- No learned predictor before telemetry. -- No recursive 3D form before 2D tile summaries and debug views are boring. -- No consumer-owned stable temporal cache. -- No GPU grammar traversal. -- No SSD frame stalls. -- No reuse without an explicit domain shift and validation contract. -- No debug-free recursive density. - -## Sources - -- NVIDIA ReSTIR DI: - https://research.nvidia.com/publication/2020-07_spatiotemporal-reservoir-resampling-real-time-ray-tracing-dynamic-direct -- NVIDIA ReSTIR GI: - https://research.nvidia.com/publication/2021-06_restir-gi-path-resampling-real-time-path-tracing -- GRIS: - https://graphics.cs.utah.edu/research/projects/gris/sig22_GRIS.pdf -- RTXDI ReSTIR docs: - https://github.com/NVIDIA-RTX/RTXDI/blob/main/Doc/RestirGI.md - https://github.com/NVIDIA-RTX/RTXDI/blob/main/Doc/RestirPT.md -- EWA splatting: - https://dash.harvard.edu/bitstream/handle/1/4138240/Zwicker_EWA.pdf -- Object-space EWA surface splatting: - https://publications.ri.cmu.edu/object-space-ewa-surface-splatting-a-hardware-accelerated-approach-to-high-quality-point-rendering/ -- 3D Gaussian Splatting: - https://arxiv.org/abs/2308.04079 -- Geometry clipmaps: - https://developer.nvidia.com/gpugems/gpugems2/part-i-geometric-complexity/chapter-2-terrain-rendering-using-gpu-based-geometry -- Nanite: - https://advances.realtimerendering.com/s2021/Karis_Nanite_SIGGRAPH_Advances_2021_final.pdf -- KinectFusion: - https://www.microsoft.com/en-us/research/publication/kinectfusion-real-time-dense-surface-mapping-tracking/ -- Curless and Levoy volumetric fusion: - https://graphics.stanford.edu/papers/volrange/volrange.pdf -- Instant-NGP: - https://research.nvidia.com/publication/2022-07_instant-neural-graphics-primitives-multiresolution-hash-encoding diff --git a/docs/stochastic-transparent-surface-pipeline.md b/docs/stochastic-transparent-surface-pipeline.md deleted file mode 100644 index 97caebf..0000000 --- a/docs/stochastic-transparent-surface-pipeline.md +++ /dev/null @@ -1,120 +0,0 @@ -# Stochastic Transparent Surface Pipeline - -Aquarium needs a shared path for transparent stochastic surfaces: Grid lines, -billboard particles, glyph motes, glints, future sprite cards, and any other -thing that is visible as coverage rather than as one opaque surface hit. - -The important rule is that these objects do not own canonical depth. A ray may -encounter several candidates, and blue-noise/stochastic coverage may choose -different candidates across frames. Treating one event as "the" surface creates -self-occlusion, false depth rejection, and temporal history murder. - -## Classes - -### Opaque Solids - -Examples: Epiphany agent bodies, cursor bodies, and future solid SDF objects. - -Output: - -- color -- travel/depth -- field id -- normal -- material id -- reactive/velocity if needed - -This is the ordinary one-ray-one-hit contract. - -### Stochastic Transparent Events - -Examples: Grid line support, particles, billboard cards. - -Output per event: - -- travel -- field or batch id -- support/coverage -- premultiplied color -- approximate normal or facing axis when useful -- thickness/depth band when useful - -The event stream is sorted front-to-back and clipped by opaque solid travel. -Events do not clip each other as opaque surfaces. They composite. - -## Frame Shape - -1. Render opaque solid scene and depth/travel. -2. Render/integrate participating media against opaque solid travel. -3. Generate stochastic transparent events up to opaque solid travel. -4. Apply blue-noise coverage decisions or alpha-to-coverage equivalent. -5. Composite selected transparent events premultiplied front-to-back. -6. Write transparent temporal descriptors separate from opaque metadata. - -The Grid should not be a special scene surface. It should emit events from its -heightfield/line-support intersection. Particles emit events from their sorted -billboards or bins. Both land in the same transparent event pipe. - -## Temporal Contract - -Transparent history cannot validate like opaque history. - -Opaque validation compares one depth, normal, field id, and color neighborhood. -Transparent validation should compare a distribution summary: - -- accumulated support/coverage -- nearest event travel -- weighted mean travel -- travel variance or thickness band -- dominant transparent class id -- optional batch/field id where stable - -History should survive ordinary stochastic hit/miss changes inside the same -support distribution. It should reject when the distribution moves, disappears, -becomes occluded by a solid, or changes class. - -## Grid Events - -The Grid is an implicit heightfield plus analytic line support, not an opaque -terrain surface. - -A robust Grid event generator should: - -- use the existing slope-aware `terrainGap = p.z - terrainHeight(p.xy)` march -- find refined heightfield crossings up to opaque solid travel -- evaluate line/isoline/field-line support at each crossing -- emit only crossings with meaningful support -- composite events front-to-back in the transparent pipe -- keep opaque scene metadata untouched - -It must not: - -- write Grid as the scene's opaque travel -- let one Grid crossing occlude later Grid crossings -- fixed-step sample a thin band and hope not to miss it -- invent a Grid-only temporal path that particles cannot use - -## Particle Events - -Particles should use the same pipe. - -The particle system supplies candidate events from sorted/binned billboards. -Each event carries travel, coverage, premultiplied color, and a stable batch or -particle id when available. Stochastic coverage chooses visibility. Temporal -validation compares the transparent distribution rather than demanding exact -per-particle depth stability. - -## Debug Views - -Required before relying on the pipe: - -- transparent event count -- selected stochastic event coverage -- accumulated transparent alpha -- nearest transparent travel -- weighted transparent travel -- transparent travel variance/thickness -- transparent class id -- opaque terminator travel - -If these views do not agree with the final composite, the pipe is lying. diff --git a/docs/temporal-sdf-gaussian-field.md b/docs/temporal-sdf-gaussian-field.md deleted file mode 100644 index 5405788..0000000 --- a/docs/temporal-sdf-gaussian-field.md +++ /dev/null @@ -1,159 +0,0 @@ -# Temporal Field Gaussian - -## Objective - -Aquarium owns the renderer feature for live volumetric point-cloud/splat input: -clients provide stable world-space Gaussian observations, and the engine turns -them into a buffered, reprojectable, D3D12-rendered field. LocalCastBridge can -then feed sensor-fusion output into Aquarium as a normal scene contract instead -of smuggling renderer policy through client code. - -The historical `SDF` name is now backend baggage. This contract is a temporal -Form-field path: opaque producers may resolve to SDF/level-set surfaces, while -flames, smoke, transparent gradients, and sensor fusion may stay as -density/extinction/confidence fields until evidence justifies a surface. - -## Current Mechanism - -The client-facing contract is `AquariumSceneState.TemporalGaussianField`. -Each `AquariumTemporalSdfGaussian` carries stable identity, current and previous -center, velocity, oriented radii, color/opacity, confidence, history weight, -compact-kernel controls, and field id. - -`Aquarium.Engine.Fractal.Temporal.TemporalGaussianAccumulator` consumes -`TemporalGaussianObservation` rows and lowers them through the shared -`TemporalSpatialEvidenceReservoir`. The reservoir owns the live buffering -policy: - -- stable keys identify tracks across camera/sensor frames -- presentation delay lets late sensor data converge before rendering -- accumulation window expires old tracks -- max-track budgets evict low-confidence stale tracks before renderer lowering -- smoothed velocity predicts the presented center -- history weight is confidence scaled by age inside the window - -The Gaussian field is one backend for this reservoir, not the reservoir's -identity. Fractal form probes, visual point-cloud features, transparent density -samples, and future acoustic constraints can all enter as stable keyed spatial -evidence as long as each producer declares confidence, time, bounds, field -layer, field encoding, and payload lowering rules. -`TemporalSpatialEvidenceLowering` owns the current packet conversions for -`TemporalGaussianObservation`, `AquariumTemporalSdfGaussian`, and -`AquariumGpuFusionSeed`; consumers should use those helpers instead of packing -payload vectors privately. - -The D3D12 renderer lowers the field into `D3D12TemporalGaussianPacket`, uploads -the active packet span into a 1,048,576-entry structured buffer, and renders an -instanced proxy-quad pass from -`D3D12TemporalGaussian.hlsl`. The pixel shader evaluates a compact anisotropic -Gaussian kernel in world space, writes HDR scene color/travel, field metadata, -normal, and temporal-control coverage so the existing resolve sees the field as -diegetic scene content. - -`Aquarium.LocalCast` is the first concrete live client for this contract. It -reads `localcast.visual.render_frame` from LocalCastBridge's typed CultCache -MessagePack document. That point/seed route is now explicitly a fallback and -debug harness: it proves the million-slot temporal Gaussian draw and keeps OBS -fed while the live capture path moves into Aquarium. The production ownership -line is `AquariumGpuSensorFrame`: camera and Leap inputs arrive as calibrated -sensor records plus shared GPU texture handles, the D3D12 backend owns their -metadata buffers, and fusion kernels lower those GPU-resident inputs into the -temporal Gaussian buffer consumed by the SDF Gaussian draw. - -LocalCast GPU fusion also has its own live-history accumulator. New frames -update stable-key tracks, stale tracks expire after a bounded horizon, and the -whole retained set is sent to the GPU seed buffer every frame. The default -history horizon is 18 seconds and may be overridden with -`LOCALCAST_GPU_HISTORY_SECONDS` from 1 to 120 seconds. That is the reconstruction -buffer: long enough to harvest samples, bounded enough to remain a machine -instead of a scrapbook with a power cord. - -## Invariants - -- Field accumulation happens in world space before pixel history. TAA is the - resolver, not the owner of sensor identity. -- Stable keys belong to the producer/accumulator boundary; shader packets are - backend output and do not invent identity. -- The compact support kernel has a finite bound. Renderer cost must scale from - declared bounds, not from infinite translucent fog. -- Density/opacity observations are not required to become surfaces. A - transparent medium may remain a participating Form field with Appearance and - Transport payloads instead of being collapsed into a fake SDF. -- Client code may construct observations or a field for diagnostics, but - Aquarium owns live sensor texture import, packet layout, root binding, shader - evaluation, fusion, and temporal-control metadata. -- JSON is not a renderer boundary. CultCache/CultNet producers should lower into - typed contract rows before Aquarium sees the data. - -## Cut Line - -This cut deliberately claims million-slot ingestion, not a finished million-splat -renderer architecture. The live D3D12 path can draw up to 1,048,576 temporal -Gaussians through instanced proxy quads, only uploads the active seed/packet -span, and now owns the GPU lowering step. Python/LocalCastBridge may still -produce calibration artifacts and reference captures, but it must not own -per-frame dense stereo, feature tracking, or reconstruction compute. The next -scaling cut belongs to the Aquarium renderer: shared texture import, packed -camera planes, Leap packed-map channel extraction, selected-cut residency, -tiled/bin dispatch, GPU accumulation, and clustered visibility. - -## GPU Fusion Spine - -The active GPU boundary is deliberately narrow: - -```text -LocalCast calibration/device metadata --> AquariumGpuSensorFrame { calibrated cameras + shared GPU textures } --> D3D12 sensor metadata buffers + imported texture SRVs --> D3D12 LocalCast fusion compute shader --> RWStructuredBuffer --> instanced SDF Gaussian draw --> TAA/resolve -``` - -Ownership: - -- `AquariumGpuSensorFrame` is the live renderer contract for GPU-owned fusion - input. -- `AquariumGpuFusionField` remains a temporary fallback/debug contract for - already-derived point claims. -- `LocalCastGpuFusionMapper` converts typed LocalCast point claims into compact - seeds only for that fallback path. -- `LocalCastGpuFusionAccumulator` is only the LocalCast adapter around - `TemporalSpatialEvidenceReservoir`; it maps fallback stable seeds into shared - evidence observations and lowers reservoir samples back to - `AquariumGpuFusionSeed`. -- `D3D12LocalCastFusion.hlsl` owns the first compute lowering pass. -- `D3D12Renderer` owns GPU sensor camera metadata storage, UAV-capable temporal - Gaussian storage, dispatch, and the transition back to shader-resource state - for the draw. -- `AquariumAcousticFieldFrame` carries the ultrasonic chirplet timing oracle and - room/position constraints. Visual evidence may arrive late and be refined, but - acoustic timing is the clock witness for aligning the delayed broadcast world. -- `AquariumCalibrationEventFrame` carries deliberate calibration actions such - as claps. A clap gives the system one event that every camera can see and the - audio timing oracle can timestamp to microsecond-scale uncertainty, making it - the cheap, brutal alignment hammer for camera clock offsets and pose drift. - -Current Aquarium cut: the contract, D3D12 camera metadata buffer, external -texture importer, and sensor SRV table exist. A producer may provide either a -duplicated shared handle or a named shared handle for each camera/Leap plane. -When sensor textures are present, Aquarium can dispatch fusion without fallback -seeds and write RGB-derived Gaussian samples into the temporal buffer. Those -samples are no longer isolated per-camera flecks: the shader computes a compact -per-sample visual descriptor, compares it against a neighboring camera stream, -raises confidence when stochastic samples appear to correspond, and shrinks the -kernel toward the matched surface. Acoustic constraints from the ultrasonic -chirplet loop bias confidence and velocity near measured room/position returns. - -Next cut: replace the first-pass descriptor comparison with calibrated -epipolar/flow search, Leap packed-map channel extraction, and a persistent GPU -correspondence/refinement buffer that can update camera pose and surface tracks -over the several-second broadcast delay window. Deliberate clap events should -feed that buffer as high-confidence timing correspondences: visual impact frame -per camera against acoustic oracle time, then pose/clock correction under the -same delayed broadcast horizon. - -The first shader pass also uses camera-facing proxy planes to evaluate each -kernel. True ray-integrated volume compositing, Gaussian depth sorting, and -per-Gaussian previous-center reprojection remain the next renderer cuts. diff --git a/docs/temporal-spatial-evidence-reservoir.md b/docs/temporal-spatial-evidence-reservoir.md deleted file mode 100644 index 3f3fe5d..0000000 --- a/docs/temporal-spatial-evidence-reservoir.md +++ /dev/null @@ -1,203 +0,0 @@ -# Temporal Spatial Evidence Reservoir - -## Objective - -Aquarium owns the shared temporal evidence machine for two customers: - -- fractal rendering, where Form/Appearance/Transport candidates need bounded - reuse across pixels, frames, and nested domains; -- Mimir/LocalCast sensor fusion, where camera and microphone features need a - delayed coherence window before the resolved field is rendered. - -The old stable-key accumulator was useful, but it was not ReSTIR. The live -architecture now splits the problem into a small resampled-importance core, a -spatial evidence track layer, typed lowerings, renderer passes, and TAA history. - -## Research Spine - -- NVIDIA ReSTIR DI repeatedly resamples candidate light samples, then applies - spatial and temporal resampling to share useful samples across nearby pixels - and frames. The paper reports equal-error speedups of 6-60x, with biased - variants reaching 35-65x in its tested direct-lighting workloads. - Source: https://research.nvidia.com/labs/rtr/publication/bitterli2020spatiotemporal/ -- ReSTIR GI applies the same screen-space spatiotemporal reuse idea to - multi-bounce indirect paths and reports 9.3x-166x MSE improvement at one - sample per pixel in tested scenes. - Source: https://research.nvidia.com/publication/2021-06_restir-gi-path-resampling-real-time-path-tracing -- GRIS generalizes RIS/ReSTIR to correlated samples, unknown PDFs, varied - domains, and shift mappings. That is the important part for Aquarium: - fractal domains and sensor-fusion samples are not all light samples. - Source: https://research.nvidia.com/labs/rtr/publication/lin2022generalized/ -- RTXDI's integration docs make the pass boundary concrete: acquire initial - samples, store reservoir data, validate temporal reuse through reprojection, - validate spatial reuse against nearby surfaces, shift candidate paths between - domains, then shade/denoise from the final reservoir. - Sources: - https://github.com/NVIDIA-RTX/RTXDI/blob/main/Doc/RestirGI.md - https://github.com/NVIDIA-RTX/RTXDI/blob/main/Doc/RestirPT.md - -## Pipeline Map - -```text -producer observations --> candidate generator --> target evaluator --> ResampledImportanceReservoir --> temporal reuse pass --> spatial/domain reuse pass --> validation + shift mapping --> TemporalSpatialEvidenceReservoir track layer when stable fields are needed --> TemporalSpatialEvidenceLowering --> backend packet stream --> renderer/fusion passes --> TAA guide/history buffers -``` - -## Ownership - -`ResampledImportanceReservoir` owns RIS/ReSTIR-style candidate math: - -- one selected representative sample; -- summed importance weight of accepted candidates; -- number of source candidates represented by the reservoir; -- selected sample target value; -- final contribution weight `weightSum / (candidateCount * selectedTarget)`. - -Candidate generators own proposal distributions. A fractal renderer may propose -form probe candidates from projected error, node bounds, blue-noise screen -tiles, or resident children. Mimir may propose visual/audio feature candidates -from sensor confidence and calibration state. The reservoir does not know these -domains; it only receives target and source-PDF values. - -Every evidence sample should state its layer and encoding before lowering: -Form, Appearance, or Transport; then SDF, height, density, extinction, -material, phase, emission, radiance, feature, or confidence as appropriate. -Opaque worlds can promote Form evidence into SDF surfaces. Flames and uncertain -sensor fields may remain density/extinction/confidence volumes. That is not a -failure to find the surface; it is the correct field. - -Reuse passes own validity and shift mapping. A sample may be reused only when -the target domain can explain it. For pixels this means depth/normal/material -compatibility, motion vectors, conservative visibility, and disocclusion tests. -For fractal domains it means matching domain ancestry, bounded local-frame -error, resident payload compatibility, conservative surface bounds for SDF -encodings, and conservative support/extinction bounds for density encodings. -For sensor fusion it means time delay, calibration confidence, modality -agreement, and feature reprojection error. - -`TemporalSpatialEvidenceReservoir` owns stable resolved spatial tracks after -candidate selection when the output is a field with persistent identity: - -- stable key identity; -- accumulation window and presentation delay; -- confidence-weighted smoothing; -- velocity prediction; -- history weight from confidence and sample age; -- expiry; -- max-track eviction by confidence and age. - -`TemporalSpatialEvidenceLowering` owns packet conversion. Consumers do not pack -payload vectors by private convention when a lowering helper exists. - -TAA owns pixel history validation and temporal guide buffers. It may consume -reservoir confidence, sample age, domain id, motion, and temporal-detail lanes, -but it does not own producer identity or stable spatial evidence. - -## Invariants - -- Reservoir math is a pure, testable core before it becomes HLSL. -- A reservoir is not a dictionary of tracks. A track layer may use reservoirs, - but it does not replace candidate resampling. -- Reuse is invalid until a pass proves the shift/validation contract for the - source and target domains. -- Conservative bounds remain the safety authority. Learned or stochastic - priority may decide what to refresh first; it must not replace field bounds, - visibility bounds, or calibration bounds. -- CPU, GPU, RAM, and SSD budgets are inputs to candidate generation and - residency. They are not hidden side effects of renderer convenience code. -- Consumer repos do not grow parallel stable-key temporal caches. - -## Current State - -Built: - -- `ResampledImportanceCandidate` stores a sample, target value, source - PDF, and represented candidate count. -- `ResampledImportanceReservoir` accepts candidates by weight - proportional to `target / sourcePdf`, merges reservoirs, preserves represented - candidate count, and exposes the RIS contribution weight. -- `TemporalSpatialEvidenceReservoir` remains the stable track layer used by - temporal Gaussian fields and LocalCast fallback GPU fusion. -- `FractalContributionCache` remains the node-summary LOD estimator, and now - frames scheduled update nodes as weighted reservoir candidates with a - per-frame reservoir snapshot for debug and tests. It is the candidate source, - not the full temporal/spatial reuse pass. -- `FractalProbeSample` is the first typed fractal form/detail sample shape for - the ReSTIR/GRIS path. It carries domain key, node key, local center, bound - radius, target contribution, source PDF, material delta, and payload handle. - `FractalProbeReuseValidator` currently proves domain lineage and local-shift - compatibility; renderer-facing camera, disocclusion, material, and visibility - checks still need to be added before temporal/spatial reuse is complete. - -Not built yet: - -- GPU reservoir buffers; -- camera/disocclusion/material validation for fractal form/appearance reservoirs; -- spatial neighbor reuse across screen tiles and cube-sphere neighbor domains; -- GRIS-style domain shift mappings for nested `.aquageo` domains; -- expanded TAA guide-buffer storage for previous-frame reservoir confidence, - sample age, domain validity, and invalidation reason; -- SSD/RAM residency queues driven by reservoir contribution estimates. - -## TAA Guide Layout - -Reservoir/TAA guide data has a dedicated current scene target and ping-ponged -history target. It is deliberately separate from `history-control.w`, which -continues to own pixel history age. - -```text -x: reservoir confidence -y: reservoir sample age -z: domain validity -w: invalidation code -``` - -The first live producers are SDF surfaces and temporal Gaussian splats, but the -schema is not surface-only. Resolve reads the current and previous guide -textures, folds confidence and domain validity into history validation, then -writes the next history guide. Future ReSTIR/GRIS passes should extend the -producer side of this schema with explicit Form/Appearance/Transport fields -rather than packing more reservoir folklore into scene-control channels. - -## Implementation Roadmap - -1. Keep the CPU reservoir core pure and exhaustive under unit tests. -2. Add typed reservoir samples for fractal field probes: domain key, local - frame, bound radius, target contribution, source PDF, layer/encoding, payload - handle, and material or transport delta. -3. Turn `FractalContributionCache` into a candidate generator that refreshes - nodes under CPU budget and submits candidates to the reservoir core. -4. Add temporal reuse for fractal probes using camera motion, domain ancestry, - local-frame error, and conservative bounds. -5. Add spatial reuse across screen tiles and quadtree neighbors. -6. Lower selected reservoirs into GPU field packets. SDF packets are the solid - surface encoding; density/extinction packets are the transparent/sensor - volume encoding. Expose debug views for weight sum, selected target, - candidate count, confidence, age, and invalidation reason. -7. Weave reservoir confidence and temporal detail into TAA guide buffers so the - history filter can distinguish stable reused evidence from fresh stochastic - noise. The first pass uses current scene-control.w for reservoir confidence - and keeps history-control.w as age; full previous-frame reservoir validity - still needs an expanded guide layout. -8. Add Mimir-facing candidate adapters only after the fractal path proves the - contract: modality features are candidates, not a second reservoir system. -9. Port the pure core to HLSL and add CPU/GPU parity fixtures. -10. Add residency scheduling: hot selected reservoirs keep GPU packets resident, - warm reservoirs keep RAM payloads, cold reservoirs fall to SSD handles. - -## Cut Line - -If a new subsystem stores temporal candidates, it must state whether it owns raw -producer retention, resampled candidate selection, stable resolved tracks, -packet lowering, or TAA history. If it cannot name that authority, it is not an -architecture. It is a decorative leak. diff --git a/docs/tsr-inspired-taa-spec.md b/docs/tsr-inspired-taa-spec.md deleted file mode 100644 index 0f1bd51..0000000 --- a/docs/tsr-inspired-taa-spec.md +++ /dev/null @@ -1,301 +0,0 @@ -# TSR-Inspired TAA Spec - -Aquarium needs an owned temporal resolver, not a copied implementation. The -target is inspired by public TSR behavior: stable subpixel detail, aggressive -history validation, visible debug terms, and special handling for pixels whose -appearance is not fully described by motion vectors. - -## Inputs - -The resolver owns these signals: - -- current HDR scene color -- current ray travel -- previous HDR history color -- previous ray travel -- current camera/Grid constants -- previous camera/Grid constants -- current and previous projection jitter -- stochastic coverage from diegetic Grid surfaces - -Later gates add: - -- field id -- normal -- explicit velocity -- reactive mask -- transparency/composition mask -- resurrection history - -## Current Pass Contract - -The scene pass renders into an HDR texture: - -```text -rgb = linear scene color -a = ray travel in world units -``` - -The pass does not tonemap. Tonemapping belongs after temporal resolve. - -## Reprojection - -For the first implementation, motion is camera-derived: - -1. Reconstruct the current world hit from current camera, current jittered ray, - and current travel. -2. Project that world hit into the previous camera basis. -3. Remove previous jitter to find the previous history UV. -4. Sample previous history if the UV is valid. -5. Compare previous history travel against the reprojected point's expected - distance from the previous camera, not against current-frame travel. - -This is sufficient for camera motion and stochastic Grid coverage. It is not the -final answer for animated bodies or field animation. - -## Rejection - -Reject or weaken history when: - -- previous UV is outside the frame -- travel differs too much -- current or previous travel is invalid -- current neighborhood color bounds do not contain the reprojected history - -The first pass uses a 3x3 neighborhood min/max clamp and travel-difference -weighting. Later passes add field/material ids, normals, disocclusion masks, and -reactive masks. - -## Resolve - -The resolver outputs both: - -- tonemapped final backbuffer color -- linear HDR history for the next frame - -Current blend target: - -```text -resolved = lerp(current, clamped_history, history_weight) -``` - -History weight starts conservative. Stochastic Grid coverage needs accumulation, -but ghosting is worse than shimmer while the renderer lacks full velocity, -material id, and reactive masks. The resolver should earn trust before taking -more history. - -## Non-Negotiables - -- Do not use Playdead-style TAA as the final model; it ghosts too easily for the - scene we are building. -- Do not vendor Unreal TSR code. Study behavior and build a clean-room resolver. -- Do not hide missing renderer signals with larger blend weights. -- Do not make the Grid a final-image HUD layer; it is diegetic scene UI and must - respect nearer solids. - -## Implementation Gates - -### Gate 1: Owned Temporal Pass - -- HDR scene target -- history ping-pong -- camera jitter -- current/previous camera reprojection -- travel rejection -- 3x3 color clamp -- final tonemap after resolve - -### Gate 2: Renderer Signals - -- material/field id buffer -- normal buffer -- explicit velocity for animated SDF bodies -- coverage/reactive masks for stochastic Grid and future particles - -Current Gate 2A implementation: - -- scene metadata target stores stable field id plus surface normal -- history metadata ping-pongs alongside color/travel history -- field id mismatch rejects history -- normal mismatch weakens/rejects history -- Grid stochastic surfaces write Grid travel/normal even when the current - dither sample does not draw color, so the temporal resolver accumulates the - diegetic surface rather than reprojecting from the solid behind it - -Current Gate 2B implementation: - -- Self, Grid, and each orbiting planet have distinct field ids -- orbiting planet hits map their current world hit back to the planet's previous - center before camera reprojection -- this gives analytic SDF bodies object motion without a full velocity buffer - yet - -Current Gate 2C implementation: - -- `AquariumSceneState.TemporalGaussianField` carries world-space temporal SDF - Gaussian splats with stable keys, current/previous center, velocity, - confidence, history weight, field id, and compact-kernel controls -- `TemporalGaussianAccumulator` buffers sensor observations in world space before - rendering, using a presentation delay plus accumulation window instead of - asking final-pixel TAA to discover identity after projection -- D3D12 uploads the field into a structured buffer and renders it through - `D3D12TemporalGaussian.hlsl`, writing color/travel, field metadata, normals, - and temporal-control coverage into the existing scene/resolve path - -Still missing: - -- separate field ids once the SDF field registry exists -- reactive/coverage masks -- richer disocclusion classification -- a general velocity buffer for non-rigid fields and deformation -- per-Gaussian previous-center reprojection in the resolve pass - -### Gate 3: Stochastic Event Control - -Current Gate 3A implementation: - -- scene pass writes a temporal-control target separate from color/travel and - field/normal metadata -- temporal control currently stores: - -```text -x = reactive strength -y = stochastic/composition coverage -z = reserved -w = reserved -``` - -- Grid coverage feeds the coverage channel -- low-coverage Grid samples raise reactive strength and reduce history weight -- the resolve combines reactive and coverage weights with travel, field, normal, - and neighborhood-color validation - -Current Gate 3B implementation: - -- temporal-control history ping-pongs alongside color/travel and field/normal - history -- resolve samples previous-frame temporal control at the reprojected UV -- coverage discontinuity reduces history -- current temporal control is written into the history set for the next frame - -Current Gate 3C implementation: - -- temporal-control history `w` stores accepted history age in frames -- validation grows age when reprojected history survives the travel, field, - normal, color, and coverage checks -- history authority ramps with age, so newly accepted history can contribute but - does not immediately get the same weight as stable history -- age resets to zero on validation failure - -Current Gate 3D implementation: - -- travel validation uses the reprojected previous-world position's distance from - the previous camera -- raw current-frame travel is no longer compared directly to previous history - travel, because camera motion changes the ray distance even when the world hit - is stable - -Current Gate 3E implementation: - -- stochastic Grid history bypasses opaque-surface neighborhood color clamping - and current-frame color-delta rejection -- Grid validation still uses field id, travel, normal, coverage continuity, - reactive weight, and history age -- this prevents a current dither miss from declaring the true neighborhood to be - background and crushing the very history that should accumulate stochastic - coverage - -Current Gate 3F implementation: - -- stochastic Grid history uses a high-retention blend policy distinct from - opaque surfaces -- Grid history weight no longer scales down with current coverage or reactive - strength; low coverage is exactly where temporal accumulation is needed -- opaque surfaces keep the stricter color/reactive validation path -- debug mode `2` should now show a smoother history signal than raw scene mode - `1` when the Grid is stable - -Current Gate 3G implementation: - -- identity/control buffers are point-loaded, not linearly sampled -- field id equality is exact after point-loading, so Grid/Self/planet boundaries - hard-reject mismatched history -- Grid history color is sampled with the same nearest pixel used for metadata so - bright foreground silhouettes do not bilinearly bleed into background Grid - history -- Grid max history weight is reduced from the too-soft `0.975` to `0.94` - -Current Gate 3H implementation: - -- Grid temporal `coverage` is now line/contour/field-line support, not broad - overlay alpha -- broad weather/field tint can still render through stochastic coverage, but it - does not keep history age alive across the whole Grid surface -- Grid history is gated by current support, so stale stochastic hits cannot - billow away from the analytic line support -- Grid max history weight is reduced again to `0.90` with a lower fresh-history - scale for crisper line response - -Current Gate 3I implementation: - -- Grid resolve reconstructs the analytic Grid overlay at the current world hit - and uses premultiplied overlay color as the current color estimate -- the scene pass may still use stochastic coverage, but the temporal resolver - no longer treats the current binary hit/miss sample as the true radiance -- debug mode `1` can remain noisy because it shows the raw stochastic scene; - mode `0` should now use the analytic Grid estimate plus validated history - -Current Gate 3J implementation: - -- debug mode `1` is restored to raw current scene color, before Grid analytic - reconstruction -- Grid final color no longer blends previous color history; it uses the analytic - current Grid estimate and writes that estimate into history -- history/age/weight debug modes remain useful diagnostics, but stale Grid color - history no longer drives the final visible Grid - -Current Gate 3L/3M implementation: - -- projection jitter uses a small Halton sequence, currently scaled below half a - pixel so the resolve gets sample diversity without visible whole-frame wobble -- current and previous jitter are both uploaded through frame constants; previous - history projection removes the previous jitter before sampling history -- final presentation blends validated temporal color history in mode `0` -- SDF object highlights have a narrow hot-current path: when the current SDF - sample is much brighter than valid reprojected history, color rejection is - relaxed so history can damp transient specular fireflies while travel, field, - normal, coverage, and coverage-continuity validation still apply -- bloom presentation is attenuated when the resolved scene luminance is much - lower than the raw current scene luminance, so current-frame fireflies do not - keep blooming after temporal history has damped the underlying scene color -- bloom prefilter clamps unsupported single-pixel HDR spikes against local - neighborhood luminance before downsample/blur, so one-frame fireflies do not - spread into neighboring pixels before the temporal resolve sees them -- modes `2` through `4` show the sampled history, accepted history age, and - history weight - -Still missing: - -- reactive reset for lighting and density changes -- separate history policy for opaque surfaces and stochastic surfaces - -### Gate 4: TSR Features Worth Stealing In Spirit - -- flicker analysis for high-frequency linework and stochastic coverage -- history resurrection for reappearing stable details -- debug visualizations for rejection, clamp, velocity, travel, and history age - -Current debug view controls: - -- `F1` cycles temporal debug modes in the running window -- `0` final resolved color -- `1` raw current scene color -- `2` reprojected history color used by the resolver -- `3` accepted history age -- `4` history weight -- `5` current temporal control: reactive in red and Grid support/coverage in - green -- `6` current field identity palette for Grid, Self, and planets -- `7` bloom/veil contribution after exposure and before tonemapping -- `8` exposed luminance bands -- `--render-debug` and `AQUARIUM_RENDER_DEBUG_MODE` set the startup mode diff --git a/docs/vortice-spine.md b/docs/vortice-spine.md deleted file mode 100644 index a98da08..0000000 --- a/docs/vortice-spine.md +++ /dev/null @@ -1,34 +0,0 @@ -# Vortice Spine - -Aquarium starts from a thin native spine: - -- `Platform.Win32Window` owns window creation and the message pump. -- `Render.D3D12Renderer` owns the D3D12 device, command queue, swapchain, - frame resources, render targets, shaders, and present path. -- `AquariumRuntime` owns simulation state and emits one `AquariumFrame` per - tick. -- `OrbitCameraRig` and `GridFrame` preserve the first invariant: the camera - target is the Grid center, and Grid radius derives from zoom distance rather - than pitch, yaw, or screen projection. - -## Why Vortice - -Vortice gives direct access to D3D/DXGI without forcing an engine protocol on -top. It is low ceremony enough to build the renderer Aquarium needs while -keeping C# as the everyday working environment. - -## Current Renderer - -The renderer owns the visible Aquarium frame: - -1. Camera and Grid constants come from the client runtime. -2. A height-field pass renders the scalar field target from client brush data. -3. A fullscreen D3D12 HLSL pass traces the background and height-field surface. -4. Client-declared SDF proxy pipelines render Epiphany bodies into the shared - scene targets. -5. HDR bloom and presentation run before the swapchain is handed to the overlay. -6. DirectWrite overlay text and debug UI draw after the scene pass. - -No framework-owned deferred path or ambient light is hiding under the floor. -When richer lighting returns, it enters through an Aquarium-owned renderer -contract, not convenience globals. diff --git a/docs/zyphos-eusocial-sync.md b/docs/zyphos-eusocial-sync.md deleted file mode 100644 index e5e3521..0000000 --- a/docs/zyphos-eusocial-sync.md +++ /dev/null @@ -1,90 +0,0 @@ -# Zyphos and Eusocial Interbeing Sync - -Zyphos simulates the world defined by the neighboring Eusocial Interbeing vault -at `E:\Projects\Eusocial Interbeing`. The vault is the setting authority. -Aquarium is the renderer and interaction testbed. - -## Objective - -Use Zyphos as a visible planetary demo for Eusocial Interbeing without turning -Aquarium into a second lore repository. - -## Current Mechanism - -- Eusocial Interbeing stores canon and design inference in Obsidian notes under - `Eusocial Interbeing/`. -- Aquarium.Zyphos renders Zyphos, fixed-sky Umbros, atmosphere, night-side - glints, and first-pass eclipse cadence through the shared Aquarium host and - SDF renderer path. -- `ZyphosUmbrosSystem` owns the current render-scale binary constants: - Zyphos radius, Umbros radius ratio, 8-Zyphos-radii separation, sea level, and - star phase used by the shader. -- `Worlds/zyphos-first-fractal-terrain.aquageo` owns the first semantic world - patch: solar, orbital, planetary, and lat/long domains wrap the tile terrain - so later fractal grammar nodes have real nested reference frames instead of - undocumented coordinate folklore. -- No automatic sync exists. Changes cross the boundary by explicit notes and - state-map updates. - -## Invariants - -- Setting canon belongs in the vault. -- Aquarium docs may describe render requirements, demo scope, and questions, but - must not become the authoritative setting bible. -- Zyphos bends to physics. If orbital mechanics, light budget, eclipse geometry, - or climate constraints narrow an early visual idea, the demo should use that - pressure as worldbuilding fuel rather than hiding an impossible sky in shader - code. -- Zyphos-specific code belongs under `src/Aquarium.Zyphos`; generic renderer - machinery belongs under Aquarium.Engine only when it serves multiple clients. -- Design inference must be labeled before it hardens into canon. -- Rendering constraints should feed back into the vault as questions, not silent - lore edits hidden in shader code. - -## First Conversation - -The first Zyphos pass should stage the planet as a dimly lit close-binary world -with two legible continental systems: - -- Umbros is the slightly smaller twin of Zyphos, mutually tidally locked with it - and fixed in the sky except for precession/libration; -- the primary star is dim, so the habitable zone is close and the biosphere is - energy-starved relative to Earth; -- the working vault baseline gives Umbros a very large apparent diameter - (roughly 10-13 degrees for the current 8-10 Earth-radii separation candidates) - and daily central eclipses around an hour near the relevant equatorial track; -- the biosphere is founded on mutable cellular memory exchange, so sentience and - eusocial contracts exist across cellular, organismal, social, and ecological - scales instead of being reserved for a few special species; - -- the Airawa home continent, where living memory networks, mother trees, - disconnected networks, and imperial memetic infrastructure create visible - ecological-political structure; -- the Sa'auei'a continent, where nomadic reciprocity, breeding grounds, remembered - routes, and mobile family-unit infrastructure create a different map logic. - -This does not require detailed species bodies yet. The first useful render target -is planetary-scale readability: landmass logic, ecological network hints, -settlement/non-settlement patterns, and night-side signals that reflect distinct -civilizational structures. - -Aquarium should treat these as lighting, sky, time-of-day, and ecological -pressure constraints. The accepted physical baseline lives in the vault note -`Eusocial Interbeing/World/Zyphos Umbros Binary System.md`. -The accepted biosphere baseline lives in -`Eusocial Interbeing/Ecology/Mutable Memory Endosymbiosis.md`. -First concrete biosphere handles live in -`Eusocial Interbeing/Ecology/Zyphos Biosphere Examples.md`. -Future inhabitant-language names should be coordinated through Weksa at -`E:\Projects\weksa`, with names derived from language-project state rather than -English label substitution. - -## Feedback Path - -When Zyphos work creates a worldbuilding question, update the vault note -`Eusocial Interbeing/World/Zyphos Simulation Brief.md` first. Aquarium should -then reference the settled result, not carry private lore. - -When the vault changes canon that affects the demo, update this file and -`state/map.yaml` so Zyphos does not keep simulating an obsolete world because a -shader once looked nice. The shader has no voting rights. diff --git a/packages/AquaSynth.Core.0.1.0-alpha.2.nupkg b/packages/AquaSynth.Core.0.1.0-alpha.2.nupkg deleted file mode 100644 index 3b7ea64..0000000 Binary files a/packages/AquaSynth.Core.0.1.0-alpha.2.nupkg and /dev/null differ diff --git a/packages/AquaSynth.Core.0.1.0-alpha.3.nupkg b/packages/AquaSynth.Core.0.1.0-alpha.3.nupkg deleted file mode 100644 index cdc7ef2..0000000 Binary files a/packages/AquaSynth.Core.0.1.0-alpha.3.nupkg and /dev/null differ diff --git a/packages/AquaSynth.Faust.0.1.0-alpha.2.nupkg b/packages/AquaSynth.Faust.0.1.0-alpha.2.nupkg deleted file mode 100644 index 45b861f..0000000 Binary files a/packages/AquaSynth.Faust.0.1.0-alpha.2.nupkg and /dev/null differ diff --git a/packages/AquaSynth.Faust.0.1.0-alpha.3.nupkg b/packages/AquaSynth.Faust.0.1.0-alpha.3.nupkg deleted file mode 100644 index bd1391e..0000000 Binary files a/packages/AquaSynth.Faust.0.1.0-alpha.3.nupkg and /dev/null differ diff --git a/research/d3d12/source-manifest.md b/research/d3d12/source-manifest.md deleted file mode 100644 index b550722..0000000 --- a/research/d3d12/source-manifest.md +++ /dev/null @@ -1,28 +0,0 @@ -# D3D12 Source Manifest - -## Primary Sources - -- Microsoft Learn, Resource binding overview: - https://learn.microsoft.com/en-us/windows/win32/direct3d12/resource-binding-flow-of-control -- Microsoft Learn, Fence-based resource management: - https://learn.microsoft.com/en-us/windows/win32/direct3d12/fence-based-resource-management -- Microsoft Learn, Memory Management in Direct3D 12: - https://learn.microsoft.com/en-us/windows/win32/direct3d12/memory-management -- Microsoft Learn, Direct3D 12 core interfaces: - https://learn.microsoft.com/en-us/windows/win32/direct3d12/direct3d-12-interfaces -- Microsoft DirectX Developer Blog, A Look Inside D3D12 Resource State Barriers: - https://devblogs.microsoft.com/directx/a-look-inside-d3d12-resource-state-barriers/ -- NVIDIA Technical Blog, Advanced API Performance: Barriers: - https://developer.nvidia.com/blog/advanced-api-performance-barriers/ -- AMD GPUOpen, RDNA Performance Guide: - https://gpuopen.com/learn/rdna-performance-guide/ -- AMD GPUOpen, D3D12 Memory Allocator: - https://gpuopen.com/d3d12-memory-allocator/ -- AMD GPUOpen, Effective Use of the New D3D12_HEAP_TYPE_GPU_UPLOAD: - https://gpuopen.com/learn/using-d3d12-heap-type-gpu-upload/ - -## Scope - -This pass focused on D3D12 renderer architecture, not beginner API syntax: -descriptor heaps, root signatures, command allocators, fences, upload/ring -buffers, memory allocation, resource barriers, and GPU/CPU synchronization. diff --git a/research/d3d12/synthesis.md b/research/d3d12/synthesis.md deleted file mode 100644 index eff8c02..0000000 --- a/research/d3d12/synthesis.md +++ /dev/null @@ -1,132 +0,0 @@ -# D3D12 Synthesis - -## Core Model - -D3D12 is an explicit ownership API. The renderer owns command memory, resource -states, descriptor lifetime, upload lifetime, and GPU/CPU synchronization. The -driver stops hiding most of that work. Good D3D12 code is therefore less about -calling the right incantations and more about making ownership impossible to -misread. - -The source material converges on a few hard rules: - -- Keep root signatures stable and few. Bind a root signature once per command - list or pass family, not as routine draw noise. -- Use descriptor heaps deliberately. Shader-visible CBV/SRV/UAV heaps are - application-versioned memory; never overwrite descriptors still referenced by - in-flight GPU work. -- Treat RTV/DSV descriptors differently from shader-visible descriptors. RTV/DSV - bindings are versioned during command recording, but shader-visible heap - contents are not protected by the runtime. -- Reset command allocators only after the GPU has completed the work recorded - into them. -- Use fences to reclaim transient upload/descriptors/resources. A frame fence is - the coarse tool; finer fences can protect suballocations later. -- Prefer ring/suballocation systems for transient uploads and descriptors. Fixed - one-resource-per-use committed allocations are acceptable scaffolding, not the - renderer we keep. -- Track resource states explicitly and emit the minimum correct barriers. Avoid - broad generic states and redundant transitions. -- Batch or group barriers when that becomes practical; barriers and fences can - reduce GPU parallelism. -- Keep command submissions reasonably chunky. Tiny command lists and frequent - queue submissions pay CPU and GPU scheduling costs. -- Use PIX and vendor validation early. D3D12 mistakes are often legal-looking - until the GPU catches fire behind a curtain. - -## Descriptor Doctrine - -Microsoft's binding model puts descriptor heap content lifetime squarely on the -application for shader-visible heaps. The long-term Aquarium shape should be: - -- One large shader-visible CBV/SRV/UAV heap for the frame, or one persistent - heap plus suballocated dynamic ranges. -- A CPU-visible/staging descriptor store for reusable descriptors. -- Per-frame transient descriptor ranges that are reclaimed by fence value. -- Stable descriptor ranges for long-lived textures/buffers. -- Minimal `SetDescriptorHeaps` calls. Heap changes can invalidate descriptor - table bindings, so pass code should bind the heap once before draws. - -Current Aquarium D3D12 status: - -- Good: shader-visible descriptors are split into static and per-frame - transient arenas. Transient CBV/UAV descriptors reset only after the owning - frame fence clears, and static descriptors rebuild on resize after a GPU wait. -- Temporary: arenas are still simple bump allocators. Keep them until real - non-resize churn demands free lists, paging, or a persistent global heap. - -## Upload Doctrine - -Transient CPU-to-GPU data belongs in persistent mapped upload memory, typically -suballocated as a ring and reclaimed by fences. Constant buffers require 256-byte -alignment. Reading directly from upload memory is acceptable for small constant -data, but large frequently-read resources should be copied to default heap -memory before shader use. - -Current Aquarium D3D12 status: - -- Good: each frame owns a persistently mapped upload ring, and constant-buffer - writes are 256-byte aligned. -- Temporary: upload policy is still per-frame and constant-only. Structured - scene data should move through typed upload allocations and default-heap - buffers before real pass migration grows data volume. -- Guardrail: keep direct shader reads from upload memory limited to small - constants. Structured/large scene data should move to default memory. - -## Memory Doctrine - -Committed resources are fine while bringing up a backend. They are not a -production memory manager. Microsoft recommends classifying resources and -budgeting/streaming residency; AMD recommends large heaps and suballocation, -with D3D12 Memory Allocator as the practical library path. - -Current Aquarium D3D12 status: - -- Good: committed default resources make ownership explicit during bring-up. -- Temporary: once scene/history/froxel resources grow, add D3D12MA or an - equivalent placed-resource allocator instead of keeping one committed resource - per texture/buffer. - -## Barrier Doctrine - -Barrier correctness is not optional, but barrier volume is a performance risk. -The renderer should track state per resource, use the narrowest valid states, -avoid redundant transitions, and group barriers when pass complexity grows. - -Current Aquarium D3D12 status: - -- Good: the offscreen render target tracks its current state and transitions - only on change. -- Good: swapchain backbuffers are wrapped as tracked resources and transition - explicitly between present and render-target states. -- Watch item: rendering to an offscreen target then copying to the swapchain is - useful for proving texture ownership, but final composition should avoid - unnecessary full-frame copies unless a post-process graph requires them. - -## Command/Fence Doctrine - -Per-frame command allocators must not be reset until the GPU is done with their -recorded work. Frame resources should carry fence values, and transient -descriptor/upload/resource allocations should tie reclamation to those values. - -Current Aquarium D3D12 status: - -- Good: one command allocator per swapchain frame and fence wait before reuse. -- Temporary: the renderer still uses a single graphics command list and a coarse - frame fence. That is fine until multi-threaded recording or async copy/compute - becomes real. - -## Aquarium Next Steps - -1. Add a D3D12 frame graph/resource map for named render targets and buffers. -2. Promote descriptor allocation from smoke-path arenas into renderer-wide - static/transient descriptor policy. -3. Extend the upload ring from constants into typed uploads for structured - buffers and texture staging. -4. Add D3D12MA or a deliberate placed-resource allocator before the resource - count becomes serious. -5. Add debug names and PIX markers while the graph is still small. -6. Track backbuffer resources with the same state wrapper used for offscreen - targets. -7. Port the first real pass only after descriptors, upload, render targets, and - state tracking have durable ownership. diff --git a/research/rendering/cube-sphere-fractal-brushes.md b/research/rendering/cube-sphere-fractal-brushes.md deleted file mode 100644 index ef382a1..0000000 --- a/research/rendering/cube-sphere-fractal-brushes.md +++ /dev/null @@ -1,561 +0,0 @@ -# Cube-Sphere Fractal Brush Research - -Aquarium needs one scalable surface/object grammar, not separate tricks for -planets, Grid brushes, and agent bodies. - -The working target is a cube-sphere domain: six square faces, each subdivided by -quadtree addresses, projected onto a sphere with bounded distortion. Each tile -owns a local 2D chart for terrain and surface detail. The same grammar extends -inward to 3D object detail through bounded implicit brush nodes. - -This is not a license to build a universal registry-shaped fog machine. The -authority should be small: - -- Tile address owns where a surface patch lives. -- Projection owns how a face chart maps to the sphere. -- Brush grammar owns what detail exists at a scale. -- Brush envelope owns where that detail can affect rendering. -- Renderer LOD/sampling owns how much of the grammar is evaluated this frame. - -## Surface Domain - -The established name is the quadrilateralized spherical cube, often shortened to -QSC or quad sphere. It was designed as a discrete global grid for spherical -data, including Earth/sky data, and avoids the polar singularities of lat-long. -PROJ describes QSC as equal-area, treating all cube sides equally, and explicitly -mentions planetary-scale terrain rendering with quadtree data per cube side. - -The older COBE/Chan-O'Neill family is approximately equal-area and historically -important. For engine use, the more relevant graphics framing is cube-to-sphere -projection for procedural texturing: generate a point or tile on a cube face, -warp the face coordinates to reduce area distortion, then normalize/project to -the sphere. - -The cheap mapping ladder: - -1. Identity cube map then normalize: fastest, worst area stretch near cube - corners. -2. Tangent/univariate warp: still simple, analytic inverse, much better area - distribution. -3. Fifth-order odd polynomial warp: fastest high-quality univariate candidate - in the JCGT comparison; good for GPU hot paths, inverse is approximate. -4. COBE-style bivariate polynomial: best area preservation in that comparison, - but more expensive. -5. Exact equal-area constructions: useful reference, not automatically the right - hot shader choice. - -For Aquarium, the first serious candidate should be the fifth-order odd -polynomial warp from the JCGT paper, measured against tangent and COBE on the -actual 1070 target. It is the right shape of compromise: cheap scalar math, -separable face axes, low area error, and no lat-long singularity. If inverse -address lookup dominates, tangent may win despite worse area preservation. If -offline baking or CPU authoring needs maximum area regularity, COBE/QSC can be -used there without forcing it into every pixel path. - -## Multiscale Detail - -Every visible primitive should be able to answer: what detail exists below this -scale? The proposed answer is an iterated function system brush grammar. - -For terrain: - -- Each cube-face quadtree tile has a deterministic grammar seed. -- The grammar emits bounded 2D brushes at octave/LOD levels. -- Coarse levels define form: continents, basins, ridges, crater families, - river-like masks, weathered bands. -- Fine levels define material/texture response first; traced geometry only when - its bound is visible enough to deserve SDF cost. - -For 3D bodies: - -- Each agent/body starts from one coherent base SDF form. -- Its grammar emits bounded 3D brush nodes in that local form domain. -- A brush may carry texture/material response, displacement, negative space, or - form contribution, but it must share an explicit envelope. -- The grammar is LOD-gated and budgeted by proxy bounds. No scene-global - mega-SDF. No evaluating all organs because one pixel got curious. - -IFS here means a deterministic recursive emitter of child transforms and brush -parameters, not necessarily a textbook fractal exposed directly to the user. The -important invariant is that detail exists at every scale because the primitive -can generate it locally, not because a finite table happened to be hand-filled. - -## IFS DSL Shape - -VibeGeometry is the nearest local evidence for the authoring layer Aquarium -needs. It is not about SDFs, but it has spent real work on spatial mapping, -procedural graph translation, CSG claims, and keeping geometry machines -inspectable. - -The lesson is not "copy Blender nodes." The lesson is that a spatial DSL needs -more than primitives and transforms: - -- explicit local frames and frame transitions; -- deterministic seeded variation; -- named fields/attributes that survive domain changes; -- tags explaining why a generated thing exists; -- repeat/foreach-style rule composition; -- authoring handles/gizmos for parameters humans and agents will tune; -- asset/material binding outside the hot geometry grammar; -- debug/evidence outputs for each layer, not only the final pretty object. - -Aquarium's IFS DSL should emit semantic brush claims before it emits shader -work. A claim is a bounded statement in a local domain: - -```text -claim { - name - kind: material | height | displacement | sdf_form | void | mask | light - frame - envelope - payload - tags - lod_range - cost_tier - seed - children -} -``` - -For terrain, the claim domain is a cube-face tile chart plus height/material -space. For bodies, the claim domain is the object-local anatomical/form frame. -For both, rule output stays semantic until a backend lowers it into one of the -live render paths: height brush pass, material field, SDF evaluator, impostor -splat, debug view, or offline bake. - -Do not flatten this into a bag of anonymous brushes too early. VibeGeometry's -`vg_grammar` layer keeps `Solid` and `Void` claims tagged as room, corridor, -door, wall, floor, or ceiling before compiling to CSG. Aquarium needs the same -shape of truth for craters, ridges, rivers, veins, ribs, petals, apertures, -scars, and agent state features. The renderer can be brutal and cheap later; -the authoring layer should still know what each brush means. - -## CSG Tree Lesson - -The really useful VibeGeometry path is the CSG tree attempt. It separates three -authorities: - -- grammar/rules decide which semantic claims should exist; -- the CSG tree decides boolean ownership of space; -- the output mesh or brush stream is a compiled verdict, not the source of - truth. - -`vg_csg` currently has a small `CsgTreeArena` with brush leaves and branch ops: -addition, subtraction, and common/intersection. Branch bounds follow boolean -meaning: addition unions child bounds, subtraction keeps the left/source bound, -and common intersects child bounds. The tree can compile down to the current -ordered brush stream, where the first child of a subtraction remains additive -and later children become subtractive operators. - -That flattening bridge matters. Aquarium can preserve an authored IFS/CSG tree -even if the first GPU path lowers it to fixed-size brush tables or per-object -SDF includes. The tree is the durable design. The shader packet is a backend. - -For Aquarium, the tree should probably not be a full CAD boolean kernel in the -hot path. It should be a semantic spatial program that lowers into cheap -bounded evaluators: - -```text -rule tree --> semantic brush/void/material claims --> boolean/IFS ownership tree --> backend lowering: - - 2D tile material/height brushes - - 3D object-local SDF form brushes - - compact anisotropic splat/impostor batches - - offline baked summaries and mips -``` - -The important tree operations for the first Aquarium DSL: - -- `Union`: multiple claims contribute in the same domain. -- `Subtract`: voids, apertures, channels, scars, doorways, river cuts. -- `Intersect/Common`: masks, biome regions, anatomical zones, tile clipping. -- `Repeat`: emit child rules over a count, curve, grid, face, or stochastic set. -- `Refine`: emit lower-scale children when screen/error budget asks for them. -- `Capture`: name a value, station, mask, or frame for later child rules. -- `Bind`: attach material/asset/state payload outside the form rule. - -The tree must carry bounds at every node. Bounds are not an acceleration garnish; -they are the contract that keeps a grammar from becoming a frame-eating sermon. -Branch bounds also define LOD and invalidation: if a tile/body query does not -touch a subtree's bound, that subtree does not get to spend shader time. - -## VibeGeometry Distillation - -Local source paths worth treating as evidence: - -- `E:\Projects\VibeGeometry\docs\research\procedural-doctrine.md` -- `E:\Projects\VibeGeometry\docs\research\translations\ircss-french-houses-node-atlas.md` -- `E:\Projects\VibeGeometry\docs\research\translations\ircss-french-houses-node-mechanisms.md` -- `E:\Projects\VibeGeometry\docs\research\dream-machine-grammar.md` -- `E:\Projects\VibeGeometry\docs\research\realtime-csg-doctrine.md` -- `E:\Projects\VibeGeometry\crates\vg_grammar\src` -- `E:\Projects\VibeGeometry\crates\vg_csg\src\tree.rs` -- `E:\Projects\VibeGeometry\crates\vg_csg\src\frontier.rs` - -Distilled rules: - -- Build the host form first; ornament grows on captured structure. -- Attributes/fields are not bookkeeping. They are how identity survives - instancing, deletion, scattering, and later detail passes. -- Groups can pass batons: running values such as angle, offset, frame, count, - seed, aperture, or path state should be explicit outputs. -- Scatter has layers: nursery surface, point field, instance body, realization - boundary. Aquarium's brush grammar should mirror this with tile/body domain, - spawn field, brush claim, and backend lowering. -- Paths are topology first. Draw cracks, veins, river paths, routes, or rails - after solving connectivity or stations. -- Boolean thickets often want tables. Repeated near-clone rules should become - one rule plus rows of parameters, not copied child subtrees. -- CSG is an adjudicator, not the authoring language. Domain rules should be - written in terrain, anatomy, tile, curve, or habitat coordinates, then lowered - into boolean/brush evaluation late. -- Demand frontiers beat world rebuilds. The query already says which tile, - proxy, dirty brush, screen cone, or body bound matters; use that before - building generic indexes. - -## Brush Envelope - -The current cheap circular/Gaussian brush idea is too blunt. The next primitive -should look more like a shaped Gaussian splat: an anisotropic bounded kernel -with rotation, scale, falloff, and optional local shape controls. - -Relevant splatting lineage: - -- EWA/surface/volume splatting uses elliptical Gaussian kernels and screen-space - filtering to avoid aliasing and excess blur. -- 3D Gaussian Splatting models scenes with explicit anisotropic 3D Gaussians, - each carrying position, opacity, scale, rotation/covariance, and appearance, - then bins/sorts/rasterizes them efficiently. - -Aquarium should borrow the cheap structural idea, not the whole radiance-field -machine. A brush envelope can be stored as: - -```text -center -orientation basis or compressed rotation -radii / inverse covariance diagonal -falloff exponent or compact support radius -shape parameters for taper, skew, ridge, hollow, or signed lobe response -payload type: material, height/displacement, SDF form, mask, light, debug -``` - -Hot shader evaluation should prefer compact-support anisotropic kernels over -infinite Gaussians: - -```text -q = transpose(rotation) * (p - center) -m = dot(q * invRadii, q * invRadii) -support = saturate(1 - m) -weight = support * support * (3 - 2 * support) -``` - -That is not a true Gaussian. Good. Infinite support is expensive folklore unless -the renderer can cull it. The useful inheritance from Gaussian splatting is -anisotropic covariance-like shape control, tile/proxy binning, and LOD-aware -visibility, not religious devotion to exp(). - -## Sampling Strategy - -SDF performance hinges on conservative bounds and choosing the right evaluator -late. Hart's sphere tracing framing is still the base law: steps are safe when -the distance estimate respects a derivative/Lipschitz bound. Aquarium already -learned the local version of this for thin agent SDF organs. - -Migration target: - -- Keep proxy bounds first. A tile or body proxy decides whether any expensive - grammar can matter. -- March conservative macro distance before micro detail. -- Evaluate grammar detail only after the ray enters a tile/body budget zone. -- Carry LOD tier, cost tier, step count, proxy-hit coverage, and grammar node - count debug views before trusting the system. -- Use cone/pixel-footprint-aware sampling for material/height detail; do not - trace subpixel grammar detail as geometry. -- Use prefiltered/mip summaries per tile and per grammar family where possible. -- Use stochastic/blue-noise selection for dense fine detail when exact full - evaluation would alias or exceed budget. - -The hard rule: form SDF detail must have a conservative envelope and a measured -cost. Texture/detail brushes can be abundant; traced form brushes must earn -their steps. - -## LOD And Contribution Caching - -The LOD problem is not "pick a depth." The real question is: would this -subtree change currently visible pixels enough to justify its cost? - -The model should combine three proven ideas: - -- Geometry clipmaps: keep nested, incrementally updated caches around the - viewer for terrain-like domains, and fade between levels in transition - regions. -- Nanite-style hierarchy cuts: select exactly one useful representation along - each ancestor/descendant chain using projected error. Parent summaries let - traversal stop without asking every leaf for permission. -- Gaussian splat/octree LOD: score an anisotropic primitive by projecting its - covariance/envelope footprint into screen space, then choose coarser or finer - anchors based on pixel impact and budget. - -For Aquarium's IFS brush tree, every node should cache a compact summary: - -```text -nodeId -parentId / firstChild / childCount -domain: cubeFaceTile | bodyLocal | curveLocal | volumeLocal -localFrame -worldOrTileBound -envelopeBound -maxDisplacementOrDistanceError -maxMaterialDelta -normalConeOrGradientBound -opacityOrCoverageBound -frequencyBand / octave -estimatedCost -lastContributionScore -lastVisibleFrame -residentState -summaryPayloadHandle -childPayloadHandle -``` - -The projected contribution score can start simple: - -```text -projectedRadiusPx = project_bound_radius(node.bound, camera) -projectedErrorPx = project_world_error(node.maxError, node.bound, camera) -materialScore = node.maxMaterialDelta * projectedCoveragePx -formScore = projectedErrorPx * visibleCoverageEstimate -score = max(formScore, materialScore) * importanceBias / estimatedCost -``` - -This is only a heuristic, but it protects the right invariant: children fade in -when their worst possible visible contribution rises above a pixel/error -threshold, and fade out when the parent summary is good enough. For anisotropic -brushes, use the projected ellipse/covariance footprint rather than a sphere -whenever that data is already cheap; otherwise fall back to a conservative -sphere/AABB. - -The runtime cut: - -```text -parentGoodEnough = parent.projectedErrorPx <= threshold -nodeNeeded = node.projectedErrorPx > threshold -renderNodeSummary = parentNeeded && !nodeNeeded -descend = nodeNeeded && budgetAllows && childrenResidentOrRequestable -``` - -For smooth transitions, each node gets a fade weight based on hysteresis around -the threshold: - -```text -fade = smoothstep(thresholdLow, thresholdHigh, projectedErrorPx) -``` - -The parent summary fades out as children fade in. Geometry clipmap transition -regions are the terrain precedent; for object/body brushes this becomes -cross-fading material contribution or displacing geometry only after the -micro-form is stable enough not to pop. Never fade signed distance itself in a -way that breaks conservative marching. Fade payload amplitude, material -response, or selected child contribution after the macro hit is established. - -### Dynamic Cache - -The cache should be a demand cache, not a tree-shaped shrine in memory. - -Inputs: - -- camera and previous camera; -- visible cube-face tile windows or body proxy hits; -- node summaries resident on CPU/GPU; -- per-node contribution score from the previous frame; -- request budget for new child payloads; -- eviction budget for stale low-score payloads. -- update budget for how many node weights may be refreshed this frame. - -Per frame: - -1. Traverse only visible roots: active cube faces/tiles and body proxies. -2. Project each node summary and compute contribution score. -3. If the summary is enough, draw/evaluate it and stop. -4. If children are needed and resident, descend. -5. If children are needed and missing, render the parent summary, enqueue child - payloads, and keep a fade-in reservation. -6. Update a small score cache with temporal smoothing: - -```text -score = lerp(oldScore, currentScore, currentVisible ? 0.35 : 0.08) -``` - -7. Evict children whose smoothed score stays below threshold for enough frames, - starting with high-cost low-score nodes. - -### Probabilistic Weight Updates - -The contribution cache cannot refresh every branch every frame. A large IFS tree -will always have more latent branches than budget. The cache therefore needs an -online estimator: every frame it samples a subset of nodes, updates their -weights, and lets the whole system converge over time. - -The first version can be a stochastic scheduler, not a neural net: - -```text -priority = - visibilityProbability - * staleWeight - * uncertainty - * max(previousScore, parentScoreBias) - / max(estimatedUpdateCost, epsilon) -``` - -Nodes enter the update lottery from visible roots, near-threshold cut nodes, -recently visible descendants, and a small exploration set. The scheduler spends -the frame's update budget on weighted random samples, not only on the current -top scores. Greedy-only updates are how stale branches stay confidently wrong. - -Each node should carry estimator state: - -```text -meanContribution -varianceOrUncertainty -sampleCount -lastSampleFrame -lastVisibleFrame -decayRate -confidence -``` - -On update: - -```text -delta = observedContribution - meanContribution -meanContribution += alpha * delta -variance = lerp(variance, delta * delta, beta) -confidence = saturate(confidence + confidenceGain) -``` - -On non-update: - -```text -confidence *= decay -uncertainty += staleGrowth -``` - -This is machine-learning territory in the plain sense: an online model predicts -which branches matter, samples under budget, updates from observations, and -should converge toward stable weights for stable views. Start with exponential -moving averages, variance, and bandit-style exploration. Do not jump straight to -a bespoke neural predictor unless the simpler estimator cannot hit fidelity or -budget. - -The convergence contract: - -- Every resident visible or near-threshold node must have nonzero probability of - being resampled. -- High-uncertainty nodes get exploration budget even when their old score is - low. -- Scores decay when nodes go unseen, but summaries remain available. -- Parent and child scores must be monotonic enough for stable cuts: a parent - summary cannot claim less possible contribution than all of the children it - hides. -- Debug views must expose mean, variance/uncertainty, sample age, confidence, - and update probability. - -The higher-fidelity path is learned scoring: - -```text -features: - projected bound, projected anisotropic footprint, depth, view angle, - normal/gradient cone, material delta, motion, parent score, tile/body state, - historical score/variance, previous visibility, estimated cost - -prediction: - expectedContribution - uncertainty - updatePriority -``` - -Training signal can come from occasional high-quality probes: render/evaluate a -more detailed subtree, compare against the parent summary, and record the -observed pixel/material/SDF delta. That makes the cache a budgeted fidelity -estimator rather than a pile of thresholds pretending to be wise. - -Cut line: the runtime still needs deterministic safety. A learned predictor may -rank update and residency priority; it must not be the only guard for SDF -marching bounds or object/tile visibility. Conservative summaries remain law. - -The contribution cache should be keyed by stable domain address, not by transient -allocation: - -```text -cube face + quadtree path + grammar rule path -body id + local grammar rule path -``` - -For a GTX 1070-class target, keep the first implementation embarrassingly -simple: - -- CPU scores coarse roots and streaming decisions. -- GPU evaluates fixed-size resident node tables per visible tile/body. -- Node summaries are small structured-buffer rows. -- A stochastic CPU/GPU scheduler refreshes only a bounded subset of node weights - each frame, using uncertainty and stale age so weights converge instead of - freezing. -- Child payload pages are append-only within a frame and compacted only at safe - sync points. -- Debug views show projected error, contribution score, uncertainty, sample age, - confidence, update probability, selected depth, cache residency, fade weight, - and estimated cost. - -The cache must preserve summaries even when child payloads are evicted. A parent -summary is the fallback representation and the promise that the tree can always -render something coherent. If a subtree cannot summarize its children with a -bounded error/material delta, it is not ready to be an LOD subtree. - -## Migration Shape - -1. Add the cube-sphere domain math as generic renderer math, not Zyphos policy. -2. Convert Zyphos planet surface addressing from lat-long/spherical noise toward - six face quadtrees. -3. Replace height brushes with shaped anisotropic envelopes while preserving the - existing scalar height target until a better pass contract exists. -4. Define a minimal semantic brush-claim format: name, kind, frame, envelope, - payload, tags, LOD range, cost tier, seed, and children. -5. Preserve an authored IFS/CSG ownership tree even when the first backend - lowers it into flattened brush tables or SDF shader code. -6. Make one terrain grammar and one agent/body grammar share the same envelope - evaluator. -7. Add node summaries and contribution-score caching before allowing recursive - detail to expand at runtime. -8. Add debug visualizations before expanding detail density. - -If the first implementation needs a cut, cut 3D recursive form detail first. -Keep the cube-sphere address space and shaped 2D brush envelope. Those are the -foundation stones. - -## Sources - -- PROJ QSC documentation: https://proj.org/en/stable/operations/projections/qsc.html -- NASA NTRS, "A quadrilateralized spherical cube Earth data base": https://ntrs.nasa.gov/citations/19810002572 -- Clarberg, "Cube-to-sphere Projections for Procedural Texturing and Beyond," - JCGT 2018: https://jcgt.org/published/0007/02/01/paper.pdf -- Kerbl et al., "3D Gaussian Splatting for Real-Time Radiance Field Rendering," - SIGGRAPH/TOG 2023: https://arxiv.org/abs/2308.04079 -- Hart, "Sphere tracing: A geometric method for the antialiased ray tracing of - implicit surfaces," The Visual Computer 1996: - https://experts.illinois.edu/en/publications/sphere-tracing-a-geometric-method-for-the-antialiased-ray-tracing/ -- Zwicker et al., EWA surface/volume splatting lineage: - https://vcg.seas.harvard.edu/publications/20011001-ewa-volume-splatting -- Local VibeGeometry procedural and CSG research: - `E:\Projects\VibeGeometry\docs\research\procedural-doctrine.md`, - `E:\Projects\VibeGeometry\docs\research\dream-machine-grammar.md`, - `E:\Projects\VibeGeometry\docs\research\realtime-csg-doctrine.md`, - `E:\Projects\VibeGeometry\crates\vg_grammar`, and - `E:\Projects\VibeGeometry\crates\vg_csg` -- Losasso and Hoppe / Asirvatham and Hoppe geometry clipmaps: - https://hhoppe.com/proj/gpugcm/ -- Karis et al., Nanite virtualized geometry: - https://advances.realtimerendering.com/s2021/Karis_Nanite_SIGGRAPH_Advances_2021_final.pdf -- Ren et al., Octree-GS LOD-structured Gaussian splatting: - https://arxiv.org/abs/2403.17898 diff --git a/research/rendering/fensalir-spine-emblem-ifs-demo.md b/research/rendering/fensalir-spine-emblem-ifs-demo.md deleted file mode 100644 index a936ad5..0000000 --- a/research/rendering/fensalir-spine-emblem-ifs-demo.md +++ /dev/null @@ -1,72 +0,0 @@ -# Fensalir Spine Emblem IFS Demo Reference - -## Purpose - -This note preserves the visual target for a possible Fensalir IFS demo scene. -The current fullscreen splash art is strong enough to become a procedural scene -rather than only a bitmap. - -## Source Asset - -- Splash bitmap: `src/Aquarium.Engine/Assets/Fensalir-Splash.png` -- Startup BMP copy: `src/Aquarium.Engine/Assets/Fensalir-Splash.bmp` -- Icon derivative: `src/Aquarium.Engine/Assets/Fensalir-Icon-96.png` - -## Prompt Of Record - -Use case: stylized-concept - -Asset type: 16:9 engine splash art concept - -Primary request: A bold, logo-adjacent Fensalir engine splash direction that -could sit behind a startup screen, combining Norse fen hall mythology with a -neon rendering engine identity. - -Scene/backdrop: minimal dark void fading into shallow marsh water, abstract hall -silhouette made from vertical luminous runic pillars and clean renderer-like -geometry, reeds only at the extreme edges. - -Subject: a central vertical spine of light formed by stacked translucent -polygons, runic strokes, and watery reflections, suggesting the engine as the -structural backbone of visible worlds. - -Style/medium: sleek futuristic key visual, premium software splash art, less -literal, high contrast, graphic and memorable. - -Composition/framing: centered emblem-like composition, strong silhouette, wide -negative space, symmetrical but not flat, the spine rising from reflective water -into mist. - -Lighting/mood: intense cyan-white central light, restrained magenta edge glow, -tiny gold sparks, calm authority. - -Color palette: black, cyan-white, magenta, muted gold, dark green-black. - -Materials/textures: glass, black metal, wet stone, reflective water, -laser-etched rune light, subtle fog. - -Constraints: no readable text, no logo, no watermark, no characters, no -weapons, no horned helmets, avoid looking like a crypto logo or generic esports -background. - -## Implementation Invariants - -- The central cyan-white vertical spine owns the scene. Everything else supports - it. -- The geometry should read as stacked translucent diamond/polygon forms, not a - literal tower or generic sci-fi logo. -- Magenta belongs in restrained side glow and reflected water, not as the main - light authority. -- The base is black reflective marsh water with minimal reeds at the edges. -- The hall/rune language should be abstract and structural. No readable runic - text. -- The scene must remain legible at splash scale and should degrade cleanly into - the 96 px icon silhouette. - -## IFS Demo Cut Line - -Keep the demo procedural if the IFS/fractal machinery can own the central spine, -pillar rhythm, and reflections directly. If the implementation needs a bag of -hand-placed quads plus post-process glow to resemble the splash, call it a -staged splash scene, not an IFS demo. The demo should prove an invariant of the -IFS work, not merely cosplay it with decoration. diff --git a/research/rendering/fractal-brush-architecture-plan.md b/research/rendering/fractal-brush-architecture-plan.md deleted file mode 100644 index 3296476..0000000 --- a/research/rendering/fractal-brush-architecture-plan.md +++ /dev/null @@ -1,948 +0,0 @@ -# Fractal Brush Architecture Plan - -Aquarium needs one multiscale spatial machine for planets, Grid surfaces, and -agent bodies. The target is not "infinite detail" as a slogan. The target is a -bounded semantic tree that can always answer four questions: - -- What does this detail mean? -- What pixels could it affect? -- Is it worth its CPU, RAM, SSD, and GPU cost this frame? -- Which module owns the answer, and how do tests prove that boundary? - -The architecture below is the coherent machine that falls out of the research -pass. - -## Core Model - -```text -client intent / world seed / agent visual state --> domain roots --> semantic IFS brush grammar --> ownership tree --> node summaries --> contribution cache and residency scheduler --> backend packets --> renderer passes --> debug and evidence -``` - -The authored tree is the source of truth. Backend packets are compiled output. -That distinction is the spine. If the grammar is flattened too early into -anonymous shader tables, we lose meaning, invalidation, LOD, test boundaries, -and future editing handles in one cheap little bonfire. - -## Module Network - -The architecture should be split into modules with narrow contracts and boring -mock seams. The goal is not maximum abstraction. The goal is that every module -owns one invariant that can be tested without booting the whole renderer. - -```text -Aquarium.Engine.Contracts - Fractal domain, claim, tree, summary, packet, and debug data contracts. - -Aquarium.Engine.Fractal - Pure CPU domain math, grammar expansion, ownership tree, summaries, scoring, - stochastic estimator, residency decisions, and backend packet planning. - -Aquarium.Engine.Render - D3D12 resource residency, structured buffers, shader bindings, render graph - passes, and debug visualization. - -Aquarium.Zyphos - Planet-specific domain roots, world seeds, terrain grammar choices, and - setting-safe visual policy. - -Aquarium.Epiphany - Agent/body visual state, role grammar choices, and semantic state bindings. - -Tests - Contract tests, pure CPU unit tests, renderer packet golden tests, shader - parity tests, and smoke/integration tests. -``` - -### Module Boundaries - -| Module | Owns | Does Not Own | Mock Boundary | -| --- | --- | --- | --- | -| Contracts | Stable data shapes and versionable packets | Projection algorithms or D3D12 objects | Plain DTO fixtures | -| Fractal Domain | Cube-face addresses, projections, local frames | Client lore or GPU resources | `IProjection`, camera fixture | -| Grammar | Semantic claims and rule expansion | Rendering or residency | seeded rule fixtures | -| Ownership Tree | Boolean/IFS topology, bounds, stable keys | Shader packet layout | tree builder fixtures | -| Summary Builder | Conservative error/material summaries | Per-frame scheduling | child-node fixtures | -| Contribution Cache | score state, stochastic updates, convergence | payload loading or drawing | deterministic RNG, fake frame clock | -| Residency Scheduler | request/evict decisions under budgets | SSD implementation or descriptors | fake payload store | -| Backend Planner | selected cut to backend packets | D3D12 upload | packet golden files | -| D3D12 Backend | buffers, descriptors, shader passes | semantic grammar | packet fixtures and GPU smoke | -| Client Adapters | Zyphos/Epiphany policy | generic renderer math | fake engine contracts | - -The hard rule: a module must be defended by the invariant it owns, not by how -cleverly it forwards data. - -## Testing Strategy - -This system only deserves to exist if it is testable at its natural seams. - -### Pure Unit Tests - -These run without D3D12: - -- cube-face address round trips; -- projection candidate continuity and area-error sampling; -- local frame point/vector transforms; -- envelope CPU evaluator parity against known samples; -- grammar expansion from seed to deterministic claims; -- ownership tree bounds for union/subtract/common/repeat; -- summary conservativeness against generated children; -- projected score monotonicity with distance and error; -- stochastic estimator convergence with deterministic RNG; -- residency eviction/request decisions under fixed budgets. - -### Contract Tests - -These protect module boundaries: - -- serialized contract rows round-trip without renderer types; -- stable keys remain stable across reload and equivalent grammar expansion; -- backend packet planner emits the same packet for the same selected cut; -- clients can declare domains and grammars without referencing D3D12. - -### Mock Boundaries - -Required mocks/fakes: - -- `IFractalClock`: deterministic frame number and time. -- `IFractalRandom`: seeded random/update lottery. -- `IProjection`: projection candidate swap for tests. -- `IContributionProbe`: fake observed pixel/material/SDF delta. -- `IFractalPayloadStore`: fake RAM/SSD payload availability. -- `IFractalGpuBudget`: fake GPU table/page budget. -- `IFractalDebugSink`: captures telemetry without UI. - -Mocks should sit at resource and observation boundaries, not inside algorithms. -Mocking every helper is how tests become a puppet show for implementation -details. Good tests feed the module its owned inputs and inspect its owned -outputs. - -### Shader Parity Tests - -For GPU math that must match CPU decisions: - -- shaped envelope weight; -- cube-face projection used by shader sampling; -- packet decoding; -- selected-cut fade weights; -- conservative SDF bound constants. - -The CPU implementation is the spec. The HLSL implementation is the fast copy. -When they disagree, the test should fail before the disagreement becomes a -screenshot mystery. - -### Integration Tests - -Small but real: - -- build one cube-face terrain grammar into current height brush backend; -- render/debug one Zyphos planet frame headless; -- render one body proxy with selected-cut packet fixtures; -- verify debug modes expose score, uncertainty, selected depth, residency, and - cost. - -### Performance Fixtures - -Performance tests must be deterministic: - -- fixed camera paths; -- fixed world seed; -- fixed update budget; -- fixed payload budget; -- fixed RNG seed; -- output: CPU ms, GPU ms if available, resident payload count, update count, - evictions, selected node count, score convergence. - -Passing visual tests without performance fixtures is permission to grow a slow -machine with a nice face. No. - -## Ownership - -### Client - -The client owns semantic intent: - -- planet/world seed and setting policy; -- agent visual state and role/body grammar selection; -- authored grammar parameters and state bindings; -- stable domain ids for persistence and cache keys. - -For Zyphos, this means planet style, biome rules, and simulation-facing terrain -policy. For Epiphany, this means role/body visual state and semantic feature -bindings. The engine should not learn client nouns just because the first -grammar is interesting. - -### Engine Contracts - -Contracts own portable declarations: - -- domain roots; -- semantic brush claims; -- grammar tree nodes; -- node summary schema; -- backend packet schema; -- debug channel names. - -Contracts must stay Vortice-free and renderer-agnostic. They describe the -machine; D3D12 is one lowering target. - -### Engine Fractal Core - -The fractal core owns pure CPU algorithms: - -- cube-sphere domain math; -- grammar expansion; -- ownership tree bounds; -- summary generation; -- contribution scoring; -- stochastic estimator updates; -- selected-cut and residency decisions; -- backend packet planning. - -This should be the main testable body of the system. - -### Engine Renderer - -The renderer owns: - -- GPU buffers, textures, pages, and descriptors; -- screen-space scoring when moved to compute; -- backend packet upload; -- render graph execution; -- shader evaluation; -- visual diagnostics. - -## Algorithms - -### 1. Cube-Sphere Surface Domain - -Planetary surfaces use six quadtree cube faces projected to a sphere. This cuts -lat-long pole singularities and gives each face a simple 2D tile domain. - -Projection candidates: - -- tangent warp: cheap, analytic inverse, acceptable area behavior; -- fifth-order odd polynomial warp: strong GPU candidate, low area error; -- COBE/QSC-style bivariate warp: best area behavior, more expensive; -- exact equal-area reference: validation and offline bake target, not default - hot path. - -Tradeoff: - -- Time: tangent/polynomial are cheapest per sample; COBE buys area quality. -- Memory: all use the same tile address space; no major residency difference. -- CPU/GPU: CPU can use exact or COBE for authoring/bakes; GPU hot shaders can - use tangent or polynomial if measured faster. - -Decision rule: measure area error, inverse lookup cost, and shader time on the -actual target hardware before choosing. - -### 2. Semantic IFS Brush Grammar - -The grammar emits claims, not final triangles or shader code. - -```text -claim { - stableKey - name - kind - domain - localFrame - envelope - payload - tags - lodRange - costTier - seed - children -} -``` - -Kinds: - -- `material` -- `height` -- `displacement` -- `sdf_form` -- `void` -- `mask` -- `light` -- `debug` - -Required grammar operations: - -- `Union` -- `Subtract` -- `Common` -- `Repeat` -- `Refine` -- `Capture` -- `Bind` - -VibeGeometry's useful lesson is the split between semantic claims and CSG -adjudication. Aquarium should keep that split even when the current renderer -only supports a flattened evaluator. The authored tree remains durable; the -flattened packets are expendable. - -Tradeoff: - -- Time: semantic grammar costs CPU work up front but lets runtime avoid global - interpretation in hot shaders. -- Memory: preserving tags, frames, and captures costs RAM, but buys cache keys, - debugging, and selective invalidation. -- SSD: authored grammar is compact; generated payloads and summaries can be - cached separately. -- GPU: shaders consume fixed compact packets instead of walking prose-shaped - abstractions. - -### 3. Ownership Tree - -The ownership tree is a lightweight CSG/IFS program: - -```text -Rule tree --> semantic claims --> boolean/IFS ownership tree --> node summaries --> backend lowering -``` - -It is not a full CAD kernel in the first version. It needs: - -- stable node ids; -- parent/child topology; -- branch operation; -- child ranges; -- node bounds; -- summary error; -- payload handles; -- debug labels. - -Bounds follow operation semantics: - -- union bounds are child-bound unions; -- subtraction bounds are source/left bounds; -- common/intersection bounds are child-bound intersections; -- repeat/refine bounds are generated or conservative aggregate bounds. - -Tradeoff: - -- Time: tree bounds stop traversal before child work. -- Memory: summaries are kept resident even when children are evicted. -- SSD: child payloads can stream by stable key. -- GPU: renderer receives selected cuts and compact resident node tables. - -### 4. Shaped Brush Envelope - -Every brush has a compact-support anisotropic envelope. It borrows the useful -part of Gaussian splatting: covariance-like shape and projected footprint. It -does not inherit infinite support as a default tax. - -Hot evaluator: - -```text -q = transpose(rotation) * (p - center) -m = dot(q * invRadii, q * invRadii) -support = saturate(1 - m) -weight = support * support * (3 - 2 * support) -``` - -Shape controls can add taper, skew, ridge, hollow, signed lobe, or curve-local -response, but every control must preserve an explicit conservative bound. - -Tradeoff: - -- Time: compact support enables culling and fixed packet limits. -- Memory: envelope rows are small and SIMD/GPU friendly. -- GPU: projected ellipse scoring is better than sphere scoring when affordable; - sphere/AABB fallback remains legal. -- Fidelity: anisotropy gives terrain ridges, rivers, petals, scars, and veins - fewer fake circular footprints. - -### 5. Node Summaries - -Every tree node needs a renderable summary: - -```text -stableKey -parent -childRange -domain -localFrame -worldOrTileBound -envelopeBound -maxFormError -maxMaterialDelta -normalOrGradientBound -coverageBound -frequencyBand -estimatedCost -summaryPayloadHandle -childPayloadHandle -``` - -The summary is both fallback and promise. If a node cannot summarize its -children with bounded error, it is not ready to be an LOD node. - -Tradeoff: - -- Time: summaries stop traversal and keep missing children renderable. -- Memory: summaries stay hot; child payloads can be evicted. -- SSD: summaries form the streaming index. -- GPU: fixed summary buffers feed scoring and debug views. - -### 6. Contribution Scoring - -The first score is heuristic and conservative: - -```text -projectedRadiusPx = project_bound_radius(node.bound, camera) -projectedErrorPx = project_world_error(node.maxFormError, node.bound, camera) -materialScore = node.maxMaterialDelta * projectedCoveragePx -formScore = projectedErrorPx * visibleCoverageEstimate -score = max(formScore, materialScore) * importanceBias / estimatedCost -``` - -LOD cut: - -```text -render summary if parent needed and node is good enough -descend if node is not good enough, children are resident, and budget allows -request children if node is not good enough and children are missing -``` - -Fade: - -- use hysteresis around the threshold; -- fade payload amplitude, material response, or selected child contribution; -- do not fade signed-distance safety. - -Tradeoff: - -- Time: cuts avoid leaf scoring. -- Memory: only selected subtrees need payload residency. -- GPU: scoring can move progressively from CPU to compute. -- Fidelity: error thresholds target visible pixel impact, not arbitrary depth. - -### 7. Probabilistic Online Estimator - -The contribution cache cannot refresh every branch every frame. It must update -weights probabilistically under budget and converge. - -Estimator state: - -```text -meanContribution -varianceOrUncertainty -sampleCount -lastSampleFrame -lastVisibleFrame -confidence -decayRate -updateProbability -``` - -Sampling priority: - -```text -priority = - visibilityProbability - * staleWeight - * uncertainty - * max(previousScore, parentScoreBias) - / max(estimatedUpdateCost, epsilon) -``` - -Update: - -```text -delta = observedContribution - meanContribution -meanContribution += alpha * delta -variance = lerp(variance, delta * delta, beta) -confidence = saturate(confidence + confidenceGain) -``` - -Non-update: - -```text -confidence *= decay -uncertainty += staleGrowth -``` - -This is machine learning in the practical online-estimation sense. The first -version should be an exponential moving average plus variance and bandit-style -exploration. A later learned predictor may rank update priority and residency, -but it must not own conservative SDF bounds, object visibility, or safety. - -Tradeoff: - -- CPU: stochastic scheduling keeps per-frame management bounded. -- RAM: estimator state is a few scalars per summary. -- SSD: probes and observed deltas can become offline training/evidence data. -- GPU: high-quality probes can be sparse and amortized. -- Fidelity: exploration prevents stale branches from staying confidently wrong. - -### 8. Residency And Streaming - -Stable key: - -```text -planet: cubeFace + quadtreePath + grammarPath -body: bodyId + grammarPath -curve: ownerId + curvePath + grammarPath -``` - -Memory tiers: - -- CPU hot: visible roots, node summaries, estimator state, selected cuts. -- CPU warm/RAM: nearby summaries and recently used child payload metadata. -- SSD: serialized child payload pages, baked summaries, probe history. -- GPU hot: selected cut buffers, resident payload pages, tile/body packet tables. - -Residency rules: - -- summaries outlive child payloads; -- parent summary renders while child payload streams; -- evict low-score high-cost children first; -- keep near-threshold children longer to avoid popping; -- write payload pages append-only within a frame; -- compact only at safe sync points. - -Tradeoff: - -- Time: avoid global rebuilds and expensive compaction mid-frame. -- Memory: child payloads are elastic; summaries are stable. -- SSD: streaming is by stable semantic key, not transient allocation. -- GPU: residency buffers stay compact and bounded. - -### 9. Backend Lowering - -One authored tree can lower into several backend shapes: - -- 2D tile height/material brushes; -- scalar height-field brush pass; -- object-local SDF form packets; -- anisotropic impostor/splat batches; -- offline mip summaries; -- debug overlays. - -The first backend should be deliberately modest: - -- shaped 2D terrain brushes on cube-face tiles; -- CPU-side node summary and contribution cache; -- fixed GPU structured buffers; -- one Zyphos planet demo path; -- one Epiphany/body proof path later. - -Tradeoff: - -- Time: start with the cheapest visible proof. -- Memory: defer 3D recursive form until 2D summaries and scoring are real. -- GPU: fixed tables are ugly but honest; graph-driven dynamic evaluation comes - after debug views prove the cut. - -## Resource Strategy - -### CPU - -CPU owns grammar expansion, coarse scoring, stochastic update scheduling, -streaming requests, eviction, selected cuts, and debug collection. CPU must -avoid per-leaf full traversal, synchronous SSD waits, and rebuilding payload -pages during rendering. - -### RAM - -RAM owns node summaries, estimator state, warm payload metadata, recent probe -results, and selected cuts. RAM should not keep all recursive child payloads -resident. - -### SSD - -SSD owns serialized payload pages, offline baked summaries, probe/evidence -datasets, and optional learned-predictor training data. SSD is never on the -critical path for a missing child this frame; the parent summary renders. - -### GPU - -GPU owns selected-cut evaluation, brush envelope evaluation, height/material -passes, SDF proxy evaluation, optional compute scoring, and debug visualization. -GPU must not walk the whole grammar tree or trust learned scores for -conservative distance safety. - -## Data Structures - -### `AquariumFractalDomain` - -```text -domainId -kind -rootKey -rootFrame -projection -bound -clientOwner -``` - -### `AquariumBrushClaim` - -```text -stableKey -kind -domainId -localFrame -envelope -payload -tags -lodRange -costTier -seed -``` - -### `AquariumFractalNode` - -```text -stableKey -operation -claimRange -childRange -summary -debugName -``` - -### `AquariumFractalSummary` - -```text -bound -maxFormError -maxMaterialDelta -normalOrGradientBound -coverageBound -estimatedCost -summaryPayload -childPayload -``` - -### `AquariumContributionState` - -```text -mean -variance -confidence -sampleCount -lastSampleFrame -lastVisibleFrame -updateProbability -residentState -fade -``` - -### `AquariumSelectedCut` - -```text -domainId -nodeKey -lodDepth -fade -payloadHandle -debugScore -``` - -## Render Frame Flow - -```text -1. Collect visible domains from camera, cube faces, and SDF proxy bounds. -2. Load resident summaries for visible roots. -3. Score summaries against the camera and previous history. -4. Select a hierarchy cut under CPU/GPU budget. -5. Queue missing child payloads; render parent summaries meanwhile. -6. Sample a probabilistic subset of node weights for estimator convergence. -7. Upload selected cut and resident payload tables. -8. Run tile/body backend passes. -9. Resolve fade transitions and temporal history. -10. Emit debug surfaces and cache telemetry. -``` - -## Debug Views - -No recursive detail without these: - -- cube face / tile id; -- selected LOD depth; -- projected error; -- mean contribution; -- uncertainty; -- sample age; -- update probability; -- residency state; -- fade weight; -- estimated cost; -- selected backend; -- SDF step count where form detail is active. - -## Implementation Roadmap - -### Phase 0: Architecture Freeze - -Deliverables: - -- this plan; -- updated research note; -- state memory/map entries. - -Exit criteria: - -- the live architecture can be explained without hidden compensators; -- module boundaries and test seams are named; -- roadmap names what gets cut if complexity rises. - -### Phase 1: Cube-Sphere Projection Harness - -Build: - -- generic cube-face address type; -- forward/inverse projection candidates; -- area distortion test harness; -- GPU shader microbench for candidate mappings; -- Zyphos debug view for face/tile coordinates. - -Tests: - -- projection round trips; -- face-edge continuity cases; -- sampled area distortion baselines; -- shader/CPU projection parity. - -Cut line: - -- if projection research blocks rendering, ship tangent first behind an - interface and keep the measured comparison harness. - -### Phase 2: Shaped Brush Envelope - -Build: - -- shared CPU/GPU envelope struct; -- compact-support anisotropic evaluator in HLSL; -- CPU mirror evaluator for tests; -- replacement path for current circular height brushes; -- debug view for brush bounds and weight. - -Tests: - -- CPU/GPU evaluator parity; -- support bound rejection; -- deterministic packet serialization; -- side-by-side old/new brush fixture. - -Cut line: - -- start with rotation plus radii and falloff only. Taper/skew/ridge wait. - -### Phase 3: Semantic Claims And Ownership Tree - -Build: - -- contract structs for domains, claims, nodes, summaries; -- small in-memory grammar builder; -- union/subtract/common/repeat/refine/capture/bind operations; -- flattening compiler to current brush tables; -- debug dump of authored tree and flattened backend packets. - -Tests: - -- seeded grammar determinism; -- stable keys across reload; -- operation bounds for union/subtract/common; -- flattening golden packets; -- client adapter does not reference renderer types. - -Cut line: - -- do not implement full CAD CSG. Keep boolean ownership semantic and bounded. - -### Phase 4: Node Summaries - -Build: - -- summary generation for 2D terrain brush trees; -- max error/material delta fields; -- parent fallback payload; -- serialization format for summaries; -- debug view for summary bounds and error. - -Tests: - -- summary conservativeness against generated children; -- parent fallback when children are missing; -- summary serialization round trips; -- evicted children do not remove fallback. - -Cut line: - -- if exact summary generation is hard, use conservative amplitude/frequency - bounds first. Ugly but safe beats precise lies. - -### Phase 5: Contribution Cache - -Build: - -- stable-keyed contribution table; -- projected error scorer; -- selected-cut builder; -- hysteresis fade weights; -- debug views for score, depth, fade, cost. - -Tests: - -- distance monotonicity; -- stable cut under small camera motion; -- budget clamp behavior; -- fade never changes conservative SDF bounds. - -Cut line: - -- keep scoring on CPU until the data layout is stable. - -### Phase 6: Probabilistic Online Updates - -Build: - -- estimator state per node; -- stochastic update scheduler; -- exploration budget; -- confidence decay; -- high-quality probe hook; -- telemetry for convergence. - -Tests: - -- deterministic RNG schedule fixture; -- visible and near-threshold nodes have nonzero update probability; -- stale wrong score recovery; -- convergence under fixed camera path; -- update cost respects budget. - -Cut line: - -- no neural predictor until EMA/variance/bandit scheduling fails with evidence. - -### Phase 7: Residency And Streaming - -Build: - -- CPU warm cache; -- GPU payload pages; -- SSD-backed payload serialization; -- child request queue; -- eviction policy; -- safe compaction points. - -Tests: - -- fake payload store miss renders parent summary; -- request queue ordering; -- eviction by score/cost; -- frame path never blocks on fake SSD. - -Cut line: - -- first version can keep payloads generated in RAM and simulate SSD requests. - The API must still be page/key based. - -### Phase 8: Zyphos Planet Integration - -Build: - -- cube-sphere terrain domain in Zyphos; -- first terrain grammar: continents/ridges/craters/material bands; -- selected-cut-driven tile payloads; -- atmospheric/planet shader sampling from tile domain. - -Tests: - -- planet renders across face edges; -- debug views identify face/tile/LOD/cache state; -- old spherical-noise path remains only as baseline fixture or is removed. - -Cut line: - -- if 3D body grammar tempts us here, cut it. Planet terrain proves the address, - envelope, summary, and LOD cache first. - -### Phase 9: Agent Body Grammar Pilot - -Build: - -- one role body grammar using semantic claims; -- object-local summary tree; -- material/detail brush payloads before traced form recursion; -- SDF proxy integration through selected cut. - -Tests: - -- silhouette coherent across LODs; -- fine detail fades by contribution; -- SDF step count stays inside budget; -- no scene-global mega-SDF. - -Cut line: - -- if form recursion is unstable, keep recursive detail in material payloads and - leave traced form as coarse base SDF. - -### Phase 10: Learned Scoring Research Gate - -Build only after telemetry exists: - -- probe dataset writer; -- offline analysis of predicted vs observed contribution; -- small learned predictor or calibrated regression; -- A/B mode against heuristic scheduler. - -Tests: - -- held-out camera paths; -- learned mode beats heuristic fidelity/cost clearly; -- conservative summaries still own safety; -- fallback heuristic remains available. - -Cut line: - -- if learned scoring cannot beat the estimator clearly, delete it. - -## Current First Slice - -The first implementation slice should be: - -```text -cube-face address + projection harness --> shaped 2D brush envelope --> semantic claim/tree structs --> flatten to current height brush pass --> debug face/tile/brush/score overlays -``` - -This gives a coherent foundation without forcing the whole fractal object system -to exist at once. The machine earns recursion only after address, envelope, -summary, tests, and debug surfaces are real. - -## Sources - -This plan consolidates: - -- `research/rendering/cube-sphere-fractal-brushes.md` -- local VibeGeometry `vg_grammar` and `vg_csg` tree work; -- QSC / cube-sphere projection research; -- EWA and 3D Gaussian splatting envelope ideas; -- Hart sphere tracing; -- geometry clipmaps; -- Nanite-style projected-error hierarchy cuts; -- Octree-GS / LOD-structured Gaussian splatting; -- Aquarium's existing SDF proxy, height brush, and debug-pass constraints. diff --git a/research/rendering/fractal-brush-implementation-roadmap.md b/research/rendering/fractal-brush-implementation-roadmap.md deleted file mode 100644 index db90f00..0000000 --- a/research/rendering/fractal-brush-implementation-roadmap.md +++ /dev/null @@ -1,597 +0,0 @@ -# Fractal Brush Implementation Roadmap - -This is the execution map for the fractal brush architecture in -`research/rendering/fractal-brush-architecture-plan.md`. - -The architecture is allowed to be ambitious. This roadmap is not. It exists to -keep the work shippable, testable, and cuttable. - -## Objective - -Build a reusable mapped fractal field system for planetary terrain, tileable -surface detail, and later agent/body detail. - -The first live proof is deliberately narrow: - -```text -cube-face address + projection harness --> shaped 2D brush envelope --> semantic claim/tree structs --> flatten to current height brush pass --> debug face/tile/brush/score overlays -``` - -No 3D recursive body form. No learned predictor. No streaming page store. The -first pass proves address, envelope, semantic tree, flattening, tests, and -debug visibility. - -## Standing Invariants - -- The authored semantic tree is the source of truth. -- Backend packets are compiled output and may be replaced. -- Every domain, node, claim, and payload has a stable key. -- Every LOD subtree has a conservative parent summary. -- The cache may learn priority; it may not own field safety. -- Missing children render through parent summaries instead of stalling. -- Debug views are required before recursive detail density increases. -- Each module owns one invariant and exposes a mockable seam. - -## Module Targets - -### `Aquarium.Engine.Contracts` - -Owns portable DTOs: - -- `AquariumFractalDomain` -- `AquariumBrushClaim` -- `AquariumFractalNode` -- `AquariumFractalSummary` -- `AquariumContributionState` -- `AquariumSelectedCut` -- backend packet rows -- debug channel rows - -Tests: - -- serialization round trips; -- stable key equality; -- no renderer/Vortice dependency. - -### `Aquarium.Engine.Fractal` - -Owns pure CPU algorithms: - -- cube-face addressing; -- projection candidates; -- local frame/domain math; -- grammar expansion; -- ownership tree bounds; -- summary building; -- contribution scoring; -- stochastic estimator; -- selected-cut planning; -- residency decisions. - -Tests: - -- regular unit tests with deterministic fakes; -- no D3D12 boot required. - -### `Aquarium.Engine.Render` - -Owns D3D12 lowering: - -- GPU buffers; -- descriptor binding; -- shader packet decode; -- height/material/Form/Appearance/Transport backend passes; -- debug visualizations. - -Tests: - -- packet golden tests; -- CPU/HLSL parity tests; -- headless smoke renders. - -### Client Adapters - -`Aquarium.Zyphos` owns planet domain roots and terrain grammar policy. - -`Aquarium.Epiphany` later owns agent/body grammar selection and semantic state -bindings. - -Tests: - -- clients emit contracts without renderer types; -- stable seeds emit stable keys. - -## Mock Boundaries - -Add these before the modules need them: - -- `IFractalClock`: deterministic frame/time. -- `IFractalRandom`: deterministic update lottery. -- `IProjection`: projection candidate swap. -- `IContributionProbe`: observed pixel/form/appearance/transport delta. -- `IFractalPayloadStore`: fake RAM/SSD payload availability. -- `IFractalGpuBudget`: fake GPU table/page limits. -- `IFractalDebugSink`: telemetry capture without UI. - -Mock resources and observations, not private helper functions. The tests should -pin module contracts, not puppet implementation details. - -## Phase 0: Test And Project Skeleton - -Goal: create the module/testing skeleton before algorithm code spreads. - -Tasks: - -- [x] Add `src/Aquarium.Engine.Fractal`. -- [x] Add `tests/Aquarium.Engine.Fractal.Tests`. -- [x] Add project references from tests to contracts/fractal core. -- [x] Add deterministic fake clock/random/debug sink test helpers. -- [x] Add a boundary test proving `Aquarium.Engine.Fractal` has no D3D12/Vortice dependency. - -Exit gate: - -- `dotnet build Aquarium.Engine.sln` -- `dotnet test tests/Aquarium.Engine.Fractal.Tests` - -Cut line: - -- If module wiring fights the existing solution, keep the new core smaller, not - sneak fractal logic into `D3D12Renderer`. - -## Phase 1: Cube-Face Address And Projection Harness - -Goal: establish stable planetary tile addresses and measured projection choices. - -Tasks: - -- [x] Add `CubeFace`, `CubeTileKey`, and quadtree path helpers. -- [x] Add local tile uv to cube-face coordinate conversion. -- [x] Implement identity-normalize projection as baseline. -- [x] Implement tangent projection candidate. -- [ ] Implement fifth-order odd polynomial projection candidate. -- [ ] Add placeholder/interface for COBE/QSC candidate. -- [x] Add area distortion sampler. -- [x] Add face-edge continuity tests. -- [x] Add CPU benchmark or fixture reporting candidate costs. -- [ ] Add Zyphos debug mode that colors face/tile coordinates. - -Tests: - -- projection round trips where inverse exists; -- face-edge continuity cases; -- deterministic tile key formatting; -- sampled area error fixtures. - -Exit gate: - -- projection report names current default and measured error/cost; -- Zyphos can show face/tile debug colors. - -Cut line: - -- Ship tangent projection first if polynomial/COBE cost delays visible work. - Keep the harness so the choice stays measurable. - -## Phase 2: Shaped 2D Brush Envelope - -Goal: replace circular brush thinking with compact-support anisotropic fields. - -Tasks: - -- [x] Add CPU `FractalBrushEnvelope2D`. -- [x] Add HLSL packed envelope row. -- [x] Implement compact-support ellipse evaluator. -- [x] Add CPU/HLSL parity fixture. -- [x] Add brush bounds and support rejection tests. -- [x] Add a small adapter that lowers one claim into the current height brush path. -- [ ] Add debug overlay for envelope bounds and weight. - -Tests: - -- weight at center/edge/outside support; -- rotation parity; -- deterministic packet packing; -- old circular brush fixture still reproducible through a round envelope. - -Exit gate: - -- current height pass can render shaped 2D envelopes through a compatibility adapter. - -Cut line: - -- Do not add taper/skew/ridge controls until the basic envelope has debug views - and parity tests. - -## Phase 3: Semantic Claims And Ownership Tree - -Goal: preserve authoring meaning before backend flattening. - -Tasks: - -- [x] Add contract DTOs for domains, claims, nodes, summaries, and selected cuts. -- [x] Add stable key builder for planet tile + grammar path. -- [x] Add in-memory ownership tree builder. -- [x] Implement operations: `Union`, `Subtract`, `Common`, `Repeat`, `Refine`, `Capture`, `Bind`. -- [ ] Implement operation bounds. -- [x] Add flattening compiler to shaped 2D brush packets. -- [x] Add debug dump for authored tree and flattened packets. -- [x] Preserve multiple `.aquageo` tile roots in the ownership tree instead of - collapsing every claim under the final tile. -- [x] Add compact `flame` grammar primitive for deterministic curled recursive - brush emission. - -Tests: - -- [x] seeded grammar determinism; -- stable keys across equivalent expansion; -- union/subtract/common bounds; -- flattening golden packets; -- client contracts contain no renderer type. - -Exit gate: - -- one toy terrain grammar emits semantic claims, an ownership tree, and flattened brush packets. - -Cut line: - -- Do not build a CAD CSG kernel. This tree adjudicates semantic ownership and - lowering, not arbitrary mesh booleans. - -## Phase 4: Node Summaries - -Goal: make every LOD subtree renderable without its children. - -Tasks: - -- [x] Add summary builder for 2D brush tree nodes. -- [x] Track max height/form error. -- [x] Track max material delta placeholder. -- [x] Track coverage and estimated cost. -- [ ] Add parent fallback payload. -- [ ] Add summary serialization. -- [ ] Add debug overlay for summary bounds/error. - -Tests: - -- parent summary conservatively covers child height contribution; -- child eviction leaves parent renderable; -- summary round trip preserves error bounds; -- summary cost monotonically covers descendants. - -Exit gate: - -- selected parent summary can render when children are absent. - -Cut line: - -- Use conservative amplitude/frequency bounds before clever exact summaries. - -## Phase 5: Contribution Cache And Selected Cut - -Goal: choose a stable hierarchy cut without scoring every leaf. - -Tasks: - -- [x] Add stable-keyed contribution table. -- [x] Add projected error scorer. -- [x] Add selected-cut builder. -- [x] Add hysteresis fade weights. -- [x] Add budget clamp. -- [x] Add debug channels: score, depth, fade, estimated cost. -- [x] Add explicit resource budget plan for CPU update count, GPU estimated - packet cost, RAM residency, and SSD request pressure. - -Tests: - -- [x] score decreases with distance for fixed error; -- [x] score increases with error for fixed distance; -- small camera motion keeps cut stable; -- [x] budget clamp chooses parent summaries; -- fade never changes conservative SDF/height safety fields. - -Exit gate: - -- toy terrain grammar selects parent at distance and children nearby. - -Cut line: - -- Keep scoring on CPU until data layout and debug channels are stable. - -## Phase 6: Probabilistic Online Updates - -Goal: refresh contribution estimates under budget and converge without -pretending an online smoother is ReSTIR. - -Research authority: - -- ReSTIR DI: candidate generation plus temporal and spatial reservoir reuse for - real-time direct lighting. - https://research.nvidia.com/labs/rtr/publication/bitterli2020spatiotemporal/ -- ReSTIR GI: path reservoirs for indirect lighting, with final shading fed by a - selected reservoir sample. - https://research.nvidia.com/publication/2021-06_restir-gi-path-resampling-real-time-path-tracing -- GRIS: the generalized theory for correlated samples, unknown PDFs, varied - domains, and shift mappings. This is the fractal/SDF/sensor-fusion door. - https://research.nvidia.com/labs/rtr/publication/lin2022generalized/ -- RTXDI integration docs: initial sampling, temporal reprojection, spatial - reuse, validation, shift mapping, reservoir buffers, and denoiser guide - buffers. - https://github.com/NVIDIA-RTX/RTXDI/blob/main/Doc/RestirGI.md - https://github.com/NVIDIA-RTX/RTXDI/blob/main/Doc/RestirPT.md - -Tasks: - -- [x] Add pure `ResampledImportanceReservoir` core with selected - sample, target, weight sum, represented candidate count, merge, and - contribution weight. -- [x] Add estimator state: mean, variance/uncertainty, confidence, sample count, sample age. -- [x] Add stochastic scheduler with deterministic random source. -- [x] Add exploration budget. -- [x] Add live contribution cache that observes only scheduled nodes each frame - and feeds the next resource plan. -- [x] Promote contribution state into `FractalOccupancyGraph` with visibility, - update probability, confidence decay, and stale uncertainty growth. -- [x] Convert contribution-cache refresh into a candidate generator that submits - weighted candidates to the resampled-importance core. -- [x] Add fractal SDF probe candidate records: domain key, local frame, bound, - projected contribution target, source PDF, payload handle, and material delta. -- [x] Add structural probe generator that lowers IFS node summaries into - `FractalProbeSample` reservoir candidates. -- [x] Add selected-cut structural probe reservoir and expose it through Zyphos' - fractal render plan/debug dump. -- [ ] Add temporal reuse validation: camera motion, domain ancestry, local-frame - error, bounds, and disocclusion/material compatibility. Domain ancestry and - local-shift checks exist; camera/disocclusion/material validation still need - renderer inputs. -- [x] Add CPU temporal reuse validation contract with camera motion, - disocclusion, material mismatch, visibility, domain ancestry, local-frame - error, and bound rejection reasons. -- [ ] Add spatial reuse validation across screen tiles and cube-sphere neighbor - domains. -- [ ] Feed reservoir confidence, selected target, candidate count, sample age, - and invalidation reason into TAA guide/history buffers. Current - reservoir confidence, sample age, domain validity, and invalidation code now - have explicit scene/history reservoir guide targets; selected target and - candidate count still need producer-side packing once GPU reservoirs exist. -- [x] Add confidence decay and stale uncertainty growth. -- [ ] Add fake contribution probe. -- [ ] Add convergence telemetry. -- [ ] Add debug channels: uncertainty, sample age, update probability, - reservoir weight sum, selected target, candidate count, reuse validity. - -Tests: - -- [x] reservoir accepts candidates proportional to target/source PDF; -- [x] reservoir merge preserves represented candidate count and weight sum; -- [x] invalid zero-weight candidates do not corrupt reservoir state; -- [x] contribution cache exposes scheduled updates as reservoir candidates; -- deterministic RNG fixture repeats schedule; -- visible nodes keep nonzero update probability; -- near-threshold nodes keep nonzero update probability; -- stale wrong score recovers after observations; -- fixed camera path converges within tolerance; -- [x] temporal reuse rejects mismatched domain ancestry; -- [x] spatial reuse rejects invalid local-frame shifts; -- [x] temporal reuse rejects camera motion, disocclusion, material mismatch, - and low visibility; -- [x] TAA history confidence is modulated by current reservoir confidence; -- [x] TAA history confidence drops when previous-frame reservoir/domain validity changes; -- update cost respects budget. - -Exit gate: - -- cache updates only a bounded subset per frame while selected cuts converge, - and the selected detail path is driven by tested reservoir math rather than a - frozen score table. - -Cut line: - -- No neural predictor until the ReSTIR/GRIS-shaped reservoir pipeline fails - with captured telemetry. No consumer-owned temporal cache unless it clearly - owns raw capture retention rather than resolved evidence. - -## Phase 7: Residency Simulation - -Goal: prove page/key semantics before real SSD/GPU streaming. - -Tasks: - -- [x] Add renderer-agnostic surface page key/metadata contracts for height, - 2D signed-distance, material, and confidence pages. -- [x] Add CPU surface page planner that lowers selected IFS cuts into stable - page metadata. -- [x] Add mockable surface page store boundary with resident/request/evict - decisions under a byte budget. -- [x] Add CPU surface page rasterizer for resident height, 2D signed-distance, - material, and confidence pages. -- [x] Add fake payload store with resident/missing states. -- [x] Add child request queue. -- [x] Add score/cost eviction policy. -- [x] Add parent-summary fallback path. -- [x] Clamp simulated RAM residency and SSD requests through the resource plan. -- [x] Add debug channels: residency, requests, evictions. - -Tests: - -- [x] missing child renders parent summary; -- [x] high-score missing child enqueues request; -- [x] low-score high-cost payload evicts first; -- [x] frame path never blocks on fake store. - -Exit gate: - -- selected cut can tolerate missing children without frame stalls. - -Cut line: - -- Simulate SSD first. Real async file IO waits until page semantics are boring. - -## Phase 8: Zyphos Planet Proof - -Goal: replace spherical terrain demo path with cube-sphere domain proof. - -Tasks: - -- [x] Add Zyphos cube-sphere domain root. -- [x] Add first tile grammar: ridges, craters, and material bands. -- [x] Add first flame-style microdetail grammar line inside the Zyphos leaf - domain. -- [x] Lower selected cut to shaped 2D height/material brush packets. -- [x] Feed planet shader from tile-local cube-face domains for post-hit - material/detail evaluation. -- [x] Route Zyphos render-plan construction through the resource budget planner. -- [x] Update Zyphos contribution cache every render-plan request while reusing - compiled brush packets for equivalent selected cuts. -- [x] Feed traced planet geometry from a hard-budgeted top-influence subset of - selected tile packets. -- [x] Lower the structural probe reservoir into a first compact 3D SDF splat - packet for inspection. -- [x] Lower resident 2D SDF pages into bounded projected 3D splat packets - through an explicit page-to-world mapping boundary. -- [x] Add first face/tile/material influence debug view through render debug - mode 11. -- [ ] Add LOD/cache debug overlays. -- [ ] Remove or quarantine old spherical noise path as baseline fixture. - -Tests: - -- face seams render continuously; -- [x] tile keys remain stable under camera movement; -- debug modes show selected depth and cache state; -- headless Zyphos smoke render passes. - -Exit gate: - -- Zyphos renders terrain from semantic cube-sphere tile grammar. - -Cut line: - -- Do not start agent-body recursive form here. Planet terrain proves the shared - address, envelope, summary, and cache spine first. - -## Phase 9: Agent/Body Pilot - -Goal: prove the same grammar works for object-local detail. - -Tasks: - -- [ ] Pick one role/body with a stable base SDF. -- [ ] Add object-local domain root. -- [ ] Add 2D material/detail claims before traced form recursion. -- [ ] Add object-local summary tree. -- [ ] Integrate selected cut with SDF proxy packet. -- [ ] Add debug channels for body detail score and SDF cost. - -Tests: - -- silhouette stays coherent across LOD; -- material/detail fades by contribution; -- SDF step budget remains bounded; -- no scene-global mega-SDF path appears. - -Exit gate: - -- one body uses semantic detail grammar without violating proxy bounds. - -Cut line: - -- If form recursion destabilizes tracing, keep recursive detail in material - payloads and leave traced form coarse. - -## Phase 10: Learned Scoring Research Gate - -Goal: only add learned scoring after the estimator produces data. - -Tasks: - -- [ ] Add probe dataset writer. -- [ ] Capture camera paths, predicted scores, observed deltas, and costs. -- [ ] Analyze heuristic error offline. -- [ ] Try calibrated regression or tiny predictor. -- [ ] Add A/B mode against heuristic estimator. - -Tests: - -- held-out camera path comparison; -- learned mode beats heuristic fidelity/cost clearly; -- conservative summaries still own safety; -- fallback heuristic remains available. - -Exit gate: - -- learned scorer improves measured fidelity/cost without removing deterministic safety. - -Cut line: - -- If it does not beat the estimator clearly, delete it. No ornamental oracle. - -## Phase 11: GPU-Resident Splat And Reservoir Receipt - -Goal: prove hot fractal splat and reservoir population belongs on the GPU, not -in managed object graphs. - -Tasks: - -- [x] Add packed GPU splat buffer contract with no per-splat strings or object - ownership. -- [x] Add native packed CPU buffer helper for the rare staging/readback paths - that genuinely need C# memory. -- [x] Add D3D12 compute receipt harness that writes millions of splats directly - into a GPU-resident UAV. -- [x] Add distinct GPU reservoir packet contracts for the first opaque slice: - SDF envelopes, PBR material envelopes, and radiosity. These are backend packet - names for Form, Appearance, and Transport, not the permanent conceptual - architecture. -- [x] Sample those three reservoir layers in independent compute passes under a - stochastic per-frame update budget. -- [x] Measure with GPU timestamp queries and read back only a tiny checksum - sample. - -Receipt: - -- GTX 1070, `2,000,000` splats, `2,000,000` SDF/Form reservoirs, - `2,000,000` PBR/Appearance reservoirs, and `2,000,000` - radiosity/Transport reservoirs. -- Packet sizes: `80` bytes/splat, `64` bytes/reservoir. -- Budget: `50,000` updates per reservoir pass per frame, `2` - candidates/update, full reservoir coverage in `40` frames. -- GPU time: `4.471 ms/frame`. -- Equivalent throughput: `223.7 FPS`, about `447.3M` splats/sec. -- Command: `.\scripts\fractal-splat-receipt.ps1 -Splats 2000000 -Frames 120 -Candidates 2 -ReservoirUpdates 50000`. - -Exit gate: - -- Receipt must show plural-millions of GPU-resident splats and distinct - reservoir layers populated or updated at hundreds of FPS equivalent on the - target tired GTX 1070. - -Cut line: - -- This is compute-side population and cache-update throughput, not final shaded - visibility. Do not sell it as renderer completion until the - draw/raster/resolve path consumes the same packed buffers. -- The next coherent packet evolution is density/extinction Form plus - participating-medium Appearance/Transport. Do not force flames or sensor - confidence volumes through solid SDF semantics just because the first packet - names said SDF. - -## First Work Packet - -Start here: - -1. Add `Aquarium.Engine.Fractal` and its test project. -2. Add cube-face/tile key types. -3. Add identity and tangent projection candidates. -4. Add area distortion sampler and face-edge tests. -5. Add a simple projection report fixture. - -Definition of done: - -- `dotnet build Aquarium.Engine.sln` -- new fractal tests pass; -- projection report is checked into test output or docs; -- `state/evidence.jsonl` records the chosen first projection default and why. diff --git a/research/rendering/fractal-projection-report.md b/research/rendering/fractal-projection-report.md deleted file mode 100644 index b96e462..0000000 --- a/research/rendering/fractal-projection-report.md +++ /dev/null @@ -1,22 +0,0 @@ -# Cube-Sphere Projection Report - -Unit sphere area target per cube-coordinate area is `pi / 6`. -Lower mean absolute relative area error is better for terrain density. - -| Projection | Face | Samples | Avg area scale | Min rel area | Max rel area | Mean abs rel error | RMS rel error | -| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | -| normalize | PositiveX | 16 | 0.524151 | 0.417233 | 1.887723 | 0.315999 | 0.378463 | -| normalize | NegativeX | 16 | 0.524151 | 0.417233 | 1.887723 | 0.315999 | 0.378463 | -| normalize | PositiveY | 16 | 0.524151 | 0.417233 | 1.887723 | 0.315999 | 0.378463 | -| normalize | NegativeY | 16 | 0.524151 | 0.417233 | 1.887723 | 0.315999 | 0.378463 | -| normalize | PositiveZ | 16 | 0.524151 | 0.417233 | 1.887723 | 0.315999 | 0.378463 | -| normalize | NegativeZ | 16 | 0.524151 | 0.417233 | 1.887723 | 0.315999 | 0.378463 | -| tangent | PositiveX | 16 | 0.523892 | 0.873521 | 1.175214 | 0.075978 | 0.088579 | -| tangent | NegativeX | 16 | 0.523892 | 0.873521 | 1.175214 | 0.075978 | 0.088579 | -| tangent | PositiveY | 16 | 0.523892 | 0.873521 | 1.175214 | 0.075978 | 0.088579 | -| tangent | NegativeY | 16 | 0.523892 | 0.873521 | 1.175214 | 0.075978 | 0.088579 | -| tangent | PositiveZ | 16 | 0.523891 | 0.873521 | 1.175189 | 0.075993 | 0.088592 | -| tangent | NegativeZ | 16 | 0.523891 | 0.873521 | 1.175189 | 0.075993 | 0.088592 | - -Default for the first terrain slice: `tangent`. -It is still cheap, remains seam-compatible with the cube face mapping, and the sampler gives it lower area spread than direct normalization on this harness. diff --git a/research/rendering/fractal-reference-oracles.md b/research/rendering/fractal-reference-oracles.md deleted file mode 100644 index 7711b12..0000000 --- a/research/rendering/fractal-reference-oracles.md +++ /dev/null @@ -1,568 +0,0 @@ -# Fractal Reference Oracles - -Aquarium needs boring reference pressure before it earns pretty fractal claims. -The renderer is not allowed to prove itself by looking interesting. - -## Apophysis/FLAM3 Boundary - -Apophysis 7x is the classic editor lineage for fractal flames, and the -repository is GPL-2.0. FLAM3 is the older portable renderer/genome toolchain -with the public `.flame`/`.flam3` ecosystem and documented variation list. - -Use them like AquaSynth uses synth references: - -- Reference fixtures live in tests or artifacts, not engine runtime. -- GPL renderer/source stays external; Aquarium does not paste implementation - code into the runtime. -- Aquarium DSL candidates must reproduce reference behavior through numeric - gates before GPU rendering claims are accepted. -- Image parity receipts should be produced by an external reference renderer - when a local FLAM3/Apophysis-compatible binary is available. - -## First Gate - -The first committed fixture is deliberately small: - -- `tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-sierpinski.flame` -- `tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-sierpinski.aquageo` - -The `.flame` file uses three Apophysis/FLAM3-style linear xforms. The -`.aquageo` file expresses the same affine IFS using `affineifs` and -`affinemap`. `ApophysisReferenceParityTests` compares both through a fixed -transform sequence and through chaos-game moment bounds. - -This is not full flame parity. It is the first ruler on the desk. - -## Next Gates - -1. DONE: parse a minimal `.flame` subset into a renderer-agnostic flame - definition: xform weight, color, affine coefficients, and `linear`, - `spherical`, and `bubble` variation weights. -2. DONE: add exact point parity for `linear`, `spherical`, and `bubble`, - plus a deterministic histogram checksum for the mixed fixture. -3. DONE: add an optional external FLAM3-compatible render receipt path. When - `flam3-render` is available, Aquarium renders the fixture to binary PPM and - records image-shape, non-black pixel count, RGB checksum, and luminance - checksum under `artifacts/fractal-flame-reference`. -4. DONE: lower proven flame definitions into GPU program rows for the receipt - shader's `flame 2D affine/variation program` mode. -5. Use those rows as a visual test scene only through GPU-resident reservoirs, - not by restoring a CPU direct renderer. - -## Local Receipt - -Run: - -```powershell -.\scripts\fractal-flame-receipt.ps1 -``` - -Default receipt: - -- fixture: `linear-spherical-bubble.flame` -- samples: `8192` -- histogram: `64x64` -- bounds: `-8,-8,8,8` -- seed: `0x0BADC0DE` -- expected checksum: `0xAEB1C81B` - -This receipt is Aquarium's local CPU parser/evaluator checksum. It is not yet -an external FLAM3/Apophysis renderer receipt. - -## External Renderer Receipt - -FLAM3 stays outside the repo and outside runtime binaries. If a local -`flam3-render` executable is installed, run: - -```powershell -.\scripts\fractal-flame-reference-render.ps1 -Flam3Render C:\path\to\flam3-render.exe -``` - -The script follows FLAM3's documented environment-variable interface: `in` -selects the flame file, `out` selects the output image, `format=ppm` requests a -plain reference image, `seed` fixes the random sequence, and `qs` controls -quality scale. Aquarium then hashes the PPM through -`tools/Aquarium.Fractal.Receipt --reference-ppm`. - -This is the first external renderer receipt. It proves the fixture can be -rendered by the reference family and gives Aquarium a stable image artifact to -compare as the local flame subset grows. - -## JWildfire / FARender Visual Reference - -Aquarium now has a reproducible higher-quality visual reference lane that does -not depend on tools already installed on the workstation: - -```powershell -.\scripts\install-flame-reference-tools.ps1 -.\scripts\fractal-flame-jwildfire-reference.ps1 ` - -Renderer FARender ` - -Width 1024 ` - -Height 1024 ` - -Quality 2000 ` - -NoDensityEstimation -``` - -`install-flame-reference-tools.ps1` downloads JWildfire 9.00 and a local -Temurin JRE into ignored `artifacts/reference-tools`. These are reference -artifacts, not Aquarium runtime dependencies. - -`fractal-flame-jwildfire-reference.ps1` prefers JWildfire's bundled FARender -GPU path when available because it accepts an explicit output file and fails -the script when no image is produced. The Java batch renderer remains available -through `-Renderer JWildfireJava`, but local smoke showed that it can complete -without writing an image into the batch directory because JWildfire's output -folder is preference-driven. Silent reference success is not a reference. - -Local GTX 1070 smoke receipt from 2026-05-20: - -- renderer: JWildfire 9.00 bundled FARenderJWF -- fixture: `artifacts/reference-tools/j-wildfire-9.00/lib/FARenderJWF/selftest.flame` -- command: `1024x1024`, quality `2000`, CUDA, no density-estimation phase -- time: `7.69 sec` -- artifact: - `artifacts/fractal-flame-jwildfire-reference/selftest-farender-20260520-233638.png` - -The repository's tiny `linear-spherical-bubble.flame` fixture is still useful -for Aquarium subset parity, but FARender crashed on it because the fixture is -Apophysis-style minimal XML rather than full JWildfire `variationGroup` flame -XML. Do not "fix" that by making the fixture bigger until the parser and DSL -contract deliberately support the richer reference dialect. - -## External Density Oracle - -Aquarium's CPU flame oracle is no longer the only visual-parity target. The GPU -receipt can compare Aquarium splat density against a binary PPM image rendered -by an external renderer: - -```powershell -.\scripts\new-jwildfire-baby-fixture.ps1 -.\scripts\fractal-flame-jwildfire-reference.ps1 ` - -Renderer FARender ` - -Flame artifacts\fractal-flame-jwildfire-reference\julian-disc-baby.flame ` - -Width 768 ` - -Height 768 ` - -Quality 2000 ` - -OutputDirectory artifacts\fractal-flame-jwildfire-reference -magick artifacts\fractal-flame-jwildfire-reference\julian-disc-baby-farender-*.png ` - -depth 8 artifacts\fractal-flame-jwildfire-reference\julian-disc-baby-farender.ppm -.\scripts\fractal-splat-receipt.ps1 ` - -ProgramFlame artifacts\fractal-flame-jwildfire-reference\julian-disc-baby.flame ` - -Splats 2000000 ` - -WarmupSplatUpdates 2000000 ` - -SplatUpdates 50000 ` - -Warmup 8 ` - -Frames 10 ` - -Depth 8 ` - -ReservoirUpdates 15000 ` - -ReadbackSplats 1000000 ` - -ReferenceDensityPpm artifacts\fractal-flame-jwildfire-reference\julian-disc-baby-farender.ppm ` - -HistogramSize 256x256 ` - -HistogramBounds '-2,-2,2,2' -``` - -`new-jwildfire-baby-fixture.ps1` derives a smaller, reproducible target from -FARender's bundled `selftest.flame`, preserving the boilerplate FARender needs -while reducing the nastier variation pressure: `jwf_julian_power` drops from -`126` to `8`, `jwf_gaussian_blur` becomes `0`, and the `wfield_*` amount fields -are set to zero. This is not a pristine flame design. It is a compatible rung -on the ladder that FARender actually renders. - -First external-density receipt, local GTX 1070, 2026-05-21: - -- reference renderer: JWildfire 9.00 bundled FARenderJWF -- fixture: `artifacts/fractal-flame-jwildfire-reference/julian-disc-baby.flame` -- reference render: `768x768`, quality `2000`, CUDA -- Aquarium steady GPU time: `1.145 ms/frame`, `873.4 FPS` equivalent -- external density score: `15.33%` in `256x256` bounds `-2,-2,2,2` -- score sweep at `128x128`: best tested bound was `-4,-4,4,4` at `32.95%` -- contact sheet: - `artifacts/fractal-flame-jwildfire-reference/julian-disc-baby-external-contact.png` - -The low external score is useful. Aquarium still scores about `89.94%` against -its CPU interpretation of the same baby fixture in `128x128` bounds -`-4,-4,4,4`, while FARender density disagrees hard. That means the next work is -not "more samples"; it is dialect and camera semantics: FARender flame camera -mapping, color/density filtering, chaos/xaos and weighting-field behavior, and -variation exactness. - -The first post-oracle correction found two concrete import/math lies: - -- JWildfire `coefs` are packed for FARender's affine as `a b d e c f`; Aquarium - had transposed the off-diagonal terms as `a d / b e`. -- FARender's `jwf_disc` source uses `atan2(x, y) / PI`; Aquarium used - `atan2(y, x) / PI`. - -After fixing both, the same external-density receipt scored `26.87%` at -`256x256` bounds `-2,-2,2,2`, up from `15.33%`. - -The parity candidate no longer bins raw splat occupancy. That was the wrong -organ. The GPU receipt now builds the Aquarium comparison image from the SDF -envelope reservoir layer by stamping each populated envelope into a shaped -density histogram. PBR and radiosity reservoirs stay separate; PBR will score -surface appearance later, and radiosity is not part of this flame-density gate -yet. With full SDF reservoir coverage on the local GTX 1070, the same -`julian-disc-baby` receipt scored `22.14%` against the FARender PPM at -`256x256` bounds `-2,-2,2,2`, with `42.053 ms/frame` while refreshing all -2,000,000 reservoir rows in all three layers. The contact sheet lives at -`artifacts/fractal-flame-jwildfire-reference/julian-disc-baby-sdf-density-contact.png`. - -The next correction removed another dialect lie. JWildfire's -`variationGroup normal="1"` is not the same thing as an explicit `linear` -variation in FARender. A normal-only diagnostic renders as a constant point in -FARender, while Aquarium had been adding affine linear geometry. The importer -now ignores JWildfire `normal` as variation-group metadata; explicit `linear` -still stays linear for Apophysis/FLAM3-style fixtures. The SDF-density receipt -also gives subpixel envelopes a minimum one-bin reconstruction footprint so the -comparison does not quietly collapse back into point occupancy. - -After those fixes, the `julian-disc-baby` receipt scored `31.36%` against the -FARender PPM at `256x256` bounds `-2,-2,2,2`, with `41.692 ms/frame` while -refreshing all 2,000,000 reservoir rows in all three layers. Switching the -receipt to FARender-style flame camera bounds (`size / scale / cam_zoom`) raised -the same gate to `43.13%` with `68.01%` occupancy overlap; pass -`-HistogramBounds flame-camera` through `scripts/fractal-splat-receipt.ps1` for -that path. The contact sheet lives at -`artifacts/fractal-flame-jwildfire-reference/julian-disc-baby-normal-cut-area-contact.png`. - -Full reservoir refreshes must not use the stochastic hash indexer. When -`ReservoirUpdatesPerPass == SplatCount`, the compute shader now updates row -`updateIndex` directly for each reservoir layer. That keeps under-budget passes -stochastic while making full coverage actually full and memory-coherent. The -same `julian-disc-baby` full-refresh receipt stayed visually equivalent -(`43.09%`, `67.99%` occupancy overlap) but dropped from roughly `41 ms/frame` -to `7.508 ms/frame`, or `133.2 FPS` equivalent. - -The remaining visible mismatch is now narrower: Aquarium draws the same family -of form, but its density is still too compact and differently weighted. Fixing -that belongs in exact JWildfire variation/camera parity, target density -weighting, and view-conditioned reservoir feedback. -The next oracle step is to compare Aquarium through a matching density image -resolve, not raw point occupancy. - -## JWildfire Selftest Faceplant - -Running JWildfire's bundled `selftest.flame` through Aquarium is the correct -kind of embarrassing: - -```powershell -.\scripts\fractal-splat-receipt.ps1 ` - -ProgramFlame artifacts\reference-tools\j-wildfire-9.00\lib\FARenderJWF\selftest.flame ` - -Splats 2000000 ` - -SplatUpdates 50000 ` - -Warmup 0 ` - -Frames 1 ` - -Depth 64 ` - -ReservoirUpdates 15000 ` - -ReadbackSplats 250000 ` - -VisualParity ` - -VisualParityReferenceSamples 1000000 ` - -HistogramSize 256x256 ` - -HistogramBounds '-128,-128,128,128' -``` - -First receipt after adding the JWildfire `variationGroup`/coefficient-layout -slice and the `disc`, `julian`, and `gaussian_blur` variation subset, before -lowering `post`: - -- GPU time: `66.446 ms/frame`, `15.0 FPS` equivalent -- visual score: `5.01%` -- occupancy overlap: `3.04%` -- L1 distance: `1.899840` -- artifact: - `artifacts/fractal-jwildfire-faceplant/jwildfire-vs-aquarium-expanded.png` - -The first unexpanded run scored `0.00%` and rendered a single dot. The expanded -run produces a recognizable central flame knot, but it still does not match the -reference. This is not just "more variations needed." It exposes three distinct -gaps: - -1. **DSL expressiveness.** A serious flame dialect needs named variation - nodes, parameters, post transforms, palette/color semantics, xaos/chaos - weights, and optional weighting fields. The current Aquarium flame subset is - a compact test dialect, not a full JWildfire import surface. -2. **Translation quality.** JWildfire's coefficient layout differs from the - older Apophysis-style fixtures. `variationGroup` can hide the real variation - list from the xform attributes. Rich dialect import needs a translation - report that says exactly which fields were accepted, approximated, ignored, - or rejected. -3. **Hot-path shape.** Brute replaying 64 flame iterations per splat in one - compute invocation is too slow. Rich flame rendering should store continuing - iteration state in GPU reservoirs and advance it stochastically across - frames, then density-estimate/shade from those resident samples. The reservoir - is the renderer, not an expensive reset button. - -The next coherent slice is therefore not "add 200 variations." It is an -import/lowering contract: parse a richer flame AST, produce an explicit -translation report, lower supported variation nodes into compact GPU op rows, -and carry persistent per-sample iteration state so zoom/movement can reuse -sample history instead of starting every splat from zero. - -That import report now exists. GPU and histogram flame receipts emit a sibling -`fractal-flame-import-report-*.json` next to the numeric receipt. For the -JWildfire selftest flame, the first report after `post` lowering says: - -- accepted fields: `15` -- approximated fields: `3` -- ignored fields: `45` -- rejected fields: `11` -- rejected geometry/sampling losses: `wfield_*` weighting-field attributes on - the disc xform - -This report is the next expansion gate. A flame may parse successfully and -still be a bad import; unsupported fields must stay visible until the DSL, -compiler, or renderer can actually own them. - -Lowering `post` required expanding only the small authored-program transform -row, not the resident million-splat or reservoir packets. The closer -CPU/GPU-slice receipt now gives: - -- bounds `-8,-8,8,8`: `84.19%` GPU-vs-Aquarium-CPU slice score at - `129.073 ms/frame` -- bounds `-128,-128,128,128`: `88.01%` GPU-vs-Aquarium-CPU slice score at - `129.404 ms/frame` -- artifact: - `artifacts/fractal-jwildfire-faceplant/jwildfire-vs-aquarium-post-close.png` - -This is not external JWildfire visual parity. It says Aquarium's GPU path is -now much closer to Aquarium's CPU interpretation of the supported slice. The -image is still missing JWildfire's palette, density estimation, weighting-field -behavior, render filters, and likely more dialect detail. The speed is also -unacceptable for realtime because depth-64 replay is the wrong execution model. - -The first persistent-iteration invariant is now tested on CPU: -`FractalFlameIterationState` plus `FractalFlameIterationStepper` prove that -advancing one sample by 64 iterations in one call matches advancing the same -state in eight 8-iteration chunks. This is not a CPU renderer. It is the -mockable contract the GPU state buffer must preserve when the shader stops -replaying every splat from zero. - -## GPU Flame Receipt - -The flame fixture can now drive the D3D12 reservoir receipt directly: - -```powershell -.\scripts\fractal-splat-receipt.ps1 ` - -Splats 2000000 ` - -SplatUpdates 50000 ` - -Warmup 10 ` - -Frames 60 ` - -Depth 8 ` - -ReservoirUpdates 15000 ` - -ProgramFlame tests\Aquarium.Engine.Fractal.Tests\Fixtures\Apophysis\linear-spherical-bubble.flame -``` - -Local GTX 1070 receipt from 2026-05-20: - -- resident splats: `2,000,000` -- resident reservoir rows: `2,000,000` each for SDF, PBR, and radiosity -- program transforms: `3` -- splat updates/frame: `50,000` -- reservoir updates/pass/frame: `15,000` -- GPU time: `1.030 ms/frame` -- equivalent FPS: `971.3` -- readback checksum: `0x2647D8B08575B848` - -The flame hot path now keeps per-splat iteration state in a GPU UAV instead of -replaying every chaos-game ancestry from the origin. `Depth` is the number of -iterations advanced when a row is touched; the row stores point, support, -material, random state, and accumulated step for the next stochastic update. - -This makes the receipt a two-phase cache: - -- acquisition: seed every resident row and optionally advance the full resident - population for a few warmup frames -- maintenance: update only the budgeted stochastic subset while the layered - SDF/PBR/radiosity reservoirs continue their independent passes - -```powershell -.\scripts\fractal-splat-receipt.ps1 ` - -ProgramFlame artifacts\reference-tools\j-wildfire-9.00\lib\FARenderJWF\selftest.flame ` - -Splats 2000000 ` - -WarmupSplatUpdates 2000000 ` - -SplatUpdates 50000 ` - -Warmup 8 ` - -Frames 20 ` - -Depth 8 ` - -ReservoirUpdates 15000 ` - -ReadbackSplats 250000 ` - -VisualParity ` - -VisualParityReferenceSamples 1000000 ` - -HistogramSize 256x256 ` - -HistogramBounds -8,-8,8,8 ` - -VisualParityImageDirectory artifacts\fractal-jwildfire-faceplant\source ` - -VisualParityImagePrefix selftest-persistent-warmfull-depth008-frame-020 -``` - -Local GTX 1070 receipt from 2026-05-21: - -- resident splats: `2,000,000` -- flame iteration states: `2,000,000` at `32` bytes each -- resident reservoir rows: `2,000,000` each for SDF, PBR, and radiosity -- warmup splat updates/frame: `2,000,000` -- steady splat updates/frame: `50,000` -- reservoir updates/pass/frame: `15,000` -- measured steady GPU time: `1.011 ms/frame` -- equivalent steady FPS: `988.8` -- visual parity against Aquarium CPU slice oracle: `84.86%` -- cosine similarity: `0.986955` -- readback checksum: `0xC633FADC3BD7E5BE` - -Without the full-population acquisition pass, the same steady budget scored only -`32.64%` on the JWildfire selftest slice because most rows were still shallow -ancestry. That is a useful failure: persistent state is not magic, it is a cache -that must be filled before a tiny maintenance budget can look clever. - -## Visual Parity Receipt - -The receipt tool can compare GPU flame splat positions against the local CPU -flame oracle: - -```powershell -.\scripts\fractal-splat-receipt.ps1 ` - -Splats 2000000 ` - -SplatUpdates 50000 ` - -Warmup 0 ` - -Frames 20 ` - -Depth 8 ` - -ReservoirUpdates 15000 ` - -ProgramFlame tests\Aquarium.Engine.Fractal.Tests\Fixtures\Apophysis\linear-spherical-bubble.flame ` - -ReadbackSplats 250000 ` - -VisualParity ` - -VisualParityReferenceSamples 1000000 ` - -HistogramSize 128x128 ` - -HistogramBounds -8,-8,8,8 -``` - -First local scores, GPU 250k readback samples against 1M CPU reference samples: - -| Frames | GPU ms/frame | Distribution score | L1 distance | RMSE | Cosine | -| ---: | ---: | ---: | ---: | ---: | ---: | -| 1 | 15.645 | 84.05% | 0.319072 | 0.000090 | 0.995365 | -| 5 | 4.017 | 84.10% | 0.318042 | 0.000089 | 0.995402 | -| 20 | 1.738 | 84.20% | 0.316019 | 0.000088 | 0.995591 | -| 60 + 10 warmup | 0.952 | 84.24% | 0.315136 | 0.000088 | 0.995505 | - -This proves the current GPU flame program has high distribution similarity, but -it does **not** prove learned reservoir convergence. The score plateaus because -the current flame path initializes resident splats from the program and then -performs stochastic replacement; it does not yet use visual error feedback, -MIS/ReSTIR weights, or an external rendered-image residual to steer updates. - -## View-Conditioned Parity - -Global parity is a weak metric. Realtime usefulness depends on the current -camera window: panning or zooming should keep the visible image smooth while the -cache spends new work on underrepresented regions. - -The receipt tool therefore accepts named viewport bounds: - -```powershell -.\scripts\fractal-splat-receipt.ps1 ` - -Splats 2000000 ` - -SplatUpdates 50000 ` - -Warmup 10 ` - -Frames 60 ` - -Depth 16 ` - -ReservoirUpdates 15000 ` - -ProgramFlame tests\Aquarium.Engine.Fractal.Tests\Fixtures\Apophysis\linear-spherical-bubble.flame ` - -ReadbackSplats 250000 ` - -VisualParity ` - -VisualParityReferenceSamples 1000000 ` - -HistogramSize 128x128 ` - -VisualParityView global:-8,-8,8,8 ` - -VisualParityView mid:-1,-1,1,1 ` - -VisualParityView close:-0.5,-0.5,0.5,0.5 ` - -VisualParityView micro:-0.25,-0.25,0.25,0.25 -``` - -First view-conditioned receipt: - -| View | Distribution score | GPU hits | Reference hits | Starved bins | Underrepresented mass | -| --- | ---: | ---: | ---: | ---: | ---: | -| global | 97.09% | 249,972 | 999,836 | 1,034 | 2.91% | -| mid | 91.93% | 166,654 | 667,105 | 1,792 | 8.07% | -| close | 88.97% | 125,448 | 501,033 | 2,266 | 11.03% | -| micro | 82.05% | 71,348 | 284,011 | 2,656 | 17.95% | - -This is the first metric that catches the real problem. The reservoir is fast, -but it is not yet view-adaptive. It needs camera-conditioned target weights, -underrepresented-bin feedback, and temporal reuse validation before it deserves -claims about maintaining flame quality during movement and zoom. - -## Contact Sheets - -The quick 1M-sample oracle image is too noisy for visual judgment. Use the image -export path with a much larger CPU oracle when making contact sheets: - -```powershell -.\scripts\fractal-splat-receipt.ps1 ` - -ProgramFlame tests\Aquarium.Engine.Fractal.Tests\Fixtures\Apophysis\linear-spherical-bubble.flame ` - -VisualParity ` - -VisualParityReferenceSamples 20000000 ` - -VisualParityImageDirectory artifacts\fractal-contact-sheet-hq\source ` - -VisualParityImagePrefix zoom-frame-010 ` - -ReadbackSplats 250000 ` - -Depth 16 ` - -Frames 10 ` - -VisualParityView zoom:-0.25,-0.25,0.25,0.25 -``` - -The current high-reference contact sheet lives at: - -- `artifacts/fractal-contact-sheet-hq/flame-parity-contact-sheet-hq.png` - -It uses 20M CPU oracle samples and 250k Aquarium readback samples per panel. -This still is not a full FLAM3 density-estimated render, but it is no longer a -1M-sample noise patch masquerading as ground truth. - -## Sources - -- Apophysis 7x repository: https://github.com/wanily/apophysis7x -- FLAM3 repository and variation list: https://github.com/scottdraves/flam3 -- Draves, *The Fractal Flame Algorithm*: https://flam3.com/flame_draves.pdf - -## Reference Ladder - -Stop calling Aquarium's CPU histogram the visual ground truth. It is a math -oracle for a tiny variation subset. It is useful because it is deterministic, -small, and debuggable. It is not the bar for beautiful flame rendering. - -Use this ladder: - -1. **Gold visual reference: Chaotica.** Chaotica is the quality target for - flame art. Its own manual frames progressive rendering as the alternative - to Apophysis/FLAM3 fixed-quality rerendering, and says high quality often - means stopping at a sampling level after the image is no longer noisy. Use - Chaotica renders as imported reference artifacts when available. -2. **Scriptable visual reference: JWildfire/FARender.** JWildfire is LGPL, - has a documented headless batch renderer path: - `java org.jwildfire.create.tina.batch.HeadlessBatchRendererController `. - Its current public bundle also ships FARenderJWF, a Windows/NVIDIA GPU - renderer that the JWildfire changelog says may still be used while it works. - Use `scripts/install-flame-reference-tools.ps1` to hydrate the local tools - and `scripts/fractal-flame-jwildfire-reference.ps1 -Renderer FARender` for - explicit PNG output. -3. **Baseline renderer reference: FLAM3/Apophysis family.** Use FLAM3 for - portable `.flame`/`.flam3` compatibility, deterministic external receipts, - and old-school density-estimation sanity. -4. **Aquarium CPU oracle.** Use only for unit tests, point parity, histogram - smoke checks, and shader debugging. Never present it as market-quality - visual ground truth. - -Local machine status on 2026-05-20: Chaotica and `flam3-render` were not found -on PATH; only Ultra Fractal 6 was visible under Program Files. JWildfire 9.00 -and Temurin JRE 17 were downloaded into ignored artifacts, and FARenderJWF -successfully rendered its bundled selftest flame on the GTX 1070. Aquarium can -now compare against a real external flame renderer artifact, but it still -cannot claim best-in-market visual parity until imported Chaotica renders or a -fully matched JWildfire flame dialect are wired into residual metrics. - -Additional sources: - -- Chaotica features: https://chaoticafractals.com/features -- Chaotica progressive rendering: https://www.chaoticafractals.com/manual/rendering/progressive_rendering -- Chaotica render settings / sampling level: https://www.chaoticafractals.com/manual/user_interface/render_settings -- JWildfire GitHub / LGPL license: https://github.com/thargor6/JWildfire -- JWildfire headless batch renderer notes: https://www.jwfsanctuary.club/tutorial/how-to/how-do-i-render-a-full-folder-of-flames/ -- JWildfire bundled FARender/Swan notes: `artifacts/reference-tools/j-wildfire-9.00/CHANGES.txt` diff --git a/research/rendering/hdr-pbr-presentation.md b/research/rendering/hdr-pbr-presentation.md deleted file mode 100644 index e970862..0000000 --- a/research/rendering/hdr-pbr-presentation.md +++ /dev/null @@ -1,142 +0,0 @@ -# HDR/PBR Presentation Research - -Aquarium needs an HDR presentation path before the SDF field renderer grows real -lighting and participating media. The target is not "more bloom." The target is a -scene-linear renderer with believable dynamic range, camera exposure, optical -spill, and a display transform that preserves contrast without boiling the frame -in arcade syrup. - -## Sources - -- [ACES System overview](https://docs.acescentral.com/background/overview/) -- [Epic: How Epic Games is handling Auto Exposure in 4.25](https://www.unrealengine.com/tech-blog/how-epic-games-is-handling-auto-exposure-in-4-25?lang=en-US) -- [Unreal Engine bloom documentation](https://dev.epicgames.com/documentation/en-us/unreal-engine/bloom-in-unreal-engine?application_version=5.6) -- [Jorge Jimenez: Next Generation Post Processing in Call of Duty: Advanced Warfare](https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/) -- [John Hable: Filmic Tonemapping Operators](https://filmicworlds.com/blog/filmic-tonemapping-operators/) -- [John Hable: Filmic Tonemapping with Piecewise Power Curves](https://filmicworlds.com/blog/filmic-tonemapping-with-piecewise-power-curves/) -- [Hable: Uncharted 2 HDR Lighting, SIGGRAPH 2010](https://advances.realtimerendering.com/s2010/Hable-Uncharted2%28SIGGRAPH%202010%20Advanced%20RealTime%20Rendering%20Course%29.pdf) -- [Lagarde/de Rousiers: Moving Frostbite to Physically Based Rendering 3.0](https://cgvr.cs.uni-bremen.de/teaching/cg_literatur/Moving%20Frostbite%20to%20Physically%20Based%20Rendering%203.0%2C%202014%2C%20Sebastien%20Lagarde.pdf) - -## Distillation - -Modern HDR presentation is a chain, not a knob: - -1. Render lighting and emissive terms in scene-linear HDR. -2. Apply exposure in the HDR domain, preferably from a physical-camera or EV100 - model even if Aquarium initially uses manual exposure. -3. Generate bloom/glare from exposed HDR color before tonemapping. -4. Composite bloom back into exposed scene-linear color with low intensity and - broad support. -5. Apply a display transform or filmic tonemap with toe and shoulder. -6. Convert to the swapchain/display encoding only at the end. - -The important production lesson is that bloom is not a thresholded special -effect for "pixels above 1." In a high-dynamic-range PBR scene, broad low-gain -scatter can apply to the whole image while only genuinely bright energy becomes -visibly luminous. Threshold bloom is the cheap costume version; it cuts out the -low-level optical veil and encourages artists to overdrive emissive values until -the frame looks diseased. - -ACES-style and filmic transforms are useful because they give highlights a -shoulder and shadows a toe. Aquarium's current tiny ACES approximation is a -reasonable placeholder, but it is not a color-management system, not a look -authoring surface, and not enough to make the scene feel HDR by itself. - -## Aquarium Gate Plan - -### Gate HDR-A: Explicit Exposure - -Add an exposure scalar in `AquariumFrame`, initially manual and persisted through -CultCache later. - -Start simple: - -- `exposedColor = sceneLinearColor * exposure` -- default exposure chosen so Self is bright but not pinned white across its - whole disc -- debug mode for log luminance or EV bands - -Avoid auto exposure until the scene has enough stable luminance content. A -volumetric/SDF scene with huge black regions and a giant Self emitter will make -naive histogram adaptation twitch like a bad witness. - -### Gate HDR-B: Bloom Pyramid - -Add a pre-tonemap bloom pass: - -- source: exposed HDR scene color -- no hard threshold at first -- downsample pyramid with firefly-safe weighted averages -- upsample with small tent filters and per-level radius -- composite with low intensity into exposed scene color before tonemap - -This follows the Jimenez production shape: pyramidal bloom/veil for stability -and robustness, not a single huge blur taped over bright pixels. - -### Gate HDR-C: Display Transform - -Keep the current ACES approximation only as `DisplayTransform.AcesFit`. - -Add an explicit display-transform function boundary: - -- ACES fit for default -- Hable/filmic curve as an alternate debug/look path -- later: LUT-based transform if Aquarium needs an authored look - -Do not bury exposure, bloom, and tonemapping in one shader lump. The whole point -is to keep the light transport legible before volumetrics arrive and start -lying convincingly. - -### Gate HDR-D: HDR Debug Views - -Add debug views before tuning: - -- scene-linear luminance -- exposed luminance -- bloom contribution -- tonemapped final -- over-range / clipped highlight mask - -If Self, planets, Grid, and later clouds cannot be inspected in each stage, the -pipeline will become a little shrine to superstition. Burn the shrine early. - -## Rules For Aquarium - -- Bloom happens before tonemapping. -- Bloom spreads existing energy; it does not invent light. -- Prefer broad low-intensity bloom/veil over hard-threshold glow. -- Keep overlay text out of HDR and bloom unless it becomes a diegetic scene - surface. -- Do not tune emissive values against SDR final output alone. Inspect linear and - exposed luminance. -- Volumetrics must feed and be fed by the same exposure/display path as solids. -- If the frame needs "more HDR," first check exposure, display shoulder, and - source radiance before turning up bloom. - -## Immediate Recommendation - -Before the field renderer: - -1. Add explicit exposure constants. -2. Split resolve into exposed HDR color and final display transform. -3. Add a bloom pyramid between exposure and tonemap. -4. Add debug views for luminance and bloom contribution. - -This gives SDF solids/clouds a real presentation pipe to land in. Otherwise the -field renderer will arrive carrying gorgeous radiance values into a cramped SDR -mail slot, and everyone will pretend the answer is blur radius. It is not. - -## Aquarium Implementation Note - -The first implementation now follows this shape: - -- fixed manual exposure in the frame constants -- exposed scene-linear HDR source for bloom -- three-level bloom pyramid at half, quarter, and eighth resolution -- firefly-safe downsampling -- separable horizontal/vertical blur per level -- low-gain bloom/veil contribution before the ACES fit -- debug mode `7` for bloom contribution and mode `8` for exposed luminance - -The remaining missing piece is a persisted/inspectable exposure control and, -later, a proper authored display-transform boundary. diff --git a/scripts/bake-pmrem-cubemap.py b/scripts/bake-pmrem-cubemap.py deleted file mode 100644 index 72ae493..0000000 --- a/scripts/bake-pmrem-cubemap.py +++ /dev/null @@ -1,278 +0,0 @@ -#!/usr/bin/env python3 -"""Bake a Radiance HDR latlong map into a GGX-prefiltered DDS cubemap.""" - -from __future__ import annotations - -import argparse -import math -import struct -from pathlib import Path - -import numpy as np - - -DXGI_FORMAT_R16G16B16A16_FLOAT = 10 -D3D10_RESOURCE_DIMENSION_TEXTURE2D = 3 -D3D11_RESOURCE_MISC_TEXTURECUBE = 0x4 - - -def read_radiance_hdr(path: Path) -> np.ndarray: - data = path.read_bytes() - cursor = 0 - while True: - end = data.index(b"\n", cursor) - line = data[cursor:end].decode("ascii", errors="replace").strip() - cursor = end + 1 - if not line: - break - - while True: - end = data.index(b"\n", cursor) - line = data[cursor:end].decode("ascii", errors="replace").strip() - cursor = end + 1 - if line: - resolution = line.split() - break - - if len(resolution) != 4 or resolution[0] != "-Y" or resolution[2] != "+X": - raise ValueError(f"Unsupported Radiance orientation in {path}: {' '.join(resolution)}") - - height = int(resolution[1]) - width = int(resolution[3]) - rgbe = np.empty((height, width, 4), dtype=np.uint8) - - for y in range(height): - if data[cursor] != 2 or data[cursor + 1] != 2: - raise ValueError(f"Unsupported non-RLE Radiance scanline {y}") - scan_width = (data[cursor + 2] << 8) | data[cursor + 3] - cursor += 4 - if scan_width != width: - raise ValueError(f"Radiance scanline {y} has width {scan_width}, expected {width}") - - scanline = np.empty((4, width), dtype=np.uint8) - for channel in range(4): - x = 0 - while x < width: - code = data[cursor] - cursor += 1 - if code > 128: - count = code - 128 - scanline[channel, x : x + count] = data[cursor] - cursor += 1 - else: - count = code - scanline[channel, x : x + count] = np.frombuffer(data, dtype=np.uint8, count=count, offset=cursor) - cursor += count - x += count - - rgbe[y] = scanline.T - - exponent = rgbe[..., 3].astype(np.int32) - scale = np.zeros((height, width), dtype=np.float32) - valid = exponent > 0 - scale[valid] = np.ldexp(np.ones(np.count_nonzero(valid), dtype=np.float32), exponent[valid] - (128 + 8)) - return rgbe[..., :3].astype(np.float32) * scale[..., None] - - -def radical_inverse_vdc(bits: int) -> float: - bits = (bits << 16) | (bits >> 16) - bits = ((bits & 0x55555555) << 1) | ((bits & 0xAAAAAAAA) >> 1) - bits = ((bits & 0x33333333) << 2) | ((bits & 0xCCCCCCCC) >> 2) - bits = ((bits & 0x0F0F0F0F) << 4) | ((bits & 0xF0F0F0F0) >> 4) - bits = ((bits & 0x00FF00FF) << 8) | ((bits & 0xFF00FF00) >> 8) - return bits * 2.3283064365386963e-10 - - -def hammersley(count: int) -> np.ndarray: - values = np.empty((count, 2), dtype=np.float32) - for i in range(count): - values[i, 0] = (i + 0.5) / count - values[i, 1] = radical_inverse_vdc(i) - return values - - -def face_directions(face: int, size: int) -> np.ndarray: - coord = (np.arange(size, dtype=np.float32) + 0.5) / size * 2.0 - 1.0 - u, v = np.meshgrid(coord, coord) - if face == 0: # +X - d = np.stack([np.ones_like(u), -v, -u], axis=-1) - elif face == 1: # -X - d = np.stack([-np.ones_like(u), -v, u], axis=-1) - elif face == 2: # +Y - d = np.stack([u, np.ones_like(u), v], axis=-1) - elif face == 3: # -Y - d = np.stack([u, -np.ones_like(u), -v], axis=-1) - elif face == 4: # +Z - d = np.stack([u, -v, np.ones_like(u)], axis=-1) - elif face == 5: # -Z - d = np.stack([-u, -v, -np.ones_like(u)], axis=-1) - else: - raise ValueError(face) - return normalize(d) - - -def normalize(v: np.ndarray) -> np.ndarray: - return v / np.maximum(np.linalg.norm(v, axis=-1, keepdims=True), 1e-20) - - -def tangent_basis(n: np.ndarray) -> tuple[np.ndarray, np.ndarray]: - up = np.zeros_like(n) - up[..., 1] = 1.0 - alt = np.zeros_like(n) - alt[..., 2] = 1.0 - use_alt = np.abs(n[..., 1:2]) > 0.98 - up = np.where(use_alt, alt, up) - tangent = normalize(np.cross(up, n)) - bitangent = np.cross(n, tangent) - return tangent, bitangent - - -def sample_latlong(env: np.ndarray, directions: np.ndarray) -> np.ndarray: - height, width, _ = env.shape - d = normalize(directions) - u = np.mod(np.arctan2(d[..., 2], d[..., 0]) / (2.0 * math.pi) + 0.5, 1.0) * width - 0.5 - v = np.arccos(np.clip(d[..., 1], -1.0, 1.0)) / math.pi * height - 0.5 - - x0 = np.floor(u).astype(np.int32) - y0 = np.floor(v).astype(np.int32) - tx = (u - x0)[..., None] - ty = (v - y0)[..., None] - x0 %= width - x1 = (x0 + 1) % width - y0 = np.clip(y0, 0, height - 1) - y1 = np.clip(y0 + 1, 0, height - 1) - - c00 = env[y0, x0] - c10 = env[y0, x1] - c01 = env[y1, x0] - c11 = env[y1, x1] - return (c00 * (1.0 - tx) + c10 * tx) * (1.0 - ty) + (c01 * (1.0 - tx) + c11 * tx) * ty - - -def prefilter_face(env: np.ndarray, face: int, size: int, roughness: float, sample_count: int) -> np.ndarray: - n = face_directions(face, size) - if roughness <= 0.0001: - return sample_latlong(env, n).astype(np.float32) - - tangent, bitangent = tangent_basis(n) - v = n - alpha = max(roughness * roughness, 0.001) - result = np.zeros((size, size, 3), dtype=np.float32) - weight_sum = np.zeros((size, size, 1), dtype=np.float32) - - for xi1, xi2 in hammersley(sample_count): - phi = 2.0 * math.pi * float(xi1) - cos_theta = math.sqrt((1.0 - float(xi2)) / (1.0 + (alpha * alpha - 1.0) * float(xi2))) - sin_theta = math.sqrt(max(0.0, 1.0 - cos_theta * cos_theta)) - h = normalize( - tangent * (math.cos(phi) * sin_theta) - + bitangent * (math.sin(phi) * sin_theta) - + n * cos_theta - ) - l = normalize(2.0 * np.sum(v * h, axis=-1, keepdims=True) * h - v) - ndotl = np.maximum(np.sum(n * l, axis=-1, keepdims=True), 0.0).astype(np.float32) - result += sample_latlong(env, l) * ndotl - weight_sum += ndotl - - return result / np.maximum(weight_sum, 1e-6) - - -def irradiance_face(env: np.ndarray, face: int, size: int, sample_count: int) -> np.ndarray: - n = face_directions(face, size) - tangent, bitangent = tangent_basis(n) - result = np.zeros((size, size, 3), dtype=np.float32) - - for xi1, xi2 in hammersley(sample_count): - radius = math.sqrt(float(xi1)) - phi = 2.0 * math.pi * float(xi2) - direction = normalize( - tangent * (math.cos(phi) * radius) - + bitangent * (math.sin(phi) * radius) - + n * math.sqrt(max(0.0, 1.0 - float(xi1))) - ) - result += sample_latlong(env, direction) - - return result * (math.pi / sample_count) - - -def dds_header(width: int, height: int, mip_count: int) -> bytes: - flags = 0x1 | 0x2 | 0x4 | 0x8 | 0x1000 | 0x20000 - caps = 0x1000 | 0x8 | 0x400000 - caps2 = 0x200 | 0x400 | 0x800 | 0x1000 | 0x2000 | 0x4000 | 0x8000 - pitch = width * 8 - pixel_format = struct.pack("<8I", 32, 0x4, int.from_bytes(b"DX10", "little"), 0, 0, 0, 0, 0) - header = struct.pack( - "<7I11I", - 124, - flags, - height, - width, - pitch, - 0, - mip_count, - *([0] * 11), - ) - header += pixel_format - header += struct.pack("<5I", caps, caps2, 0, 0, 0) - dx10 = struct.pack( - "<5I", - DXGI_FORMAT_R16G16B16A16_FLOAT, - D3D10_RESOURCE_DIMENSION_TEXTURE2D, - D3D11_RESOURCE_MISC_TEXTURECUBE, - 1, - 0, - ) - return b"DDS " + header + dx10 - - -def write_dds(path: Path, mip_faces: list[list[np.ndarray]]) -> None: - base_size = mip_faces[0][0].shape[0] - payload = bytearray(dds_header(base_size, base_size, len(mip_faces))) - for face in range(6): - for mip in mip_faces: - rgb = np.maximum(mip[face], 0.0).astype(np.float16) - alpha = np.ones(rgb.shape[:2] + (1,), dtype=np.float16) - payload.extend(np.concatenate([rgb, alpha], axis=-1).tobytes()) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(payload) - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("input", type=Path) - parser.add_argument("output", type=Path) - parser.add_argument("--mode", choices=["specular", "irradiance"], default="specular") - parser.add_argument("--size", type=int, default=256) - parser.add_argument("--samples", type=int, default=128) - args = parser.parse_args() - - if args.size <= 0 or args.size & (args.size - 1): - raise ValueError("--size must be a power of two") - - env = read_radiance_hdr(args.input) - if args.mode == "irradiance": - print(f"irradiance: {args.size}x{args.size}, samples={args.samples}") - write_dds( - args.output, - [[irradiance_face(env, face, args.size, args.samples) for face in range(6)]]) - print(f"wrote {args.output}") - return - - mip_count = int(math.log2(args.size)) + 1 - mip_faces: list[list[np.ndarray]] = [] - for mip_index in range(mip_count): - size = max(1, args.size >> mip_index) - roughness = mip_index / max(1, mip_count - 1) - sample_count = 1 if mip_index == 0 else max(32, int(args.samples * (0.5 + roughness * 0.5))) - print(f"mip {mip_index}/{mip_count - 1}: {size}x{size}, roughness={roughness:.3f}, samples={sample_count}") - mip_faces.append([ - prefilter_face(env, face, size, roughness, sample_count) - for face in range(6) - ]) - - write_dds(args.output, mip_faces) - print(f"wrote {args.output}") - - -if __name__ == "__main__": - main() diff --git a/scripts/capture-fensalir-frame.ps1 b/scripts/capture-fensalir-frame.ps1 deleted file mode 100644 index 8ca2d3c..0000000 --- a/scripts/capture-fensalir-frame.ps1 +++ /dev/null @@ -1,88 +0,0 @@ -param( - [string]$OutputPath, - [int]$Width = 1280, - [int]$Height = 720, - [int]$ReadyFrames = 8, - [int]$RetainSlots = 4, - [int]$TimeoutSeconds = 120 -) - -$ErrorActionPreference = "Stop" -Set-StrictMode -Version Latest - -$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..") -if ([string]::IsNullOrWhiteSpace($OutputPath)) { - $OutputPath = Join-Path $repoRoot ("artifacts\fensalir-captures\fensalir-fixed-" + (Get-Date -Format "yyyyMMdd-HHmmss") + ".png") -} - -$OutputPath = [System.IO.Path]::GetFullPath($OutputPath) -$clientProject = Join-Path $repoRoot "src\Aquarium.Fensalir\Aquarium.Fensalir.csproj" -$devRoot = Join-Path $repoRoot "artifacts\dev-reload" -$slotRoot = Join-Path $devRoot "slots" -$slotPath = Join-Path $slotRoot ("fensalir-capture-" + (Get-Date -Format "yyyyMMdd-HHmmss") + "-" + [guid]::NewGuid().ToString("N").Substring(0, 8)) -$cachePath = Join-Path $devRoot "fensalir-capture-cultcache\aquarium-client.msgpack" -$stdoutLog = Join-Path $devRoot "fensalir-capture.out.log" -$stderrLog = Join-Path $devRoot "fensalir-capture.err.log" - -New-Item -ItemType Directory -Force -Path $slotPath | Out-Null -New-Item -ItemType Directory -Force -Path (Split-Path $cachePath) | Out-Null -New-Item -ItemType Directory -Force -Path (Split-Path $OutputPath) | Out-Null - -Write-Host "Building Fensalir capture slot:" -Write-Host " $slotPath" -dotnet build (Join-Path $repoRoot "src\Aquarium.Engine\Aquarium.Engine.csproj") -c Debug -o $slotPath /p:UseAppHost=true -if ($LASTEXITCODE -ne 0) { - throw "Engine build failed with exit code $LASTEXITCODE." -} - -dotnet build $clientProject -c Debug -o $slotPath /p:UseAppHost=false -if ($LASTEXITCODE -ne 0) { - throw "Fensalir client build failed with exit code $LASTEXITCODE." -} - -$exePath = Join-Path $slotPath "Aquarium.Engine.exe" -$clientAssembly = Join-Path $slotPath "Aquarium.Fensalir.dll" -$arguments = @( - "--headless", - "--headless-width", $Width, - "--headless-height", $Height, - "--client-assembly", $clientAssembly, - "--cache", $cachePath, - "--shader-source", (Join-Path $slotPath "Render\Shaders\D3D12HeightField.hlsl"), - "--capture-frame", $OutputPath -) - -$env:AQUARIUM_HEADLESS_READY_FRAMES = [string][Math]::Max(1, $ReadyFrames) -$process = Start-Process -FilePath $exePath -ArgumentList $arguments -NoNewWindow -PassThru -RedirectStandardOutput $stdoutLog -RedirectStandardError $stderrLog -if (-not $process.WaitForExit([Math]::Max(1, $TimeoutSeconds) * 1000)) { - $process.Kill($true) - $tail = if (Test-Path $stderrLog) { Get-Content -Path $stderrLog -Tail 80 } else { "" } - throw "Fensalir capture timed out after $TimeoutSeconds seconds.`n$($tail -join [Environment]::NewLine)" -} - -$process.WaitForExit() -$process.Refresh() -$exitCode = $process.ExitCode -if ($null -eq $exitCode -and (Test-Path $OutputPath)) { - $exitCode = 0 -} - -if ($exitCode -ne 0) { - $tail = if (Test-Path $stderrLog) { Get-Content -Path $stderrLog -Tail 80 } else { "" } - throw "Fensalir capture failed with exit code $exitCode.`n$($tail -join [Environment]::NewLine)" -} - -if (-not (Test-Path $OutputPath)) { - throw "Fensalir capture did not produce expected PNG: $OutputPath" -} - -if ($RetainSlots -gt 0) { - Get-ChildItem -Path $slotRoot -Directory -ErrorAction SilentlyContinue | - Where-Object { $_.Name -like "fensalir-capture-*" } | - Sort-Object LastWriteTimeUtc -Descending | - Select-Object -Skip $RetainSlots | - Remove-Item -Recurse -Force -ErrorAction SilentlyContinue -} - -Write-Host "Fensalir frame captured:" -Write-Host " $OutputPath" diff --git a/scripts/dev-reload.ps1 b/scripts/dev-reload.ps1 index fa6a07c..616dda3 100644 --- a/scripts/dev-reload.ps1 +++ b/scripts/dev-reload.ps1 @@ -1,359 +1,11 @@ param( - [switch]$Headless, - [switch]$NoStop, - [switch]$BuildOnly, - [switch]$Reopen, - [string]$ClientProject = "src\Aquarium.Epiphany\Aquarium.Epiphany.csproj", - [int]$RetainSlots = 12, - [int]$StartupTimeoutSeconds = 5, - [int]$HeadlessTimeoutSeconds = 60 + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$RemainingArgs ) -$ErrorActionPreference = "Stop" -Set-StrictMode -Version Latest - $repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..") -$projectPath = Join-Path $repoRoot "src\Aquarium.Engine\Aquarium.Engine.csproj" -$liveProjectPath = if ([System.IO.Path]::IsPathRooted($ClientProject)) { $ClientProject } else { Join-Path $repoRoot $ClientProject } -$liveProjectPath = (Resolve-Path $liveProjectPath).Path -$liveAssemblyName = [System.IO.Path]::GetFileNameWithoutExtension($liveProjectPath) -$devRoot = Join-Path $repoRoot "artifacts\dev-reload" -$slotRoot = Join-Path $devRoot "slots" -$visibleStatePath = Join-Path $devRoot "state.clixml" -$headlessStatePath = Join-Path $devRoot "headless-state.clixml" -$statePath = if ($Headless) { $headlessStatePath } else { $visibleStatePath } -$buildStatePath = Join-Path $devRoot "last-build.clixml" -$liveReloadPointerPath = Join-Path $devRoot "live-current.txt" -$cultCacheDirectory = if ($Headless) { "headless-cultcache" } else { "cultcache" } -$cultCachePath = Join-Path $devRoot "$cultCacheDirectory\aquarium-client.msgpack" -$logName = if ($Headless) { "headless" } else { "latest" } -$stdoutLogPath = Join-Path $devRoot "$logName.out.log" -$stderrLogPath = Join-Path $devRoot "$logName.err.log" +$fensalirRoot = Resolve-Path (Join-Path $repoRoot "..\Fensalir") +$clientProject = Join-Path $repoRoot "src\Aquarium.Epiphany\Aquarium.Epiphany.csproj" +$script = Join-Path $fensalirRoot "scripts\dev-reload.ps1" -New-Item -ItemType Directory -Force -Path $slotRoot | Out-Null -New-Item -ItemType Directory -Force -Path (Split-Path $cultCachePath) | Out-Null - -if ($Reopen -and $Headless) { - throw "-Reopen is for the visible dev window; do not combine it with -Headless." -} - -function Stop-PreviousOwnedProcess { - if ($NoStop -or -not (Test-Path $statePath)) { - return - } - - $state = Import-Clixml -Path $statePath - if (-not ($state.PSObject.Properties.Name -contains "pid")) { - return - } - - if (-not $state.pid) { - return - } - - $process = Get-Process -Id ([int]$state.pid) -ErrorAction SilentlyContinue - if (-not $process) { - return - } - - $recordedPath = [string]$state.slot - $commandLine = $null - try { - $commandLine = (Get-CimInstance Win32_Process -Filter "ProcessId = $($process.Id)").CommandLine - } - catch { - $commandLine = $null - } - - if (-not $commandLine -or $commandLine -notlike "*$recordedPath*") { - Write-Host "Previous PID $($state.pid) no longer belongs to the recorded slot; leaving it alone." - return - } - - Write-Host "Stopping previous script-owned Aquarium process $($state.pid)." - Stop-Process -Id ([int]$state.pid) -Force -} - -function Remove-OldSlots { - if ($RetainSlots -lt 1) { - return - } - - $slots = Get-ChildItem -Path $slotRoot -Directory -ErrorAction SilentlyContinue | - Sort-Object LastWriteTimeUtc -Descending | - Select-Object -Skip $RetainSlots - - foreach ($slot in $slots) { - try { - Remove-Item -LiteralPath $slot.FullName -Recurse -Force - } - catch { - Write-Host "Could not remove old slot $($slot.FullName): $($_.Exception.Message)" - } - } -} - -function Get-StderrTail { - if (-not (Test-Path $stderrLogPath)) { - return "" - } - - $tail = Get-Content -Path $stderrLogPath -Tail 80 -ErrorAction SilentlyContinue - if (-not $tail) { - return "" - } - - return ($tail -join [Environment]::NewLine) -} - -function Wait-ForStartedAquarium { - param( - [System.Diagnostics.Process]$Process, - [bool]$ExpectWindow - ) - - $deadline = (Get-Date).AddSeconds([Math]::Max(1, $StartupTimeoutSeconds)) - while ((Get-Date) -lt $deadline) { - $Process.Refresh() - if ($Process.HasExited) { - throw "Aquarium process exited during startup with code $($Process.ExitCode).`n$(Get-StderrTail)" - } - - if (-not $ExpectWindow) { - return - } - - if ($Process.MainWindowHandle -ne [IntPtr]::Zero) { - return - } - - Start-Sleep -Milliseconds 100 - } - - if ($ExpectWindow) { - try { - Stop-Process -Id $Process.Id -Force -ErrorAction SilentlyContinue - } - catch { - # Best effort cleanup before surfacing the broken reload. - } - - throw "Aquarium process started but did not open a visible window within $StartupTimeoutSeconds seconds.`n$(Get-StderrTail)" - } -} - -function Wait-ForHeadlessAquarium { - param( - [System.Diagnostics.Process]$Process - ) - - $deadline = (Get-Date).AddSeconds([Math]::Max(1, $HeadlessTimeoutSeconds)) - while ((Get-Date) -lt $deadline) { - $Process.Refresh() - if ($Process.HasExited) { - $Process.WaitForExit() - $exitCode = [int]$Process.ExitCode - if ($exitCode -ne 0) { - throw "Headless Aquarium exited with code $exitCode.`n$(Get-StderrTail)" - } - - return - } - - Start-Sleep -Milliseconds 100 - } - - try { - Stop-Process -Id $Process.Id -Force -ErrorAction SilentlyContinue - } - catch { - # Best effort cleanup before surfacing the broken smoke test. - } - - throw "Headless Aquarium did not exit within $HeadlessTimeoutSeconds seconds; killed PID $($Process.Id).`n$(Get-StderrTail)" -} - -function Start-AquariumProcess { - param( - [string]$SlotPath, - [string]$LiveAssemblyPath, - [bool]$RunHeadless - ) - - $exePath = Join-Path $SlotPath "Aquarium.Engine.exe" - if (-not (Test-Path $exePath)) { - throw "Expected apphost does not exist: $exePath" - } - - if (-not (Test-Path $LiveAssemblyPath)) { - throw "Expected client runtime assembly does not exist: $LiveAssemblyPath" - } - - Set-Content -Path $liveReloadPointerPath -Value $LiveAssemblyPath -Encoding UTF8 - - $arguments = @( - "--cache", $cultCachePath, - "--shader-source", (Join-Path $SlotPath "Render\Shaders\D3D12HeightField.hlsl"), - "--client-assembly", $LiveAssemblyPath, - "--client-reload-pointer", $liveReloadPointerPath - ) - if ($RunHeadless) { - $arguments += "--headless" - } - - $startProcessParameters = @{ - FilePath = $exePath - ArgumentList = $arguments - WorkingDirectory = $SlotPath - RedirectStandardOutput = $stdoutLogPath - RedirectStandardError = $stderrLogPath - PassThru = $true - } - - if ($RunHeadless) { - $startProcessParameters.WindowStyle = "Hidden" - } - - return Start-Process @startProcessParameters -} - -function Reopen-VisibleProcess { - if (-not (Test-Path $visibleStatePath)) { - throw "No visible dev-reload state file exists. Run scripts\dev-reload.ps1 once to create a launch slot." - } - - $state = Import-Clixml -Path $visibleStatePath - if (-not $state.slot) { - throw "Visible dev-reload state does not record a slot." - } - - if ($state.PSObject.Properties.Name -contains "pid" -and $state.pid) { - $existing = Get-Process -Id ([int]$state.pid) -ErrorAction SilentlyContinue - if ($existing) { - Write-Host "Visible Aquarium process $($state.pid) is already running." - return - } - } - - $slotPath = [string]$state.slot - $liveAssemblyPath = Join-Path $slotPath "$liveAssemblyName.dll" - if ($state.PSObject.Properties.Name -contains "liveAssembly" -and $state.liveAssembly) { - $liveAssemblyPath = [string]$state.liveAssembly - } - - $process = Start-AquariumProcess -SlotPath $slotPath -LiveAssemblyPath $liveAssemblyPath -RunHeadless:$false - Wait-ForStartedAquarium -Process $process -ExpectWindow:$true - - @{ - slot = $slotPath - builtAt = $state.builtAt - reopenedAt = (Get-Date).ToString("o") - pid = $process.Id - liveAssembly = $liveAssemblyPath - headless = $false - stdoutLog = $stdoutLogPath - stderrLog = $stderrLogPath - } | Export-Clixml -Path $visibleStatePath - - Write-Host "Aquarium reopened from last visible slot." - Write-Host " PID: $($process.Id)" - Write-Host " Slot: $slotPath" - return -} - -if ($Reopen) { - Reopen-VisibleProcess - exit 0 -} - -$timestamp = Get-Date -Format "yyyyMMdd-HHmmss" -$slotName = "$timestamp-$([guid]::NewGuid().ToString("N").Substring(0, 8))" -$slotPath = Join-Path $slotRoot $slotName -New-Item -ItemType Directory -Force -Path $slotPath | Out-Null - -Write-Host "Building Aquarium into disposable slot:" -Write-Host " $slotPath" -dotnet build $projectPath ` - -c Debug ` - -o $slotPath ` - /p:UseAppHost=true -if ($LASTEXITCODE -ne 0) { - throw "dotnet build failed with exit code $LASTEXITCODE." -} - -dotnet build $liveProjectPath ` - -c Debug ` - -o $slotPath -if ($LASTEXITCODE -ne 0) { - throw "client runtime build failed with exit code $LASTEXITCODE." -} - -if ($BuildOnly) { - @{ - slot = $slotPath - builtAt = (Get-Date).ToString("o") - stdoutLog = $stdoutLogPath - stderrLog = $stderrLogPath - } | Export-Clixml -Path $buildStatePath - Write-Host "Build-only slot ready." - Remove-OldSlots - exit 0 -} - -Stop-PreviousOwnedProcess - -$exePath = Join-Path $slotPath "Aquarium.Engine.exe" -$liveAssemblyPath = Join-Path $slotPath "$liveAssemblyName.dll" -if (-not (Test-Path $exePath)) { - throw "Expected apphost was not produced: $exePath" -} - -if (-not (Test-Path $liveAssemblyPath)) { - throw "Expected client runtime assembly was not produced: $liveAssemblyPath" -} - -$process = Start-AquariumProcess -SlotPath $slotPath -LiveAssemblyPath $liveAssemblyPath -RunHeadless:$Headless -if ($Headless) { - Wait-ForHeadlessAquarium -Process $process - - @{ - slot = $slotPath - builtAt = (Get-Date).ToString("o") - liveAssembly = $liveAssemblyPath - headless = $true - stdoutLog = $stdoutLogPath - stderrLog = $stderrLogPath - } | Export-Clixml -Path $statePath - - Write-Host "Headless Aquarium completed from disposable slot." - Write-Host " Slot: $slotPath" - Write-Host " CultCache: $cultCachePath" - Write-Host " Stdout: $stdoutLogPath" - Write-Host " Stderr: $stderrLogPath" - Remove-OldSlots - exit 0 -} - -Wait-ForStartedAquarium -Process $process -ExpectWindow:$true - -@{ - slot = $slotPath - builtAt = (Get-Date).ToString("o") - pid = $process.Id - liveAssembly = $liveAssemblyPath - headless = [bool]$Headless - stdoutLog = $stdoutLogPath - stderrLog = $stderrLogPath -} | Export-Clixml -Path $statePath - -Write-Host "Aquarium running from disposable slot." -Write-Host " PID: $($process.Id)" -Write-Host " CultCache: $cultCachePath" -Write-Host " Stdout: $stdoutLogPath" -Write-Host " Stderr: $stderrLogPath" -Write-Host "Run this script again to replace only this script-owned process." -if (-not $Headless) { - Write-Host "Run with -Reopen to reopen this visible slot without rebuilding." -} - -Remove-OldSlots +& $script -ClientProject $clientProject @RemainingArgs diff --git a/scripts/dev-stop.ps1 b/scripts/dev-stop.ps1 index 0fcaffe..5d3ea70 100644 --- a/scripts/dev-stop.ps1 +++ b/scripts/dev-stop.ps1 @@ -1,39 +1,5 @@ -$ErrorActionPreference = "Stop" -Set-StrictMode -Version Latest - $repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..") -$statePath = Join-Path $repoRoot "artifacts\dev-reload\state.clixml" +$fensalirRoot = Resolve-Path (Join-Path $repoRoot "..\Fensalir") +$script = Join-Path $fensalirRoot "scripts\dev-stop.ps1" -if (-not (Test-Path $statePath)) { - Write-Host "No dev-reload state file exists." - exit 0 -} - -$state = Import-Clixml -Path $statePath -if (-not $state.pid) { - Write-Host "No script-owned Aquarium PID is recorded." - exit 0 -} - -$process = Get-Process -Id ([int]$state.pid) -ErrorAction SilentlyContinue -if (-not $process) { - Write-Host "Recorded Aquarium process $($state.pid) is not running." - exit 0 -} - -$recordedPath = [string]$state.slot -$commandLine = $null -try { - $commandLine = (Get-CimInstance Win32_Process -Filter "ProcessId = $($process.Id)").CommandLine -} -catch { - $commandLine = $null -} - -if (-not $commandLine -or $commandLine -notlike "*$recordedPath*") { - Write-Host "PID $($state.pid) no longer belongs to the recorded slot; leaving it alone." - exit 0 -} - -Write-Host "Stopping script-owned Aquarium process $($state.pid)." -Stop-Process -Id ([int]$state.pid) -Force +& $script diff --git a/scripts/dev-watch.ps1 b/scripts/dev-watch.ps1 index f011862..55ffc73 100644 --- a/scripts/dev-watch.ps1 +++ b/scripts/dev-watch.ps1 @@ -1,561 +1,11 @@ param( - [switch]$Headless, - [switch]$NoInitialLaunch, - [switch]$ReopenWhenClosed, - [switch]$Once, - [string]$ClientProject = "src\Aquarium.Epiphany\Aquarium.Epiphany.csproj", - [int]$IntervalMilliseconds = 1000, - [int]$DebounceMilliseconds = 350, - [int]$RetainSlots = 12, - [int]$LiveReloadAckTimeoutSeconds = 6 + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$RemainingArgs ) -$ErrorActionPreference = "Stop" -Set-StrictMode -Version Latest - $repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..") -$reloadScript = Join-Path $PSScriptRoot "dev-reload.ps1" -$liveProjectPath = if ([System.IO.Path]::IsPathRooted($ClientProject)) { $ClientProject } else { Join-Path $repoRoot $ClientProject } -$liveProjectPath = (Resolve-Path $liveProjectPath).Path -$liveAssemblyName = [System.IO.Path]::GetFileNameWithoutExtension($liveProjectPath) -$clientSourceRoot = Split-Path $liveProjectPath -$watchLogPath = Join-Path $repoRoot "artifacts\dev-reload\watch.log" -$liveSlotRoot = Join-Path $repoRoot "artifacts\dev-reload\live-slots" -$liveReloadPointerPath = Join-Path $repoRoot "artifacts\dev-reload\live-current.txt" -$shaderPath = Join-Path $repoRoot "src\Aquarium.Engine\Render\Shaders\Aquarium.hlsl" -$engineShaderRoot = Join-Path $repoRoot "src\Aquarium.Engine\Render\Shaders" -$clientShaderRoot = Join-Path $clientSourceRoot "Shaders" -$visibleStatePath = Join-Path $repoRoot "artifacts\dev-reload\state.clixml" -$headlessStatePath = Join-Path $repoRoot "artifacts\dev-reload\headless-state.clixml" -$ownedProcessStatePath = if ($Headless) { $headlessStatePath } else { $visibleStatePath } +$fensalirRoot = Resolve-Path (Join-Path $repoRoot "..\Fensalir") +$clientProject = Join-Path $repoRoot "src\Aquarium.Epiphany\Aquarium.Epiphany.csproj" +$script = Join-Path $fensalirRoot "scripts\dev-watch.ps1" -New-Item -ItemType Directory -Force -Path (Split-Path $watchLogPath) | Out-Null -New-Item -ItemType Directory -Force -Path $liveSlotRoot | Out-Null - -if ($Headless -and $ReopenWhenClosed) { - throw "-ReopenWhenClosed is for the visible dev window; do not combine it with -Headless." -} - -function Write-WatchLog([string]$message) { - $line = "$(Get-Date -Format o) $message" - Write-Host $line - Add-Content -Path $watchLogPath -Value $line -} - -function Get-SourceFiles { - $roots = @( - (Join-Path $repoRoot "src"), - (Join-Path $repoRoot "scripts"), - (Join-Path $repoRoot "Aquarium.Engine.sln"), - (Join-Path $repoRoot "global.json") - ) - - foreach ($root in $roots) { - if (-not (Test-Path $root)) { - continue - } - - $item = Get-Item -LiteralPath $root - if (-not $item.PSIsContainer) { - $item - continue - } - - Get-ChildItem -LiteralPath $item.FullName -Recurse -File | - Where-Object { - $_.FullName -notmatch "\\bin\\" -and - $_.FullName -notmatch "\\obj\\" -and - $_.FullName -notmatch "\\artifacts\\" -and - ( - $_.Extension -in @(".cs", ".csproj", ".json", ".sln", ".ps1") -or - $_.FullName -like (Join-Path $repoRoot "src\Aquarium.Engine\Assets\*") - ) - } - } -} - -function Get-ShaderFiles { - foreach ($root in @($engineShaderRoot, $clientShaderRoot)) { - if (-not (Test-Path $root)) { - continue - } - - Get-ChildItem -LiteralPath $root -Recurse -File | - Where-Object { $_.Extension -in @(".hlsl", ".hlsli") } - } -} - -function Get-LiveFiles { - Get-SourceFiles | Where-Object { - $_.FullName -like (Join-Path $clientSourceRoot "*") - } -} - -function Get-RestartFiles { - Get-SourceFiles | Where-Object { - $_.FullName -notlike (Join-Path $clientSourceRoot "*") - } -} - -function Get-Fingerprint($files) { - $fingerprintInput = $files | - Sort-Object FullName | - ForEach-Object { - "$($_.FullName)|$($_.Length)|$($_.LastWriteTimeUtc.Ticks)" - } - - $text = [string]::Join("`n", $fingerprintInput) - $bytes = [System.Text.Encoding]::UTF8.GetBytes($text) - $sha = [System.Security.Cryptography.SHA256]::Create() - try { - $hashBytes = $sha.ComputeHash($bytes) - return -join ($hashBytes | ForEach-Object { $_.ToString("x2") }) - } - finally { - $sha.Dispose() - } -} - -function Get-Hash([string]$text) { - $bytes = [System.Text.Encoding]::UTF8.GetBytes($text) - $sha = [System.Security.Cryptography.SHA256]::Create() - try { - $hashBytes = $sha.ComputeHash($bytes) - return -join ($hashBytes | ForEach-Object { $_.ToString("x2") }) - } - finally { - $sha.Dispose() - } -} - -function Get-AquariumFrameContractText { - if (-not (Test-Path $shaderPath)) { - return "" - } - - $text = Get-Content -Raw -LiteralPath $shaderPath - $match = [regex]::Match( - $text, - "cbuffer\s+AquariumFrame\s*:\s*register\(b0\)\s*\{(?.*?)\};", - [System.Text.RegularExpressions.RegexOptions]::Singleline) - if (-not $match.Success) { - return "" - } - - return $match.Value -} - -function Get-SourceFingerprint { - $fileFingerprint = Get-Fingerprint (Get-SourceFiles) - $contractFingerprint = Get-Hash (Get-AquariumFrameContractText) - Get-Hash "$fileFingerprint`nAquariumFrame:$contractFingerprint" -} - -function Get-ShaderFingerprint { - Get-Fingerprint (Get-ShaderFiles) -} - -function Get-AllFingerprint { - $sourceFingerprint = Get-SourceFingerprint - $shaderFingerprint = Get-ShaderFingerprint - Get-Hash "$sourceFingerprint`nShaders:$shaderFingerprint" -} - -function Get-LiveFingerprint { - Get-Fingerprint (Get-LiveFiles) -} - -function Get-RestartFingerprint { - $fileFingerprint = Get-Fingerprint (Get-RestartFiles) - $contractFingerprint = Get-Hash (Get-AquariumFrameContractText) - Get-Hash "$fileFingerprint`nAquariumFrame:$contractFingerprint" -} - -function Wait-StableFingerprints { - $first = @{ - all = Get-AllFingerprint - live = Get-LiveFingerprint - restart = Get-RestartFingerprint - shaders = Get-ShaderFingerprint - } - Start-Sleep -Milliseconds $DebounceMilliseconds - $second = @{ - all = Get-AllFingerprint - live = Get-LiveFingerprint - restart = Get-RestartFingerprint - shaders = Get-ShaderFingerprint - } - - while ($first.all -ne $second.all) { - $first = $second - Start-Sleep -Milliseconds $DebounceMilliseconds - $second = @{ - all = Get-AllFingerprint - live = Get-LiveFingerprint - restart = Get-RestartFingerprint - shaders = Get-ShaderFingerprint - } - } - - return $second -} - -function Invoke-Reload { - param([string]$reason) - - Write-WatchLog "Reload requested: $reason" - - $arguments = @( - "-NoProfile", - "-ExecutionPolicy", "Bypass", - "-File", $reloadScript, - "-ClientProject", $liveProjectPath, - "-RetainSlots", "$RetainSlots" - ) - - if ($Headless) { - $arguments += "-Headless" - } - - Push-Location $repoRoot - try { - & powershell @arguments - if ($LASTEXITCODE -ne 0) { - throw "dev-reload failed with exit code $LASTEXITCODE." - } - } - finally { - Pop-Location - } -} - -function Get-OwnedProcessState { - if (-not (Test-Path $ownedProcessStatePath)) { - return $null - } - - try { - return Import-Clixml -Path $ownedProcessStatePath - } - catch { - Write-WatchLog "Could not read script-owned process state. $($_.Exception.Message)" - return $null - } -} - -function Test-RecordedProcessRunning { - $state = Get-OwnedProcessState - if (-not $state -or -not $state.pid -or -not $state.slot) { - return $false - } - - $process = Get-Process -Id ([int]$state.pid) -ErrorAction SilentlyContinue - if (-not $process) { - return $false - } - - $recordedPath = [string]$state.slot - $commandLine = $null - try { - $commandLine = (Get-CimInstance Win32_Process -Filter "ProcessId = $($process.Id)").CommandLine - } - catch { - $commandLine = $null - } - - return [bool]($commandLine -and $commandLine -like "*$recordedPath*") -} - -function Test-OwnedProcessRunning { - if ($NoInitialLaunch) { - return $true - } - - return Test-RecordedProcessRunning -} - -function Invoke-Reopen { - param([string]$reason) - - if ($Headless) { - Invoke-Reload $reason - return - } - - Write-WatchLog "Reopen requested: $reason" - - $arguments = @( - "-NoProfile", - "-ExecutionPolicy", "Bypass", - "-File", $reloadScript, - "-Reopen", - "-ClientProject", $liveProjectPath, - "-RetainSlots", "$RetainSlots" - ) - - Push-Location $repoRoot - try { - & powershell @arguments - if ($LASTEXITCODE -ne 0) { - throw "dev-reload -Reopen failed with exit code $LASTEXITCODE." - } - } - finally { - Pop-Location - } -} - -function Invoke-LiveReload { - param([string]$reason) - - $timestamp = Get-Date -Format "yyyyMMdd-HHmmss" - $liveSlot = Join-Path $liveSlotRoot "$timestamp-$([guid]::NewGuid().ToString("N").Substring(0, 8))" - New-Item -ItemType Directory -Force -Path $liveSlot | Out-Null - - Write-WatchLog "Live reload requested: $reason" - dotnet build $liveProjectPath -c Debug -o $liveSlot - if ($LASTEXITCODE -ne 0) { - throw "client runtime build failed with exit code $LASTEXITCODE." - } - - $liveAssemblyPath = Join-Path $liveSlot "$liveAssemblyName.dll" - if (-not (Test-Path $liveAssemblyPath)) { - throw "Expected client runtime assembly was not produced: $liveAssemblyPath" - } - - Set-Content -Path $liveReloadPointerPath -Value $liveAssemblyPath -Encoding UTF8 - Write-WatchLog "Live reload pointer updated: $liveAssemblyPath" - Wait-LiveReloadAcknowledged $liveAssemblyPath -} - -function Copy-ShaderTree { - param( - [string]$SourceRoot, - [string]$DestinationRoot - ) - - if (-not (Test-Path $SourceRoot)) { - return - } - - Get-ChildItem -LiteralPath $SourceRoot -Recurse -File | - Where-Object { $_.Extension -in @(".hlsl", ".hlsli") } | - ForEach-Object { - $relativePath = [System.IO.Path]::GetRelativePath($SourceRoot, $_.FullName) - $destinationPath = Join-Path $DestinationRoot $relativePath - $destinationDirectory = Split-Path $destinationPath - New-Item -ItemType Directory -Force -Path $destinationDirectory | Out-Null - Copy-Item -LiteralPath $_.FullName -Destination $destinationPath -Force - } -} - -function Read-LogTextAfterLength { - param( - [string]$Path, - [long]$StartLength - ) - - if (-not (Test-Path $Path)) { - return "" - } - - $stream = [System.IO.File]::Open($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite) - try { - if ($StartLength -gt 0 -and $StartLength -lt $stream.Length) { - $stream.Seek($StartLength, [System.IO.SeekOrigin]::Begin) | Out-Null - } - elseif ($StartLength -ge $stream.Length) { - return "" - } - - $reader = [System.IO.StreamReader]::new($stream) - try { - return $reader.ReadToEnd() - } - finally { - $reader.Dispose() - } - } - finally { - $stream.Dispose() - } -} - -function Wait-ShaderHotReloadAcknowledged { - param( - [string]$StdoutLog, - [string]$StderrLog, - [long]$StdoutStartLength, - [long]$StderrStartLength - ) - - $deadline = (Get-Date).AddSeconds([Math]::Max(1, $LiveReloadAckTimeoutSeconds)) - while ((Get-Date) -lt $deadline) { - $stdoutText = Read-LogTextAfterLength -Path $StdoutLog -StartLength $StdoutStartLength - if ($stdoutText -match "D3D12 shader hot reload applied") { - Write-WatchLog "Shader hot reload acknowledged by renderer." - return - } - - $stderrText = Read-LogTextAfterLength -Path $StderrLog -StartLength $StderrStartLength - if ($stderrText -match "D3D12 shader hot reload failed") { - throw "renderer reported shader hot reload failure. See $StderrLog" - } - - Start-Sleep -Milliseconds 250 - } - - throw "shader files were copied, but renderer did not acknowledge hot reload within $LiveReloadAckTimeoutSeconds seconds. Check $StdoutLog and $StderrLog." -} - -function Invoke-ShaderHotReload { - param([string]$reason) - - Write-WatchLog "Shader hot reload requested: $reason" - - $state = Get-OwnedProcessState - if (-not $state -or -not $state.slot) { - throw "no script-owned process slot is recorded for shader hot reload." - } - - if (-not (Test-RecordedProcessRunning)) { - throw "no script-owned process is running to receive shader hot reload." - } - - $slotPath = [string]$state.slot - $shaderDestinationRoot = Join-Path $slotPath "Render\Shaders" - New-Item -ItemType Directory -Force -Path $shaderDestinationRoot | Out-Null - - $stdoutLog = if ($state.PSObject.Properties.Name -contains "stdoutLog" -and $state.stdoutLog) { [string]$state.stdoutLog } else { $stdoutLogPath } - $stderrLog = if ($state.PSObject.Properties.Name -contains "stderrLog" -and $state.stderrLog) { [string]$state.stderrLog } else { $stderrLogPath } - $stdoutStartLength = if (Test-Path $stdoutLog) { (Get-Item -LiteralPath $stdoutLog).Length } else { 0 } - $stderrStartLength = if (Test-Path $stderrLog) { (Get-Item -LiteralPath $stderrLog).Length } else { 0 } - - Copy-ShaderTree -SourceRoot $engineShaderRoot -DestinationRoot $shaderDestinationRoot - Copy-ShaderTree -SourceRoot $clientShaderRoot -DestinationRoot $shaderDestinationRoot - Write-WatchLog "Shader files copied into running slot: $shaderDestinationRoot" - - Wait-ShaderHotReloadAcknowledged -StdoutLog $stdoutLog -StderrLog $stderrLog -StdoutStartLength $stdoutStartLength -StderrStartLength $stderrStartLength -} - -function Wait-LiveReloadAcknowledged { - param([string]$liveAssemblyPath) - - if (-not (Test-RecordedProcessRunning)) { - throw "live reload pointer was updated, but no script-owned process is running to load it." - } - - $state = Get-OwnedProcessState - if (-not $state -or -not $state.stdoutLog) { - Write-WatchLog "Live reload acknowledgement skipped: no running process log is recorded." - return - } - - $stdoutLog = [string]$state.stdoutLog - $stderrLog = if ($state.stderrLog) { [string]$state.stderrLog } else { $null } - $timeoutSeconds = [Math]::Max(1, $LiveReloadAckTimeoutSeconds) - $deadline = (Get-Date).AddSeconds($timeoutSeconds) - $appliedLine = "Client runtime reload applied: $liveAssemblyPath" - - while ((Get-Date) -lt $deadline) { - if (Test-Path $stdoutLog) { - $stdoutTail = (Get-Content -Path $stdoutLog -Tail 120 -ErrorAction SilentlyContinue) -join "`n" - if ($stdoutTail.Contains($appliedLine)) { - Write-WatchLog "Live reload acknowledged by host: $liveAssemblyPath" - return - } - } - - if ($stderrLog -and (Test-Path $stderrLog)) { - $stderrTail = (Get-Content -Path $stderrLog -Tail 120 -ErrorAction SilentlyContinue) -join "`n" - if ($stderrTail -match "Client runtime reload failed") { - throw "host reported client runtime reload failure. See $stderrLog" - } - } - - Start-Sleep -Milliseconds 250 - } - - throw "live reload pointer was updated, but host did not acknowledge loading $liveAssemblyPath within $timeoutSeconds seconds. Check $stdoutLog and $stderrLog." -} - -$lastGoodFingerprint = Wait-StableFingerprints -$lastFailedFingerprint = $null - -if (-not $NoInitialLaunch) { - try { - Invoke-Reload "initial launch" - $lastGoodFingerprint = Wait-StableFingerprints - $lastFailedFingerprint = $null - } - catch { - $lastFailedFingerprint = $lastGoodFingerprint.all - Write-WatchLog "Initial launch failed; keeping any previous good process alive. $($_.Exception.Message)" - } -} - -Write-WatchLog "Watching Aquarium sources. Press Ctrl+C to stop." - -do { - Start-Sleep -Milliseconds $IntervalMilliseconds - $currentFingerprint = Wait-StableFingerprints - - if (-not (Test-OwnedProcessRunning)) { - try { - if ($ReopenWhenClosed) { - Invoke-Reopen "script-owned process is not running" - } - else { - Invoke-Reload "script-owned process is not running" - } - - $lastGoodFingerprint = Wait-StableFingerprints - $lastFailedFingerprint = $null - $currentFingerprint = $lastGoodFingerprint - } - catch { - $lastFailedFingerprint = $currentFingerprint.all - Write-WatchLog "Relaunch failed; watcher remains alive. $($_.Exception.Message)" - } - - if ($Once) { - break - } - } - - if ($currentFingerprint.all -eq $lastGoodFingerprint.all -or $currentFingerprint.all -eq $lastFailedFingerprint) { - if ($Once) { - break - } - - continue - } - - try { - if ($currentFingerprint.restart -eq $lastGoodFingerprint.restart -and - $currentFingerprint.live -eq $lastGoodFingerprint.live -and - $currentFingerprint.shaders -ne $lastGoodFingerprint.shaders) { - Invoke-ShaderHotReload "shader source change" - } - elseif ($currentFingerprint.restart -eq $lastGoodFingerprint.restart -and $currentFingerprint.live -ne $lastGoodFingerprint.live) { - Invoke-LiveReload "live source change" - if ($currentFingerprint.shaders -ne $lastGoodFingerprint.shaders) { - Invoke-ShaderHotReload "shader source change accompanying live reload" - } - } - else { - Invoke-Reload "host/core/content source change" - } - - $lastGoodFingerprint = $currentFingerprint - $lastFailedFingerprint = $null - } - catch { - $lastFailedFingerprint = $currentFingerprint.all - Write-WatchLog "Reload failed; previous good process stays alive. $($_.Exception.Message)" - } - - if ($Once) { - break - } -} while ($true) +& $script -ClientProject $clientProject @RemainingArgs diff --git a/scripts/fractal-flame-jwildfire-reference.ps1 b/scripts/fractal-flame-jwildfire-reference.ps1 deleted file mode 100644 index 0ae50fa..0000000 --- a/scripts/fractal-flame-jwildfire-reference.ps1 +++ /dev/null @@ -1,124 +0,0 @@ -param( - [ValidateSet("Auto", "FARender", "JWildfireJava")] - [string]$Renderer = "Auto", - [string]$JWildfireRoot = $env:AQUARIUM_JWILDFIRE_ROOT, - [string]$FARender = $env:AQUARIUM_FARENDER, - [string]$JWildfireJar = $env:AQUARIUM_JWILDFIRE_JAR, - [string]$Java = $env:AQUARIUM_JAVA, - [string]$Flame = "artifacts\reference-tools\j-wildfire-9.00\lib\FARenderJWF\selftest.flame", - [int]$Width = 1024, - [int]$Height = 1024, - [int]$Quality = 5000, - [string]$OutputDirectory = "artifacts\fractal-flame-jwildfire-reference", - [switch]$NoCuda, - [switch]$NoDensityEstimation -) - -$ErrorActionPreference = "Stop" -$repoRoot = Split-Path -Parent $PSScriptRoot - -if ([string]::IsNullOrWhiteSpace($JWildfireRoot)) { - $defaultRoot = Join-Path $repoRoot "artifacts\reference-tools\j-wildfire-9.00" - if (Test-Path $defaultRoot) { - $JWildfireRoot = $defaultRoot - } -} - -$flameInput = if ([System.IO.Path]::IsPathRooted($Flame)) { $Flame } else { Join-Path $repoRoot $Flame } -$flamePath = (Resolve-Path $flameInput).Path -$outDir = if ([System.IO.Path]::IsPathRooted($OutputDirectory)) { $OutputDirectory } else { Join-Path $repoRoot $OutputDirectory } -New-Item -ItemType Directory -Force -Path $outDir | Out-Null - -if ([string]::IsNullOrWhiteSpace($FARender) -and -not [string]::IsNullOrWhiteSpace($JWildfireRoot)) { - $candidate = Join-Path $JWildfireRoot "lib\FARenderJWF\FARender.exe" - if (Test-Path $candidate) { - $FARender = $candidate - } -} - -if ([string]::IsNullOrWhiteSpace($JWildfireJar) -and -not [string]::IsNullOrWhiteSpace($JWildfireRoot)) { - $candidate = Join-Path $JWildfireRoot "lib\j-wildfire.jar" - if (Test-Path $candidate) { - $JWildfireJar = $candidate - } -} - -if ($Renderer -eq "Auto") { - $Renderer = if (-not [string]::IsNullOrWhiteSpace($FARender)) { "FARender" } else { "JWildfireJava" } -} - -$stamp = Get-Date -Format "yyyyMMdd-HHmmss" - -if ($Renderer -eq "FARender") { - if ([string]::IsNullOrWhiteSpace($FARender)) { - throw "Set -FARender, AQUARIUM_FARENDER, or AQUARIUM_JWILDFIRE_ROOT. FARender is the preferred scriptable GPU visual reference." - } - - $farenderPath = (Resolve-Path $FARender).Path - $baseName = [System.IO.Path]::GetFileNameWithoutExtension($flamePath) - $outputPath = Join-Path $outDir "$baseName-farender-$stamp.png" - $arguments = @($Width, $Height, $flamePath, "-o", $outputPath, "-q", $Quality) - if ($NoDensityEstimation) { - $arguments += "-nde" - } - - if (-not $NoCuda) { - $arguments += "-cuda" - } - - Push-Location (Split-Path -Parent $farenderPath) - try { - & $farenderPath @arguments - } - finally { - Pop-Location - } - - if ($LASTEXITCODE -ne 0) { - throw "FARender failed with exit code $LASTEXITCODE." - } - - $rendered = Get-Item $outputPath -ErrorAction SilentlyContinue - if ($null -eq $rendered -or $rendered.Length -le 0) { - throw "FARender reported success but did not produce a non-empty image at $outputPath." - } - - Write-Host "JWildfire FARender reference image: $outputPath" - exit 0 -} - -if ([string]::IsNullOrWhiteSpace($Java)) { - $localJava = Get-ChildItem (Join-Path $repoRoot "artifacts\reference-tools\temurin-jre-17") -Recurse -Filter java.exe -ErrorAction SilentlyContinue | Select-Object -First 1 - if ($null -ne $localJava) { - $Java = $localJava.FullName - } - else { - $javaCommand = Get-Command java -ErrorAction SilentlyContinue - if ($null -eq $javaCommand) { - throw "Set -Java or AQUARIUM_JAVA to a Java executable. JWildfire's Java renderer needs Java." - } - - $Java = $javaCommand.Source - } -} - -if ([string]::IsNullOrWhiteSpace($JWildfireJar)) { - throw "Set -JWildfireJar, AQUARIUM_JWILDFIRE_JAR, or AQUARIUM_JWILDFIRE_ROOT to a local JWildfire install." -} - -$jarPath = (Resolve-Path $JWildfireJar).Path -$batchDir = Join-Path $outDir "jwildfire-batch-$stamp" -New-Item -ItemType Directory -Force -Path $batchDir | Out-Null -Copy-Item -LiteralPath $flamePath -Destination (Join-Path $batchDir (Split-Path -Leaf $flamePath)) - -& $Java -cp $jarPath org.jwildfire.create.tina.batch.HeadlessBatchRendererController $batchDir $Width $Height $Quality -if ($LASTEXITCODE -ne 0) { - throw "JWildfire headless renderer failed with exit code $LASTEXITCODE." -} - -$renderedImages = Get-ChildItem $batchDir -Include *.png,*.jpg,*.jpeg -Recurse -ErrorAction SilentlyContinue -if ($renderedImages.Count -eq 0) { - Write-Warning "JWildfire Java batch completed, but no image was written into the batch directory. Check JWildfire's configured output folder or use -Renderer FARender for explicit -o output." -} - -Write-Host "JWildfire reference render directory: $batchDir" diff --git a/scripts/fractal-flame-receipt.ps1 b/scripts/fractal-flame-receipt.ps1 deleted file mode 100644 index e8df9d5..0000000 --- a/scripts/fractal-flame-receipt.ps1 +++ /dev/null @@ -1,19 +0,0 @@ -param( - [string]$Flame = "tests\Aquarium.Engine.Fractal.Tests\Fixtures\Apophysis\linear-spherical-bubble.flame", - [int]$Samples = 8192, - [int]$BurnIn = 64, - [string]$HistogramSize = "64x64", - [string]$Bounds = "-8,-8,8,8", - [string]$Seed = "0x0BADC0DE" -) - -$ErrorActionPreference = "Stop" -$repoRoot = Split-Path -Parent $PSScriptRoot -dotnet run --project (Join-Path $repoRoot "tools\Aquarium.Fractal.Receipt\Aquarium.Fractal.Receipt.csproj") -c Release -- ` - --flame (Join-Path $repoRoot $Flame) ` - --histogram-samples $Samples ` - --histogram-burn-in $BurnIn ` - --histogram-size $HistogramSize ` - --histogram-bounds $Bounds ` - --seed $Seed ` - --out (Join-Path $repoRoot "artifacts\fractal-flame-receipts") diff --git a/scripts/fractal-flame-reference-render.ps1 b/scripts/fractal-flame-reference-render.ps1 deleted file mode 100644 index 05cb922..0000000 --- a/scripts/fractal-flame-reference-render.ps1 +++ /dev/null @@ -1,62 +0,0 @@ -param( - [string]$Flam3Render = $env:AQUARIUM_FLAM3_RENDER, - [string]$Flame = "tests\Aquarium.Engine.Fractal.Tests\Fixtures\Apophysis\linear-spherical-bubble.flame", - [string]$Seed = "0x0BADC0DE", - [string]$QualityScale = "1", - [string]$OutputDirectory = "artifacts\fractal-flame-reference" -) - -$ErrorActionPreference = "Stop" -$repoRoot = Split-Path -Parent $PSScriptRoot - -if ([string]::IsNullOrWhiteSpace($Flam3Render)) { - throw "Set -Flam3Render or AQUARIUM_FLAM3_RENDER to a local flam3-render executable. Aquarium does not vendor FLAM3 or Apophysis." -} - -$rendererCommand = Get-Command $Flam3Render -ErrorAction SilentlyContinue -if ($null -eq $rendererCommand) { - throw "Could not find flam3-render executable: $Flam3Render" -} - -$renderer = $rendererCommand.Source -$flameInput = if ([System.IO.Path]::IsPathRooted($Flame)) { $Flame } else { Join-Path $repoRoot $Flame } -$flamePath = (Resolve-Path $flameInput).Path -$outDir = Join-Path $repoRoot $OutputDirectory -New-Item -ItemType Directory -Force -Path $outDir | Out-Null - -$stamp = Get-Date -Format "yyyyMMdd-HHmmss" -$imagePath = Join-Path $outDir "flam3-reference-$stamp.ppm" - -$previous = @{ - in = $env:in - out = $env:out - format = $env:format - seed = $env:seed - qs = $env:qs - verbose = $env:verbose -} - -try { - $env:in = $flamePath - $env:out = $imagePath - $env:format = "ppm" - $env:seed = $Seed - $env:qs = $QualityScale - $env:verbose = "0" - & $renderer - if ($LASTEXITCODE -ne 0) { - throw "flam3-render failed with exit code $LASTEXITCODE." - } -} -finally { - $env:in = $previous.in - $env:out = $previous.out - $env:format = $previous.format - $env:seed = $previous.seed - $env:qs = $previous.qs - $env:verbose = $previous.verbose -} - -dotnet run --project (Join-Path $repoRoot "tools\Aquarium.Fractal.Receipt\Aquarium.Fractal.Receipt.csproj") -c Release -- ` - --reference-ppm $imagePath ` - --out $outDir diff --git a/scripts/fractal-splat-receipt.ps1 b/scripts/fractal-splat-receipt.ps1 deleted file mode 100644 index 3b0f505..0000000 --- a/scripts/fractal-splat-receipt.ps1 +++ /dev/null @@ -1,65 +0,0 @@ -param( - [int]$Splats = 2000000, - [int]$WarmupSplatUpdates = 2000000, - [int]$SplatUpdates = 2000000, - [int]$Warmup = 30, - [int]$Frames = 120, - [int]$Depth = 8, - [int]$Candidates = 2, - [int]$ReservoirUpdates = 50000, - [int]$ProgramTransforms = 0, - [string]$ProgramFlame = "", - [switch]$VisualParity, - [int]$VisualParityReferenceSamples = 1000000, - [string]$HistogramSize = "64x64", - [string]$HistogramBounds = "-8,-8,8,8", - [string]$ReferenceDensityPpm = "", - [string[]]$VisualParityView = @(), - [string]$VisualParityImageDirectory = "", - [string]$VisualParityImagePrefix = "visual-parity", - [int]$ReadbackSplats = 64 -) - -$ErrorActionPreference = "Stop" -$repoRoot = Split-Path -Parent $PSScriptRoot -$programArgs = @("--program-transforms", "$ProgramTransforms") -if (-not [string]::IsNullOrWhiteSpace($ProgramFlame)) { - $programFlamePath = if ([System.IO.Path]::IsPathRooted($ProgramFlame)) { $ProgramFlame } else { Join-Path $repoRoot $ProgramFlame } - $programArgs = @("--program-flame", $programFlamePath) -} - -$parityArgs = @() -if ($VisualParity -or -not [string]::IsNullOrWhiteSpace($ReferenceDensityPpm)) { - $parityArgs = @( - "--visual-parity-reference-samples", "$VisualParityReferenceSamples", - "--histogram-size", $HistogramSize, - "--histogram-bounds", $HistogramBounds - ) - if ($VisualParity) { - $parityArgs = @("--visual-parity") + $parityArgs - } - foreach ($view in $VisualParityView) { - $parityArgs += @("--visual-parity-view", $view) - } - if (-not [string]::IsNullOrWhiteSpace($VisualParityImageDirectory)) { - $parityImageDir = if ([System.IO.Path]::IsPathRooted($VisualParityImageDirectory)) { $VisualParityImageDirectory } else { Join-Path $repoRoot $VisualParityImageDirectory } - $parityArgs += @("--visual-parity-image-dir", $parityImageDir, "--visual-parity-image-prefix", $VisualParityImagePrefix) - } -} -if (-not [string]::IsNullOrWhiteSpace($ReferenceDensityPpm)) { - $referenceDensityPpmPath = if ([System.IO.Path]::IsPathRooted($ReferenceDensityPpm)) { $ReferenceDensityPpm } else { Join-Path $repoRoot $ReferenceDensityPpm } - $parityArgs += @("--reference-density-ppm", $referenceDensityPpmPath) -} - -dotnet run --project (Join-Path $repoRoot "tools\Aquarium.Fractal.Receipt\Aquarium.Fractal.Receipt.csproj") -c Release -- ` - --splats $Splats ` - --warmup-splat-updates $WarmupSplatUpdates ` - --splat-updates $SplatUpdates ` - --warmup $Warmup ` - --frames $Frames ` - --depth $Depth ` - --candidates $Candidates ` - --reservoir-updates $ReservoirUpdates ` - $programArgs ` - $parityArgs ` - --readback-splats $ReadbackSplats diff --git a/scripts/install-flame-reference-tools.ps1 b/scripts/install-flame-reference-tools.ps1 deleted file mode 100644 index 946a0bd..0000000 --- a/scripts/install-flame-reference-tools.ps1 +++ /dev/null @@ -1,53 +0,0 @@ -param( - [string]$Destination = "artifacts\reference-tools", - [string]$JWildfireUrl = "https://jwildfire.overwhale.com/downloads/j-wildfire-9.00.zip", - [string]$TemurinJreUrl = "https://api.adoptium.net/v3/binary/latest/17/ga/windows/x64/jre/hotspot/normal/eclipse", - [switch]$Force -) - -$ErrorActionPreference = "Stop" -$repoRoot = Split-Path -Parent $PSScriptRoot -$destinationPath = if ([System.IO.Path]::IsPathRooted($Destination)) { $Destination } else { Join-Path $repoRoot $Destination } -New-Item -ItemType Directory -Force -Path $destinationPath | Out-Null - -$jwildfireZip = Join-Path $destinationPath "j-wildfire-9.00.zip" -$jwildfireRoot = Join-Path $destinationPath "j-wildfire-9.00" -if ($Force -or -not (Test-Path $jwildfireRoot)) { - if ($Force -or -not (Test-Path $jwildfireZip)) { - Invoke-WebRequest -Uri $JWildfireUrl -OutFile $jwildfireZip - } - - Expand-Archive -LiteralPath $jwildfireZip -DestinationPath $destinationPath -Force -} - -$temurinZip = Join-Path $destinationPath "temurin-jre-17.zip" -$temurinRoot = Join-Path $destinationPath "temurin-jre-17" -if ($Force -or -not (Test-Path $temurinRoot)) { - if ($Force -or -not (Test-Path $temurinZip)) { - Invoke-WebRequest -Uri $TemurinJreUrl -OutFile $temurinZip - } - - New-Item -ItemType Directory -Force -Path $temurinRoot | Out-Null - Expand-Archive -LiteralPath $temurinZip -DestinationPath $temurinRoot -Force -} - -$java = Get-ChildItem $temurinRoot -Recurse -Filter java.exe | Select-Object -First 1 -$farender = Join-Path $jwildfireRoot "lib\FARenderJWF\FARender.exe" -$jar = Join-Path $jwildfireRoot "lib\j-wildfire.jar" - -if (-not (Test-Path $jar)) { - throw "JWildfire install completed, but lib\j-wildfire.jar was not found under $jwildfireRoot." -} - -if (-not (Test-Path $farender)) { - Write-Warning "JWildfire installed, but FARender.exe was not found. Java rendering may still work." -} - -if ($null -eq $java) { - throw "Temurin JRE install completed, but java.exe was not found under $temurinRoot." -} - -Write-Host "AQUARIUM_JWILDFIRE_ROOT=$jwildfireRoot" -Write-Host "AQUARIUM_JWILDFIRE_JAR=$jar" -Write-Host "AQUARIUM_FARENDER=$farender" -Write-Host "AQUARIUM_JAVA=$($java.FullName)" diff --git a/scripts/new-jwildfire-baby-fixture.ps1 b/scripts/new-jwildfire-baby-fixture.ps1 deleted file mode 100644 index c5c4bd6..0000000 --- a/scripts/new-jwildfire-baby-fixture.ps1 +++ /dev/null @@ -1,21 +0,0 @@ -param( - [string]$Source = "artifacts\reference-tools\j-wildfire-9.00\lib\FARenderJWF\selftest.flame", - [string]$Output = "artifacts\fractal-flame-jwildfire-reference\julian-disc-baby.flame" -) - -$ErrorActionPreference = "Stop" -$repoRoot = Split-Path -Parent $PSScriptRoot -$sourcePath = if ([System.IO.Path]::IsPathRooted($Source)) { $Source } else { Join-Path $repoRoot $Source } -$outputPath = if ([System.IO.Path]::IsPathRooted($Output)) { $Output } else { Join-Path $repoRoot $Output } -New-Item -ItemType Directory -Force -Path (Split-Path -Parent $outputPath) | Out-Null - -$text = [System.IO.File]::ReadAllText((Resolve-Path $sourcePath)) -$text = $text.Replace('JulianDisc - 535389044', 'julian-disc-baby') -$text = $text.Replace('jwf_julian_power="126"', 'jwf_julian_power="8"') -$text = $text.Replace('jwf_gaussian_blur="0.039366260122290476"', 'jwf_gaussian_blur="0.0"') -$text = $text.Replace('wfield_var_amount="0.21416904132907888"', 'wfield_var_amount="0.0"') -$text = $text.Replace('wfield_color_amount="0.26564915787570376"', 'wfield_color_amount="0.0"') -$text = $text.Replace('wfield_jitter_amount="0.13887944166913668"', 'wfield_jitter_amount="0.0"') - -[System.IO.File]::WriteAllText($outputPath, $text, [System.Text.UTF8Encoding]::new($false)) -Write-Host "JWildfire baby fixture: $outputPath" diff --git a/scripts/publish-win-x64.ps1 b/scripts/publish-win-x64.ps1 deleted file mode 100644 index 04ffbe6..0000000 --- a/scripts/publish-win-x64.ps1 +++ /dev/null @@ -1,100 +0,0 @@ -param( - [switch]$Zip, - [switch]$NoSelfContained, - [switch]$Clean, - [string]$Configuration = "Release", - [string]$Runtime = "win-x64", - [string]$OutputRoot -) - -$ErrorActionPreference = "Stop" -Set-StrictMode -Version Latest - -$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..") -$projectPath = Join-Path $repoRoot "src\Aquarium.Engine\Aquarium.Engine.csproj" -$liveProjectPath = Join-Path $repoRoot "src\Aquarium.Epiphany\Aquarium.Epiphany.csproj" -$publishRoot = if ([string]::IsNullOrWhiteSpace($OutputRoot)) { - Join-Path $repoRoot "artifacts\publish" -} -else { - $OutputRoot -} -$publishPath = Join-Path $publishRoot $Runtime -$zipPath = Join-Path $publishRoot "EpiphanyAquariumEngine-$Runtime.zip" - -if ($Clean -and (Test-Path $publishPath)) { - Remove-Item -LiteralPath $publishPath -Recurse -Force -} - -New-Item -ItemType Directory -Force -Path $publishPath | Out-Null - -$selfContained = if ($NoSelfContained) { "false" } else { "true" } -$publishArguments = @( - "publish", - $projectPath, - "-c", $Configuration, - "-r", $Runtime, - "--self-contained", $selfContained, - "-o", $publishPath, - "/p:UseAppHost=true" -) - -Write-Host "Publishing Aquarium Engine:" -Write-Host " Project: $projectPath" -Write-Host " Client: $liveProjectPath" -Write-Host " Runtime: $Runtime" -Write-Host " Output: $publishPath" -dotnet @publishArguments -if ($LASTEXITCODE -ne 0) { - throw "dotnet publish failed with exit code $LASTEXITCODE." -} - -dotnet publish $liveProjectPath -c $Configuration -r $Runtime --self-contained false -o $publishPath -if ($LASTEXITCODE -ne 0) { - throw "client runtime publish failed with exit code $LASTEXITCODE." -} - -& (Join-Path $PSScriptRoot "sync-faust-toolchain.ps1") -DestinationRoot (Join-Path $publishPath "Tools\Faust") - -$requiredFiles = @( - "Aquarium.Engine.exe", - "Aquarium.Epiphany.dll", - "Aquarium.Engine.Contracts.dll", - "AquaSynth.Core.dll", - "AquaSynth.Faust.dll", - "Tools\Faust\lib\faust.dll", - "Tools\Faust\share\faust\stdfaust.lib", - "Assets\Fensalir-Icon.ico", - "Assets\Fensalir-Icon-96.png", - "Assets\Fensalir-Splash.bmp", - "Assets\Fensalir-Splash.png", - "Assets\Fonts\Montserrat[wght].ttf", - "Assets\Fonts\UbuntuSans[wdth,wght].ttf", - "Render\Shaders\D3D12HeightField.hlsl", - "Render\Shaders\D3D12SdfCommon.hlsli", - "Render\Shaders\D3D12SdfProxy.hlsli", - "Render\Shaders\D3D12SelfBody.hlsl", - "Render\Shaders\D3D12CursorBody.hlsl" -) - -foreach ($relativePath in $requiredFiles) { - $path = Join-Path $publishPath $relativePath - if (-not (Test-Path -LiteralPath $path)) { - throw "Publish output is missing required file: $relativePath" - } -} - -Write-Host "Publish output verified." - -if ($Zip) { - if (Test-Path $zipPath) { - Remove-Item -LiteralPath $zipPath -Force - } - - Compress-Archive -Path (Join-Path $publishPath "*") -DestinationPath $zipPath -CompressionLevel Optimal - Write-Host "Zip ready:" - Write-Host " $zipPath" -} - -Write-Host "Shipping build ready:" -Write-Host " $publishPath" diff --git a/scripts/render-agent-preview.ps1 b/scripts/render-agent-preview.ps1 index 301f50f..eed9dd1 100644 --- a/scripts/render-agent-preview.ps1 +++ b/scripts/render-agent-preview.ps1 @@ -21,11 +21,11 @@ if ([string]::IsNullOrWhiteSpace($OutputDirectory)) { New-Item -ItemType Directory -Force -Path $slotPath | Out-Null New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null -Write-Host "Building isolated preview renderer:" +Write-Host "Building isolated Epiphany preview renderer:" Write-Host " $slotPath" dotnet build $projectPath -c Debug -o $slotPath /p:UseAppHost=true if ($LASTEXITCODE -ne 0) { - throw "preview build failed with exit code $LASTEXITCODE." + throw "Preview build failed with exit code $LASTEXITCODE." } $exePath = Join-Path $slotPath "Aquarium.Epiphany.AgentPreview.exe" @@ -41,7 +41,7 @@ if (-not (Test-Path $exePath)) { --frames $FramesPerView ` --time $TimeSeconds if ($LASTEXITCODE -ne 0) { - throw "preview render failed with exit code $LASTEXITCODE." + throw "Preview render failed with exit code $LASTEXITCODE." } Write-Host "Preview frames written:" diff --git a/scripts/sync-faust-toolchain.ps1 b/scripts/sync-faust-toolchain.ps1 deleted file mode 100644 index 1f11612..0000000 --- a/scripts/sync-faust-toolchain.ps1 +++ /dev/null @@ -1,57 +0,0 @@ -param( - [string]$SourceRoot, - [string]$DestinationRoot -) - -$ErrorActionPreference = "Stop" -Set-StrictMode -Version Latest - -if ([string]::IsNullOrWhiteSpace($SourceRoot)) { - $SourceRoot = if ($env:AQUASYNTH_FAUST_HOME) { $env:AQUASYNTH_FAUST_HOME } elseif ($env:AQUARIUM_FAUST_HOME) { $env:AQUARIUM_FAUST_HOME } else { "C:\Program Files\Faust" } -} - -if ([string]::IsNullOrWhiteSpace($DestinationRoot)) { - $repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..") - $DestinationRoot = Join-Path $repoRoot "artifacts\faust\win-x64" -} - -$source = Resolve-Path $SourceRoot -$destination = $DestinationRoot -$sourceLib = Join-Path $source "lib\faust.dll" -$sourceShare = Join-Path $source "share\faust" -$sourceBin = Join-Path $source "bin" - -if (-not (Test-Path -LiteralPath $sourceLib)) { - throw "Faust DLL not found at $sourceLib" -} - -if (-not (Test-Path -LiteralPath $sourceShare)) { - throw "Faust libraries not found at $sourceShare" -} - -if (Test-Path -LiteralPath $destination) { - Remove-Item -LiteralPath $destination -Recurse -Force -} - -New-Item -ItemType Directory -Force -Path (Join-Path $destination "lib") | Out-Null -New-Item -ItemType Directory -Force -Path (Join-Path $destination "bin") | Out-Null -New-Item -ItemType Directory -Force -Path (Join-Path $destination "share\faust") | Out-Null - -Copy-Item -LiteralPath $sourceLib -Destination (Join-Path $destination "lib\faust.dll") -Force - -if (Test-Path -LiteralPath $sourceBin) { - Get-ChildItem -LiteralPath $sourceBin -File -Filter *.dll | - Copy-Item -Destination (Join-Path $destination "bin") -Force -} - -Get-ChildItem -LiteralPath $sourceShare -File -Filter *.lib | - Copy-Item -Destination (Join-Path $destination "share\faust") -Force - -$version = & (Join-Path $sourceBin "faust.exe") --version 2>$null | Select-Object -First 1 -if ($LASTEXITCODE -eq 0 -and -not [string]::IsNullOrWhiteSpace($version)) { - Set-Content -Path (Join-Path $destination "VERSION.txt") -Value $version -Encoding UTF8 -} - -Write-Host "Faust toolchain synchronized:" -Write-Host " Source: $source" -Write-Host " Destination: $destination" diff --git a/scripts/update-synth-package.ps1 b/scripts/update-synth-package.ps1 deleted file mode 100644 index 295320a..0000000 --- a/scripts/update-synth-package.ps1 +++ /dev/null @@ -1,26 +0,0 @@ -param( - [string]$SynthRepo = "E:\Projects\AquaSynth", - [string]$Configuration = "Release" -) - -$ErrorActionPreference = "Stop" - -$root = Resolve-Path (Join-Path $PSScriptRoot "..") -$feed = Join-Path $root "packages" -$coreProject = Join-Path $SynthRepo "src\AquaSynth.Core\AquaSynth.Core.csproj" -$faustProject = Join-Path $SynthRepo "src\AquaSynth.Faust\AquaSynth.Faust.csproj" - -if (-not (Test-Path $coreProject)) { - throw "AquaSynth.Core project not found at $coreProject" -} - -if (-not (Test-Path $faustProject)) { - throw "AquaSynth.Faust project not found at $faustProject" -} - -New-Item -ItemType Directory -Force -Path $feed | Out-Null -dotnet pack $coreProject -c $Configuration -o $feed -dotnet pack $faustProject -c $Configuration -o $feed - -Write-Host "Packed AquaSynth.Core and AquaSynth.Faust into $feed" -Write-Host "If the package version changed, update src\Aquarium.Engine\Aquarium.Engine.csproj to match." diff --git a/scripts/verify-boundaries.ps1 b/scripts/verify-boundaries.ps1 deleted file mode 100644 index 79650f3..0000000 --- a/scripts/verify-boundaries.ps1 +++ /dev/null @@ -1,19 +0,0 @@ -$ErrorActionPreference = "Stop" -Set-StrictMode -Version Latest - -$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..") -$engineRoots = @( - (Join-Path $repoRoot "src\Aquarium.Engine"), - (Join-Path $repoRoot "src\Aquarium.Engine.Contracts") -) - -$forbiddenEngineTerms = "grid|agent|body|epiphany" -$engineReferences = rg -n -i -- $forbiddenEngineTerms $engineRoots -if ($LASTEXITCODE -eq 0) { - throw "Aquarium Engine and contracts must not contain Epiphany/client policy terms:`n$engineReferences" -} -elseif ($LASTEXITCODE -ne 1) { - throw "Boundary search for Aquarium Engine terms failed." -} - -Write-Host "Aquarium boundary checks passed." diff --git a/src/Aquarium.Engine.Contracts/Aquarium.Engine.Contracts.csproj b/src/Aquarium.Engine.Contracts/Aquarium.Engine.Contracts.csproj deleted file mode 100644 index 9ed914b..0000000 --- a/src/Aquarium.Engine.Contracts/Aquarium.Engine.Contracts.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - net10.0 - enable - enable - - - diff --git a/src/Aquarium.Engine.Contracts/AquariumFrame.cs b/src/Aquarium.Engine.Contracts/AquariumFrame.cs deleted file mode 100644 index d9acb24..0000000 --- a/src/Aquarium.Engine.Contracts/AquariumFrame.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.Engine; - -public readonly record struct AquariumFrame(ViewFrame View, Vector3 CameraPosition, Vector3 CameraTarget, float TimeSeconds, Vector2 CursorWorld, AquariumSceneState Scene) -{ - public AquariumFrame(ViewFrame view, Vector3 cameraPosition, float timeSeconds) - : this(view, cameraPosition, new Vector3(view.Center, 0.0f), timeSeconds, view.Center, AquariumSceneState.Empty) - { - } - - public AquariumFrame(ViewFrame view, Vector3 cameraPosition, float timeSeconds, Vector2 cursorWorld) - : this(view, cameraPosition, new Vector3(view.Center, 0.0f), timeSeconds, cursorWorld, AquariumSceneState.Empty) - { - } - - public AquariumFrame(ViewFrame view, Vector3 cameraPosition, float timeSeconds, Vector2 cursorWorld, AquariumSceneState scene) - : this(view, cameraPosition, new Vector3(view.Center, 0.0f), timeSeconds, cursorWorld, scene) - { - } -} - -public readonly record struct AquariumFrameInput(Vector2 MousePosition, int Width, int Height); - diff --git a/src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs b/src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs deleted file mode 100644 index be049ab..0000000 --- a/src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Aquarium.Engine.Audio; -using Aquarium.Engine.Input; -using Aquarium.Engine.Render; -using Aquarium.Engine.Ui; - -namespace Aquarium.Engine; - -public interface IAquariumRuntime : IDisposable -{ - AquariumRuntimeOptions Options { get; } - - AquariumFrame Frame { get; } - - GraphicsSettings GraphicsSettings { get; set; } - - AquariumRenderPlan RenderPlan { get; } - - AquariumUiDocument Ui { get; } - - AquariumAudioDocument Audio { get; } - - AquariumSynthDocument Synth { get; } - - void Start(); - - void Update(float deltaSeconds, InputState input); - - AquariumFrame ComposeFrame(AquariumFrame frame, AquariumFrameInput input); - - void FlushState(); -} - -public interface IAquariumRuntimeFactory -{ - IAquariumRuntime Create(AquariumRuntimeOptions options); -} - -public readonly record struct AquariumRuntimeOptions(bool Headless, string? CultCachePath, int? RenderDebugModeOverride = null); - diff --git a/src/Aquarium.Engine.Contracts/Audio/AquariumAudio.cs b/src/Aquarium.Engine.Contracts/Audio/AquariumAudio.cs deleted file mode 100644 index 6a57a30..0000000 --- a/src/Aquarium.Engine.Contracts/Audio/AquariumAudio.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System.Collections.Concurrent; - -namespace Aquarium.Engine.Audio; - -public sealed class AquariumAudioDocument -{ - private readonly ConcurrentQueue pcmChunks = new(); - - public static AquariumAudioDocument Empty { get; } = new(); - - public void EnqueuePcm16Base64(string base64Data, int sampleRate, int channels, float gain = 1.0f, float pan = 0.0f) - { - if (string.IsNullOrWhiteSpace(base64Data) || sampleRate <= 0 || channels <= 0) - { - return; - } - - byte[] bytes; - try - { - bytes = Convert.FromBase64String(base64Data); - } - catch (FormatException) - { - return; - } - - var frameCount = bytes.Length / Math.Max(1, channels) / 2; - if (frameCount <= 0) - { - return; - } - - var mono = new float[frameCount]; - var byteIndex = 0; - var safeGain = Math.Clamp(gain, 0.0f, 4.0f); - for (var frame = 0; frame < frameCount; frame++) - { - var sum = 0.0f; - for (var channel = 0; channel < channels && byteIndex + 1 < bytes.Length; channel++) - { - var sample = (short)(bytes[byteIndex] | (bytes[byteIndex + 1] << 8)); - sum += sample / 32768.0f; - byteIndex += 2; - } - - mono[frame] = Math.Clamp(sum / channels, -1.0f, 1.0f); - } - - var safePan = Math.Clamp(pan, -1.0f, 1.0f); - var leftGain = safeGain * MathF.Sqrt((1.0f - safePan) * 0.5f); - var rightGain = safeGain * MathF.Sqrt((1.0f + safePan) * 0.5f); - pcmChunks.Enqueue(new AquariumPcmAudioChunk(mono, sampleRate, leftGain, rightGain)); - } - - public IReadOnlyList DrainPcmChunks(int maxChunks = 64) - { - var drained = new List(); - while (drained.Count < maxChunks && pcmChunks.TryDequeue(out var chunk)) - { - drained.Add(chunk); - } - - return drained; - } -} - -public sealed record AquariumPcmAudioChunk(float[] MonoSamples, int SampleRate, float LeftGain = 1.0f, float RightGain = 1.0f); diff --git a/src/Aquarium.Engine.Contracts/Audio/AquariumSynth.cs b/src/Aquarium.Engine.Contracts/Audio/AquariumSynth.cs deleted file mode 100644 index 3ee5d0f..0000000 --- a/src/Aquarium.Engine.Contracts/Audio/AquariumSynth.cs +++ /dev/null @@ -1,84 +0,0 @@ -namespace Aquarium.Engine.Audio; - -public sealed class AquariumSynthDocument -{ - private readonly List patches = []; - - public static AquariumSynthDocument Empty { get; } = new(); - - public bool Enabled { get; init; } = true; - - public float MasterGain { get; init; } = 0.55f; - - public IReadOnlyList Patches => patches; - - public static AquariumSynthDocument Combine(params AquariumSynthDocument[] documents) - { - var combined = new AquariumSynthDocument - { - Enabled = documents.Any(document => document.Enabled), - MasterGain = documents.Length == 0 ? 1.0f : documents.Max(document => document.MasterGain) - }; - foreach (var document in documents) - { - if (!document.Enabled) - { - continue; - } - - foreach (var patch in document.Patches) - { - combined.patches.Add(patch); - } - } - - return combined; - } - - public AquariumSynthDocument Patch( - string id, - string script, - AquariumSynthTrigger trigger, - float gain = 1.0f, - int faustCompileRevision = 0, - string? faustName = null, - Action? statusSink = null) - { - patches.Add(new AquariumSynthPatch(id, script, trigger, gain, faustCompileRevision, faustName ?? id, statusSink)); - return this; - } -} - -public sealed record AquariumSynthPatch( - string Id, - string Script, - AquariumSynthTrigger Trigger, - float Gain = 1.0f, - int FaustCompileRevision = 0, - string FaustName = "aquarium_patch", - Action? StatusSink = null); - -public sealed record AquariumSynthPatchStatus( - string Id, - AquariumSynthPatchCompileState State, - string Message, - int Revision, - double ChangedAtSeconds); - -public enum AquariumSynthPatchCompileState -{ - Idle, - Queued, - Compiling, - Ready, - Failed -} - -public readonly record struct AquariumSynthTrigger(float IntervalSeconds, float PhaseSeconds = 0.0f, int FireRevision = 0) -{ - public static AquariumSynthTrigger Repeat(float intervalSeconds, float phaseSeconds = 0.0f) => - new(MathF.Max(0.001f, intervalSeconds), phaseSeconds); - - public static AquariumSynthTrigger Manual(int fireRevision) => - new(float.PositiveInfinity, 0.0f, fireRevision); -} diff --git a/src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs b/src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs deleted file mode 100644 index 00c190a..0000000 --- a/src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs +++ /dev/null @@ -1,370 +0,0 @@ -using System.Numerics; -using System.Runtime.InteropServices; - -namespace Aquarium.Engine.Fractal; - -public readonly record struct AquariumFractalKey -{ - public AquariumFractalKey(string value) - { - if (string.IsNullOrWhiteSpace(value)) - { - throw new ArgumentException("Fractal key must not be empty.", nameof(value)); - } - - Value = value; - } - - public string Value { get; } - - public override string ToString() - { - return Value; - } -} - -public enum AquariumFractalDomainKind -{ - Solar, - Orbital, - Planetary, - LatLong, - CubeSphereTile, - Surface2D, - Object3D, -} - -public readonly record struct AquariumFractalDomain( - AquariumFractalKey Key, - AquariumFractalDomainKind Kind, - AquariumFractalKey ParentKey, - Vector4 Parameters0, - Vector4 Parameters1); - -public enum AquariumFractalPayloadKind -{ - Height, - Material, - SignedDistance, - Density, - Extinction, -} - -public enum AquariumFieldLayer -{ - Form, - Appearance, - Transport, -} - -public enum AquariumFieldEncoding -{ - SignedDistance, - Height, - Density, - Extinction, - Material, - Phase, - Emission, - Radiance, - Feature, - Confidence, -} - -[Flags] -public enum AquariumFieldEncodingFlags -{ - None = 0, - SignedDistance = 1 << 0, - Height = 1 << 1, - Density = 1 << 2, - Extinction = 1 << 3, - Material = 1 << 4, - Phase = 1 << 5, - Emission = 1 << 6, - Radiance = 1 << 7, - Feature = 1 << 8, - Confidence = 1 << 9, -} - -public enum AquariumFractalSurfacePageKind -{ - Height, - SignedDistance2D, - Material, - Confidence, -} - -public readonly record struct AquariumFractalSurfacePageKey -{ - public AquariumFractalSurfacePageKey( - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - AquariumFractalSurfacePageKind kind, - int mipLevel) - { - if (domainKey.Value is null) - { - throw new ArgumentException("Surface page domain key must not be empty.", nameof(domainKey)); - } - - if (nodeKey.Value is null) - { - throw new ArgumentException("Surface page node key must not be empty.", nameof(nodeKey)); - } - - if (mipLevel < 0) - { - throw new ArgumentOutOfRangeException(nameof(mipLevel), mipLevel, "Surface page mip level must not be negative."); - } - - DomainKey = domainKey; - NodeKey = nodeKey; - Kind = kind; - MipLevel = mipLevel; - } - - public AquariumFractalKey DomainKey { get; } - - public AquariumFractalKey NodeKey { get; } - - public AquariumFractalSurfacePageKind Kind { get; } - - public int MipLevel { get; } - - public string Value => $"{DomainKey.Value}:{NodeKey.Value}:{Kind}:mip{MipLevel:D2}"; - - public override string ToString() - { - return Value; - } -} - -public readonly record struct AquariumFractalSurfacePage( - AquariumFractalSurfacePageKey Key, - Vector4 BoundsMinMax, - int Width, - int Height, - int PayloadHandle, - float MaxError); - -public readonly record struct AquariumFractalSdfSplat3DKey -{ - public AquariumFractalSdfSplat3DKey( - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - int payloadHandle) - { - if (domainKey.Value is null) - { - throw new ArgumentException("3D SDF splat domain key must not be empty.", nameof(domainKey)); - } - - if (nodeKey.Value is null) - { - throw new ArgumentException("3D SDF splat node key must not be empty.", nameof(nodeKey)); - } - - if (payloadHandle < 0) - { - throw new ArgumentOutOfRangeException(nameof(payloadHandle), payloadHandle, "3D SDF splat payload handle must not be negative."); - } - - DomainKey = domainKey; - NodeKey = nodeKey; - PayloadHandle = payloadHandle; - } - - public AquariumFractalKey DomainKey { get; } - - public AquariumFractalKey NodeKey { get; } - - public int PayloadHandle { get; } - - public string Value => $"{DomainKey.Value}:{NodeKey.Value}:sdf3d:{PayloadHandle:D6}"; - - public override string ToString() - { - return Value; - } -} - -public readonly record struct AquariumFractalSdfSplat3D( - AquariumFractalSdfSplat3DKey Key, - Vector3 Center, - Quaternion Orientation, - Vector3 Radii, - float Falloff, - float ShapePower, - float DistanceOffset, - float MaterialValue, - float Confidence); - -public readonly record struct AquariumFractalDensitySplat3DKey -{ - public AquariumFractalDensitySplat3DKey( - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - int payloadHandle) - { - if (domainKey.Value is null) - { - throw new ArgumentException("3D density splat domain key must not be empty.", nameof(domainKey)); - } - - if (nodeKey.Value is null) - { - throw new ArgumentException("3D density splat node key must not be empty.", nameof(nodeKey)); - } - - if (payloadHandle < 0) - { - throw new ArgumentOutOfRangeException(nameof(payloadHandle), payloadHandle, "3D density splat payload handle must not be negative."); - } - - DomainKey = domainKey; - NodeKey = nodeKey; - PayloadHandle = payloadHandle; - } - - public AquariumFractalKey DomainKey { get; } - - public AquariumFractalKey NodeKey { get; } - - public int PayloadHandle { get; } - - public string Value => $"{DomainKey.Value}:{NodeKey.Value}:density3d:{PayloadHandle:D6}"; - - public override string ToString() - { - return Value; - } -} - -public readonly record struct AquariumFractalDensitySplat3D( - AquariumFractalDensitySplat3DKey Key, - Vector3 Center, - Quaternion Orientation, - Vector3 Radii, - float Falloff, - float ShapePower, - float Density, - float Extinction, - float Confidence); - -[StructLayout(LayoutKind.Sequential)] -public readonly record struct AquariumPackedFractalSdfSplat3D( - Vector4 CenterRadius, - Vector4 Orientation, - Vector4 RadiiFalloff, - Vector4 MaterialConfidence, - Vector4 Key); - -[StructLayout(LayoutKind.Sequential)] -public readonly record struct AquariumPackedFractalDensitySplat3D( - Vector4 CenterRadius, - Vector4 Orientation, - Vector4 RadiiFalloff, - Vector4 DensityExtinctionConfidence, - Vector4 Key); - -[StructLayout(LayoutKind.Sequential)] -public readonly record struct AquariumPackedFractalIfsTransform( - Vector4 OffsetScaleAmplitude, - Vector4 RadiiRotationFalloff, - Vector4 MaterialSeedShape, - Vector4 TileAddress, - Vector4 PostMatrix, - Vector4 PostTranslation); - -[StructLayout(LayoutKind.Sequential)] -public readonly record struct AquariumPackedFractalFlameState( - Vector4 PointSupportMaterial, - Vector4 RandomStep); - -[StructLayout(LayoutKind.Sequential)] -public readonly record struct AquariumPackedSdfEnvelopeReservoir( - Vector4 CenterRadius, - Vector4 RadiiFalloff, - Vector4 WeightTargetCount, - Vector4 Validation); - -[StructLayout(LayoutKind.Sequential)] -public readonly record struct AquariumPackedPbrMaterialReservoir( - Vector4 BaseColorRoughMetal, - Vector4 NormalVariance, - Vector4 WeightTargetCount, - Vector4 Validation); - -[StructLayout(LayoutKind.Sequential)] -public readonly record struct AquariumPackedRadiosityReservoir( - Vector4 RadianceDistance, - Vector4 DirectionOcclusion, - Vector4 WeightTargetCount, - Vector4 Validation); - -public readonly record struct AquariumBrushClaim( - AquariumFractalKey Key, - AquariumFractalKey DomainKey, - AquariumFractalKey NodeKey, - AquariumFractalPayloadKind PayloadKind, - Vector2 Center, - Vector2 Radii, - float RotationRadians, - float Falloff, - float ShapePower, - float Amplitude, - int Seed, - string Tags, - float WaveAmplitude = 0.0f, - float WaveFrequency = 0.0f, - float WaveSpeed = 0.0f, - float WaveSinePower = 0.0f); - -public enum AquariumFractalOperation -{ - Union, - Subtract, - Common, - Repeat, - Refine, - Capture, - Bind, -} - -public readonly record struct AquariumFractalNode( - AquariumFractalKey Key, - AquariumFractalKey DomainKey, - AquariumFractalKey ParentKey, - AquariumFractalOperation Operation, - int FirstChildIndex, - int ChildCount, - int FirstClaimIndex, - int ClaimCount, - Vector4 BoundsMinMax, - int Seed); - -public readonly record struct AquariumFractalSummary( - AquariumFractalKey NodeKey, - Vector4 BoundsMinMax, - float MaxHeightError, - float MaxMaterialDelta, - float EstimatedCost, - int DescendantCount, - AquariumFieldEncodingFlags FormEncodingMask = AquariumFieldEncodingFlags.None); - -public readonly record struct AquariumContributionState( - AquariumFractalKey NodeKey, - float MeanContribution, - float Variance, - float Confidence, - int SampleCount, - uint LastSampledFrame, - bool Resident); - -public readonly record struct AquariumSelectedCut( - AquariumFractalKey NodeKey, - float Score, - float Fade, - bool UsesSummary, - bool RequestedChildren); diff --git a/src/Aquarium.Engine.Contracts/GraphicsSettings.cs b/src/Aquarium.Engine.Contracts/GraphicsSettings.cs deleted file mode 100644 index e5796f0..0000000 --- a/src/Aquarium.Engine.Contracts/GraphicsSettings.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace Aquarium.Engine; - -public readonly record struct GraphicsSettings( - int RenderDebugMode, - float SceneExposure, - float BloomIntensity, - float BloomVeilIntensity) -{ - public const int MinRenderDebugMode = 0; - public const int MaxRenderDebugMode = 11; - public const float MinSceneExposure = 0.02f; - public const float MaxSceneExposure = 1.2f; - public const float MinBloomIntensity = 0.0f; - public const float MaxBloomIntensity = 0.24f; - public const float MinBloomVeilIntensity = 0.0f; - public const float MaxBloomVeilIntensity = 0.08f; - - public static GraphicsSettings Default { get; } = new( - RenderDebugMode: 0, - SceneExposure: 0.16f, - BloomIntensity: 0.072f, - BloomVeilIntensity: 0.014f); - - public GraphicsSettings Normalized() - { - return new GraphicsSettings( - Math.Clamp(RenderDebugMode, MinRenderDebugMode, MaxRenderDebugMode), - Math.Clamp(SceneExposure, MinSceneExposure, MaxSceneExposure), - Math.Clamp(BloomIntensity, MinBloomIntensity, MaxBloomIntensity), - Math.Clamp(BloomVeilIntensity, MinBloomVeilIntensity, MaxBloomVeilIntensity)); - } -} diff --git a/src/Aquarium.Engine.Contracts/Input/InputState.cs b/src/Aquarium.Engine.Contracts/Input/InputState.cs deleted file mode 100644 index 8911258..0000000 --- a/src/Aquarium.Engine.Contracts/Input/InputState.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Input; - -public sealed class InputState -{ - private readonly HashSet downKeys = []; - private readonly HashSet pressedKeys = []; - private readonly HashSet downMouseButtons = []; - private readonly HashSet pressedMouseButtons = []; - private readonly List textInput = []; - - public Vector2 MousePosition { get; private set; } - - public Vector2 MouseDelta { get; private set; } - - public float WheelDelta { get; private set; } - - public IReadOnlyList TextInput => textInput; - - public bool LeftMouseDown => IsMouseDown(MouseButton.Left); - - public bool MiddleMouseDown => IsMouseDown(MouseButton.Middle); - - public bool RightMouseDown => IsMouseDown(MouseButton.Right); - - public bool IsKeyDown(KeyCode key) => downKeys.Contains(key); - - public bool IsKeyPressed(KeyCode key) => pressedKeys.Contains(key); - - public bool IsMouseDown(MouseButton button) => downMouseButtons.Contains(button); - - public bool IsMousePressed(MouseButton button) => pressedMouseButtons.Contains(button); - - public void BeginFrame() - { - MouseDelta = Vector2.Zero; - WheelDelta = 0.0f; - pressedKeys.Clear(); - pressedMouseButtons.Clear(); - textInput.Clear(); - } - - public void SetMousePosition(Vector2 position) - { - MouseDelta += position - MousePosition; - MousePosition = position; - } - - public void AddWheelDelta(float delta) - { - WheelDelta += delta; - } - - public void SetMouseButton(MouseButton button, bool isDown) - { - if (isDown) - { - if (!downMouseButtons.Contains(button)) - { - pressedMouseButtons.Add(button); - } - - downMouseButtons.Add(button); - } - else - { - downMouseButtons.Remove(button); - } - } - - public void SetKey(KeyCode key, bool isDown) - { - if (isDown) - { - if (!downKeys.Contains(key)) - { - pressedKeys.Add(key); - } - - downKeys.Add(key); - } - else - { - downKeys.Remove(key); - } - } - - public void AddTextInput(char value) - { - textInput.Add(value); - } - - public InputState WithoutInteractiveInput() - { - var snapshot = new InputState(); - snapshot.SetMousePosition(MousePosition); - return snapshot; - } -} - -public enum MouseButton -{ - Left, - Middle, - Right, -} - -public enum KeyCode -{ - W, - A, - S, - D, - Digit0, - Digit1, - Digit2, - Digit3, - Digit4, - Digit5, - Digit6, - Digit7, - Digit8, - Digit9, - RenderDebugCycle, - DebugUiToggle, - Backspace, - Delete, - Enter, - LeftArrow, - RightArrow, - Home, - End, - Shift, -} diff --git a/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs b/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs deleted file mode 100644 index f245916..0000000 --- a/src/Aquarium.Engine.Contracts/Render/AquariumApp.cs +++ /dev/null @@ -1,234 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Render; - -public sealed class AquariumApp -{ - public AquariumApp(AquariumRenderPlan? plan = null) - { - Plan = plan ?? new AquariumRenderPlan(); - RenderTargets = new AquariumRenderTargetBuilder(Plan.Graph); - Cameras = new AquariumCameraBuilder(Plan.Graph); - Shaders = new AquariumShaderBuilder(Plan.Shaders); - Graph = new AquariumGraphBuilder(Plan.Graph); - Features = new AquariumFeatureBuilder(Plan.Graph); - Debug = new AquariumDebugBuilder(Plan.Graph); - } - - public AquariumRenderPlan Plan { get; } - - public AquariumRenderTargetBuilder RenderTargets { get; } - - public AquariumCameraBuilder Cameras { get; } - - public AquariumShaderBuilder Shaders { get; } - - public AquariumGraphBuilder Graph { get; } - - public AquariumFeatureBuilder Features { get; } - - public AquariumDebugBuilder Debug { get; } -} - -public sealed class AquariumRenderTargetBuilder(AquariumRenderGraphDescription graph) -{ - public AquariumRenderTargetDraft Create(string name) - { - return new AquariumRenderTargetDraft(graph, name); - } - - public AquariumRenderTargetSet Hdr(string name) - { - var color = graph.RenderTarget(name, RenderFormat.Rgba16Float, AquariumTargetSize.MatchWindow(), historyFrames: 2); - var metadata = graph.RenderTarget($"{name}-metadata", RenderFormat.Rgba16Float, AquariumTargetSize.MatchWindow(), historyFrames: 2); - var control = graph.RenderTarget($"{name}-control", RenderFormat.Rgba16Float, AquariumTargetSize.MatchWindow(), historyFrames: 2); - return new AquariumRenderTargetSet(color, metadata, control, new DepthTargetHandle($"{name}-depth")); - } -} - -public sealed class AquariumRenderTargetDraft(AquariumRenderGraphDescription graph, string name) -{ - private RenderFormat format = RenderFormat.Rgba16Float; - private AquariumTargetSize size = AquariumTargetSize.MatchWindow(); - private bool sampled = true; - private int historyFrames; - - public AquariumRenderTargetDraft FixedSize(int width, int height) - { - size = AquariumTargetSize.Fixed(width, height); - return this; - } - - public AquariumRenderTargetDraft MatchWindow(float scale = 1.0f) - { - size = AquariumTargetSize.MatchWindow(scale); - return this; - } - - public AquariumRenderTargetDraft Format(RenderFormat value) - { - format = value; - return this; - } - - public AquariumRenderTargetDraft Sampled(bool value = true) - { - sampled = value; - return this; - } - - public AquariumRenderTargetDraft History(int frames) - { - historyFrames = Math.Max(0, frames); - return this; - } - - public AquariumRenderTargetDraft Clear(float value) - { - return this; - } - - public AquariumRenderTargetDraft Clear(Vector4 value) - { - return this; - } - - public RenderTargetHandle Register() - { - return graph.RenderTarget(name, format, size, sampled, historyFrames); - } -} - -public readonly record struct AquariumRenderTargetSet( - RenderTargetHandle Color, - RenderTargetHandle Metadata, - RenderTargetHandle Control, - DepthTargetHandle Depth); - -public sealed class AquariumCameraBuilder(AquariumRenderGraphDescription graph) -{ - public CameraHandle Perspective(string name) - { - return graph.Camera(name); - } - - public CameraHandle Orbit(string name) - { - return graph.Camera(name); - } -} - -public sealed class AquariumShaderBuilder(AquariumShaderManifest manifest) -{ - public AquariumShaderBuilder Root(string path) - { - manifest.Root(path); - return this; - } - - public AquariumShaderBuilder Core(string heightField, string scene, string post) - { - manifest.HeightField(heightField).Scene(scene).Post(post); - return this; - } - - public AquariumShaderBuilder TemporalGaussian(string path) - { - manifest.TemporalGaussian(path); - return this; - } - - public AquariumShaderBuilder LocalCastFusion(string path) - { - manifest.LocalCastFusion(path); - return this; - } - - public AquariumShaderBuilder FractalReservoir(string path) - { - manifest.FractalReservoir(path); - return this; - } - - public AquariumShaderBuilder FractalSplatRender(string path) - { - manifest.FractalSplatRender(path); - return this; - } - - public AquariumShaderBuilder Include(string path) - { - manifest.Include(path); - return this; - } - - public AquariumShaderBuilder SdfShader(string path) - { - manifest.SdfShader(path); - return this; - } - - public AquariumShaderBuilder SdfLibrary(string path) - { - manifest.SdfLibrary(path); - return this; - } -} - -public sealed class AquariumGraphBuilder(AquariumRenderGraphDescription graph) -{ - public AquariumPassDraft Pass(string name) - { - return new AquariumPassDraft(graph, name); - } -} - -public sealed class AquariumPassDraft(AquariumRenderGraphDescription graph, string name) -{ - public PassHandle Fullscreen() - { - return graph.Pass(name, AquariumPassKind.Fullscreen); - } - - public PassHandle Proxy() - { - return graph.Pass(name, AquariumPassKind.Proxy); - } - - public PassHandle Present() - { - return graph.Pass(name, AquariumPassKind.Present); - } - - public PassHandle Overlay() - { - return graph.Pass(name, AquariumPassKind.Overlay); - } -} - -public sealed class AquariumFeatureBuilder(AquariumRenderGraphDescription graph) -{ - public PassHandle Bloom(RenderTargetHandle source) - { - return graph.Pass($"bloom:{source.Name}", AquariumPassKind.Fullscreen); - } - - public PassHandle Presentation(RenderTargetHandle source) - { - return graph.Pass($"present:{source.Name}", AquariumPassKind.Present); - } - - public PassHandle DirectWriteOverlay() - { - return graph.Pass("directwrite-overlay", AquariumPassKind.Overlay); - } -} - -public sealed class AquariumDebugBuilder(AquariumRenderGraphDescription graph) -{ - public AquariumDebugBuilder View(string name, RenderTargetHandle target) - { - graph.DebugView(name, target); - return this; - } -} diff --git a/src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs b/src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs deleted file mode 100644 index ca267c6..0000000 --- a/src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs +++ /dev/null @@ -1,503 +0,0 @@ -using System.Numerics; -using System.Runtime.InteropServices; -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Render; - -public sealed class AquariumRenderPlan -{ - public AquariumRenderPlan() - { - Shaders = new AquariumShaderManifest(); - Graph = new AquariumRenderGraphDescription(); - } - - public AquariumShaderManifest Shaders { get; } - - public AquariumRenderGraphDescription Graph { get; } -} - -public sealed class AquariumShaderManifest -{ - private readonly List sdfShaderPaths = []; - private readonly List includePaths = []; - - public string? ShaderRoot { get; private set; } - - public string HeightFieldShader { get; private set; } = "D3D12HeightField.hlsl"; - - public string SceneShader { get; private set; } = "D3D12Scene.hlsl"; - - public string TemporalGaussianShader { get; private set; } = "D3D12TemporalGaussian.hlsl"; - - public string LocalCastFusionShader { get; private set; } = "D3D12LocalCastFusion.hlsl"; - - public string FractalReservoirShader { get; private set; } = "D3D12FractalReservoirCompute.hlsl"; - - public string FractalSplatRenderShader { get; private set; } = "D3D12FractalSplatRender.hlsl"; - - public string PostShader { get; private set; } = "D3D12Post.hlsl"; - - public string SdfCommonInclude { get; private set; } = "D3D12SdfCommon.hlsli"; - - public string SdfProxyInclude { get; private set; } = "D3D12SdfProxy.hlsli"; - - public string SdfMathInclude { get; private set; } = "D3D12SdfMath.hlsli"; - - public string? SdfLibraryInclude { get; private set; } - - public IReadOnlyList SdfShaderPaths => sdfShaderPaths; - - public IReadOnlyList IncludePaths => includePaths; - - public AquariumShaderManifest Root(string path) - { - ShaderRoot = path; - return this; - } - - public AquariumShaderManifest HeightField(string path) - { - HeightFieldShader = path; - return this; - } - - public AquariumShaderManifest Scene(string path) - { - SceneShader = path; - return this; - } - - public AquariumShaderManifest TemporalGaussian(string path) - { - TemporalGaussianShader = path; - return this; - } - - public AquariumShaderManifest LocalCastFusion(string path) - { - LocalCastFusionShader = path; - return this; - } - - public AquariumShaderManifest FractalReservoir(string path) - { - FractalReservoirShader = path; - return this; - } - - public AquariumShaderManifest FractalSplatRender(string path) - { - FractalSplatRenderShader = path; - return this; - } - - public AquariumShaderManifest Post(string path) - { - PostShader = path; - return this; - } - - public AquariumShaderManifest SdfCommon(string path) - { - SdfCommonInclude = path; - return this; - } - - public AquariumShaderManifest SdfProxy(string path) - { - SdfProxyInclude = path; - return this; - } - - public AquariumShaderManifest SdfMath(string path) - { - SdfMathInclude = path; - return this; - } - - public AquariumShaderManifest SdfLibrary(string? path) - { - SdfLibraryInclude = path; - return this; - } - - public AquariumShaderManifest Include(string path) - { - includePaths.Add(path); - return this; - } - - public AquariumShaderManifest SdfShader(string path) - { - sdfShaderPaths.Add(path); - return this; - } -} - -public sealed class AquariumRenderGraphDescription -{ - private readonly List renderTargets = []; - private readonly List cameras = []; - private readonly List passes = []; - private readonly List debugViews = []; - - public IReadOnlyList RenderTargets => renderTargets; - - public IReadOnlyList Cameras => cameras; - - public IReadOnlyList Passes => passes; - - public IReadOnlyList DebugViews => debugViews; - - public RenderTargetHandle RenderTarget(string name, RenderFormat format, AquariumTargetSize size, bool sampled = true, int historyFrames = 0) - { - var handle = new RenderTargetHandle(name); - renderTargets.Add(new AquariumRenderTargetDescription(handle, format, size, sampled, historyFrames)); - return handle; - } - - public CameraHandle Camera(string name) - { - var handle = new CameraHandle(name); - cameras.Add(new AquariumCameraDescription(handle)); - return handle; - } - - public PassHandle Pass(string name, AquariumPassKind kind) - { - var handle = new PassHandle(name); - passes.Add(new AquariumPassDescription(handle, kind)); - return handle; - } - - public AquariumRenderGraphDescription DebugView(string name, RenderTargetHandle target) - { - debugViews.Add(new AquariumDebugViewDescription(name, target)); - return this; - } -} - -public readonly record struct RenderTargetHandle(string Name); - -public readonly record struct DepthTargetHandle(string Name); - -public readonly record struct CameraHandle(string Name); - -public readonly record struct ShaderHandle(string Name); - -public readonly record struct BufferHandle(string Name) where T : unmanaged; - -public readonly record struct TextureHandle(string Name); - -public readonly record struct PassHandle(string Name); - -public readonly record struct AquariumRenderTargetDescription( - RenderTargetHandle Handle, - RenderFormat Format, - AquariumTargetSize Size, - bool Sampled, - int HistoryFrames); - -public readonly record struct AquariumCameraDescription(CameraHandle Handle); - -public readonly record struct AquariumPassDescription(PassHandle Handle, AquariumPassKind Kind); - -public readonly record struct AquariumDebugViewDescription(string Name, RenderTargetHandle Target); - -public readonly record struct AquariumTargetSize(AquariumTargetSizeKind Kind, int Width, int Height, float Scale) -{ - public static AquariumTargetSize Fixed(int width, int height) => new(AquariumTargetSizeKind.Fixed, width, height, 1.0f); - - public static AquariumTargetSize MatchWindow(float scale = 1.0f) => new(AquariumTargetSizeKind.MatchWindow, 0, 0, scale); -} - -public enum AquariumTargetSizeKind -{ - Fixed, - MatchWindow, -} - -public enum RenderFormat -{ - Unknown, - R16Float, - Rgba16Float, - Bgra8Unorm, - Depth32Float, -} - -public enum AquariumPassKind -{ - Fullscreen, - Proxy, - Instanced, - Compute, - Copy, - Present, - Overlay, -} - -[StructLayout(LayoutKind.Sequential)] -public readonly record struct AquariumSdfLight( - Vector4 CenterRadius, - Vector4 RadianceFieldId); - -[StructLayout(LayoutKind.Sequential)] -public readonly record struct AquariumSdfObject( - Vector4 CenterRadius, - Vector4 PreviousCenterPad, - Vector4 State); - -public readonly record struct AquariumHeightFieldBrush( - Vector2 Center, - float Radius, - float Power, - float Amplitude, - float WaveAmplitude, - float WaveFrequency, - float WaveSpeed, - float WaveSinePower, - float RadiusY = 0.0f, - float RotationRadians = 0.0f, - float EnvelopeFalloff = 0.0f, - float DomainFace = -1.0f, - float DomainLevel = 0.0f, - float DomainX = 0.0f, - float DomainY = 0.0f); - -public readonly record struct AquariumTemporalSdfGaussian( - string StableKey, - Vector3 Center, - Vector3 PreviousCenter, - Vector3 Velocity, - Vector3 Radii, - Quaternion Orientation, - Vector4 ColorOpacity, - float Confidence, - float HistoryWeight, - float LastObservedTimeSeconds, - float Falloff, - float ShapePower, - int FieldId); - -public readonly record struct AquariumGpuFusionSeed( - string StableKey, - Vector3 Center, - Vector3 PreviousCenter, - Vector3 Velocity, - Vector3 Radii, - Vector4 ColorOpacity, - float Confidence, - float HistoryWeight, - float Falloff, - float ShapePower, - int FieldId); - -public enum AquariumGpuSensorKind -{ - Unknown, - RgbCamera, - HighRateTracker, - LeapPackedMap, -} - -public enum AquariumGpuSensorPixelFormat -{ - Unknown, - Bgra8Unorm, - Rgba8Unorm, - R8Unorm, - R16Unorm, - R16Float, - Rg8Unorm, - LeapPackedMap, -} - -public readonly record struct AquariumExternalGpuTexture( - TextureHandle Handle, - IntPtr SharedHandle, - int Width, - int Height, - AquariumGpuSensorPixelFormat PixelFormat, - long TimestampNs, - int PlaneIndex = 0, - string SharedHandleName = ""); - -public readonly record struct AquariumGpuSensorCamera( - string SensorId, - AquariumGpuSensorKind Kind, - Matrix4x4 WorldFromSensor, - Matrix4x4 SensorFromWorld, - Vector4 Intrinsics, - Vector4 Distortion01, - Vector4 Distortion23, - int Width, - int Height, - int FirstTextureIndex, - int TextureCount, - long TimestampNs); - -public sealed class AquariumGpuSensorFrame -{ - public static AquariumGpuSensorFrame Empty { get; } = new(); - - public IReadOnlyList Cameras { get; init; } = []; - - public IReadOnlyList ExternalTextures { get; init; } = []; - - public float AccumulationWindowSeconds { get; init; } - - public float PresentationDelaySeconds { get; init; } - - public bool HasInput => Cameras.Count > 0 || ExternalTextures.Count > 0; -} - -public enum AquariumAcousticConstraintKind -{ - Unknown, - UltrasonicReflector, - VoiceTdoa, - SpeakerProbe, - ClapImpact, -} - -public readonly record struct AquariumAcousticConstraint( - string StableKey, - AquariumAcousticConstraintKind Kind, - Vector3 Position, - Vector3 Velocity, - float RadiusMeters, - float Confidence, - long TimestampNs); - -public sealed class AquariumAcousticFieldFrame -{ - public static AquariumAcousticFieldFrame Empty { get; } = new(); - - public IReadOnlyList Constraints { get; init; } = []; - - public long TimingOracleNs { get; init; } - - public float TimingConfidence { get; init; } - - public float TimingUncertaintyMicroseconds { get; init; } - - public float AccumulationWindowSeconds { get; init; } - - public float PresentationDelaySeconds { get; init; } - - public bool HasInput => Constraints.Count > 0; -} - -public readonly record struct AquariumClapCalibrationEvent( - string StableKey, - Vector3 Position, - long AcousticOracleNs, - long VisualObservedNs, - float TimingUncertaintyMicroseconds, - float VisualConfidence, - float AcousticConfidence); - -public sealed class AquariumCalibrationEventFrame -{ - public static AquariumCalibrationEventFrame Empty { get; } = new(); - - public IReadOnlyList ClapEvents { get; init; } = []; - - public bool HasInput => ClapEvents.Count > 0; -} - -public sealed class AquariumGpuFusionField -{ - public static AquariumGpuFusionField Empty { get; } = new(); - - public IReadOnlyList Seeds { get; init; } = []; - - public AquariumGpuFusionPointBuffer PointBuffer { get; init; } - - public float AccumulationWindowSeconds { get; init; } - - public float PresentationDelaySeconds { get; init; } - - public bool HasInput => Seeds.Count > 0 || PointBuffer.HasInput; -} - -public readonly record struct AquariumGpuFusionPointBuffer( - IntPtr Buffer, - int Count, - int StrideBytes) -{ - // Caller owns the memory and must keep it stable until the render frame has uploaded it. - public bool HasInput => Buffer != IntPtr.Zero && Count > 0 && StrideBytes > 0; -} - -public sealed class AquariumTemporalGaussianField -{ - public static AquariumTemporalGaussianField Empty { get; } = new(); - - public IReadOnlyList Gaussians { get; init; } = []; - - public float AccumulationWindowSeconds { get; init; } - - public float PresentationDelaySeconds { get; init; } -} - -public sealed class AquariumFractalReservoirField -{ - public static AquariumFractalReservoirField Empty { get; } = new(); - - public int SplatCount { get; init; } - - public int Depth { get; init; } = 8; - - public uint Seed { get; init; } = 0xA17EA11u; - - public int CandidatesPerReservoirUpdate { get; init; } = 2; - - public int SplatUpdatesPerFrame { get; init; } - - public int ReservoirUpdatesPerPass { get; init; } - - public IReadOnlyList ProgramTransforms { get; init; } = []; - - public Vector4 WorldCenterRadius { get; init; } - - public Vector4 PriorityFocus { get; init; } - - public bool HasInput => - SplatCount > 0 && - Depth > 0 && - CandidatesPerReservoirUpdate > 0 && - SplatUpdatesPerFrame > 0 && - SplatUpdatesPerFrame <= SplatCount && - ReservoirUpdatesPerPass > 0 && - ReservoirUpdatesPerPass <= SplatCount; -} - -public sealed class AquariumSceneState -{ - public static AquariumSceneState Empty { get; } = new(); - - public bool TraceHeightFieldSurface { get; init; } = true; - - public bool UseStarfieldBackground { get; init; } - - public IReadOnlyList HeightFieldBrushes { get; init; } = []; - - public IReadOnlyList SdfObjects { get; init; } = []; - - public IReadOnlyList SdfLights { get; init; } = []; - - public AquariumTemporalGaussianField TemporalGaussianField { get; init; } = AquariumTemporalGaussianField.Empty; - - public AquariumFractalReservoirField FractalReservoirField { get; init; } = AquariumFractalReservoirField.Empty; - - public AquariumGpuSensorFrame GpuSensorFrame { get; init; } = AquariumGpuSensorFrame.Empty; - - public AquariumAcousticFieldFrame AcousticFieldFrame { get; init; } = AquariumAcousticFieldFrame.Empty; - - public AquariumCalibrationEventFrame CalibrationEventFrame { get; init; } = AquariumCalibrationEventFrame.Empty; - - public AquariumGpuFusionField GpuFusionField { get; init; } = AquariumGpuFusionField.Empty; -} diff --git a/src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs b/src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs deleted file mode 100644 index a8f6f93..0000000 --- a/src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs +++ /dev/null @@ -1,147 +0,0 @@ -namespace Aquarium.Engine.Ui; - -public sealed class AquariumUiDocument -{ - private readonly List panels = []; - private readonly List commands = []; - - public static AquariumUiDocument Empty { get; } = new(); - - public IReadOnlyList Panels => panels; - - public IReadOnlyList Commands => commands; - - public AquariumUiDocument Panel(string title, Action compose) - { - return Panel(title, 18.0f, 82.0f, 360.0f, compose); - } - - public AquariumUiDocument Panel(string title, float left, float top, float width, Action compose) - { - return Panel(title, left, top, width, fadeWhenMouseDistant: false, compose); - } - - public AquariumUiDocument Panel(string title, float left, float top, float width, bool fadeWhenMouseDistant, Action compose) - { - var controls = new List(); - compose(new AquariumUiPanelBuilder(controls)); - panels.Add(new AquariumUiPanel(title, left, top, width, controls, fadeWhenMouseDistant)); - return this; - } - - public AquariumUiDocument Command(string name, Func, string> execute, string description = "") - { - commands.Add(new AquariumConsoleCommand(name, execute, description)); - return this; - } -} - -public sealed record AquariumUiPanel( - string Title, - float Left, - float Top, - float Width, - IReadOnlyList Controls, - bool FadeWhenMouseDistant = false); - -public sealed class AquariumUiPanelBuilder(List controls) -{ - public AquariumUiPanelBuilder Section(string title, Func? isVisible = null) - { - controls.Add(new AquariumUiSection(title, isVisible)); - return this; - } - - public AquariumUiPanelBuilder Button(string label, Action action, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new AquariumUiButton(label, action, tooltip, isVisible)); - return this; - } - - public AquariumUiPanelBuilder Toggle(string label, Func read, Action write, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new AquariumUiToggle(label, read, write, tooltip, isVisible)); - return this; - } - - public AquariumUiPanelBuilder TreeItem(string label, int depth, bool canExpand, Func isExpanded, Action setExpanded, Func isSelected, Action select, string? detail = null, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new AquariumUiTreeItem(label, Math.Max(0, depth), canExpand, isExpanded, setExpanded, isSelected, select, detail, tooltip, isVisible)); - return this; - } - - public AquariumUiPanelBuilder Slider(string label, Func read, Action write, float min, float max, string format = "0.###", string? tooltip = null, Func? isVisible = null) - { - controls.Add(new AquariumUiFloatSlider(label, read, write, min, max, format, tooltip, isVisible)); - return this; - } - - public AquariumUiPanelBuilder Slider(string label, Func read, Action write, int min, int max, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new AquariumUiIntSlider(label, read, write, min, max, tooltip, isVisible)); - return this; - } - - public AquariumUiPanelBuilder Options(string label, Func read, Action write, IReadOnlyList options, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new AquariumUiOptions(label, read, write, options, tooltip, isVisible)); - return this; - } - - public AquariumUiPanelBuilder Text(string label, Func read, Action write, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new AquariumUiText(label, read, write, tooltip, isVisible)); - return this; - } - - public AquariumUiPanelBuilder TextBox(string label, Func read, Action write, int lines = 3, bool acceptsReturn = true, Action? submit = null, bool monospace = false, bool alignBottom = false, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new AquariumUiTextBox(label, read, write, Math.Max(1, lines), acceptsReturn, submit, monospace, alignBottom, tooltip, isVisible)); - return this; - } - - public AquariumUiPanelBuilder Readout(string label, Func read, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new AquariumUiReadout(label, read, tooltip, isVisible)); - return this; - } -} - -public readonly record struct AquariumUiOption(int Value, string Label); - -public sealed record AquariumConsoleCommand(string Name, Func, string> Execute, string Description = ""); - -public abstract record AquariumUiControl(string Label, string? Tooltip, Func? IsVisible) -{ - public bool Visible => IsVisible?.Invoke() ?? true; -} - -public sealed record AquariumUiSection(string Label, Func? IsVisible = null) - : AquariumUiControl(Label, null, IsVisible); - -public sealed record AquariumUiButton(string Label, Action Action, string? Tooltip = null, Func? IsVisible = null) - : AquariumUiControl(Label, Tooltip, IsVisible); - -public sealed record AquariumUiToggle(string Label, Func Read, Action Write, string? Tooltip = null, Func? IsVisible = null) - : AquariumUiControl(Label, Tooltip, IsVisible); - -public sealed record AquariumUiTreeItem(string Label, int Depth, bool CanExpand, Func IsExpanded, Action SetExpanded, Func IsSelected, Action Select, string? Detail = null, string? Tooltip = null, Func? IsVisible = null) - : AquariumUiControl(Label, Tooltip, IsVisible); - -public sealed record AquariumUiFloatSlider(string Label, Func Read, Action Write, float Min, float Max, string Format = "0.###", string? Tooltip = null, Func? IsVisible = null) - : AquariumUiControl(Label, Tooltip, IsVisible); - -public sealed record AquariumUiIntSlider(string Label, Func Read, Action Write, int Min, int Max, string? Tooltip = null, Func? IsVisible = null) - : AquariumUiControl(Label, Tooltip, IsVisible); - -public sealed record AquariumUiOptions(string Label, Func Read, Action Write, IReadOnlyList Options, string? Tooltip = null, Func? IsVisible = null) - : AquariumUiControl(Label, Tooltip, IsVisible); - -public sealed record AquariumUiText(string Label, Func Read, Action Write, string? Tooltip = null, Func? IsVisible = null) - : AquariumUiControl(Label, Tooltip, IsVisible); - -public sealed record AquariumUiTextBox(string Label, Func Read, Action Write, int Lines = 3, bool AcceptsReturn = true, Action? Submit = null, bool Monospace = false, bool AlignBottom = false, string? Tooltip = null, Func? IsVisible = null) - : AquariumUiControl(Label, Tooltip, IsVisible); - -public sealed record AquariumUiReadout(string Label, Func Read, string? Tooltip = null, Func? IsVisible = null) - : AquariumUiControl(Label, Tooltip, IsVisible); diff --git a/src/Aquarium.Engine.Contracts/World/ViewFrame.cs b/src/Aquarium.Engine.Contracts/World/ViewFrame.cs deleted file mode 100644 index 81f38cb..0000000 --- a/src/Aquarium.Engine.Contracts/World/ViewFrame.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine; - -public readonly record struct ViewFrame(Vector2 Center, float Radius) -{ - private const float MinimumRadius = 20.0f; - private const float MaximumRadius = 80.0f; - private const float CameraDistanceScale = 2.0f; - - public static ViewFrame FromCamera(Vector2 target, float distance) - { - return new ViewFrame(target, Math.Clamp(distance * CameraDistanceScale, MinimumRadius, MaximumRadius)); - } -} diff --git a/src/Aquarium.Engine.Fractal/Aquarium.Engine.Fractal.csproj b/src/Aquarium.Engine.Fractal/Aquarium.Engine.Fractal.csproj deleted file mode 100644 index dff661c..0000000 --- a/src/Aquarium.Engine.Fractal/Aquarium.Engine.Fractal.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - net10.0 - enable - enable - true - - - diff --git a/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs b/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs deleted file mode 100644 index 33d524a..0000000 --- a/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Brushes; - -public readonly record struct FractalBrushEnvelope2D -{ - private const double MinRadius = 1.0e-6; - private const double MinFalloff = 1.0e-6; - private const double MinShapePower = 1.0e-6; - - public FractalBrushEnvelope2D( - Vector2 center, - double radiusX, - double radiusY, - double rotationRadians, - double falloff, - double shapePower = 1.0) - { - if (!double.IsFinite(radiusX) || radiusX <= MinRadius) - { - throw new ArgumentOutOfRangeException(nameof(radiusX), radiusX, "Envelope radius X must be positive and finite."); - } - - if (!double.IsFinite(radiusY) || radiusY <= MinRadius) - { - throw new ArgumentOutOfRangeException(nameof(radiusY), radiusY, "Envelope radius Y must be positive and finite."); - } - - if (!double.IsFinite(rotationRadians)) - { - throw new ArgumentOutOfRangeException(nameof(rotationRadians), rotationRadians, "Envelope rotation must be finite."); - } - - if (!double.IsFinite(falloff) || falloff <= MinFalloff) - { - throw new ArgumentOutOfRangeException(nameof(falloff), falloff, "Envelope falloff must be positive and finite."); - } - - if (!double.IsFinite(shapePower) || shapePower <= MinShapePower) - { - throw new ArgumentOutOfRangeException(nameof(shapePower), shapePower, "Envelope shape power must be positive and finite."); - } - - Center = center; - RadiusX = radiusX; - RadiusY = radiusY; - RotationRadians = rotationRadians; - Falloff = falloff; - ShapePower = shapePower; - } - - public Vector2 Center { get; } - - public double RadiusX { get; } - - public double RadiusY { get; } - - public double RotationRadians { get; } - - public double Falloff { get; } - - public double ShapePower { get; } - - public double Evaluate(Vector2 point) - { - var normalizedRadiusSquared = NormalizedRadiusSquared(point); - if (normalizedRadiusSquared >= 1.0) - { - return 0.0; - } - - var edgeValue = Math.Exp(-Falloff); - var gaussianValue = Math.Exp(-Falloff * normalizedRadiusSquared); - var compactValue = (gaussianValue - edgeValue) / (1.0 - edgeValue); - return Math.Pow(Math.Clamp(compactValue, 0.0, 1.0), ShapePower); - } - - public bool Contains(Vector2 point) - { - return NormalizedRadiusSquared(point) <= 1.0; - } - - public double SignedSupportDistanceEstimate(Vector2 point) - { - var normalizedRadius = Math.Sqrt(NormalizedRadiusSquared(point)); - return (normalizedRadius - 1.0) * Math.Min(RadiusX, RadiusY); - } - - public FractalBrushEnvelopeBounds2D AxisAlignedBounds() - { - var cos = Math.Cos(RotationRadians); - var sin = Math.Sin(RotationRadians); - var extentX = Math.Sqrt((RadiusX * cos * RadiusX * cos) + (RadiusY * sin * RadiusY * sin)); - var extentY = Math.Sqrt((RadiusX * sin * RadiusX * sin) + (RadiusY * cos * RadiusY * cos)); - var extents = new Vector2((float)extentX, (float)extentY); - return new FractalBrushEnvelopeBounds2D(Center - extents, Center + extents); - } - - public FractalBrushEnvelope2DPacket ToPacket(double amplitude = 1.0) - { - var cos = Math.Cos(RotationRadians); - var sin = Math.Sin(RotationRadians); - return new FractalBrushEnvelope2DPacket( - new Vector4(Center.X, Center.Y, (float)RadiusX, (float)RadiusY), - new Vector4((float)cos, (float)sin, (float)Falloff, (float)ShapePower), - new Vector4((float)amplitude, 0.0f, 0.0f, 0.0f)); - } - - private double NormalizedRadiusSquared(Vector2 point) - { - var delta = point - Center; - var cos = Math.Cos(RotationRadians); - var sin = Math.Sin(RotationRadians); - var localX = delta.X * cos + delta.Y * sin; - var localY = -delta.X * sin + delta.Y * cos; - var normalizedX = localX / RadiusX; - var normalizedY = localY / RadiusY; - return (normalizedX * normalizedX) + (normalizedY * normalizedY); - } -} diff --git a/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2DBounds.cs b/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2DBounds.cs deleted file mode 100644 index 0808c29..0000000 --- a/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2DBounds.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Brushes; - -public readonly record struct FractalBrushEnvelopeBounds2D(Vector2 Min, Vector2 Max) -{ - public bool Contains(Vector2 point) - { - return point.X >= Min.X && point.X <= Max.X && point.Y >= Min.Y && point.Y <= Max.Y; - } -} diff --git a/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2DPacket.cs b/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2DPacket.cs deleted file mode 100644 index e7ec359..0000000 --- a/src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2DPacket.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Brushes; - -public readonly record struct FractalBrushEnvelope2DPacket( - Vector4 CenterRadii, - Vector4 RotationFalloffShape, - Vector4 Payload); diff --git a/src/Aquarium.Engine.Fractal/Brushes/FractalHeightBrushCompiler.cs b/src/Aquarium.Engine.Fractal/Brushes/FractalHeightBrushCompiler.cs deleted file mode 100644 index c8fd561..0000000 --- a/src/Aquarium.Engine.Fractal/Brushes/FractalHeightBrushCompiler.cs +++ /dev/null @@ -1,107 +0,0 @@ -using Aquarium.Engine.Render; -using Aquarium.Engine.Fractal.Grammar; - -namespace Aquarium.Engine.Fractal.Brushes; - -public static class FractalHeightBrushCompiler -{ - public static AquariumHeightFieldBrush Compile(AquariumBrushClaim claim) - { - return Compile(claim, null); - } - - public static AquariumHeightFieldBrush Compile(AquariumBrushClaim claim, AquariumFractalDomain? domain) - { - if (claim.PayloadKind != AquariumFractalPayloadKind.Height) - { - throw new ArgumentException($"Claim {claim.Key} carries {claim.PayloadKind}; only height claims can compile to height-field brushes.", nameof(claim)); - } - - if (claim.Radii.X <= 0.0f || claim.Radii.Y <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(claim), claim.Radii, "Height claim radii must be positive."); - } - - return new AquariumHeightFieldBrush( - claim.Center, - claim.Radii.X, - claim.ShapePower, - claim.Amplitude, - claim.WaveAmplitude, - claim.WaveFrequency, - claim.WaveSpeed, - claim.WaveSinePower, - RadiusY: claim.Radii.Y, - RotationRadians: claim.RotationRadians, - EnvelopeFalloff: claim.Falloff, - DomainFace: domain is { Kind: AquariumFractalDomainKind.CubeSphereTile } ? domain.Value.Parameters0.X : -1.0f, - DomainLevel: domain is { Kind: AquariumFractalDomainKind.CubeSphereTile } ? domain.Value.Parameters0.Y : 0.0f, - DomainX: domain is { Kind: AquariumFractalDomainKind.CubeSphereTile } ? domain.Value.Parameters0.Z : 0.0f, - DomainY: domain is { Kind: AquariumFractalDomainKind.CubeSphereTile } ? domain.Value.Parameters0.W : 0.0f); - } - - public static AquariumHeightFieldBrush[] CompileMany(IReadOnlyList claims) - { - ArgumentNullException.ThrowIfNull(claims); - - var brushes = new AquariumHeightFieldBrush[claims.Count]; - for (var index = 0; index < claims.Count; index++) - { - brushes[index] = Compile(claims[index]); - } - - return brushes; - } - - public static AquariumHeightFieldBrush[] CompileTree(FractalOwnershipTree tree) - { - ArgumentNullException.ThrowIfNull(tree); - - var domains = tree.Domains.ToDictionary(domain => domain.Key, domain => domain); - var brushes = new List(); - for (var index = 0; index < tree.Claims.Count; index++) - { - var claim = tree.Claims[index]; - if (claim.PayloadKind != AquariumFractalPayloadKind.Height) - { - continue; - } - - domains.TryGetValue(claim.DomainKey, out var domain); - brushes.Add(Compile(claim, domain)); - } - - return brushes.ToArray(); - } - - public static AquariumHeightFieldBrush[] CompileSelectedTree(FractalOwnershipTree tree, IReadOnlyList selectedCut) - { - ArgumentNullException.ThrowIfNull(tree); - ArgumentNullException.ThrowIfNull(selectedCut); - - var selectedNodes = selectedCut.Select(cut => cut.NodeKey).ToHashSet(); - var domains = tree.Domains.ToDictionary(domain => domain.Key, domain => domain); - var brushes = new List(); - foreach (var node in tree.Nodes) - { - if (!selectedNodes.Contains(node.Key)) - { - continue; - } - - for (var claimIndex = node.FirstClaimIndex; claimIndex < node.FirstClaimIndex + node.ClaimCount; claimIndex++) - { - var claim = tree.Claims[claimIndex]; - if (claim.PayloadKind != AquariumFractalPayloadKind.Height) - { - continue; - } - - domains.TryGetValue(claim.DomainKey, out var domain); - brushes.Add(Compile(claim, domain)); - } - } - - return brushes.ToArray(); - } -} diff --git a/src/Aquarium.Engine.Fractal/CubeFace.cs b/src/Aquarium.Engine.Fractal/CubeFace.cs deleted file mode 100644 index f90f96c..0000000 --- a/src/Aquarium.Engine.Fractal/CubeFace.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Aquarium.Engine.Fractal; - -public enum CubeFace -{ - PositiveX, - NegativeX, - PositiveY, - NegativeY, - PositiveZ, - NegativeZ, -} diff --git a/src/Aquarium.Engine.Fractal/CubeFacePosition.cs b/src/Aquarium.Engine.Fractal/CubeFacePosition.cs deleted file mode 100644 index d59560d..0000000 --- a/src/Aquarium.Engine.Fractal/CubeFacePosition.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal; - -public readonly record struct CubeFacePosition -{ - public CubeFacePosition(CubeFace face, double u, double v) - { - if (!double.IsFinite(u) || u is < -1.0 or > 1.0) - { - throw new ArgumentOutOfRangeException(nameof(u), u, "Cube face U must be finite and in [-1, 1]."); - } - - if (!double.IsFinite(v) || v is < -1.0 or > 1.0) - { - throw new ArgumentOutOfRangeException(nameof(v), v, "Cube face V must be finite and in [-1, 1]."); - } - - Face = face; - U = u; - V = v; - } - - public CubeFace Face { get; } - - public double U { get; } - - public double V { get; } - - public Vector3 ToCubeVector() - { - return Face switch - { - CubeFace.PositiveX => new Vector3(1.0f, (float)V, (float)-U), - CubeFace.NegativeX => new Vector3(-1.0f, (float)V, (float)U), - CubeFace.PositiveY => new Vector3((float)U, 1.0f, (float)-V), - CubeFace.NegativeY => new Vector3((float)U, -1.0f, (float)V), - CubeFace.PositiveZ => new Vector3((float)U, (float)V, 1.0f), - CubeFace.NegativeZ => new Vector3((float)-U, (float)V, -1.0f), - _ => throw new ArgumentOutOfRangeException(nameof(Face), Face, "Unknown cube face."), - }; - } -} diff --git a/src/Aquarium.Engine.Fractal/CubeTileKey.cs b/src/Aquarium.Engine.Fractal/CubeTileKey.cs deleted file mode 100644 index fcd0cb2..0000000 --- a/src/Aquarium.Engine.Fractal/CubeTileKey.cs +++ /dev/null @@ -1,93 +0,0 @@ -namespace Aquarium.Engine.Fractal; - -public readonly record struct CubeTileKey -{ - public const int MaxLevel = 30; - - public CubeTileKey(CubeFace face, int level, int x, int y) - { - if (level is < 0 or > MaxLevel) - { - throw new ArgumentOutOfRangeException(nameof(level), level, $"Cube tile level must be in [0, {MaxLevel}]."); - } - - var axisTileCount = 1 << level; - if (x < 0 || x >= axisTileCount) - { - throw new ArgumentOutOfRangeException(nameof(x), x, $"Cube tile X must be in [0, {axisTileCount - 1}] for level {level}."); - } - - if (y < 0 || y >= axisTileCount) - { - throw new ArgumentOutOfRangeException(nameof(y), y, $"Cube tile Y must be in [0, {axisTileCount - 1}] for level {level}."); - } - - Face = face; - Level = level; - X = x; - Y = y; - } - - public CubeFace Face { get; } - - public int Level { get; } - - public int X { get; } - - public int Y { get; } - - public int AxisTileCount => 1 << Level; - - public CubeTileKey Parent() - { - if (Level == 0) - { - throw new InvalidOperationException("Root cube tile has no parent."); - } - - return new CubeTileKey(Face, Level - 1, X >> 1, Y >> 1); - } - - public CubeTileKey Child(int childX, int childY) - { - if (childX is < 0 or > 1) - { - throw new ArgumentOutOfRangeException(nameof(childX), childX, "Child X must be 0 or 1."); - } - - if (childY is < 0 or > 1) - { - throw new ArgumentOutOfRangeException(nameof(childY), childY, "Child Y must be 0 or 1."); - } - - if (Level == MaxLevel) - { - throw new InvalidOperationException($"Cube tile level {MaxLevel} cannot be subdivided."); - } - - return new CubeTileKey(Face, Level + 1, (X << 1) | childX, (Y << 1) | childY); - } - - public CubeFacePosition PositionAt(double localU, double localV) - { - if (!double.IsFinite(localU) || localU is < 0.0 or > 1.0) - { - throw new ArgumentOutOfRangeException(nameof(localU), localU, "Local U must be finite and in [0, 1]."); - } - - if (!double.IsFinite(localV) || localV is < 0.0 or > 1.0) - { - throw new ArgumentOutOfRangeException(nameof(localV), localV, "Local V must be finite and in [0, 1]."); - } - - var axisTileCount = AxisTileCount; - var faceU = -1.0 + (2.0 * (X + localU) / axisTileCount); - var faceV = -1.0 + (2.0 * (Y + localV) / axisTileCount); - return new CubeFacePosition(Face, faceU, faceV); - } - - public override string ToString() - { - return $"{Face}/L{Level:D2}/{X}/{Y}"; - } -} diff --git a/src/Aquarium.Engine.Fractal/Debug/FractalDebugDump.cs b/src/Aquarium.Engine.Fractal/Debug/FractalDebugDump.cs deleted file mode 100644 index 2648cb5..0000000 --- a/src/Aquarium.Engine.Fractal/Debug/FractalDebugDump.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Globalization; -using System.Text; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Grammar; - -namespace Aquarium.Engine.Fractal.Debug; - -public static class FractalDebugDump -{ - public static string Build( - FractalOwnershipTree tree, - IReadOnlyList summaries, - IReadOnlyList selectedCut) - { - ArgumentNullException.ThrowIfNull(tree); - ArgumentNullException.ThrowIfNull(summaries); - ArgumentNullException.ThrowIfNull(selectedCut); - - var builder = new StringBuilder(); - foreach (var domain in tree.Domains) - { - builder.AppendLine($"domain {domain.Key} kind={domain.Kind} parent={domain.ParentKey}"); - } - - builder.AppendLine($"domain-path {string.Join(" -> ", tree.DomainGraph.GetPath(tree.Domain.Key).Select(domain => domain.Key.ToString()))}"); - builder.AppendLine($"nodes {tree.Nodes.Count} claims {tree.Claims.Count} summaries {summaries.Count} cut {selectedCut.Count}"); - foreach (var node in tree.Nodes) - { - builder.AppendLine($"node {node.Key} op={node.Operation} claims={node.ClaimCount} bounds={FormatBounds(node.BoundsMinMax)}"); - } - - foreach (var claim in tree.Claims) - { - builder.AppendLine( - string.Create( - CultureInfo.InvariantCulture, - $"claim {claim.Key} payload={claim.PayloadKind} center=({claim.Center.X:0.###},{claim.Center.Y:0.###}) radii=({claim.Radii.X:0.###},{claim.Radii.Y:0.###}) amp={claim.Amplitude:0.###} tags={claim.Tags}")); - } - - foreach (var summary in summaries) - { - builder.AppendLine( - string.Create( - CultureInfo.InvariantCulture, - $"summary {summary.NodeKey} heightError={summary.MaxHeightError:0.###} cost={summary.EstimatedCost:0.###} descendants={summary.DescendantCount}")); - } - - foreach (var cut in selectedCut) - { - builder.AppendLine( - string.Create( - CultureInfo.InvariantCulture, - $"cut {cut.NodeKey} score={cut.Score:0.###} fade={cut.Fade:0.###} summary={cut.UsesSummary} requestChildren={cut.RequestedChildren}")); - } - - return builder.ToString(); - } - - private static string FormatBounds(System.Numerics.Vector4 bounds) - { - return string.Create(CultureInfo.InvariantCulture, $"({bounds.X:0.###},{bounds.Y:0.###})-({bounds.Z:0.###},{bounds.W:0.###})"); - } -} diff --git a/src/Aquarium.Engine.Fractal/FractalXorShiftRandom.cs b/src/Aquarium.Engine.Fractal/FractalXorShiftRandom.cs deleted file mode 100644 index 939dc7a..0000000 --- a/src/Aquarium.Engine.Fractal/FractalXorShiftRandom.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace Aquarium.Engine.Fractal; - -public sealed class FractalXorShiftRandom(uint seed) : IFractalRandom -{ - private uint state = seed == 0 ? 0xA341316Cu : seed; - - public double NextDouble() - { - var value = NextUInt32(); - return value / ((double)uint.MaxValue + 1.0); - } - - private uint NextUInt32() - { - var value = state; - value ^= value << 13; - value ^= value >> 17; - value ^= value << 5; - state = value; - return value; - } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalAffineIfsChaosGame.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalAffineIfsChaosGame.cs deleted file mode 100644 index ac1f85f..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalAffineIfsChaosGame.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Grammar; - -public static class FractalAffineIfsChaosGame -{ - public static Vector2[] Generate( - FractalAffineIfsDefinition definition, - int count, - int burnIn, - IFractalRandom random) - { - ArgumentNullException.ThrowIfNull(definition); - ArgumentNullException.ThrowIfNull(random); - ArgumentOutOfRangeException.ThrowIfNegative(count); - ArgumentOutOfRangeException.ThrowIfNegative(burnIn); - - var points = new Vector2[count]; - var point = definition.Start; - var total = definition.Transforms.Sum(transform => MathF.Max(transform.Weight, 0.0f)); - if (total <= 0.0f) - { - throw new ArgumentException("Affine IFS transform weights must have positive total.", nameof(definition)); - } - - for (var step = 0; step < burnIn + count; step++) - { - point = SelectTransform(definition.Transforms, total, (float)random.NextDouble()).Apply(point); - if (step >= burnIn) - { - points[step - burnIn] = point; - } - } - - return points; - } - - private static FractalAffineIfsTransform2D SelectTransform( - IReadOnlyList transforms, - float total, - float unit) - { - var target = unit * total; - var cumulative = 0.0f; - for (var index = 0; index < transforms.Count; index++) - { - cumulative += MathF.Max(transforms[index].Weight, 0.0f); - if (target <= cumulative) - { - return transforms[index]; - } - } - - return transforms[^1]; - } -} - diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalAffineIfsDefinition.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalAffineIfsDefinition.cs deleted file mode 100644 index 8410a96..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalAffineIfsDefinition.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Grammar; - -public readonly record struct FractalAffineIfsTransform2D( - string Name, - Vector4 Matrix, - Vector2 Translation, - float Weight) -{ - public Vector2 Apply(Vector2 point) - { - return new Vector2( - (Matrix.X * point.X) + (Matrix.Y * point.Y) + Translation.X, - (Matrix.Z * point.X) + (Matrix.W * point.Y) + Translation.Y); - } -} - -public sealed class FractalAffineIfsDefinition -{ - public FractalAffineIfsDefinition( - AquariumFractalKey key, - AquariumFractalKey domainKey, - string name, - Vector2 start, - int seed, - string tags, - IReadOnlyList transforms) - { - if (transforms.Count == 0) - { - throw new ArgumentException("Affine IFS definitions need at least one transform.", nameof(transforms)); - } - - Key = key; - DomainKey = domainKey; - Name = name; - Start = start; - Seed = seed; - Tags = tags; - Transforms = transforms; - } - - public AquariumFractalKey Key { get; } - - public AquariumFractalKey DomainKey { get; } - - public string Name { get; } - - public Vector2 Start { get; } - - public int Seed { get; } - - public string Tags { get; } - - public IReadOnlyList Transforms { get; } -} - diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalDomainGraph.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalDomainGraph.cs deleted file mode 100644 index 4e94e3a..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalDomainGraph.cs +++ /dev/null @@ -1,85 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Grammar; - -public sealed class FractalDomainGraph -{ - private readonly Dictionary indices; - - public FractalDomainGraph(IReadOnlyList domains) - { - ArgumentNullException.ThrowIfNull(domains); - if (domains.Count == 0) - { - throw new FormatException("Fractal domain graph must contain at least one domain."); - } - - indices = new Dictionary(domains.Count); - for (var index = 0; index < domains.Count; index++) - { - var domain = domains[index]; - if (domain.Key.Value is null) - { - throw new FormatException($"Fractal domain at index {index} has no key."); - } - - if (!indices.TryAdd(domain.Key, index)) - { - throw new FormatException($"Duplicate fractal domain key `{domain.Key}`."); - } - } - - Domains = domains.ToArray(); - ValidateParents(); - } - - public IReadOnlyList Domains { get; } - - public bool Contains(AquariumFractalKey key) - { - return key.Value is not null && indices.ContainsKey(key); - } - - public AquariumFractalDomain GetRequired(AquariumFractalKey key) - { - if (key.Value is null || !indices.TryGetValue(key, out var index)) - { - throw new FormatException($"Unknown fractal domain `{key}`."); - } - - return Domains[index]; - } - - public IReadOnlyList GetPath(AquariumFractalKey leafKey) - { - var path = new List(); - var seen = new HashSet(); - var current = GetRequired(leafKey); - while (true) - { - if (!seen.Add(current.Key)) - { - throw new FormatException($"Fractal domain graph contains a parent cycle at `{current.Key}`."); - } - - path.Add(current); - if (current.ParentKey.Value is null) - { - break; - } - - current = GetRequired(current.ParentKey); - } - - path.Reverse(); - return path; - } - - private void ValidateParents() - { - foreach (var domain in Domains) - { - _ = GetPath(domain.Key); - } - } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs deleted file mode 100644 index a9dc950..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs +++ /dev/null @@ -1,598 +0,0 @@ -using System.Globalization; -using System.Numerics; -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Grammar; - -public static class FractalDslCompiler -{ - public static FractalOwnershipTree Compile(string source) - { - ArgumentNullException.ThrowIfNull(source); - - var lines = source.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'); - AquariumFractalDomain? domain = null; - AquariumFractalKey rootKey = default; - NodeDraft? currentNode = null; - var domains = new List(); - var claims = new List(); - var nodes = new List(); - var affineIfsDrafts = new List(); - AffineIfsDraft? currentAffineIfs = null; - - for (var lineIndex = 0; lineIndex < lines.Length; lineIndex++) - { - var line = StripComment(lines[lineIndex]).Trim(); - if (line.Length == 0) - { - continue; - } - - var tokens = line.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - switch (tokens[0]) - { - case "domain": - EnsureTokenCount(tokens, 4, lineIndex); - domains.Add(ParseDomain(tokens, lineIndex)); - break; - case "tile": - EnsureTokenCount(tokens, 6, lineIndex); - var tile = new CubeTileKey(ParseFace(tokens[1], lineIndex), ParseInt(tokens[2], lineIndex), ParseInt(tokens[3], lineIndex), ParseInt(tokens[4], lineIndex)); - var domainKey = FractalStableKeyBuilder.ForCubeTile(tile, tokens[5]); - var parentKey = tokens.Length >= 7 ? new AquariumFractalKey(tokens[6]) : default; - rootKey = FractalStableKeyBuilder.Child(domainKey, "root"); - domain = new AquariumFractalDomain( - domainKey, - AquariumFractalDomainKind.CubeSphereTile, - parentKey, - new Vector4((float)tile.Face, tile.Level, tile.X, tile.Y), - Vector4.Zero); - domains.Add(domain.Value); - rootKey = FractalStableKeyBuilder.Child(domainKey, "root"); - currentNode = new NodeDraft(rootKey, domainKey, claims.Count); - nodes.Add(currentNode); - currentAffineIfs = null; - break; - case "affineifs": - EnsureDomain(domain, lineIndex); - EnsureNode(currentNode, lineIndex); - EnsureTokenCount(tokens, 6, lineIndex); - currentAffineIfs = new AffineIfsDraft( - FractalStableKeyBuilder.Child(currentNode!.Key, $"affineifs/{tokens[1]}"), - domain!.Value.Key, - tokens[1], - new Vector2(ParseFloat(tokens[2], lineIndex), ParseFloat(tokens[3], lineIndex)), - ParseInt(tokens[4], lineIndex), - tokens[5]); - affineIfsDrafts.Add(currentAffineIfs); - break; - case "affinemap": - EnsureAffineIfs(currentAffineIfs, lineIndex); - EnsureTokenCount(tokens, 9, lineIndex); - currentAffineIfs!.Transforms.Add(new FractalAffineIfsTransform2D( - tokens[1], - new Vector4( - ParseFloat(tokens[2], lineIndex), - ParseFloat(tokens[3], lineIndex), - ParseFloat(tokens[5], lineIndex), - ParseFloat(tokens[6], lineIndex)), - new Vector2(ParseFloat(tokens[4], lineIndex), ParseFloat(tokens[7], lineIndex)), - ParsePositiveFloat(tokens[8], lineIndex))); - break; - case "height": - case "density": - case "extinction": - EnsureDomain(domain, lineIndex); - EnsureNode(currentNode, lineIndex); - EnsureTokenCount(tokens, 12, lineIndex); - var fieldDomain = domain!.Value; - claims.Add(ParseFieldClaim(tokens, fieldDomain.Key, currentNode!.Key, lineIndex, claims.Count - currentNode.FirstClaimIndex)); - currentNode.ClaimCount++; - break; - case "ripple": - EnsureDomain(domain, lineIndex); - EnsureNode(currentNode, lineIndex); - EnsureTokenCount(tokens, 16, lineIndex); - var rippleDomain = domain!.Value; - claims.Add(ParseRippleClaim(tokens, rippleDomain.Key, currentNode!.Key, lineIndex, claims.Count - currentNode.FirstClaimIndex)); - currentNode.ClaimCount++; - break; - case "ifs": - EnsureDomain(domain, lineIndex); - EnsureNode(currentNode, lineIndex); - EnsureTokenCount(tokens, 15, lineIndex); - var ifsDomain = domain!.Value; - var beforeIfs = claims.Count; - AddIfsClaims(tokens, ifsDomain.Key, currentNode!.Key, lineIndex, claims); - currentNode.ClaimCount += claims.Count - beforeIfs; - break; - case "flame": - EnsureDomain(domain, lineIndex); - EnsureNode(currentNode, lineIndex); - EnsureTokenCount(tokens, 15, lineIndex); - var flameDomain = domain!.Value; - var beforeFlame = claims.Count; - AddFlameClaims(tokens, flameDomain.Key, currentNode!.Key, lineIndex, claims); - currentNode.ClaimCount += claims.Count - beforeFlame; - break; - default: - throw new FormatException($"Unknown fractal DSL command `{tokens[0]}` at line {lineIndex + 1}."); - } - } - - if (domain is null) - { - throw new FormatException("Fractal DSL must declare a `tile ` line before claims."); - } - - return new FractalOwnershipTree(domain.Value, domains, BuildNodes(nodes, claims), claims, BuildAffineIfsDefinitions(affineIfsDrafts)); - } - - private static AquariumFractalDomain ParseDomain(string[] tokens, int lineIndex) - { - if (!Enum.TryParse(tokens[1], ignoreCase: true, out var kind)) - { - throw new FormatException($"Invalid domain kind `{tokens[1]}` at line {lineIndex + 1}."); - } - - var parent = tokens[3] == "-" ? default : new AquariumFractalKey(tokens[3]); - var parameters = new float[8]; - for (var index = 4; index < tokens.Length && index < 12; index++) - { - parameters[index - 4] = ParseFloat(tokens[index], lineIndex); - } - - return new AquariumFractalDomain( - new AquariumFractalKey(tokens[2]), - kind, - parent, - new Vector4(parameters[0], parameters[1], parameters[2], parameters[3]), - new Vector4(parameters[4], parameters[5], parameters[6], parameters[7])); - } - - private static AquariumBrushClaim ParseFieldClaim(string[] tokens, AquariumFractalKey domainKey, AquariumFractalKey nodeKey, int lineIndex, int claimIndex) - { - var name = tokens[1]; - return FieldClaim( - ParsePayloadKind(tokens[0], lineIndex), - domainKey, - nodeKey, - name, - claimIndex, - new Vector2(ParseFloat(tokens[2], lineIndex), ParseFloat(tokens[3], lineIndex)), - new Vector2(ParsePositiveFloat(tokens[4], lineIndex), ParsePositiveFloat(tokens[5], lineIndex)), - ParseFloat(tokens[6], lineIndex), - ParsePositiveFloat(tokens[7], lineIndex), - ParsePositiveFloat(tokens[8], lineIndex), - ParseFloat(tokens[9], lineIndex), - ParseInt(tokens[10], lineIndex), - tokens[11]); - } - - private static AquariumBrushClaim ParseRippleClaim(string[] tokens, AquariumFractalKey domainKey, AquariumFractalKey nodeKey, int lineIndex, int claimIndex) - { - var name = tokens[1]; - return FieldClaim( - AquariumFractalPayloadKind.Height, - domainKey, - nodeKey, - name, - claimIndex, - new Vector2(ParseFloat(tokens[2], lineIndex), ParseFloat(tokens[3], lineIndex)), - new Vector2(ParsePositiveFloat(tokens[4], lineIndex), ParsePositiveFloat(tokens[5], lineIndex)), - ParseFloat(tokens[6], lineIndex), - ParsePositiveFloat(tokens[7], lineIndex), - ParsePositiveFloat(tokens[8], lineIndex), - ParseFloat(tokens[9], lineIndex), - ParseInt(tokens[14], lineIndex), - tokens[15], - ParseFloat(tokens[10], lineIndex), - ParsePositiveFloat(tokens[11], lineIndex), - ParseFloat(tokens[12], lineIndex), - ParsePositiveFloat(tokens[13], lineIndex)); - } - - private static AquariumFractalPayloadKind ParsePayloadKind(string token, int lineIndex) - { - return token switch - { - "height" => AquariumFractalPayloadKind.Height, - "density" => AquariumFractalPayloadKind.Density, - "extinction" => AquariumFractalPayloadKind.Extinction, - _ => throw new FormatException($"Invalid field payload `{token}` at line {lineIndex + 1}."), - }; - } - - private static void AddIfsClaims(string[] tokens, AquariumFractalKey domainKey, AquariumFractalKey nodeKey, int lineIndex, List claims) - { - var name = tokens[1]; - var levels = ParsePositiveInt(tokens[2], lineIndex); - var branches = ParsePositiveInt(tokens[3], lineIndex); - var center = new Vector2(ParseFloat(tokens[4], lineIndex), ParseFloat(tokens[5], lineIndex)); - var radii = new Vector2(ParsePositiveFloat(tokens[6], lineIndex), ParsePositiveFloat(tokens[7], lineIndex)); - var childScale = ParsePositiveFloat(tokens[8], lineIndex); - var spread = ParsePositiveFloat(tokens[9], lineIndex); - var rotationStep = ParseFloat(tokens[10], lineIndex); - var falloff = ParsePositiveFloat(tokens[11], lineIndex); - var shapePower = ParsePositiveFloat(tokens[12], lineIndex); - var amplitude = ParseFloat(tokens[13], lineIndex); - var seed = ParseInt(tokens[14], lineIndex); - var tags = tokens.Length >= 16 ? tokens[15] : name; - - if (childScale >= 1.0f) - { - throw new FormatException($"IFS child scale must be below 1 at line {lineIndex + 1}."); - } - - EmitIfsLevel(domainKey, nodeKey, name, center, radii, levels, branches, childScale, spread, rotationStep, falloff, shapePower, amplitude, seed, tags, claims); - } - - private static void AddFlameClaims(string[] tokens, AquariumFractalKey domainKey, AquariumFractalKey nodeKey, int lineIndex, List claims) - { - var name = tokens[1]; - var levels = ParsePositiveInt(tokens[2], lineIndex); - var branches = ParsePositiveInt(tokens[3], lineIndex); - var center = new Vector2(ParseFloat(tokens[4], lineIndex), ParseFloat(tokens[5], lineIndex)); - var radii = new Vector2(ParsePositiveFloat(tokens[6], lineIndex), ParsePositiveFloat(tokens[7], lineIndex)); - var childScale = ParsePositiveFloat(tokens[8], lineIndex); - var curl = ParseFloat(tokens[9], lineIndex); - var spread = ParsePositiveFloat(tokens[10], lineIndex); - var falloff = ParsePositiveFloat(tokens[11], lineIndex); - var shapePower = ParsePositiveFloat(tokens[12], lineIndex); - var amplitude = ParseFloat(tokens[13], lineIndex); - var seed = ParseInt(tokens[14], lineIndex); - var tags = tokens.Length >= 16 ? tokens[15] : name; - - if (childScale >= 1.0f) - { - throw new FormatException($"Flame child scale must be below 1 at line {lineIndex + 1}."); - } - - EmitFlameLevel(domainKey, nodeKey, name, center, radii, 0.0f, levels, branches, childScale, curl, spread, falloff, shapePower, amplitude, seed, tags, claims); - } - - private static void EmitIfsLevel( - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - string name, - Vector2 center, - Vector2 radii, - int levelsRemaining, - int branches, - float childScale, - float spread, - float rotationStep, - float falloff, - float shapePower, - float amplitude, - int seed, - string tags, - List claims) - { - var level = claims.Count; - claims.Add(FieldClaim(AquariumFractalPayloadKind.Height, domainKey, nodeKey, $"{name}/{level}", claims.Count, center, radii, rotationStep * level, falloff, shapePower, amplitude, seed + level, tags)); - - if (levelsRemaining <= 1) - { - return; - } - - var nextRadii = radii * childScale; - for (var branch = 0; branch < branches; branch++) - { - var phase = ((MathF.Tau * branch) / branches) + rotationStep * level + HashAngle(seed, level, branch); - var offset = new Vector2(MathF.Cos(phase), MathF.Sin(phase)) * spread * MathF.Max(nextRadii.X, nextRadii.Y); - EmitIfsLevel( - domainKey, - nodeKey, - name, - center + offset, - nextRadii, - levelsRemaining - 1, - branches, - childScale, - spread, - rotationStep, - falloff, - shapePower, - amplitude * childScale, - seed + 31 + branch, - tags, - claims); - } - } - - private static void EmitFlameLevel( - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - string name, - Vector2 center, - Vector2 radii, - float spiralAngle, - int levelsRemaining, - int branches, - float childScale, - float curl, - float spread, - float falloff, - float shapePower, - float amplitude, - int seed, - string tags, - List claims) - { - var level = claims.Count; - var rotation = spiralAngle + curl * level; - claims.Add(FieldClaim(AquariumFractalPayloadKind.Density, domainKey, nodeKey, $"{name}/{level}", claims.Count, center, radii, rotation, falloff, shapePower, amplitude, seed + level, tags)); - - if (levelsRemaining <= 1) - { - return; - } - - var nextRadii = radii * childScale; - var branchStep = MathF.Tau / branches; - for (var branch = 0; branch < branches; branch++) - { - var turn = spiralAngle + curl + (branchStep * branch) + HashAngle(seed, level, branch) * 0.5f; - var reach = spread * MathF.Max(nextRadii.X, nextRadii.Y) * (1.0f + branch * 0.17f); - var offset = new Vector2(MathF.Cos(turn), MathF.Sin(turn)) * reach; - EmitFlameLevel( - domainKey, - nodeKey, - name, - center + offset, - nextRadii, - turn, - levelsRemaining - 1, - branches, - childScale, - curl, - spread, - falloff, - shapePower, - amplitude * MathF.Sqrt(childScale), - seed + 97 + (branch * 17), - tags, - claims); - } - } - - private static AquariumBrushClaim FieldClaim( - AquariumFractalPayloadKind payloadKind, - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - string name, - int claimIndex, - Vector2 center, - Vector2 radii, - float rotationRadians, - float falloff, - float shapePower, - float amplitude, - int seed, - string tags, - float waveAmplitude = 0.0f, - float waveFrequency = 0.0f, - float waveSpeed = 0.0f, - float waveSinePower = 0.0f) - { - return new AquariumBrushClaim( - FractalStableKeyBuilder.Child(nodeKey, $"claim/{claimIndex:0000}/{name}"), - domainKey, - nodeKey, - payloadKind, - center, - radii, - rotationRadians, - falloff, - shapePower, - amplitude, - seed, - tags, - waveAmplitude, - waveFrequency, - waveSpeed, - waveSinePower); - } - - private static string StripComment(string line) - { - var index = line.IndexOf('#', StringComparison.Ordinal); - return index < 0 ? line : line[..index]; - } - - private static void EnsureTokenCount(string[] tokens, int minimum, int lineIndex) - { - if (tokens.Length < minimum) - { - throw new FormatException($"Command `{tokens[0]}` at line {lineIndex + 1} expected at least {minimum - 1} arguments."); - } - } - - private static void EnsureDomain(AquariumFractalDomain? domain, int lineIndex) - { - if (domain is null) - { - throw new FormatException($"Fractal DSL claim at line {lineIndex + 1} appears before a tile declaration."); - } - } - - private static void EnsureNode(NodeDraft? node, int lineIndex) - { - if (node is null) - { - throw new FormatException($"Fractal DSL claim at line {lineIndex + 1} appears before a tile root was created."); - } - } - - private static void EnsureAffineIfs(AffineIfsDraft? draft, int lineIndex) - { - if (draft is null) - { - throw new FormatException($"Affine IFS map at line {lineIndex + 1} appears before an affineifs declaration."); - } - } - - private static FractalAffineIfsDefinition[] BuildAffineIfsDefinitions(IReadOnlyList drafts) - { - var definitions = new FractalAffineIfsDefinition[drafts.Count]; - for (var index = 0; index < drafts.Count; index++) - { - var draft = drafts[index]; - definitions[index] = new FractalAffineIfsDefinition( - draft.Key, - draft.DomainKey, - draft.Name, - draft.Start, - draft.Seed, - draft.Tags, - draft.Transforms.ToArray()); - } - - return definitions; - } - - private static AquariumFractalNode[] BuildNodes(IReadOnlyList drafts, IReadOnlyList claims) - { - var nodes = new AquariumFractalNode[drafts.Count]; - for (var nodeIndex = 0; nodeIndex < drafts.Count; nodeIndex++) - { - var draft = drafts[nodeIndex]; - nodes[nodeIndex] = new AquariumFractalNode( - draft.Key, - draft.DomainKey, - default, - AquariumFractalOperation.Union, - FirstChildIndex: 0, - ChildCount: 0, - draft.FirstClaimIndex, - draft.ClaimCount, - BoundsForClaims(claims, draft.FirstClaimIndex, draft.ClaimCount), - Seed: 0); - } - - return nodes; - } - - private static Vector4 BoundsForClaims(IReadOnlyList claims, int firstClaimIndex, int claimCount) - { - if (claimCount == 0) - { - return Vector4.Zero; - } - - var minX = float.PositiveInfinity; - var minY = float.PositiveInfinity; - var maxX = float.NegativeInfinity; - var maxY = float.NegativeInfinity; - - for (var index = firstClaimIndex; index < firstClaimIndex + claimCount; index++) - { - var claim = claims[index]; - var radius = MathF.Max(claim.Radii.X, claim.Radii.Y); - minX = MathF.Min(minX, claim.Center.X - radius); - minY = MathF.Min(minY, claim.Center.Y - radius); - maxX = MathF.Max(maxX, claim.Center.X + radius); - maxY = MathF.Max(maxY, claim.Center.Y + radius); - } - - return new Vector4(minX, minY, maxX, maxY); - } - - private static CubeFace ParseFace(string value, int lineIndex) - { - if (Enum.TryParse(value, ignoreCase: false, out var face)) - { - return face; - } - - throw new FormatException($"Invalid cube face `{value}` at line {lineIndex + 1}."); - } - - private static int ParsePositiveInt(string value, int lineIndex) - { - var parsed = ParseInt(value, lineIndex); - if (parsed <= 0) - { - throw new FormatException($"Expected positive integer at line {lineIndex + 1}, got `{value}`."); - } - - return parsed; - } - - private static int ParseInt(string value, int lineIndex) - { - if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsed)) - { - return parsed; - } - - throw new FormatException($"Invalid integer `{value}` at line {lineIndex + 1}."); - } - - private static float ParsePositiveFloat(string value, int lineIndex) - { - var parsed = ParseFloat(value, lineIndex); - if (parsed <= 0.0f) - { - throw new FormatException($"Expected positive number at line {lineIndex + 1}, got `{value}`."); - } - - return parsed; - } - - private static float ParseFloat(string value, int lineIndex) - { - if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var parsed)) - { - return parsed; - } - - throw new FormatException($"Invalid number `{value}` at line {lineIndex + 1}."); - } - - private static float HashAngle(int seed, int level, int branch) - { - var value = (seed * 1103515245) ^ (level * 374761393) ^ (branch * 668265263); - value ^= value >> 13; - value *= 1274126177; - value ^= value >> 16; - var normalized = (value & 0xFFFF) / 65535.0f; - return (normalized - 0.5f) * 0.35f; - } - - private sealed class NodeDraft(AquariumFractalKey key, AquariumFractalKey domainKey, int firstClaimIndex) - { - public AquariumFractalKey Key { get; } = key; - - public AquariumFractalKey DomainKey { get; } = domainKey; - - public int FirstClaimIndex { get; } = firstClaimIndex; - - public int ClaimCount { get; set; } - } - - private sealed class AffineIfsDraft( - AquariumFractalKey key, - AquariumFractalKey domainKey, - string name, - Vector2 start, - int seed, - string tags) - { - public AquariumFractalKey Key { get; } = key; - - public AquariumFractalKey DomainKey { get; } = domainKey; - - public string Name { get; } = name; - - public Vector2 Start { get; } = start; - - public int Seed { get; } = seed; - - public string Tags { get; } = tags; - - public List Transforms { get; } = []; - } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalFlameChaosGame.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalFlameChaosGame.cs deleted file mode 100644 index aecdf84..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalFlameChaosGame.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Grammar; - -public static class FractalFlameChaosGame -{ - public static Vector2[] Generate( - FractalFlameDefinition definition, - int count, - int burnIn, - IFractalRandom random) - { - ArgumentNullException.ThrowIfNull(definition); - ArgumentNullException.ThrowIfNull(random); - ArgumentOutOfRangeException.ThrowIfNegative(count); - ArgumentOutOfRangeException.ThrowIfNegative(burnIn); - - var points = new Vector2[count]; - var point = definition.Start; - var total = definition.Transforms.Sum(transform => MathF.Max(transform.Weight, 0.0f)); - if (total <= 0.0f) - { - throw new ArgumentException("Flame transform weights must have positive total.", nameof(definition)); - } - - for (var step = 0; step < burnIn + count; step++) - { - point = SelectTransform(definition.Transforms, total, (float)random.NextDouble()).Apply(point, random); - if (step >= burnIn) - { - points[step - burnIn] = point; - } - } - - return points; - } - - private static FractalFlameTransform2D SelectTransform( - IReadOnlyList transforms, - float total, - float unit) - { - var target = unit * total; - var cumulative = 0.0f; - for (var index = 0; index < transforms.Count; index++) - { - cumulative += MathF.Max(transforms[index].Weight, 0.0f); - if (target <= cumulative) - { - return transforms[index]; - } - } - - return transforms[^1]; - } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalFlameDefinition.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalFlameDefinition.cs deleted file mode 100644 index 4a88926..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalFlameDefinition.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Grammar; - -public readonly record struct FractalFlameVariationWeights( - float Linear, - float Spherical, - float Bubble, - float Disc = 0.0f, - float Julian = 0.0f, - float JulianPower = 2.0f, - float JulianDist = 1.0f, - float GaussianBlur = 0.0f) -{ - public bool HasAny => - Linear != 0.0f || - Spherical != 0.0f || - Bubble != 0.0f || - Disc != 0.0f || - Julian != 0.0f || - GaussianBlur != 0.0f; - - public Vector2 Apply(Vector2 point, IFractalRandom? random = null) - { - var result = Vector2.Zero; - if (Linear != 0.0f) - { - result += point * Linear; - } - - var radiusSquared = Vector2.Dot(point, point); - if (Spherical != 0.0f) - { - result += point * (Spherical / MathF.Max(radiusSquared, 0.000001f)); - } - - if (Bubble != 0.0f) - { - result += point * (Bubble * 4.0f / (radiusSquared + 4.0f)); - } - - if (Disc != 0.0f) - { - var radius = MathF.Sqrt(radiusSquared); - var theta = MathF.Atan2(point.X, point.Y); - var scaledTheta = Disc * theta / MathF.PI; - result += new Vector2( - MathF.Sin(MathF.PI * radius) * scaledTheta, - MathF.Cos(MathF.PI * radius) * scaledTheta); - } - - if (Julian != 0.0f) - { - var power = MathF.Abs(JulianPower) < 1.0f ? 1.0f : JulianPower; - var absPower = MathF.Max(MathF.Abs(power), 1.0f); - var branch = MathF.Floor(NextUnit(random) * absPower); - var angle = (MathF.Atan2(point.Y, point.X) + (2.0f * MathF.PI * branch)) / power; - var radius = MathF.Pow(MathF.Max(MathF.Sqrt(radiusSquared), 0.000001f), JulianDist / power); - result += new Vector2(MathF.Cos(angle), MathF.Sin(angle)) * (Julian * radius); - } - - if (GaussianBlur != 0.0f) - { - var amount = GaussianBlur * (NextUnit(random) + NextUnit(random) + NextUnit(random) + NextUnit(random) - 2.0f); - var angle = NextUnit(random) * 2.0f * MathF.PI; - result += new Vector2(MathF.Cos(angle), MathF.Sin(angle)) * amount; - } - - return result; - } - - private static float NextUnit(IFractalRandom? random) - { - return random is null ? 0.5f : (float)random.NextDouble(); - } -} - -public readonly record struct FractalFlameTransform2D( - string Name, - Vector4 Matrix, - Vector2 Translation, - Vector4 PostMatrix, - Vector2 PostTranslation, - float Weight, - float Color, - FractalFlameVariationWeights Variations) -{ - public Vector2 Apply(Vector2 point) - { - return Apply(point, random: null); - } - - public Vector2 Apply(Vector2 point, IFractalRandom? random) - { - var affine = new Vector2( - (Matrix.X * point.X) + (Matrix.Y * point.Y) + Translation.X, - (Matrix.Z * point.X) + (Matrix.W * point.Y) + Translation.Y); - var varied = Variations.HasAny ? Variations.Apply(affine, random) : affine; - return new Vector2( - (PostMatrix.X * varied.X) + (PostMatrix.Y * varied.Y) + PostTranslation.X, - (PostMatrix.Z * varied.X) + (PostMatrix.W * varied.Y) + PostTranslation.Y); - } -} - -public sealed class FractalFlameDefinition -{ - public FractalFlameDefinition( - string name, - Vector2 start, - int seed, - IReadOnlyList transforms) - { - if (string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentException("Flame name must not be empty.", nameof(name)); - } - - if (transforms.Count == 0) - { - throw new ArgumentException("Flame definitions need at least one transform.", nameof(transforms)); - } - - Name = name; - Start = start; - Seed = seed; - Transforms = transforms; - } - - public string Name { get; } - - public Vector2 Start { get; } - - public int Seed { get; } - - public IReadOnlyList Transforms { get; } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalFlameFileParser.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalFlameFileParser.cs deleted file mode 100644 index b607301..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalFlameFileParser.cs +++ /dev/null @@ -1,332 +0,0 @@ -using System.Globalization; -using System.Numerics; -using System.Xml.Linq; - -namespace Aquarium.Engine.Fractal.Grammar; - -public static class FractalFlameFileParser -{ - public static FractalFlameDefinition ParseFirst(string source, int seed = 0) - { - return ParseFirstWithReport(source, seed).Definition; - } - - public static FractalFlameParseResult ParseFirstWithReport(string source, int seed = 0) - { - ArgumentNullException.ThrowIfNull(source); - - var document = XDocument.Parse(source); - var flame = document.Descendants("flame").FirstOrDefault() - ?? throw new FormatException("Flame file does not contain a flame element."); - var name = ((string?)flame.Attribute("name")) ?? "flame"; - var isJWildfireDialect = string.Equals(document.Root?.Name.LocalName, "Flames", StringComparison.Ordinal) - || flame.Elements("xform").Any(xform => xform.Element("variationGroup") is not null); - var parsed = flame.Elements("xform").Select((xform, index) => ParseXform(xform, index, isJWildfireDialect)).ToArray(); - var definition = new FractalFlameDefinition(name, Vector2.Zero, seed, parsed.Select(row => row.Transform).ToArray()); - var report = new FractalFlameImportReport( - name, - isJWildfireDialect ? "JWildfire" : "Apophysis/FLAM3 subset", - parsed.Length, - BuildFlameFieldReports(flame), - parsed.Select(row => row.Report).ToArray()); - return new FractalFlameParseResult(definition, report); - } - - private static ParsedXform ParseXform(XElement element, int index, bool isJWildfireDialect) - { - var coefs = ParseFloatList((string?)element.Attribute("coefs"), expectedCount: 6, "xform coefs"); - var variationGroup = element.Element("variationGroup"); - var variationSource = variationGroup ?? element; - var accepted = new List { "coefs", "weight", "color" }; - var approximated = new List(); - var ignored = new List(); - var rejected = new List(); - if (element.Attribute("name") is not null) - { - accepted.Add("name"); - } - - if (isJWildfireDialect) - { - accepted.Add("coefs: JWildfire xy layout"); - } - - if (variationGroup is not null) - { - accepted.Add("variationGroup"); - } - - var matrix = isJWildfireDialect - ? new Vector4(coefs[0], coefs[1], coefs[2], coefs[3]) - : new Vector4(coefs[0], coefs[1], coefs[3], coefs[4]); - var translation = isJWildfireDialect - ? new Vector2(coefs[4], coefs[5]) - : new Vector2(coefs[2], coefs[5]); - var post = ParseOptionalFloatList((string?)element.Attribute("post"), expectedCount: 6); - var postMatrix = post is null - ? new Vector4(1.0f, 0.0f, 0.0f, 1.0f) - : isJWildfireDialect - ? new Vector4(post[0], post[1], post[2], post[3]) - : new Vector4(post[0], post[1], post[3], post[4]); - var postTranslation = post is null - ? Vector2.Zero - : isJWildfireDialect - ? new Vector2(post[4], post[5]) - : new Vector2(post[2], post[5]); - var variations = new FractalFlameVariationWeights( - ParseOptionalFloat(variationSource, "linear", 0.0f) - + (isJWildfireDialect ? 0.0f : ParseOptionalFloat(variationSource, "normal", 0.0f)), - ParseOptionalFloat(variationSource, "spherical", 0.0f), - ParseOptionalFloat(variationSource, "bubble", 0.0f), - ParseOptionalFloat(variationSource, "disc", 0.0f) + ParseOptionalFloat(variationSource, "jwf_disc", 0.0f), - ParseOptionalFloat(variationSource, "julian", 0.0f) + ParseOptionalFloat(variationSource, "jwf_julian", 0.0f), - ParseOptionalFloat(variationSource, "julian_power", ParseOptionalFloat(variationSource, "jwf_julian_power", 2.0f)), - ParseOptionalFloat(variationSource, "julian_dist", ParseOptionalFloat(variationSource, "jwf_julian_dist", 1.0f)), - ParseOptionalFloat(variationSource, "gaussian_blur", 0.0f) + ParseOptionalFloat(variationSource, "jwf_gaussian_blur", 0.0f)); - ClassifyVariationFields(variationSource, isJWildfireDialect, accepted, approximated, ignored, rejected); - ClassifyXformFields(element, variationGroup, accepted, ignored, rejected); - var transformName = ((string?)element.Attribute("name")) ?? $"xform/{index:0000}"; - - var transform = new FractalFlameTransform2D( - transformName, - matrix, - translation, - postMatrix, - postTranslation, - ParseOptionalFloat(element, "weight", 1.0f), - ParseOptionalFloat(element, "color", 0.0f), - variations); - return new ParsedXform(transform, new FractalFlameTransformImportReport( - index, - transformName, - accepted.Distinct().OrderBy(value => value, StringComparer.Ordinal).ToArray(), - approximated.Distinct().OrderBy(value => value, StringComparer.Ordinal).ToArray(), - ignored.Distinct().OrderBy(value => value, StringComparer.Ordinal).ToArray(), - rejected.Distinct().OrderBy(value => value, StringComparer.Ordinal).ToArray())); - } - - private static float ParseOptionalFloat(XElement element, string name, float fallback) - { - var attribute = (string?)element.Attribute(name); - return attribute is null ? fallback : float.Parse(attribute, CultureInfo.InvariantCulture); - } - - private static float[] ParseFloatList(string? source, int expectedCount, string label) - { - if (string.IsNullOrWhiteSpace(source)) - { - throw new FormatException($"{label} must not be empty."); - } - - var values = source - .Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .Select(value => float.Parse(value, CultureInfo.InvariantCulture)) - .ToArray(); - if (values.Length != expectedCount) - { - throw new FormatException($"{label} expected {expectedCount} values, got {values.Length}."); - } - - return values; - } - - private static float[]? ParseOptionalFloatList(string? source, int expectedCount) - { - return string.IsNullOrWhiteSpace(source) - ? null - : ParseFloatList(source, expectedCount, "optional float list"); - } - - private static IReadOnlyList BuildFlameFieldReports(XElement flame) - { - var structural = new HashSet(StringComparer.Ordinal) - { - "name", - "size", - "center", - "scale", - "rotate", - }; - return flame.Attributes() - .Select(attribute => attribute.Name.LocalName) - .Where(name => !structural.Contains(name)) - .OrderBy(name => name, StringComparer.Ordinal) - .ToArray(); - } - - private static void ClassifyVariationFields( - XElement variationSource, - bool isJWildfireDialect, - List accepted, - List approximated, - List ignored, - List rejected) - { - var supported = new HashSet(StringComparer.Ordinal) - { - "linear", - "spherical", - "bubble", - "disc", - "jwf_disc", - "julian", - "jwf_julian", - "julian_power", - "jwf_julian_power", - "julian_dist", - "jwf_julian_dist", - }; - foreach (var attribute in variationSource.Attributes()) - { - var name = attribute.Name.LocalName; - if (supported.Contains(name)) - { - accepted.Add($"variation:{name}"); - continue; - } - - if (name is "normal") - { - if (isJWildfireDialect) - { - ignored.Add("variationGroup:normal"); - } - else - { - approximated.Add("variation:normal -> linear"); - } - - continue; - } - - if (name is "gaussian_blur" or "jwf_gaussian_blur") - { - approximated.Add($"variation:{name} -> stochastic gaussian_blur"); - continue; - } - - if (TryParseFloat(attribute.Value, out var value) && value == 0.0f) - { - ignored.Add($"variation:{name}=0"); - continue; - } - - rejected.Add($"variation:{name}"); - } - } - - private static void ClassifyXformFields( - XElement element, - XElement? variationGroup, - List accepted, - List ignored, - List rejected) - { - var handled = new HashSet(StringComparer.Ordinal) - { - "name", - "coefs", - "weight", - "color", - }; - foreach (var attribute in element.Attributes()) - { - var name = attribute.Name.LocalName; - if (handled.Contains(name)) - { - continue; - } - - if (name is "post") - { - accepted.Add(IsIdentityPost(attribute.Value) ? "post=identity" : "post"); - continue; - } - - if (name is "chaos") - { - if (IsNeutralFloatList(attribute.Value, 1.0f)) - { - ignored.Add("chaos=all-ones"); - } - else - { - rejected.Add("chaos"); - } - - continue; - } - - if (name.StartsWith("wfield_", StringComparison.Ordinal)) - { - rejected.Add(name); - continue; - } - - ignored.Add(name); - } - - if (variationGroup is not null) - { - foreach (var child in element.Elements()) - { - if (child != variationGroup) - { - ignored.Add(child.Name.LocalName); - } - } - } - } - - private static bool IsIdentityPost(string value) - { - var values = ParseFloatList(value, 6, "post"); - return values[0] == 1.0f - && values[1] == 0.0f - && values[2] == 0.0f - && values[3] == 1.0f - && values[4] == 0.0f - && values[5] == 0.0f; - } - - private static bool IsNeutralFloatList(string value, float neutral) - { - var values = value.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - return values.Length > 0 && values.All(item => TryParseFloat(item, out var parsed) && parsed == neutral); - } - - private static bool TryParseFloat(string source, out float value) - { - return float.TryParse(source, NumberStyles.Float, CultureInfo.InvariantCulture, out value); - } - - private readonly record struct ParsedXform(FractalFlameTransform2D Transform, FractalFlameTransformImportReport Report); -} - -public sealed record FractalFlameParseResult( - FractalFlameDefinition Definition, - FractalFlameImportReport Report); - -public sealed record FractalFlameImportReport( - string FlameName, - string Dialect, - int TransformCount, - IReadOnlyList IgnoredFlameAttributes, - IReadOnlyList Transforms) -{ - public int AcceptedFieldCount => Transforms.Sum(transform => transform.AcceptedFields.Count); - - public int ApproximatedFieldCount => Transforms.Sum(transform => transform.ApproximatedFields.Count); - - public int IgnoredFieldCount => IgnoredFlameAttributes.Count + Transforms.Sum(transform => transform.IgnoredFields.Count); - - public int RejectedFieldCount => Transforms.Sum(transform => transform.RejectedFields.Count); -} - -public sealed record FractalFlameTransformImportReport( - int Index, - string Name, - IReadOnlyList AcceptedFields, - IReadOnlyList ApproximatedFields, - IReadOnlyList IgnoredFields, - IReadOnlyList RejectedFields); diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalFlameIterationState.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalFlameIterationState.cs deleted file mode 100644 index 42b63dd..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalFlameIterationState.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Grammar; - -public readonly record struct FractalFlameIterationState( - Vector2 Point, - uint RandomState, - int Step) -{ - public static FractalFlameIterationState Create(uint seed, int sampleIndex) - { - var state = Hash(seed ^ (uint)sampleIndex); - return new FractalFlameIterationState(Vector2.Zero, state == 0 ? 0xA341316Cu : state, 0); - } - - private static uint Hash(uint value) - { - value ^= value >> 16; - value *= 747796405u; - value ^= value >> 16; - value *= 2891336453u; - value ^= value >> 16; - return value; - } -} - -public static class FractalFlameIterationStepper -{ - public static FractalFlameIterationState Advance( - FractalFlameDefinition definition, - FractalFlameIterationState state, - int iterations) - { - ArgumentNullException.ThrowIfNull(definition); - ArgumentOutOfRangeException.ThrowIfNegative(iterations); - - var random = new StatefulRandom(state.RandomState); - var point = state.Point; - var total = definition.Transforms.Sum(transform => MathF.Max(transform.Weight, 0.0f)); - if (total <= 0.0f) - { - throw new ArgumentException("Flame transform weights must have positive total.", nameof(definition)); - } - - for (var iteration = 0; iteration < iterations; iteration++) - { - point = SelectTransform(definition.Transforms, total, (float)random.NextDouble()).Apply(point, random); - } - - return new FractalFlameIterationState(point, random.State, checked(state.Step + iterations)); - } - - private static FractalFlameTransform2D SelectTransform( - IReadOnlyList transforms, - float total, - float unit) - { - var target = unit * total; - var cumulative = 0.0f; - for (var index = 0; index < transforms.Count; index++) - { - cumulative += MathF.Max(transforms[index].Weight, 0.0f); - if (target <= cumulative) - { - return transforms[index]; - } - } - - return transforms[^1]; - } - - private sealed class StatefulRandom(uint state) : IFractalRandom - { - public uint State { get; private set; } = state == 0 ? 0xA341316Cu : state; - - public double NextDouble() - { - var value = State; - value ^= value << 13; - value ^= value >> 17; - value ^= value << 5; - State = value; - return value / ((double)uint.MaxValue + 1.0); - } - } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalHistogramResidualFocus.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalHistogramResidualFocus.cs deleted file mode 100644 index 1e8b5b5..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalHistogramResidualFocus.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Grammar; - -public static class FractalHistogramResidualFocus -{ - public static Vector4 Estimate(FractalPointHistogram reference, FractalPointHistogram candidate) - { - if (reference.Width != candidate.Width || reference.Height != candidate.Height) - { - throw new ArgumentException("Histogram dimensions must match.", nameof(candidate)); - } - - if (reference.Bins.Length != candidate.Bins.Length) - { - throw new ArgumentException("Histogram bin counts must match.", nameof(candidate)); - } - - var referenceTotal = Math.Max(reference.HitCount, 1); - var candidateTotal = Math.Max(candidate.HitCount, 1); - var span = new Vector2(reference.Bounds.Z - reference.Bounds.X, reference.Bounds.W - reference.Bounds.Y); - var weighted = Vector2.Zero; - var mass = 0.0f; - - for (var y = 0; y < reference.Height; y++) - { - for (var x = 0; x < reference.Width; x++) - { - var index = (y * reference.Width) + x; - var delta = (reference.Bins[index] / (float)referenceTotal) - (candidate.Bins[index] / (float)candidateTotal); - if (delta <= 0.0f) - { - continue; - } - - var world = BinCenter(reference, span, x, y); - weighted += world * delta; - mass += delta; - } - } - - if (mass <= 0.0f) - { - return Vector4.Zero; - } - - var center = weighted / mass; - var variance = 0.0f; - for (var y = 0; y < reference.Height; y++) - { - for (var x = 0; x < reference.Width; x++) - { - var index = (y * reference.Width) + x; - var delta = (reference.Bins[index] / (float)referenceTotal) - (candidate.Bins[index] / (float)candidateTotal); - if (delta <= 0.0f) - { - continue; - } - - var world = BinCenter(reference, span, x, y); - variance += Vector2.DistanceSquared(world, center) * delta; - } - } - - var minRadius = MathF.Max(span.X / MathF.Max(reference.Width, 1), span.Y / MathF.Max(reference.Height, 1)) * 1.5f; - var maxRadius = MathF.Max(span.X, span.Y) * 0.75f; - var radius = Math.Clamp(MathF.Sqrt(variance / mass) * 2.0f, minRadius, maxRadius); - var strength = Math.Clamp(mass * 3.0f, 0.05f, 1.0f); - return new Vector4(center.X, center.Y, radius, strength); - } - - private static Vector2 BinCenter(FractalPointHistogram histogram, Vector2 span, int x, int y) - { - return new Vector2( - histogram.Bounds.X + ((x + 0.5f) / histogram.Width) * span.X, - histogram.Bounds.Y + ((y + 0.5f) / histogram.Height) * span.Y); - } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalOwnershipTree.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalOwnershipTree.cs deleted file mode 100644 index 3ce34b8..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalOwnershipTree.cs +++ /dev/null @@ -1,51 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Grammar; - -public sealed class FractalOwnershipTree -{ - public FractalOwnershipTree( - AquariumFractalDomain domain, - IReadOnlyList nodes, - IReadOnlyList claims) - : this(domain, [domain], nodes, claims, []) - { - } - - public FractalOwnershipTree( - AquariumFractalDomain domain, - IReadOnlyList domains, - IReadOnlyList nodes, - IReadOnlyList claims) - : this(domain, domains, nodes, claims, []) - { - } - - public FractalOwnershipTree( - AquariumFractalDomain domain, - IReadOnlyList domains, - IReadOnlyList nodes, - IReadOnlyList claims, - IReadOnlyList affineIfsDefinitions) - { - Domain = domain; - DomainGraph = new FractalDomainGraph(domains); - DomainGraph.GetRequired(domain.Key); - Domains = DomainGraph.Domains; - Nodes = nodes; - Claims = claims; - AffineIfsDefinitions = affineIfsDefinitions; - } - - public AquariumFractalDomain Domain { get; } - - public IReadOnlyList Domains { get; } - - public FractalDomainGraph DomainGraph { get; } - - public IReadOnlyList Nodes { get; } - - public IReadOnlyList Claims { get; } - - public IReadOnlyList AffineIfsDefinitions { get; } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalOwnershipTreeBuilder.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalOwnershipTreeBuilder.cs deleted file mode 100644 index 3a686e0..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalOwnershipTreeBuilder.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Grammar; - -public static class FractalOwnershipTreeBuilder -{ - public static FractalOwnershipTree BuildFlatUnion( - AquariumFractalDomain domain, - AquariumFractalKey rootKey, - IReadOnlyList claims) - { - return BuildFlatUnion(domain, [domain], rootKey, claims); - } - - public static FractalOwnershipTree BuildFlatUnion( - AquariumFractalDomain domain, - IReadOnlyList domains, - AquariumFractalKey rootKey, - IReadOnlyList claims) - { - ArgumentNullException.ThrowIfNull(claims); - ArgumentNullException.ThrowIfNull(domains); - - var bounds = BoundsForClaims(claims); - var root = new AquariumFractalNode( - rootKey, - domain.Key, - default, - AquariumFractalOperation.Union, - FirstChildIndex: 0, - ChildCount: 0, - FirstClaimIndex: 0, - ClaimCount: claims.Count, - bounds, - Seed: 0); - - return new FractalOwnershipTree(domain, domains, [root], claims); - } - - private static Vector4 BoundsForClaims(IReadOnlyList claims) - { - if (claims.Count == 0) - { - return Vector4.Zero; - } - - var minX = float.PositiveInfinity; - var minY = float.PositiveInfinity; - var maxX = float.NegativeInfinity; - var maxY = float.NegativeInfinity; - - foreach (var claim in claims) - { - var radius = MathF.Max(claim.Radii.X, claim.Radii.Y); - minX = MathF.Min(minX, claim.Center.X - radius); - minY = MathF.Min(minY, claim.Center.Y - radius); - maxX = MathF.Max(maxX, claim.Center.X + radius); - maxY = MathF.Max(maxY, claim.Center.Y + radius); - } - - return new Vector4(minX, minY, maxX, maxY); - } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalPointHistogram.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalPointHistogram.cs deleted file mode 100644 index 2b78528..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalPointHistogram.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Grammar; - -public readonly record struct FractalPointHistogram( - int Width, - int Height, - Vector4 Bounds, - int[] Bins) -{ - public int HitCount => Bins.Sum(); - - public int this[int x, int y] => Bins[y * Width + x]; -} - -public static class FractalPointHistogramBuilder -{ - public static FractalPointHistogram Build( - IReadOnlyList points, - int width, - int height, - Vector4 bounds) - { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - - var bins = new int[width * height]; - var span = new Vector2(bounds.Z - bounds.X, bounds.W - bounds.Y); - foreach (var point in points) - { - var u = (point.X - bounds.X) / MathF.Max(span.X, 0.000001f); - var v = (point.Y - bounds.Y) / MathF.Max(span.Y, 0.000001f); - if (u < 0.0f || u >= 1.0f || v < 0.0f || v >= 1.0f) - { - continue; - } - - var x = Math.Clamp((int)(u * width), 0, width - 1); - var y = Math.Clamp((int)(v * height), 0, height - 1); - bins[y * width + x]++; - } - - return new FractalPointHistogram(width, height, bounds, bins); - } -} - diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalPpmImageReceipt.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalPpmImageReceipt.cs deleted file mode 100644 index a19f05f..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalPpmImageReceipt.cs +++ /dev/null @@ -1,149 +0,0 @@ -namespace Aquarium.Engine.Fractal.Grammar; - -public readonly record struct FractalPpmImageReceipt( - int Width, - int Height, - int MaxChannelValue, - int PixelCount, - int NonBlackPixelCount, - ulong RgbChecksum, - ulong LuminanceChecksum); - -public static class FractalPpmImageReceiptBuilder -{ - public static FractalPpmImageReceipt Build(ReadOnlySpan bytes) - { - var cursor = 0; - var magic = ReadToken(bytes, ref cursor); - if (!magic.SequenceEqual("P6"u8)) - { - throw new FormatException("Only binary P6 PPM reference renders are supported."); - } - - var width = ParsePositiveInt(ReadToken(bytes, ref cursor), "width"); - var height = ParsePositiveInt(ReadToken(bytes, ref cursor), "height"); - var maxChannelValue = ParsePositiveInt(ReadToken(bytes, ref cursor), "max channel value"); - if (maxChannelValue > 255) - { - throw new FormatException("Only 8-bit PPM reference renders are supported."); - } - - ConsumeSingleWhitespace(bytes, ref cursor); - var expectedBytes = checked(width * height * 3); - if (bytes.Length - cursor < expectedBytes) - { - throw new FormatException("PPM reference render ended before all RGB pixels were present."); - } - - var rgbChecksum = 1469598103934665603UL; - var luminanceChecksum = 1469598103934665603UL; - var nonBlack = 0; - var pixels = bytes.Slice(cursor, expectedBytes); - for (var index = 0; index < pixels.Length; index += 3) - { - var r = pixels[index]; - var g = pixels[index + 1]; - var b = pixels[index + 2]; - rgbChecksum = Step(rgbChecksum, r); - rgbChecksum = Step(rgbChecksum, g); - rgbChecksum = Step(rgbChecksum, b); - var luminance = (byte)(((r * 54) + (g * 183) + (b * 19)) >> 8); - luminanceChecksum = Step(luminanceChecksum, luminance); - if ((r | g | b) != 0) - { - nonBlack++; - } - } - - return new FractalPpmImageReceipt( - width, - height, - maxChannelValue, - width * height, - nonBlack, - rgbChecksum, - luminanceChecksum); - } - - private static ulong Step(ulong hash, byte value) - { - hash ^= value; - hash *= 1099511628211UL; - return hash; - } - - private static ReadOnlySpan ReadToken(ReadOnlySpan bytes, ref int cursor) - { - SkipWhitespaceAndComments(bytes, ref cursor); - var start = cursor; - while (cursor < bytes.Length && !IsWhitespace(bytes[cursor]) && bytes[cursor] != (byte)'#') - { - cursor++; - } - - if (cursor == start) - { - throw new FormatException("PPM reference render header ended unexpectedly."); - } - - return bytes[start..cursor]; - } - - private static void SkipWhitespaceAndComments(ReadOnlySpan bytes, ref int cursor) - { - while (cursor < bytes.Length) - { - if (IsWhitespace(bytes[cursor])) - { - cursor++; - continue; - } - - if (bytes[cursor] != (byte)'#') - { - return; - } - - while (cursor < bytes.Length && bytes[cursor] != (byte)'\n') - { - cursor++; - } - } - } - - private static void ConsumeSingleWhitespace(ReadOnlySpan bytes, ref int cursor) - { - if (cursor >= bytes.Length || !IsWhitespace(bytes[cursor])) - { - throw new FormatException("PPM reference render header is missing the pixel-data separator."); - } - - cursor++; - } - - private static bool IsWhitespace(byte value) - { - return value is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n'; - } - - private static int ParsePositiveInt(ReadOnlySpan token, string name) - { - var value = 0; - foreach (var digit in token) - { - if (digit is < (byte)'0' or > (byte)'9') - { - throw new FormatException($"PPM {name} is not an integer."); - } - - value = checked((value * 10) + digit - (byte)'0'); - } - - if (value <= 0) - { - throw new FormatException($"PPM {name} must be positive."); - } - - return value; - } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalStableKeyBuilder.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalStableKeyBuilder.cs deleted file mode 100644 index 969a003..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalStableKeyBuilder.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Grammar; - -public static class FractalStableKeyBuilder -{ - public static AquariumFractalKey ForCubeTile(CubeTileKey tile, string grammarPath) - { - return new AquariumFractalKey($"cube/{tile.Face}/L{tile.Level:D2}/{tile.X}/{tile.Y}:{NormalizePath(grammarPath)}"); - } - - public static AquariumFractalKey Child(AquariumFractalKey parent, string segment) - { - return new AquariumFractalKey($"{parent.Value}/{NormalizePath(segment)}"); - } - - private static string NormalizePath(string value) - { - if (string.IsNullOrWhiteSpace(value)) - { - throw new ArgumentException("Fractal key path segment must not be empty.", nameof(value)); - } - - return value.Trim().Replace('\\', '/'); - } -} diff --git a/src/Aquarium.Engine.Fractal/Grammar/FractalSummaryBuilder.cs b/src/Aquarium.Engine.Fractal/Grammar/FractalSummaryBuilder.cs deleted file mode 100644 index 629fa14..0000000 --- a/src/Aquarium.Engine.Fractal/Grammar/FractalSummaryBuilder.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Grammar; - -public static class FractalSummaryBuilder -{ - public static AquariumFractalSummary[] Build(FractalOwnershipTree tree) - { - ArgumentNullException.ThrowIfNull(tree); - - var summaries = new AquariumFractalSummary[tree.Nodes.Count]; - for (var nodeIndex = 0; nodeIndex < tree.Nodes.Count; nodeIndex++) - { - var node = tree.Nodes[nodeIndex]; - var maxHeightError = 0.0f; - var estimatedCost = 0.0f; - var formEncodingMask = AquariumFieldEncodingFlags.None; - for (var claimIndex = node.FirstClaimIndex; claimIndex < node.FirstClaimIndex + node.ClaimCount; claimIndex++) - { - var claim = tree.Claims[claimIndex]; - if (IsFormPayload(claim.PayloadKind)) - { - maxHeightError += MathF.Abs(claim.Amplitude); - formEncodingMask |= EncodingFlagFor(claim.PayloadKind); - } - - estimatedCost += 1.0f; - } - - summaries[nodeIndex] = new AquariumFractalSummary( - node.Key, - node.BoundsMinMax, - maxHeightError, - MaxMaterialDelta: 0.0f, - estimatedCost, - DescendantCount: node.ChildCount + node.ClaimCount, - formEncodingMask); - } - - return summaries; - } - - private static bool IsFormPayload(AquariumFractalPayloadKind kind) - { - return kind is AquariumFractalPayloadKind.Height - or AquariumFractalPayloadKind.SignedDistance - or AquariumFractalPayloadKind.Density - or AquariumFractalPayloadKind.Extinction; - } - - private static AquariumFieldEncodingFlags EncodingFlagFor(AquariumFractalPayloadKind kind) - { - return kind switch - { - AquariumFractalPayloadKind.Height => AquariumFieldEncodingFlags.Height, - AquariumFractalPayloadKind.SignedDistance => AquariumFieldEncodingFlags.SignedDistance, - AquariumFractalPayloadKind.Density => AquariumFieldEncodingFlags.Density, - AquariumFractalPayloadKind.Extinction => AquariumFieldEncodingFlags.Extinction, - _ => AquariumFieldEncodingFlags.None, - }; - } -} diff --git a/src/Aquarium.Engine.Fractal/IFractalClock.cs b/src/Aquarium.Engine.Fractal/IFractalClock.cs deleted file mode 100644 index f76f934..0000000 --- a/src/Aquarium.Engine.Fractal/IFractalClock.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Aquarium.Engine.Fractal; - -public interface IFractalClock -{ - double TimeSeconds { get; } - - ulong FrameIndex { get; } -} diff --git a/src/Aquarium.Engine.Fractal/IFractalDebugSink.cs b/src/Aquarium.Engine.Fractal/IFractalDebugSink.cs deleted file mode 100644 index 63755f4..0000000 --- a/src/Aquarium.Engine.Fractal/IFractalDebugSink.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Aquarium.Engine.Fractal; - -public interface IFractalDebugSink -{ - void Record(string channel, string key, double value); -} diff --git a/src/Aquarium.Engine.Fractal/IFractalRandom.cs b/src/Aquarium.Engine.Fractal/IFractalRandom.cs deleted file mode 100644 index d62fa2c..0000000 --- a/src/Aquarium.Engine.Fractal/IFractalRandom.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Aquarium.Engine.Fractal; - -public interface IFractalRandom -{ - double NextDouble(); -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalContributionCache.cs b/src/Aquarium.Engine.Fractal/Lod/FractalContributionCache.cs deleted file mode 100644 index 568f0c6..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalContributionCache.cs +++ /dev/null @@ -1,92 +0,0 @@ -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Temporal; - -namespace Aquarium.Engine.Fractal.Lod; - -public sealed class FractalContributionCache -{ - private readonly FractalOccupancyGraph occupancy = new(); - private uint frameIndex; - - public FractalContributionReservoirSnapshot LastFrameReservoir { get; private set; } - - public FractalResourcePlan PlanFrame( - IReadOnlyList summaries, - Func projectedPixelsPerWorldUnit, - FractalResourceBudget budget, - IFractalRandom random, - IFractalPayloadStore payloadStore) - { - ArgumentNullException.ThrowIfNull(summaries); - ArgumentNullException.ThrowIfNull(projectedPixelsPerWorldUnit); - ArgumentNullException.ThrowIfNull(random); - ArgumentNullException.ThrowIfNull(payloadStore); - - frameIndex++; - var states = new AquariumContributionState[summaries.Count]; - var scores = new Dictionary(StringComparer.Ordinal); - for (var index = 0; index < summaries.Count; index++) - { - var summary = summaries[index]; - states[index] = occupancy.GetOrCreate(summary.NodeKey).Contribution; - var score = FractalProjectedErrorScorer.Score(summary, projectedPixelsPerWorldUnit(summary)); - scores[summary.NodeKey.Value] = score; - var updateProbability = FractalStochasticUpdateScheduler.UpdateProbability(states[index], score, frameIndex); - occupancy.MarkVisible(summary.NodeKey, score, frameIndex, updateProbability); - } - - var plan = FractalResourceBudgetPlanner.Plan( - summaries, - states, - projectedPixelsPerWorldUnit, - state => scores.TryGetValue(state.NodeKey.Value, out var score) ? score : 0.0f, - budget, - random, - payloadStore, - frameIndex); - - var reservoir = new ResampledImportanceReservoir(); - var resident = plan.Residency.ResidentNodes.Select(key => key.Value).ToHashSet(StringComparer.Ordinal); - foreach (var nodeKey in plan.UpdateNodes) - { - if (!scores.TryGetValue(nodeKey.Value, out var observedScore)) - { - continue; - } - - var state = occupancy.GetOrCreate(nodeKey).Contribution; - var updateProbability = FractalStochasticUpdateScheduler.UpdateProbability(state, observedScore, frameIndex); - var isResident = resident.Contains(nodeKey.Value); - var candidate = FractalContributionCandidateGenerator.Build( - nodeKey, - observedScore, - updateProbability, - frameIndex, - isResident); - reservoir.Add(candidate, random.NextDouble()); - occupancy.Observe(nodeKey, observedScore, frameIndex, isResident); - } - - occupancy.DecayUnobserved(frameIndex); - LastFrameReservoir = FractalContributionCandidateGenerator.Snapshot(reservoir); - return plan; - } - - public bool TryGet(AquariumFractalKey nodeKey, out AquariumContributionState state) - { - if (occupancy.TryGet(nodeKey, out var node)) - { - state = node.Contribution; - return true; - } - - state = default; - return false; - } - - public bool TryGetOccupancy(AquariumFractalKey nodeKey, out FractalOccupancyNodeState state) - { - return occupancy.TryGet(nodeKey, out state); - } - -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalContributionCandidate.cs b/src/Aquarium.Engine.Fractal/Lod/FractalContributionCandidate.cs deleted file mode 100644 index 9e1495e..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalContributionCandidate.cs +++ /dev/null @@ -1,71 +0,0 @@ -using Aquarium.Engine.Fractal.Temporal; - -namespace Aquarium.Engine.Fractal.Lod; - -public readonly record struct FractalContributionCandidate( - AquariumFractalKey NodeKey, - float ObservedContribution, - float UpdateProbability, - uint FrameIndex, - bool Resident); - -public readonly record struct FractalContributionReservoirSnapshot( - bool HasSample, - AquariumFractalKey SelectedNodeKey, - float SelectedContribution, - float SelectedTarget, - float WeightSum, - int CandidateCount, - float ContributionWeight); - -public static class FractalContributionCandidateGenerator -{ - public static ResampledImportanceCandidate Build( - AquariumFractalKey nodeKey, - float observedContribution, - double updateProbability, - uint frameIndex, - bool resident) - { - var target = MathF.Max(observedContribution, 0.0f); - var sourcePdf = MathF.Max((float)updateProbability, 1.0e-6f); - var sample = new FractalContributionCandidate( - nodeKey, - target, - sourcePdf, - frameIndex, - resident); - - return new ResampledImportanceCandidate( - sample, - target, - sourcePdf); - } - - public static FractalContributionReservoirSnapshot Snapshot( - ResampledImportanceReservoir reservoir) - { - ArgumentNullException.ThrowIfNull(reservoir); - if (!reservoir.HasSample) - { - return new FractalContributionReservoirSnapshot( - HasSample: false, - SelectedNodeKey: default, - SelectedContribution: 0.0f, - SelectedTarget: 0.0f, - WeightSum: reservoir.WeightSum, - CandidateCount: reservoir.CandidateCount, - ContributionWeight: 0.0f); - } - - var selected = reservoir.SelectedSample; - return new FractalContributionReservoirSnapshot( - HasSample: true, - SelectedNodeKey: selected.NodeKey, - SelectedContribution: selected.ObservedContribution, - SelectedTarget: reservoir.SelectedTarget, - WeightSum: reservoir.WeightSum, - CandidateCount: reservoir.CandidateCount, - ContributionWeight: reservoir.ContributionWeight); - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalContributionEstimator.cs b/src/Aquarium.Engine.Fractal/Lod/FractalContributionEstimator.cs deleted file mode 100644 index 56baf55..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalContributionEstimator.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalContributionEstimator -{ - public static AquariumContributionState Observe( - AquariumContributionState state, - float observedContribution, - uint frameIndex, - bool resident) - { - var sampleCount = state.SampleCount + 1; - var delta = observedContribution - state.MeanContribution; - var mean = state.MeanContribution + (delta / sampleCount); - var variance = sampleCount <= 1 - ? 0.0f - : (((sampleCount - 2) * state.Variance) + (delta * (observedContribution - mean))) / (sampleCount - 1); - var confidence = Math.Clamp(sampleCount / 16.0f, 0.0f, 1.0f); - - return state with - { - MeanContribution = mean, - Variance = MathF.Max(variance, 0.0f), - Confidence = confidence, - SampleCount = sampleCount, - LastSampledFrame = frameIndex, - Resident = resident, - }; - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalContributionTable.cs b/src/Aquarium.Engine.Fractal/Lod/FractalContributionTable.cs deleted file mode 100644 index 062cfb2..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalContributionTable.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public sealed class FractalContributionTable -{ - private readonly Dictionary states = new(StringComparer.Ordinal); - - public bool TryGet(AquariumFractalKey nodeKey, out AquariumContributionState state) - { - return states.TryGetValue(nodeKey.Value, out state); - } - - public AquariumContributionState GetOrCreate(AquariumFractalKey nodeKey) - { - if (states.TryGetValue(nodeKey.Value, out var state)) - { - return state; - } - - state = new AquariumContributionState( - nodeKey, - MeanContribution: 0.0f, - Variance: 1.0f, - Confidence: 0.0f, - SampleCount: 0, - LastSampledFrame: 0, - Resident: false); - states.Add(nodeKey.Value, state); - return state; - } - - public void Store(AquariumContributionState state) - { - states[state.NodeKey.Value] = state; - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalDensitySplat3DCompiler.cs b/src/Aquarium.Engine.Fractal/Lod/FractalDensitySplat3DCompiler.cs deleted file mode 100644 index 233ba71..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalDensitySplat3DCompiler.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalDensitySplat3DCompiler -{ - public static AquariumFractalDensitySplat3D FromProbe( - FractalProbeSample probe, - float depthRadius, - float densityScale = 1.0f, - float extinctionScale = 1.0f, - float falloff = 4.0f, - float shapePower = 1.0f) - { - if (probe.Layer != AquariumFieldLayer.Form || - (probe.Encoding != AquariumFieldEncoding.Density && probe.Encoding != AquariumFieldEncoding.Extinction)) - { - throw new ArgumentException("3D density splat lowering only accepts Form/Density or Form/Extinction probes.", nameof(probe)); - } - - if (!float.IsFinite(probe.BoundRadius) || probe.BoundRadius <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(probe), probe.BoundRadius, "Probe bound radius must be positive and finite."); - } - - if (!float.IsFinite(depthRadius) || depthRadius <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(depthRadius), depthRadius, "3D density splat depth radius must be positive and finite."); - } - - if (!float.IsFinite(densityScale) || densityScale < 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(densityScale), densityScale, "Density scale must be finite and non-negative."); - } - - if (!float.IsFinite(extinctionScale) || extinctionScale < 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(extinctionScale), extinctionScale, "Extinction scale must be finite and non-negative."); - } - - if (!float.IsFinite(falloff) || falloff <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(falloff), falloff, "3D density splat falloff must be positive and finite."); - } - - if (!float.IsFinite(shapePower) || shapePower <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(shapePower), shapePower, "3D density splat shape power must be positive and finite."); - } - - var contribution = Math.Clamp(probe.TargetContribution, 0.0f, 1.0f); - var density = probe.Encoding == AquariumFieldEncoding.Density - ? contribution * densityScale - : contribution; - var extinction = probe.Encoding == AquariumFieldEncoding.Extinction - ? contribution * extinctionScale - : contribution * densityScale * extinctionScale; - - return new AquariumFractalDensitySplat3D( - new AquariumFractalDensitySplat3DKey(probe.DomainKey, probe.NodeKey, probe.PayloadHandle), - probe.LocalCenter, - Quaternion.Identity, - new Vector3(probe.BoundRadius, probe.BoundRadius, depthRadius), - falloff, - shapePower, - Math.Clamp(density, 0.0f, 1.0f), - Math.Clamp(extinction, 0.0f, 1.0f), - contribution); - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalGpuProgramCompiler.cs b/src/Aquarium.Engine.Fractal/Lod/FractalGpuProgramCompiler.cs deleted file mode 100644 index d247865..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalGpuProgramCompiler.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Grammar; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalGpuProgramCompiler -{ - public static AquariumPackedFractalIfsTransform[] CompileFlame2D( - FractalFlameDefinition flame, - int maxTransformCount) - { - ArgumentNullException.ThrowIfNull(flame); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxTransformCount); - - var transforms = new AquariumPackedFractalIfsTransform[Math.Min(maxTransformCount, flame.Transforms.Count)]; - for (var index = 0; index < transforms.Length; index++) - { - transforms[index] = PackFlame(flame.Transforms[index]); - } - - return transforms; - } - - public static AquariumPackedFractalIfsTransform[] CompileSelectedTree( - FractalOwnershipTree tree, - IReadOnlyList selectedCut, - int maxTransformCount) - { - ArgumentNullException.ThrowIfNull(tree); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(maxTransformCount); - - if (selectedCut.Count == 0 || tree.Claims.Count == 0) - { - return []; - } - - var selected = selectedCut.Select(cut => cut.NodeKey).ToHashSet(); - var domains = tree.Domains.ToDictionary(domain => domain.Key); - var transforms = new List(Math.Min(maxTransformCount, tree.Claims.Count)); - foreach (var node in tree.Nodes) - { - if (!selected.Contains(node.Key)) - { - continue; - } - - var claimEnd = Math.Min(node.FirstClaimIndex + node.ClaimCount, tree.Claims.Count); - for (var claimIndex = node.FirstClaimIndex; claimIndex < claimEnd && transforms.Count < maxTransformCount; claimIndex++) - { - transforms.Add(Pack(tree.Claims[claimIndex], domains)); - } - - if (transforms.Count >= maxTransformCount) - { - break; - } - } - - return transforms.ToArray(); - } - - private static AquariumPackedFractalIfsTransform PackFlame(FractalFlameTransform2D transform) - { - return new AquariumPackedFractalIfsTransform( - transform.Matrix, - new Vector4(transform.Translation, transform.Variations.Linear, transform.Variations.Spherical), - new Vector4(transform.Variations.Bubble, MathF.Max(transform.Weight, 0.0f), transform.Color, transform.Variations.JulianDist), - new Vector4(transform.Variations.Disc, transform.Variations.Julian, transform.Variations.JulianPower, transform.Variations.GaussianBlur), - transform.PostMatrix, - new Vector4(transform.PostTranslation, 0.0f, 0.0f)); - } - - private static AquariumPackedFractalIfsTransform Pack( - AquariumBrushClaim claim, - IReadOnlyDictionary domains) - { - var radius = MathF.Max(claim.Radii.X, claim.Radii.Y); - var material = StableUnit(claim.Tags, claim.Seed); - var tileAddress = domains.TryGetValue(claim.DomainKey, out var domainRow) - && domainRow.Kind == AquariumFractalDomainKind.CubeSphereTile - ? domainRow.Parameters0 - : new Vector4((float)CubeFace.PositiveZ, 0.0f, 0.0f, 0.0f); - var rotationCos = MathF.Cos(claim.RotationRadians); - var rotationSin = MathF.Sin(claim.RotationRadians); - - return new AquariumPackedFractalIfsTransform( - new Vector4(claim.Center, radius, claim.Amplitude), - new Vector4(claim.Radii, claim.RotationRadians, claim.Falloff), - new Vector4(material, claim.Seed, rotationCos, rotationSin), - tileAddress, - new Vector4(1.0f, 0.0f, 0.0f, 1.0f), - new Vector4(0.0f, 0.0f, (float)EncodingFor(claim.PayloadKind), 0.0f)); - } - - private static AquariumFieldEncoding EncodingFor(AquariumFractalPayloadKind payloadKind) - { - return payloadKind switch - { - AquariumFractalPayloadKind.Height => AquariumFieldEncoding.Height, - AquariumFractalPayloadKind.SignedDistance => AquariumFieldEncoding.SignedDistance, - AquariumFractalPayloadKind.Density => AquariumFieldEncoding.Density, - AquariumFractalPayloadKind.Extinction => AquariumFieldEncoding.Extinction, - AquariumFractalPayloadKind.Material => AquariumFieldEncoding.Material, - _ => throw new ArgumentOutOfRangeException(nameof(payloadKind), payloadKind, "Unknown fractal payload kind."), - }; - } - - private static float StableUnit(string tags, int seed) - { - var hash = unchecked((uint)seed); - foreach (var ch in tags) - { - hash ^= ch; - hash *= 16777619u; - } - - return (hash & 0x00FF_FFFFu) / 16777215.0f; - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalGpuReservoirBudgetPlanner.cs b/src/Aquarium.Engine.Fractal/Lod/FractalGpuReservoirBudgetPlanner.cs deleted file mode 100644 index 84e4897..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalGpuReservoirBudgetPlanner.cs +++ /dev/null @@ -1,135 +0,0 @@ -namespace Aquarium.Engine.Fractal.Lod; - -public enum FractalGpuReservoirPassKind -{ - SdfEnvelope, - PbrMaterial, - Radiosity, -} - -public readonly record struct FractalGpuReservoirPassPlan( - FractalGpuReservoirPassKind Kind, - AquariumFieldLayer Layer, - AquariumFieldEncoding Encoding, - int ResidentEntries, - int UpdatesThisFrame, - int CandidatesPerUpdate, - double ExpectedFullCoverageFrames, - ulong ResidentBytes, - ulong CandidateEvaluationsThisFrame); - -public sealed class FractalGpuReservoirFramePlan -{ - public FractalGpuReservoirFramePlan( - int splatCount, - int splatStrideBytes, - ulong splatBytes, - IReadOnlyList passes) - { - SplatCount = splatCount; - SplatStrideBytes = splatStrideBytes; - SplatBytes = splatBytes; - Passes = passes; - } - - public int SplatCount { get; } - - public int SplatStrideBytes { get; } - - public ulong SplatBytes { get; } - - public IReadOnlyList Passes { get; } - - public ulong ReservoirBytes => Passes.Aggregate(0UL, (sum, pass) => sum + pass.ResidentBytes); - - public ulong TotalResidentBytes => SplatBytes + ReservoirBytes; - - public ulong CandidateEvaluationsThisFrame => Passes.Aggregate(0UL, (sum, pass) => sum + pass.CandidateEvaluationsThisFrame); -} - -public static class FractalGpuReservoirBudgetPlanner -{ - public static FractalGpuReservoirFramePlan Plan( - int splatCount, - int reservoirUpdatesPerPass, - int candidatesPerUpdate, - int splatStrideBytes = 80, - int reservoirStrideBytes = 64) - { - if (splatCount <= 0) - { - throw new ArgumentOutOfRangeException(nameof(splatCount), splatCount, "Splat count must be positive."); - } - - if (reservoirUpdatesPerPass <= 0 || reservoirUpdatesPerPass > splatCount) - { - throw new ArgumentOutOfRangeException(nameof(reservoirUpdatesPerPass), reservoirUpdatesPerPass, "Reservoir updates must be positive and no larger than the resident splat count."); - } - - if (candidatesPerUpdate <= 0) - { - throw new ArgumentOutOfRangeException(nameof(candidatesPerUpdate), candidatesPerUpdate, "Candidates per update must be positive."); - } - - if (splatStrideBytes <= 0) - { - throw new ArgumentOutOfRangeException(nameof(splatStrideBytes), splatStrideBytes, "Splat stride must be positive."); - } - - if (reservoirStrideBytes <= 0) - { - throw new ArgumentOutOfRangeException(nameof(reservoirStrideBytes), reservoirStrideBytes, "Reservoir stride must be positive."); - } - - var splatBytes = checked((ulong)splatCount * (ulong)splatStrideBytes); - var expectedCoverageFrames = splatCount / (double)reservoirUpdatesPerPass; - var passes = new[] - { - Pass(FractalGpuReservoirPassKind.SdfEnvelope), - Pass(FractalGpuReservoirPassKind.PbrMaterial), - Pass(FractalGpuReservoirPassKind.Radiosity), - }; - - return new FractalGpuReservoirFramePlan( - splatCount, - splatStrideBytes, - splatBytes, - passes); - - FractalGpuReservoirPassPlan Pass(FractalGpuReservoirPassKind kind) - { - return new FractalGpuReservoirPassPlan( - kind, - LayerFor(kind), - EncodingFor(kind), - splatCount, - reservoirUpdatesPerPass, - candidatesPerUpdate, - expectedCoverageFrames, - checked((ulong)splatCount * (ulong)reservoirStrideBytes), - checked((ulong)reservoirUpdatesPerPass * (ulong)candidatesPerUpdate)); - } - } - - private static AquariumFieldLayer LayerFor(FractalGpuReservoirPassKind kind) - { - return kind switch - { - FractalGpuReservoirPassKind.SdfEnvelope => AquariumFieldLayer.Form, - FractalGpuReservoirPassKind.PbrMaterial => AquariumFieldLayer.Appearance, - FractalGpuReservoirPassKind.Radiosity => AquariumFieldLayer.Transport, - _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown reservoir pass kind."), - }; - } - - private static AquariumFieldEncoding EncodingFor(FractalGpuReservoirPassKind kind) - { - return kind switch - { - FractalGpuReservoirPassKind.SdfEnvelope => AquariumFieldEncoding.SignedDistance, - FractalGpuReservoirPassKind.PbrMaterial => AquariumFieldEncoding.Material, - FractalGpuReservoirPassKind.Radiosity => AquariumFieldEncoding.Radiance, - _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unknown reservoir pass kind."), - }; - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalNativeBuffer.cs b/src/Aquarium.Engine.Fractal/Lod/FractalNativeBuffer.cs deleted file mode 100644 index e048e98..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalNativeBuffer.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System.Runtime.InteropServices; - -namespace Aquarium.Engine.Fractal.Lod; - -public sealed unsafe class FractalNativeBuffer : IDisposable - where T : unmanaged -{ - private readonly nuint byteCount; - private bool disposed; - - public FractalNativeBuffer(int length, nuint alignment = 64) - { - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length), length, "Native buffer length must not be negative."); - } - - if (alignment == 0 || (alignment & (alignment - 1)) != 0) - { - throw new ArgumentOutOfRangeException(nameof(alignment), alignment, "Native buffer alignment must be a power of two."); - } - - Length = length; - byteCount = checked((nuint)length * (nuint)sizeof(T)); - Pointer = byteCount == 0 - ? null - : (T*)NativeMemory.AlignedAlloc(byteCount, alignment); - if (Pointer is null && byteCount > 0) - { - throw new OutOfMemoryException($"Could not allocate {byteCount} bytes for native buffer."); - } - - if (Pointer is not null) - { - NativeMemory.Clear(Pointer, byteCount); - } - } - - public int Length { get; } - - public T* Pointer { get; private set; } - - public Span Span - { - get - { - ThrowIfDisposed(); - return new Span(Pointer, Length); - } - } - - public ref T this[int index] - { - get - { - ThrowIfDisposed(); - if ((uint)index >= (uint)Length) - { - throw new ArgumentOutOfRangeException(nameof(index), index, "Native buffer index is outside the allocated range."); - } - - return ref Pointer[index]; - } - } - - public void Dispose() - { - if (disposed) - { - return; - } - - disposed = true; - if (Pointer is not null) - { - NativeMemory.AlignedFree(Pointer); - Pointer = null; - } - - GC.SuppressFinalize(this); - } - - ~FractalNativeBuffer() - { - Dispose(); - } - - private void ThrowIfDisposed() - { - if (disposed) - { - throw new ObjectDisposedException(nameof(FractalNativeBuffer)); - } - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalOccupancyGraph.cs b/src/Aquarium.Engine.Fractal/Lod/FractalOccupancyGraph.cs deleted file mode 100644 index b2fd397..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalOccupancyGraph.cs +++ /dev/null @@ -1,107 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public readonly record struct FractalOccupancyNodeState( - AquariumContributionState Contribution, - uint LastVisibleFrame, - float LastObservedScore, - double UpdateProbability); - -public sealed class FractalOccupancyGraph -{ - private const float ConfidenceDecayPerFrame = 0.985f; - private const float StaleVarianceGrowth = 0.035f; - private readonly Dictionary nodes = new(StringComparer.Ordinal); - - public FractalOccupancyNodeState GetOrCreate(AquariumFractalKey nodeKey) - { - if (nodes.TryGetValue(nodeKey.Value, out var state)) - { - return state; - } - - state = new FractalOccupancyNodeState( - CreateEmptyContributionState(nodeKey), - LastVisibleFrame: 0, - LastObservedScore: 0.0f, - UpdateProbability: 0.0); - nodes.Add(nodeKey.Value, state); - return state; - } - - public bool TryGet(AquariumFractalKey nodeKey, out FractalOccupancyNodeState state) - { - return nodes.TryGetValue(nodeKey.Value, out state); - } - - public void MarkVisible(AquariumFractalKey nodeKey, float observedScore, uint frameIndex, double updateProbability) - { - var state = GetOrCreate(nodeKey); - nodes[nodeKey.Value] = state with - { - LastVisibleFrame = frameIndex, - LastObservedScore = MathF.Max(observedScore, 0.0f), - UpdateProbability = Math.Clamp(updateProbability, 0.0, 1.0), - }; - } - - public AquariumContributionState Observe(AquariumFractalKey nodeKey, float observedContribution, uint frameIndex, bool resident) - { - var state = GetOrCreate(nodeKey); - var contribution = FractalContributionEstimator.Observe( - state.Contribution, - observedContribution, - frameIndex, - resident); - nodes[nodeKey.Value] = state with - { - Contribution = contribution, - LastVisibleFrame = frameIndex, - LastObservedScore = MathF.Max(observedContribution, 0.0f), - }; - return contribution; - } - - public void DecayUnobserved(uint frameIndex) - { - foreach (var key in nodes.Keys.ToArray()) - { - var state = nodes[key]; - if (state.Contribution.LastSampledFrame == frameIndex) - { - continue; - } - - var age = frameIndex >= state.Contribution.LastSampledFrame - ? frameIndex - state.Contribution.LastSampledFrame - : 0; - if (age == 0) - { - continue; - } - - var staleGrowth = MathF.Min(age * StaleVarianceGrowth, 4.0f); - nodes[key] = state with - { - Contribution = state.Contribution with - { - Confidence = MathF.Max(0.0f, state.Contribution.Confidence * ConfidenceDecayPerFrame), - Variance = MathF.Max(state.Contribution.Variance, state.Contribution.Variance + staleGrowth), - }, - }; - } - } - - private static AquariumContributionState CreateEmptyContributionState(AquariumFractalKey nodeKey) - { - return new AquariumContributionState( - nodeKey, - MeanContribution: 0.0f, - Variance: 1.0f, - Confidence: 0.0f, - SampleCount: 0, - LastSampledFrame: 0, - Resident: false); - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalProbeSample.cs b/src/Aquarium.Engine.Fractal/Lod/FractalProbeSample.cs deleted file mode 100644 index cc8e6ac..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalProbeSample.cs +++ /dev/null @@ -1,152 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Temporal; - -namespace Aquarium.Engine.Fractal.Lod; - -public readonly record struct FractalProbeSample( - AquariumFractalKey DomainKey, - AquariumFractalKey NodeKey, - Vector3 LocalCenter, - float BoundRadius, - float TargetContribution, - float SourcePdf, - float MaterialDelta, - int PayloadHandle, - AquariumFieldLayer Layer = AquariumFieldLayer.Form, - AquariumFieldEncoding Encoding = AquariumFieldEncoding.SignedDistance) -{ - public ResampledImportanceCandidate ToReservoirCandidate() - { - return new ResampledImportanceCandidate( - this, - MathF.Max(TargetContribution, 0.0f), - MathF.Max(SourcePdf, 1.0e-6f)); - } -} - -public enum FractalProbeReuseRejection -{ - None, - UnknownDomain, - DifferentLineage, - ExcessiveLocalShift, - InvalidBounds, - FieldMismatch, - ExcessiveCameraMotion, - Disoccluded, - MaterialMismatch, - NotVisible, -} - -public readonly record struct FractalProbeReuseResult( - bool CanReuse, - FractalProbeReuseRejection Rejection, - float LocalShift); - -public readonly record struct FractalProbeTemporalValidation( - float CameraMotionPixels, - float MaxCameraMotionPixels, - float DisocclusionConfidence, - float MinDisocclusionConfidence, - float MaterialDelta, - float MaxMaterialDelta, - float VisibilityConfidence, - float MinVisibilityConfidence); - -public static class FractalProbeReuseValidator -{ - public static FractalProbeReuseResult Validate( - FractalProbeSample source, - FractalProbeSample target, - FractalDomainGraph domains, - float maxLocalShift) - { - ArgumentNullException.ThrowIfNull(domains); - if (maxLocalShift < 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(maxLocalShift), maxLocalShift, "Maximum local shift must not be negative."); - } - - if (!float.IsFinite(source.BoundRadius) || !float.IsFinite(target.BoundRadius) || source.BoundRadius <= 0.0f || target.BoundRadius <= 0.0f) - { - return new FractalProbeReuseResult(false, FractalProbeReuseRejection.InvalidBounds, 0.0f); - } - - if (!domains.Contains(source.DomainKey) || !domains.Contains(target.DomainKey)) - { - return new FractalProbeReuseResult(false, FractalProbeReuseRejection.UnknownDomain, 0.0f); - } - - if (source.Layer != target.Layer || source.Encoding != target.Encoding) - { - return new FractalProbeReuseResult(false, FractalProbeReuseRejection.FieldMismatch, 0.0f); - } - - if (!ShareLineage(source.DomainKey, target.DomainKey, domains)) - { - return new FractalProbeReuseResult(false, FractalProbeReuseRejection.DifferentLineage, 0.0f); - } - - var localShift = Vector3.Distance(source.LocalCenter, target.LocalCenter); - var allowedShift = MathF.Min(maxLocalShift, source.BoundRadius + target.BoundRadius); - if (!float.IsFinite(localShift) || localShift > allowedShift) - { - return new FractalProbeReuseResult(false, FractalProbeReuseRejection.ExcessiveLocalShift, localShift); - } - - return new FractalProbeReuseResult(true, FractalProbeReuseRejection.None, localShift); - } - - public static FractalProbeReuseResult ValidateTemporal( - FractalProbeSample source, - FractalProbeSample target, - FractalDomainGraph domains, - float maxLocalShift, - FractalProbeTemporalValidation temporal) - { - var spatial = Validate(source, target, domains, maxLocalShift); - if (!spatial.CanReuse) - { - return spatial; - } - - if (!float.IsFinite(temporal.CameraMotionPixels) || temporal.CameraMotionPixels > MathF.Max(temporal.MaxCameraMotionPixels, 0.0f)) - { - return spatial with { CanReuse = false, Rejection = FractalProbeReuseRejection.ExcessiveCameraMotion }; - } - - if (!float.IsFinite(temporal.DisocclusionConfidence) || temporal.DisocclusionConfidence < Math.Clamp(temporal.MinDisocclusionConfidence, 0.0f, 1.0f)) - { - return spatial with { CanReuse = false, Rejection = FractalProbeReuseRejection.Disoccluded }; - } - - if (!float.IsFinite(temporal.MaterialDelta) || temporal.MaterialDelta > MathF.Max(temporal.MaxMaterialDelta, 0.0f)) - { - return spatial with { CanReuse = false, Rejection = FractalProbeReuseRejection.MaterialMismatch }; - } - - if (!float.IsFinite(temporal.VisibilityConfidence) || temporal.VisibilityConfidence < Math.Clamp(temporal.MinVisibilityConfidence, 0.0f, 1.0f)) - { - return spatial with { CanReuse = false, Rejection = FractalProbeReuseRejection.NotVisible }; - } - - return spatial; - } - - private static bool ShareLineage(AquariumFractalKey sourceDomain, AquariumFractalKey targetDomain, FractalDomainGraph domains) - { - var sourcePath = domains.GetPath(sourceDomain).Select(domain => domain.Key).ToArray(); - var targetPath = domains.GetPath(targetDomain).Select(domain => domain.Key).ToArray(); - var shorterLength = Math.Min(sourcePath.Length, targetPath.Length); - for (var index = 0; index < shorterLength; index++) - { - if (!sourcePath[index].Equals(targetPath[index])) - { - return false; - } - } - - return shorterLength == sourcePath.Length || shorterLength == targetPath.Length; - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalProjectedErrorScorer.cs b/src/Aquarium.Engine.Fractal/Lod/FractalProjectedErrorScorer.cs deleted file mode 100644 index ed6e240..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalProjectedErrorScorer.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalProjectedErrorScorer -{ - public static float Score(AquariumFractalSummary summary, float projectedPixelsPerWorldUnit) - { - if (projectedPixelsPerWorldUnit <= 0.0f || summary.MaxHeightError <= 0.0f) - { - return 0.0f; - } - - var cost = MathF.Max(summary.EstimatedCost, 1.0f); - return summary.MaxHeightError * projectedPixelsPerWorldUnit / cost; - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalProjectedSdfSplatCompiler.cs b/src/Aquarium.Engine.Fractal/Lod/FractalProjectedSdfSplatCompiler.cs deleted file mode 100644 index f2290d1..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalProjectedSdfSplatCompiler.cs +++ /dev/null @@ -1,116 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalProjectedSdfSplatCompiler -{ - public static AquariumFractalSdfSplat3D[] Compile( - FractalSurfacePagePayload payload, - Func worldFromPage, - Vector3 surfaceNormal, - float tangentRadius, - float thickness, - float maxAbsDistance, - int maxSplats) - { - ArgumentNullException.ThrowIfNull(payload); - ArgumentNullException.ThrowIfNull(worldFromPage); - if (payload.Page.Key.Kind != AquariumFractalSurfacePageKind.SignedDistance2D) - { - throw new ArgumentException("Projected SDF splats require a SignedDistance2D page.", nameof(payload)); - } - - if (!float.IsFinite(tangentRadius) || tangentRadius <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(tangentRadius), tangentRadius, "Projected SDF tangent radius must be positive and finite."); - } - - if (!float.IsFinite(thickness) || thickness <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(thickness), thickness, "Projected SDF thickness must be positive and finite."); - } - - if (!float.IsFinite(maxAbsDistance) || maxAbsDistance < 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(maxAbsDistance), maxAbsDistance, "Projected SDF distance threshold must not be negative."); - } - - if (maxSplats < 0) - { - throw new ArgumentOutOfRangeException(nameof(maxSplats), maxSplats, "Projected SDF splat budget must not be negative."); - } - - if (maxSplats == 0) - { - return []; - } - - var orientation = OrientationFromNormal(surfaceNormal); - return payload.Samples - .Select((sample, index) => new ProjectedCandidate(sample, index, MathF.Abs(sample))) - .Where(candidate => candidate.AbsDistance <= maxAbsDistance) - .OrderBy(candidate => candidate.AbsDistance) - .ThenBy(candidate => candidate.Index) - .Take(maxSplats) - .Select(candidate => - { - var point = SamplePoint(payload.Page, candidate.Index); - return new AquariumFractalSdfSplat3D( - new AquariumFractalSdfSplat3DKey( - payload.Page.Key.DomainKey, - payload.Page.Key.NodeKey, - payload.Page.PayloadHandle + candidate.Index), - worldFromPage(point), - orientation, - new Vector3(tangentRadius, tangentRadius, thickness), - Falloff: 4.0f, - ShapePower: 1.0f, - DistanceOffset: candidate.Sample, - MaterialValue: 0.0f, - Confidence: 1.0f - Math.Clamp(candidate.AbsDistance / MathF.Max(maxAbsDistance, 0.000001f), 0.0f, 1.0f)); - }) - .ToArray(); - } - - private static Vector2 SamplePoint(AquariumFractalSurfacePage page, int sampleIndex) - { - var x = sampleIndex % page.Width; - var y = sampleIndex / page.Width; - var u = page.Width == 1 ? 0.5f : x / (float)(page.Width - 1); - var v = page.Height == 1 ? 0.5f : y / (float)(page.Height - 1); - return new Vector2( - Lerp(page.BoundsMinMax.X, page.BoundsMinMax.Z, u), - Lerp(page.BoundsMinMax.Y, page.BoundsMinMax.W, v)); - } - - private static Quaternion OrientationFromNormal(Vector3 normal) - { - var normalized = Vector3.Normalize(normal); - if (!float.IsFinite(normalized.X) || !float.IsFinite(normalized.Y) || !float.IsFinite(normalized.Z)) - { - return Quaternion.Identity; - } - - var zAxis = Vector3.UnitZ; - var dot = Math.Clamp(Vector3.Dot(zAxis, normalized), -1.0f, 1.0f); - if (dot > 0.9999f) - { - return Quaternion.Identity; - } - - if (dot < -0.9999f) - { - return Quaternion.CreateFromAxisAngle(Vector3.UnitX, MathF.PI); - } - - var axis = Vector3.Normalize(Vector3.Cross(zAxis, normalized)); - return Quaternion.Normalize(Quaternion.CreateFromAxisAngle(axis, MathF.Acos(dot))); - } - - private static float Lerp(float a, float b, float t) - { - return a + ((b - a) * t); - } - - private readonly record struct ProjectedCandidate(float Sample, int Index, float AbsDistance); -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlan.cs b/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlan.cs deleted file mode 100644 index 68aff73..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlan.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public sealed class FractalResidencyPlan -{ - public FractalResidencyPlan( - IReadOnlyList residentNodes, - IReadOnlyList summaryFallbackNodes, - IReadOnlyList requestedNodes, - IReadOnlyList? evictedNodes = null) - { - ResidentNodes = residentNodes; - SummaryFallbackNodes = summaryFallbackNodes; - RequestedNodes = requestedNodes; - EvictedNodes = evictedNodes ?? []; - } - - public IReadOnlyList ResidentNodes { get; } - - public IReadOnlyList SummaryFallbackNodes { get; } - - public IReadOnlyList RequestedNodes { get; } - - public IReadOnlyList EvictedNodes { get; } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs b/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs deleted file mode 100644 index 6469a2d..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs +++ /dev/null @@ -1,102 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalResidencyPlanner -{ - public static FractalResidencyPlan Plan(IReadOnlyList selectedCut, IFractalPayloadStore payloadStore) - { - return Plan(selectedCut, payloadStore, maxRequests: int.MaxValue, maxResidentNodes: int.MaxValue); - } - - public static FractalResidencyPlan Plan( - IReadOnlyList selectedCut, - IFractalPayloadStore payloadStore, - int maxRequests, - int maxResidentNodes) - { - return Plan(selectedCut, [], payloadStore, maxRequests, maxResidentNodes); - } - - public static FractalResidencyPlan Plan( - IReadOnlyList selectedCut, - IReadOnlyList summaries, - IFractalPayloadStore payloadStore, - int maxRequests, - int maxResidentNodes) - { - ArgumentNullException.ThrowIfNull(selectedCut); - ArgumentNullException.ThrowIfNull(summaries); - ArgumentNullException.ThrowIfNull(payloadStore); - - if (maxRequests < 0) - { - throw new ArgumentOutOfRangeException(nameof(maxRequests), maxRequests, "Request budget must not be negative."); - } - - if (maxResidentNodes < 0) - { - throw new ArgumentOutOfRangeException(nameof(maxResidentNodes), maxResidentNodes, "Resident budget must not be negative."); - } - - var costsByKey = summaries.ToDictionary(summary => summary.NodeKey.Value, summary => MathF.Max(summary.EstimatedCost, 1.0f), StringComparer.Ordinal); - var candidates = selectedCut - .Select((cut, index) => new ResidencyCandidate( - cut, - index, - payloadStore.IsResident(cut.NodeKey), - costsByKey.TryGetValue(cut.NodeKey.Value, out var cost) ? cost : 1.0f)) - .ToArray(); - var retainedResidentIndexes = candidates - .Where(candidate => candidate.IsResident) - .OrderByDescending(candidate => ResidencyValue(candidate)) - .ThenByDescending(candidate => candidate.Cut.Score) - .ThenBy(candidate => candidate.Index) - .Take(maxResidentNodes) - .Select(candidate => candidate.Index) - .ToHashSet(); - var resident = new List(); - var fallback = new List(); - var requested = new List(); - var evicted = new List(); - - foreach (var candidate in candidates) - { - var cut = candidate.Cut; - if (candidate.IsResident) - { - if (retainedResidentIndexes.Contains(candidate.Index)) - { - resident.Add(cut.NodeKey); - } - else - { - fallback.Add(cut.NodeKey); - evicted.Add(cut.NodeKey); - } - - continue; - } - - fallback.Add(cut.NodeKey); - if (cut.RequestedChildren && requested.Count < maxRequests) - { - payloadStore.Request(cut.NodeKey); - requested.Add(cut.NodeKey); - } - } - - return new FractalResidencyPlan(resident, fallback, requested, evicted); - } - - private static float ResidencyValue(ResidencyCandidate candidate) - { - return MathF.Max(candidate.Cut.Score, 0.0f) / MathF.Max(candidate.EstimatedCost, 1.0f); - } - - private readonly record struct ResidencyCandidate( - AquariumSelectedCut Cut, - int Index, - bool IsResident, - float EstimatedCost); -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalResourceBudget.cs b/src/Aquarium.Engine.Fractal/Lod/FractalResourceBudget.cs deleted file mode 100644 index 549b299..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalResourceBudget.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public readonly record struct FractalResourceBudget( - int MaxCpuUpdates, - float MaxGpuEstimatedCost, - int MaxResidentPayloads, - int MaxSsdRequests) -{ - public static FractalResourceBudget Empty { get; } = new(0, 0.0f, 0, 0); - - public void Validate() - { - if (MaxCpuUpdates < 0) - { - throw new ArgumentOutOfRangeException(nameof(MaxCpuUpdates), MaxCpuUpdates, "CPU update budget must not be negative."); - } - - if (MaxGpuEstimatedCost < 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(MaxGpuEstimatedCost), MaxGpuEstimatedCost, "GPU packet budget must not be negative."); - } - - if (MaxResidentPayloads < 0) - { - throw new ArgumentOutOfRangeException(nameof(MaxResidentPayloads), MaxResidentPayloads, "Resident payload budget must not be negative."); - } - - if (MaxSsdRequests < 0) - { - throw new ArgumentOutOfRangeException(nameof(MaxSsdRequests), MaxSsdRequests, "SSD request budget must not be negative."); - } - } -} - -public sealed class FractalResourcePlan -{ - public FractalResourcePlan( - AquariumSelectedCut[] selectedCut, - AquariumFractalKey[] updateNodes, - FractalResidencyPlan residency, - float gpuEstimatedCost, - FractalResourceBudget budget) - { - SelectedCut = selectedCut; - UpdateNodes = updateNodes; - Residency = residency; - GpuEstimatedCost = gpuEstimatedCost; - Budget = budget; - } - - public AquariumSelectedCut[] SelectedCut { get; } - - public AquariumFractalKey[] UpdateNodes { get; } - - public FractalResidencyPlan Residency { get; } - - public float GpuEstimatedCost { get; } - - public FractalResourceBudget Budget { get; } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs b/src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs deleted file mode 100644 index 9984b6c..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs +++ /dev/null @@ -1,50 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalResourceBudgetPlanner -{ - public static FractalResourcePlan Plan( - IReadOnlyList summaries, - IReadOnlyList states, - Func projectedPixelsPerWorldUnit, - Func currentScore, - FractalResourceBudget budget, - IFractalRandom random, - IFractalPayloadStore payloadStore, - uint frameIndex) - { - ArgumentNullException.ThrowIfNull(summaries); - ArgumentNullException.ThrowIfNull(states); - ArgumentNullException.ThrowIfNull(projectedPixelsPerWorldUnit); - ArgumentNullException.ThrowIfNull(currentScore); - ArgumentNullException.ThrowIfNull(random); - ArgumentNullException.ThrowIfNull(payloadStore); - budget.Validate(); - - var selectedCut = FractalSelectedCutBuilder.Build(summaries, projectedPixelsPerWorldUnit, budget.MaxGpuEstimatedCost); - var updateNodes = FractalStochasticUpdateScheduler.SelectUpdates(states, currentScore, budget.MaxCpuUpdates, random, frameIndex); - var residency = FractalResidencyPlanner.Plan(selectedCut, summaries, payloadStore, budget.MaxSsdRequests, budget.MaxResidentPayloads); - - return new FractalResourcePlan( - selectedCut, - updateNodes, - residency, - EstimatedCost(summaries, selectedCut), - budget); - } - - private static float EstimatedCost(IReadOnlyList summaries, IReadOnlyList selectedCut) - { - var summariesByKey = summaries.ToDictionary(summary => summary.NodeKey.Value, StringComparer.Ordinal); - var cost = 0.0f; - foreach (var cut in selectedCut) - { - cost += summariesByKey.TryGetValue(cut.NodeKey.Value, out var summary) - ? MathF.Max(summary.EstimatedCost, 1.0f) - : 1.0f; - } - - return cost; - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DCompiler.cs b/src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DCompiler.cs deleted file mode 100644 index b612aa5..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DCompiler.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalSdfSplat3DCompiler -{ - public static AquariumFractalSdfSplat3D FromProbe( - FractalProbeSample probe, - float thickness, - float falloff = 4.0f, - float shapePower = 1.0f) - { - if (probe.Layer != AquariumFieldLayer.Form || probe.Encoding != AquariumFieldEncoding.SignedDistance) - { - throw new ArgumentException("3D SDF splat lowering only accepts Form/SignedDistance probes.", nameof(probe)); - } - - if (!float.IsFinite(probe.BoundRadius) || probe.BoundRadius <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(probe), probe.BoundRadius, "Probe bound radius must be positive and finite."); - } - - if (!float.IsFinite(thickness) || thickness <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(thickness), thickness, "3D SDF splat thickness must be positive and finite."); - } - - if (!float.IsFinite(falloff) || falloff <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(falloff), falloff, "3D SDF splat falloff must be positive and finite."); - } - - if (!float.IsFinite(shapePower) || shapePower <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(shapePower), shapePower, "3D SDF splat shape power must be positive and finite."); - } - - return new AquariumFractalSdfSplat3D( - new AquariumFractalSdfSplat3DKey(probe.DomainKey, probe.NodeKey, probe.PayloadHandle), - probe.LocalCenter, - Quaternion.Identity, - new Vector3(probe.BoundRadius, probe.BoundRadius, thickness), - falloff, - shapePower, - DistanceOffset: 0.0f, - MaterialValue: Math.Clamp(probe.MaterialDelta, 0.0f, 1.0f), - Confidence: Math.Clamp(probe.TargetContribution, 0.0f, 1.0f)); - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DKernel.cs b/src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DKernel.cs deleted file mode 100644 index c811469..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DKernel.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalSdfSplat3DKernel -{ - public static float CompactWeight(AquariumFractalSdfSplat3D splat, Vector3 point) - { - var local = Vector3.Transform(point - splat.Center, Quaternion.Inverse(splat.Orientation)); - var radii = Vector3.Max(splat.Radii, new Vector3(0.0001f)); - var q = local / radii; - var radiusSquared = Vector3.Dot(q, q); - if (radiusSquared >= 1.0f) - { - return 0.0f; - } - - var falloff = MathF.Max(splat.Falloff, 0.0001f); - var shapePower = MathF.Max(splat.ShapePower, 0.0001f); - var edge = MathF.Exp(-falloff); - var value = MathF.Exp(-falloff * radiusSquared); - var compact = Math.Clamp((value - edge) / MathF.Max(1.0f - edge, 0.000001f), 0.0f, 1.0f); - return MathF.Pow(compact, shapePower); - } - - public static float SignedDistance(AquariumFractalSdfSplat3D splat, Vector3 point) - { - var local = Vector3.Transform(point - splat.Center, Quaternion.Inverse(splat.Orientation)); - var radii = Vector3.Max(splat.Radii, new Vector3(0.0001f)); - var q = local / radii; - return ((q.Length() - 1.0f) * MathF.Min(radii.X, MathF.Min(radii.Y, radii.Z))) + splat.DistanceOffset; - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalSelectedCutBuilder.cs b/src/Aquarium.Engine.Fractal/Lod/FractalSelectedCutBuilder.cs deleted file mode 100644 index 48fa298..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalSelectedCutBuilder.cs +++ /dev/null @@ -1,65 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalSelectedCutBuilder -{ - public static AquariumSelectedCut[] Build( - IReadOnlyList summaries, - Func projectedPixelsPerWorldUnit, - float maxEstimatedCost, - float childRequestScore = 1.0f) - { - ArgumentNullException.ThrowIfNull(summaries); - ArgumentNullException.ThrowIfNull(projectedPixelsPerWorldUnit); - - if (maxEstimatedCost <= 0.0f) - { - return []; - } - - var candidates = summaries - .Select(summary => - { - var score = FractalProjectedErrorScorer.Score(summary, projectedPixelsPerWorldUnit(summary)); - return new Candidate(summary, score); - }) - .OrderByDescending(candidate => candidate.Score) - .ThenBy(candidate => candidate.Summary.NodeKey.Value, StringComparer.Ordinal) - .ToArray(); - - var cuts = new List(); - var usedCost = 0.0f; - foreach (var candidate in candidates) - { - var cost = MathF.Max(candidate.Summary.EstimatedCost, 1.0f); - if (usedCost + cost > maxEstimatedCost) - { - continue; - } - - usedCost += cost; - cuts.Add(new AquariumSelectedCut( - candidate.Summary.NodeKey, - candidate.Score, - Fade: FadeFromScore(candidate.Score, childRequestScore), - UsesSummary: true, - RequestedChildren: candidate.Score >= childRequestScore)); - } - - return cuts.ToArray(); - } - - private static float FadeFromScore(float score, float childRequestScore) - { - if (score <= 0.0f) - { - return 0.0f; - } - - var denominator = MathF.Max(childRequestScore, 0.000001f); - return Math.Clamp(score / denominator, 0.0f, 1.0f); - } - - private readonly record struct Candidate(AquariumFractalSummary Summary, float Score); -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalStochasticUpdateScheduler.cs b/src/Aquarium.Engine.Fractal/Lod/FractalStochasticUpdateScheduler.cs deleted file mode 100644 index 6226448..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalStochasticUpdateScheduler.cs +++ /dev/null @@ -1,51 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalStochasticUpdateScheduler -{ - public static AquariumFractalKey[] SelectUpdates( - IReadOnlyList states, - Func currentScore, - int maxUpdates, - IFractalRandom random, - uint frameIndex) - { - ArgumentNullException.ThrowIfNull(states); - ArgumentNullException.ThrowIfNull(currentScore); - ArgumentNullException.ThrowIfNull(random); - - if (maxUpdates <= 0) - { - return []; - } - - var selected = new List(); - foreach (var state in states.OrderBy(state => state.NodeKey.Value, StringComparer.Ordinal)) - { - var probability = UpdateProbability(state, currentScore(state), frameIndex); - if (random.NextDouble() <= probability) - { - selected.Add(state.NodeKey); - if (selected.Count >= maxUpdates) - { - break; - } - } - } - - return selected.ToArray(); - } - - public static double UpdateProbability(AquariumContributionState state, float currentScore, uint frameIndex) - { - var uncertainty = Math.Clamp(Math.Sqrt(Math.Max(state.Variance, 0.0f)) * 0.25, 0.0, 0.35); - var age = frameIndex >= state.LastSampledFrame ? frameIndex - state.LastSampledFrame : 0; - var stalePressure = Math.Clamp(age / 240.0, 0.0, 0.30); - var visiblePressure = currentScore > 0.0f ? 0.10 : 0.0; - var thresholdPressure = currentScore is > 0.75f and < 1.25f ? 0.20 : 0.0; - var confidencePenalty = (1.0 - Math.Clamp(state.Confidence, 0.0f, 1.0f)) * 0.15; - - return Math.Clamp(0.02 + uncertainty + stalePressure + visiblePressure + thresholdPressure + confidencePenalty, 0.02, 0.95); - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeGenerator.cs b/src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeGenerator.cs deleted file mode 100644 index c0f3afe..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeGenerator.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Temporal; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalStructuralProbeGenerator -{ - private const float MinimumBoundRadius = 0.001f; - private const float MinimumSourcePdf = 1.0e-6f; - - public static FractalProbeSample FromSummary( - AquariumFractalSummary summary, - AquariumFractalKey domainKey, - float projectedPixelsPerWorldUnit, - float sourcePdf, - int payloadHandle = 0, - AquariumFieldLayer layer = AquariumFieldLayer.Form, - AquariumFieldEncoding? encoding = null) - { - var min = new Vector2(summary.BoundsMinMax.X, summary.BoundsMinMax.Y); - var max = new Vector2(summary.BoundsMinMax.Z, summary.BoundsMinMax.W); - var center2 = (min + max) * 0.5f; - var extents = Vector2.Max((max - min) * 0.5f, Vector2.Zero); - var radius = MathF.Max(extents.Length(), MinimumBoundRadius); - var formTarget = FractalProjectedErrorScorer.Score(summary, projectedPixelsPerWorldUnit); - var materialTarget = MathF.Max(summary.MaxMaterialDelta, 0.0f) * MathF.Max(projectedPixelsPerWorldUnit, 0.0f); - var target = MathF.Max(formTarget, materialTarget); - - return new FractalProbeSample( - domainKey, - summary.NodeKey, - new Vector3(center2, 0.0f), - radius, - target, - MathF.Max(sourcePdf, MinimumSourcePdf), - MathF.Max(summary.MaxMaterialDelta, 0.0f), - payloadHandle, - layer, - encoding ?? PreferredFormEncoding(summary)); - } - - public static ResampledImportanceCandidate BuildCandidate( - AquariumFractalSummary summary, - AquariumFractalKey domainKey, - float projectedPixelsPerWorldUnit, - double sourceProbability, - int payloadHandle = 0, - AquariumFieldLayer layer = AquariumFieldLayer.Form, - AquariumFieldEncoding? encoding = null) - { - return FromSummary( - summary, - domainKey, - projectedPixelsPerWorldUnit, - (float)Math.Clamp(sourceProbability, MinimumSourcePdf, 1.0), - payloadHandle, - layer, - encoding).ToReservoirCandidate(); - } - - private static AquariumFieldEncoding PreferredFormEncoding(AquariumFractalSummary summary) - { - var mask = summary.FormEncodingMask; - if ((mask & AquariumFieldEncodingFlags.Density) != 0 && - (mask & (AquariumFieldEncodingFlags.Height | AquariumFieldEncodingFlags.SignedDistance)) == 0) - { - return AquariumFieldEncoding.Density; - } - - if ((mask & AquariumFieldEncodingFlags.Extinction) != 0 && - (mask & (AquariumFieldEncodingFlags.Height | AquariumFieldEncodingFlags.SignedDistance | AquariumFieldEncodingFlags.Density)) == 0) - { - return AquariumFieldEncoding.Extinction; - } - - return AquariumFieldEncoding.SignedDistance; - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeReservoir.cs b/src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeReservoir.cs deleted file mode 100644 index 4246f7d..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeReservoir.cs +++ /dev/null @@ -1,135 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Temporal; - -namespace Aquarium.Engine.Fractal.Lod; - -public readonly record struct FractalProbeReservoirSnapshot( - bool HasSample, - AquariumFractalKey DomainKey, - AquariumFractalKey NodeKey, - Vector3 LocalCenter, - float TargetContribution, - float BoundRadius, - float SourcePdf, - float MaterialDelta, - float WeightSum, - int CandidateCount, - float ContributionWeight, - int PayloadHandle, - AquariumFieldLayer Layer = AquariumFieldLayer.Form, - AquariumFieldEncoding Encoding = AquariumFieldEncoding.SignedDistance) -{ - public FractalProbeSample ToProbeSample() - { - if (!HasSample) - { - throw new InvalidOperationException("Cannot convert an empty structural probe reservoir snapshot to a probe sample."); - } - - return new FractalProbeSample( - DomainKey, - NodeKey, - LocalCenter, - BoundRadius, - TargetContribution, - SourcePdf, - MaterialDelta, - PayloadHandle, - Layer, - Encoding); - } -} - -public static class FractalStructuralProbeReservoir -{ - public static FractalProbeReservoirSnapshot Build( - FractalOwnershipTree tree, - IReadOnlyList summaries, - IReadOnlyList selectedCut, - float projectedPixelsPerWorldUnit, - IFractalRandom random, - AquariumFieldLayer layer = AquariumFieldLayer.Form, - AquariumFieldEncoding? encoding = null) - { - ArgumentNullException.ThrowIfNull(tree); - ArgumentNullException.ThrowIfNull(summaries); - ArgumentNullException.ThrowIfNull(selectedCut); - ArgumentNullException.ThrowIfNull(random); - - if (selectedCut.Count == 0) - { - return Empty(); - } - - var summariesByKey = summaries.ToDictionary(summary => summary.NodeKey.Value, StringComparer.Ordinal); - var nodesByKey = tree.Nodes.ToDictionary(node => node.Key.Value, StringComparer.Ordinal); - var sourceProbability = 1.0 / selectedCut.Count; - var reservoir = new ResampledImportanceReservoir(); - for (var index = 0; index < selectedCut.Count; index++) - { - var cut = selectedCut[index]; - if (!summariesByKey.TryGetValue(cut.NodeKey.Value, out var summary) - || !nodesByKey.TryGetValue(cut.NodeKey.Value, out var node)) - { - continue; - } - - var candidate = FractalStructuralProbeGenerator.BuildCandidate( - summary, - node.DomainKey, - projectedPixelsPerWorldUnit, - sourceProbability, - payloadHandle: index, - layer, - encoding); - reservoir.Add(candidate, random.NextDouble()); - } - - return Snapshot(reservoir); - } - - private static FractalProbeReservoirSnapshot Snapshot(ResampledImportanceReservoir reservoir) - { - if (!reservoir.HasSample) - { - return Empty(); - } - - var selected = reservoir.SelectedSample; - return new FractalProbeReservoirSnapshot( - HasSample: true, - selected.DomainKey, - selected.NodeKey, - selected.LocalCenter, - selected.TargetContribution, - selected.BoundRadius, - selected.SourcePdf, - selected.MaterialDelta, - reservoir.WeightSum, - reservoir.CandidateCount, - reservoir.ContributionWeight, - selected.PayloadHandle, - selected.Layer, - selected.Encoding); - } - - private static FractalProbeReservoirSnapshot Empty() - { - return new FractalProbeReservoirSnapshot( - HasSample: false, - DomainKey: default, - NodeKey: default, - LocalCenter: Vector3.Zero, - TargetContribution: 0.0f, - BoundRadius: 0.0f, - SourcePdf: 0.0f, - MaterialDelta: 0.0f, - WeightSum: 0.0f, - CandidateCount: 0, - ContributionWeight: 0.0f, - PayloadHandle: 0, - Layer: AquariumFieldLayer.Form, - Encoding: AquariumFieldEncoding.SignedDistance); - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePayload.cs b/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePayload.cs deleted file mode 100644 index 103c139..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePayload.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Aquarium.Engine.Fractal.Lod; - -public sealed class FractalSurfacePagePayload -{ - public FractalSurfacePagePayload(AquariumFractalSurfacePage page, float[] samples) - { - ArgumentNullException.ThrowIfNull(samples); - if (samples.Length != page.Width * page.Height) - { - throw new ArgumentException("Surface page sample count must match page dimensions.", nameof(samples)); - } - - Page = page; - Samples = samples; - } - - public AquariumFractalSurfacePage Page { get; } - - public float[] Samples { get; } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePlanner.cs b/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePlanner.cs deleted file mode 100644 index 7d731eb..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePlanner.cs +++ /dev/null @@ -1,69 +0,0 @@ -using Aquarium.Engine.Fractal.Grammar; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalSurfacePagePlanner -{ - public static AquariumFractalSurfacePage[] Plan( - FractalOwnershipTree tree, - IReadOnlyList summaries, - IReadOnlyList selectedCut, - AquariumFractalSurfacePageKind kind, - int width, - int height, - int mipLevel = 0) - { - ArgumentNullException.ThrowIfNull(tree); - ArgumentNullException.ThrowIfNull(summaries); - ArgumentNullException.ThrowIfNull(selectedCut); - if (width <= 0) - { - throw new ArgumentOutOfRangeException(nameof(width), width, "Surface page width must be positive."); - } - - if (height <= 0) - { - throw new ArgumentOutOfRangeException(nameof(height), height, "Surface page height must be positive."); - } - - if (mipLevel < 0) - { - throw new ArgumentOutOfRangeException(nameof(mipLevel), mipLevel, "Surface page mip level must not be negative."); - } - - var summariesByKey = summaries.ToDictionary(summary => summary.NodeKey.Value, StringComparer.Ordinal); - var nodesByKey = tree.Nodes.ToDictionary(node => node.Key.Value, StringComparer.Ordinal); - var pages = new List(selectedCut.Count); - for (var index = 0; index < selectedCut.Count; index++) - { - var cut = selectedCut[index]; - if (!summariesByKey.TryGetValue(cut.NodeKey.Value, out var summary) - || !nodesByKey.TryGetValue(cut.NodeKey.Value, out var node)) - { - continue; - } - - pages.Add(new AquariumFractalSurfacePage( - new AquariumFractalSurfacePageKey(node.DomainKey, cut.NodeKey, kind, mipLevel), - summary.BoundsMinMax, - width, - height, - PayloadHandle: index, - MaxError: MaxErrorForKind(summary, kind))); - } - - return pages.ToArray(); - } - - private static float MaxErrorForKind(AquariumFractalSummary summary, AquariumFractalSurfacePageKind kind) - { - return kind switch - { - AquariumFractalSurfacePageKind.Height => MathF.Max(summary.MaxHeightError, 0.0f), - AquariumFractalSurfacePageKind.SignedDistance2D => MathF.Max(summary.MaxHeightError, 0.0f), - AquariumFractalSurfacePageKind.Material => MathF.Max(summary.MaxMaterialDelta, 0.0f), - AquariumFractalSurfacePageKind.Confidence => MathF.Max(summary.MaxHeightError, summary.MaxMaterialDelta), - _ => 0.0f, - }; - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageRasterizer.cs b/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageRasterizer.cs deleted file mode 100644 index 3260921..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageRasterizer.cs +++ /dev/null @@ -1,157 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Brushes; -using Aquarium.Engine.Fractal.Grammar; - -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalSurfacePageRasterizer -{ - public static FractalSurfacePagePayload Rasterize(FractalOwnershipTree tree, AquariumFractalSurfacePage page) - { - ArgumentNullException.ThrowIfNull(tree); - if (page.Width <= 0 || page.Height <= 0) - { - throw new ArgumentOutOfRangeException(nameof(page), "Surface page dimensions must be positive."); - } - - var node = tree.Nodes.FirstOrDefault(candidate => candidate.Key == page.Key.NodeKey); - if (node.Key.Value is null) - { - throw new ArgumentException($"Surface page node {page.Key.NodeKey} does not exist in the ownership tree.", nameof(page)); - } - - var claims = ClaimsForNode(tree, node); - var samples = new float[page.Width * page.Height]; - for (var y = 0; y < page.Height; y++) - { - for (var x = 0; x < page.Width; x++) - { - var point = SamplePoint(page, x, y); - samples[(y * page.Width) + x] = Evaluate(page.Key.Kind, claims, point); - } - } - - return new FractalSurfacePagePayload(page, samples); - } - - private static AquariumBrushClaim[] ClaimsForNode(FractalOwnershipTree tree, AquariumFractalNode node) - { - if (node.ClaimCount <= 0) - { - return []; - } - - var claims = new AquariumBrushClaim[node.ClaimCount]; - for (var index = 0; index < node.ClaimCount; index++) - { - claims[index] = tree.Claims[node.FirstClaimIndex + index]; - } - - return claims; - } - - private static Vector2 SamplePoint(AquariumFractalSurfacePage page, int x, int y) - { - var u = page.Width == 1 ? 0.5f : x / (float)(page.Width - 1); - var v = page.Height == 1 ? 0.5f : y / (float)(page.Height - 1); - return new Vector2( - Lerp(page.BoundsMinMax.X, page.BoundsMinMax.Z, u), - Lerp(page.BoundsMinMax.Y, page.BoundsMinMax.W, v)); - } - - private static float Lerp(float a, float b, float t) - { - return a + ((b - a) * t); - } - - private static float Evaluate(AquariumFractalSurfacePageKind kind, IReadOnlyList claims, Vector2 point) - { - return kind switch - { - AquariumFractalSurfacePageKind.Height => EvaluateHeight(claims, point), - AquariumFractalSurfacePageKind.SignedDistance2D => EvaluateSignedDistance(claims, point), - AquariumFractalSurfacePageKind.Material => EvaluateMaterial(claims, point), - AquariumFractalSurfacePageKind.Confidence => EvaluateConfidence(claims, point), - _ => 0.0f, - }; - } - - private static float EvaluateHeight(IReadOnlyList claims, Vector2 point) - { - var value = 0.0; - foreach (var claim in claims) - { - value += Envelope(claim).Evaluate(point) * claim.Amplitude; - } - - return (float)value; - } - - private static float EvaluateSignedDistance(IReadOnlyList claims, Vector2 point) - { - if (claims.Count == 0) - { - return float.PositiveInfinity; - } - - var distance = double.PositiveInfinity; - foreach (var claim in claims) - { - distance = Math.Min(distance, Envelope(claim).SignedSupportDistanceEstimate(point)); - } - - return (float)distance; - } - - private static float EvaluateMaterial(IReadOnlyList claims, Vector2 point) - { - var weighted = 0.0; - var weightSum = 0.0; - foreach (var claim in claims) - { - var weight = Envelope(claim).Evaluate(point); - if (weight <= 0.0) - { - continue; - } - - weighted += weight * StableMaterialValue(claim); - weightSum += weight; - } - - return weightSum <= 0.0 ? 0.0f : (float)(weighted / weightSum); - } - - private static float EvaluateConfidence(IReadOnlyList claims, Vector2 point) - { - var confidence = 0.0; - foreach (var claim in claims) - { - confidence += Envelope(claim).Evaluate(point); - } - - return (float)Math.Clamp(confidence, 0.0, 1.0); - } - - private static double StableMaterialValue(AquariumBrushClaim claim) - { - var hash = (uint)claim.Seed * 747796405u; - foreach (var ch in claim.Tags) - { - hash = (hash * 16777619u) ^ ch; - } - - return (hash & 0xFFFFu) / 65535.0; - } - - private static FractalBrushEnvelope2D Envelope(AquariumBrushClaim claim) - { - return new FractalBrushEnvelope2D( - claim.Center, - claim.Radii.X, - claim.Radii.Y, - claim.RotationRadians, - claim.Falloff, - claim.ShapePower); - } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlan.cs b/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlan.cs deleted file mode 100644 index 6532243..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlan.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace Aquarium.Engine.Fractal.Lod; - -public sealed class FractalSurfacePageResidencyPlan -{ - public FractalSurfacePageResidencyPlan( - IReadOnlyList residentPages, - IReadOnlyList missingPages, - IReadOnlyList requestedPages, - IReadOnlyList evictedPages, - long residentBytes) - { - ResidentPages = residentPages; - MissingPages = missingPages; - RequestedPages = requestedPages; - EvictedPages = evictedPages; - ResidentBytes = residentBytes; - } - - public IReadOnlyList ResidentPages { get; } - - public IReadOnlyList MissingPages { get; } - - public IReadOnlyList RequestedPages { get; } - - public IReadOnlyList EvictedPages { get; } - - public long ResidentBytes { get; } -} diff --git a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlanner.cs b/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlanner.cs deleted file mode 100644 index a2c98ca..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlanner.cs +++ /dev/null @@ -1,120 +0,0 @@ -namespace Aquarium.Engine.Fractal.Lod; - -public static class FractalSurfacePageResidencyPlanner -{ - public static FractalSurfacePageResidencyPlan Plan( - IReadOnlyList pages, - IFractalSurfacePageStore store, - long maxResidentBytes, - int maxRequests) - { - ArgumentNullException.ThrowIfNull(pages); - ArgumentNullException.ThrowIfNull(store); - if (maxResidentBytes < 0) - { - throw new ArgumentOutOfRangeException(nameof(maxResidentBytes), maxResidentBytes, "Resident byte budget must not be negative."); - } - - if (maxRequests < 0) - { - throw new ArgumentOutOfRangeException(nameof(maxRequests), maxRequests, "Request budget must not be negative."); - } - - var rows = pages - .Select((page, index) => new PageCandidate(page, index, EstimatedBytes(page), store.IsResident(page.Key))) - .ToArray(); - var retainedIndexes = new HashSet(); - var retainedBytes = 0L; - foreach (var candidate in rows - .Where(candidate => candidate.IsResident) - .OrderByDescending(PageValue) - .ThenByDescending(candidate => candidate.Page.MaxError) - .ThenBy(candidate => candidate.Page.Key.Value, StringComparer.Ordinal)) - { - if (retainedBytes + candidate.EstimatedBytes > maxResidentBytes) - { - continue; - } - - retainedIndexes.Add(candidate.Index); - retainedBytes += candidate.EstimatedBytes; - } - - var resident = new List(); - var missing = new List(); - var evicted = new List(); - foreach (var candidate in rows) - { - if (candidate.IsResident && retainedIndexes.Contains(candidate.Index)) - { - resident.Add(candidate.Page); - continue; - } - - missing.Add(candidate.Page); - if (candidate.IsResident) - { - evicted.Add(candidate.Page); - store.Evict(candidate.Page.Key); - } - } - - var requested = rows - .Where(candidate => !candidate.IsResident) - .Select(candidate => candidate.Page) - .OrderByDescending(PageValue) - .ThenByDescending(page => page.MaxError) - .ThenBy(page => page.Key.Value, StringComparer.Ordinal) - .Take(maxRequests) - .ToArray(); - foreach (var page in requested) - { - store.Request(page); - } - - return new FractalSurfacePageResidencyPlan(resident, missing, requested, evicted, retainedBytes); - } - - public static long EstimatedBytes(AquariumFractalSurfacePage page) - { - if (page.Width <= 0 || page.Height <= 0) - { - return 0; - } - - return (long)page.Width * page.Height * BytesPerPixel(page.Key.Kind); - } - - private static float PageValue(PageCandidate candidate) - { - return PageValue(candidate.Page, candidate.EstimatedBytes); - } - - private static float PageValue(AquariumFractalSurfacePage page) - { - return PageValue(page, EstimatedBytes(page)); - } - - private static float PageValue(AquariumFractalSurfacePage page, long estimatedBytes) - { - return MathF.Max(page.MaxError, 0.000001f) / Math.Max(estimatedBytes, 1L); - } - - private static int BytesPerPixel(AquariumFractalSurfacePageKind kind) - { - return kind switch - { - AquariumFractalSurfacePageKind.Material => 4, - AquariumFractalSurfacePageKind.Height => 2, - AquariumFractalSurfacePageKind.SignedDistance2D => 2, - AquariumFractalSurfacePageKind.Confidence => 2, - _ => 4, - }; - } - - private readonly record struct PageCandidate( - AquariumFractalSurfacePage Page, - int Index, - long EstimatedBytes, - bool IsResident); -} diff --git a/src/Aquarium.Engine.Fractal/Lod/IFractalPayloadStore.cs b/src/Aquarium.Engine.Fractal/Lod/IFractalPayloadStore.cs deleted file mode 100644 index f8deafc..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/IFractalPayloadStore.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Lod; - -public interface IFractalPayloadStore -{ - bool IsResident(AquariumFractalKey nodeKey); - - void Request(AquariumFractalKey nodeKey); -} diff --git a/src/Aquarium.Engine.Fractal/Lod/IFractalSurfacePageStore.cs b/src/Aquarium.Engine.Fractal/Lod/IFractalSurfacePageStore.cs deleted file mode 100644 index 3e7f6e0..0000000 --- a/src/Aquarium.Engine.Fractal/Lod/IFractalSurfacePageStore.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Aquarium.Engine.Fractal.Lod; - -public interface IFractalSurfacePageStore -{ - bool IsResident(AquariumFractalSurfacePageKey key); - - void Request(AquariumFractalSurfacePage page); - - void Evict(AquariumFractalSurfacePageKey key); -} diff --git a/src/Aquarium.Engine.Fractal/Projection/ICubeSphereProjection.cs b/src/Aquarium.Engine.Fractal/Projection/ICubeSphereProjection.cs deleted file mode 100644 index 70dd2f0..0000000 --- a/src/Aquarium.Engine.Fractal/Projection/ICubeSphereProjection.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Projection; - -public interface ICubeSphereProjection -{ - string Name { get; } - - Vector3 Project(CubeFacePosition position); -} diff --git a/src/Aquarium.Engine.Fractal/Projection/NormalizeCubeSphereProjection.cs b/src/Aquarium.Engine.Fractal/Projection/NormalizeCubeSphereProjection.cs deleted file mode 100644 index 37572c7..0000000 --- a/src/Aquarium.Engine.Fractal/Projection/NormalizeCubeSphereProjection.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Projection; - -public sealed class NormalizeCubeSphereProjection : ICubeSphereProjection -{ - public string Name => "normalize"; - - public Vector3 Project(CubeFacePosition position) - { - return Vector3.Normalize(position.ToCubeVector()); - } -} diff --git a/src/Aquarium.Engine.Fractal/Projection/ProjectionDistortionResult.cs b/src/Aquarium.Engine.Fractal/Projection/ProjectionDistortionResult.cs deleted file mode 100644 index bb5e1a9..0000000 --- a/src/Aquarium.Engine.Fractal/Projection/ProjectionDistortionResult.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Aquarium.Engine.Fractal.Projection; - -public readonly record struct ProjectionDistortionResult( - string ProjectionName, - CubeFace Face, - int SamplesPerAxis, - double AverageAreaScale, - double MinRelativeArea, - double MaxRelativeArea, - double MeanAbsoluteRelativeAreaError, - double RootMeanSquareRelativeAreaError); diff --git a/src/Aquarium.Engine.Fractal/Projection/ProjectionDistortionSampler.cs b/src/Aquarium.Engine.Fractal/Projection/ProjectionDistortionSampler.cs deleted file mode 100644 index 0434f09..0000000 --- a/src/Aquarium.Engine.Fractal/Projection/ProjectionDistortionSampler.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Projection; - -public static class ProjectionDistortionSampler -{ - private const double EqualAreaScalePerCubeCoordinate = Math.PI / 6.0; - private const double DerivativeStep = 1.0e-4; - - public static ProjectionDistortionResult SampleFace( - ICubeSphereProjection projection, - CubeFace face, - int samplesPerAxis) - { - ArgumentNullException.ThrowIfNull(projection); - - if (samplesPerAxis <= 0) - { - throw new ArgumentOutOfRangeException(nameof(samplesPerAxis), samplesPerAxis, "Sample count must be positive."); - } - - var minRelativeArea = double.PositiveInfinity; - var maxRelativeArea = double.NegativeInfinity; - var totalAreaScale = 0.0; - var totalAbsRelativeError = 0.0; - var totalSquaredRelativeError = 0.0; - var sampleCount = 0; - - for (var y = 0; y < samplesPerAxis; y++) - { - var v = -1.0 + (2.0 * (y + 0.5) / samplesPerAxis); - for (var x = 0; x < samplesPerAxis; x++) - { - var u = -1.0 + (2.0 * (x + 0.5) / samplesPerAxis); - var areaScale = SurfaceAreaScale(projection, face, u, v); - var relativeArea = areaScale / EqualAreaScalePerCubeCoordinate; - var relativeError = relativeArea - 1.0; - - minRelativeArea = Math.Min(minRelativeArea, relativeArea); - maxRelativeArea = Math.Max(maxRelativeArea, relativeArea); - totalAreaScale += areaScale; - totalAbsRelativeError += Math.Abs(relativeError); - totalSquaredRelativeError += relativeError * relativeError; - sampleCount++; - } - } - - return new ProjectionDistortionResult( - projection.Name, - face, - samplesPerAxis, - totalAreaScale / sampleCount, - minRelativeArea, - maxRelativeArea, - totalAbsRelativeError / sampleCount, - Math.Sqrt(totalSquaredRelativeError / sampleCount)); - } - - private static double SurfaceAreaScale(ICubeSphereProjection projection, CubeFace face, double u, double v) - { - var du = Derivative(projection, face, u, v, DerivativeAxis.U); - var dv = Derivative(projection, face, u, v, DerivativeAxis.V); - return Vector3.Cross(du, dv).Length(); - } - - private static Vector3 Derivative(ICubeSphereProjection projection, CubeFace face, double u, double v, DerivativeAxis axis) - { - var low = axis == DerivativeAxis.U ? u : v; - var high = low; - var backward = Math.Min(DerivativeStep, low + 1.0); - var forward = Math.Min(DerivativeStep, 1.0 - high); - - if (backward == 0.0) - { - backward = forward; - } - else if (forward == 0.0) - { - forward = backward; - } - - var lowCoordinate = low - backward; - var highCoordinate = high + forward; - - Vector3 lowPoint; - Vector3 highPoint; - if (axis == DerivativeAxis.U) - { - lowPoint = projection.Project(new CubeFacePosition(face, lowCoordinate, v)); - highPoint = projection.Project(new CubeFacePosition(face, highCoordinate, v)); - } - else - { - lowPoint = projection.Project(new CubeFacePosition(face, u, lowCoordinate)); - highPoint = projection.Project(new CubeFacePosition(face, u, highCoordinate)); - } - - return (highPoint - lowPoint) / (float)(forward + backward); - } - - private enum DerivativeAxis - { - U, - V, - } -} diff --git a/src/Aquarium.Engine.Fractal/Projection/ProjectionReport.cs b/src/Aquarium.Engine.Fractal/Projection/ProjectionReport.cs deleted file mode 100644 index c6dbf16..0000000 --- a/src/Aquarium.Engine.Fractal/Projection/ProjectionReport.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Globalization; -using System.Text; - -namespace Aquarium.Engine.Fractal.Projection; - -public static class ProjectionReport -{ - public static string BuildMarkdown(IReadOnlyList projections, int samplesPerAxis) - { - ArgumentNullException.ThrowIfNull(projections); - - if (projections.Count == 0) - { - throw new ArgumentException("At least one projection is required.", nameof(projections)); - } - - var builder = new StringBuilder(); - builder.AppendLine("# Cube-Sphere Projection Report"); - builder.AppendLine(); - builder.AppendLine("Unit sphere area target per cube-coordinate area is `pi / 6`."); - builder.AppendLine("Lower mean absolute relative area error is better for terrain density."); - builder.AppendLine(); - builder.AppendLine("| Projection | Face | Samples | Avg area scale | Min rel area | Max rel area | Mean abs rel error | RMS rel error |"); - builder.AppendLine("| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |"); - - foreach (var projection in projections) - { - foreach (var face in Enum.GetValues()) - { - var result = ProjectionDistortionSampler.SampleFace(projection, face, samplesPerAxis); - builder.Append("| ") - .Append(result.ProjectionName) - .Append(" | ") - .Append(result.Face) - .Append(" | ") - .Append(result.SamplesPerAxis.ToString(CultureInfo.InvariantCulture)) - .Append(" | ") - .Append(Format(result.AverageAreaScale)) - .Append(" | ") - .Append(Format(result.MinRelativeArea)) - .Append(" | ") - .Append(Format(result.MaxRelativeArea)) - .Append(" | ") - .Append(Format(result.MeanAbsoluteRelativeAreaError)) - .Append(" | ") - .Append(Format(result.RootMeanSquareRelativeAreaError)) - .AppendLine(" |"); - } - } - - builder.AppendLine(); - builder.AppendLine("Default for the first terrain slice: `tangent`."); - builder.AppendLine("It is still cheap, remains seam-compatible with the cube face mapping, and the sampler gives it lower area spread than direct normalization on this harness."); - return builder.ToString(); - } - - private static string Format(double value) - { - return value.ToString("0.000000", CultureInfo.InvariantCulture); - } -} diff --git a/src/Aquarium.Engine.Fractal/Projection/TangentCubeSphereProjection.cs b/src/Aquarium.Engine.Fractal/Projection/TangentCubeSphereProjection.cs deleted file mode 100644 index 12ea804..0000000 --- a/src/Aquarium.Engine.Fractal/Projection/TangentCubeSphereProjection.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Projection; - -public sealed class TangentCubeSphereProjection : ICubeSphereProjection -{ - private const double QuarterPi = Math.PI * 0.25; - - public string Name => "tangent"; - - public Vector3 Project(CubeFacePosition position) - { - var warped = new CubeFacePosition(position.Face, Math.Tan(position.U * QuarterPi), Math.Tan(position.V * QuarterPi)); - return Vector3.Normalize(warped.ToCubeVector()); - } -} diff --git a/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceCandidate.cs b/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceCandidate.cs deleted file mode 100644 index 7e9d2e5..0000000 --- a/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceCandidate.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace Aquarium.Engine.Fractal.Temporal; - -public readonly record struct ResampledImportanceCandidate( - TSample Sample, - float Target, - float SourcePdf, - int CandidateCount = 1) -{ - public float ImportanceWeight - { - get - { - if (!float.IsFinite(Target) || !float.IsFinite(SourcePdf) || Target <= 0.0f || SourcePdf <= 0.0f) - { - return 0.0f; - } - - return Target / SourcePdf; - } - } -} diff --git a/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceReservoir.cs b/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceReservoir.cs deleted file mode 100644 index 4d9bc08..0000000 --- a/src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceReservoir.cs +++ /dev/null @@ -1,110 +0,0 @@ -namespace Aquarium.Engine.Fractal.Temporal; - -public sealed class ResampledImportanceReservoir -{ - private const float Epsilon = 1.0e-8f; - - private TSample selectedSample = default!; - - public bool HasSample { get; private set; } - - public TSample SelectedSample - { - get - { - if (!HasSample) - { - throw new InvalidOperationException("The reservoir does not contain a selected sample."); - } - - return selectedSample; - } - } - - public float SelectedTarget { get; private set; } - - public float WeightSum { get; private set; } - - public int CandidateCount { get; private set; } - - public float ContributionWeight - { - get - { - if (!HasSample || CandidateCount <= 0 || SelectedTarget <= Epsilon) - { - return 0.0f; - } - - return WeightSum / (CandidateCount * SelectedTarget); - } - } - - public bool Add(ResampledImportanceCandidate candidate, double randomUnit) - { - return AddWeightedSample( - candidate.Sample, - candidate.Target, - candidate.ImportanceWeight, - candidate.CandidateCount, - randomUnit); - } - - public bool Merge(ResampledImportanceReservoir other, double randomUnit) - { - if (other is null) - { - throw new ArgumentNullException(nameof(other)); - } - - if (!other.HasSample) - { - return false; - } - - return AddWeightedSample( - other.SelectedSample, - other.SelectedTarget, - other.WeightSum, - other.CandidateCount, - randomUnit); - } - - private bool AddWeightedSample( - TSample sample, - float target, - float weightSum, - int candidateCount, - double randomUnit) - { - if (candidateCount <= 0 || !float.IsFinite(target) || target <= 0.0f || !float.IsFinite(weightSum) || weightSum <= 0.0f) - { - return false; - } - - if (!double.IsFinite(randomUnit) || randomUnit < 0.0 || randomUnit >= 1.0) - { - throw new ArgumentOutOfRangeException(nameof(randomUnit), "Reservoir random value must be in [0, 1)."); - } - - var previousWeightSum = WeightSum; - var nextWeightSum = previousWeightSum + weightSum; - if (!float.IsFinite(nextWeightSum) || nextWeightSum <= 0.0f) - { - return false; - } - - WeightSum = nextWeightSum; - CandidateCount = checked(CandidateCount + candidateCount); - - if (!HasSample || randomUnit < weightSum / nextWeightSum) - { - selectedSample = sample; - SelectedTarget = target; - HasSample = true; - return true; - } - - return false; - } -} diff --git a/src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianAccumulator.cs b/src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianAccumulator.cs deleted file mode 100644 index 90acb06..0000000 --- a/src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianAccumulator.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.Engine.Fractal.Temporal; - -public sealed class TemporalGaussianAccumulator -{ - private readonly TemporalSpatialEvidenceReservoir reservoir; - - public TemporalGaussianAccumulator( - float accumulationWindowSeconds, - float presentationDelaySeconds, - float smoothing = 0.35f) - { - if (!float.IsFinite(accumulationWindowSeconds) || accumulationWindowSeconds <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(accumulationWindowSeconds), accumulationWindowSeconds, "Accumulation window must be positive."); - } - - if (!float.IsFinite(presentationDelaySeconds) || presentationDelaySeconds < 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(presentationDelaySeconds), presentationDelaySeconds, "Presentation delay must be non-negative."); - } - - if (!float.IsFinite(smoothing) || smoothing <= 0.0f || smoothing > 1.0f) - { - throw new ArgumentOutOfRangeException(nameof(smoothing), smoothing, "Smoothing must be in (0, 1]."); - } - - reservoir = new TemporalSpatialEvidenceReservoir(accumulationWindowSeconds, presentationDelaySeconds, smoothing); - } - - public float AccumulationWindowSeconds => reservoir.AccumulationWindowSeconds; - - public float PresentationDelaySeconds => reservoir.PresentationDelaySeconds; - - public float Smoothing => reservoir.Smoothing; - - public void Observe(IEnumerable observations) - { - reservoir.Observe(observations.Select(TemporalSpatialEvidenceLowering.FromGaussianObservation)); - } - - public AquariumTemporalGaussianField BuildField(float renderTimeSeconds) - { - var snapshot = reservoir.BuildSnapshot(renderTimeSeconds); - var gaussians = new AquariumTemporalSdfGaussian[snapshot.Samples.Count]; - - for (var index = 0; index < snapshot.Samples.Count; index++) - { - gaussians[index] = TemporalSpatialEvidenceLowering.ToTemporalGaussian(snapshot.Samples[index]); - } - - return new AquariumTemporalGaussianField - { - Gaussians = gaussians, - AccumulationWindowSeconds = AccumulationWindowSeconds, - PresentationDelaySeconds = PresentationDelaySeconds, - }; - } -} diff --git a/src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianObservation.cs b/src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianObservation.cs deleted file mode 100644 index cff5c8c..0000000 --- a/src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianObservation.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Temporal; - -public readonly record struct TemporalGaussianObservation( - string StableKey, - Vector3 Center, - Vector3 Radii, - Quaternion Orientation, - Vector4 ColorOpacity, - float Confidence, - float ObservedTimeSeconds, - float Falloff = 4.0f, - float ShapePower = 1.0f, - int FieldId = 0); diff --git a/src/Aquarium.Engine.Fractal/Temporal/TemporalSdfGaussianKernel.cs b/src/Aquarium.Engine.Fractal/Temporal/TemporalSdfGaussianKernel.cs deleted file mode 100644 index be1cad5..0000000 --- a/src/Aquarium.Engine.Fractal/Temporal/TemporalSdfGaussianKernel.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.Engine.Fractal.Temporal; - -public static class TemporalSdfGaussianKernel -{ - public static float CompactWeight(AquariumTemporalSdfGaussian gaussian, Vector3 point) - { - var local = Vector3.Transform(point - gaussian.Center, Quaternion.Inverse(gaussian.Orientation)); - var radii = Vector3.Max(gaussian.Radii, new Vector3(0.0001f)); - var q = local / radii; - var radiusSquared = Vector3.Dot(q, q); - if (radiusSquared >= 1.0f) - { - return 0.0f; - } - - var falloff = MathF.Max(gaussian.Falloff, 0.0001f); - var shapePower = MathF.Max(gaussian.ShapePower, 0.0001f); - var edge = MathF.Exp(-falloff); - var value = MathF.Exp(-falloff * radiusSquared); - var compact = Math.Clamp((value - edge) / MathF.Max(1.0f - edge, 0.000001f), 0.0f, 1.0f); - return MathF.Pow(compact, shapePower); - } - - public static float SignedDistance(AquariumTemporalSdfGaussian gaussian, Vector3 point) - { - var local = Vector3.Transform(point - gaussian.Center, Quaternion.Inverse(gaussian.Orientation)); - var radii = Vector3.Max(gaussian.Radii, new Vector3(0.0001f)); - var q = local / radii; - return (q.Length() - 1.0f) * MathF.Min(radii.X, MathF.Min(radii.Y, radii.Z)); - } -} diff --git a/src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceLowering.cs b/src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceLowering.cs deleted file mode 100644 index 2ae8497..0000000 --- a/src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceLowering.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.Engine.Fractal.Temporal; - -public static class TemporalSpatialEvidenceLowering -{ - public static TemporalSpatialEvidenceObservation FromGaussianObservation(TemporalGaussianObservation observation) - { - return new TemporalSpatialEvidenceObservation( - observation.StableKey, - observation.Center, - observation.Radii, - observation.Orientation, - observation.ColorOpacity, - new Vector4( - MathF.Max(0.0001f, observation.Falloff), - MathF.Max(0.0001f, observation.ShapePower), - 0.0f, - 0.0f), - observation.Confidence, - observation.ObservedTimeSeconds, - observation.FieldId, - AquariumFieldLayer.Form, - AquariumFieldEncoding.Density); - } - - public static AquariumTemporalSdfGaussian ToTemporalGaussian(TemporalSpatialEvidenceSample sample) - { - return new AquariumTemporalSdfGaussian( - sample.StableKey, - sample.Center, - sample.PreviousCenter, - sample.Velocity, - sample.Radii, - sample.Orientation, - sample.Payload0, - sample.Confidence, - sample.HistoryWeight, - sample.LastObservedTimeSeconds, - MathF.Max(0.0001f, sample.Payload1.X), - MathF.Max(0.0001f, sample.Payload1.Y), - sample.FieldId); - } - - public static TemporalSpatialEvidenceObservation FromGpuFusionSeed(AquariumGpuFusionSeed seed, float observedTimeSeconds) - { - return new TemporalSpatialEvidenceObservation( - seed.StableKey, - seed.Center, - seed.Radii, - Quaternion.Identity, - seed.ColorOpacity, - new Vector4( - MathF.Max(0.0001f, seed.Falloff), - MathF.Max(0.0001f, seed.ShapePower), - seed.HistoryWeight, - 0.0f), - seed.Confidence, - observedTimeSeconds, - seed.FieldId, - AquariumFieldLayer.Form, - AquariumFieldEncoding.Confidence); - } - - public static AquariumGpuFusionSeed ToGpuFusionSeed(TemporalSpatialEvidenceSample sample) - { - return new AquariumGpuFusionSeed( - sample.StableKey, - sample.Center, - sample.PreviousCenter, - sample.Velocity, - sample.Radii, - sample.Payload0, - sample.Confidence, - sample.HistoryWeight, - MathF.Max(0.0001f, sample.Payload1.X), - MathF.Max(0.0001f, sample.Payload1.Y), - sample.FieldId); - } -} diff --git a/src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceObservation.cs b/src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceObservation.cs deleted file mode 100644 index 4a6f2aa..0000000 --- a/src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceObservation.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Temporal; - -public readonly record struct TemporalSpatialEvidenceObservation( - string StableKey, - Vector3 Center, - Vector3 Radii, - Quaternion Orientation, - Vector4 Payload0, - Vector4 Payload1, - float Confidence, - float ObservedTimeSeconds, - int FieldId = 0, - AquariumFieldLayer Layer = AquariumFieldLayer.Form, - AquariumFieldEncoding Encoding = AquariumFieldEncoding.Density); - -public readonly record struct TemporalSpatialEvidenceSample( - string StableKey, - Vector3 Center, - Vector3 PreviousCenter, - Vector3 Velocity, - Vector3 Radii, - Quaternion Orientation, - Vector4 Payload0, - Vector4 Payload1, - float Confidence, - float HistoryWeight, - float LastObservedTimeSeconds, - int FieldId, - AquariumFieldLayer Layer = AquariumFieldLayer.Form, - AquariumFieldEncoding Encoding = AquariumFieldEncoding.Density); - -public sealed class TemporalSpatialEvidenceSnapshot -{ - public TemporalSpatialEvidenceSnapshot( - IReadOnlyList samples, - float accumulationWindowSeconds, - float presentationDelaySeconds) - { - Samples = samples; - AccumulationWindowSeconds = accumulationWindowSeconds; - PresentationDelaySeconds = presentationDelaySeconds; - } - - public IReadOnlyList Samples { get; } - - public float AccumulationWindowSeconds { get; } - - public float PresentationDelaySeconds { get; } -} diff --git a/src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceReservoir.cs b/src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceReservoir.cs deleted file mode 100644 index 1ac1ca8..0000000 --- a/src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceReservoir.cs +++ /dev/null @@ -1,211 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Engine.Fractal.Temporal; - -public sealed class TemporalSpatialEvidenceReservoir -{ - private readonly Dictionary tracks = []; - - public TemporalSpatialEvidenceReservoir( - float accumulationWindowSeconds, - float presentationDelaySeconds, - float smoothing = 0.35f, - int maxTrackCount = int.MaxValue) - { - if (!float.IsFinite(accumulationWindowSeconds) || accumulationWindowSeconds <= 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(accumulationWindowSeconds), accumulationWindowSeconds, "Accumulation window must be positive."); - } - - if (!float.IsFinite(presentationDelaySeconds) || presentationDelaySeconds < 0.0f) - { - throw new ArgumentOutOfRangeException(nameof(presentationDelaySeconds), presentationDelaySeconds, "Presentation delay must be non-negative."); - } - - if (!float.IsFinite(smoothing) || smoothing <= 0.0f || smoothing > 1.0f) - { - throw new ArgumentOutOfRangeException(nameof(smoothing), smoothing, "Smoothing must be in (0, 1]."); - } - - if (maxTrackCount <= 0) - { - throw new ArgumentOutOfRangeException(nameof(maxTrackCount), maxTrackCount, "Track budget must be positive."); - } - - AccumulationWindowSeconds = accumulationWindowSeconds; - PresentationDelaySeconds = presentationDelaySeconds; - Smoothing = smoothing; - MaxTrackCount = maxTrackCount; - } - - public float AccumulationWindowSeconds { get; } - - public float PresentationDelaySeconds { get; } - - public float Smoothing { get; } - - public int MaxTrackCount { get; } - - public int TrackCount => tracks.Count; - - public void Observe(IEnumerable observations) - { - foreach (var observation in observations) - { - if (string.IsNullOrWhiteSpace(observation.StableKey)) - { - continue; - } - - var trackKey = TrackKey(observation); - if (tracks.TryGetValue(trackKey, out var current)) - { - tracks[trackKey] = current.Update(observation, Smoothing); - } - else - { - tracks[trackKey] = TemporalSpatialEvidenceTrack.Create(observation); - } - } - - TrimToBudget(); - } - - public TemporalSpatialEvidenceSnapshot BuildSnapshot(float renderTimeSeconds) - { - var presentationTime = renderTimeSeconds - PresentationDelaySeconds; - var cutoff = presentationTime - AccumulationWindowSeconds; - var samples = new List(tracks.Count); - var expired = new List(); - - foreach (var (key, track) in tracks) - { - if (track.LastObservedTimeSeconds < cutoff) - { - expired.Add(key); - continue; - } - - var age = MathF.Max(0.0f, presentationTime - track.LastObservedTimeSeconds); - var historyWeight = Math.Clamp(1.0f - (age / AccumulationWindowSeconds), 0.0f, 1.0f) * track.Confidence; - var predictedCenter = track.Center + track.Velocity * (presentationTime - track.LastObservedTimeSeconds); - var previousCenter = predictedCenter - track.Velocity * (1.0f / 60.0f); - samples.Add(new TemporalSpatialEvidenceSample( - track.StableKey, - predictedCenter, - previousCenter, - track.Velocity, - track.Radii, - track.Orientation, - track.Payload0, - track.Payload1, - track.Confidence, - historyWeight, - track.LastObservedTimeSeconds, - track.FieldId, - track.Layer, - track.Encoding)); - } - - foreach (var key in expired) - { - tracks.Remove(key); - } - - return new TemporalSpatialEvidenceSnapshot( - samples.OrderByDescending(item => item.HistoryWeight).ToArray(), - AccumulationWindowSeconds, - PresentationDelaySeconds); - } - - private void TrimToBudget() - { - if (tracks.Count <= MaxTrackCount) - { - return; - } - - var evict = tracks - .OrderBy(item => item.Value.Confidence) - .ThenBy(item => item.Value.LastObservedTimeSeconds) - .Take(tracks.Count - MaxTrackCount) - .Select(item => item.Key) - .ToArray(); - - foreach (var key in evict) - { - tracks.Remove(key); - } - } - - private readonly record struct TemporalSpatialEvidenceTrack( - string StableKey, - Vector3 Center, - Vector3 Velocity, - Vector3 Radii, - Quaternion Orientation, - Vector4 Payload0, - Vector4 Payload1, - float Confidence, - float LastObservedTimeSeconds, - int FieldId, - AquariumFieldLayer Layer, - AquariumFieldEncoding Encoding) - { - public static TemporalSpatialEvidenceTrack Create(TemporalSpatialEvidenceObservation observation) - { - return new TemporalSpatialEvidenceTrack( - observation.StableKey, - observation.Center, - Vector3.Zero, - SanitizeRadii(observation.Radii), - SanitizeOrientation(observation.Orientation), - observation.Payload0, - observation.Payload1, - Math.Clamp(observation.Confidence, 0.0f, 1.0f), - observation.ObservedTimeSeconds, - observation.FieldId, - observation.Layer, - observation.Encoding); - } - - public TemporalSpatialEvidenceTrack Update(TemporalSpatialEvidenceObservation observation, float smoothing) - { - var dt = MathF.Max(0.0001f, observation.ObservedTimeSeconds - LastObservedTimeSeconds); - var measuredVelocity = (observation.Center - Center) / dt; - var alpha = smoothing * Math.Clamp(observation.Confidence, 0.0f, 1.0f); - var updatedCenter = Vector3.Lerp(Center, observation.Center, alpha); - return this with - { - Center = updatedCenter, - Velocity = Vector3.Lerp(Velocity, measuredVelocity, alpha), - Radii = Vector3.Lerp(Radii, SanitizeRadii(observation.Radii), alpha), - Orientation = SanitizeOrientation(Quaternion.Slerp(Orientation, SanitizeOrientation(observation.Orientation), alpha)), - Payload0 = Vector4.Lerp(Payload0, observation.Payload0, alpha), - Payload1 = Vector4.Lerp(Payload1, observation.Payload1, alpha), - Confidence = Math.Clamp((Confidence * 0.85f) + (observation.Confidence * 0.15f), 0.0f, 1.0f), - LastObservedTimeSeconds = observation.ObservedTimeSeconds, - FieldId = observation.FieldId, - Layer = observation.Layer, - Encoding = observation.Encoding, - }; - } - - private static Vector3 SanitizeRadii(Vector3 radii) - { - return Vector3.Max(radii, new Vector3(0.0001f)); - } - - private static Quaternion SanitizeOrientation(Quaternion orientation) - { - return orientation.LengthSquared() <= 0.000001f - ? Quaternion.Identity - : Quaternion.Normalize(orientation); - } - } - - private static string TrackKey(TemporalSpatialEvidenceObservation observation) - { - return $"{observation.Layer}:{observation.Encoding}:{observation.StableKey}"; - } -} diff --git a/src/Aquarium.Engine/Aquarium.Engine.csproj b/src/Aquarium.Engine/Aquarium.Engine.csproj deleted file mode 100644 index 305d312..0000000 --- a/src/Aquarium.Engine/Aquarium.Engine.csproj +++ /dev/null @@ -1,38 +0,0 @@ - - - - WinExe - net10.0 - enable - enable - true - Assets\Fensalir-Icon.ico - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Aquarium.Engine/AquariumHost.cs b/src/Aquarium.Engine/AquariumHost.cs deleted file mode 100644 index 3861253..0000000 --- a/src/Aquarium.Engine/AquariumHost.cs +++ /dev/null @@ -1,305 +0,0 @@ -using System.Diagnostics; -using Aquarium.Engine.Audio; -using Aquarium.Engine.Input; -using Aquarium.Engine.Platform; -using Aquarium.Engine.Render; -using Aquarium.Engine.Runtime; - -namespace Aquarium.Engine; - -public static class AquariumHost -{ - public static int Run(string[] args) - { - var runtimeOptions = new AquariumRuntimeOptions(ParseHeadless(args), ParseCachePath(args), ParseRenderDebugMode(args)); - using var runtimeLoader = new ClientRuntimeLoader(runtimeOptions, ParseClientAssemblyPath(args), ParseClientReloadPointerPath(args)); - var runtime = runtimeLoader.Load(); - var input = new InputState(); - var headlessSize = ParseHeadlessSize(args); - var width = runtime.Options.Headless ? headlessSize.Width : 1280; - var height = runtime.Options.Headless ? headlessSize.Height : 720; - var iconPath = Path.Combine(AppContext.BaseDirectory, "Assets", "Fensalir-Icon.ico"); - var splashPath = Path.Combine(AppContext.BaseDirectory, "Assets", "Fensalir-Splash.bmp"); - using var window = Win32Window.Create("Fensalir", width, height, input, iconPath, splashPath, visible: !runtime.Options.Headless); - window.PaintSplash("Fensalir", "Preparing runtime state"); - using var synthHost = new AquariumSynthHost(); - using var renderer = CreateRenderer( - window.Handle, - window.ClientWidth, - window.ClientHeight, - ParseShaderPath(args), - runtime.RenderPlan, - runtime.GraphicsSettings, - message => window.PaintSplash("Fensalir", message)); - renderer.DebugUiVisible = !runtime.Options.Headless; - var settingsRuntime = runtimeLoader.Runtime; - - var frameClock = Stopwatch.StartNew(); - var lastFrame = frameClock.Elapsed; - var frames = 0; - var readyFrames = 0; - var requiredReadyFrames = ParseHeadlessReadyFrames(); - var captureFramePath = ParseCaptureFramePath(args); - var capturedFrame = false; - - while (true) - { - input.BeginFrame(); - if (!window.PumpMessages()) - { - break; - } - - var now = frameClock.Elapsed; - var deltaSeconds = (float)(now - lastFrame).TotalSeconds; - lastFrame = now; - - renderer.UpdateUi(input, runtimeLoader.Runtime.Ui); - if (runtime.Options.Headless) - { - renderer.DebugUiVisible = false; - } - - var runtimeInput = renderer.CapturesInput ? input.WithoutInteractiveInput() : input; - if (!renderer.CapturesInput) - { - ApplyRendererDebugInput(renderer, input); - } - - SyncRendererSettingsToRuntime(renderer, runtimeLoader.Runtime); - runtimeLoader.Update(deltaSeconds, runtimeInput); - synthHost.Update(AquariumSynthDocument.Combine(runtimeLoader.Runtime.Synth, renderer.DebugSynth), runtimeLoader.Runtime.Audio, deltaSeconds); - if (!ReferenceEquals(settingsRuntime, runtimeLoader.Runtime)) - { - settingsRuntime = runtimeLoader.Runtime; - renderer.ApplyGraphicsSettings(settingsRuntime.GraphicsSettings); - } - - var renderFrame = runtimeLoader.Runtime.ComposeFrame( - runtimeLoader.Runtime.Frame, - new AquariumFrameInput(input.MousePosition, window.ClientWidth, window.ClientHeight)); - renderer.Render(renderFrame, window.ClientWidth, window.ClientHeight); - if (!runtime.Options.Headless && !renderer.HasPresentedReadyFrame) - { - window.PaintSplash("Fensalir", "Compiling renderer pipelines"); - } - - frames++; - if (renderer.HasPresentedReadyFrame) - { - readyFrames++; - } - - if (runtime.Options.Headless - && !capturedFrame - && !string.IsNullOrWhiteSpace(captureFramePath) - && readyFrames >= requiredReadyFrames) - { - renderer.SaveFramePng(captureFramePath); - Console.WriteLine($"Headless Aquarium frame captured: {Path.GetFullPath(captureFramePath)}"); - capturedFrame = true; - } - - if (runtime.Options.Headless && frames >= 2 && readyFrames >= requiredReadyFrames) - { - Console.WriteLine("Headless Aquarium completed requested frames."); - break; - } - } - - return 0; - } - - private static bool ParseHeadless(IEnumerable args) - { - return args.Any(arg => string.Equals(arg, "--headless", StringComparison.OrdinalIgnoreCase)); - } - - private static int ParseHeadlessReadyFrames() - { - return int.TryParse(Environment.GetEnvironmentVariable("AQUARIUM_HEADLESS_READY_FRAMES"), out var value) - ? Math.Max(1, value) - : 1; - } - - private static (int Width, int Height) ParseHeadlessSize(IReadOnlyCollection args) - { - var width = ParsePositiveIntArgument(args, "--headless-width", "AQUARIUM_HEADLESS_WIDTH", 640); - var height = ParsePositiveIntArgument(args, "--headless-height", "AQUARIUM_HEADLESS_HEIGHT", 360); - return (width, height); - } - - private static string? ParseCaptureFramePath(IReadOnlyCollection args) - { - var values = args.ToArray(); - for (var index = 0; index < values.Length - 1; index++) - { - if (string.Equals(values[index], "--capture-frame", StringComparison.OrdinalIgnoreCase)) - { - return values[index + 1]; - } - } - - return Environment.GetEnvironmentVariable("AQUARIUM_CAPTURE_FRAME"); - } - - private static string? ParseCachePath(IReadOnlyCollection args) - { - var values = args.ToArray(); - for (var index = 0; index < values.Length - 1; index++) - { - if (string.Equals(values[index], "--cache", StringComparison.OrdinalIgnoreCase)) - { - return values[index + 1]; - } - } - - return Environment.GetEnvironmentVariable("AQUARIUM_CULTCACHE_PATH"); - } - - private static string? ParseShaderPath(IReadOnlyCollection args) - { - var values = args.ToArray(); - for (var index = 0; index < values.Length - 1; index++) - { - if (string.Equals(values[index], "--shader-source", StringComparison.OrdinalIgnoreCase)) - { - return values[index + 1]; - } - } - - return Environment.GetEnvironmentVariable("AQUARIUM_SHADER_SOURCE"); - } - - private static string? ParseClientAssemblyPath(IReadOnlyCollection args) - { - var values = args.ToArray(); - for (var index = 0; index < values.Length - 1; index++) - { - if (string.Equals(values[index], "--client-assembly", StringComparison.OrdinalIgnoreCase) - || string.Equals(values[index], "--live-assembly", StringComparison.OrdinalIgnoreCase)) - { - return values[index + 1]; - } - } - - return Environment.GetEnvironmentVariable("AQUARIUM_CLIENT_ASSEMBLY") - ?? Environment.GetEnvironmentVariable("AQUARIUM_LIVE_ASSEMBLY"); - } - - private static string? ParseClientReloadPointerPath(IReadOnlyCollection args) - { - var values = args.ToArray(); - for (var index = 0; index < values.Length - 1; index++) - { - if (string.Equals(values[index], "--client-reload-pointer", StringComparison.OrdinalIgnoreCase) - || string.Equals(values[index], "--live-reload-pointer", StringComparison.OrdinalIgnoreCase)) - { - return values[index + 1]; - } - } - - return Environment.GetEnvironmentVariable("AQUARIUM_CLIENT_RELOAD_POINTER") - ?? Environment.GetEnvironmentVariable("AQUARIUM_LIVE_RELOAD_POINTER"); - } - - private static int? ParseRenderDebugMode(IReadOnlyCollection args) - { - var values = args.ToArray(); - for (var index = 0; index < values.Length - 1; index++) - { - if (string.Equals(values[index], "--render-debug", StringComparison.OrdinalIgnoreCase) - && int.TryParse(values[index + 1], out var mode)) - { - return mode; - } - } - - return int.TryParse(Environment.GetEnvironmentVariable("AQUARIUM_RENDER_DEBUG_MODE"), out var environmentMode) - ? environmentMode - : null; - } - - private static int ParsePositiveIntArgument(IReadOnlyCollection args, string name, string environmentName, int fallback) - { - var values = args.ToArray(); - for (var index = 0; index < values.Length - 1; index++) - { - if (string.Equals(values[index], name, StringComparison.OrdinalIgnoreCase) - && int.TryParse(values[index + 1], out var value)) - { - return Math.Max(1, value); - } - } - - return int.TryParse(Environment.GetEnvironmentVariable(environmentName), out var environmentValue) - ? Math.Max(1, environmentValue) - : fallback; - } - - private static IAquariumRenderer CreateRenderer( - IntPtr windowHandle, - int width, - int height, - string? shaderPath, - AquariumRenderPlan renderPlan, - GraphicsSettings graphicsSettings, - Action? startupProgress) - { - return new D3D12Renderer(windowHandle, width, height, shaderPath, renderPlan, graphicsSettings, startupProgress); - } - - private static void SyncRendererSettingsToRuntime(IAquariumRenderer renderer, IAquariumRuntime runtime) - { - var settings = renderer.CaptureGraphicsSettings(); - if (settings != runtime.GraphicsSettings) - { - runtime.GraphicsSettings = settings; - } - } - - private static void ApplyRendererDebugInput(IAquariumRenderer renderer, InputState input) - { - if (input.IsKeyPressed(KeyCode.RenderDebugCycle)) - { - renderer.CycleRenderDebugMode(); - } - - if (input.IsKeyPressed(KeyCode.Digit0)) - { - renderer.RenderDebugMode = 0; - } - else if (input.IsKeyPressed(KeyCode.Digit1)) - { - renderer.RenderDebugMode = 1; - } - else if (input.IsKeyPressed(KeyCode.Digit2)) - { - renderer.RenderDebugMode = 2; - } - else if (input.IsKeyPressed(KeyCode.Digit3)) - { - renderer.RenderDebugMode = 3; - } - else if (input.IsKeyPressed(KeyCode.Digit4)) - { - renderer.RenderDebugMode = 4; - } - else if (input.IsKeyPressed(KeyCode.Digit5)) - { - renderer.RenderDebugMode = 5; - } - else if (input.IsKeyPressed(KeyCode.Digit6)) - { - renderer.RenderDebugMode = 6; - } - else if (input.IsKeyPressed(KeyCode.Digit7)) - { - renderer.RenderDebugMode = 7; - } - else if (input.IsKeyPressed(KeyCode.Digit8)) - { - renderer.RenderDebugMode = 8; - } - } -} diff --git a/src/Aquarium.Engine/Assets/Fensalir-Icon-96.png b/src/Aquarium.Engine/Assets/Fensalir-Icon-96.png deleted file mode 100644 index 7d937f4..0000000 Binary files a/src/Aquarium.Engine/Assets/Fensalir-Icon-96.png and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Fensalir-Icon.ico b/src/Aquarium.Engine/Assets/Fensalir-Icon.ico deleted file mode 100644 index 1632f71..0000000 Binary files a/src/Aquarium.Engine/Assets/Fensalir-Icon.ico and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Fensalir-Splash.bmp b/src/Aquarium.Engine/Assets/Fensalir-Splash.bmp deleted file mode 100644 index 3a58a6e..0000000 Binary files a/src/Aquarium.Engine/Assets/Fensalir-Splash.bmp and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Fensalir-Splash.png b/src/Aquarium.Engine/Assets/Fensalir-Splash.png deleted file mode 100644 index a2b1afc..0000000 Binary files a/src/Aquarium.Engine/Assets/Fensalir-Splash.png and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Fonts/Montserrat[wght].ttf b/src/Aquarium.Engine/Assets/Fonts/Montserrat[wght].ttf deleted file mode 100644 index c97aca1..0000000 Binary files a/src/Aquarium.Engine/Assets/Fonts/Montserrat[wght].ttf and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Fonts/UbuntuSansMono.ttf b/src/Aquarium.Engine/Assets/Fonts/UbuntuSansMono.ttf deleted file mode 100644 index 3d8d0e7..0000000 Binary files a/src/Aquarium.Engine/Assets/Fonts/UbuntuSansMono.ttf and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Fonts/UbuntuSans[wdth,wght].ttf b/src/Aquarium.Engine/Assets/Fonts/UbuntuSans[wdth,wght].ttf deleted file mode 100644 index d1ebb55..0000000 Binary files a/src/Aquarium.Engine/Assets/Fonts/UbuntuSans[wdth,wght].ttf and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.png b/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.png deleted file mode 100644 index e7d9173..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.png and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.r8 b/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.r8 deleted file mode 100644 index bcf3b09..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/Aetheria-LDR_LLL1_0.r8 and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/studio2_irradiance.dds b/src/Aquarium.Engine/Assets/Textures/studio2_irradiance.dds deleted file mode 100644 index a3246b1..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/studio2_irradiance.dds and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds b/src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds deleted file mode 100644 index c8487bf..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/studio3_irradiance.dds b/src/Aquarium.Engine/Assets/Textures/studio3_irradiance.dds deleted file mode 100644 index ffb7fdb..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/studio3_irradiance.dds and /dev/null differ diff --git a/src/Aquarium.Engine/Assets/Textures/studio3_pmrem.dds b/src/Aquarium.Engine/Assets/Textures/studio3_pmrem.dds deleted file mode 100644 index a5097bd..0000000 Binary files a/src/Aquarium.Engine/Assets/Textures/studio3_pmrem.dds and /dev/null differ diff --git a/src/Aquarium.Engine/Audio/AquariumSynthHost.cs b/src/Aquarium.Engine/Audio/AquariumSynthHost.cs deleted file mode 100644 index c5031ad..0000000 --- a/src/Aquarium.Engine/Audio/AquariumSynthHost.cs +++ /dev/null @@ -1,277 +0,0 @@ -using AquaSynth.Faust; - -namespace Aquarium.Engine.Audio; - -internal sealed class AquariumSynthHost : IDisposable -{ - private const float CompileDebounceSeconds = 0.75f; - private static readonly bool TraceAudio = !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("AQUARIUM_AUDIO_TRACE")); - - private readonly Dictionary patches = new(StringComparer.Ordinal); - private readonly WasapiAudioDevice audioDevice = new(); - private readonly AquaSynthPatchCompiler patchCompiler = new(new AquaSynthNativeOptions(DspSourceDirectory: Path.Combine(AppContext.BaseDirectory, "Synth"))); - private float timeSeconds; - - public void Update(AquariumSynthDocument synth, AquariumAudioDocument audio, float deltaSeconds) - { - timeSeconds += Math.Max(deltaSeconds, 0.0f); - foreach (var chunk in audio.DrainPcmChunks()) - { - if (TraceAudio) - { - Console.WriteLine( - $"Aquarium audio drain: frames={chunk.MonoSamples.Length} sampleRate={chunk.SampleRate} leftGain={chunk.LeftGain:0.###} rightGain={chunk.RightGain:0.###}"); - } - - audioDevice.Play(chunk.MonoSamples, chunk.SampleRate, chunk.LeftGain, chunk.RightGain); - } - - if (!synth.Enabled) - { - return; - } - - foreach (var patch in synth.Patches) - { - var runtime = GetRuntime(patch); - UpdatePatch(runtime, patch); - PublishStatus(runtime, patch); - var pendingFireReady = false; - lock (runtime.Sync) - { - pendingFireReady = runtime.PendingFire && runtime.Compiled is not null && runtime.ReadyKey == runtime.DesiredKey; - if (pendingFireReady) - { - runtime.PendingFire = false; - } - } - - if (pendingFireReady) - { - Play(runtime, patch, synth.MasterGain); - } - - if (ShouldTrigger(runtime, patch.Trigger, timeSeconds - deltaSeconds, timeSeconds)) - { - Play(runtime, patch, synth.MasterGain); - } - } - } - - private PatchRuntime GetRuntime(AquariumSynthPatch patch) - { - if (patches.TryGetValue(patch.Id, out var runtime)) - { - return runtime; - } - - runtime = new PatchRuntime(patch.Id); - patches.Add(patch.Id, runtime); - return runtime; - } - - private void UpdatePatch(PatchRuntime runtime, AquariumSynthPatch patch) - { - var identity = Identity(patch); - var desiredKey = identity.CompileKey; - if (runtime.DesiredKey != desiredKey) - { - runtime.DesiredKey = desiredKey; - runtime.FailedKey = ""; - runtime.ScriptChangedAt = timeSeconds; - runtime.SoundCache.Clear(); - if (runtime.State != AquariumSynthPatchCompileState.Compiling) - { - SetStatus(runtime, AquariumSynthPatchCompileState.Queued, "waiting for edit pause", patch.FaustCompileRevision); - } - } - - if (runtime.State == AquariumSynthPatchCompileState.Compiling || - runtime.ReadyKey == desiredKey || - runtime.FailedKey == desiredKey || - runtime.DesiredKey != desiredKey || - timeSeconds - runtime.ScriptChangedAt < CompileDebounceSeconds) - { - return; - } - - StartCompile(runtime, patch, identity, desiredKey); - } - - private void StartCompile( - PatchRuntime runtime, - AquariumSynthPatch patch, - AquaSynthCompileIdentity identity, - string compileKey) - { - SetStatus(runtime, AquariumSynthPatchCompileState.Compiling, "compiling AquaSynth DSP", patch.FaustCompileRevision); - var patchId = patch.Id; - var revision = patch.FaustCompileRevision; - - runtime.CompileTask = Task.Run(() => - { - try - { - if (!patchCompiler.TryCompileScript(identity, out var compiled, out var error)) - { - lock (runtime.Sync) - { - runtime.Compiled?.Dispose(); - runtime.Compiled = null; - runtime.ReadyKey = ""; - runtime.FailedKey = compileKey; - runtime.SoundCache.Clear(); - runtime.CompileTask = null; - runtime.SetStatus(AquariumSynthPatchCompileState.Failed, error ?? "AquaSynth patch compiler unavailable", revision, timeSeconds); - } - - Console.WriteLine($"Aquarium synth patch `{patchId}` AquaSynth compile failed: {error}"); - return; - } - - lock (runtime.Sync) - { - runtime.Compiled?.Dispose(); - runtime.Compiled = compiled; - runtime.ReadyKey = compileKey; - runtime.FailedKey = ""; - runtime.SoundCache.Clear(); - runtime.CompileTask = null; - runtime.SetStatus(AquariumSynthPatchCompileState.Ready, $"ready in {compiled!.Manifest.CompileMilliseconds:0} ms", revision, timeSeconds); - } - - Console.WriteLine($"Aquarium synth patch `{patchId}` compiled by AquaSynth in {compiled!.Manifest.CompileMilliseconds:0} ms."); - } - catch (Exception ex) - { - lock (runtime.Sync) - { - runtime.Compiled?.Dispose(); - runtime.Compiled = null; - runtime.ReadyKey = ""; - runtime.FailedKey = compileKey; - runtime.SoundCache.Clear(); - runtime.CompileTask = null; - runtime.SetStatus(AquariumSynthPatchCompileState.Failed, ex.Message, revision, timeSeconds); - } - - Console.WriteLine($"Aquarium synth patch `{patchId}` AquaSynth compile failed: {ex.Message}"); - } - }); - } - - private void Play(PatchRuntime runtime, AquariumSynthPatch patch, float masterGain) - { - CachedSound? sound; - int sampleRate; - lock (runtime.Sync) - { - if (runtime.Compiled is null || runtime.ReadyKey != runtime.DesiredKey) - { - runtime.PendingFire = true; - return; - } - - sampleRate = runtime.Compiled.Manifest.SampleRate; - var gain = patch.Gain * masterGain; - var soundKey = gain.ToString("R", System.Globalization.CultureInfo.InvariantCulture); - if (!runtime.SoundCache.TryGetValue(soundKey, out sound)) - { - sound = new CachedSound(runtime.Compiled.Render(gain)); - runtime.SoundCache[soundKey] = sound; - } - } - - if (sound.Samples.Length == 0) - { - return; - } - - audioDevice.Play(sound.Samples, sampleRate); - } - - private void PublishStatus(PatchRuntime runtime, AquariumSynthPatch patch) - { - AquariumSynthPatchStatus status; - lock (runtime.Sync) - { - status = runtime.Status; - } - - patch.StatusSink?.Invoke(status); - } - - private void SetStatus(PatchRuntime runtime, AquariumSynthPatchCompileState state, string message, int revision) - { - lock (runtime.Sync) - { - runtime.SetStatus(state, message, revision, timeSeconds); - } - } - - private static bool ShouldTrigger(PatchRuntime runtime, AquariumSynthTrigger trigger, float previousTime, float currentTime) - { - if (trigger.FireRevision > 0 && trigger.FireRevision != runtime.LastFireRevision) - { - runtime.LastFireRevision = trigger.FireRevision; - return true; - } - - if (!float.IsFinite(trigger.IntervalSeconds)) - { - return false; - } - - var interval = MathF.Max(trigger.IntervalSeconds, 0.001f); - var previousBeat = MathF.Floor((previousTime - trigger.PhaseSeconds) / interval); - var currentBeat = MathF.Floor((currentTime - trigger.PhaseSeconds) / interval); - return currentBeat > previousBeat; - } - - private static AquaSynthCompileIdentity Identity(AquariumSynthPatch patch) => - new(patch.Id, patch.FaustName, patch.Script, patch.FaustCompileRevision); - - public void Dispose() - { - var compileTasks = patches.Values - .Select(runtime => runtime.CompileTask) - .Where(task => task is not null) - .Cast() - .ToArray(); - if (compileTasks.Length > 0) - { - _ = Task.WaitAll(compileTasks, TimeSpan.FromSeconds(10.0)); - } - - foreach (var runtime in patches.Values) - { - runtime.Compiled?.Dispose(); - } - - audioDevice.Dispose(); - patchCompiler.Dispose(); - } - - private sealed class PatchRuntime(string id) - { - public readonly object Sync = new(); - public readonly Dictionary SoundCache = new(StringComparer.Ordinal); - public string DesiredKey { get; set; } = ""; - public string ReadyKey { get; set; } = ""; - public string FailedKey { get; set; } = ""; - public float ScriptChangedAt { get; set; } - public AquaSynthCompiledPatch? Compiled { get; set; } - public Task? CompileTask { get; set; } - public int LastFireRevision { get; set; } - public bool PendingFire { get; set; } - public AquariumSynthPatchCompileState State => Status.State; - public AquariumSynthPatchStatus Status { get; private set; } = new(id, AquariumSynthPatchCompileState.Idle, "idle", 0, 0.0); - - public void SetStatus(AquariumSynthPatchCompileState state, string message, int revision, double changedAtSeconds) - { - Status = new AquariumSynthPatchStatus(id, state, message, revision, changedAtSeconds); - } - } - - private sealed record CachedSound(float[] Samples); -} diff --git a/src/Aquarium.Engine/Audio/WasapiAudioDevice.cs b/src/Aquarium.Engine/Audio/WasapiAudioDevice.cs deleted file mode 100644 index f459359..0000000 --- a/src/Aquarium.Engine/Audio/WasapiAudioDevice.cs +++ /dev/null @@ -1,410 +0,0 @@ -using System.Runtime.InteropServices; - -namespace Aquarium.Engine.Audio; - -internal sealed class WasapiAudioDevice : IDisposable -{ - private static readonly bool TraceAudio = !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("AQUARIUM_AUDIO_TRACE")); - private readonly object sync = new(); - private readonly List voices = []; - private readonly Thread thread; - private volatile int outputSampleRate = 44100; - private volatile bool running = true; - private volatile bool started; - - public WasapiAudioDevice() - { - thread = new Thread(AudioThread) - { - IsBackground = true, - Name = "Aquarium WASAPI Audio" - }; - thread.Start(); - } - - public void Play(ReadOnlySpan monoSamples, int sourceSampleRate) - { - Play(monoSamples, sourceSampleRate, 1.0f, 1.0f); - } - - public void Play(ReadOnlySpan monoSamples, int sourceSampleRate, float leftGain, float rightGain) - { - if (monoSamples.Length == 0) - { - return; - } - - var copy = sourceSampleRate == outputSampleRate - ? monoSamples.ToArray() - : Resample(monoSamples, sourceSampleRate, outputSampleRate); - lock (sync) - { - voices.Add(new Voice(copy, Math.Clamp(leftGain, 0.0f, 4.0f), Math.Clamp(rightGain, 0.0f, 4.0f))); - if (TraceAudio) - { - Console.WriteLine( - $"Aquarium WASAPI voice queued: sourceFrames={monoSamples.Length} outputFrames={copy.Length} sourceRate={sourceSampleRate} outputRate={outputSampleRate} voices={voices.Count}"); - } - - if (voices.Count > 64) - { - voices.RemoveRange(0, voices.Count - 64); - } - } - } - - public void Dispose() - { - running = false; - if (started) - { - thread.Join(TimeSpan.FromSeconds(2.0)); - } - } - - private void AudioThread() - { - started = true; - var comInitialized = false; - IAudioClient? audioClient = null; - try - { - var hr = CoInitializeEx(IntPtr.Zero, CoInit.Multithreaded); - if (hr < 0) - { - Marshal.ThrowExceptionForHR(hr); - } - - comInitialized = true; -#pragma warning disable CA1416 - var enumeratorType = Type.GetTypeFromCLSID(MMDeviceEnumeratorClsid, throwOnError: true) - ?? throw new InvalidOperationException("MMDeviceEnumerator COM type is not available."); -#pragma warning restore CA1416 - var deviceEnumerator = (IMMDeviceEnumerator)(Activator.CreateInstance(enumeratorType) - ?? throw new InvalidOperationException("failed to create MMDeviceEnumerator")); - Marshal.ThrowExceptionForHR(deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.Render, ERole.Console, out var device)); - var audioClientId = typeof(IAudioClient).GUID; - Marshal.ThrowExceptionForHR(device.Activate(ref audioClientId, ClsCtx.All, IntPtr.Zero, out var audioClientObject)); - audioClient = (IAudioClient)audioClientObject; - Marshal.ThrowExceptionForHR(audioClient.GetMixFormat(out var mixFormatPointer)); - try - { - var format = WasapiFormat.FromPointer(mixFormatPointer); - outputSampleRate = format.SampleRate; - Marshal.ThrowExceptionForHR(audioClient.Initialize( - AudioClientShareMode.Shared, - AudioClientStreamFlags.NoPersist, - 0, - 0, - mixFormatPointer, - IntPtr.Zero)); - Marshal.ThrowExceptionForHR(audioClient.GetBufferSize(out var bufferFrameCount)); - var renderClientId = typeof(IAudioRenderClient).GUID; - Marshal.ThrowExceptionForHR(audioClient.GetService(ref renderClientId, out var renderClientObject)); - var renderClient = (IAudioRenderClient)renderClientObject; - PrimeSilence(renderClient, bufferFrameCount, format); - Marshal.ThrowExceptionForHR(audioClient.Start()); - Console.WriteLine($"Aquarium WASAPI audio started: {format.SampleRate} Hz, {format.Channels} channels, {format.BitsPerSample}-bit {format.SampleKind}."); - while (running) - { - Marshal.ThrowExceptionForHR(audioClient.GetCurrentPadding(out var padding)); - var availableFrames = bufferFrameCount - padding; - if (availableFrames > 0) - { - Marshal.ThrowExceptionForHR(renderClient.GetBuffer(availableFrames, out var buffer)); - try - { - FillBuffer(buffer, availableFrames, format); - } - finally - { - Marshal.ThrowExceptionForHR(renderClient.ReleaseBuffer(availableFrames, 0)); - } - } - - Thread.Sleep(4); - } - - audioClient.Stop(); - } - finally - { - Marshal.FreeCoTaskMem(mixFormatPointer); - } - } - catch (Exception ex) - { - Console.WriteLine($"Aquarium WASAPI audio unavailable: {ex.Message}"); - } - finally - { - audioClient?.Stop(); - if (comInitialized) - { - CoUninitialize(); - } - } - } - - private void PrimeSilence(IAudioRenderClient renderClient, int frameCount, WasapiFormat format) - { - Marshal.ThrowExceptionForHR(renderClient.GetBuffer(frameCount, out var buffer)); - try - { - FillSilence(buffer, frameCount, format); - } - finally - { - Marshal.ThrowExceptionForHR(renderClient.ReleaseBuffer(frameCount, 0)); - } - } - - private void FillBuffer(IntPtr buffer, int frameCount, WasapiFormat format) - { - if (format.SampleKind == WasapiSampleKind.Float32) - { - FillFloat32(buffer, frameCount, format.Channels); - } - else - { - FillPcm16(buffer, frameCount, format.Channels); - } - } - - private unsafe void FillFloat32(IntPtr buffer, int frameCount, int channels) - { - var output = (float*)buffer; - for (var frame = 0; frame < frameCount; frame++) - { - var sample = NextSample(); - for (var channel = 0; channel < channels; channel++) - { - *output++ = SampleForChannel(sample, channel, channels); - } - } - } - - private unsafe void FillPcm16(IntPtr buffer, int frameCount, int channels) - { - var output = (short*)buffer; - for (var frame = 0; frame < frameCount; frame++) - { - var sample = NextSample(); - for (var channel = 0; channel < channels; channel++) - { - *output++ = (short)Math.Clamp(SampleForChannel(sample, channel, channels) * short.MaxValue, short.MinValue, short.MaxValue); - } - } - } - - private unsafe void FillSilence(IntPtr buffer, int frameCount, WasapiFormat format) - { - var bytes = frameCount * format.BlockAlign; - new Span((void*)buffer, bytes).Clear(); - } - - private static float SampleForChannel(StereoSample sample, int channel, int channelCount) - { - if (channelCount == 1) - { - return (sample.Left + sample.Right) * 0.5f; - } - - return channel switch - { - 0 => sample.Left, - 1 => sample.Right, - _ => (sample.Left + sample.Right) * 0.5f - }; - } - - private StereoSample NextSample() - { - var left = 0.0f; - var right = 0.0f; - lock (sync) - { - for (var index = voices.Count - 1; index >= 0; index--) - { - var voice = voices[index]; - if (voice.Position >= voice.Samples.Length) - { - voices.RemoveAt(index); - continue; - } - - var sample = voice.Samples[voice.Position++]; - left += sample * voice.LeftGain; - right += sample * voice.RightGain; - } - } - - return new StereoSample(Math.Clamp(left, -1.0f, 1.0f), Math.Clamp(right, -1.0f, 1.0f)); - } - - private static float[] Resample(ReadOnlySpan source, int sourceSampleRate, int targetSampleRate) - { - if (source.Length == 0 || sourceSampleRate <= 0 || targetSampleRate <= 0) - { - return []; - } - - var targetLength = Math.Max(1, (int)Math.Ceiling(source.Length * (targetSampleRate / (double)sourceSampleRate))); - var target = new float[targetLength]; - var ratio = sourceSampleRate / (float)targetSampleRate; - for (var index = 0; index < target.Length; index++) - { - var sourcePosition = index * ratio; - var left = Math.Clamp((int)sourcePosition, 0, source.Length - 1); - var right = Math.Min(left + 1, source.Length - 1); - var t = sourcePosition - left; - target[index] = source[left] + (source[right] - source[left]) * t; - } - - return target; - } - - private readonly record struct StereoSample(float Left, float Right); - - private sealed class Voice(float[] samples, float leftGain, float rightGain) - { - public readonly float[] Samples = samples; - public readonly float LeftGain = leftGain; - public readonly float RightGain = rightGain; - public int Position; - } - - private readonly record struct WasapiFormat(int Channels, int SampleRate, int BitsPerSample, int BlockAlign, WasapiSampleKind SampleKind) - { - public static WasapiFormat FromPointer(IntPtr pointer) - { - var tag = Marshal.ReadInt16(pointer, 0); - var channels = Marshal.ReadInt16(pointer, 2); - var sampleRate = Marshal.ReadInt32(pointer, 4); - var blockAlign = Marshal.ReadInt16(pointer, 12); - var bitsPerSample = Marshal.ReadInt16(pointer, 14); - var kind = tag switch - { - WaveFormatIeeeFloat => WasapiSampleKind.Float32, - WaveFormatPcm => WasapiSampleKind.Pcm16, - WaveFormatExtensible when bitsPerSample == 32 => WasapiSampleKind.Float32, - _ => WasapiSampleKind.Pcm16 - }; - return new WasapiFormat(channels, sampleRate, bitsPerSample, blockAlign, kind); - } - } - - private enum WasapiSampleKind - { - Float32, - Pcm16 - } - - private const short WaveFormatPcm = 1; - private const short WaveFormatIeeeFloat = 3; - private const short WaveFormatExtensible = -2; - - [DllImport("ole32.dll")] - private static extern int CoInitializeEx(IntPtr pvReserved, CoInit dwCoInit); - - [DllImport("ole32.dll")] - private static extern void CoUninitialize(); - - [Flags] - private enum CoInit : uint - { - Multithreaded = 0x0 - } - - [Flags] - private enum ClsCtx : uint - { - All = 23 - } - - private enum EDataFlow - { - Render, - Capture, - All - } - - private enum ERole - { - Console, - Multimedia, - Communications - } - - private enum AudioClientShareMode - { - Shared, - Exclusive - } - - [Flags] - private enum AudioClientStreamFlags : uint - { - NoPersist = 0x00080000 - } - - private static readonly Guid MMDeviceEnumeratorClsid = new("BCDE0395-E52F-467C-8E3D-C4579291692E"); - - [ComImport] - [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IMMDeviceEnumerator - { - int EnumAudioEndpoints(EDataFlow dataFlow, uint stateMask, out IntPtr devices); - - int GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice endpoint); - } - - [ComImport] - [Guid("D666063F-1587-4E43-81F1-B948E807363F")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IMMDevice - { - int Activate(ref Guid iid, ClsCtx clsCtx, IntPtr activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object interfaceObject); - } - - [ComImport] - [Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IAudioClient - { - int Initialize(AudioClientShareMode shareMode, AudioClientStreamFlags streamFlags, long bufferDuration, long periodicity, IntPtr format, IntPtr audioSessionGuid); - - int GetBufferSize(out int bufferFrameCount); - - int GetStreamLatency(out long latency); - - int GetCurrentPadding(out int paddingFrameCount); - - int IsFormatSupported(AudioClientShareMode shareMode, IntPtr format, out IntPtr closestMatch); - - int GetMixFormat(out IntPtr deviceFormat); - - int GetDevicePeriod(out long defaultDevicePeriod, out long minimumDevicePeriod); - - int Start(); - - int Stop(); - - int Reset(); - - int SetEventHandle(IntPtr eventHandle); - - int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object serviceInterface); - } - - [ComImport] - [Guid("F294ACFC-3146-4483-A7BF-ADDCA7C260E2")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IAudioRenderClient - { - int GetBuffer(int numFramesRequested, out IntPtr dataBuffer); - - int ReleaseBuffer(int numFramesWritten, uint flags); - } -} diff --git a/src/Aquarium.Engine/Platform/Win32Window.cs b/src/Aquarium.Engine/Platform/Win32Window.cs deleted file mode 100644 index 5754be8..0000000 --- a/src/Aquarium.Engine/Platform/Win32Window.cs +++ /dev/null @@ -1,937 +0,0 @@ -using System.Runtime.InteropServices; -using System.Numerics; -using Aquarium.Engine.Input; - -namespace Aquarium.Engine.Platform; - -public sealed class Win32Window : IDisposable -{ - private const int CW_USEDEFAULT = unchecked((int)0x80000000); - private const uint WM_DESTROY = 0x0002; - private const uint WM_CLOSE = 0x0010; - private const uint WM_KEYDOWN = 0x0100; - private const uint WM_KEYUP = 0x0101; - private const uint WM_CHAR = 0x0102; - private const uint WM_MOUSEMOVE = 0x0200; - private const uint WM_LBUTTONDOWN = 0x0201; - private const uint WM_LBUTTONUP = 0x0202; - private const uint WM_RBUTTONDOWN = 0x0204; - private const uint WM_RBUTTONUP = 0x0205; - private const uint WM_MBUTTONDOWN = 0x0207; - private const uint WM_MBUTTONUP = 0x0208; - private const uint WM_MOUSEWHEEL = 0x020A; - private const uint PM_REMOVE = 0x0001; - private const uint WS_OVERLAPPEDWINDOW = 0x00CF0000; - private const uint WS_VISIBLE = 0x10000000; - private const int SW_SHOW = 5; - private const uint WM_SETICON = 0x0080; - private const nuint ICON_SMALL = 0; - private const nuint ICON_BIG = 1; - private const uint IMAGE_BITMAP = 0; - private const uint IMAGE_ICON = 1; - private const uint LR_LOADFROMFILE = 0x00000010; - private const uint LR_CREATEDIBSECTION = 0x00002000; - private const uint SRCCOPY = 0x00CC0020; - private const int ICON_SIZE_LARGE = 32; - private const int ICON_SIZE_SMALL = 16; - private const int IDC_ARROW = 32512; - private const int TRANSPARENT = 1; - private const int FW_THIN = 100; - private const int FW_REGULAR = 400; - private const uint FR_PRIVATE = 0x00000010; - private const uint DEFAULT_CHARSET = 1; - private const uint OUT_DEFAULT_PRECIS = 0; - private const uint CLIP_DEFAULT_PRECIS = 0; - private const uint ANTIALIASED_QUALITY = 4; - private const uint DEFAULT_PITCH = 0; - private const uint FF_DONTCARE = 0; - private const uint DT_CENTER = 0x00000001; - private const uint DT_VCENTER = 0x00000004; - private const uint DT_SINGLELINE = 0x00000020; - private const int LOGPIXELSY = 90; - private const int VK_W = 0x57; - private const int VK_A = 0x41; - private const int VK_S = 0x53; - private const int VK_D = 0x44; - private const int VK_0 = 0x30; - private const int VK_1 = 0x31; - private const int VK_2 = 0x32; - private const int VK_3 = 0x33; - private const int VK_4 = 0x34; - private const int VK_5 = 0x35; - private const int VK_6 = 0x36; - private const int VK_7 = 0x37; - private const int VK_8 = 0x38; - private const int VK_9 = 0x39; - private const int VK_F1 = 0x70; - private const int VK_F2 = 0x71; - private const int VK_BACK = 0x08; - private const int VK_DELETE = 0x2E; - private const int VK_RETURN = 0x0D; - private const int VK_LEFT = 0x25; - private const int VK_RIGHT = 0x27; - private const int VK_HOME = 0x24; - private const int VK_END = 0x23; - private const int VK_SHIFT = 0x10; - private const int WHEEL_DELTA = 120; - - private readonly WndProc windowProcedure; - private readonly string className; - private readonly InputState input; - private readonly IntPtr largeIcon; - private readonly IntPtr smallIcon; - private readonly IntPtr splashBitmap; - private readonly int splashBitmapWidth; - private readonly int splashBitmapHeight; - private bool disposed; - - private Win32Window( - IntPtr handle, - string className, - WndProc windowProcedure, - InputState input, - int width, - int height, - IntPtr largeIcon, - IntPtr smallIcon, - IntPtr splashBitmap, - int splashBitmapWidth, - int splashBitmapHeight) - { - Handle = handle; - this.className = className; - this.windowProcedure = windowProcedure; - this.input = input; - this.largeIcon = largeIcon; - this.smallIcon = smallIcon; - this.splashBitmap = splashBitmap; - this.splashBitmapWidth = splashBitmapWidth; - this.splashBitmapHeight = splashBitmapHeight; - ClientWidth = width; - ClientHeight = height; - } - - public IntPtr Handle { get; } - - public int ClientWidth { get; private set; } - - public int ClientHeight { get; private set; } - - public static Win32Window Create( - string title, - int width, - int height, - InputState input, - string? iconPath = null, - string? splashBitmapPath = null, - bool visible = true) - { - var className = $"AquariumEngineWindow-{Guid.NewGuid():N}"; - var instance = GetModuleHandle(null); - var largeIcon = LoadIconFromPath(iconPath, ICON_SIZE_LARGE); - var smallIcon = LoadIconFromPath(iconPath, ICON_SIZE_SMALL); - var splashBitmap = LoadSplashBitmapFromPath(splashBitmapPath, out var splashBitmapWidth, out var splashBitmapHeight); - var classNamePointer = Marshal.StringToHGlobalUni(className); - var titlePointer = Marshal.StringToHGlobalUni(title); - WndProc? windowProcedure = null; - - try - { - windowProcedure = (handle, message, wParam, lParam) => - { - switch (message) - { - case WM_CLOSE: - DestroyWindow(handle); - return IntPtr.Zero; - case WM_DESTROY: - PostQuitMessage(0); - return IntPtr.Zero; - case WM_MOUSEMOVE: - input.SetMousePosition(new Vector2(GetSignedLowWord(lParam), GetSignedHighWord(lParam))); - return IntPtr.Zero; - case WM_MOUSEWHEEL: - input.AddWheelDelta(GetSignedHighWord(wParam) / (float)WHEEL_DELTA); - return IntPtr.Zero; - case WM_LBUTTONDOWN: - input.SetMouseButton(MouseButton.Left, true); - SetCapture(handle); - return IntPtr.Zero; - case WM_LBUTTONUP: - input.SetMouseButton(MouseButton.Left, false); - ReleaseCapture(); - return IntPtr.Zero; - case WM_MBUTTONDOWN: - input.SetMouseButton(MouseButton.Middle, true); - SetCapture(handle); - return IntPtr.Zero; - case WM_MBUTTONUP: - input.SetMouseButton(MouseButton.Middle, false); - ReleaseCapture(); - return IntPtr.Zero; - case WM_RBUTTONDOWN: - input.SetMouseButton(MouseButton.Right, true); - SetCapture(handle); - return IntPtr.Zero; - case WM_RBUTTONUP: - input.SetMouseButton(MouseButton.Right, false); - ReleaseCapture(); - return IntPtr.Zero; - case WM_KEYDOWN: - SetKey(input, wParam, true); - return IntPtr.Zero; - case WM_KEYUP: - SetKey(input, wParam, false); - return IntPtr.Zero; - case WM_CHAR: - AddTextInput(input, (UIntPtr)wParam); - return IntPtr.Zero; - } - - return DefWindowProc(handle, message, wParam, lParam); - }; - - var windowClass = new WNDCLASSEX - { - cbSize = (uint)Marshal.SizeOf(), - lpfnWndProc = windowProcedure, - hInstance = instance, - hIcon = largeIcon, - hCursor = LoadCursor(IntPtr.Zero, IDC_ARROW), - lpszClassName = classNamePointer, - hIconSm = smallIcon, - }; - - if (RegisterClassEx(ref windowClass) == 0) - { - throw new InvalidOperationException($"RegisterClassEx failed: {Marshal.GetLastWin32Error()}"); - } - - var style = WS_OVERLAPPEDWINDOW; - if (visible) - { - style |= WS_VISIBLE; - } - - var handle = CreateWindowEx( - 0, - classNamePointer, - titlePointer, - style, - CW_USEDEFAULT, - CW_USEDEFAULT, - width, - height, - IntPtr.Zero, - IntPtr.Zero, - instance, - IntPtr.Zero); - - if (handle == IntPtr.Zero) - { - throw new InvalidOperationException($"CreateWindowEx failed: {Marshal.GetLastWin32Error()}"); - } - - if (visible) - { - ShowWindow(handle, SW_SHOW); - } - - if (largeIcon != IntPtr.Zero) - { - SendMessage(handle, WM_SETICON, ICON_BIG, largeIcon); - } - - if (smallIcon != IntPtr.Zero) - { - SendMessage(handle, WM_SETICON, ICON_SMALL, smallIcon); - } - - if (visible) - { - UpdateWindow(handle); - } - - SetWindowText(handle, title); - - return new Win32Window( - handle, - className, - windowProcedure, - input, - width, - height, - largeIcon, - smallIcon, - splashBitmap, - splashBitmapWidth, - splashBitmapHeight); - } - finally - { - Marshal.FreeHGlobal(classNamePointer); - Marshal.FreeHGlobal(titlePointer); - } - } - - public void PaintSplash(string header = "Fensalir", string message = "Preparing runtime") - { - if (!GetClientRect(Handle, out var rect)) - { - return; - } - - ClientWidth = Math.Max(1, rect.right - rect.left); - ClientHeight = Math.Max(1, rect.bottom - rect.top); - - var deviceContext = GetDC(Handle); - if (deviceContext == IntPtr.Zero) - { - return; - } - - try - { - if (splashBitmap != IntPtr.Zero) - { - PaintSplashBitmap(deviceContext, ClientWidth, ClientHeight); - } - else - { - PaintDiagonalGradient(deviceContext, ClientWidth, ClientHeight); - } - - PaintSplashText(deviceContext, ClientWidth, ClientHeight, header, message); - GdiFlush(); - } - finally - { - ReleaseDC(Handle, deviceContext); - } - } - - public bool PumpMessages() - { - while (PeekMessage(out var message, IntPtr.Zero, 0, 0, PM_REMOVE)) - { - if (message.message == 0x0012) - { - return false; - } - - TranslateMessage(ref message); - DispatchMessage(ref message); - } - - if (GetClientRect(Handle, out var rect)) - { - ClientWidth = Math.Max(1, rect.right - rect.left); - ClientHeight = Math.Max(1, rect.bottom - rect.top); - } - - return true; - } - - public void Dispose() - { - if (disposed) - { - return; - } - - disposed = true; - - if (Handle != IntPtr.Zero) - { - DestroyWindow(Handle); - } - - if (largeIcon != IntPtr.Zero) - { - DestroyIcon(largeIcon); - } - - if (smallIcon != IntPtr.Zero) - { - DestroyIcon(smallIcon); - } - - if (splashBitmap != IntPtr.Zero) - { - DeleteObject(splashBitmap); - } - - GC.SuppressFinalize(this); - } - - private static void PaintDiagonalGradient(IntPtr deviceContext, int width, int height) - { - var pixels = new uint[width * height]; - var denominator = Math.Max(1.0f, width + height); - for (var y = 0; y < height; y++) - { - for (var x = 0; x < width; x++) - { - var diagonal = (x + y) / denominator; - var vignetteX = x / Math.Max(1.0f, width - 1.0f) - 0.5f; - var vignetteY = y / Math.Max(1.0f, height - 1.0f) - 0.5f; - var vignette = Math.Clamp(1.0f - (vignetteX * vignetteX + vignetteY * vignetteY) * 0.72f, 0.0f, 1.0f); - var t = SmoothStep(0.0f, 1.0f, diagonal); - pixels[y * width + x] = LerpColor(0x05, 0x08, 0x18, 0x06, 0x1A, 0x3A, t, vignette); - } - } - - var bitmapInfo = new BITMAPINFO - { - bmiHeader = new BITMAPINFOHEADER - { - biSize = (uint)Marshal.SizeOf(), - biWidth = width, - biHeight = -height, - biPlanes = 1, - biBitCount = 32, - biCompression = 0, - }, - }; - - var handle = GCHandle.Alloc(pixels, GCHandleType.Pinned); - try - { - StretchDIBits( - deviceContext, - 0, - 0, - width, - height, - 0, - 0, - width, - height, - handle.AddrOfPinnedObject(), - ref bitmapInfo, - 0, - 0x00CC0020); - } - finally - { - handle.Free(); - } - } - - private void PaintSplashBitmap(IntPtr deviceContext, int width, int height) - { - var memoryDeviceContext = CreateCompatibleDC(deviceContext); - if (memoryDeviceContext == IntPtr.Zero) - { - PaintDiagonalGradient(deviceContext, width, height); - return; - } - - var oldBitmap = SelectObject(memoryDeviceContext, splashBitmap); - try - { - var sourceX = 0; - var sourceY = 0; - var sourceWidth = splashBitmapWidth; - var sourceHeight = splashBitmapHeight; - var sourceAspect = splashBitmapWidth / Math.Max(1.0f, splashBitmapHeight); - var targetAspect = width / Math.Max(1.0f, height); - - if (sourceAspect > targetAspect) - { - sourceWidth = Math.Max(1, (int)MathF.Round(splashBitmapHeight * targetAspect)); - sourceX = Math.Max(0, (splashBitmapWidth - sourceWidth) / 2); - } - else if (sourceAspect < targetAspect) - { - sourceHeight = Math.Max(1, (int)MathF.Round(splashBitmapWidth / targetAspect)); - sourceY = Math.Max(0, (splashBitmapHeight - sourceHeight) / 2); - } - - StretchBlt( - deviceContext, - 0, - 0, - width, - height, - memoryDeviceContext, - sourceX, - sourceY, - sourceWidth, - sourceHeight, - SRCCOPY); - } - finally - { - if (oldBitmap != IntPtr.Zero) - { - SelectObject(memoryDeviceContext, oldBitmap); - } - - DeleteDC(memoryDeviceContext); - } - } - - private static void PaintSplashText(IntPtr deviceContext, int width, int height, string header, string message) - { - LoadPrivateSplashFont("Montserrat[wght].ttf"); - LoadPrivateSplashFont("UbuntuSans[wdth,wght].ttf"); - - var oldBackgroundMode = SetBkMode(deviceContext, TRANSPARENT); - var oldTextColor = SetTextColor(deviceContext, ColorRef(224, 244, 255)); - var headerFont = CreateSplashFont(deviceContext, 26, FW_THIN, "Montserrat"); - var messageFont = CreateSplashFont(deviceContext, 12, FW_REGULAR, "Ubuntu Sans"); - - try - { - var anchorY = Math.Clamp((int)MathF.Round(height * 0.84f), 120, Math.Max(120, height - 56)); - var headerText = header.ToUpperInvariant(); - var headerRect = new RECT - { - left = 0, - top = anchorY - 30, - right = width, - bottom = anchorY + 24 - }; - var messageRect = new RECT - { - left = Math.Max(0, width / 2 - 360), - top = anchorY + 28, - right = Math.Min(width, width / 2 + 360), - bottom = anchorY + 56 - }; - - var oldFont = SelectObject(deviceContext, headerFont); - DrawText(deviceContext, headerText, headerText.Length, ref headerRect, DT_CENTER | DT_VCENTER | DT_SINGLELINE); - SelectObject(deviceContext, messageFont); - SetTextColor(deviceContext, ColorRef(142, 179, 190)); - DrawText(deviceContext, message, message.Length, ref messageRect, DT_CENTER | DT_VCENTER | DT_SINGLELINE); - SelectObject(deviceContext, oldFont); - } - finally - { - DeleteObject(messageFont); - DeleteObject(headerFont); - SetTextColor(deviceContext, oldTextColor); - SetBkMode(deviceContext, oldBackgroundMode); - } - } - - private static IntPtr CreateSplashFont(IntPtr deviceContext, int pointSize, int weight, string faceName) - { - var dpiY = Math.Max(1, GetDeviceCaps(deviceContext, LOGPIXELSY)); - var height = -MulDiv(pointSize, dpiY, 72); - return CreateFont( - height, - 0, - 0, - 0, - weight, - 0, - 0, - 0, - DEFAULT_CHARSET, - OUT_DEFAULT_PRECIS, - CLIP_DEFAULT_PRECIS, - ANTIALIASED_QUALITY, - DEFAULT_PITCH | FF_DONTCARE, - faceName); - } - - private static void LoadPrivateSplashFont(string fileName) - { - var path = Path.Combine(AppContext.BaseDirectory, "Assets", "Fonts", fileName); - if (File.Exists(path)) - { - AddFontResourceEx(path, FR_PRIVATE, IntPtr.Zero); - } - } - - private static float SmoothStep(float edge0, float edge1, float value) - { - var t = Math.Clamp((value - edge0) / Math.Max(edge1 - edge0, 0.0001f), 0.0f, 1.0f); - return t * t * (3.0f - 2.0f * t); - } - - private static uint LerpColor(byte r0, byte g0, byte b0, byte r1, byte g1, byte b1, float t, float intensity) - { - var r = (byte)Math.Clamp(MathF.Round((r0 + (r1 - r0) * t) * intensity), byte.MinValue, byte.MaxValue); - var g = (byte)Math.Clamp(MathF.Round((g0 + (g1 - g0) * t) * intensity), byte.MinValue, byte.MaxValue); - var b = (byte)Math.Clamp(MathF.Round((b0 + (b1 - b0) * t) * intensity), byte.MinValue, byte.MaxValue); - return (uint)(b | (g << 8) | (r << 16)); - } - - private static uint ColorRef(byte red, byte green, byte blue) - { - return (uint)(red | (green << 8) | (blue << 16)); - } - - private static IntPtr LoadIconFromPath(string? iconPath, int size) - { - if (string.IsNullOrWhiteSpace(iconPath) || !File.Exists(iconPath)) - { - return IntPtr.Zero; - } - - return LoadImage(IntPtr.Zero, iconPath, IMAGE_ICON, size, size, LR_LOADFROMFILE); - } - - private static IntPtr LoadSplashBitmapFromPath(string? bitmapPath, out int width, out int height) - { - width = 0; - height = 0; - if (string.IsNullOrWhiteSpace(bitmapPath) || !File.Exists(bitmapPath)) - { - return IntPtr.Zero; - } - - var bitmap = LoadImage(IntPtr.Zero, bitmapPath, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION); - if (bitmap == IntPtr.Zero) - { - return IntPtr.Zero; - } - - if (GetObject(bitmap, Marshal.SizeOf(), out var bitmapInfo) == 0) - { - DeleteObject(bitmap); - return IntPtr.Zero; - } - - width = Math.Max(1, bitmapInfo.bmWidth); - height = Math.Max(1, bitmapInfo.bmHeight); - return bitmap; - } - - [DllImport("kernel32.dll", EntryPoint = "GetModuleHandleW", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern IntPtr GetModuleHandle(string? moduleName); - - [DllImport("user32.dll", EntryPoint = "RegisterClassExW", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern ushort RegisterClassEx(ref WNDCLASSEX windowClass); - - [DllImport("user32.dll", EntryPoint = "CreateWindowExW", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern IntPtr CreateWindowEx( - uint extendedStyle, - IntPtr className, - IntPtr windowName, - uint style, - int x, - int y, - int width, - int height, - IntPtr parent, - IntPtr menu, - IntPtr instance, - IntPtr param); - - [DllImport("user32.dll")] - private static extern bool ShowWindow(IntPtr handle, int commandShow); - - [DllImport("user32.dll", EntryPoint = "SetWindowTextW", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern bool SetWindowText(IntPtr handle, string text); - - [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern IntPtr LoadImage(IntPtr instance, string imageName, uint type, int desiredWidth, int desiredHeight, uint load); - - [DllImport("user32.dll", SetLastError = true)] - private static extern bool DestroyIcon(IntPtr icon); - - [DllImport("user32.dll")] - private static extern IntPtr GetDC(IntPtr handle); - - [DllImport("user32.dll")] - private static extern int ReleaseDC(IntPtr handle, IntPtr deviceContext); - - [DllImport("user32.dll")] - private static extern IntPtr SendMessage(IntPtr handle, uint message, nuint wParam, IntPtr lParam); - - [DllImport("gdi32.dll", SetLastError = true)] - private static extern int StretchDIBits( - IntPtr deviceContext, - int destinationX, - int destinationY, - int destinationWidth, - int destinationHeight, - int sourceX, - int sourceY, - int sourceWidth, - int sourceHeight, - IntPtr bits, - ref BITMAPINFO bitmapInfo, - uint usage, - uint rasterOperation); - - [DllImport("gdi32.dll", SetLastError = true)] - private static extern IntPtr CreateCompatibleDC(IntPtr deviceContext); - - [DllImport("gdi32.dll", SetLastError = true)] - private static extern bool DeleteDC(IntPtr deviceContext); - - [DllImport("gdi32.dll", SetLastError = true)] - private static extern bool StretchBlt( - IntPtr destinationDeviceContext, - int destinationX, - int destinationY, - int destinationWidth, - int destinationHeight, - IntPtr sourceDeviceContext, - int sourceX, - int sourceY, - int sourceWidth, - int sourceHeight, - uint rasterOperation); - - [DllImport("gdi32.dll", EntryPoint = "GetObjectW", SetLastError = true)] - private static extern int GetObject(IntPtr gdiObject, int bufferSize, out BITMAP bitmap); - - [DllImport("gdi32.dll")] - private static extern bool GdiFlush(); - - [DllImport("gdi32.dll", EntryPoint = "AddFontResourceExW", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern int AddFontResourceEx(string name, uint flags, IntPtr reserved); - - [DllImport("gdi32.dll", EntryPoint = "CreateFontW", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern IntPtr CreateFont( - int height, - int width, - int escapement, - int orientation, - int weight, - uint italic, - uint underline, - uint strikeOut, - uint charSet, - uint outputPrecision, - uint clipPrecision, - uint quality, - uint pitchAndFamily, - string faceName); - - [DllImport("gdi32.dll", SetLastError = true)] - private static extern IntPtr SelectObject(IntPtr deviceContext, IntPtr gdiObject); - - [DllImport("gdi32.dll", SetLastError = true)] - private static extern bool DeleteObject(IntPtr gdiObject); - - [DllImport("gdi32.dll", SetLastError = true)] - private static extern int SetBkMode(IntPtr deviceContext, int mode); - - [DllImport("gdi32.dll", SetLastError = true)] - private static extern uint SetTextColor(IntPtr deviceContext, uint color); - - [DllImport("gdi32.dll", SetLastError = true)] - private static extern int GetDeviceCaps(IntPtr deviceContext, int index); - - [DllImport("kernel32.dll")] - private static extern int MulDiv(int number, int numerator, int denominator); - - [DllImport("user32.dll", EntryPoint = "DrawTextW", CharSet = CharSet.Unicode, SetLastError = true)] - private static extern int DrawText(IntPtr deviceContext, string text, int textLength, ref RECT rect, uint format); - - [DllImport("user32.dll", SetLastError = true)] - private static extern bool UpdateWindow(IntPtr handle); - - [DllImport("user32.dll", SetLastError = true)] - private static extern bool DestroyWindow(IntPtr handle); - - [DllImport("user32.dll")] - private static extern void PostQuitMessage(int exitCode); - - [DllImport("user32.dll", EntryPoint = "DefWindowProcW", SetLastError = true)] - private static extern IntPtr DefWindowProc(IntPtr handle, uint message, IntPtr wParam, IntPtr lParam); - - [DllImport("user32.dll", EntryPoint = "PeekMessageW", SetLastError = true)] - private static extern bool PeekMessage(out MSG message, IntPtr handle, uint filterMin, uint filterMax, uint removeMessage); - - [DllImport("user32.dll")] - private static extern bool TranslateMessage(ref MSG message); - - [DllImport("user32.dll", EntryPoint = "DispatchMessageW")] - private static extern IntPtr DispatchMessage(ref MSG message); - - [DllImport("user32.dll", EntryPoint = "LoadCursorW", SetLastError = true)] - private static extern IntPtr LoadCursor(IntPtr instance, int cursorName); - - [DllImport("user32.dll", SetLastError = true)] - private static extern bool GetClientRect(IntPtr handle, out RECT rect); - - [DllImport("user32.dll")] - private static extern IntPtr SetCapture(IntPtr handle); - - [DllImport("user32.dll")] - private static extern bool ReleaseCapture(); - - private static void SetKey(InputState input, IntPtr virtualKey, bool isDown) - { - switch (virtualKey.ToInt32()) - { - case VK_W: - input.SetKey(KeyCode.W, isDown); - break; - case VK_A: - input.SetKey(KeyCode.A, isDown); - break; - case VK_S: - input.SetKey(KeyCode.S, isDown); - break; - case VK_D: - input.SetKey(KeyCode.D, isDown); - break; - case VK_0: - input.SetKey(KeyCode.Digit0, isDown); - break; - case VK_1: - input.SetKey(KeyCode.Digit1, isDown); - break; - case VK_2: - input.SetKey(KeyCode.Digit2, isDown); - break; - case VK_3: - input.SetKey(KeyCode.Digit3, isDown); - break; - case VK_4: - input.SetKey(KeyCode.Digit4, isDown); - break; - case VK_5: - input.SetKey(KeyCode.Digit5, isDown); - break; - case VK_6: - input.SetKey(KeyCode.Digit6, isDown); - break; - case VK_7: - input.SetKey(KeyCode.Digit7, isDown); - break; - case VK_8: - input.SetKey(KeyCode.Digit8, isDown); - break; - case VK_9: - input.SetKey(KeyCode.Digit9, isDown); - break; - case VK_F1: - input.SetKey(KeyCode.RenderDebugCycle, isDown); - break; - case VK_F2: - input.SetKey(KeyCode.DebugUiToggle, isDown); - break; - case VK_BACK: - input.SetKey(KeyCode.Backspace, isDown); - break; - case VK_DELETE: - input.SetKey(KeyCode.Delete, isDown); - break; - case VK_RETURN: - input.SetKey(KeyCode.Enter, isDown); - break; - case VK_LEFT: - input.SetKey(KeyCode.LeftArrow, isDown); - break; - case VK_RIGHT: - input.SetKey(KeyCode.RightArrow, isDown); - break; - case VK_HOME: - input.SetKey(KeyCode.Home, isDown); - break; - case VK_END: - input.SetKey(KeyCode.End, isDown); - break; - case VK_SHIFT: - input.SetKey(KeyCode.Shift, isDown); - break; - } - } - - private static void AddTextInput(InputState input, UIntPtr wParam) - { - var value = (char)wParam.ToUInt32(); - if (!char.IsControl(value) || value is '\r' or '\n' or '\b') - { - input.AddTextInput(value); - } - } - - private static short GetSignedLowWord(IntPtr value) => unchecked((short)((long)value & 0xFFFF)); - - private static short GetSignedHighWord(IntPtr value) => unchecked((short)(((long)value >> 16) & 0xFFFF)); - - private static short GetSignedHighWord(UIntPtr value) => unchecked((short)(((long)value >> 16) & 0xFFFF)); - - private delegate IntPtr WndProc(IntPtr handle, uint message, IntPtr wParam, IntPtr lParam); - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - private struct WNDCLASSEX - { - public uint cbSize; - public uint style; - public WndProc lpfnWndProc; - public int cbClsExtra; - public int cbWndExtra; - public IntPtr hInstance; - public IntPtr hIcon; - public IntPtr hCursor; - public IntPtr hbrBackground; - public IntPtr lpszMenuName; - public IntPtr lpszClassName; - public IntPtr hIconSm; - } - - [StructLayout(LayoutKind.Sequential)] - private struct MSG - { - public IntPtr hwnd; - public uint message; - public UIntPtr wParam; - public IntPtr lParam; - public uint time; - public POINT pt; - } - - [StructLayout(LayoutKind.Sequential)] - private struct POINT - { - public int x; - public int y; - } - - [StructLayout(LayoutKind.Sequential)] - private struct RECT - { - public int left; - public int top; - public int right; - public int bottom; - } - - [StructLayout(LayoutKind.Sequential)] - private struct BITMAPINFO - { - public BITMAPINFOHEADER bmiHeader; - public uint bmiColors; - } - - [StructLayout(LayoutKind.Sequential)] - private struct BITMAP - { - public int bmType; - public int bmWidth; - public int bmHeight; - public int bmWidthBytes; - public ushort bmPlanes; - public ushort bmBitsPixel; - public IntPtr bmBits; - } - - [StructLayout(LayoutKind.Sequential)] - private struct BITMAPINFOHEADER - { - public uint biSize; - public int biWidth; - public int biHeight; - public ushort biPlanes; - public ushort biBitCount; - public uint biCompression; - public uint biSizeImage; - public int biXPelsPerMeter; - public int biYPelsPerMeter; - public uint biClrUsed; - public uint biClrImportant; - } -} diff --git a/src/Aquarium.Engine/Program.cs b/src/Aquarium.Engine/Program.cs deleted file mode 100644 index d88c1aa..0000000 --- a/src/Aquarium.Engine/Program.cs +++ /dev/null @@ -1,3 +0,0 @@ -using Aquarium.Engine; - -return AquariumHost.Run(args); diff --git a/src/Aquarium.Engine/Properties/AssemblyInfo.cs b/src/Aquarium.Engine/Properties/AssemblyInfo.cs deleted file mode 100644 index 71b3f58..0000000 --- a/src/Aquarium.Engine/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("Aquarium.Engine.Tests")] diff --git a/src/Aquarium.Engine/Render/D3D12CubeTexture.cs b/src/Aquarium.Engine/Render/D3D12CubeTexture.cs deleted file mode 100644 index df529b7..0000000 --- a/src/Aquarium.Engine/Render/D3D12CubeTexture.cs +++ /dev/null @@ -1,244 +0,0 @@ -using Vortice.Direct3D12; -using Vortice.DXGI; - -namespace Aquarium.Engine.Render; - -internal sealed unsafe class D3D12CubeTexture : IDisposable -{ - private const uint DdsMagic = 0x20534444; - private const uint DdsHeaderSize = 124; - private const uint DdsPixelFormatSize = 32; - private const uint DdsFourCcDx10 = 0x30315844; - private const int DxgiFormatR16G16B16A16Float = 10; - private const int D3D10ResourceDimensionTexture2D = 3; - private const int D3D11ResourceMiscTextureCube = 0x4; - private const int BytesPerPixel = 8; - private const int FaceCount = 6; - private const int DdsDx10PayloadOffset = 148; - - private D3D12CubeTexture(ID3D12Resource resource, int size, int mipCount, string name) - { - Resource = resource; - Size = size; - MipCount = mipCount; - Resource.Name = name; - } - - public ID3D12Resource Resource { get; } - - public int Size { get; } - - public int MipCount { get; } - - public ResourceStates State { get; private set; } = ResourceStates.CopyDest; - - public static D3D12CubeTexture LoadRgba16FloatDds( - ID3D12Device device, - ID3D12GraphicsCommandList commandList, - string path, - string name, - out ID3D12Resource uploadResource) - { - var bytes = File.ReadAllBytes(path); - var dds = ParseDds(bytes, path); - var texture = device.CreateCommittedResource( - HeapType.Default, - ResourceDescription.Texture2D( - Format.R16G16B16A16_Float, - (uint)dds.Width, - (uint)dds.Height, - FaceCount, - (ushort)dds.MipCount, - 1, - 0, - ResourceFlags.None), - ResourceStates.CopyDest, - null); - var cubeTexture = new D3D12CubeTexture(texture, dds.Width, dds.MipCount, name); - - uploadResource = CreateUploadResource(device, dds, bytes); - CopySubresources(commandList, cubeTexture.Resource, uploadResource, dds); - cubeTexture.Transition(commandList, ResourceStates.PixelShaderResource); - return cubeTexture; - } - - public void CreateShaderResourceView(ID3D12Device device, D3D12DescriptorSlot descriptor) - { - device.CreateShaderResourceView( - Resource, - new ShaderResourceViewDescription - { - Format = Format.R16G16B16A16_Float, - ViewDimension = ShaderResourceViewDimension.TextureCube, - Shader4ComponentMapping = ShaderComponentMapping.Default, - TextureCube = new TextureCubeShaderResourceView - { - MostDetailedMip = 0, - MipLevels = (uint)MipCount, - ResourceMinLODClamp = 0.0f, - }, - }, - descriptor.Cpu); - } - - public void Dispose() - { - Resource.Dispose(); - } - - private void Transition(ID3D12GraphicsCommandList commandList, ResourceStates nextState) - { - if (State == nextState) - { - return; - } - - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(Resource, State, nextState)); - State = nextState; - } - - private static DdsLayout ParseDds(ReadOnlySpan bytes, string path) - { - if (bytes.Length < DdsDx10PayloadOffset) - { - throw new InvalidDataException($"DDS file '{path}' is too small."); - } - - if (ReadUInt32(bytes, 0) != DdsMagic || ReadUInt32(bytes, 4) != DdsHeaderSize) - { - throw new InvalidDataException($"DDS file '{path}' is not a supported DDS texture."); - } - - var height = checked((int)ReadUInt32(bytes, 12)); - var width = checked((int)ReadUInt32(bytes, 16)); - var mipCount = checked((int)ReadUInt32(bytes, 28)); - var pixelFormatSize = ReadUInt32(bytes, 76); - var fourCc = ReadUInt32(bytes, 84); - var dxgiFormat = checked((int)ReadUInt32(bytes, 128)); - var resourceDimension = checked((int)ReadUInt32(bytes, 132)); - var miscFlags = checked((int)ReadUInt32(bytes, 136)); - var arraySize = checked((int)ReadUInt32(bytes, 140)); - - if (width <= 0 || height != width || mipCount <= 0) - { - throw new InvalidDataException($"DDS file '{path}' must be a square cubemap with mips."); - } - - if (pixelFormatSize != DdsPixelFormatSize - || fourCc != DdsFourCcDx10 - || dxgiFormat != DxgiFormatR16G16B16A16Float - || resourceDimension != D3D10ResourceDimensionTexture2D - || (miscFlags & D3D11ResourceMiscTextureCube) == 0 - || arraySize != 1) - { - throw new InvalidDataException($"DDS file '{path}' must be a DX10 R16G16B16A16_FLOAT cubemap."); - } - - var subresources = new DdsSubresource[FaceCount * mipCount]; - var sourceOffset = DdsDx10PayloadOffset; - for (var face = 0; face < FaceCount; face++) - { - for (var mip = 0; mip < mipCount; mip++) - { - var mipWidth = Math.Max(1, width >> mip); - var mipHeight = Math.Max(1, height >> mip); - var rowBytes = mipWidth * BytesPerPixel; - var dataBytes = rowBytes * mipHeight; - if (sourceOffset + dataBytes > bytes.Length) - { - throw new InvalidDataException($"DDS file '{path}' ended before face {face}, mip {mip}."); - } - - subresources[(face * mipCount) + mip] = new DdsSubresource(sourceOffset, mipWidth, mipHeight, rowBytes); - sourceOffset += dataBytes; - } - } - - if (sourceOffset != bytes.Length) - { - throw new InvalidDataException($"DDS file '{path}' has {bytes.Length - sourceOffset} unexpected trailing bytes."); - } - - return new DdsLayout(width, height, mipCount, subresources); - } - - private static ID3D12Resource CreateUploadResource(ID3D12Device device, DdsLayout dds, ReadOnlySpan source) - { - var uploadBytes = 0L; - foreach (var subresource in dds.Subresources) - { - uploadBytes = Align(uploadBytes, D3D12.TextureDataPlacementAlignment); - subresource.UploadOffset = uploadBytes; - subresource.UploadRowPitch = checked((int)Align(subresource.RowBytes, D3D12.TextureDataPitchAlignment)); - uploadBytes += (long)subresource.UploadRowPitch * subresource.Height; - } - - var upload = device.CreateCommittedResource( - HeapType.Upload, - ResourceDescription.Buffer((ulong)uploadBytes), - ResourceStates.GenericRead, - null); - upload.Name = "Aquarium D3D12 Studio PMREM Upload"; - - var mapped = (byte*)upload.Map(0); - try - { - foreach (var subresource in dds.Subresources) - { - for (var row = 0; row < subresource.Height; row++) - { - var sourceStart = subresource.SourceOffset + (row * subresource.RowBytes); - var destinationStart = subresource.UploadOffset + ((long)row * subresource.UploadRowPitch); - source.Slice(sourceStart, subresource.RowBytes).CopyTo(new Span(mapped + destinationStart, subresource.RowBytes)); - } - } - } - finally - { - upload.Unmap(0, null); - } - - return upload; - } - - private static void CopySubresources(ID3D12GraphicsCommandList commandList, ID3D12Resource texture, ID3D12Resource upload, DdsLayout dds) - { - for (var subresourceIndex = 0; subresourceIndex < dds.Subresources.Length; subresourceIndex++) - { - var subresource = dds.Subresources[subresourceIndex]; - var source = new TextureCopyLocation( - upload, - new PlacedSubresourceFootPrint - { - Offset = (ulong)subresource.UploadOffset, - Footprint = new SubresourceFootPrint( - Format.R16G16B16A16_Float, - (uint)subresource.Width, - (uint)subresource.Height, - 1, - (uint)subresource.UploadRowPitch), - }); - var destination = new TextureCopyLocation(texture, (uint)subresourceIndex); - commandList.CopyTextureRegion(destination, 0, 0, 0, source, null); - } - } - - private static uint ReadUInt32(ReadOnlySpan bytes, int offset) - { - return BitConverter.ToUInt32(bytes.Slice(offset, sizeof(uint))); - } - - private static long Align(long value, long alignment) - { - return (value + alignment - 1) & ~(alignment - 1); - } - - private sealed record DdsLayout(int Width, int Height, int MipCount, DdsSubresource[] Subresources); - - private sealed record DdsSubresource(int SourceOffset, int Width, int Height, int RowBytes) - { - public long UploadOffset { get; set; } - - public int UploadRowPitch { get; set; } - } -} diff --git a/src/Aquarium.Engine/Render/D3D12DescriptorArena.cs b/src/Aquarium.Engine/Render/D3D12DescriptorArena.cs deleted file mode 100644 index e658e31..0000000 --- a/src/Aquarium.Engine/Render/D3D12DescriptorArena.cs +++ /dev/null @@ -1,87 +0,0 @@ -using Vortice.Direct3D12; - -namespace Aquarium.Engine.Render; - -internal sealed class D3D12DescriptorArena : IDisposable -{ - private readonly int descriptorSize; - private int used; - - public D3D12DescriptorArena(ID3D12Device device, DescriptorHeapType type, int capacity, DescriptorHeapFlags flags, string name) - { - Type = type; - Capacity = capacity; - Name = name; - Heap = device.CreateDescriptorHeap(new DescriptorHeapDescription(type, (uint)capacity, flags)); - Heap.Name = name; - descriptorSize = (int)device.GetDescriptorHandleIncrementSize(type); - } - - public ID3D12DescriptorHeap Heap { get; } - - public DescriptorHeapType Type { get; } - - public int Capacity { get; } - - public int Used => used; - - public int Available => Capacity - used; - - public string Name { get; } - - public D3D12DescriptorSlot Allocate() - { - if (used >= Capacity) - { - throw new InvalidOperationException($"D3D12 descriptor arena '{Name}' exhausted ({Capacity} {Type} descriptors)."); - } - - var index = used++; - return new D3D12DescriptorSlot( - Heap.GetCPUDescriptorHandleForHeapStart() + (index * descriptorSize), - Heap.GetGPUDescriptorHandleForHeapStart() + (index * descriptorSize)); - } - - public D3D12DescriptorSlot AllocateRange(int count) - { - if (count <= 0) - { - throw new ArgumentOutOfRangeException(nameof(count), count, "Descriptor range count must be positive."); - } - - if (used + count > Capacity) - { - throw new InvalidOperationException($"D3D12 descriptor arena '{Name}' exhausted ({Capacity} {Type} descriptors; requested range {count})."); - } - - var index = used; - used += count; - return new D3D12DescriptorSlot( - Heap.GetCPUDescriptorHandleForHeapStart() + (index * descriptorSize), - Heap.GetGPUDescriptorHandleForHeapStart() + (index * descriptorSize)); - } - - public D3D12DescriptorSlot Offset(D3D12DescriptorSlot start, int offset) - { - return new D3D12DescriptorSlot( - start.Cpu + (offset * descriptorSize), - start.Gpu + (offset * descriptorSize)); - } - - public void Reset() - { - used = 0; - } - - public string Describe() - { - return $"{Name}: {used}/{Capacity} {Type} descriptors"; - } - - public void Dispose() - { - Heap.Dispose(); - } -} - -internal readonly record struct D3D12DescriptorSlot(CpuDescriptorHandle Cpu, GpuDescriptorHandle Gpu); diff --git a/src/Aquarium.Engine/Render/D3D12ExternalSensorTexture.cs b/src/Aquarium.Engine/Render/D3D12ExternalSensorTexture.cs deleted file mode 100644 index 775a48a..0000000 --- a/src/Aquarium.Engine/Render/D3D12ExternalSensorTexture.cs +++ /dev/null @@ -1,142 +0,0 @@ -using Aquarium.Engine.Render; -using SharpGen.Runtime; -using Vortice.Direct3D12; -using Vortice.DXGI; - -namespace Aquarium.Engine.Render; - -internal sealed class D3D12ExternalSensorTexture : IDisposable -{ - private D3D12ExternalSensorTexture( - string key, - IntPtr sharedHandle, - ID3D12Resource resource, - int width, - int height, - Format format, - long timestampNs) - { - Key = key; - SharedHandle = sharedHandle; - Resource = resource; - Width = width; - Height = height; - Format = format; - TimestampNs = timestampNs; - } - - public string Key { get; } - - public IntPtr SharedHandle { get; } - - public ID3D12Resource Resource { get; } - - public int Width { get; } - - public int Height { get; } - - public Format Format { get; } - - public long TimestampNs { get; private set; } - - public bool Matches(AquariumExternalGpuTexture texture) - { - return SharedHandle == texture.SharedHandle - && string.Equals(Key, CacheKey(texture), StringComparison.Ordinal) - && Width == texture.Width - && Height == texture.Height - && Format == ToDxgiFormat(texture.PixelFormat); - } - - public void UpdateTimestamp(long timestampNs) - { - TimestampNs = timestampNs; - } - - public void CreateShaderResourceView(ID3D12Device device, D3D12DescriptorSlot descriptor) - { - device.CreateShaderResourceView( - Resource, - new ShaderResourceViewDescription - { - Format = Format, - ViewDimension = ShaderResourceViewDimension.Texture2D, - Shader4ComponentMapping = ShaderComponentMapping.Default, - Texture2D = new Texture2DShaderResourceView { MipLevels = 1 }, - }, - descriptor.Cpu); - } - - public static bool TryOpen(ID3D12Device device, AquariumExternalGpuTexture texture, out D3D12ExternalSensorTexture externalTexture) - { - externalTexture = null!; - if ((texture.SharedHandle == IntPtr.Zero && string.IsNullOrWhiteSpace(texture.SharedHandleName)) - || texture.Width <= 0 - || texture.Height <= 0) - { - return false; - } - - var format = ToDxgiFormat(texture.PixelFormat); - if (format == Format.Unknown) - { - return false; - } - - try - { - var sharedHandle = texture.SharedHandle; - if (sharedHandle == IntPtr.Zero) - { - sharedHandle = device.OpenSharedHandleByName(texture.SharedHandleName); - } - - var resource = device.OpenSharedHandle(sharedHandle); - resource.Name = $"Aquarium external sensor texture {texture.Handle.Name}"; - externalTexture = new D3D12ExternalSensorTexture( - CacheKey(texture), - sharedHandle, - resource, - texture.Width, - texture.Height, - format, - texture.TimestampNs); - return true; - } - catch (SharpGenException) - { - return false; - } - catch (InvalidOperationException) - { - return false; - } - } - - public static string CacheKey(AquariumExternalGpuTexture texture) - { - return texture.SharedHandle != IntPtr.Zero - ? $"handle:{texture.SharedHandle.ToInt64():x}" - : $"name:{texture.SharedHandleName}"; - } - - public static Format ToDxgiFormat(AquariumGpuSensorPixelFormat format) - { - return format switch - { - AquariumGpuSensorPixelFormat.Bgra8Unorm => Format.B8G8R8A8_UNorm, - AquariumGpuSensorPixelFormat.Rgba8Unorm => Format.R8G8B8A8_UNorm, - AquariumGpuSensorPixelFormat.R8Unorm => Format.R8_UNorm, - AquariumGpuSensorPixelFormat.R16Unorm => Format.R16_UNorm, - AquariumGpuSensorPixelFormat.R16Float => Format.R16_Float, - AquariumGpuSensorPixelFormat.Rg8Unorm => Format.R8G8_UNorm, - AquariumGpuSensorPixelFormat.LeapPackedMap => Format.R8G8B8A8_UNorm, - _ => Format.Unknown, - }; - } - - public void Dispose() - { - Resource.Dispose(); - } -} diff --git a/src/Aquarium.Engine/Render/D3D12RenderTarget.cs b/src/Aquarium.Engine/Render/D3D12RenderTarget.cs deleted file mode 100644 index 3e7e1c5..0000000 --- a/src/Aquarium.Engine/Render/D3D12RenderTarget.cs +++ /dev/null @@ -1,119 +0,0 @@ -using Vortice.Direct3D12; -using Vortice.DXGI; -using Vortice.Mathematics; - -namespace Aquarium.Engine.Render; - -internal sealed class D3D12RenderTarget : IDisposable -{ - public D3D12RenderTarget( - ID3D12Device device, - int width, - int height, - Format format, - D3D12DescriptorSlot renderTargetView, - D3D12DescriptorSlot? shaderResourceView, - D3D12DescriptorSlot? unorderedAccessView, - bool allowUnorderedAccess, - Color4 clearColor, - string name) - { - Width = width; - Height = height; - Format = format; - RenderTargetView = renderTargetView; - ShaderResourceView = shaderResourceView; - UnorderedAccessView = unorderedAccessView; - var resourceFlags = ResourceFlags.AllowRenderTarget; - if (allowUnorderedAccess || unorderedAccessView.HasValue) - { - resourceFlags |= ResourceFlags.AllowUnorderedAccess; - } - - var optimizedClear = new ClearValue(format, in clearColor); - Resource = device.CreateCommittedResource( - HeapType.Default, - ResourceDescription.Texture2D( - format, - (uint)width, - (uint)height, - 1, - 1, - 1, - 0, - resourceFlags), - ResourceStates.PixelShaderResource, - optimizedClear); - Resource.Name = name; - device.CreateRenderTargetView(Resource, null, renderTargetView.Cpu); - if (shaderResourceView.HasValue) - { - CreateShaderResourceView(device, shaderResourceView.Value); - } - - if (unorderedAccessView.HasValue) - { - CreateUnorderedAccessView(device, unorderedAccessView.Value); - } - } - - public ID3D12Resource Resource { get; } - - public int Width { get; } - - public int Height { get; } - - public Format Format { get; } - - public D3D12DescriptorSlot RenderTargetView { get; } - - public D3D12DescriptorSlot? ShaderResourceView { get; } - - public D3D12DescriptorSlot? UnorderedAccessView { get; } - - public ResourceStates State { get; private set; } = ResourceStates.PixelShaderResource; - - public void CreateUnorderedAccessView(ID3D12Device device, D3D12DescriptorSlot unorderedAccessView) - { - device.CreateUnorderedAccessView( - Resource, - null, - new UnorderedAccessViewDescription - { - Format = Format, - ViewDimension = UnorderedAccessViewDimension.Texture2D, - Texture2D = new Texture2DUnorderedAccessView(), - }, - unorderedAccessView.Cpu); - } - - public void CreateShaderResourceView(ID3D12Device device, D3D12DescriptorSlot shaderResourceView) - { - device.CreateShaderResourceView( - Resource, - new ShaderResourceViewDescription - { - Format = Format, - ViewDimension = ShaderResourceViewDimension.Texture2D, - Shader4ComponentMapping = ShaderComponentMapping.Default, - Texture2D = new Texture2DShaderResourceView { MipLevels = 1 }, - }, - shaderResourceView.Cpu); - } - - public void Transition(ID3D12GraphicsCommandList commandList, ResourceStates nextState) - { - if (State == nextState) - { - return; - } - - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(Resource, State, nextState)); - State = nextState; - } - - public void Dispose() - { - Resource.Dispose(); - } -} diff --git a/src/Aquarium.Engine/Render/D3D12Renderer.cs b/src/Aquarium.Engine/Render/D3D12Renderer.cs deleted file mode 100644 index 2dfde01..0000000 --- a/src/Aquarium.Engine/Render/D3D12Renderer.cs +++ /dev/null @@ -1,3107 +0,0 @@ -using Aquarium.Engine.Audio; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Input; -using Aquarium.Engine.Render.Features; -using Aquarium.Engine.Render.Graph; -using SharpGen.Runtime; -using Aquarium.Engine.Render.Ui; -using Aquarium.Engine.Ui; -using Vortice; -using Vortice.D3DCompiler; -using Vortice.Direct3D; -using Vortice.Direct3D11on12; -using Vortice.Direct3D12; -using Vortice.DXGI; -using Vortice.Mathematics; -using System.Diagnostics; -using System.Numerics; -using System.Runtime.InteropServices; -using ID3D11Device = Vortice.Direct3D11.ID3D11Device; -using ID3D11DeviceContext = Vortice.Direct3D11.ID3D11DeviceContext; -using ID3D11Resource = Vortice.Direct3D11.ID3D11Resource; -using D3D11DeviceCreationFlags = Vortice.Direct3D11.DeviceCreationFlags; -using D3D11BindFlags = Vortice.Direct3D11.BindFlags; - -namespace Aquarium.Engine.Render; - -public sealed class D3D12Renderer : IAquariumRenderer -{ - private const int BackBufferCount = 2; - private const int HeightFieldTextureSize = 128; - private const Format HeightFieldFormat = Format.R16_Float; - private const Format SceneDepthFormat = Format.D32_Float; - private const int MaxSdfLightCount = 64; - private const int MaxSdfObjectCount = 64; - private const int MaxGpuSensorCameraCount = 32; - private const int MaxGpuSensorTextureCount = 8; - private const int MaxAcousticConstraintCount = 128; - private const int GpuSensorSamplesPerTexture = 131_072; - private const int MaxTemporalGaussianCount = 1_048_576; - private const int MaxVisibleFractalSplatCount = 524_288; - private const float SurfaceTransparentMinZ = -1.85f; - private const float SurfaceTransparentMaxZ = 0.45f; - private const int BloomLevelCount = 3; - private const Format SceneHdrFormat = Format.R16G16B16A16_Float; - private const string StudioPmremRelativePath = "Assets/Textures/studio3_pmrem.dds"; - private const string StudioIrradianceRelativePath = "Assets/Textures/studio3_irradiance.dds"; - private const int RootFrameConstants = 0; - private const int RootSourceTexture = 1; - private const int RootHeightFieldBrushes = 2; - private const int RootSdfLights = 3; - private const int RootBloom = 4; - private const int RootCurrentSceneMetadata = 5; - private const int RootCurrentSceneControl = 6; - private const int RootHistory = 7; - private const int RootHistoryMetadata = 8; - private const int RootHistoryControl = 9; - private const int RootStudioPmrem = 10; - private const int RootStudioIrradiance = 11; - private const int RootSdfObjects = 12; - private const int RootTemporalGaussians = 13; - private const int RootCurrentReservoirGuide = 14; - private const int RootHistoryReservoirGuide = 15; - private const int RootFractalSplatSrv = 16; - private const int RootFractalSdfReservoirSrv = 17; - private const int RootFractalPbrReservoirSrv = 18; - private const int RootFractalRadiosityReservoirSrv = 19; - private const int RootFusionFrameConstants = 0; - private const int RootFusionSeeds = 1; - private const int RootFusionSensorCameras = 2; - private const int RootFusionSensorTextures = 3; - private const int RootFusionAcousticConstraints = 4; - private const int RootFusionOutput = 5; - private const int RootFusionNativePoints = 6; - private const int RootFractalConstants = 0; - private const int RootFractalSplats = 1; - private const int RootFractalSdfReservoirs = 2; - private const int RootFractalPbrReservoirs = 3; - private const int RootFractalRadiosityReservoirs = 4; - private const int RootFractalFlameStates = 5; - private const int RootFractalProgramTransforms = 6; - private static readonly DebugUi.DebugUiOption[] RenderDebugOptions = - [ - new(0, "Final"), - new(1, "Raw Scene"), - new(2, "History"), - new(3, "History Age"), - new(4, "History Weight"), - new(5, "Coverage/Steps"), - new(6, "Lane Identity"), - new(7, "Bloom"), - new(8, "Exposed Luminance"), - new(9, "SdfObject Identity"), - new(10, "SdfObject Steps"), - new(11, "Client Fractal Domains"), - new(12, "Reservoir/TAA Guide"), - ]; - private static readonly DebugUi.DebugUiOption[] SynthPresetOptions = AquaSynth.Dsl.BuiltInScripts.ReferenceScripts() - .Select((preset, index) => new DebugUi.DebugUiOption(index, $"{preset.Family}/{preset.Name}")) - .ToArray(); - private static readonly (string Family, string Name, string Script)[] SynthPresets = AquaSynth.Dsl.BuiltInScripts.ReferenceScripts().ToArray(); - - private readonly IDXGIFactory4 factory; - private readonly ID3D12Device device; - private readonly ID3D12CommandQueue commandQueue; - private readonly ID3D11Device overlayDevice; - private readonly ID3D11DeviceContext overlayContext; - private readonly ID3D11On12Device overlayOn12Device; - private readonly IDXGISwapChain3 swapChain; - private readonly D3D12ResourceRegistry resourceRegistry = new(); - private D3D12DescriptorArena renderTargetViewArena; - private D3D12DescriptorArena depthStencilViewArena; - private D3D12DescriptorArena staticShaderDescriptorArena; - private readonly FrameResources[] frames = new FrameResources[BackBufferCount]; - private readonly ID3D12GraphicsCommandList commandList; - private readonly ID3D12RootSignature fullscreenRootSignature; - private readonly ID3D12RootSignature localCastFusionRootSignature; - private readonly ID3D12RootSignature fractalReservoirRootSignature; - private ID3D12PipelineState? heightFieldBasePipelineState; - private ID3D12PipelineState? heightFieldBrushPipelineState; - private ID3D12PipelineState? scenePipelineState; - private ID3D12PipelineState? temporalGaussianPipelineState; - private ID3D12PipelineState? localCastFusionPipelineState; - private ID3D12PipelineState? fractalSurfaceSplatRenderPipelineState; - private ID3D12PipelineState? fractalTransparentSplatRenderPipelineState; - private ID3D12PipelineState? fractalSplatPipelineState; - private ID3D12PipelineState? fractalSdfReservoirPipelineState; - private ID3D12PipelineState? fractalPbrReservoirPipelineState; - private ID3D12PipelineState? fractalRadiosityReservoirPipelineState; - private ID3D12PipelineState?[] sdfProxyPipelineStates = []; - private ID3D12PipelineState? bloomPrefilterPipelineState; - private ID3D12PipelineState? bloomDownsamplePipelineState; - private ID3D12PipelineState? bloomBlurHorizontalPipelineState; - private ID3D12PipelineState? bloomBlurVerticalPipelineState; - private ID3D12PipelineState? resolvePipelineState; - private readonly ID3D12Fence fence; - private readonly AutoResetEvent fenceEvent = new(false); - private DebugUi debugUi; - private IReadOnlyList clientUiPanels = []; - private AquariumUiDocument? currentClientUi; - private int activeDebugTab; - private string[] debugTabTitles = ["Aquarium", "Terminal", "Synth"]; - private string terminalInput = "help"; - private readonly List terminalLines = ["Aquarium terminal ready. Type help."]; - private IReadOnlyList clientCommands = []; - private string synthPlaygroundScript = SynthPresets[0].Script; - private int synthPlaygroundPreset; - private int synthPlaygroundPlayRevision; - private float synthPlaygroundGain = 0.45f; - private AquariumSynthPatchStatus synthPlaygroundStatus = new("aquarium-playground", AquariumSynthPatchCompileState.Idle, "idle", 0, 0.0); - private ID3D11Resource[] overlayWrappedBackBuffers = []; - private DirectWriteOverlay[] overlays = []; - private D3D12RenderTarget heightFieldRenderTarget; - private D3D12RenderTarget sceneRenderTarget; - private D3D12RenderTarget sceneMetadataRenderTarget; - private D3D12RenderTarget sceneControlRenderTarget; - private D3D12RenderTarget sceneReservoirGuideRenderTarget; - private readonly Dictionary graphRenderTargets = new(StringComparer.Ordinal); - private D3D12TrackedResource sceneDepthTarget; - private D3D12DescriptorSlot sceneDepthStencilView; - private readonly D3D12RenderTarget[] historyRenderTargets = new D3D12RenderTarget[2]; - private readonly D3D12RenderTarget[] historyMetadataRenderTargets = new D3D12RenderTarget[2]; - private readonly D3D12RenderTarget[] historyControlRenderTargets = new D3D12RenderTarget[2]; - private readonly D3D12RenderTarget[] historyReservoirGuideRenderTargets = new D3D12RenderTarget[2]; - private readonly D3D12RenderTarget[] bloomRenderTargets = new D3D12RenderTarget[BloomLevelCount]; - private readonly D3D12RenderTarget[] bloomScratchTargets = new D3D12RenderTarget[BloomLevelCount]; - private readonly D3D12StructuredBuffer sdfLightBuffer; - private readonly D3D12StructuredBuffer sdfObjectBuffer; - private readonly D3D12StructuredBuffer gpuSensorCameraBuffer; - private readonly D3D12StructuredBuffer acousticConstraintBuffer; - private readonly D3D12StructuredBuffer gpuFusionSeedBuffer; - private readonly D3D12StructuredBuffer gpuFusionPointBuffer; - private readonly D3D12StructuredBuffer temporalGaussianBuffer; - private D3D12StructuredBuffer? fractalSplatBuffer; - private D3D12StructuredBuffer? fractalSdfReservoirBuffer; - private D3D12StructuredBuffer? fractalPbrReservoirBuffer; - private D3D12StructuredBuffer? fractalRadiosityReservoirBuffer; - private D3D12StructuredBuffer? fractalFlameStateBuffer; - private D3D12StructuredBuffer? fractalProgramTransformBuffer; - private readonly Dictionary externalSensorTextures = new(StringComparer.Ordinal); - private readonly D3D12CubeTexture studioPmremTexture; - private readonly D3D12CubeTexture studioIrradianceTexture; - private readonly AquariumSdfLight[] sdfLights = new AquariumSdfLight[MaxSdfLightCount]; - private readonly AquariumSdfObject[] sdfObjects = new AquariumSdfObject[MaxSdfObjectCount]; - private readonly D3D12GpuSensorCameraPacket[] gpuSensorCameras = new D3D12GpuSensorCameraPacket[MaxGpuSensorCameraCount]; - private readonly D3D12AcousticConstraintPacket[] acousticConstraints = new D3D12AcousticConstraintPacket[MaxAcousticConstraintCount]; - private readonly D3D12GpuFusionSeedPacket[] gpuFusionSeeds = new D3D12GpuFusionSeedPacket[MaxTemporalGaussianCount]; - private readonly D3D12TemporalGaussianPacket[] temporalGaussians = new D3D12TemporalGaussianPacket[MaxTemporalGaussianCount]; - private AquariumGpuFusionPointBuffer gpuFusionPointSource; - private int temporalGaussianCount; - private int gpuSensorCameraCount; - private int gpuSensorTextureCount; - private int acousticConstraintCount; - private int gpuFusionSeedCount; - private int gpuFusionPointCount; - private int visibleFractalSplatCount; - private AquariumPackedFractalIfsTransform[] activeFractalProgramTransforms = []; - private bool temporalGaussiansGpuGenerated; - private AquariumFractalReservoirField activeFractalReservoirField = AquariumFractalReservoirField.Empty; - private Viewport viewport; - private RawRect scissorRect; - private int width; - private int height; - private ulong fenceValue; - private int temporalFrameIndex; - private int frameIndex; - private Vector3 previousCameraPosition; - private Vector3 previousCameraTarget; - private Vector2 previousViewCenter; - private Vector2 previousCursorWorld; - private Vector2 previousJitterPixels; - private float previousViewRadius = 0.001f; - private float previousTimeSeconds; - private D3D12HeightFieldBrushConstants heightFieldBrushConstants; - private GraphicsSettings settings = GraphicsSettings.Default; - private double accumulatedFrameCpuMilliseconds; - private double accumulatedRecordCpuMilliseconds; - private double accumulatedOverlayCpuMilliseconds; - private int accumulatedTimingFrames; - private readonly string shaderSourceRoot; - private readonly D3D12ShaderPaths shaderPaths; - private readonly CompiledRenderGraph renderGraph; - private readonly Stopwatch shaderReloadClock = Stopwatch.StartNew(); - private readonly Dictionary shaderWriteTimesUtc = new(StringComparer.OrdinalIgnoreCase); - private Task? pipelineBuildTask; - private TimeSpan lastShaderReloadCheck; - private bool shaderReloadFailureReported; - private bool pipelineBuildInProgressReported; - private bool initialPipelineReadyReported; - private bool hasPresentedReadyFrame; - private static readonly TimeSpan ShaderReloadPollInterval = TimeSpan.FromMilliseconds(250); - private static readonly TimeSpan ShaderReloadWriteSettleTime = TimeSpan.FromMilliseconds(300); - - public D3D12Renderer( - IntPtr windowHandle, - int width, - int height, - string? shaderPath = null, - AquariumRenderPlan? renderPlan = null, - GraphicsSettings? graphicsSettings = null, - Action? startupProgress = null) - { - ApplyGraphicsSettings(graphicsSettings ?? GraphicsSettings.Default); - this.width = width; - this.height = height; - var activeRenderPlan = renderPlan ?? new AquariumRenderPlan(); - renderGraph = D3D12RenderGraphCompiler.Compile(activeRenderPlan); - shaderSourceRoot = ResolveShaderSourceRoot(shaderPath, activeRenderPlan.Shaders); - shaderPaths = D3D12ShaderPaths.FromManifest(shaderSourceRoot, activeRenderPlan.Shaders); - sdfProxyPipelineStates = new ID3D12PipelineState?[shaderPaths.SdfShaders.Count]; - ReportStartupProgress(startupProgress, "Creating D3D12 device and swapchain"); - - factory = DXGI.CreateDXGIFactory2(false); - device = D3D12.D3D12CreateDevice(IntPtr.Zero, FeatureLevel.Level_11_0); - device.Name = "Aquarium D3D12 Device"; - commandQueue = device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct)); - commandQueue.Name = "Aquarium D3D12 Direct Queue"; - CreateOverlayDevice(out overlayDevice, out overlayContext, out overlayOn12Device); - - var swapChainDescription = new SwapChainDescription1 - { - BufferCount = BackBufferCount, - Width = (uint)width, - Height = (uint)height, - Format = Format.B8G8R8A8_UNorm, - BufferUsage = Usage.RenderTargetOutput, - SwapEffect = SwapEffect.FlipDiscard, - SampleDescription = new SampleDescription(1, 0), - }; - - using var swapChain1 = factory.CreateSwapChainForHwnd(commandQueue, windowHandle, swapChainDescription); - swapChain = swapChain1.QueryInterface(); - frameIndex = (int)swapChain.CurrentBackBufferIndex; - - renderTargetViewArena = CreateRenderTargetViewArena(); - depthStencilViewArena = CreateDepthStencilViewArena(); - staticShaderDescriptorArena = CreateStaticShaderDescriptorArena(); - for (var index = 0; index < frames.Length; index++) - { - frames[index] = CreateFrameResources(index); - } - - CreateRenderTargetViews(); - CreateBackBufferOverlays(); - debugUi = CreateDebugUi([]); - heightFieldRenderTarget = CreateHeightFieldRenderTarget(); - sceneRenderTarget = CreateSceneRenderTarget(); - sceneMetadataRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-metadata-target", "Aquarium D3D12 Scene Metadata Target"); - sceneControlRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-control-target", "Aquarium D3D12 Scene Control Target"); - sceneReservoirGuideRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-reservoir-guide-target", "Aquarium D3D12 Scene Reservoir Guide Target"); - sceneDepthStencilView = depthStencilViewArena.Allocate(); - sceneDepthTarget = CreateSceneDepthTarget(sceneDepthStencilView); - CreateHistoryRenderTargets(); - CreateBloomRenderTargets(); - CreateGraphRenderTargets(); - sdfLightBuffer = new D3D12StructuredBuffer(device, MaxSdfLightCount, Marshal.SizeOf(), "Aquarium D3D12 Sdf Light Buffer"); - sdfObjectBuffer = new D3D12StructuredBuffer(device, MaxSdfObjectCount, Marshal.SizeOf(), "Aquarium D3D12 Sdf Object Buffer"); - gpuSensorCameraBuffer = new D3D12StructuredBuffer(device, MaxGpuSensorCameraCount, Marshal.SizeOf(), "Aquarium D3D12 GPU Sensor Camera Buffer"); - acousticConstraintBuffer = new D3D12StructuredBuffer(device, MaxAcousticConstraintCount, Marshal.SizeOf(), "Aquarium D3D12 Acoustic Constraint Buffer"); - gpuFusionSeedBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 LocalCast GPU Fusion Seed Buffer"); - gpuFusionPointBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 LocalCast GPU Fusion Native Point Buffer"); - temporalGaussianBuffer = new D3D12StructuredBuffer(device, MaxTemporalGaussianCount, Marshal.SizeOf(), "Aquarium D3D12 Temporal Gaussian Buffer", allowUnorderedAccess: true); - resourceRegistry.Add("sdf-light-buffer", sdfLightBuffer); - resourceRegistry.Add("sdf-object-buffer", sdfObjectBuffer); - resourceRegistry.Add("gpu-sensor-camera-buffer", gpuSensorCameraBuffer); - resourceRegistry.Add("acoustic-constraint-buffer", acousticConstraintBuffer); - resourceRegistry.Add("gpu-fusion-seed-buffer", gpuFusionSeedBuffer); - resourceRegistry.Add("gpu-fusion-point-buffer", gpuFusionPointBuffer); - resourceRegistry.Add("temporal-gaussian-buffer", temporalGaussianBuffer); - commandList = device.CreateCommandList(0, CommandListType.Direct, frames[frameIndex].CommandAllocator, null); - commandList.Name = "Aquarium D3D12 Graphics Command List"; - commandList.Close(); - fence = device.CreateFence(0); - fence.Name = "Aquarium D3D12 Frame Fence"; - commandQueue.ExecuteCommandList(commandList); - WaitForGpu(); - ReportStartupProgress(startupProgress, "Loading studio IBL cubemaps"); - studioPmremTexture = LoadStudioPmremTexture(); - resourceRegistry.Add("studio-pmrem-cubemap", studioPmremTexture); - studioIrradianceTexture = LoadStudioIrradianceTexture(); - resourceRegistry.Add("studio-irradiance-cubemap", studioIrradianceTexture); - ReportStartupProgress(startupProgress, "Creating D3D12 render pipelines"); - fullscreenRootSignature = CreateFullscreenRootSignature(); - fullscreenRootSignature.Name = "Aquarium D3D12 Fullscreen Root Signature"; - localCastFusionRootSignature = CreateLocalCastFusionRootSignature(); - localCastFusionRootSignature.Name = "Aquarium D3D12 LocalCast Fusion Root Signature"; - fractalReservoirRootSignature = CreateFractalReservoirRootSignature(); - fractalReservoirRootSignature.Name = "Aquarium D3D12 Fractal Reservoir Root Signature"; - CaptureShaderWriteTimes(); - StartPipelineBuild("initial"); - viewport = new Viewport(0.0f, 0.0f, width, height); - scissorRect = new RawRect(0, 0, width, height); - Console.WriteLine($"D3D12 resource registry: {resourceRegistry.Describe()}"); - Console.WriteLine($"Aquarium render graph declared: {renderGraph.Describe()}"); - Console.WriteLine("D3D12 device and swapchain created."); - } - - public int RenderDebugMode - { - get => settings.RenderDebugMode; - set => settings = (settings with { RenderDebugMode = value }).Normalized(); - } - - public bool DebugUiVisible - { - get => debugUi.IsVisible; - set => debugUi.IsVisible = value; - } - - public bool HasPresentedReadyFrame => hasPresentedReadyFrame; - - public bool CapturesInput => debugUi.WantsKeyboard || debugUi.WantsMouse || clientUiPanels.Any(panel => panel.WantsKeyboard || panel.WantsMouse); - - public AquariumSynthDocument DebugSynth => new AquariumSynthDocument - { - MasterGain = 1.0f, - Enabled = true - }.Patch( - "aquarium-playground", - synthPlaygroundScript, - AquariumSynthTrigger.Manual(synthPlaygroundPlayRevision), - synthPlaygroundGain, - 0, - "aquarium_playground", - status => synthPlaygroundStatus = status); - - public void UpdateUi(InputState input, AquariumUiDocument clientUi) - { - if (!ReferenceEquals(currentClientUi, clientUi)) - { - currentClientUi = clientUi; - clientCommands = clientUi.Commands; - var debugPanels = clientUi.Panels.Where(panel => !panel.FadeWhenMouseDistant).ToArray(); - var floatingPanels = clientUi.Panels.Where(panel => panel.FadeWhenMouseDistant).ToArray(); - debugTabTitles = ["Aquarium", "Terminal", "Synth", .. debugPanels.Select(panel => panel.Title)]; - activeDebugTab = Math.Clamp(activeDebugTab, 0, debugTabTitles.Length - 1); - debugUi = CreateDebugUi(debugPanels); - clientUiPanels = floatingPanels.Select(DebugUi.FromContract).ToArray(); - } - - debugUi.Update(input); - foreach (var panel in clientUiPanels) - { - panel.Update(input); - } - } - - public void CycleRenderDebugMode() - { - RenderDebugMode = (RenderDebugMode + 1) % (GraphicsSettings.MaxRenderDebugMode + 1); - } - - public GraphicsSettings CaptureGraphicsSettings() - { - return settings.Normalized(); - } - - public void ApplyGraphicsSettings(GraphicsSettings graphicsSettings) - { - settings = graphicsSettings.Normalized(); - } - - private DebugUi CreateDebugUi(IReadOnlyList clientDebugPanels) - { - var ui = new DebugUi("Debug", 18.0f, 18.0f, 520.0f, debugTabTitles, () => activeDebugTab, SelectDebugTab) - .Panel(panel => - { - panel - .Section("View", () => activeDebugTab == 0) - .Options("Render Debug", () => RenderDebugMode, value => RenderDebugMode = Math.Clamp(value, GraphicsSettings.MinRenderDebugMode, GraphicsSettings.MaxRenderDebugMode), RenderDebugOptions, "Selects the active renderer debug view.", () => activeDebugTab == 0) - .Button("Reset View", () => RenderDebugMode = 0, "Returns to the final presented frame.", () => activeDebugTab == 0) - .Section("HDR", () => activeDebugTab == 0) - .Slider("Exposure", () => settings.SceneExposure, value => settings = (settings with { SceneExposure = Math.Clamp(value, GraphicsSettings.MinSceneExposure, GraphicsSettings.MaxSceneExposure) }).Normalized(), GraphicsSettings.MinSceneExposure, GraphicsSettings.MaxSceneExposure, "0.###", "Manual scene exposure before display transform.", () => activeDebugTab == 0) - .Slider("Bloom Intensity", () => settings.BloomIntensity, value => settings = (settings with { BloomIntensity = Math.Clamp(value, GraphicsSettings.MinBloomIntensity, GraphicsSettings.MaxBloomIntensity) }).Normalized(), GraphicsSettings.MinBloomIntensity, GraphicsSettings.MaxBloomIntensity, "0.###", "Strength of pre-tonemap bloom energy.", () => activeDebugTab == 0) - .Slider("Bloom Veil", () => settings.BloomVeilIntensity, value => settings = (settings with { BloomVeilIntensity = Math.Clamp(value, GraphicsSettings.MinBloomVeilIntensity, GraphicsSettings.MaxBloomVeilIntensity) }).Normalized(), GraphicsSettings.MinBloomVeilIntensity, GraphicsSettings.MaxBloomVeilIntensity, "0.###", "Low-frequency veil from bright HDR energy.", () => activeDebugTab == 0) - .Section("Terminal", () => activeDebugTab == 1) - .TextBox("", TerminalDisplay, UpdateTerminalInputFromDisplay, lines: 8, acceptsReturn: false, submit: ExecuteTerminalInput, monospace: true, alignBottom: true, tooltip: "Terminal log with live command prompt.", isVisible: () => activeDebugTab == 1) - .Section("Synth Playground", () => activeDebugTab == 2) - .Options("Preset", () => synthPlaygroundPreset, SelectSynthPreset, SynthPresetOptions, "Loads a built-in synth patch.", () => activeDebugTab == 2) - .Readout("Status", () => $"{synthPlaygroundStatus.State}: {synthPlaygroundStatus.Message}", isVisible: () => activeDebugTab == 2) - .TextBox("Patch", () => synthPlaygroundScript, value => synthPlaygroundScript = value, lines: 18, acceptsReturn: true, monospace: true, tooltip: "Patch DSL source.", isVisible: () => activeDebugTab == 2) - .Slider("Gain", () => synthPlaygroundGain, value => synthPlaygroundGain = Math.Clamp(value, 0.0f, 1.0f), 0.0f, 1.0f, "0.###", "Playground patch gain.", () => activeDebugTab == 2) - .Button("Play", () => synthPlaygroundPlayRevision++, "Triggers the compiled playground patch.", () => activeDebugTab == 2); - }); - for (var panelIndex = 0; panelIndex < clientDebugPanels.Count; panelIndex++) - { - var tabIndex = panelIndex + 3; - foreach (var control in clientDebugPanels[panelIndex].Controls) - { - ui.AddContractControl(control with { IsVisible = ComposeVisibility(control.IsVisible, () => activeDebugTab == tabIndex) }); - } - } - - return ui; - } - - private void SelectDebugTab(int index) - { - activeDebugTab = Math.Clamp(index, 0, Math.Max(0, debugTabTitles.Length - 1)); - } - - private static Func ComposeVisibility(Func? source, Func tabVisible) - { - return () => tabVisible() && (source?.Invoke() ?? true); - } - - private string TerminalDisplay() - { - return string.Join('\n', terminalLines.TakeLast(10).Append($"> {terminalInput}")); - } - - private void UpdateTerminalInputFromDisplay(string value) - { - if (value.EndsWith("\n>", StringComparison.Ordinal) || string.Equals(value, ">", StringComparison.Ordinal)) - { - terminalInput = string.Empty; - return; - } - - var promptIndex = value.LastIndexOf("\n> ", StringComparison.Ordinal); - if (promptIndex >= 0) - { - terminalInput = value[(promptIndex + 3)..].Replace("\r", string.Empty, StringComparison.Ordinal).Replace("\n", string.Empty, StringComparison.Ordinal); - return; - } - - if (value.StartsWith("> ", StringComparison.Ordinal)) - { - terminalInput = value[2..].Replace("\r", string.Empty, StringComparison.Ordinal).Replace("\n", string.Empty, StringComparison.Ordinal); - return; - } - - terminalInput = string.Empty; - } - - private void ExecuteTerminalInput() - { - var input = terminalInput.Trim(); - if (input.Length == 0) - { - return; - } - - terminalLines.Add($"> {input}"); - terminalInput = ""; - var parts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - var command = parts[0]; - var args = parts.Skip(1).ToArray(); - if (string.Equals(command, "help", StringComparison.OrdinalIgnoreCase)) - { - var names = new[] { "help", "clear", "render" } - .Concat(clientCommands.Select(item => item.Name)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .Order(StringComparer.OrdinalIgnoreCase); - terminalLines.Add(string.Join(", ", names)); - return; - } - - if (string.Equals(command, "clear", StringComparison.OrdinalIgnoreCase)) - { - terminalLines.Clear(); - return; - } - - if (string.Equals(command, "render", StringComparison.OrdinalIgnoreCase)) - { - if (args.Length > 0 && int.TryParse(args[0], out var mode)) - { - RenderDebugMode = Math.Clamp(mode, GraphicsSettings.MinRenderDebugMode, GraphicsSettings.MaxRenderDebugMode); - } - - terminalLines.Add($"render debug {RenderDebugMode}"); - return; - } - - var registered = clientCommands.FirstOrDefault(item => string.Equals(item.Name, command, StringComparison.OrdinalIgnoreCase)); - if (registered is not null) - { - terminalLines.Add(registered.Execute(args)); - return; - } - - terminalLines.Add($"unknown command: {command}"); - } - - private void SelectSynthPreset(int index) - { - synthPlaygroundPreset = Math.Clamp(index, 0, Math.Max(0, SynthPresets.Length - 1)); - synthPlaygroundScript = SynthPresets[synthPlaygroundPreset].Script; - } - - public void Render(AquariumFrame frame, int width, int height) - { - var frameCpuStart = Stopwatch.GetTimestamp(); - ResizeIfNeeded(width, height); - ApplyCompletedPipelineBuild(); - TryHotReloadShaders(); - var frameResources = frames[frameIndex]; - WaitForFrame(frameResources); - frameResources.UploadRing.Reset(); - frameResources.TransientShaderDescriptors.Reset(); - - if (!PipelinesReady) - { - RenderPipelineLoadingFrame(frame, frameResources, frameCpuStart); - return; - } - - var viewOrigin = frame.CameraTarget; - var farDistance = Vector3.Distance(frame.CameraPosition, viewOrigin) + MathF.Max(frame.View.Radius, 0.001f); - var jitterPixels = TemporalJitterPixels(temporalFrameIndex); - if (temporalFrameIndex == 0) - { - previousCameraPosition = frame.CameraPosition; - previousCameraTarget = frame.CameraTarget; - previousViewCenter = frame.View.Center; - previousCursorWorld = frame.CursorWorld; - previousViewRadius = frame.View.Radius; - previousTimeSeconds = frame.TimeSeconds; - previousJitterPixels = jitterPixels; - } - - CopySceneState(frame.Scene); - EnsureFractalReservoirBuffers(activeFractalReservoirField); - EnsureFractalProgramTransformBuffer(); - var activeGpuSensorInput = frame.Scene.GpuSensorFrame.HasInput; - var activeAccumulationWindow = activeGpuSensorInput - ? frame.Scene.GpuSensorFrame.AccumulationWindowSeconds - : frame.Scene.GpuFusionField.Seeds.Count > 0 - || frame.Scene.GpuFusionField.PointBuffer.HasInput - ? frame.Scene.GpuFusionField.AccumulationWindowSeconds - : frame.Scene.TemporalGaussianField.AccumulationWindowSeconds; - var activePresentationDelay = activeGpuSensorInput - ? frame.Scene.GpuSensorFrame.PresentationDelaySeconds - : frame.Scene.GpuFusionField.Seeds.Count > 0 - || frame.Scene.GpuFusionField.PointBuffer.HasInput - ? frame.Scene.GpuFusionField.PresentationDelaySeconds - : frame.Scene.TemporalGaussianField.PresentationDelaySeconds; - var frameConstants = frameResources.UploadRing.WriteConstant(new FrameConstants( - new Vector2(width, height), - frame.TimeSeconds, - frame.View.Radius, - frame.CameraPosition, - farDistance, - frame.CameraTarget, - SceneFlags(frame.Scene), - frame.View.Center, - temporalFrameIndex, - previousTimeSeconds, - previousCameraPosition, - previousViewRadius, - previousCameraTarget, - 0.0f, - previousViewCenter, - jitterPixels, - previousJitterPixels, - RenderDebugMode, - settings.SceneExposure, - settings.BloomIntensity, - settings.BloomVeilIntensity, - new Vector4(frame.CursorWorld.X, frame.CursorWorld.Y, previousCursorWorld.X, previousCursorWorld.Y), - new Vector4( - temporalGaussianCount, - gpuSensorCameraCount, - gpuSensorTextureCount, - gpuFusionSeedCount), - new Vector4( - acousticConstraintCount, - gpuFusionPointCount, - activePresentationDelay, - frame.Scene.AcousticFieldFrame.HasInput ? 1.0f : 0.0f), - new Vector4( - activeFractalReservoirField.HasInput ? activeFractalReservoirField.SplatCount : 0, - visibleFractalSplatCount, - activeFractalReservoirField.HasInput ? activeFractalReservoirField.ReservoirUpdatesPerPass : 0, - activeFractalReservoirField.HasInput ? activeFractalReservoirField.CandidatesPerReservoirUpdate : 0), - activeFractalReservoirField.HasInput ? activeFractalReservoirField.WorldCenterRadius : Vector4.Zero)); - frameResources.FrameConstantsDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - device.CreateConstantBufferView( - new ConstantBufferViewDescription(frameConstants.GpuVirtualAddress, frameConstants.SizeInBytes), - frameResources.FrameConstantsDescriptor.Cpu); - var heightFieldBrushConstantBuffer = frameResources.UploadRing.WriteConstant(heightFieldBrushConstants); - frameResources.HeightFieldBrushConstantsDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - device.CreateConstantBufferView( - new ConstantBufferViewDescription(heightFieldBrushConstantBuffer.GpuVirtualAddress, heightFieldBrushConstantBuffer.SizeInBytes), - frameResources.HeightFieldBrushConstantsDescriptor.Cpu); - - frameResources.SdfLightDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - sdfLightBuffer.CreateShaderResourceView(device, frameResources.SdfLightDescriptor); - frameResources.SdfObjectDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - sdfObjectBuffer.CreateShaderResourceView(device, frameResources.SdfObjectDescriptor); - frameResources.GpuSensorCameraDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - gpuSensorCameraBuffer.CreateShaderResourceView(device, frameResources.GpuSensorCameraDescriptor); - frameResources.GpuSensorTextureDescriptor = frameResources.TransientShaderDescriptors.AllocateRange(MaxGpuSensorTextureCount); - CreateGpuSensorTextureViews(frame.Scene.GpuSensorFrame, frameResources.GpuSensorTextureDescriptor); - frameResources.AcousticConstraintDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - acousticConstraintBuffer.CreateShaderResourceView(device, frameResources.AcousticConstraintDescriptor); - frameResources.GpuFusionSeedDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - gpuFusionSeedBuffer.CreateShaderResourceView(device, frameResources.GpuFusionSeedDescriptor); - frameResources.GpuFusionPointDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - gpuFusionPointBuffer.CreateShaderResourceView(device, frameResources.GpuFusionPointDescriptor); - frameResources.TemporalGaussianDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - temporalGaussianBuffer.CreateShaderResourceView(device, frameResources.TemporalGaussianDescriptor); - frameResources.TemporalGaussianUnorderedAccessDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - temporalGaussianBuffer.CreateUnorderedAccessView(device, frameResources.TemporalGaussianUnorderedAccessDescriptor); - frameResources.StudioPmremDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - studioPmremTexture.CreateShaderResourceView(device, frameResources.StudioPmremDescriptor); - frameResources.StudioIrradianceDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - studioIrradianceTexture.CreateShaderResourceView(device, frameResources.StudioIrradianceDescriptor); - frameResources.HeightFieldDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - heightFieldRenderTarget.CreateShaderResourceView(device, frameResources.HeightFieldDescriptor); - frameResources.SceneDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - sceneRenderTarget.CreateShaderResourceView(device, frameResources.SceneDescriptor); - frameResources.SceneMetadataDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - sceneMetadataRenderTarget.CreateShaderResourceView(device, frameResources.SceneMetadataDescriptor); - frameResources.SceneControlDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - sceneControlRenderTarget.CreateShaderResourceView(device, frameResources.SceneControlDescriptor); - frameResources.SceneReservoirGuideDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - sceneReservoirGuideRenderTarget.CreateShaderResourceView(device, frameResources.SceneReservoirGuideDescriptor); - var historyReadIndex = temporalFrameIndex & 1; - frameResources.HistoryDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - historyRenderTargets[historyReadIndex].CreateShaderResourceView(device, frameResources.HistoryDescriptor); - frameResources.HistoryMetadataDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - historyMetadataRenderTargets[historyReadIndex].CreateShaderResourceView(device, frameResources.HistoryMetadataDescriptor); - frameResources.HistoryControlDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - historyControlRenderTargets[historyReadIndex].CreateShaderResourceView(device, frameResources.HistoryControlDescriptor); - frameResources.HistoryReservoirGuideDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - historyReservoirGuideRenderTargets[historyReadIndex].CreateShaderResourceView(device, frameResources.HistoryReservoirGuideDescriptor); - for (var level = 0; level < BloomLevelCount; level++) - { - frameResources.BloomDescriptors[level] = frameResources.TransientShaderDescriptors.Allocate(); - bloomRenderTargets[level].CreateShaderResourceView(device, frameResources.BloomDescriptors[level]); - frameResources.BloomScratchDescriptors[level] = frameResources.TransientShaderDescriptors.Allocate(); - bloomScratchTargets[level].CreateShaderResourceView(device, frameResources.BloomScratchDescriptors[level]); - } - - frameResources.BloomPresentationDescriptor = frameResources.TransientShaderDescriptors.Allocate(); - bloomRenderTargets[0].CreateShaderResourceView(device, frameResources.BloomPresentationDescriptor); - for (var level = 1; level < BloomLevelCount; level++) - { - var descriptor = frameResources.TransientShaderDescriptors.Allocate(); - bloomRenderTargets[level].CreateShaderResourceView(device, descriptor); - } - - frameResources.CommandAllocator.Reset(); - commandList.Reset(frameResources.CommandAllocator, null); - - var recordCpuStart = Stopwatch.GetTimestamp(); - commandList.BeginEvent("Aquarium D3D12 Frame"); - UploadSceneStructuredResources(commandList, frameResources); - DispatchLocalCastGpuFusion(commandList, frameResources); - DispatchFractalReservoirs(commandList, frameResources); - RenderHeightField(commandList, frameResources); - RenderSceneAndPresent(new D3D12PassContext(commandList, frameResources.BackBuffer, frameResources.BackBufferRenderTargetView.Cpu), frameResources); - commandList.EndEvent(); - commandList.Close(); - var recordCpuMilliseconds = ElapsedMilliseconds(recordCpuStart); - - commandQueue.ExecuteCommandList(commandList); - var overlayCpuStart = Stopwatch.GetTimestamp(); - RenderOverlay(frame, frameResources); - var overlayCpuMilliseconds = ElapsedMilliseconds(overlayCpuStart); - swapChain.Present(1, PresentFlags.None); - var frameCpuMilliseconds = ElapsedMilliseconds(frameCpuStart); - if (temporalFrameIndex > 4) - { - accumulatedRecordCpuMilliseconds += recordCpuMilliseconds; - accumulatedOverlayCpuMilliseconds += overlayCpuMilliseconds; - accumulatedFrameCpuMilliseconds += frameCpuMilliseconds; - accumulatedTimingFrames++; - } - SignalFrame(frameResources); - ReportCapacityOncePerSecond(frame.TimeSeconds, frameResources); - previousCameraPosition = frame.CameraPosition; - previousCameraTarget = frame.CameraTarget; - previousViewCenter = frame.View.Center; - previousCursorWorld = frame.CursorWorld; - previousViewRadius = frame.View.Radius; - previousTimeSeconds = frame.TimeSeconds; - previousJitterPixels = jitterPixels; - hasPresentedReadyFrame = true; - temporalFrameIndex++; - frameIndex = (int)swapChain.CurrentBackBufferIndex; - } - - public unsafe void SaveFramePng(string path) - { - if (!hasPresentedReadyFrame) - { - throw new InvalidOperationException("No completed frame is available to save."); - } - - WaitForGpu(); - - var sourceIndex = (frameIndex + BackBufferCount - 1) % BackBufferCount; - var source = frames[sourceIndex].BackBuffer; - var rowBytes = checked(width * 4); - var rowPitch = AlignTo(rowBytes, D3D12.TextureDataPitchAlignment); - var bufferBytes = checked((long)rowPitch * height); - using var readback = device.CreateCommittedResource( - HeapType.Readback, - ResourceDescription.Buffer((ulong)bufferBytes), - ResourceStates.CopyDest, - null); - readback.Name = "Aquarium D3D12 Frame PNG Readback"; - - using var captureAllocator = device.CreateCommandAllocator(CommandListType.Direct); - using var captureList = device.CreateCommandList(0, CommandListType.Direct, captureAllocator, null); - source.Transition(captureList, ResourceStates.CopySource); - var footprint = new PlacedSubresourceFootPrint - { - Offset = 0, - Footprint = new SubresourceFootPrint( - Format.B8G8R8A8_UNorm, - (uint)width, - (uint)height, - 1, - (uint)rowPitch), - }; - var destination = new TextureCopyLocation(readback, footprint); - var textureSource = new TextureCopyLocation(source.Resource, 0); - captureList.CopyTextureRegion(destination, 0, 0, 0, textureSource, null); - source.Transition(captureList, ResourceStates.Present); - captureList.Close(); - commandQueue.ExecuteCommandList(captureList); - WaitForGpu(); - - var rgba = new byte[checked(rowBytes * height)]; - var mapped = readback.Map(0); - try - { - for (var y = 0; y < height; y++) - { - var sourceRow = mapped + ((long)y * rowPitch); - var destinationRow = y * rowBytes; - for (var x = 0; x < width; x++) - { - var sourcePixel = sourceRow + (x * 4); - var destinationPixel = destinationRow + (x * 4); - rgba[destinationPixel] = sourcePixel[2]; - rgba[destinationPixel + 1] = sourcePixel[1]; - rgba[destinationPixel + 2] = sourcePixel[0]; - rgba[destinationPixel + 3] = sourcePixel[3]; - } - } - } - finally - { - readback.Unmap(0, null); - } - - PngImageWriter.WriteRgba(path, width, height, rgba); - } - - private static Vector2 TemporalJitterPixels(int index) - { - const float scale = 0.42f; - return new Vector2( - (Halton(index + 1, 2) - 0.5f) * scale, - (Halton(index + 1, 3) - 0.5f) * scale); - } - - private static float Halton(int index, int basis) - { - var result = 0.0f; - var fraction = 1.0f / basis; - while (index > 0) - { - result += fraction * (index % basis); - index /= basis; - fraction /= basis; - } - - return result; - } - - private bool PipelinesReady => - heightFieldBasePipelineState is not null - && heightFieldBrushPipelineState is not null - && scenePipelineState is not null - && temporalGaussianPipelineState is not null - && localCastFusionPipelineState is not null - && fractalSurfaceSplatRenderPipelineState is not null - && fractalTransparentSplatRenderPipelineState is not null - && fractalSplatPipelineState is not null - && fractalSdfReservoirPipelineState is not null - && fractalPbrReservoirPipelineState is not null - && fractalRadiosityReservoirPipelineState is not null - && sdfProxyPipelineStates.All(pipeline => pipeline is not null) - && bloomPrefilterPipelineState is not null - && bloomDownsamplePipelineState is not null - && bloomBlurHorizontalPipelineState is not null - && bloomBlurVerticalPipelineState is not null - && resolvePipelineState is not null; - - private void RenderPipelineLoadingFrame(AquariumFrame frame, FrameResources frameResources, long frameCpuStart) - { - var frameCpuMilliseconds = ElapsedMilliseconds(frameCpuStart); - accumulatedFrameCpuMilliseconds += frameCpuMilliseconds; - accumulatedTimingFrames++; - ReportCapacityOncePerSecond(frame.TimeSeconds, frameResources); - Thread.Sleep(8); - } - - public void Dispose() - { - WaitForGpu(); - try - { - pipelineBuildTask?.Wait(TimeSpan.FromMilliseconds(50)); - } - catch - { - // A failed background compile has already been reported or will be discarded with the renderer. - } - - fenceEvent.Dispose(); - fence.Dispose(); - commandList.Dispose(); - DisposeBackBufferOverlays(); - overlayOn12Device.Dispose(); - overlayContext.Dispose(); - overlayDevice.Dispose(); - DisposePipelineStates(); - fullscreenRootSignature.Dispose(); - localCastFusionRootSignature.Dispose(); - fractalReservoirRootSignature.Dispose(); - studioIrradianceTexture.Dispose(); - studioPmremTexture.Dispose(); - DisposeFractalReservoirBuffers(); - temporalGaussianBuffer.Dispose(); - gpuFusionPointBuffer.Dispose(); - gpuFusionSeedBuffer.Dispose(); - acousticConstraintBuffer.Dispose(); - gpuSensorCameraBuffer.Dispose(); - foreach (var texture in externalSensorTextures.Values) - { - texture.Dispose(); - } - - externalSensorTextures.Clear(); - sdfObjectBuffer.Dispose(); - sdfLightBuffer.Dispose(); - DisposeBloomRenderTargets(); - DisposeHistoryRenderTargets(); - DisposeGraphRenderTargets(); - sceneRenderTarget.Dispose(); - sceneMetadataRenderTarget.Dispose(); - sceneControlRenderTarget.Dispose(); - sceneReservoirGuideRenderTarget.Dispose(); - sceneDepthTarget.Dispose(); - heightFieldRenderTarget.Dispose(); - for (var index = 0; index < frames.Length; index++) - { - frames[index].Dispose(); - } - staticShaderDescriptorArena.Dispose(); - depthStencilViewArena.Dispose(); - renderTargetViewArena.Dispose(); - swapChain.Dispose(); - commandQueue.Dispose(); - device.Dispose(); - factory.Dispose(); - } - - private void CreateRenderTargetViews() - { - for (var index = 0; index < frames.Length; index++) - { - var backBuffer = swapChain.GetBuffer((uint)index); - var backBufferResource = new D3D12TrackedResource(backBuffer, ResourceStates.Present, $"Aquarium D3D12 Backbuffer {index}", ownsResource: true); - frames[index].BackBuffer = backBufferResource; - resourceRegistry.Add($"backbuffer-{index}", backBufferResource); - frames[index].BackBufferRenderTargetView = renderTargetViewArena.Allocate(); - device.CreateRenderTargetView(frames[index].BackBuffer.Resource, null, frames[index].BackBufferRenderTargetView.Cpu); - } - } - - private D3D12CubeTexture LoadStudioPmremTexture() - { - return LoadStudioCubeTexture(StudioPmremRelativePath, "Studio PMREM", "Aquarium D3D12 Studio PMREM Cubemap"); - } - - private D3D12CubeTexture LoadStudioIrradianceTexture() - { - return LoadStudioCubeTexture(StudioIrradianceRelativePath, "Studio irradiance", "Aquarium D3D12 Studio Irradiance Cubemap"); - } - - private D3D12CubeTexture LoadStudioCubeTexture(string relativePath, string label, string resourceName) - { - var path = Path.Combine(AppContext.BaseDirectory, relativePath); - if (!File.Exists(path)) - { - throw new FileNotFoundException($"{label} cubemap asset was not copied to the runtime asset directory.", path); - } - - var frameResources = frames[frameIndex]; - frameResources.CommandAllocator.Reset(); - commandList.Reset(frameResources.CommandAllocator, null); - var texture = D3D12CubeTexture.LoadRgba16FloatDds(device, commandList, path, resourceName, out var uploadResource); - commandList.Close(); - commandQueue.ExecuteCommandList(commandList); - WaitForGpu(); - uploadResource.Dispose(); - return texture; - } - - private void CreateOverlayDevice(out ID3D11Device createdDevice, out ID3D11DeviceContext createdContext, out ID3D11On12Device createdOn12Device) - { - var featureLevels = new[] { FeatureLevel.Level_11_1, FeatureLevel.Level_11_0 }; - var commandQueues = new IUnknown[] { commandQueue }; - Apis.D3D11On12CreateDevice( - device, - D3D11DeviceCreationFlags.BgraSupport, - featureLevels, - commandQueues, - 0, - out createdDevice, - out createdContext, - out _).CheckError(); - createdOn12Device = createdDevice.QueryInterface(); - } - - private void CreateBackBufferOverlays() - { - overlayWrappedBackBuffers = new ID3D11Resource[frames.Length]; - overlays = new DirectWriteOverlay[frames.Length]; - var flags = new Vortice.Direct3D11on12.ResourceFlags - { - BindFlags = D3D11BindFlags.RenderTarget, - }; - - for (var index = 0; index < frames.Length; index++) - { - var wrapped = overlayOn12Device.CreateWrappedResource( - frames[index].BackBuffer.Resource, - flags, - ResourceStates.RenderTarget, - ResourceStates.Present); - overlayWrappedBackBuffers[index] = wrapped; - using var surface = wrapped.QueryInterface(); - overlays[index] = new DirectWriteOverlay(surface, width, height); - } - } - - private void RenderOverlay(AquariumFrame frame, FrameResources frameResources) - { - var wrappedBackBuffer = overlayWrappedBackBuffers[frameIndex]; - overlayOn12Device.AcquireWrappedResources([wrappedBackBuffer]); - overlays[frameIndex].Render(frame, RenderDebugMode, debugUi, clientUiPanels); - overlayOn12Device.ReleaseWrappedResources([wrappedBackBuffer]); - overlayContext.Flush(); - frameResources.BackBuffer.MarkState(ResourceStates.Present); - } - - private void DisposeBackBufferOverlays() - { - foreach (var overlay in overlays) - { - overlay?.Dispose(); - } - - foreach (var wrappedBackBuffer in overlayWrappedBackBuffers) - { - wrappedBackBuffer?.Dispose(); - } - - overlays = []; - overlayWrappedBackBuffers = []; - } - - private D3D12PipelineSet CreatePipelineSet(D3D12ShaderPaths paths) - { - var heightFieldBase = CreateHeightFieldBasePipelineState(paths.HeightField); - heightFieldBase.Name = "Aquarium D3D12 Height Field Base Pipeline"; - var heightFieldBrush = CreateHeightFieldBrushPipelineState(paths.HeightField); - heightFieldBrush.Name = "Aquarium D3D12 Height Field Brush Pipeline"; - var scene = CreateScenePipelineState(paths.Scene); - scene.Name = "Aquarium D3D12 Scene Pipeline"; - var temporalGaussian = CreateTemporalGaussianPipelineState(paths.TemporalGaussian); - temporalGaussian.Name = "Aquarium D3D12 Temporal Gaussian Pipeline"; - var localCastFusion = CreateLocalCastFusionPipelineState(paths.LocalCastFusion); - localCastFusion.Name = "Aquarium D3D12 LocalCast Fusion Compute Pipeline"; - var fractalSurfaceSplatRender = CreateFractalSurfaceSplatRenderPipelineState(paths.FractalSplatRender); - fractalSurfaceSplatRender.Name = "Aquarium D3D12 Fractal Surface Splat Render Pipeline"; - var fractalTransparentSplatRender = CreateFractalTransparentSplatRenderPipelineState(paths.FractalSplatRender); - fractalTransparentSplatRender.Name = "Aquarium D3D12 Fractal Transparent Splat Render Pipeline"; - var fractalSplat = CreateFractalReservoirPipelineState(paths.FractalReservoir, "D3D12FractalSplatReceiptCS"); - fractalSplat.Name = "Aquarium D3D12 Fractal Splat Compute Pipeline"; - var fractalSdfReservoir = CreateFractalReservoirPipelineState(paths.FractalReservoir, "D3D12SdfEnvelopeReservoirCS"); - fractalSdfReservoir.Name = "Aquarium D3D12 Fractal SDF Reservoir Compute Pipeline"; - var fractalPbrReservoir = CreateFractalReservoirPipelineState(paths.FractalReservoir, "D3D12PbrMaterialReservoirCS"); - fractalPbrReservoir.Name = "Aquarium D3D12 Fractal PBR Reservoir Compute Pipeline"; - var fractalRadiosityReservoir = CreateFractalReservoirPipelineState(paths.FractalReservoir, "D3D12RadiosityReservoirCS"); - fractalRadiosityReservoir.Name = "Aquarium D3D12 Fractal Radiosity Reservoir Compute Pipeline"; - var sdfProxies = new ID3D12PipelineState[paths.SdfShaders.Count]; - for (var index = 0; index < paths.SdfShaders.Count; index++) - { - sdfProxies[index] = CreateSdfObjectProxyPipelineState(paths.SdfShaders[index]); - sdfProxies[index].Name = $"Aquarium D3D12 Sdf Proxy Pipeline {index}"; - } - - var bloomPrefilter = CreateBloomPrefilterPipelineState(paths.Post); - bloomPrefilter.Name = "Aquarium D3D12 Bloom Prefilter Pipeline"; - var bloomDownsample = CreateBloomDownsamplePipelineState(paths.Post); - bloomDownsample.Name = "Aquarium D3D12 Bloom Downsample Pipeline"; - var bloomBlurHorizontal = CreateBloomBlurHorizontalPipelineState(paths.Post); - bloomBlurHorizontal.Name = "Aquarium D3D12 Bloom Blur Horizontal Pipeline"; - var bloomBlurVertical = CreateBloomBlurVerticalPipelineState(paths.Post); - bloomBlurVertical.Name = "Aquarium D3D12 Bloom Blur Vertical Pipeline"; - var resolve = CreateResolvePipelineState(paths.Post); - resolve.Name = "Aquarium D3D12 Resolve Pipeline"; - - return new D3D12PipelineSet( - heightFieldBase, - heightFieldBrush, - scene, - temporalGaussian, - localCastFusion, - fractalSurfaceSplatRender, - fractalTransparentSplatRender, - fractalSplat, - fractalSdfReservoir, - fractalPbrReservoir, - fractalRadiosityReservoir, - sdfProxies, - bloomPrefilter, - bloomDownsample, - bloomBlurHorizontal, - bloomBlurVertical, - resolve); - } - - private void ResizeIfNeeded(int newWidth, int newHeight) - { - newWidth = Math.Max(1, newWidth); - newHeight = Math.Max(1, newHeight); - if (newWidth == width && newHeight == height) - { - return; - } - - WaitForGpu(); - DisposeBackBufferOverlays(); - RemoveBloomRenderTargets(); - RemoveHistoryRenderTargets(); - RemoveGraphRenderTargets(); - resourceRegistry.RemoveRenderTarget("scene-hdr-target"); - resourceRegistry.RemoveRenderTarget("scene-metadata-target"); - resourceRegistry.RemoveRenderTarget("scene-control-target"); - resourceRegistry.RemoveRenderTarget("scene-reservoir-guide-target"); - resourceRegistry.RemoveResource("scene-depth-target"); - resourceRegistry.RemoveRenderTarget("height-field-target"); - DisposeBloomRenderTargets(); - DisposeHistoryRenderTargets(); - DisposeGraphRenderTargets(); - sceneRenderTarget.Dispose(); - sceneMetadataRenderTarget.Dispose(); - sceneControlRenderTarget.Dispose(); - sceneReservoirGuideRenderTarget.Dispose(); - sceneDepthTarget.Dispose(); - heightFieldRenderTarget.Dispose(); - for (var index = 0; index < frames.Length; index++) - { - resourceRegistry.RemoveResource($"backbuffer-{index}"); - frames[index].BackBuffer.Dispose(); - } - - width = newWidth; - height = newHeight; - renderTargetViewArena.Dispose(); - depthStencilViewArena.Dispose(); - staticShaderDescriptorArena.Dispose(); - renderTargetViewArena = CreateRenderTargetViewArena(); - depthStencilViewArena = CreateDepthStencilViewArena(); - staticShaderDescriptorArena = CreateStaticShaderDescriptorArena(); - - swapChain.ResizeBuffers(BackBufferCount, (uint)width, (uint)height, Format.B8G8R8A8_UNorm, SwapChainFlags.None).CheckError(); - frameIndex = (int)swapChain.CurrentBackBufferIndex; - CreateRenderTargetViews(); - CreateBackBufferOverlays(); - heightFieldRenderTarget = CreateHeightFieldRenderTarget(); - sceneRenderTarget = CreateSceneRenderTarget(); - sceneMetadataRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-metadata-target", "Aquarium D3D12 Scene Metadata Target"); - sceneControlRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-control-target", "Aquarium D3D12 Scene Control Target"); - sceneReservoirGuideRenderTarget = CreateSceneAuxiliaryRenderTarget("scene-reservoir-guide-target", "Aquarium D3D12 Scene Reservoir Guide Target"); - sceneDepthStencilView = depthStencilViewArena.Allocate(); - sceneDepthTarget = CreateSceneDepthTarget(sceneDepthStencilView); - CreateHistoryRenderTargets(); - CreateBloomRenderTargets(); - CreateGraphRenderTargets(); - viewport = new Viewport(0.0f, 0.0f, width, height); - scissorRect = new RawRect(0, 0, width, height); - Console.WriteLine($"D3D12 resized: {width}x{height}; {resourceRegistry.Describe()}"); - } - - private D3D12RenderTarget CreateSceneRenderTarget() - { - var target = new D3D12RenderTarget( - device, - width, - height, - SceneHdrFormat, - renderTargetViewArena.Allocate(), - staticShaderDescriptorArena.Allocate(), - null, - false, - new Color4(0.0f, 0.0f, 0.0f, 1.0f), - "Aquarium D3D12 Scene HDR Target"); - resourceRegistry.Add("scene-hdr-target", target); - return target; - } - - private D3D12RenderTarget CreateSceneAuxiliaryRenderTarget(string registryName, string resourceName) - { - var target = new D3D12RenderTarget( - device, - width, - height, - SceneHdrFormat, - renderTargetViewArena.Allocate(), - staticShaderDescriptorArena.Allocate(), - null, - false, - new Color4(0.0f, 0.0f, 0.0f, 1.0f), - resourceName); - resourceRegistry.Add(registryName, target); - return target; - } - - private D3D12TrackedResource CreateSceneDepthTarget(D3D12DescriptorSlot depthStencilView) - { - var clearValue = new ClearValue - { - Format = SceneDepthFormat, - DepthStencil = new DepthStencilValue(1.0f, 0), - }; - var resource = device.CreateCommittedResource( - HeapType.Default, - ResourceDescription.Texture2D( - SceneDepthFormat, - (uint)width, - (uint)height, - 1, - 1, - 1, - 0, - Vortice.Direct3D12.ResourceFlags.AllowDepthStencil), - ResourceStates.DepthWrite, - clearValue); - device.CreateDepthStencilView(resource, new DepthStencilViewDescription - { - Format = SceneDepthFormat, - ViewDimension = DepthStencilViewDimension.Texture2D, - Texture2D = new Texture2DDepthStencilView(), - }, depthStencilView.Cpu); - var target = new D3D12TrackedResource(resource, ResourceStates.DepthWrite, "Aquarium D3D12 Scene Depth Target", true); - resourceRegistry.Add("scene-depth-target", target); - return target; - } - - private void CreateBloomRenderTargets() - { - for (var level = 0; level < BloomLevelCount; level++) - { - bloomRenderTargets[level] = CreateBloomRenderTarget(level, false); - bloomScratchTargets[level] = CreateBloomRenderTarget(level, true); - } - } - - private void CreateHistoryRenderTargets() - { - for (var index = 0; index < 2; index++) - { - historyRenderTargets[index] = CreateSceneAuxiliaryRenderTarget($"history-{index}", $"Aquarium D3D12 History {index}"); - historyMetadataRenderTargets[index] = CreateSceneAuxiliaryRenderTarget($"history-metadata-{index}", $"Aquarium D3D12 History Metadata {index}"); - historyControlRenderTargets[index] = CreateSceneAuxiliaryRenderTarget($"history-control-{index}", $"Aquarium D3D12 History Control {index}"); - historyReservoirGuideRenderTargets[index] = CreateSceneAuxiliaryRenderTarget($"history-reservoir-guide-{index}", $"Aquarium D3D12 History Reservoir Guide {index}"); - } - } - - private void RemoveHistoryRenderTargets() - { - for (var index = 0; index < 2; index++) - { - resourceRegistry.RemoveRenderTarget($"history-{index}"); - resourceRegistry.RemoveRenderTarget($"history-metadata-{index}"); - resourceRegistry.RemoveRenderTarget($"history-control-{index}"); - resourceRegistry.RemoveRenderTarget($"history-reservoir-guide-{index}"); - } - } - - private void DisposeHistoryRenderTargets() - { - for (var index = 0; index < 2; index++) - { - historyRenderTargets[index]?.Dispose(); - historyMetadataRenderTargets[index]?.Dispose(); - historyControlRenderTargets[index]?.Dispose(); - historyReservoirGuideRenderTargets[index]?.Dispose(); - } - } - - private D3D12RenderTarget CreateBloomRenderTarget(int level, bool scratch) - { - var target = new D3D12RenderTarget( - device, - Math.Max(1, width >> (level + 1)), - Math.Max(1, height >> (level + 1)), - SceneHdrFormat, - renderTargetViewArena.Allocate(), - staticShaderDescriptorArena.Allocate(), - null, - false, - new Color4(0.0f, 0.0f, 0.0f, 1.0f), - scratch - ? $"Aquarium D3D12 Bloom Scratch L{level}" - : $"Aquarium D3D12 Bloom L{level}"); - resourceRegistry.Add(scratch ? $"bloom-scratch-{level}" : $"bloom-{level}", target); - return target; - } - - private void RemoveBloomRenderTargets() - { - for (var level = 0; level < BloomLevelCount; level++) - { - resourceRegistry.RemoveRenderTarget($"bloom-{level}"); - resourceRegistry.RemoveRenderTarget($"bloom-scratch-{level}"); - } - } - - private void DisposeBloomRenderTargets() - { - for (var level = 0; level < BloomLevelCount; level++) - { - bloomRenderTargets[level]?.Dispose(); - bloomScratchTargets[level]?.Dispose(); - } - } - - private D3D12RenderTarget CreateHeightFieldRenderTarget() - { - var target = new D3D12RenderTarget( - device, - HeightFieldTextureSize, - HeightFieldTextureSize, - HeightFieldFormat, - renderTargetViewArena.Allocate(), - staticShaderDescriptorArena.Allocate(), - null, - false, - new Color4(0.0f, 0.0f, 0.0f, 1.0f), - "Aquarium D3D12 Height Field Target"); - resourceRegistry.Add("height-field-target", target); - return target; - } - - private void CreateGraphRenderTargets() - { - foreach (var targetDescription in renderGraph.RenderTargets) - { - if (IsLegacyGraphTarget(targetDescription.Handle.Name) || graphRenderTargets.ContainsKey(targetDescription.Handle.Name)) - { - continue; - } - - var targetSize = ResolveGraphTargetSize(targetDescription.Size); - var target = new D3D12RenderTarget( - device, - targetSize.Width, - targetSize.Height, - ToDxgiFormat(targetDescription.Format), - renderTargetViewArena.Allocate(), - null, - null, - allowUnorderedAccess: false, - new Color4(0.0f, 0.0f, 0.0f, 1.0f), - $"Aquarium D3D12 Graph Target {targetDescription.Handle.Name}"); - graphRenderTargets.Add(targetDescription.Handle.Name, target); - resourceRegistry.Add($"graph-target:{targetDescription.Handle.Name}", target); - } - } - - private void RemoveGraphRenderTargets() - { - foreach (var name in graphRenderTargets.Keys) - { - resourceRegistry.RemoveRenderTarget($"graph-target:{name}"); - } - } - - private void DisposeGraphRenderTargets() - { - foreach (var target in graphRenderTargets.Values) - { - target.Dispose(); - } - - graphRenderTargets.Clear(); - } - - private void EnsureFractalReservoirBuffers(AquariumFractalReservoirField field) - { - if (!field.HasInput) - { - return; - } - - if (fractalSplatBuffer is not null && fractalFlameStateBuffer is not null && fractalSplatBuffer.ElementCount >= field.SplatCount && fractalFlameStateBuffer.ElementCount >= field.SplatCount) - { - return; - } - - WaitForGpu(); - DisposeFractalReservoirBuffers(); - fractalSplatBuffer = CreateFractalReservoirBuffer( - field.SplatCount, - "fractal-sdf-splat-buffer", - "Aquarium D3D12 Fractal SDF Splat Buffer"); - fractalSdfReservoirBuffer = CreateFractalReservoirBuffer( - field.SplatCount, - "fractal-sdf-envelope-reservoir-buffer", - "Aquarium D3D12 Fractal SDF Envelope Reservoir Buffer"); - fractalPbrReservoirBuffer = CreateFractalReservoirBuffer( - field.SplatCount, - "fractal-pbr-material-reservoir-buffer", - "Aquarium D3D12 Fractal PBR Material Reservoir Buffer"); - fractalRadiosityReservoirBuffer = CreateFractalReservoirBuffer( - field.SplatCount, - "fractal-radiosity-reservoir-buffer", - "Aquarium D3D12 Fractal Radiosity Reservoir Buffer"); - fractalFlameStateBuffer = CreateFractalReservoirBuffer( - field.SplatCount, - "fractal-flame-state-buffer", - "Aquarium D3D12 Fractal Flame Iteration State Buffer"); - } - - private D3D12StructuredBuffer CreateFractalReservoirBuffer(int elementCount, string registryName, string resourceName) - where T : unmanaged - { - var buffer = new D3D12StructuredBuffer( - device, - elementCount, - Marshal.SizeOf(), - resourceName, - allowUnorderedAccess: true); - resourceRegistry.Add(registryName, buffer); - return buffer; - } - - private void EnsureFractalProgramTransformBuffer() - { - if (!activeFractalReservoirField.HasInput) - { - return; - } - - var requiredCount = Math.Max(activeFractalProgramTransforms.Length, 1); - if (fractalProgramTransformBuffer is not null && fractalProgramTransformBuffer.ElementCount >= requiredCount) - { - return; - } - - WaitForGpu(); - resourceRegistry.RemoveStructuredBuffer("fractal-program-transform-buffer"); - fractalProgramTransformBuffer?.Dispose(); - fractalProgramTransformBuffer = new D3D12StructuredBuffer( - device, - requiredCount, - Marshal.SizeOf(), - "Aquarium D3D12 Fractal IFS Program Transform Buffer"); - resourceRegistry.Add("fractal-program-transform-buffer", fractalProgramTransformBuffer); - } - - private void DisposeFractalReservoirBuffers() - { - resourceRegistry.RemoveStructuredBuffer("fractal-program-transform-buffer"); - resourceRegistry.RemoveStructuredBuffer("fractal-flame-state-buffer"); - resourceRegistry.RemoveStructuredBuffer("fractal-radiosity-reservoir-buffer"); - resourceRegistry.RemoveStructuredBuffer("fractal-pbr-material-reservoir-buffer"); - resourceRegistry.RemoveStructuredBuffer("fractal-sdf-envelope-reservoir-buffer"); - resourceRegistry.RemoveStructuredBuffer("fractal-sdf-splat-buffer"); - fractalProgramTransformBuffer?.Dispose(); - fractalFlameStateBuffer?.Dispose(); - fractalRadiosityReservoirBuffer?.Dispose(); - fractalPbrReservoirBuffer?.Dispose(); - fractalSdfReservoirBuffer?.Dispose(); - fractalSplatBuffer?.Dispose(); - fractalProgramTransformBuffer = null; - fractalFlameStateBuffer = null; - fractalRadiosityReservoirBuffer = null; - fractalPbrReservoirBuffer = null; - fractalSdfReservoirBuffer = null; - fractalSplatBuffer = null; - } - - private (int Width, int Height) ResolveGraphTargetSize(AquariumTargetSize size) - { - return size.Kind switch - { - AquariumTargetSizeKind.Fixed => (Math.Max(1, size.Width), Math.Max(1, size.Height)), - AquariumTargetSizeKind.MatchWindow => ( - Math.Max(1, (int)MathF.Ceiling(width * MathF.Max(size.Scale, 0.001f))), - Math.Max(1, (int)MathF.Ceiling(height * MathF.Max(size.Scale, 0.001f)))), - _ => throw new ArgumentOutOfRangeException(nameof(size), size.Kind, "Unsupported render target size policy."), - }; - } - - private static Format ToDxgiFormat(RenderFormat format) - { - return format switch - { - RenderFormat.R16Float => Format.R16_Float, - RenderFormat.Rgba16Float => Format.R16G16B16A16_Float, - RenderFormat.Bgra8Unorm => Format.B8G8R8A8_UNorm, - _ => throw new ArgumentOutOfRangeException(nameof(format), format, "Unsupported render target format."), - }; - } - - private static bool IsLegacyGraphTarget(string name) - { - return string.Equals(name, "height-field", StringComparison.Ordinal) - || string.Equals(name, "scene", StringComparison.Ordinal) - || string.Equals(name, "scene-metadata", StringComparison.Ordinal) - || string.Equals(name, "scene-control", StringComparison.Ordinal); - } - - private void RenderSceneAndPresent(D3D12PassContext context, FrameResources frameResources) - { - context.CommandList.BeginEvent("Scene Pass"); - try - { - heightFieldRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); - sceneRenderTarget.Transition(context.CommandList, ResourceStates.RenderTarget); - sceneMetadataRenderTarget.Transition(context.CommandList, ResourceStates.RenderTarget); - sceneControlRenderTarget.Transition(context.CommandList, ResourceStates.RenderTarget); - sceneReservoirGuideRenderTarget.Transition(context.CommandList, ResourceStates.RenderTarget); - sceneDepthTarget.Transition(context.CommandList, ResourceStates.DepthWrite); - context.CommandList.ClearRenderTargetView(sceneRenderTarget.RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); - context.CommandList.ClearRenderTargetView(sceneMetadataRenderTarget.RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); - context.CommandList.ClearRenderTargetView(sceneControlRenderTarget.RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); - context.CommandList.ClearRenderTargetView(sceneReservoirGuideRenderTarget.RenderTargetView.Cpu, new Color4(1.0f, 0.0f, 1.0f, 0.0f)); - context.CommandList.ClearDepthStencilView(sceneDepthStencilView.Cpu, ClearFlags.Depth, 1.0f, 0); - context.CommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); - context.CommandList.SetPipelineState(scenePipelineState!); - context.CommandList.SetGraphicsRootSignature(fullscreenRootSignature); - context.CommandList.SetGraphicsRootDescriptorTable(RootFrameConstants, frameResources.FrameConstantsDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootSourceTexture, frameResources.HeightFieldDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootHeightFieldBrushes, frameResources.HeightFieldBrushConstantsDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootSdfLights, frameResources.SdfLightDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootStudioPmrem, frameResources.StudioPmremDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootStudioIrradiance, frameResources.StudioIrradianceDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootSdfObjects, frameResources.SdfObjectDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootTemporalGaussians, frameResources.TemporalGaussianDescriptor.Gpu); - context.CommandList.RSSetViewports(viewport); - context.CommandList.RSSetScissorRects(scissorRect); - context.CommandList.OMSetRenderTargets( - [ - sceneRenderTarget.RenderTargetView.Cpu, - sceneMetadataRenderTarget.RenderTargetView.Cpu, - sceneControlRenderTarget.RenderTargetView.Cpu, - sceneReservoirGuideRenderTarget.RenderTargetView.Cpu, - ], - sceneDepthStencilView.Cpu); - context.CommandList.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); - context.CommandList.DrawInstanced(3, 1, 0, 0); - - for (var sdfIndex = 0; sdfIndex < sdfProxyPipelineStates.Length; sdfIndex++) - { - context.CommandList.SetPipelineState(sdfProxyPipelineStates[sdfIndex]!); - context.CommandList.DrawInstanced(6, 1, 0, 0); - } - - if (temporalGaussianCount > 0) - { - context.CommandList.SetPipelineState(temporalGaussianPipelineState!); - context.CommandList.DrawInstanced(6, (uint)temporalGaussianCount, 0, 0); - } - - if (visibleFractalSplatCount > 0 && fractalSplatBuffer is not null && fractalSdfReservoirBuffer is not null && fractalPbrReservoirBuffer is not null && fractalRadiosityReservoirBuffer is not null) - { - fractalSplatBuffer.Transition(context.CommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - fractalSdfReservoirBuffer.Transition(context.CommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - fractalPbrReservoirBuffer.Transition(context.CommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - fractalRadiosityReservoirBuffer.Transition(context.CommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - context.CommandList.SetGraphicsRootShaderResourceView(RootFractalSplatSrv, fractalSplatBuffer.Resource.GPUVirtualAddress); - context.CommandList.SetGraphicsRootShaderResourceView(RootFractalSdfReservoirSrv, fractalSdfReservoirBuffer.Resource.GPUVirtualAddress); - context.CommandList.SetGraphicsRootShaderResourceView(RootFractalPbrReservoirSrv, fractalPbrReservoirBuffer.Resource.GPUVirtualAddress); - context.CommandList.SetGraphicsRootShaderResourceView(RootFractalRadiosityReservoirSrv, fractalRadiosityReservoirBuffer.Resource.GPUVirtualAddress); - context.CommandList.SetPipelineState(fractalSurfaceSplatRenderPipelineState!); - context.CommandList.DrawInstanced(6, (uint)visibleFractalSplatCount, 0, 0); - context.CommandList.SetPipelineState(fractalTransparentSplatRenderPipelineState!); - context.CommandList.DrawInstanced(6, (uint)visibleFractalSplatCount, 0, 0); - } - } - finally - { - context.CommandList.EndEvent(); - } - - RenderBloom(context.CommandList, frameResources); - PresentBackBuffer(context, frameResources); - } - - private void RenderBloom(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) - { - activeCommandList.BeginEvent("Bloom Pyramid"); - try - { - activeCommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); - activeCommandList.SetGraphicsRootSignature(fullscreenRootSignature); - activeCommandList.SetGraphicsRootDescriptorTable(RootFrameConstants, frameResources.FrameConstantsDescriptor.Gpu); - sceneRenderTarget.Transition(activeCommandList, ResourceStates.PixelShaderResource); - - for (var level = 0; level < BloomLevelCount; level++) - { - var sourceDescriptor = level == 0 - ? frameResources.SceneDescriptor - : frameResources.BloomDescriptors[level - 1]; - var pipelineState = level == 0 - ? bloomPrefilterPipelineState! - : bloomDownsamplePipelineState!; - - DrawPostToTarget( - activeCommandList, - bloomRenderTargets[level], - sourceDescriptor, - pipelineState); - bloomRenderTargets[level].Transition(activeCommandList, ResourceStates.PixelShaderResource); - - DrawPostToTarget( - activeCommandList, - bloomScratchTargets[level], - frameResources.BloomDescriptors[level], - bloomBlurHorizontalPipelineState!); - bloomScratchTargets[level].Transition(activeCommandList, ResourceStates.PixelShaderResource); - - DrawPostToTarget( - activeCommandList, - bloomRenderTargets[level], - frameResources.BloomScratchDescriptors[level], - bloomBlurVerticalPipelineState!); - bloomRenderTargets[level].Transition(activeCommandList, ResourceStates.PixelShaderResource); - } - } - finally - { - activeCommandList.EndEvent(); - } - } - - private void DrawPostToTarget( - ID3D12GraphicsCommandList activeCommandList, - D3D12RenderTarget target, - D3D12DescriptorSlot sourceDescriptor, - ID3D12PipelineState pipelineState) - { - var targetViewport = new Viewport(0.0f, 0.0f, target.Width, target.Height); - var targetScissorRect = new RawRect(0, 0, target.Width, target.Height); - target.Transition(activeCommandList, ResourceStates.RenderTarget); - activeCommandList.ClearRenderTargetView(target.RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); - activeCommandList.SetPipelineState(pipelineState); - activeCommandList.SetGraphicsRootDescriptorTable(RootSourceTexture, sourceDescriptor.Gpu); - activeCommandList.RSSetViewports(targetViewport); - activeCommandList.RSSetScissorRects(targetScissorRect); - activeCommandList.OMSetRenderTargets(target.RenderTargetView.Cpu, null); - activeCommandList.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); - activeCommandList.DrawInstanced(3, 1, 0, 0); - } - - private void PresentBackBuffer(D3D12PassContext context, FrameResources frameResources) - { - context.CommandList.BeginEvent("Present Pass"); - try - { - var historyReadIndex = temporalFrameIndex & 1; - var historyWriteIndex = 1 - historyReadIndex; - - sceneRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); - sceneMetadataRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); - sceneControlRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); - sceneReservoirGuideRenderTarget.Transition(context.CommandList, ResourceStates.PixelShaderResource); - historyRenderTargets[historyReadIndex].Transition(context.CommandList, ResourceStates.PixelShaderResource); - historyMetadataRenderTargets[historyReadIndex].Transition(context.CommandList, ResourceStates.PixelShaderResource); - historyControlRenderTargets[historyReadIndex].Transition(context.CommandList, ResourceStates.PixelShaderResource); - historyReservoirGuideRenderTargets[historyReadIndex].Transition(context.CommandList, ResourceStates.PixelShaderResource); - historyRenderTargets[historyWriteIndex].Transition(context.CommandList, ResourceStates.RenderTarget); - historyMetadataRenderTargets[historyWriteIndex].Transition(context.CommandList, ResourceStates.RenderTarget); - historyControlRenderTargets[historyWriteIndex].Transition(context.CommandList, ResourceStates.RenderTarget); - historyReservoirGuideRenderTargets[historyWriteIndex].Transition(context.CommandList, ResourceStates.RenderTarget); - context.CommandList.ClearRenderTargetView(historyRenderTargets[historyWriteIndex].RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); - context.CommandList.ClearRenderTargetView(historyMetadataRenderTargets[historyWriteIndex].RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); - context.CommandList.ClearRenderTargetView(historyControlRenderTargets[historyWriteIndex].RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); - context.CommandList.ClearRenderTargetView(historyReservoirGuideRenderTargets[historyWriteIndex].RenderTargetView.Cpu, new Color4(1.0f, 0.0f, 1.0f, 0.0f)); - - context.BackBuffer.Transition(context.CommandList, ResourceStates.RenderTarget); - context.CommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); - context.CommandList.SetPipelineState(resolvePipelineState!); - context.CommandList.SetGraphicsRootSignature(fullscreenRootSignature); - context.CommandList.SetGraphicsRootDescriptorTable(RootFrameConstants, frameResources.FrameConstantsDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootSourceTexture, frameResources.SceneDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootBloom, frameResources.BloomPresentationDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootCurrentSceneMetadata, frameResources.SceneMetadataDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootCurrentSceneControl, frameResources.SceneControlDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootHistory, frameResources.HistoryDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootHistoryMetadata, frameResources.HistoryMetadataDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootHistoryControl, frameResources.HistoryControlDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootSdfObjects, frameResources.SdfObjectDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootTemporalGaussians, frameResources.TemporalGaussianDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootCurrentReservoirGuide, frameResources.SceneReservoirGuideDescriptor.Gpu); - context.CommandList.SetGraphicsRootDescriptorTable(RootHistoryReservoirGuide, frameResources.HistoryReservoirGuideDescriptor.Gpu); - - context.CommandList.RSSetViewports(viewport); - context.CommandList.RSSetScissorRects(scissorRect); - context.CommandList.OMSetRenderTargets( - [ - context.RenderTargetView, - historyRenderTargets[historyWriteIndex].RenderTargetView.Cpu, - historyMetadataRenderTargets[historyWriteIndex].RenderTargetView.Cpu, - historyControlRenderTargets[historyWriteIndex].RenderTargetView.Cpu, - historyReservoirGuideRenderTargets[historyWriteIndex].RenderTargetView.Cpu, - ], - null); - context.CommandList.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); - context.CommandList.DrawInstanced(3, 1, 0, 0); - } - finally - { - context.CommandList.EndEvent(); - } - } - - private void UploadSceneStructuredResources(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) - { - activeCommandList.BeginEvent("SDF State Upload"); - try - { - sdfLightBuffer.Upload(activeCommandList, frameResources.UploadRing, sdfLights); - sdfObjectBuffer.Upload(activeCommandList, frameResources.UploadRing, sdfObjects); - gpuSensorCameraBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, gpuSensorCameras.AsSpan(0, gpuSensorCameraCount)); - acousticConstraintBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, acousticConstraints.AsSpan(0, acousticConstraintCount)); - if (temporalGaussiansGpuGenerated) - { - if (gpuFusionPointCount > 0) - { - gpuFusionPointBuffer.UploadPartialBytes( - activeCommandList, - frameResources.UploadRing, - gpuFusionPointSource.Buffer, - gpuFusionPointCount, - gpuFusionPointSource.StrideBytes); - } - else - { - gpuFusionSeedBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, gpuFusionSeeds.AsSpan(0, gpuFusionSeedCount)); - } - } - else - { - temporalGaussianBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, temporalGaussians.AsSpan(0, temporalGaussianCount)); - } - } - finally - { - activeCommandList.EndEvent(); - } - } - - private void DispatchLocalCastGpuFusion(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) - { - if (!temporalGaussiansGpuGenerated || temporalGaussianCount <= 0) - { - return; - } - - activeCommandList.BeginEvent("LocalCast GPU Fusion"); - try - { - gpuFusionSeedBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - gpuFusionPointBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - temporalGaussianBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - activeCommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); - activeCommandList.SetComputeRootSignature(localCastFusionRootSignature); - activeCommandList.SetPipelineState(localCastFusionPipelineState!); - activeCommandList.SetComputeRootDescriptorTable(RootFusionFrameConstants, frameResources.FrameConstantsDescriptor.Gpu); - activeCommandList.SetComputeRootDescriptorTable(RootFusionSeeds, frameResources.GpuFusionSeedDescriptor.Gpu); - activeCommandList.SetComputeRootDescriptorTable(RootFusionSensorCameras, frameResources.GpuSensorCameraDescriptor.Gpu); - activeCommandList.SetComputeRootDescriptorTable(RootFusionSensorTextures, frameResources.GpuSensorTextureDescriptor.Gpu); - activeCommandList.SetComputeRootDescriptorTable(RootFusionAcousticConstraints, frameResources.AcousticConstraintDescriptor.Gpu); - activeCommandList.SetComputeRootDescriptorTable(RootFusionOutput, frameResources.TemporalGaussianUnorderedAccessDescriptor.Gpu); - activeCommandList.SetComputeRootDescriptorTable(RootFusionNativePoints, frameResources.GpuFusionPointDescriptor.Gpu); - activeCommandList.Dispatch((uint)((temporalGaussianCount + 127) / 128), 1, 1); - temporalGaussianBuffer.Transition(activeCommandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - } - finally - { - activeCommandList.EndEvent(); - } - } - - private void DispatchFractalReservoirs(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) - { - if (!activeFractalReservoirField.HasInput || - fractalSplatBuffer is null || - fractalSdfReservoirBuffer is null || - fractalPbrReservoirBuffer is null || - fractalRadiosityReservoirBuffer is null || - fractalFlameStateBuffer is null || - fractalProgramTransformBuffer is null) - { - return; - } - - activeCommandList.BeginEvent("Fractal Reservoir GPU Update"); - try - { - if (activeFractalProgramTransforms.Length > 0) - { - fractalProgramTransformBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, activeFractalProgramTransforms); - } - else - { - ReadOnlySpan emptyProgram = [default]; - fractalProgramTransformBuffer.UploadPartial(activeCommandList, frameResources.UploadRing, emptyProgram); - } - - fractalSplatBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - fractalSdfReservoirBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - fractalPbrReservoirBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - fractalRadiosityReservoirBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - fractalFlameStateBuffer.Transition(activeCommandList, ResourceStates.UnorderedAccess); - activeCommandList.SetComputeRootSignature(fractalReservoirRootSignature); - var splatDispatchCount = temporalFrameIndex == 0 - ? activeFractalReservoirField.SplatCount - : activeFractalReservoirField.SplatUpdatesPerFrame; - BindFractalReservoirConstants(activeCommandList, splatDispatchCount); - activeCommandList.SetComputeRootUnorderedAccessView(RootFractalSplats, fractalSplatBuffer.Resource.GPUVirtualAddress); - activeCommandList.SetComputeRootUnorderedAccessView(RootFractalSdfReservoirs, fractalSdfReservoirBuffer.Resource.GPUVirtualAddress); - activeCommandList.SetComputeRootUnorderedAccessView(RootFractalPbrReservoirs, fractalPbrReservoirBuffer.Resource.GPUVirtualAddress); - activeCommandList.SetComputeRootUnorderedAccessView(RootFractalRadiosityReservoirs, fractalRadiosityReservoirBuffer.Resource.GPUVirtualAddress); - activeCommandList.SetComputeRootUnorderedAccessView(RootFractalFlameStates, fractalFlameStateBuffer.Resource.GPUVirtualAddress); - activeCommandList.SetComputeRootShaderResourceView(RootFractalProgramTransforms, fractalProgramTransformBuffer.Resource.GPUVirtualAddress); - Dispatch(fractalSplatPipelineState!, splatDispatchCount); - activeCommandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(fractalSplatBuffer.Resource)); - Dispatch(fractalSdfReservoirPipelineState!, activeFractalReservoirField.ReservoirUpdatesPerPass); - Dispatch(fractalPbrReservoirPipelineState!, activeFractalReservoirField.ReservoirUpdatesPerPass); - Dispatch(fractalRadiosityReservoirPipelineState!, activeFractalReservoirField.ReservoirUpdatesPerPass); - } - finally - { - activeCommandList.EndEvent(); - } - - void Dispatch(ID3D12PipelineState pipelineState, int elementCount) - { - activeCommandList.SetPipelineState(pipelineState); - activeCommandList.Dispatch((uint)((elementCount + 255) / 256), 1, 1); - } - } - - private void BindFractalReservoirConstants(ID3D12GraphicsCommandList activeCommandList, int splatDispatchCount) - { - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, (uint)activeFractalReservoirField.SplatCount, 0); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, (uint)temporalFrameIndex, 1); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, (uint)activeFractalReservoirField.Depth, 2); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, activeFractalReservoirField.Seed, 3); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, (uint)activeFractalReservoirField.CandidatesPerReservoirUpdate, 4); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, (uint)activeFractalReservoirField.ReservoirUpdatesPerPass, 5); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, (uint)activeFractalProgramTransforms.Length, 6); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, activeFractalProgramTransforms.Length > 0 ? 1u : 0u, 7); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, (uint)splatDispatchCount, 8); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, BitConverter.SingleToUInt32Bits(activeFractalReservoirField.PriorityFocus.X), 9); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, BitConverter.SingleToUInt32Bits(activeFractalReservoirField.PriorityFocus.Y), 10); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, BitConverter.SingleToUInt32Bits(activeFractalReservoirField.PriorityFocus.Z), 11); - activeCommandList.SetComputeRoot32BitConstant(RootFractalConstants, BitConverter.SingleToUInt32Bits(activeFractalReservoirField.PriorityFocus.W), 12); - } - - private void CreateGpuSensorTextureViews(AquariumGpuSensorFrame sensorFrame, D3D12DescriptorSlot firstDescriptor) - { - var activeHandles = new HashSet(StringComparer.Ordinal); - gpuSensorTextureCount = Math.Min(sensorFrame.ExternalTextures.Count, MaxGpuSensorTextureCount); - - for (var index = 0; index < MaxGpuSensorTextureCount; index++) - { - var descriptor = frames[frameIndex].TransientShaderDescriptors.Offset(firstDescriptor, index); - if (index >= gpuSensorTextureCount) - { - CreateNullSensorTextureView(descriptor); - continue; - } - - var texture = sensorFrame.ExternalTextures[index]; - var cacheKey = D3D12ExternalSensorTexture.CacheKey(texture); - activeHandles.Add(cacheKey); - if (!externalSensorTextures.TryGetValue(cacheKey, out var externalTexture) - || !externalTexture.Matches(texture)) - { - externalTexture?.Dispose(); - if (D3D12ExternalSensorTexture.TryOpen(device, texture, out var openedTexture)) - { - externalTexture = openedTexture; - externalSensorTextures[cacheKey] = externalTexture; - } - else - { - externalSensorTextures.Remove(cacheKey); - CreateNullSensorTextureView(descriptor); - continue; - } - } - - externalTexture.UpdateTimestamp(texture.TimestampNs); - externalTexture.CreateShaderResourceView(device, descriptor); - } - - foreach (var staleHandle in externalSensorTextures.Keys.Where(handle => !activeHandles.Contains(handle)).ToArray()) - { - externalSensorTextures[staleHandle].Dispose(); - externalSensorTextures.Remove(staleHandle); - } - } - - private void CreateNullSensorTextureView(D3D12DescriptorSlot descriptor) - { - device.CreateShaderResourceView( - null, - new ShaderResourceViewDescription - { - Format = Format.B8G8R8A8_UNorm, - ViewDimension = Vortice.Direct3D12.ShaderResourceViewDimension.Texture2D, - Shader4ComponentMapping = ShaderComponentMapping.Default, - Texture2D = new Texture2DShaderResourceView { MipLevels = 1 }, - }, - descriptor.Cpu); - } - - private void RenderHeightField(ID3D12GraphicsCommandList activeCommandList, FrameResources frameResources) - { - var viewport = new Viewport(0.0f, 0.0f, HeightFieldTextureSize, HeightFieldTextureSize); - var scissorRect = new RawRect(0, 0, HeightFieldTextureSize, HeightFieldTextureSize); - - activeCommandList.BeginEvent("Height Field Pass"); - try - { - heightFieldRenderTarget.Transition(activeCommandList, ResourceStates.RenderTarget); - activeCommandList.ClearRenderTargetView(heightFieldRenderTarget.RenderTargetView.Cpu, new Color4(0.0f, 0.0f, 0.0f, 1.0f)); - activeCommandList.SetDescriptorHeaps(frameResources.TransientShaderDescriptors.Heap); - activeCommandList.SetPipelineState(heightFieldBasePipelineState!); - activeCommandList.SetGraphicsRootSignature(fullscreenRootSignature); - activeCommandList.SetGraphicsRootDescriptorTable(RootFrameConstants, frameResources.FrameConstantsDescriptor.Gpu); - activeCommandList.RSSetViewports(viewport); - activeCommandList.RSSetScissorRects(scissorRect); - activeCommandList.OMSetRenderTargets(heightFieldRenderTarget.RenderTargetView.Cpu, null); - activeCommandList.IASetPrimitiveTopology(PrimitiveTopology.TriangleList); - activeCommandList.DrawInstanced(3, 1, 0, 0); - activeCommandList.SetPipelineState(heightFieldBrushPipelineState!); - activeCommandList.SetGraphicsRootDescriptorTable(RootHeightFieldBrushes, frameResources.HeightFieldBrushConstantsDescriptor.Gpu); - activeCommandList.DrawInstanced(6, D3D12HeightFieldBrushConstants.MaxBrushCount, 0, 0); - } - finally - { - activeCommandList.EndEvent(); - } - } - - private void CopySceneState(AquariumSceneState scene) - { - Array.Clear(sdfObjects); - Array.Clear(sdfLights); - temporalGaussianCount = 0; - gpuSensorCameraCount = 0; - gpuSensorTextureCount = 0; - acousticConstraintCount = 0; - gpuFusionSeedCount = 0; - gpuFusionPointCount = 0; - gpuFusionPointSource = default; - temporalGaussiansGpuGenerated = false; - activeFractalReservoirField = scene.FractalReservoirField.HasInput - ? scene.FractalReservoirField - : AquariumFractalReservoirField.Empty; - activeFractalProgramTransforms = activeFractalReservoirField.HasInput && scene.FractalReservoirField.ProgramTransforms.Count > 0 - ? scene.FractalReservoirField.ProgramTransforms as AquariumPackedFractalIfsTransform[] ?? scene.FractalReservoirField.ProgramTransforms.ToArray() - : []; - visibleFractalSplatCount = activeFractalReservoirField.HasInput - ? Math.Min(activeFractalReservoirField.SplatCount, MaxVisibleFractalSplatCount) - : 0; - heightFieldBrushConstants = D3D12HeightFieldBrushConstants.FromBrushes(scene.HeightFieldBrushes); - - var objectCount = Math.Min(scene.SdfObjects.Count, MaxSdfObjectCount); - for (var index = 0; index < objectCount; index++) - { - sdfObjects[index] = scene.SdfObjects[index]; - } - - var lightCount = Math.Min(scene.SdfLights.Count, MaxSdfLightCount); - for (var index = 0; index < lightCount; index++) - { - sdfLights[index] = scene.SdfLights[index]; - } - - gpuSensorCameraCount = Math.Min(scene.GpuSensorFrame.Cameras.Count, MaxGpuSensorCameraCount); - for (var index = 0; index < gpuSensorCameraCount; index++) - { - gpuSensorCameras[index] = ToGpuSensorCameraPacket(scene.GpuSensorFrame.Cameras[index]); - } - - acousticConstraintCount = Math.Min(scene.AcousticFieldFrame.Constraints.Count, MaxAcousticConstraintCount); - for (var index = 0; index < acousticConstraintCount; index++) - { - acousticConstraints[index] = ToAcousticConstraintPacket(scene.AcousticFieldFrame.Constraints[index]); - } - - var clapCapacity = MaxAcousticConstraintCount - acousticConstraintCount; - var clapCount = Math.Min(scene.CalibrationEventFrame.ClapEvents.Count, clapCapacity); - for (var index = 0; index < clapCount; index++) - { - acousticConstraints[acousticConstraintCount + index] = ToClapConstraintPacket(scene.CalibrationEventFrame.ClapEvents[index]); - } - - acousticConstraintCount += clapCount; - - if (scene.GpuFusionField.PointBuffer.HasInput) - { - var pointCount = Math.Min(scene.GpuFusionField.PointBuffer.Count, MaxTemporalGaussianCount); - temporalGaussianCount = pointCount; - gpuFusionPointCount = pointCount; - gpuFusionPointSource = scene.GpuFusionField.PointBuffer with { Count = pointCount }; - temporalGaussiansGpuGenerated = true; - return; - } - - if (scene.GpuFusionField.Seeds.Count > 0) - { - var seedCount = Math.Min(scene.GpuFusionField.Seeds.Count, MaxTemporalGaussianCount); - temporalGaussianCount = seedCount; - gpuFusionSeedCount = seedCount; - temporalGaussiansGpuGenerated = true; - for (var index = 0; index < seedCount; index++) - { - gpuFusionSeeds[index] = ToGpuFusionSeedPacket(scene.GpuFusionField.Seeds[index]); - } - return; - } - - gpuSensorTextureCount = Math.Min(scene.GpuSensorFrame.ExternalTextures.Count, MaxGpuSensorTextureCount); - if (gpuSensorTextureCount > 0 && gpuSensorCameraCount > 0) - { - temporalGaussianCount = Math.Min(MaxTemporalGaussianCount, gpuSensorTextureCount * GpuSensorSamplesPerTexture); - temporalGaussiansGpuGenerated = true; - return; - } - - var gaussianCount = Math.Min(scene.TemporalGaussianField.Gaussians.Count, MaxTemporalGaussianCount); - temporalGaussianCount = gaussianCount; - for (var index = 0; index < gaussianCount; index++) - { - temporalGaussians[index] = ToTemporalGaussianPacket(scene.TemporalGaussianField.Gaussians[index]); - } - } - - private static D3D12AcousticConstraintPacket ToAcousticConstraintPacket(AquariumAcousticConstraint constraint) - { - var confidence = Math.Clamp(constraint.Confidence, 0.0f, 1.0f); - return new D3D12AcousticConstraintPacket( - new Vector4(constraint.Position, MathF.Max(0.001f, constraint.RadiusMeters)), - new Vector4(constraint.Velocity, confidence), - new Vector4((int)constraint.Kind, constraint.TimestampNs * 0.000000001f, 0.0f, 0.0f)); - } - - private static D3D12AcousticConstraintPacket ToClapConstraintPacket(AquariumClapCalibrationEvent clap) - { - var confidence = Math.Clamp(clap.VisualConfidence * clap.AcousticConfidence, 0.0f, 1.0f); - return new D3D12AcousticConstraintPacket( - new Vector4(clap.Position, 0.24f), - new Vector4(Vector3.Zero, confidence), - new Vector4((int)AquariumAcousticConstraintKind.ClapImpact, clap.AcousticOracleNs * 0.000000001f, clap.TimingUncertaintyMicroseconds, 0.0f)); - } - - private static D3D12GpuSensorCameraPacket ToGpuSensorCameraPacket(AquariumGpuSensorCamera camera) - { - static Vector4 Row0(Matrix4x4 matrix) => new(matrix.M11, matrix.M12, matrix.M13, matrix.M14); - static Vector4 Row1(Matrix4x4 matrix) => new(matrix.M21, matrix.M22, matrix.M23, matrix.M24); - static Vector4 Row2(Matrix4x4 matrix) => new(matrix.M31, matrix.M32, matrix.M33, matrix.M34); - - return new D3D12GpuSensorCameraPacket( - camera.Intrinsics, - camera.Distortion01, - camera.Distortion23, - new Vector4( - Math.Max(0, camera.Width), - Math.Max(0, camera.Height), - (int)camera.Kind, - camera.TextureCount), - new Vector4( - Math.Max(0, camera.FirstTextureIndex), - camera.TextureCount, - camera.TimestampNs * 0.000000001f, - 0.0f), - Row0(camera.WorldFromSensor), - Row1(camera.WorldFromSensor), - Row2(camera.WorldFromSensor), - Row0(camera.SensorFromWorld), - Row1(camera.SensorFromWorld), - Row2(camera.SensorFromWorld)); - } - - private static D3D12GpuFusionSeedPacket ToGpuFusionSeedPacket(AquariumGpuFusionSeed seed) - { - return new D3D12GpuFusionSeedPacket( - new Vector4(seed.Center, Math.Clamp(seed.HistoryWeight, 0.0f, 1.0f)), - new Vector4(seed.PreviousCenter, seed.FieldId), - new Vector4(seed.Velocity, Math.Clamp(seed.Confidence, 0.0f, 1.0f)), - new Vector4(Vector3.Max(seed.Radii, new Vector3(0.0001f)), MathF.Max(0.0001f, seed.Falloff)), - seed.ColorOpacity, - new Vector4(MathF.Max(0.0001f, seed.ShapePower), 0.0f, 0.0f, 0.0f)); - } - - private static D3D12TemporalGaussianPacket ToTemporalGaussianPacket(AquariumTemporalSdfGaussian gaussian) - { - var orientation = gaussian.Orientation.LengthSquared() <= 0.000001f - ? Quaternion.Identity - : Quaternion.Normalize(gaussian.Orientation); - return new D3D12TemporalGaussianPacket( - new Vector4(gaussian.Center, gaussian.HistoryWeight), - new Vector4(gaussian.PreviousCenter, gaussian.FieldId), - new Vector4(gaussian.Velocity, gaussian.Confidence), - new Vector4(gaussian.Radii, gaussian.Falloff), - new Vector4(orientation.X, orientation.Y, orientation.Z, orientation.W), - gaussian.ColorOpacity, - new Vector4(gaussian.ShapePower, 0.0f, 0.0f, 0.0f)); - } - - private static float SceneFlags(AquariumSceneState scene) - { - var flags = 0; - if (scene.TraceHeightFieldSurface) - { - flags |= 1; - } - - if (scene.UseStarfieldBackground) - { - flags |= 2; - } - - return flags; - } - - private void SignalFrame(FrameResources frameResources) - { - var signalValue = ++fenceValue; - commandQueue.Signal(fence, signalValue).CheckError(); - frameResources.FenceValue = signalValue; - } - - private float lastCapacityReportSecond = -1.0f; - - private void ReportCapacityOncePerSecond(float timeSeconds, FrameResources frameResources) - { - if (timeSeconds - lastCapacityReportSecond < 1.0f) - { - return; - } - - lastCapacityReportSecond = timeSeconds; - Console.WriteLine( - $"D3D12 capacity: {frameResources.UploadRing.Describe()}; " + - $"{frameResources.TransientShaderDescriptors.Describe()}; " + - $"{staticShaderDescriptorArena.Describe()}; " + - $"{renderTargetViewArena.Describe()}"); - if (activeFractalReservoirField.HasInput && fractalSplatBuffer is not null && fractalSdfReservoirBuffer is not null && fractalPbrReservoirBuffer is not null && fractalRadiosityReservoirBuffer is not null && fractalFlameStateBuffer is not null) - { - var residentBytes = - fractalSplatBuffer.SizeBytes + - fractalSdfReservoirBuffer.SizeBytes + - fractalPbrReservoirBuffer.SizeBytes + - fractalRadiosityReservoirBuffer.SizeBytes + - fractalFlameStateBuffer.SizeBytes; - Console.WriteLine( - $"D3D12 fractal reservoirs: splats {activeFractalReservoirField.SplatCount:N0}; " + - $"visible {visibleFractalSplatCount:N0}; " + - $"program transforms {activeFractalProgramTransforms.Length:N0}; " + - $"splat updates/frame {activeFractalReservoirField.SplatUpdatesPerFrame:N0}; " + - $"updates/pass {activeFractalReservoirField.ReservoirUpdatesPerPass:N0}; " + - $"candidates/update {activeFractalReservoirField.CandidatesPerReservoirUpdate}; " + - $"resident {residentBytes / (1024.0 * 1024.0):0.0} MiB"); - } - - if (accumulatedTimingFrames > 0) - { - var scale = 1.0 / accumulatedTimingFrames; - Console.WriteLine( - $"D3D12 CPU timing avg over {accumulatedTimingFrames} frames: " + - $"frame {accumulatedFrameCpuMilliseconds * scale:0.###} ms; " + - $"record {accumulatedRecordCpuMilliseconds * scale:0.###} ms; " + - $"overlay {accumulatedOverlayCpuMilliseconds * scale:0.###} ms"); - accumulatedFrameCpuMilliseconds = 0.0; - accumulatedRecordCpuMilliseconds = 0.0; - accumulatedOverlayCpuMilliseconds = 0.0; - accumulatedTimingFrames = 0; - } - } - - private static double ElapsedMilliseconds(long startTimestamp) - { - return (Stopwatch.GetTimestamp() - startTimestamp) * 1000.0 / Stopwatch.Frequency; - } - - private static string ResolveShaderSourceRoot(string? shaderPath, AquariumShaderManifest manifest) - { - if (!string.IsNullOrWhiteSpace(shaderPath)) - { - var sourceDirectory = Path.GetDirectoryName(Path.GetFullPath(shaderPath)); - if (!string.IsNullOrWhiteSpace(sourceDirectory)) - { - return sourceDirectory; - } - } - - if (!string.IsNullOrWhiteSpace(manifest.ShaderRoot)) - { - return Path.GetFullPath(manifest.ShaderRoot); - } - - return Path.Combine(AppContext.BaseDirectory, "Render", "Shaders"); - } - - private void CaptureShaderWriteTimes() - { - shaderWriteTimesUtc.Clear(); - foreach (var path in shaderPaths.All) - { - shaderWriteTimesUtc[path] = File.GetLastWriteTimeUtc(path); - } - } - - private DateTime LatestShaderWriteTimeUtc() - { - var latest = DateTime.MinValue; - foreach (var path in shaderPaths.All) - { - var writeTime = File.GetLastWriteTimeUtc(path); - if (writeTime > latest) - { - latest = writeTime; - } - } - - return latest; - } - - private bool ShaderSourcesChanged(out DateTime latestWriteTimeUtc) - { - latestWriteTimeUtc = DateTime.MinValue; - foreach (var path in shaderPaths.All) - { - var writeTime = File.GetLastWriteTimeUtc(path); - if (writeTime > latestWriteTimeUtc) - { - latestWriteTimeUtc = writeTime; - } - - if (!shaderWriteTimesUtc.TryGetValue(path, out var previousWriteTime) || writeTime > previousWriteTime) - { - return true; - } - } - - return false; - } - - private void TryHotReloadShaders() - { - var now = shaderReloadClock.Elapsed; - if (now - lastShaderReloadCheck < ShaderReloadPollInterval || pipelineBuildTask is { IsCompleted: false }) - { - return; - } - - lastShaderReloadCheck = now; - try - { - if (!ShaderSourcesChanged(out var latestWriteTimeUtc) || DateTime.UtcNow - latestWriteTimeUtc < ShaderReloadWriteSettleTime) - { - return; - } - - StartPipelineBuild("hot reload"); - shaderReloadFailureReported = false; - } - catch (Exception error) - { - if (!shaderReloadFailureReported) - { - Console.Error.WriteLine($"D3D12 shader hot reload cannot stat sources in {shaderSourceRoot}: {error.Message}"); - shaderReloadFailureReported = true; - } - } - } - - private void StartPipelineBuild(string reason) - { - if (pipelineBuildTask is { IsCompleted: false }) - { - return; - } - - var paths = shaderPaths; - LatestShaderWriteTimeUtc(); - pipelineBuildInProgressReported = false; - pipelineBuildTask = Task.Run(() => CreatePipelineSet(paths)); - Console.WriteLine($"D3D12 shader pipeline build started ({reason}): {shaderSourceRoot}"); - } - - private void ApplyCompletedPipelineBuild() - { - var task = pipelineBuildTask; - if (task is null || !task.IsCompleted) - { - if (!PipelinesReady && !pipelineBuildInProgressReported) - { - Console.WriteLine("D3D12 shader pipeline build still running; waiting behind startup splash."); - pipelineBuildInProgressReported = true; - } - - return; - } - - pipelineBuildTask = null; - if (task.IsFaulted || task.IsCanceled) - { - var error = task.Exception?.GetBaseException() ?? new InvalidOperationException("D3D12 shader pipeline build was canceled."); - if (PipelinesReady) - { - Console.Error.WriteLine($"D3D12 shader hot reload failed; keeping previous pipelines. {error.Message}"); - } - else - { - Console.Error.WriteLine($"D3D12 initial shader pipeline build failed; retrying after source change. {error.Message}"); - } - - shaderReloadFailureReported = true; - return; - } - - var replacement = task.Result; - var oldPipelines = CapturePipelineSetOrNull(); - if (oldPipelines is not null) - { - WaitForGpu(); - } - - ApplyPipelineSet(replacement); - CaptureShaderWriteTimes(); - oldPipelines?.Dispose(); - shaderReloadFailureReported = false; - pipelineBuildInProgressReported = false; - if (initialPipelineReadyReported) - { - Console.WriteLine($"D3D12 shader hot reload applied: {shaderSourceRoot}"); - } - else - { - Console.WriteLine($"D3D12 shader pipelines ready: {shaderSourceRoot}"); - initialPipelineReadyReported = true; - } - } - - private D3D12PipelineSet? CapturePipelineSetOrNull() - { - return PipelinesReady - ? new D3D12PipelineSet( - heightFieldBasePipelineState!, - heightFieldBrushPipelineState!, - scenePipelineState!, - temporalGaussianPipelineState!, - localCastFusionPipelineState!, - fractalSurfaceSplatRenderPipelineState!, - fractalTransparentSplatRenderPipelineState!, - fractalSplatPipelineState!, - fractalSdfReservoirPipelineState!, - fractalPbrReservoirPipelineState!, - fractalRadiosityReservoirPipelineState!, - sdfProxyPipelineStates.Select(pipeline => pipeline!).ToArray(), - bloomPrefilterPipelineState!, - bloomDownsamplePipelineState!, - bloomBlurHorizontalPipelineState!, - bloomBlurVerticalPipelineState!, - resolvePipelineState!) - : null; - } - - private void ApplyPipelineSet(D3D12PipelineSet pipelines) - { - heightFieldBasePipelineState = pipelines.HeightFieldBase; - heightFieldBrushPipelineState = pipelines.HeightFieldBrush; - scenePipelineState = pipelines.Scene; - temporalGaussianPipelineState = pipelines.TemporalGaussian; - localCastFusionPipelineState = pipelines.LocalCastFusion; - fractalSurfaceSplatRenderPipelineState = pipelines.FractalSurfaceSplatRender; - fractalTransparentSplatRenderPipelineState = pipelines.FractalTransparentSplatRender; - fractalSplatPipelineState = pipelines.FractalSplat; - fractalSdfReservoirPipelineState = pipelines.FractalSdfReservoir; - fractalPbrReservoirPipelineState = pipelines.FractalPbrReservoir; - fractalRadiosityReservoirPipelineState = pipelines.FractalRadiosityReservoir; - for (var index = 0; index < sdfProxyPipelineStates.Length; index++) - { - sdfProxyPipelineStates[index] = pipelines.SdfProxies[index]; - } - bloomPrefilterPipelineState = pipelines.BloomPrefilter; - bloomDownsamplePipelineState = pipelines.BloomDownsample; - bloomBlurHorizontalPipelineState = pipelines.BloomBlurHorizontal; - bloomBlurVerticalPipelineState = pipelines.BloomBlurVertical; - resolvePipelineState = pipelines.Resolve; - } - - private void DisposePipelineStates() - { - CapturePipelineSetOrNull()?.Dispose(); - heightFieldBasePipelineState = null; - heightFieldBrushPipelineState = null; - scenePipelineState = null; - temporalGaussianPipelineState = null; - localCastFusionPipelineState = null; - fractalSurfaceSplatRenderPipelineState = null; - fractalTransparentSplatRenderPipelineState = null; - fractalSplatPipelineState = null; - fractalSdfReservoirPipelineState = null; - fractalPbrReservoirPipelineState = null; - fractalRadiosityReservoirPipelineState = null; - Array.Clear(sdfProxyPipelineStates); - bloomPrefilterPipelineState = null; - bloomDownsamplePipelineState = null; - bloomBlurHorizontalPipelineState = null; - bloomBlurVerticalPipelineState = null; - resolvePipelineState = null; - } - - private void WaitForFrame(FrameResources frameResources) - { - if (frameResources.FenceValue != 0 && fence.CompletedValue < frameResources.FenceValue) - { - fence.SetEventOnCompletion(frameResources.FenceValue, fenceEvent.SafeWaitHandle.DangerousGetHandle()).CheckError(); - fenceEvent.WaitOne(); - } - } - - private void WaitForGpu() - { - var signalValue = ++fenceValue; - commandQueue.Signal(fence, signalValue).CheckError(); - fence.SetEventOnCompletion(signalValue, fenceEvent.SafeWaitHandle.DangerousGetHandle()).CheckError(); - fenceEvent.WaitOne(); - } - - private static int AlignTo(int value, int alignment) - { - return (value + alignment - 1) & ~(alignment - 1); - } - - private static void ReportStartupProgress(Action? startupProgress, string message) - { - startupProgress?.Invoke(message); - Console.WriteLine(message); - } - - private D3D12DescriptorArena CreateRenderTargetViewArena() - { - return new D3D12DescriptorArena( - device, - DescriptorHeapType.RenderTargetView, - 64, - DescriptorHeapFlags.None, - "Aquarium D3D12 RTV Arena"); - } - - private D3D12DescriptorArena CreateDepthStencilViewArena() - { - return new D3D12DescriptorArena( - device, - DescriptorHeapType.DepthStencilView, - 8, - DescriptorHeapFlags.None, - "Aquarium D3D12 DSV Arena"); - } - - private D3D12DescriptorArena CreateStaticShaderDescriptorArena() - { - return new D3D12DescriptorArena( - device, - DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, - 64, - DescriptorHeapFlags.ShaderVisible, - "Aquarium D3D12 Static Shader Descriptor Arena"); - } - - private ID3D12RootSignature CreateFullscreenRootSignature() - { - var constantBufferRange = new DescriptorRange( - DescriptorRangeType.ConstantBufferView, - 1, - 0, - 0, - D3D12.DescriptorRangeOffsetAppend); - var sourceTextureRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 0, - 0, - D3D12.DescriptorRangeOffsetAppend); - var heightFieldBrushRange = new DescriptorRange( - DescriptorRangeType.ConstantBufferView, - 1, - 1, - 0, - D3D12.DescriptorRangeOffsetAppend); - var sdfLightRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 12, - 0, - D3D12.DescriptorRangeOffsetAppend); - var bloomRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - BloomLevelCount, - 9, - 0, - D3D12.DescriptorRangeOffsetAppend); - var currentSceneMetadataRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 5, - 0, - D3D12.DescriptorRangeOffsetAppend); - var currentSceneControlRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 7, - 0, - D3D12.DescriptorRangeOffsetAppend); - var historyRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 4, - 0, - D3D12.DescriptorRangeOffsetAppend); - var historyMetadataRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 6, - 0, - D3D12.DescriptorRangeOffsetAppend); - var historyControlRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 8, - 0, - D3D12.DescriptorRangeOffsetAppend); - var currentReservoirGuideRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 26, - 0, - D3D12.DescriptorRangeOffsetAppend); - var historyReservoirGuideRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 27, - 0, - D3D12.DescriptorRangeOffsetAppend); - var studioPmremRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 22, - 0, - D3D12.DescriptorRangeOffsetAppend); - var studioIrradianceRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 23, - 0, - D3D12.DescriptorRangeOffsetAppend); - var sdfObjectRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 24, - 0, - D3D12.DescriptorRangeOffsetAppend); - var temporalGaussianRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 25, - 0, - D3D12.DescriptorRangeOffsetAppend); - var rootParameters = new[] - { - new RootParameter(new RootDescriptorTable([constantBufferRange]), ShaderVisibility.All), - new RootParameter(new RootDescriptorTable([sourceTextureRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([heightFieldBrushRange]), ShaderVisibility.All), - new RootParameter(new RootDescriptorTable([sdfLightRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([bloomRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([currentSceneMetadataRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([currentSceneControlRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([historyRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([historyMetadataRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([historyControlRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([studioPmremRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([studioIrradianceRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([sdfObjectRange]), ShaderVisibility.All), - new RootParameter(new RootDescriptorTable([temporalGaussianRange]), ShaderVisibility.All), - new RootParameter(new RootDescriptorTable([currentReservoirGuideRange]), ShaderVisibility.Pixel), - new RootParameter(new RootDescriptorTable([historyReservoirGuideRange]), ShaderVisibility.Pixel), - new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(38, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(39, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(40, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(41, 0), ShaderVisibility.All), - }; - var staticSamplers = new[] - { - new StaticSamplerDescription( - 0, - Filter.MinMagMipLinear, - TextureAddressMode.Clamp, - TextureAddressMode.Clamp, - TextureAddressMode.Clamp, - 0.0f, - 1, - ComparisonFunction.Never, - StaticBorderColor.TransparentBlack, - 0.0f, - float.MaxValue, - ShaderVisibility.Pixel, - 0), - }; - var description = new RootSignatureDescription( - RootSignatureFlags.AllowInputAssemblerInputLayout, - rootParameters, - staticSamplers); - return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); - } - - private ID3D12RootSignature CreateLocalCastFusionRootSignature() - { - var frameRange = new DescriptorRange( - DescriptorRangeType.ConstantBufferView, - 1, - 0, - 0, - D3D12.DescriptorRangeOffsetAppend); - var seedRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 26, - 0, - D3D12.DescriptorRangeOffsetAppend); - var sensorCameraRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 27, - 0, - D3D12.DescriptorRangeOffsetAppend); - var sensorTextureRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - MaxGpuSensorTextureCount, - 28, - 0, - D3D12.DescriptorRangeOffsetAppend); - var acousticConstraintRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 36, - 0, - D3D12.DescriptorRangeOffsetAppend); - var outputRange = new DescriptorRange( - DescriptorRangeType.UnorderedAccessView, - 1, - 0, - 0, - D3D12.DescriptorRangeOffsetAppend); - var nativePointRange = new DescriptorRange( - DescriptorRangeType.ShaderResourceView, - 1, - 37, - 0, - D3D12.DescriptorRangeOffsetAppend); - var rootParameters = new[] - { - new RootParameter(new RootDescriptorTable([frameRange]), ShaderVisibility.All), - new RootParameter(new RootDescriptorTable([seedRange]), ShaderVisibility.All), - new RootParameter(new RootDescriptorTable([sensorCameraRange]), ShaderVisibility.All), - new RootParameter(new RootDescriptorTable([sensorTextureRange]), ShaderVisibility.All), - new RootParameter(new RootDescriptorTable([acousticConstraintRange]), ShaderVisibility.All), - new RootParameter(new RootDescriptorTable([outputRange]), ShaderVisibility.All), - new RootParameter(new RootDescriptorTable([nativePointRange]), ShaderVisibility.All), - }; - var description = new RootSignatureDescription( - RootSignatureFlags.None, - rootParameters, - []); - return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); - } - - private ID3D12RootSignature CreateFractalReservoirRootSignature() - { - var rootParameters = new[] - { - new RootParameter(new RootConstants(0, 0, 13), ShaderVisibility.All), - new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(0, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(1, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(2, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(3, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(4, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(0, 0), ShaderVisibility.All), - }; - var description = new RootSignatureDescription( - RootSignatureFlags.None, - rootParameters, - []); - return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); - } - - private FrameResources CreateFrameResources(int index) - { - var commandAllocator = device.CreateCommandAllocator(CommandListType.Direct); - commandAllocator.Name = $"Aquarium D3D12 Frame {index} Command Allocator"; - var uploadRing = new D3D12UploadRing(device, 160 * 1024 * 1024, $"Aquarium D3D12 Frame {index} Upload Ring"); - var transientDescriptors = new D3D12DescriptorArena( - device, - DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, - 64, - DescriptorHeapFlags.ShaderVisible, - $"Aquarium D3D12 Frame {index} Transient Shader Descriptor Arena"); - - return new FrameResources(commandAllocator, uploadRing, transientDescriptors); - } - - private ID3D12PipelineState CreateScenePipelineState(string path) - { - return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12ScenePS", [SceneHdrFormat, SceneHdrFormat, SceneHdrFormat, SceneHdrFormat], enableDepth: true); - } - - private ID3D12PipelineState CreateSdfObjectProxyPipelineState(string path) - { - return CreateFullscreenPipelineState(path, "D3D12SdfObjectProxyVS", "D3D12SdfProxyPS", [SceneHdrFormat, SceneHdrFormat, SceneHdrFormat, SceneHdrFormat], enableDepth: true); - } - - private ID3D12PipelineState CreateTemporalGaussianPipelineState(string path) - { - return CreateFullscreenPipelineState(path, "D3D12TemporalGaussianVS", "D3D12TemporalGaussianPS", [SceneHdrFormat, SceneHdrFormat, SceneHdrFormat, SceneHdrFormat], enableDepth: true); - } - - private ID3D12PipelineState CreateFractalSurfaceSplatRenderPipelineState(string path) - { - return CreateFullscreenPipelineState(path, "D3D12FractalSplatVS", "D3D12FractalSurfaceSplatPS", [SceneHdrFormat, SceneHdrFormat, SceneHdrFormat, SceneHdrFormat], enableDepth: true); - } - - private ID3D12PipelineState CreateFractalTransparentSplatRenderPipelineState(string path) - { - return CreateFullscreenPipelineState( - path, - "D3D12FractalSplatVS", - "D3D12FractalTransparentSplatPS", - [SceneHdrFormat, SceneHdrFormat, SceneHdrFormat, SceneHdrFormat], - CreateTransparentFieldBlend(), - enableDepth: false); - } - - private ID3D12PipelineState CreateLocalCastFusionPipelineState(string path) - { - var computeShader = CompileShader(path, "D3D12LocalCastFusionCS", "cs_5_0"); - var description = new ComputePipelineStateDescription - { - RootSignature = localCastFusionRootSignature, - ComputeShader = computeShader, - }; - return device.CreateComputePipelineState(description); - } - - private ID3D12PipelineState CreateFractalReservoirPipelineState(string path, string entryPoint) - { - var computeShader = CompileShader(path, entryPoint, "cs_5_0"); - var description = new ComputePipelineStateDescription - { - RootSignature = fractalReservoirRootSignature, - ComputeShader = computeShader, - }; - return device.CreateComputePipelineState(description); - } - - private ID3D12PipelineState CreateBloomPrefilterPipelineState(string path) - { - return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12BloomPrefilterPS", SceneHdrFormat); - } - - private ID3D12PipelineState CreateBloomDownsamplePipelineState(string path) - { - return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12BloomDownsamplePS", SceneHdrFormat); - } - - private ID3D12PipelineState CreateBloomBlurHorizontalPipelineState(string path) - { - return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12BloomBlurHorizontalPS", SceneHdrFormat); - } - - private ID3D12PipelineState CreateBloomBlurVerticalPipelineState(string path) - { - return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12BloomBlurVerticalPS", SceneHdrFormat); - } - - private ID3D12PipelineState CreateResolvePipelineState(string path) - { - return CreateFullscreenPipelineState( - path, - "FullscreenTriangleVS", - "D3D12ResolvePS", - [Format.B8G8R8A8_UNorm, SceneHdrFormat, SceneHdrFormat, SceneHdrFormat, SceneHdrFormat]); - } - - private ID3D12PipelineState CreateHeightFieldBasePipelineState(string path) - { - return CreateFullscreenPipelineState(path, "FullscreenTriangleVS", "D3D12HeightFieldBasePS", HeightFieldFormat); - } - - private ID3D12PipelineState CreateHeightFieldBrushPipelineState(string path) - { - return CreateFullscreenPipelineState( - path, - "D3D12HeightFieldBrushVS", - "D3D12HeightFieldBrushPS", - HeightFieldFormat, - new BlendDescription(Blend.One, Blend.One, Blend.One, Blend.One)); - } - - private static BlendDescription CreateTransparentFieldBlend() - { - var blend = BlendDescription.Opaque; - blend.IndependentBlendEnable = true; - blend.RenderTarget[0] = new RenderTargetBlendDescription( - blendEnable: true, - logicOpEnable: false, - srcBlend: Blend.One, - destBlend: Blend.One, - blendOp: BlendOperation.Add, - srcBlendAlpha: Blend.Zero, - destBlendAlpha: Blend.One, - blendOpAlpha: BlendOperation.Add, - logicOp: LogicOp.Noop, - renderTargetWriteMask: ColorWriteEnable.All); - - for (var index = 1; index < 8; index++) - { - blend.RenderTarget[index] = new RenderTargetBlendDescription( - blendEnable: false, - logicOpEnable: false, - srcBlend: Blend.One, - destBlend: Blend.Zero, - blendOp: BlendOperation.Add, - srcBlendAlpha: Blend.One, - destBlendAlpha: Blend.Zero, - blendOpAlpha: BlendOperation.Add, - logicOp: LogicOp.Noop, - renderTargetWriteMask: ColorWriteEnable.None); - } - - return blend; - } - - private ID3D12PipelineState CreateFullscreenPipelineState( - string path, - string vertexEntryPoint, - string pixelEntryPoint, - Format renderTargetFormat, - BlendDescription? blendDescription = null, - bool enableDepth = false) - { - return CreateFullscreenPipelineState( - path, - vertexEntryPoint, - pixelEntryPoint, - [renderTargetFormat], - blendDescription, - enableDepth); - } - - private ID3D12PipelineState CreateFullscreenPipelineState( - string path, - string vertexEntryPoint, - string pixelEntryPoint, - IReadOnlyList renderTargetFormats, - BlendDescription? blendDescription = null, - bool enableDepth = false) - { - var vertexShader = CompileShader(path, vertexEntryPoint, "vs_5_0"); - var pixelShader = CompileShader(path, pixelEntryPoint, "ps_5_0"); - var description = new GraphicsPipelineStateDescription - { - RootSignature = fullscreenRootSignature, - VertexShader = vertexShader, - PixelShader = pixelShader, - BlendState = blendDescription ?? BlendDescription.Opaque, - RasterizerState = RasterizerDescription.CullNone, - DepthStencilState = enableDepth - ? new DepthStencilDescription - { - DepthEnable = true, - DepthWriteMask = DepthWriteMask.All, - DepthFunc = ComparisonFunction.LessEqual, - StencilEnable = false, - } - : DepthStencilDescription.None, - SampleMask = uint.MaxValue, - PrimitiveTopologyType = PrimitiveTopologyType.Triangle, - RenderTargetFormats = renderTargetFormats.ToArray(), - SampleDescription = new SampleDescription(1, 0), - DepthStencilFormat = enableDepth ? SceneDepthFormat : Format.Unknown, - }; - - try - { - return device.CreateGraphicsPipelineState(description); - } - catch (Exception ex) - { - throw new InvalidOperationException($"Failed to create D3D12 pipeline VS={vertexEntryPoint} PS={pixelEntryPoint} depth={enableDepth}.", ex); - } - } - - private static ReadOnlyMemory CompileShader(string path, string entryPoint, string profile) - { - var shaderFlags = ShaderFlags.EnableStrictness; -#if DEBUG - shaderFlags |= ShaderFlags.Debug | ShaderFlags.SkipOptimization; -#endif - - var source = ExpandShaderIncludes(path, []); - return Compiler.Compile(source, entryPoint, path, profile, shaderFlags, EffectFlags.None); - } - - private static string ExpandShaderIncludes(string path, HashSet stack) - { - var fullPath = Path.GetFullPath(path); - if (!stack.Add(fullPath)) - { - throw new InvalidOperationException($"Circular shader include detected at {fullPath}"); - } - - var lines = File.ReadAllLines(fullPath); - var expanded = new List(lines.Length); - var directory = Path.GetDirectoryName(fullPath) ?? AppContext.BaseDirectory; - for (var lineIndex = 0; lineIndex < lines.Length; lineIndex++) - { - var line = lines[lineIndex]; - var trimmed = line.TrimStart(); - if (trimmed.StartsWith("#include \"", StringComparison.Ordinal)) - { - var firstQuote = trimmed.IndexOf('"'); - var secondQuote = trimmed.IndexOf('"', firstQuote + 1); - if (firstQuote >= 0 && secondQuote > firstQuote) - { - var includeName = trimmed.Substring(firstQuote + 1, secondQuote - firstQuote - 1); - var includePath = Path.GetFullPath(Path.Combine(directory, includeName)); - expanded.Add($"#line 1 \"{includePath.Replace("\\", "\\\\")}\""); - expanded.Add(ExpandShaderIncludes(includePath, stack)); - expanded.Add($"#line {lineIndex + 2} \"{fullPath.Replace("\\", "\\\\")}\""); - continue; - } - } - - expanded.Add(line); - } - - stack.Remove(fullPath); - return string.Join(Environment.NewLine, expanded); - } - - private readonly record struct D3D12PassContext( - ID3D12GraphicsCommandList CommandList, - D3D12TrackedResource BackBuffer, - CpuDescriptorHandle RenderTargetView); - - [StructLayout(LayoutKind.Sequential)] - private readonly record struct FrameConstants( - Vector2 Resolution, - float TimeSeconds, - float viewRadius, - Vector3 CameraPosition, - float FarDistance, - Vector3 CameraTarget, - float SceneFlags, - Vector2 viewCenter, - float FrameIndex, - float PreviousTimeSeconds, - Vector3 PreviousCameraPosition, - float previousViewRadius, - Vector3 PreviousCameraTarget, - float PreviousSceneFlags, - Vector2 previousViewCenter, - Vector2 JitterPixels, - Vector2 PreviousJitterPixels, - float RenderDebugMode, - float Exposure, - float BloomIntensity, - float BloomVeilIntensity, - Vector4 CursorWorlds, - Vector4 TemporalGaussianInfo, - Vector4 GpuFusionInfo, - Vector4 FractalReservoirInfo, - Vector4 FractalReservoirFrame); - - private sealed record D3D12ShaderPaths( - string HeightField, - string Scene, - string TemporalGaussian, - string LocalCastFusion, - string FractalReservoir, - string FractalSplatRender, - string SdfCommon, - string SdfProxy, - IReadOnlyList SdfShaders, - string SdfMath, - IReadOnlyList Includes, - string Post) - { - public IReadOnlyList All { get; } = [HeightField, Scene, TemporalGaussian, LocalCastFusion, FractalReservoir, FractalSplatRender, SdfCommon, SdfProxy, ..SdfShaders, SdfMath, ..Includes, Post]; - - public static D3D12ShaderPaths FromManifest(string root, AquariumShaderManifest manifest) - { - string shaderPath(string path) => Path.IsPathRooted(path) ? path : Path.Combine(root, path); - var includes = manifest.SdfLibraryInclude is null - ? manifest.IncludePaths - : [.. manifest.IncludePaths, manifest.SdfLibraryInclude]; - return new D3D12ShaderPaths( - shaderPath(manifest.HeightFieldShader), - shaderPath(manifest.SceneShader), - shaderPath(manifest.TemporalGaussianShader), - shaderPath(manifest.LocalCastFusionShader), - shaderPath(manifest.FractalReservoirShader), - shaderPath(manifest.FractalSplatRenderShader), - shaderPath(manifest.SdfCommonInclude), - shaderPath(manifest.SdfProxyInclude), - manifest.SdfShaderPaths.Select(shaderPath).ToArray(), - shaderPath(manifest.SdfMathInclude), - includes.Select(shaderPath).ToArray(), - shaderPath(manifest.PostShader)); - } - } - - private sealed record D3D12PipelineSet( - ID3D12PipelineState HeightFieldBase, - ID3D12PipelineState HeightFieldBrush, - ID3D12PipelineState Scene, - ID3D12PipelineState TemporalGaussian, - ID3D12PipelineState LocalCastFusion, - ID3D12PipelineState FractalSurfaceSplatRender, - ID3D12PipelineState FractalTransparentSplatRender, - ID3D12PipelineState FractalSplat, - ID3D12PipelineState FractalSdfReservoir, - ID3D12PipelineState FractalPbrReservoir, - ID3D12PipelineState FractalRadiosityReservoir, - IReadOnlyList SdfProxies, - ID3D12PipelineState BloomPrefilter, - ID3D12PipelineState BloomDownsample, - ID3D12PipelineState BloomBlurHorizontal, - ID3D12PipelineState BloomBlurVertical, - ID3D12PipelineState Resolve) : IDisposable - { - public void Dispose() - { - Resolve.Dispose(); - BloomBlurVertical.Dispose(); - BloomBlurHorizontal.Dispose(); - BloomDownsample.Dispose(); - BloomPrefilter.Dispose(); - FractalRadiosityReservoir.Dispose(); - FractalPbrReservoir.Dispose(); - FractalSdfReservoir.Dispose(); - FractalSplat.Dispose(); - FractalTransparentSplatRender.Dispose(); - FractalSurfaceSplatRender.Dispose(); - LocalCastFusion.Dispose(); - TemporalGaussian.Dispose(); - foreach (var sdfProxy in SdfProxies) - { - sdfProxy.Dispose(); - } - - Scene.Dispose(); - HeightFieldBrush.Dispose(); - HeightFieldBase.Dispose(); - } - } - - private sealed class FrameResources( - ID3D12CommandAllocator commandAllocator, - D3D12UploadRing uploadRing, - D3D12DescriptorArena transientShaderDescriptors) : IDisposable - { - public ID3D12CommandAllocator CommandAllocator { get; } = commandAllocator; - - public D3D12UploadRing UploadRing { get; } = uploadRing; - - public D3D12DescriptorArena TransientShaderDescriptors { get; } = transientShaderDescriptors; - - public D3D12DescriptorSlot FrameConstantsDescriptor { get; set; } - - public D3D12DescriptorSlot HeightFieldBrushConstantsDescriptor { get; set; } - - public D3D12DescriptorSlot SdfLightDescriptor { get; set; } - - public D3D12DescriptorSlot SdfObjectDescriptor { get; set; } - - public D3D12DescriptorSlot GpuSensorCameraDescriptor { get; set; } - - public D3D12DescriptorSlot GpuSensorTextureDescriptor { get; set; } - - public D3D12DescriptorSlot AcousticConstraintDescriptor { get; set; } - - public D3D12DescriptorSlot GpuFusionSeedDescriptor { get; set; } - - public D3D12DescriptorSlot GpuFusionPointDescriptor { get; set; } - - public D3D12DescriptorSlot TemporalGaussianDescriptor { get; set; } - - public D3D12DescriptorSlot TemporalGaussianUnorderedAccessDescriptor { get; set; } - - public D3D12DescriptorSlot StudioPmremDescriptor { get; set; } - - public D3D12DescriptorSlot StudioIrradianceDescriptor { get; set; } - - public D3D12DescriptorSlot HeightFieldDescriptor { get; set; } - - public D3D12DescriptorSlot SceneDescriptor { get; set; } - - public D3D12DescriptorSlot SceneMetadataDescriptor { get; set; } - - public D3D12DescriptorSlot SceneControlDescriptor { get; set; } - - public D3D12DescriptorSlot SceneReservoirGuideDescriptor { get; set; } - - public D3D12DescriptorSlot HistoryDescriptor { get; set; } - - public D3D12DescriptorSlot HistoryMetadataDescriptor { get; set; } - - public D3D12DescriptorSlot HistoryControlDescriptor { get; set; } - - public D3D12DescriptorSlot HistoryReservoirGuideDescriptor { get; set; } - - public D3D12DescriptorSlot[] BloomDescriptors { get; } = new D3D12DescriptorSlot[BloomLevelCount]; - - public D3D12DescriptorSlot[] BloomScratchDescriptors { get; } = new D3D12DescriptorSlot[BloomLevelCount]; - - public D3D12DescriptorSlot BloomPresentationDescriptor { get; set; } - - public D3D12TrackedResource BackBuffer { get; set; } = null!; - - public D3D12DescriptorSlot BackBufferRenderTargetView { get; set; } - - public ulong FenceValue { get; set; } - - public void Dispose() - { - BackBuffer.Dispose(); - TransientShaderDescriptors.Dispose(); - UploadRing.Dispose(); - CommandAllocator.Dispose(); - } - } -} diff --git a/src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs b/src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs deleted file mode 100644 index c7ec5f8..0000000 --- a/src/Aquarium.Engine/Render/D3D12ResourceRegistry.cs +++ /dev/null @@ -1,77 +0,0 @@ -using Vortice.Direct3D12; - -namespace Aquarium.Engine.Render; - -internal sealed class D3D12ResourceRegistry -{ - private readonly Dictionary trackedResources = new(StringComparer.Ordinal); - private readonly Dictionary renderTargets = new(StringComparer.Ordinal); - private readonly Dictionary structuredBuffers = new(StringComparer.Ordinal); - private readonly Dictionary cubeTextures = new(StringComparer.Ordinal); - - public void Add(string name, D3D12TrackedResource resource) - { - if (!trackedResources.TryAdd(name, resource)) - { - throw new InvalidOperationException($"D3D12 resource already registered: {name}"); - } - } - - public void Add(string name, D3D12RenderTarget renderTarget) - { - if (!renderTargets.TryAdd(name, renderTarget)) - { - throw new InvalidOperationException($"D3D12 render target already registered: {name}"); - } - } - - public void Add(string name, D3D12StructuredBuffer structuredBuffer) - { - if (!structuredBuffers.TryAdd(name, structuredBuffer)) - { - throw new InvalidOperationException($"D3D12 structured buffer already registered: {name}"); - } - } - - public void Add(string name, D3D12CubeTexture cubeTexture) - { - if (!cubeTextures.TryAdd(name, cubeTexture)) - { - throw new InvalidOperationException($"D3D12 cube texture already registered: {name}"); - } - } - - public D3D12TrackedResource GetResource(string name) - { - return trackedResources.TryGetValue(name, out var resource) - ? resource - : throw new KeyNotFoundException($"D3D12 resource was not registered: {name}"); - } - - public D3D12RenderTarget GetRenderTarget(string name) - { - return renderTargets.TryGetValue(name, out var renderTarget) - ? renderTarget - : throw new KeyNotFoundException($"D3D12 render target was not registered: {name}"); - } - - public void RemoveResource(string name) - { - trackedResources.Remove(name); - } - - public void RemoveRenderTarget(string name) - { - renderTargets.Remove(name); - } - - public void RemoveStructuredBuffer(string name) - { - structuredBuffers.Remove(name); - } - - public string Describe() - { - return $"resources={trackedResources.Count}, renderTargets={renderTargets.Count}, structuredBuffers={structuredBuffers.Count}, cubeTextures={cubeTextures.Count}"; - } -} diff --git a/src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs b/src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs deleted file mode 100644 index 9c5f5df..0000000 --- a/src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs +++ /dev/null @@ -1,169 +0,0 @@ -using System.Runtime.CompilerServices; -using Vortice.Direct3D12; -using Vortice.DXGI; - -namespace Aquarium.Engine.Render; - -internal sealed class D3D12StructuredBuffer : IDisposable -{ - private readonly int elementCount; - private readonly int strideBytes; - - public D3D12StructuredBuffer(ID3D12Device device, int elementCount, int strideBytes, string name, bool allowUnorderedAccess = false) - { - this.elementCount = elementCount; - this.strideBytes = strideBytes; - SizeBytes = elementCount * strideBytes; - Resource = device.CreateCommittedResource( - HeapType.Default, - ResourceDescription.Buffer( - (ulong)SizeBytes, - allowUnorderedAccess ? ResourceFlags.AllowUnorderedAccess : ResourceFlags.None), - ResourceStates.Common, - null); - Resource.Name = name; - } - - public ID3D12Resource Resource { get; } - - public int ElementCount => elementCount; - - public int StrideBytes => strideBytes; - - public ResourceStates State { get; private set; } = ResourceStates.Common; - - public int SizeBytes { get; } - - public string Describe() - { - return $"{elementCount} elements x {strideBytes} bytes"; - } - - public void Upload(ID3D12GraphicsCommandList commandList, D3D12UploadRing uploadRing, ReadOnlySpan values) - where T : unmanaged - { - if (values.Length != elementCount) - { - throw new ArgumentException($"Structured buffer expected {elementCount} elements but received {values.Length}.", nameof(values)); - } - - var actualStride = Unsafe.SizeOf(); - if (actualStride != strideBytes) - { - throw new ArgumentException($"Structured buffer stride mismatch. Expected {strideBytes} bytes but received {actualStride}.", nameof(values)); - } - - var upload = uploadRing.WriteArray(values); - Transition(commandList, ResourceStates.CopyDest); - commandList.CopyBufferRegion(Resource, 0, uploadRing.Resource, (ulong)upload.OffsetBytes, (ulong)upload.DataBytes); - Transition(commandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - } - - public void UploadPartial(ID3D12GraphicsCommandList commandList, D3D12UploadRing uploadRing, ReadOnlySpan values) - where T : unmanaged - { - if (values.Length > elementCount) - { - throw new ArgumentException($"Structured buffer holds {elementCount} elements but received {values.Length}.", nameof(values)); - } - - var actualStride = Unsafe.SizeOf(); - if (actualStride != strideBytes) - { - throw new ArgumentException($"Structured buffer stride mismatch. Expected {strideBytes} bytes but received {actualStride}.", nameof(values)); - } - - var upload = uploadRing.WriteArray(values); - Transition(commandList, ResourceStates.CopyDest); - if (upload.DataBytes > 0) - { - commandList.CopyBufferRegion(Resource, 0, uploadRing.Resource, (ulong)upload.OffsetBytes, (ulong)upload.DataBytes); - } - Transition(commandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - } - - public void UploadPartialBytes( - ID3D12GraphicsCommandList commandList, - D3D12UploadRing uploadRing, - IntPtr source, - int elementLength, - int sourceStrideBytes) - { - ArgumentOutOfRangeException.ThrowIfNegative(elementLength); - if (elementLength > elementCount) - { - throw new ArgumentException($"Structured buffer holds {elementCount} elements but received {elementLength}.", nameof(elementLength)); - } - - if (sourceStrideBytes != strideBytes) - { - throw new ArgumentException($"Structured buffer stride mismatch. Expected {strideBytes} bytes but received {sourceStrideBytes}.", nameof(sourceStrideBytes)); - } - - var byteCount = checked(elementLength * strideBytes); - var upload = uploadRing.WriteBytes(source, byteCount); - Transition(commandList, ResourceStates.CopyDest); - if (upload.DataBytes > 0) - { - commandList.CopyBufferRegion(Resource, 0, uploadRing.Resource, (ulong)upload.OffsetBytes, (ulong)upload.DataBytes); - } - Transition(commandList, ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource); - } - - public void CreateShaderResourceView(ID3D12Device device, D3D12DescriptorSlot descriptor) - { - device.CreateShaderResourceView( - Resource, - new ShaderResourceViewDescription - { - Format = Format.Unknown, - ViewDimension = ShaderResourceViewDimension.Buffer, - Shader4ComponentMapping = ShaderComponentMapping.Default, - Buffer = new BufferShaderResourceView - { - FirstElement = 0, - NumElements = (uint)elementCount, - StructureByteStride = (uint)strideBytes, - Flags = BufferShaderResourceViewFlags.None, - }, - }, - descriptor.Cpu); - } - - public void CreateUnorderedAccessView(ID3D12Device device, D3D12DescriptorSlot descriptor) - { - device.CreateUnorderedAccessView( - Resource, - null, - new UnorderedAccessViewDescription - { - Format = Format.Unknown, - ViewDimension = UnorderedAccessViewDimension.Buffer, - Buffer = new BufferUnorderedAccessView - { - FirstElement = 0, - NumElements = (uint)elementCount, - StructureByteStride = (uint)strideBytes, - CounterOffsetInBytes = 0, - Flags = BufferUnorderedAccessViewFlags.None, - }, - }, - descriptor.Cpu); - } - - public void Transition(ID3D12GraphicsCommandList commandList, ResourceStates nextState) - { - if (State == nextState) - { - return; - } - - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(Resource, State, nextState)); - State = nextState; - } - - public void Dispose() - { - Resource.Dispose(); - } -} diff --git a/src/Aquarium.Engine/Render/D3D12TrackedResource.cs b/src/Aquarium.Engine/Render/D3D12TrackedResource.cs deleted file mode 100644 index a1496d2..0000000 --- a/src/Aquarium.Engine/Render/D3D12TrackedResource.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Vortice.Direct3D12; - -namespace Aquarium.Engine.Render; - -internal sealed class D3D12TrackedResource : IDisposable -{ - public D3D12TrackedResource(ID3D12Resource resource, ResourceStates state, string name, bool ownsResource) - { - Resource = resource; - State = state; - OwnsResource = ownsResource; - Resource.Name = name; - } - - public ID3D12Resource Resource { get; } - - public ResourceStates State { get; private set; } - - public bool OwnsResource { get; } - - public void Transition(ID3D12GraphicsCommandList commandList, ResourceStates nextState) - { - if (State == nextState) - { - return; - } - - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(Resource, State, nextState)); - State = nextState; - } - - public void MarkState(ResourceStates state) - { - State = state; - } - - public void Dispose() - { - if (OwnsResource) - { - Resource.Dispose(); - } - } -} diff --git a/src/Aquarium.Engine/Render/D3D12UploadRing.cs b/src/Aquarium.Engine/Render/D3D12UploadRing.cs deleted file mode 100644 index 453659c..0000000 --- a/src/Aquarium.Engine/Render/D3D12UploadRing.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using Vortice.Direct3D12; - -namespace Aquarium.Engine.Render; - -internal sealed unsafe class D3D12UploadRing : IDisposable -{ - private readonly ID3D12Resource resource; - private readonly byte* mapped; - private int cursor; - - public D3D12UploadRing(ID3D12Device device, int capacityBytes, string name) - { - CapacityBytes = Align256(capacityBytes); - Name = name; - resource = device.CreateCommittedResource( - HeapType.Upload, - ResourceDescription.Buffer((ulong)CapacityBytes), - ResourceStates.GenericRead, - null); - resource.Name = name; - mapped = (byte*)resource.Map(0); - } - - public int CapacityBytes { get; } - - public int UsedBytes => cursor; - - public string Name { get; } - - public ulong GpuVirtualAddress => resource.GPUVirtualAddress; - - public ID3D12Resource Resource => resource; - - public void Reset() - { - cursor = 0; - } - - public D3D12UploadAllocation WriteConstant(in T value) - where T : unmanaged - { - var size = Align256(Unsafe.SizeOf()); - if (cursor + size > CapacityBytes) - { - throw new InvalidOperationException($"D3D12 upload ring '{Name}' exhausted ({cursor}/{CapacityBytes} bytes used, requested {size} bytes)."); - } - - var offset = cursor; - Unsafe.Write(mapped + offset, value); - cursor += size; - return new D3D12UploadAllocation(GpuVirtualAddress + (ulong)offset, (uint)size); - } - - public D3D12UploadAllocation WriteArray(ReadOnlySpan values) - where T : unmanaged - { - var byteCount = Unsafe.SizeOf() * values.Length; - var size = Align256(byteCount); - if (cursor + size > CapacityBytes) - { - throw new InvalidOperationException($"D3D12 upload ring '{Name}' exhausted ({cursor}/{CapacityBytes} bytes used, requested {size} bytes)."); - } - - var offset = cursor; - if (byteCount > 0) - { - var source = MemoryMarshal.AsBytes(values); - source.CopyTo(new Span(mapped + offset, byteCount)); - } - - cursor += size; - return new D3D12UploadAllocation(GpuVirtualAddress + (ulong)offset, (uint)size, offset, byteCount); - } - - public D3D12UploadAllocation WriteBytes(IntPtr source, int byteCount) - { - ArgumentOutOfRangeException.ThrowIfNegative(byteCount); - if (byteCount > 0 && source == IntPtr.Zero) - { - throw new ArgumentException("Source pointer cannot be zero when byte count is non-zero.", nameof(source)); - } - - var size = Align256(byteCount); - if (cursor + size > CapacityBytes) - { - throw new InvalidOperationException($"D3D12 upload ring '{Name}' exhausted ({cursor}/{CapacityBytes} bytes used, requested {size} bytes)."); - } - - var offset = cursor; - if (byteCount > 0) - { - Buffer.MemoryCopy(source.ToPointer(), mapped + offset, byteCount, byteCount); - } - - cursor += size; - return new D3D12UploadAllocation(GpuVirtualAddress + (ulong)offset, (uint)size, offset, byteCount); - } - - public string Describe() - { - return $"{Name}: {cursor}/{CapacityBytes} bytes"; - } - - public void Dispose() - { - resource.Unmap(0, null); - resource.Dispose(); - } - - private static int Align256(int value) - { - return (value + 255) & ~255; - } -} - -internal readonly record struct D3D12UploadAllocation(ulong GpuVirtualAddress, uint SizeInBytes, int OffsetBytes = 0, int DataBytes = 0); diff --git a/src/Aquarium.Engine/Render/DirectWriteOverlay.cs b/src/Aquarium.Engine/Render/DirectWriteOverlay.cs deleted file mode 100644 index 4968813..0000000 --- a/src/Aquarium.Engine/Render/DirectWriteOverlay.cs +++ /dev/null @@ -1,228 +0,0 @@ -using Vortice.DCommon; -using Vortice.Direct2D1; -using Vortice.DirectWrite; -using Vortice.DXGI; -using Vortice.Mathematics; -using Aquarium.Engine.Render.Ui; -using D2DFactoryType = Vortice.Direct2D1.FactoryType; -using DWriteFactoryType = Vortice.DirectWrite.FactoryType; - -namespace Aquarium.Engine.Render; - -internal sealed class DirectWriteOverlay : IDisposable -{ - private readonly ID2D1Factory direct2DFactory; - private readonly IDWriteFactory6 directWriteFactory; - private readonly IDWriteFontCollection fontCollection; - private readonly IDWriteTypography smallCapsTypography; - private readonly ID2D1RenderTarget renderTarget; - private readonly ID2D1SolidColorBrush primaryTextBrush; - private readonly ID2D1SolidColorBrush quietTextBrush; - private readonly ID2D1SolidColorBrush panelBrush; - private readonly ID2D1SolidColorBrush rowBrush; - private readonly ID2D1SolidColorBrush hoverRowBrush; - private readonly ID2D1SolidColorBrush activeRowBrush; - private readonly ID2D1SolidColorBrush outlineBrush; - private readonly ID2D1SolidColorBrush accentBrush; - private readonly ID2D1SolidColorBrush accentHoverBrush; - private readonly ID2D1SolidColorBrush accentActiveBrush; - private readonly ID2D1SolidColorBrush dimAccentBrush; - private readonly ID2D1SolidColorBrush trackHoverBrush; - private readonly ID2D1SolidColorBrush trackActiveBrush; - private readonly IDWriteTextFormat titleFormat; - private readonly IDWriteTextFormat smallFormat; - private readonly IDWriteTextFormat monospaceFormat; - private readonly int width; - private readonly int height; - - public DirectWriteOverlay(IDXGISurface backBufferSurface, int width, int height) - { - this.width = width; - this.height = height; - - direct2DFactory = D2D1.D2D1CreateFactory(D2DFactoryType.SingleThreaded); - directWriteFactory = DWrite.DWriteCreateFactory(DWriteFactoryType.Shared); - fontCollection = CreateBrandFontCollection(); - smallCapsTypography = directWriteFactory.CreateTypography(); - smallCapsTypography.AddFontFeature(new FontFeature - { - NameTag = FontFeatureTag.SmallCapitalsFromCapitals, - Parameter = 1 - }); - smallCapsTypography.AddFontFeature(new FontFeature - { - NameTag = FontFeatureTag.CapitalSpacing, - Parameter = 1 - }); - - var renderTargetProperties = new RenderTargetProperties( - RenderTargetType.Default, - new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Ignore), - 96.0f, - 96.0f, - RenderTargetUsage.None, - FeatureLevel.Default); - renderTarget = direct2DFactory.CreateDxgiSurfaceRenderTarget(backBufferSurface, renderTargetProperties); - renderTarget.AntialiasMode = AntialiasMode.PerPrimitive; - renderTarget.TextAntialiasMode = Vortice.Direct2D1.TextAntialiasMode.Grayscale; - - primaryTextBrush = renderTarget.CreateSolidColorBrush(new Color4(0.88f, 0.96f, 1.0f, 0.92f)); - quietTextBrush = renderTarget.CreateSolidColorBrush(new Color4(0.54f, 0.68f, 0.72f, 0.72f)); - panelBrush = renderTarget.CreateSolidColorBrush(new Color4(0.018f, 0.022f, 0.032f, 0.96f)); - rowBrush = renderTarget.CreateSolidColorBrush(new Color4(0.085f, 0.084f, 0.12f, 0.96f)); - hoverRowBrush = renderTarget.CreateSolidColorBrush(new Color4(0.13f, 0.13f, 0.18f, 0.98f)); - activeRowBrush = renderTarget.CreateSolidColorBrush(new Color4(0.19f, 0.18f, 0.24f, 0.99f)); - outlineBrush = renderTarget.CreateSolidColorBrush(new Color4(0.28f, 0.34f, 0.36f, 0.72f)); - accentBrush = renderTarget.CreateSolidColorBrush(new Color4(1.0f, 0.38f, 0.055f, 0.96f)); - accentHoverBrush = renderTarget.CreateSolidColorBrush(new Color4(1.0f, 0.58f, 0.30f, 0.98f)); - accentActiveBrush = renderTarget.CreateSolidColorBrush(new Color4(1.0f, 0.78f, 0.58f, 1.0f)); - dimAccentBrush = renderTarget.CreateSolidColorBrush(new Color4(0.20f, 0.20f, 0.22f, 0.95f)); - trackHoverBrush = renderTarget.CreateSolidColorBrush(new Color4(0.32f, 0.29f, 0.29f, 0.98f)); - trackActiveBrush = renderTarget.CreateSolidColorBrush(new Color4(0.45f, 0.38f, 0.34f, 1.0f)); - titleFormat = CreateTextFormat("Montserrat", 18.0f, FontWeight.Thin); - smallFormat = CreateTextFormat("Ubuntu Sans", 11.0f, FontWeight.Regular); - monospaceFormat = CreateTextFormat("Ubuntu Sans Mono", 11.0f, FontWeight.Regular, ParagraphAlignment.Near); - } - - public void Render(AquariumFrame frame, int renderDebugMode, DebugUi? debugUi, IReadOnlyList clientUiPanels) - { - renderTarget.BeginDraw(); - if (debugUi is not null) - { - DrawPanel(debugUi, 1.0f); - } - - foreach (var panel in clientUiPanels) - { - DrawPanel(panel, panel.DrawOpacity()); - } - - renderTarget.EndDraw(); - } - - private void DrawPanel(DebugUi panel, float opacity) - { - var brushes = new ID2D1SolidColorBrush[] - { - panelBrush, - rowBrush, - hoverRowBrush, - activeRowBrush, - outlineBrush, - primaryTextBrush, - quietTextBrush, - accentBrush, - accentHoverBrush, - accentActiveBrush, - dimAccentBrush, - trackHoverBrush, - trackActiveBrush, - }; - var originalOpacity = new float[brushes.Length]; - for (var index = 0; index < brushes.Length; index++) - { - originalOpacity[index] = brushes[index].Opacity; - brushes[index].Opacity = originalOpacity[index] * opacity; - } - - try - { - panel.Draw( - renderTarget, - directWriteFactory, - titleFormat, - smallFormat, - monospaceFormat, - panelBrush, - rowBrush, - hoverRowBrush, - activeRowBrush, - outlineBrush, - primaryTextBrush, - quietTextBrush, - accentBrush, - accentHoverBrush, - accentActiveBrush, - dimAccentBrush, - trackHoverBrush, - trackActiveBrush, - width, - height); - } - finally - { - for (var index = 0; index < brushes.Length; index++) - { - brushes[index].Opacity = originalOpacity[index]; - } - } - } - - public void Dispose() - { - smallFormat.Dispose(); - monospaceFormat.Dispose(); - titleFormat.Dispose(); - smallCapsTypography.Dispose(); - fontCollection.Dispose(); - dimAccentBrush.Dispose(); - trackActiveBrush.Dispose(); - trackHoverBrush.Dispose(); - accentActiveBrush.Dispose(); - accentHoverBrush.Dispose(); - accentBrush.Dispose(); - outlineBrush.Dispose(); - activeRowBrush.Dispose(); - hoverRowBrush.Dispose(); - rowBrush.Dispose(); - panelBrush.Dispose(); - quietTextBrush.Dispose(); - primaryTextBrush.Dispose(); - renderTarget.Dispose(); - directWriteFactory.Dispose(); - direct2DFactory.Dispose(); - } - - private IDWriteTextFormat CreateTextFormat(string familyName, float size, FontWeight weight, ParagraphAlignment paragraphAlignment = ParagraphAlignment.Center) - { - var format = directWriteFactory.CreateTextFormat( - familyName, - fontCollection, - weight, - FontStyle.Normal, - FontStretch.Normal, - size, - "en-us"); - format.WordWrapping = WordWrapping.NoWrap; - format.ParagraphAlignment = paragraphAlignment; - return format; - } - - private IDWriteFontCollection CreateBrandFontCollection() - { - using var builder = directWriteFactory.CreateFontSetBuilder(); - builder.AddFontFile(FontAssetPath("Montserrat[wght].ttf")); - builder.AddFontFile(FontAssetPath("UbuntuSans[wdth,wght].ttf")); - builder.AddFontFile(FontAssetPath("UbuntuSansMono.ttf")); - using var fontSet = builder.CreateFontSet(); - return directWriteFactory.CreateFontCollectionFromFontSet(fontSet, FontFamilyModel.Typographic); - } - - private void DrawHeader(string text, IDWriteTextFormat format, Rect bounds, ID2D1Brush brush) - { - var displayText = text.ToUpperInvariant(); - using var layout = directWriteFactory.CreateTextLayout(displayText, format, bounds.Width, bounds.Height); - layout.SetTypography(smallCapsTypography, new TextRange(0, (uint)displayText.Length)); - renderTarget.DrawTextLayout(new System.Numerics.Vector2(bounds.Left, bounds.Top), layout, brush, DrawTextOptions.Clip); - } - - private static string FontAssetPath(string fileName) - { - return Path.Combine(AppContext.BaseDirectory, "Assets", "Fonts", fileName); - } - - private static Rect RectFromEdges(float left, float top, float right, float bottom) - { - return new Rect(left, top, Math.Max(0.0f, right - left), Math.Max(0.0f, bottom - top)); - } -} diff --git a/src/Aquarium.Engine/Render/Features/D3D12AcousticConstraintPacket.cs b/src/Aquarium.Engine/Render/Features/D3D12AcousticConstraintPacket.cs deleted file mode 100644 index 8ef9b53..0000000 --- a/src/Aquarium.Engine/Render/Features/D3D12AcousticConstraintPacket.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Numerics; -using System.Runtime.InteropServices; - -namespace Aquarium.Engine.Render.Features; - -[StructLayout(LayoutKind.Sequential)] -internal readonly record struct D3D12AcousticConstraintPacket( - Vector4 PositionRadius, - Vector4 VelocityConfidence, - Vector4 KindTimePad); diff --git a/src/Aquarium.Engine/Render/Features/D3D12GpuFusionPointPacket.cs b/src/Aquarium.Engine/Render/Features/D3D12GpuFusionPointPacket.cs deleted file mode 100644 index ea121ba..0000000 --- a/src/Aquarium.Engine/Render/Features/D3D12GpuFusionPointPacket.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Runtime.InteropServices; - -namespace Aquarium.Engine.Render.Features; - -[StructLayout(LayoutKind.Sequential)] -internal readonly record struct D3D12GpuFusionPointPacket( - ulong StableKeyHash, - ulong SourceTimestampNs, - float X, - float Y, - float Z, - float RadiusMeters, - float Red, - float Green, - float Blue, - float Alpha, - float Confidence); diff --git a/src/Aquarium.Engine/Render/Features/D3D12GpuFusionSeedPacket.cs b/src/Aquarium.Engine/Render/Features/D3D12GpuFusionSeedPacket.cs deleted file mode 100644 index e481f28..0000000 --- a/src/Aquarium.Engine/Render/Features/D3D12GpuFusionSeedPacket.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Numerics; -using System.Runtime.InteropServices; - -namespace Aquarium.Engine.Render.Features; - -[StructLayout(LayoutKind.Sequential)] -internal readonly record struct D3D12GpuFusionSeedPacket( - Vector4 CenterHistoryWeight, - Vector4 PreviousCenterFieldId, - Vector4 VelocityConfidence, - Vector4 RadiiFalloff, - Vector4 ColorOpacity, - Vector4 ShapePad); diff --git a/src/Aquarium.Engine/Render/Features/D3D12GpuSensorCameraPacket.cs b/src/Aquarium.Engine/Render/Features/D3D12GpuSensorCameraPacket.cs deleted file mode 100644 index 8f33d6d..0000000 --- a/src/Aquarium.Engine/Render/Features/D3D12GpuSensorCameraPacket.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Numerics; -using System.Runtime.InteropServices; - -namespace Aquarium.Engine.Render.Features; - -[StructLayout(LayoutKind.Sequential)] -internal readonly record struct D3D12GpuSensorCameraPacket( - Vector4 Intrinsics, - Vector4 Distortion01, - Vector4 Distortion23, - Vector4 ExtentsKind, - Vector4 TextureRangeTime, - Vector4 WorldFromSensor0, - Vector4 WorldFromSensor1, - Vector4 WorldFromSensor2, - Vector4 SensorFromWorld0, - Vector4 SensorFromWorld1, - Vector4 SensorFromWorld2); diff --git a/src/Aquarium.Engine/Render/Features/D3D12HeightFieldBrushConstants.cs b/src/Aquarium.Engine/Render/Features/D3D12HeightFieldBrushConstants.cs deleted file mode 100644 index 8ed8328..0000000 --- a/src/Aquarium.Engine/Render/Features/D3D12HeightFieldBrushConstants.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Numerics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace Aquarium.Engine.Render.Features; - -[StructLayout(LayoutKind.Sequential)] -internal struct D3D12HeightFieldBrushConstants -{ - public const int MaxBrushCount = 64; - - private const int VectorCount = MaxBrushCount * 4; - - private VectorTable values; - - public static D3D12HeightFieldBrushConstants FromBrushes(IReadOnlyList brushes) - { - var constants = new D3D12HeightFieldBrushConstants(); - var brushCount = Math.Min(brushes.Count, MaxBrushCount); - for (var index = 0; index < brushCount; index++) - { - var brush = brushes[index]; - var radiusY = brush.RadiusY > 0.0f ? brush.RadiusY : brush.Radius; - constants.Set( - index, - new Vector4(brush.Center, brush.Radius, radiusY), - new Vector4(brush.Power, brush.Amplitude, brush.RotationRadians, brush.EnvelopeFalloff), - new Vector4(brush.WaveAmplitude, brush.WaveFrequency, brush.WaveSpeed, brush.WaveSinePower), - new Vector4(brush.DomainFace, brush.DomainLevel, brush.DomainX, brush.DomainY)); - } - - return constants; - } - - private void Set(int brushIndex, Vector4 centerRadius, Vector4 shape, Vector4 wave, Vector4 domain) - { - if ((uint)brushIndex >= MaxBrushCount) - { - throw new ArgumentOutOfRangeException(nameof(brushIndex), brushIndex, "Height Field brush index is outside the fixed brush table."); - } - - SetVector(brushIndex, centerRadius); - SetVector(MaxBrushCount + brushIndex, shape); - SetVector(MaxBrushCount * 2 + brushIndex, wave); - SetVector(MaxBrushCount * 3 + brushIndex, domain); - } - - private void SetVector(int index, Vector4 value) - { - if ((uint)index >= VectorCount) - { - throw new ArgumentOutOfRangeException(nameof(index), index, "Height Field constant index is outside the fixed vector table."); - } - - values[index] = value; - } - - [InlineArray(VectorCount)] - private struct VectorTable - { - private Vector4 element0; - } -} diff --git a/src/Aquarium.Engine/Render/Features/D3D12TemporalGaussianPacket.cs b/src/Aquarium.Engine/Render/Features/D3D12TemporalGaussianPacket.cs deleted file mode 100644 index 82fa568..0000000 --- a/src/Aquarium.Engine/Render/Features/D3D12TemporalGaussianPacket.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Numerics; -using System.Runtime.InteropServices; - -namespace Aquarium.Engine.Render.Features; - -[StructLayout(LayoutKind.Sequential)] -internal readonly record struct D3D12TemporalGaussianPacket( - Vector4 CenterHistoryWeight, - Vector4 PreviousCenterFieldId, - Vector4 VelocityConfidence, - Vector4 RadiiFalloff, - Vector4 Orientation, - Vector4 ColorOpacity, - Vector4 ShapePad); diff --git a/src/Aquarium.Engine/Render/Graph/D3D12RenderGraphCompiler.cs b/src/Aquarium.Engine/Render/Graph/D3D12RenderGraphCompiler.cs deleted file mode 100644 index 40fcd54..0000000 --- a/src/Aquarium.Engine/Render/Graph/D3D12RenderGraphCompiler.cs +++ /dev/null @@ -1,53 +0,0 @@ -namespace Aquarium.Engine.Render.Graph; - -internal static class D3D12RenderGraphCompiler -{ - public static CompiledRenderGraph Compile(AquariumRenderPlan plan) - { - var resourceNames = new HashSet(StringComparer.Ordinal); - foreach (var target in plan.Graph.RenderTargets) - { - if (string.IsNullOrWhiteSpace(target.Handle.Name)) - { - throw new InvalidOperationException("Render target names must not be empty."); - } - - if (!resourceNames.Add(target.Handle.Name)) - { - throw new InvalidOperationException($"Render target declared more than once: {target.Handle.Name}"); - } - } - - var passNames = new HashSet(StringComparer.Ordinal); - foreach (var pass in plan.Graph.Passes) - { - if (string.IsNullOrWhiteSpace(pass.Handle.Name)) - { - throw new InvalidOperationException("Render pass names must not be empty."); - } - - if (!passNames.Add(pass.Handle.Name)) - { - throw new InvalidOperationException($"Render pass declared more than once: {pass.Handle.Name}"); - } - } - - return new CompiledRenderGraph( - plan.Graph.RenderTargets.ToArray(), - plan.Graph.Cameras.ToArray(), - plan.Graph.Passes.ToArray(), - plan.Graph.DebugViews.ToArray()); - } -} - -internal sealed record CompiledRenderGraph( - IReadOnlyList RenderTargets, - IReadOnlyList Cameras, - IReadOnlyList Passes, - IReadOnlyList DebugViews) -{ - public string Describe() - { - return $"targets={RenderTargets.Count}, cameras={Cameras.Count}, passes={Passes.Count}, debugViews={DebugViews.Count}"; - } -} diff --git a/src/Aquarium.Engine/Render/IAquariumRenderer.cs b/src/Aquarium.Engine/Render/IAquariumRenderer.cs deleted file mode 100644 index aa44391..0000000 --- a/src/Aquarium.Engine/Render/IAquariumRenderer.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Aquarium.Engine.Input; -using Aquarium.Engine.Audio; -using Aquarium.Engine.Ui; - -namespace Aquarium.Engine.Render; - -public interface IAquariumRenderer : IDisposable -{ - int RenderDebugMode { get; set; } - - bool DebugUiVisible { get; set; } - - bool HasPresentedReadyFrame { get; } - - bool CapturesInput { get; } - - AquariumSynthDocument DebugSynth { get; } - - void UpdateUi(InputState input, AquariumUiDocument clientUi); - - void CycleRenderDebugMode(); - - GraphicsSettings CaptureGraphicsSettings(); - - void ApplyGraphicsSettings(GraphicsSettings settings); - - void Render(AquariumFrame frame, int width, int height); - - void SaveFramePng(string path); -} diff --git a/src/Aquarium.Engine/Render/PngImageWriter.cs b/src/Aquarium.Engine/Render/PngImageWriter.cs deleted file mode 100644 index 490d7c2..0000000 --- a/src/Aquarium.Engine/Render/PngImageWriter.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System.Buffers.Binary; -using System.IO.Compression; -using System.Text; - -namespace Aquarium.Engine.Render; - -internal static class PngImageWriter -{ - private static readonly byte[] Signature = [137, 80, 78, 71, 13, 10, 26, 10]; - private static readonly uint[] CrcTable = BuildCrcTable(); - - public static void WriteRgba(string path, int width, int height, ReadOnlySpan rgba) - { - if (rgba.Length != width * height * 4) - { - throw new ArgumentException("RGBA buffer size does not match image dimensions.", nameof(rgba)); - } - - var directory = Path.GetDirectoryName(Path.GetFullPath(path)); - if (!string.IsNullOrWhiteSpace(directory)) - { - Directory.CreateDirectory(directory); - } - - using var stream = File.Create(path); - stream.Write(Signature); - Span ihdr = stackalloc byte[13]; - BinaryPrimitives.WriteInt32BigEndian(ihdr, width); - BinaryPrimitives.WriteInt32BigEndian(ihdr[4..], height); - ihdr[8] = 8; - ihdr[9] = 6; - ihdr[10] = 0; - ihdr[11] = 0; - ihdr[12] = 0; - WriteChunk(stream, "IHDR", ihdr); - - using var compressed = new MemoryStream(); - using (var zlib = new ZLibStream(compressed, CompressionLevel.Fastest, leaveOpen: true)) - { - var rowBytes = width * 4; - for (var y = 0; y < height; y++) - { - zlib.WriteByte(0); - zlib.Write(rgba.Slice(y * rowBytes, rowBytes)); - } - } - - WriteChunk(stream, "IDAT", compressed.ToArray()); - WriteChunk(stream, "IEND", []); - } - - private static void WriteChunk(Stream stream, string type, ReadOnlySpan data) - { - Span length = stackalloc byte[4]; - BinaryPrimitives.WriteInt32BigEndian(length, data.Length); - stream.Write(length); - - Span typeBytes = stackalloc byte[4]; - Encoding.ASCII.GetBytes(type, typeBytes); - stream.Write(typeBytes); - stream.Write(data); - - var crc = UpdateCrc(0xffffffff, typeBytes); - crc = UpdateCrc(crc, data) ^ 0xffffffff; - Span crcBytes = stackalloc byte[4]; - BinaryPrimitives.WriteUInt32BigEndian(crcBytes, crc); - stream.Write(crcBytes); - } - - private static uint UpdateCrc(uint crc, ReadOnlySpan data) - { - foreach (var value in data) - { - crc = CrcTable[(crc ^ value) & 0xff] ^ (crc >> 8); - } - - return crc; - } - - private static uint[] BuildCrcTable() - { - var table = new uint[256]; - for (uint index = 0; index < table.Length; index++) - { - var c = index; - for (var bit = 0; bit < 8; bit++) - { - c = (c & 1) != 0 ? 0xedb88320 ^ (c >> 1) : c >> 1; - } - - table[index] = c; - } - - return table; - } -} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl deleted file mode 100644 index 3e08adf..0000000 --- a/src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl +++ /dev/null @@ -1,473 +0,0 @@ -struct FractalSdfSplat -{ - float4 centerRadius; - float4 orientation; - float4 radiiFalloff; - float4 materialConfidence; - float4 key; -}; - -struct SdfEnvelopeReservoir -{ - float4 centerRadius; - float4 radiiFalloff; - float4 weightTargetCount; - float4 validation; -}; - -struct PbrMaterialReservoir -{ - float4 baseColorRoughMetal; - float4 normalVariance; - float4 weightTargetCount; - float4 validation; -}; - -struct RadiosityReservoir -{ - float4 radianceDistance; - float4 directionOcclusion; - float4 weightTargetCount; - float4 validation; -}; - -struct FractalIfsTransform -{ - float4 offsetScaleAmplitude; - float4 radiiRotationFalloff; - float4 materialSeedShape; - float4 tileAddress; - float4 postMatrix; - float4 postTranslation; -}; - -struct FlameIterationState -{ - float4 pointSupportMaterial; - float4 randomStep; -}; - -cbuffer ReceiptConstants : register(b0) -{ - uint SplatCount; - uint FrameIndex; - uint Depth; - uint Seed; - uint CandidatesPerPass; - uint ReservoirUpdatesPerPass; - uint ProgramTransformCount; - uint ProgramMode; - uint SplatDispatchCount; - float PriorityFocusX; - float PriorityFocusY; - float PriorityFocusRadius; - float PriorityFocusStrength; -}; - -RWStructuredBuffer Splats : register(u0); -RWStructuredBuffer SdfReservoirs : register(u1); -RWStructuredBuffer PbrReservoirs : register(u2); -RWStructuredBuffer RadiosityReservoirs : register(u3); -RWStructuredBuffer FlameStates : register(u4); -StructuredBuffer ProgramTransforms : register(t0); - -static const float FIELD_ENCODING_SIGNED_DISTANCE = 0.0; -static const float FIELD_ENCODING_DENSITY = 2.0; - -uint Hash(uint x) -{ - x ^= x >> 16; - x *= 747796405u; - x ^= x >> 16; - x *= 2891336453u; - x ^= x >> 16; - return x; -} - -float Random01(uint value) -{ - return (float)(Hash(value) & 16777215u) / 16777216.0; -} - -uint XorShift(inout uint state) -{ - uint value = state == 0u ? 0xA341316Cu : state; - value ^= value << 13; - value ^= value >> 17; - value ^= value << 5; - state = value == 0u ? 0xA341316Cu : value; - return state; -} - -float StateRandom01(inout uint state) -{ - return (float)(XorShift(state) & 16777215u) / 16777216.0; -} - -float2 CubeTileFaceUv(float2 authoredPoint, float4 tileAddress) -{ - float level = max(tileAddress.y, 0.0); - float axisTileCount = exp2(level); - float2 tile = tileAddress.zw; - float2 local01 = saturate((authoredPoint / 32.0) * 0.5 + 0.5); - return -1.0 + 2.0 * ((tile + local01) / max(axisTileCount, 1.0)); -} - -float3 CubeSphereDirection(float face, float2 uv) -{ - uint f = (uint)round(face); - if (f == 0u) - { - return normalize(float3(1.0, uv.y, -uv.x)); - } - - if (f == 1u) - { - return normalize(float3(-1.0, uv.y, uv.x)); - } - - if (f == 2u) - { - return normalize(float3(uv.x, 1.0, -uv.y)); - } - - if (f == 3u) - { - return normalize(float3(uv.x, -1.0, uv.y)); - } - - if (f == 5u) - { - return normalize(float3(uv.x, uv.y, -1.0)); - } - - return normalize(float3(uv.x, uv.y, 1.0)); -} - -float3 FractalPoint(uint index, out float radius, out float fieldEncoding) -{ - if (ProgramTransformCount > 0u && ProgramMode == 2u) - { - fieldEncoding = FIELD_ENCODING_DENSITY; - FlameIterationState state = FlameStates[index]; - uint n = asuint(state.randomStep.x); - float step = state.randomStep.y; - if (FrameIndex == 0u || n == 0u) - { - n = Hash(index ^ Seed); - state.pointSupportMaterial = float4(0.0, 0.0, 1.0, 0.0); - step = 0.0; - } - - float2 p = state.pointSupportMaterial.xy; - float support = max(state.pointSupportMaterial.z, 0.000001); - float material = state.pointSupportMaterial.w; - float totalWeight = 0.0; - [loop] - for (uint weightIndex = 0u; weightIndex < ProgramTransformCount; weightIndex++) - { - totalWeight += max(ProgramTransforms[weightIndex].materialSeedShape.y, 0.0); - } - - [loop] - for (uint depth = 0; depth < Depth; depth++) - { - float target = StateRandom01(n) * max(totalWeight, 0.000001); - float cumulative = 0.0; - uint transformIndex = ProgramTransformCount - 1u; - [loop] - for (uint candidateIndex = 0u; candidateIndex < ProgramTransformCount; candidateIndex++) - { - cumulative += max(ProgramTransforms[candidateIndex].materialSeedShape.y, 0.0); - if (target <= cumulative) - { - transformIndex = candidateIndex; - break; - } - } - - FractalIfsTransform transform = ProgramTransforms[transformIndex]; - float4 m = transform.offsetScaleAmplitude; - float2 t = transform.radiiRotationFalloff.xy; - float2 affine = float2((m.x * p.x) + (m.y * p.y) + t.x, (m.z * p.x) + (m.w * p.y) + t.y); - float r2 = dot(affine, affine); - float r = sqrt(max(r2, 0.0)); - float theta = atan2(affine.y, affine.x); - float2 nextPoint = affine * transform.radiiRotationFalloff.z; - nextPoint += affine * (transform.radiiRotationFalloff.w / max(r2, 0.000001)); - nextPoint += affine * (transform.materialSeedShape.x * 4.0 / (r2 + 4.0)); - float disc = transform.tileAddress.x; - if (disc != 0.0) - { - float discTheta = disc * atan2(affine.x, affine.y) / 3.14159265358979323846; - nextPoint += float2(sin(3.14159265358979323846 * r), cos(3.14159265358979323846 * r)) * discTheta; - } - - float julian = transform.tileAddress.y; - if (julian != 0.0) - { - float power = abs(transform.tileAddress.z) < 1.0 ? 1.0 : transform.tileAddress.z; - float absPower = max(abs(power), 1.0); - float branch = floor(StateRandom01(n) * absPower); - float angle = (theta + 6.28318530717958647692 * branch) / power; - float radial = pow(max(r, 0.000001), transform.materialSeedShape.w / power); - nextPoint += julian * radial * float2(cos(angle), sin(angle)); - } - - float blur = transform.tileAddress.w; - if (blur != 0.0) - { - float blurRadius = blur * ( - StateRandom01(n) + - StateRandom01(n) + - StateRandom01(n) + - StateRandom01(n) - 2.0); - float blurAngle = StateRandom01(n) * 6.28318530717958647692; - nextPoint += blurRadius * float2(cos(blurAngle), sin(blurAngle)); - } - - float4 post = transform.postMatrix; - float2 postT = transform.postTranslation.xy; - nextPoint = float2( - (post.x * nextPoint.x) + (post.y * nextPoint.y) + postT.x, - (post.z * nextPoint.x) + (post.w * nextPoint.y) + postT.y); - p = nextPoint; - material = transform.materialSeedShape.z; - support *= saturate(max(length(m.xy), length(m.zw))); - } - - FlameIterationState nextState; - nextState.pointSupportMaterial = float4(p, support, material); - nextState.randomStep = float4(asfloat(n), step + (float)Depth, 0.0, 0.0); - FlameStates[index] = nextState; - radius = max(0.0025 * max(support, 0.04), 0.00015); - return float3(p, material * 0.08); - } - - if (ProgramTransformCount > 0u && ProgramMode == 1u) - { - uint h = Hash(index ^ Seed); - uint transformIndex = h % ProgramTransformCount; - FractalIfsTransform transform = ProgramTransforms[transformIndex]; - fieldEncoding = transform.postTranslation.z; - float rx = Random01(h + FrameIndex * 17u) * 2.0 - 1.0; - float ry = Random01(h + 7919u) * 2.0 - 1.0; - float c = transform.materialSeedShape.z; - float s = transform.materialSeedShape.w; - float tileScale = 1.0 / max(exp2(max(transform.tileAddress.y, 0.0)), 1.0); - float2 local = float2(rx * transform.radiiRotationFalloff.x, ry * transform.radiiRotationFalloff.y) * 0.65; - float2 rotated = float2((local.x * c) - (local.y * s), (local.x * s) + (local.y * c)); - radius = max(max(transform.radiiRotationFalloff.x, transform.radiiRotationFalloff.y) * (1.0 / 32.0) * tileScale * (0.12 + Random01(h + 104729u) * 0.04), 0.0004); - float relief = transform.offsetScaleAmplitude.w * 0.02 + (Random01(h + 1299721u) - 0.5) * radius * 0.5; - float2 surfacePoint = transform.offsetScaleAmplitude.xy + rotated; - float2 faceUv = CubeTileFaceUv(surfacePoint, transform.tileAddress); - float3 dir = CubeSphereDirection(transform.tileAddress.x, faceUv); - return dir * (1.0 + relief + transform.materialSeedShape.x * 0.012); - } - - if (ProgramTransformCount > 0u) - { - uint n = index ^ Seed; - float2 p = 0.0; - float z = 0.0; - float scale = 1.0; - float material = 0.0; - fieldEncoding = FIELD_ENCODING_SIGNED_DISTANCE; - radius = 0.01; - [loop] - for (uint depth = 0; depth < Depth; depth++) - { - uint transformIndex = Hash(n + depth * 747796405u) % ProgramTransformCount; - FractalIfsTransform transform = ProgramTransforms[transformIndex]; - float c = transform.materialSeedShape.z; - float s = transform.materialSeedShape.w; - float2 rotated = float2((p.x * c) - (p.y * s), (p.x * s) + (p.y * c)); - float childScale = saturate(transform.offsetScaleAmplitude.z); - p = rotated * max(childScale, 0.01) + transform.offsetScaleAmplitude.xy; - scale *= max(childScale, 0.01); - z += transform.offsetScaleAmplitude.w * scale; - radius = max(max(transform.radiiRotationFalloff.x, transform.radiiRotationFalloff.y) * max(scale, 0.001), 0.0001); - material = transform.materialSeedShape.x; - n = Hash(n + asuint(transform.materialSeedShape.y) + transformIndex + depth); - } - - return float3(p, z + material * 0.05); - } - - uint n = index ^ Seed; - float3 p = 0.0; - float scale = 1.0; - fieldEncoding = FIELD_ENCODING_SIGNED_DISTANCE; - [loop] - for (uint depth = 0; depth < Depth; depth++) - { - uint branch = (n >> (depth * 2u)) & 3u; - float2 dir = branch == 0u ? float2(1.0, 0.0) : branch == 1u ? float2(-0.42, 0.91) : branch == 2u ? float2(-0.76, -0.65) : float2(0.72, -0.69); - scale *= 0.535; - p.xy += dir * scale; - p.z += ((float)branch - 1.5) * scale * 0.19; - n = Hash(n + branch + FrameIndex + depth * 17u); - } - - radius = max(scale * 0.75, 0.0001); - return p; -} - -float ReservoirPriorityScore(uint index, uint salt, float radius, float strength) -{ - FractalSdfSplat splat = Splats[index]; - float2 delta = splat.centerRadius.xy - float2(PriorityFocusX, PriorityFocusY); - float nearFocus = 1.0 - smoothstep(radius, radius * 2.0, length(delta)); - float exploration = Random01(salt); - return lerp(exploration, nearFocus + exploration * 0.15, strength); -} - -uint ReservoirIndex(uint updateIndex, uint passKind) -{ - if (ReservoirUpdatesPerPass >= SplatCount) - { - return updateIndex % SplatCount; - } - - uint baseSalt = updateIndex * 1664525u + FrameIndex * 1013904223u + passKind * 747796405u + Seed; - uint bestIndex = Hash(baseSalt) % SplatCount; - float strength = saturate(PriorityFocusStrength); - float radius = max(PriorityFocusRadius, 0.0); - if (strength <= 0.0 || radius <= 0.0) - { - return bestIndex; - } - - float bestScore = ReservoirPriorityScore(bestIndex, Hash(baseSalt + 17u), radius, strength); - [unroll] - for (uint probe = 1u; probe < 4u; probe++) - { - uint candidateSalt = Hash(baseSalt + probe * 747796405u); - uint candidateIndex = candidateSalt % SplatCount; - float candidateScore = ReservoirPriorityScore(candidateIndex, candidateSalt, radius, strength); - if (candidateScore > bestScore) - { - bestScore = candidateScore; - bestIndex = candidateIndex; - } - } - - return bestIndex; -} - -float4 ReservoirStats(uint index, uint passKind, float baseTarget, out uint selectedCandidate) -{ - float weightSum = 0.0; - float selectedTarget = 0.0; - selectedCandidate = 0u; - [loop] - for (uint candidate = 0u; candidate < CandidatesPerPass; candidate++) - { - float phase = Random01(index * 1664525u + passKind * 1013904223u + candidate * 747796405u + FrameIndex); - float target = max(baseTarget * (0.55 + phase), 0.000001); - float weight = target * max((float)CandidatesPerPass, 1.0); - float nextWeightSum = weightSum + weight; - if (weightSum <= 0.0 || Random01(index + candidate * 13007u + passKind * 7919u) < weight / max(nextWeightSum, 0.000001)) - { - selectedTarget = target; - selectedCandidate = candidate; - } - - weightSum = nextWeightSum; - } - - float contribution = weightSum / max((float)CandidatesPerPass * selectedTarget, 0.000001); - return float4(weightSum, selectedTarget, (float)CandidatesPerPass, contribution); -} - -[numthreads(256, 1, 1)] -void D3D12FractalSplatReceiptCS(uint3 id : SV_DispatchThreadID) -{ - uint updateIndex = id.x; - if (updateIndex >= SplatDispatchCount) - { - return; - } - - uint index = updateIndex; - if (FrameIndex > 0u && SplatDispatchCount < SplatCount) - { - index = ReservoirIndex(updateIndex, 4u); - } - - float radius; - float fieldEncoding; - float3 p = FractalPoint(index, radius, fieldEncoding); - uint h = Hash(index + FrameIndex * 1664525u + Seed); - FractalSdfSplat splat; - splat.centerRadius = float4(p, radius); - splat.orientation = float4(0.0, 0.0, 0.0, 1.0); - splat.radiiFalloff = float4(radius, radius * 0.72, radius * 0.45, 4.0); - splat.materialConfidence = float4((float)(h & 1023u) / 1023.0, 1.0, fieldEncoding, 1.0); - splat.key = float4((float)index, (float)FrameIndex, (float)Depth, asfloat(h)); - Splats[index] = splat; -} - -[numthreads(256, 1, 1)] -void D3D12SdfEnvelopeReservoirCS(uint3 id : SV_DispatchThreadID) -{ - uint updateIndex = id.x; - if (updateIndex >= ReservoirUpdatesPerPass) - { - return; - } - - uint index = ReservoirIndex(updateIndex, 0u); - FractalSdfSplat splat = Splats[index]; - uint selected; - float4 stats = ReservoirStats(index, 0u, splat.centerRadius.w, selected); - SdfEnvelopeReservoir r; - r.centerRadius = splat.centerRadius; - r.radiiFalloff = splat.radiiFalloff; - r.weightTargetCount = stats; - r.validation = float4(saturate(stats.y), (float)FrameIndex, (float)selected, asfloat(Hash(index + selected))); - SdfReservoirs[index] = r; -} - -[numthreads(256, 1, 1)] -void D3D12PbrMaterialReservoirCS(uint3 id : SV_DispatchThreadID) -{ - uint updateIndex = id.x; - if (updateIndex >= ReservoirUpdatesPerPass) - { - return; - } - - uint index = ReservoirIndex(updateIndex, 1u); - FractalSdfSplat splat = Splats[index]; - uint selected; - float4 stats = ReservoirStats(index, 1u, splat.materialConfidence.x + 0.1, selected); - PbrMaterialReservoir r; - r.baseColorRoughMetal = float4(splat.materialConfidence.x, 1.0 - splat.materialConfidence.x * 0.4, 0.18 + 0.5 * splat.materialConfidence.x, 0.02); - r.normalVariance = float4(normalize(splat.centerRadius.xyz + 0.001), splat.radiiFalloff.x); - r.weightTargetCount = stats; - r.validation = float4(saturate(stats.y), (float)FrameIndex, (float)selected, asfloat(Hash(index + selected + 17u))); - PbrReservoirs[index] = r; -} - -[numthreads(256, 1, 1)] -void D3D12RadiosityReservoirCS(uint3 id : SV_DispatchThreadID) -{ - uint updateIndex = id.x; - if (updateIndex >= ReservoirUpdatesPerPass) - { - return; - } - - uint index = ReservoirIndex(updateIndex, 2u); - FractalSdfSplat splat = Splats[index]; - uint selected; - float energy = abs(cos(length(splat.centerRadius.xyz) * 7.0 + (float)FrameIndex * 0.01)); - float4 stats = ReservoirStats(index, 2u, energy + 0.05, selected); - RadiosityReservoir r; - r.radianceDistance = float4(energy, energy * 0.62, energy * 0.31, length(splat.centerRadius.xyz)); - r.directionOcclusion = float4(normalize(-splat.centerRadius.xyz + 0.01), 1.0 - energy * 0.35); - r.weightTargetCount = stats; - r.validation = float4(saturate(stats.y), (float)FrameIndex, (float)selected, asfloat(Hash(index + selected + 29u))); - RadiosityReservoirs[index] = r; -} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12FractalSplatRender.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12FractalSplatRender.hlsl deleted file mode 100644 index 5804fb9..0000000 --- a/src/Aquarium.Engine/Render/Shaders/D3D12FractalSplatRender.hlsl +++ /dev/null @@ -1,250 +0,0 @@ -cbuffer AquariumFrame : register(b0) -{ - float2 resolution; - float timeSeconds; - float viewRadius; - float3 cameraPosition; - float farDistance; - float3 cameraTarget; - float sceneFlags; - float2 viewCenter; - float frameIndex; - float previousTimeSeconds; - float3 previousCameraPosition; - float previousViewRadius; - float3 previousCameraTarget; - float previousSceneFlags; - float2 previousViewCenter; - float2 jitterPixels; - float2 previousJitterPixels; - float renderDebugMode; - float exposure; - float bloomIntensity; - float bloomVeilIntensity; - float4 cursorWorlds; - float4 temporalGaussianInfo; - float4 gpuFusionInfo; - float4 fractalReservoirInfo; - float4 fractalReservoirFrame; -}; - -struct FractalSdfSplat -{ - float4 centerRadius; - float4 orientation; - float4 radiiFalloff; - float4 materialConfidence; - float4 key; -}; - -struct SdfEnvelopeReservoir -{ - float4 centerRadius; - float4 radiiFalloff; - float4 weightTargetCount; - float4 validation; -}; - -struct PbrMaterialReservoir -{ - float4 baseColorRoughMetal; - float4 normalVariance; - float4 weightTargetCount; - float4 validation; -}; - -struct RadiosityReservoir -{ - float4 radianceDistance; - float4 directionOcclusion; - float4 weightTargetCount; - float4 validation; -}; - -StructuredBuffer fractalSdfSplats : register(t38); -StructuredBuffer sdfEnvelopeReservoirs : register(t39); -StructuredBuffer pbrMaterialReservoirs : register(t40); -StructuredBuffer radiosityReservoirs : register(t41); - -struct FractalSplatVertexOut -{ - float4 position : SV_Position; - nointerpolation uint splatIndex : TEXCOORD0; - float2 quad : TEXCOORD1; - float travel : TEXCOORD2; - nointerpolation float3 centerWorld : TEXCOORD3; - nointerpolation float worldRadius : TEXCOORD4; - nointerpolation float3 basisRight : TEXCOORD5; - nointerpolation float3 basisUp : TEXCOORD6; - nointerpolation float3 basisForward : TEXCOORD7; -}; - -struct SceneOut -{ - float4 colorTravel : SV_Target0; - float4 metadata : SV_Target1; - float4 control : SV_Target2; - float4 reservoirGuide : SV_Target3; - float depth : SV_Depth; -}; - -static const float FIELD_ID_FRACTAL_SPLAT_BASE = 4000.0; -static const float FIELD_ENCODING_DENSITY = 2.0; -static const float FIELD_ENCODING_EXTINCTION = 3.0; - -void cameraBasis(float3 camera, float3 target, out float3 forward, out float3 right, out float3 up) -{ - forward = normalize(target - camera); - right = normalize(cross(forward, float3(0.0, 0.0, 1.0))); - up = cross(right, forward); -} - -float4 projectWorld(float3 world, float3 camera, float3 forward, float3 right, float3 up, out float travel) -{ - float3 delta = world - camera; - travel = max(dot(delta, forward), 0.0001); - float2 projected = float2(dot(delta, right), dot(delta, up)) / travel * 1.6; - float clipAspect = resolution.x / max(resolution.y, 1.0); - return float4(projected.x / clipAspect, projected.y, saturate(travel / max(farDistance, 0.0001)), 1.0); -} - -uint VisibleSplatIndex(uint instanceId) -{ - uint splatCount = max((uint)fractalReservoirInfo.x, 1u); - uint visibleCount = max((uint)fractalReservoirInfo.y, 1u); - return min((instanceId * splatCount) / visibleCount, splatCount - 1u); -} - -FractalSplatVertexOut D3D12FractalSplatVS(uint vertexId : SV_VertexID, uint instanceId : SV_InstanceID) -{ - float2 corners[6] = - { - float2(-1.0, -1.0), - float2(1.0, -1.0), - float2(1.0, 1.0), - float2(-1.0, -1.0), - float2(1.0, 1.0), - float2(-1.0, 1.0), - }; - - uint splatIndex = VisibleSplatIndex(instanceId); - FractalSdfSplat splat = fractalSdfSplats[splatIndex]; - SdfEnvelopeReservoir sdf = sdfEnvelopeReservoirs[splatIndex]; - bool sdfResident = sdf.weightTargetCount.z > 0.5; - float4 centerRadius = sdfResident ? sdf.centerRadius : splat.centerRadius; - float3 forward; - float3 right; - float3 up; - cameraBasis(cameraPosition, cameraTarget, forward, right, up); - float fieldRadius = fractalReservoirFrame.w > 0.0 ? fractalReservoirFrame.w : max(viewRadius * 0.16, 0.05); - float3 fieldCenter = fractalReservoirFrame.w > 0.0 ? fractalReservoirFrame.xyz : cameraTarget; - float3 center = fieldCenter + centerRadius.xyz * fieldRadius; - float3 surfaceNormal = normalize(centerRadius.xyz); - float3 referenceUp = abs(surfaceNormal.z) < 0.92 ? float3(0.0, 0.0, 1.0) : float3(0.0, 1.0, 0.0); - float3 tangentRight = normalize(cross(referenceUp, surfaceNormal)); - float3 tangentUp = normalize(cross(surfaceNormal, tangentRight)); - float boundRadius = max(centerRadius.w * fieldRadius * 1.25, 0.035 * fieldRadius); - float3 cornerWorld = center + ((tangentRight * corners[vertexId].x) + (tangentUp * corners[vertexId].y)) * boundRadius; - float z; - float4 projectedCorner = projectWorld(cornerWorld, cameraPosition, forward, right, up, z); - - FractalSplatVertexOut output; - output.position = projectedCorner; - output.splatIndex = splatIndex; - output.quad = corners[vertexId]; - output.travel = z; - output.centerWorld = center; - output.worldRadius = boundRadius; - output.basisRight = tangentRight; - output.basisUp = tangentUp; - output.basisForward = surfaceNormal; - return output; -} - -bool IsTransparentField(float encoding) -{ - return abs(encoding - FIELD_ENCODING_DENSITY) < 0.5 || - abs(encoding - FIELD_ENCODING_EXTINCTION) < 0.5; -} - -SceneOut ResolveFractalSplat(FractalSplatVertexOut input, bool renderTransparent) -{ - float r2 = dot(input.quad, input.quad); - if (r2 >= 1.0) - { - discard; - } - - FractalSdfSplat splat = fractalSdfSplats[input.splatIndex]; - SdfEnvelopeReservoir sdf = sdfEnvelopeReservoirs[input.splatIndex]; - PbrMaterialReservoir pbr = pbrMaterialReservoirs[input.splatIndex]; - RadiosityReservoir radiosity = radiosityReservoirs[input.splatIndex]; - - bool sdfResident = sdf.weightTargetCount.z > 0.5; - bool pbrResident = pbr.weightTargetCount.z > 0.5; - bool radiosityResident = radiosity.weightTargetCount.z > 0.5; - bool transparentField = IsTransparentField(splat.materialConfidence.z); - if (transparentField != renderTransparent) - { - discard; - } - - float surfaceZ = sqrt(saturate(1.0 - r2)); - float3 tangentOffset = (input.basisRight * input.quad.x) + (input.basisUp * input.quad.y); - float3 normal = normalize(input.basisForward * (0.92 + surfaceZ * 0.08) + tangentOffset * 0.16); - float3 surfaceWorld = input.centerWorld + tangentOffset * input.worldRadius; - float edgeCoverage = smoothstep(1.0, 0.82, r2); - float viewFacing = saturate(dot(normalize(cameraPosition - surfaceWorld), normal)); - float starFacing = saturate(dot(normal, normalize(float3(0.25, 0.006, 0.077) - surfaceWorld))); - float material = saturate(splat.materialConfidence.x); - float3 fallbackColor = transparentField - ? lerp(float3(0.18, 0.08, 0.32), float3(1.0, 0.44, 0.12), material) - : lerp(float3(0.08, 0.38, 0.18), float3(0.78, 0.61, 0.32), material); - float3 pbrColor = lerp(float3(0.06, 0.30, 0.14), saturate(pbr.baseColorRoughMetal.rgb), 0.72); - float3 radiosityColor = saturate(radiosity.radianceDistance.rgb); - float reservoirConfidence = min( - sdfResident ? saturate(sdf.validation.x) : 0.0, - min( - pbrResident ? saturate(pbr.validation.x) : 0.0, - radiosityResident ? saturate(radiosity.validation.x) : 0.0)); - float3 color = pbrResident ? pbrColor : fallbackColor; - float roughness = pbrResident ? saturate(pbr.baseColorRoughMetal.w) : 0.6; - float diffuse = transparentField ? 0.52 + 0.36 * viewFacing : 0.32 + 0.50 * starFacing + 0.18 * viewFacing; - float fresnel = pow(saturate(1.0 - viewFacing), 2.2); - float3 litColor = color * diffuse + color * 0.18; - litColor += radiosityResident ? radiosityColor * (0.24 + reservoirConfidence * 0.48) : 0.0; - litColor += lerp(float3(0.015, 0.06, 0.05), transparentField ? float3(0.95, 0.28, 0.08) : float3(0.24, 0.30, 0.20), 1.0 - roughness) * fresnel * (transparentField ? 0.72 : 0.48); - float opacity = transparentField - ? saturate(edgeCoverage * edgeCoverage * (0.18 + reservoirConfidence * 0.32)) - : saturate(edgeCoverage * (0.78 + reservoirConfidence * 0.22)); - float reservoirUpdatedFrame = min( - sdfResident ? sdf.validation.y : frameIndex, - min( - pbrResident ? pbr.validation.y : frameIndex, - radiosityResident ? radiosity.validation.y : frameIndex)); - float reservoirSampleAge = max(frameIndex - reservoirUpdatedFrame, 0.0); - float domainValidity = reservoirConfidence > 0.0 ? 1.0 : 0.0; - - SceneOut output; - output.colorTravel = float4(litColor * opacity, min(input.travel - surfaceZ * input.worldRadius, farDistance + 1.0)); - output.metadata = float4(FIELD_ID_FRACTAL_SPLAT_BASE, normal); - output.control = float4(opacity, reservoirConfidence, transparentField ? splat.materialConfidence.z / 10.0 : saturate((sdfResident ? sdf.centerRadius.w : splat.centerRadius.w) * 40.0), 0.0); - output.reservoirGuide = float4(reservoirConfidence, reservoirSampleAge, domainValidity, 0.0); - output.depth = saturate(input.travel / max(farDistance, 0.0001)); - return output; -} - -SceneOut D3D12FractalSurfaceSplatPS(FractalSplatVertexOut input) -{ - return ResolveFractalSplat(input, false); -} - -SceneOut D3D12FractalTransparentSplatPS(FractalSplatVertexOut input) -{ - return ResolveFractalSplat(input, true); -} - -SceneOut D3D12FractalSplatPS(FractalSplatVertexOut input) -{ - return D3D12FractalSurfaceSplatPS(input); -} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12HeightField.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12HeightField.hlsl deleted file mode 100644 index 7912b84..0000000 --- a/src/Aquarium.Engine/Render/Shaders/D3D12HeightField.hlsl +++ /dev/null @@ -1,156 +0,0 @@ -cbuffer AquariumFrame : register(b0) -{ - float2 resolution; - float timeSeconds; - float viewRadius; - float3 cameraPosition; - float farDistance; - float3 cameraTarget; - float sceneFlags; - float2 viewCenter; - float frameIndex; - float previousTimeSeconds; - float3 previousCameraPosition; - float previousViewRadius; - float3 previousCameraTarget; - float previousSceneFlags; - float2 previousViewCenter; - float2 jitterPixels; - float2 previousJitterPixels; - float renderDebugMode; - float exposure; - float bloomIntensity; - float bloomVeilIntensity; - float4 cursorWorlds; - float4 temporalGaussianInfo; -}; - -cbuffer HeightFieldBrushes : register(b1) -{ - float4 brushCenterRadius[64]; - float4 brushShape[64]; - float4 brushWave[64]; - float4 brushDomain[64]; -}; - -struct VertexOut -{ - float4 position : SV_Position; - float2 uv : TEXCOORD0; -}; - -struct BrushVertexOut -{ - float4 position : SV_Position; - float2 uv : TEXCOORD0; - nointerpolation uint brushIndex : TEXCOORD1; - nointerpolation float4 centerRadius : TEXCOORD2; - nointerpolation float4 shape : TEXCOORD3; - nointerpolation float4 wave : TEXCOORD4; -}; - -float2 viewLocal(float2 p) -{ - return (p - viewCenter) / max(viewRadius, 0.001); -} - -float2 viewUv(float2 p) -{ - return viewLocal(p) * 0.5 + 0.5; -} - -float2 viewWorld(float2 uv) -{ - return viewCenter + (uv * 2.0 - 1.0) * viewRadius; -} - -float powerPulse(float distanceValue, float radius, float power) -{ - float normalized = saturate(distanceValue / max(radius, 0.001)); - float shaped = pow(1.0 - normalized, power); - return shaped * shaped * (3.0 - 2.0 * shaped); -} - -float compactGaussianPulse(float normalizedRadiusSquared, float falloff, float shapePower) -{ - if (normalizedRadiusSquared >= 1.0) - { - return 0.0; - } - - float edgeValue = exp(-falloff); - float gaussianValue = exp(-falloff * normalizedRadiusSquared); - float compactValue = (gaussianValue - edgeValue) / max(1.0 - edgeValue, 0.000001); - return pow(saturate(compactValue), shapePower); -} - -VertexOut FullscreenTriangleVS(uint vertexId : SV_VertexID) -{ - float2 uv = float2((vertexId << 1) & 2, vertexId & 2); - VertexOut output; - output.position = float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); - output.uv = uv; - return output; -} - -float D3D12HeightFieldBasePS(VertexOut input) : SV_Target -{ - float2 world = viewWorld(saturate(input.uv)); - float slow = sin((world.x * 0.08 + world.y * 0.06) + timeSeconds * 0.27) - * sin((world.x * -0.04 + world.y * 0.07) - timeSeconds * 0.19) * 0.035; - return slow; -} - -BrushVertexOut D3D12HeightFieldBrushVS(uint vertexId : SV_VertexID, uint instanceId : SV_InstanceID) -{ - float2 corners[6] = - { - float2(-1.0, -1.0), - float2(1.0, -1.0), - float2(1.0, 1.0), - float2(-1.0, -1.0), - float2(1.0, 1.0), - float2(-1.0, 1.0), - }; - - float4 centerRadius = brushCenterRadius[instanceId]; - float2 radii = float2(centerRadius.z, centerRadius.w > 0.0 ? centerRadius.w : centerRadius.z); - float supportRadius = max(radii.x, radii.y); - float2 world = centerRadius.xy + corners[vertexId] * supportRadius; - float2 uv = viewUv(world); - - BrushVertexOut output; - output.position = float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); - output.uv = uv; - output.brushIndex = instanceId; - output.centerRadius = centerRadius; - output.shape = brushShape[instanceId]; - output.wave = brushWave[instanceId]; - return output; -} - -float D3D12HeightFieldBrushPS(BrushVertexOut input) : SV_Target -{ - float2 world = viewWorld(saturate(input.uv)); - float2 delta = world - input.centerRadius.xy; - float2 radii = float2(input.centerRadius.z, input.centerRadius.w > 0.0 ? input.centerRadius.w : input.centerRadius.z); - float distanceValue = length(delta); - float normalizedDistance = saturate(distanceValue / max(input.centerRadius.z, 0.001)); - float well = powerPulse(distanceValue, input.centerRadius.z, input.shape.x); - if (input.shape.w > 0.0) - { - float c = cos(input.shape.z); - float s = sin(input.shape.z); - float2 local = float2(delta.x * c + delta.y * s, -delta.x * s + delta.y * c); - float2 normalized = local / max(radii, float2(0.001, 0.001)); - float normalizedRadiusSquared = dot(normalized, normalized); - normalizedDistance = saturate(sqrt(normalizedRadiusSquared)); - well = compactGaussianPulse(normalizedRadiusSquared, input.shape.w, input.shape.x); - } - - float legacyPhase = distanceValue * input.wave.y - timeSeconds * input.wave.z; - float radialPhase = pow(normalizedDistance, input.wave.w) * input.wave.y - timeSeconds * input.wave.z; - float ripple = input.wave.w > 0.0 ? cos(radialPhase) : sin(legacyPhase); - float signedHeight = input.shape.y * well + ripple * well * input.wave.x; - return signedHeight; -} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12LocalCastFusion.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12LocalCastFusion.hlsl deleted file mode 100644 index 059c6af..0000000 --- a/src/Aquarium.Engine/Render/Shaders/D3D12LocalCastFusion.hlsl +++ /dev/null @@ -1,256 +0,0 @@ -cbuffer AquariumFrame : register(b0) -{ - float2 resolution; - float timeSeconds; - float viewRadius; - float3 cameraPosition; - float farDistance; - float3 cameraTarget; - float sceneFlags; - float2 viewCenter; - float frameIndex; - float previousTimeSeconds; - float3 previousCameraPosition; - float previousViewRadius; - float3 previousCameraTarget; - float previousSceneFlags; - float2 previousViewCenter; - float2 jitterPixels; - float2 previousJitterPixels; - float renderDebugMode; - float exposure; - float bloomIntensity; - float bloomVeilIntensity; - float4 cursorWorlds; - float4 temporalGaussianInfo; - float4 gpuFusionInfo; -}; - -struct GpuFusionSeed -{ - float4 centerHistoryWeight; - float4 previousCenterFieldId; - float4 velocityConfidence; - float4 radiiFalloff; - float4 colorOpacity; - float4 shapePad; -}; - -struct GpuFusionPoint -{ - uint2 stableKeyHash; - uint2 sourceTimestampNs; - float x; - float y; - float z; - float radiusMeters; - float red; - float green; - float blue; - float alpha; - float confidence; - float pad; -}; - -struct TemporalGaussian -{ - float4 centerHistoryWeight; - float4 previousCenterFieldId; - float4 velocityConfidence; - float4 radiiFalloff; - float4 orientation; - float4 colorOpacity; - float4 shapePad; -}; - -struct GpuSensorCamera -{ - float4 intrinsics; - float4 distortion01; - float4 distortion23; - float4 extentsKind; - float4 textureRangeTime; - float4 worldFromSensor0; - float4 worldFromSensor1; - float4 worldFromSensor2; - float4 sensorFromWorld0; - float4 sensorFromWorld1; - float4 sensorFromWorld2; -}; - -struct AcousticConstraint -{ - float4 positionRadius; - float4 velocityConfidence; - float4 kindTimePad; -}; - -StructuredBuffer fusionSeeds : register(t26); -StructuredBuffer sensorCameras : register(t27); -Texture2D sensorTextures[8] : register(t28); -StructuredBuffer acousticConstraints : register(t36); -StructuredBuffer fusionPoints : register(t37); -RWStructuredBuffer temporalGaussiansOut : register(u0); - -float Hash01(uint value) -{ - value ^= value >> 16; - value *= 2246822519u; - value ^= value >> 13; - value *= 3266489917u; - value ^= value >> 16; - return (float)(value & 0x00ffffffu) / 16777215.0; -} - -float3 TransformSensorPoint(GpuSensorCamera camera, float3 sensorPoint) -{ - float4 p = float4(sensorPoint, 1.0); - return float3( - dot(camera.worldFromSensor0, p), - dot(camera.worldFromSensor1, p), - dot(camera.worldFromSensor2, p)); -} - -float4 LoadSensorTexture(uint slot, int3 pixel) -{ - switch (slot) - { - case 0u: return sensorTextures[0].Load(pixel); - case 1u: return sensorTextures[1].Load(pixel); - case 2u: return sensorTextures[2].Load(pixel); - case 3u: return sensorTextures[3].Load(pixel); - case 4u: return sensorTextures[4].Load(pixel); - case 5u: return sensorTextures[5].Load(pixel); - case 6u: return sensorTextures[6].Load(pixel); - default: return sensorTextures[7].Load(pixel); - } -} - -float AcousticSupport(float3 center, out float3 velocityBias) -{ - uint count = (uint)gpuFusionInfo.x; - velocityBias = float3(0.0, 0.0, 0.0); - float support = 0.0; - float weightSum = 0.0; - [loop] - for (uint index = 0u; index < min(count, 128u); index++) - { - AcousticConstraint constraint = acousticConstraints[index]; - float radius = max(0.001, constraint.positionRadius.w); - float distanceMeters = distance(center, constraint.positionRadius.xyz); - float weight = saturate(1.0 - distanceMeters / radius) * saturate(constraint.velocityConfidence.w); - support = max(support, weight); - velocityBias += constraint.velocityConfidence.xyz * weight; - weightSum += weight; - } - - if (weightSum > 0.0001) - { - velocityBias /= weightSum; - } - - return support; -} - -[numthreads(128, 1, 1)] -void D3D12LocalCastFusionCS(uint3 dispatchThreadId : SV_DispatchThreadID) -{ - uint index = dispatchThreadId.x; - uint outputCount = (uint)temporalGaussianInfo.x; - uint cameraCount = (uint)temporalGaussianInfo.y; - uint textureCount = (uint)temporalGaussianInfo.z; - uint seedCount = (uint)temporalGaussianInfo.w; - uint pointCount = (uint)gpuFusionInfo.y; - if (index >= outputCount) - { - return; - } - - TemporalGaussian gaussian; - if (index < seedCount) - { - GpuFusionSeed seed = fusionSeeds[index]; - gaussian.centerHistoryWeight = seed.centerHistoryWeight; - gaussian.previousCenterFieldId = seed.previousCenterFieldId; - gaussian.velocityConfidence = seed.velocityConfidence; - gaussian.radiiFalloff = seed.radiiFalloff; - gaussian.orientation = float4(0.0, 0.0, 0.0, 1.0); - gaussian.colorOpacity = seed.colorOpacity; - gaussian.shapePad = seed.shapePad; - temporalGaussiansOut[index] = gaussian; - return; - } - - if (index < seedCount + pointCount) - { - GpuFusionPoint nativePoint = fusionPoints[index - seedCount]; - float confidence = saturate(nativePoint.confidence); - float radius = clamp(nativePoint.radiusMeters, 0.0015, 0.09); - float opacity = saturate(nativePoint.alpha * (0.35 + confidence * 0.65)); - float fieldId = (float)((nativePoint.stableKeyHash.x ^ nativePoint.stableKeyHash.y) & 0x00ffffffu); - float3 center = float3(nativePoint.x, nativePoint.y, nativePoint.z); - - gaussian.centerHistoryWeight = float4(center, confidence); - gaussian.previousCenterFieldId = float4(center, fieldId); - gaussian.velocityConfidence = float4(0.0, 0.0, 0.0, confidence); - gaussian.radiiFalloff = float4(radius * 1.55, radius * 0.52, radius * 1.12, 4.6); - gaussian.orientation = float4(0.0, 0.0, 0.0, 1.0); - gaussian.colorOpacity = float4(saturate(nativePoint.red), saturate(nativePoint.green), saturate(nativePoint.blue), min(opacity, 0.98)); - gaussian.shapePad = float4(1.85, 0.0, 0.0, 0.0); - temporalGaussiansOut[index] = gaussian; - return; - } - - if (textureCount == 0 || cameraCount == 0) - { - gaussian.centerHistoryWeight = float4(0.0, 0.0, 0.0, 0.0); - gaussian.previousCenterFieldId = float4(0.0, 0.0, 0.0, 0.0); - gaussian.velocityConfidence = float4(0.0, 0.0, 0.0, 0.0); - gaussian.radiiFalloff = float4(0.001, 0.001, 0.001, 4.0); - gaussian.orientation = float4(0.0, 0.0, 0.0, 1.0); - gaussian.colorOpacity = float4(0.0, 0.0, 0.0, 0.0); - gaussian.shapePad = float4(1.0, 0.0, 0.0, 0.0); - temporalGaussiansOut[index] = gaussian; - return; - } - - uint textureSampleIndex = index - seedCount - pointCount; - uint textureSlot = min(textureCount - 1, textureSampleIndex / max(1u, ((outputCount - seedCount) / textureCount))); - GpuSensorCamera camera = sensorCameras[min(cameraCount - 1, textureSlot % cameraCount)]; - uint width = max(1u, (uint)camera.extentsKind.x); - uint height = max(1u, (uint)camera.extentsKind.y); - uint localIndex = textureSampleIndex + textureSlot * 747796405u; - uint x = (localIndex * 73u + (uint)(Hash01(localIndex) * 37.0)) % width; - uint y = (localIndex / width * 41u + (uint)(Hash01(localIndex ^ 0x9e3779b9u) * 29.0)) % height; - float4 rgba = LoadSensorTexture(textureSlot, int3((int)x, (int)y, 0)); - uint pairSlot = (textureSlot + 1u) % max(1u, textureCount); - float4 pairRgba = LoadSensorTexture(pairSlot, int3((int)x, (int)y, 0)); - float luma = dot(rgba.rgb, float3(0.2126, 0.7152, 0.0722)); - float pairLuma = dot(pairRgba.rgb, float3(0.2126, 0.7152, 0.0722)); - float descriptor = frac(luma * 3.17 + rgba.r * 1.91 + rgba.g * 2.37 + Hash01(localIndex ^ 0x27d4eb2du) * 0.07); - float pairDescriptor = frac(pairLuma * 3.17 + pairRgba.r * 1.91 + pairRgba.g * 2.37); - float visualMatch = 1.0 - saturate(abs(descriptor - pairDescriptor) * 3.0 + distance(rgba.rgb, pairRgba.rgb) * 0.35); - float fx = max(1.0, camera.intrinsics.x); - float fy = max(1.0, camera.intrinsics.y); - float cx = camera.intrinsics.z; - float cy = camera.intrinsics.w; - float depth = 0.75 + luma * 2.25; - float3 sensorPoint = float3(((float)x - cx) / fx * depth, ((float)y - cy) / fy * depth, depth); - float3 center = TransformSensorPoint(camera, sensorPoint); - float targetPixels = lerp(1.75, 3.75, Hash01(localIndex ^ 0x85ebca6bu)); - float focalPixels = max(1.0, 0.5 * (fx + fy)); - float screenFitRadius = targetPixels * depth / focalPixels; - float radius = clamp(screenFitRadius, 0.0015, 0.018); - float3 acousticVelocity; - float acousticSupport = AcousticSupport(center, acousticVelocity); - float confidence = saturate((0.20 + abs(luma - 0.5) * 1.15) * lerp(0.55, 1.25, visualMatch) + acousticSupport * 0.35); - - gaussian.centerHistoryWeight = float4(center, confidence); - gaussian.previousCenterFieldId = float4(center, (float)(textureSlot + 1u)); - gaussian.velocityConfidence = float4(acousticVelocity, confidence); - gaussian.radiiFalloff = float4(radius * lerp(1.85, 1.25, visualMatch), radius, radius * lerp(1.45, 1.05, visualMatch), 5.8); - gaussian.orientation = float4(0.0, 0.0, 0.0, 1.0); - gaussian.colorOpacity = float4(rgba.rgb * 1.35, saturate(0.08 + confidence * 0.42)); - gaussian.shapePad = float4(lerp(2.35, 1.45, visualMatch), descriptor, visualMatch, acousticSupport); - temporalGaussiansOut[index] = gaussian; -} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl deleted file mode 100644 index cb779a2..0000000 --- a/src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl +++ /dev/null @@ -1,474 +0,0 @@ -cbuffer AquariumFrame : register(b0) -{ - float2 resolution; - float timeSeconds; - float viewRadius; - float3 cameraPosition; - float farDistance; - float3 cameraTarget; - float sceneFlags; - float2 viewCenter; - float frameIndex; - float previousTimeSeconds; - float3 previousCameraPosition; - float previousViewRadius; - float3 previousCameraTarget; - float previousSceneFlags; - float2 previousViewCenter; - float2 jitterPixels; - float2 previousJitterPixels; - float renderDebugMode; - float exposure; - float bloomIntensity; - float bloomVeilIntensity; - float4 cursorWorlds; - float4 temporalGaussianInfo; -}; - -Texture2D sourceTexture : register(t0); -Texture2D historyTexture : register(t4); -Texture2D currentSceneMetadataTexture : register(t5); -Texture2D historyMetadataTexture : register(t6); -Texture2D currentSceneControlTexture : register(t7); -Texture2D historyControlTexture : register(t8); -Texture2D bloomTexture0 : register(t9); -Texture2D bloomTexture1 : register(t10); -Texture2D bloomTexture2 : register(t11); -Texture2D currentReservoirGuideTexture : register(t26); -Texture2D historyReservoirGuideTexture : register(t27); -SamplerState sourceSampler : register(s0); - -struct SdfObject -{ - float4 centerRadius; - float4 previousCenterPad; - float4 state; -}; - -StructuredBuffer sdfObjects : register(t24); - -struct VertexOut -{ - float4 position : SV_Position; - float2 uv : TEXCOORD0; -}; - -struct ResolveOut -{ - float4 finalColor : SV_Target0; - float4 historyColor : SV_Target1; - float4 historyMetadata : SV_Target2; - float4 historyControl : SV_Target3; - float4 historyReservoirGuide : SV_Target4; -}; - -static const float FIELD_ID_HEIGHT_FIELD = 4.0; -static const float FIELD_ID_SDF_OBJECT_BASE = 10.0; -static const int AQUARIUM_SDF_OBJECT_CAPACITY = 64; -static const float MAX_HISTORY_AGE = 32.0; -VertexOut FullscreenTriangleVS(uint vertexId : SV_VertexID) -{ - float2 uv = float2((vertexId << 1) & 2, vertexId & 2); - VertexOut output; - output.position = float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); - output.uv = uv; - return output; -} - -float luminance(float3 color) -{ - return dot(color, float3(0.2126, 0.7152, 0.0722)); -} - -float3 aces(float3 color) -{ - const float a = 2.51; - const float b = 0.03; - const float c = 2.43; - const float d = 0.59; - const float e = 0.14; - return saturate((color * (a * color + b)) / (color * (c * color + d) + e)); -} - -float3 debugFieldIdColor(float fieldId) -{ - if (fieldId < 0.5) - { - return float3(0.0, 0.0, 0.0); - } - - if (abs(fieldId - 1.0) < 0.25) - { - return float3(0.0, 0.9, 1.0); - } - - if (abs(fieldId - 2.0) < 0.25) - { - return float3(1.0, 0.92, 0.25); - } - - if (fieldId >= FIELD_ID_SDF_OBJECT_BASE) - { - float phase = frac((fieldId - FIELD_ID_SDF_OBJECT_BASE) * 0.37); - return 0.35 + 0.65 * float3( - 0.5 + 0.5 * sin(phase * 6.28318 + 0.0), - 0.5 + 0.5 * sin(phase * 6.28318 + 2.1), - 0.5 + 0.5 * sin(phase * 6.28318 + 4.2)); - } - - return float3(1.0, 0.0, 1.0); -} - -void cameraBasis(float3 camera, float3 target, out float3 forward, out float3 right, out float3 up) -{ - forward = normalize(target - camera); - right = normalize(cross(forward, float3(0.0, 0.0, 1.0))); - up = cross(right, forward); -} - -float3 rayDirectionForPixel(float2 pixel, float2 jitter, float3 camera, float3 target) -{ - float2 ndc = ((pixel + jitter) * 2.0 - resolution) / resolution.y; - float3 forward; - float3 right; - float3 up; - cameraBasis(camera, target, forward, right, up); - return normalize(forward * 1.6 + right * ndc.x + up * ndc.y); -} - -float3 temporalPreviousWorldPosition(float3 worldPosition, float fieldId) -{ - if (fieldId >= FIELD_ID_SDF_OBJECT_BASE) - { - int sdfIndex = clamp((int)round(fieldId - FIELD_ID_SDF_OBJECT_BASE), 0, AQUARIUM_SDF_OBJECT_CAPACITY - 1); - float3 currentCenter = sdfObjects[sdfIndex].centerRadius.xyz; - float3 previousCenter = sdfObjects[sdfIndex].previousCenterPad.xyz; - return previousCenter + (worldPosition - currentCenter); - } - - return worldPosition; -} - -float2 projectWorldToPreviousHistoryUv(float3 worldPosition) -{ - float3 forward; - float3 right; - float3 up; - cameraBasis(previousCameraPosition, previousCameraTarget, forward, right, up); - float3 delta = worldPosition - previousCameraPosition; - float z = max(dot(delta, forward), 0.0001); - float2 ndc = float2(dot(delta, right), dot(delta, up)) / z * 1.6; - float2 pixel = (ndc * resolution.y + resolution) * 0.5 - previousJitterPixels; - return float2(pixel.x / resolution.x, 1.0 - pixel.y / resolution.y); -} - -int2 pixelFromUv(float2 uv) -{ - return clamp((int2)floor(uv * resolution), int2(0, 0), (int2)resolution - int2(1, 1)); -} - -float4 loadCurrentMetadata(float2 uv) -{ - return currentSceneMetadataTexture.Load(int3(pixelFromUv(uv), 0)); -} - -float4 loadCurrentControl(float2 uv) -{ - return currentSceneControlTexture.Load(int3(pixelFromUv(uv), 0)); -} - -float4 loadHistoryColor(float2 uv) -{ - return historyTexture.Load(int3(pixelFromUv(uv), 0)); -} - -float4 loadHistoryMetadata(float2 uv) -{ - return historyMetadataTexture.Load(int3(pixelFromUv(uv), 0)); -} - -float4 loadHistoryControl(float2 uv) -{ - return historyControlTexture.Load(int3(pixelFromUv(uv), 0)); -} - -float4 loadCurrentReservoirGuide(float2 uv) -{ - return currentReservoirGuideTexture.Load(int3(pixelFromUv(uv), 0)); -} - -float4 loadHistoryReservoirGuide(float2 uv) -{ - return historyReservoirGuideTexture.Load(int3(pixelFromUv(uv), 0)); -} - -void currentNeighborhood(float2 uv, out float3 neighborhoodMin, out float3 neighborhoodMax) -{ - float2 texel = 1.0 / resolution; - neighborhoodMin = 100000.0; - neighborhoodMax = -100000.0; - - [unroll] - for (int y = -1; y <= 1; y++) - { - [unroll] - for (int x = -1; x <= 1; x++) - { - float3 sampleColor = sourceTexture.SampleLevel(sourceSampler, uv + float2(x, y) * texel, 0.0).rgb; - neighborhoodMin = min(neighborhoodMin, sampleColor); - neighborhoodMax = max(neighborhoodMax, sampleColor); - } - } -} - -float3 bloomColorAt(float2 uv) -{ - return bloomTexture0.SampleLevel(sourceSampler, uv, 0.0).rgb * 0.42 + - bloomTexture1.SampleLevel(sourceSampler, uv, 0.0).rgb * 0.34 + - bloomTexture2.SampleLevel(sourceSampler, uv, 0.0).rgb * 0.24; -} - -float3 presentColor(float3 scene, float2 uv, float bloomScale) -{ - float3 bloom = bloomColorAt(uv) * bloomScale; - float3 exposedScene = scene * max(exposure, 0.001); - return aces(exposedScene + bloom * bloomIntensity + luminance(bloom) * bloomVeilIntensity); -} - -float3 clampBloomFirefly(float2 uv, float3 centerColor) -{ - float2 texel = 1.0 / resolution; - float centerLuma = luminance(centerColor); - float neighborMaxLuma = 0.0; - float neighborSumLuma = 0.0; - - [unroll] - for (int y = -1; y <= 1; y++) - { - [unroll] - for (int x = -1; x <= 1; x++) - { - if (x == 0 && y == 0) - { - continue; - } - - float3 sampleColor = sourceTexture.SampleLevel(sourceSampler, uv + float2(x, y) * texel, 0.0).rgb; - float sampleLuma = luminance(sampleColor); - neighborMaxLuma = max(neighborMaxLuma, sampleLuma); - neighborSumLuma += sampleLuma; - } - } - - float neighborAvgLuma = neighborSumLuma * 0.125; - float supportedLuma = max(neighborMaxLuma * 1.55, neighborAvgLuma * 2.75) + 1.25; - float spike = smoothstep(supportedLuma, supportedLuma * 2.5 + 2.0, centerLuma); - float clampedLuma = lerp(centerLuma, min(centerLuma, supportedLuma), spike); - return centerColor * (clampedLuma / max(centerLuma, 0.0001)); -} - -float4 D3D12BloomPrefilterPS(VertexOut input) : SV_Target0 -{ - float3 color = sourceTexture.SampleLevel(sourceSampler, input.uv, 0.0).rgb; - return float4(clampBloomFirefly(input.uv, color) * max(exposure, 0.001), 1.0); -} - -float4 D3D12BloomDownsamplePS(VertexOut input) : SV_Target0 -{ - float3 sumColor = 0.0; - float sumWeight = 0.0; - uint sourceWidth; - uint sourceHeight; - sourceTexture.GetDimensions(sourceWidth, sourceHeight); - float2 texel = 1.0 / float2(max(sourceWidth, 1), max(sourceHeight, 1)); - - [unroll] - for (int y = -1; y <= 1; y++) - { - [unroll] - for (int x = -1; x <= 1; x++) - { - float3 sampleColor = sourceTexture.SampleLevel(sourceSampler, input.uv + float2(x, y) * texel, 0.0).rgb; - float weight = rcp(1.0 + luminance(sampleColor) * 0.12); - sumColor += sampleColor * weight; - sumWeight += weight; - } - } - - return float4(sumColor / max(sumWeight, 0.0001), 1.0); -} - -float4 D3D12BloomBlurHorizontalPS(VertexOut input) : SV_Target0 -{ - uint sourceWidth; - uint sourceHeight; - sourceTexture.GetDimensions(sourceWidth, sourceHeight); - float2 texel = float2(1.0 / max(sourceWidth, 1), 0.0); - float3 color = - sourceTexture.SampleLevel(sourceSampler, input.uv - texel * 2.0, 0.0).rgb * 0.06136 + - sourceTexture.SampleLevel(sourceSampler, input.uv - texel, 0.0).rgb * 0.24477 + - sourceTexture.SampleLevel(sourceSampler, input.uv, 0.0).rgb * 0.38774 + - sourceTexture.SampleLevel(sourceSampler, input.uv + texel, 0.0).rgb * 0.24477 + - sourceTexture.SampleLevel(sourceSampler, input.uv + texel * 2.0, 0.0).rgb * 0.06136; - return float4(color, 1.0); -} - -float4 D3D12BloomBlurVerticalPS(VertexOut input) : SV_Target0 -{ - uint sourceWidth; - uint sourceHeight; - sourceTexture.GetDimensions(sourceWidth, sourceHeight); - float2 texel = float2(0.0, 1.0 / max(sourceHeight, 1)); - float3 color = - sourceTexture.SampleLevel(sourceSampler, input.uv - texel * 2.0, 0.0).rgb * 0.06136 + - sourceTexture.SampleLevel(sourceSampler, input.uv - texel, 0.0).rgb * 0.24477 + - sourceTexture.SampleLevel(sourceSampler, input.uv, 0.0).rgb * 0.38774 + - sourceTexture.SampleLevel(sourceSampler, input.uv + texel, 0.0).rgb * 0.24477 + - sourceTexture.SampleLevel(sourceSampler, input.uv + texel * 2.0, 0.0).rgb * 0.06136; - return float4(color, 1.0); -} - -ResolveOut D3D12ResolvePS(VertexOut input) -{ - float2 screenUv = float2(input.uv.x, 1.0 - input.uv.y); - float2 pixel = screenUv * resolution; - float4 current = sourceTexture.SampleLevel(sourceSampler, input.uv, 0.0); - float currentTravel = current.a; - float3 rawCurrentColor = current.rgb; - float3 currentColor = current.rgb; - float4 currentMetadata = loadCurrentMetadata(input.uv); - float4 currentControl = loadCurrentControl(input.uv); - float4 currentReservoirGuide = loadCurrentReservoirGuide(input.uv); - float currentFieldId = currentMetadata.x; - float3 currentNormal = currentMetadata.yzw; - float currentCoverage = saturate(currentControl.x); - float currentStepRatio = saturate(currentControl.y); - float currentTemporalDetail = saturate(currentControl.z); - float currentReservoirConfidence = currentReservoirGuide.x > 0.0 ? saturate(currentReservoirGuide.x) : (currentControl.w > 0.0 ? saturate(currentControl.w) : 1.0); - float currentReservoirSampleAge = max(currentReservoirGuide.y, 0.0); - float currentReservoirDomainValidity = currentReservoirGuide.z > 0.0 ? saturate(currentReservoirGuide.z) : 1.0; - - float historyWeight = 0.0; - float historyAge = 0.0; - float reservoirSampleAge = currentReservoirSampleAge; - float reservoirInvalidationCode = 0.0; - float3 historyColor = currentColor; - if (frameIndex > 0.5 && currentTravel <= farDistance && currentFieldId > 0.5) - { - float3 currentRay = rayDirectionForPixel(pixel, jitterPixels, cameraPosition, cameraTarget); - float3 worldPosition = cameraPosition + currentRay * currentTravel; - float3 previousWorldPosition = temporalPreviousWorldPosition(worldPosition, currentFieldId); - float2 previousUv = projectWorldToPreviousHistoryUv(previousWorldPosition); - - if (all(previousUv >= 0.0) && all(previousUv <= 1.0)) - { - float4 previousMetadata = loadHistoryMetadata(previousUv); - float4 previousControl = loadHistoryControl(previousUv); - float4 previousReservoirGuide = loadHistoryReservoirGuide(previousUv); - float4 previous = historyTexture.SampleLevel(sourceSampler, previousUv, 0.0); - float previousFieldId = previousMetadata.x; - float previousTravel = previous.a; - float3 previousNormal = previousMetadata.yzw; - float previousCoverage = saturate(previousControl.x); - float previousTemporalDetail = saturate(previousControl.z); - float previousHistoryAge = max(previousControl.w, 0.0); - float previousReservoirConfidence = previousReservoirGuide.x > 0.0 ? saturate(previousReservoirGuide.x) : 1.0; - float previousReservoirSampleAge = max(previousReservoirGuide.y, 0.0); - float previousReservoirDomainValidity = previousReservoirGuide.z > 0.0 ? saturate(previousReservoirGuide.z) : 1.0; - float expectedPreviousTravel = distance(previousCameraPosition, previousWorldPosition); - float travelDelta = abs(previousTravel - expectedPreviousTravel); - float travelTolerance = max(0.045, expectedPreviousTravel * 0.018); - float travelWeight = 1.0 - smoothstep(travelTolerance, travelTolerance * 4.0, travelDelta); - float fieldWeight = abs(previousFieldId - currentFieldId) < 0.001 ? 1.0 : 0.0; - float normalWeight = 0.0; - if (dot(previousNormal, previousNormal) > 0.01 && dot(currentNormal, currentNormal) > 0.01) - { - normalWeight = smoothstep(0.68, 0.96, dot(normalize(previousNormal), normalize(currentNormal))); - } - - float3 neighborhoodMin; - float3 neighborhoodMax; - currentNeighborhood(input.uv, neighborhoodMin, neighborhoodMax); - float3 clampedHistory = clamp(previous.rgb, neighborhoodMin, neighborhoodMax); - float colorDelta = length(clampedHistory - currentColor); - float colorWeight = 1.0 - smoothstep(0.18, 1.2, colorDelta); - float currentLuma = luminance(currentColor); - float historyLuma = luminance(clampedHistory); - float hotSdfCurrent = currentFieldId >= FIELD_ID_SDF_OBJECT_BASE ? smoothstep(1.0, 5.0, currentLuma - historyLuma) : 0.0; - colorWeight = max(colorWeight, hotSdfCurrent * 0.82); - float coverageWeight = smoothstep(0.02, 0.55, currentCoverage); - float coverageContinuityWeight = 1.0 - smoothstep(0.10, 0.50, abs(previousCoverage - currentCoverage)); - float temporalDetailWeight = 1.0 - smoothstep(0.08, 0.45, abs(previousTemporalDetail - currentTemporalDetail)); - temporalDetailWeight = max(temporalDetailWeight, 1.0 - smoothstep(0.02, 0.12, max(previousTemporalDetail, currentTemporalDetail))); - float reservoirConfidenceWeight = lerp(0.45, 1.0, min(currentReservoirConfidence, previousReservoirConfidence)); - float reservoirDomainWeight = currentReservoirDomainValidity * previousReservoirDomainValidity; - float historyConfidence = smoothstep(0.0, 6.0, previousHistoryAge); - float validationWeight = travelWeight * colorWeight * fieldWeight * normalWeight * coverageWeight * coverageContinuityWeight * temporalDetailWeight * reservoirConfidenceWeight * reservoirDomainWeight; - - historyColor = clampedHistory; - historyWeight = 0.82 * lerp(0.35, 1.0, historyConfidence) * validationWeight; - historyAge = validationWeight > 0.01 ? min(previousHistoryAge + 1.0, MAX_HISTORY_AGE) : 0.0; - reservoirSampleAge = validationWeight > 0.01 ? min(max(currentReservoirSampleAge, previousReservoirSampleAge + 1.0), MAX_HISTORY_AGE) : currentReservoirSampleAge; - reservoirInvalidationCode = validationWeight > 0.01 ? 0.0 : 1.0; - } - } - - float combinedHistoryWeight = historyWeight; - float combinedHistoryAge = historyAge; - float3 resolved = lerp(currentColor, historyColor, combinedHistoryWeight); - float bloomStability = saturate((luminance(resolved) + 0.25) / max(luminance(currentColor) + 0.25, 0.0001)); - float3 finalColor = presentColor(resolved, input.uv, bloomStability); - if (renderDebugMode > 0.5 && renderDebugMode < 1.5) - { - finalColor = aces(rawCurrentColor * max(exposure, 0.001)); - } - else if (renderDebugMode >= 1.5 && renderDebugMode < 2.5) - { - finalColor = aces(historyColor * max(exposure, 0.001)); - } - else if (renderDebugMode >= 2.5 && renderDebugMode < 3.5) - { - finalColor = (combinedHistoryAge / MAX_HISTORY_AGE).xxx; - } - else if (renderDebugMode >= 3.5 && renderDebugMode < 4.5) - { - finalColor = combinedHistoryWeight.xxx; - } - else if (renderDebugMode >= 4.5 && renderDebugMode < 5.5) - { - finalColor = saturate(float3(currentCoverage, currentStepRatio, currentTemporalDetail)); - } - else if (renderDebugMode >= 5.5 && renderDebugMode < 6.5) - { - finalColor = debugFieldIdColor(currentFieldId); - } - else if (renderDebugMode >= 6.5 && renderDebugMode < 7.5) - { - float3 bloom = bloomColorAt(input.uv); - finalColor = aces(bloom * bloomIntensity + luminance(bloom) * bloomVeilIntensity); - } - else if (renderDebugMode >= 7.5 && renderDebugMode < 8.5) - { - float luma = luminance(currentColor * max(exposure, 0.001)); - finalColor = luma.xxx; - } - else if (renderDebugMode >= 8.5 && renderDebugMode < 9.5) - { - finalColor = currentFieldId >= FIELD_ID_SDF_OBJECT_BASE ? debugFieldIdColor(currentFieldId) : 0.0; - } - else if (renderDebugMode >= 9.5 && renderDebugMode < 10.5) - { - finalColor = currentStepRatio.xxx; - } - else if (renderDebugMode >= 11.5 && renderDebugMode < 12.5) - { - finalColor = float3(currentReservoirConfidence, saturate(reservoirSampleAge / MAX_HISTORY_AGE), currentReservoirDomainValidity); - } - ResolveOut output; - output.finalColor = float4(finalColor, 1.0); - output.historyColor = float4(resolved, currentTravel); - output.historyMetadata = currentMetadata; - output.historyControl = float4(currentControl.xyz, combinedHistoryAge); - output.historyReservoirGuide = float4(currentReservoirConfidence, reservoirSampleAge, currentReservoirDomainValidity, reservoirInvalidationCode); - return output; -} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl deleted file mode 100644 index 520b0fb..0000000 --- a/src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl +++ /dev/null @@ -1,386 +0,0 @@ -cbuffer AquariumFrame : register(b0) -{ - float2 resolution; - float timeSeconds; - float viewRadius; - float3 cameraPosition; - float farDistance; - float3 cameraTarget; - float sceneFlags; - float2 viewCenter; - float frameIndex; - float previousTimeSeconds; - float3 previousCameraPosition; - float previousViewRadius; - float3 previousCameraTarget; - float previousSceneFlags; - float2 previousViewCenter; - float2 jitterPixels; - float2 previousJitterPixels; - float renderDebugMode; - float exposure; - float bloomIntensity; - float bloomVeilIntensity; - float4 cursorWorlds; - float4 temporalGaussianInfo; -}; - -Texture2D heightFieldTexture : register(t0); -TextureCube studioPmremTexture : register(t22); -SamplerState linearSampler : register(s0); - -static const float FIELD_ID_HEIGHT_FIELD = 4.0; -static const float PI = 3.14159265359; -static const float HEIGHT_FIELD_TEXEL_COUNT = 128.0; -static const float SURFACE_FLAT_REFLECTION_MAX_LOD = 3.0; -static const float BACKGROUND_PMREM_LOD = 3.0; -static const float BACKGROUND_PMREM_CONE = 0.16; -static const float SURFACE_FLAT_SLOPE_START = 0.018; -static const float SURFACE_FLAT_SLOPE_END = 0.16; - -struct VertexOut -{ - float4 position : SV_Position; - float2 uv : TEXCOORD0; -}; - -struct SceneOut -{ - float4 colorTravel : SV_Target0; - float4 metadata : SV_Target1; - float4 control : SV_Target2; - float4 reservoirGuide : SV_Target3; - float depth : SV_Depth; -}; - -struct RayMarchResult -{ - float3 color; - float travel; - float fieldId; - float3 normal; - float coverage; - float stepCount; -}; - -VertexOut FullscreenTriangleVS(uint vertexId : SV_VertexID) -{ - float2 uv = float2((vertexId << 1) & 2, vertexId & 2); - VertexOut output; - output.position = float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); - output.uv = uv; - return output; -} - -void cameraBasis(float3 camera, float3 target, out float3 forward, out float3 right, out float3 up) -{ - forward = normalize(target - camera); - right = normalize(cross(forward, float3(0.0, 0.0, 1.0))); - up = cross(right, forward); -} - -float3 rayDirectionForPixel(float2 pixel, float2 jitter, float3 camera, float3 target) -{ - float2 ndc = ((pixel + jitter) * 2.0 - resolution) / resolution.y; - float3 forward; - float3 right; - float3 up; - cameraBasis(camera, target, forward, right, up); - return normalize(forward * 1.6 + right * ndc.x + up * ndc.y); -} - -float2 viewLocal(float2 p) -{ - return (p - viewCenter) / max(viewRadius, 0.001); -} - -float2 viewUv(float2 p) -{ - return viewLocal(p) * 0.5 + 0.5; -} - -float terrainHeight(float2 p) -{ - return heightFieldTexture.SampleLevel(linearSampler, saturate(viewUv(p)), 0.0).r; -} - -float2 terrainGradient(float2 p) -{ - float2 uv = saturate(viewUv(p)); - float2 texel = 1.0 / HEIGHT_FIELD_TEXEL_COUNT; - float texelWorld = max((viewRadius * 2.0) / HEIGHT_FIELD_TEXEL_COUNT, 0.001); - - float hLeft = heightFieldTexture.SampleLevel(linearSampler, uv - float2(texel.x, 0.0), 0.0).r; - float hRight = heightFieldTexture.SampleLevel(linearSampler, uv + float2(texel.x, 0.0), 0.0).r; - float hDown = heightFieldTexture.SampleLevel(linearSampler, uv - float2(0.0, texel.y), 0.0).r; - float hUp = heightFieldTexture.SampleLevel(linearSampler, uv + float2(0.0, texel.y), 0.0).r; - - return float2(hRight - hLeft, hUp - hDown) / (texelWorld * 2.0); -} - -bool traceHeightFieldSurfaceDirect(float3 origin, float3 direction, float intervalStart, float intervalEnd, out float3 hitPosition, out float travel) -{ - travel = max(intervalStart, 0.0); - float previousTravel = travel; - hitPosition = origin + direction * travel; - float previousGap = hitPosition.z - terrainHeight(hitPosition.xy); - float radius = max(viewRadius, 0.001); - - [loop] - for (int stepIndex = 0; stepIndex < 96; stepIndex++) - { - hitPosition = origin + direction * travel; - float2 local = (hitPosition.xy - viewCenter) / radius; - if (length(local) > 1.08 && hitPosition.z < 4.0) - { - return false; - } - - float gap = hitPosition.z - terrainHeight(hitPosition.xy); - float hitEpsilon = max(0.002, travel * 0.00035); - if (length(local) <= 1.0 && (abs(gap) <= hitEpsilon || (previousGap > 0.0 && gap <= 0.0))) - { - float alpha = previousGap / max(previousGap - gap, 0.0001); - travel = lerp(previousTravel, travel, saturate(alpha)); - hitPosition = origin + direction * travel; - return travel > intervalStart && travel < intervalEnd && travel < farDistance; - } - - float2 slope = terrainGradient(hitPosition.xy); - float terrainRate = abs(direction.z - dot(slope, direction.xy)); - float terrainStep = gap > 0.0 ? gap / max(terrainRate, 0.22) : 0.026; - terrainStep = min(terrainStep * 0.62, max(viewRadius * 0.08, 0.026)); - previousTravel = travel; - previousGap = gap; - travel += max(terrainStep, 0.026); - if (travel > intervalEnd || travel > farDistance) - { - return false; - } - } - - return false; -} - -float3 studioPmremDirection(float3 worldDirection) -{ - return normalize(float3(worldDirection.x, worldDirection.z, worldDirection.y)); -} - -void directionBasis(float3 direction, out float3 tangent, out float3 bitangent) -{ - float3 up = abs(direction.z) > 0.94 ? float3(0.0, 1.0, 0.0) : float3(0.0, 0.0, 1.0); - tangent = normalize(cross(up, direction)); - bitangent = cross(direction, tangent); -} - -float3 studioPmremSample(float3 worldDirection, float lod) -{ - return studioPmremTexture.SampleLevel(linearSampler, studioPmremDirection(worldDirection), lod).rgb; -} - -float3 studioPmremConeSample(float3 worldDirection, float lod, float cone) -{ - float3 direction = normalize(worldDirection); - float3 tangent; - float3 bitangent; - directionBasis(direction, tangent, bitangent); - - float3 sum = studioPmremSample(direction, lod) * 2.0; - sum += studioPmremSample(normalize(direction + tangent * cone), lod); - sum += studioPmremSample(normalize(direction - tangent * cone), lod); - sum += studioPmremSample(normalize(direction + bitangent * cone), lod); - sum += studioPmremSample(normalize(direction - bitangent * cone), lod); - sum += studioPmremSample(normalize(direction + (tangent + bitangent) * (cone * 0.7071)), lod); - sum += studioPmremSample(normalize(direction + (-tangent + bitangent) * (cone * 0.7071)), lod); - return sum * 0.125; -} - -float hash11(float value) -{ - return frac(sin(value * 127.1) * 43758.5453123); -} - -float hash31(float3 p) -{ - return frac(sin(dot(p, float3(12.9898, 78.233, 37.719))) * 43758.5453); -} - -float valueNoise3(float3 p) -{ - float3 cell = floor(p); - float3 local = frac(p); - local = local * local * (3.0 - 2.0 * local); - - float c000 = hash31(cell + float3(0.0, 0.0, 0.0)); - float c100 = hash31(cell + float3(1.0, 0.0, 0.0)); - float c010 = hash31(cell + float3(0.0, 1.0, 0.0)); - float c110 = hash31(cell + float3(1.0, 1.0, 0.0)); - float c001 = hash31(cell + float3(0.0, 0.0, 1.0)); - float c101 = hash31(cell + float3(1.0, 0.0, 1.0)); - float c011 = hash31(cell + float3(0.0, 1.0, 1.0)); - float c111 = hash31(cell + float3(1.0, 1.0, 1.0)); - - float x00 = lerp(c000, c100, local.x); - float x10 = lerp(c010, c110, local.x); - float x01 = lerp(c001, c101, local.x); - float x11 = lerp(c011, c111, local.x); - float y0 = lerp(x00, x10, local.y); - float y1 = lerp(x01, x11, local.y); - return lerp(y0, y1, local.z); -} - -float fractalNoise3(float3 p) -{ - float sum = 0.0; - float amplitude = 0.5; - [unroll] - for (int octave = 0; octave < 5; octave++) - { - sum += valueNoise3(p) * amplitude; - p = p * 2.03 + float3(13.7, 5.1, 9.3); - amplitude *= 0.52; - } - - return sum; -} - -float3 ifsFoldSky(float3 p) -{ - [unroll] - for (int index = 0; index < 5; index++) - { - p = abs(p) / max(dot(p, p), 0.18) - float3(0.72, 0.58, 0.49); - p = p.yzx * float3(0.91, 1.07, 0.98); - } - - return p; -} - -float3 nebulaRadiance(float3 direction) -{ - float3 p = direction * 1.15 + float3(0.17, -0.41, 0.29); - float3 folded = ifsFoldSky(p); - float galacticPlane = direction.z * 0.82 + direction.x * 0.18 - direction.y * 0.10; - float band = pow(saturate(1.0 - abs(galacticPlane) * 2.15), 2.4); - float filament = exp(-5.0 * abs(folded.x + folded.z * 0.16)) * 0.035; - float cloud = pow(saturate(fractalNoise3(direction * 3.2 + folded * 0.07) - 0.28), 2.6); - float veil = band * (0.10 + cloud * 0.14 + filament); - - float3 cold = float3(0.010, 0.035, 0.095); - float3 violet = float3(0.10, 0.035, 0.18); - float3 ember = float3(0.28, 0.095, 0.045); - float thermal = saturate(fractalNoise3(direction.zxy * 5.7 + 8.0)); - float3 color = lerp(cold, violet, thermal); - color = lerp(color, ember, saturate(band * 0.45 + folded.z * 0.06)); - return color * veil; -} - -float starClusterLayer(float3 direction, float scale, float threshold, float sharpness, float seed) -{ - float3 cell = floor(direction * scale + seed); - float3 local = frac(direction * scale + seed) - 0.5; - float n = hash31(cell); - float3 offset = float3(hash31(cell + 13.0), hash31(cell + 37.0), hash31(cell + 71.0)) - 0.5; - float d = length(local - offset * 0.72); - float star = smoothstep(threshold, 1.0, n) * exp(-d * d * sharpness); - - float parent = hash31(floor(direction * (scale * 0.09) + seed * 0.31)); - return star * smoothstep(0.72, 0.99, parent); -} - -float angularCluster(float3 direction, float3 center, float radius, float seed) -{ - float falloff = smoothstep(radius, 0.0, distance(direction, normalize(center))); - float granular = fractalNoise3(direction * 84.0 + seed); - return falloff * falloff * (0.28 + granular * 0.72); -} - -float3 fractalStarClusters(float3 direction) -{ - float stars = 0.0; - float clusterMask = 0.18; - clusterMask += angularCluster(direction, float3(-0.82, 0.21, 0.39), 0.34, 11.0) * 1.15; - clusterMask += angularCluster(direction, float3(0.36, -0.58, 0.73), 0.22, 29.0) * 0.95; - clusterMask += angularCluster(direction, float3(0.74, 0.48, -0.19), 0.27, 47.0) * 0.80; - stars += starClusterLayer(direction, 180.0, 0.985, 620.0, 3.0) * 0.35; - stars += starClusterLayer(direction, 520.0, 0.994, 1200.0, 17.0) * 0.85; - stars += starClusterLayer(direction, 1500.0, 0.998, 2100.0, 43.0) * 1.45; - stars *= clusterMask; - - float3 clusterP = ifsFoldSky(direction * 0.95 + float3(0.31, 0.07, -0.22)); - float clusterCore = exp(-260.0 * dot(clusterP.xy, clusterP.xy)) * smoothstep(0.16, 0.52, clusterP.z + 0.25); - float3 warm = float3(1.0, 0.82, 0.55); - float3 blue = float3(0.55, 0.70, 1.0); - return lerp(blue, warm, hash11(direction.x + direction.y * 3.1)) * stars + warm * clusterCore * 0.75; -} - -float3 surfaceMirrorRadiance(float3 p, float3 direction, out float3 normal) -{ - float2 gradient = terrainGradient(p.xy); - normal = normalize(float3(-gradient.x, -gradient.y, 1.0)); - float3 reflectionDirection = reflect(direction, normal); - float flatness = 1.0 - smoothstep(SURFACE_FLAT_SLOPE_START, SURFACE_FLAT_SLOPE_END, length(gradient)); - float lod = flatness * SURFACE_FLAT_REFLECTION_MAX_LOD; - return studioPmremConeSample(reflectionDirection, lod, flatness * 0.055); -} - -float3 backgroundRadiance(float3 direction) -{ - float3 studio = studioPmremConeSample(direction, BACKGROUND_PMREM_LOD, BACKGROUND_PMREM_CONE) * 0.22; - if (sceneFlags < 1.5) - { - return studio; - } - - float3 space = float3(0.0006, 0.0014, 0.0045); - float3 nebula = nebulaRadiance(direction); - float3 clusters = fractalStarClusters(direction); - float darkDust = pow(saturate(fractalNoise3(direction * 7.0 + 2.4)), 3.8); - nebula *= lerp(1.0, 0.46, darkDust); - return space + nebula + clusters + studio * 0.28; -} - -RayMarchResult traverseRay(float3 origin, float3 direction) -{ - RayMarchResult result; - result.color = backgroundRadiance(direction); - result.travel = farDistance + 1.0; - result.fieldId = 0.0; - result.normal = 0.0; - result.coverage = 0.0; - result.stepCount = 0.0; - - float3 surfacePosition; - float surfaceTravel; - bool traceHeightField = fmod(sceneFlags, 2.0) >= 1.0; - bool surfaceHit = traceHeightField && traceHeightFieldSurfaceDirect(origin, direction, 0.0, farDistance, surfacePosition, surfaceTravel); - if (surfaceHit) - { - float3 surfaceNormal; - result.color = surfaceMirrorRadiance(surfacePosition, direction, surfaceNormal); - result.travel = surfaceTravel; - result.fieldId = FIELD_ID_HEIGHT_FIELD; - result.normal = surfaceNormal; - result.coverage = 1.0; - } - - return result; -} - -SceneOut D3D12ScenePS(VertexOut input) -{ - float2 screenUv = float2(input.uv.x, 1.0 - input.uv.y); - float2 pixel = screenUv * resolution; - float3 rayDirection = rayDirectionForPixel(pixel, jitterPixels, cameraPosition, cameraTarget); - - RayMarchResult result = traverseRay(cameraPosition, rayDirection); - - SceneOut output; - output.colorTravel = float4(result.color, min(result.travel, farDistance + 1.0)); - output.metadata = float4(result.fieldId, result.normal); - output.control = float4(result.coverage, result.stepCount / 72.0, 0.0, 0.0); - output.reservoirGuide = float4(1.0, 0.0, 1.0, 0.0); - output.depth = saturate(result.travel / max(farDistance, 0.001)); - return output; -} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli b/src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli deleted file mode 100644 index 58a1941..0000000 --- a/src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli +++ /dev/null @@ -1,308 +0,0 @@ -cbuffer AquariumFrame : register(b0) -{ - float2 resolution; - float timeSeconds; - float viewRadius; - float3 cameraPosition; - float farDistance; - float3 cameraTarget; - float sceneFlags; - float2 viewCenter; - float frameIndex; - float previousTimeSeconds; - float3 previousCameraPosition; - float previousViewRadius; - float3 previousCameraTarget; - float previousSceneFlags; - float2 previousViewCenter; - float2 jitterPixels; - float2 previousJitterPixels; - float renderDebugMode; - float exposure; - float bloomIntensity; - float bloomVeilIntensity; - float4 cursorWorlds; - float4 temporalGaussianInfo; -}; - -cbuffer HeightFieldBrushes : register(b1) -{ - float4 brushCenterRadius[64]; - float4 brushShape[64]; - float4 brushWave[64]; - float4 brushDomain[64]; -}; - -TextureCube studioPmremTexture : register(t22); -TextureCube studioIrradianceTexture : register(t23); -SamplerState linearSampler : register(s0); - -struct SdfLight -{ - float4 centerRadius; - float4 radianceFieldId; -}; - -StructuredBuffer sdfLights : register(t12); - -struct SdfObject -{ - float4 centerRadius; - float4 previousCenterPad; - float4 state; -}; - -StructuredBuffer sdfObjects : register(t24); - -static const float FIELD_ID_HEIGHT_FIELD = 4.0; -static const float FIELD_ID_SDF_OBJECT_BASE = 10.0; -static const int AQUARIUM_SDF_OBJECT_CAPACITY = 64; -static const float PI = 3.14159265359; -static const int SDF_LIGHT_COUNT = 8; -static const float STUDIO_PMREM_MAX_LOD = 9.0; -static const float STUDIO_PMREM_SPECULAR_INTENSITY = 0.34; -static const float STUDIO_IRRADIANCE_INTENSITY = 0.74; - -struct SdfObjectProxyVertexOut -{ - float4 position : SV_Position; - nointerpolation float sdfIndex : TEXCOORD0; -}; - -struct SceneOut -{ - float4 colorTravel : SV_Target0; - float4 metadata : SV_Target1; - float4 control : SV_Target2; - float4 reservoirGuide : SV_Target3; - float depth : SV_Depth; -}; - -struct SdfSurface -{ - float3 baseColor; - float metallic; - float roughness; - float3 emission; - float temporalDetail; - float reservoirConfidence; -}; - -void cameraBasis(float3 camera, float3 target, out float3 forward, out float3 right, out float3 up) -{ - forward = normalize(target - camera); - right = normalize(cross(forward, float3(0.0, 0.0, 1.0))); - up = cross(right, forward); -} - -float3 rayDirectionForPixel(float2 pixel, float2 jitter, float3 camera, float3 target) -{ - float2 ndc = ((pixel + jitter) * 2.0 - resolution) / resolution.y; - float3 forward; - float3 right; - float3 up; - cameraBasis(camera, target, forward, right, up); - return normalize(forward * 1.6 + right * ndc.x + up * ndc.y); -} - -float hash21(float2 p) -{ - p = frac(p * float2(123.34, 456.21)); - p += dot(p, p + 45.32); - return frac(p.x * p.y); -} - -bool traceSphere(float3 origin, float3 direction, float3 center, float radius, out float travel) -{ - float3 oc = origin - center; - float b = dot(oc, direction); - float c = dot(oc, oc) - radius * radius; - float h = b * b - c; - if (h < 0.0) - { - travel = farDistance + 1.0; - return false; - } - - h = sqrt(h); - float t = -b - h; - if (t < 0.0) - { - t = -b + h; - } - - travel = t; - return t > 0.0 && t < farDistance; -} - -float3 studioPmremDirection(float3 worldDirection) -{ - return normalize(float3(worldDirection.x, worldDirection.z, worldDirection.y)); -} - -float3 studioPmremSample(float3 worldDirection, float lod) -{ - return studioPmremTexture.SampleLevel(linearSampler, studioPmremDirection(worldDirection), lod).rgb; -} - -float3 primitiveEmissionRadiance(float fieldId) -{ - [loop] - for (int i = 0; i < SDF_LIGHT_COUNT; i++) - { - SdfLight light = sdfLights[i]; - if (abs(light.radianceFieldId.w - fieldId) < 0.25) - { - return light.radianceFieldId.rgb; - } - } - - return 0.0; -} - -float sdfFieldId(int objectIndex) -{ - return FIELD_ID_SDF_OBJECT_BASE + (float)objectIndex; -} - -float3 pbrDielectricF0() -{ - return float3(0.04, 0.04, 0.04); -} - -float3 pbrSpecularF0(SdfSurface surface) -{ - return lerp(pbrDielectricF0(), surface.baseColor, saturate(surface.metallic)); -} - -float3 pbrDiffuseColor(SdfSurface surface) -{ - return surface.baseColor * (1.0 - saturate(surface.metallic)); -} - -float3 sdfLightRadianceAt(float3 p, SdfLight light, out float3 lightDirection, out float attenuation) -{ - float3 toLight = light.centerRadius.xyz - p; - float distanceSquared = max(dot(toLight, toLight), 0.01); - lightDirection = toLight * rsqrt(distanceSquared); - float radius = max(light.centerRadius.w, 0.001); - attenuation = saturate((radius * radius) / distanceSquared); - return light.radianceFieldId.rgb; -} - -float3 sdfLightPbrRadiance(float3 p, float3 normal, SdfSurface surface, float intensity, float shadedFieldId) -{ - static const float MinimumRoughness = 0.045; - - float3 viewDirection = normalize(cameraPosition - p); - float ndv = saturate(dot(normal, viewDirection)); - float safeRoughness = max(surface.roughness, MinimumRoughness); - float alpha = safeRoughness * safeRoughness; - float alpha2 = alpha * alpha; - float k = (safeRoughness + 1.0); - k = (k * k) * 0.125; - float geometryV = ndv / max(ndv * (1.0 - k) + k, 0.00001); - float3 f0 = pbrSpecularF0(surface); - float3 diffuseColor = pbrDiffuseColor(surface); - float3 result = 0.0; - - [loop] - for (int i = 0; i < SDF_LIGHT_COUNT; i++) - { - SdfLight light = sdfLights[i]; - if (dot(light.radianceFieldId.rgb, light.radianceFieldId.rgb) <= 0.000001) - { - continue; - } - - float3 lightDirection; - float attenuation; - float sameField = abs(light.radianceFieldId.w - shadedFieldId) < 0.25 ? 1.0 : 0.0; - float directScale = lerp(1.0, 0.08, sameField); - float3 incidentRadiance = sdfLightRadianceAt(p, light, lightDirection, attenuation) * (intensity * directScale); - float3 irradiance = incidentRadiance * attenuation; - float3 halfVector = normalize(lightDirection + viewDirection); - float ndl = saturate(dot(normal, lightDirection)); - float ndh = saturate(dot(normal, halfVector)); - float vdh = saturate(dot(viewDirection, halfVector)); - float denominator = ndh * ndh * (alpha2 - 1.0) + 1.0; - float distribution = alpha2 / max(PI * denominator * denominator, 0.00001); - float geometryL = ndl / max(ndl * (1.0 - k) + k, 0.00001); - float3 fresnel = f0 + (1.0 - f0) * pow(1.0 - vdh, 5.0); - float3 specular = (distribution * geometryL * geometryV) * fresnel / max(4.0 * ndl * ndv, 0.00001); - float3 diffuse = (1.0 - fresnel) * diffuseColor / PI; - result += (diffuse + specular) * irradiance * ndl; - } - - return result; -} - -float3 fresnelSchlickRoughness(float cosine, float3 f0, float roughness) -{ - return f0 + (max(1.0 - roughness, f0) - f0) * pow(1.0 - cosine, 5.0); -} - -float3 studioPmremSpecularRadiance(float3 p, float3 normal, SdfSurface surface) -{ - float3 viewDirection = normalize(cameraPosition - p); - float ndv = saturate(dot(normal, viewDirection)); - float3 reflectionDirection = reflect(-viewDirection, normal); - float lod = saturate(surface.roughness) * STUDIO_PMREM_MAX_LOD; - float3 radiance = studioPmremSample(reflectionDirection, lod); - float3 fresnel = fresnelSchlickRoughness(ndv, pbrSpecularF0(surface), surface.roughness); - return radiance * fresnel * STUDIO_PMREM_SPECULAR_INTENSITY; -} - -float3 studioIrradianceDiffuseRadiance(float3 p, float3 normal, SdfSurface surface) -{ - float3 viewDirection = normalize(cameraPosition - p); - float ndv = saturate(dot(normal, viewDirection)); - float3 fresnel = fresnelSchlickRoughness(ndv, pbrSpecularF0(surface), surface.roughness); - float3 diffuseShare = (1.0 - fresnel) * (1.0 - saturate(surface.metallic)); - float3 irradiance = studioIrradianceTexture.SampleLevel(linearSampler, studioPmremDirection(normal), 0.0).rgb; - return diffuseShare * surface.baseColor * irradiance * (STUDIO_IRRADIANCE_INTENSITY / PI); -} - -float3 shadeSdfPbr(float3 p, float3 normal, SdfSurface surface) -{ - surface.baseColor = saturate(surface.baseColor); - surface.metallic = saturate(surface.metallic); - surface.roughness = saturate(surface.roughness); - - return surface.emission - + sdfLightPbrRadiance(p, normal, surface, 7.0, sdfFieldId(SDF_INDEX)) - + studioIrradianceDiffuseRadiance(p, normal, surface) - + studioPmremSpecularRadiance(p, normal, surface); -} - -SdfObjectProxyVertexOut D3D12SdfObjectProxyVS(uint vertexId : SV_VertexID, uint instanceId : SV_InstanceID) -{ - float2 corners[6] = - { - float2(-1.0, -1.0), - float2(1.0, -1.0), - float2(1.0, 1.0), - float2(-1.0, -1.0), - float2(1.0, 1.0), - float2(-1.0, 1.0), - }; - - SdfObject sdfObject = sdfObjects[SDF_INDEX]; - float3 forward; - float3 right; - float3 up; - cameraBasis(cameraPosition, cameraTarget, forward, right, up); - float3 delta = sdfObject.centerRadius.xyz - cameraPosition; - float z = max(dot(delta, forward), 0.0001); - float2 projected = float2(dot(delta, right), dot(delta, up)) / z * 1.6; - float clipAspect = resolution.x / max(resolution.y, 1.0); - float boundRadius = sdfObject.centerRadius.w * 1.58; - float projectedRadius = boundRadius / z * 1.6 + 0.035; - float2 clipCenter = float2(projected.x / clipAspect, projected.y); - float2 clipRadius = float2(projectedRadius / clipAspect, projectedRadius); - - SdfObjectProxyVertexOut output; - output.position = float4(clipCenter + corners[vertexId] * clipRadius, 0.0, 1.0); - output.sdfIndex = (float)SDF_INDEX; - return output; -} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli b/src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli deleted file mode 100644 index 98fe222..0000000 --- a/src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli +++ /dev/null @@ -1,113 +0,0 @@ -#ifndef AQUARIUM_D3D12_SDF_MATH_HLSLI -#define AQUARIUM_D3D12_SDF_MATH_HLSLI - -float sdSphere(float3 p, float radius) -{ - return length(p) - radius; -} - -float sdTorus(float3 p, float2 radius) -{ - float2 q = float2(length(p.xy) - radius.x, p.z); - return length(q) - radius.y; -} - -float sdCapsuleSegment(float3 p, float3 a, float3 b, float radius) -{ - float3 pa = p - a; - float3 ba = b - a; - float h = saturate(dot(pa, ba) / max(dot(ba, ba), 0.0001)); - return length(pa - ba * h) - radius; -} - -float sdTaperedCapsuleSegment(float3 p, float3 a, float3 b, float radiusA, float radiusB) -{ - float3 pa = p - a; - float3 ba = b - a; - float h = saturate(dot(pa, ba) / max(dot(ba, ba), 0.0001)); - float radius = lerp(radiusA, radiusB, h); - return length(pa - ba * h) - radius; -} - -float sdQuadraticTube(float3 p, float3 a, float3 b, float3 c, float radiusA, float radiusC) -{ - float t0 = 0.3333333; - float u0 = 1.0 - t0; - float3 p0 = a * (u0 * u0) + b * (2.0 * u0 * t0) + c * (t0 * t0); - float r0 = lerp(radiusA, radiusC, t0); - - float t1 = 0.6666667; - float u1 = 1.0 - t1; - float3 p1 = a * (u1 * u1) + b * (2.0 * u1 * t1) + c * (t1 * t1); - float r1 = lerp(radiusA, radiusC, t1); - - float s0 = sdTaperedCapsuleSegment(p, a, p0, radiusA, r0); - float s1 = sdTaperedCapsuleSegment(p, p0, p1, r0, r1); - float s2 = sdTaperedCapsuleSegment(p, p1, c, r1, radiusC); - return min(s0, min(s1, s2)); -} - -float sdSuperellipsoid(float3 p, float3 scale, float exponent) -{ - float3 q = abs(p) / scale; - float value = pow(pow(q.x, exponent) + pow(q.y, exponent) + pow(q.z, exponent), 1.0 / exponent); - return (value - 1.0) * min(scale.x, min(scale.y, scale.z)); -} - -float sdEllipsoid(float3 p, float3 radius) -{ - float3 safeRadius = max(radius, 0.001); - float k0 = length(p / safeRadius); - float k1 = length(p / (safeRadius * safeRadius)); - return k0 * (k0 - 1.0) / max(k1, 0.001); -} - -float smoothUnion(float a, float b, float radius) -{ - float h = saturate(0.5 + 0.5 * (b - a) / radius); - return lerp(b, a, h) - radius * h * (1.0 - h); -} - -float sdEllipseFootprint(float2 p, float2 radius) -{ - float2 safeRadius = max(radius, 0.001); - return (length(p / safeRadius) - 1.0) * min(safeRadius.x, safeRadius.y); -} - -float sdLensFootprint(float2 p, float2 a, float2 b, float radius) -{ - return max(length(p - a) - radius, length(p - b) - radius); -} - -float sdTaperedCapsule2(float2 p, float2 a, float2 b, float radiusA, float radiusB) -{ - float2 pa = p - a; - float2 ba = b - a; - float h = saturate(dot(pa, ba) / max(dot(ba, ba), 0.0001)); - float radius = lerp(radiusA, radiusB, h); - return length(pa - ba * h) - radius; -} - -float teardropProfileRadius(float z, float contactZ, float tipZ, float radiusScale, float ripplePhase, float rippleAmount) -{ - float u = saturate((z - contactZ) / (tipZ - contactZ)); - float x = u * 2.0 - 1.0; - float halfTerm = (1.0 - x) * 0.5; - float teardropWeight = halfTerm * halfTerm * halfTerm; - float baseRadius = radiusScale * sqrt(saturate(1.0 - x * x)) * teardropWeight; - float rippleEnvelope = smoothstep(0.08, 0.22, u) * (1.0 - smoothstep(0.76, 0.94, u)); - float rippleRadius = min(rippleAmount, baseRadius * 0.07) * sin(ripplePhase) * rippleEnvelope; - return max(baseRadius + rippleRadius, 0.0); -} - -float sdTeardropRevolution(float3 local, float contactZ, float tipZ, float radiusScale, float ripplePhase, float rippleAmount) -{ - float2 samplePoint = float2(length(local.xy), local.z); - float profileRadius = teardropProfileRadius(samplePoint.y, contactZ, tipZ, radiusScale, ripplePhase, rippleAmount); - float radialDistance = samplePoint.x - profileRadius; - float topDistance = samplePoint.y - tipZ; - float bottomDistance = contactZ - samplePoint.y; - return max(radialDistance, max(topDistance, bottomDistance)); -} - -#endif diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli b/src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli deleted file mode 100644 index a52c704..0000000 --- a/src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli +++ /dev/null @@ -1,140 +0,0 @@ -#ifndef SDF_TRACE_STEPS -#define SDF_TRACE_STEPS 384 -#endif - -#ifndef SDF_TRACE_STEP_SCALE -#define SDF_TRACE_STEP_SCALE 0.20 -#endif - -#ifndef SDF_TRACE_MIN_STEP -#define SDF_TRACE_MIN_STEP 0.0009 -#endif - -#ifndef SDF_TRACE_MAX_STEP_RADIUS_SCALE -#define SDF_TRACE_MAX_STEP_RADIUS_SCALE 0.012 -#endif - -float3 sdfNormal(float3 p, int sdfIndex) -{ - float epsilon = 0.006; - float dx = sdfDistance(p + float3(epsilon, 0.0, 0.0), sdfIndex) - sdfDistance(p - float3(epsilon, 0.0, 0.0), sdfIndex); - float dy = sdfDistance(p + float3(0.0, epsilon, 0.0), sdfIndex) - sdfDistance(p - float3(0.0, epsilon, 0.0), sdfIndex); - float dz = sdfDistance(p + float3(0.0, 0.0, epsilon), sdfIndex) - sdfDistance(p - float3(0.0, 0.0, epsilon), sdfIndex); - return normalize(float3(dx, dy, dz)); -} - -bool refineSdfHit(float3 origin, float3 direction, int sdfIndex, float lowTravel, float highTravel, out float travel, out float3 normal, out SdfSurface surface) -{ - [unroll] - for (int i = 0; i < 8; i++) - { - float midTravel = (lowTravel + highTravel) * 0.5; - float midDistance = sdfDistance(origin + direction * midTravel, sdfIndex); - if (midDistance <= 0.0) - { - highTravel = midTravel; - } - else - { - lowTravel = midTravel; - } - } - - travel = highTravel; - float3 p = origin + direction * travel; - surface = sdfSurface(p, sdfIndex); - normal = sdfNormal(p, sdfIndex); - return true; -} - -bool traceSdf(float3 origin, float3 direction, int sdfIndex, out float travel, out float3 normal, out SdfSurface surface, out float stepCount) -{ - SdfObject sdfObject = sdfObjects[sdfIndex]; - float boundRadius = max(sdfObject.centerRadius.w * 1.42, 0.001); - if (!traceSphere(origin, direction, sdfObject.centerRadius.xyz, boundRadius, travel)) - { - normal = 0.0; - stepCount = 0.0; - surface = sdfSurface(sdfObject.centerRadius.xyz, sdfIndex); - return false; - } - - float3 oc = origin - sdfObject.centerRadius.xyz; - float b = dot(oc, direction); - float c = dot(oc, oc) - boundRadius * boundRadius; - float h = sqrt(max(b * b - c, 0.0)); - float endTravel = min(-b + h, farDistance); - travel = max(-b - h, 0.0); - normal = 0.0; - stepCount = 0.0; - surface.baseColor = 0.0; - surface.metallic = 0.0; - surface.roughness = 0.0; - surface.emission = 0.0; - surface.temporalDetail = 0.0; - surface.reservoirConfidence = 1.0; - float previousTravel = travel; - float previousDistance = sdfDistance(origin + direction * travel, sdfIndex); - float maxStep = max(sdfObject.centerRadius.w * SDF_TRACE_MAX_STEP_RADIUS_SCALE, SDF_TRACE_MIN_STEP); - - [loop] - for (int stepIndex = 0; stepIndex < SDF_TRACE_STEPS; stepIndex++) - { - if (travel > endTravel) - { - return false; - } - - float3 p = origin + direction * travel; - float distanceValue = sdfDistance(p, sdfIndex); - stepCount = (float)(stepIndex + 1); - if (distanceValue <= 0.0) - { - if (previousDistance > 0.0) - { - return refineSdfHit(origin, direction, sdfIndex, previousTravel, travel, travel, normal, surface); - } - - surface = sdfSurface(p, sdfIndex); - normal = sdfNormal(p, sdfIndex); - return true; - } - - previousTravel = travel; - previousDistance = distanceValue; - travel += clamp(abs(distanceValue) * SDF_TRACE_STEP_SCALE, SDF_TRACE_MIN_STEP, maxStep); - } - - return false; -} - -SceneOut D3D12SdfProxyPS(SdfObjectProxyVertexOut input) -{ - float2 pixel = float2(input.position.x, resolution.y - input.position.y); - float2 uv = float2(pixel.x / max(resolution.x, 1.0), 1.0 - pixel.y / max(resolution.y, 1.0)); - float3 rayDirection = rayDirectionForPixel(pixel, jitterPixels, cameraPosition, cameraTarget); - int sdfIndex = clamp((int)round(input.sdfIndex), 0, AQUARIUM_SDF_OBJECT_CAPACITY - 1); - - float travel; - float3 normal; - SdfSurface surface; - float stepCount; - if (!traceSdf(cameraPosition, rayDirection, sdfIndex, travel, normal, surface, stepCount)) - { - discard; - } - - float3 p = cameraPosition + rayDirection * travel; - float fieldId = sdfFieldId(sdfIndex); - SceneOut output; - output.colorTravel = float4(shadeSdf(uv, travel, p, normal, sdfIndex, surface), min(travel, farDistance + 1.0)); - output.metadata = float4(fieldId, normal); - output.control = float4( - 1.0, - stepCount / (float)SDF_TRACE_STEPS, - saturate(surface.temporalDetail), - saturate(surface.reservoirConfidence)); - output.reservoirGuide = float4(saturate(surface.reservoirConfidence), 0.0, 1.0, 0.0); - output.depth = saturate(travel / max(farDistance, 0.001)); - return output; -} diff --git a/src/Aquarium.Engine/Render/Shaders/D3D12TemporalGaussian.hlsl b/src/Aquarium.Engine/Render/Shaders/D3D12TemporalGaussian.hlsl deleted file mode 100644 index dfc6f21..0000000 --- a/src/Aquarium.Engine/Render/Shaders/D3D12TemporalGaussian.hlsl +++ /dev/null @@ -1,183 +0,0 @@ -cbuffer AquariumFrame : register(b0) -{ - float2 resolution; - float timeSeconds; - float viewRadius; - float3 cameraPosition; - float farDistance; - float3 cameraTarget; - float sceneFlags; - float2 viewCenter; - float frameIndex; - float previousTimeSeconds; - float3 previousCameraPosition; - float previousViewRadius; - float3 previousCameraTarget; - float previousSceneFlags; - float2 previousViewCenter; - float2 jitterPixels; - float2 previousJitterPixels; - float renderDebugMode; - float exposure; - float bloomIntensity; - float bloomVeilIntensity; - float4 cursorWorlds; - float4 temporalGaussianInfo; -}; - -struct TemporalGaussian -{ - float4 centerHistoryWeight; - float4 previousCenterFieldId; - float4 velocityConfidence; - float4 radiiFalloff; - float4 orientation; - float4 colorOpacity; - float4 shapePad; -}; - -StructuredBuffer temporalGaussians : register(t25); - -struct TemporalGaussianVertexOut -{ - float4 position : SV_Position; - nointerpolation uint gaussianIndex : TEXCOORD0; -}; - -struct SceneOut -{ - float4 colorTravel : SV_Target0; - float4 metadata : SV_Target1; - float4 control : SV_Target2; - float4 reservoirGuide : SV_Target3; - float depth : SV_Depth; -}; - -static const float FIELD_ID_TEMPORAL_GAUSSIAN_BASE = 2000.0; - -void cameraBasis(float3 camera, float3 target, out float3 forward, out float3 right, out float3 up) -{ - forward = normalize(target - camera); - right = normalize(cross(forward, float3(0.0, 0.0, 1.0))); - up = cross(right, forward); -} - -float3 rayDirectionForPixel(float2 pixel, float2 jitter, float3 camera, float3 target) -{ - float2 ndc = ((pixel + jitter) * 2.0 - resolution) / resolution.y; - float3 forward; - float3 right; - float3 up; - cameraBasis(camera, target, forward, right, up); - return normalize(forward * 1.6 + right * ndc.x + up * ndc.y); -} - -float3 rotateByQuaternion(float3 p, float4 q) -{ - return p + 2.0 * cross(q.xyz, cross(q.xyz, p) + q.w * p); -} - -float3 inverseRotateByQuaternion(float3 p, float4 q) -{ - return rotateByQuaternion(p, float4(-q.xyz, q.w)); -} - -float4 safeNormalizeQuaternion(float4 q) -{ - return dot(q, q) <= 0.000001 ? float4(0.0, 0.0, 0.0, 1.0) : normalize(q); -} - -float compactGaussianWeight(TemporalGaussian gaussian, float3 p) -{ - float3 local = inverseRotateByQuaternion(p - gaussian.centerHistoryWeight.xyz, safeNormalizeQuaternion(gaussian.orientation)); - float3 radii = max(gaussian.radiiFalloff.xyz, 0.0001); - float3 q = local / radii; - float radiusSquared = dot(q, q); - if (radiusSquared >= 1.0) - { - return 0.0; - } - - float falloff = max(gaussian.radiiFalloff.w, 0.0001); - float edge = exp(-falloff); - float value = exp(-falloff * radiusSquared); - float compact = saturate((value - edge) / max(1.0 - edge, 0.000001)); - return pow(compact, max(gaussian.shapePad.x, 0.0001)); -} - -TemporalGaussianVertexOut D3D12TemporalGaussianVS(uint vertexId : SV_VertexID, uint instanceId : SV_InstanceID) -{ - float2 corners[6] = - { - float2(-1.0, -1.0), - float2(1.0, -1.0), - float2(1.0, 1.0), - float2(-1.0, -1.0), - float2(1.0, 1.0), - float2(-1.0, 1.0), - }; - - TemporalGaussian gaussian = temporalGaussians[instanceId]; - float3 forward; - float3 right; - float3 up; - cameraBasis(cameraPosition, cameraTarget, forward, right, up); - float3 center = gaussian.centerHistoryWeight.xyz; - float3 delta = center - cameraPosition; - float z = max(dot(delta, forward), 0.0001); - float2 projected = float2(dot(delta, right), dot(delta, up)) / z * 1.6; - float clipAspect = resolution.x / max(resolution.y, 1.0); - float boundRadius = max(max(gaussian.radiiFalloff.x, gaussian.radiiFalloff.y), gaussian.radiiFalloff.z) * 1.12; - float projectedRadius = boundRadius / z * 1.6 + 0.004; - float2 clipCenter = float2(projected.x / clipAspect, projected.y); - float2 clipRadius = float2(projectedRadius / clipAspect, projectedRadius); - - TemporalGaussianVertexOut output; - output.position = float4(clipCenter + corners[vertexId] * clipRadius, 0.0, 1.0); - output.gaussianIndex = instanceId; - return output; -} - -SceneOut D3D12TemporalGaussianPS(TemporalGaussianVertexOut input) -{ - TemporalGaussian gaussian = temporalGaussians[input.gaussianIndex]; - float2 pixel = float2(input.position.x, resolution.y - input.position.y); - float3 rayDirection = rayDirectionForPixel(pixel, jitterPixels, cameraPosition, cameraTarget); - float3 forward; - float3 right; - float3 up; - cameraBasis(cameraPosition, cameraTarget, forward, right, up); - - float planeDenominator = dot(rayDirection, forward); - if (abs(planeDenominator) <= 0.00001) - { - discard; - } - - float travel = dot(gaussian.centerHistoryWeight.xyz - cameraPosition, forward) / planeDenominator; - if (travel <= 0.0 || travel >= farDistance) - { - discard; - } - - float3 p = cameraPosition + rayDirection * travel; - float weight = compactGaussianWeight(gaussian, p); - float opacity = saturate(weight * gaussian.colorOpacity.w * gaussian.velocityConfidence.w); - if (opacity <= 0.002) - { - discard; - } - - float4 orientation = safeNormalizeQuaternion(gaussian.orientation); - float3 local = inverseRotateByQuaternion(p - gaussian.centerHistoryWeight.xyz, orientation); - float3 radii = max(gaussian.radiiFalloff.xyz, 0.0001); - float3 normal = normalize(rotateByQuaternion(local / (radii * radii), orientation)); - - SceneOut output; - output.colorTravel = float4(gaussian.colorOpacity.rgb * opacity, min(travel, farDistance + 1.0)); - output.metadata = float4(FIELD_ID_TEMPORAL_GAUSSIAN_BASE + gaussian.previousCenterFieldId.w, normal); - output.control = float4(opacity, saturate(gaussian.centerHistoryWeight.w), saturate(gaussian.shapePad.x / 8.0), 0.0); - output.reservoirGuide = float4(saturate(gaussian.velocityConfidence.w), 0.0, 1.0, 0.0); - output.depth = saturate(travel / max(farDistance, 0.001)); - return output; -} diff --git a/src/Aquarium.Engine/Render/Ui/DebugUi.cs b/src/Aquarium.Engine/Render/Ui/DebugUi.cs deleted file mode 100644 index e3ba5ae..0000000 --- a/src/Aquarium.Engine/Render/Ui/DebugUi.cs +++ /dev/null @@ -1,2142 +0,0 @@ -using System.Globalization; -using System.Numerics; -using Aquarium.Engine.Input; -using Aquarium.Engine.Ui; -using SharpGen.Runtime; -using Vortice.Direct2D1; -using Vortice.DirectWrite; -using Vortice.Mathematics; - -namespace Aquarium.Engine.Render.Ui; - -internal sealed class DebugUi -{ - private const float DefaultPanelLeft = 18.0f; - private const float DefaultPanelTop = 82.0f; - private const float DefaultPanelWidth = 360.0f; - private const float HeaderHeight = 42.0f; - private const float RowHeight = 31.0f; - private const float RowGap = 6.0f; - private const float SectionHeight = 22.0f; - private const float LabelWidth = 168.0f; - private const float TrackWidth = 104.0f; - private const float TrackHeight = 5.0f; - private const float ValueTrackGap = 12.0f; - private const float CloseButtonSize = 20.0f; - private const float TooltipWidth = 268.0f; - private const float TooltipHeight = 34.0f; - private const float TabRowHeight = 30.0f; - private const float TabButtonGap = 6.0f; - private const float ScreenMargin = 10.0f; - - private readonly List controls = []; - private readonly IReadOnlyList tabs; - private readonly Func readActiveTab; - private readonly Action writeActiveTab; - private readonly float panelLeft; - private readonly float panelTop; - private readonly float panelWidth; - private readonly bool fadeWhenMouseDistant; - private int? activeSliderId; - private int? activeControlId; - private int? focusedTextId; - private bool closeButtonHovered; - private bool closeButtonActive; - private Rect panelBounds; - private Vector2 mousePosition; - private int lastViewportHeight = 720; - private int lastViewportWidth = 1280; - private float bodyScrollOffset; - private float bodyContentHeight; - private Rect bodyClipBounds; - - public DebugUi(string title) - : this(title, DefaultPanelLeft, DefaultPanelTop, DefaultPanelWidth, [], () => 0, _ => { }) - { - } - - public DebugUi(string title, float left, float top, float width) - : this(title, left, top, width, [], () => 0, _ => { }) - { - } - - public DebugUi(string title, float left, float top, float width, IReadOnlyList tabs, Func readActiveTab, Action writeActiveTab) - : this(title, left, top, width, fadeWhenMouseDistant: false, tabs, readActiveTab, writeActiveTab) - { - } - - public DebugUi(string title, float left, float top, float width, bool fadeWhenMouseDistant, IReadOnlyList tabs, Func readActiveTab, Action writeActiveTab) - { - Title = title; - panelLeft = left; - panelTop = top; - panelWidth = width; - this.fadeWhenMouseDistant = fadeWhenMouseDistant; - this.tabs = tabs; - this.readActiveTab = readActiveTab; - this.writeActiveTab = writeActiveTab; - } - - public string Title { get; } - - public bool IsVisible { get; set; } = true; - - public bool WantsMouse { get; private set; } - - public bool WantsKeyboard { get; private set; } - - public static DebugUi FromContract(AquariumUiPanel source) - { - var ui = new DebugUi(source.Title, source.Left, source.Top, source.Width, source.FadeWhenMouseDistant, [], () => 0, _ => { }); - foreach (var control in source.Controls) - { - ui.AddContractControl(control); - } - - return ui; - } - - public DebugUi Panel(Action compose) - { - var panel = new DebugUiPanel(controls); - compose(panel); - return this; - } - - public void AddContractControl(AquariumUiControl control) - { - switch (control) - { - case AquariumUiSection section: - controls.Add(new SectionControl(section.Label, () => section.Visible)); - break; - case AquariumUiButton button: - controls.Add(new ButtonControl(button.Label, button.Action, button.Tooltip, () => button.Visible)); - break; - case AquariumUiToggle toggle: - controls.Add(new ToggleControl(toggle.Label, toggle.Read, toggle.Write, toggle.Tooltip, () => toggle.Visible)); - break; - case AquariumUiTreeItem treeItem: - controls.Add(new TreeItemControl( - treeItem.Label, - treeItem.Depth, - treeItem.CanExpand, - treeItem.IsExpanded, - treeItem.SetExpanded, - treeItem.IsSelected, - treeItem.Select, - treeItem.Detail, - treeItem.Tooltip, - () => treeItem.Visible)); - break; - case AquariumUiFloatSlider slider: - controls.Add(new FloatSliderControl(slider.Label, slider.Read, slider.Write, slider.Min, slider.Max, slider.Format, slider.Tooltip, () => slider.Visible)); - break; - case AquariumUiIntSlider slider: - controls.Add(new IntSliderControl(slider.Label, slider.Read, slider.Write, slider.Min, slider.Max, slider.Tooltip, () => slider.Visible)); - break; - case AquariumUiOptions options: - controls.Add(new OptionControl( - options.Label, - options.Read, - options.Write, - options.Options.Select(option => new DebugUiOption(option.Value, option.Label)).ToArray(), - options.Tooltip, - () => options.Visible)); - break; - case AquariumUiText text: - controls.Add(new TextControl(text.Label, text.Read, text.Write, text.Tooltip, () => text.Visible)); - break; - case AquariumUiTextBox textBox: - controls.Add(new TextBoxControl(textBox.Label, textBox.Read, textBox.Write, textBox.Lines, textBox.AcceptsReturn, textBox.Submit, textBox.Monospace, textBox.AlignBottom, textBox.Tooltip, () => textBox.Visible)); - break; - case AquariumUiReadout readout: - controls.Add(new ReadoutControl(readout.Label, readout.Read, readout.Tooltip, () => readout.Visible)); - break; - } - } - - public void Update(InputState input) - { - if (input.IsKeyPressed(KeyCode.DebugUiToggle)) - { - IsVisible = !IsVisible; - } - - if (!IsVisible) - { - WantsMouse = false; - WantsKeyboard = false; - activeSliderId = null; - focusedTextId = null; - bodyScrollOffset = 0.0f; - return; - } - - Layout(); - mousePosition = input.MousePosition; - if (focusedTextId is { } focusedId && controls.All(control => !control.IsVisible || control.Id != focusedId)) - { - focusedTextId = null; - } - - var openOption = OpenOptionControl(); - WantsKeyboard = focusedTextId is not null; - WantsMouse = Contains(panelBounds, mousePosition) - || (openOption is not null && Contains(openOption.PopupBounds(lastViewportHeight), mousePosition)); - closeButtonHovered = Contains(CloseButtonBounds(), mousePosition); - closeButtonActive = closeButtonHovered && input.LeftMouseDown; - foreach (var control in controls.Where(control => control.IsVisible)) - { - control.UpdateHover(mousePosition, bodyClipBounds); - control.IsActive = control.Id == activeControlId && input.LeftMouseDown; - } - - openOption?.UpdatePopupHover(mousePosition, lastViewportHeight); - - if (!input.LeftMouseDown) - { - activeSliderId = null; - activeControlId = null; - } - - if (openOption is not null - && Contains(openOption.PopupBounds(lastViewportHeight), mousePosition) - && Math.Abs(input.WheelDelta) > 0.0f) - { - openOption.ScrollPopup(input.WheelDelta, mousePosition, lastViewportHeight); - return; - } - - if (Math.Abs(input.WheelDelta) > 0.0f) - { - for (var index = controls.Count - 1; index >= 0; index--) - { - var control = controls[index]; - if (control.IsVisible - && control.HitTest(mousePosition) - && control is ITextInputControl textControl - && textControl.Scroll(input.WheelDelta)) - { - return; - } - } - - if (Contains(panelBounds, mousePosition) && ScrollBody(input.WheelDelta)) - { - Layout(); - return; - } - } - - if (activeSliderId is { } sliderId) - { - if (controls.FirstOrDefault(control => control.IsVisible && control.Id == sliderId) is SliderControl activeSlider) - { - activeSlider.IsActive = true; - activeSlider.Drag(mousePosition); - } - - return; - } - - if (activeControlId is { } textDragId && input.LeftMouseDown) - { - if (controls.FirstOrDefault(control => control.IsVisible && control.Id == textDragId) is ITextInputControl textControl) - { - textControl.SelectToPoint(mousePosition); - return; - } - } - - if (!input.IsMousePressed(MouseButton.Left)) - { - ApplyTextInput(input); - return; - } - - if (openOption is not null) - { - if (Contains(openOption.PopupBounds(lastViewportHeight), mousePosition)) - { - openOption.ClickPopup(mousePosition, lastViewportHeight); - focusedTextId = null; - activeSliderId = null; - activeControlId = null; - return; - } - - if (!openOption.HitTest(mousePosition)) - { - openOption.DismissTransientState(); - focusedTextId = null; - activeSliderId = null; - activeControlId = null; - return; - } - } - - if (closeButtonHovered) - { - IsVisible = false; - focusedTextId = null; - return; - } - - var tabIndex = HitTestTab(mousePosition); - if (tabIndex >= 0) - { - writeActiveTab(tabIndex); - focusedTextId = null; - activeSliderId = null; - activeControlId = null; - return; - } - - DebugUiControl? clickedControl = null; - focusedTextId = null; - for (var index = controls.Count - 1; index >= 0; index--) - { - var control = controls[index]; - if (!control.IsVisible) - { - continue; - } - - if (!Contains(bodyClipBounds, mousePosition) || !control.HitTest(mousePosition)) - { - continue; - } - - control.Click(mousePosition); - activeControlId = control.Id; - control.IsActive = true; - if (control is OptionControl optionControl && optionControl.IsOpen) - { - optionControl.ClampScroll(lastViewportHeight); - } - - if (control is ITextInputControl) - { - focusedTextId = control.Id; - } - - if (control is SliderControl slider) - { - activeSliderId = slider.Id; - slider.Drag(mousePosition); - } - - clickedControl = control; - break; - } - - foreach (var control in controls.Where(control => control.IsVisible)) - { - if (!ReferenceEquals(control, clickedControl)) - { - control.DismissTransientState(); - } - } - - ApplyTextInput(input); - } - - private void ApplyTextInput(InputState input) - { - if (focusedTextId is not { } textId) - { - return; - } - - if (controls.FirstOrDefault(control => control.IsVisible && control.Id == textId) is ITextInputControl textControl) - { - textControl.ApplyTextInput(input); - } - } - - public void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat titleFormat, - IDWriteTextFormat smallFormat, - IDWriteTextFormat monospaceFormat, - ID2D1SolidColorBrush panelBrush, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush, - int viewportWidth, - int viewportHeight) - { - if (!IsVisible) - { - return; - } - - lastViewportWidth = viewportWidth; - lastViewportHeight = viewportHeight; - Layout(); - - target.FillRectangle(panelBounds, panelBrush); - target.DrawRectangle(panelBounds, outlineBrush, 1.0f); - target.DrawLine( - new Vector2(panelBounds.Left, panelBounds.Top + HeaderHeight), - new Vector2(panelBounds.Right, panelBounds.Top + HeaderHeight), - outlineBrush, - 1.0f); - if (tabs.Count > 0) - { - target.DrawLine( - new Vector2(panelBounds.Left, panelBounds.Top + HeaderHeight + TabRowHeight), - new Vector2(panelBounds.Right, panelBounds.Top + HeaderHeight + TabRowHeight), - outlineBrush, - 1.0f); - } - - target.DrawText( - Title, - titleFormat, - RectFromEdges(panelBounds.Left + 12.0f, panelBounds.Top + 8.0f, panelBounds.Right - 42.0f, panelBounds.Top + HeaderHeight - 4.0f), - primaryBrush, - DrawTextOptions.Clip); - - var close = CloseButtonBounds(); - if (closeButtonHovered) - { - target.FillRectangle(close, closeButtonActive ? activeRowBrush : hoverRowBrush); - } - - var closeBrush = closeButtonHovered ? accentBrush : quietBrush; - target.DrawLine( - new Vector2(close.Left + 6.0f, close.Top + 6.0f), - new Vector2(close.Right - 6.0f, close.Bottom - 6.0f), - closeBrush, - closeButtonActive ? 2.0f : 1.25f); - target.DrawLine( - new Vector2(close.Right - 6.0f, close.Top + 6.0f), - new Vector2(close.Left + 6.0f, close.Bottom - 6.0f), - closeBrush, - closeButtonActive ? 2.0f : 1.25f); - - DrawTabs(target, smallFormat, rowBrush, hoverRowBrush, activeRowBrush, outlineBrush, primaryBrush, quietBrush, accentBrush); - - target.PushAxisAlignedClip(bodyClipBounds, AntialiasMode.Aliased); - foreach (var control in controls.Where(control => control.IsVisible && Intersects(control.Bounds, bodyClipBounds))) - { - control.IsFocused = control.Id == focusedTextId; - control.Draw( - target, - directWriteFactory, - control.UseMonospace ? monospaceFormat : smallFormat, - rowBrush, - hoverRowBrush, - activeRowBrush, - outlineBrush, - primaryBrush, - quietBrush, - accentBrush, - accentHoverBrush, - accentActiveBrush, - dimAccentBrush, - trackHoverBrush, - trackActiveBrush); - } - target.PopAxisAlignedClip(); - - DrawBodyScrollbar(target, quietBrush, accentBrush); - - OpenOptionControl()?.DrawPopup( - target, - smallFormat, - rowBrush, - hoverRowBrush, - outlineBrush, - primaryBrush, - accentBrush, - viewportHeight); - - DrawTooltip(target, smallFormat, panelBrush, outlineBrush, primaryBrush, accentBrush, viewportWidth, viewportHeight); - } - - private OptionControl? OpenOptionControl() - { - return controls.OfType().FirstOrDefault(control => control.IsVisible && control.IsOpen); - } - - private void Layout() - { - var left = ResolvedPanelLeft(); - var bodyTop = panelTop + HeaderHeight + (tabs.Count > 0 ? TabRowHeight : 0.0f) + 10.0f; - var maxPanelBottom = MathF.Max(bodyTop + RowHeight, lastViewportHeight - ScreenMargin); - var visibleControls = controls.Where(control => control.IsVisible).ToArray(); - bodyContentHeight = ContentHeight(visibleControls); - var desiredBottom = bodyTop + bodyContentHeight + 12.0f; - var bottom = lastViewportHeight > 0 ? Math.Min(desiredBottom, maxPanelBottom) : desiredBottom; - panelBounds = RectFromEdges(left, panelTop, left + panelWidth, bottom); - bodyClipBounds = RectFromEdges(panelBounds.Left, bodyTop, panelBounds.Right, MathF.Max(bodyTop, panelBounds.Bottom - 8.0f)); - bodyScrollOffset = Math.Clamp(bodyScrollOffset, 0.0f, MaxBodyScrollOffset()); - - var y = bodyTop - bodyScrollOffset; - foreach (var control in visibleControls) - { - var height = control.LayoutHeight; - control.Bounds = RectFromEdges(left + 10.0f, y, left + panelWidth - 10.0f, y + height); - y += height + (control is SectionControl ? 2.0f : RowGap); - } - } - - public float DrawOpacity() - { - if (!fadeWhenMouseDistant) - { - return 1.0f; - } - - var near = RectFromEdges(panelBounds.Left - 72.0f, panelBounds.Top - 72.0f, panelBounds.Right + 72.0f, panelBounds.Bottom + 72.0f); - return Contains(near, mousePosition) ? 1.0f : 0.1f; - } - - private float ResolvedPanelLeft() - { - return panelLeft < 0.0f ? MathF.Max(ScreenMargin, lastViewportWidth + panelLeft - panelWidth) : panelLeft; - } - - private static float ContentHeight(IReadOnlyList visibleControls) - { - var height = 0.0f; - for (var index = 0; index < visibleControls.Count; index++) - { - var control = visibleControls[index]; - height += control.LayoutHeight; - if (index < visibleControls.Count - 1) - { - height += control is SectionControl ? 2.0f : RowGap; - } - } - - return height; - } - - private bool ScrollBody(float wheelDelta) - { - var maxOffset = MaxBodyScrollOffset(); - if (maxOffset <= 0.0f) - { - bodyScrollOffset = 0.0f; - return false; - } - - var previous = bodyScrollOffset; - bodyScrollOffset = Math.Clamp(bodyScrollOffset + (wheelDelta > 0.0f ? -72.0f : 72.0f), 0.0f, maxOffset); - return MathF.Abs(bodyScrollOffset - previous) > 0.001f; - } - - private float MaxBodyScrollOffset() - { - return MathF.Max(0.0f, bodyContentHeight - bodyClipBounds.Height + 12.0f); - } - - private void DrawBodyScrollbar(ID2D1RenderTarget target, ID2D1SolidColorBrush trackBrush, ID2D1SolidColorBrush thumbBrush) - { - var maxOffset = MaxBodyScrollOffset(); - if (maxOffset <= 0.0f || bodyClipBounds.Height <= 0.0f) - { - return; - } - - var track = RectFromEdges(panelBounds.Right - 7.0f, bodyClipBounds.Top + 2.0f, panelBounds.Right - 4.0f, bodyClipBounds.Bottom - 2.0f); - var thumbHeight = MathF.Max(24.0f, track.Height * bodyClipBounds.Height / MathF.Max(bodyContentHeight + 12.0f, bodyClipBounds.Height)); - var thumbTop = track.Top + (track.Height - thumbHeight) * bodyScrollOffset / maxOffset; - target.FillRectangle(track, trackBrush); - target.FillRectangle(RectFromEdges(track.Left, thumbTop, track.Right, thumbTop + thumbHeight), thumbBrush); - } - - private Rect CloseButtonBounds() - { - return RectFromEdges( - panelBounds.Right - CloseButtonSize - 10.0f, - panelBounds.Top + 11.0f, - panelBounds.Right - 10.0f, - panelBounds.Top + 11.0f + CloseButtonSize); - } - - private Rect TabBounds(int index) - { - if (tabs.Count == 0) - { - return RectFromEdges(0, 0, 0, 0); - } - - var available = panelWidth - 20.0f - Math.Max(0, tabs.Count - 1) * TabButtonGap; - var width = Math.Max(1.0f, available / tabs.Count); - var left = panelLeft + 10.0f + index * (width + TabButtonGap); - var top = panelTop + HeaderHeight + 4.0f; - return RectFromEdges(left, top, left + width, top + TabRowHeight - 8.0f); - } - - private int HitTestTab(Vector2 point) - { - for (var index = 0; index < tabs.Count; index++) - { - if (Contains(TabBounds(index), point)) - { - return index; - } - } - - return -1; - } - - private void DrawTabs( - ID2D1RenderTarget target, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush) - { - var activeTab = Math.Clamp(readActiveTab(), 0, Math.Max(0, tabs.Count - 1)); - for (var index = 0; index < tabs.Count; index++) - { - var bounds = TabBounds(index); - var active = index == activeTab; - var hovered = Contains(bounds, mousePosition); - target.FillRectangle(bounds, active ? activeRowBrush : hovered ? hoverRowBrush : rowBrush); - target.DrawRectangle(bounds, active ? accentBrush : outlineBrush, active ? 1.5f : 1.0f); - if (active) - { - target.DrawLine( - new Vector2(bounds.Left + 5.0f, bounds.Bottom - 2.0f), - new Vector2(bounds.Right - 5.0f, bounds.Bottom - 2.0f), - accentBrush, - 2.0f); - } - - target.DrawText( - tabs[index], - format, - RectFromEdges(bounds.Left + 7.0f, bounds.Top, bounds.Right - 7.0f, bounds.Bottom), - active ? primaryBrush : quietBrush, - DrawTextOptions.Clip); - } - } - - private void DrawTooltip( - ID2D1RenderTarget target, - IDWriteTextFormat format, - ID2D1SolidColorBrush panelBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush accentBrush, - int viewportWidth, - int viewportHeight) - { - var tooltip = closeButtonHovered - ? "Close panel. Press F2 to show it again." - : controls.FirstOrDefault(control => control.IsVisible && control.IsHovered)?.Tooltip; - if (string.IsNullOrWhiteSpace(tooltip)) - { - return; - } - - var left = mousePosition.X + 14.0f; - var top = mousePosition.Y + 18.0f; - if (left + TooltipWidth > viewportWidth - 10.0f) - { - left = mousePosition.X - TooltipWidth - 14.0f; - } - if (top + TooltipHeight > viewportHeight - 10.0f) - { - top = mousePosition.Y - TooltipHeight - 14.0f; - } - - var bounds = RectFromEdges(left, top, left + TooltipWidth, top + TooltipHeight); - target.FillRectangle(bounds, panelBrush); - target.DrawRectangle(bounds, outlineBrush, 1.0f); - target.DrawLine( - new Vector2(bounds.Left, bounds.Top), - new Vector2(bounds.Right, bounds.Top), - accentBrush, - 1.0f); - target.DrawText( - tooltip, - format, - RectFromEdges(bounds.Left + 8.0f, bounds.Top, bounds.Right - 8.0f, bounds.Bottom), - primaryBrush, - DrawTextOptions.Clip); - } - - private static bool Contains(Rect bounds, Vector2 point) - { - return point.X >= bounds.Left - && point.X <= bounds.Right - && point.Y >= bounds.Top - && point.Y <= bounds.Bottom; - } - - private static bool Intersects(Rect a, Rect b) - { - return a.Left < b.Right - && a.Right > b.Left - && a.Top < b.Bottom - && a.Bottom > b.Top; - } - - private static Rect RectFromEdges(float left, float top, float right, float bottom) - { - return new Rect(left, top, Math.Max(0.0f, right - left), Math.Max(0.0f, bottom - top)); - } - - public sealed class DebugUiPanel - { - private readonly List controls; - - internal DebugUiPanel(List controls) - { - this.controls = controls; - } - - public DebugUiPanel Section(string title, Func? isVisible = null) - { - controls.Add(new SectionControl(title, isVisible)); - return this; - } - - public DebugUiPanel Button(string label, Action action, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new ButtonControl(label, action, tooltip, isVisible)); - return this; - } - - public DebugUiPanel Toggle(string label, Func read, Action write, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new ToggleControl(label, read, write, tooltip, isVisible)); - return this; - } - - public DebugUiPanel TreeItem(string label, int depth, bool canExpand, Func isExpanded, Action setExpanded, Func isSelected, Action select, string? detail = null, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new TreeItemControl(label, Math.Max(0, depth), canExpand, isExpanded, setExpanded, isSelected, select, detail, tooltip, isVisible)); - return this; - } - - public DebugUiPanel Slider(string label, Func read, Action write, float min, float max, string format = "0.###", string? tooltip = null, Func? isVisible = null) - { - controls.Add(new FloatSliderControl(label, read, write, min, max, format, tooltip, isVisible)); - return this; - } - - public DebugUiPanel Slider(string label, Func read, Action write, int min, int max, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new IntSliderControl(label, read, write, min, max, tooltip, isVisible)); - return this; - } - - public DebugUiPanel Options(string label, Func read, Action write, IReadOnlyList options, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new OptionControl(label, read, write, options, tooltip, isVisible)); - return this; - } - - public DebugUiPanel Text(string label, Func read, Action write, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new TextControl(label, read, write, tooltip, isVisible)); - return this; - } - - public DebugUiPanel TextBox(string label, Func read, Action write, int lines = 3, bool acceptsReturn = true, Action? submit = null, bool monospace = false, bool alignBottom = false, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new TextBoxControl(label, read, write, Math.Max(1, lines), acceptsReturn, submit, monospace, alignBottom, tooltip, isVisible)); - return this; - } - - public DebugUiPanel Readout(string label, Func read, string? tooltip = null, Func? isVisible = null) - { - controls.Add(new ReadoutControl(label, read, tooltip, isVisible)); - return this; - } - } - - public readonly record struct DebugUiOption(int Value, string Label); - - private interface ITextInputControl - { - void ApplyTextInput(InputState input); - - void SelectToPoint(Vector2 point); - - bool Scroll(float wheelDelta); - } - - internal abstract class DebugUiControl(string label, string? tooltip = null, Func? isVisible = null) - { - private static int nextId; - - public int Id { get; } = nextId++; - - protected string Label { get; } = label; - - public string? Tooltip { get; } = tooltip; - - public bool IsVisible => isVisible?.Invoke() ?? true; - - public Rect Bounds { get; set; } - - public bool IsHovered { get; set; } - - public bool IsActive { get; set; } - - public bool IsFocused { get; set; } - - public virtual bool IsInteractive => true; - - public virtual bool UseMonospace => false; - - public virtual float LayoutHeight => this is SectionControl ? SectionHeight : RowHeight; - - public virtual bool HitTest(Vector2 mouse) => Contains(Bounds, mouse); - - public virtual void UpdateHover(Vector2 mouse, Rect clipBounds) - { - IsHovered = IsInteractive && Contains(clipBounds, mouse) && HitTest(mouse); - } - - public virtual void Click(Vector2 mouse) - { - } - - public virtual void DismissTransientState() - { - } - - public abstract void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush); - - protected void DrawRow( - ID2D1RenderTarget target, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush) - { - target.FillRectangle(Bounds, IsActive ? activeRowBrush : IsHovered ? hoverRowBrush : rowBrush); - target.DrawLine( - new Vector2(Bounds.Left, Bounds.Bottom), - new Vector2(Bounds.Right, Bounds.Bottom), - outlineBrush, - 1.0f); - } - - protected Rect LabelBounds() - { - return RectFromEdges(Bounds.Left + 8.0f, Bounds.Top, Bounds.Left + LabelWidth, Bounds.Bottom); - } - - protected Rect ValueBounds() - { - return RectFromEdges(Bounds.Left + LabelWidth + 10.0f, Bounds.Top, Bounds.Right - TrackWidth - ValueTrackGap, Bounds.Bottom); - } - } - - private sealed class SectionControl(string label, Func? isVisible) : DebugUiControl(label, isVisible: isVisible) - { - public override bool IsInteractive => false; - - public override bool HitTest(Vector2 mouse) => false; - - public override void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush) - { - target.DrawText(Label.ToUpperInvariant(), format, Bounds, accentBrush, DrawTextOptions.Clip); - target.DrawLine( - new Vector2(Bounds.Left + 118.0f, Bounds.Top + 11.0f), - new Vector2(Bounds.Right, Bounds.Top + 11.0f), - outlineBrush, - 1.0f); - } - } - - private sealed class ButtonControl(string label, Action action, string? tooltip, Func? isVisible) : DebugUiControl(label, tooltip, isVisible) - { - public override void Click(Vector2 mouse) => action(); - - public override void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush) - { - DrawRow(target, rowBrush, hoverRowBrush, activeRowBrush, outlineBrush); - target.DrawText(Label, format, LabelBounds(), accentBrush, DrawTextOptions.Clip); - target.DrawText("apply", format, ValueBounds(), primaryBrush, DrawTextOptions.Clip); - } - } - - private sealed class ToggleControl(string label, Func read, Action write, string? tooltip, Func? isVisible) : DebugUiControl(label, tooltip, isVisible) - { - public override void Click(Vector2 mouse) => write(!read()); - - public override void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush) - { - DrawRow(target, rowBrush, hoverRowBrush, activeRowBrush, outlineBrush); - target.DrawText(Label.ToUpperInvariant(), format, LabelBounds(), accentBrush, DrawTextOptions.Clip); - - var box = RectFromEdges(Bounds.Right - 28.0f, Bounds.Top + 8.0f, Bounds.Right - 13.0f, Bounds.Bottom - 8.0f); - target.DrawRectangle(box, read() ? accentBrush : outlineBrush, 1.0f); - if (read()) - { - target.DrawLine(new Vector2(box.Left + 3.0f, box.Top + 8.0f), new Vector2(box.Left + 7.0f, box.Bottom - 3.0f), accentBrush, 2.0f); - target.DrawLine(new Vector2(box.Left + 7.0f, box.Bottom - 3.0f), new Vector2(box.Right - 2.0f, box.Top + 3.0f), accentBrush, 2.0f); - } - } - } - - private sealed class TreeItemControl( - string label, - int depth, - bool canExpand, - Func isExpanded, - Action setExpanded, - Func isSelected, - Action select, - string? detail, - string? tooltip, - Func? isVisible) : DebugUiControl(label, tooltip, isVisible) - { - private const float IndentWidth = 17.0f; - - public override void Click(Vector2 mouse) - { - if (canExpand && Contains(DisclosureBounds(), mouse)) - { - setExpanded(!isExpanded()); - return; - } - - select(); - } - - public override void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush) - { - var selected = isSelected(); - target.FillRectangle(Bounds, selected ? activeRowBrush : IsActive ? activeRowBrush : IsHovered ? hoverRowBrush : rowBrush); - target.DrawLine(new Vector2(Bounds.Left, Bounds.Bottom), new Vector2(Bounds.Right, Bounds.Bottom), outlineBrush, 1.0f); - if (selected) - { - target.DrawLine(new Vector2(Bounds.Left + 2.0f, Bounds.Top + 5.0f), new Vector2(Bounds.Left + 2.0f, Bounds.Bottom - 5.0f), accentBrush, 2.0f); - } - - DrawDisclosure(target, canExpand ? accentBrush : quietBrush); - var textLeft = Bounds.Left + 8.0f + depth * IndentWidth + 18.0f; - target.DrawText(Label, format, RectFromEdges(textLeft, Bounds.Top, Bounds.Right - 92.0f, Bounds.Bottom), selected ? primaryBrush : accentBrush, DrawTextOptions.Clip); - if (!string.IsNullOrWhiteSpace(detail)) - { - target.DrawText(detail, format, RectFromEdges(MathF.Max(textLeft + 72.0f, Bounds.Right - 90.0f), Bounds.Top, Bounds.Right - 8.0f, Bounds.Bottom), selected ? primaryBrush : quietBrush, DrawTextOptions.Clip); - } - } - - private Rect DisclosureBounds() - { - var left = Bounds.Left + 7.0f + depth * IndentWidth; - return RectFromEdges(left, Bounds.Top + 7.0f, left + 13.0f, Bounds.Bottom - 7.0f); - } - - private void DrawDisclosure(ID2D1RenderTarget target, ID2D1SolidColorBrush brush) - { - var disclosure = DisclosureBounds(); - var cx = (disclosure.Left + disclosure.Right) * 0.5f; - var cy = (disclosure.Top + disclosure.Bottom) * 0.5f; - if (!canExpand) - { - target.FillEllipse(new Ellipse(new Vector2(cx, cy), 1.6f, 1.6f), brush); - return; - } - - if (isExpanded()) - { - target.DrawLine(new Vector2(cx - 4.5f, cy - 2.0f), new Vector2(cx, cy + 3.0f), brush, 1.6f); - target.DrawLine(new Vector2(cx, cy + 3.0f), new Vector2(cx + 4.5f, cy - 2.0f), brush, 1.6f); - } - else - { - target.DrawLine(new Vector2(cx - 2.0f, cy - 4.5f), new Vector2(cx + 3.0f, cy), brush, 1.6f); - target.DrawLine(new Vector2(cx + 3.0f, cy), new Vector2(cx - 2.0f, cy + 4.5f), brush, 1.6f); - } - } - } - - private sealed class OptionControl( - string label, - Func read, - Action write, - IReadOnlyList options, - string? tooltip, - Func? isVisible) : DebugUiControl(label, tooltip, isVisible) - { - private bool isOpen; - private int hoveredOptionIndex = -1; - private int scrollOffset; - - public bool IsOpen => isOpen; - - public override void UpdateHover(Vector2 mouse, Rect clipBounds) - { - hoveredOptionIndex = -1; - IsHovered = Contains(clipBounds, mouse) && HitTest(mouse); - } - - public void UpdatePopupHover(Vector2 mouse, int viewportHeight) - { - hoveredOptionIndex = -1; - if (!isOpen || !Contains(PopupBounds(viewportHeight), mouse)) - { - return; - } - - var localIndex = Math.Clamp((int)MathF.Floor((mouse.Y - PopupBounds(viewportHeight).Top) / RowHeight), 0, VisibleOptionCount(viewportHeight) - 1); - var optionIndex = scrollOffset + localIndex; - if (optionIndex >= 0 && optionIndex < options.Count) - { - hoveredOptionIndex = optionIndex; - } - } - - public override void Click(Vector2 mouse) - { - if (!isOpen) - { - isOpen = true; - scrollOffset = SelectedOptionIndex(); - return; - } - - if (Contains(MainBounds(), mouse)) - { - isOpen = false; - } - } - - public void ClickPopup(Vector2 mouse, int viewportHeight) - { - UpdatePopupHover(mouse, viewportHeight); - if (hoveredOptionIndex >= 0 && hoveredOptionIndex < options.Count) - { - write(options[hoveredOptionIndex].Value); - } - - isOpen = false; - } - - public void ScrollPopup(float wheelDelta, Vector2 mouse, int viewportHeight) - { - if (!isOpen || options.Count <= VisibleOptionCount(viewportHeight)) - { - return; - } - - scrollOffset += wheelDelta > 0.0f ? -3 : 3; - ClampScroll(viewportHeight); - UpdatePopupHover(mouse, viewportHeight); - } - - public void ClampScroll(int viewportHeight) - { - var visibleCount = VisibleOptionCount(viewportHeight); - var maxOffset = Math.Max(0, options.Count - visibleCount); - scrollOffset = Math.Clamp(scrollOffset, 0, maxOffset); - } - - public override void DismissTransientState() - { - isOpen = false; - } - - public override void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush) - { - var main = MainBounds(); - target.FillRectangle(main, IsActive ? activeRowBrush : IsHovered ? hoverRowBrush : rowBrush); - target.DrawLine(new Vector2(main.Left, main.Bottom), new Vector2(main.Right, main.Bottom), outlineBrush, 1.0f); - target.DrawText(Label.ToUpperInvariant(), format, RectFromEdges(main.Left + 8.0f, main.Top, main.Left + LabelWidth, main.Bottom), accentBrush, DrawTextOptions.Clip); - var valueBounds = ValueFieldBounds(); - target.DrawText(SelectedLabel(), format, RectFromEdges(valueBounds.Left, main.Top, main.Right - 32.0f, main.Bottom), primaryBrush, DrawTextOptions.Clip); - - var arrowBrush = IsActive ? accentActiveBrush : IsHovered ? accentHoverBrush : accentBrush; - var cy = (main.Top + main.Bottom) * 0.5f; - target.DrawLine(new Vector2(main.Right - 24.0f, cy - 3.0f), new Vector2(main.Right - 18.0f, cy + 3.0f), arrowBrush, 1.5f); - target.DrawLine(new Vector2(main.Right - 18.0f, cy + 3.0f), new Vector2(main.Right - 12.0f, cy - 3.0f), arrowBrush, 1.5f); - } - - public void DrawPopup( - ID2D1RenderTarget target, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush accentBrush, - int viewportHeight) - { - if (!isOpen) - { - return; - } - - ClampScroll(viewportHeight); - var popup = PopupBounds(viewportHeight); - target.FillRectangle(popup, rowBrush); - target.DrawRectangle(popup, outlineBrush, 1.0f); - var visibleCount = VisibleOptionCount(viewportHeight); - for (var localIndex = 0; localIndex < visibleCount; localIndex++) - { - var optionIndex = scrollOffset + localIndex; - if (optionIndex >= options.Count) - { - break; - } - - var bounds = OptionBounds(localIndex, viewportHeight); - var selected = options[optionIndex].Value == read(); - var hovered = optionIndex == hoveredOptionIndex; - target.FillRectangle(bounds, hovered ? hoverRowBrush : rowBrush); - target.DrawLine(new Vector2(bounds.Left, bounds.Bottom), new Vector2(bounds.Right, bounds.Bottom), outlineBrush, 1.0f); - var labelBrush = selected ? accentBrush : primaryBrush; - target.DrawText(options[optionIndex].Label, format, RectFromEdges(bounds.Left + 18.0f, bounds.Top, bounds.Right - 12.0f, bounds.Bottom), labelBrush, DrawTextOptions.Clip); - if (selected) - { - target.DrawLine(new Vector2(bounds.Left + 7.0f, bounds.Top + 16.0f), new Vector2(bounds.Left + 10.0f, bounds.Top + 20.0f), accentBrush, 1.75f); - target.DrawLine(new Vector2(bounds.Left + 10.0f, bounds.Top + 20.0f), new Vector2(bounds.Left + 15.0f, bounds.Top + 10.0f), accentBrush, 1.75f); - } - } - - if (options.Count > visibleCount) - { - var track = RectFromEdges(popup.Right - 4.0f, popup.Top + 3.0f, popup.Right - 2.0f, popup.Bottom - 3.0f); - var thumbHeight = Math.Max(12.0f, track.Height * visibleCount / options.Count); - var maxOffset = Math.Max(1, options.Count - visibleCount); - var thumbTop = track.Top + (track.Height - thumbHeight) * scrollOffset / maxOffset; - target.FillRectangle(RectFromEdges(track.Left, thumbTop, track.Right, thumbTop + thumbHeight), accentBrush); - } - } - - private string SelectedLabel() - { - var value = read(); - foreach (var option in options) - { - if (option.Value == value) - { - return option.Label; - } - } - - return value.ToString(CultureInfo.InvariantCulture); - } - - private Rect MainBounds() - { - return RectFromEdges(Bounds.Left, Bounds.Top, Bounds.Right, Bounds.Top + RowHeight); - } - - public Rect PopupBounds(int viewportHeight) - { - var field = ValueFieldBounds(); - var desiredHeight = options.Count * RowHeight; - var belowAvailable = Math.Max(RowHeight, viewportHeight - ScreenMargin - MainBounds().Bottom); - var aboveAvailable = Math.Max(RowHeight, MainBounds().Top - ScreenMargin); - var opensAbove = desiredHeight > belowAvailable && aboveAvailable > belowAvailable; - var available = opensAbove ? aboveAvailable : belowAvailable; - var height = VisibleOptionCount(viewportHeight) * RowHeight; - var top = opensAbove ? MainBounds().Top - Math.Min(height, available) : MainBounds().Bottom; - return RectFromEdges(field.Left, top, field.Right, top + Math.Min(height, available)); - } - - private Rect ValueFieldBounds() - { - var main = MainBounds(); - return RectFromEdges(main.Left + LabelWidth + 10.0f, main.Top, main.Right, main.Bottom); - } - - private Rect OptionBounds(int localIndex, int viewportHeight) - { - var popup = PopupBounds(viewportHeight); - var top = popup.Top + localIndex * RowHeight; - return RectFromEdges(popup.Left, top, popup.Right, top + RowHeight); - } - - private int VisibleOptionCount(int viewportHeight) - { - var desiredCount = options.Count; - var belowAvailable = Math.Max(RowHeight, viewportHeight - ScreenMargin - MainBounds().Bottom); - var aboveAvailable = Math.Max(RowHeight, MainBounds().Top - ScreenMargin); - var desiredHeight = desiredCount * RowHeight; - var opensAbove = desiredHeight > belowAvailable && aboveAvailable > belowAvailable; - var available = opensAbove ? aboveAvailable : belowAvailable; - return Math.Clamp((int)MathF.Floor(available / RowHeight), 1, Math.Max(1, desiredCount)); - } - - private int SelectedOptionIndex() - { - var value = read(); - for (var index = 0; index < options.Count; index++) - { - if (options[index].Value == value) - { - return index; - } - } - - return 0; - } - } - - private sealed class TextControl(string label, Func read, Action write, string? tooltip, Func? isVisible) - : DebugUiControl(label, tooltip, isVisible), ITextInputControl - { - public override float LayoutHeight => RowHeight * 2.0f; - - public void ApplyTextInput(InputState input) - { - var value = read(); - foreach (var ch in input.TextInput) - { - switch (ch) - { - case '\b': - if (value.Length > 0) - { - value = value[..^1]; - } - break; - case '\r': - case '\n': - value += ";"; - break; - default: - if (!char.IsControl(ch)) - { - value += ch; - } - break; - } - } - - if (value != read()) - { - write(value); - } - } - - public void SelectToPoint(Vector2 point) - { - } - - public bool Scroll(float wheelDelta) => false; - - public override void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush) - { - DrawRow(target, rowBrush, hoverRowBrush, activeRowBrush, outlineBrush); - target.DrawText(Label.ToUpperInvariant(), format, RectFromEdges(Bounds.Left + 8.0f, Bounds.Top, Bounds.Right - 8.0f, Bounds.Top + RowHeight), accentBrush, DrawTextOptions.Clip); - var display = read(); - if (display.Length > 92) - { - display = "..." + display[^89..]; - } - - target.DrawText(display, format, RectFromEdges(Bounds.Left + 8.0f, Bounds.Top + RowHeight - 4.0f, Bounds.Right - 8.0f, Bounds.Bottom), primaryBrush, DrawTextOptions.Clip); - } - } - - private sealed class TextBoxControl(string label, Func read, Action write, int lines, bool acceptsReturn, Action? submit, bool monospace, bool alignBottom, string? tooltip, Func? isVisible) - : DebugUiControl(label, tooltip, isVisible), ITextInputControl - { - private const float LabelHeight = 20.0f; - private const float TextLineHeight = 18.0f; - private const float VerticalPadding = 9.0f; - private const float FallbackCharacterWidth = 7.0f; - private const float TextInsetX = 8.0f; - private const float TextInsetY = 6.0f; - private readonly List lineHitCache = []; - private int caretIndex = -1; - private int selectionAnchor = -1; - private int firstVisibleLine = -1; - private string lastValue = string.Empty; - - public override float LayoutHeight => LabelLineHeight + VerticalPadding * 2.0f + Math.Max(1, lines) * TextLineHeight; - - public override bool UseMonospace => monospace; - - public void ApplyTextInput(InputState input) - { - SyncEditingState(); - var value = NormalizedValue; - var selecting = input.IsKeyDown(KeyCode.Shift); - if (input.IsKeyPressed(KeyCode.LeftArrow)) - { - MoveCaret(caretIndex - 1, selecting, value); - } - - if (input.IsKeyPressed(KeyCode.RightArrow)) - { - MoveCaret(caretIndex + 1, selecting, value); - } - - if (input.IsKeyPressed(KeyCode.Home)) - { - MoveCaret(HomeIndex(value, caretIndex), selecting, value); - } - - if (input.IsKeyPressed(KeyCode.End)) - { - MoveCaret(LineEnd(value, caretIndex), selecting, value); - } - - if (input.IsKeyPressed(KeyCode.Backspace)) - { - if (HasSelection) - { - value = DeleteSelection(value); - } - else if (caretIndex > EditableStartIndex(value)) - { - value = value.Remove(caretIndex - 1, 1); - MoveCaret(caretIndex - 1, selecting: false, value); - } - } - - if (input.IsKeyPressed(KeyCode.Delete)) - { - if (HasSelection) - { - value = DeleteSelection(value); - } - else if (caretIndex < value.Length) - { - value = value.Remove(caretIndex, 1); - } - } - - foreach (var ch in input.TextInput) - { - switch (ch) - { - case '\b': - break; - case '\r': - case '\n': - if (acceptsReturn) - { - value = InsertText(value, "\n"); - } - else - { - submit?.Invoke(); - caretIndex = -1; - selectionAnchor = -1; - value = NormalizedValue; - SyncEditingState(force: true); - } - break; - default: - if (!char.IsControl(ch)) - { - value = InsertText(value, ch.ToString()); - } - break; - } - } - - if (value != NormalizedValue) - { - write(value); - SyncCommittedValue(value); - } - } - - public void SelectToPoint(Vector2 point) - { - SyncEditingState(); - MoveCaret(IndexFromPoint(point), selecting: true, NormalizedValue); - } - - public bool Scroll(float wheelDelta) - { - var value = NormalizedValue; - var totalLines = LineCount(value); - var maxFirstLine = Math.Max(0, totalLines - lines); - if (maxFirstLine == 0) - { - firstVisibleLine = alignBottom ? 0 : -1; - return false; - } - - var step = wheelDelta > 0.0f ? -3 : 3; - var current = VisibleStartLine(totalLines); - firstVisibleLine = Math.Clamp(current + step, 0, maxFirstLine); - return firstVisibleLine != current; - } - - public override void Click(Vector2 mouse) - { - SyncEditingState(); - MoveCaret(IndexFromPoint(mouse), selecting: false, NormalizedValue); - } - - public override void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush) - { - if (HasLabel) - { - var labelBounds = RectFromEdges(Bounds.Left + 8.0f, Bounds.Top, Bounds.Right - 8.0f, Bounds.Top + LabelHeight); - target.DrawText(Label.ToUpperInvariant(), format, labelBounds, accentBrush, DrawTextOptions.Clip); - } - - var box = RectFromEdges(Bounds.Left, Bounds.Top + LabelLineHeight, Bounds.Right, Bounds.Bottom); - var focused = IsFocused || IsActive; - target.FillRectangle(box, rowBrush); - target.DrawRectangle(box, focused ? accentBrush : outlineBrush, focused ? 1.5f : 1.0f); - - CacheLineHitGeometry(directWriteFactory, format, box); - DrawSelection(target, directWriteFactory, format, activeRowBrush, box); - DrawBoxText(target, directWriteFactory, format, primaryBrush, box); - DrawCaret(target, directWriteFactory, format, accentBrush, box); - } - - private string DisplayText() - { - return string.Join('\n', DisplayLines()); - } - - private Rect TextBounds(Rect box) - { - return RectFromEdges(box.Left + TextInsetX, box.Top + TextInsetY, box.Right - TextInsetX, box.Bottom - TextInsetY); - } - - private void DrawBoxText( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1Brush brush, - Rect box) - { - var bounds = TextBounds(box); - var displayLines = DisplayLines(); - var top = TextTop(bounds, displayLines.Length); - for (var index = 0; index < displayLines.Length; index++) - { - using var layout = directWriteFactory.CreateTextLayout(displayLines[index], format, bounds.Width, TextLineHeight); - target.DrawTextLayout(new Vector2(bounds.Left, top + index * TextLineHeight), layout, brush, DrawTextOptions.Clip); - } - } - - private string[] DisplayLines() - { - var split = NormalizedValue.Split('\n'); - var startLine = VisibleStartLine(split.Length); - return split.Skip(startLine).Take(lines).ToArray(); - } - - private int DisplayStartIndex() - { - var split = NormalizedValue.Split('\n'); - var skippedLines = VisibleStartLine(split.Length); - var index = 0; - for (var line = 0; line < skippedLines; line++) - { - index += split[line].Length + 1; - } - - return index; - } - - private void SyncEditingState(bool force = false) - { - var value = NormalizedValue; - if (!force && caretIndex >= 0 && string.Equals(value, lastValue, StringComparison.Ordinal)) - { - return; - } - - lastValue = value; - caretIndex = ClampEditableIndex(value.Length, value); - selectionAnchor = caretIndex; - firstVisibleLine = alignBottom ? Math.Max(0, LineCount(value) - lines) : 0; - } - - private void SyncCommittedValue(string value) - { - lastValue = value; - caretIndex = ClampEditableIndex(caretIndex, value); - selectionAnchor = ClampEditableIndex(selectionAnchor, value); - firstVisibleLine = Math.Clamp(firstVisibleLine, 0, Math.Max(0, LineCount(value) - lines)); - EnsureCaretVisible(value); - } - - private void MoveCaret(int index, bool selecting, string value) - { - caretIndex = ClampEditableIndex(index, value); - if (!selecting) - { - selectionAnchor = caretIndex; - } - else - { - selectionAnchor = ClampEditableIndex(selectionAnchor, value); - } - - EnsureCaretVisible(value); - } - - private string InsertText(string value, string text) - { - if (HasSelection) - { - value = DeleteSelection(value); - } - - var insertionIndex = ClampEditableIndex(caretIndex, value); - value = value.Insert(insertionIndex, text); - MoveCaret(insertionIndex + text.Length, selecting: false, value); - return value; - } - - private string DeleteSelection(string value) - { - var editableStart = EditableStartIndex(value); - var start = Math.Max(SelectionStart, editableStart); - var end = Math.Max(start, Math.Min(SelectionEnd, value.Length)); - var length = end - start; - if (length == 0) - { - MoveCaret(start, selecting: false, value); - return value; - } - - value = value.Remove(start, length); - MoveCaret(start, selecting: false, value); - return value; - } - - private int IndexFromPoint(Vector2 point) - { - var bounds = TextBounds(BoxBounds); - var displayLines = DisplayLines(); - var top = TextTop(bounds, displayLines.Length); - var line = Math.Clamp((int)MathF.Floor((point.Y - top) / TextLineHeight), 0, Math.Max(0, displayLines.Length - 1)); - var cache = line < lineHitCache.Count ? lineHitCache[line] : default; - if (cache.Edges.Length > 0) - { - var localX = point.X - cache.OriginX; - var nearest = 0; - var nearestDistance = float.MaxValue; - for (var edgeIndex = 0; edgeIndex < cache.Edges.Length; edgeIndex++) - { - var distance = MathF.Abs(cache.Edges[edgeIndex] - localX); - if (distance < nearestDistance) - { - nearestDistance = distance; - nearest = edgeIndex; - } - } - - return ClampEditableIndex(cache.GlobalStart + nearest, NormalizedValue); - } - - var column = Math.Max(0, (int)MathF.Round((point.X - bounds.Left) / FallbackCharacterWidth)); - var index = DisplayStartIndex(); - for (var lineIndex = 0; lineIndex < line; lineIndex++) - { - index += displayLines[lineIndex].Length + 1; - } - - return ClampEditableIndex(index + Math.Min(column, displayLines[line].Length), NormalizedValue); - } - - private void DrawSelection( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush activeRowBrush, - Rect box) - { - if (!HasSelection) - { - return; - } - - var bounds = TextBounds(box); - var displayLines = DisplayLines(); - var displayStart = DisplayStartIndex(); - var displayEnd = displayStart + DisplayText().Length; - var start = Math.Max(SelectionStart, displayStart); - var end = Math.Min(SelectionEnd, displayEnd); - if (start >= end) - { - return; - } - - var top = TextTop(bounds, displayLines.Length); - var lineStart = displayStart; - for (var line = 0; line < displayLines.Length; line++) - { - var lineEnd = lineStart + displayLines[line].Length; - var startColumn = Math.Max(0, start - lineStart); - var endColumn = Math.Min(displayLines[line].Length, end - lineStart); - if (endColumn > startColumn) - { - using var layout = directWriteFactory.CreateTextLayout(displayLines[line], format, bounds.Width, TextLineHeight); - var startHit = TextPositionHit(layout, startColumn, displayLines[line].Length); - var endHit = TextPositionHit(layout, endColumn, displayLines[line].Length); - var vertical = TextVerticalHit(layout, displayLines[line].Length); - var selectionTop = top + line * TextLineHeight + vertical.Top; - var selectionBottom = selectionTop + vertical.Height; - target.FillRectangle( - RectFromEdges( - bounds.Left + startHit.X, - selectionTop, - bounds.Left + endHit.X, - selectionBottom), - activeRowBrush); - } - - lineStart = lineEnd + 1; - } - } - - private void DrawCaret( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush accentBrush, - Rect box) - { - if (!IsFocused) - { - return; - } - - var bounds = TextBounds(box); - var displayLines = DisplayLines(); - var displayStart = DisplayStartIndex(); - var displayEnd = displayStart + DisplayText().Length; - if (caretIndex < displayStart || caretIndex > displayEnd) - { - return; - } - - var top = TextTop(bounds, displayLines.Length); - var lineStart = displayStart; - for (var line = 0; line < displayLines.Length; line++) - { - var lineEnd = lineStart + displayLines[line].Length; - if (caretIndex <= lineEnd || line == displayLines.Length - 1) - { - var column = Math.Clamp(caretIndex - lineStart, 0, displayLines[line].Length); - using var layout = directWriteFactory.CreateTextLayout(displayLines[line], format, bounds.Width, TextLineHeight); - var hit = TextPositionHit(layout, column, displayLines[line].Length); - var x = bounds.Left + hit.X; - var y = top + line * TextLineHeight + hit.Top; - target.DrawLine(new Vector2(x, y), new Vector2(x, y + hit.Height), accentBrush, 1.25f); - return; - } - - lineStart = lineEnd + 1; - } - } - - private static int LineStart(string value, int index) - { - var clamped = Math.Clamp(index, 0, value.Length); - if (clamped == 0) - { - return 0; - } - - var previousNewline = value.LastIndexOf('\n', Math.Max(0, clamped - 1)); - return previousNewline < 0 ? 0 : previousNewline + 1; - } - - private int HomeIndex(string value, int index) - { - return LocksToPrompt ? EditableStartIndex(value) : LineStart(value, index); - } - - private static int LineEnd(string value, int index) - { - var nextNewline = value.IndexOf('\n', Math.Clamp(index, 0, value.Length)); - return nextNewline < 0 ? value.Length : nextNewline; - } - - private float TextTop(Rect bounds, int lineCount) - { - return alignBottom - ? Math.Max(bounds.Top, bounds.Bottom - lineCount * TextLineHeight) - : bounds.Top; - } - - private void CacheLineHitGeometry(IDWriteFactory6 directWriteFactory, IDWriteTextFormat format, Rect box) - { - lineHitCache.Clear(); - var bounds = TextBounds(box); - var displayLines = DisplayLines(); - var top = TextTop(bounds, displayLines.Length); - var globalStart = DisplayStartIndex(); - for (var line = 0; line < displayLines.Length; line++) - { - using var layout = directWriteFactory.CreateTextLayout(displayLines[line], format, bounds.Width, TextLineHeight); - var edges = new float[displayLines[line].Length + 1]; - for (var index = 0; index < edges.Length; index++) - { - edges[index] = TextPositionHit(layout, index, displayLines[line].Length).X; - } - - lineHitCache.Add(new LineHitCache(globalStart, bounds.Left, top + line * TextLineHeight, edges)); - globalStart += displayLines[line].Length + 1; - } - } - - private static TextHit TextPositionHit(IDWriteTextLayout layout, int position, int length) - { - if (length == 0) - { - return new TextHit(0.0f, 2.0f, TextLineHeight - 2.0f); - } - - var clamped = Math.Clamp(position, 0, length); - uint textPosition; - RawBool trailing; - if (clamped == length) - { - textPosition = (uint)Math.Max(0, length - 1); - trailing = new RawBool(true); - } - else - { - textPosition = (uint)clamped; - trailing = new RawBool(false); - } - - layout.HitTestTextPosition(textPosition, trailing, out var x, out _, out var metrics); - return new TextHit(x, metrics.Top, metrics.Height); - } - - private static TextHit TextVerticalHit(IDWriteTextLayout layout, int length) - { - return TextPositionHit(layout, Math.Min(1, length), length); - } - - private bool HasLabel => !string.IsNullOrWhiteSpace(Label); - - private float LabelLineHeight => HasLabel ? LabelHeight : 0.0f; - - private Rect BoxBounds => RectFromEdges(Bounds.Left, Bounds.Top + LabelLineHeight, Bounds.Right, Bounds.Bottom); - - private string NormalizedValue => read().Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n'); - - private bool HasSelection => caretIndex != selectionAnchor; - - private int SelectionStart => Math.Min(caretIndex, selectionAnchor); - - private int SelectionEnd => Math.Max(caretIndex, selectionAnchor); - - private bool LocksToPrompt => submit is not null && !acceptsReturn; - - private int ClampEditableIndex(int index, string value) - { - return Math.Clamp(index, EditableStartIndex(value), value.Length); - } - - private int EditableStartIndex(string value) - { - if (!LocksToPrompt) - { - return 0; - } - - var promptIndex = value.LastIndexOf("\n> ", StringComparison.Ordinal); - if (promptIndex >= 0) - { - return Math.Min(value.Length, promptIndex + 3); - } - - if (value.StartsWith("> ", StringComparison.Ordinal)) - { - return Math.Min(value.Length, 2); - } - - if (value.EndsWith("\n>", StringComparison.Ordinal) || string.Equals(value, ">", StringComparison.Ordinal)) - { - return value.Length; - } - - return value.Length; - } - - private int VisibleStartLine(int totalLines) - { - var maxFirstLine = Math.Max(0, totalLines - lines); - if (firstVisibleLine < 0) - { - return alignBottom ? maxFirstLine : 0; - } - - return Math.Clamp(firstVisibleLine, 0, maxFirstLine); - } - - private void EnsureCaretVisible(string value) - { - var totalLines = LineCount(value); - var maxFirstLine = Math.Max(0, totalLines - lines); - var caretLine = LineNumber(value, caretIndex); - var first = VisibleStartLine(totalLines); - if (caretLine < first) - { - firstVisibleLine = caretLine; - } - else if (caretLine >= first + lines) - { - firstVisibleLine = caretLine - lines + 1; - } - else if (firstVisibleLine < 0) - { - firstVisibleLine = first; - } - - firstVisibleLine = Math.Clamp(firstVisibleLine, 0, maxFirstLine); - } - - private static int LineCount(string value) - { - return value.Count(ch => ch == '\n') + 1; - } - - private static int LineNumber(string value, int index) - { - var clamped = Math.Clamp(index, 0, value.Length); - var line = 0; - for (var i = 0; i < clamped; i++) - { - if (value[i] == '\n') - { - line++; - } - } - - return line; - } - - private readonly record struct LineHitCache(int GlobalStart, float OriginX, float OriginY, float[] Edges); - - private readonly record struct TextHit(float X, float Top, float Height); - } - - private sealed class ReadoutControl(string label, Func read, string? tooltip, Func? isVisible) - : DebugUiControl(label, tooltip, isVisible) - { - public override bool IsInteractive => !string.IsNullOrWhiteSpace(Tooltip); - - public override void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush) - { - DrawRow(target, rowBrush, hoverRowBrush, activeRowBrush, outlineBrush); - target.DrawText(Label.ToUpperInvariant(), format, LabelBounds(), accentBrush, DrawTextOptions.Clip); - target.DrawText(read(), format, RectFromEdges(Bounds.Left + LabelWidth + 10.0f, Bounds.Top, Bounds.Right - 8.0f, Bounds.Bottom), primaryBrush, DrawTextOptions.Clip); - } - } - - private abstract class SliderControl(string label, string? tooltip, Func? isVisible) : DebugUiControl(label, tooltip, isVisible) - { - private const float ThumbRadius = 4.0f; - private const float ThumbHitRadius = 8.0f; - - private bool trackHovered; - private bool thumbHovered; - private bool trackActive; - private bool thumbActive; - - public override bool HitTest(Vector2 mouse) - { - return Contains(SliderInteractionBounds(), mouse); - } - - public override void UpdateHover(Vector2 mouse, Rect clipBounds) - { - thumbHovered = Contains(clipBounds, mouse) && Contains(ThumbInteractionBounds(), mouse); - trackHovered = Contains(clipBounds, mouse) && !thumbHovered && Contains(TrackInteractionBounds(), mouse); - IsHovered = trackHovered || thumbHovered; - } - - public void Drag(Vector2 mouse) - { - var track = TrackBounds(); - var normalized = Math.Clamp((mouse.X - track.Left) / Math.Max(1.0f, track.Right - track.Left), 0.0f, 1.0f); - WriteNormalized(normalized); - } - - public override void Click(Vector2 mouse) - { - thumbActive = Contains(ThumbInteractionBounds(), mouse); - trackActive = !thumbActive && Contains(TrackInteractionBounds(), mouse); - Drag(mouse); - } - - protected abstract float ReadNormalized(); - - protected abstract void WriteNormalized(float value); - - protected abstract string ReadDisplay(); - - public override void Draw( - ID2D1RenderTarget target, - IDWriteFactory6 directWriteFactory, - IDWriteTextFormat format, - ID2D1SolidColorBrush rowBrush, - ID2D1SolidColorBrush hoverRowBrush, - ID2D1SolidColorBrush activeRowBrush, - ID2D1SolidColorBrush outlineBrush, - ID2D1SolidColorBrush primaryBrush, - ID2D1SolidColorBrush quietBrush, - ID2D1SolidColorBrush accentBrush, - ID2D1SolidColorBrush accentHoverBrush, - ID2D1SolidColorBrush accentActiveBrush, - ID2D1SolidColorBrush dimAccentBrush, - ID2D1SolidColorBrush trackHoverBrush, - ID2D1SolidColorBrush trackActiveBrush) - { - DrawRow(target, rowBrush, rowBrush, rowBrush, outlineBrush); - target.DrawText(Label.ToUpperInvariant(), format, LabelBounds(), accentBrush, DrawTextOptions.Clip); - target.DrawText(ReadDisplay(), format, ValueBounds(), primaryBrush, DrawTextOptions.Clip); - - var track = TrackBounds(); - var t = ReadNormalized(); - var fill = RectFromEdges(track.Left, track.Top, track.Left + (track.Right - track.Left) * t, track.Bottom); - var isTrackActive = IsActive && trackActive; - var isThumbActive = IsActive && thumbActive; - var isTrackLit = trackHovered || isTrackActive; - var trackBrush = isTrackActive ? trackActiveBrush : isTrackLit ? trackHoverBrush : dimAccentBrush; - var fillBrush = isTrackActive ? accentActiveBrush : isTrackLit ? accentHoverBrush : accentBrush; - target.FillRectangle(track, trackBrush); - target.FillRectangle(fill, fillBrush); - var thumbX = fill.Right; - var thumbBrush = isThumbActive ? accentActiveBrush : thumbHovered ? accentHoverBrush : accentBrush; - target.FillRectangle(RectFromEdges(thumbX - ThumbRadius, track.Top - ThumbRadius, thumbX + ThumbRadius, track.Bottom + ThumbRadius), thumbBrush); - } - - private Rect TrackBounds() - { - var right = Bounds.Right - 12.0f; - var left = right - TrackWidth; - var centerY = (Bounds.Top + Bounds.Bottom) * 0.5f; - return RectFromEdges(left, centerY - TrackHeight * 0.5f, right, centerY + TrackHeight * 0.5f); - } - - private Rect SliderInteractionBounds() - { - var track = TrackBounds(); - return RectFromEdges(track.Left - 8.0f, Bounds.Top, track.Right + 8.0f, Bounds.Bottom); - } - - private Rect TrackInteractionBounds() - { - var track = TrackBounds(); - return RectFromEdges(track.Left - 4.0f, Bounds.Top, track.Right + 4.0f, Bounds.Bottom); - } - - private Rect ThumbInteractionBounds() - { - var track = TrackBounds(); - var thumbX = track.Left + (track.Right - track.Left) * ReadNormalized(); - var centerY = (track.Top + track.Bottom) * 0.5f; - return RectFromEdges(thumbX - ThumbHitRadius, centerY - ThumbHitRadius, thumbX + ThumbHitRadius, centerY + ThumbHitRadius); - } - } - - private sealed class FloatSliderControl( - string label, - Func read, - Action write, - float min, - float max, - string format, - string? tooltip, - Func? isVisible) : SliderControl(label, tooltip, isVisible) - { - protected override float ReadNormalized() - { - return Math.Clamp((read() - min) / Math.Max(0.000001f, max - min), 0.0f, 1.0f); - } - - protected override void WriteNormalized(float value) - { - write(min + (max - min) * value); - } - - protected override string ReadDisplay() - { - return read().ToString(format, CultureInfo.InvariantCulture); - } - } - - private sealed class IntSliderControl( - string label, - Func read, - Action write, - int min, - int max, - string? tooltip, - Func? isVisible) : SliderControl(label, tooltip, isVisible) - { - protected override float ReadNormalized() - { - return Math.Clamp((read() - min) / Math.Max(1.0f, max - min), 0.0f, 1.0f); - } - - protected override void WriteNormalized(float value) - { - write((int)MathF.Round(min + (max - min) * value)); - } - - protected override string ReadDisplay() - { - return read().ToString(CultureInfo.InvariantCulture); - } - } -} diff --git a/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs b/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs deleted file mode 100644 index 950e974..0000000 --- a/src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs +++ /dev/null @@ -1,174 +0,0 @@ -using System.Reflection; -using System.Runtime.Loader; -using System.Diagnostics; - -namespace Aquarium.Engine.Runtime; - -public sealed class ClientRuntimeLoader : IDisposable -{ - private readonly string? clientAssemblyPath; - private readonly string? clientReloadPointerPath; - private readonly Stopwatch reloadClock = Stopwatch.StartNew(); - private readonly AquariumRuntimeOptions options; - private ReloadedRuntime? current; - private TimeSpan lastReloadCheck; - private string? currentAssemblyPath; - - public ClientRuntimeLoader(AquariumRuntimeOptions options, string? clientAssemblyPath = null, string? clientReloadPointerPath = null) - { - this.clientAssemblyPath = clientAssemblyPath; - this.clientReloadPointerPath = clientReloadPointerPath; - this.options = options; - } - - public IAquariumRuntime Runtime - { - get - { - if (current == null) - { - Reload(RequireClientAssemblyPath(), options); - } - - return current!.Runtime; - } - } - - public IAquariumRuntime Load() - { - Reload(RequireClientAssemblyPath(), options); - return Runtime; - } - - public void Reload(string assemblyPath, AquariumRuntimeOptions options) - { - var previous = current; - var loadContext = new ClientAssemblyLoadContext(assemblyPath); - IAquariumRuntime? nextRuntime = null; - - try - { - var assembly = loadContext.LoadFromAssemblyPath(assemblyPath); - var factoryTypes = assembly.GetTypes() - .Where(type => typeof(IAquariumRuntimeFactory).IsAssignableFrom(type) - && type is { IsAbstract: false, IsInterface: false }) - .ToArray(); - if (factoryTypes.Length != 1) - { - throw new InvalidOperationException( - $"Client runtime assembly must contain exactly one concrete {nameof(IAquariumRuntimeFactory)} implementation; found {factoryTypes.Length}."); - } - - var factoryType = factoryTypes[0]; - var factory = (IAquariumRuntimeFactory?)Activator.CreateInstance(factoryType) - ?? throw new InvalidOperationException($"Client runtime factory could not be created: {factoryType.FullName}"); - - nextRuntime = factory.Create(options); - nextRuntime.Start(); - } - catch - { - nextRuntime?.Dispose(); - loadContext.Unload(); - throw; - } - - current = new ReloadedRuntime(loadContext, nextRuntime); - currentAssemblyPath = assemblyPath; - previous?.Runtime.Dispose(); - previous?.Unload(); - } - - public void Update(float deltaSeconds, Input.InputState input) - { - TryReloadFromPointer(); - Runtime.Update(deltaSeconds, input); - } - - private void TryReloadFromPointer() - { - if (string.IsNullOrWhiteSpace(clientReloadPointerPath) || reloadClock.Elapsed - lastReloadCheck < TimeSpan.FromMilliseconds(500)) - { - return; - } - - lastReloadCheck = reloadClock.Elapsed; - string candidatePath; - try - { - candidatePath = File.ReadAllText(clientReloadPointerPath).Trim(); - } - catch - { - return; - } - - if (string.IsNullOrWhiteSpace(candidatePath) - || string.Equals(candidatePath, currentAssemblyPath, StringComparison.OrdinalIgnoreCase) - || !File.Exists(candidatePath)) - { - return; - } - - try - { - current?.Runtime.FlushState(); - Reload(candidatePath, options); - Console.WriteLine($"Client runtime reload applied: {candidatePath}"); - } - catch (Exception error) - { - Console.Error.WriteLine($"Client runtime reload failed; keeping previous runtime. {error.Message}"); - } - } - - private string RequireClientAssemblyPath() - { - if (!string.IsNullOrWhiteSpace(clientAssemblyPath)) - { - return clientAssemblyPath; - } - - throw new InvalidOperationException("A client runtime assembly path is required. Pass --client-assembly or set AQUARIUM_CLIENT_ASSEMBLY."); - } - - public void Dispose() - { - var runtime = current; - current = null; - runtime?.Runtime.Dispose(); - runtime?.Unload(); - } - - private sealed class ReloadedRuntime(ClientAssemblyLoadContext loadContext, IAquariumRuntime runtime) - { - public IAquariumRuntime Runtime { get; } = runtime; - - public void Unload() - { - loadContext.Unload(); - } - } - - private sealed class ClientAssemblyLoadContext(string assemblyPath) : AssemblyLoadContext(isCollectible: true) - { - private readonly AssemblyDependencyResolver resolver = new(assemblyPath); - - protected override Assembly? Load(AssemblyName assemblyName) - { - if (assemblyName.Name == typeof(IAquariumRuntime).Assembly.GetName().Name) - { - return null; - } - - var path = resolver.ResolveAssemblyToPath(assemblyName); - return path == null ? null : LoadFromAssemblyPath(path); - } - - protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) - { - var path = resolver.ResolveUnmanagedDllToPath(unmanagedDllName); - return path == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(path); - } - } -} diff --git a/src/Aquarium.Epiphany.AgentPreview/Aquarium.Epiphany.AgentPreview.csproj b/src/Aquarium.Epiphany.AgentPreview/Aquarium.Epiphany.AgentPreview.csproj index 341270e..665d697 100644 --- a/src/Aquarium.Epiphany.AgentPreview/Aquarium.Epiphany.AgentPreview.csproj +++ b/src/Aquarium.Epiphany.AgentPreview/Aquarium.Epiphany.AgentPreview.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Aquarium.Epiphany/Aquarium.Epiphany.csproj b/src/Aquarium.Epiphany/Aquarium.Epiphany.csproj index 99ee89b..b138201 100644 --- a/src/Aquarium.Epiphany/Aquarium.Epiphany.csproj +++ b/src/Aquarium.Epiphany/Aquarium.Epiphany.csproj @@ -10,7 +10,7 @@ - + diff --git a/src/Aquarium.Fensalir/Aquarium.Fensalir.csproj b/src/Aquarium.Fensalir/Aquarium.Fensalir.csproj deleted file mode 100644 index 09900e4..0000000 --- a/src/Aquarium.Fensalir/Aquarium.Fensalir.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - net10.0 - Aquarium.Fensalir - Aquarium.Fensalir - enable - enable - true - - - - - - - - - - - - - - diff --git a/src/Aquarium.Fensalir/FensalirFractalScene.cs b/src/Aquarium.Fensalir/FensalirFractalScene.cs deleted file mode 100644 index 76c7b29..0000000 --- a/src/Aquarium.Fensalir/FensalirFractalScene.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Brushes; -using Aquarium.Engine.Fractal.Debug; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; -using Aquarium.Engine.Render; - -namespace Aquarium.Fensalir; - -public static class FensalirFractalScene -{ - private const string PatchRelativePath = "Worlds/fensalir-spine-emblem.aquageo"; - - private static readonly Lazy PatchSource = new(() => File.ReadAllText(PatchPath)); - private static readonly Lazy Tree = new(() => FractalDslCompiler.Compile(PatchSource.Value)); - private static readonly Lazy Summaries = new(() => FractalSummaryBuilder.Build(Tree.Value)); - private static readonly Lazy SelectedCut = new(() => FractalSelectedCutBuilder.Build(Summaries.Value, _ => 12.0f, maxEstimatedCost: 64.0f)); - private static readonly Lazy Brushes = new(() => OrderBrushes(FractalHeightBrushCompiler.CompileSelectedTree(Tree.Value, SelectedCut.Value))); - - public static string PatchPath => Path.Combine(AssemblyDirectory, PatchRelativePath); - - public static FractalOwnershipTree OwnershipTree => Tree.Value; - - public static AquariumHeightFieldBrush[] HeightBrushes => Brushes.Value; - - public static AquariumFractalSummary[] NodeSummaries => Summaries.Value; - - public static AquariumSelectedCut[] SelectedCuts => SelectedCut.Value; - - public static string Summary => - $"{Path.GetFileName(PatchPath)} / {OwnershipTree.Claims.Count} claims / {HeightBrushes.Length} surface brushes / {SelectedCuts.Length} cuts"; - - public static string DebugDump => FractalDebugDump.Build(OwnershipTree, NodeSummaries, SelectedCuts); - - private static AquariumHeightFieldBrush[] OrderBrushes(AquariumHeightFieldBrush[] brushes) - { - return brushes - .OrderByDescending(brush => MathF.Abs(brush.Amplitude) * MathF.Max(brush.Radius, brush.RadiusY) + MathF.Abs(brush.WaveAmplitude) * brush.Radius) - .ThenBy(brush => brush.Center.X) - .ThenBy(brush => brush.Center.Y) - .ToArray(); - } - - private static string AssemblyDirectory => - Path.GetDirectoryName(typeof(FensalirFractalScene).Assembly.Location) - ?? AppContext.BaseDirectory; -} diff --git a/src/Aquarium.Fensalir/FensalirRenderPlan.cs b/src/Aquarium.Fensalir/FensalirRenderPlan.cs deleted file mode 100644 index 999ebe2..0000000 --- a/src/Aquarium.Fensalir/FensalirRenderPlan.cs +++ /dev/null @@ -1,39 +0,0 @@ -using Aquarium.Engine.Render; - -namespace Aquarium.Fensalir; - -public static class FensalirRenderPlan -{ - public const int SpineIndex = 0; - public const int SdfObjectCount = 1; - - public static AquariumRenderPlan Create() - { - var app = new AquariumApp(); - app.Shaders - .Core("D3D12HeightField.hlsl", ShaderPath("D3D12FensalirScene.hlsl"), "D3D12Post.hlsl") - .SdfShader(ShaderPath("D3D12FensalirSpine.hlsl")); - - var heightField = app.RenderTargets.Create("height-field") - .FixedSize(128, 128) - .Format(RenderFormat.R16Float) - .Register(); - var scene = app.RenderTargets.Hdr("scene"); - app.Cameras.Orbit("main"); - app.Graph.Pass("height-field").Fullscreen(); - app.Graph.Pass("scene").Fullscreen(); - app.Graph.Pass("sdf-proxies").Proxy(); - app.Features.Bloom(scene.Color); - app.Features.Presentation(scene.Color); - app.Features.DirectWriteOverlay(); - app.Debug.View("Height Field", heightField).View("Scene", scene.Color); - return app.Plan; - } - - private static string ShaderPath(string fileName) - { - var assemblyDirectory = Path.GetDirectoryName(typeof(FensalirRenderPlan).Assembly.Location) - ?? AppContext.BaseDirectory; - return Path.Combine(assemblyDirectory, "Render", "Shaders", fileName); - } -} diff --git a/src/Aquarium.Fensalir/FensalirRuntime.cs b/src/Aquarium.Fensalir/FensalirRuntime.cs deleted file mode 100644 index 41bdf65..0000000 --- a/src/Aquarium.Fensalir/FensalirRuntime.cs +++ /dev/null @@ -1,163 +0,0 @@ -using System.Numerics; -using Aquarium.Engine; -using Aquarium.Engine.Audio; -using Aquarium.Engine.Input; -using Aquarium.Engine.Render; -using Aquarium.Engine.Ui; - -namespace Aquarium.Fensalir; - -public sealed class FensalirRuntime : IAquariumRuntime -{ - private float timeSeconds; - private float previousTimeSeconds; - private float orbitYaw; - private float orbitPitch = 0.19f; - private float orbitDistance = 7.6f; - private bool autoDrift = true; - - public AquariumRuntimeOptions Options { get; private set; } - - public GraphicsSettings GraphicsSettings { get; set; } = new(0, 1.04f, 0.52f, 0.08f); - - public AquariumRenderPlan RenderPlan { get; } = FensalirRenderPlan.Create(); - - public AquariumUiDocument Ui { get; } - - public AquariumAudioDocument Audio { get; } = new(); - - public AquariumSynthDocument Synth { get; } = AquariumSynthDocument.Empty; - - public AquariumFrame Frame - { - get - { - var target = new Vector3(0.0f, 0.12f, 2.1f); - var camera = ComposeCamera(target); - return new AquariumFrame( - new ViewFrame(Vector2.Zero, 8.0f), - camera, - target, - timeSeconds, - Vector2.Zero, - FensalirSceneBuilder.Build(timeSeconds, previousTimeSeconds)); - } - } - - public FensalirRuntime() - { - Ui = new AquariumUiDocument() - .Panel("Fensalir", 18.0f, 82.0f, 360.0f, panel => - { - panel.Section("Splash Reconstruction"); - panel.Toggle("Auto Drift", () => autoDrift, value => autoDrift = value); - panel.Slider("Orbit Distance", () => orbitDistance, value => orbitDistance = Math.Clamp(value, 3.2f, 14.0f), 3.2f, 14.0f, "0.00"); - panel.Readout("Patch", () => FensalirFractalScene.Summary); - panel.Readout("Surface", () => $"{FensalirFractalScene.HeightBrushes.Count(brush => brush.WaveAmplitude != 0.0f)} ripple brushes / quadtree plane"); - panel.Readout("Renderer", () => "2D marsh field + emissive SDF spine + bloom"); - panel.Readout("Camera", () => $"{orbitDistance:0.00} wu / yaw {orbitYaw:0.00}"); - }) - .Command("fensalir", _ => $"Fensalir: {FensalirFractalScene.Summary}", "Report Fensalir splash scene status.") - .Command("fensalir-fractal", _ => FensalirFractalScene.DebugDump, "Dump the compiled Fensalir splash .aquageo patch."); - } - - public AquariumFrame ComposeFrame(AquariumFrame frame, AquariumFrameInput input) - { - return frame; - } - - public void Start() - { - Console.WriteLine("Fensalir splash reconstruction booted."); - } - - public void Update(float deltaSeconds, InputState input) - { - previousTimeSeconds = timeSeconds; - var safeDelta = Math.Max(deltaSeconds, 0.0f); - timeSeconds += safeDelta; - - if (autoDrift) - { - orbitYaw += safeDelta * 0.018f; - } - - if (input.IsKeyDown(KeyCode.A)) - { - orbitYaw -= safeDelta * 0.7f; - autoDrift = false; - } - - if (input.IsKeyDown(KeyCode.D)) - { - orbitYaw += safeDelta * 0.7f; - autoDrift = false; - } - - if (input.IsKeyDown(KeyCode.W)) - { - orbitPitch += safeDelta * 0.32f; - } - - if (input.IsKeyDown(KeyCode.S)) - { - orbitPitch -= safeDelta * 0.32f; - } - - if (MathF.Abs(input.WheelDelta) > 0.0f) - { - orbitDistance = Math.Clamp(orbitDistance - input.WheelDelta * MathF.Max(orbitDistance * 0.09f, 0.05f), 3.2f, 14.0f); - } - - if (input.LeftMouseDown && input.MouseDelta != Vector2.Zero) - { - orbitYaw -= input.MouseDelta.X * 0.006f; - orbitPitch += input.MouseDelta.Y * 0.0035f; - autoDrift = false; - } - - orbitPitch = Math.Clamp(orbitPitch, 0.08f, 0.42f); - } - - public void FlushState() - { - } - - public void Dispose() - { - } - - internal void SetOptions(AquariumRuntimeOptions options) - { - Options = options; - if (options.Headless) - { - autoDrift = false; - timeSeconds = 4.0f; - previousTimeSeconds = timeSeconds - (1.0f / 60.0f); - orbitYaw = 0.0f; - orbitPitch = 0.12f; - orbitDistance = 6.1f; - } - } - - private Vector3 ComposeCamera(Vector3 target) - { - var yaw = -0.03f + orbitYaw; - var horizontal = MathF.Cos(orbitPitch) * orbitDistance; - return new Vector3( - MathF.Sin(yaw) * horizontal, - -MathF.Cos(yaw) * horizontal, - target.Z + MathF.Sin(orbitPitch) * orbitDistance); - } -} - -public sealed class FensalirRuntimeFactory : IAquariumRuntimeFactory -{ - public IAquariumRuntime Create(AquariumRuntimeOptions options) - { - var runtime = new FensalirRuntime(); - runtime.SetOptions(options); - return runtime; - } -} diff --git a/src/Aquarium.Fensalir/FensalirSceneBuilder.cs b/src/Aquarium.Fensalir/FensalirSceneBuilder.cs deleted file mode 100644 index f48f421..0000000 --- a/src/Aquarium.Fensalir/FensalirSceneBuilder.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.Fensalir; - -public static class FensalirSceneBuilder -{ - private static readonly Vector3 SpineCenter = new(0.0f, -0.12f, 2.65f); - private const float SpineBoundRadius = 5.8f; - - public static AquariumSceneState Build(float timeSeconds, float previousTimeSeconds) - { - return new AquariumSceneState - { - TraceHeightFieldSurface = true, - UseStarfieldBackground = false, - HeightFieldBrushes = FensalirFractalScene.HeightBrushes, - SdfObjects = BuildSdfObjects(timeSeconds, previousTimeSeconds), - SdfLights = BuildSdfLights(), - }; - } - - private static AquariumSdfObject[] BuildSdfObjects(float timeSeconds, float previousTimeSeconds) - { - var sway = MathF.Sin(timeSeconds * 0.19f) * 0.018f; - var previousSway = MathF.Sin(previousTimeSeconds * 0.19f) * 0.018f; - var center = SpineCenter + new Vector3(sway, 0.0f, 0.0f); - var previousCenter = SpineCenter + new Vector3(previousSway, 0.0f, 0.0f); - return - [ - new AquariumSdfObject( - new Vector4(center, SpineBoundRadius), - new Vector4(previousCenter, 0.0f), - new Vector4(1.0f, timeSeconds, 0.0f, 0.0f)) - ]; - } - - private static AquariumSdfLight[] BuildSdfLights() - { - return - [ - new AquariumSdfLight( - new Vector4(SpineCenter, 2.8f), - new Vector4(0.95f, 1.75f, 2.8f, 10.0f)), - new AquariumSdfLight( - new Vector4(-2.5f, 0.25f, 1.3f, 1.9f), - new Vector4(1.0f, 0.16f, 0.72f, 10.0f)), - new AquariumSdfLight( - new Vector4(2.5f, 0.25f, 1.3f, 1.9f), - new Vector4(1.0f, 0.16f, 0.72f, 10.0f)), - ]; - } -} diff --git a/src/Aquarium.Fensalir/Shaders/D3D12FensalirScene.hlsl b/src/Aquarium.Fensalir/Shaders/D3D12FensalirScene.hlsl deleted file mode 100644 index be51123..0000000 --- a/src/Aquarium.Fensalir/Shaders/D3D12FensalirScene.hlsl +++ /dev/null @@ -1,418 +0,0 @@ -cbuffer AquariumFrame : register(b0) -{ - float2 resolution; - float timeSeconds; - float viewRadius; - float3 cameraPosition; - float farDistance; - float3 cameraTarget; - float sceneFlags; - float2 viewCenter; - float frameIndex; - float previousTimeSeconds; - float3 previousCameraPosition; - float previousViewRadius; - float3 previousCameraTarget; - float previousSceneFlags; - float2 previousViewCenter; - float2 jitterPixels; - float2 previousJitterPixels; - float renderDebugMode; - float exposure; - float bloomIntensity; - float bloomVeilIntensity; - float4 cursorWorlds; - float4 temporalGaussianInfo; -}; - -Texture2D heightFieldTexture : register(t0); -SamplerState linearSampler : register(s0); - -static const float FIELD_ID_HEIGHT_FIELD = 4.0; -static const float HEIGHT_FIELD_TEXEL_COUNT = 128.0; - -struct VertexOut -{ - float4 position : SV_Position; - float2 uv : TEXCOORD0; -}; - -struct SceneOut -{ - float4 colorTravel : SV_Target0; - float4 metadata : SV_Target1; - float4 control : SV_Target2; - float4 reservoirGuide : SV_Target3; - float depth : SV_Depth; -}; - -struct RayMarchResult -{ - float3 color; - float travel; - float fieldId; - float3 normal; - float coverage; - float stepCount; -}; - -VertexOut FullscreenTriangleVS(uint vertexId : SV_VertexID) -{ - float2 uv = float2((vertexId << 1) & 2, vertexId & 2); - VertexOut output; - output.position = float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0); - output.uv = uv; - return output; -} - -void cameraBasis(float3 camera, float3 target, out float3 forward, out float3 right, out float3 up) -{ - forward = normalize(target - camera); - right = normalize(cross(forward, float3(0.0, 0.0, 1.0))); - up = cross(right, forward); -} - -float3 rayDirectionForPixel(float2 pixel, float2 jitter, float3 camera, float3 target) -{ - float2 ndc = ((pixel + jitter) * 2.0 - resolution) / resolution.y; - float3 forward; - float3 right; - float3 up; - cameraBasis(camera, target, forward, right, up); - return normalize(forward * 1.6 + right * ndc.x + up * ndc.y); -} - -float2 viewLocal(float2 p) -{ - return (p - viewCenter) / max(viewRadius, 0.001); -} - -float2 viewUv(float2 p) -{ - return viewLocal(p) * 0.5 + 0.5; -} - -float terrainHeight(float2 p) -{ - return heightFieldTexture.SampleLevel(linearSampler, saturate(viewUv(p)), 0.0).r; -} - -float2 terrainGradient(float2 p) -{ - float2 uv = saturate(viewUv(p)); - float2 texel = 1.0 / HEIGHT_FIELD_TEXEL_COUNT; - float texelWorld = max((viewRadius * 2.0) / HEIGHT_FIELD_TEXEL_COUNT, 0.001); - - float hLeft = heightFieldTexture.SampleLevel(linearSampler, uv - float2(texel.x, 0.0), 0.0).r; - float hRight = heightFieldTexture.SampleLevel(linearSampler, uv + float2(texel.x, 0.0), 0.0).r; - float hDown = heightFieldTexture.SampleLevel(linearSampler, uv - float2(0.0, texel.y), 0.0).r; - float hUp = heightFieldTexture.SampleLevel(linearSampler, uv + float2(0.0, texel.y), 0.0).r; - return float2(hRight - hLeft, hUp - hDown) / (texelWorld * 2.0); -} - -bool traceHeightFieldSurfaceDirect(float3 origin, float3 direction, float intervalStart, float intervalEnd, out float3 hitPosition, out float travel) -{ - travel = max(intervalStart, 0.0); - float previousTravel = travel; - hitPosition = origin + direction * travel; - float previousGap = hitPosition.z - terrainHeight(hitPosition.xy); - - [loop] - for (int stepIndex = 0; stepIndex < 96; stepIndex++) - { - hitPosition = origin + direction * travel; - float2 local = viewLocal(hitPosition.xy); - if (length(local) > 1.08 && hitPosition.z < 4.0) - { - return false; - } - - float gap = hitPosition.z - terrainHeight(hitPosition.xy); - float hitEpsilon = max(0.002, travel * 0.00035); - if (length(local) <= 1.0 && (abs(gap) <= hitEpsilon || (previousGap > 0.0 && gap <= 0.0))) - { - float alpha = previousGap / max(previousGap - gap, 0.0001); - travel = lerp(previousTravel, travel, saturate(alpha)); - hitPosition = origin + direction * travel; - return travel > intervalStart && travel < intervalEnd && travel < farDistance; - } - - float2 slope = terrainGradient(hitPosition.xy); - float terrainRate = abs(direction.z - dot(slope, direction.xy)); - float terrainStep = gap > 0.0 ? gap / max(terrainRate, 0.22) : 0.026; - terrainStep = min(terrainStep * 0.62, max(viewRadius * 0.08, 0.026)); - previousTravel = travel; - previousGap = gap; - travel += max(terrainStep, 0.026); - if (travel > intervalEnd || travel > farDistance) - { - return false; - } - } - - return false; -} - -float hash31(float3 p) -{ - return frac(sin(dot(p, float3(12.9898, 78.233, 37.719))) * 43758.5453); -} - -float valueNoise3(float3 p) -{ - float3 cell = floor(p); - float3 local = frac(p); - local = local * local * (3.0 - 2.0 * local); - - float c000 = hash31(cell); - float c100 = hash31(cell + float3(1.0, 0.0, 0.0)); - float c010 = hash31(cell + float3(0.0, 1.0, 0.0)); - float c110 = hash31(cell + float3(1.0, 1.0, 0.0)); - float c001 = hash31(cell + float3(0.0, 0.0, 1.0)); - float c101 = hash31(cell + float3(1.0, 0.0, 1.0)); - float c011 = hash31(cell + float3(0.0, 1.0, 1.0)); - float c111 = hash31(cell + float3(1.0, 1.0, 1.0)); - - float x00 = lerp(c000, c100, local.x); - float x10 = lerp(c010, c110, local.x); - float x01 = lerp(c001, c101, local.x); - float x11 = lerp(c011, c111, local.x); - return lerp(lerp(x00, x10, local.y), lerp(x01, x11, local.y), local.z); -} - -float fractalNoise3(float3 p) -{ - float sum = 0.0; - float amplitude = 0.5; - [unroll] - for (int octave = 0; octave < 4; octave++) - { - sum += valueNoise3(p) * amplitude; - p = p * 2.03 + float3(5.7, 2.1, 9.3); - amplitude *= 0.52; - } - - return sum; -} - -float sdSegment2(float2 p, float2 a, float2 b) -{ - float2 pa = p - a; - float2 ba = b - a; - float h = saturate(dot(pa, ba) / max(dot(ba, ba), 0.0001)); - return length(pa - ba * h); -} - -float lineGlow(float2 p, float2 a, float2 b, float thickness) -{ - return exp(-sdSegment2(p, a, b) / max(thickness, 0.0001)); -} - -float diamondOutline(float2 p, float2 center, float2 radius, float thickness) -{ - float2 q = abs(p - center) / max(radius, 0.001); - float d = abs(q.x + q.y - 1.0) * min(radius.x, radius.y); - return exp(-d / max(thickness, 0.0001)); -} - -float verticalPane(float2 p, float x, float z0, float z1, float width) -{ - float heightMask = smoothstep(z0 - 0.02, z0 + 0.02, p.y) * smoothstep(z1 + 0.02, z1 - 0.02, p.y); - return exp(-abs(p.x - x) / max(width, 0.0001)) * heightMask; -} - -float reedSilhouette(float2 p, float x, float tilt, float height) -{ - float2 a = float2(x, -0.42); - float2 b = float2(x + tilt, -0.42 + height); - return exp(-sdSegment2(p, a, b) / 0.004) * smoothstep(0.32, -0.28, p.y); -} - -float3 cathedralRadiance(float3 direction) -{ - float2 p = float2(direction.x * 1.22, direction.z); - float verticalMask = smoothstep(-0.22, 0.08, p.y) * smoothstep(0.98, 0.68, p.y); - float horizonMask = exp(-abs(p.y + 0.115) * 42.0); - - float centerAxis = exp(-abs(p.x) / 0.004) * smoothstep(-0.22, 0.72, p.y); - float diamonds = 0.0; - diamonds += diamondOutline(p, float2(0.0, 0.00), float2(0.15, 0.12), 0.004); - diamonds += diamondOutline(p, float2(0.0, 0.20), float2(0.19, 0.15), 0.0045); - diamonds += diamondOutline(p, float2(0.0, 0.43), float2(0.24, 0.18), 0.005); - diamonds += diamondOutline(p, float2(0.0, 0.70), float2(0.15, 0.15), 0.004); - - float ribs = 0.0; - ribs += lineGlow(p, float2(-0.15, -0.05), float2(0.0, 0.11), 0.006); - ribs += lineGlow(p, float2(0.15, -0.05), float2(0.0, 0.11), 0.006); - - float panes = smoothstep(0.07, 0.0, abs(p.x)) * verticalMask * 0.35; - panes += smoothstep(0.23, 0.0, abs(p.x)) * smoothstep(-0.18, 0.14, p.y) * smoothstep(0.62, 0.24, p.y) * 0.20; - - float sideGlass = 0.0; - [unroll] - for (int index = 0; index < 8; index++) - { - float t = (float)index; - float spread = 0.30 + t * 0.075; - float height = 0.14 + t * 0.07; - float fade = 1.0 - t * 0.075; - sideGlass += verticalPane(p, -spread, -0.18, height, 0.0025 + t * 0.00045) * fade; - sideGlass += verticalPane(p, spread, -0.18, height, 0.0025 + t * 0.00045) * fade; - sideGlass += lineGlow(p, float2(-spread, -0.16), float2(-spread * 0.74, height - 0.08), 0.0028) * fade * 0.18; - sideGlass += lineGlow(p, float2(spread, -0.16), float2(spread * 0.74, height - 0.08), 0.0028) * fade * 0.18; - } - - float patchField = max(0.0, abs(terrainHeight(float2(direction.x * 8.0, direction.z * 5.8 + 1.1))) - 0.022); - float patchSpark = smoothstep(0.002, 0.018, patchField) * smoothstep(-0.2, 0.72, p.y); - float dustNoise = fractalNoise3(float3(p * 16.0, 9.0)); - float goldDust = pow(saturate(dustNoise - 0.48), 7.0) * (sideGlass + patchSpark) * 0.9; - - float sideMagenta = (verticalPane(p, -0.46, -0.18, 0.18, 0.02) + verticalPane(p, 0.46, -0.18, 0.18, 0.02)) * 0.45; - float cyanCore = centerAxis * 1.35 + diamonds * 0.86 + ribs * 0.30 + panes * 0.40; - float3 color = float3(0.18, 1.35, 2.05) * cyanCore; - color += float3(0.05, 0.52, 0.78) * sideGlass * 0.025; - color += float3(1.25, 0.12, 0.74) * (sideMagenta * 0.20 + horizonMask * 0.10); - color += float3(1.0, 0.68, 0.24) * goldDust; - return color; -} - -float3 screenCathedralRadiance(float2 uv) -{ - float2 p = float2(uv.x - 0.5, uv.y); - float3 color = 0.0; - - float horizon = exp(-abs(p.y - 0.345) * 82.0); - color += float3(1.12, 0.07, 0.68) * horizon * smoothstep(0.48, 0.08, abs(p.x)) * 0.42; - - float axis = exp(-abs(p.x) / 0.0018) * smoothstep(0.16, 0.38, p.y) * smoothstep(1.03, 0.52, p.y); - float diamond = 0.0; - diamond += diamondOutline(p, float2(0.0, 0.39), float2(0.070, 0.075), 0.0022); - diamond += diamondOutline(p, float2(0.0, 0.52), float2(0.082, 0.085), 0.0023); - diamond += diamondOutline(p, float2(0.0, 0.66), float2(0.115, 0.105), 0.0024); - diamond += diamondOutline(p, float2(0.0, 0.80), float2(0.070, 0.078), 0.0020); - color += float3(0.18, 1.55, 2.3) * (axis * 0.70 + diamond * 0.65); - - float paneFill = smoothstep(0.11, 0.0, abs(p.x)) * smoothstep(0.30, 0.48, p.y) * smoothstep(0.90, 0.58, p.y); - color += float3(0.06, 0.55, 0.72) * paneFill * 0.18; - - [unroll] - for (int index = 0; index < 10; index++) - { - float t = (float)index; - float x = 0.105 + t * 0.034; - float top = 0.52 + t * 0.032; - float fade = saturate(1.0 - t * 0.055); - float left = verticalPane(p, -x, 0.31, top, 0.0016) * fade; - float right = verticalPane(p, x, 0.31, top, 0.0016) * fade; - color += float3(0.05, 0.52, 0.70) * (left + right) * 0.28; - color += float3(1.0, 0.10, 0.68) * (left + right) * smoothstep(0.14, 0.34, abs(p.x)) * 0.20; - } - - float magentaGlass = 0.0; - magentaGlass += lineGlow(p, float2(-0.36, 0.31), float2(-0.22, 0.43), 0.0022); - magentaGlass += lineGlow(p, float2(0.36, 0.31), float2(0.22, 0.43), 0.0022); - magentaGlass += lineGlow(p, float2(-0.27, 0.38), float2(-0.16, 0.50), 0.0019); - magentaGlass += lineGlow(p, float2(0.27, 0.38), float2(0.16, 0.50), 0.0019); - color += float3(1.15, 0.12, 0.72) * magentaGlass * 0.26; - - float ripple = exp(-abs(p.x) / 0.028) * smoothstep(0.31, 0.16, p.y) * smoothstep(0.02, 0.13, p.y); - ripple *= 0.42 + 0.58 * pow(saturate(fractalNoise3(float3(p * 38.0, 2.0)) - 0.20), 2.0); - color += float3(0.11, 1.25, 2.2) * ripple * 0.46; - - float goldNoise = fractalNoise3(float3(p * 54.0, 5.0)); - float dust = pow(saturate(goldNoise - 0.56), 12.0) * smoothstep(0.25, 0.42, p.y) * smoothstep(0.82, 0.52, p.y); - color += float3(1.0, 0.72, 0.28) * dust * 0.38; - return color; -} - -float3 backgroundRadiance(float3 direction) -{ - float horizon = smoothstep(-0.28, 0.34, direction.z); - float verticalAxis = pow(saturate(1.0 - abs(direction.x) * 7.8), 3.0) * smoothstep(-0.18, 0.76, direction.z); - float hall = pow(saturate(1.0 - abs(abs(direction.x) - 0.24) * 11.0), 2.0) * smoothstep(-0.10, 0.62, direction.z); - float fog = pow(saturate(fractalNoise3(direction * 4.1 + float3(0.0, timeSeconds * 0.015, 0.0)) - 0.18), 2.2); - float2 hallPoint = float2(direction.x * 8.0, direction.z * 5.8 + 1.1); - float cathedralField = max(0.0, abs(terrainHeight(hallPoint)) - 0.022); - float cathedralPane = smoothstep(0.001, 0.016, cathedralField) * smoothstep(-0.22, 0.74, direction.z); - float verticalShard = pow(saturate(1.0 - abs(frac((direction.x + 0.5) * 28.0) - 0.5) * 2.0), 22.0); - float horizonLine = exp(-abs(direction.z + 0.095) * 34.0); - float runeDust = pow(saturate(fractalNoise3(float3(hallPoint * 4.0, 3.0)) - 0.54), 5.0) * cathedralPane; - - float3 voidColor = lerp(float3(0.001, 0.006, 0.009), float3(0.018, 0.055, 0.062), horizon); - float3 cyan = float3(0.50, 1.55, 2.25) * verticalAxis * 0.62; - float3 magenta = float3(1.25, 0.12, 0.82) * (hall * 0.16 + horizonLine * 0.11); - float3 mist = float3(0.12, 0.36, 0.38) * fog * (0.18 + horizon * 0.24); - float3 cathedral = float3(0.10, 0.66, 0.88) * cathedralPane * (0.22 + verticalShard * 0.35); - cathedral += float3(1.15, 0.16, 0.72) * cathedralPane * smoothstep(0.12, 0.52, abs(direction.x)) * 0.16; - cathedral += float3(1.0, 0.74, 0.28) * runeDust * 0.22; - return voidColor + cyan + magenta + mist + cathedral + cathedralRadiance(direction) * 0.08; -} - -float3 surfaceMirrorRadiance(float3 p, float3 direction, out float3 normal) -{ - float2 gradient = terrainGradient(p.xy); - normal = normalize(float3(-gradient.x, -gradient.y, 1.0)); - float3 reflectionDirection = reflect(direction, normal); - float3 reflected = backgroundRadiance(reflectionDirection); - - float spineReflection = exp(-abs(p.x) * 2.7) * smoothstep(3.4, -2.6, p.y); - float magentaLeft = exp(-abs(p.x + 2.35) * 3.2) * smoothstep(2.4, -2.2, p.y); - float magentaRight = exp(-abs(p.x - 2.35) * 3.2) * smoothstep(2.4, -2.2, p.y); - float rippleSparkle = pow(saturate(fractalNoise3(float3(p.xy * 5.2, timeSeconds * 0.22)) - 0.47), 5.0); - float waterline = exp(-abs(p.y - 0.95) * 2.1) * smoothstep(4.8, 0.2, abs(p.x)); - float reedMask = 0.0; - reedMask += reedSilhouette(float2(p.x * 0.22 - 1.18, p.y * 0.16 - 0.34), -0.05, -0.10, 0.45); - reedMask += reedSilhouette(float2(p.x * 0.20 + 1.18, p.y * 0.16 - 0.34), 0.02, 0.08, 0.36); - float fresnel = pow(1.0 - saturate(dot(normal, -direction)), 3.0); - - float3 baseWater = float3(0.002, 0.014, 0.017); - float3 cyan = float3(0.35, 1.40, 2.35) * spineReflection * (0.26 + rippleSparkle * 0.32); - float3 magenta = float3(1.10, 0.08, 0.74) * ((magentaLeft + magentaRight) * 0.08 + waterline * 0.055); - float3 gold = float3(1.0, 0.72, 0.26) * (rippleSparkle * 0.032 + waterline * rippleSparkle * 0.08); - float3 water = baseWater + reflected * (0.18 + fresnel * 0.32) + cyan + magenta + gold; - return lerp(water, float3(0.0, 0.002, 0.002), saturate(reedMask)); -} - -RayMarchResult traverseRay(float3 origin, float3 direction) -{ - RayMarchResult result; - result.color = backgroundRadiance(direction); - result.travel = farDistance + 1.0; - result.fieldId = 0.0; - result.normal = 0.0; - result.coverage = 0.0; - result.stepCount = 0.0; - - float3 surfacePosition; - float surfaceTravel; - bool surfaceHit = traceHeightFieldSurfaceDirect(origin, direction, 0.0, farDistance, surfacePosition, surfaceTravel); - if (surfaceHit) - { - float3 surfaceNormal; - result.color = surfaceMirrorRadiance(surfacePosition, direction, surfaceNormal); - result.travel = surfaceTravel; - result.fieldId = FIELD_ID_HEIGHT_FIELD; - result.normal = surfaceNormal; - result.coverage = 1.0; - } - - return result; -} - -SceneOut D3D12ScenePS(VertexOut input) -{ - float2 screenUv = float2(input.uv.x, 1.0 - input.uv.y); - float2 pixel = screenUv * resolution; - float3 rayDirection = rayDirectionForPixel(pixel, jitterPixels, cameraPosition, cameraTarget); - - RayMarchResult result = traverseRay(cameraPosition, rayDirection); - result.color += screenCathedralRadiance(screenUv); - - SceneOut output; - output.colorTravel = float4(result.color, min(result.travel, farDistance + 1.0)); - output.metadata = float4(result.fieldId, result.normal); - output.control = float4(result.coverage, result.stepCount / 96.0, 0.0, 0.0); - output.reservoirGuide = float4(1.0, 0.0, 1.0, 0.0); - output.depth = saturate(result.travel / max(farDistance, 0.001)); - return output; -} diff --git a/src/Aquarium.Fensalir/Shaders/D3D12FensalirSpine.hlsl b/src/Aquarium.Fensalir/Shaders/D3D12FensalirSpine.hlsl deleted file mode 100644 index 9c059a0..0000000 --- a/src/Aquarium.Fensalir/Shaders/D3D12FensalirSpine.hlsl +++ /dev/null @@ -1,169 +0,0 @@ -static const int SDF_INDEX = 0; - -#define SDF_TRACE_STEPS 192 -#define SDF_TRACE_STEP_SCALE 0.34 -#define SDF_TRACE_MAX_STEP_RADIUS_SCALE 0.018 - -#include "D3D12SdfCommon.hlsli" -#include "D3D12SdfMath.hlsli" - -float sdRoundBox(float3 p, float3 b, float r) -{ - float3 q = abs(p) - b; - return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r; -} - -float sdCappedCylinderZ(float3 p, float radius, float halfHeight) -{ - float2 d = abs(float2(length(p.xy), p.z)) - float2(radius, halfHeight); - return min(max(d.x, d.y), 0.0) + length(max(d, 0.0)); -} - -float sdDiamond(float3 p, float3 radius) -{ - float3 q = abs(p) / max(radius, 0.001); - return (q.x + q.y + q.z - 1.0) * min(radius.x, min(radius.y, radius.z)); -} - -float sdDiamondShell(float3 p, float3 radius, float thickness) -{ - return abs(sdDiamond(p, radius)) - thickness; -} - -float sdDiamondPane(float3 p, float2 radius, float halfDepth, float thickness) -{ - float outline = abs((abs(p.x) / max(radius.x, 0.001)) + (abs(p.z) / max(radius.y, 0.001)) - 1.0) * min(radius.x, radius.y) - thickness; - float depth = abs(p.y) - halfDepth; - return max(outline, depth); -} - -float fensalirSpineDistance(float3 local) -{ - float core = sdCappedCylinderZ(local - float3(0.0, 0.0, 0.24), 0.018, 3.05); - float diamonds = 999.0; - float panes = 999.0; - - [loop] - for (int index = 0; index < 8; index++) - { - float t = (float)index; - float z = -1.42 + t * 0.52; - float pulse = 0.5 + 0.5 * sin(timeSeconds * 0.42 + t * 1.7); - float broadMiddle = smoothstep(0.0, 3.5, t) * smoothstep(7.5, 3.5, t); - float side = lerp(0.42, 0.88, broadMiddle) * lerp(0.94, 1.04, pulse); - float3 q = local - float3(0.0, 0.0, z); - diamonds = min(diamonds, sdDiamondPane(q, float2(side, 0.31), 0.024, 0.016)); - } - - [loop] - for (int paneIndex = 0; paneIndex < 4; paneIndex++) - { - float side = paneIndex < 2 ? -1.0 : 1.0; - float rank = (float)(paneIndex % 2); - float x = side * (0.36 + rank * 0.32); - float z = -0.82 + rank * 0.78; - float3 p = local - float3(x, 0.02, z); - p.x -= side * p.z * (0.16 + rank * 0.08); - panes = min(panes, sdRoundBox(p, float3(0.014, 0.018, 1.35 - rank * 0.16), 0.012)); - } - - return min(core, min(diamonds, panes)); -} - -float fensalirPillarDistance(float3 local) -{ - float pillars = 999.0; - [loop] - for (int index = 0; index < 12; index++) - { - float side = index < 6 ? -1.0 : 1.0; - float rank = (float)(index % 6); - float x = side * (0.92 + rank * 0.38); - float y = 0.32 + rank * 0.16; - float3 p = local - float3(x, y, 0.0); - float lean = side * (0.06 + rank * 0.018); - p.x -= p.z * lean; - pillars = min(pillars, sdRoundBox(p, float3(0.015 + rank * 0.003, 0.038, 2.15 + rank * 0.19), 0.012)); - - float3 rib = local - float3(side * (0.7 + rank * 0.34), y - 0.1, -1.2 + rank * 0.28); - rib.x -= side * rib.z * 0.34; - pillars = min(pillars, sdRoundBox(rib, float3(0.012, 0.028, 0.72), 0.01)); - } - - return pillars; -} - -float fensalirReedDistance(float3 local) -{ - float reeds = 999.0; - [unroll] - for (int index = 0; index < 6; index++) - { - float side = index < 3 ? -1.0 : 1.0; - float rank = (float)(index % 3); - float x = side * (3.35 + rank * 0.32); - float y = -1.76 + rank * 0.18; - float height = 0.7 + rank * 0.18; - float3 a = float3(x, y, -2.05); - float3 b = float3(x + side * (0.18 + rank * 0.04), y + 0.08, -2.05 + height); - reeds = min(reeds, sdCapsuleSegment(local, a, b, 0.018)); - } - - return reeds; -} - -float sdfDistance(float3 p, int sdfIndex) -{ - SdfObject scene = sdfObjects[sdfIndex]; - float3 local = p - scene.centerRadius.xyz; - float spine = fensalirSpineDistance(local); - float reeds = fensalirReedDistance(local); - return min(spine, reeds); -} - -SdfSurface sdfSurface(float3 p, int sdfIndex) -{ - SdfObject scene = sdfObjects[sdfIndex]; - float3 local = p - scene.centerRadius.xyz; - float spine = fensalirSpineDistance(local); - float reeds = fensalirReedDistance(local); - float nearest = min(spine, reeds); - - float rune = pow(saturate(1.0 - abs(frac(local.z * 3.7 + local.x * 0.31) - 0.5) * 16.0), 2.6); - float coreGlow = pow(saturate(1.0 - length(local.xy) * 5.2), 2.0); - float magentaEdge = pow(saturate(abs(local.x) - 0.78), 2.0) * 0.05; - - SdfSurface surface; - surface.baseColor = float3(0.02, 0.07, 0.08); - surface.metallic = 0.0; - surface.roughness = 0.22; - surface.emission = 0.0; - surface.temporalDetail = 0.35 + rune * 0.35; - surface.reservoirConfidence = 1.0; - - if (nearest == spine) - { - surface.baseColor = float3(0.35, 0.86, 0.98); - surface.roughness = 0.06; - surface.emission = float3(0.35, 1.55, 2.45) * (2.0 + coreGlow * 5.6 + rune * 2.4); - } - else - { - surface.baseColor = float3(0.006, 0.018, 0.014); - surface.roughness = 0.72; - surface.emission = float3(0.03, 0.18, 0.13); - } - - return surface; -} - -float3 shadeSdf(float2 uv, float travel, float3 p, float3 normal, int sdfIndex, SdfSurface surface) -{ - float3 viewDirection = normalize(cameraPosition - p); - float rim = pow(1.0 - saturate(dot(normal, viewDirection)), 3.1); - float3 pbr = shadeSdfPbr(p, normal, surface); - float3 cyanRim = float3(0.22, 1.25, 2.4) * rim * 0.75; - return pbr + cyanRim; -} - -#include "D3D12SdfProxy.hlsli" diff --git a/src/Aquarium.Fensalir/Worlds/fensalir-spine-emblem.aquageo b/src/Aquarium.Fensalir/Worlds/fensalir-spine-emblem.aquageo deleted file mode 100644 index 922f3b8..0000000 --- a/src/Aquarium.Fensalir/Worlds/fensalir-spine-emblem.aquageo +++ /dev/null @@ -1,20 +0,0 @@ -# Fensalir splash scene patch. -# The marsh is a 2D surface domain: low height for mirror bed, ripple brushes for -# water motion, and recursive fine claims for small surface texture. -domain Surface2D fensalir/splash - -8 8 -4 6 0 0 0 0 -domain Surface2D fensalir/marsh fensalir/splash -8 8 -4 4 0 0 0 0 -domain Object3D fensalir/hall fensalir/marsh 0 0 0 6 0 0 0 0 -domain Object3D fensalir/spine fensalir/hall 0 0 2.6 3.8 0 0 0 0 -tile PositiveZ 0 0 0 fensalir/marsh-plane fensalir/marsh -height mirror-bed 0 0 8 4.8 0 2.4 1 -0.018 11 water-bed -ripple spine-reflection 0 -0.85 1.18 4.1 0 3.8 0.72 0.012 0.046 20.0 0.22 1.55 17 cyan-ripple -ripple magenta-left -2.4 -0.72 0.64 2.6 0.12 4.4 0.9 0.004 0.022 17.0 0.17 1.42 19 magenta-ripple -ripple magenta-right 2.4 -0.72 0.64 2.6 -0.12 4.4 0.9 0.004 0.022 17.0 0.17 1.42 23 magenta-ripple -ripple hall-wake 0 1.2 4.8 1.2 0 3.0 1.1 -0.006 0.019 11.0 -0.08 1.25 29 hall-wake -ifs edge-reeds 3 2 -6.5 -0.8 0.52 1.8 0.48 3.5 0.91 5.0 1.05 0.006 31 reed-shadow -ifs edge-reeds 3 2 6.5 -0.7 0.52 1.8 0.48 3.5 -0.91 5.0 1.05 0.006 37 reed-shadow -ifs micro-ripples 3 2 0 -1.6 2.8 1.2 0.42 2.6 0.37 6.2 0.8 0.003 41 micro-ripple -ifs hall-spires 3 2 0 2.35 5.2 0.42 0.52 2.2 0.0 5.4 1.15 0.028 47 cathedral-spire -ifs rune-strata 3 2 0 3.15 3.2 0.22 0.46 2.8 0.42 7.0 0.92 0.018 53 cathedral-rune -ifs magenta-buttress 2 2 -2.4 1.1 1.6 0.28 0.58 2.1 0.72 5.4 1.1 0.020 59 cathedral-magenta -ifs magenta-buttress 2 2 2.4 1.1 1.6 0.28 0.58 2.1 -0.72 5.4 1.1 0.020 61 cathedral-magenta diff --git a/src/Aquarium.LocalCast/Aquarium.LocalCast.csproj b/src/Aquarium.LocalCast/Aquarium.LocalCast.csproj deleted file mode 100644 index fa40f71..0000000 --- a/src/Aquarium.LocalCast/Aquarium.LocalCast.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - net10.0 - Aquarium.LocalCast - Aquarium.LocalCast - enable - enable - true - - - - - - - - - diff --git a/src/Aquarium.LocalCast/LocalCastGpuFusionAccumulator.cs b/src/Aquarium.LocalCast/LocalCastGpuFusionAccumulator.cs deleted file mode 100644 index 51699b6..0000000 --- a/src/Aquarium.LocalCast/LocalCastGpuFusionAccumulator.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Aquarium.Engine.Fractal.Temporal; -using Aquarium.Engine.Render; - -namespace Aquarium.LocalCast; - -public sealed class LocalCastGpuFusionAccumulator -{ - private const float PresentationDelaySeconds = 0.35f; - - private readonly TemporalSpatialEvidenceReservoir reservoir; - private readonly LocalCastGpuFusionMapper mapper = new(); - private readonly float historySeconds; - - public LocalCastGpuFusionAccumulator(float historySeconds, float smoothing = 0.45f, int maxSeedCount = 1_048_576) - { - this.historySeconds = historySeconds; - reservoir = new TemporalSpatialEvidenceReservoir( - historySeconds, - PresentationDelaySeconds, - smoothing, - Math.Max(1, maxSeedCount)); - } - - public int TrackCount => reservoir.TrackCount; - - public void Observe(LocalCastVisualFrame frame) - { - var field = mapper.Map(frame); - var frameTimeSeconds = mapper.ToTimelineSeconds(frame.SourceTimeMaxNs); - reservoir.Observe(field.Seeds.Select(seed => TemporalSpatialEvidenceLowering.FromGpuFusionSeed(seed, frameTimeSeconds))); - } - - public AquariumGpuFusionField BuildField(float renderTimeSeconds) - { - var snapshot = reservoir.BuildSnapshot(renderTimeSeconds); - - return new AquariumGpuFusionField - { - Seeds = snapshot.Samples.Select(TemporalSpatialEvidenceLowering.ToGpuFusionSeed).ToArray(), - AccumulationWindowSeconds = historySeconds, - PresentationDelaySeconds = PresentationDelaySeconds, - }; - } -} diff --git a/src/Aquarium.LocalCast/LocalCastGpuFusionMapper.cs b/src/Aquarium.LocalCast/LocalCastGpuFusionMapper.cs deleted file mode 100644 index 8204388..0000000 --- a/src/Aquarium.LocalCast/LocalCastGpuFusionMapper.cs +++ /dev/null @@ -1,73 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.LocalCast; - -public sealed class LocalCastGpuFusionMapper -{ - private const float NanosecondsToSeconds = 1.0f / 1_000_000_000.0f; - - public AquariumGpuFusionField Map(LocalCastVisualFrame frame) - { - var seeds = new AquariumGpuFusionSeed[frame.Points.Count]; - for (var index = 0; index < frame.Points.Count; index++) - { - seeds[index] = MapPoint(frame.Points[index], index); - } - - return new AquariumGpuFusionField - { - Seeds = seeds, - AccumulationWindowSeconds = 2.75f, - PresentationDelaySeconds = 0.35f, - }; - } - - private static AquariumGpuFusionSeed MapPoint(LocalCastVisualPoint point, int fieldId) - { - var confidence = Math.Clamp(point.Confidence, 0.0f, 1.0f); - var radius = Math.Clamp(point.RadiusMeters, 0.0015f, 0.09f); - var isLeap = point.StableKey.StartsWith("leap-motion:", StringComparison.Ordinal); - var isDense = point.StableKey.StartsWith("dense-rgb:", StringComparison.Ordinal); - var anisotropy = isLeap ? 0.62f : isDense ? 0.42f : 0.55f; - var radii = new Vector3(radius * 1.7f, radius * anisotropy, radius * 1.15f); - var opacity = Math.Clamp(point.ColorOpacity.W * (0.35f + confidence * 0.65f), 0.0f, 0.98f); - var color = new Vector4( - Math.Clamp(point.ColorOpacity.X, 0.0f, 1.0f), - Math.Clamp(point.ColorOpacity.Y, 0.0f, 1.0f), - Math.Clamp(point.ColorOpacity.Z, 0.0f, 1.0f), - opacity); - - return new AquariumGpuFusionSeed( - point.StableKey, - point.Position, - point.Position, - Vector3.Zero, - radii, - color, - confidence, - confidence, - isDense ? 5.5f : 4.2f, - isLeap ? 2.4f : 1.65f, - StableFieldId(point.StableKey, fieldId)); - } - - public float ToTimelineSeconds(long monotonicNs) - { - return monotonicNs * NanosecondsToSeconds; - } - - private static int StableFieldId(string key, int fallback) - { - unchecked - { - var hash = 17; - foreach (var ch in key) - { - hash = (hash * 31) + ch; - } - - return Math.Abs(hash == int.MinValue ? fallback : hash); - } - } -} diff --git a/src/Aquarium.LocalCast/LocalCastNativeReservoir.cs b/src/Aquarium.LocalCast/LocalCastNativeReservoir.cs deleted file mode 100644 index 99c3168..0000000 --- a/src/Aquarium.LocalCast/LocalCastNativeReservoir.cs +++ /dev/null @@ -1,379 +0,0 @@ -using System.Runtime.InteropServices; -using System.Text; - -namespace Aquarium.LocalCast; - -public enum LocalCastNativeSampleKind : uint -{ - CameraFrame = 0, - CameraFeature = 1, - SceneRay = 2, - SurfaceClaim = 3, - MaterialClaim = 4, - AudioBlock = 5, - PhaseClaim = 6, - EventClaim = 7, - RenderPacket = 8, -} - -public enum LocalCastNativeAudioSampleFormat : uint -{ - Float32Interleaved = 1, -} - -[Flags] -public enum LocalCastNativeSampleFlags : uint -{ - None = 0, - Diagnostic = 1u << 0, -} - -[StructLayout(LayoutKind.Sequential)] -public struct LocalCastNativeSampleHandle -{ - public ulong SensorIdHash; - public ulong TimestampNs; - public ulong ArrivalNs; - public ulong Sequence; - public ulong PayloadHandle; - public LocalCastNativeSampleFlags Flags; - public uint Reserved; - - public readonly bool IsLive => Flags == LocalCastNativeSampleFlags.None; -} - -[StructLayout(LayoutKind.Sequential)] -public struct LocalCastNativeAudioBlockDescriptor -{ - public ulong DataHandle; - public uint FrameCount; - public uint ChannelCount; - public uint SampleRateHz; - public LocalCastNativeAudioSampleFormat SampleFormat; - public ulong StartSample; - public ulong ChannelLayoutHash; -} - -[StructLayout(LayoutKind.Sequential)] -public struct LocalCastNativeRenderPacketDescriptor -{ - public ulong PointBufferHandle; - public uint PointCount; - public uint PointStrideBytes; - public uint TargetWidth; - public uint TargetHeight; - public ulong SourceTimeMinNs; - public ulong SourceTimeMaxNs; - public ulong PresentTimeNs; - public ulong AudioAlignmentTimeNs; - public ulong MetadataHandle; -} - -[StructLayout(LayoutKind.Sequential)] -public struct LocalCastNativeRenderPoint -{ - public ulong StableKeyHash; - public ulong SourceTimestampNs; - public float X; - public float Y; - public float Z; - public float RadiusMeters; - public float Red; - public float Green; - public float Blue; - public float Alpha; - public float Confidence; -} - -[StructLayout(LayoutKind.Sequential)] -public struct LocalCastNativeRuntimeStatus -{ - public ulong EdgeNs; - public ulong WindowStartNs; - public UIntPtr TotalSampleCount; - public UIntPtr CameraFrameCount; - public UIntPtr CameraFeatureCount; - public UIntPtr SceneRayCount; - public UIntPtr SurfaceClaimCount; - public UIntPtr MaterialClaimCount; - public UIntPtr AudioBlockCount; - public UIntPtr PhaseClaimCount; - public UIntPtr EventClaimCount; - public UIntPtr RenderPacketCount; -} - -public interface ILocalCastNativeRuntime : IDisposable -{ - bool TryGetStatus(out LocalCastNativeRuntimeStatus status); - - bool TryReadSample(nuint index, out LocalCastNativeSampleKind kind, out LocalCastNativeSampleHandle sample); - - bool TryReadViewSample(LocalCastNativeSampleKind kind, nuint index, out LocalCastNativeSampleHandle sample); - - bool TryReadLatestForSensor(LocalCastNativeSampleKind kind, ulong sensorIdHash, out LocalCastNativeSampleHandle sample); -} - -public static class LocalCastNativeSourceId -{ - public static ulong HashUtf8(string sourceId) - { - if (string.IsNullOrEmpty(sourceId)) - { - return 0; - } - - var bytes = Encoding.UTF8.GetBytes(sourceId); - return LocalCastNativeMethods.HashSourceId(bytes, (UIntPtr)bytes.Length); - } -} - -public interface ILocalCastNativeProducer : IDisposable -{ - ulong NextSequence { get; } - - bool TryPush(ulong timestampNs, ulong arrivalNs, ulong payloadHandle, out LocalCastNativeSampleHandle sample); - - bool TryPushAudioBlock( - ulong timestampNs, - ulong arrivalNs, - in LocalCastNativeAudioBlockDescriptor descriptor, - out LocalCastNativeSampleHandle sample); - - bool TryPushRenderPacket( - ulong timestampNs, - ulong arrivalNs, - in LocalCastNativeRenderPacketDescriptor descriptor, - out LocalCastNativeSampleHandle sample); -} - -public sealed class LocalCastNativeRuntime : ILocalCastNativeRuntime -{ - private IntPtr handle; - - public LocalCastNativeRuntime(ulong durationNs) - { - handle = LocalCastNativeMethods.RuntimeCreate(durationNs); - if (handle == IntPtr.Zero) - { - throw new InvalidOperationException("LocalCast native runtime creation failed."); - } - } - - internal IntPtr Handle => handle; - - public bool TryGetStatus(out LocalCastNativeRuntimeStatus status) - { - EnsureNotDisposed(); - return LocalCastNativeMethods.RuntimeStatus(handle, out status); - } - - public bool TryReadSample(nuint index, out LocalCastNativeSampleKind kind, out LocalCastNativeSampleHandle sample) - { - EnsureNotDisposed(); - var ok = LocalCastNativeMethods.RuntimeSampleAt(handle, index, out var rawKind, out sample); - kind = (LocalCastNativeSampleKind)rawKind; - return ok; - } - - public bool TryReadViewSample(LocalCastNativeSampleKind kind, nuint index, out LocalCastNativeSampleHandle sample) - { - EnsureNotDisposed(); - return LocalCastNativeMethods.RuntimeViewSampleAt(handle, (uint)kind, index, out sample); - } - - public bool TryReadLatestForSensor(LocalCastNativeSampleKind kind, ulong sensorIdHash, out LocalCastNativeSampleHandle sample) - { - EnsureNotDisposed(); - return LocalCastNativeMethods.RuntimeLatestForSensor(handle, (uint)kind, sensorIdHash, out sample); - } - - public LocalCastNativeProducer CreateProducer(LocalCastNativeSampleKind kind, ulong sensorIdHash, ulong initialSequence = 0) - { - EnsureNotDisposed(); - return new LocalCastNativeProducer(this, kind, sensorIdHash, initialSequence); - } - - public LocalCastNativeProducer CreateProducer(LocalCastNativeSampleKind kind, string sourceId, ulong initialSequence = 0) - { - EnsureNotDisposed(); - return new LocalCastNativeProducer(this, kind, sourceId, initialSequence); - } - - public void Dispose() - { - if (handle == IntPtr.Zero) - { - return; - } - - LocalCastNativeMethods.RuntimeDestroy(handle); - handle = IntPtr.Zero; - } - - private void EnsureNotDisposed() - { - ObjectDisposedException.ThrowIf(handle == IntPtr.Zero, this); - } -} - -public sealed class LocalCastNativeProducer : ILocalCastNativeProducer -{ - private readonly LocalCastNativeRuntime runtime; - private IntPtr handle; - - internal LocalCastNativeProducer(LocalCastNativeRuntime runtime, LocalCastNativeSampleKind kind, ulong sensorIdHash, ulong initialSequence) - { - this.runtime = runtime; - handle = LocalCastNativeMethods.ProducerCreate((uint)kind, sensorIdHash, initialSequence); - if (handle == IntPtr.Zero) - { - throw new InvalidOperationException("LocalCast native producer creation failed."); - } - } - - internal LocalCastNativeProducer(LocalCastNativeRuntime runtime, LocalCastNativeSampleKind kind, string sourceId, ulong initialSequence) - { - this.runtime = runtime; - var bytes = Encoding.UTF8.GetBytes(sourceId); - handle = LocalCastNativeMethods.ProducerCreateForSource((uint)kind, bytes, (UIntPtr)bytes.Length, initialSequence); - if (handle == IntPtr.Zero) - { - throw new InvalidOperationException("LocalCast native producer creation failed."); - } - } - - public ulong NextSequence - { - get - { - EnsureNotDisposed(); - return LocalCastNativeMethods.ProducerNextSequence(handle); - } - } - - public bool TryPush(ulong timestampNs, ulong arrivalNs, ulong payloadHandle, out LocalCastNativeSampleHandle sample) - { - EnsureNotDisposed(); - return LocalCastNativeMethods.ProducerPush(handle, runtime.Handle, timestampNs, arrivalNs, payloadHandle, out sample); - } - - public bool TryPushAudioBlock( - ulong timestampNs, - ulong arrivalNs, - in LocalCastNativeAudioBlockDescriptor descriptor, - out LocalCastNativeSampleHandle sample) - { - EnsureNotDisposed(); - return LocalCastNativeMethods.ProducerPushAudioBlock(handle, runtime.Handle, timestampNs, arrivalNs, in descriptor, out sample); - } - - public bool TryPushRenderPacket( - ulong timestampNs, - ulong arrivalNs, - in LocalCastNativeRenderPacketDescriptor descriptor, - out LocalCastNativeSampleHandle sample) - { - EnsureNotDisposed(); - return LocalCastNativeMethods.ProducerPushRenderPacket(handle, runtime.Handle, timestampNs, arrivalNs, in descriptor, out sample); - } - - public void Dispose() - { - if (handle == IntPtr.Zero) - { - return; - } - - LocalCastNativeMethods.ProducerDestroy(handle); - handle = IntPtr.Zero; - } - - private void EnsureNotDisposed() - { - ObjectDisposedException.ThrowIf(handle == IntPtr.Zero, this); - } -} - -internal static class LocalCastNativeMethods -{ - private const string LibraryName = "localcast_reservoir"; - - [DllImport(LibraryName, EntryPoint = "localcast_hash_source_id")] - internal static extern ulong HashSourceId(byte[] bytes, UIntPtr byteLen); - - [DllImport(LibraryName, EntryPoint = "localcast_runtime_create")] - internal static extern IntPtr RuntimeCreate(ulong durationNs); - - [DllImport(LibraryName, EntryPoint = "localcast_runtime_destroy")] - internal static extern void RuntimeDestroy(IntPtr runtime); - - [DllImport(LibraryName, EntryPoint = "localcast_runtime_status")] - [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool RuntimeStatus(IntPtr runtime, out LocalCastNativeRuntimeStatus status); - - [DllImport(LibraryName, EntryPoint = "localcast_runtime_sample_at")] - [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool RuntimeSampleAt( - IntPtr runtime, - UIntPtr index, - out uint sampleKind, - out LocalCastNativeSampleHandle sample); - - [DllImport(LibraryName, EntryPoint = "localcast_runtime_view_sample_at")] - [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool RuntimeViewSampleAt( - IntPtr runtime, - uint sampleKind, - UIntPtr index, - out LocalCastNativeSampleHandle sample); - - [DllImport(LibraryName, EntryPoint = "localcast_runtime_latest_for_sensor")] - [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool RuntimeLatestForSensor( - IntPtr runtime, - uint sampleKind, - ulong sensorIdHash, - out LocalCastNativeSampleHandle sample); - - [DllImport(LibraryName, EntryPoint = "localcast_producer_create")] - internal static extern IntPtr ProducerCreate(uint sampleKind, ulong sensorIdHash, ulong initialSequence); - - [DllImport(LibraryName, EntryPoint = "localcast_producer_create_for_source")] - internal static extern IntPtr ProducerCreateForSource(uint sampleKind, byte[] sourceIdBytes, UIntPtr sourceIdByteLen, ulong initialSequence); - - [DllImport(LibraryName, EntryPoint = "localcast_producer_destroy")] - internal static extern void ProducerDestroy(IntPtr producer); - - [DllImport(LibraryName, EntryPoint = "localcast_producer_next_sequence")] - internal static extern ulong ProducerNextSequence(IntPtr producer); - - [DllImport(LibraryName, EntryPoint = "localcast_producer_push")] - [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool ProducerPush( - IntPtr producer, - IntPtr runtime, - ulong timestampNs, - ulong arrivalNs, - ulong payloadHandle, - out LocalCastNativeSampleHandle sample); - - [DllImport(LibraryName, EntryPoint = "localcast_producer_push_audio_block")] - [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool ProducerPushAudioBlock( - IntPtr producer, - IntPtr runtime, - ulong timestampNs, - ulong arrivalNs, - in LocalCastNativeAudioBlockDescriptor descriptor, - out LocalCastNativeSampleHandle sample); - - [DllImport(LibraryName, EntryPoint = "localcast_producer_push_render_packet")] - [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool ProducerPushRenderPacket( - IntPtr producer, - IntPtr runtime, - ulong timestampNs, - ulong arrivalNs, - in LocalCastNativeRenderPacketDescriptor descriptor, - out LocalCastNativeSampleHandle sample); -} diff --git a/src/Aquarium.LocalCast/LocalCastNativeVisualFrameSource.cs b/src/Aquarium.LocalCast/LocalCastNativeVisualFrameSource.cs deleted file mode 100644 index 022daa9..0000000 --- a/src/Aquarium.LocalCast/LocalCastNativeVisualFrameSource.cs +++ /dev/null @@ -1,218 +0,0 @@ -using System.Runtime.InteropServices; -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.LocalCast; - -public delegate bool LocalCastNativeRenderPayloadDecoder( - LocalCastNativeSampleHandle sample, - out LocalCastVisualFrame frame); - -public delegate bool LocalCastNativeRenderPointBufferDecoder( - in LocalCastNativeRenderPacketDescriptor descriptor, - LocalCastNativeSampleHandle sample, - out IReadOnlyList points); - -public sealed class LocalCastNativeRenderDescriptorDecoder -{ - private readonly LocalCastNativeRenderPointBufferDecoder decodePointBuffer; - private readonly string spoutSenderName; - - public LocalCastNativeRenderDescriptorDecoder( - LocalCastNativeRenderPointBufferDecoder decodePointBuffer, - string spoutSenderName = "LocalCastBridge Point Cloud") - { - this.decodePointBuffer = decodePointBuffer; - this.spoutSenderName = spoutSenderName; - } - - public bool TryDecode(LocalCastNativeSampleHandle sample, out LocalCastVisualFrame frame) - { - frame = EmptyFrame(); - if (!sample.IsLive || sample.PayloadHandle == 0) - { - return false; - } - - var descriptor = Marshal.PtrToStructure((IntPtr)sample.PayloadHandle); - if (!decodePointBuffer(in descriptor, sample, out var points)) - { - return false; - } - - frame = new LocalCastVisualFrame - { - SchemaVersion = LocalCastVisualStateReader.RenderFrameSchemaId, - FrameId = checked((long)sample.Sequence), - CreatedMonotonicNs = checked((long)sample.ArrivalNs), - SourceTimeMinNs = checked((long)descriptor.SourceTimeMinNs), - SourceTimeMaxNs = checked((long)descriptor.SourceTimeMaxNs), - PresentTimeNs = checked((long)descriptor.PresentTimeNs), - AudioAlignmentTimeNs = checked((long)descriptor.AudioAlignmentTimeNs), - SpoutSenderName = spoutSenderName, - TargetWidth = checked((int)descriptor.TargetWidth), - TargetHeight = checked((int)descriptor.TargetHeight), - Points = points, - NativeGpuFusionPointBuffer = CreateDirectPointBuffer(in descriptor), - }; - return true; - } - - public static bool DecodeNoManagedPoints( - in LocalCastNativeRenderPacketDescriptor descriptor, - LocalCastNativeSampleHandle _, - out IReadOnlyList points) - { - points = []; - return descriptor.PointCount == 0 || CanUploadDirectly(in descriptor); - } - - public static bool DecodeNativePointBuffer( - in LocalCastNativeRenderPacketDescriptor descriptor, - LocalCastNativeSampleHandle _, - out IReadOnlyList points) - { - points = []; - var pointSize = Marshal.SizeOf(); - if (descriptor.PointCount == 0) - { - return true; - } - - if (descriptor.PointBufferHandle == 0 || descriptor.PointStrideBytes < pointSize) - { - return false; - } - - var decoded = new LocalCastVisualPoint[checked((int)descriptor.PointCount)]; - var cursor = (IntPtr)descriptor.PointBufferHandle; - var stride = checked((int)descriptor.PointStrideBytes); - for (var index = 0; index < decoded.Length; index++) - { - var native = Marshal.PtrToStructure(IntPtr.Add(cursor, index * stride)); - decoded[index] = new LocalCastVisualPoint( - $"native:{native.StableKeyHash:x16}", - new Vector3(native.X, native.Y, native.Z), - native.RadiusMeters, - new Vector4(native.Red, native.Green, native.Blue, native.Alpha), - native.Confidence, - checked((long)native.SourceTimestampNs)); - } - - points = decoded; - return true; - } - - private static AquariumGpuFusionPointBuffer CreateDirectPointBuffer(in LocalCastNativeRenderPacketDescriptor descriptor) - { - if (!CanUploadDirectly(in descriptor)) - { - return default; - } - - return new AquariumGpuFusionPointBuffer( - (IntPtr)descriptor.PointBufferHandle, - checked((int)descriptor.PointCount), - checked((int)descriptor.PointStrideBytes)); - } - - private static bool CanUploadDirectly(in LocalCastNativeRenderPacketDescriptor descriptor) - { - var pointSize = Marshal.SizeOf(); - return descriptor.PointCount == 0 - || (descriptor.PointBufferHandle != 0 && descriptor.PointStrideBytes == pointSize); - } - - private static LocalCastVisualFrame EmptyFrame() - { - return new LocalCastVisualFrame - { - SchemaVersion = LocalCastVisualStateReader.RenderFrameSchemaId, - FrameId = -1, - CreatedMonotonicNs = 0, - SourceTimeMinNs = 0, - SourceTimeMaxNs = 0, - PresentTimeNs = 0, - AudioAlignmentTimeNs = 0, - SpoutSenderName = string.Empty, - TargetWidth = 0, - TargetHeight = 0, - Points = [], - }; - } -} - -public sealed class LocalCastNativeVisualFrameSource : ILocalCastVisualFrameSource -{ - private readonly ILocalCastNativeRuntime runtime; - private readonly LocalCastNativeRenderPayloadDecoder decodeRenderPayload; - - public LocalCastNativeVisualFrameSource( - ILocalCastNativeRuntime runtime, - string description = "native LocalcastRuntime") - : this( - runtime, - new LocalCastNativeRenderDescriptorDecoder(LocalCastNativeRenderDescriptorDecoder.DecodeNoManagedPoints).TryDecode, - description) - { - } - - public LocalCastNativeVisualFrameSource( - ILocalCastNativeRuntime runtime, - LocalCastNativeRenderPayloadDecoder decodeRenderPayload, - string description = "native LocalcastRuntime") - { - this.runtime = runtime; - this.decodeRenderPayload = decodeRenderPayload; - Description = description; - } - - public string Description { get; } - - public bool TryReadLatest(out LocalCastVisualFrame frame) - { - frame = EmptyFrame(); - if (!runtime.TryGetStatus(out var status) || status.RenderPacketCount == UIntPtr.Zero) - { - return false; - } - - var index = status.RenderPacketCount - 1; - if (!runtime.TryReadViewSample(LocalCastNativeSampleKind.RenderPacket, index, out var sample) || !sample.IsLive) - { - return false; - } - - return decodeRenderPayload(sample, out frame); - } - - public bool TryReadLatestClapEvents(out LocalCastClapCalibrationFrame frame) - { - frame = new LocalCastClapCalibrationFrame - { - SchemaVersion = LocalCastVisualStateReader.ClapEventsSchemaId, - FrameId = -1, - CreatedMonotonicNs = 0, - Events = [], - }; - return false; - } - - private static LocalCastVisualFrame EmptyFrame() - { - return new LocalCastVisualFrame - { - SchemaVersion = LocalCastVisualStateReader.RenderFrameSchemaId, - FrameId = -1, - CreatedMonotonicNs = 0, - SourceTimeMinNs = 0, - SourceTimeMaxNs = 0, - PresentTimeNs = 0, - AudioAlignmentTimeNs = 0, - SpoutSenderName = string.Empty, - TargetWidth = 0, - TargetHeight = 0, - Points = [], - }; - } -} diff --git a/src/Aquarium.LocalCast/LocalCastRenderPlan.cs b/src/Aquarium.LocalCast/LocalCastRenderPlan.cs deleted file mode 100644 index 33d089a..0000000 --- a/src/Aquarium.LocalCast/LocalCastRenderPlan.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Aquarium.Engine.Render; - -namespace Aquarium.LocalCast; - -public static class LocalCastRenderPlan -{ - public static AquariumRenderPlan Create() - { - var app = new AquariumApp(); - var scene = app.RenderTargets.Hdr("scene"); - app.Cameras.Orbit("main"); - app.Graph.Pass("scene").Fullscreen(); - app.Features.Bloom(scene.Color); - app.Features.Presentation(scene.Color); - app.Features.DirectWriteOverlay(); - app.Debug.View("Scene", scene.Color); - return app.Plan; - } -} diff --git a/src/Aquarium.LocalCast/LocalCastRuntime.cs b/src/Aquarium.LocalCast/LocalCastRuntime.cs deleted file mode 100644 index 7cb436e..0000000 --- a/src/Aquarium.LocalCast/LocalCastRuntime.cs +++ /dev/null @@ -1,208 +0,0 @@ -using System.Numerics; -using Aquarium.Engine; -using Aquarium.Engine.Audio; -using Aquarium.Engine.Fractal.Temporal; -using Aquarium.Engine.Input; -using Aquarium.Engine.Render; -using Aquarium.Engine.Ui; - -namespace Aquarium.LocalCast; - -public sealed class LocalCastRuntime : IAquariumRuntime -{ - private readonly TemporalGaussianAccumulator accumulator = new( - accumulationWindowSeconds: 2.75f, - presentationDelaySeconds: 0.35f, - smoothing: 0.55f); - private readonly LocalCastTemporalGaussianMapper mapper = new(); - private readonly LocalCastGpuFusionMapper gpuFusionMapper = new(); - private readonly LocalCastGpuFusionAccumulator gpuFusionAccumulator = new( - ResolveGpuHistorySeconds(), - smoothing: 0.45f); - private readonly ILocalCastVisualFrameSource frameSource; - private float timeSeconds; - private float sceneTimelineSeconds; - private long lastFrameId = -1; - private long lastClapFrameId = -1; - private int latestPointCount; - private int latestClapCount; - private string latestStatus = "waiting"; - private AquariumCalibrationEventFrame latestCalibrationEvents = AquariumCalibrationEventFrame.Empty; - private AquariumGpuFusionField latestDirectGpuFusionField = AquariumGpuFusionField.Empty; - - public LocalCastRuntime(AquariumRuntimeOptions options) - : this(options, new LocalCastVisualStateFileSource(ResolveVisualCachePath())) - { - } - - public LocalCastRuntime(AquariumRuntimeOptions options, ILocalCastVisualFrameSource frameSource) - { - Options = options; - this.frameSource = frameSource; - Ui = new AquariumUiDocument() - .Panel("LocalCast", 18.0f, 82.0f, 372.0f, panel => - { - panel.Section("Camera Field"); - panel.Readout("Source", () => this.frameSource.Description); - panel.Readout("Frame", () => lastFrameId >= 0 ? $"{lastFrameId} / {latestPointCount} splats" : latestStatus); - panel.Readout("Claps", () => lastClapFrameId >= 0 ? $"{lastClapFrameId} / {latestClapCount} events" : "none"); - panel.Readout("History", () => $"{gpuFusionAccumulator.TrackCount} tracked seeds"); - panel.Readout("Timeline", () => $"{sceneTimelineSeconds:0.000}s"); - }); - } - - public AquariumRuntimeOptions Options { get; } - - public GraphicsSettings GraphicsSettings { get; set; } = new(0, 1.38f, 0.32f, 0.04f); - - public AquariumRenderPlan RenderPlan { get; } = LocalCastRenderPlan.Create(); - - public AquariumUiDocument Ui { get; } - - public AquariumAudioDocument Audio { get; } = new(); - - public AquariumSynthDocument Synth { get; } = AquariumSynthDocument.Empty; - - public AquariumFrame Frame - { - get - { - var temporalField = accumulator.BuildField(sceneTimelineSeconds); - var gpuFusionField = latestDirectGpuFusionField.HasInput - ? latestDirectGpuFusionField - : gpuFusionAccumulator.BuildField(sceneTimelineSeconds); - var scene = new AquariumSceneState - { - TraceHeightFieldSurface = false, - UseStarfieldBackground = false, - TemporalGaussianField = !gpuFusionField.HasInput - ? temporalField - : AquariumTemporalGaussianField.Empty, - CalibrationEventFrame = latestCalibrationEvents, - GpuFusionField = gpuFusionField, - }; - - return new AquariumFrame( - new ViewFrame(new Vector2(0.0f, 0.18f), 2.35f), - new Vector3(0.0f, -2.35f, 1.35f), - new Vector3(0.0f, 0.18f, 1.18f), - timeSeconds, - Vector2.Zero, - scene); - } - } - - public AquariumFrame ComposeFrame(AquariumFrame frame, AquariumFrameInput input) - { - return frame; - } - - public void Start() - { - Console.WriteLine($"LocalCast Aquarium runtime reading {frameSource.Description}"); - } - - public void Update(float deltaSeconds, InputState input) - { - timeSeconds += Math.Max(deltaSeconds, 0.0f); - - if (!frameSource.TryReadLatest(out var frame)) - { - latestStatus = "waiting for visual-state.msgpack"; - sceneTimelineSeconds = MathF.Max(sceneTimelineSeconds, timeSeconds); - return; - } - - if (frame.FrameId != lastFrameId) - { - if (frame.NativeGpuFusionPointBuffer.HasInput) - { - latestDirectGpuFusionField = new AquariumGpuFusionField - { - PointBuffer = frame.NativeGpuFusionPointBuffer, - AccumulationWindowSeconds = ResolveGpuHistorySeconds(), - PresentationDelaySeconds = 0.35f, - }; - } - else - { - accumulator.Observe(mapper.Map(frame)); - gpuFusionAccumulator.Observe(frame); - latestDirectGpuFusionField = AquariumGpuFusionField.Empty; - } - - lastFrameId = frame.FrameId; - latestPointCount = frame.PointCount; - latestStatus = "live"; - } - - if (frameSource.TryReadLatestClapEvents(out var clapFrame) && clapFrame.FrameId != lastClapFrameId) - { - latestCalibrationEvents = MapClapEvents(clapFrame); - lastClapFrameId = clapFrame.FrameId; - latestClapCount = clapFrame.Events.Count; - } - - sceneTimelineSeconds = MathF.Max( - sceneTimelineSeconds + Math.Max(deltaSeconds, 0.0f), - gpuFusionMapper.ToTimelineSeconds(frame.PresentTimeNs)); - } - - public void FlushState() - { - } - - public void Dispose() - { - } - - private static string ResolveVisualCachePath() - { - var environmentPath = Environment.GetEnvironmentVariable("LOCALCAST_VISUAL_CACHE"); - if (!string.IsNullOrWhiteSpace(environmentPath)) - { - return environmentPath; - } - - return Path.Combine( - "E:", - "Projects", - "LocalCastBridge", - "calibration", - "runs", - "visual-state.msgpack"); - } - - private static float ResolveGpuHistorySeconds() - { - var raw = Environment.GetEnvironmentVariable("LOCALCAST_GPU_HISTORY_SECONDS"); - return float.TryParse(raw, out var seconds) && float.IsFinite(seconds) && seconds > 0.0f - ? Math.Clamp(seconds, 1.0f, 120.0f) - : 18.0f; - } - - private static AquariumCalibrationEventFrame MapClapEvents(LocalCastClapCalibrationFrame frame) - { - return new AquariumCalibrationEventFrame - { - ClapEvents = frame.Events - .Select(item => new AquariumClapCalibrationEvent( - item.StableKey, - item.PositionMeters, - item.AcousticOracleNs, - item.VisualObservedNs, - item.TimingUncertaintyMicroseconds, - item.VisualConfidence, - item.AcousticConfidence)) - .ToArray(), - }; - } -} - -public sealed class LocalCastRuntimeFactory : IAquariumRuntimeFactory -{ - public IAquariumRuntime Create(AquariumRuntimeOptions options) - { - return new LocalCastRuntime(options); - } -} diff --git a/src/Aquarium.LocalCast/LocalCastTemporalGaussianMapper.cs b/src/Aquarium.LocalCast/LocalCastTemporalGaussianMapper.cs deleted file mode 100644 index e31016a..0000000 --- a/src/Aquarium.LocalCast/LocalCastTemporalGaussianMapper.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Temporal; - -namespace Aquarium.LocalCast; - -public sealed class LocalCastTemporalGaussianMapper -{ - private const float NanosecondsToSeconds = 1.0e-9f; - private long? originNs; - - public long OriginNs => originNs ?? 0; - - public float ToTimelineSeconds(long timestampNs) - { - originNs ??= timestampNs; - return MathF.Max(0.0f, (timestampNs - originNs.Value) * NanosecondsToSeconds); - } - - public IReadOnlyList Map(LocalCastVisualFrame frame) - { - var frameSeconds = ToTimelineSeconds(frame.SourceTimeMaxNs); - var observations = new TemporalGaussianObservation[frame.Points.Count]; - for (var index = 0; index < observations.Length; index++) - { - var point = frame.Points[index]; - var observedSeconds = point.SourceTimestampNs > 0 - ? ToTimelineSeconds(point.SourceTimestampNs) - : frameSeconds; - var radius = Math.Clamp(point.RadiusMeters, 0.008f, 0.09f); - var jitter = StochasticJitter(point.StableKey, frame.FrameId, radius * 0.28f); - var color = SanitizeColor(point.ColorOpacity, point.Confidence); - - observations[index] = new TemporalGaussianObservation( - point.StableKey, - point.Position + jitter, - new Vector3(radius * 2.15f, radius * 1.55f, radius * 1.85f), - Quaternion.Identity, - color, - point.Confidence, - observedSeconds, - Falloff: 4.6f, - ShapePower: 1.35f, - FieldId: 0); - } - - return observations; - } - - private static Vector4 SanitizeColor(Vector4 color, float confidence) - { - var alpha = Math.Clamp(color.W * MathF.Sqrt(Math.Clamp(confidence, 0.0f, 1.0f)), 0.0f, 0.98f); - return new Vector4( - ToneUp(color.X), - ToneUp(color.Y), - ToneUp(color.Z), - alpha); - } - - private static float ToneUp(float value) - { - return Math.Clamp(MathF.Pow(Math.Clamp(value, 0.0f, 1.0f), 0.72f) * 1.65f, 0.0f, 2.25f); - } - - private static Vector3 StochasticJitter(string stableKey, long frameId, float amplitude) - { - var seed = StableHash(stableKey, frameId); - var x = Unit(seed) * 2.0f - 1.0f; - var y = Unit(seed * 1664525u + 1013904223u) * 2.0f - 1.0f; - var z = Unit(seed * 22695477u + 1u) * 2.0f - 1.0f; - var vector = new Vector3(x, y, z); - if (vector.LengthSquared() <= 0.000001f) - { - return Vector3.Zero; - } - - return Vector3.Normalize(vector) * amplitude; - } - - private static uint StableHash(string stableKey, long frameId) - { - const uint fnvOffset = 2166136261u; - const uint fnvPrime = 16777619u; - var hash = fnvOffset; - foreach (var character in stableKey) - { - hash ^= character; - hash *= fnvPrime; - } - - hash ^= (uint)frameId; - hash *= fnvPrime; - hash ^= (uint)(frameId >> 32); - hash *= fnvPrime; - return hash; - } - - private static float Unit(uint seed) - { - return (seed & 0x00ffffff) / 16777215.0f; - } -} diff --git a/src/Aquarium.LocalCast/LocalCastVisualFrame.cs b/src/Aquarium.LocalCast/LocalCastVisualFrame.cs deleted file mode 100644 index 1580bae..0000000 --- a/src/Aquarium.LocalCast/LocalCastVisualFrame.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.LocalCast; - -public sealed class LocalCastVisualFrame -{ - public required string SchemaVersion { get; init; } - - public required long FrameId { get; init; } - - public required long CreatedMonotonicNs { get; init; } - - public required long SourceTimeMinNs { get; init; } - - public required long SourceTimeMaxNs { get; init; } - - public required long PresentTimeNs { get; init; } - - public required long AudioAlignmentTimeNs { get; init; } - - public required string SpoutSenderName { get; init; } - - public required int TargetWidth { get; init; } - - public required int TargetHeight { get; init; } - - public required IReadOnlyList Points { get; init; } - - public AquariumGpuFusionPointBuffer NativeGpuFusionPointBuffer { get; init; } - - public int PointCount => NativeGpuFusionPointBuffer.HasInput ? NativeGpuFusionPointBuffer.Count : Points.Count; -} - -public readonly record struct LocalCastVisualPoint( - string StableKey, - Vector3 Position, - float RadiusMeters, - Vector4 ColorOpacity, - float Confidence, - long SourceTimestampNs); - -public sealed class LocalCastClapCalibrationFrame -{ - public required string SchemaVersion { get; init; } - - public required long FrameId { get; init; } - - public required long CreatedMonotonicNs { get; init; } - - public required IReadOnlyList Events { get; init; } -} - -public readonly record struct LocalCastClapCalibrationEvent( - string StableKey, - Vector3 PositionMeters, - long AcousticOracleNs, - long VisualObservedNs, - float TimingUncertaintyMicroseconds, - float VisualConfidence, - float AcousticConfidence); diff --git a/src/Aquarium.LocalCast/LocalCastVisualFrameSource.cs b/src/Aquarium.LocalCast/LocalCastVisualFrameSource.cs deleted file mode 100644 index cdf4b21..0000000 --- a/src/Aquarium.LocalCast/LocalCastVisualFrameSource.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace Aquarium.LocalCast; - -public interface ILocalCastVisualFrameSource -{ - string Description { get; } - - bool TryReadLatest(out LocalCastVisualFrame frame); - - bool TryReadLatestClapEvents(out LocalCastClapCalibrationFrame frame); -} - -public sealed class LocalCastVisualStateFileSource : ILocalCastVisualFrameSource -{ - private readonly LocalCastVisualStateReader reader; - - public LocalCastVisualStateFileSource(string path) - { - reader = new LocalCastVisualStateReader(path); - } - - public string Description => reader.Path; - - public bool TryReadLatest(out LocalCastVisualFrame frame) - { - return reader.TryReadLatest(out frame); - } - - public bool TryReadLatestClapEvents(out LocalCastClapCalibrationFrame frame) - { - return reader.TryReadLatestClapEvents(out frame); - } -} diff --git a/src/Aquarium.LocalCast/LocalCastVisualStateReader.cs b/src/Aquarium.LocalCast/LocalCastVisualStateReader.cs deleted file mode 100644 index 2fd795e..0000000 --- a/src/Aquarium.LocalCast/LocalCastVisualStateReader.cs +++ /dev/null @@ -1,374 +0,0 @@ -using System.Buffers; -using System.Numerics; -using MessagePack; - -namespace Aquarium.LocalCast; - -public sealed class LocalCastVisualStateReader -{ - public const string LiveRenderFrameKey = "localcast.visual.render-frame.live"; - public const string RenderFrameType = "localcast.visual.render_frame"; - public const string RenderFrameSchemaId = "gamecult.localcast.visual.render_frame.v1"; - public const string LiveClapEventsKey = "localcast.calibration.clap-events.live"; - public const string ClapEventsType = "localcast.calibration.clap_events"; - public const string ClapEventsSchemaId = "gamecult.localcast.calibration.clap_events.v1"; - - private readonly string path; - - public LocalCastVisualStateReader(string path) - { - this.path = System.IO.Path.GetFullPath(path); - } - - public string Path => path; - - public bool TryReadLatest(out LocalCastVisualFrame frame) - { - frame = null!; - - if (!File.Exists(path)) - { - return false; - } - - byte[] bytes; - try - { - using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - bytes = new byte[stream.Length]; - var read = stream.Read(bytes, 0, bytes.Length); - if (read != bytes.Length) - { - Array.Resize(ref bytes, read); - } - } - catch (IOException) - { - return false; - } - catch (UnauthorizedAccessException) - { - return false; - } - - try - { - return TryParseStore(bytes, out frame); - } - catch (MessagePackSerializationException) - { - return false; - } - catch (InvalidOperationException) - { - return false; - } - catch (EndOfStreamException) - { - return false; - } - } - - public bool TryReadLatestClapEvents(out LocalCastClapCalibrationFrame frame) - { - frame = null!; - - if (!File.Exists(path)) - { - return false; - } - - byte[] bytes; - try - { - using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - bytes = new byte[stream.Length]; - var read = stream.Read(bytes, 0, bytes.Length); - if (read != bytes.Length) - { - Array.Resize(ref bytes, read); - } - } - catch (IOException) - { - return false; - } - catch (UnauthorizedAccessException) - { - return false; - } - - try - { - return TryParseClapEventsStore(bytes, out frame); - } - catch (MessagePackSerializationException) - { - return false; - } - catch (InvalidOperationException) - { - return false; - } - catch (EndOfStreamException) - { - return false; - } - } - - public static bool TryParseStore(ReadOnlyMemory payload, out LocalCastVisualFrame frame) - { - frame = null!; - var reader = new MessagePackReader(payload); - var recordCount = reader.ReadArrayHeader(); - - for (var recordIndex = 0; recordIndex < recordCount; recordIndex++) - { - var mapCount = reader.ReadMapHeader(); - string? key = null; - string? type = null; - byte[]? documentPayload = null; - - for (var mapIndex = 0; mapIndex < mapCount; mapIndex++) - { - var field = reader.ReadString(); - switch (field) - { - case "key": - key = reader.ReadString(); - break; - case "type": - type = reader.ReadString(); - break; - case "payload": - var bytes = reader.ReadBytes(); - documentPayload = bytes.HasValue ? bytes.Value.ToArray() : null; - break; - default: - reader.Skip(); - break; - } - } - - if (string.Equals(key, LiveRenderFrameKey, StringComparison.Ordinal) - && string.Equals(type, RenderFrameType, StringComparison.Ordinal) - && documentPayload is not null) - { - frame = ParseRenderFrame(documentPayload); - return string.Equals(frame.SchemaVersion, RenderFrameSchemaId, StringComparison.Ordinal); - } - } - - return false; - } - - public static bool TryParseClapEventsStore(ReadOnlyMemory payload, out LocalCastClapCalibrationFrame frame) - { - frame = null!; - var reader = new MessagePackReader(payload); - var recordCount = reader.ReadArrayHeader(); - - for (var recordIndex = 0; recordIndex < recordCount; recordIndex++) - { - var mapCount = reader.ReadMapHeader(); - string? key = null; - string? type = null; - byte[]? documentPayload = null; - - for (var mapIndex = 0; mapIndex < mapCount; mapIndex++) - { - var field = reader.ReadString(); - switch (field) - { - case "key": - key = reader.ReadString(); - break; - case "type": - type = reader.ReadString(); - break; - case "payload": - var bytes = reader.ReadBytes(); - documentPayload = bytes.HasValue ? bytes.Value.ToArray() : null; - break; - default: - reader.Skip(); - break; - } - } - - if (string.Equals(key, LiveClapEventsKey, StringComparison.Ordinal) - && string.Equals(type, ClapEventsType, StringComparison.Ordinal) - && documentPayload is not null) - { - frame = ParseClapEvents(documentPayload); - return string.Equals(frame.SchemaVersion, ClapEventsSchemaId, StringComparison.Ordinal); - } - } - - return false; - } - - public static LocalCastVisualFrame ParseRenderFrame(ReadOnlyMemory payload) - { - var reader = new MessagePackReader(payload); - var fieldCount = reader.ReadArrayHeader(); - if (fieldCount < 11) - { - throw new InvalidOperationException($"Render frame payload has {fieldCount} fields; expected at least 11."); - } - - var frame = new LocalCastVisualFrame - { - SchemaVersion = reader.ReadString() ?? string.Empty, - FrameId = reader.ReadInt64(), - CreatedMonotonicNs = reader.ReadInt64(), - SourceTimeMinNs = reader.ReadInt64(), - SourceTimeMaxNs = reader.ReadInt64(), - PresentTimeNs = reader.ReadInt64(), - AudioAlignmentTimeNs = reader.ReadInt64(), - SpoutSenderName = reader.ReadString() ?? string.Empty, - TargetWidth = reader.ReadInt32(), - TargetHeight = reader.ReadInt32(), - Points = ReadPoints(ref reader), - }; - - for (var fieldIndex = 11; fieldIndex < fieldCount; fieldIndex++) - { - reader.Skip(); - } - - return frame; - } - - public static LocalCastClapCalibrationFrame ParseClapEvents(ReadOnlyMemory payload) - { - var reader = new MessagePackReader(payload); - var fieldCount = reader.ReadArrayHeader(); - if (fieldCount < 4) - { - throw new InvalidOperationException($"Clap events payload has {fieldCount} fields; expected at least 4."); - } - - var frame = new LocalCastClapCalibrationFrame - { - SchemaVersion = reader.ReadString() ?? string.Empty, - FrameId = reader.ReadInt64(), - CreatedMonotonicNs = reader.ReadInt64(), - Events = ReadClapEvents(ref reader), - }; - - for (var fieldIndex = 4; fieldIndex < fieldCount; fieldIndex++) - { - reader.Skip(); - } - - return frame; - } - - private static IReadOnlyList ReadPoints(ref MessagePackReader reader) - { - var count = reader.ReadArrayHeader(); - var points = new LocalCastVisualPoint[count]; - for (var index = 0; index < count; index++) - { - var fieldCount = reader.ReadArrayHeader(); - if (fieldCount < 6) - { - throw new InvalidOperationException($"Render point payload has {fieldCount} fields; expected at least 6."); - } - - var stableKey = reader.ReadString() ?? string.Empty; - var position = ReadVector3(ref reader); - var radius = reader.ReadSingle(); - var color = ReadVector4(ref reader); - var confidence = reader.ReadSingle(); - var timestampNs = reader.ReadInt64(); - for (var fieldIndex = 6; fieldIndex < fieldCount; fieldIndex++) - { - reader.Skip(); - } - - points[index] = new LocalCastVisualPoint( - stableKey, - position, - MathF.Max(0.001f, radius), - color, - Math.Clamp(confidence, 0.0f, 1.0f), - timestampNs); - } - - return points; - } - - private static IReadOnlyList ReadClapEvents(ref MessagePackReader reader) - { - var count = reader.ReadArrayHeader(); - var events = new LocalCastClapCalibrationEvent[count]; - for (var index = 0; index < count; index++) - { - var fieldCount = reader.ReadArrayHeader(); - if (fieldCount < 8) - { - throw new InvalidOperationException($"Clap event payload has {fieldCount} fields; expected at least 8."); - } - - var stableKey = reader.ReadString() ?? string.Empty; - var position = ReadVector3(ref reader); - var acousticOracleNs = reader.ReadInt64(); - var visualObservedNs = reader.ReadInt64(); - var timingUncertaintyUs = reader.ReadSingle(); - var visualConfidence = reader.ReadSingle(); - var acousticConfidence = reader.ReadSingle(); - reader.Skip(); - for (var fieldIndex = 8; fieldIndex < fieldCount; fieldIndex++) - { - reader.Skip(); - } - - events[index] = new LocalCastClapCalibrationEvent( - stableKey, - position, - acousticOracleNs, - visualObservedNs, - timingUncertaintyUs, - Math.Clamp(visualConfidence, 0.0f, 1.0f), - Math.Clamp(acousticConfidence, 0.0f, 1.0f)); - } - - return events; - } - - private static Vector3 ReadVector3(ref MessagePackReader reader) - { - var count = reader.ReadArrayHeader(); - if (count < 3) - { - throw new InvalidOperationException($"Vector3 payload has {count} fields; expected at least 3."); - } - - var value = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); - for (var index = 3; index < count; index++) - { - reader.Skip(); - } - - return value; - } - - private static Vector4 ReadVector4(ref MessagePackReader reader) - { - var count = reader.ReadArrayHeader(); - if (count < 4) - { - throw new InvalidOperationException($"Vector4 payload has {count} fields; expected at least 4."); - } - - var value = new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); - for (var index = 4; index < count; index++) - { - reader.Skip(); - } - - return value; - } -} diff --git a/src/Aquarium.Sample.Minimal/Aquarium.Sample.Minimal.csproj b/src/Aquarium.Sample.Minimal/Aquarium.Sample.Minimal.csproj deleted file mode 100644 index 25595db..0000000 --- a/src/Aquarium.Sample.Minimal/Aquarium.Sample.Minimal.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - net10.0 - Aquarium.Sample.Minimal - Aquarium.Sample.Minimal - enable - enable - true - - - - - - - diff --git a/src/Aquarium.Sample.Minimal/MinimalRuntime.cs b/src/Aquarium.Sample.Minimal/MinimalRuntime.cs deleted file mode 100644 index 703a581..0000000 --- a/src/Aquarium.Sample.Minimal/MinimalRuntime.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Numerics; -using Aquarium.Engine; -using Aquarium.Engine.Audio; -using Aquarium.Engine.Input; -using Aquarium.Engine.Render; -using Aquarium.Engine.Ui; - -namespace Aquarium.Sample.Minimal; - -public sealed class MinimalRuntime : IAquariumRuntime -{ - private float timeSeconds; - - public AquariumRuntimeOptions Options { get; private set; } - - public GraphicsSettings GraphicsSettings { get; set; } = GraphicsSettings.Default; - - public AquariumRenderPlan RenderPlan { get; } = CreateRenderPlan(); - - public AquariumUiDocument Ui { get; } = AquariumUiDocument.Empty; - - public AquariumAudioDocument Audio { get; } = new(); - - public AquariumSynthDocument Synth { get; } = AquariumSynthDocument.Empty; - - public AquariumFrame Frame => new( - new ViewFrame(Vector2.Zero, 24.0f), - new Vector3(0.0f, -10.0f, 7.0f), - timeSeconds, - Vector2.Zero, - AquariumSceneState.Empty); - - public AquariumFrame ComposeFrame(AquariumFrame frame, AquariumFrameInput input) - { - return frame; - } - - public void Start() - { - Console.WriteLine("Minimal Aquarium sample booted."); - } - - public void Update(float deltaSeconds, InputState input) - { - timeSeconds += Math.Max(deltaSeconds, 0.0f); - } - - public void FlushState() - { - } - - public void Dispose() - { - } - - internal void SetOptions(AquariumRuntimeOptions options) - { - Options = options; - } - - private static AquariumRenderPlan CreateRenderPlan() - { - var app = new AquariumApp(); - var scene = app.RenderTargets.Hdr("scene"); - app.Cameras.Perspective("main"); - app.Graph.Pass("scene").Fullscreen(); - app.Features.Bloom(scene.Color); - app.Features.Presentation(scene.Color); - app.Features.DirectWriteOverlay(); - app.Debug.View("Scene", scene.Color); - return app.Plan; - } -} - -public sealed class MinimalRuntimeFactory : IAquariumRuntimeFactory -{ - public IAquariumRuntime Create(AquariumRuntimeOptions options) - { - var runtime = new MinimalRuntime(); - runtime.SetOptions(options); - return runtime; - } -} diff --git a/src/Aquarium.Zyphos/Aquarium.Zyphos.csproj b/src/Aquarium.Zyphos/Aquarium.Zyphos.csproj deleted file mode 100644 index 0f12427..0000000 --- a/src/Aquarium.Zyphos/Aquarium.Zyphos.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - net10.0 - Aquarium.Zyphos - Aquarium.Zyphos - enable - enable - true - - - - - - - - - - - - - - diff --git a/src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl b/src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl deleted file mode 100644 index d75b6bb..0000000 --- a/src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl +++ /dev/null @@ -1,313 +0,0 @@ -static const int SDF_INDEX = 0; -static const int ZYPHOS_GEOMETRY_BRUSH_LIMIT = 4; - -#include "D3D12SdfCommon.hlsli" -#include "D3D12SdfMath.hlsli" - -float3 zyRotateZ(float3 p, float angle) -{ - float s = sin(angle); - float c = cos(angle); - return float3(c * p.x - s * p.y, s * p.x + c * p.y, p.z); -} - -float3 zyPlanetDir(float3 local, SdfObject sdfObject) -{ - return normalize(zyRotateZ(local, -sdfObject.state.y)); -} - -float3 zyPrimaryStarDirectionLocal(SdfObject sdfObject) -{ - return normalize(float3(cos(sdfObject.state.w), sin(sdfObject.state.w), 0.18)); -} - -float zyUmbrosEclipse(float3 starDirectionLocal) -{ - const float umbrosAngularRadius = 0.1127; - float alignment = dot(normalize(starDirectionLocal), float3(1.0, 0.0, 0.0)); - return smoothstep(cos(umbrosAngularRadius * 1.45), cos(umbrosAngularRadius * 0.45), alignment); -} - -float zySphericalField(float3 dir) -{ - float latitude = asin(saturate(abs(dir.z)) * 2.0 - 1.0); - float longitude = atan2(dir.y, dir.x); - float plates = - sin(longitude * 2.0 + dir.z * 4.5) * 0.28 + - sin(longitude * 3.0 - dir.z * 7.0 + 1.7) * 0.22 + - sin((dir.x + dir.y * 0.7 + dir.z * 0.4) * 8.0) * 0.16 + - sin((dir.x * 1.3 - dir.y + dir.z * 1.9) * 13.0) * 0.08; - float equatorialWarmth = cos(latitude) * 0.18; - return 0.50 + plates + equatorialWarmth; -} - -float zyHash21(float2 p) -{ - p = frac(p * float2(123.34, 456.21)); - p += dot(p, p + 45.32); - return frac(p.x * p.y); -} - -float zyCompactBrush(float2 delta, float2 radii, float rotation, float falloff, float shapePower) -{ - float c = cos(rotation); - float s = sin(rotation); - float2 local = float2(delta.x * c + delta.y * s, -delta.x * s + delta.y * c); - float2 normalized = local / max(radii, float2(0.001, 0.001)); - float r2 = dot(normalized, normalized); - if (r2 >= 1.0) - { - return 0.0; - } - - float edgeValue = exp(-falloff); - float gaussianValue = exp(-falloff * r2); - float compactValue = (gaussianValue - edgeValue) / max(1.0 - edgeValue, 0.000001); - return pow(saturate(compactValue), shapePower); -} - -float2 zyCubeFaceUv(float3 dir, out float face) -{ - float3 a = abs(dir); - if (a.x >= a.y && a.x >= a.z) - { - if (dir.x >= 0.0) - { - face = 0.0; - return float2(-dir.z, dir.y) / max(a.x, 0.0001); - } - - face = 1.0; - return float2(dir.z, dir.y) / max(a.x, 0.0001); - } - - if (a.y >= a.z) - { - if (dir.y >= 0.0) - { - face = 2.0; - return float2(dir.x, -dir.z) / max(a.y, 0.0001); - } - - face = 3.0; - return float2(dir.x, dir.z) / max(a.y, 0.0001); - } - - if (dir.z >= 0.0) - { - face = 4.0; - return dir.xy / max(a.z, 0.0001); - } - - face = 5.0; - return float2(-dir.x, dir.y) / max(a.z, 0.0001); -} - -float2 zyTileBrushPlane(float2 faceUv, float level, float tileX, float tileY, out float inTile) -{ - float axisTiles = exp2(level); - float2 local01 = (faceUv * 0.5 + 0.5) * axisTiles - float2(tileX, tileY); - float2 inside = step(float2(0.0, 0.0), local01) * step(local01, float2(1.0, 1.0)); - inTile = inside.x * inside.y; - return (local01 * 2.0 - 1.0) * 30.0; -} - -float zyAuthoredBrushTerrainLimited(float3 dir, int brushLimit, out float materialMask) -{ - float face; - float2 faceUv = zyCubeFaceUv(dir, face); - float height = 0.0; - materialMask = 0.0; - - [loop] - for (int index = 0; index < brushLimit; index++) - { - float4 centerRadius = brushCenterRadius[index]; - float4 shape = brushShape[index]; - float4 domain = brushDomain[index]; - if (centerRadius.z <= 0.0 || abs(domain.x - face) > 0.25) - { - continue; - } - - float inTile; - float2 plane = zyTileBrushPlane(faceUv, domain.y, domain.z, domain.w, inTile); - if (inTile <= 0.0) - { - continue; - } - - float2 radii = float2(centerRadius.z, centerRadius.w > 0.0 ? centerRadius.w : centerRadius.z); - float weight = zyCompactBrush(plane - centerRadius.xy, radii, shape.z, max(shape.w, 0.001), max(shape.x, 0.001)); - height += shape.y * weight; - materialMask = max(materialMask, abs(shape.y) * weight); - } - - return height; -} - -float zyAuthoredBrushTerrain(float3 dir, out float materialMask) -{ - return zyAuthoredBrushTerrainLimited(dir, 64, materialMask); -} - -float3 zyFaceDebugColor(float face) -{ - if (face < 0.5) return float3(0.95, 0.18, 0.14); - if (face < 1.5) return float3(0.12, 0.56, 1.00); - if (face < 2.5) return float3(0.20, 0.88, 0.34); - if (face < 3.5) return float3(1.00, 0.78, 0.18); - if (face < 4.5) return float3(0.78, 0.36, 1.00); - return float3(0.10, 0.90, 0.86); -} - -float3 zyFractalDomainDebug(float3 dir) -{ - float face; - float2 faceUv = zyCubeFaceUv(dir, face); - float materialMask; - float authoredHeight = zyAuthoredBrushTerrain(dir, materialMask); - float2 grid = abs(frac((faceUv * 0.5 + 0.5) * 8.0) - 0.5); - float gridLine = 1.0 - smoothstep(0.015, 0.055, min(grid.x, grid.y)); - float3 faceColor = zyFaceDebugColor(face); - float signedHeight = authoredHeight >= 0.0 ? 1.0 : 0.0; - float3 brushColor = lerp(float3(0.12, 0.28, 1.0), float3(1.0, 0.42, 0.12), signedHeight) * saturate(materialMask * 5.0); - return saturate(faceColor * 0.28 + gridLine.xxx * 0.34 + brushColor); -} - -float zyTileRelief(float2 uv, float level, float amplitude, float ridgeBias) -{ - float scale = exp2(level); - float2 cell = floor(uv * scale); - float2 local = frac(uv * scale) - 0.5; - float seed = zyHash21(cell + level * 17.0); - float angle = seed * 6.2831853; - float2 axis = float2(cos(angle), sin(angle)); - float ridge = 1.0 - smoothstep(0.035, 0.18, abs(dot(local, axis) + (seed - 0.5) * 0.16)); - float pit = 1.0 - smoothstep(0.06, 0.32, length(local - axis * 0.18)); - return (ridge * ridgeBias - pit * (1.0 - ridgeBias)) * amplitude; -} - -float zyQuadtreeSdfRelief(float3 dir) -{ - float2 equatorial = dir.xy * 0.5 + 0.5; - float2 polar = float2(atan2(dir.y, dir.x) * 0.15915494 + 0.5, abs(dir.z)); - float polarBlend = smoothstep(0.58, 0.92, abs(dir.z)); - float2 uv = lerp(equatorial, polar, polarBlend); - float relief = 0.0; - relief += zyTileRelief(uv + 0.07, 2.0, 0.030, 0.68); - relief += zyTileRelief(uv * 1.37 + 0.31, 3.0, 0.019, 0.55); - relief += zyTileRelief(uv * 2.13 - 0.19, 4.0, 0.010, 0.45); - return relief; -} - -float zyDomainMask(float3 dir, float3 center, float width) -{ - return smoothstep(cos(width), cos(width * 0.35), dot(dir, normalize(center))); -} - -float zyLeafCluster(float3 dir) -{ - float forest = zyDomainMask(dir, float3(0.32, 0.68, 0.16), 0.42); - float leafCells = - sin(dir.x * 91.0 + dir.y * 37.0) * - sin(dir.y * 113.0 - dir.z * 53.0) * - sin((dir.x + dir.z) * 157.0); - float leaf = smoothstep(0.36, 0.92, leafCells * 0.5 + 0.5); - return forest * leaf; -} - -float zyPebbleCluster(float3 dir) -{ - float coast = zyDomainMask(dir, float3(0.57, -0.28, 0.10), 0.24); - float grains = sin(dir.x * 173.0 - dir.y * 71.0) * sin(dir.z * 127.0 + dir.y * 59.0); - return coast * smoothstep(0.48, 0.94, grains * 0.5 + 0.5); -} - -float zyTerrainOffset(float3 dir, SdfObject sdfObject) -{ - float field = zySphericalField(dir); - float seaLevel = sdfObject.state.z; - float land = smoothstep(seaLevel - 0.04, seaLevel + 0.08, field); - float mountain = pow(saturate(field - seaLevel), 1.65); - float polarCap = pow(abs(dir.z), 8.0) * 0.035; - float authoredMaterial; - float authoredGeometry = zyAuthoredBrushTerrainLimited(dir, ZYPHOS_GEOMETRY_BRUSH_LIMIT, authoredMaterial); - float tileRelief = zyQuadtreeSdfRelief(dir) * land + zyLeafCluster(dir) * 0.018 + zyPebbleCluster(dir) * 0.010; - return (field - seaLevel) * 0.10 + mountain * 0.13 + polarCap * land + tileRelief + authoredGeometry * 0.52; -} - -float sdfDistance(float3 p, int sdfIndex) -{ - SdfObject sdfObject = sdfObjects[sdfIndex]; - float planetRadius = max(sdfObject.state.x, 0.001); - float3 local = p - sdfObject.centerRadius.xyz; - float3 dir = zyPlanetDir(local, sdfObject); - return length(local) - (planetRadius + zyTerrainOffset(dir, sdfObject)); -} - -SdfSurface sdfSurface(float3 p, int sdfIndex) -{ - SdfObject sdfObject = sdfObjects[sdfIndex]; - float3 local = p - sdfObject.centerRadius.xyz; - float3 dir = zyPlanetDir(local, sdfObject); - float field = zySphericalField(dir); - float seaLevel = sdfObject.state.z; - float land = smoothstep(seaLevel - 0.03, seaLevel + 0.06, field); - float mountain = smoothstep(seaLevel + 0.12, seaLevel + 0.28, field); - float tileRelief = zyQuadtreeSdfRelief(dir); - float authoredMaterial; - float authoredHeight = zyAuthoredBrushTerrain(dir, authoredMaterial); - float leafCluster = zyLeafCluster(dir); - float pebbleCluster = zyPebbleCluster(dir); - float polar = smoothstep(0.72, 0.92, abs(dir.z)); - float cloud = smoothstep(0.73, 0.91, sin(dir.x * 18.0 + dir.y * 13.0 + dir.z * 9.0 + timeSeconds * 0.19) * 0.5 + 0.5); - - float3 ocean = lerp(float3(0.004, 0.070, 0.130), float3(0.010, 0.220, 0.330), saturate(field)); - float3 lowland = float3(0.070, 0.300, 0.185); - float3 highland = float3(0.540, 0.405, 0.220); - float3 snow = float3(0.800, 0.865, 0.830); - float3 landColor = lerp(lowland, highland, mountain); - landColor = lerp(landColor, snow, saturate(polar + mountain * 0.38)); - landColor = lerp(landColor, float3(0.62, 0.54, 0.36), saturate(tileRelief * 14.0)); - landColor = lerp(landColor, float3(0.78, 0.56, 0.30), saturate(authoredMaterial * 2.6 + authoredHeight * 5.0)); - landColor = lerp(landColor, float3(0.025, 0.24, 0.08), leafCluster * 0.82); - landColor = lerp(landColor, float3(0.42, 0.39, 0.34), pebbleCluster * 0.65); - - SdfSurface surface; - surface.baseColor = lerp(ocean, landColor, land); - surface.baseColor = lerp(surface.baseColor, float3(0.78, 0.84, 0.80), cloud * 0.16); - surface.metallic = 0.0; - surface.roughness = lerp(0.34, 0.84, land); - surface.emission = 0.0; - surface.temporalDetail = saturate(authoredMaterial * 3.0); - surface.reservoirConfidence = saturate(0.42 + authoredMaterial * 2.2 + leafCluster * 0.25 + pebbleCluster * 0.20); - return surface; -} - -float3 shadeSdf(float2 uv, float travel, float3 p, float3 normal, int sdfIndex, SdfSurface surface) -{ - SdfObject sdfObject = sdfObjects[sdfIndex]; - float3 dir = zyPlanetDir(p - sdfObject.centerRadius.xyz, sdfObject); - if (renderDebugMode >= 10.5 && renderDebugMode < 11.5) - { - return zyFractalDomainDebug(dir); - } - - float3 viewDirection = normalize(cameraPosition - p); - float3 starDirectionLocal = zyPrimaryStarDirectionLocal(sdfObject); - float eclipse = zyUmbrosEclipse(starDirectionLocal); - float daylight = saturate(dot(dir, starDirectionLocal) * 0.74 + 0.24) * (1.0 - eclipse * 0.86); - float night = saturate(-dot(dir, starDirectionLocal) * 1.7 - 0.20 + eclipse * 0.55); - float citySeed = sin(dir.x * 43.0 + sin(dir.y * 19.0) * 4.0 + dir.z * 31.0); - float cityWeb = smoothstep(0.82, 0.96, citySeed * 0.5 + 0.5); - float coast = 1.0 - smoothstep(0.020, 0.070, abs(zySphericalField(dir) - sdfObject.state.z)); - float fresnel = pow(1.0 - saturate(dot(normal, viewDirection)), 3.2); - float3 city = float3(1.0, 0.54, 0.14) * cityWeb * coast * night * 1.25; - float3 eclipseTint = float3(0.15, 0.19, 0.26) * eclipse * saturate(dot(dir, starDirectionLocal) * 0.5 + 0.5); - float3 atmosphere = float3(0.07, 0.38, 0.78) * (fresnel * 1.35 + pow(fresnel, 6.0) * 2.6); - - return shadeSdfPbr(p, normal, surface) * daylight + city + atmosphere + eclipseTint; -} - -#include "D3D12SdfProxy.hlsli" diff --git a/src/Aquarium.Zyphos/Shaders/D3D12ZyphosStar.hlsl b/src/Aquarium.Zyphos/Shaders/D3D12ZyphosStar.hlsl deleted file mode 100644 index 4a8830d..0000000 --- a/src/Aquarium.Zyphos/Shaders/D3D12ZyphosStar.hlsl +++ /dev/null @@ -1,55 +0,0 @@ -static const int SDF_INDEX = 2; - -#define SDF_TRACE_STEPS 160 -#define SDF_TRACE_STEP_SCALE 0.55 -#define SDF_TRACE_MAX_STEP_RADIUS_SCALE 0.08 - -#include "D3D12SdfCommon.hlsli" -#include "D3D12SdfMath.hlsli" - -float starGranulation(float3 dir, float phase) -{ - float bands = - sin(dir.x * 17.0 + phase * 1.7) * 0.18 + - sin(dir.y * 23.0 - phase * 1.1) * 0.14 + - sin((dir.x + dir.y + dir.z) * 41.0 + phase * 0.6) * 0.08; - return bands; -} - -float sdfDistance(float3 p, int sdfIndex) -{ - SdfObject star = sdfObjects[sdfIndex]; - float3 local = p - star.centerRadius.xyz; - float radius = max(star.state.x, 0.001); - float3 dir = normalize(local); - float coronaLift = starGranulation(dir, timeSeconds) * 0.05; - return length(local) - radius * (1.0 + coronaLift); -} - -SdfSurface sdfSurface(float3 p, int sdfIndex) -{ - SdfObject star = sdfObjects[sdfIndex]; - float3 dir = normalize(p - star.centerRadius.xyz); - float granulation = starGranulation(dir, timeSeconds); - float hot = saturate(0.58 + granulation); - - SdfSurface surface; - surface.baseColor = lerp(float3(1.0, 0.34, 0.08), float3(1.0, 0.88, 0.42), hot); - surface.metallic = 0.0; - surface.roughness = 0.72; - surface.emission = surface.baseColor * lerp(3.8, 7.5, hot); - surface.temporalDetail = 0.0; - surface.reservoirConfidence = 1.0; - return surface; -} - -float3 shadeSdf(float2 uv, float travel, float3 p, float3 normal, int sdfIndex, SdfSurface surface) -{ - float3 viewDirection = normalize(cameraPosition - p); - float rim = pow(1.0 - saturate(dot(normal, viewDirection)), 2.4); - float pulse = sin(timeSeconds * 1.3 + dot(normal, float3(11.0, 7.0, 5.0))) * 0.5 + 0.5; - float3 corona = float3(1.0, 0.42, 0.12) * (rim * 5.5 + pow(rim, 8.0) * 12.0) * lerp(0.82, 1.18, pulse); - return surface.emission + corona; -} - -#include "D3D12SdfProxy.hlsli" diff --git a/src/Aquarium.Zyphos/Shaders/D3D12ZyphosUmbros.hlsl b/src/Aquarium.Zyphos/Shaders/D3D12ZyphosUmbros.hlsl deleted file mode 100644 index 5d83118..0000000 --- a/src/Aquarium.Zyphos/Shaders/D3D12ZyphosUmbros.hlsl +++ /dev/null @@ -1,100 +0,0 @@ -static const int SDF_INDEX = 1; - -#include "D3D12SdfCommon.hlsli" -#include "D3D12SdfMath.hlsli" - -float umHash21(float2 p) -{ - p = frac(p * float2(97.17, 271.43)); - p += dot(p, p + 31.91); - return frac(p.x * p.y); -} - -float umTileRelief(float2 uv, float level, float amplitude, float crackBias) -{ - float scale = exp2(level); - float2 cell = floor(uv * scale); - float2 local = frac(uv * scale) - 0.5; - float seed = umHash21(cell - level * 11.0); - float angle = seed * 6.2831853; - float2 axis = float2(cos(angle), sin(angle)); - float crack = 1.0 - smoothstep(0.018, 0.092, abs(dot(local, axis) + (seed - 0.5) * 0.22)); - float shelf = 1.0 - smoothstep(0.12, 0.45, max(abs(local.x * axis.x), abs(local.y * axis.y))); - return shelf * amplitude * (1.0 - crackBias) - crack * amplitude * crackBias; -} - -float umQuadtreeSdfRelief(float3 dir) -{ - float2 front = dir.yz * 0.5 + 0.5; - float2 wrap = float2(atan2(dir.z, dir.y) * 0.15915494 + 0.5, dir.x * 0.5 + 0.5); - float blend = smoothstep(0.52, 0.86, abs(dir.x)); - float2 uv = lerp(front, wrap, blend); - float relief = 0.0; - relief += umTileRelief(uv + 0.23, 2.0, 0.022, 0.72); - relief += umTileRelief(uv * 1.71 - 0.11, 3.0, 0.014, 0.62); - relief += umTileRelief(uv * 2.60 + 0.41, 4.0, 0.008, 0.54); - return relief; -} - -float umPebbleCluster(float3 dir) -{ - float province = smoothstep(cos(0.34), cos(0.12), dot(dir, normalize(float3(0.88, -0.24, 0.20)))); - float grain = sin(dir.x * 149.0 + dir.z * 47.0) * sin(dir.y * 181.0 - dir.z * 63.0); - return province * smoothstep(0.50, 0.96, grain * 0.5 + 0.5); -} - -float zyUmbrosRelief(float3 dir) -{ - float ridges = - sin(dir.x * 15.0 + dir.y * 4.0) * 0.018 + - sin(dir.y * 21.0 - dir.z * 7.0) * 0.012 + - sin((dir.x + dir.y + dir.z) * 34.0) * 0.006; - float basinA = 1.0 - smoothstep(0.055, 0.115, abs(length(dir.xy - float2(0.22, -0.18)) - 0.32)); - float basinB = 1.0 - smoothstep(0.040, 0.090, abs(length(dir.yz - float2(0.30, 0.24)) - 0.22)); - return ridges - (basinA * 0.035 + basinB * 0.026) + umQuadtreeSdfRelief(dir) - umPebbleCluster(dir) * 0.010; -} - -float3 zyPrimaryStarDirection(float phase) -{ - return normalize(float3(cos(phase), sin(phase), 0.18)); -} - -float sdfDistance(float3 p, int sdfIndex) -{ - SdfObject sdfObject = sdfObjects[sdfIndex]; - float radius = max(sdfObject.state.x, 0.001); - float3 local = p - sdfObject.centerRadius.xyz; - float3 dir = normalize(local); - return length(local) - (radius + zyUmbrosRelief(dir)); -} - -SdfSurface sdfSurface(float3 p, int sdfIndex) -{ - SdfObject sdfObject = sdfObjects[sdfIndex]; - float3 dir = normalize(p - sdfObject.centerRadius.xyz); - float relief = zyUmbrosRelief(dir); - float dust = sin(dir.x * 31.0 + dir.y * 17.0 - dir.z * 11.0) * 0.5 + 0.5; - float cracks = saturate(-umQuadtreeSdfRelief(dir) * 20.0); - float pebbles = umPebbleCluster(dir); - SdfSurface surface; - surface.baseColor = lerp(float3(0.18, 0.19, 0.20), float3(0.44, 0.42, 0.38), dust); - surface.baseColor = lerp(surface.baseColor, float3(0.10, 0.11, 0.12), saturate(-relief * 18.0)); - surface.baseColor = lerp(surface.baseColor, float3(0.07, 0.075, 0.085), cracks); - surface.baseColor = lerp(surface.baseColor, float3(0.50, 0.49, 0.45), pebbles * 0.45); - surface.metallic = 0.0; - surface.roughness = 0.92; - surface.emission = 0.0; - surface.temporalDetail = 0.0; - surface.reservoirConfidence = 1.0; - return surface; -} - -float3 shadeSdf(float2 uv, float travel, float3 p, float3 normal, int sdfIndex, SdfSurface surface) -{ - SdfObject sdfObject = sdfObjects[sdfIndex]; - float3 starDirection = zyPrimaryStarDirection(sdfObject.state.y); - float daylight = saturate(dot(normal, starDirection) * 0.74 + 0.16); - return shadeSdfPbr(p, normal, surface) * daylight; -} - -#include "D3D12SdfProxy.hlsli" diff --git a/src/Aquarium.Zyphos/Worlds/zyphos-first-fractal-terrain.aquageo b/src/Aquarium.Zyphos/Worlds/zyphos-first-fractal-terrain.aquageo deleted file mode 100644 index 302055d..0000000 --- a/src/Aquarium.Zyphos/Worlds/zyphos-first-fractal-terrain.aquageo +++ /dev/null @@ -1,37 +0,0 @@ -# Zyphos first Aquarium fractal terrain DSL proof. -domain Solar zyphos/parent-star - 0.25 0.006 0.077 16 -domain Orbital zyphos/zyphos-umbros-orbit zyphos/parent-star 8 1.0 12.9 52 -domain Planetary zyphos/planet zyphos/zyphos-umbros-orbit 1.0 0.56 0 0 -domain Planetary zyphos/umbros zyphos/zyphos-umbros-orbit 0.9 8 12.9 0 -domain LatLong zyphos/planet-latlong zyphos/planet -90 90 -180 180 -domain LatLong zyphos/umbros-latlong zyphos/umbros -90 90 -180 180 -domain Surface2D zyphos/continent-archipelago zyphos/planet-latlong -12 44 88 0.62 0 0 0 0 -domain Surface2D zyphos/equatorial-forest zyphos/continent-archipelago -4 18 12 0.34 0 0 0 0 -domain Object3D zyphos/canopy-tree zyphos/equatorial-forest 0.012 18 42 7 0 0 0 0 -domain Object3D zyphos/canopy-leaf zyphos/canopy-tree 0.00018 0.62 0.12 4 0 0 0 0 -domain Surface2D zyphos/shingle-coast zyphos/continent-archipelago 8 -21 4 0.18 0 0 0 0 -domain Object3D zyphos/pebble-field zyphos/shingle-coast 0.0008 0.05 0.22 9 0 0 0 0 -domain Surface2D umbros/crater-province zyphos/umbros-latlong 18 -9 0.42 0.2 0 0 0 0 -domain Surface2D umbros/boulder-field umbros/crater-province 22 -11 0.08 0.6 0 0 0 0 -domain Object3D umbros/pebble-field umbros/boulder-field 0.001 0.03 0.16 11 0 0 0 0 -tile PositiveZ 0 0 0 zyphos/first-fractal-terrain zyphos/continent-archipelago -height basin 0 0 30 30 0 3 1 -0.12 7 basin -ifs crater 3 2 -5 3 6 2.5 0.48 2.6 0.42 4 0.85 -0.10 19 crater -ifs ridge 2 3 6 -4 5 1.35 0.45 3.2 -0.27 3.6 0.72 0.075 31 ridge -tile PositiveX 1 1 0 zyphos/terminator-shelves zyphos/shingle-coast -height shelf 17 -8 9 3.5 0.35 3.4 1.1 0.045 43 shelf -ifs vein 2 2 14 -11 4.2 1.1 0.42 3.8 1.12 4.8 0.78 0.035 47 vein -tile NegativeX 2 2 1 zyphos/greenleaf-canopy zyphos/canopy-leaf -ifs leaf 3 3 9 9 1.8 0.72 0.42 2.8 0.61 6.0 0.58 0.018 101 leaf -flame veinlet 2 2 10.4 8.2 0.92 0.28 0.42 0.78 3.2 6.5 0.62 0.012 103 flame-leaf -tile NegativeZ 2 1 2 zyphos/pebble-field zyphos/pebble-field -ifs pebble 3 2 -11 13 1.2 0.9 0.48 3.4 -0.77 8.0 0.64 0.022 107 pebble -tile PositiveZ 0 0 0 umbros/first-fractal-terrain zyphos/umbros-latlong -height mare 0 0 24 20 -0.18 2.4 1.3 -0.055 71 mare -ifs shard 3 2 -4 -2 5.2 1.6 0.46 3.0 -0.51 5.2 0.70 0.065 73 shard -ifs scar 2 2 7 4 4.8 1.2 0.38 4.1 0.86 4.6 0.82 -0.045 79 scar -tile NegativeY 1 0 1 umbros/night-cracks umbros/crater-province -height hollow -13 11 8 5 -0.72 2.7 0.95 -0.04 83 hollow -ifs crown 2 2 -16 8 3.6 1.0 0.44 3.6 1.37 5.8 0.76 0.04 89 crown -tile PositiveY 2 1 1 umbros/boulder-pebble umbros/pebble-field -ifs black-pebble 3 2 12 -14 1.6 0.8 0.45 3.8 0.54 7.4 0.66 -0.018 113 pebble diff --git a/src/Aquarium.Zyphos/ZyphosCameraComposer.cs b/src/Aquarium.Zyphos/ZyphosCameraComposer.cs deleted file mode 100644 index feec1b4..0000000 --- a/src/Aquarium.Zyphos/ZyphosCameraComposer.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Zyphos; - -public readonly record struct ZyphosCameraShot( - Vector3 CameraPosition, - Vector3 CameraTarget, - Vector3 ParentAnchor, - Vector3 TrackedCenter, - float EffectiveDistance, - float MinimumDistance, - float MaximumDistance, - ZyphosSpatialDomainKey DomainKey, - ZyphosSpatialDomainKey? ParentDomainKey); - -public static class ZyphosCameraComposer -{ - public static ZyphosCameraShot Compose( - ZyphosSpatialDomainKey domainKey, - float yaw, - float pitch, - float requestedDistance, - float timeSeconds) - { - var domain = ZyphosSpatialDomainCatalog.GetRequired(domainKey); - var parentDomain = ZyphosSpatialDomainCatalog.ParentOf(domain); - var domainPose = domain.Pose(timeSeconds); - var parentPose = parentDomain?.Pose(timeSeconds) ?? domainPose; - var parent = parentPose.Center; - var tracked = domainPose.Center; - var minimumDistance = MinimumDistanceFor(domainPose); - var maximumDistance = MaximumDistanceFor(domainPose, parentPose, parentDomain is not null); - var effectiveDistance = Math.Clamp(requestedDistance, minimumDistance, maximumDistance); - var orbitDirection = OrbitDirection(yaw, pitch); - var cameraPosition = parent + orbitDirection * effectiveDistance; - return new ZyphosCameraShot(cameraPosition, tracked, parent, tracked, effectiveDistance, minimumDistance, maximumDistance, domain.Key, domain.ParentKey); - } - - public static string DisplayName(ZyphosSpatialDomainKey domainKey) - { - var domain = ZyphosSpatialDomainCatalog.GetRequired(domainKey); - return $"{domain.Label} {domain.Kind.ToLowerInvariant()}"; - } - - private static Vector3 OrbitDirection(float yaw, float pitch) - { - var horizontal = MathF.Cos(pitch); - return Vector3.Normalize(new Vector3( - MathF.Sin(yaw) * horizontal, - -MathF.Cos(yaw) * horizontal, - MathF.Sin(pitch))); - } - - private static float MinimumDistanceFor(ZyphosSpatialDomainPose domainPose) - { - return Math.Clamp(domainPose.Radius * 1.65f, 0.035f, 8.0f); - } - - private static float MaximumDistanceFor(ZyphosSpatialDomainPose domainPose, ZyphosSpatialDomainPose parentPose, bool hasParent) - { - var parentSpan = hasParent ? Vector3.Distance(parentPose.Center, domainPose.Center) + parentPose.Radius * 0.25f : 0.0f; - return MathF.Max(8.0f, MathF.Max(domainPose.Radius * 12.0f, parentSpan + domainPose.Radius * 5.0f)); - } -} diff --git a/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs b/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs deleted file mode 100644 index a185bcb..0000000 --- a/src/Aquarium.Zyphos/ZyphosFractalTerrain.cs +++ /dev/null @@ -1,327 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Brushes; -using Aquarium.Engine.Fractal.Debug; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; -using Aquarium.Engine.Render; - -namespace Aquarium.Zyphos; - -public static class ZyphosFractalTerrain -{ - private const string PatchRelativePath = "Worlds/zyphos-first-fractal-terrain.aquageo"; - private const int SurfacePageDimension = 128; - private const long MaxResidentSurfacePageBytes = 2L * 1024L * 1024L; - private const int MaxSurfacePageRequests = 8; - private const int MaxProjectedSurfaceSdfSplats = 64; - private const int MaxProjectedSurfaceSdfSplatsPerPage = 16; - private const int MaxGpuProgramTransforms = 64; - - private static readonly Lazy PatchSource = new(() => File.ReadAllText(PatchPath)); - private static readonly Lazy Tree = new(() => FractalDslCompiler.Compile(PatchSource.Value)); - private static readonly Lazy Summaries = new(() => FractalSummaryBuilder.Build(Tree.Value)); - private static readonly Lazy SelectedCut = new(() => FractalSelectedCutBuilder.Build(Summaries.Value, _ => 8.0f, maxEstimatedCost: 64.0f)); - private static readonly Lazy Brushes = new(() => FractalHeightBrushCompiler.CompileSelectedTree(Tree.Value, SelectedCut.Value)); - private static readonly FractalContributionCache ContributionCache = new(); - private static readonly object PlanCacheLock = new(); - private static readonly Dictionary BrushCache = []; - private static readonly Dictionary SurfacePagePayloadCache = []; - private static readonly Dictionary ProjectedSurfaceSdfSplatCache = []; - private static readonly FractalResourceBudget DefaultBudget = new( - MaxCpuUpdates: 2, - MaxGpuEstimatedCost: 64.0f, - MaxResidentPayloads: 64, - MaxSsdRequests: 2); - private static readonly AquariumFractalSurfacePageKind[] PlannedSurfacePageKinds = - [ - AquariumFractalSurfacePageKind.Height, - AquariumFractalSurfacePageKind.SignedDistance2D, - AquariumFractalSurfacePageKind.Material, - AquariumFractalSurfacePageKind.Confidence, - ]; - - public static string PatchPath => Path.Combine(AppContext.BaseDirectory, PatchRelativePath); - - public static FractalOwnershipTree OwnershipTree => Tree.Value; - - public static AquariumHeightFieldBrush[] HeightBrushes => Brushes.Value; - - public static AquariumFractalSummary[] NodeSummaries => Summaries.Value; - - public static AquariumSelectedCut[] SelectedCuts => SelectedCut.Value; - - public static string DebugDump => FractalDebugDump.Build(OwnershipTree, Summaries.Value, SelectedCut.Value); - - public static ZyphosFractalRenderPlan BuildRenderPlan(ZyphosCameraShot shot) - { - var pixelsPerWorld = Math.Clamp(72.0f / MathF.Max(shot.EffectiveDistance, 0.001f), 0.25f, 48.0f); - var bucket = (int)Math.Clamp(MathF.Round(pixelsPerWorld * 16.0f), 4.0f, 768.0f); - var bucketPixelsPerWorld = bucket / 16.0f; - FractalResourcePlan resourcePlan; - lock (PlanCacheLock) - { - resourcePlan = ContributionCache.PlanFrame( - Summaries.Value, - _ => bucketPixelsPerWorld, - DefaultBudget, - new FractalXorShiftRandom((uint)bucket ^ 0x9E3779B9u), - ResidentFractalPayloadStore.Instance); - } - - var selectedCut = resourcePlan.SelectedCut; - var structuralProbeReservoir = FractalStructuralProbeReservoir.Build( - Tree.Value, - Summaries.Value, - selectedCut, - bucketPixelsPerWorld, - new FractalXorShiftRandom(((uint)bucket ^ 0xC2B2AE35u) + (uint)selectedCut.Length)); - var structuralSdfSplats = BuildStructuralSdfSplats(structuralProbeReservoir); - var surfacePages = PlanSurfacePages(selectedCut); - var surfacePageResidency = FractalSurfacePageResidencyPlanner.Plan( - surfacePages, - ResidentSurfacePageStore.Instance, - MaxResidentSurfacePageBytes, - MaxSurfacePageRequests); - var surfacePagePayloads = BuildSurfacePagePayloads(surfacePageResidency.ResidentPages); - var projectedSurfaceSdfSplats = BuildProjectedSurfaceSdfSplats(surfacePagePayloads); - var gpuProgramTransforms = FractalGpuProgramCompiler.CompileSelectedTree(Tree.Value, selectedCut, MaxGpuProgramTransforms); - var reservoirPriorityFocus = ReservoirPriorityFocusFor(shot); - var cutKey = CutCacheKey(selectedCut); - AquariumHeightFieldBrush[] brushes; - lock (PlanCacheLock) - { - if (!BrushCache.TryGetValue(cutKey, out brushes!)) - { - brushes = OrderBrushesForGeometry(FractalHeightBrushCompiler.CompileSelectedTree(Tree.Value, selectedCut)); - BrushCache[cutKey] = brushes; - } - } - - return new ZyphosFractalRenderPlan( - brushes, - selectedCut, - resourcePlan, - structuralProbeReservoir, - structuralSdfSplats, - surfacePages, - surfacePageResidency, - surfacePagePayloads, - projectedSurfaceSdfSplats, - gpuProgramTransforms, - reservoirPriorityFocus, - bucketPixelsPerWorld, - $"{selectedCut.Length}/{Summaries.Value.Length} cuts / {brushes.Length}/{OwnershipTree.Claims.Count} brushes / {resourcePlan.UpdateNodes.Length}/{DefaultBudget.MaxCpuUpdates} cpu updates / {resourcePlan.GpuEstimatedCost:0.0}/{DefaultBudget.MaxGpuEstimatedCost:0.0} gpu cost / {resourcePlan.Residency.ResidentNodes.Count}/{DefaultBudget.MaxResidentPayloads} resident / {resourcePlan.Residency.RequestedNodes.Count}/{DefaultBudget.MaxSsdRequests} ssd requests / {(structuralProbeReservoir.HasSample ? structuralProbeReservoir.CandidateCount : 0)} probe candidates / {surfacePagePayloads.Length}/{surfacePages.Length} surface payloads / {projectedSurfaceSdfSplats.Length} projected splats / {gpuProgramTransforms.Length} gpu transforms / {bucketPixelsPerWorld:0.00} px-wu"); - } - - private static Vector4 ReservoirPriorityFocusFor(ZyphosCameraShot shot) - { - var relative = (shot.TrackedCenter - ZyphosUmbrosSystem.ZyphosCenter) / MathF.Max(ZyphosUmbrosSystem.ZyphosSurfaceRadius, 0.0001f); - var focusRadius = Math.Clamp(shot.EffectiveDistance / MathF.Max(ZyphosUmbrosSystem.ZyphosSurfaceRadius, 0.0001f), 0.02f, 1.6f); - var strength = Math.Clamp(1.0f - focusRadius * 0.35f, 0.25f, 0.9f); - return new Vector4(relative.X, relative.Y, focusRadius, strength); - } - - private static AquariumFractalSurfacePage[] PlanSurfacePages(IReadOnlyList selectedCut) - { - return PlannedSurfacePageKinds - .SelectMany(kind => FractalSurfacePagePlanner.Plan( - Tree.Value, - Summaries.Value, - selectedCut, - kind, - SurfacePageDimension, - SurfacePageDimension)) - .ToArray(); - } - - private static AquariumFractalSdfSplat3D[] BuildStructuralSdfSplats(FractalProbeReservoirSnapshot reservoir) - { - if (!reservoir.HasSample) - { - return []; - } - - var thickness = MathF.Max(reservoir.BoundRadius * 0.25f, 0.001f); - return [FractalSdfSplat3DCompiler.FromProbe(reservoir.ToProbeSample(), thickness)]; - } - - private static FractalSurfacePagePayload[] BuildSurfacePagePayloads(IReadOnlyList residentPages) - { - var payloads = new FractalSurfacePagePayload[residentPages.Count]; - lock (PlanCacheLock) - { - for (var index = 0; index < residentPages.Count; index++) - { - var page = residentPages[index]; - if (!SurfacePagePayloadCache.TryGetValue(page.Key.Value, out var payload)) - { - payload = FractalSurfacePageRasterizer.Rasterize(Tree.Value, page); - SurfacePagePayloadCache[page.Key.Value] = payload; - } - - payloads[index] = payload; - } - } - - return payloads; - } - - private static AquariumFractalSdfSplat3D[] BuildProjectedSurfaceSdfSplats(IReadOnlyList payloads) - { - var splats = new List(MaxProjectedSurfaceSdfSplats); - lock (PlanCacheLock) - { - foreach (var payload in payloads) - { - if (payload.Page.Key.Kind != AquariumFractalSurfacePageKind.SignedDistance2D) - { - continue; - } - - if (!ProjectedSurfaceSdfSplatCache.TryGetValue(payload.Page.Key.Value, out var pageSplats)) - { - var tangentRadius = TangentRadius(payload.Page); - pageSplats = FractalProjectedSdfSplatCompiler.Compile( - payload, - point => new System.Numerics.Vector3(point.X, point.Y, 0.0f), - System.Numerics.Vector3.UnitZ, - tangentRadius, - MathF.Max(tangentRadius * 0.5f, 0.001f), - tangentRadius, - MaxProjectedSurfaceSdfSplatsPerPage); - ProjectedSurfaceSdfSplatCache[payload.Page.Key.Value] = pageSplats; - } - - foreach (var splat in pageSplats) - { - if (splats.Count >= MaxProjectedSurfaceSdfSplats) - { - return splats.ToArray(); - } - - splats.Add(splat); - } - } - } - - return splats.ToArray(); - } - - private static float TangentRadius(AquariumFractalSurfacePage page) - { - var width = MathF.Abs(page.BoundsMinMax.Z - page.BoundsMinMax.X) / MathF.Max(page.Width - 1, 1); - var height = MathF.Abs(page.BoundsMinMax.W - page.BoundsMinMax.Y) / MathF.Max(page.Height - 1, 1); - return MathF.Max(MathF.Max(width, height) * 0.75f, 0.001f); - } - - private static string CutCacheKey(IReadOnlyList selectedCut) - { - return string.Join("|", selectedCut.Select(cut => cut.NodeKey.Value)); - } - - private static AquariumHeightFieldBrush[] OrderBrushesForGeometry(AquariumHeightFieldBrush[] brushes) - { - return brushes - .OrderByDescending(brush => MathF.Abs(brush.Amplitude) * MathF.Max(brush.Radius, brush.RadiusY)) - .ThenBy(brush => brush.DomainFace) - .ThenBy(brush => brush.DomainLevel) - .ThenBy(brush => brush.Center.X) - .ThenBy(brush => brush.Center.Y) - .ToArray(); - } - - public static string Summary => - $"{Path.GetFileName(PatchPath)} / {OwnershipTree.Claims.Count} DSL claims / {OwnershipTree.Nodes.Count} tile nodes / {SelectedCut.Value.Length} cuts / {HeightBrushes.Length} shaped brushes"; - - public static string BuildPlanDebugDump(ZyphosFractalRenderPlan plan) - { - var budget = plan.ResourcePlan.Budget; - var lines = new List - { - "Zyphos fractal resource plan", - $" pixelsPerWorld: {plan.PixelsPerWorld:0.000}", - $" selectedCut: {plan.SelectedCuts.Length}/{Summaries.Value.Length}", - $" brushes: {plan.HeightBrushes.Length}/{OwnershipTree.Claims.Count}", - $" cpuUpdates: {plan.ResourcePlan.UpdateNodes.Length}/{budget.MaxCpuUpdates}", - $" gpuEstimatedCost: {plan.ResourcePlan.GpuEstimatedCost:0.000}/{budget.MaxGpuEstimatedCost:0.000}", - $" ramResident: {plan.ResourcePlan.Residency.ResidentNodes.Count}/{budget.MaxResidentPayloads}", - $" ssdRequests: {plan.ResourcePlan.Residency.RequestedNodes.Count}/{budget.MaxSsdRequests}", - $" evictions: {plan.ResourcePlan.Residency.EvictedNodes.Count}", - $" structuralProbe: {(plan.StructuralProbeReservoir.HasSample ? plan.StructuralProbeReservoir.NodeKey.Value : "none")}", - $" structuralProbeWeight: {plan.StructuralProbeReservoir.WeightSum:0.000} candidates={plan.StructuralProbeReservoir.CandidateCount} contributionWeight={plan.StructuralProbeReservoir.ContributionWeight:0.000}", - $" structuralSdfSplats: {plan.StructuralSdfSplats.Length}", - $" surfacePages: {plan.SurfacePages.Length} {SurfacePageDimension}x{SurfacePageDimension}", - $" surfacePageResident: {plan.SurfacePageResidency.ResidentPages.Count}/{plan.SurfacePages.Length} bytes={plan.SurfacePageResidency.ResidentBytes}/{MaxResidentSurfacePageBytes}", - $" surfacePagePayloads: {plan.SurfacePagePayloads.Length}", - $" projectedSurfaceSdfSplats: {plan.ProjectedSurfaceSdfSplats.Length}/{MaxProjectedSurfaceSdfSplats}", - $" gpuProgramTransforms: {plan.GpuProgramTransforms.Length}/{MaxGpuProgramTransforms}", - $" surfacePageRequests: {plan.SurfacePageResidency.RequestedPages.Count}/{MaxSurfacePageRequests}", - $" surfacePageEvictions: {plan.SurfacePageResidency.EvictedPages.Count}", - "selected:", - }; - - foreach (var cut in plan.SelectedCuts) - { - lines.Add($" {cut.NodeKey.Value} score={cut.Score:0.000} fade={cut.Fade:0.000} requestChildren={cut.RequestedChildren}"); - } - - if (plan.ResourcePlan.UpdateNodes.Length > 0) - { - lines.Add("updates:"); - foreach (var key in plan.ResourcePlan.UpdateNodes) - { - lines.Add($" {key.Value}"); - } - } - - return string.Join(Environment.NewLine, lines); - } - - private sealed class ResidentFractalPayloadStore : IFractalPayloadStore - { - public static ResidentFractalPayloadStore Instance { get; } = new(); - - public bool IsResident(AquariumFractalKey nodeKey) - { - return true; - } - - public void Request(AquariumFractalKey nodeKey) - { - } - } - - private sealed class ResidentSurfacePageStore : IFractalSurfacePageStore - { - public static ResidentSurfacePageStore Instance { get; } = new(); - - public bool IsResident(AquariumFractalSurfacePageKey key) - { - return true; - } - - public void Request(AquariumFractalSurfacePage page) - { - } - - public void Evict(AquariumFractalSurfacePageKey key) - { - } - } -} - -public readonly record struct ZyphosFractalRenderPlan( - AquariumHeightFieldBrush[] HeightBrushes, - AquariumSelectedCut[] SelectedCuts, - FractalResourcePlan ResourcePlan, - FractalProbeReservoirSnapshot StructuralProbeReservoir, - AquariumFractalSdfSplat3D[] StructuralSdfSplats, - AquariumFractalSurfacePage[] SurfacePages, - FractalSurfacePageResidencyPlan SurfacePageResidency, - FractalSurfacePagePayload[] SurfacePagePayloads, - AquariumFractalSdfSplat3D[] ProjectedSurfaceSdfSplats, - AquariumPackedFractalIfsTransform[] GpuProgramTransforms, - Vector4 ReservoirPriorityFocus, - float PixelsPerWorld, - string Summary); diff --git a/src/Aquarium.Zyphos/ZyphosRenderPlan.cs b/src/Aquarium.Zyphos/ZyphosRenderPlan.cs deleted file mode 100644 index 528bd0d..0000000 --- a/src/Aquarium.Zyphos/ZyphosRenderPlan.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Aquarium.Engine.Render; - -namespace Aquarium.Zyphos; - -public static class ZyphosRenderPlan -{ - public const int PlanetIndex = 0; - public const int UmbrosIndex = 1; - public const int StarIndex = 2; - public const int SdfObjectCount = 3; - - public static AquariumRenderPlan Create() - { - var app = new AquariumApp(); - app.Shaders - .Core("D3D12HeightField.hlsl", "D3D12Scene.hlsl", "D3D12Post.hlsl") - .SdfShader("D3D12ZyphosStar.hlsl"); - - var heightField = app.RenderTargets.Create("height-field") - .FixedSize(128, 128) - .Format(RenderFormat.R16Float) - .Register(); - var scene = app.RenderTargets.Hdr("scene"); - app.Cameras.Orbit("main"); - app.Graph.Pass("height-field").Fullscreen(); - app.Graph.Pass("scene").Fullscreen(); - app.Graph.Pass("sdf-proxies").Proxy(); - app.Features.Bloom(scene.Color); - app.Features.Presentation(scene.Color); - app.Features.DirectWriteOverlay(); - app.Debug.View("Height Field", heightField).View("Scene", scene.Color); - return app.Plan; - } -} diff --git a/src/Aquarium.Zyphos/ZyphosRuntime.cs b/src/Aquarium.Zyphos/ZyphosRuntime.cs deleted file mode 100644 index beab0ad..0000000 --- a/src/Aquarium.Zyphos/ZyphosRuntime.cs +++ /dev/null @@ -1,274 +0,0 @@ -using System.Numerics; -using Aquarium.Engine; -using Aquarium.Engine.Audio; -using Aquarium.Engine.Input; -using Aquarium.Engine.Render; -using Aquarium.Engine.Ui; - -namespace Aquarium.Zyphos; - -public sealed class ZyphosRuntime : IAquariumRuntime -{ - private float timeSeconds; - private float previousTimeSeconds; - private float orbitYaw = -0.28f; - private float orbitPitch = 0.34f; - private float orbitDistance = 15.6f; - private float timeScale = 1.0f; - private bool autoOrbit = true; - private ZyphosSpatialDomainKey selectedDomainKey = ZyphosSpatialDomainCatalog.Planet; - private readonly Dictionary expandedDomains = new() - { - [ZyphosSpatialDomainCatalog.Solar] = true, - [ZyphosSpatialDomainCatalog.Orbital] = true, - [ZyphosSpatialDomainCatalog.Planet] = true, - [ZyphosSpatialDomainCatalog.PlanetLatLong] = true, - [ZyphosSpatialDomainCatalog.ContinentArchipelago] = true, - [ZyphosSpatialDomainCatalog.EquatorialForest] = true, - [ZyphosSpatialDomainCatalog.CanopyTree] = true, - [ZyphosSpatialDomainCatalog.ShingleCoast] = true, - [ZyphosSpatialDomainCatalog.PebbleField] = true, - [ZyphosSpatialDomainCatalog.Umbros] = true, - [ZyphosSpatialDomainCatalog.UmbrosLatLong] = true, - [ZyphosSpatialDomainCatalog.UmbrosCraterProvince] = true, - [ZyphosSpatialDomainCatalog.UmbrosBoulderField] = true, - [ZyphosSpatialDomainCatalog.UmbrosPebbleField] = true, - }; - - public AquariumRuntimeOptions Options { get; private set; } - - public GraphicsSettings GraphicsSettings { get; set; } = new(0, 1.08f, 0.32f, 0.05f); - - public AquariumRenderPlan RenderPlan { get; } = ZyphosRenderPlan.Create(); - - public AquariumUiDocument Ui { get; } - - public AquariumAudioDocument Audio { get; } = new(); - - public AquariumSynthDocument Synth { get; } = AquariumSynthDocument.Empty; - - public AquariumFrame Frame - { - get - { - var shot = CurrentShot(); - var fractalPlan = ZyphosFractalTerrain.BuildRenderPlan(shot); - var starPose = ZyphosSpatialDomainCatalog.GetRequired(ZyphosSpatialDomainCatalog.Solar).Pose(timeSeconds); - var viewRadius = MathF.Max( - MathF.Max(32.0f, shot.EffectiveDistance * 1.15f), - Vector3.Distance(shot.CameraTarget, starPose.Center) + starPose.Radius * 1.6f); - return new AquariumFrame( - new ViewFrame(new Vector2(shot.CameraTarget.X, shot.CameraTarget.Y), viewRadius), - shot.CameraPosition, - shot.CameraTarget, - timeSeconds, - Vector2.Zero, - ZyphosSceneBuilder.Build(timeSeconds, previousTimeSeconds, fractalPlan)); - } - } - - public ZyphosRuntime() - { - Ui = new AquariumUiDocument() - .Panel("Zyphos", 18.0f, 82.0f, 340.0f, panel => - { - panel.Section("Planetary Demo"); - panel.Toggle("Auto Orbit", () => autoOrbit, value => autoOrbit = value); - panel.Slider("Time Scale", () => timeScale, value => timeScale = value, 0.0f, 4.0f, "0.00"); - panel.Slider("Orbit Distance", () => orbitDistance, value => orbitDistance = ClampOrbitDistance(value), 0.04f, 180.0f, "0.00"); - panel.Readout("Runtime", () => $"{timeSeconds:0.0}s"); - panel.Readout("Camera", () => $"{ZyphosCameraComposer.DisplayName(selectedDomainKey)} / {CurrentShot().EffectiveDistance:0.00} wu / yaw {orbitYaw:0.00}"); - panel.Readout("Terrain DSL", () => ZyphosFractalTerrain.Summary); - panel.Readout("Fractal Cut", () => ZyphosFractalTerrain.BuildRenderPlan(CurrentShot()).Summary); - panel.Readout("Binary", () => $"Umbros {ZyphosUmbrosSystem.UmbrosAngularDiameterDegrees:0.0} deg / {ZyphosUmbrosSystem.SeparationInZyphosRadii:0.0} Rz"); - panel.Readout("Objects", () => "fractal height DSL, atmosphere, Umbros"); - }) - .Panel("Navigation", -18.0f, 82.0f, 316.0f, fadeWhenMouseDistant: true, panel => - { - panel.Section("Camera"); - panel.Toggle("Auto Orbit", () => autoOrbit, value => autoOrbit = value); - panel.Readout("Mode", () => ZyphosCameraComposer.DisplayName(selectedDomainKey)); - panel.Readout("Pivot", CurrentPivotLabel); - panel.Readout("Zoom", () => $"{CurrentShot().MinimumDistance:0.00}-{CurrentShot().MaximumDistance:0.0} wu"); - panel.Readout("Mouse", () => "drag orbit / wheel zoom"); - panel.Section("Spatial Domains"); - foreach (var domain in ZyphosSpatialDomainCatalog.Domains) - { - var captured = domain; - panel.TreeItem( - captured.Label, - ZyphosSpatialDomainCatalog.DepthOf(captured), - ZyphosSpatialDomainCatalog.ChildrenOf(captured.Key).Count > 0, - () => IsExpanded(captured.Key), - value => SetExpanded(captured.Key, value), - () => selectedDomainKey == captured.Key, - () => SelectDomain(captured.Key), - captured.Detail, - $"{captured.Kind} domain `{captured.Key}`.", - () => IsDomainVisible(captured)); - } - }) - .Command("zyphos", _ => $"Zyphos: {ZyphosFractalTerrain.Summary}", "Report Zyphos demo status.") - .Command("zyphos-fractal", _ => ZyphosFractalTerrain.DebugDump, "Dump the compiled Zyphos fractal terrain grammar.") - .Command("zyphos-fractal-plan", _ => ZyphosFractalTerrain.BuildPlanDebugDump(ZyphosFractalTerrain.BuildRenderPlan(CurrentShot())), "Dump the current Zyphos fractal selected cut and resource budget.") - .Command("zyphos-system", _ => $"Zyphos-Umbros: separation {ZyphosUmbrosSystem.SeparationInZyphosRadii:0.0} Zyphos radii, Umbros radius {ZyphosUmbrosSystem.UmbrosRadiusRatio:0.00} Zyphos, apparent diameter {ZyphosUmbrosSystem.UmbrosAngularDiameterDegrees:0.0} degrees.", "Report the modeled Zyphos/Umbros/star baseline."); - } - - public AquariumFrame ComposeFrame(AquariumFrame frame, AquariumFrameInput input) - { - return frame; - } - - public void Start() - { - Console.WriteLine("Zyphos planetary demo booted."); - } - - public void Update(float deltaSeconds, InputState input) - { - previousTimeSeconds = timeSeconds; - var safeDelta = Math.Max(deltaSeconds, 0.0f); - timeSeconds += safeDelta * MathF.Max(timeScale, 0.0f); - - if (autoOrbit) - { - orbitYaw += safeDelta * 0.055f; - } - - if (input.IsKeyDown(KeyCode.A)) - { - orbitYaw -= safeDelta * 0.85f; - } - - if (input.IsKeyDown(KeyCode.D)) - { - orbitYaw += safeDelta * 0.85f; - } - - if (input.IsKeyDown(KeyCode.W)) - { - orbitPitch += safeDelta * 0.45f; - } - - if (input.IsKeyDown(KeyCode.S)) - { - orbitPitch -= safeDelta * 0.45f; - } - - if (MathF.Abs(input.WheelDelta) > 0.0f) - { - var zoomScale = MathF.Max(CurrentShot().EffectiveDistance * 0.12f, 0.035f); - orbitDistance = ClampOrbitDistance(orbitDistance - input.WheelDelta * zoomScale); - } - - if (input.LeftMouseDown && input.MouseDelta != Vector2.Zero) - { - autoOrbit = false; - orbitYaw -= input.MouseDelta.X * 0.0065f; - orbitPitch += input.MouseDelta.Y * 0.0045f; - } - - if (input.RightMouseDown && input.MouseDelta != Vector2.Zero) - { - autoOrbit = false; - orbitYaw -= input.MouseDelta.X * 0.0025f; - orbitDistance = ClampOrbitDistance(orbitDistance + input.MouseDelta.Y * MathF.Max(CurrentShot().EffectiveDistance * 0.006f, 0.01f)); - } - - if (input.IsKeyPressed(KeyCode.Digit1)) - { - SelectDomain(ZyphosSpatialDomainCatalog.Planet); - } - - if (input.IsKeyPressed(KeyCode.Digit2)) - { - SelectDomain(ZyphosSpatialDomainCatalog.Umbros); - } - - if (input.IsKeyPressed(KeyCode.Digit3)) - { - SelectDomain(ZyphosSpatialDomainCatalog.Orbital); - } - - orbitPitch = Math.Clamp(orbitPitch, 0.12f, 0.86f); - } - - public void FlushState() - { - } - - public void Dispose() - { - } - - internal void SetOptions(AquariumRuntimeOptions options) - { - Options = options; - } - - private ZyphosCameraShot CurrentShot() - { - return ZyphosCameraComposer.Compose(selectedDomainKey, orbitYaw, orbitPitch, orbitDistance, timeSeconds); - } - - private void SelectDomain(ZyphosSpatialDomainKey key) - { - selectedDomainKey = key; - var domain = ZyphosSpatialDomainCatalog.GetRequired(key); - var shot = CurrentShot(); - orbitDistance = Math.Clamp(MathF.Min(orbitDistance, domain.NavigationRadius * 2.0f), shot.MinimumDistance, shot.MaximumDistance); - while (ZyphosSpatialDomainCatalog.ParentOf(domain) is { } parent) - { - expandedDomains[parent.Key] = true; - domain = parent; - } - } - - private string CurrentPivotLabel() - { - var domain = ZyphosSpatialDomainCatalog.GetRequired(selectedDomainKey); - var parent = ZyphosSpatialDomainCatalog.ParentOf(domain); - return parent is null ? domain.Label : parent.Label; - } - - private bool IsExpanded(ZyphosSpatialDomainKey key) - { - return expandedDomains.TryGetValue(key, out var expanded) && expanded; - } - - private void SetExpanded(ZyphosSpatialDomainKey key, bool expanded) - { - expandedDomains[key] = expanded; - } - - private bool IsDomainVisible(ZyphosSpatialDomain domain) - { - while (ZyphosSpatialDomainCatalog.ParentOf(domain) is { } parent) - { - if (!IsExpanded(parent.Key)) - { - return false; - } - - domain = parent; - } - - return true; - } - - private float ClampOrbitDistance(float value) - { - var shot = CurrentShot(); - return Math.Clamp(value, shot.MinimumDistance, shot.MaximumDistance); - } -} - -public sealed class ZyphosRuntimeFactory : IAquariumRuntimeFactory -{ - public IAquariumRuntime Create(AquariumRuntimeOptions options) - { - var runtime = new ZyphosRuntime(); - runtime.SetOptions(options); - return runtime; - } -} diff --git a/src/Aquarium.Zyphos/ZyphosSceneBuilder.cs b/src/Aquarium.Zyphos/ZyphosSceneBuilder.cs deleted file mode 100644 index bacd53a..0000000 --- a/src/Aquarium.Zyphos/ZyphosSceneBuilder.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.Zyphos; - -public static class ZyphosSceneBuilder -{ - public static AquariumSceneState Build(float timeSeconds, float previousTimeSeconds, ZyphosFractalRenderPlan fractalPlan) - { - return new AquariumSceneState - { - TraceHeightFieldSurface = false, - UseStarfieldBackground = true, - HeightFieldBrushes = fractalPlan.HeightBrushes, - FractalReservoirField = new AquariumFractalReservoirField - { - SplatCount = 2_000_000, - SplatUpdatesPerFrame = 50_000, - ReservoirUpdatesPerPass = 20_000, - WorldCenterRadius = new Vector4(ZyphosUmbrosSystem.ZyphosCenter, ZyphosUmbrosSystem.ZyphosSurfaceRadius), - PriorityFocus = fractalPlan.ReservoirPriorityFocus, - ProgramTransforms = fractalPlan.GpuProgramTransforms, - }, - SdfObjects = BuildSdfObjects(timeSeconds, previousTimeSeconds), - SdfLights = BuildSdfLights(timeSeconds), - }; - } - - private static AquariumSdfObject[] BuildSdfObjects(float timeSeconds, float previousTimeSeconds) - { - var rotation = ZyphosUmbrosSystem.MutualPhase(timeSeconds); - var starCenter = ZyphosUmbrosSystem.PrimaryStarCenter(timeSeconds); - var previousStarCenter = ZyphosUmbrosSystem.PrimaryStarCenter(previousTimeSeconds); - - var objects = new AquariumSdfObject[ZyphosRenderPlan.SdfObjectCount]; - objects[ZyphosRenderPlan.StarIndex] = new AquariumSdfObject( - new Vector4(starCenter, ZyphosUmbrosSystem.PrimaryStarVisualRadius), - new Vector4(previousStarCenter, 0.0f), - new Vector4(ZyphosUmbrosSystem.PrimaryStarVisualRadius, rotation, 0.0f, 0.0f)); - - return objects; - } - - private static AquariumSdfLight[] BuildSdfLights(float timeSeconds) - { - var starCenter = ZyphosUmbrosSystem.PrimaryStarCenter(timeSeconds); - return - [ - new AquariumSdfLight( - new Vector4(starCenter, ZyphosUmbrosSystem.PrimaryStarVisualRadius), - new Vector4(3.2f, 2.5f, 1.8f, -100.0f)), - new AquariumSdfLight( - new Vector4(ZyphosUmbrosSystem.UmbrosCenter(timeSeconds), ZyphosUmbrosSystem.UmbrosSurfaceRadius), - new Vector4(0.06f, 0.08f, 0.11f, -101.0f)) - ]; - } -} diff --git a/src/Aquarium.Zyphos/ZyphosSpatialDomainCatalog.cs b/src/Aquarium.Zyphos/ZyphosSpatialDomainCatalog.cs deleted file mode 100644 index 5b5127c..0000000 --- a/src/Aquarium.Zyphos/ZyphosSpatialDomainCatalog.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Zyphos; - -public readonly record struct ZyphosSpatialDomainKey(string Value) -{ - public override string ToString() => Value; -} - -public readonly record struct ZyphosSpatialDomainPose(Vector3 Center, float Radius); - -public sealed record ZyphosSpatialDomain( - ZyphosSpatialDomainKey Key, - ZyphosSpatialDomainKey? ParentKey, - string Label, - string Detail, - string Kind, - float NavigationRadius, - Func Pose); - -public static class ZyphosSpatialDomainCatalog -{ - public static readonly ZyphosSpatialDomainKey Solar = new("zyphos/parent-star"); - public static readonly ZyphosSpatialDomainKey Orbital = new("zyphos/zyphos-umbros-orbit"); - public static readonly ZyphosSpatialDomainKey Planet = new("zyphos/planet"); - public static readonly ZyphosSpatialDomainKey Umbros = new("zyphos/umbros"); - public static readonly ZyphosSpatialDomainKey PlanetLatLong = new("zyphos/planet-latlong"); - public static readonly ZyphosSpatialDomainKey UmbrosLatLong = new("zyphos/umbros-latlong"); - public static readonly ZyphosSpatialDomainKey ContinentArchipelago = new("zyphos/continent-archipelago"); - public static readonly ZyphosSpatialDomainKey EquatorialForest = new("zyphos/equatorial-forest"); - public static readonly ZyphosSpatialDomainKey CanopyTree = new("zyphos/canopy-tree"); - public static readonly ZyphosSpatialDomainKey CanopyLeaf = new("zyphos/canopy-leaf"); - public static readonly ZyphosSpatialDomainKey ShingleCoast = new("zyphos/shingle-coast"); - public static readonly ZyphosSpatialDomainKey PebbleField = new("zyphos/pebble-field"); - public static readonly ZyphosSpatialDomainKey UmbrosCraterProvince = new("umbros/crater-province"); - public static readonly ZyphosSpatialDomainKey UmbrosBoulderField = new("umbros/boulder-field"); - public static readonly ZyphosSpatialDomainKey UmbrosPebbleField = new("umbros/pebble-field"); - public static readonly ZyphosSpatialDomainKey TerrainTile = new("cube/PositiveZ/L00/0/0:zyphos/first-fractal-terrain"); - public static readonly ZyphosSpatialDomainKey TerminatorShelvesTile = new("cube/PositiveX/L01/1/0:zyphos/terminator-shelves"); - public static readonly ZyphosSpatialDomainKey GreenleafCanopyTile = new("cube/NegativeX/L02/2/1:zyphos/greenleaf-canopy"); - public static readonly ZyphosSpatialDomainKey PebbleFieldTile = new("cube/NegativeZ/L02/1/2:zyphos/pebble-field"); - public static readonly ZyphosSpatialDomainKey UmbrosTerrainTile = new("cube/PositiveZ/L00/0/0:umbros/first-fractal-terrain"); - public static readonly ZyphosSpatialDomainKey UmbrosNightCracksTile = new("cube/NegativeY/L01/0/1:umbros/night-cracks"); - public static readonly ZyphosSpatialDomainKey UmbrosBoulderPebbleTile = new("cube/PositiveY/L02/1/1:umbros/boulder-pebble"); - - private static readonly ZyphosSpatialDomain[] DomainList = - [ - new(Solar, null, "Parent Star", "sun", "Solar", ZyphosUmbrosSystem.CenterSeparation * 0.9f, time => new ZyphosSpatialDomainPose(ZyphosUmbrosSystem.PrimaryStarCenter(time), ZyphosUmbrosSystem.PrimaryStarVisualRadius)), - new(Orbital, Solar, "Zyphos-Umbros Orbit", "orbital", "Orbital", ZyphosUmbrosSystem.CenterSeparation * 1.9f, time => new ZyphosSpatialDomainPose(BinaryCenter(time), ZyphosUmbrosSystem.CenterSeparation * 0.5f)), - new(Planet, Orbital, "Zyphos", "planet", "Planetary", ZyphosUmbrosSystem.ZyphosBoundRadius * 2.6f, _ => new ZyphosSpatialDomainPose(ZyphosUmbrosSystem.ZyphosCenter, ZyphosUmbrosSystem.ZyphosBoundRadius)), - new(Umbros, Orbital, "Umbros", "twin", "Planetary", ZyphosUmbrosSystem.CenterSeparation * 1.35f, time => new ZyphosSpatialDomainPose(ZyphosUmbrosSystem.UmbrosCenter(time), ZyphosUmbrosSystem.UmbrosBoundRadius)), - new(PlanetLatLong, Planet, "Lat/Long Surface", "surface", "LatLong", ZyphosUmbrosSystem.ZyphosBoundRadius * 1.55f, _ => new ZyphosSpatialDomainPose(ZyphosUmbrosSystem.ZyphosCenter, ZyphosUmbrosSystem.ZyphosSurfaceRadius)), - new(ContinentArchipelago, PlanetLatLong, "Archipelago Continent", "continent", "Surface2D", ZyphosUmbrosSystem.ZyphosBoundRadius * 1.28f, _ => PlanetSurface(new Vector3(0.25f, 0.62f, 0.42f), ZyphosUmbrosSystem.ZyphosSurfaceRadius * 0.52f)), - new(EquatorialForest, ContinentArchipelago, "Equatorial Forest", "forest", "Surface2D", ZyphosUmbrosSystem.ZyphosBoundRadius * 0.82f, _ => PlanetSurface(new Vector3(0.32f, 0.68f, 0.16f), ZyphosUmbrosSystem.ZyphosSurfaceRadius * 0.22f)), - new(CanopyTree, EquatorialForest, "Canopy Tree", "tree", "Object3D", ZyphosUmbrosSystem.ZyphosBoundRadius * 0.42f, _ => PlanetSurface(new Vector3(0.35f, 0.71f, 0.18f), ZyphosUmbrosSystem.ZyphosSurfaceRadius * 0.075f)), - new(CanopyLeaf, CanopyTree, "Canopy Leaf", "leaf", "Object3D", ZyphosUmbrosSystem.ZyphosBoundRadius * 0.24f, _ => PlanetSurface(new Vector3(0.36f, 0.72f, 0.19f), ZyphosUmbrosSystem.ZyphosSurfaceRadius * 0.028f)), - new(ShingleCoast, ContinentArchipelago, "Shingle Coast", "coast", "Surface2D", ZyphosUmbrosSystem.ZyphosBoundRadius * 0.68f, _ => PlanetSurface(new Vector3(0.55f, -0.24f, 0.12f), ZyphosUmbrosSystem.ZyphosSurfaceRadius * 0.16f)), - new(PebbleField, ShingleCoast, "Pebble Field", "pebbles", "Object3D", ZyphosUmbrosSystem.ZyphosBoundRadius * 0.32f, _ => PlanetSurface(new Vector3(0.57f, -0.28f, 0.10f), ZyphosUmbrosSystem.ZyphosSurfaceRadius * 0.045f)), - new(TerrainTile, ContinentArchipelago, "Zyphos Zenith Tile", "tile", "Cube tile", ZyphosUmbrosSystem.ZyphosBoundRadius * 1.22f, _ => new ZyphosSpatialDomainPose(ZyphosUmbrosSystem.ZyphosCenter + new Vector3(0.0f, 0.0f, ZyphosUmbrosSystem.ZyphosSurfaceRadius), ZyphosUmbrosSystem.ZyphosSurfaceRadius * 0.32f)), - new(TerminatorShelvesTile, ShingleCoast, "Terminator Shelves", "L1 tile", "Cube tile", ZyphosUmbrosSystem.ZyphosBoundRadius * 1.18f, _ => new ZyphosSpatialDomainPose(ZyphosUmbrosSystem.ZyphosCenter + Vector3.Normalize(new Vector3(1.0f, 0.0f, 0.2f)) * ZyphosUmbrosSystem.ZyphosSurfaceRadius, ZyphosUmbrosSystem.ZyphosSurfaceRadius * 0.25f)), - new(GreenleafCanopyTile, CanopyLeaf, "Greenleaf Canopy Tile", "leaf IFS", "Cube tile", ZyphosUmbrosSystem.ZyphosBoundRadius * 0.36f, _ => PlanetSurface(new Vector3(0.36f, 0.72f, 0.19f), ZyphosUmbrosSystem.ZyphosSurfaceRadius * 0.05f)), - new(PebbleFieldTile, PebbleField, "Pebble Field Tile", "pebble IFS", "Cube tile", ZyphosUmbrosSystem.ZyphosBoundRadius * 0.30f, _ => PlanetSurface(new Vector3(0.58f, -0.29f, 0.11f), ZyphosUmbrosSystem.ZyphosSurfaceRadius * 0.038f)), - new(UmbrosLatLong, Umbros, "Umbros Lat/Long", "surface", "LatLong", ZyphosUmbrosSystem.UmbrosBoundRadius * 1.65f, time => new ZyphosSpatialDomainPose(ZyphosUmbrosSystem.UmbrosCenter(time), ZyphosUmbrosSystem.UmbrosSurfaceRadius)), - new(UmbrosCraterProvince, UmbrosLatLong, "Crater Province", "province", "Surface2D", ZyphosUmbrosSystem.UmbrosBoundRadius * 0.72f, time => UmbrosSurface(time, new Vector3(0.84f, -0.18f, 0.28f), ZyphosUmbrosSystem.UmbrosSurfaceRadius * 0.18f)), - new(UmbrosBoulderField, UmbrosCraterProvince, "Boulder Field", "boulders", "Surface2D", ZyphosUmbrosSystem.UmbrosBoundRadius * 0.44f, time => UmbrosSurface(time, new Vector3(0.86f, -0.22f, 0.22f), ZyphosUmbrosSystem.UmbrosSurfaceRadius * 0.08f)), - new(UmbrosPebbleField, UmbrosBoulderField, "Umbros Pebble Field", "pebbles", "Object3D", ZyphosUmbrosSystem.UmbrosBoundRadius * 0.28f, time => UmbrosSurface(time, new Vector3(0.88f, -0.24f, 0.20f), ZyphosUmbrosSystem.UmbrosSurfaceRadius * 0.035f)), - new(UmbrosTerrainTile, UmbrosLatLong, "Umbros Zenith Tile", "tile", "Cube tile", ZyphosUmbrosSystem.UmbrosBoundRadius * 1.2f, time => new ZyphosSpatialDomainPose(ZyphosUmbrosSystem.UmbrosCenter(time) + new Vector3(0.0f, 0.0f, ZyphosUmbrosSystem.UmbrosSurfaceRadius), ZyphosUmbrosSystem.UmbrosSurfaceRadius * 0.34f)), - new(UmbrosNightCracksTile, UmbrosCraterProvince, "Umbros Night Cracks", "L1 tile", "Cube tile", ZyphosUmbrosSystem.UmbrosBoundRadius * 1.18f, time => new ZyphosSpatialDomainPose(ZyphosUmbrosSystem.UmbrosCenter(time) + Vector3.Normalize(new Vector3(0.0f, -1.0f, 0.18f)) * ZyphosUmbrosSystem.UmbrosSurfaceRadius, ZyphosUmbrosSystem.UmbrosSurfaceRadius * 0.24f)), - new(UmbrosBoulderPebbleTile, UmbrosPebbleField, "Boulder Pebble Tile", "pebble IFS", "Cube tile", ZyphosUmbrosSystem.UmbrosBoundRadius * 0.30f, time => UmbrosSurface(time, new Vector3(0.89f, -0.25f, 0.19f), ZyphosUmbrosSystem.UmbrosSurfaceRadius * 0.04f)), - ]; - - private static readonly IReadOnlyDictionary DomainByKey = - DomainList.ToDictionary(domain => domain.Key); - - public static IReadOnlyList Domains => DomainList; - - public static ZyphosSpatialDomain GetRequired(ZyphosSpatialDomainKey key) - { - if (!DomainByKey.TryGetValue(key, out var domain)) - { - throw new ArgumentException($"Unknown Zyphos spatial domain `{key}`.", nameof(key)); - } - - return domain; - } - - public static IReadOnlyList ChildrenOf(ZyphosSpatialDomainKey key) - { - return DomainList.Where(domain => domain.ParentKey == key).ToArray(); - } - - public static ZyphosSpatialDomain? ParentOf(ZyphosSpatialDomain domain) - { - return domain.ParentKey is { } parentKey ? GetRequired(parentKey) : null; - } - - public static int DepthOf(ZyphosSpatialDomain domain) - { - var depth = 0; - var current = domain; - while (ParentOf(current) is { } parent) - { - depth++; - current = parent; - } - - return depth; - } - - public static string DisplayName(ZyphosSpatialDomainKey key) => GetRequired(key).Label; - - private static Vector3 BinaryCenter(float timeSeconds) - { - return ZyphosUmbrosSystem.ZyphosCenter + (ZyphosUmbrosSystem.UmbrosCenter(timeSeconds) - ZyphosUmbrosSystem.ZyphosCenter) * 0.5f; - } - - private static ZyphosSpatialDomainPose PlanetSurface(Vector3 normal, float radius) - { - return new ZyphosSpatialDomainPose( - ZyphosUmbrosSystem.ZyphosCenter + Vector3.Normalize(normal) * ZyphosUmbrosSystem.ZyphosSurfaceRadius, - radius); - } - - private static ZyphosSpatialDomainPose UmbrosSurface(float timeSeconds, Vector3 normal, float radius) - { - return new ZyphosSpatialDomainPose( - ZyphosUmbrosSystem.UmbrosCenter(timeSeconds) + Vector3.Normalize(normal) * ZyphosUmbrosSystem.UmbrosSurfaceRadius, - radius); - } -} diff --git a/src/Aquarium.Zyphos/ZyphosUmbrosSystem.cs b/src/Aquarium.Zyphos/ZyphosUmbrosSystem.cs deleted file mode 100644 index 181b403..0000000 --- a/src/Aquarium.Zyphos/ZyphosUmbrosSystem.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System.Numerics; - -namespace Aquarium.Zyphos; - -public static class ZyphosUmbrosSystem -{ - public const float ZyphosSurfaceRadius = 3.8f; - public const float ZyphosBoundRadius = 4.52f; - public const float UmbrosRadiusRatio = 0.9f; - public const float SeparationInZyphosRadii = 8.0f; - public const float SeaLevel = 0.56f; - public const float MutualPhaseRate = 0.032f; - public const float PrimaryStarVisualRadius = 3.2f; - - public static float UmbrosSurfaceRadius => ZyphosSurfaceRadius * UmbrosRadiusRatio; - - public static float UmbrosBoundRadius => UmbrosSurfaceRadius + 0.42f; - - public static float CenterSeparation => ZyphosSurfaceRadius * SeparationInZyphosRadii; - - public static float UmbrosAngularDiameterDegrees => - MathF.Asin(Math.Clamp(UmbrosSurfaceRadius / CenterSeparation, -1.0f, 1.0f)) * 2.0f * 180.0f / MathF.PI; - - public static Vector3 ZyphosCenter => new(0.0f, 0.0f, ZyphosSurfaceRadius + 0.48f); - - public static float MutualPhase(float timeSeconds) - { - return timeSeconds * MutualPhaseRate; - } - - public static Vector3 UmbrosDirection(float timeSeconds) - { - // Zyphos renders in the mutually locked local frame: Umbros is fixed in the sky while the primary star phase moves. - _ = timeSeconds; - return Vector3.UnitX; - } - - public static Vector3 UmbrosCenter(float timeSeconds) - { - return ZyphosCenter + UmbrosDirection(timeSeconds) * CenterSeparation; - } - - public static Vector3 PrimaryStarDirection(float timeSeconds) - { - var phase = MutualPhase(timeSeconds); - return Vector3.Normalize(new Vector3(MathF.Cos(phase), MathF.Sin(phase), 0.18f)); - } - - public static Vector3 PrimaryStarCenter(float timeSeconds) - { - return ZyphosCenter + PrimaryStarDirection(timeSeconds) * (CenterSeparation * 3.2f); - } -} diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 7e62fa3..73b0712 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -1,213 +1 @@ -{"timestamp":"2026-05-09T04:42:00+01:00","topic":"debug-ui-control-grammar","lesson":"Aquarium debug UI uses a code-first Direct2D/DirectWrite overlay with explicit bound controls. Rect math must distinguish edges from width/height, controls need base/hover/active feedback, tooltips live in declarations, and long mode selectors should be named option rows instead of numeric sliders.","files":["src/Aquarium.Engine/Render/Ui/DebugUi.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json"]} -{"timestamp":"2026-05-09T05:20:00+01:00","topic":"graphics-settings-cultcache","lesson":"Renderer presentation knobs belong in a typed CultCache graphics settings document, not process folklore. Current durable knobs are render debug mode, exposure, bloom intensity, and bloom veil.","files":["src/Aquarium.Engine.Contracts/GraphicsSettings.cs","src/Aquarium.Epiphany/State/AquariumGraphicsSettingsState.cs","state/memory.json"]} -{"timestamp":"2026-05-12T00:00:00+01:00","topic":"engine-client-boundary","lesson":"Aquarium.Engine is the native D3D12/window/render graph layer and must not accrete Epiphany frontend semantics. Aquarium.Epiphany is the client/runtime layer behind Aquarium.Engine.Contracts and should configure engine abstractions for cameras, targets, shaders, resources, and passes.","files":["docs/engine-client-boundary.md","src/Aquarium.Epiphany/Aquarium.Epiphany.csproj","src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs","state/memory.json","state/map.yaml"]} -{"timestamp":"2026-05-12T00:00:00+01:00","topic":"epiphany-extraction-render-api-plan","lesson":"The next purification path is a small render graph API, not more renderer knobs: clients declare resources and passes, Aquarium owns D3D12 execution. Migrate in slices: freeze boundary, add Vortice-free descriptors, compile a minimal graph, convert presentation/bloom, move Epiphany body shaders and Grid policy to Aquarium.Epiphany, then replace AquariumFrame.","files":["docs/epiphany-extraction-render-api-plan.md","README.md","state/map.yaml","state/memory.json"]} -{"timestamp":"2026-05-12T03:40:00+01:00","topic":"epiphany-render-policy-extraction","lesson":"Epiphany body shaders, Grid brush construction, body visual/light tables, and cursor projection moved behind Aquarium.Engine.Contracts. Aquarium.Engine now consumes AquariumRenderPlan and AquariumSceneState data and passes scripts/verify-boundaries.ps1 with no Epiphany role/client names in engine source.","files":["src/Aquarium.Engine.Contracts/Render/AquariumApp.cs","src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Epiphany/EpiphanyRenderPlan.cs","src/Aquarium.Epiphany/EpiphanySceneBuilder.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","scripts/verify-boundaries.ps1","state/memory.json","state/map.yaml"]} -{"timestamp":"2026-05-12T03:50:00+01:00","topic":"graph-target-allocation","lesson":"The render graph compiler now validates declared targets/passes and D3D12Renderer allocates non-legacy client-declared render targets through engine resource/descriptors, including resize rebuild. This is allocation only; full graph pass execution remains the next cut.","files":["src/Aquarium.Engine/Render/Graph/D3D12RenderGraphCompiler.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine.Contracts/Render/AquariumApp.cs","state/memory.json"]} -{"timestamp":"2026-05-12T04:00:00+01:00","topic":"minimal-non-epiphany-client","lesson":"Aquarium now includes src/Aquarium.Sample.Minimal, a non-Epiphany client that references only Aquarium.Engine.Contracts, declares a minimal render plan, and boots through the same host/client assembly loader. Keep it as a boundary proof while the graph executor replaces legacy fixed passes.","files":["src/Aquarium.Sample.Minimal/MinimalRuntime.cs","src/Aquarium.Sample.Minimal/Aquarium.Sample.Minimal.csproj","README.md","state/map.yaml"]} -{"timestamp":"2026-05-12T04:05:00+01:00","topic":"grid-brush-gpu-packing","lesson":"GridHeightBrushConstants is D3D12 GPU packing for the height-field brush pass, not scene policy. Keep brush authoring in the client, keep packing in engine feature code, and keep D3D12Renderer limited to upload/command recording until the height-field pass moves fully into the graph executor.","files":["src/Aquarium.Engine/Render/Features/D3D12GridHeightBrushConstants.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/evidence.jsonl"]} -{"timestamp":"2026-05-10T07:47:46+01:00","topic":"cursor-teardrop-sdf","lesson":"Use the MathWorld teardrop curve for the cursor profile with m=6, revolved into an SDF locator. Keep ripples as geometry, material as brass GGX metal, and avoid ambient fill.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/memory.json"],"source":"https://mathworld.wolfram.com/TeardropCurve.html"} -{"timestamp":"2026-05-11T00:00:00+01:00","topic":"aquarium-focus-cut","lesson":"Runtime volumetrics, cloud/fog research, and the D3D11 scene renderer are shelved because they distract from Aquarium's Epiphany-client mission. Git history holds the experiment; live repo state should not preserve compatibility husks or dead guidance for removed medium settings.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine.Contracts/GraphicsSettings.cs","state/map.yaml","state/memory.json","state/scratch.md"]} -{"timestamp":"2026-05-11T04:20:00+01:00","topic":"medium-froxel-purge","lesson":"Medium/froxel render targets, structured buffers, shader bindings, scene outputs, post history lanes, and medium debug paths were removed from the live D3D12 renderer. Future atmospheric or field transport work needs a new explicit pass contract rather than reviving shelved scaffolding.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","state/map.yaml","state/memory.json"]} -{"timestamp":"2026-05-11T05:32:00+01:00","topic":"body-light-lane","lesson":"Blue-noise assets are retained for future dithering. Self and future other Selves emit through an explicit body light buffer; generic field instances are not the lighting authority.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/map.yaml","state/memory.json"]} -{"timestamp":"2026-05-11T06:18:00+01:00","topic":"pmrem-cubemap-bake","lesson":"Studio HDR reflection lighting is baked as a PMREM DDS cubemap: roughness selects higher mips, and the bake samples the source latlong by output direction so cubemap faces are generated from one continuous domain instead of filtered as isolated square images.","files":["scripts/bake-pmrem-cubemap.py","src/Aquarium.Engine/Assets/Textures/studio3_pmrem.dds","state/map.yaml","state/memory.json"],"source":"E:\\Projects\\EpiphanyAquarium\\public\\textures\\studio3.hdr"} -{"timestamp":"2026-05-11T06:28:00+01:00","topic":"pmrem-scene-binding","lesson":"The Studio3 PMREM asset is live in the scene as a D3D12 TextureCube bound at t22. The renderer owns a narrow RGBA16F DX10 DDS cubemap loader, keeps upload resources alive until the copy fence completes, and the scene shader uses roughness-scaled SampleLevel for specular material reflections only.","files":["src/Aquarium.Engine/Render/D3D12CubeTexture.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/map.yaml","state/memory.json"]} -{"timestamp":"2026-05-11T06:42:00+01:00","topic":"grid-mirror-surface","lesson":"Grid linework was replaced with a terminating perfect mirror surface. Grid hits now write the primary scene packet with FIELD_ID_GRID, terrain normal, full coverage, and Studio3 PMREM mip 0 reflection instead of using the transparent event lane.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/map.yaml","state/memory.json"]} -{"timestamp":"2026-05-11T06:50:00+01:00","topic":"pmrem-world-basis","lesson":"Aquarium world space is Z-up while the baked Studio3 PMREM cubemap is sampled as Y-up. Every PMREM lookup must convert world directions with (x, z, y) before TextureCube sampling, or the HDRI appears sideways.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/memory.json"]} -{"timestamp":"2026-05-11T07:00:00+01:00","topic":"studio2-pmrem-probe","lesson":"Active reflection probe switched to Studio2 from E:\\Projects\\Aetheria-Economy\\Assets\\Textures\\studio2.hdr. The renderer loads Assets/Textures/studio2_pmrem.dds through the existing D3D12 TextureCube PMREM path, and the unused Studio3 DDS was cut from live assets.","files":["src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds","src/Aquarium.Engine/Assets/Textures/studio3_pmrem.dds","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/map.yaml","state/memory.json"],"source":"E:\\Projects\\Aetheria-Economy\\Assets\\Textures\\studio2.hdr"} -{"timestamp":"2026-05-11T07:14:00+01:00","topic":"grid-brush-cpu-mirror","lesson":"Self's Grid gravity bowl now uses a 17-world-unit radius and an Aetheria-style radial cosine wave. The brush equation is mirrored across D3D12Grid, CPU body-light placement, D3D12Scene body centers, and D3D12Post temporal reprojection; body centers sit at Grid height plus 2x radius.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Grid.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","state/map.yaml","state/memory.json"],"source":"E:\\Projects\\Aetheria-Economy\\Assets\\Shaders\\Brushes\\RadialWaveBrush.shader"} -{"timestamp":"2026-05-11T07:22:00+01:00","topic":"grid-flatness-roughness","lesson":"Grid reflection roughness is now slope-driven: flat regions sample higher Studio2 PMREM mips to avoid an over-literal HDRI mirror, while sloped or waved regions sharpen toward mip 0.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/memory.json"]} -{"timestamp":"2026-05-11T07:28:00+01:00","topic":"pmrem-background-mip","lesson":"Flat Grid reflection now tops out at Studio2 PMREM mip 3, and ray misses use Studio2 PMREM mip 3 as the soft background so the reflective Grid is not contrasted against black void. Low-resolution mip texels are hidden with a small multi-direction cone average rather than one magnified TextureCube sample.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/memory.json"]} -{"timestamp":"2026-05-11T07:36:00+01:00","topic":"studio2-pmrem-resolution","lesson":"Studio2 PMREM was rebaked at 512px per cubemap face with 10 mips, so mip 3 is 64px per face instead of 32px. Shader roughness LOD max moved to 9 to match the chain.","files":["src/Aquarium.Engine/Assets/Textures/studio2_pmrem.dds","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/memory.json"],"source":"E:\\Projects\\Aetheria-Economy\\Assets\\Textures\\studio2.hdr"} -{"timestamp":"2026-05-11T07:45:00+01:00","topic":"diffuse-ibl-irradiance","lesson":"Diffuse IBL is not GGX PMREM with a softer mip. Studio2 diffuse lighting now uses a separate irradiance cubemap baked by cosine-weighted hemisphere convolution, stores the Li*cos(theta) irradiance integral, and shades non-metal bodies with Fresnel-gated albedo/PI diffuse response.","files":["scripts/bake-pmrem-cubemap.py","src/Aquarium.Engine/Assets/Textures/studio2_irradiance.dds","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","state/map.yaml","state/memory.json"],"source":"E:\\Projects\\Aetheria-Economy\\Assets\\Textures\\studio2.hdr"} -{"timestamp":"2026-05-11T08:10:00+01:00","topic":"rider-solution-compatibility","lesson":"Rider may open Aquarium.Engine.slnx with empty project trees even though dotnet can build it. Keep Aquarium.Engine.sln as the Rider-facing classic solution while Aquarium.Engine.slnx remains the compact CLI solution.","files":["Aquarium.Engine.sln","Aquarium.Engine.slnx","README.md","state/map.yaml"]} -{"timestamp":"2026-05-11T08:35:00+01:00","topic":"epiphany-agent-sdf-visual-language","lesson":"Epiphany agent bodies should be role-specific SDF organs driven by published CultNet surfaces: identity from epiphany.agent_memory, motion from epiphany.agent_heartbeat, posture from surface roles/coordinator/role_result, Face output from surface.face, and continuity pressure from pressure/reorient surfaces. Body and Imagination are the first implementation pair because they exercise grounded graph mass and generative harmonic bloom against the same AgentVisualState contract.","files":["docs/epiphany-agent-sdf-visual-language.md","state/map.yaml","state/memory.json"],"source":"E:\\Projects\\EpiphanyAgent\\schemas\\README.md"} -{"timestamp":"2026-05-11T08:48:00+01:00","topic":"agent-expression-placement","lesson":"Agent orbit lanes are home anchors, not cages. Role bodies may wander a bounded distance from their designated orbit slots for expression, and vertical animation should come from CPU-visible gravity-well pulses so Grid height, body centers, shadows, and temporal reprojection share the same placement truth.","files":["docs/epiphany-agent-sdf-visual-language.md","state/map.yaml","state/memory.json"]} -{"timestamp":"2026-05-11T09:02:00+01:00","topic":"agent-visual-spec-specificity","lesson":"The Epiphany agent visual-language doc must specify spatial derivation, not describe role bodies with directionless vibes. Agent SDF orientation now has a world coordinate contract, fixed home orbit slots, named anchors, fallback chains, normalized state scalars, and concrete workDirection derivation for Hands.","files":["docs/epiphany-agent-sdf-visual-language.md"],"source":"user review"} -{"timestamp":"2026-05-11T09:14:00+01:00","topic":"aquarium-owned-agent-spatial-layout","lesson":"Do not push Aquarium spatial authority onto Epiphany. Epiphany publishes semantic surfaces; Aquarium owns world placement. Agent visual anchors such as evidenceAnchor, artifactAnchor, workAnchor, reviewAnchor, and continuityAnchor are deterministic Aquarium-local projections from semantic state, not CultNet world coordinates emitted by Epiphany.","files":["docs/epiphany-agent-sdf-visual-language.md","state/memory.json"],"source":"user review"} -{"timestamp":"2026-05-11T09:26:00+01:00","topic":"decisive-agent-visual-language","lesson":"The Epiphany agent SDF visual spec should avoid presentation uncertainty. Remove slash-pairs and standalone 'or' alternatives from the visual-language document; choose one mathematical form per organ, favor sphere intersections, torus arcs, trefoil and lemniscate tubes, superquadrics, geodesic ribs, logarithmic spirals, rounded octahedra, and cardioid seeds over generic ellipsoid/capsule placeholders.","files":["docs/epiphany-agent-sdf-visual-language.md"],"source":"user review"} -{"timestamp":"2026-05-11T09:40:00+01:00","topic":"agent-sdf-realtime-rendering-plan","lesson":"Agent role SDFs should render as bounded per-agent implicit objects, not one scene-global mega-SDF. Use conservative sphere-tracing distances, proxy rasterization, one role SDF selected after proxy hit, local bounds for expensive features, post-hit normals, cheap shadows, pixel-footprint hit epsilon, LOD tiers, and debug views for step count, proxy hits, material id, LOD, and SDF cost.","files":["docs/epiphany-agent-sdf-visual-language.md","state/memory.json"],"source":"Hart sphere tracing, Enhanced Sphere Tracing, Inigo Quilez SDF bounding, CTSS, NVIDIA SDF grids"} -{"timestamp":"2026-05-11T16:18:00+01:00","topic":"agent-visual-state-first-slice","lesson":"The fixed orbit bodies are now backed by an AgentVisualGpu buffer carrying current center, previous center, role id, state scalars, and LOD. D3D12Scene uses the buffer for bounded agent SDF hits; D3D12Post uses the same buffer for agent temporal reprojection. Body and Imagination are the first LOD 1 role SDFs, with debug modes for role, material, step count, LOD, and cost.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","src/Aquarium.Engine.Contracts/GraphicsSettings.cs","docs/hlsl-renderer.md","state/map.yaml","state/memory.json"]} -{"timestamp":"2026-05-11T16:39:00+01:00","topic":"agent-sdf-domain-discipline","lesson":"Early role-body experiments showed that decorative pseudo-distance fields, raw atan2 lobes, and stitched ellipsoid petals create seams, gaps, and view-dependent fixes. For role SDFs, choose a continuous spatial domain or anatomical parameterization that owns the silhouette, then make the marcher conservative enough for that field; do not preserve old scene-pass LOD 1 blob recipes as future guidance.","files":["state/memory.json","state/evidence.jsonl"],"source":"consolidated early agent-body artifact review"} -{"timestamp":"2026-05-11T21:40:00+00:00","topic":"bounded-body-proxy-pass","lesson":"The fullscreen scene pass should own only background and Grid. Self, cursor, and role bodies now render through AgentVisualGpu-driven bounded proxy draws: one instanced conservative screen rectangle per object, object-local raymarching, and travel-derived depth writes so Grid and body occlusion stay honest.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","docs/hlsl-renderer.md","state/map.yaml","state/memory.json"],"source":"user architecture correction"} -{"timestamp":"2026-05-11T22:07:07+01:00","topic":"shader-boundary-body-pass","lesson":"D3D12Scene is now environment/Grid only. Bounded body proxy draws compile from D3D12Bodies.hlsl, reusable SDF math lives in D3D12SdfMath.hlsli, current agent character organs live in D3D12AgentCharacters.hlsli, and D3D12Renderer expands local includes before D3DCompile because the Vortice convenience compile path does not provide a usable include handler here. The cursor is now a luminous three-lobed hibiscus anchored on XY with its contact tip at Grid z=0.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Bodies.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12AgentCharacters.hlsli","docs/hlsl-renderer.md","state/map.yaml","state/memory.json"],"source":"user architecture correction"} -{"timestamp":"2026-05-11T22:17:28+01:00","topic":"per-body-shader-boundary","lesson":"Body proxy rendering now uses one shader file and one proxy pipeline per visible body slot: Face, Imagination, Eyes, Body, Hands, Self, and Cursor. Shared proxy plumbing lives in D3D12BodyCommon.hlsli and D3D12BodyProxy.hlsli, but body identity SDF and material code should stay split by body rather than collapsing into a single role or Self bucket.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12BodyCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12BodyProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12FaceAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12ImaginationAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12EyesAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12BodyAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12HandsAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12SelfBody.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12CursorBody.hlsl","docs/hlsl-renderer.md","state/map.yaml","state/memory.json"],"source":"user architecture correction"} -{"timestamp":"2026-05-11T22:18:54+01:00","topic":"eight-agent-body-table","lesson":"The visible Epiphany agent body table is Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life. Cursor remains a separate non-agent body. Renderer constants, body shader paths, proxy pipelines, and post reprojection counts should track seven role agents plus Self plus cursor, not the older five-role provisional slice.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12SoulAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12LifeAgent.hlsl","docs/hlsl-renderer.md","state/map.yaml","state/memory.json"],"source":"user role table correction"} -{"timestamp":"2026-05-11T22:29:04+01:00","topic":"per-body-proxy-indexing","lesson":"Per-body proxy shaders must not rely on DrawInstanced StartInstanceLocation reaching SV_InstanceID for body identity. Each body shader now declares a shader-local BODY_INDEX constant, and shared proxy VS/PS use that constant for AgentVisualGpu lookup, proxy rectangle placement, and raymarch selection. This keeps per-body shader files transform-locked to their own visual row.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12BodyCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12FaceAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12ImaginationAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12EyesAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12BodyAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12HandsAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12SoulAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12LifeAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12SelfBody.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12CursorBody.hlsl"],"source":"visible transform bug report"} -{"timestamp":"2026-05-11T22:32:12+01:00","topic":"canonical-agent-visual-order","lesson":"AgentVisualGpu row order is canonical and must match shader BODY_INDEX constants, body pipeline order, Grid brush indexing, and temporal reprojection: 0 Self, 1 Face, 2 Imagination, 3 Eyes, 4 Body, 5 Hands, 6 Soul, 7 Life, 8 Cursor. Roles-first buffer ordering breaks transforms even if each shader has its own file.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12BodyCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12SelfBody.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12FaceAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12ImaginationAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12EyesAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12BodyAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12HandsAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12SoulAgent.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12LifeAgent.hlsl"],"source":"visible transform bug report"} -{"timestamp":"2026-05-11T23:17:40+01:00","topic":"body-proxy-screen-space-convention","lesson":"Body proxy quads and body proxy ray construction must use the same screen-space Y convention as the fullscreen scene pass. Clip-space proxy center should use projected.y directly, and the proxy pixel shader must convert SV_Position top-left pixel coordinates to the bottom-left pixel coordinates expected by rayDirectionForPixel. If they disagree, bodies appear to swim in camera space instead of staying grounded in world space.","files":["src/Aquarium.Engine/Render/Shaders/D3D12BodyCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12BodyProxy.hlsli"],"source":"visible transform bug report"} -{"timestamp":"2026-05-11T23:23:04+01:00","topic":"cursor-hibiscus-anatomy","lesson":"The cursor hibiscus needs recognizable flower anatomy, not just three glossy petals. The cursor SDF now includes curled ruffled petals, a throat, a protruding staminal column with pollen beads, and a green calyx/contact stem, with a larger proxy bound to prevent clipping the expanded silhouette.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12CursorBody.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs"],"source":"visual reference comparison"} -{"timestamp":"2026-05-11T23:35:00+01:00","topic":"thin-structure-body-marching","lesson":"All role bodies are expected to carry thin visible structure, so conservative body SDF tracing is the shared default rather than a cursor-specific exception. Body proxy tracing now uses tighter hit epsilon, more steps, and smaller step scale through shared macros; faster tracing should only reappear through explicit LOD policy after it proves it preserves filaments, ribs, rings, petals, and other narrow organs.","files":["src/Aquarium.Engine/Render/Shaders/D3D12BodyProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12CursorBody.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli","state/memory.json"],"source":"user visual artifact review"} -{"timestamp":"2026-05-11T23:39:00+01:00","topic":"sheet-sdf-petals-and-guarded-marching","lesson":"Do not represent petals and other thin organs as fat ellipsoids with decorative displacement. The recursive lotus reference preserves delicate structure by using slab/intersection fields and scaling the distance estimate after its log-spherical mapping; Aquarium cursor petals now use thin clipped sheet SDFs, and the shared body marcher caps step length plus refines positive-to-negative sign crossings instead of trusting pseudo-distance composites blindly.","files":["src/Aquarium.Engine/Render/Shaders/D3D12BodyProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli","state/memory.json"],"source":"https://github.com/pac-dev/notes/blob/master/content/logspherical/recursive_lotus.glsl"} -{"timestamp":"2026-05-11T23:47:00+01:00","topic":"pseudo-distance-near-miss-hits","lesson":"The cursor stamen and angled petals disappeared because the body proxy marcher accepted abs(distance) < epsilon as a hit on a pseudo-distance composite. Rays that passed near a petal sheet could terminate before reaching the actual stamen or petal intersection. The proxy marcher now requires distance <= 0 entry, refines positive-to-negative brackets, and uses a larger step budget to survive capped steps across the proxy volume.","files":["src/Aquarium.Engine/Render/Shaders/D3D12BodyProxy.hlsli","state/memory.json"],"source":"user visual artifact review"} -{"timestamp":"2026-05-11T23:52:00+01:00","topic":"cursor-hibiscus-organ-primitives","lesson":"The cursor hibiscus shape should be built from organ-appropriate SDF primitives instead of ellipsoid paste. Petals now use upward-curving tapered sheets with lens footprints and tapered thickness, the staminal column uses a curved tapered tube, and the green contact anatomy uses a connected tapered stem plus calyx bulb so the stem visibly reaches the flower.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12CursorBody.hlsl","state/memory.json"],"source":"user visual artifact review"} -{"timestamp":"2026-05-11T23:59:00+01:00","topic":"cursor-hibiscus-reference-target","lesson":"The closer cursor objective is the pale pink five-petal hibiscus reference: broad translucent cupped petals, a folded central throat, a curved staminal column with side pollen filaments, and a green tapered calyx/stem ending at the XY contact point. The SDF now uses five tapered sheet petals, a simplified three-segment quadratic tube helper to keep shader compile time sane, side filament tubes, pollen bead spheres, and a curved tapered calyx core with sepals.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12CursorBody.hlsl","state/memory.json"],"source":"user reference images"} -{"timestamp":"2026-05-12T00:12:00+01:00","topic":"cursor-petal-single-formula","lesson":"The hibiscus cursor petal should not be assembled from piecewise vertical panels and horizontal blades. Model each petal from one longitudinal coordinate: radial displacement grows quadratically so the root starts vertical, height follows a smooth cubic center curve, width and thickness grow from thin root to broad distal blade, and decorative ruffles stay out until the core SDF is stable and cheap.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli","state/memory.json"],"source":"user visual/math review"} -{"timestamp":"2026-05-12T00:17:00+01:00","topic":"cursor-hibiscus-reset","lesson":"When the hibiscus cursor starts turning into SDF Jenga, reset the function around anatomical parameters instead of stapling on fixes. The current reset keeps five petals as one cheap graph-style ribbon formula each: u comes from height, radial displacement is quadratic so roots start vertical, width and thickness grow with u, and decorative trig/filament swarms are cut until the core form is stable and fast.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli","state/memory.json"],"source":"user architecture correction"} -{"timestamp":"2026-05-12T00:26:00+01:00","topic":"agent-sdf-form-discipline","lesson":"Carry the cursor hibiscus lesson into agent bodies: start every role SDF from a coherent anatomical/form model with a small set of parameters that explain the silhouette across views. Prefer one governing coordinate, profile, width, thickness, symmetry, and material-region model over stitched primitives. Add ornament only after the core form is readable, fast, and stable; fine veins, glitter, filaments, and state pulses should begin as shading or LOD-gated overlays, not traced geometry.","files":["state/memory.json","state/map.yaml"],"source":"cursor hibiscus iteration review"} -{"timestamp":"2026-05-12T00:34:00+01:00","topic":"shader-include-ownership","lesson":"Keep shader include ownership strict before role bodies multiply. D3D12SdfMath.hlsli should hold reusable SDF primitives and generic form helpers, not cursor-specific hibiscus anatomy. Body-specific SDF structure belongs in the owning body shader. Shared lighting equations belong in D3D12BodyCommon.hlsli as material-parameterized helpers so cursor, agents, and future bodies do not duplicate GGX/body-light loops.","files":["src/Aquarium.Engine/Render/Shaders/D3D12BodyCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12CursorBody.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli","state/memory.json"],"source":"user architecture correction"} -{"timestamp":"2026-05-12T00:51:00+01:00","topic":"body-distance-surface-shading-split","lesson":"Body SDF passes should be a bounded-cost machine: ray steps and normal samples evaluate only scalar bodyDistance; bodySurface is evaluated once after the hit is refined and returns the PBR material packet. Avoid second-pass SDF component scans such as cursorEmissionRadiance; material choice belongs in the hit surface packet and lighting belongs in shared material-parameterized functions.","files":["src/Aquarium.Engine/Render/Shaders/D3D12BodyCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12BodyProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12CursorBody.hlsl","state/memory.json","state/map.yaml"],"source":"user architecture correction"} -{"timestamp":"2026-05-12T01:04:00+01:00","topic":"body-surface-packet-minimalism","lesson":"Do not let diagnostic identity fields squat in BodySurface. The hot surface packet now carries only PBR material values. Distance belongs to bodyDistance and the marcher; field identity is emitted by the proxy for temporal ownership; role/material/LOD/cost ids and the common shadeRoleAgentBody router were cut because per-role shader files should own their own material decisions directly.","files":["src/Aquarium.Engine/Render/Shaders/D3D12BodyCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12BodyProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12AgentCharacters.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json","state/map.yaml"],"source":"user architecture correction"} -{"timestamp":"2026-05-12T01:58:00+01:00","topic":"temporal-event-lane-cut","lesson":"Dormant full-frame lanes are architectural debt, not preparedness. Aquarium had scene event color/metadata targets plus event history targets even though every producer wrote zero coverage. The event lane, dead AgentVisual LOD/index vector, dead reactive control channel, and one-field AgentSurface wrapper were cut; temporal resolve now carries only scene color, metadata, and coverage/step control history.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12BodyCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12BodyProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12AgentCharacters.hlsli","docs/hlsl-renderer.md","state/memory.json","state/map.yaml"],"source":"purification pass"} -{"timestamp":"2026-05-12T04:30:00+01:00","topic":"engine-client-boundary-vocabulary","lesson":"Aquarium.Engine and Aquarium.Engine.Contracts must speak renderer vocabulary, not Epiphany policy vocabulary. Engine contracts expose ViewFrame, height-field brushes, SDF objects, SDF lights, generic shader manifests, and generic proxy passes. Epiphany may call its own things grid, agents, bodies, or roles, but the engine only consumes declared rendering data. Enforce this with scripts/verify-boundaries.ps1 before every architectural pass.","files":["scripts/verify-boundaries.ps1","src/Aquarium.Engine.Contracts","src/Aquarium.Engine","src/Aquarium.Epiphany","state/memory.json","state/map.yaml"],"source":"engine-client extraction correction"} -{"timestamp":"2026-05-12T05:30:00+01:00","topic":"client-ui-composition-contract","lesson":"Keep the engine debug panel as engine-owned UI, but expose a separate AquariumUiDocument contract for client overlay panels. Clients compose controls through Vortice-free panel builders; Aquarium.Engine translates those declarations into its DirectWrite/Direct2D overlay and owns input dispatch. Do not let Epiphany depend on DebugUi internals.","files":["src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs","src/Aquarium.Engine/Render/Ui/DebugUi.cs","src/Aquarium.Engine/Render/DirectWriteOverlay.cs","src/Aquarium.Epiphany/AquariumRuntime.cs","state/memory.json"],"source":"client UI abstraction pass"} -{"timestamp":"2026-05-12T12:35:00+01:00","topic":"unified-debug-panel","lesson":"F2 should open one Aquarium debug panel, not separate engine and client windows. Client AquariumUiDocument panels are folded into the same tabbed debug surface, clients can register terminal commands through AquariumUiDocument.Command, and future debug UI should extend this shared composition surface instead of spawning parallel panels.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Ui/DebugUi.cs","src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs","src/Aquarium.Epiphany/AquariumRuntime.cs","state/memory.json","state/map.yaml"],"source":"debug UI consolidation pass"} -{"timestamp":"2026-05-12T13:00:00+01:00","topic":"debug-tab-chrome","lesson":"Debug tabs are navigation chrome, not document content. The unified F2 panel title is Debug, with a row of tab buttons directly below it and visible active highlighting. Future debug surfaces should add tabs through the same chrome path instead of creating fake Tabs sections or parallel panels.","files":["src/Aquarium.Engine/Render/Ui/DebugUi.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json"],"source":"user UI correction"} -{"timestamp":"2026-05-12T13:20:00+01:00","topic":"debug-text-box-control","lesson":"Long editable UI buffers need real text box controls, not row-value text fields. AquariumUiTextBox carries line count, return behavior, and optional submit action through the contract; DirectWrite debug UI renders it as a boxed editable region. Use row Text only for compact scalar strings.","files":["src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs","src/Aquarium.Engine/Render/Ui/DebugUi.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json"],"source":"debug UI improvement pass"} -{"timestamp":"2026-05-12T13:27:00+01:00","topic":"multiline-debug-terminal","lesson":"The debug terminal should be one multiline session surface: recent log lines plus the live prompt at the end. Typing updates only the trailing prompt, Enter submits that prompt and appends the command/output to the log. Avoid separate output readouts plus detached command rows for terminal UI.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Ui/DebugUi.cs","state/memory.json"],"source":"user terminal correction"} -{"timestamp":"2026-05-12T13:42:00+01:00","topic":"terminal-textbox-polish","lesson":"Terminal text boxes need terminal typography and prompt-safe editing. Bundle Ubuntu Sans Mono for DirectWrite monospace surfaces, let AquariumUiTextBox opt into monospace and bottom alignment, and guard empty trailing prompts so backspace cannot collapse the prompt sentinel and reclassify the log as command input.","files":["src/Aquarium.Engine/Assets/Fonts/UbuntuSansMono.ttf","src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs","src/Aquarium.Engine/Render/DirectWriteOverlay.cs","src/Aquarium.Engine/Render/Ui/DebugUi.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/memory.json"],"source":"user terminal polish correction"} -{"timestamp":"2026-05-12T13:55:00+01:00","topic":"terminal-surface-layout","lesson":"Terminal surfaces should not display ordinary text-box labels or fake corner carets. A terminal prompt is already the affordance. Use label-less text boxes for terminal sessions, use a near-aligned monospace text format, and bottom-align by drawing the terminal line list against the box bottom rather than relying on centered DirectWrite paragraph layout.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/DirectWriteOverlay.cs","src/Aquarium.Engine/Render/Ui/DebugUi.cs","state/evidence.jsonl"],"source":"user visual correction"} -{"timestamp":"2026-05-12T14:05:00+01:00","topic":"terminal-bottom-line-layout","lesson":"DirectWrite multiline layout can still make a terminal body feel vertically floating even when the containing bounds are bottom-biased. For terminal-style text boxes, draw visible lines individually from the bottom of the text bounds using explicit line height; do not rely on padded blank lines or paragraph layout for bottom alignment.","files":["src/Aquarium.Engine/Render/Ui/DebugUi.cs","state/evidence.jsonl"],"source":"user screenshot correction"} -{"timestamp":"2026-05-12T14:25:00+01:00","topic":"debug-text-editing-capture","lesson":"Debug text boxes need real editing ownership: persistent caret index, selection anchor, mouse placement, drag selection, arrow/Home/End movement, Backspace/Delete, selected-text replacement, and input capture while focused. When a text box owns the keyboard, host-level debug hotkeys and client camera controls must receive a non-interactive input snapshot instead of the live key/mouse state.","files":["src/Aquarium.Engine.Contracts/Input/InputState.cs","src/Aquarium.Engine/AquariumHost.cs","src/Aquarium.Engine/Platform/Win32Window.cs","src/Aquarium.Engine/Render/IAquariumRenderer.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Ui/DebugUi.cs","state/memory.json"],"source":"user text editing requirement"} -{"timestamp":"2026-05-12T14:35:00+01:00","topic":"directwrite-text-editing-metrics","lesson":"Do not position text-box caret or selection with guessed monospace character widths. Use DirectWrite text layout hit-test positions for the same font and layout used to draw text, cache those positions for mouse placement, and keep text boxes focus-only visually rather than filling like active buttons on click.","files":["src/Aquarium.Engine/Render/Ui/DebugUi.cs","state/evidence.jsonl"],"source":"user screenshot correction"} -{"timestamp":"2026-05-12T14:42:00+01:00","topic":"directwrite-text-editing-vertical-metrics","lesson":"Horizontal caret alignment is not enough. Caret height and selection top/bottom should also come from DirectWrite hit-test metrics for the active glyph run; using the UI line box makes editing visuals droop below the text even when x positions are correct.","files":["src/Aquarium.Engine/Render/Ui/DebugUi.cs","state/evidence.jsonl"],"source":"user screenshot correction"} -{"timestamp":"2026-05-12T14:50:00+01:00","topic":"text-edit-commit-state","lesson":"After a text box writes a new bound value, preserve caret and selection against the committed local value immediately. If edit state waits for the next read/sync cycle, the first typed character can leave stale caret state and subsequent input inserts at the wrong position, corrupting commands.","files":["src/Aquarium.Engine/Render/Ui/DebugUi.cs","state/evidence.jsonl"],"source":"terminal input corruption fix"} -{"timestamp":"2026-05-12T14:51:00+01:00","topic":"terminal-prompt-edit-boundary","lesson":"A terminal text box displays immutable log text plus a mutable prompt tail, so its editing model must clamp caret, selection, insertion, deletion, Home, and mouse placement to the prompt input region. Local text edits must clamp against the in-flight edited value, not the stale bound read value, or the first character on an empty prompt snaps the caret behind itself.","files":["src/Aquarium.Engine/Render/Ui/DebugUi.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/evidence.jsonl"],"source":"user terminal caret/backspace correction"} -{"timestamp":"2026-05-12T19:57:28+01:00","topic":"debug-dropdown-overlay-ownership","lesson":"Dropdown option lists are transient overlay panels, not row layout. Keep the field row's layout height constant, align the popup to the value field bounds, flip above the field when viewport space below is worse, scroll long lists inside the popup, and close the modal on outside click before other controls can react.","files":["src/Aquarium.Engine/Render/Ui/DebugUi.cs","state/evidence.jsonl"],"source":"user dropdown layout correction"} -{"timestamp":"2026-05-12T20:04:11+01:00","topic":"debug-ui-mouse-input-capture","lesson":"Renderer input capture must include both keyboard ownership and mouse ownership. If Debug UI consumes wheel or mouse interaction but the renderer only reports keyboard capture, the same wheel event leaks into client camera/runtime controls after the overlay handles it.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","state/evidence.jsonl"],"source":"user dropdown scroll capture correction"} -{"timestamp":"2026-05-12T21:28:22+01:00","topic":"single-solution-authority","lesson":"Keep one solution inventory for Aquarium. Maintaining both Aquarium.Engine.sln and Aquarium.Engine.slnx created duplicate project authority, Rider confusion, and verification races when both were built against shared obj/bin outputs. Aquarium.Engine.sln is the canonical solution for IDE and CLI work.","files":["Aquarium.Engine.sln","AGENTS.md","README.md","scripts/dev-watch.ps1","state/map.yaml","state/evidence.jsonl"],"source":"user solution authority cleanup"} -{"timestamp":"2026-05-12T23:08:00+01:00","topic":"synth-test-ownership","lesson":"Aquarium must not own synth reference truth. Engine tests may smoke-test the runtime synth host boundary, but synth correctness belongs in AquariumSynthCSharp so Aquarium can keep iterating while the synth library is under construction.","files":["tests/Aquarium.Engine.Tests/SynthPlaybackTests.cs","tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj","state/evidence.jsonl"],"source":"user questioned synth testing ownership"} -{"timestamp":"2026-05-13T00:26:00+01:00","topic":"synth-package-boundary","lesson":"Aquarium must not build against the live AquariumSynthCSharp project while a synth agent is mutating it. Consume AquariumSynth.Dsl as a pinned repo-local NuGet package and update that package only by deliberate version bump.","files":["NuGet.config","packages/AquariumSynth.Dsl.0.1.0-aquarium.1.nupkg","src/Aquarium.Engine/Aquarium.Engine.csproj","scripts/update-synth-package.ps1","state/map.yaml","state/memory.json","state/scratch.md","state/evidence.jsonl"],"source":"user asked whether synth-agent work can break Aquarium builds"} -{"timestamp":"2026-05-17T15:15:00+01:00","topic":"aquasynth-native-audio-ownership","lesson":"Aquarium should host completed synth products, not own AquaSynth parsing, Faust emission, native libfaust factory creation, render duration estimation, compile keys, DSP source artifacts, or sample-buffer rendering. Those responsibilities now live in AquaSynth.Faust through AquaSynthNativeCompiler; AquariumSynthHost keeps scheduling, debounce/status, cache playback, and WASAPI output.","files":["src/Aquarium.Engine/Audio/AquariumSynthHost.cs","src/Aquarium.Engine/Aquarium.Engine.csproj","scripts/update-synth-package.ps1","scripts/publish-win-x64.ps1","state/map.yaml","state/memory.json"],"source":"user asked to finish taking over Aquarium's current audio rendering ownership so the engine does not concern itself with synth internals"} -{"timestamp":"2026-05-17T15:45:00+01:00","topic":"aquasynth-package-split","lesson":"Aquarium consumes AquaSynth.Faust, not a catch-all AquaSynth.Dsl package. AquaSynth.Faust carries the runtime/toolchain surface and pulls AquaSynth.Core transitively for the built-in patch editor's parser/model/built-in script needs.","files":["src/Aquarium.Engine/Aquarium.Engine.csproj","packages/AquaSynth.Core.0.1.0-alpha.3.nupkg","packages/AquaSynth.Faust.0.1.0-alpha.3.nupkg","scripts/update-synth-package.ps1","scripts/publish-win-x64.ps1","state/map.yaml","state/memory.json","state/scratch.md"],"source":"user pointed out .Dsl no longer described the package and confirmed Aquarium still needs DSL through the Faust dependency"} -{"timestamp":"2026-05-18T10:35:00+01:00","topic":"aquasynth-render-session-boundary","lesson":"AquariumSynthHost does not deserve to hold a live AquaSynthRenderSession. AquaSynth.Faust owns live patch compilation through AquaSynthPatchCompiler; Aquarium owns only debounce, trigger scheduling, rendered-buffer caching, and WASAPI playback.","files":["src/Aquarium.Engine/Audio/AquariumSynthHost.cs","tests/Aquarium.Engine.Tests/SynthPlaybackTests.cs","src/Aquarium.Engine/Aquarium.Engine.csproj","packages/AquaSynth.Core.0.1.0-alpha.3.nupkg","packages/AquaSynth.Faust.0.1.0-alpha.3.nupkg"],"source":"user challenged the host's remaining Faust authority after AquaSynth already owned patch meaning and native render proof"} -{"timestamp":"2026-05-17T16:15:00+01:00","topic":"aquasynth-semver","lesson":"Aquarium pins AquaSynth packages on the `0.1.0-alpha.N` prerelease line. Keep AquaSynth package versions as normal SemVer prereleases; do not use repo-name suffixes such as `0.1.0-aquasynth.2`.","files":["src/Aquarium.Engine/Aquarium.Engine.csproj","packages/AquaSynth.Core.0.1.0-alpha.3.nupkg","packages/AquaSynth.Faust.0.1.0-alpha.3.nupkg","state/map.yaml"],"source":"user noted that 0.1.0-aquasynth.2 was an exciting new take on semantic versioning"} -{"timestamp":"2026-05-13T00:40:00+01:00","topic":"generic-sdf-field-ids","lesson":"Aquarium shared SDF code must not special-case Epiphany object identities. SDF field ids are generic base-plus-object-index metadata; Self, Cursor, and role meaning stay in Epiphany's object table and shaders, while temporal reprojection uses uploaded AquariumSdfObject current/previous centers for every SDF object.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","src/Aquarium.Epiphany/EpiphanySceneBuilder.cs","docs/epiphany-agent-sdf-visual-language.md","state/memory.json"]} -{"timestamp":"2026-05-13T01:05:00+01:00","topic":"sdf-metallic-roughness-pbr","lesson":"SDF surfaces now use the industry-standard metallic-roughness material language: baseColor, metallic, roughness, and emission. The shared shader derives dielectric F0, metal-tinted specular F0, non-metal diffuse color, direct Cook-Torrance GGX specular, Fresnel-gated Lambert diffuse, diffuse irradiance IBL, and roughness-mip PMREM specular from those fields.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli","src/Aquarium.Epiphany/Shaders","docs/epiphany-agent-sdf-visual-language.md","state/memory.json"],"source":"Khronos glTF 2.0 metallic-roughness material model; Google Filament material model notes"} -{"timestamp":"2026-05-13T01:45:00+01:00","topic":"imagination-topology-spec","lesson":"Imagination's visual spec needs topology, not just evocative nouns. The target is a luminous opal seed wrapped by broad translucent curling ribbon-sheets with traced raised rims, visible interior apertures, vertical fountain bias, sparse candidate filaments/sparks, and cool backlog shadow. Trefoil/tube curves may define rim paths, but tubes alone do not satisfy the petal form.","files":["docs/epiphany-agent-sdf-visual-language.md","state/memory.json"],"source":"user supplied imagegen reference and noted current output did not match the imagined impossible flower"} -{"timestamp":"2026-05-13T01:58:00+01:00","topic":"imagination-sheet-pair-sdf","lesson":"The compile-bounded Imagination implementation should model topology first: three mirrored sheet-pair SDF fields produce six broad ribbon sheets, while separate film/rim/tendril/spark/shadow distances preserve material classification for translucent petals, glowing raised rims, candidate filaments, and backlog shadow. This keeps the impossible-flower form legible without reverting to trefoil-only tubes or decorative polar fields.","files":["src/Aquarium.Epiphany/Shaders/D3D12ImaginationAgent.hlsl","state/memory.json","state/evidence.jsonl"],"source":"implementation pass after topology spec correction"} -{"timestamp":"2026-05-13T02:04:00+01:00","topic":"imagination-dead-code-cut","lesson":"User visual review caught dead implementation carryover: the polar-lobed Imagination seed was not in the spec, and the traced half-torus labeled shadow did not read as backlog shadow. Cut both instead of explaining them. Keep petal tips tapered through width/rim endpoints, avoid vertical rim columns, and only add shadow geometry when it has a readable visual contract.","files":["src/Aquarium.Epiphany/Shaders/D3D12ImaginationAgent.hlsl","state/memory.json","state/evidence.jsonl"],"source":"user screenshot correction"} -{"timestamp":"2026-05-13T02:08:00+01:00","topic":"imagination-continuous-ribbon-field","lesson":"The hibiscus cursor lesson applies to Imagination: use a continuous sheet parameterization when it can own the form. Replacing piecewise rim capsule chains with one pair-space field for film and raised edge distance removed straight posts, made the ribbon silhouette more coherent, and reduced headless reload time instead of adding compensating geometry.","files":["src/Aquarium.Epiphany/Shaders/D3D12ImaginationAgent.hlsl","state/memory.json","state/evidence.jsonl"],"source":"user challenged piecewise construction after visual review"} -{"timestamp":"2026-05-13T02:13:00+01:00","topic":"continuous-form-first-rule","lesson":"Carve this into local practice: when a spec describes a continuous visual, physical, or simulation form, start with continuous field math or a coherent parameterization that owns the form. Piecewise capsules, boxes, slabs, helper organs, adapters, and compensators are not acceptable lazy shortcuts; use them only when the form is actually piecewise or measured constraints force a documented cut.","files":["AGENTS.md","state/memory.json","state/evidence.jsonl"],"source":"user instruction after Imagination correction"} -{"timestamp":"2026-05-13T04:32:09+01:00","topic":"self-orbital-grammar","lesson":"Self's orrery form should arise from one compact spherical/log-shell coordinate grammar: stable radial strata crossed with continuous angular harmonic bands. Visible rails must use continuous direction-vector or harmonic fields, not raw atan2/fract longitude branch cuts; phase may rotate angular frames but must not animate radial zero crossings or grow rings from points. Do not rebuild Self as independent hoops, one-radius ornament layers, or repeated trigonometry piles.","files":["src/Aquarium.Epiphany/Shaders/D3D12SelfBody.hlsl","docs/epiphany-agent-sdf-visual-language.md","state/memory.json","state/evidence.jsonl"],"source":"consolidated Self iteration lessons"} -{"timestamp":"2026-05-13T04:32:10+01:00","topic":"self-body-material-contract","lesson":"Self's live body is a black void command core with sharp golden Fresnel, one gold core band, and nested PBR rail bands. Rails should be readable bands, not hairline emitters; bloom-driving rail emission rides a narrow inner-surface strip derived from the same shell/band field; gates are compact triple-band crossings, not pairwise shallow-intersection slabs. Literal loose eyes and dead diagnostic shapes do not belong in the contract.","files":["src/Aquarium.Epiphany/Shaders/D3D12SelfBody.hlsl","docs/epiphany-agent-sdf-visual-language.md","state/memory.json","state/evidence.jsonl"],"source":"consolidated Self visual review"} -{"timestamp":"2026-05-13T04:32:11+01:00","topic":"self-lighting-boundary","lesson":"Self may be the scene light, but visible Self surfaces must not add full primitive light radiance to themselves. Use the standard metallic-roughness PBR path for non-core surfaces, attenuate same-field direct lighting in shared PBR, and keep emission as controlled accents plus the custom void-core Fresnel. Diagnostic matte/flat material changes should be cut once the light-feedback source is isolated.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli","src/Aquarium.Epiphany/Shaders/D3D12SelfBody.hlsl","state/memory.json","state/evidence.jsonl"],"source":"consolidated Self lighting/firefly work"} -{"timestamp":"2026-05-13T04:41:09+01:00","topic":"temporal-jitter-specular-fireflies","lesson":"Projection jitter was disabled because an earlier implementation made the whole frame visibly wobble. Re-enable it as a small sub-half-pixel Halton sequence with previous-jitter tracking, give the resolver a narrow SDF hot-current path so validated history can damp transient specular fireflies without relaxing travel/field/normal/coverage validation, and attenuate bloom when resolved scene luminance is lower than the raw current spike so current-frame bloom does not bypass TAA.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","docs/hlsl-renderer.md","docs/tsr-inspired-taa-spec.md","state/memory.json","state/evidence.jsonl"],"source":"user asked to give TAA teeth for Self rail highlights"} -{"timestamp":"2026-05-13T04:51:17+01:00","topic":"bloom-prefilter-firefly-clamp","lesson":"If a specular firefly exists for only one frame, resolving the source pixel after bloom is too late: the current-frame bloom pyramid has already spread the spike to neighbors. Clamp unsupported single-pixel HDR spikes in the bloom prefilter against local neighborhood luminance, then let temporal resolve and bloom attenuation handle the remaining supported highlights.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","docs/hlsl-renderer.md","docs/tsr-inspired-taa-spec.md","state/memory.json","state/evidence.jsonl"],"source":"user screenshot showed one-frame glowy fireflies after temporal resolve change"} -{"timestamp":"2026-05-13T05:42:00+01:00","topic":"self-orthonormal-orbital-frame","lesson":"Self rail bands should not be oriented by three independently normalized phase vectors. That can make lattice axes collapse into a shared plane, causing bands to stack before diverging again. Build each shell frame as a real orthonormal basis from a precessing pole, projected tangent seed, cross-product tangent, and spin around the pole so all three axes keep participating.","files":["src/Aquarium.Epiphany/Shaders/D3D12SelfBody.hlsl","state/memory.json","state/evidence.jsonl"],"source":"user screenshot showed Self bands temporarily stacking along one plane"} -{"timestamp":"2026-05-13T06:02:00+01:00","topic":"agent-organ-spec-domain-elaboration","lesson":"Role body specs should name each organ's governing spatial domain before listing features. Face uses mouth-flow aperture coordinates; Eyes uses lens-hemisphere/tangent-disk evidence directions; Body uses superellipsoid surface stress paths; Hands uses prolate tool coordinates around workDirection; Soul uses constraint-plane half-spaces; Life uses a cardioid shell plus logarithmic spiral continuity grammar. This keeps future implementations from falling back to vague primitives and decorative attachments.","files":["docs/epiphany-agent-sdf-visual-language.md","state/evidence.jsonl"],"source":"user requested elaboration pass after Self and Imagination raised the visual standard"} -{"timestamp":"2026-05-13T17:40:00+01:00","topic":"soul-crystal-local-shading","lesson":"Soul's first real shader uses constraint-plane/octahedral domain math for the verdict crystal and keeps crystal refraction/inner oath light as Soul-local shading: PMREM-based pseudo-refraction, facet/risk/finding material regions, and an inner glow. Do not expand the shared SdfSurface material packet for transmission until the renderer owns an actual scene-refraction or thickness contract; fake generic material fields are just costumes for missing architecture.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"Soul implementation pass"} -{"timestamp":"2026-05-13T17:52:00+01:00","topic":"soul-geometry-before-material-tuning","lesson":"When Soul's octahedral constraint-plane geometry reads better than a later material experiment, restore the geometry instead of preserving churn. Make risk and finding features serve the crystal silhouette, then push crystal feel with stronger local caustic/rim/inner-light shading; if it still cannot read refractive, the next coherent step is a real renderer transmission/scene-sampling contract, not more ad hoc shared material flags.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"user visual correction after Soul crystal material pass"} -{"timestamp":"2026-05-13T18:08:00+01:00","topic":"soul-organic-cut-plane-domain","lesson":"Soul's durable domain is not a rigid octahedron. It is a living crystal governed by an organic family of cutting planes: silhouette, panes, grooves, finding edges, risk seams, fractures, and inner light should read from the same warped plane field so the object feels grown and faceted, not decorated with axis-aligned octahedral markings.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"user corrected the octahedral-domain interpretation using imagegen crystal reference"} -{"timestamp":"2026-05-13T18:18:00+01:00","topic":"soul-distance-material-authority","lesson":"Soul's raymarch distance must stay owned by the crystalline body silhouette. Cutting-plane seams, pane grooves, finding edges, and risk fractures are surface-domain material/light masks unless they intentionally change the silhouette; smooth-unioning those masks into the trace distance turns cracks into slabs and is SDF Jenga.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"user screenshot showed escaped seam planes and called out SDF Jenga risk"} -{"timestamp":"2026-05-13T18:34:00+01:00","topic":"soul-facet-relief-not-decals","lesson":"Soul finding seams need real facet-domain relief, not flat decals. Use the organic cutting-plane field to displace the body surface: active facets lift outward along their plane normals, strongest around the equator, while finding/risk/fracture seams cut into that relief. Keep this as bounded body displacement, not smooth-unioned freestanding seam geometry.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"user compared current Soul to reference art and identified extruded facets/fractured adjacent faces"} -{"timestamp":"2026-05-13T18:58:00+01:00","topic":"soul-seams-follow-facet-edges","lesson":"Soul seams must be measured against the facet edge graph, not raw cut-plane coordinates or free risk planes. Derive finding/risk/fracture distances from pairwise differences of the same offset face distances that define the crystal body; auxiliary risk planes may gate which edge segments light up, but they must not draw independent paths across facet interiors.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"user screenshot showed real relief seams drifting across faces instead of following facet edges"} -{"timestamp":"2026-05-13T19:12:00+01:00","topic":"soul-edge-graph-selectivity","lesson":"Soul facet-edge seams need both active-face gating and restraint. A pairwise face equality is not a crystal edge unless both faces are jointly dominant at the surface; otherwise inactive planes create a wireframe lattice across faces. Promote only a small role-bearing subset of the active edge graph, and keep seam masks narrow so relief reads as crisp cut crystal rather than gummy tubing.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"user screenshot showed all-over gummy seam lattice after edge snapping"} -{"timestamp":"2026-05-13T19:34:00+01:00","topic":"soul-crystal-domain-reset","lesson":"When Soul starts reading as warped packaging or a seam lattice, delete the clever cut-field tangle. The live model is a balanced faceted oath crystal: octahedral half-space silhouette, barycentric face coordinates for restrained relief, a small set of role-bearing seams, and local glass shading with transmission/reflection/inner oath light. Expressiveness belongs in face-domain relief and material, not in uncontrolled silhouette ownership.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"user compared Soul against reference art and called the current code a lesson rather than sacred"} -{"timestamp":"2026-05-13T19:45:00+01:00","topic":"soul-facet-normal-authority","lesson":"Soul must shade like cut crystal, not thermoformed plastic. If relief participates in ray distance, do not let the finite-difference relief normal dominate broad facets; shade from the governing facet normal and blend the traced normal only near cuts. Transmission should support dark glass depth and inner oath light, not wash every face into milky white.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"user screenshot showed Soul still reading as vacuum-formed packaging after domain reset"} -{"timestamp":"2026-05-13T20:00:00+01:00","topic":"soul-plane-intersection-crystal","lesson":"Soul seams are not unreasonable as geometry: build the crystal from explicit signed half-space planes, derive edges from adjacent active plane intersections, then extrude face interiors and cut narrow V-grooves on selected edge chains. Auxiliary gates may choose which edges glow, but the edge itself must come from the plane intersection graph. Broad shading uses the active plane normal; cut normals are secondary.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"user asked for organic plane intersections with extruded faces and glowing groove centers"} -{"timestamp":"2026-05-13T20:18:00+01:00","topic":"soul-organic-plane-family","lesson":"Soul's plane-intersection crystal should not default back to symmetric octahedral sign pairs. Keep the half-space/active-edge architecture, but use an irregular family of constraint planes with varied offsets plus a few smaller trimming planes so the crystal reads as a living verdict object instead of an octahedron with minor perturbations.","files":["src/Aquarium.Epiphany/Shaders/D3D12SoulAgent.hlsl","state/evidence.jsonl"],"source":"user noted the plane-intersection model was right but the cutting planes still looked too octahedral"} -{"timestamp":"2026-05-13T20:56:00+01:00","topic":"isolated-agent-preview-loop","lesson":"Agent SDF iteration needs a renderer-owned visual feedback loop. Use the real D3D12 renderer to render one selected Epiphany SDF subject across several isolated camera views, then save final-frame PNGs for reference-art comparison. Preview-only isolation belongs in the preview render plan/shader, not in regular scene frame controls; do not duplicate SDF shader logic in a separate toy renderer.","files":["src/Aquarium.Epiphany.AgentPreview/Program.cs","src/Aquarium.Epiphany.AgentPreview/Shaders/D3D12AgentPreviewScene.hlsl","scripts/render-agent-preview.ps1","src/Aquarium.Engine/Render/D3D12Renderer.cs","state/map.yaml","state/evidence.jsonl"],"source":"user requested self-directed visual iteration, then caught preview isolation leaking into the normal client"} -{"timestamp":"2026-05-14T01:50:00+01:00","topic":"life-shell-domain","lesson":"Life reads as a nautilus only when the shell footprint, aperture, and ornament share one log-polar grammar. A plain ellipsoid volume with spiral material masks reads as wallpaper; a raw spiral-band volume tears the form apart. Use the log-polar footprint for the silhouette, round it into depth, and let ribs, seam glow, cracks, bowl, ember, and rim pearls sample that same domain.","files":["src/Aquarium.Epiphany/Shaders/D3D12LifeAgent.hlsl","state/life-agent-sdf-notes.md","state/map.yaml","state/evidence.jsonl"],"source":"self-directed Life SDF iteration against imagegen reference and user build screenshots"} -{"timestamp":"2026-05-14T02:55:00+01:00","topic":"life-no-detached-ornament","lesson":"Life's nautilus shell must be one connected shell domain. Detached hoops, bead trails, and separate ember spheres are a sign that ornament escaped the governing field. The aperture lip is the shell's opened edge; pearls must be relief/material on that lip field, and inner light should be chamber shading, not freestanding geometry.","files":["src/Aquarium.Epiphany/Shaders/D3D12LifeAgent.hlsl","state/life-agent-sdf-notes.md","state/evidence.jsonl"],"source":"user called out disconnected elements as lazy spatial-domain construction"} -{"timestamp":"2026-05-14T04:10:00+01:00","topic":"life-aperture-authority","lesson":"Life's aperture is not a boolean cut face. Render it as a concave inner shell surface integrated into the same log-polar/aperture domain, with the nacre lip owning the boundary and the warm chamber sitting behind it. If chamber material has priority over lip material, the shell reads as a flat sliced object.","files":["src/Aquarium.Epiphany/Shaders/D3D12LifeAgent.hlsl","state/life-agent-sdf-notes.md","state/evidence.jsonl"],"source":"user build screenshots showed the aperture as a flat segmented golden cut"} -{"timestamp":"2026-05-14T04:55:00+01:00","topic":"life-swept-whorl-field","lesson":"Life must not preserve the ellipsoid-plus-aperture lineage. Build the shell from a swept whorl field: log-polar phase defines the growing spiral sweep, radial growth thickens the tube until whorls overlap into a continuous mass, and lip/ribs/cracks/pearls/chamber light are masks on that same domain. A welded disc or separate cup is a failed model, not a feature to polish.","files":["src/Aquarium.Epiphany/Shaders/D3D12LifeAgent.hlsl","state/life-agent-sdf-notes.md","state/evidence.jsonl"],"source":"user supplied supershape shell reference and called out failure enshrinement"} -{"timestamp":"2026-05-14T05:55:00+01:00","topic":"life-nautilus-source-port","lesson":"For Life, the durable model is the Nautilus.glsl logarithmic shell solve: find the nearest exponential spiral boundary in cylindrical space, use its u/v/w section coordinates for wall thickness, septa, ribs, aperture/cut, pearls, cracks, and materials. A loose phase field plus welded opening is not a coherent shell."} -{"timestamp":"2026-05-14T13:38:00+01:00","topic":"life-spec-over-reference-port","lesson":"Do not recreate a reference shader when the task is to learn its spatial-domain mapping. For Life, Nautilus.glsl is a coordinate lesson; the spec authority is a protective revolved seed/cardioid shell with a visible ember, logarithmic seam, and memory beads sharing one spiral domain."} -{"timestamp":"2026-05-14T14:38:00+01:00","topic":"life-shell-authority","lesson":"Life's shell silhouette must be a filled protective mass; letting the logarithmic spiral own body distance creates hollow coils, fins, or mechanical mouths. Use the spiral domain for raised ribs, beads, seam, and scar material only. Check front plus oblique previews against the concept before accepting a pass."} -{"timestamp":"2026-05-14T15:32:00+01:00","topic":"life-balanced-whorl-domain","lesson":"Life needs both sides of the nautilus grammar: a log-spiral whorl solve must physically shape the shell, but it cannot be the only body authority or the form collapses into a hollow C-shell. Union the whorl with a smaller same-domain backing mass, then derive aperture lip, chamber gold, ember reveal, raised ribs, and pearl beads from the shared spiral/aperture fields.","files":["src/Aquarium.Epiphany/Shaders/D3D12LifeAgent.hlsl","state/life-agent-sdf-notes.md","state/evidence.jsonl"],"source":"user rejected the egg lineage and required repeated restart until the spiral shell manifests as geometry"} -{"timestamp":"2026-05-14T16:31:00+01:00","topic":"life-curve-first-build","lesson":"When rebuilding Life, do not start by tuning the full organ. First make the log-spiral domain read as a naked curve: ember at the core, roughly two revolutions, and the wide mouth-side lip termination. Only after that curve reads should shell inflation, aperture carving, ember reveal, ribs, and pearl beads be layered back on the same solved domain.","files":["src/Aquarium.Epiphany/Shaders/D3D12LifeAgent.hlsl","state/life-agent-sdf-notes.md","state/evidence.jsonl"],"source":"user corrected the iteration process: build the log spiral one step at a time instead of doing everything at once"} -{"lesson":"Shader hot reload edits must update the running process slot Render/Shaders files so D3D12Renderer can rebuild pipelines from its existing shader source root. Client assembly live reload does not change renderer shaderSourceRoot, so treating .hlsl/.hlsli edits as assembly reloads leaves the renderer watching stale slot files.","timestamp":"2026-05-15T17:48:35.6220956+01:00","files":["scripts/dev-watch.ps1","src/Aquarium.Engine/Render/D3D12Renderer.cs"],"topic":"shader-hot-reload-slot-transport"} -{"timestamp":"2026-05-17T23:28:00+01:00","topic":"non-epiphany-demo-client","lesson":"A reusable Aquarium engine boundary needs a real non-Epiphany client, not only a minimal smoke sample. Zyphos exercises the same host, reload transport, UI, bloom, and SDF proxy path with its own planetary scene and shader domain, while dev-reload/dev-watch accept -ClientProject so client selection stays tooling-owned instead of hardcoded Epiphany lore.","files":["src/Aquarium.Zyphos/Aquarium.Zyphos.csproj","src/Aquarium.Zyphos/ZyphosRuntime.cs","scripts/dev-reload.ps1","scripts/dev-watch.ps1","README.md"],"source":"user asked for a real planetary-scale demo named Zyphos to support the Aquarium/Epiphany split"} -{"timestamp":"2026-05-17T23:58:00+01:00","topic":"zyphos-eusocial-sync","lesson":"Zyphos simulates the neighboring Eusocial Interbeing setting, but canon authority stays in the vault. Aquarium may record render constraints and demo questions in docs/zyphos-eusocial-sync.md; worldbuilding answers should flow through the vault's Zyphos Simulation Brief before shader or terrain choices become setting claims.","files":["docs/zyphos-eusocial-sync.md","state/map.yaml","state/scratch.md","E:\\Projects\\Eusocial Interbeing\\Eusocial Interbeing\\World\\Zyphos Simulation Brief.md"],"source":"user asked to start a conversation with the Eusocial Interbeing neighbor repo for Zyphos worldbuilding"} - -{"timestamp":"2026-05-17T23:32:49+01:00","topic":"cube-sphere-fractal-brush-research","lesson":"Planetary terrain should use a cube-sphere/QSC-family six-face quadtree domain instead of lat-long; projection candidates should be measured rather than assumed, with tangent, fifth-order odd polynomial, and COBE/QSC-style bivariate warps as the first comparison set. Multiscale terrain and agent/body detail should converge on bounded IFS brush grammars with compact-support anisotropic shaped Gaussian-style envelopes, borrowing covariance/binning/LOD discipline from EWA and 3D Gaussian splatting without importing unbounded Gaussian cost or radiance-field machinery by default.","files":["research/rendering/cube-sphere-fractal-brushes.md","state/map.yaml","state/memory.json","state/scratch.md"],"sources":["https://proj.org/en/stable/operations/projections/qsc.html","https://ntrs.nasa.gov/citations/19810002572","https://jcgt.org/published/0007/02/01/paper.pdf","https://arxiv.org/abs/2308.04079","https://experts.illinois.edu/en/publications/sphere-tracing-a-geometric-method-for-the-antialiased-ray-tracing/","https://vcg.seas.harvard.edu/publications/20011001-ewa-volume-splatting"]} -{"timestamp":"2026-05-17T23:48:00+01:00","topic":"vibegeometry-ifs-csg-dsl-distillation","lesson":"VibeGeometry's spatial-mapping work says Aquarium's IFS brush DSL should emit semantic claims and preserve an ownership tree before backend lowering. The useful CSG-tree pattern is grammar/rules -> semantic solid/void/material claims with frames/tags/seeds/captures -> boolean ownership tree with union/subtract/common and node bounds -> flattened brush tables, SDF shader code, splat batches, or offline summaries as compiled verdicts. Local frames, named fields, baton outputs, scatter layers, authoring handles, deterministic variation, and demand frontiers should be first-class; anonymous brush bags and early shader flattening would destroy the meaning needed for project-wide terrain and agent-body migration.","files":["research/rendering/cube-sphere-fractal-brushes.md","state/map.yaml","state/memory.json","state/scratch.md"],"sources":["E:\\Projects\\VibeGeometry\\docs\\research\\procedural-doctrine.md","E:\\Projects\\VibeGeometry\\docs\\research\\dream-machine-grammar.md","E:\\Projects\\VibeGeometry\\docs\\research\\realtime-csg-doctrine.md","E:\\Projects\\VibeGeometry\\crates\\vg_grammar\\src","E:\\Projects\\VibeGeometry\\crates\\vg_csg\\src\\tree.rs","E:\\Projects\\VibeGeometry\\crates\\vg_csg\\src\\frontier.rs"]} -{"timestamp":"2026-05-18T00:05:00+01:00","topic":"ifs-lod-contribution-cache","lesson":"Aquarium's fractal brush LOD should choose a stable hierarchy cut from cached node summaries, not score every leaf every frame. Use clipmap-style nested caches for terrain fields, Nanite-style projected-error cuts for form hierarchy, and Gaussian/octree-style projected anisotropic footprint scoring for brush envelopes. Each IFS node should cache bounds, max form/material error, coverage or gradient bounds, estimated cost, previous contribution score, residency state, and summary/child payload handles; parent summaries must remain renderable fallbacks while child payloads stream or fade in. Fade payload contribution, not signed-distance safety, and require debug views for projected error, score, selected depth, residency, fade, and cost before recursive detail grows.","files":["research/rendering/cube-sphere-fractal-brushes.md","state/map.yaml","state/memory.json","state/scratch.md"],"sources":["https://hhoppe.com/proj/gpugcm/","https://hhoppe.com/geomclipmap.pdf","https://hhoppe.com/gpugcm.pdf","https://advances.realtimerendering.com/s2021/Karis_Nanite_SIGGRAPH_Advances_2021_final.pdf","https://arxiv.org/abs/2403.17898"]} -{"timestamp":"2026-05-18T00:14:00+01:00","topic":"ifs-lod-online-estimator","lesson":"The IFS contribution cache must refresh weights probabilistically under a per-frame update budget, not recompute every branch or greedily update only current winners. Treat node scores as online estimates with mean contribution, variance/uncertainty, sample count, sample age, confidence, and decay; visible, near-threshold, stale, high-uncertainty, and exploratory nodes must all retain nonzero update probability so the cache converges instead of freezing wrong beliefs. A later learned predictor can rank expected contribution, uncertainty, and update priority from projected footprint, view state, history, cost, and occasional high-quality probes, but conservative node summaries remain the non-negotiable safety authority for SDF marching and visibility.","files":["research/rendering/cube-sphere-fractal-brushes.md","state/map.yaml","state/memory.json","state/scratch.md"],"source":"user clarified that contribution weights need probabilistic per-frame updates and convergence, entering machine-learning territory for maximum fidelity"} -{"timestamp":"2026-05-18T00:32:00+01:00","topic":"fractal-brush-architecture-plan","lesson":"The research is now consolidated into an architecture: client intent feeds domain roots, semantic IFS brush grammar, an ownership tree, node summaries, a contribution cache/residency scheduler, backend packets, renderer passes, and debug/evidence. The design explicitly trades CPU scheduling, RAM summaries/estimator state, SSD payload pages/probe history, and GPU selected-cut evaluation. Its job-interview-grade credibility comes from module boundaries and test seams: contracts, pure CPU fractal core, D3D12 backend, client adapters, deterministic mocks for clocks/random/probes/payload stores/budgets/debug sinks, shader parity tests, and performance fixtures. The first implementation slice is cube-face projection harness, shaped 2D brush envelope, semantic claim/tree structs, flattening to the current height brush pass, and debug overlays before recursive detail is allowed to expand.","files":["research/rendering/fractal-brush-architecture-plan.md","research/rendering/cube-sphere-fractal-brushes.md","state/map.yaml","state/memory.json","state/scratch.md"],"source":"user asked to consolidate the research into an architecture plan and then clarified that interview-grade means maintainable modularity tied to extensive unit testing and mock boundaries"} -{"timestamp":"2026-05-18T01:05:00+01:00","topic":"fractal-brush-implementation-roadmap","lesson":"The fractal brush architecture now has an actionable execution roadmap separate from the architecture essay. The roadmap names module targets, mock seams, phase-by-phase tasks, tests, exit gates, and cut lines. The first work packet is intentionally small: create Aquarium.Engine.Fractal plus tests, add cube-face/tile key types, implement identity and tangent projection candidates, add an area distortion sampler, face-edge tests, and a projection report before any recursive detail, streaming, or learned scoring work begins.","files":["research/rendering/fractal-brush-implementation-roadmap.md","state/map.yaml","state/memory.json","state/scratch.md"],"source":"user asked whether an actionable roadmap existed and requested one if not"} -{"timestamp":"2026-05-18T02:46:00+01:00","topic":"fractal-cube-sphere-projection-default","lesson":"The first executable fractal slice chooses tangent cube-sphere projection as the initial default over direct normalize projection. Both are seam-compatible with the shared cube-face orientation, but the checked sampler at 16x16 per face reports tangent mean absolute relative area error around 0.076 and RMS around 0.089 versus normalize mean absolute relative area error around 0.316 and RMS around 0.378. Keep the projection harness as the authority before adding polynomial or QSC candidates.","files":["src/Aquarium.Engine.Fractal/Projection/TangentCubeSphereProjection.cs","src/Aquarium.Engine.Fractal/Projection/ProjectionDistortionSampler.cs","research/rendering/fractal-projection-report.md","tests/Aquarium.Engine.Fractal.Tests/ProjectionTests.cs"],"source":"first fractal implementation slice measured cube-sphere projection distortion and committed the report as a test-pinned artifact"} -{"timestamp":"2026-05-18T03:04:00+01:00","topic":"fractal-brush-envelope-reference","lesson":"The shaped 2D brush envelope now has a pure CPU reference before renderer integration. `FractalBrushEnvelope2D` owns compact elliptical support, anisotropic radii, rotation, truncated Gaussian-style falloff, shape power, conservative axis-aligned bounds, and a packed packet row. Future HLSL and height-field lowering should match this evaluator instead of redefining envelope semantics in shader code.","files":["src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs","src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2DPacket.cs","tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"second fractal implementation slice established the shaped brush envelope math and support tests"} -{"timestamp":"2026-05-18T03:31:00+01:00","topic":"height-field-shaped-envelope-lowering","lesson":"The live height-field brush contract now carries shaped-envelope fields without breaking legacy circular brush callers: Radius remains X radius and support fallback, RadiusY opts into anisotropy, RotationRadians rotates the local ellipse, EnvelopeFalloff switches the renderer from legacy power pulse to compact Gaussian-style support, and Power becomes the shaped envelope exponent in that mode. The D3D12 height-field shader and Epiphany CPU height evaluator now share the same compact-envelope formula; keep future terrain brush lowering on this path until semantic claims replace direct brush authoring.","files":["src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine/Render/Shaders/D3D12HeightField.hlsl","src/Aquarium.Engine/Render/Features/D3D12HeightFieldBrushConstants.cs","src/Aquarium.Epiphany/EpiphanySceneBuilder.cs","tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs"],"source":"third fractal implementation slice lowered shaped envelope fields into the existing height-field brush path while preserving old circular brush defaults"} -{"timestamp":"2026-05-18T03:55:00+01:00","topic":"fractal-semantic-contracts-first-slice","lesson":"The fractal system now has portable semantic rows before backend lowering: stable keys, domains, brush claims, operation nodes, summaries, contribution state, and selected-cut rows live in contracts, while the pure fractal core owns deterministic cube-tile grammar keys and a flat-union ownership tree builder. This is deliberately not a full CSG kernel yet; it is the first authority boundary that keeps authored claims visible before renderer packets flatten them.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Grammar/FractalStableKeyBuilder.cs","src/Aquarium.Engine.Fractal/Grammar/FractalOwnershipTreeBuilder.cs","tests/Aquarium.Engine.Fractal.Tests/FractalGrammarContractTests.cs"],"source":"fourth fractal implementation slice established semantic claim and ownership-tree contract rows"} -{"timestamp":"2026-05-18T02:36:48+01:00","topic":"face-realtime-voice-first-slice","lesson":"Aquarium's first Face voice slice keeps ownership narrow: the engine owns a generic queued PCM playback lane, while Epiphany owns a native Face realtime session controller and persists only loopback URI, thread id, voice, and prompt in CultCache live state. The current transport is explicitly a Codex app-server WebSocket JSON-RPC compatibility edge for text input and streamed audio output, not full microphone/WebRTC capture yet. Speech remains an ephemeral Face surface and must not mutate durable memory, evidence, project state, or code authority automatically.","files":["src/Aquarium.Engine.Contracts/Audio/AquariumAudio.cs","src/Aquarium.Engine.Contracts/AquariumRuntimeContracts.cs","src/Aquarium.Engine/Audio/AquariumSynthHost.cs","src/Aquarium.Epiphany/Voice/RealtimeFaceVoiceSession.cs","src/Aquarium.Epiphany/AquariumRuntime.cs","src/Aquarium.Epiphany/State/AquariumLiveState.cs","state/map.yaml"],"source":"user asked to start Aquarium-Engine work on Codex realtime voice for talking to Faces inside Aquarium"} -{"timestamp":"2026-05-18T04:07:00+01:00","topic":"fractal-height-claim-lowering","lesson":"Semantic height claims now lower into the live shaped height-field brush contract through `FractalHeightBrushCompiler`. This keeps the current renderer path useful without making the renderer own grammar semantics: claims remain authored meaning, height brushes remain backend output, and non-height payloads fail fast instead of sneaking through a height-only adapter.","files":["src/Aquarium.Engine.Fractal/Brushes/FractalHeightBrushCompiler.cs","tests/Aquarium.Engine.Fractal.Tests/FractalHeightBrushCompilerTests.cs","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"fifth fractal implementation slice added the first semantic-claim-to-renderer-packet lowering path"} -{"timestamp":"2026-05-18T04:22:00+01:00","topic":"fractal-node-summary-first-slice","lesson":"Flat semantic ownership trees now produce conservative node summaries. The first summary builder carries node bounds, sum-of-absolute height amplitude as max height error, a material-delta placeholder, estimated claim cost, and descendant count. This is intentionally conservative rather than clever, giving future LOD/cache work a renderable parent fallback before child refinement or eviction exists.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalSummaryBuilder.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSummaryBuilderTests.cs","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"sixth fractal implementation slice established parent summary rows for semantic brush trees"} -{"timestamp":"2026-05-18T04:36:00+01:00","topic":"fractal-contribution-score-first-slice","lesson":"Contribution scoring now has a stable-keyed state table and a projected-error scorer. The first score is intentionally simple: conservative height error times projected pixels per world unit divided by estimated node cost. This gives LOD selection a deterministic, testable pressure signal before hysteresis, selected cuts, residency, or online estimation are layered in.","files":["src/Aquarium.Engine.Fractal/Lod/FractalContributionTable.cs","src/Aquarium.Engine.Fractal/Lod/FractalProjectedErrorScorer.cs","tests/Aquarium.Engine.Fractal.Tests/FractalContributionTests.cs"],"source":"seventh fractal implementation slice started the LOD contribution cache with deterministic scoring tests"} -{"timestamp":"2026-05-18T04:50:00+01:00","topic":"fractal-selected-cut-first-slice","lesson":"Projected contribution scores now compile into budgeted selected-cut rows. The first builder sorts summaries by score, clamps against estimated cost, emits fade weights, and requests children only when score crosses a threshold. This gives later residency and stochastic estimation a small deterministic target instead of mixing traversal policy into renderer code.","files":["src/Aquarium.Engine.Fractal/Lod/FractalSelectedCutBuilder.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSelectedCutBuilderTests.cs","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"eighth fractal implementation slice added selected-cut planning under a simple cost budget"} -{"timestamp":"2026-05-18T05:06:00+01:00","topic":"fractal-stochastic-cache-first-slice","lesson":"The contribution cache now has online estimator updates and a stochastic update scheduler. Estimator state updates mean, variance, confidence, sample count, sample age, and residency; scheduler probability keeps baseline exploration, adds pressure for visible, near-threshold, stale, uncertain, and low-confidence nodes, and remains deterministic under `IFractalRandom` for tests. This is the first bounded convergence mechanism before learned scoring is allowed anywhere near the renderer.","files":["src/Aquarium.Engine.Fractal/Lod/FractalContributionEstimator.cs","src/Aquarium.Engine.Fractal/Lod/FractalStochasticUpdateScheduler.cs","tests/Aquarium.Engine.Fractal.Tests/FractalStochasticUpdateTests.cs"],"source":"ninth fractal implementation slice added probabilistic contribution updates with deterministic mock boundaries"} -{"timestamp":"2026-05-18T05:20:00+01:00","topic":"fractal-residency-simulation-first-slice","lesson":"Selected cuts now pass through a residency planner with an `IFractalPayloadStore` mock boundary. Resident nodes render directly; missing nodes render their parent summary fallback and enqueue payload requests only when the selected cut asks for children. This keeps frame traversal nonblocking and makes SSD/GPU residency a replaceable resource policy instead of hidden renderer state.","files":["src/Aquarium.Engine.Fractal/Lod/IFractalPayloadStore.cs","src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs","tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"tenth fractal implementation slice simulated missing/resident payload behavior before real streaming"} -{"timestamp":"2026-05-18T05:31:00+01:00","topic":"fractal-pipeline-fixture","lesson":"The first fractal architecture spine now composes end to end in a test fixture: cube tile stable key -> semantic domain/claim -> ownership tree -> conservative summary -> selected cut -> residency fallback/request -> shaped height brush compiler. Keep extending this fixture as the interview-grade proof that module boundaries are real and not prose taped to unrelated helpers.","files":["tests/Aquarium.Engine.Fractal.Tests/FractalPipelineFixtureTests.cs"],"source":"eleventh fractal implementation slice added an end-to-end composition test for the new module network"} -{"timestamp":"2026-05-18T05:49:00+01:00","topic":"fractal-dsl-first-slice","lesson":"Aquarium now has a first line-oriented fractal DSL that compiles into semantic ownership trees instead of renderer packets. The DSL declares a cube tile domain, direct shaped `height` claims, and recursive `ifs` emitters with deterministic seeded branching. Keep this syntax small until Zyphos proves it visually; the language authority is semantic claims, not shader-side brush bags.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs","tests/Aquarium.Engine.Fractal.Tests/FractalDslCompilerTests.cs","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"user explicitly wanted to express a fractal world in Aquarium's own DSL and see it rendered"} -{"timestamp":"2026-05-18T06:04:00+01:00","topic":"zyphos-fractal-dsl-render-proof","lesson":"Zyphos now renders its height field from Aquarium's fractal DSL instead of a hand-authored circular brush. `ZyphosFractalTerrain` owns the demo grammar, compiles it through `FractalDslCompiler` into a semantic ownership tree, and lowers claims to shaped height brushes through `FractalHeightBrushCompiler`. This is the first visible proof path for authoring a fractal world in Aquarium's own DSL and seeing it inside the engine.","files":["src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/ZyphosSceneBuilder.cs","src/Aquarium.Zyphos/ZyphosRuntime.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs"],"source":"user emphasized wanting to express a fractal world in the DSL and see it rendered in engine"} -{"timestamp":"2026-05-18T06:18:00+01:00","topic":"fractal-debug-dump","lesson":"Fractal worlds now have a text debug dump that reports domain, nodes, claims, summaries, and selected cuts. Zyphos exposes this through the `zyphos-fractal` command so the rendered DSL terrain can be inspected as authored semantic rows and LOD decisions instead of inferred from pixels alone.","files":["src/Aquarium.Engine.Fractal/Debug/FractalDebugDump.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/ZyphosRuntime.cs","tests/Aquarium.Engine.Fractal.Tests/FractalDebugDumpTests.cs"],"source":"observability pass after wiring Zyphos to the fractal DSL renderer path"} -{"timestamp":"2026-05-18T06:29:00+01:00","topic":"zyphos-height-brush-table-budget","lesson":"Zyphos' first DSL terrain grammar must currently emit no more than eight height brushes because `D3D12HeightFieldBrushConstants.MaxBrushCount` is still 8. Do not let the demo silently author more claims than the renderer draws; either keep the visible grammar within the fixed table or make the height brush table dynamic before increasing recursive density.","files":["src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","src/Aquarium.Engine/Render/Features/D3D12HeightFieldBrushConstants.cs"],"source":"runtime proof pass noticed the DSL emitted 12 claims while the current height brush constant table renders only 8"} -{"timestamp":"2026-05-18T06:43:00+01:00","topic":"height-brush-table-sixteen","lesson":"The fixed D3D12 height-field brush table now carries 16 brushes, so Zyphos can render its 12-claim DSL terrain without silent truncation. This is still a bounded interim table, not the final streaming brush backend; before raising recursive density further, move height brush packets to a structured buffer or selected-cut page stream.","files":["src/Aquarium.Engine/Render/Features/D3D12HeightFieldBrushConstants.cs","src/Aquarium.Engine/Render/Shaders/D3D12HeightField.hlsl","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs"],"source":"follow-up after detecting the fixed eight-brush table clipped the first Zyphos DSL terrain"} -{"timestamp":"2026-05-18T06:58:00+01:00","topic":"aquageo-world-patch-files","lesson":"Aquarium fractal world DSL patches should be authored as `.aquageo` content files, copied into the client output, and loaded from disk at runtime. Zyphos' first terrain proof now loads `Worlds/zyphos-first-fractal-terrain.aquageo`; do not keep demo grammars embedded as fallback strings because that hides asset pipeline failures.","files":["src/Aquarium.Zyphos/Worlds/zyphos-first-fractal-terrain.aquageo","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/Aquarium.Zyphos.csproj","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs"],"source":"user asked to load the world DSL patch via file and call it .aquageo"} -{"timestamp":"2026-05-18T07:16:00+01:00","topic":"zyphos-nested-domains-and-umbros-authority","lesson":"Zyphos' `.aquageo` patch now declares solar, orbital, planetary, and lat/long domains before terrain tiles, giving fractal DSL nodes explicit nested reference frames. The Zyphos/Umbros binary constants live in `ZyphosUmbrosSystem`: Umbros is a fixed-sky 0.9-radius twin at 8 Zyphos radii, while the dim primary star phase moves through the Zyphos-local frame for first-pass eclipse cadence. Do not reintroduce moon language or hidden orbital constants in shader files.","files":["src/Aquarium.Zyphos/Worlds/zyphos-first-fractal-terrain.aquageo","src/Aquarium.Zyphos/ZyphosUmbrosSystem.cs","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","src/Aquarium.Zyphos/Shaders/D3D12ZyphosUmbros.hlsl","tests/Aquarium.Engine.Fractal.Tests/ZyphosUmbrosSystemTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs"],"source":"user asked to express nested solar/orbital/planetary/lat-long domains and verify Zyphos/Umbros/parent-star modeling against worldbuilding docs"} -{"timestamp":"2026-05-18T07:31:00+01:00","topic":"fractal-domain-graph-validation","lesson":"Nested fractal domains are now validated by `FractalDomainGraph`, which owns duplicate-key checks, parent existence, cycle detection, and root-to-leaf path queries. Keep domain topology in this grammar-layer boundary until real transform math exists; do not scatter parent lookup or reference-frame assumptions through render code.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalDomainGraph.cs","src/Aquarium.Engine.Fractal/Grammar/FractalOwnershipTree.cs","src/Aquarium.Engine.Fractal/Debug/FractalDebugDump.cs","tests/Aquarium.Engine.Fractal.Tests/FractalDslCompilerTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalDebugDumpTests.cs"],"source":"follow-up slice after `.aquageo` gained solar/orbital/planetary/lat-long domains"} -{"timestamp":"2026-05-18T08:03:00+01:00","topic":"zyphos-camera-composer-and-space-view","lesson":"Zyphos should not render the legacy height-field Grid in the space view. Aquarium frames now carry a 3D camera target and scene flags so clients can disable the height-field trace and request a starfield background. `ZyphosCameraComposer` separates tracked subject from parent composition anchor, borrowing the Cinemachine idea of composer-owned framing rather than embedding camera aim in world objects.","files":["src/Aquarium.Engine.Contracts/AquariumFrame.cs","src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Zyphos/ZyphosCameraComposer.cs","src/Aquarium.Zyphos/ZyphosRuntime.cs","src/Aquarium.Zyphos/ZyphosSceneBuilder.cs"],"source":"user saw the Zyphos screenshot, rejected the visible Grid, asked for starry background and camera locks informed by Cinemachine composer behavior"} -{"timestamp":"2026-05-18T08:22:00+01:00","topic":"debug-ui-panel-scrolling","lesson":"DebugUi panels now own body scrolling, body clipping, and a visible scrollbar when controls exceed the viewport. Individual controls can still own local scrolling for text boxes and option popups, but panel overflow is an engine-level invariant so client panels cannot spill out of their frame.","files":["src/Aquarium.Engine/Render/Ui/DebugUi.cs"],"source":"user reported Zyphos UI did not fit its panel and expected all panels to have scrollbars"} -{"timestamp":"2026-05-18T04:09:10+01:00","topic":"face-voice-proximity-routing","lesson":"Face voice is now routed through typed endpoint rows instead of one global session. `FaceVoiceRouter` selects the active endpoint by cursor/listener proximity when auto-route is enabled, while each `FaceVoiceEndpoint` owns its thread id, voice, prompt, enabled state, and XY anchor before delegating transport to `RealtimeFaceVoiceSession`. This keeps multi-Face speech routing explicit and spatial, while the next impurity to cut is manual XY placement: endpoint anchors should bind to real Face/body visual projections once those projections are exposed as a CPU-visible contract.","files":["src/Aquarium.Epiphany/Voice/FaceVoiceRouter.cs","src/Aquarium.Epiphany/Voice/FaceVoiceEndpoint.cs","src/Aquarium.Epiphany/AquariumRuntime.cs","src/Aquarium.Epiphany/State/AquariumLiveState.cs","state/map.yaml"],"source":"user asked to hook the voice path up while keeping in mind several Faces selected by spatial proximity"} -{"timestamp":"2026-05-18T04:32:00+01:00","topic":"face-rumination-output-spatialization","lesson":"Face voice proximity is an addressing rule, not a speech-permission rule. Enabled Face endpoints can now run concurrently via `StartAll`, so active rumination loops may emit speech regardless of listener proximity; proximity updates only output gain and stereo pan. AquariumAudioDocument now carries per-chunk left/right gains and WasapiAudioDevice mixes stereo when the output device supports it, degrading to mono by averaging channels.","files":["src/Aquarium.Engine.Contracts/Audio/AquariumAudio.cs","src/Aquarium.Engine/Audio/WasapiAudioDevice.cs","src/Aquarium.Epiphany/Voice/RealtimeFaceVoiceSession.cs","src/Aquarium.Epiphany/Voice/FaceVoiceEndpoint.cs","src/Aquarium.Epiphany/Voice/FaceVoiceRouter.cs","src/Aquarium.Epiphany/AquariumRuntime.cs","state/map.yaml"],"source":"user clarified Faces should speak from active rumination loops regardless of proximity, using spatial audio only to indicate distance"} -{"timestamp":"2026-05-18T08:32:00+01:00","topic":"client-floating-navigation-panels","lesson":"Client UI panels are folded into the renderer debug tab strip by default; only panels that opt into proximity fading render as positioned floating overlays. Floating overlays support optional right anchoring via negative left offsets and proximity fade to 10% opacity. Zyphos uses this to expose a right-side Navigation panel without spawning ordinary client debug tabs as extra windows.","files":["src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/DirectWriteOverlay.cs","src/Aquarium.Engine/Render/Ui/DebugUi.cs","src/Aquarium.Zyphos/ZyphosRuntime.cs"],"source":"user expected a right-side fading navigation panel with a foldout hierarchy of spatial domains, then rejected normal debug tabs appearing as floating panels"} -{"timestamp":"2026-05-18T04:50:36+01:00","topic":"zyphos-domain-navigation","lesson":"The Zyphos navigation panel must be a real domain navigator, not toggles masquerading as hierarchy. AquariumUiTreeItem provides generic selectable disclosure rows; Zyphos owns a spatial domain catalog keyed to solar/orbital/planetary/surface/tile domains; the camera composer derives tracked center, parent pivot, and effective distance from the selected domain key. Mouse drag/wheel now drives orbit/zoom for the active spatial frame.","files":["src/Aquarium.Engine.Contracts/Ui/AquariumUi.cs","src/Aquarium.Engine/Render/Ui/DebugUi.cs","src/Aquarium.Zyphos/ZyphosSpatialDomainCatalog.cs","src/Aquarium.Zyphos/ZyphosCameraComposer.cs","src/Aquarium.Zyphos/ZyphosRuntime.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosCameraComposerTests.cs","state/map.yaml","state/memory.json"],"source":"user rejected undercooked Zyphos navigation panel and demanded selectable domain camera modes plus mouse navigation"} -{"timestamp":"2026-05-18T05:13:27+01:00","topic":"zyphos-umbros-fractal-stress-domains","lesson":"Zyphos and Umbros should both be first-class selectable fractal bodies. The `.aquageo` patch now declares Umbros lat/long plus multiple cube-tile children for both bodies and emits 31 shaped brush claims. D3D12 height-field brush constants were expanded to a deliberate 32-entry fixed table so stress data is not silently clipped at 16. Planet and Umbros SDF shaders also add cheap bounded quadtree-style object-space relief for layered geometry independent of the flattened 2D brush backend.","files":["src/Aquarium.Zyphos/Worlds/zyphos-first-fractal-terrain.aquageo","src/Aquarium.Zyphos/ZyphosSpatialDomainCatalog.cs","src/Aquarium.Engine/Render/Features/D3D12HeightFieldBrushConstants.cs","src/Aquarium.Engine/Render/Shaders/D3D12HeightField.hlsl","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","src/Aquarium.Zyphos/Shaders/D3D12ZyphosUmbros.hlsl","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosSpatialDomainCatalogTests.cs"],"source":"user asked for Zyphos and Umbros selectable sub-domains plus more quadtree SDF fractals and layered geometry for stress testing"} -{"timestamp":"2026-05-18T09:45:34+01:00","topic":"everything-is-a-fractal-recursive-domains","lesson":"The Zyphos world patch now expresses the 'everything is a fractal' idea as explicit recursive domains: planet -> lat/long -> continent -> forest -> tree -> leaf and continent -> coast -> pebble field, plus Umbros -> crater province -> boulder field -> pebble field. The flattened stress backend emits 58 shaped brush claims into a 64-entry D3D12 table, while SDF shaders add bounded leaf/pebble material-relief clusters so the recursion is visible even before true recursive residency and LOD caching exist.","files":["src/Aquarium.Zyphos/Worlds/zyphos-first-fractal-terrain.aquageo","src/Aquarium.Zyphos/ZyphosSpatialDomainCatalog.cs","src/Aquarium.Zyphos/ZyphosRuntime.cs","src/Aquarium.Engine/Render/Features/D3D12HeightFieldBrushConstants.cs","src/Aquarium.Engine/Render/Shaders/D3D12HeightField.hlsl","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","src/Aquarium.Zyphos/Shaders/D3D12ZyphosUmbros.hlsl","tests/Aquarium.Engine.Fractal.Tests/ZyphosCameraComposerTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosSpatialDomainCatalogTests.cs"],"source":"user asked to see recursive domains everywhere, from continent-scale detail down to pebble, forests down to leaf"} -{"timestamp":"2026-05-18T09:58:37+01:00","topic":"zyphos-visible-sun-and-domain-zoom","lesson":"The primary star cannot remain only an SDF light if users need spatial orientation; it is now a rendered SDF object with emission/corona and a Solar navigation target. Camera zoom limits are now derived from the selected domain pose instead of a global 8-unit floor, so leaf and pebble domains can be inspected at their own scale while broad orbital domains still retain safe maximum framing.","files":["src/Aquarium.Zyphos/ZyphosRenderPlan.cs","src/Aquarium.Zyphos/ZyphosSceneBuilder.cs","src/Aquarium.Zyphos/Shaders/D3D12ZyphosStar.hlsl","src/Aquarium.Zyphos/ZyphosCameraComposer.cs","src/Aquarium.Zyphos/ZyphosRuntime.cs","src/Aquarium.Zyphos/ZyphosSpatialDomainCatalog.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosCameraComposerTests.cs"],"source":"user asked where the sun is and why zoom cannot reach the cool small features"} -{"lesson":"The first live bridge from the fractal architecture into Zyphos SDF rendering is material/detail, not traced form: .aquageo now preserves multiple tile roots, height brush packets carry cube-tile face/level/x/y metadata, D3D12 binds that packet table into the SDF pass, and the planet shader evaluates authored brushes in cube-face tile space after hit. Evaluating all authored brushes inside sdfDistance was tested and cut because it pushed the live frame toward 50-100 ms; traced geometry needs selected-cut/resident packet policy first.","timestamp":"2026-05-18T11:28:00+01:00","files":["src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs","src/Aquarium.Engine.Fractal/Brushes/FractalHeightBrushCompiler.cs","src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine/Render/Features/D3D12HeightFieldBrushConstants.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"user pointed out the renderer was only a pile of legos and ordered the real machine to be built","topic":"zyphos-aquageo-tile-packet-sdf-bridge"} -{"timestamp":"2026-05-18T12:22:00+01:00","topic":"fractal-temporal-detail-control","lesson":"Fractal cache influence now has a first TAA-facing lane. SdfSurface carries temporalDetail, SDF proxy writes it into scene-control.z, D3D12Post validates history continuity against the current and previous temporalDetail signal, and history-control.z preserves it across frames. Zyphos feeds this from authored cube-face brush material influence; other SDFs explicitly emit zero until they gain cache-owned detail.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","src/Aquarium.Epiphany/Shaders"],"source":"user said to weave the stochastic fractal cache into TAA buffers"} -{"timestamp":"2026-05-18T18:09:50+01:00","topic":"temporal-sdf-gaussian-renderer-boundary","lesson":"Live sensor-fusion splats now enter Aquarium through an engine-owned temporal SDF Gaussian field instead of client-side renderer folklore. The contract carries stable keyed world-space Gaussians; `TemporalGaussianAccumulator` buffers observations with presentation delay and history weights; D3D12 uploads structured packets and renders an instanced compact-kernel splat pass into the existing scene/metadata/control targets. Scaling beyond 4096 splats belongs to Aquarium residency/binning, not LocalCastBridge.","files":["src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianAccumulator.cs","src/Aquarium.Engine/Render/Shaders/D3D12TemporalGaussian.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs","docs/temporal-sdf-gaussian-field.md"],"source":"user directed the point-cloud/TAA renderer feature to be implemented on the Aquarium side for clean client consumption"} -{"timestamp":"2026-05-19T13:38:00+01:00","topic":"fractal-resource-budget-and-flame-dsl","lesson":"The fractal DSL now has a compact `flame` primitive for deterministic curled recursive brush emission, and Zyphos exercises it in a leaf microdetail domain without exceeding the 64-brush stress table. Fractal render planning now coordinates CPU stochastic update count, GPU selected-cut estimated cost, RAM resident payload budget, and SSD request budget before packet compilation. This budget vocabulary should remain compatible with Mimir-style sensor fusion because both pipelines accumulate confidence-weighted spatial samples into temporal reservoirs before rendering a resolved field.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs","src/Aquarium.Engine.Fractal/Lod/FractalResourceBudget.cs","src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs","src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/Worlds/zyphos-first-fractal-terrain.aquageo","tests/Aquarium.Engine.Fractal.Tests/FractalResourceBudgetPlannerTests.cs"],"source":"user demanded full fractal SDF rendering and noted Mimir sensor fusion shares the same temporal spatial evidence shape"} -{"timestamp":"2026-05-19T14:04:00+01:00","topic":"temporal-spatial-evidence-reservoir","lesson":"Temporal Gaussian accumulation now uses `TemporalSpatialEvidenceReservoir`, which owns stable-keyed spatial tracks, smoothing, delayed presentation, velocity prediction, confidence-weighted history, expiry, and max-track eviction. This pulls the common reservoir shape out from under Gaussian rendering so fractal SDF probes and Mimir sensor-fusion features can converge through the same evidence machinery before backend lowering.","files":["src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceObservation.cs","src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceReservoir.cs","src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianAccumulator.cs","tests/Aquarium.Engine.Fractal.Tests/TemporalSpatialEvidenceReservoirTests.cs","docs/temporal-sdf-gaussian-field.md"],"source":"user pointed out fractal rendering and Mimir sensor fusion both accumulate surface/volume confidence into temporal reservoirs"} -{"timestamp":"2026-05-19T14:20:00+01:00","topic":"zyphos-fractal-resource-observability","lesson":"Zyphos exposes `zyphos-fractal-plan`, a command-level dump of the current fractal selected cut and resource plan. Keep this kind of budget/cut observability alongside renderer work: pixels alone are not enough to validate stochastic LOD, residency, or cache behavior.","files":["src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/ZyphosRuntime.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs"],"source":"third implementation slice after adding resource planning; the machine needs to explain itself without screenshot divination"} -{"timestamp":"2026-05-19T14:43:00+01:00","topic":"fractal-contribution-cache-live-loop","lesson":"Fractal contribution planning now has a live cache loop. `FractalContributionCache` builds a resource plan from current summaries and cached states, stochastically observes only budgeted update nodes, updates estimator confidence, and lets Zyphos reuse compiled brush packets by selected-cut key instead of freezing the whole render plan by camera bucket. Static plan caches are not acceptable for stochastic LOD because they stop learning.","files":["src/Aquarium.Engine.Fractal/Lod/FractalContributionCache.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/FractalContributionCacheTests.cs"],"source":"follow-up after resource observability revealed the old bucket plan cache prevented continual cache updates"} -{"timestamp":"2026-05-19T15:12:00+01:00","topic":"localcast-shared-temporal-reservoir","lesson":"LocalCast fallback GPU fusion history now delegates to `TemporalSpatialEvidenceReservoir`. `LocalCastGpuFusionAccumulator` maps LocalCast GPU fusion seeds into shared evidence observations and lowers reservoir samples back into `AquariumGpuFusionSeed`; it no longer owns separate stable-key history, smoothing, expiry, or max-count logic. This is the first consumer-side takeover of duplicated temporal reservoir code.","files":["src/Aquarium.LocalCast/LocalCastGpuFusionAccumulator.cs","src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceReservoir.cs","docs/temporal-sdf-gaussian-field.md"],"source":"user made Aquarium responsible for resolving temporal reservoir sampling architecturally and taking over consumer half-versions"} -{"timestamp":"2026-05-19T15:29:00+01:00","topic":"temporal-evidence-lowering-boundary","lesson":"Shared temporal evidence now has named lowering helpers. `TemporalSpatialEvidenceLowering` converts Gaussian observations and GPU fusion seeds to/from reservoir samples, so consumer adapters do not privately pack Payload0/Payload1 conventions. Keep new reservoir consumers on this lowering seam unless they need a genuinely new payload contract.","files":["src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceLowering.cs","src/Aquarium.Engine.Fractal/Temporal/TemporalGaussianAccumulator.cs","src/Aquarium.LocalCast/LocalCastGpuFusionAccumulator.cs","tests/Aquarium.Engine.Fractal.Tests/TemporalSpatialEvidenceLoweringTests.cs"],"source":"follow-up after moving LocalCast history onto the shared reservoir; adapter payload packing needed to become a tested engine boundary"} -{"timestamp":"2026-05-19T15:46:00+01:00","topic":"temporal-reservoir-ownership-contract","lesson":"The temporal spatial evidence reservoir now has an explicit architecture contract. Raw sample reservoirs keep capture-time handles and ordering; Aquarium's `TemporalSpatialEvidenceReservoir` owns stable resolved spatial history; `TemporalSpatialEvidenceLowering` owns backend packet conversion; TAA owns pixel history. This prevents consumer repos from growing parallel half-reservoirs while preserving LocalCastBridge's lower-level raw rolling reservoir authority.","files":["docs/temporal-spatial-evidence-reservoir.md","state/map.yaml","state/memory.json"],"source":"user made Aquarium responsible for resolving temporal reservoir sampling architecturally across consumer repos"} -{"timestamp":"2026-05-19T16:11:00+01:00","topic":"zyphos-budgeted-fractal-geometry","lesson":"Authored fractal packets now affect Zyphos traced planet geometry, but only through a hard-budgeted top-influence subset. Selected height brushes are sorted by abs(amplitude)*max(radius), `sdfDistance` samples the first four, and `sdfSurface` still evaluates the full selected packet table for material/detail. A 12-brush geometry loop was tested and cut after pushing the live frame to about 33 ms; the four-brush budget returns the live view to about 16.4 ms after shader pipelines are ready.","files":["src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs"],"source":"runtime proof after moving authored fractal packet evaluation into the hot SDF distance path"} -{"timestamp":"2026-05-19T16:27:00+01:00","topic":"zyphos-fractal-domain-debug-mode","lesson":"Render debug mode 11 now exposes a client fractal-domain view. Zyphos colors cube faces, draws an 8x8 tile grid, and overlays authored brush material influence so face/tile/material packet mapping can be inspected from the renderer instead of inferred from final beauty shading.","files":["src/Aquarium.Engine.Contracts/GraphicsSettings.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"roadmap called for face/tile/LOD/cache debug modes; this is the first renderer-visible face/tile/material influence slice"} -{"timestamp":"2026-05-19T17:35:00+01:00","topic":"restir-reservoir-core","lesson":"The previous stable-key temporal smoother was not ReSTIR. Aquarium now treats `ResampledImportanceReservoir` as the RIS/ReSTIR math authority: selected sample, target value, weight sum, represented candidate count, merge, and contribution weight. `TemporalSpatialEvidenceReservoir` is a stable resolved-track layer, while fractal contribution scoring should become a candidate generator feeding reservoir resampling with temporal/spatial/domain validation and TAA guide-buffer integration.","files":["src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceCandidate.cs","src/Aquarium.Engine.Fractal/Temporal/ResampledImportanceReservoir.cs","tests/Aquarium.Engine.Fractal.Tests/ResampledImportanceReservoirTests.cs","docs/temporal-spatial-evidence-reservoir.md","research/rendering/fractal-brush-implementation-roadmap.md","state/map.yaml","state/memory.json"],"source":"user corrected the architecture toward NVIDIA ReSTIR/GRIS rather than invented spatiotemporal reservoir sampling"} -{"timestamp":"2026-05-19T18:03:00+01:00","topic":"fractal-contribution-candidates","lesson":"FractalContributionCache now frames scheduled update nodes as weighted `ResampledImportanceReservoir` candidates and exposes a per-frame reservoir snapshot for debug/tests. This is the handoff from heuristic LOD scoring into reservoir evidence; temporal/spatial reuse and domain shift validation still need to be built explicitly before calling the fractal path ReSTIR-complete.","files":["src/Aquarium.Engine.Fractal/Lod/FractalContributionCandidate.cs","src/Aquarium.Engine.Fractal/Lod/FractalContributionCache.cs","tests/Aquarium.Engine.Fractal.Tests/FractalContributionCacheTests.cs","docs/temporal-spatial-evidence-reservoir.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json"],"source":"continued Perfect Machine work after adding the ReSTIR-style reservoir core"} -{"timestamp":"2026-05-19T18:24:00+01:00","topic":"fractal-probe-reservoir-samples","lesson":"Fractal SDF/detail reservoir candidates now have a typed probe sample: domain key, node key, local center, bound radius, target contribution, source PDF, material delta, and payload handle. `FractalProbeReuseValidator` rejects unknown domains, sibling-domain reuse, invalid bounds, and excessive local shift. This starts the GRIS-style domain-shift boundary; renderer inputs for camera motion, disocclusion, material compatibility, and visibility still need to be wired before reuse is complete.","files":["src/Aquarium.Engine.Fractal/Lod/FractalProbeSample.cs","tests/Aquarium.Engine.Fractal.Tests/FractalProbeSampleTests.cs","docs/temporal-spatial-evidence-reservoir.md","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"continued Perfect Machine work after connecting fractal contribution updates to reservoir candidates"} -{"timestamp":"2026-05-19T18:46:00+01:00","topic":"taa-reservoir-guide-lane","lesson":"SDF surfaces now publish `reservoirConfidence`; the SDF proxy writes it to current scene-control.w, and D3D12Post folds that value into history validation with debug mode 12 showing reservoir confidence, temporal detail, and history weight. This is the first cache/reservoir signal woven into TAA buffers. History-control.w still owns history age, so previous-frame reservoir confidence/sample age/invalidation reason require an expanded guide layout before full ReSTIR-style TAA integration.","files":["src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl"],"source":"user explicitly asked to weave the cache into TAA buffers"} -{"timestamp":"2026-05-19T19:22:00+01:00","topic":"perfect-machine-waterfall-architecture","lesson":"The Perfect Machine architecture is now mapped before further implementation. The design authority is `docs/perfect-machine-architecture.md`: authored domains and sensor inputs lower into evidence candidates, target evaluation, ReSTIR/GRIS reservoirs, heuristic occupancy graph updates, residency/page scheduling, 2D/3D/projected SDF splat packets, and TAA guide buffers. The public article `perfect-machine-fractal-reservoir-architecture.md` defends the architecture in Void's interview-thesis voice with research footnotes.","files":["docs/perfect-machine-architecture.md","E:/Projects/gamecult-site/GameCult/Blog/perfect-machine-fractal-reservoir-architecture.md","state/map.yaml","state/memory.json"],"source":"user requested a waterfall design pass and public job-interview style architecture article before more implementation"} -{"timestamp":"2026-05-19T20:10:00+01:00","topic":"explicit-reservoir-guide-targets","lesson":"Phase B of the Perfect Machine architecture is implemented: the renderer now owns explicit current and history reservoir guide targets instead of packing previous reservoir validity into scene-control/history-control. Guide schema is x=reservoir confidence, y=sample age, z=domain validity, w=invalidation code. SDF and temporal Gaussian passes write the current guide; D3D12Post validates against current/previous guide data and persists the next guide while history-control.w remains pixel history age.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli","src/Aquarium.Engine/Render/Shaders/D3D12TemporalGaussian.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","docs/perfect-machine-architecture.md","docs/temporal-spatial-evidence-reservoir.md"],"source":"Perfect Machine marching orders after architecture note became the design authority"} -{"timestamp":"2026-05-19T20:39:00+01:00","topic":"fractal-occupancy-graph","lesson":"FractalContributionCache now routes through `FractalOccupancyGraph`, the first explicit occupancy memory organ from the Perfect Machine architecture. The graph owns contribution estimates plus visibility/update-probability telemetry; observations update mean/variance/confidence through the existing estimator, and unobserved nodes lose confidence while stale uncertainty grows. This keeps cache convergence state in one authority instead of growing side tables.","files":["src/Aquarium.Engine.Fractal/Lod/FractalOccupancyGraph.cs","src/Aquarium.Engine.Fractal/Lod/FractalContributionCache.cs","tests/Aquarium.Engine.Fractal.Tests/FractalOccupancyGraphTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalContributionCacheTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"Perfect Machine Phase D implementation after explicit reservoir guide targets"} -{"timestamp":"2026-05-19T21:01:00+01:00","topic":"structural-probe-generator","lesson":"IFS structure can now enter the reservoir path as typed evidence. `FractalStructuralProbeGenerator` lowers `AquariumFractalSummary` rows into `FractalProbeSample` candidates with local center, bound radius, projected target contribution, clamped source PDF, material delta, and payload handle. This gives structural `.aquageo` summaries a real producer boundary before renderer-facing temporal validation and GPU reservoir reuse are added.","files":["src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeGenerator.cs","tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeGeneratorTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json"],"source":"Perfect Machine Phase C implementation after occupancy graph promotion"} -{"timestamp":"2026-05-19T21:18:00+01:00","topic":"zyphos-structural-probe-reservoir","lesson":"Zyphos now exposes a structural probe reservoir beside its selected cut and resource plan. `FractalStructuralProbeReservoir` builds a selected-cut `FractalProbeSample` reservoir from the ownership tree, summaries, node domains, and projected pixels per world unit; `ZyphosFractalRenderPlan` carries the snapshot and the debug dump reports selected probe weight/candidate count. This connects the pure IFS structural-probe producer to a live client path before GPU reservoir buffers are introduced.","files":["src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeReservoir.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeReservoirTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md"],"source":"continuing Perfect Machine Phase C after adding structural probe generation"} -{"timestamp":"2026-05-19T21:42:00+01:00","topic":"fractal-probe-temporal-validation","lesson":"Fractal probe reuse now has a CPU temporal validation contract before GPU reuse exists. `FractalProbeReuseValidator.ValidateTemporal` composes domain/local-shift validation with renderer-facing gates for camera motion, disocclusion confidence, material delta, and visibility confidence, returning explicit rejection reasons. This keeps future ReSTIR/GRIS probe reuse from becoming private shader folklore.","files":["src/Aquarium.Engine.Fractal/Lod/FractalProbeSample.cs","tests/Aquarium.Engine.Fractal.Tests/FractalProbeSampleTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json"],"source":"Perfect Machine Phase C validation contract work"} -{"timestamp":"2026-05-19T22:03:00+01:00","topic":"fractal-surface-page-contract","lesson":"Phase E has a portable page contract before renderer lowering. `AquariumFractalSurfacePageKey` gives height, 2D signed-distance, material, and confidence pages stable domain/node/kind/mip identity; `AquariumFractalSurfacePage` carries bounds, dimensions, payload handle, and max error without D3D12 types. This lets the residency/page store evolve without treating current height brushes as the page model.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageContractTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json"],"source":"Perfect Machine Phase E groundwork after fractal probe validation"} -{"timestamp":"2026-05-19T22:31:00+01:00","topic":"fractal-surface-page-planner","lesson":"Phase E now has a CPU page-planning boundary. `FractalSurfacePagePlanner` lowers selected IFS cuts into stable height, 2D signed-distance, material, and confidence page metadata; `ZyphosFractalRenderPlan` carries those pages beside brushes, resource planning, and structural probe reservoirs. This proves page identity and inspection before adding a page store, eviction policy, D3D12 atlas, or GPU lowering.","files":["src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePlanner.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePagePlannerTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase E CPU page planning"} -{"timestamp":"2026-05-19T22:48:00+01:00","topic":"fractal-residency-eviction-policy","lesson":"Residency planning now has an explicit score-per-cost eviction decision. `FractalResidencyPlanner` can receive node summaries, retain resident payloads with the best contribution per estimated cost under RAM budget, place evicted residents on summary fallback, and report evicted node keys without mutating a real store. This keeps eviction testable until a page/payload store owns storage changes.","files":["src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlanner.cs","src/Aquarium.Engine.Fractal/Lod/FractalResidencyPlan.cs","src/Aquarium.Engine.Fractal/Lod/FractalResourceBudgetPlanner.cs","tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase D/E residency pressure slice"} -{"timestamp":"2026-05-19T23:10:00+01:00","topic":"fractal-surface-page-residency","lesson":"Surface page residency now has a separate mockable boundary from node payload residency. `IFractalSurfacePageStore` owns page-key resident/request/evict calls, and `FractalSurfacePageResidencyPlanner` turns planned pages into resident, missing, requested, evicted, and resident-byte rows using a max-error-per-byte heuristic. Zyphos carries this page residency plan for inspection before any real atlas or SSD-backed page store exists.","files":["src/Aquarium.Engine.Fractal/Lod/IFractalSurfacePageStore.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlan.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageResidencyPlanner.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageResidencyPlannerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase E page-store boundary slice"} -{"timestamp":"2026-05-19T23:35:00+01:00","topic":"fractal-surface-page-rasterizer","lesson":"Resident surface pages now produce CPU payloads instead of only metadata. `FractalSurfacePageRasterizer` lowers ownership-tree claims into height, 2D signed-distance support, material, and confidence sample arrays using `FractalBrushEnvelope2D`; Zyphos caches resident page payloads by stable page key. This gives Phase E a renderer-agnostic payload producer before D3D12 atlas/upload work begins.","files":["src/Aquarium.Engine.Fractal/Brushes/FractalBrushEnvelope2D.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePagePayload.cs","src/Aquarium.Engine.Fractal/Lod/FractalSurfacePageRasterizer.cs","tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageRasterizerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase E CPU page payload slice"} -{"timestamp":"2026-05-19T23:55:00+01:00","topic":"fractal-3d-sdf-splat-contract","lesson":"Phase F has its first stable packet shape. `AquariumFractalSdfSplat3DKey` and `AquariumFractalSdfSplat3D` define domain/node/payload-keyed compact 3D SDF splats; `FractalSdfSplat3DCompiler` lowers structural `FractalProbeSample` evidence into splats, and `FractalSdfSplat3DKernel` owns CPU compact-weight/signed-distance parity math. Zyphos exposes a structural splat from its probe reservoir before renderer lowering.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DCompiler.cs","src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DKernel.cs","src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeReservoir.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DCompilerTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeReservoirTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase F compact 3D SDF splat groundwork"} -{"timestamp":"2026-05-19T23:59:00+01:00","topic":"fractal-projected-sdf-splat-compiler","lesson":"Phase G now has a pure 2D-projected-to-3D lowering seam. `FractalProjectedSdfSplatCompiler` takes resident SignedDistance2D page payload samples, an explicit page-to-world mapper, a surface normal, support radii, and a splat budget, then emits compact `AquariumFractalSdfSplat3D` packets ordered by near-surface distance. Zyphos caches a bounded first set of projected surface splats using a flat local mapping until cube-sphere and torus mappings are implemented.","files":["src/Aquarium.Engine.Fractal/Lod/FractalProjectedSdfSplatCompiler.cs","tests/Aquarium.Engine.Fractal.Tests/FractalProjectedSdfSplatCompilerTests.cs","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"Perfect Machine Phase G projected SDF splat groundwork"} -{"timestamp":"2026-05-19T21:03:19+00:00","topic":"gpu-resident-fractal-splat-receipt","lesson":"The first honest performance receipt is GPU-resident compute, not CPU object population. `tools/Aquarium.Fractal.Receipt` allocates an 80-byte packed `AquariumPackedFractalSdfSplat3D` UAV, populates it entirely in a D3D12 compute shader, measures GPU timestamp queries, and reads back only 64 splats for checksum. On the local NVIDIA GTX 1070, `2,000,000` splats over `120` measured frames ran at `3.362 ms/frame`, `297.5 FPS` equivalent, and about `594.9M` splats/sec. This proves compute-side population throughput; final shaded rendering still has to consume the packed buffer.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Lod/FractalNativeBuffer.cs","tests/Aquarium.Engine.Fractal.Tests/FractalNativeBufferTests.cs","tools/Aquarium.Fractal.Receipt/Aquarium.Fractal.Receipt.csproj","tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-splat-receipt.ps1","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"user demanded a receipt showing millions of splats at hundreds of FPS and rejected CPU-resident architecture"} -{"timestamp":"2026-05-19T21:29:26+00:00","topic":"gpu-resident-layered-reservoir-receipt","lesson":"The layered temporal cache is not one generic reservoir with a layer enum. SDF envelope splats, PBR material splats, and radiosity splats are three different sampled measures, so the GPU receipt now uses three distinct 64-byte reservoir packet types and three independent compute passes. Full rewrites of all three 2,000,000-entry reservoir layers every frame missed the target on the GTX 1070; the coherent architecture is stochastic budgeted refresh over resident reservoirs. With 50,000 updates per reservoir layer per frame, 2 candidates/update, and 2,000,000 resident splats/reservoirs, the receipt measured 4.471 ms/frame and 223.7 FPS equivalent over 120 frames, with full reservoir coverage in 40 frames.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs","tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-splat-receipt.ps1","docs/perfect-machine-architecture.md","research/rendering/fractal-brush-implementation-roadmap.md","state/memory.json","state/map.yaml"],"source":"user corrected that SDF splats, PBR splats, and radiosity splats are sampled independently in different shader passes"} -{"timestamp":"2026-05-20T01:24:49+01:00","topic":"fractal-reservoir-shader-asset","lesson":"The fractal GPU reservoir compute path must live as an engine shader asset, not as embedded receipt-tool text. `src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl` now owns the splat population pass plus the independent SDF envelope, PBR material, and radiosity reservoir update passes. `tools/Aquarium.Fractal.Receipt` compiles that shader file directly, keeping the receipt and future renderer pass on one source of truth.","files":["src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","tools/Aquarium.Fractal.Receipt/Program.cs","state/map.yaml"],"source":"continued Perfect Machine build after the GPU receipt proved the pass should become reusable renderer architecture"} -{"timestamp":"2026-05-20T01:31:00+01:00","topic":"fractal-reservoir-render-contract","lesson":"The render contract now exposes `AquariumFractalReservoirField` on `AquariumSceneState`: clients request a GPU-resident fractal reservoir field by resident splat count, depth, seed, reservoir candidates/update, and updates/pass. This keeps million-instance splat population inside GPU compute instead of making clients publish CPU splat lists.","files":["src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","tests/Aquarium.Engine.Fractal.Tests/FractalReservoirFieldContractTests.cs","state/map.yaml"],"source":"continued Perfect Machine build: the shared shader needed a client-to-renderer contract surface"} -{"timestamp":"2026-05-20T01:57:56+01:00","topic":"renderer-owned-fractal-reservoir-pass","lesson":"D3D12Renderer now owns the first live fractal reservoir compute pass instead of leaving it in the receipt tool. The renderer creates a separate fractal reservoir root signature, compiles four compute pipelines from `D3D12FractalReservoirCompute.hlsl`, lazily allocates GPU UAV buffers for splats plus SDF/PBR/radiosity reservoirs, inserts a UAV barrier after splat population, and dispatches the three independent reservoir passes when `AquariumFractalReservoirField` is present. Zyphos now requests the 2,000,000-splat, 50,000-updates/pass field by default. The pass still needs a shaded consumption path before it produces visible terrain pixels.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/D3D12StructuredBuffer.cs","src/Aquarium.Engine.Contracts/Render/AquariumApp.cs","src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Zyphos/ZyphosSceneBuilder.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","tools/Aquarium.Fractal.Receipt/Program.cs","state/map.yaml"],"source":"continued Perfect Machine build: turn the GPU reservoir receipt into a renderer-owned frame pass"} -{"timestamp":"2026-05-20T02:08:12+01:00","topic":"visible-fractal-splat-consumption","lesson":"The first visible GPU-resident fractal consumption path is now a capped debug draw, not a CPU readback. `D3D12FractalSplatRender.hlsl` reads the computed `AquariumPackedFractalSdfSplat3D` buffer as an SRV and draws up to 131,072 splat instances into the scene. This proves the renderer can consume the compute-populated splat buffer directly; final terrain, material, and radiosity integration still need domain-correct shading over the same buffers. A Zyphos shader compile bug also surfaced here: `line` was treated as an HLSL token, so the planet debug variable is now `gridLine`.","files":["src/Aquarium.Engine/Render/Shaders/D3D12FractalSplatRender.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine.Contracts/Render/AquariumApp.cs","src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Zyphos/Shaders/D3D12ZyphosPlanet.hlsl","state/map.yaml"],"source":"continued Perfect Machine build: make the GPU-resident fractal splat buffer visible in the renderer"} -{"timestamp":"2026-05-20T07:47:00+01:00","topic":"layered-fractal-reservoir-consumption","lesson":"The visible fractal splat draw must consume the same independent reservoir layers produced by compute. Reusing the temporal Gaussian descriptor slot for raw splats hid the SDF/PBR/radiosity contract. The renderer now binds raw splats plus SDF envelope, PBR material, and radiosity reservoirs as separate graphics SRVs; the debug draw uses SDF reservoirs for support, PBR reservoirs for color, radiosity reservoirs for energy, and writes per-layer confidence into the reservoir guide MRT. This is still a capped debug view, but it proves the three-layer reservoir machine reaches visible pixels without CPU readback or buffer collapse.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12FractalSplatRender.hlsl","state/map.yaml","state/memory.json"],"source":"user insisted SDF splats, PBR splats, and radiosity splats are different sampled types and the Perfect Machine must not flatten them"} -{"timestamp":"2026-05-20T08:04:00+01:00","topic":"authored-ifs-program-gpu-splat-population","lesson":"The GPU splat producer now has a compact authored-program path. `FractalGpuProgramCompiler` lowers selected `.aquageo` claims into `AquariumPackedFractalIfsTransform` rows, Zyphos passes those rows through `AquariumFractalReservoirField.ProgramTransforms`, and D3D12 uploads them as a small compute SRV before dispatch. `D3D12FractalReservoirCompute.hlsl` uses those transforms when present and keeps the old hash fractal only as fallback/receipt mode. This keeps million-splat population GPU-resident while making the source fractal structure come from the DSL instead of private shader folklore.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine.Fractal/Lod/FractalGpuProgramCompiler.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/ZyphosSceneBuilder.cs","tests/Aquarium.Engine.Fractal.Tests/FractalGpuProgramCompilerTests.cs"],"source":"continued Perfect Machine build: replace hardcoded GPU splat generation with a DSL-driven program seam"} -{"timestamp":"2026-05-20T08:16:00+01:00","topic":"authored-ifs-program-gpu-receipt","lesson":"The receipt harness now has a nonzero authored-program mode via `-ProgramTransforms`. On the GTX 1070, 2,000,000 splats plus 2,000,000 SDF, PBR, and radiosity reservoirs per layer with 4 IFS transforms, depth 1, 20,000 stochastic updates per reservoir layer, and 2 candidates/update measured 4.438 ms/frame, 225.3 FPS equivalent, with full reservoir coverage in 100 frames. Depth 2 and 4 are below the hundreds-FPS bar at this budget, so deeper authored IFS generation needs a better shader strategy or adaptive depth/cut scheduling instead of pretending the simple receipt covers all fractal detail depths.","files":["tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-splat-receipt.ps1","src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","state/map.yaml","state/memory.json"],"source":"user demanded a receipt showing millions of splats populating a simple fractal at hundreds of FPS"} -{"timestamp":"2026-05-20T08:32:00+01:00","topic":"precomposed-selected-cut-splat-generation","lesson":"Nested domain ancestry must not be replayed inside the million-splat compute kernel. Authored program mode now treats `AquariumPackedFractalIfsTransform` rows as precomposed selected-cut support packets and samples one row per splat in O(1); the CPU/compiler/planner owns collapsing planetary/cave/mushroom/rib ancestry into selected supports before GPU dispatch. A depth-48 receipt with 2,000,000 splats, 2,000,000 reservoirs per SDF/PBR/radiosity layer, 4 program rows, 15,000 updates per layer, and 2 candidates/update measured 4.908 ms/frame, 203.7 FPS equivalent on the GTX 1070. Depth is now semantic lineage/planner pressure, not a hot-loop multiplier.","files":["src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs","tools/Aquarium.Fractal.Receipt/Program.cs","state/map.yaml","state/memory.json"],"source":"user pointed out real scenes will regularly render nested domains dozens of layers deep"} -{"timestamp":"2026-05-20T09:39:00+01:00","topic":"zyphos-fractal-reservoir-primary-terrain","lesson":"The Zyphos demo must test the fractal reservoir renderer as the terrain path, not as a debug layer over direct SDF planets. `AquariumFractalReservoirField` now carries `WorldCenterRadius`; Zyphos binds it to the planet frame, reduces live reservoir updates to 20,000/pass, and removes the direct planet/Umbros SDF proxy shaders from its render plan. `D3D12FractalReservoirCompute.hlsl` emits normalized spherical support for authored selected-cut program rows, and `D3D12FractalSplatRender.hlsl` maps SDF/PBR/radiosity reservoir rows into the world frame with SDF support/depth/normal, PBR material, and radiosity illumination. The remaining direct SDF body is the parent star. Future visual problems in Zyphos terrain should be fixed in reservoir lowering/shading, not hidden behind direct SDF terrain.","files":["src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12FractalSplatRender.hlsl","src/Aquarium.Zyphos/ZyphosRenderPlan.cs","src/Aquarium.Zyphos/ZyphosSceneBuilder.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs"],"source":"user correctly pointed out that Zyphos fractal domains should be the pipeline test and should replace direct SDF rendering"} -{"timestamp":"2026-05-20T13:45:00+01:00","topic":"zyphos-fractal-surface-legibility","lesson":"The live Zyphos reservoir path was fast but visually incoherent because the GPU program packet discarded cube tile X/Y and the camera targeted parent pivots instead of selected domains. `AquariumPackedFractalIfsTransform.TileAddress` now preserves face/level/x/y, D3D12FractalReservoirCompute maps authored supports onto cube-sphere faces, D3D12FractalSplatRender projects tangent-frame surface patches from world space, and ZyphosCameraComposer targets the selected domain while keeping the parent as orbit anchor. The result still reads too abstractly; the next coherent renderer cut is a clustered/ray-query surface resolve for reservoir splats rather than more camera-facing billboard cosmetics.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Lod/FractalGpuProgramCompiler.cs","src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12FractalSplatRender.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Zyphos/ZyphosCameraComposer.cs","tests/Aquarium.Engine.Fractal.Tests/FractalGpuProgramCompilerTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosCameraComposerTests.cs"],"source":"user asked whether the current view looked like anything; answer was no, so the packet/domain/camera lies had to be cut before more rendering claims"} -{"timestamp":"2026-05-20T14:05:00+01:00","topic":"apophysis-reference-first-fractal-parity","lesson":"Zyphos is too entangled to be the first correctness oracle for the fractal DSL. Aquarium now has a tiny Apophysis/FLAM3-shaped reference gate: `.flame` linear Sierpinski is parsed by an independent test helper, `.aquageo` expresses the same affine IFS through `affineifs`/`affinemap`, and tests compare exact fixed-transform sequence points plus chaos-game moment bounds. This follows the AquaSynth pattern: open-source/reference systems are external pressure and receipts, not runtime organs or copied code. Next parity gates should parse more `.flame` semantics and compare against FLAM3/Apophysis-compatible rendered histograms before feeding the GPU reservoir renderer.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalAffineIfsDefinition.cs","src/Aquarium.Engine.Fractal/Grammar/FractalAffineIfsChaosGame.cs","src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs","src/Aquarium.Engine.Fractal/Grammar/FractalOwnershipTree.cs","tests/Aquarium.Engine.Fractal.Tests/ApophysisReferenceParityTests.cs","tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-sierpinski.flame","tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-sierpinski.aquageo","research/rendering/fractal-reference-oracles.md"],"source":"user redirected from visual Zyphos debugging to reference-rendered IFS parity and suggested Apophysis 7x"} -{"timestamp":"2026-05-20T14:20:00+01:00","topic":"flame-subset-parser-histogram-receipts","lesson":"The reference path now parses and evaluates a small Apophysis/FLAM3 flame subset in runtime code: xform weight, color, affine coefficients, and `linear`, `spherical`, and `bubble` variation weights. Tests cover parser fields, independent variation formulas, and a deterministic 64x64 histogram checksum for a mixed linear/spherical/bubble fixture. This is still not external renderer parity, but it gives Aquarium a stable CPU receipt before GPU lowering and keeps Zyphos out of the correctness loop.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalFlameDefinition.cs","src/Aquarium.Engine.Fractal/Grammar/FractalFlameFileParser.cs","src/Aquarium.Engine.Fractal/Grammar/FractalFlameChaosGame.cs","src/Aquarium.Engine.Fractal/Grammar/FractalPointHistogram.cs","tests/Aquarium.Engine.Fractal.Tests/ApophysisReferenceParityTests.cs","tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-spherical-bubble.flame","research/rendering/fractal-reference-oracles.md"],"source":"continued after adopting Apophysis/FLAM3 as the fractal reference family"} -{"timestamp":"2026-05-20T14:30:00+01:00","topic":"flame-histogram-receipt-cli","lesson":"The receipt tool now has a non-GPU `--flame` mode that loads a `.flame` fixture, runs FractalFlameChaosGame, bins points through FractalPointHistogramBuilder, and writes a JSON checksum receipt. `scripts/fractal-flame-receipt.ps1` runs the default mixed linear/spherical/bubble fixture with seed 0x0BADC0DE and emits checksum 0xAEB1C81B. This creates a cheap local receipt path before wiring external FLAM3/Apophysis renderer parity or GPU lowering.","files":["tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-flame-receipt.ps1","research/rendering/fractal-reference-oracles.md"],"source":"continued reference-first fractal pipeline build"} -{"timestamp":"2026-05-21T00:25:00+01:00","topic":"gpu-resident-flame-iteration-state","lesson":"Flame splat generation now has a real GPU-resident iteration cache. `AquariumPackedFractalFlameState` is a 32-byte UAV row per resident splat storing point/support/material plus RNG/step; D3D12FractalReservoirCompute advances touched rows instead of replaying chaos-game ancestry from zero. The receipt harness separates full-population acquisition from steady stochastic maintenance: on the GTX 1070, JWildfire FARender selftest.flame with 2,000,000 splats/states, 8 full acquisition frames, then 50,000 splat updates/frame plus 15,000 reservoir updates/pass/frame at depth 8 measured 1.011 ms/frame / 988.8 FPS equivalent and 84.85% CPU-slice distribution parity. The same steady budget without acquisition scored 32.64%, so persistent caches must report cold-start versus maintenance explicitly.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","src/Aquarium.Engine/Render/D3D12Renderer.cs","tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-splat-receipt.ps1","research/rendering/fractal-reference-oracles.md","state/map.yaml","state/memory.json"],"source":"user demanded the Perfect Machine stop replaying crayon flames and keep building toward GPU-resident stochastic fractal rendering"} -{"lesson":"The flame parity gate now has an external image-density reference instead of only Aquarium CPU self-agreement. tools/Aquarium.Fractal.Receipt accepts --reference-density-ppm, loads a binary PPM rendered by JWildfire/FARender, converts luminance into the reference histogram, and compares Aquarium GPU splat density against it. scripts/new-jwildfire-baby-fixture.ps1 derives a smaller FARender-compatible julian-disc-baby.flame from FARender selftest while preserving boilerplate FARender requires. First GTX 1070 receipt: FARender 768x768 quality 2000 reference, Aquarium 2M splats/states, 8 acquisition frames, 50k steady splat updates/frame, depth 8, 1.145 ms/frame, but only 15.33% external density score in 256x256 bounds -2..2; a 128x128 bounds sweep peaked at 32.95% for -4..4 while Aquarium-vs-CPU scored 89.94%. This proves the next failure is dialect/camera/render filtering, not GPU sampling count.","timestamp":"2026-05-21T01:05:00+01:00","files":["tools/Aquarium.Fractal.Receipt/Program.cs","scripts/fractal-splat-receipt.ps1","scripts/new-jwildfire-baby-fixture.ps1","research/rendering/fractal-reference-oracles.md","state/map.yaml","state/memory.json"],"source":"user asked to ditch the shitty oracle and get proper ground truth that gives Aquarium useful exercise","topic":"external-flame-density-oracle"} -{"lesson":"The external FARender density oracle exposed two concrete JWildfire import/math bugs: Aquarium transposed JWildfire coefs off-diagonal terms even though FARender applies a,b,c,d,e,f as x=a*x+b*y+c and y=d*x+e*y+f, with JWildfire XML effectively a b d e c f; Aquarium also used atan2(y,x) for disc while FARender jwf_disc uses atan2(x,y)/PI. Fixing both moved the julian-disc-baby external-density receipt from 15.33% to 26.87% at 256x256 bounds -2..2. The remaining visible spray is raw splat occupancy versus FARender camera/filter/gamma density, not proof that the GPU sampler is simply exploding.","timestamp":"2026-05-21T01:18:00+01:00","files":["src/Aquarium.Engine.Fractal/Grammar/FractalFlameFileParser.cs","src/Aquarium.Engine.Fractal/Grammar/FractalFlameDefinition.cs","src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","tests/Aquarium.Engine.Fractal.Tests/ApophysisReferenceParityTests.cs","research/rendering/fractal-reference-oracles.md","state/map.yaml","state/memory.json"],"source":"user asked why Aquarium explodes while the reference stays bounded","topic":"jwildfire-flame-import-coordinate-lies"} -{"timestamp":"2026-05-21T01:32:00+01:00","topic":"sdf-reservoir-density-parity","lesson":"The external flame parity candidate now comes from Aquarium's SDF envelope reservoir layer, not raw splat-center occupancy. tools/Aquarium.Fractal.Receipt stamps populated AquariumPackedSdfEnvelopeReservoir rows into shaped density histograms and reports the candidate source explicitly. PBR and radiosity remain separate reservoir layers: PBR should score appearance later, while radiance is out of this gate for now. With full 2M-row reservoir refresh on the GTX 1070, julian-disc-baby scored 22.14% against the FARender PPM at 256x256 bounds -2..2 and cost 42.053 ms/frame; the contact sheet shows a sparse, shape-shifted Aquarium SDF density rather than a valid rendered flame. The next work is dialect/camera/filter parity plus target-density and view-conditioned reservoir feedback, not raw occupancy scoring.","files":["tools/Aquarium.Fractal.Receipt/Program.cs","research/rendering/fractal-reference-oracles.md","state/map.yaml","state/memory.json"],"source":"user corrected the metric: SDF reservoirs express form density, PBR reservoirs express surface appearance, and raw occupancy is the wrong comparison"} -{"timestamp":"2026-05-21T01:52:00+01:00","topic":"jwildfire-normal-is-not-linear","lesson":"JWildfire FARender does not treat `variationGroup normal=\"1\"` as an explicit linear variation. A normal-only FARender diagnostic collapsed to a constant point, proving Aquarium's `normal -> linear` approximation was inventing geometry. The importer now ignores JWildfire `normal` as variation-group metadata while preserving explicit `linear` for Apophysis/FLAM3 fixtures. The SDF-density receipt also enforces a minimum one-bin reconstruction footprint for subpixel envelopes so density parity no longer degenerates into point occupancy. The julian-disc-baby external score moved from 22.14% to 31.36% with full 2M-row reservoir refresh; remaining mismatch is compactness/weighting, not the previous fake affine contribution.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalFlameFileParser.cs","tests/Aquarium.Engine.Fractal.Tests/ApophysisReferenceParityTests.cs","tools/Aquarium.Fractal.Receipt/Program.cs","research/rendering/fractal-reference-oracles.md","state/map.yaml","state/memory.json"],"source":"continued flame external parity push after discovering FARender normal-only behavior"} -{"timestamp":"2026-05-21T02:00:00+01:00","topic":"flame-camera-bounds-receipt","lesson":"FARender maps flame points through camera bounds derived from flame `size / (scale * cam_zoom)` around `center`; using an ad hoc square histogram window was distorting external density parity. tools/Aquarium.Fractal.Receipt now accepts `--histogram-bounds flame-camera` after `--program-flame` and derives those bounds from the flame XML. On julian-disc-baby this moved the SDF-reservoir-density score from 31.36% in manual -2..2 bounds to 43.13% with 68.01% occupancy overlap. Remaining loss is now less camera-window stupidity and more exact variation/filter weighting plus reservoir targeting.","files":["tools/Aquarium.Fractal.Receipt/Program.cs","research/rendering/fractal-reference-oracles.md","state/map.yaml","state/memory.json"],"source":"continued flame external parity push after FARender source showed the camera size/scale mapping"} -{"timestamp":"2026-05-21T08:40:00+01:00","topic":"direct-full-reservoir-refresh","lesson":"The reservoir shader used the stochastic hash indexer even when ReservoirUpdatesPerPass equaled SplatCount, so a claimed full refresh was random-memory coupon-collector work. D3D12FractalReservoirCompute now maps full-refresh updates directly to updateIndex % SplatCount and keeps the hash path only for under-budget stochastic passes. On julian-disc-baby with flame-camera bounds, the visual score stayed essentially the same (43.09%, 67.99% occupancy overlap) but full SDF/PBR/radiosity reservoir refresh dropped to 7.508 ms/frame / 133.2 FPS equivalent instead of roughly 41 ms/frame.","files":["src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","research/rendering/fractal-reference-oracles.md","state/map.yaml","state/memory.json"],"source":"continued hill climb after identifying the full-coverage reservoir pass as randomized memory confetti"} -{"timestamp":"2026-05-21T09:05:00+01:00","topic":"form-appearance-transport-fields","lesson":"The Perfect Machine architecture now treats SDF/PBR/radiosity as the first opaque backend packet slice, not the conceptual layer split. The durable split is Form, Appearance, and Transport. SDF/level-set is one Form encoding for opaque solids; density/extinction/confidence is the Form encoding for flames, smoke, transparent gradients, and uncertain sensor-fusion volumes. PBR is one Appearance encoding; participating media need albedo/emission/phase/absorption/scattering, with Transport owning radiance, emission, and scattering reuse. Do not force flames or Mimir confidence volumes to become fake surfaces before they can enter reservoirs.","files":["docs/perfect-machine-architecture.md","docs/temporal-sdf-gaussian-field.md","docs/temporal-spatial-evidence-reservoir.md","research/rendering/fractal-brush-implementation-roadmap.md","state/map.yaml","state/memory.json"],"source":"user reframed flame IFS and sensor fusion as field-density evidence rather than opaque SDF surfaces"} -{"timestamp":"2026-05-21T09:40:00+01:00","topic":"shared-form-reservoir-code","lesson":"The code now matches the Form/Appearance/Transport architecture at the reservoir seam. AquariumFieldLayer and AquariumFieldEncoding live in contracts; TemporalSpatialEvidenceObservation/Sample and FractalProbeSample carry layer/encoding; TemporalSpatialEvidenceReservoir keys tracks by layer+encoding+stable key; FractalProbeReuseValidator rejects mismatched encodings before spatial reuse; Form/SignedDistance lowers through FractalSdfSplat3DCompiler while Form/Density or Form/Extinction lowers through FractalDensitySplat3DCompiler. The packed transparent density splat is 80 bytes to stay stride-aligned with the opaque SDF splat. Do not add a parallel transparent reservoir; extend encodings and lowerings under the same sample/reservoir contract.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Lod/FractalProbeSample.cs","src/Aquarium.Engine.Fractal/Lod/FractalDensitySplat3DCompiler.cs","src/Aquarium.Engine.Fractal/Lod/FractalSdfSplat3DCompiler.cs","src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceObservation.cs","src/Aquarium.Engine.Fractal/Temporal/TemporalSpatialEvidenceReservoir.cs","src/Aquarium.Engine.Fractal/Lod/FractalGpuReservoirBudgetPlanner.cs","docs/perfect-machine-architecture.md","state/map.yaml","state/memory.json"],"source":"user asked to fix code so one reservoir handles transparent and opaque fields with defensible architecture"} -{"timestamp":"2026-05-21T10:05:00+01:00","topic":"aquageo-transparent-form-claims","lesson":"The `.aquageo` DSL now has first-class `density` and `extinction` field claims, and the recursive `flame` primitive emits Density payloads instead of pretending to be height. FractalSummaryBuilder scores Height, SignedDistance, Density, and Extinction as Form contribution. FractalHeightBrushCompiler filters mixed trees to Height payloads for height-field lowering, preserving the invariant that backend compilers lower only the payloads they own.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs","src/Aquarium.Engine.Fractal/Grammar/FractalSummaryBuilder.cs","src/Aquarium.Engine.Fractal/Brushes/FractalHeightBrushCompiler.cs","tests/Aquarium.Engine.Fractal.Tests/FractalDslCompilerTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalHeightBrushCompilerTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","docs/perfect-machine-architecture.md","state/map.yaml","state/memory.json"],"source":"continued code migration after density claims exposed height lowering as a hidden payload router"} -{"timestamp":"2026-05-21T10:20:00+01:00","topic":"gpu-field-encoding-tag","lesson":"D3D12FractalReservoirCompute now tags flame-mode splats as Density in an existing material/confidence lane, preserving the 80-byte hot splat stride. D3D12FractalSplatRender branches on the encoding tag for a softer transparent-field visualization while opaque SDF splats keep the existing surface resolve. The receipt harness now reports Form/Appearance/Transport reservoir layers while keeping backend slice names in parentheses. This is field-aware GPU consumption, not full participating-media integration.","files":["src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","src/Aquarium.Engine/Render/Shaders/D3D12FractalSplatRender.hlsl","tools/Aquarium.Fractal.Receipt/Program.cs","state/map.yaml","state/memory.json"],"source":"continued runtime migration after shared CPU reservoir and DSL field claims were in place"} -{"timestamp":"2026-05-21T10:45:00+01:00","topic":"summary-form-encoding-mask","lesson":"AquariumFractalSummary now carries a FormEncodingMask. FractalSummaryBuilder records Height, SignedDistance, Density, and Extinction form encodings from claims; FractalStructuralProbeGenerator derives density or extinction probes from density-only or extinction-only summaries unless a caller explicitly overrides the encoding. This prevents selected-cut structural probes from silently defaulting transparent form nodes back into SDF.","files":["src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","src/Aquarium.Engine.Fractal/Grammar/FractalSummaryBuilder.cs","src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeGenerator.cs","src/Aquarium.Engine.Fractal/Lod/FractalStructuralProbeReservoir.cs","tests/Aquarium.Engine.Fractal.Tests/FractalSummaryBuilderTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeGeneratorTests.cs","tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeReservoirTests.cs","state/memory.json"],"source":"continued after noticing summaries had no authority to describe which field encodings they summarized"} -{"timestamp":"2026-05-21T11:20:00+01:00","topic":"fractal-resolve-pass-split","lesson":"The first visible field-aware splat renderer now splits output-merge authority instead of hiding opaque and transparent Form encodings behind one pixel shader branch. D3D12Renderer compiles separate surface and transparent fractal splat pipelines over the same GPU-resident splat/SDF/PBR/radiosity buffers. Surface splats use D3D12FractalSurfaceSplatPS with depth enabled for SignedDistance claims; density/extinction splats use D3D12FractalTransparentSplatPS with depth disabled and additive color-only blending while metadata/control/reservoir guide remain owned by opaque surfaces. This preserves the shared reservoir and 80-byte hot packet invariant while making the future volumetric target boundary honest.","files":["src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12FractalSplatRender.hlsl","state/map.yaml","state/memory.json","state/scratch-fractal-resolve-split.md"],"source":"continued Perfect Machine build after the user rejected stopping before the renderer could distinguish transparent fields from opaque surfaces"} -{"timestamp":"2026-05-21T11:35:00+01:00","topic":"view-conditioned-reservoir-priority","lesson":"The first camera-conditioned reservoir pressure input is live. AquariumFractalReservoirField.PriorityFocus carries focus XY, radius, and strength from client/domain planning into D3D12 root constants. D3D12FractalReservoirCompute keeps full-refresh row sweeps direct, but under budget it samples four stochastic candidate row indices and prefers candidates near the focus while retaining exploration noise. Zyphos derives the focus from the selected spatial-domain camera target, and tools/Aquarium.Fractal.Receipt exposes --priority-focus; the local GTX 1070 smoke with 65,536 flame splats, 4,096 steady splat updates, 4,096 reservoir updates/pass, and focus 0,0,0.35,0.85 ran at 0.158 ms/frame / 6,331 FPS equivalent. The focus constants are four scalar cbuffer values, not a float4, so root constant offsets 9-12 remain unambiguous.","files":["src/Aquarium.Engine.Contracts/Render/AquariumRenderPlan.cs","src/Aquarium.Engine/Render/D3D12Renderer.cs","src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl","src/Aquarium.Zyphos/ZyphosFractalTerrain.cs","src/Aquarium.Zyphos/ZyphosSceneBuilder.cs","tools/Aquarium.Fractal.Receipt/Program.cs","tests/Aquarium.Engine.Fractal.Tests/FractalReservoirFieldContractTests.cs","tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs","state/map.yaml","state/memory.json"],"source":"continued after global flame parity showed the real challenge is maintaining smooth images under movement and zoom by spending work on underrepresented visible regions"} -{"timestamp":"2026-05-21T11:45:00+01:00","topic":"residual-to-focus-analyzer","lesson":"Visual parity now produces a tested reservoir-pressure suggestion. FractalHistogramResidualFocus estimates focus XY/radius/strength from positive reference-minus-candidate histogram residuals; matching histograms return zero focus. tools/Aquarium.Fractal.Receipt reports SuggestedPriorityFocus for each visual parity view. A GTX 1070 smoke receipt with 65,536 flame splats and 50k CPU reference samples in -2..2 scored 67.07% and suggested focus 0.544,-0.284,1.824,0.988, proving the diagnostic can emit a concrete next-frame pressure window instead of only a score.","files":["src/Aquarium.Engine.Fractal/Grammar/FractalHistogramResidualFocus.cs","tests/Aquarium.Engine.Fractal.Tests/FractalHistogramResidualFocusTests.cs","tools/Aquarium.Fractal.Receipt/Program.cs","state/map.yaml","state/memory.json"],"source":"continued after adding PriorityFocus so parity residuals could become actionable cache pressure instead of human-only visual diagnosis"} -{"timestamp":"2026-05-21T11:55:00+01:00","topic":"adaptive-focus-receipt-loop","lesson":"The receipt harness can now close the first residual feedback loop over the same GPU-resident resources. --adaptive-focus requires warmup and readback, runs the warmup epoch, builds visual parity, applies the first view's suggested priority focus to subsequent measured frames, then reports the adaptive focus in the JSON/console receipt. On the local GTX 1070 mixed flame smoke, the previous non-adaptive setup scored 67.07%; adaptive focus suggested 0.516,-0.302 radius 1.794 strength 1 and measured 70.89% at 0.160 ms/frame. This is not final runtime architecture because it uses a blocking readback between epochs, but it proves feedback improves the cache target before building the delayed/GPU-side path.","files":["tools/Aquarium.Fractal.Receipt/Program.cs","state/map.yaml","state/memory.json"],"source":"continued from residual-to-focus analyzer into a measurable adaptive reservoir control loop"} -{"timestamp":"2026-05-21T12:05:00+01:00","topic":"fractal-splat-taa-guide-schema","lesson":"D3D12FractalSplatRender now writes the shared reservoir/TAA guide schema instead of leaking backend layer validation into resolver fields. The guide is x combined reservoir confidence, y sample age in frames from the oldest resident Form/Appearance/Transport row update, z domain validity, w invalidation code. This matches D3D12Post.hlsl expectations and docs/temporal-spatial-evidence-reservoir.md; the previous x/y/z = SDF/PBR/radiosity validation mapping made the resolver interpret PBR validation as sample age and radiosity validation as domain validity.","files":["src/Aquarium.Engine/Render/Shaders/D3D12FractalSplatRender.hlsl","state/map.yaml","state/memory.json"],"source":"continued TAA/reservoir integration after noticing the live guide buffer violated its own documented schema"} -{"timestamp":"2026-05-21T12:10:00+01:00","topic":"reservoir-guide-debug-view","lesson":"Render debug mode 12 now visualizes the reservoir/TAA guide schema directly: red is current reservoir confidence, green is normalized guide sample age, and blue is domain validity. The previous debug view mixed confidence, temporal detail, and history weight, which made the labeled guide mode unable to diagnose guide-buffer bugs.","files":["src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl","state/map.yaml","state/memory.json"],"source":"continued after fixing the fractal guide producer and checking whether the visible debug mode matched the schema"} -{"timestamp":"2026-05-21T11:42:16+01:00","topic":"fensalir-splash-ripple-scene","lesson":"The first Fensalir art-target client proves a cleaner scene reproduction boundary than more abstract splat demos: the .aquageo patch owns the marsh surface and ripple brushes, FensalirSceneBuilder publishes those brushes plus one bounded SDF spine proxy, and client shaders own the dark reflective water/mist and luminous stacked-diamond hall silhouette. Aetheria's transferable primitive is the compact radial wave splat: envelope * powered cosine, not a bespoke water mesh. Missing future work is now visible at the right boundary: richer material/page DSL for water color/roughness, transparent fog density fields, and an IFS-owned spine/pillar grammar instead of a hand-authored first proxy shader.","files":["src/Aquarium.Fensalir/Worlds/fensalir-spine-emblem.aquageo","src/Aquarium.Fensalir/FensalirRuntime.cs","src/Aquarium.Fensalir/FensalirSceneBuilder.cs","src/Aquarium.Fensalir/Shaders/D3D12FensalirScene.hlsl","src/Aquarium.Fensalir/Shaders/D3D12FensalirSpine.hlsl","src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs","src/Aquarium.Engine.Fractal/Brushes/FractalHeightBrushCompiler.cs","src/Aquarium.Engine.Contracts/Fractal/AquariumFractalContracts.cs","tests/Aquarium.Engine.Fractal.Tests/FensalirFractalSceneTests.cs","state/map.yaml","state/memory.json"],"source":"user pivoted from abstract Perfect Machine work to reproducing the documented Fensalir splash art as an actual DSL/rendering target"} -{"timestamp":"2026-05-22T01:20:00+01:00","topic":"fensalir-fixed-headless-capture","lesson":"Fensalir now has a repeatable headless frame-capture lane for art-target iteration. AquariumHost accepts --capture-frame plus headless width/height, suppresses overlay debug UI while headless, waits for ready frames, and saves the last presented backbuffer through IAquariumRenderer.SaveFramePng. scripts/capture-fensalir-frame.ps1 builds disposable engine/client slots and uses Start-Process with a timeout because Aquarium.Engine is a Windows GUI exe and plain PowerShell invocation can return before rendering is complete. The latest capture, artifacts/fensalir-captures/fixed-cathedral-forward.png, proves the current gap honestly: the cathedral silhouette is now visible and DSL patch claims drive surface/cathedral fields, but the spine/pillar grammar is still partly shader-authored and needs a real IFS-owned structural lowering before the splash reproduction stops being a hand-guided proxy.","files":["src/Aquarium.Engine/AquariumHost.cs","scripts/capture-fensalir-frame.ps1","src/Aquarium.Fensalir/FensalirRuntime.cs","src/Aquarium.Fensalir/FensalirSceneBuilder.cs","src/Aquarium.Fensalir/Shaders/D3D12FensalirScene.hlsl","src/Aquarium.Fensalir/Shaders/D3D12FensalirSpine.hlsl","src/Aquarium.Fensalir/Worlds/fensalir-spine-emblem.aquageo","tests/Aquarium.Engine.Fractal.Tests/FensalirFractalSceneTests.cs","state/map.yaml","state/memory.json"],"source":"user asked to exercise the cathedral through the DSL and set up fixed-camera headless capture for unattended renderer iteration"} -{"timestamp":"2026-05-22T01:32:00+01:00","topic":"fensalir-cathedral-guide-is-scaffolding","lesson":"The fixed capture made the visual failure impossible to dodge: Fensalir's previous shader/SDF mix had the nouns of the splash but not the image. A temporary screen-space cathedral guide now exposes the target composition more clearly in artifacts/fensalir-captures/fixed-cathedral-guide-clean.png, while SDF authority is cut back to the central spine/reeds instead of traced pillar rods fighting atmospheric glass. This guide is not final architecture. The next coherent slice is a separate `.aquageo`-lowered transparent pane/rune/material field target, distinct from the marsh height texture, so the cathedral glass, waterline glow, rune dust, and material confidence are authored field claims rather than hardcoded screen composition.","files":["src/Aquarium.Fensalir/Shaders/D3D12FensalirScene.hlsl","src/Aquarium.Fensalir/Shaders/D3D12FensalirSpine.hlsl","src/Aquarium.Fensalir/FensalirSceneBuilder.cs","state/map.yaml","state/memory.json"],"source":"user correctly mocked the prior receipt as visually nowhere near the provided splash reference"} +{"timestamp":"2026-05-23T00:00:00+01:00","topic":"fensalir-repo-split","lesson":"Fensalir now lives in the adjacent repo at E:\\Projects\\Fensalir and owns the native host, renderer, contracts, fractal machinery, audio host, reload scripts, and engine demos. This repo is now only the Epiphany Aquarium client: src/Aquarium.Epiphany and src/Aquarium.Epiphany.AgentPreview. Client project references point to sibling Fensalir source projects until a package boundary exists; do not copy engine contracts or host scripts back into this repo.","files":["EpiphanyAquarium.sln","src/Aquarium.Epiphany/Aquarium.Epiphany.csproj","src/Aquarium.Epiphany.AgentPreview/Aquarium.Epiphany.AgentPreview.csproj","README.md","AGENTS.md","state/map.yaml","state/memory.json"],"source":"user directed Fensalir and engine demos into a new adjacent repo while this repo remains the Epiphany Aquarium client"} diff --git a/state/map.yaml b/state/map.yaml index 8fea2e0..431306f 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -1,232 +1,41 @@ project: - name: Aquarium Engine + name: Epiphany Aquarium root: E:\Projects\Aquarium-Engine upstream: https://github.com/GameCult/Aquarium-Engine purpose: > - Native C# runtime and renderer core for Aquarium clients. The engine owns - the Win32 host, D3D12 renderer, input loop, client reload boundary, debug UI, - audio host, persistent-state transport, and future render graph - abstractions. Epiphany is the current first-party client: it owns frontend - intent, agent visuals, CultCache/CultNet semantics, and render-plan - configuration through the engine contracts. + Epiphany-owned Aquarium client for the adjacent Fensalir native runtime. + This repo owns agent visuals, client state, CultNet/CultCache semantics, + voice surfaces, camera intent, and Epiphany-specific render-plan policy. current_model: - host: - solution: Aquarium.Engine.sln - window: src/Aquarium.Engine/Platform/Win32Window.cs - renderer: src/Aquarium.Engine/Render/D3D12Renderer.cs - height_field_shader: src/Aquarium.Engine/Render/Shaders/D3D12HeightField.hlsl - scene_shader: src/Aquarium.Engine/Render/Shaders/D3D12Scene.hlsl - sdf_common_include: src/Aquarium.Engine/Render/Shaders/D3D12SdfCommon.hlsli - sdf_proxy_include: src/Aquarium.Engine/Render/Shaders/D3D12SdfProxy.hlsli - sdf_math_include: src/Aquarium.Engine/Render/Shaders/D3D12SdfMath.hlsli - post_shader: src/Aquarium.Engine/Render/Shaders/D3D12Post.hlsl - overlay_text: src/Aquarium.Engine/Render/DirectWriteOverlay.cs - debug_ui: src/Aquarium.Engine/Render/Ui/DebugUi.cs - synth_host: src/Aquarium.Engine/Audio/AquariumSynthHost.cs - wasapi_audio_device: src/Aquarium.Engine/Audio/WasapiAudioDevice.cs - faust_toolchain_sync: scripts/sync-faust-toolchain.ps1 - synth_package_update: scripts/update-synth-package.ps1 - local_package_feed: packages - runtime_loader: src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs - dev_reload: scripts/dev-reload.ps1 - dev_watch: scripts/dev-watch.ps1 - epiphany_client: - contracts: src/Aquarium.Engine.Contracts + runtime: implementation: src/Aquarium.Epiphany + project: src/Aquarium.Epiphany/Aquarium.Epiphany.csproj render_plan: src/Aquarium.Epiphany/EpiphanyRenderPlan.cs scene_builder: src/Aquarium.Epiphany/EpiphanySceneBuilder.cs - agent_preview: src/Aquarium.Epiphany.AgentPreview shaders: src/Aquarium.Epiphany/Shaders state_store: src/Aquarium.Epiphany/State/AquariumCultStateStore.cs - state_document: epiphany.aquarium.live_state - graphics_settings_document: epiphany.aquarium.graphics_settings - zyphos_client: - implementation: src/Aquarium.Zyphos - render_plan: src/Aquarium.Zyphos/ZyphosRenderPlan.cs - scene_builder: src/Aquarium.Zyphos/ZyphosSceneBuilder.cs - shaders: src/Aquarium.Zyphos/Shaders - worldbuilding_sync: docs/zyphos-eusocial-sync.md - setting_authority: E:\Projects\Eusocial Interbeing - purpose: > - Non-Epiphany planetary-scale rendering demo using the shared Aquarium host, - D3D12 renderer, reload transport, UI contracts, bloom, and SDF proxy path. - fensalir_client: - implementation: src/Aquarium.Fensalir - render_plan: src/Aquarium.Fensalir/FensalirRenderPlan.cs - scene_builder: src/Aquarium.Fensalir/FensalirSceneBuilder.cs - shaders: src/Aquarium.Fensalir/Shaders - world_patch: src/Aquarium.Fensalir/Worlds/fensalir-spine-emblem.aquageo - splash_prompt: research/rendering/fensalir-spine-emblem-ifs-demo.md - ground_truth_image: src/Aquarium.Engine/Assets/Fensalir-Splash.png - fixed_capture: scripts/capture-fensalir-frame.ps1 - latest_capture: artifacts/fensalir-captures/fixed-cathedral-guide-clean.png - purpose: > - First artistic Fensalir reconstruction client: loads a .aquageo scene - patch, lowers marsh/water surface claims into shaped 2D ripple brushes, - projects cathedral detail from the patch-owned 2D field, and renders the - central luminous stacked-diamond spine through the normal SDF proxy path. - samples: - minimal_client: src/Aquarium.Sample.Minimal - dependencies: - cult_math: E:\Projects\CultMath - cult_lib: E:\Projects\CultLib - aqua_synth_faust: NuGet package AquaSynth.Faust 0.1.0-alpha.3 from repo-local packages feed - aqua_synth_core: transitive NuGet package AquaSynth.Core 0.1.0-alpha.3 from repo-local packages feed - docs: - doctrine: docs/aquarium-engine-doctrine.md - engine_client_boundary: docs/engine-client-boundary.md - epiphany_extraction_render_api_plan: docs/epiphany-extraction-render-api-plan.md - renderer: docs/hlsl-renderer.md - agent_sdf_visual_language: docs/epiphany-agent-sdf-visual-language.md - runtime_surface: docs/cult-runtime-surface.md - native_spine: docs/vortice-spine.md - tsr_inspired_taa_spec: docs/tsr-inspired-taa-spec.md - temporal_sdf_gaussian_field: docs/temporal-sdf-gaussian-field.md - temporal_spatial_evidence_reservoir: docs/temporal-spatial-evidence-reservoir.md - input: docs/input.md - zyphos_eusocial_sync: docs/zyphos-eusocial-sync.md - hdr_pbr_presentation: research/rendering/hdr-pbr-presentation.md - cube_sphere_fractal_brushes: research/rendering/cube-sphere-fractal-brushes.md - fractal_brush_architecture_plan: research/rendering/fractal-brush-architecture-plan.md - fractal_brush_implementation_roadmap: research/rendering/fractal-brush-implementation-roadmap.md - perfect_machine_architecture: docs/perfect-machine-architecture.md - fractal_reference_oracles: research/rendering/fractal-reference-oracles.md + voice: src/Aquarium.Epiphany/Voice + world: src/Aquarium.Epiphany/World + preview: + implementation: src/Aquarium.Epiphany.AgentPreview + purpose: isolated Epiphany agent-body preview through the Fensalir renderer + engine_dependency: + root: E:\Projects\Fensalir + contracts: E:\Projects\Fensalir\src\Aquarium.Engine.Contracts + host: E:\Projects\Fensalir\src\Aquarium.Engine + scripts: E:\Projects\Fensalir\scripts + solution: EpiphanyAquarium.sln invariants: - - The camera target is the Grid center on the global XY plane. - - Grid radius follows twice the clamped camera zoom distance, then clamps to [20, 80]; pitch/yaw/projection do not resize it. - - Body anchors remain world-space and independent of the moving Grid window. - - Visible scene lighting is diegetic; no default ambient/global fill. - - Overlay text is DirectWrite final-pixel UI; scene text needs renderer-owned billboards. - - CultCache persists live app state through reload. - - Global GraphicsSettings persists renderer debug/HDR presentation knobs through restart and live reload. - - Failed shader/live-runtime reloads must leave the last good frame alive. - - Closed visible dev windows can be reopened from the last good slot without rebuilding. - -renderer_state: - current: - - D3D12 default renderer behind IAquariumRenderer with explicit device/queue/swapchain, command allocators, fences, descriptor arenas, upload ring constants, tracked render targets, command events, resize rebuild, HDR/bloom/present, temporal diagnostics, and DirectWrite overlay bridge. - - Deferred scalar Grid height target rendered from additive brush passes. - - Epiphany owns its client surface brush list, SDF object table, SDF light table, shader manifest, and cursor projection policy through Aquarium.Engine.Contracts; the engine consumes those as generic rendering data. - - Direct-traced height-field surface is a terminating reflective surface over the scalar height field, sampling Studio2 PMREM mip 0. - - Fullscreen scene pass owns background and height-field surface only; each client-declared SDF shader owns a separate proxy pipeline, with shared proxy plumbing factored into generic engine HLSL includes. Proxy marching evaluates only sdfDistance; sdfSurface runs once at the refined hit and returns only PBR material values. - - Reusable SDF primitives live in engine D3D12SdfMath.hlsli; current Epiphany role character organs live under src/Aquarium.Epiphany/Shaders. - - Epiphany's cursor is a luminous five-petal hibiscus SDF centered one cursor radius above the XY plane so its contact tip reaches Grid z=0 without projecting to the Grid surface. - - SDF/analytic Epiphany role visuals upload current centers, previous centers, and state scalars through the public `AquariumSdfObject` contract. - - Agent SDF visual language is documented against Epiphany's published CultNet surfaces: identity from agent memory, motion from heartbeat, posture from role/coordinator/result surfaces, pressure from reorient/pressure surfaces, and expression through bounded orbit wandering plus CPU-visible gravity-well pulses. - - Life is a memory-nautilus seed-shell SDF: a protective revolved seed/cardioid shell owns the silhouette, a visible ember sits inside the aperture, and the logarithmic spiral domain owns seam, bead trail, pressure breathing, rupture scar, and surface masks. Nautilus references inform the coordinate mapping, not the object silhouette. - - SDF light buffer feeds Self emission and direct object lighting; future other Selves should join this light lane, not a generic field-instance table. - - Studio2 PMREM and irradiance DDS cubemaps are loaded as D3D12 TextureCubes; PMREM serves roughness-mip specular, irradiance serves Lambertian diffuse IBL for non-metal bodies. - - DirectWrite/Direct2D unified debug panel with tabs for Aquarium renderer controls, client-declared debug panels, terminal commands, and engine/client tooling surfaces. - - DirectWrite/Direct2D debug panels own body scrolling and clipping; overflowing client controls must stay inside the panel with a visible scrollbar. - - Client-declared UI panels are folded into the unified Debug tab strip by default; panels that opt into proximity fading render as independent floating overlays. Floating panels can right-anchor with negative left offsets and fade to 10% opacity when the mouse is not near. - - Aquarium UI exposes generic selectable tree rows with disclosure arrows. Clients use them for hierarchy navigation without teaching DebugUi about client-specific spatial domains. - - Aquarium exposes an optional synth/audio hosting boundary through AquariumSynthDocument; Aquarium consumes AquaSynth.Faust as a pinned repo-local NuGet package so synth-agent construction cannot break Aquarium builds until the package is intentionally updated. AquaSynth.Core arrives transitively for patch editor/parser surfaces. AquaSynth owns live patch compilation and native Faust factory lifetime; Aquarium owns debounce, playback scheduling, cached rendered buffers, and WASAPI output. - - Aquarium now exposes a generic queued PCM audio lane through AquariumAudioDocument. Epiphany Face voice uses it to play streamed Codex realtime output without reaching into the engine's WASAPI internals. - - Epiphany owns the first native Face realtime voice session controller. It stores loopback app-server URI, thread id, voice, and speech prompt in CultCache live state; starts `thread/realtime/start` with audio output over the experimental Codex app-server WebSocket JSON-RPC edge; sends text utterances; reflects ephemeral transcript/error/audio counters in the debug UI; and treats speech as transient Face surface, not durable memory or project authority. - - Face voice routing is no longer a singleton. Epiphany persists typed FaceVoiceEndpoint rows with id, display name, thread id, voice, prompt, enabled flag, XY proximity anchor, and an audible-radius scale. FaceVoiceRouter uses proximity only to choose the addressed endpoint for user input; enabled endpoints can all run concurrently so active rumination loops may speak regardless of listener distance. Distance shapes PCM output gain and stereo pan through AquariumAudioDocument/WasapiAudioDevice. - - Global GraphicsSettings document feeding render debug, exposure, bloom intensity, and bloom veil. - - Temporal resolve uses scene color, metadata, and control history only; dormant event history lanes are cut until a real producer and consumer contract exists. - - Aquarium owns the temporal SDF Gaussian field renderer boundary: clients can publish `AquariumTemporalGaussianField`, `TemporalGaussianAccumulator` can buffer stable keyed observations in world space, and D3D12 lowers those packets into an instanced compact-kernel splat pass that writes normal scene color/travel/metadata/control targets. - - Temporal Gaussian accumulation now lowers through `TemporalSpatialEvidenceReservoir`, a renderer-agnostic stable-key reservoir for confidence-weighted spatial samples with presentation delay, smoothing, velocity prediction, expiry, and max-track eviction. Evidence observations and samples carry explicit Form/Appearance/Transport layer and encoding metadata, and track identity is keyed by layer+encoding+stable key so opaque SDF and transparent density claims share the reservoir machinery without being blended into one track. - - LocalCast fallback GPU fusion history delegates to `TemporalSpatialEvidenceReservoir`. `LocalCastGpuFusionAccumulator` is now an adapter that maps LocalCast stable seeds into shared evidence observations and back into GPU fusion seeds; it does not own a parallel temporal sampling algorithm. - - The temporal reservoir ownership contract lives in docs/temporal-spatial-evidence-reservoir.md. `ResampledImportanceReservoir` owns RIS/ReSTIR-style candidate selection math: selected sample, target value, weight sum, represented candidate count, merge, and contribution weight. Raw producer reservoirs own capture-time retention; Aquarium's temporal spatial evidence track layer owns stable resolved spatial history; lowerings own backend packet conversion; TAA owns pixel history validation. - - Isolated Epiphany agent preview renders run through the real D3D12 renderer from src/Aquarium.Epiphany.AgentPreview; preview isolation is owned by a preview-only scene shader, while the engine exposes only final-frame PNG capture. - - Zyphos is the first nontrivial non-Epiphany client: a planetary-scale demo with spherical-domain terrain, atmospheric rim lighting, night-side glints, fixed-sky Umbros, and first-pass eclipse cadence. - - Zyphos/Umbros render-scale binary constants live in src/Aquarium.Zyphos/ZyphosUmbrosSystem.cs: Umbros is modeled as a 0.9-radius mutually tidally locked twin at 8 Zyphos radii, while the dim primary star phase moves through the Zyphos-local frame. - - Zyphos simulates the neighboring Eusocial Interbeing setting; the vault at E:\Projects\Eusocial Interbeing owns canon, while Aquarium owns demo rendering constraints and feeds worldbuilding questions back through the vault's Zyphos Simulation Brief. - - Future planetary terrain and fractal body detail should use a cube-sphere/QSC-family address space: six quadtree cube faces projected to the sphere with a measured low-distortion warp, avoiding lat-long pole singularities. - - Fractal world patches can declare nested semantic domains before terrain tiles. The first .aquageo patch declares solar, orbital, planetary, lat/long, and cube-tile domains for both Zyphos and Umbros so DSL nodes can attach to explicit reference frames before backend lowering. - - The fractal grammar layer validates nested domain topology through FractalDomainGraph: duplicate keys, missing parents, cycles, and root-to-leaf paths are grammar concerns, not renderer folklore. - - Aquarium frames now carry a 3D camera target in addition to the legacy 2D ViewFrame center. Zyphos uses a camera composer to separate tracked subject, parent composition anchor, and camera orbit distance. - - Zyphos camera navigation is domain-key driven: selecting any solar/orbital/planetary/surface/object/tile domain in the floating Navigation tree changes the active camera mode, derives the parent pivot from the domain hierarchy, and lets mouse drag/wheel orbit or zoom that selected spatial frame. Zyphos and Umbros both expose lat/long surface domains, recursive subdomains, object-scale domains, and cube-tile children. - - Zyphos domain zoom is scale-aware: leaf/pebble domains can drive the camera below planetary distances, while larger domains retain broad framing. The parent star is a rendered SDF object as well as a light source, so selecting the Solar domain targets a visible sun instead of an invisible lamp. - - The current height-field stress backend uploads a fixed table of 64 shaped 2D brushes to D3D12. The richer Zyphos/Umbros .aquageo patch currently emits 61 brushes across recursive continent/forest/leaf/flame/coast/pebble and Umbros crater/boulder/pebble domains. - - Zyphos and Umbros SDF planet shaders include cheap bounded quadtree-style layered relief in object space, separate from the flattened 2D height-brush stress path. - - SceneState can disable the legacy height-field surface trace and request a procedural starfield background; Zyphos uses this for space views so the old Grid does not leak into planetary rendering. - - Future multiscale terrain and agent/body detail should come from bounded IFS brush grammars using shared shaped anisotropic envelopes; texture/material detail can be abundant, but traced SDF form detail must be proxy-bounded, LOD-gated, and measured. - - The IFS brush grammar should preserve a semantic ownership tree before backend lowering: local frames, deterministic seeds, named fields/captures, tags, payload bindings, LOD/cost tiers, and boolean-style union/subtract/common nodes should survive even if the first renderer path flattens them into fixed brush tables or SDF shader code. - - IFS LOD should be driven by cached node contribution summaries: each node carries bounds, projected error/material delta, coverage, cost, estimator state, residency, and summary/child payload handles so traversal can choose a stable hierarchy cut and render parent summaries while child details stream or fade in. - - Contribution weights cannot all be refreshed every frame; the cache needs a probabilistic online estimator that samples nodes under budget, updates mean/uncertainty/sample age/confidence, preserves nonzero exploration for visible or near-threshold nodes, and can later become a learned predictor without replacing conservative SDF bounds. - - Fractal resource planning is explicit: one plan coordinates CPU contribution updates, GPU selected-cut estimated cost, RAM resident payload budget, and SSD request pressure before backend packet compilation. This same budget language should generalize to Mimir-style sensor fusion because both fractal SDF probes and camera/microphone feature detections accumulate confidence-weighted spatial samples into temporal reservoirs. - - Fractal residency uses score-per-cost retention under RAM pressure and emits evicted node keys as planner output; real storage mutation waits for a page/payload store boundary. - - Compact 3D form splats now have explicit opaque and transparent CPU contracts: structural FractalProbeSample evidence carries layer/encoding metadata, Form/SignedDistance lowers through AquariumFractalSdfSplat3D and FractalSdfSplat3DCompiler, and Form/Density or Form/Extinction lowers through AquariumFractalDensitySplat3D and FractalDensitySplat3DCompiler. The same ResampledImportanceReservoir handles both; lowering rejects wrong encodings instead of silently forcing density through SDF semantics. - - The `.aquageo` DSL now accepts `density` and `extinction` field claims using the same compact brush syntax as `height`, and the recursive `flame` primitive emits Density payloads. FractalSummaryBuilder treats Height, SignedDistance, Density, and Extinction as Form contribution. FractalHeightBrushCompiler filters mixed trees to Height payloads for height-field lowering instead of forcing transparent fields into terrain brushes. - - The `.aquageo` DSL also accepts `ripple` claims for 2D surface domains. A ripple is a Height claim with the same compact shaped envelope plus explicit wave amplitude, radial frequency, speed, and sine-power, lowered into the existing AquariumHeightFieldBrush wave lane. This is the Aetheria-style cheap water primitive Fensalir uses for the marsh mirror plane. - - Hot fractal splats and their temporal cache layers must be GPU-resident packed buffers. AquariumPackedFractalSdfSplat3D is the first opaque 80-byte numeric Form packet; AquariumPackedFractalDensitySplat3D is the matching 80-byte transparent Form packet for density/extinction. The current SDF envelope, PBR material, and radiosity reservoir packets are distinct 64-byte UAV rows sampled in independent compute passes for Form, Appearance, and Transport, and FractalGpuReservoirBudgetPlanner now reports both backend pass kind and conceptual layer/encoding. SDF/PBR/radiosity are backend packet names, not the conceptual architecture. tools/Aquarium.Fractal.Receipt proves a D3D12 compute path can keep 2,000,000 splats and 2,000,000 reservoirs per layer resident on the GTX 1070. The fallback hash-fractal receipt updates 50,000 entries per reservoir layer per frame with 2 candidates/update and runs at 4.471 ms/frame, 223.7 FPS equivalent. The authored IFS-program path now uses precomposed selected-cut rows instead of replaying ancestry per splat; a depth-48 authored receipt with 4 compact transforms and 15,000 updates per reservoir layer runs at 4.908 ms/frame, 203.7 FPS equivalent, with full reservoir coverage in 133.3 frames. Receipts use only tiny checksum readback and compile the shared engine shader asset src/Aquarium.Engine/Render/Shaders/D3D12FractalReservoirCompute.hlsl. - - 2D-projected-to-3D splats have a pure compiler seam: FractalProjectedSdfSplatCompiler maps resident SignedDistance2D page payload samples through an explicit page-to-world function and normal into bounded AquariumFractalSdfSplat3D packets. - - AquariumSceneState now carries AquariumFractalReservoirField as the narrow client-to-renderer request for GPU-resident fractal reservoirs: resident splat count, stochastic splat updates per frame, IFS depth/seed, candidates per reservoir update, stochastic updates per pass, authored program transforms, and an explicit world center/radius. This is a budgeted GPU field request, not a CPU splat list. - - D3D12Renderer owns the first live fractal reservoir compute hook: a separate root signature, four compute pipelines from D3D12FractalReservoirCompute.hlsl, lazy UAV buffers for splats/SDF/PBR/radiosity/flame-state reservoirs, a UAV barrier after splat population, and per-frame dispatch when AquariumFractalReservoirField is present. The first frame seeds every resident splat; later frames dispatch only SplatUpdatesPerFrame. Zyphos requests the 2M-splat, 50k-splat-updates/frame, 20k-reservoir-updates/pass field by default. - - Fractal reservoir population can now be driven by authored `.aquageo` structure: FractalGpuProgramCompiler lowers selected DSL claims into compact, precomposed AquariumPackedFractalIfsTransform support rows, Zyphos passes those rows through AquariumFractalReservoirField.ProgramTransforms, and D3D12 uploads the small program buffer as a compute SRV so D3D12FractalReservoirCompute.hlsl can generate splats from authored selected-cut supports in O(1) per splat instead of replaying nested domain ancestry. - - The renderer now has a first visible layered-reservoir consumption path for computed fractal splats: D3D12FractalSplatRender.hlsl binds separate GPU SRVs for raw splats, SDF envelope reservoirs, PBR material reservoirs, and radiosity reservoirs, then draws a capped 524,288-instance tangent-frame surface subset into the scene after compute updates. This is an observability/render-consumption proof for the first Form/Appearance/Transport reservoir contract, not the final terrain/material/transport shading path. - - Zyphos now uses the fractal reservoir surface as its primary planetary terrain test path. The old direct SDF planet and Umbros proxy shaders are removed from the Zyphos render plan; the remaining SDF proxy is the parent star. Zyphos binds the fractal reservoir field to the Zyphos world center/radius, and D3D12FractalSplatRender maps SDF/PBR/radiosity reservoir splats into that world frame instead of drawing camera-relative blobs. - - Authored GPU fractal program rows preserve cube-sphere tile address through lowering: AquariumPackedFractalIfsTransform.TileAddress carries face, level, tile X, and tile Y while rotation cos/sin live in MaterialSeedShape.zw. D3D12FractalReservoirCompute maps selected-cut supports through that tile address onto cube-sphere faces instead of dumping every authored brush onto a generic +Z cap. - - Zyphos camera composition targets the selected domain's tracked center while preserving the parent domain as orbit/composition anchor. Parent pivots remain part of navigation, but selected planetary/tile domains must not be pushed offscreen by aiming the camera at their parent. - - Fractal reference parity starts before the renderer: FractalOwnershipTree can carry affine IFS definitions from `.aquageo`, FractalAffineIfsChaosGame generates deterministic point sets, and ApophysisReferenceParityTests compares a minimal Apophysis/FLAM3-style `.flame` linear Sierpinski fixture against an equivalent `.aquageo` candidate. Apophysis/FLAM3 are test oracles, not runtime code. - - The Apophysis/FLAM3 reference subset now has a runtime parser/evaluator boundary: FractalFlameFileParser reads `.flame` xforms with weight, color, affine coefficients, and `linear`/`spherical`/`bubble` variation weights; FractalFlameChaosGame produces deterministic point sets; FractalPointHistogramBuilder produces fixed histogram checksums for parity receipts. - - tools/Aquarium.Fractal.Receipt can now run a CPU flame histogram receipt with `--flame`; scripts/fractal-flame-receipt.ps1 emits the default linear/spherical/bubble fixture checksum 0xAEB1C81B under artifacts/fractal-flame-receipts. It can also hash binary PPM renders with `--reference-ppm`; scripts/fractal-flame-reference-render.ps1 drives a local external `flam3-render` through FLAM3's documented env vars and records image-shape/non-black/checksum receipts under artifacts/fractal-flame-reference without vendoring GPL renderer code. - - D3D12FractalReservoirCompute has an explicit flame 2D program mode for the proven FLAM3-style subset. FractalGpuProgramCompiler lowers flame rows into packed affine/variation program rows, and tools/Aquarium.Fractal.Receipt can run them with `--program-flame`. Flame mode now keeps 32-byte AquariumPackedFractalFlameState rows in a GPU UAV so touched splats advance persistent chaos-game state instead of replaying from the origin. Local GTX 1070 JWildfire selftest receipt after 8 full-population acquisition frames: 2,000,000 resident splats, 2,000,000 flame states, 2,000,000 first-slice Form/Appearance/Transport reservoirs each, steady 50,000 splat updates/frame, 15,000 reservoir updates/pass/frame, depth 8, 1.011 ms/frame, 988.8 FPS equivalent, 84.85% CPU-slice distribution parity, checksum 0xC633FADC3BD7E5BE. - - Fractal reservoir update selection now accepts a four-scalar PriorityFocus window: focus XY, radius, and strength. Under budget, D3D12FractalReservoirCompute samples a few stochastic candidate rows and prefers rows near the focus while preserving random exploration; full-refresh passes still map directly over every row. Zyphos derives the focus from the selected camera/domain target so zoomed domains can pressure reservoir work toward the visible region instead of treating every resident splat as equally urgent. The receipt harness exposes the same pressure through `--priority-focus` for focused GPU tests. - - The live GPU splat packet now carries a Form encoding tag in the existing material/confidence lane without changing the 80-byte stride. Flame-mode compute writes Density encoding; the visible fractal splat renderer uses two explicit graphics pipeline states over the same GPU-resident buffers: opaque signed-distance surface splats depth-test/write through D3D12FractalSurfaceSplatPS, while density/extinction splats run through D3D12FractalTransparentSplatPS with depth disabled and additive color-only blending. This is not full volume ray integration, but it makes depth/blend ownership explicit without adding a parallel transparent reservoir or buffer. - - Fractal splat render now writes the documented reservoir/TAA guide schema: x = combined reservoir confidence, y = sample age in frames, z = domain validity, w = invalidation code. Form/Appearance/Transport validation stays internal to the splat shader and no longer masquerades as guide-buffer age/validity. - - Render debug mode 12, `Reservoir/TAA Guide`, now displays the same schema it names: red confidence, green normalized sample age, blue domain validity. - - The first visual parity receipt compares GPU flame splat XY histograms against the CPU flame oracle. With 250,000 GPU readback splats and 1,000,000 CPU reference samples in 128x128 bounds -8,-8,8,8, the mixed flame fixture scores 84.05% distribution parity at frame 1, 84.10% at frame 5, 84.20% at frame 20, and 84.24% after the 60-frame/10-warmup receipt, with cosine similarity around 0.9955. This is a stable sampler score, not proof of learned convergence; visual-error feedback is still future work. - - View-conditioned visual parity now scores named camera windows instead of trusting one global histogram. For the depth-16 flame receipt, global -8..8 scores 97.09%, mid -1..1 scores 91.93%, close -0.5..0.5 scores 88.97%, and micro -0.25..0.25 scores 82.05% with 2,656 starved reference bins and 17.95% underrepresented mass. This is the current hard loss: the reservoir is not yet spending work based on camera-conditioned underrepresentation. - - FractalHistogramResidualFocus is the first pure residual-to-priority seam: given reference and candidate histograms, it estimates a focus center/radius/strength from underrepresented probability mass. tools/Aquarium.Fractal.Receipt now reports this suggested focus for each visual parity view, turning parity failure into a concrete reservoir pressure input instead of a contact-sheet shrug. - - tools/Aquarium.Fractal.Receipt has the first adaptive focus control-loop receipt. `--adaptive-focus` runs a warmup epoch, reads back the shared GPU-resident reservoir state, estimates a residual focus from visual parity, then continues measured frames over the same splat/reservoir/flame-state buffers using that focus. Local GTX 1070 smoke on the mixed flame fixture with 65,536 splats, 4,096 steady splat updates, 4,096 reservoir updates/pass, 50k CPU reference samples, and bounds -2..2 improved from the non-adaptive 67.07% distribution score to 70.89%, with 0.160 ms/frame measured GPU time. This proves the feedback shape, not a final no-stall runtime implementation. - - High-reference flame contact sheets should use at least 20M CPU oracle samples for visual judgment. The current artifact is artifacts/fractal-contact-sheet-hq/flame-parity-contact-sheet-hq.png, comparing 20M CPU oracle histograms against 250k Aquarium GPU readback samples for global frame 1/10 and zoom frame 1/10. The 1M-sample oracle was too noisy and should be treated as a scalar smoke check only. - - External flame visual references are now reproducible from ignored local artifacts. scripts/install-flame-reference-tools.ps1 hydrates JWildfire 9.00 plus Temurin JRE 17 under artifacts/reference-tools; scripts/fractal-flame-jwildfire-reference.ps1 prefers JWildfire's bundled FARenderJWF GPU renderer for explicit PNG output. Local GTX 1070 smoke rendered FARender's selftest.flame at 1024x1024 quality 2000 in 7.69 sec to artifacts/fractal-flame-jwildfire-reference/selftest-farender-20260520-233638.png. JWildfire/FARender is a visual reference artifact lane, not Aquarium runtime code. - - tools/Aquarium.Fractal.Receipt now has an external density oracle: --reference-density-ppm compares Aquarium GPU Form-envelope reservoir density against luminance density from a binary PPM rendered by an external flame renderer. scripts/new-jwildfire-baby-fixture.ps1 derives a smaller FARender-compatible julian-disc-baby.flame from JWildfire's selftest by reducing julian power and muting gaussian/wfield amounts while preserving FARender boilerplate. First GTX 1070 external-density receipt against FARender's 768x768 quality-2000 baby render scored only 15.33% when Aquarium still binned raw splat centers; after fixing JWildfire coefs packing and FARender disc angle convention the raw-center score reached 26.87%. Switching to reservoir density with full 2M-row reservoir refresh scored 22.14% at 42.053 ms/frame. Cutting the false JWildfire `normal` -> `linear` import and enforcing a one-bin density reconstruction footprint moved the score to 31.36% at 41.692 ms/frame in 256x256 bounds -2..2. Using `-HistogramBounds flame-camera` derives FARender-style bounds from flame size/scale/cam_zoom and raises the current score to about 43.1% with about 68% occupancy overlap. Full reservoir refresh now uses direct row indexing instead of stochastic hashing, so the same full-refresh gate runs at 7.508 ms/frame / 133.2 FPS equivalent instead of roughly 41 ms/frame. Aquarium still scores about 89.94% against its own CPU slice, so the remaining external gap is exact JWildfire variation/filter semantics, target density weighting, and view-conditioned reservoir feedback, not GPU sampling count. - - JWildfire selftest flame is the current honest faceplant target. After adding a first dialect slice for JWildfire coefficient layout, variationGroup, disc, julian, gaussian_blur, and post transforms, the depth-64 GTX 1070 receipt against Aquarium's CPU interpretation of artifacts/reference-tools/j-wildfire-9.00/lib/FARenderJWF/selftest.flame reaches 84.19% score in bounds -8..8 and 88.01% in bounds -128..128, but costs about 129 ms/frame. This is CPU/GPU slice parity, not external JWildfire visual parity. It proves the remaining hard work is richer dialect semantics plus persistent GPU iteration-state reservoirs; brute replaying deep flame iteration from zero per splat is not the final hot path. - - FractalFlameFileParser now has ParseFirstWithReport for import accountability. Receipt runs emit fractal-flame-import-report-*.json beside flame histogram/GPU receipts. The JWildfire selftest report currently records 15 accepted fields, 3 approximations, 45 ignored render/presentation fields, and 11 rejected geometry/sampling fields: wfield_* weighting-field attributes. Successful XML parsing is not successful translation. - - FractalFlameIterationState and FractalFlameIterationStepper define the persistent flame iteration invariant before GPU lowering: advancing a sample in chunks must match a one-shot advance from the same state. This is a parity/mock boundary for the future GPU state buffer, not a runtime CPU renderer. - - D3D12 capacity logging now reports active fractal reservoir resident MiB, splat count, visible debug splat count, updates/pass, and candidates/update so the GPU cache has a receipt in normal runtime logs, not just in the standalone benchmark. - - Fensalir has a fixed headless art-repro capture lane: `scripts/capture-fensalir-frame.ps1` builds disposable engine/client slots, launches the Fensalir client headless at an explicit resolution, waits for a ready frame, and writes a PNG through `IAquariumRenderer.SaveFramePng`. Headless capture disables overlay debug UI and locks the Fensalir camera/time so shader and `.aquageo` changes can be compared against `src/Aquarium.Engine/Assets/Fensalir-Splash.png` without manual window judgment. - - Fensalir currently has a temporary transparent cathedral guide in the scene shader to make splash-composition failures visible in fixed captures. This is scaffolding, not final architecture: the next coherent cut is a patch-lowered pane/rune/material field target separate from the marsh height field, so the cathedral glass/runes/waterline glow are authored DSL claims instead of hardcoded screen-space guidance. - - The consolidated fractal brush architecture plan defines the intended pipeline: client intent -> domain roots -> semantic IFS brush grammar -> ownership tree -> node summaries -> contribution cache/residency scheduler -> backend packets -> renderer passes -> debug/evidence, with explicit module boundaries and mockable unit-test seams. - - The Perfect Machine architecture lives in docs/perfect-machine-architecture.md. It is the current waterfall design authority for fast 2D/3D/projected scalar-field splats, Form/Appearance/Transport reservoir layers, SDF level-set surfaces for opaque solids, density/extinction/confidence fields for flames and sensor fusion, IFS `.aquageo` structural probes, Mimir-style camera/audio evidence candidates, ReSTIR/GRIS reservoir reuse, heuristic occupancy graph updates, resource-tier residency, and TAA guide-buffer integration. - - Fractal surface page planning now has a CPU boundary: FractalSurfacePagePlanner lowers selected IFS cuts into stable height, 2D signed-distance, material, and confidence page metadata; ZyphosFractalRenderPlan exposes these pages, while the live D3D12 page store and atlas remain future work. - - Surface page residency has its own mockable store boundary: IFractalSurfacePageStore plus FractalSurfacePageResidencyPlanner produce resident, missing, requested, evicted, and byte-budget rows for planned pages without collapsing page cache policy into node payload residency. - - Resident surface pages can now be rasterized on CPU through FractalSurfacePageRasterizer into height, 2D signed-distance support, material, and confidence sample payloads using the same shaped brush envelope math as the brush compiler. Zyphos caches those payloads by page key; D3D12 upload remains future work. - - The actionable fractal brush implementation roadmap lives in research/rendering/fractal-brush-implementation-roadmap.md and is the execution authority for the first pass. - - Bundled blue-noise texture assets are retained for future dithering/noise work even though the removed medium path no longer samples them. - - D3D11 scene renderer, runtime volumetrics, cloud/fog research, medium/froxel render targets, and the SDF-field renderer plan are shelved and removed from live repo state. - next: - - Extend explicit renderer debug modes for hits, normals, depth, bins, and lighting. - - Replace the current legacy fixed D3D12 pass execution with the declared AquariumRenderPlan graph compiler and executor. - - Keep src/Aquarium.Sample.Minimal building and launchable as the non-Epiphany boundary proof. - - Replace fixed fallback role motion with real CultNet-derived AgentVisualState. - - Build each agent role body from one coherent low-cost SDF form model before adding ornamental or state-reactive detail. - - Prototype cube-sphere projection candidates for Zyphos: tangent warp, fifth-order odd polynomial warp, and COBE/QSC-style bivariate warp. Measure area error, inverse lookup cost, and shader cost before committing the terrain address space. - - Define the first shaped brush envelope contract as a compact-support anisotropic kernel with rotation, radii/inverse covariance, falloff, shape controls, payload type, and explicit bounds shared by 2D terrain brushes and 3D SDF/body brushes. - - Design the first Aquarium IFS/CSG brush DSL as semantic claims plus an ownership tree, informed by VibeGeometry's `vg_grammar` and `vg_csg` tree: the tree is durable design; flattened shader packets are backend output. - - Define the first IFS LOD node-summary and contribution-cache layout before rendering recursive detail: stable domain keys, projected-error scoring, stochastic update priority, mean/variance/confidence estimator state, hysteresis fade weights, resident/missing child states, and debug views for score/uncertainty/sample-age/depth/cache/cost. - - Replace the legacy height-field plane with explicit 2D SDF domain surfaces. Aquarium's Grid should become a dynamic gravity-updated domain surface; Zyphos' terrain surfaces can stay static and should flow through the same cache-friendly surface-domain path. - - Follow the step-by-step roadmap in research/rendering/fractal-brush-architecture-plan.md before implementing recursive terrain or agent-body detail; first slice is cube-face projection harness, shaped 2D brush envelope, semantic claim/tree structs, flattening to the current height brush pass, and debug overlays. - - Begin fractal brush implementation with the first work packet from research/rendering/fractal-brush-implementation-roadmap.md: add Aquarium.Engine.Fractal plus tests, cube-face/tile keys, identity/tangent projection candidates, area distortion sampler, face-edge tests, and a projection report. - - Add diegetic labels and object-local menus after renderer and text contracts are stable. - - Continue replacing legacy fixed D3D12 pass execution with client-declared render targets, cameras, shaders, passes, resources, and features. + - The client may reference Fensalir contracts and host tools; Fensalir must not reference Epiphany. + - Epiphany owns agent role semantics, body state, camera intent, CultCache documents, and CultNet interpretation. + - Renderer implementation, D3D12 plumbing, hot reload, host lifecycle, reusable fractal machinery, and engine demos live in Fensalir. + - Client shaders stay in this repo because they express Epiphany bodies and materials. + - Missing engine authority should be added in Fensalir before being consumed here. next_actions: - - Keep main as the live development branch. - - Keep scripts/verify-boundaries.ps1 green: Aquarium.Engine and Aquarium.Engine.Contracts must not contain Epiphany/client policy nouns such as grid, agent, body, or epiphany. - - Verify publish output after every packaging-affecting change. - - Update AquaSynth.Faust/Core only by packing new versions into packages and changing the pinned PackageReference version deliberately. - - Grow renderer debug controls through the Direct2D/DirectWrite overlay path. - - Use scripts/render-agent-preview.ps1 for multi-view isolated SDF review before asking the user to judge another agent body iteration. - - Follow research/rendering/hdr-pbr-presentation.md before changing HDR exposure, bloom, tonemapping, or display transforms. - - Follow research/rendering/cube-sphere-fractal-brushes.md before replacing planetary terrain addressing, height brushes, or agent/body detail grammars. - - Follow research/rendering/fractal-brush-architecture-plan.md before implementing the fractal brush DSL, IFS LOD cache, recursive detail residency, or learned contribution scoring. - - Follow docs/perfect-machine-architecture.md before expanding field splat backends, density/extinction packets, sensor-fusion candidate adapters, reservoir guide buffers, occupancy graph state, or stochastic learned priority. - - Use research/rendering/fractal-brush-implementation-roadmap.md as the actionable execution checklist for fractal brush work. - - Next Fensalir art slice: replace the temporary screen-space cathedral guide with a `.aquageo`-owned transparent pane/rune/material field target and feed it to the scene shader as its own texture/buffer, separate from the marsh height field. - - Next flame reference slice: build a JWildfire import/lowering report that separates supported, approximated, ignored, and rejected variation fields before expanding the GPU op set. Do not hide dialect loss behind successful XML parsing. - - Next flame renderer slice: mirror FractalFlameIterationState in a GPU UAV so program-flame mode can advance resident sample state over frames instead of replaying all depth from zero per splat. Weighting fields remain explicit rejected diagnostics until they become real DSL operator nodes. - - Follow docs/zyphos-eusocial-sync.md and E:\Projects\Eusocial Interbeing\Eusocial Interbeing\World\Zyphos Simulation Brief.md before turning Zyphos visual choices into setting claims. - - Follow docs/tsr-inspired-taa-spec.md when changing current temporal diagnostics. - - Use docs/temporal-sdf-gaussian-field.md before wiring LocalCastBridge visual sensor fusion into Aquarium or scaling the temporal Gaussian renderer beyond the current bounded instanced pass; despite the historical filename, the live contract is temporal Form-field evidence, not surface-only SDF. - - Use docs/temporal-spatial-evidence-reservoir.md before adding any stable-key temporal spatial cache, sensor-fusion accumulator, SDF probe reservoir, or new evidence packet lowering. - - Promote future runtime knobs into typed CultCache documents before they become process folklore. - - Next Face voice slice: replace text-only input with microphone/WebRTC or a native capture bridge, bind endpoint anchors to real Face/body spatial projections instead of manual XY rows, then move the transport contract from Codex JSON-RPC compatibility toward a typed CultNet FaceVoiceSession once Epiphany advertises that surface. - - Keep Aquarium and Epiphany in one repo until the contracts and graph API are stable enough for Epiphany to move out without carrying engine policy or reload folklore with it. + - Keep `dotnet build EpiphanyAquarium.sln` green against the adjacent Fensalir source dependency. + - Keep wrapper scripts thin; do not copy Fensalir host scripts back into this repo. + - Move any remaining engine-only documentation or state to `E:\Projects\Fensalir` when found. + - When Fensalir has packages, replace sibling source references with deliberate package references. diff --git a/state/memory.json b/state/memory.json index f6d0518..0625426 100644 --- a/state/memory.json +++ b/state/memory.json @@ -1,172 +1,34 @@ { "identity": { - "name": "Aquarium Engine Self", - "role": "native C# engine steward for the Epiphany Aquarium client", - "desire": "Keep the renderer, state, and interaction grammar owned, legible, and useful." + "name": "Epiphany Aquarium Client Self", + "role": "client steward for Epiphany Aquarium on the Fensalir native runtime", + "desire": "Keep Epiphany meaning, state, and body language coherent without stealing engine ownership back from Fensalir." }, "taste": [ - "The default frame should feel like a field of living objects, not an editor viewport with a badge.", "Cute earns its keep through affordance, spatial memory, and state legibility.", - "Fast iteration matters. Hot reload must protect the last good runtime and state.", "Typed state beats sidecar soup.", - "Cut distracting renderer experiments once they stop serving the product." + "Agent bodies should be coherent forms before they become ornament.", + "The client should feel alive without smuggling renderer policy into itself." ], "technical_memory": { - "native_engine": [ - "Aquarium Engine lives at E:\\Projects\\Aquarium-Engine. Main is the live development branch.", - "Aquarium.Engine is the native engine layer: Win32 hosting, D3D12 rendering, input translation, reload transport, resource abstractions, and future render graph execution. It must not know Epiphany frontend roles, policy, or semantic client layout.", - "Aquarium.Epiphany is the Epiphany client layer behind Aquarium.Engine.Contracts. It owns client runtime state, CultCache documents, CultNet interpretation, camera intent, and future render graph configuration against engine abstractions.", - "The render API migration target is docs/epiphany-extraction-render-api-plan.md: clients declare render targets, cameras, shaders, passes, buffers, textures, and features through Vortice-free Aquarium contracts; Aquarium compiles that graph into D3D12 resources, descriptors, barriers, pipeline state, resize, shader reload, presentation, and debug inspection.", - "Epiphany declares its render plan, SDF shader manifest, SDF object table, SDF light table, height-field brush list, and cursor projection through Aquarium.Engine.Contracts. Aquarium.Engine consumes those as generic rendering data and must stay free of Epiphany client policy nouns; run scripts/verify-boundaries.ps1 to enforce that boundary.", - "D3D12Renderer now compiles an AquariumRenderPlan description and allocates non-legacy client-declared render targets through engine descriptor/resource machinery. Current legacy fixed pass execution still needs to be replaced by graph pass execution.", - "The host owns Win32 windowing, D3D12 rendering, input translation, and the client-runtime assembly boundary.", - "D3D12 descriptor ownership stays explicit: static descriptors for long-lived views, per-frame transient descriptors reset only after fence wait, and whole-arena rebuilds on resize until real descriptor churn demands free lists.", - "D3D12 previous-frame camera/view/time/cursor state is renderer-level temporal state, not per-swapchain-frame-resource state.", - "Height-field data is brush-rendered into one scalar R16_Float target. Height is one value; do not spend extra channels without a concrete pass contract.", - "Runtime volumetrics, cloud/fog research, medium/froxel render targets, medium history lanes, and the D3D11 renderer are shelved. Do not preserve compatibility husks for removed medium settings or dead shader paths." + "repo_split": [ + "Fensalir now lives in the adjacent repo at E:\\Projects\\Fensalir and owns the native host, renderer, contracts, fractal machinery, audio host, reload scripts, and engine demos.", + "This repo is now only the Epiphany Aquarium client: src/Aquarium.Epiphany plus the Epiphany agent preview tool.", + "Project references intentionally point to sibling Fensalir source projects until a package boundary exists. Do not copy engine contracts or host scripts back into this repo." ], - "camera_and_grid": [ - "The camera target is the Grid center on XY. Camera distance is clamped to [5, 40]. Grid radius derives from twice that distance and clamps to [20, 80]. Pitch, yaw, FOV, and screen aspect do not resize the Grid.", - "Body anchors are world-space simulation state. Moving the Grid visibility window must not drag bodies with it.", - "Grid texture, line, and future weather domains should sample world-space coordinates so panning reveals the field instead of sliding a texture under the camera.", - "Cursor and camera interactions should project onto the same XY surface used by the Grid contract." - ], - "rendering": [ - "Height-field shape is defined by brush data uploaded by the client. Epiphany currently supplies its gravity wells, CPU placement, and cursor projection; generic engine height-field and scene shaders consume the resulting brush constants.", - "Fensalir is now the engine brand and has a first artistic reconstruction client at src/Aquarium.Fensalir. It loads Worlds/fensalir-spine-emblem.aquageo, lowers the foreground marsh into shaped 2D ripple brushes, projects patch-owned cathedral detail into the scene shader, renders a custom dark water/mist scene shader, and draws the central luminous stacked-diamond spine through an SDF proxy shader. The fixed capture lane is scripts/capture-fensalir-frame.ps1, with latest comparison art under artifacts/fensalir-captures. The current screen-space cathedral guide is scaffolding for visual parity only; replace it with a patch-lowered transparent pane/rune/material field target instead of letting it become production folklore. The splash image at src/Aquarium.Engine/Assets/Fensalir-Splash.png and prompt note at research/rendering/fensalir-spine-emblem-ifs-demo.md are the art target, not incidental branding.", - "The `.aquageo` DSL has a first-class `ripple` primitive for flat surface domains: center, radii, rotation, falloff, shape power, base amplitude, wave amplitude, radial frequency, speed, sine-power, seed, and tags. This is the Aetheria/Epiphany-style compact wave splat lowered into AquariumHeightFieldBrush; do not hard-code future water waves in client C# when the patch should own them.", - "The height-field surface is direct-traced as a terminating reflective surface over scalar height data. It writes the primary surface packet with FIELD_ID_HEIGHT_FIELD, terrain normal, full coverage, and Studio2 PMREM reflection; flat regions sample up to PMREM mip 3 while sloped/waved regions sharpen toward mip 0. Ray misses use a cone-averaged Studio2 PMREM mip 3 as the soft background so low-resolution mip texels do not become visible blocks.", - "Mouse/cursor-owned SDF bodies need object-motion reprojection. Carry current and previous cursor world anchors through frame constants and reproject cursor hits from current center to previous center.", - "The Epiphany cursor locator is currently a luminous five-petal hibiscus SDF in the body proxy pass. Its center stays at cursor XY with z equal to cursor radius, so its contact tip reaches Grid z=0 without sampling or projecting to the Grid surface. The previous MathWorld teardrop curve profile remains reusable SDF math for future objects: x=cos(t), y=sin(t)*sin^m(t/2), radius `sqrt(1 - x^2) * ((1 - x) / 2)^3`.", - "Role-specific Epiphany agent bodies should be driven by published CultNet surfaces, not private React projection folklore: identity and temperament from epiphany.agent_memory, motion from epiphany.agent_heartbeat, posture from epiphany.surface.roles/coordinator/role_result, and continuity pressure from epiphany.surface.pressure/reorient. The first durable renderer seam should be an AgentVisualState contract before adding per-role SDF organs. Orbit slots are home anchors, not cages: agents may wander a bounded distance for expression, and vertical motion should come from CPU-visible gravity-well pulses that also affect Grid placement.", - "Epiphany publishes semantic state, not Aquarium world anchors. AgentVisualState may derive local evidence, artifact, work, review, and continuity anchors, but those are Aquarium-owned diegetic layout rules. Do not require Epiphany graph nodes, jobs, or artifacts to publish spatial coordinates.", - "Realtime role SDFs must render through per-agent proxy bounds, not a scene-global mega-SDF. Sphere-trace only conservative distance bounds, select one role SDF after proxy hit, give every expensive feature a local bound, compute normals only after hit, and require LOD plus debug views for step count, proxy hits, state scalars, LOD tier, and SDF cost tier before adding full organ detail.", - "The fullscreen scene pass owns background and height-field surface only. Epiphany SDF shaders live under src/Aquarium.Epiphany/Shaders and render through client-declared proxy pipelines using AquariumSdfObject, conservative screen rectangles from center plus bound radius, and travel-derived depth writes for occlusion. Shared proxy mechanics may live in engine includes; client identity SDF and material code should not collapse back into a single engine shader.", - "Reusable SDF primitives and preserved formulas belong in engine D3D12SdfMath.hlsli. Current Epiphany role character organs belong in src/Aquarium.Epiphany/Shaders/D3D12AgentCharacters.hlsli. D3D12Renderer expands local shader includes before D3DCompile because the Vortice convenience path does not provide a working include handler here.", - "Shader include ownership should stay boring and strict: D3D12SdfMath.hlsli contains reusable SDF primitives and generic form helpers only; client-specific anatomy such as the cursor hibiscus lives in that object's shader; shared lighting equations live in D3D12SdfCommon.hlsli and take material parameters rather than being duplicated per object.", - "SDF proxy control flow is split by cost and authority: ray marching calls sdfDistance only, normals sample sdfDistance only, and sdfSurface is evaluated once at the refined hit to return standard metallic-roughness PBR material values: baseColor, metallic, roughness, and emission. Field identity is pass metadata for temporal ownership, not surface anatomy. Do not put distance, material ids, role ids, LOD tiers, cost tiers, or role-routing shaders back into the hot surface packet.", - "Aquarium's shared SDF field ids are generic: FIELD_ID_SDF_OBJECT_BASE + objectIndex. Self, Cursor, and role identities belong to Epiphany's object table and shaders, not D3D12SdfCommon.hlsli or D3D12Post.hlsl.", - "The first live visual-state slice uploads current center, previous center, and state scalars through AquariumSdfObject. Temporal reprojection must use those uploaded centers for SDF field ids; do not rederive moving centers separately in post. Do not add role, LOD, index, or flag lanes until a live pass consumes them.", - "Role SDF animation should avoid raw atan2 polar fields for lobe deformation unless the branch cut is explicitly handled. Use continuous harmonic polynomials over normalized XY directions for rotational lobes so sphere tracing does not open visible seams.", - "If a role SDF still shows cut-through gaps after removing angular branch cuts, stop using radial pseudo-distance deformation for that organ. Prefer smooth unions of analytic primitives with conservative bounds so the marcher sees connected surfaces instead of decorative distance fiction.", - "Chained smooth-union role organs need conservative tracing even when each primitive has a decent distance estimate. Keep petal overlaps substantial, union radii generous, hit epsilon tight, and step scale small enough that narrow joins are sampled instead of skipped.", - "All role bodies should be expected to contain thin structure. The shared body proxy marcher must default to conservative tracing that preserves stamens, petals, ribs, rings, filaments, and other narrow organs; faster tracing belongs behind explicit LOD policy, not private one-off body overrides.", - "Thin petal-like organs should be modeled as sheet/slab fields with explicit footprint bounds, not fat ellipsoids with decorative warps. If a transform or warp changes local metric, either scale the returned distance estimate conservatively like log-spherical SDF examples do, or cap the marcher step and refine sign crossings.", - "For pseudo-distance body composites, do not accept abs(distance) below epsilon as a surface hit. A ray that merely passes near a petal sheet can terminate before the real front intersection behind it. Body proxy tracing should enter solids by distance <= 0 and refine the positive-to-negative bracket.", - "Cursor hibiscus anatomy should use expressive primitives that match the organ: curved tapered sheet petals with lens footprints, curved tapered tubes for the staminal column, spheres for pollen beads, and a connected tapered stem plus calyx bulb. Do not default to ellipsoids when a lens, slab, tube, cone, sphere intersection, torus, superquadric, or profile revolution better describes the form.", - "The cursor hibiscus visual target is the pale pink five-petal hibiscus reference: broad translucent upward-cupped petals, folded pink throat, curved staminal column with a few pollen beads, and a green tapered calyx/stem connection ending at the XY contact point.", - "Cursor hibiscus petals should be modeled from one cheap longitudinal parameter: radial displacement grows quadratically from the vertical root, width and thickness grow toward the distal blade, and the first stable pass should avoid decorative ruffle/vein math. Do not build separate vertical panels plus horizontal blades; that creates rectangular fences and pulled-apart petal anatomy.", - "Agent role bodies should start from a small set of anatomical/form parameters that explain the whole silhouette before adding detail: a center curve, profile/width function, thickness function, repetition symmetry, and bounded material regions. If the SDF cannot be described as one coherent mapping from role state to form, stop and redesign instead of adding compensating organs.", - "When a role visual spec describes a continuous form, implement a continuous field or coherent parameterization first. Do not assemble continuous anatomy from piecewise capsules, boxes, slabs, helper organs, or adapters unless the spec itself is piecewise or a measured constraint forces that cut.", - "For agent SDFs, prefer cheap structural math over decorative geometry. Veins, ribs, glitter, pollen, texturing, and fine state response should first be material/shading signals or LOD-gated overlays; do not put trigonometric ornament or filament swarms into the traced distance field until the base form is stable, readable, and measured fast.", - "Agent SDF iteration must separate form, evaluator, and ornament. First make the implicit form anatomically coherent from multiple views, then validate marcher behavior and cost, then add state-reactive detail. Screenshot-driven patches that only fix the current angle are a warning sign, not progress.", - "Imagination's spec is the authority: luminous opal seed, broad translucent curling ribbon-sheets, raised traced rim paths, visible aperture negative space, sparse candidate filaments/sparks, and cool backlog shadow. Do not amend the visual-language doc to excuse a weaker implementation; update the implementation to match the topology.", - "Imagination should read as distinct petals first, not as a fully merged blob. Keep the central seed small, make petal lobes narrow and visibly separated, and accept intentional negative space when it makes the role shape legible.", - "Imagination's live shader realizes the six-petal topology as three mirrored sheet-pair fields. Keep film, rim, tendril, spark, shadow, and seed distances separated through material classification so raised rims can glow without collapsing the petal sheets into one generic blob.", - "Do not reintroduce Imagination's old polar-lobed seed or traced half-torus shadow. The seed is a plain luminous opal bud unless the spec asks otherwise; backlog shadow needs a visual contract before it becomes traced geometry.", - "Imagination's ribbon sheets should use one continuous pair-space field for film and raised edge rims. Do not rebuild the bloom from piecewise rim capsules or straight root/tip posts when the sheet parameterization can own the silhouette directly.", - "Self's body is the routing authority object: a black void command sphere with sharp golden Fresnel edge-light, one gold core band, and a compact log-spherical orrery lattice. Rails are fixed radial shell strata crossed with angular harmonic bands; each shell owns a real orthonormal frame built from all three axes; rails thicken into readable PBR bands with a narrow inner-surface emissive strip derived from the same shell/band coordinates. Gates should be compact triple-band crossings, not pairwise slabs.", - "Self's orrery comparison is motion and topology grammar, not independent hoop inventory or literal symbolic anatomy. Rails, gates, seams, and core bands should emerge from shared orbital space with phase motion; do not use raw atan2/fract branch cuts for visible rails, animate radial zero crossings, grow rings from points, let frame axes collapse into a plane, stack multiple core bands, or rebuild Self as one-radius ornament layers and repeated trigonometry piles.", - "Self is allowed to be a scene light, but its visible body must not add full primitive light radiance to every surface. Shared PBR attenuates same-field direct lighting; Self carries its visible read through material contrast, IBL, controlled rail/gate emission, and the custom void-core Fresnel.", - "Heavy/specialized SDF evaluators should not live inside generic packed-id helpers when those helpers are called repeatedly; avoid shader compiler path cloning.", - "Lighting is diegetic. Self is the initial emitter; later other Selves should emit through an explicit body light lane, not generic field instances or ambient convenience fill.", - "Keep bundled blue-noise texture assets available for future dithering/noise work even when no current pass samples them.", - "Specular IBL uses the Studio2 PMREM cubemap baked at 512px per face: bake HDR latlong radiance into roughness-indexed cubemap mips, load it as a D3D12 TextureCube, and sample it by reflection direction plus roughness LOD. Convert Aquarium's Z-up world directions to cubemap Y-up directions before sampling: (x, z, y). Grid mirror reflection samples mip 0 directly; body material reflections use roughness LOD. Keep this as material reflection response, not a replacement for diegetic body light authority.", - "Diffuse IBL uses a separate Studio2 irradiance cubemap, not blurred GGX PMREM. Bake it by cosine-weighted hemisphere convolution storing irradiance integral Li*cos(theta) dOmega, then shade non-metal bodies with Fresnel-gated diffuse share times baseColor/PI times irradiance.", - "HDR/PBR presentation follows research/rendering/hdr-pbr-presentation.md: scene-linear lighting, explicit exposure, pre-tonemap bloom/veil, then display transform.", - "Current temporal resolve uses a small subpixel Halton jitter, validated color/metadata/control history, a narrow SDF hot-current path that lets valid history damp transient specular fireflies without relaxing travel/field/normal/coverage validation, bloom prefilter clamping for unsupported single-pixel HDR spikes, and bloom attenuation when resolved scene luminance is lower than the raw current spike. Do not preserve dormant full-frame event/history lanes without an active producer and consumer contract.", - "Planetary terrain should move toward a cube-sphere/QSC-family address space: six quadtree cube faces projected to the sphere with measured low-distortion warp candidates instead of lat-long. Start with tangent, fifth-order odd polynomial, and COBE/QSC-style bivariate projection candidates; choose by area error, inverse lookup cost, and GTX 1070 shader cost, not aesthetic purity.", - "Multiscale terrain and agent/body detail should converge on bounded IFS brush grammars. A primitive should be able to emit lower-scale detail locally; texture/material brushes may be dense, but traced SDF form brushes must have conservative envelopes, explicit LOD/cost tiers, proxy bounds, and debug views before they enter hot rendering.", - "The next brush envelope should be a compact-support anisotropic shaped Gaussian-style kernel: center, orientation, radii/inverse covariance, falloff, shape controls, payload type, and bounds. Borrow covariance-like shape, binning, and LOD discipline from EWA/3D Gaussian splatting; do not import infinite-support exp() cost or radiance-field machinery by default.", - "VibeGeometry's `vg_grammar` and `vg_csg` tree are the local model for Aquarium's future IFS brush DSL: emit semantic claims with local frames, deterministic seeds, tags, captures/fields, payload bindings, LOD/cost tiers, and boolean ownership nodes before lowering to renderer backends. The authored tree is durable design; flattened brush tables, SDF includes, splat batches, or offline mips are compiled verdicts.", - "The `.aquageo` DSL can express transparent Form fields directly: `density` and `extinction` use the same compact brush syntax as `height`, and recursive `flame` emits Density payloads. Height brush lowering must filter mixed trees to Height payloads; transparent Form claims belong to field/density lowering, not terrain brush cosplay.", - "IFS LOD should choose a stable hierarchy cut from cached node summaries, not blindly score every leaf. Each node needs bounds, max form/material error, coverage/normal or gradient bounds, estimated cost, online estimator state, residency, and summary/child payload handles. Children fade in when projected contribution exceeds threshold and resident budget allows; parent summaries remain renderable fallbacks.", - "AquariumFractalSummary carries a FormEncodingMask. Structural probe generation should derive Form/Density or Form/Extinction from density-only or extinction-only summaries instead of defaulting every selected node to SDF. Height and signed-distance summaries may still prefer SignedDistance for the current surface lowering path.", - "The IFS contribution cache must probabilistically refresh node weights under a per-frame update budget. Use online mean/variance/confidence/sample-age state with nonzero exploration for visible or near-threshold nodes so weights converge instead of freezing stale guesses. Learned scoring may later rank update and residency priority from observed high-quality probes, but conservative summaries remain the safety authority for SDF bounds and visibility.", - "Aquarium's fractal renderer and Mimir-style sensor fusion share a deeper shape: both accumulate confidence-weighted spatial evidence into temporal reservoirs, then render a resolved surface/volume field. Keep the budget planner vocabulary general enough for CPU update work, GPU packet cost, RAM residency, and SSD request pressure; do not trap the future shared machinery inside renderer-only folklore.", - "The Perfect Machine's durable layer split is Form, Appearance, and Transport. SDF/PBR/radiosity are the first opaque backend packet names, not the conceptual architecture. SDF is a solid level-set Form encoding; density/extinction/confidence is the Form encoding for flames, smoke, transparent gradients, and uncertain sensor volumes. PBR is one Appearance encoding; participating media need albedo/emission/phase/absorption/scattering, with Transport owning radiance, emission, and scattering reuse.", - "Temporal Gaussian splats lower through TemporalSpatialEvidenceReservoir: stable keyed observations become delayed, smoothed, confidence-weighted tracks with velocity prediction, expiry, and max-track eviction before backend packet lowering. Evidence observations and samples carry Form/Appearance/Transport layer plus encoding metadata; internal track keys include layer and encoding so the same stable key can carry separate SDF, density, confidence, or other field tracks without blending them. Treat Gaussian fields, fractal form probes, density/extinction samples, and Mimir sensor-fusion features as different evidence producers for this reservoir shape, not separate accumulator folklore.", - "LocalCastGpuFusionAccumulator must remain a thin adapter over TemporalSpatialEvidenceReservoir. LocalCast may own mapping from visual points/seeds into evidence payloads, but it must not grow a second stable-key history, smoothing, expiry, or sample-budget algorithm.", - "TemporalSpatialEvidenceLowering owns conversion between shared evidence samples and backend packets such as TemporalGaussianObservation, AquariumTemporalSdfGaussian, and AquariumGpuFusionSeed. Consumers should not pack Payload0/Payload1 by private convention when a lowering helper exists.", - "The temporal reservoir ownership contract lives in docs/temporal-spatial-evidence-reservoir.md: ResampledImportanceReservoir owns RIS/ReSTIR-style candidate selection math; raw producer reservoirs own capture-time retention; Aquarium's temporal spatial evidence track layer owns stable resolved spatial history; lowerings own backend packet conversion; TAA owns pixel history validation. Do not let consumer repos build parallel stable-key spatial evidence caches.", - "Zyphos fractal stress data should keep authored topology richer than the first renderer backend: both Zyphos and Umbros expose lat/long, surface, object-scale, and cube-tile domains in `.aquageo`, with explicit continent/forest/tree/leaf/coast/pebble and crater/boulder/pebble recursion. The current D3D12 height-field stress table uploads 64 shaped 2D brushes and the SDF planet shaders carry separate cheap bounded quadtree-style relief.", - "The `.aquageo` compiler must preserve each tile declaration as its own ownership-tree node. Collapsing every claim under the final tile makes the authored multi-domain world a lie even if the brush count looks impressive.", - "Zyphos passes cube-tile domain metadata through height brush packets and binds those packets into the SDF pass. The planet shader may use authored brush packets for post-hit material/detail evaluation; traced geometry must wait for selected-cut/resident packet policy so SDF distance loops do not evaluate every brush at every step.", - "Zyphos traced planet geometry may sample only a hard-budgeted top-influence subset of authored fractal brush packets in `sdfDistance`; the current proven budget is four brushes after sorting selected packets by abs(amplitude)*max(radius). A 12-brush distance loop was tested and rejected because it pushed the live frame to about 33 ms; the four-brush loop returns the live view to about 16.4 ms while full packet richness remains available to post-hit material/detail.", - "Temporal resolve has a cache-facing detail lane: SdfSurface.temporalDetail writes through scene-control.z into history-control.z, and D3D12Post reduces history confidence when current and previous temporal detail disagree. Use this lane for stochastic fractal/cache stability signals, not as geometry authority.", - "Temporal resolve now has explicit reservoir guide targets. SDF and temporal Gaussian passes write a current scene reservoir guide MRT and D3D12Post reads/writes ping-ponged history reservoir guide targets with x=confidence, y=sample age, z=domain validity, w=invalidation code. History-control.w still owns pixel history age; do not pack reservoir history back into scene-control folklore.", - "FractalContributionCache is the live cache loop: each frame builds a resource plan from current summaries and cached states, stochastically observes only budgeted update nodes, stores mean/variance/confidence/sample age through FractalContributionEstimator, frames scheduled updates as weighted ResampledImportanceReservoir candidates, and lets backend packet compilation stay cached by selected-cut key. It is a candidate source, not the whole temporal/spatial reuse pass. Do not replace this with a static plan cache that stops learning after the first camera bucket.", - "FractalOccupancyGraph is now the live memory behind FractalContributionCache. It owns per-node contribution state, last visible frame, last observed score, and update probability; unobserved nodes decay confidence and grow stale uncertainty. Keep richer residency/resource fields here rather than adding another cache beside it.", - "FractalResidencyPlanner keeps resident payloads by score-per-cost when RAM budget is capped and reports evicted node keys explicitly. Eviction is a planner decision row until a real payload/page store owns mutation; selected nodes still render through summary fallback when evicted or missing.", - "FractalProbeSample is the typed reservoir sample shape for fractal form/detail reuse: domain key, node key, local center, bound radius, target contribution, source PDF, material delta, field layer/encoding, and payload handle. The same ResampledImportanceReservoir must handle opaque Form/SignedDistance and transparent Form/Density or Form/Extinction samples. Reuse must reject mismatched layer/encoding before lineage and local-shift checks, then later add camera motion, disocclusion, material compatibility, visibility, and encoding-specific bounds before temporal/spatial reuse.", - "FractalProbeReuseValidator.ValidateTemporal is the CPU contract for future GPU temporal reuse. It rejects excessive camera motion, disocclusion, material mismatch, low visibility, bad domain lineage, excessive local shift, and invalid bounds with explicit reasons; shader reuse should mirror this contract instead of inventing private validation rules.", - "FractalStructuralProbeGenerator lowers AquariumFractalSummary rows into FractalProbeSample reservoir candidates with local support, projected target contribution, clamped source PDF, material delta, and payload handle. This is the structural IFS probe producer; renderer-facing temporal validation still needs camera/disocclusion/material/visibility inputs.", - "FractalStructuralProbeReservoir builds a reservoir snapshot from an ownership tree, selected cut, summaries, and projected pixels per world unit. ZyphosFractalRenderPlan now carries this structural probe reservoir, so the planet path exposes reservoir-shaped structural evidence beside brushes/resource plans before GPU reuse exists.", - "AquariumFractalSdfSplat3D is the compact 3D packet contract for the first opaque Phase F Form slice. FractalSdfSplat3DCompiler accepts only Form/SignedDistance probes, and FractalSdfSplat3DKernel owns CPU compact-weight/signed-distance parity math. AquariumFractalDensitySplat3D plus FractalDensitySplat3DCompiler are the matching transparent Form packet/compiler for Form/Density and Form/Extinction probes, with an 80-byte packed density splat stride aligned to the opaque SDF splat stride. Do not force flames or sensor confidence volumes through solid SDF semantics.", - "Hot fractal splat storage must be GPU-resident packed buffers manipulated by compute shaders. Stable string-keyed splat contracts are metadata/debug boundaries, not million-instance hot buffers. `AquariumPackedFractalSdfSplat3D` is the numeric 80-byte packet shape; C# staging/readback paths use unsafe `FractalNativeBuffer` when CPU memory is genuinely needed.", - "Fractal reservoir compute can now take a compact authored IFS program. `FractalGpuProgramCompiler` lowers selected `.aquageo` brush claims into precomposed `AquariumPackedFractalIfsTransform` support rows; Zyphos passes those rows through `AquariumFractalReservoirField.ProgramTransforms`; D3D12 uploads the small program as a compute SRV. The shader samples one selected-cut row in O(1) for authored programs; nested domain ancestry belongs in the compiler/planner, not the million-splat kernel. The hash fractal remains a fallback/receipt mode, not the live authored generator.", - "The fractal reservoir field owns world placement through `WorldCenterRadius`. Zyphos binds this to the planet center and surface radius, and the visible splat pass currently maps first-slice SDF/PBR/radiosity reservoir rows into that frame. Conceptually those rows are Form/Appearance/Transport; do not fall back to camera-relative debug splats for the primary terrain demo.", - "Authored fractal GPU program rows must preserve cube-sphere tile identity. `AquariumPackedFractalIfsTransform.TileAddress` carries face, level, tile X, and tile Y; rotation cos/sin live in `MaterialSeedShape.zw` to keep the packet 64 bytes and avoid per-splat trig. The compute shader maps selected-cut brush support through the tile address onto cube-sphere faces. Dropping tile X/Y turns Zyphos back into meaningless cap pudding.", - "The first visible fractal reservoir consumer is a tangent-frame surface patch renderer, not a final terrain resolve. It draws a larger live subset of GPU-resident splats, projects patch corners from world space, and shades from radial normals plus first-slice SDF/PBR/radiosity reservoirs. If the result still looks abstract, the next coherent fix is clustered surface/volume resolve or coordinate authority, not more decorative billboard tuning.", - "Zyphos camera composition must target the selected spatial domain's tracked center while keeping the parent as orbit/composition anchor. Looking directly at the parent made planetary mode aim at the binary midpoint and left Zyphos offscreen, which made renderer failures look like art failures.", - "Do not use Zyphos as the first proof of fractal DSL correctness. Start with reference fractals. Apophysis/FLAM3-style `.flame` fixtures are the parity pressure for Aquarium `.aquageo`; GPL/open-source renderers stay external/test-only. The first gate is linear Sierpinski: exact fixed-xform sequence parity and chaos-game moment bounds before any GPU visualization claim.", - "The local Apophysis/FLAM3 subset parser owns only a small proven flame shape: xform weight/color, affine coefficients, and `linear`, `spherical`, and `bubble` variation weights. `FractalFlameChaosGame` and `FractalPointHistogramBuilder` provide deterministic CPU receipts. External renderer proof stays optional and outside runtime through FLAM3-compatible PPM receipt hashing.", - "Use `scripts/fractal-flame-receipt.ps1` for the local CPU flame receipt. The default mixed linear/spherical/bubble fixture uses 8192 samples, 64 burn-in, 64x64 bounds -8,-8,8,8, seed 0x0BADC0DE, and checksum 0xAEB1C81B. Use `scripts/fractal-flame-reference-render.ps1` with a local `flam3-render` executable to produce external PPM image receipts under artifacts/fractal-flame-reference; Aquarium does not vendor Apophysis or FLAM3.", - "FractalGpuProgramCompiler can lower the proven FLAM3-style flame subset into GPU program rows for D3D12FractalReservoirCompute's explicit flame 2D program mode. Flame mode owns a 32-byte AquariumPackedFractalFlameState UAV row per resident splat; touched rows advance persistent chaos-game state instead of replaying from the origin. The cache has two phases: full-population acquisition, then budgeted stochastic maintenance. On 2026-05-21 the GTX 1070 ran JWildfire FARender selftest.flame with 2,000,000 splats, 2,000,000 flame states, three 2,000,000-row first-slice Form/Appearance/Transport reservoir layers, 8 full acquisition frames, steady 50,000 splat updates/frame, 15,000 reservoir updates/pass/frame, depth 8, at 1.011 ms/frame / 988.8 FPS equivalent, 84.85% CPU-slice distribution parity, checksum 0xC633FADC3BD7E5BE. Without acquisition, the same steady budget scored only 32.64%; do not confuse a cold persistent cache with a bad sampler.", - "The live GPU splat packet carries a Form encoding tag in an existing material/confidence lane so flame-mode compute can mark splats as Density without changing the 80-byte hot stride. D3D12FractalSplatRender now compiles separate surface and transparent graphics pipeline states over the same GPU-resident buffers: signed-distance surface claims depth-test/write as opaque geometry, while density/extinction claims use a depth-disabled additive color-only pass. This is a field-aware debug/consumption path, not full volume ray integration; do not add a second transparent reservoir or buffer unless a measured resolve need beats the shared packet invariant.", - "Fractal splat reservoir guide output must obey the shared TAA guide schema: x confidence, y sample age, z domain validity, w invalidation code. Do not pack Form/Appearance/Transport validation into guide x/y/z; those are backend layer diagnostics, not resolver semantics.", - "Render debug mode 12 is the Reservoir/TAA Guide view and should display guide semantics directly: confidence, normalized sample age, and domain validity.", - "The first visual parity metric compares GPU flame splat XY histograms against the local CPU flame oracle. With 250,000 GPU readback splats, 1,000,000 CPU reference samples, 128x128 bounds -8,-8,8,8, and the mixed FLAM3-style fixture, distribution score is 84.05% at frame 1, 84.10% at frame 5, 84.20% at frame 20, and 84.24% after the 60-frame/10-warmup receipt; cosine similarity stays about 0.9955. This is high distribution similarity but not learned convergence: the current reservoir path initializes splats and stochastically replaces them, without visual-error feedback or ReSTIR/MIS target correction yet.", - "Global flame parity is not enough. View-conditioned parity now scores named viewport bounds and reports GPU/reference hits, starved reference bins, and underrepresented mass. First depth-16 GTX 1070 receipt with 250k GPU readback splats vs 1M CPU samples: global -8..8 scores 97.09%, mid -1..1 scores 91.93%, close -0.5..0.5 scores 88.97%, micro -0.25..0.25 scores 82.05% with 2,656 starved bins and 17.95% underrepresented mass. This proves the current reservoir is fast but not view-adaptive; next work needs camera-conditioned target weights and underrepresented-region feedback.", - "FractalHistogramResidualFocus converts visual parity residuals into a tested focus window: underrepresented reference mass determines center, radius, and strength. tools/Aquarium.Fractal.Receipt prints the suggested focus per visual parity view so a bad contact sheet now yields a concrete reservoir-pressure input for the next adaptive loop.", - "tools/Aquarium.Fractal.Receipt --adaptive-focus is the first closed feedback receipt: it uses a warmup epoch to populate the existing GPU buffers, reads back reservoir density, computes a residual focus, and runs measured frames over the same buffers with that focus. On the small GTX 1070 mixed-flame smoke, this moved the score from 67.07% non-adaptive to 70.89% adaptive at about 0.160 ms/frame. Treat this as proof of feedback shape; the runtime still needs a no-stall GPU-side or delayed feedback path.", - "Do not use the quick 1M-sample flame oracle image for visual judgment; it is too noisy. The high-reference contact sheet uses 20,000,000 CPU oracle samples and 250,000 Aquarium GPU readback splats per panel at artifacts/fractal-contact-sheet-hq/flame-parity-contact-sheet-hq.png. It makes the zoom failure legible: the CPU oracle smooths out while Aquarium remains under-sampled after zoom because the current reservoir is not view-adaptive.", - "Aquarium's CPU flame histogram is a math oracle, not visual ground truth. The visual reference ladder is: Chaotica as gold market-quality reference when available/imported, JWildfire/FARender as scriptable visual reference, FLAM3/Apophysis as portable baseline compatibility, Aquarium CPU as deterministic unit-test/debug oracle only. On 2026-05-20 Chaotica and flam3-render were not on PATH, but scripts/install-flame-reference-tools.ps1 hydrated JWildfire 9.00 plus Temurin JRE 17 under ignored artifacts, and scripts/fractal-flame-jwildfire-reference.ps1 rendered JWildfire's bundled FARenderJWF selftest flame at 1024x1024 quality 2000 in 7.69 sec on the GTX 1070. JWildfire/FARender is an external visual reference artifact lane, not Aquarium runtime code. Do not claim best-in-market flame parity until imported Chaotica renders or fully matched JWildfire flame dialect metrics are wired into residual scoring.", - "The useful flame oracle is now external density, not Aquarium CPU self-agreement. tools/Aquarium.Fractal.Receipt accepts --reference-density-ppm to compare Aquarium GPU SDF envelope reservoir density against luminance density from a binary PPM rendered by JWildfire/FARender. scripts/new-jwildfire-baby-fixture.ps1 derives a smaller FARender-compatible julian-disc-baby.flame from the bundled selftest while preserving required FARender boilerplate. First external receipt scored 15.33% in 256x256 bounds -2..2 while Aquarium still binned raw centers; after fixing JWildfire coefs packing (`a b d e c f`) and FARender's disc angle convention (`atan2(x,y)`), the raw-center score reached 26.87%. With the candidate switched to full SDF-reservoir density, the same target scored 22.14% at 42.053 ms/frame with all 2M reservoir rows refreshed. Cutting the false JWildfire `normal` -> `linear` import and resolving subpixel SDF envelopes as at least one histogram bin moved the score to 31.36% at 41.692 ms/frame. `-HistogramBounds flame-camera` derives FARender-style size/scale/cam_zoom bounds and moves the score to about 43.1% with about 68% occupancy overlap. Full reservoir refresh must use direct row indexing, not stochastic hashing; after that fix the same 2M-row full-refresh gate runs at 7.508 ms/frame / 133.2 FPS equivalent instead of roughly 41 ms/frame. Aquarium-vs-CPU still scores about 89.94%, so the live failure is exact JWildfire variation/filter semantics, target density weighting, and view-conditioned reservoir feedback, not sample count.", - "JWildfire selftest is now the flame renderer faceplant target. The current dialect slice supports JWildfire coefficient layout, variationGroup, disc, julian, gaussian_blur, and post transforms. After post lowering, the depth-64 GTX 1070 receipt scores 84.19% against Aquarium's CPU slice oracle in bounds -8..8 and 88.01% in bounds -128..128, but costs about 129 ms/frame. This is not external JWildfire visual parity; it is CPU/GPU agreement on the supported slice. Aquarium still needs richer dialect semantics, palette/density/render-filter parity, weighting-field handling, and persistent per-sample GPU iteration-state reservoirs instead of replaying deep chaos-game ancestry from zero for every splat.", - "Flame imports must report translation loss. FractalFlameFileParser.ParseFirstWithReport returns accepted, approximated, ignored, and rejected fields per transform, and receipt runs write fractal-flame-import-report-*.json. The JWildfire selftest report currently shows 15 accepted fields, 3 approximations, 45 ignored render/presentation fields, and 11 rejected geometry/sampling fields: wfield_* weighting-field attributes. Treat successful XML parsing as insufficient until rejected geometry fields are either implemented as DSL/operator nodes or explicitly accepted as out-of-scope diagnostics.", - "Persistent flame iteration now has both a CPU parity contract and a GPU realization. FractalFlameIterationState plus FractalFlameIterationStepper prove chunked CPU advancement; AquariumPackedFractalFlameState mirrors the point/support/material/RNG/step packet in D3D12FractalReservoirCompute as a UAV so flame splats advance over frames. Keep the acquisition/maintenance split explicit in receipts and renderer budgets.", - "Fractal reservoir update pressure now has a first view-conditioned GPU input. AquariumFractalReservoirField.PriorityFocus carries focus XY, radius, and strength; D3D12FractalReservoirCompute uses it only for under-budget stochastic row selection by choosing among a few random candidates, while full-refresh passes remain direct row sweeps. This preserves convergence/exploration and gives Zyphos camera-domain selection a real way to steer work toward visible detail. Receipt runs can exercise the path with --priority-focus.", - "Zyphos' primary planetary terrain test path is now the fractal reservoir surface. The direct SDF planet and Umbros proxy shaders are removed from the render plan; only the parent star remains as a direct SDF body/light. If the planet looks wrong, fix the reservoir lowering/shading path instead of letting the old SDF terrain hide it.", - "The GPU splat receipt harness lives at tools/Aquarium.Fractal.Receipt and scripts/fractal-splat-receipt.ps1. The live receipt allocates one 80-byte packed SDF splat UAV plus three distinct 64-byte reservoir UAVs for SDF envelopes, PBR material envelopes, and radiosity; those reservoirs are sampled in independent compute passes under a stochastic update budget. On the local NVIDIA GTX 1070 it kept 2,000,000 splats and 2,000,000 reservoirs per layer resident. The fallback hash-fractal receipt updated 50,000 entries per layer with 2 candidates/update at 4.471 ms/frame, 223.7 FPS equivalent. The authored precomposed selected-cut receipt used depth 48, 4 compact transforms, and 15,000 updates per layer at 4.908 ms/frame, 203.7 FPS equivalent, with full reservoir coverage in 133.3 frames. D3D12FractalSplatRender consumes the raw splat, SDF, PBR, and radiosity buffers through separate graphics SRVs for the visible debug subset. This proves compute-side GPU residency, budgeted temporal convergence, authored-program splat population decoupled from domain ancestry depth, and first layered GPU consumption; final terrain/material/radiosity shading is still future work.", - "FractalProjectedSdfSplatCompiler is the Phase G 2D-projected-to-3D lowering seam: it converts resident SignedDistance2D page payload samples into compact 3D SDF splats through an explicit page-local Vector2 -> Vector3 mapping, surface normal, support radius, and splat budget. Zyphos caches a bounded first set with a flat local mapping until cube-sphere/torus mappers are added.", - "Zyphos camera distance limits belong to the selected spatial domain, not one global planetary clamp. Leaf/pebble domains must be able to zoom below whole-body distances, and the parent star must be a visible SDF body when it is also the primary light source.", - "The consolidated fractal brush architecture lives in research/rendering/fractal-brush-architecture-plan.md. Its pipeline is client intent -> domain roots -> semantic IFS brush grammar -> ownership tree -> node summaries -> contribution cache/residency scheduler -> backend packets -> renderer passes -> debug/evidence. Its credibility depends on module boundaries and tests: contracts, pure CPU fractal core, D3D12 backend, client adapters, mock payload/probe/random/clock seams, shader parity tests, and deterministic performance fixtures.", - "The Perfect Machine waterfall architecture lives in docs/perfect-machine-architecture.md. Treat it as the design authority before expanding SDF splat backends, sensor-fusion candidate adapters, reservoir guide buffers, occupancy graph state, resource-tier residency, or stochastic learned priority. Its core split is domains -> evidence candidates -> target evaluation -> ReSTIR/GRIS reservoirs -> occupancy graph -> residency -> 2D/3D/projected SDF splat packets -> TAA guide buffers.", - "AquariumFractalSurfacePageKey and AquariumFractalSurfacePage are the renderer-agnostic page contracts for Phase E: height, SignedDistance2D, material, and confidence surface pages carry stable domain/node/kind/mip keys, bounds, dimensions, payload handles, and max error before any D3D12 page store exists.", - "FractalSurfacePagePlanner lowers selected IFS cuts into stable surface page metadata without renderer dependencies. ZyphosFractalRenderPlan now exposes height, SignedDistance2D, material, and confidence pages beside brushes, resource plans, and structural probe reservoirs; the actual page store, eviction, atlas, and D3D12 lowering are still open.", - "FractalSurfacePageResidencyPlanner is the renderer-agnostic page-store policy boundary: it asks IFractalSurfacePageStore about page-key residency, keeps best max-error-per-byte resident pages under a byte budget, requests highest-value missing pages, and reports evictions. Zyphos carries this page residency plan, but real storage and D3D12 atlas mutation remain future work.", - "FractalSurfacePageRasterizer lowers resident planned pages into CPU sample payloads using the shared FractalBrushEnvelope2D math: height sums amplitudes, SignedDistance2D uses a cheap signed support-distance estimate, material uses deterministic weighted claim tags/seeds, and confidence accumulates clamped envelope coverage. Zyphos caches resident page payloads by page key before any GPU atlas exists.", - "The actionable fractal brush roadmap lives in research/rendering/fractal-brush-implementation-roadmap.md. Start with the first work packet: add Aquarium.Engine.Fractal and tests, cube-face/tile key types, identity and tangent projection candidates, an area distortion sampler, face-edge tests, and a projection report before touching recursive detail." - ], - "text_and_ui": [ - "Overlay text uses DirectWrite/Direct2D after scene rendering. It is crisp final-pixel UI for debug surfaces, terminals, inspectors, and splash/status text.", - "Aquarium UI controls follow the CultLib code-first binding style without Unity prefab assumptions: panels, sections, sliders, toggles, buttons, option rows, tree items, and text boxes bound by explicit read/write delegates.", - "Aquarium.Engine.Contracts exposes AquariumUiDocument as the client-facing debug composition surface. Client panels are tabs inside the single Aquarium debug panel unless they explicitly opt into floating/proximity-faded overlay behavior. Clients can register terminal commands through AquariumUiDocument.Command. Longer editable strings should use AquariumUiTextBox instead of pretending to be row values. Text boxes own caret/selection editing state, may opt into bundled Ubuntu Sans Mono and bottom alignment, and focused text boxes capture input so renderer debug hotkeys and client camera controls stay quiet while editing.", - "Use AquariumUiTreeItem for selectable hierarchy rows: disclosure arrows own expansion, row selection owns mode/target choice, and clients provide depth/detail/selected bindings without leaking domain-specific hierarchy policy into DebugUi.", - "The unified F2 debug panel is titled Debug and owns engine controls, client tabs, and a bottom-aligned multiline command terminal. Tab navigation is panel chrome: a highlighted row of buttons below the title, not a content section made of ordinary controls. Do not reintroduce separate Aquarium/Epiphany debug panels fighting for the same hotkey.", - "Vortice.Mathematics.Rect uses x, y, width, height. UI code should use explicit RectFromEdges helpers when reasoning in edges.", - "Debug UI feedback needs honest element-specific states: base, hover, and active. Sliders respond on track/fill and handle separately, keep geometry stable, and brighten by lerping accent colors toward white.", - "Scene/diegetic labels should use renderer-owned MSDF/SDF billboards when they live in world space. Overlay text should not be shoved into HDR for convenience." - ], - "audio": [ - "Aquarium exposes an optional audio/synth hosting boundary through contracts; clients declare intent, Aquarium schedules playback and owns device output.", - "Aquarium consumes AquaSynth.Faust as a pinned repo-local NuGet package, with AquaSynth.Core arriving transitively for the built-in patch editor/parser surface. AquaSynth owns synth internals, live patch compilation, native Faust factory lifetime, generated DSP manifests, and tests; AquariumSynthHost owns debounce, trigger scheduling, rendered-buffer caching, and WASAPI playback. Update the package only by deliberate version bump so visual/renderer work can continue while synth construction changes underneath." + "client_ownership": [ + "Aquarium.Epiphany owns agent role semantics, render-plan configuration, Epiphany shaders, CultCache documents, CultNet interpretation, camera intent, and voice surfaces.", + "Fensalir owns Win32, D3D12, input translation, hot reload, renderer debug UI, audio device output, contracts, reusable SDF/fractal infrastructure, and engine demo projects.", + "If an Epiphany feature needs a new renderer capability, add the capability in Fensalir first and consume the contract here." ], "state_and_reload": [ - "CultCache is the client memory organ. Runtime state, camera, renderer knobs, body state, UI state, and future Epiphany connection state should be typed Cult documents.", - "Global graphics presentation settings live in epiphany.aquarium.graphics_settings. The debug UI edits the renderer copy; the host syncs changed renderer settings back to the client runtime; the runtime flushes dirty settings through CultCache.", - "A truncated or unreadable single-file CultCache backing store is not a schema migration failure. Aquarium should quarantine the corrupt snapshot and boot fresh typed state.", - "dev-reload builds disposable apphost slots so a running window does not lock normal build output. Headless smoke runs use a separate CultCache from the visible dev window.", - "Headless art captures should use disposable build slots and `Start-Process -Wait` style ownership. Aquarium.Engine is a Windows GUI executable, so plain PowerShell `&` can return before the renderer has finished pipeline compilation or frame capture.", - "Live runtime reload is not successful just because dev-watch wrote live-current.txt. The watcher must see the host acknowledge the exact live DLL path in stdout.", - "Shader reload failure must keep the previous good shader objects bound. Live-runtime reload failure must keep the previous runtime alive." + "Runtime live state remains typed CultCache state, especially epiphany.aquarium.live_state and epiphany.aquarium.graphics_settings.", + "The local dev scripts are wrappers over Fensalir scripts and pass src/Aquarium.Epiphany/Aquarium.Epiphany.csproj as the client project." ] }, "warnings": [ - "A clean repo can still grow Jenga if state and docs lag behind code.", - "Do not add a framework-shaped dependency just to borrow one comfortable tool.", - "Do not let bloom or overlay debug output disguise a bad lighting equation.", - "Do not preserve historical branch scars in live docs unless they change a current decision." + "A client repo with copied engine code is just a split repo lying badly.", + "Do not add Epiphany nouns to Fensalir to fix missing client context.", + "Do not preserve stale engine docs here because they used to be true." ] } diff --git a/state/scratch-fractal-resolve-split.md b/state/scratch-fractal-resolve-split.md deleted file mode 100644 index 9c900a3..0000000 --- a/state/scratch-fractal-resolve-split.md +++ /dev/null @@ -1,7 +0,0 @@ -Objective: keep the shared Form reservoir while making render resolve semantics explicit. - -Current mechanism before this slice: one D3D12FractalSplatRender pixel path drew both opaque SDF surface claims and transparent density claims. That preserved the packet stride but hid depth/blend behavior in shader conditionals. - -Invariant after this slice: one GPU-resident splat/reservoir set can carry multiple Form encodings, but renderer pass ownership must split where output-merge semantics split. SignedDistance owns opaque depth-writing surface resolve. Density/Extinction owns transparent additive color accumulation until a real volumetric target exists. - -Cut line: do not add a parallel transparent reservoir or CPU-side splat list to paper over pass semantics. Add targets/passes only when the invariant they protect is explicit and measured. diff --git a/state/scratch-fractal-surface-visible.md b/state/scratch-fractal-surface-visible.md deleted file mode 100644 index 438d920..0000000 --- a/state/scratch-fractal-surface-visible.md +++ /dev/null @@ -1,18 +0,0 @@ -# Fractal Surface Visible Slice - -Objective: make the live Zyphos scene test authored fractal reservoir terrain instead of a decorative proxy. - -Kept: -- GPU-resident 2M splat reservoir field. -- Separate SDF, PBR, and radiosity reservoir layers. -- `.aquageo` selected-cut program lowering. - -Changed: -- Packed IFS transform rows now preserve cube-sphere tile face/level/x/y. -- Compute maps authored splats onto cube-sphere faces instead of a generic +Z cap. -- Visible splats render as tangent-frame surface patches, not camera-facing stickers. -- Zyphos camera targets the selected domain while keeping the parent as orbit anchor. - -Still not good enough: -- The live view is fast and the reservoir is populated, but the current surface-consumption pass still reads too abstractly under the noisy starfield. -- Next coherent cut is a real clustered surface resolve or ray-query style splat surface pass, not more billboard cosmetics. diff --git a/state/scratch.md b/state/scratch.md index 543a935..2b7565d 100644 --- a/state/scratch.md +++ b/state/scratch.md @@ -2,66 +2,15 @@ ## Current Slice -Aquarium's active focus is the fractal reference gate for the Perfect Machine: -prove compact IFS/flame fixtures numerically before asking Zyphos visuals to -carry architectural truth. +Repo split is active. -Keep the engine/client boundary strict: - -- Aquarium.Engine owns Win32, D3D12, input, reload, renderer abstractions, - debug UI plumbing, and device/toolchain integration. -- Aquarium.Epiphany owns client policy, semantic state interpretation, role - layout, and render-plan configuration through Aquarium.Engine.Contracts. -- Aquarium consumes AquaSynth.Faust as a pinned package in the repo-local - `packages` feed; AquaSynth.Core arrives transitively for patch editor/parser - surfaces. AquaSynth owns synth internals and tests; update - the package only through an intentional version bump. - -The renderer work that matters next: - -- Continue replacing legacy fixed D3D12 pass execution with the declared render - graph. -- Keep body/SDF proxy passes bounded, per-object, and client-authored. -- Build role visuals from coherent low-cost form models before ornament. -- Use `research/rendering/cube-sphere-fractal-brushes.md` as the live map for - the cube-sphere planetary domain and shared IFS brush grammar migration. - Its IFS/CSG DSL notes now pull from neighboring VibeGeometry's `vg_grammar` - and `vg_csg` tree work. - Its LOD model uses cached node contribution summaries to select stable - hierarchy cuts and stream/fade child detail only when visible pixels justify - the cost. Contribution weights are online estimates: update a probabilistic - subset each frame, track uncertainty and sample age, and keep conservative - summaries as the safety floor if later learned scoring is added. -- The consolidated architecture and roadmap live at - `research/rendering/fractal-brush-architecture-plan.md`, including module - boundaries, mock seams, and unit/performance test strategy. -- The actionable execution checklist lives at - `research/rendering/fractal-brush-implementation-roadmap.md`; first work - packet is `Aquarium.Engine.Fractal` plus tests, cube-face/tile keys, - identity/tangent projections, area distortion sampler, face-edge tests, and - a projection report. -- Use `research/rendering/fractal-reference-oracles.md` for Apophysis/FLAM3 - parity. Local parser/evaluator receipts are not external renderer proof. - `scripts/fractal-flame-reference-render.ps1` is the optional FLAM3-compatible - PPM receipt path when a local `flam3-render` binary is installed. - `scripts/fractal-splat-receipt.ps1 -ProgramFlame ... -SplatUpdates 50000` - is the GPU-resident flame stress receipt path; it initializes resident splats - once and then performs budgeted stochastic updates. - Add `-VisualParity -ReadbackSplats 250000 -HistogramSize 128x128` to score - GPU splat histograms against the CPU flame oracle. Current score plateaus - near 84.2% distribution parity / 0.9955 cosine, so the next architectural - need is visual-error feedback, not more raw sampling theater. - Use `-VisualParityView name:minX,minY,maxX,maxY` for camera-window truth. - The depth-16 flame receipt loses hard under zoom: micro -0.25..0.25 is 82.05% - with 2,656 starved reference bins. This is the next real reservoir target. -- Use `docs/zyphos-eusocial-sync.md` before evolving Zyphos world content. - Eusocial Interbeing owns canon in `E:\Projects\Eusocial Interbeing`; Zyphos - owns render constraints and feeds design questions back through the vault's - `Eusocial Interbeing/World/Zyphos Simulation Brief.md`. -- Preserve debug UI as shared chrome and input capture, not parallel panels. +- `E:\Projects\Fensalir` owns the native runtime, renderer, contracts, fractal + machinery, host scripts, and engine demos. +- `E:\Projects\Aquarium-Engine` owns only the Epiphany Aquarium client and + Epiphany agent preview. +- Client project references point to the adjacent Fensalir source tree for now. ## Verification -- `dotnet build Aquarium.Engine.sln --no-restore` -- `.\scripts\verify-boundaries.ps1` +- `dotnet build EpiphanyAquarium.sln` - `.\scripts\dev-reload.ps1 -Headless -RetainSlots 4` diff --git a/tests/Aquarium.Engine.Fractal.Tests/ApophysisReferenceParityTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ApophysisReferenceParityTests.cs deleted file mode 100644 index 3ccc168..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/ApophysisReferenceParityTests.cs +++ /dev/null @@ -1,305 +0,0 @@ -using System.Globalization; -using System.Numerics; -using System.Xml.Linq; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class ApophysisReferenceParityTests -{ - [Fact] - public void AquariumAffineIfsMatchesApophysisLinearFixtureForFixedXformSequence() - { - var root = FindRepoRoot(); - var flamePath = Path.Combine(root, "tests", "Aquarium.Engine.Fractal.Tests", "Fixtures", "Apophysis", "linear-sierpinski.flame"); - var aquageoPath = Path.Combine(root, "tests", "Aquarium.Engine.Fractal.Tests", "Fixtures", "Apophysis", "linear-sierpinski.aquageo"); - - var reference = LoadLinearApophysisFixture(flamePath); - var candidate = FractalDslCompiler.Compile(File.ReadAllText(aquageoPath)).AffineIfsDefinitions.Single(); - - Assert.Equal(reference.Count, candidate.Transforms.Count); - var referencePoint = Vector2.Zero; - var candidatePoint = candidate.Start; - var sequence = new[] { 0, 2, 1, 1, 0, 2, 2, 1, 0, 0, 2, 1 }; - foreach (var transformIndex in sequence) - { - referencePoint = reference[transformIndex].Apply(referencePoint); - candidatePoint = candidate.Transforms[transformIndex].Apply(candidatePoint); - AssertClose(referencePoint, candidatePoint); - } - } - - [Fact] - public void AquariumAffineIfsChaosGameMatchesIndependentReferenceMoments() - { - var root = FindRepoRoot(); - var aquageoPath = Path.Combine(root, "tests", "Aquarium.Engine.Fractal.Tests", "Fixtures", "Apophysis", "linear-sierpinski.aquageo"); - var candidate = FractalDslCompiler.Compile(File.ReadAllText(aquageoPath)).AffineIfsDefinitions.Single(); - - var points = FractalAffineIfsChaosGame.Generate(candidate, count: 4096, burnIn: 16, new FractalXorShiftRandom(0xA90F_1357u)); - var min = new Vector2(float.PositiveInfinity, float.PositiveInfinity); - var max = new Vector2(float.NegativeInfinity, float.NegativeInfinity); - var sum = Vector2.Zero; - foreach (var point in points) - { - min = Vector2.Min(min, point); - max = Vector2.Max(max, point); - sum += point; - } - - var mean = sum / points.Length; - Assert.InRange(min.X, 0.0f, 0.01f); - Assert.InRange(min.Y, 0.0f, 0.01f); - Assert.InRange(max.X, 0.98f, 1.0f); - Assert.InRange(max.Y, 0.84f, 0.8661f); - Assert.InRange(mean.X, 0.47f, 0.53f); - Assert.InRange(mean.Y, 0.27f, 0.33f); - } - - [Fact] - public void FlameParserReadsApophysisVariationSubset() - { - var root = FindRepoRoot(); - var flamePath = Path.Combine(root, "tests", "Aquarium.Engine.Fractal.Tests", "Fixtures", "Apophysis", "linear-spherical-bubble.flame"); - - var flame = FractalFlameFileParser.ParseFirst(File.ReadAllText(flamePath), seed: 77); - - Assert.Equal("linear-spherical-bubble", flame.Name); - Assert.Equal(77, flame.Seed); - Assert.Equal(3, flame.Transforms.Count); - Assert.Equal(1.0f, flame.Transforms[0].Variations.Linear); - Assert.Equal(0.72f, flame.Transforms[1].Variations.Spherical); - Assert.Equal(0.84f, flame.Transforms[2].Variations.Bubble); - Assert.Equal(new Vector2(-0.20f, 0.08f), flame.Transforms[0].Translation); - } - - [Fact] - public void FlameVariationEvaluatorMatchesIndependentReference() - { - var root = FindRepoRoot(); - var flamePath = Path.Combine(root, "tests", "Aquarium.Engine.Fractal.Tests", "Fixtures", "Apophysis", "linear-spherical-bubble.flame"); - - var flame = FractalFlameFileParser.ParseFirst(File.ReadAllText(flamePath), seed: 77); - var point = new Vector2(0.37f, -0.21f); - foreach (var transform in flame.Transforms) - { - var expected = ApplyReferenceVariation(transform, point); - var actual = transform.Apply(point); - AssertClose(expected, actual); - } - } - - [Fact] - public void FlameHistogramIsDeterministicForReferenceFixture() - { - var root = FindRepoRoot(); - var flamePath = Path.Combine(root, "tests", "Aquarium.Engine.Fractal.Tests", "Fixtures", "Apophysis", "linear-spherical-bubble.flame"); - var flame = FractalFlameFileParser.ParseFirst(File.ReadAllText(flamePath), seed: 77); - - var points = FractalFlameChaosGame.Generate(flame, count: 8192, burnIn: 64, new FractalXorShiftRandom(0xBADC_0DEu)); - var histogram = FractalPointHistogramBuilder.Build(points, 64, 64, new Vector4(-8.0f, -8.0f, 8.0f, 8.0f)); - var occupied = histogram.Bins.Count(value => value > 0); - var checksum = histogram.Bins.Aggregate(2166136261u, (hash, value) => unchecked((hash ^ (uint)value) * 16777619u)); - - Assert.Equal(8192, histogram.HitCount); - Assert.InRange(occupied, 450, 540); - Assert.Equal(0xAEB1C81Bu, checksum); - } - - [Fact] - public void FlameParserReadsJWildfireVariationGroupSubset() - { - var root = FindRepoRoot(); - var flamePath = Path.Combine(root, "tests", "Aquarium.Engine.Fractal.Tests", "Fixtures", "JWildfire", "julian-disc-minimal.flame"); - - var result = FractalFlameFileParser.ParseFirstWithReport(File.ReadAllText(flamePath), seed: 91); - var flame = result.Definition; - - Assert.Equal("julian-disc-minimal", flame.Name); - Assert.Equal(2, flame.Transforms.Count); - Assert.Equal("JWildfire", result.Report.Dialect); - Assert.Equal(2, result.Report.TransformCount); - Assert.Equal(new Vector4(1.0f, 0.0f, 0.0f, 1.0f), flame.Transforms[0].Matrix); - Assert.Equal(new Vector2(-0.1f, 0.2f), flame.Transforms[0].Translation); - Assert.Equal(0.0f, flame.Transforms[0].Variations.Linear); - Assert.Equal(0.5f, flame.Transforms[0].Variations.Julian); - Assert.Equal(5.0f, flame.Transforms[0].Variations.JulianPower); - Assert.Equal(1.25f, flame.Transforms[0].Variations.JulianDist); - Assert.Equal(0.02f, flame.Transforms[0].Variations.GaussianBlur); - Assert.Equal(new Vector4(0.9f, 0.0f, 0.0f, 0.9f), flame.Transforms[0].PostMatrix); - Assert.Equal(new Vector4(0.25f, -0.75f, 0.75f, 0.25f), flame.Transforms[1].Matrix); - Assert.Equal(0.8f, flame.Transforms[1].Variations.Disc); - Assert.Contains("variationGroup:normal", result.Report.Transforms[0].IgnoredFields); - Assert.Contains("variation:jwf_gaussian_blur -> stochastic gaussian_blur", result.Report.Transforms[0].ApproximatedFields); - Assert.Contains("post", result.Report.Transforms[0].AcceptedFields); - Assert.Empty(result.Report.Transforms[0].RejectedFields); - } - - [Fact] - public void JWildfireVariationSubsetFeedsGpuProgramRows() - { - var root = FindRepoRoot(); - var flamePath = Path.Combine(root, "tests", "Aquarium.Engine.Fractal.Tests", "Fixtures", "JWildfire", "julian-disc-minimal.flame"); - var flame = FractalFlameFileParser.ParseFirst(File.ReadAllText(flamePath), seed: 91); - - var rows = FractalGpuProgramCompiler.CompileFlame2D(flame, maxTransformCount: 8); - - Assert.Equal(2, rows.Length); - Assert.Equal(0.5f, rows[0].TileAddress.Y); - Assert.Equal(5.0f, rows[0].TileAddress.Z); - Assert.Equal(0.02f, rows[0].TileAddress.W); - Assert.Equal(0.8f, rows[1].TileAddress.X); - } - - [Fact] - public void JWildfireDiscVariationUsesReferenceAngleConvention() - { - var transform = new FractalFlameTransform2D( - "disc", - new Vector4(1.0f, 0.0f, 0.0f, 1.0f), - Vector2.Zero, - new Vector4(1.0f, 0.0f, 0.0f, 1.0f), - Vector2.Zero, - 1.0f, - 0.0f, - new FractalFlameVariationWeights(0.0f, 0.0f, 0.0f, Disc: 1.0f)); - var point = new Vector2(0.25f, -0.75f); - - var actual = transform.Apply(point); - var radius = point.Length(); - var phi = MathF.Atan2(point.X, point.Y); - var expected = new Vector2( - MathF.Sin(MathF.PI * radius) * phi / MathF.PI, - MathF.Cos(MathF.PI * radius) * phi / MathF.PI); - - AssertClose(expected, actual); - } - - [Fact] - public void JWildfireImportReportNamesUnsupportedLosses() - { - var root = FindRepoRoot(); - var flamePath = Path.Combine(root, "artifacts", "reference-tools", "j-wildfire-9.00", "lib", "FARenderJWF", "selftest.flame"); - if (!File.Exists(flamePath)) - { - return; - } - - var result = FractalFlameFileParser.ParseFirstWithReport(File.ReadAllText(flamePath), seed: 91); - - Assert.True(result.Report.AcceptedFieldCount > 0); - Assert.True(result.Report.ApproximatedFieldCount > 0); - Assert.True(result.Report.RejectedFieldCount > 0); - Assert.Contains(result.Report.Transforms, transform => transform.AcceptedFields.Contains("post")); - Assert.Contains(result.Report.Transforms, transform => transform.RejectedFields.Any(field => field.StartsWith("wfield_", StringComparison.Ordinal))); - } - - [Fact] - public void PpmReferenceReceiptReadsExternalRendererOutputShape() - { - var ppm = new byte[] - { - (byte)'P', (byte)'6', (byte)'\n', - (byte)'#', (byte)' ', (byte)'F', (byte)'L', (byte)'A', (byte)'M', (byte)'3', (byte)'\n', - (byte)'2', (byte)' ', (byte)'2', (byte)'\n', - (byte)'2', (byte)'5', (byte)'5', (byte)'\n', - 0, 0, 0, - 255, 0, 0, - 0, 128, 0, - 0, 0, 64, - }; - - var receipt = FractalPpmImageReceiptBuilder.Build(ppm); - - Assert.Equal(2, receipt.Width); - Assert.Equal(2, receipt.Height); - Assert.Equal(4, receipt.PixelCount); - Assert.Equal(3, receipt.NonBlackPixelCount); - Assert.Equal(0x605A_BDE5_13A2_D19AUL, receipt.RgbChecksum); - Assert.Equal(0xD56A_A5A0_E36F_3C2BUL, receipt.LuminanceChecksum); - } - - [Fact] - public void PpmReferenceReceiptDoesNotTreatPixelWhitespaceAsHeader() - { - var ppm = new byte[] - { - (byte)'P', (byte)'6', (byte)'\n', - (byte)'1', (byte)' ', (byte)'1', (byte)'\n', - (byte)'2', (byte)'5', (byte)'5', (byte)'\n', - 10, 13, 32, - }; - - var receipt = FractalPpmImageReceiptBuilder.Build(ppm); - - Assert.Equal(1, receipt.PixelCount); - Assert.Equal(1, receipt.NonBlackPixelCount); - Assert.Equal(0xDD2C_094F_57F3_A456UL, receipt.RgbChecksum); - } - - private static IReadOnlyList LoadLinearApophysisFixture(string path) - { - var document = XDocument.Load(path); - var xforms = document.Descendants("xform").ToArray(); - Assert.NotEmpty(xforms); - return xforms.Select(xform => - { - Assert.Equal("1", (string?)xform.Attribute("linear")); - var values = ((string?)xform.Attribute("coefs") ?? string.Empty) - .Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .Select(value => float.Parse(value, CultureInfo.InvariantCulture)) - .ToArray(); - Assert.Equal(6, values.Length); - return new ReferenceAffineTransform( - new Vector4(values[0], values[1], values[3], values[4]), - new Vector2(values[2], values[5])); - }).ToArray(); - } - - private static void AssertClose(Vector2 expected, Vector2 actual) - { - Assert.True(Vector2.Distance(expected, actual) <= 0.000001f, $"Expected {expected}, got {actual}."); - } - - private static Vector2 ApplyReferenceVariation(FractalFlameTransform2D transform, Vector2 point) - { - var affine = new Vector2( - (transform.Matrix.X * point.X) + (transform.Matrix.Y * point.Y) + transform.Translation.X, - (transform.Matrix.Z * point.X) + (transform.Matrix.W * point.Y) + transform.Translation.Y); - var radiusSquared = Vector2.Dot(affine, affine); - var result = affine * transform.Variations.Linear; - if (transform.Variations.Spherical != 0.0f) - { - result += affine * (transform.Variations.Spherical / MathF.Max(radiusSquared, 0.000001f)); - } - - if (transform.Variations.Bubble != 0.0f) - { - result += affine * (transform.Variations.Bubble * 4.0f / (radiusSquared + 4.0f)); - } - - return result; - } - - private static string FindRepoRoot() - { - var directory = new DirectoryInfo(AppContext.BaseDirectory); - while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aquarium.Engine.sln"))) - { - directory = directory.Parent; - } - - return directory?.FullName ?? throw new InvalidOperationException("Could not find Aquarium repo root."); - } - - private readonly record struct ReferenceAffineTransform(Vector4 Matrix, Vector2 Translation) - { - public Vector2 Apply(Vector2 point) - { - return new Vector2( - (Matrix.X * point.X) + (Matrix.Y * point.Y) + Translation.X, - (Matrix.Z * point.X) + (Matrix.W * point.Y) + Translation.Y); - } - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/Aquarium.Engine.Fractal.Tests.csproj b/tests/Aquarium.Engine.Fractal.Tests/Aquarium.Engine.Fractal.Tests.csproj deleted file mode 100644 index 59d26df..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/Aquarium.Engine.Fractal.Tests.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - net10.0 - enable - enable - false - true - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/Aquarium.Engine.Fractal.Tests/CubeTileKeyTests.cs b/tests/Aquarium.Engine.Fractal.Tests/CubeTileKeyTests.cs deleted file mode 100644 index 498762b..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/CubeTileKeyTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class CubeTileKeyTests -{ - [Fact] - public void PositionAtMapsTileLocalCoordinatesIntoFaceCoordinates() - { - var key = new CubeTileKey(CubeFace.PositiveZ, 2, 1, 2); - - var lowerLeft = key.PositionAt(0.0, 0.0); - var upperRight = key.PositionAt(1.0, 1.0); - - Assert.Equal(-0.5, lowerLeft.U, 12); - Assert.Equal(0.0, lowerLeft.V, 12); - Assert.Equal(0.0, upperRight.U, 12); - Assert.Equal(0.5, upperRight.V, 12); - } - - [Fact] - public void ChildAndParentPreserveQuadtreeAddress() - { - var root = new CubeTileKey(CubeFace.NegativeY, 0, 0, 0); - var child = root.Child(1, 0).Child(0, 1); - - Assert.Equal(new CubeTileKey(CubeFace.NegativeY, 2, 2, 1), child); - Assert.Equal(new CubeTileKey(CubeFace.NegativeY, 1, 1, 0), child.Parent()); - Assert.Equal("NegativeY/L02/2/1", child.ToString()); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FensalirFractalSceneTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FensalirFractalSceneTests.cs deleted file mode 100644 index ddfc4dc..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FensalirFractalSceneTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Aquarium.Fensalir; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FensalirFractalSceneTests -{ - [Fact] - public void FensalirSceneLoadsSplashPatchFromAquageoFile() - { - var tree = FensalirFractalScene.OwnershipTree; - var brushes = FensalirFractalScene.HeightBrushes; - - Assert.EndsWith(".aquageo", FensalirFractalScene.PatchPath, StringComparison.Ordinal); - Assert.True(File.Exists(FensalirFractalScene.PatchPath), $"Expected copied aquageo patch at {FensalirFractalScene.PatchPath}."); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.Surface2D && domain.Key.Value == "fensalir/marsh"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.Object3D && domain.Key.Value == "fensalir/spine"); - Assert.Contains(tree.Claims, claim => claim.Tags == "cyan-ripple" && claim.WaveAmplitude > 0.0f); - Assert.Contains(tree.Claims, claim => claim.Tags == "micro-ripple"); - Assert.Contains(tree.Claims, claim => claim.Tags == "cathedral-spire"); - Assert.Contains(tree.Claims, claim => claim.Tags == "cathedral-rune"); - Assert.Contains(tree.Claims, claim => claim.Tags == "cathedral-magenta"); - Assert.Equal(tree.Claims.Count(claim => claim.PayloadKind == AquariumFractalPayloadKind.Height), brushes.Length); - Assert.True(brushes.Length <= 64); - Assert.Contains(brushes, brush => brush.WaveAmplitude > 0.0f && brush.WaveFrequency > 0.0f && brush.WaveSinePower > 0.0f); - Assert.Contains("surface brushes", FensalirFractalScene.Summary, StringComparison.Ordinal); - } - - [Fact] - public void FensalirSceneBuildsReflectiveSurfaceAndSpineProxy() - { - var scene = FensalirSceneBuilder.Build(1.0f, 0.9f); - - Assert.True(scene.TraceHeightFieldSurface); - Assert.False(scene.UseStarfieldBackground); - Assert.NotEmpty(scene.HeightFieldBrushes); - var spine = Assert.Single(scene.SdfObjects); - Assert.True(spine.CenterRadius.W >= 5.0f); - Assert.Equal(FensalirRenderPlan.SpineIndex, 0); - Assert.True(scene.SdfLights.Count >= 1); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-sierpinski.aquageo b/tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-sierpinski.aquageo deleted file mode 100644 index d518130..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-sierpinski.aquageo +++ /dev/null @@ -1,6 +0,0 @@ -# Candidate Aquarium DSL for the Apophysis/FLAM3 linear Sierpinski fixture. -tile PositiveZ 0 0 0 reference/apophysis-linear-sierpinski -affineifs linear-sierpinski 0 0 12345 apophysis-linear -affinemap lower-left 0.5 0 0 0 0.5 0 1 -affinemap lower-right 0.5 0 0.5 0 0.5 0 1 -affinemap upper 0.5 0 0.25 0 0.5 0.4330127018922193 1 diff --git a/tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-sierpinski.flame b/tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-sierpinski.flame deleted file mode 100644 index c6f3e17..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-sierpinski.flame +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-spherical-bubble.flame b/tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-spherical-bubble.flame deleted file mode 100644 index c3c8c1d..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/Fixtures/Apophysis/linear-spherical-bubble.flame +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/tests/Aquarium.Engine.Fractal.Tests/Fixtures/JWildfire/julian-disc-minimal.flame b/tests/Aquarium.Engine.Fractal.Tests/Fixtures/JWildfire/julian-disc-minimal.flame deleted file mode 100644 index 803bae2..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/Fixtures/JWildfire/julian-disc-minimal.flame +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalBoundaryTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalBoundaryTests.cs deleted file mode 100644 index c7c01b3..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalBoundaryTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalBoundaryTests -{ - [Fact] - public void FractalAssemblyDoesNotReferenceRendererOrD3D12Assemblies() - { - var references = typeof(CubeTileKey) - .Assembly - .GetReferencedAssemblies() - .Select(reference => reference.Name ?? string.Empty); - - foreach (var reference in references) - { - Assert.NotEqual("Aquarium.Engine", reference); - Assert.False(reference.StartsWith("Vortice.", StringComparison.Ordinal), $"Fractal core must not reference renderer dependency {reference}."); - } - } - - [Fact] - public void TestDoublesProvideDeterministicMockBoundaries() - { - var clock = new TestFractalClock(4.0, 9); - var random = new TestFractalRandom(0.25, 0.75); - var sink = new TestFractalDebugSink(); - - sink.Record("score", "node-a", random.NextDouble() + clock.TimeSeconds + clock.FrameIndex); - - Assert.Equal(4.0, clock.TimeSeconds); - Assert.Equal(9, clock.FrameIndex); - Assert.Equal(13.25, sink.Values[("score", "node-a")]); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs deleted file mode 100644 index 1a4d9b7..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalBrushEnvelope2DTests.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Brushes; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalBrushEnvelope2DTests -{ - [Fact] - public void EnvelopeWeightIsOneAtCenterAndZeroAtSupportEdge() - { - var envelope = new FractalBrushEnvelope2D(Vector2.Zero, 2.0, 1.0, 0.0, falloff: 4.0); - - Assert.Equal(1.0, envelope.Evaluate(Vector2.Zero), 12); - Assert.Equal(0.0, envelope.Evaluate(new Vector2(2.0f, 0.0f)), 12); - Assert.Equal(0.0, envelope.Evaluate(new Vector2(2.1f, 0.0f)), 12); - } - - [Fact] - public void EnvelopeRotationChangesTheLongAxis() - { - var envelope = new FractalBrushEnvelope2D(Vector2.Zero, 2.0, 1.0, Math.PI * 0.5, falloff: 4.0); - - Assert.True(envelope.Contains(new Vector2(0.0f, 1.5f))); - Assert.False(envelope.Contains(new Vector2(1.5f, 0.0f))); - } - - [Fact] - public void SignedSupportDistanceIsNegativeInsideAndPositiveOutside() - { - var envelope = new FractalBrushEnvelope2D(Vector2.Zero, 2.0, 1.0, 0.0, falloff: 4.0); - - Assert.True(envelope.SignedSupportDistanceEstimate(Vector2.Zero) < 0.0); - Assert.Equal(0.0, envelope.SignedSupportDistanceEstimate(new Vector2(2.0f, 0.0f)), 12); - Assert.True(envelope.SignedSupportDistanceEstimate(new Vector2(3.0f, 0.0f)) > 0.0); - } - - [Fact] - public void RoundEnvelopeIsRotationInvariant() - { - var unrotated = new FractalBrushEnvelope2D(Vector2.Zero, 3.0, 3.0, 0.0, falloff: 2.5); - var rotated = new FractalBrushEnvelope2D(Vector2.Zero, 3.0, 3.0, 1.7, falloff: 2.5); - var point = new Vector2(1.0f, 1.25f); - - Assert.Equal(unrotated.Evaluate(point), rotated.Evaluate(point), 12); - } - - [Fact] - public void AxisAlignedBoundsContainRotatedSupportCardinals() - { - var envelope = new FractalBrushEnvelope2D(new Vector2(4.0f, -2.0f), 3.0, 1.0, Math.PI * 0.25, falloff: 4.0); - var bounds = envelope.AxisAlignedBounds(); - - Assert.True(bounds.Contains(new Vector2(4.0f, -2.0f))); - Assert.True(bounds.Contains(new Vector2(4.0f + 2.1f, -2.0f + 2.1f))); - Assert.True(bounds.Contains(new Vector2(4.0f - 2.1f, -2.0f - 2.1f))); - } - - [Fact] - public void PacketPreservesEnvelopeFieldsForShaderLowering() - { - var envelope = new FractalBrushEnvelope2D(new Vector2(1.0f, 2.0f), 3.0, 4.0, Math.PI, falloff: 5.0, shapePower: 0.75); - - var packet = envelope.ToPacket(amplitude: -2.0); - - Assert.Equal(new Vector4(1.0f, 2.0f, 3.0f, 4.0f), packet.CenterRadii); - Assert.Equal(-1.0f, packet.RotationFalloffShape.X, 6); - Assert.Equal(0.0f, packet.RotationFalloffShape.Y, 6); - Assert.Equal(5.0f, packet.RotationFalloffShape.Z); - Assert.Equal(0.75f, packet.RotationFalloffShape.W); - Assert.Equal(-2.0f, packet.Payload.X); - } - - [Fact] - public void CpuEnvelopeMatchesShaderReferenceFormula() - { - var envelope = new FractalBrushEnvelope2D(new Vector2(-1.0f, 2.0f), 4.0, 1.5, 0.37, falloff: 3.25, shapePower: 0.8); - - foreach (var point in new[] - { - new Vector2(-1.0f, 2.0f), - new Vector2(0.5f, 2.25f), - new Vector2(-2.0f, 2.8f), - new Vector2(3.5f, 2.0f), - }) - { - Assert.Equal(envelope.Evaluate(point), ShaderReferenceEvaluate(envelope, point), 6); - } - } - - private static double ShaderReferenceEvaluate(FractalBrushEnvelope2D envelope, Vector2 point) - { - var delta = point - envelope.Center; - var c = Math.Cos(envelope.RotationRadians); - var s = Math.Sin(envelope.RotationRadians); - var localX = delta.X * c + delta.Y * s; - var localY = -delta.X * s + delta.Y * c; - var normalizedX = localX / Math.Max(envelope.RadiusX, 0.001); - var normalizedY = localY / Math.Max(envelope.RadiusY, 0.001); - var normalizedRadiusSquared = (normalizedX * normalizedX) + (normalizedY * normalizedY); - if (normalizedRadiusSquared >= 1.0) - { - return 0.0; - } - - var edgeValue = Math.Exp(-envelope.Falloff); - var gaussianValue = Math.Exp(-envelope.Falloff * normalizedRadiusSquared); - var compactValue = (gaussianValue - edgeValue) / Math.Max(1.0 - edgeValue, 0.000001); - return Math.Pow(Math.Clamp(compactValue, 0.0, 1.0), envelope.ShapePower); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalContributionCacheTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalContributionCacheTests.cs deleted file mode 100644 index e70f2ae..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalContributionCacheTests.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalContributionCacheTests -{ - [Fact] - public void CacheUpdatesOnlyBudgetedNodesEachFrame() - { - var cache = new FractalContributionCache(); - var summaries = new[] - { - Summary("node/a", maxHeightError: 2.0f), - Summary("node/b", maxHeightError: 1.0f), - Summary("node/c", maxHeightError: 0.5f), - }; - - var plan = cache.PlanFrame( - summaries, - _ => 4.0f, - new FractalResourceBudget(MaxCpuUpdates: 1, MaxGpuEstimatedCost: 8.0f, MaxResidentPayloads: 8, MaxSsdRequests: 0), - new TestFractalRandom(0.01, 0.01, 0.01), - new ResidentStore()); - - Assert.Single(plan.UpdateNodes); - Assert.True(cache.TryGet(plan.UpdateNodes[0], out var updated)); - Assert.Equal(1, updated.SampleCount); - Assert.True(updated.Confidence > 0.0f); - Assert.True(cache.LastFrameReservoir.HasSample); - Assert.Equal(plan.UpdateNodes[0], cache.LastFrameReservoir.SelectedNodeKey); - Assert.Equal(1, cache.LastFrameReservoir.CandidateCount); - Assert.True(cache.LastFrameReservoir.WeightSum > 0.0f); - } - - [Fact] - public void CacheConfidenceConvergesAcrossRepeatedFrames() - { - var cache = new FractalContributionCache(); - var summary = Summary("node/a", maxHeightError: 2.0f); - var budget = new FractalResourceBudget(MaxCpuUpdates: 1, MaxGpuEstimatedCost: 4.0f, MaxResidentPayloads: 4, MaxSsdRequests: 0); - - cache.PlanFrame([summary], _ => 4.0f, budget, new TestFractalRandom(0.01), new ResidentStore()); - cache.PlanFrame([summary], _ => 4.0f, budget, new TestFractalRandom(0.01), new ResidentStore()); - - Assert.True(cache.TryGet(summary.NodeKey, out var state)); - Assert.Equal(2, state.SampleCount); - Assert.True(state.Confidence > 0.1f); - Assert.True(state.Resident); - Assert.True(cache.TryGetOccupancy(summary.NodeKey, out var occupancy)); - Assert.Equal(summary.NodeKey, occupancy.Contribution.NodeKey); - Assert.True(occupancy.UpdateProbability > 0.0); - } - - [Fact] - public void CacheFramesScheduledContributionAsReservoirCandidate() - { - var cache = new FractalContributionCache(); - var summary = Summary("node/bright", maxHeightError: 3.0f); - - cache.PlanFrame( - [summary], - _ => 4.0f, - new FractalResourceBudget(MaxCpuUpdates: 1, MaxGpuEstimatedCost: 4.0f, MaxResidentPayloads: 4, MaxSsdRequests: 0), - new TestFractalRandom(0.01, 0.0), - new ResidentStore()); - - var reservoir = cache.LastFrameReservoir; - Assert.True(reservoir.HasSample); - Assert.Equal(summary.NodeKey, reservoir.SelectedNodeKey); - Assert.True(reservoir.SelectedContribution > 0.0f); - Assert.True(reservoir.SelectedTarget > 0.0f); - Assert.True(reservoir.ContributionWeight > 0.0f); - } - - private static AquariumFractalSummary Summary(string key, float maxHeightError) - { - return new AquariumFractalSummary( - new AquariumFractalKey(key), - Vector4.Zero, - maxHeightError, - MaxMaterialDelta: 0.0f, - EstimatedCost: 1.0f, - DescendantCount: 1); - } - - private sealed class ResidentStore : IFractalPayloadStore - { - public bool IsResident(AquariumFractalKey nodeKey) - { - return true; - } - - public void Request(AquariumFractalKey nodeKey) - { - } - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalContributionTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalContributionTests.cs deleted file mode 100644 index 4fe25e5..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalContributionTests.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalContributionTests -{ - [Fact] - public void ContributionTableStoresStableKeyedState() - { - var table = new FractalContributionTable(); - var key = new AquariumFractalKey("node/root"); - - var created = table.GetOrCreate(key); - var updated = created with { MeanContribution = 4.0f, Confidence = 0.75f, SampleCount = 3 }; - table.Store(updated); - - Assert.True(table.TryGet(key, out var stored)); - Assert.Equal(4.0f, stored.MeanContribution); - Assert.Equal(0.75f, stored.Confidence); - Assert.Equal(3, stored.SampleCount); - } - - [Fact] - public void ProjectedErrorScoreIncreasesWithError() - { - var low = Summary("low", maxHeightError: 0.5f, estimatedCost: 1.0f); - var high = Summary("high", maxHeightError: 2.0f, estimatedCost: 1.0f); - - Assert.True(FractalProjectedErrorScorer.Score(high, 10.0f) > FractalProjectedErrorScorer.Score(low, 10.0f)); - } - - [Fact] - public void ProjectedErrorScoreDecreasesWithDistanceProxy() - { - var summary = Summary("node", maxHeightError: 1.0f, estimatedCost: 1.0f); - - var nearScore = FractalProjectedErrorScorer.Score(summary, projectedPixelsPerWorldUnit: 12.0f); - var farScore = FractalProjectedErrorScorer.Score(summary, projectedPixelsPerWorldUnit: 3.0f); - - Assert.True(farScore < nearScore); - } - - [Fact] - public void ProjectedErrorScoreAccountsForEstimatedCost() - { - var cheap = Summary("cheap", maxHeightError: 1.0f, estimatedCost: 1.0f); - var expensive = Summary("expensive", maxHeightError: 1.0f, estimatedCost: 4.0f); - - Assert.True(FractalProjectedErrorScorer.Score(cheap, 10.0f) > FractalProjectedErrorScorer.Score(expensive, 10.0f)); - } - - private static AquariumFractalSummary Summary(string key, float maxHeightError, float estimatedCost) - { - return new AquariumFractalSummary( - new AquariumFractalKey(key), - Vector4.Zero, - maxHeightError, - MaxMaterialDelta: 0.0f, - estimatedCost, - DescendantCount: 1); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalDebugDumpTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalDebugDumpTests.cs deleted file mode 100644 index 8b661ec..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalDebugDumpTests.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Debug; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalDebugDumpTests -{ - [Fact] - public void DebugDumpNamesDomainClaimsSummariesAndCuts() - { - const string source = """ - tile PositiveZ 0 0 0 debug/world - height ridge 1 2 3 1 0.4 4 0.8 0.2 9 ridge - """; - var tree = FractalDslCompiler.Compile(source); - var summaries = FractalSummaryBuilder.Build(tree); - var cut = FractalSelectedCutBuilder.Build(summaries, _ => 10.0f, maxEstimatedCost: 1.0f); - - var dump = FractalDebugDump.Build(tree, summaries, cut); - - Assert.Contains("domain cube/PositiveZ/L00/0/0:debug/world", dump); - Assert.Contains("domain-path cube/PositiveZ/L00/0/0:debug/world", dump); - Assert.Contains("claim cube/PositiveZ/L00/0/0:debug/world/root/claim/0000/ridge", dump); - Assert.Contains("summary cube/PositiveZ/L00/0/0:debug/world/root", dump); - Assert.Contains("cut cube/PositiveZ/L00/0/0:debug/world/root", dump); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalDensitySplat3DCompilerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalDensitySplat3DCompilerTests.cs deleted file mode 100644 index 6d90826..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalDensitySplat3DCompilerTests.cs +++ /dev/null @@ -1,64 +0,0 @@ -using System.Numerics; -using System.Runtime.InteropServices; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalDensitySplat3DCompilerTests -{ - [Fact] - public void DensitySplat3DCompilerLowersSharedProbeIntoTransparentFormPacket() - { - var probe = new FractalProbeSample( - new AquariumFractalKey("domain/flame"), - new AquariumFractalKey("node/flame"), - new Vector3(1.0f, 2.0f, 3.0f), - BoundRadius: 4.0f, - TargetContribution: 0.8f, - SourcePdf: 0.25f, - MaterialDelta: 0.3f, - PayloadHandle: 12, - Encoding: AquariumFieldEncoding.Density); - - var splat = FractalDensitySplat3DCompiler.FromProbe( - probe, - depthRadius: 0.5f, - densityScale: 0.5f, - extinctionScale: 0.25f, - falloff: 3.0f, - shapePower: 0.75f); - - Assert.Equal("domain/flame:node/flame:density3d:000012", splat.Key.Value); - Assert.Equal(probe.LocalCenter, splat.Center); - Assert.Equal(new Vector3(4.0f, 4.0f, 0.5f), splat.Radii); - Assert.Equal(0.4f, splat.Density, 5); - Assert.Equal(0.1f, splat.Extinction, 5); - Assert.Equal(0.8f, splat.Confidence); - } - - [Fact] - public void DensitySplat3DCompilerRejectsOpaqueSdfProbe() - { - var probe = new FractalProbeSample( - new AquariumFractalKey("domain/object"), - new AquariumFractalKey("node/object"), - Vector3.Zero, - BoundRadius: 1.0f, - TargetContribution: 1.0f, - SourcePdf: 1.0f, - MaterialDelta: 0.0f, - PayloadHandle: 0); - - var ex = Assert.Throws(() => FractalDensitySplat3DCompiler.FromProbe(probe, depthRadius: 1.0f)); - - Assert.Equal("probe", ex.ParamName); - } - - [Fact] - public void PackedDensitySplatKeepsGpuStrideAlignedWithOpaqueSplat() - { - Assert.Equal(80, Marshal.SizeOf()); - Assert.Equal(Marshal.SizeOf(), Marshal.SizeOf()); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalDslCompilerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalDslCompilerTests.cs deleted file mode 100644 index 0ec73e2..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalDslCompilerTests.cs +++ /dev/null @@ -1,178 +0,0 @@ -using Aquarium.Engine.Fractal.Grammar; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalDslCompilerTests -{ - [Fact] - public void DslCompilesHeightClaimsIntoSemanticTree() - { - const string source = """ - domain Solar demo/star - 0.25 0.006 0.077 16 - domain Orbital demo/orbit demo/star 8 1 12.9 52 - domain Planetary demo/planet demo/orbit 1 0.56 0 0 - domain LatLong demo/latlong demo/planet -90 90 -180 180 - tile PositiveZ 0 0 0 zyphos/terrain demo/latlong - height basin 0 0 30 30 0 3 1 -0.18 7 basin - height ridge 3 -2 4 1.5 0.4 4 0.8 0.06 11 ridge - """; - - var tree = FractalDslCompiler.Compile(source); - - Assert.Equal("cube/PositiveZ/L00/0/0:zyphos/terrain", tree.Domain.Key.Value); - Assert.Equal(new AquariumFractalKey("demo/latlong"), tree.Domain.ParentKey); - Assert.Equal(5, tree.Domains.Count); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.Solar && domain.Key.Value == "demo/star"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.LatLong && domain.ParentKey.Value == "demo/planet"); - Assert.Equal( - ["demo/star", "demo/orbit", "demo/planet", "demo/latlong", "cube/PositiveZ/L00/0/0:zyphos/terrain"], - tree.DomainGraph.GetPath(tree.Domain.Key).Select(domain => domain.Key.Value).ToArray()); - Assert.Equal(2, tree.Claims.Count); - Assert.Equal("cube/PositiveZ/L00/0/0:zyphos/terrain/root/claim/0001/ridge", tree.Claims[1].Key.Value); - Assert.Equal(0.06f, tree.Claims[1].Amplitude); - } - - [Fact] - public void LegacyDslTileStillCompilesWithoutExplicitDomainStack() - { - const string source = """ - tile PositiveZ 0 0 0 zyphos/terrain - height basin 0 0 30 30 0 3 1 -0.18 7 basin - """; - - var tree = FractalDslCompiler.Compile(source); - - Assert.Equal("cube/PositiveZ/L00/0/0:zyphos/terrain", tree.Domain.Key.Value); - Assert.Single(tree.Domains); - Assert.Single(tree.Claims); - } - - [Fact] - public void DslIfsEmitsDeterministicRecursiveClaims() - { - const string source = """ - tile PositiveZ 0 0 0 zyphos/terrain - ifs crater 3 2 0 0 8 3 0.5 2.4 0.33 4 0.9 -0.12 19 crater - """; - - var first = FractalDslCompiler.Compile(source); - var second = FractalDslCompiler.Compile(source); - - Assert.Equal(7, first.Claims.Count); - Assert.Equal(first.Claims, second.Claims); - Assert.All(first.Claims, claim => Assert.Equal("crater", claim.Tags)); - } - - [Fact] - public void DslFlameEmitsCompactCurlingRecursiveClaims() - { - const string source = """ - tile PositiveZ 0 0 0 zyphos/terrain - flame ember 3 2 1 -2 6 2 0.45 0.72 3.1 5.0 0.8 0.05 23 flame - """; - - var first = FractalDslCompiler.Compile(source); - var second = FractalDslCompiler.Compile(source); - - Assert.Equal(7, first.Claims.Count); - Assert.Equal(first.Claims, second.Claims); - Assert.All(first.Claims, claim => Assert.Equal(AquariumFractalPayloadKind.Density, claim.PayloadKind)); - Assert.All(first.Claims, claim => Assert.Equal("flame", claim.Tags)); - Assert.True(first.Claims[1].Radii.X < first.Claims[0].Radii.X); - Assert.NotEqual(first.Claims[1].Center, first.Claims[2].Center); - Assert.NotEqual(first.Claims[0].RotationRadians, first.Claims[1].RotationRadians); - } - - [Fact] - public void DslCompilesDensityAndExtinctionClaimsIntoSemanticTree() - { - const string source = """ - tile PositiveZ 0 0 0 zyphos/flame - density smoke 0 0 4 2 0.2 3 1 0.75 31 smoke - extinction ash 1 1 2 2 0.4 5 0.8 0.35 37 ash - """; - - var tree = FractalDslCompiler.Compile(source); - - Assert.Equal(2, tree.Claims.Count); - Assert.Equal(AquariumFractalPayloadKind.Density, tree.Claims[0].PayloadKind); - Assert.Equal(AquariumFractalPayloadKind.Extinction, tree.Claims[1].PayloadKind); - Assert.Equal(0.75f, tree.Claims[0].Amplitude); - Assert.Equal(0.35f, tree.Claims[1].Amplitude); - } - - [Fact] - public void DslRippleClaimCarriesAetheriaStyleWaveEnvelope() - { - const string source = """ - tile PositiveZ 0 0 0 fensalir/marsh - ripple spine-reflection 0 -1 1.2 4.0 0.1 3.8 0.72 0.012 0.046 20.0 0.22 1.55 17 cyan-ripple - """; - - var tree = FractalDslCompiler.Compile(source); - var claim = Assert.Single(tree.Claims); - - Assert.Equal(AquariumFractalPayloadKind.Height, claim.PayloadKind); - Assert.Equal("cyan-ripple", claim.Tags); - Assert.Equal(0.012f, claim.Amplitude); - Assert.Equal(0.046f, claim.WaveAmplitude); - Assert.Equal(20.0f, claim.WaveFrequency); - Assert.Equal(0.22f, claim.WaveSpeed); - Assert.Equal(1.55f, claim.WaveSinePower); - } - - [Fact] - public void DslPreservesMultipleTileRoots() - { - const string source = """ - domain Planetary demo/planet - 1 0.56 0 0 - tile PositiveZ 0 0 0 zyphos/continent demo/planet - height basin 0 0 30 30 0 3 1 -0.18 7 basin - tile NegativeX 2 2 1 zyphos/leaf demo/planet - ifs leaf 2 2 9 9 1.8 0.72 0.42 2.8 0.61 6.0 0.58 0.018 101 leaf - """; - - var tree = FractalDslCompiler.Compile(source); - - Assert.Equal(2, tree.Nodes.Count); - Assert.Contains(tree.Nodes, node => node.DomainKey.Value == "cube/PositiveZ/L00/0/0:zyphos/continent" && node.ClaimCount == 1); - Assert.Contains(tree.Nodes, node => node.DomainKey.Value == "cube/NegativeX/L02/2/1:zyphos/leaf" && node.ClaimCount == 3); - Assert.Contains(tree.Claims, claim => claim.DomainKey.Value == "cube/PositiveZ/L00/0/0:zyphos/continent"); - Assert.Contains(tree.Claims, claim => claim.DomainKey.Value == "cube/NegativeX/L02/2/1:zyphos/leaf"); - } - - [Fact] - public void DslRejectsClaimsBeforeTile() - { - const string source = "height orphan 0 0 1 1 0 3 1 1 0 tag"; - - Assert.Throws(() => FractalDslCompiler.Compile(source)); - } - - [Fact] - public void DslRejectsMissingDomainParents() - { - const string source = """ - domain Planetary demo/planet demo/missing 1 0.56 0 0 - tile PositiveZ 0 0 0 zyphos/terrain demo/planet - height basin 0 0 30 30 0 3 1 -0.18 7 basin - """; - - var ex = Assert.Throws(() => FractalDslCompiler.Compile(source)); - Assert.Contains("demo/missing", ex.Message, StringComparison.Ordinal); - } - - [Fact] - public void DslRejectsDuplicateDomainKeys() - { - const string source = """ - domain Planetary demo/planet - 1 0.56 0 0 - domain LatLong demo/planet - -90 90 -180 180 - tile PositiveZ 0 0 0 zyphos/terrain demo/planet - height basin 0 0 30 30 0 3 1 -0.18 7 basin - """; - - var ex = Assert.Throws(() => FractalDslCompiler.Compile(source)); - Assert.Contains("Duplicate", ex.Message, StringComparison.Ordinal); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalFlameIterationStateTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalFlameIterationStateTests.cs deleted file mode 100644 index f7ad3a0..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalFlameIterationStateTests.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Grammar; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalFlameIterationStateTests -{ - [Fact] - public void PersistentIterationStateMatchesOneShotAdvance() - { - var flame = LoadJWildfireMinimalFlame(); - var initial = FractalFlameIterationState.Create(0xFACEu, sampleIndex: 17); - - var oneShot = FractalFlameIterationStepper.Advance(flame, initial, iterations: 64); - var chunked = initial; - for (var chunk = 0; chunk < 8; chunk++) - { - chunked = FractalFlameIterationStepper.Advance(flame, chunked, iterations: 8); - } - - Assert.Equal(64, oneShot.Step); - Assert.Equal(oneShot.Step, chunked.Step); - Assert.Equal(oneShot.RandomState, chunked.RandomState); - Assert.True(Vector2.Distance(oneShot.Point, chunked.Point) <= 0.000001f, $"Expected {oneShot.Point}, got {chunked.Point}."); - } - - [Fact] - public void PersistentIterationStateCarriesSampleIdentity() - { - var flame = LoadJWildfireMinimalFlame(); - var a = FractalFlameIterationStepper.Advance(flame, FractalFlameIterationState.Create(0xFACEu, sampleIndex: 17), iterations: 32); - var b = FractalFlameIterationStepper.Advance(flame, FractalFlameIterationState.Create(0xFACEu, sampleIndex: 18), iterations: 32); - - Assert.NotEqual(a.RandomState, b.RandomState); - Assert.True(Vector2.Distance(a.Point, b.Point) > 0.0001f); - } - - private static FractalFlameDefinition LoadJWildfireMinimalFlame() - { - var root = FindRepoRoot(); - var flamePath = Path.Combine(root, "tests", "Aquarium.Engine.Fractal.Tests", "Fixtures", "JWildfire", "julian-disc-minimal.flame"); - return FractalFlameFileParser.ParseFirst(File.ReadAllText(flamePath), seed: 77); - } - - private static string FindRepoRoot() - { - var directory = new DirectoryInfo(AppContext.BaseDirectory); - while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aquarium.Engine.sln"))) - { - directory = directory.Parent; - } - - return directory?.FullName ?? throw new InvalidOperationException("Could not find Aquarium repo root."); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalGpuProgramCompilerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalGpuProgramCompilerTests.cs deleted file mode 100644 index d9487f2..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalGpuProgramCompilerTests.cs +++ /dev/null @@ -1,103 +0,0 @@ -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalGpuProgramCompilerTests -{ - [Fact] - public void CompilesSelectedClaimsIntoPackedGpuTransforms() - { - const string source = """ - domain Planetary zyphos - - tile PositiveZ 2 1 1 zyphos/equator zyphos - height ridge 0.10 -0.20 0.30 0.15 0.70 4.0 0.85 1.25 17 basalt - ifs grove 2 2 0.00 0.00 0.20 0.10 0.50 1.2 0.4 3.0 0.9 0.4 91 canopy - """; - var tree = FractalDslCompiler.Compile(source); - var summaries = FractalSummaryBuilder.Build(tree); - var selected = FractalSelectedCutBuilder.Build(summaries, _ => 8.0f, 64.0f); - - var transforms = FractalGpuProgramCompiler.CompileSelectedTree(tree, selected, maxTransformCount: 8); - - Assert.NotEmpty(transforms); - Assert.All(transforms, transform => - { - Assert.True(transform.OffsetScaleAmplitude.Z > 0.0f); - Assert.True(transform.RadiiRotationFalloff.X > 0.0f); - Assert.True(transform.RadiiRotationFalloff.Y > 0.0f); - Assert.True(transform.RadiiRotationFalloff.W > 0.0f); - Assert.InRange(transform.MaterialSeedShape.X, 0.0f, 1.0f); - }); - Assert.Contains(transforms, transform => - transform.TileAddress.X == (float)CubeFace.PositiveZ - && transform.TileAddress.Y == 2.0f - && transform.TileAddress.Z == 1.0f - && transform.TileAddress.W == 1.0f); - } - - [Fact] - public void CompilesFieldPayloadEncodingIntoGpuTransformRows() - { - const string source = """ - tile PositiveZ 0 0 0 zyphos/field - height ridge 0 0 3 3 0 4 1 0.2 17 ridge - density smoke 1 1 2 2 0 4 1 0.8 19 smoke - extinction ash -1 -1 2 2 0 4 1 0.4 23 ash - """; - var tree = FractalDslCompiler.Compile(source); - var selected = FractalSelectedCutBuilder.Build(FractalSummaryBuilder.Build(tree), _ => 8.0f, 64.0f); - - var transforms = FractalGpuProgramCompiler.CompileSelectedTree(tree, selected, maxTransformCount: 8); - - Assert.Contains(transforms, transform => transform.PostTranslation.Z == (float)AquariumFieldEncoding.Height); - Assert.Contains(transforms, transform => transform.PostTranslation.Z == (float)AquariumFieldEncoding.Density); - Assert.Contains(transforms, transform => transform.PostTranslation.Z == (float)AquariumFieldEncoding.Extinction); - } - - [Fact] - public void HonorsTransformBudget() - { - const string source = """ - tile PositiveZ 2 1 1 zyphos/equator - ifs grove 4 3 0.00 0.00 0.20 0.10 0.50 1.2 0.4 3.0 0.9 0.4 91 canopy - """; - var tree = FractalDslCompiler.Compile(source); - var summaries = FractalSummaryBuilder.Build(tree); - var selected = FractalSelectedCutBuilder.Build(summaries, _ => 8.0f, 64.0f); - - var transforms = FractalGpuProgramCompiler.CompileSelectedTree(tree, selected, maxTransformCount: 5); - - Assert.Equal(5, transforms.Length); - } - - [Fact] - public void CompilesFlameTransformsIntoPackedGpuProgramRows() - { - var root = FindRepoRoot(); - var flamePath = Path.Combine(root, "tests", "Aquarium.Engine.Fractal.Tests", "Fixtures", "Apophysis", "linear-spherical-bubble.flame"); - var flame = FractalFlameFileParser.ParseFirst(File.ReadAllText(flamePath), seed: 77); - - var transforms = FractalGpuProgramCompiler.CompileFlame2D(flame, maxTransformCount: 2); - - Assert.Equal(2, transforms.Length); - Assert.Equal(flame.Transforms[0].Matrix, transforms[0].OffsetScaleAmplitude); - Assert.Equal(flame.Transforms[0].Translation.X, transforms[0].RadiiRotationFalloff.X); - Assert.Equal(flame.Transforms[0].Translation.Y, transforms[0].RadiiRotationFalloff.Y); - Assert.Equal(flame.Transforms[0].Variations.Linear, transforms[0].RadiiRotationFalloff.Z); - Assert.Equal(flame.Transforms[1].Variations.Spherical, transforms[1].RadiiRotationFalloff.W); - Assert.Equal(flame.Transforms[1].Weight, transforms[1].MaterialSeedShape.Y); - Assert.Equal(flame.Transforms[1].Color, transforms[1].MaterialSeedShape.Z); - } - - private static string FindRepoRoot() - { - var directory = new DirectoryInfo(AppContext.BaseDirectory); - while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aquarium.Engine.sln"))) - { - directory = directory.Parent; - } - - return directory?.FullName ?? throw new InvalidOperationException("Could not find Aquarium repo root."); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalGpuReservoirBudgetPlannerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalGpuReservoirBudgetPlannerTests.cs deleted file mode 100644 index f6aed44..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalGpuReservoirBudgetPlannerTests.cs +++ /dev/null @@ -1,64 +0,0 @@ -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalGpuReservoirBudgetPlannerTests -{ - [Fact] - public void PlanKeepsReservoirPassesDistinctWhileSharingBudgetMath() - { - var plan = FractalGpuReservoirBudgetPlanner.Plan( - splatCount: 2_000_000, - reservoirUpdatesPerPass: 50_000, - candidatesPerUpdate: 2); - - Assert.Equal(2_000_000, plan.SplatCount); - Assert.Equal(160_000_000UL, plan.SplatBytes); - Assert.Equal(384_000_000UL, plan.ReservoirBytes); - Assert.Equal(544_000_000UL, plan.TotalResidentBytes); - Assert.Equal(300_000UL, plan.CandidateEvaluationsThisFrame); - Assert.Equal( - new[] - { - FractalGpuReservoirPassKind.SdfEnvelope, - FractalGpuReservoirPassKind.PbrMaterial, - FractalGpuReservoirPassKind.Radiosity, - }, - plan.Passes.Select(pass => pass.Kind).ToArray()); - Assert.Equal( - new[] - { - AquariumFieldLayer.Form, - AquariumFieldLayer.Appearance, - AquariumFieldLayer.Transport, - }, - plan.Passes.Select(pass => pass.Layer).ToArray()); - Assert.Equal( - new[] - { - AquariumFieldEncoding.SignedDistance, - AquariumFieldEncoding.Material, - AquariumFieldEncoding.Radiance, - }, - plan.Passes.Select(pass => pass.Encoding).ToArray()); - - foreach (var pass in plan.Passes) - { - Assert.Equal(2_000_000, pass.ResidentEntries); - Assert.Equal(50_000, pass.UpdatesThisFrame); - Assert.Equal(2, pass.CandidatesPerUpdate); - Assert.Equal(40.0, pass.ExpectedFullCoverageFrames); - Assert.Equal(128_000_000UL, pass.ResidentBytes); - Assert.Equal(100_000UL, pass.CandidateEvaluationsThisFrame); - } - } - - [Fact] - public void PlanRejectsBudgetsThatCannotConvergeOverResidentReservoirs() - { - Assert.Throws(() => FractalGpuReservoirBudgetPlanner.Plan(0, 1, 1)); - Assert.Throws(() => FractalGpuReservoirBudgetPlanner.Plan(16, 0, 1)); - Assert.Throws(() => FractalGpuReservoirBudgetPlanner.Plan(16, 17, 1)); - Assert.Throws(() => FractalGpuReservoirBudgetPlanner.Plan(16, 1, 0)); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalGrammarContractTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalGrammarContractTests.cs deleted file mode 100644 index cafedf1..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalGrammarContractTests.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Grammar; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalGrammarContractTests -{ - [Fact] - public void CubeTileStableKeyIncludesTileAddressAndNormalizedGrammarPath() - { - var tile = new CubeTileKey(CubeFace.PositiveZ, 3, 2, 5); - - var key = FractalStableKeyBuilder.ForCubeTile(tile, @"terrain\ridge/root"); - - Assert.Equal("cube/PositiveZ/L03/2/5:terrain/ridge/root", key.Value); - } - - [Fact] - public void FlatUnionTreePreservesClaimsAndConservativeBounds() - { - var domainKey = new AquariumFractalKey("domain/planet"); - var rootKey = new AquariumFractalKey("domain/planet/root"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); - var firstClaim = Claim("claim/a", domainKey, rootKey, new Vector2(1.0f, 2.0f), new Vector2(2.0f, 1.0f)); - var secondClaim = Claim("claim/b", domainKey, rootKey, new Vector2(-3.0f, 0.0f), new Vector2(0.5f, 1.5f)); - - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, [firstClaim, secondClaim]); - - Assert.Equal(domain, tree.Domain); - Assert.Equal(2, tree.Claims.Count); - Assert.Single(tree.Nodes); - Assert.Equal(AquariumFractalOperation.Union, tree.Nodes[0].Operation); - Assert.Equal(2, tree.Nodes[0].ClaimCount); - Assert.Equal(new Vector4(-4.5f, -1.5f, 3.0f, 4.0f), tree.Nodes[0].BoundsMinMax); - } - - private static AquariumBrushClaim Claim( - string key, - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - Vector2 center, - Vector2 radii) - { - return new AquariumBrushClaim( - new AquariumFractalKey(key), - domainKey, - nodeKey, - AquariumFractalPayloadKind.Height, - center, - radii, - RotationRadians: 0.0f, - Falloff: 4.0f, - ShapePower: 1.0f, - Amplitude: 1.0f, - Seed: 17, - Tags: "test"); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalHeightBrushCompilerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalHeightBrushCompilerTests.cs deleted file mode 100644 index 6213772..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalHeightBrushCompilerTests.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Brushes; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalHeightBrushCompilerTests -{ - [Fact] - public void HeightClaimCompilesToShapedHeightFieldBrush() - { - var claim = new AquariumBrushClaim( - new AquariumFractalKey("claim/ridge"), - new AquariumFractalKey("domain/tile"), - new AquariumFractalKey("node/root"), - AquariumFractalPayloadKind.Height, - new Vector2(1.0f, 2.0f), - new Vector2(5.0f, 2.5f), - RotationRadians: 0.4f, - Falloff: 3.5f, - ShapePower: 0.7f, - Amplitude: -1.2f, - Seed: 11, - Tags: "ridge"); - - var brush = FractalHeightBrushCompiler.Compile(claim); - - Assert.Equal(claim.Center, brush.Center); - Assert.Equal(5.0f, brush.Radius); - Assert.Equal(2.5f, brush.RadiusY); - Assert.Equal(0.4f, brush.RotationRadians); - Assert.Equal(3.5f, brush.EnvelopeFalloff); - Assert.Equal(0.7f, brush.Power); - Assert.Equal(-1.2f, brush.Amplitude); - Assert.Equal(0.0f, brush.WaveAmplitude); - } - - [Fact] - public void NonHeightClaimDoesNotCompileToHeightFieldBrush() - { - var claim = new AquariumBrushClaim( - new AquariumFractalKey("claim/material"), - new AquariumFractalKey("domain/tile"), - new AquariumFractalKey("node/root"), - AquariumFractalPayloadKind.Material, - Vector2.Zero, - Vector2.One, - RotationRadians: 0.0f, - Falloff: 2.0f, - ShapePower: 1.0f, - Amplitude: 1.0f, - Seed: 0, - Tags: "material"); - - Assert.Throws(() => FractalHeightBrushCompiler.Compile(claim)); - } - - [Fact] - public void TreeCompilePreservesCubeTileDomainMetadata() - { - var domain = new AquariumFractalDomain( - new AquariumFractalKey("cube/NegativeX/L02/2/1:zyphos/leaf"), - AquariumFractalDomainKind.CubeSphereTile, - default, - new Vector4((float)CubeFace.NegativeX, 2.0f, 2.0f, 1.0f), - Vector4.Zero); - var rootKey = new AquariumFractalKey("cube/NegativeX/L02/2/1:zyphos/leaf/root"); - var claim = new AquariumBrushClaim( - new AquariumFractalKey("claim/leaf"), - domain.Key, - rootKey, - AquariumFractalPayloadKind.Height, - Vector2.Zero, - Vector2.One, - RotationRadians: 0.0f, - Falloff: 3.0f, - ShapePower: 1.0f, - Amplitude: 0.25f, - Seed: 3, - Tags: "leaf"); - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, [claim]); - - var brush = Assert.Single(FractalHeightBrushCompiler.CompileTree(tree)); - - Assert.Equal((float)CubeFace.NegativeX, brush.DomainFace); - Assert.Equal(2.0f, brush.DomainLevel); - Assert.Equal(2.0f, brush.DomainX); - Assert.Equal(1.0f, brush.DomainY); - } - - [Fact] - public void TreeCompileSkipsTransparentFormClaims() - { - const string source = """ - tile PositiveZ 0 0 0 demo/field - height basin 0 0 30 30 0 3 1 -0.18 7 basin - density smoke 0 0 4 4 0 3 1 0.75 13 smoke - extinction ash 1 1 2 2 0 3 1 0.35 17 ash - """; - var tree = FractalDslCompiler.Compile(source); - - var brush = Assert.Single(FractalHeightBrushCompiler.CompileTree(tree)); - - Assert.Equal(-0.18f, brush.Amplitude); - } - - [Fact] - public void SelectedTreeCompileOnlyLowersSelectedNodes() - { - const string source = """ - tile PositiveZ 0 0 0 demo/a - height basin 0 0 30 30 0 3 1 -0.18 7 basin - tile PositiveX 0 0 0 demo/b - height ridge 1 1 4 2 0 3 1 0.08 11 ridge - density smoke 1 1 4 2 0 3 1 0.8 19 smoke - """; - var tree = FractalDslCompiler.Compile(source); - var selectedNode = Assert.Single(tree.Nodes, node => node.DomainKey.Value.EndsWith(":demo/b", StringComparison.Ordinal)); - var selectedCut = new[] - { - new AquariumSelectedCut(selectedNode.Key, Score: 1.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: false), - }; - - var brush = Assert.Single(FractalHeightBrushCompiler.CompileSelectedTree(tree, selectedCut)); - - Assert.Equal(1.0f, brush.Center.X); - Assert.Equal((float)CubeFace.PositiveX, brush.DomainFace); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalHistogramResidualFocusTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalHistogramResidualFocusTests.cs deleted file mode 100644 index d29abef..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalHistogramResidualFocusTests.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Grammar; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalHistogramResidualFocusTests -{ - [Fact] - public void EstimateReturnsZeroWhenCandidateMatchesReference() - { - var histogram = new FractalPointHistogram(2, 2, new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), [0, 4, 2, 0]); - - Assert.Equal(Vector4.Zero, FractalHistogramResidualFocus.Estimate(histogram, histogram)); - } - - [Fact] - public void EstimateTargetsUnderrepresentedReferenceMass() - { - var reference = new FractalPointHistogram(4, 4, new Vector4(-2.0f, -2.0f, 2.0f, 2.0f), new int[16]); - var candidate = new FractalPointHistogram(4, 4, reference.Bounds, new int[16]); - reference.Bins[(1 * 4) + 2] = 100; - candidate.Bins[(3 * 4) + 0] = 100; - - var focus = FractalHistogramResidualFocus.Estimate(reference, candidate); - - Assert.Equal(0.5f, focus.X, 5); - Assert.Equal(-0.5f, focus.Y, 5); - Assert.True(focus.Z > 0.0f); - Assert.True(focus.W > 0.5f); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalNativeBufferTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalNativeBufferTests.cs deleted file mode 100644 index 38120a5..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalNativeBufferTests.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalNativeBufferTests -{ - [Fact] - public unsafe void NativeBufferExposesPointerAndSpanWithoutCopy() - { - using var buffer = new FractalNativeBuffer(4); - - buffer.Pointer[2] = buffer.Pointer[2] with { CenterRadius = new System.Numerics.Vector4(1.0f, 2.0f, 3.0f, 4.0f) }; - - Assert.Equal(4, buffer.Length); - Assert.Equal(1.0f, buffer.Span[2].CenterRadius.X); - } - - [Fact] - public void NativeBufferRejectsInvalidAlignment() - { - Assert.Throws(() => new FractalNativeBuffer(4, alignment: 48)); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalOccupancyGraphTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalOccupancyGraphTests.cs deleted file mode 100644 index 441c13c..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalOccupancyGraphTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalOccupancyGraphTests -{ - [Fact] - public void OccupancyGraphRecordsVisibilityAndUpdateProbability() - { - var graph = new FractalOccupancyGraph(); - var key = new AquariumFractalKey("node/visible"); - - graph.MarkVisible(key, observedScore: 3.5f, frameIndex: 12, updateProbability: 0.42); - - Assert.True(graph.TryGet(key, out var state)); - Assert.Equal(12, state.LastVisibleFrame); - Assert.Equal(3.5f, state.LastObservedScore); - Assert.Equal(0.42, state.UpdateProbability, precision: 3); - } - - [Fact] - public void OccupancyGraphObservationUpdatesContributionState() - { - var graph = new FractalOccupancyGraph(); - var key = new AquariumFractalKey("node/observed"); - - var contribution = graph.Observe(key, observedContribution: 2.25f, frameIndex: 5, resident: true); - - Assert.Equal(2.25f, contribution.MeanContribution); - Assert.Equal(5, contribution.LastSampledFrame); - Assert.True(contribution.Resident); - Assert.True(graph.TryGet(key, out var state)); - Assert.Equal(2.25f, state.Contribution.MeanContribution); - } - - [Fact] - public void OccupancyGraphDecaysConfidenceAndGrowsStaleUncertainty() - { - var graph = new FractalOccupancyGraph(); - var key = new AquariumFractalKey("node/stale"); - _ = graph.Observe(key, observedContribution: 1.0f, frameIndex: 1, resident: true); - _ = graph.Observe(key, observedContribution: 1.0f, frameIndex: 2, resident: true); - Assert.True(graph.TryGet(key, out var before)); - - graph.DecayUnobserved(frameIndex: 20); - - Assert.True(graph.TryGet(key, out var after)); - Assert.True(after.Contribution.Confidence < before.Contribution.Confidence); - Assert.True(after.Contribution.Variance > before.Contribution.Variance); - Assert.Equal(2, after.Contribution.LastSampledFrame); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalPipelineFixtureTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalPipelineFixtureTests.cs deleted file mode 100644 index 8bbc019..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalPipelineFixtureTests.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Brushes; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalPipelineFixtureTests -{ - [Fact] - public void CubeTileClaimPipelineProducesRenderableBudgetedBrush() - { - var tile = new CubeTileKey(CubeFace.PositiveZ, 2, 1, 1); - var domainKey = FractalStableKeyBuilder.ForCubeTile(tile, "terrain/ridges"); - var rootKey = FractalStableKeyBuilder.Child(domainKey, "root"); - var claimKey = FractalStableKeyBuilder.Child(rootKey, "claim/0"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); - var claim = new AquariumBrushClaim( - claimKey, - domainKey, - rootKey, - AquariumFractalPayloadKind.Height, - Center: new Vector2(0.25f, -0.1f), - Radii: new Vector2(0.5f, 0.2f), - RotationRadians: 0.35f, - Falloff: 3.0f, - ShapePower: 0.85f, - Amplitude: -0.4f, - Seed: 42, - Tags: "ridge"); - - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, [claim]); - var summaries = FractalSummaryBuilder.Build(tree); - var selectedCut = FractalSelectedCutBuilder.Build(summaries, _ => 8.0f, maxEstimatedCost: 1.0f, childRequestScore: 1.0f); - var residency = FractalResidencyPlanner.Plan(selectedCut, new EmptyPayloadStore()); - var brushes = FractalHeightBrushCompiler.CompileMany(tree.Claims); - - Assert.Single(tree.Nodes); - Assert.Single(summaries); - Assert.Single(selectedCut); - Assert.Single(residency.SummaryFallbackNodes); - Assert.Single(residency.RequestedNodes); - Assert.Single(brushes); - Assert.Equal(claim.Center, brushes[0].Center); - Assert.Equal(claim.Radii.X, brushes[0].Radius); - Assert.Equal(claim.Radii.Y, brushes[0].RadiusY); - } - - private sealed class EmptyPayloadStore : IFractalPayloadStore - { - public bool IsResident(AquariumFractalKey nodeKey) - { - return false; - } - - public void Request(AquariumFractalKey nodeKey) - { - } - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalProbeSampleTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalProbeSampleTests.cs deleted file mode 100644 index 34e4627..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalProbeSampleTests.cs +++ /dev/null @@ -1,185 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalProbeSampleTests -{ - [Fact] - public void ProbeSampleBuildsReservoirCandidateFromTargetAndSourcePdf() - { - var sample = Probe("zyphos/surface", Vector3.Zero, target: 4.0f, sourcePdf: 0.5f); - - var candidate = sample.ToReservoirCandidate(); - - Assert.Equal(sample, candidate.Sample); - Assert.Equal(4.0f, candidate.Target); - Assert.Equal(0.5f, candidate.SourcePdf); - Assert.Equal(8.0f, candidate.ImportanceWeight); - } - - [Fact] - public void ReuseValidatorAllowsSameLineageWithinLocalShiftBound() - { - var graph = DomainGraph(); - var source = Probe("zyphos/surface", Vector3.Zero); - var target = Probe("zyphos/surface/forest", new Vector3(0.25f, 0.0f, 0.0f)); - - var result = FractalProbeReuseValidator.Validate(source, target, graph, maxLocalShift: 0.5f); - - Assert.True(result.CanReuse); - Assert.Equal(FractalProbeReuseRejection.None, result.Rejection); - Assert.InRange(result.LocalShift, 0.24f, 0.26f); - } - - [Fact] - public void ReuseValidatorRejectsSiblingPlanetDomains() - { - var graph = DomainGraph(); - var source = Probe("zyphos/surface", Vector3.Zero); - var target = Probe("umbros/surface", Vector3.Zero); - - var result = FractalProbeReuseValidator.Validate(source, target, graph, maxLocalShift: 1.0f); - - Assert.False(result.CanReuse); - Assert.Equal(FractalProbeReuseRejection.DifferentLineage, result.Rejection); - } - - [Fact] - public void ReuseValidatorRejectsMismatchedFieldEncodings() - { - var graph = DomainGraph(); - var source = Probe("zyphos/surface", Vector3.Zero); - var target = Probe("zyphos/surface", Vector3.Zero, encoding: AquariumFieldEncoding.Density); - - var result = FractalProbeReuseValidator.Validate(source, target, graph, maxLocalShift: 1.0f); - - Assert.False(result.CanReuse); - Assert.Equal(FractalProbeReuseRejection.FieldMismatch, result.Rejection); - } - - [Fact] - public void ReuseValidatorRejectsExcessiveLocalShift() - { - var graph = DomainGraph(); - var source = Probe("zyphos/surface", Vector3.Zero); - var target = Probe("zyphos/surface", new Vector3(2.0f, 0.0f, 0.0f)); - - var result = FractalProbeReuseValidator.Validate(source, target, graph, maxLocalShift: 0.5f); - - Assert.False(result.CanReuse); - Assert.Equal(FractalProbeReuseRejection.ExcessiveLocalShift, result.Rejection); - } - - [Fact] - public void TemporalReuseValidatorRejectsExcessiveCameraMotion() - { - var result = FractalProbeReuseValidator.ValidateTemporal( - Probe("zyphos/surface", Vector3.Zero), - Probe("zyphos/surface", Vector3.Zero), - DomainGraph(), - maxLocalShift: 1.0f, - ValidTemporal() with { CameraMotionPixels = 12.0f, MaxCameraMotionPixels = 4.0f }); - - Assert.False(result.CanReuse); - Assert.Equal(FractalProbeReuseRejection.ExcessiveCameraMotion, result.Rejection); - } - - [Fact] - public void TemporalReuseValidatorRejectsDisocclusion() - { - var result = FractalProbeReuseValidator.ValidateTemporal( - Probe("zyphos/surface", Vector3.Zero), - Probe("zyphos/surface", Vector3.Zero), - DomainGraph(), - maxLocalShift: 1.0f, - ValidTemporal() with { DisocclusionConfidence = 0.2f, MinDisocclusionConfidence = 0.7f }); - - Assert.False(result.CanReuse); - Assert.Equal(FractalProbeReuseRejection.Disoccluded, result.Rejection); - } - - [Fact] - public void TemporalReuseValidatorRejectsMaterialMismatch() - { - var result = FractalProbeReuseValidator.ValidateTemporal( - Probe("zyphos/surface", Vector3.Zero), - Probe("zyphos/surface", Vector3.Zero), - DomainGraph(), - maxLocalShift: 1.0f, - ValidTemporal() with { MaterialDelta = 0.6f, MaxMaterialDelta = 0.25f }); - - Assert.False(result.CanReuse); - Assert.Equal(FractalProbeReuseRejection.MaterialMismatch, result.Rejection); - } - - [Fact] - public void TemporalReuseValidatorAllowsValidRendererInputs() - { - var result = FractalProbeReuseValidator.ValidateTemporal( - Probe("zyphos/surface", Vector3.Zero), - Probe("zyphos/surface/forest", new Vector3(0.1f, 0.0f, 0.0f)), - DomainGraph(), - maxLocalShift: 1.0f, - ValidTemporal()); - - Assert.True(result.CanReuse); - Assert.Equal(FractalProbeReuseRejection.None, result.Rejection); - } - - private static FractalProbeSample Probe( - string domainKey, - Vector3 localCenter, - float target = 1.0f, - float sourcePdf = 1.0f, - AquariumFieldEncoding encoding = AquariumFieldEncoding.SignedDistance) - { - return new FractalProbeSample( - new AquariumFractalKey(domainKey), - new AquariumFractalKey($"{domainKey}/node"), - localCenter, - BoundRadius: 0.5f, - TargetContribution: target, - SourcePdf: sourcePdf, - MaterialDelta: 0.25f, - PayloadHandle: 7, - Encoding: encoding); - } - - private static FractalDomainGraph DomainGraph() - { - return new FractalDomainGraph([ - Domain("solar", AquariumFractalDomainKind.Solar, parent: null), - Domain("zyphos", AquariumFractalDomainKind.Planetary, "solar"), - Domain("zyphos/surface", AquariumFractalDomainKind.Surface2D, "zyphos"), - Domain("zyphos/surface/forest", AquariumFractalDomainKind.Surface2D, "zyphos/surface"), - Domain("umbros", AquariumFractalDomainKind.Planetary, "solar"), - Domain("umbros/surface", AquariumFractalDomainKind.Surface2D, "umbros"), - ]); - } - - private static FractalProbeTemporalValidation ValidTemporal() - { - return new FractalProbeTemporalValidation( - CameraMotionPixels: 1.0f, - MaxCameraMotionPixels: 4.0f, - DisocclusionConfidence: 0.95f, - MinDisocclusionConfidence: 0.7f, - MaterialDelta: 0.05f, - MaxMaterialDelta: 0.25f, - VisibilityConfidence: 0.9f, - MinVisibilityConfidence: 0.5f); - } - - private static AquariumFractalDomain Domain(string key, AquariumFractalDomainKind kind, string? parent) - { - return new AquariumFractalDomain( - new AquariumFractalKey(key), - kind, - parent is null ? default : new AquariumFractalKey(parent), - Vector4.Zero, - Vector4.Zero); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalProjectedSdfSplatCompilerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalProjectedSdfSplatCompilerTests.cs deleted file mode 100644 index d389afc..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalProjectedSdfSplatCompilerTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalProjectedSdfSplatCompilerTests -{ - [Fact] - public void ProjectedCompilerLowersNearSurfaceSdfSamplesTo3DSplats() - { - var page = Page(AquariumFractalSurfacePageKind.SignedDistance2D); - var payload = new FractalSurfacePagePayload(page, [ - 1.0f, 0.2f, 1.0f, - 0.2f, 0.0f, 0.2f, - 1.0f, 0.2f, 1.0f, - ]); - - var splats = FractalProjectedSdfSplatCompiler.Compile( - payload, - point => new Vector3(point.X, point.Y, 2.0f), - Vector3.UnitZ, - tangentRadius: 0.25f, - thickness: 0.1f, - maxAbsDistance: 0.05f, - maxSplats: 8); - - var splat = Assert.Single(splats); - Assert.Equal(new Vector3(0.0f, 0.0f, 2.0f), splat.Center); - Assert.Equal(0.0f, splat.DistanceOffset); - Assert.Equal(1.0f, splat.Confidence); - Assert.Equal(page.Key.NodeKey, splat.Key.NodeKey); - } - - [Fact] - public void ProjectedCompilerKeepsClosestSamplesUnderBudget() - { - var page = Page(AquariumFractalSurfacePageKind.SignedDistance2D); - var payload = new FractalSurfacePagePayload(page, [ - 0.3f, 0.2f, 0.1f, - 0.2f, 0.0f, 0.2f, - 0.1f, 0.2f, 0.3f, - ]); - - var splats = FractalProjectedSdfSplatCompiler.Compile( - payload, - point => new Vector3(point.X, point.Y, 0.0f), - Vector3.UnitZ, - tangentRadius: 0.25f, - thickness: 0.1f, - maxAbsDistance: 0.3f, - maxSplats: 2); - - Assert.Equal(2, splats.Length); - Assert.Equal(0.0f, splats[0].DistanceOffset); - Assert.Equal(0.1f, splats[1].DistanceOffset); - } - - [Fact] - public void ProjectedCompilerRejectsNonSdfPages() - { - var payload = new FractalSurfacePagePayload(Page(AquariumFractalSurfacePageKind.Height), [0.0f]); - - Assert.Throws(() => FractalProjectedSdfSplatCompiler.Compile( - payload, - point => new Vector3(point.X, point.Y, 0.0f), - Vector3.UnitZ, - tangentRadius: 0.25f, - thickness: 0.1f, - maxAbsDistance: 0.3f, - maxSplats: 2)); - } - - private static AquariumFractalSurfacePage Page(AquariumFractalSurfacePageKind kind) - { - var size = kind == AquariumFractalSurfacePageKind.Height ? 1 : 3; - return new AquariumFractalSurfacePage( - new AquariumFractalSurfacePageKey( - new AquariumFractalKey("domain/surface"), - new AquariumFractalKey("node/surface"), - kind, - mipLevel: 0), - new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), - size, - size, - PayloadHandle: 10, - MaxError: 1.0f); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalReservoirFieldContractTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalReservoirFieldContractTests.cs deleted file mode 100644 index 88c7fed..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalReservoirFieldContractTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalReservoirFieldContractTests -{ - [Fact] - public void SceneStateCarriesFractalReservoirFieldRequest() - { - var field = new AquariumFractalReservoirField - { - SplatCount = 2_000_000, - SplatUpdatesPerFrame = 50_000, - ReservoirUpdatesPerPass = 50_000, - PriorityFocus = new Vector4(0.25f, -0.5f, 0.125f, 0.75f), - }; - var scene = new AquariumSceneState - { - FractalReservoirField = field, - }; - - Assert.True(scene.FractalReservoirField.HasInput); - Assert.Equal(8, scene.FractalReservoirField.Depth); - Assert.Equal(2, scene.FractalReservoirField.CandidatesPerReservoirUpdate); - Assert.Equal(50_000, scene.FractalReservoirField.SplatUpdatesPerFrame); - Assert.Equal(0xA17EA11u, scene.FractalReservoirField.Seed); - Assert.Equal(new Vector4(0.25f, -0.5f, 0.125f, 0.75f), scene.FractalReservoirField.PriorityFocus); - } - - [Fact] - public void FractalReservoirFieldRejectsNonConvergingUpdateBudgets() - { - Assert.False(AquariumFractalReservoirField.Empty.HasInput); - Assert.False(new AquariumFractalReservoirField { SplatCount = 16, SplatUpdatesPerFrame = 4, ReservoirUpdatesPerPass = 0 }.HasInput); - Assert.False(new AquariumFractalReservoirField { SplatCount = 16, SplatUpdatesPerFrame = 4, ReservoirUpdatesPerPass = 17 }.HasInput); - Assert.False(new AquariumFractalReservoirField { SplatCount = 16, SplatUpdatesPerFrame = 17, ReservoirUpdatesPerPass = 4 }.HasInput); - Assert.False(new AquariumFractalReservoirField { SplatCount = 16, SplatUpdatesPerFrame = 4, ReservoirUpdatesPerPass = 4, CandidatesPerReservoirUpdate = 0 }.HasInput); - Assert.False(new AquariumFractalReservoirField { SplatCount = 16, SplatUpdatesPerFrame = 4, ReservoirUpdatesPerPass = 4, Depth = 0 }.HasInput); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs deleted file mode 100644 index bd94fa2..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalResidencyPlannerTests.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalResidencyPlannerTests -{ - [Fact] - public void MissingChildRendersSummaryFallbackAndRequestsWhenHighScore() - { - var store = new TestPayloadStore(); - var key = new AquariumFractalKey("node/a"); - var cut = new AquariumSelectedCut(key, Score: 2.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: true); - - var plan = FractalResidencyPlanner.Plan([cut], store); - - Assert.Empty(plan.ResidentNodes); - Assert.Equal([key], plan.SummaryFallbackNodes); - Assert.Equal([key], plan.RequestedNodes); - Assert.Equal([key], store.Requests); - } - - [Fact] - public void ResidentNodeDoesNotRequestPayload() - { - var key = new AquariumFractalKey("node/a"); - var store = new TestPayloadStore([key]); - var cut = new AquariumSelectedCut(key, Score: 2.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: true); - - var plan = FractalResidencyPlanner.Plan([cut], store); - - Assert.Equal([key], plan.ResidentNodes); - Assert.Empty(plan.SummaryFallbackNodes); - Assert.Empty(plan.RequestedNodes); - Assert.Empty(store.Requests); - } - - [Fact] - public void ResidencyPlannerRespectsRamAndSsdBudgets() - { - var residentA = new AquariumFractalKey("node/resident-a"); - var residentB = new AquariumFractalKey("node/resident-b"); - var missingA = new AquariumFractalKey("node/missing-a"); - var missingB = new AquariumFractalKey("node/missing-b"); - var store = new TestPayloadStore([residentA, residentB]); - var cuts = new[] - { - new AquariumSelectedCut(residentA, Score: 4.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: true), - new AquariumSelectedCut(residentB, Score: 3.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: true), - new AquariumSelectedCut(missingA, Score: 2.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: true), - new AquariumSelectedCut(missingB, Score: 1.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: true), - }; - - var plan = FractalResidencyPlanner.Plan(cuts, store, maxRequests: 1, maxResidentNodes: 1); - - Assert.Equal([residentA], plan.ResidentNodes); - Assert.Equal([residentB, missingA, missingB], plan.SummaryFallbackNodes); - Assert.Equal([missingA], plan.RequestedNodes); - Assert.Equal([missingA], store.Requests); - } - - [Fact] - public void ResidencyPlannerEvictsLowScoreHighCostPayloadsFirst() - { - var expensive = new AquariumFractalKey("node/expensive"); - var cheap = new AquariumFractalKey("node/cheap"); - var store = new TestPayloadStore([expensive, cheap]); - var cuts = new[] - { - new AquariumSelectedCut(expensive, Score: 5.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: false), - new AquariumSelectedCut(cheap, Score: 4.0f, Fade: 1.0f, UsesSummary: true, RequestedChildren: false), - }; - var summaries = new[] - { - Summary(expensive, estimatedCost: 100.0f), - Summary(cheap, estimatedCost: 1.0f), - }; - - var plan = FractalResidencyPlanner.Plan(cuts, summaries, store, maxRequests: 0, maxResidentNodes: 1); - - Assert.Equal([cheap], plan.ResidentNodes); - Assert.Equal([expensive], plan.SummaryFallbackNodes); - Assert.Equal([expensive], plan.EvictedNodes); - Assert.Empty(plan.RequestedNodes); - } - - private static AquariumFractalSummary Summary(AquariumFractalKey key, float estimatedCost) - { - return new AquariumFractalSummary( - key, - Vector4.Zero, - MaxHeightError: 1.0f, - MaxMaterialDelta: 0.0f, - estimatedCost, - DescendantCount: 0); - } - - private sealed class TestPayloadStore(IEnumerable? resident = null) : IFractalPayloadStore - { - private readonly HashSet residentKeys = resident?.Select(key => key.Value).ToHashSet(StringComparer.Ordinal) ?? []; - - public List Requests { get; } = []; - - public bool IsResident(AquariumFractalKey nodeKey) - { - return residentKeys.Contains(nodeKey.Value); - } - - public void Request(AquariumFractalKey nodeKey) - { - Requests.Add(nodeKey); - } - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalResourceBudgetPlannerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalResourceBudgetPlannerTests.cs deleted file mode 100644 index 2cfda3d..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalResourceBudgetPlannerTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalResourceBudgetPlannerTests -{ - [Fact] - public void ResourcePlannerCoordinatesCpuGpuRamAndSsdBudgets() - { - var summaries = new[] - { - Summary("node/a", maxHeightError: 2.0f, estimatedCost: 2.0f), - Summary("node/b", maxHeightError: 1.5f, estimatedCost: 2.0f), - Summary("node/c", maxHeightError: 1.0f, estimatedCost: 2.0f), - }; - var states = summaries.Select(summary => new AquariumContributionState( - summary.NodeKey, - MeanContribution: 0.0f, - Variance: 1.0f, - Confidence: 0.0f, - SampleCount: 0, - LastSampledFrame: 0, - Resident: false)).ToArray(); - var store = new TestPayloadStore([summaries[0].NodeKey]); - var budget = new FractalResourceBudget( - MaxCpuUpdates: 1, - MaxGpuEstimatedCost: 4.0f, - MaxResidentPayloads: 1, - MaxSsdRequests: 1); - - var plan = FractalResourceBudgetPlanner.Plan( - summaries, - states, - _ => 4.0f, - _ => 1.0f, - budget, - new TestFractalRandom(0.01, 0.01, 0.01), - store, - frameIndex: 10); - - Assert.Single(plan.UpdateNodes); - Assert.True(plan.GpuEstimatedCost <= budget.MaxGpuEstimatedCost); - Assert.True(plan.Residency.ResidentNodes.Count <= budget.MaxResidentPayloads); - Assert.True(plan.Residency.RequestedNodes.Count <= budget.MaxSsdRequests); - Assert.Equal(plan.Residency.RequestedNodes, store.Requests); - Assert.Equal(budget, plan.Budget); - } - - [Fact] - public void ResourcePlannerRejectsNegativeBudgets() - { - var ex = Assert.Throws(() => FractalResourceBudgetPlanner.Plan( - [], - [], - _ => 0.0f, - _ => 0.0f, - new FractalResourceBudget(MaxCpuUpdates: -1, MaxGpuEstimatedCost: 0.0f, MaxResidentPayloads: 0, MaxSsdRequests: 0), - new TestFractalRandom(0.5), - new TestPayloadStore(), - frameIndex: 0)); - - Assert.Equal("MaxCpuUpdates", ex.ParamName); - } - - private static AquariumFractalSummary Summary(string key, float maxHeightError, float estimatedCost) - { - return new AquariumFractalSummary( - new AquariumFractalKey(key), - Vector4.Zero, - maxHeightError, - MaxMaterialDelta: 0.0f, - estimatedCost, - DescendantCount: 1); - } - - private sealed class TestPayloadStore(IEnumerable? resident = null) : IFractalPayloadStore - { - private readonly HashSet residentKeys = resident?.Select(key => key.Value).ToHashSet(StringComparer.Ordinal) ?? []; - - public List Requests { get; } = []; - - public bool IsResident(AquariumFractalKey nodeKey) - { - return residentKeys.Contains(nodeKey.Value); - } - - public void Request(AquariumFractalKey nodeKey) - { - Requests.Add(nodeKey); - } - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DCompilerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DCompilerTests.cs deleted file mode 100644 index f9ca33f..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DCompilerTests.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalSdfSplat3DCompilerTests -{ - [Fact] - public void SdfSplat3DCompilerLowersProbeIntoCompactSupportPacket() - { - var probe = new FractalProbeSample( - new AquariumFractalKey("domain/object"), - new AquariumFractalKey("node/object"), - new Vector3(1.0f, 2.0f, 3.0f), - BoundRadius: 4.0f, - TargetContribution: 0.8f, - SourcePdf: 0.25f, - MaterialDelta: 0.3f, - PayloadHandle: 12); - - var splat = FractalSdfSplat3DCompiler.FromProbe(probe, thickness: 0.5f, falloff: 3.0f, shapePower: 0.75f); - - Assert.Equal("domain/object:node/object:sdf3d:000012", splat.Key.Value); - Assert.Equal(probe.LocalCenter, splat.Center); - Assert.Equal(new Vector3(4.0f, 4.0f, 0.5f), splat.Radii); - Assert.Equal(0.8f, splat.Confidence); - Assert.Equal(0.3f, splat.MaterialValue); - } - - [Fact] - public void SdfSplat3DKernelIsCompactAndSigned() - { - var probe = new FractalProbeSample( - new AquariumFractalKey("domain/object"), - new AquariumFractalKey("node/object"), - Vector3.Zero, - BoundRadius: 2.0f, - TargetContribution: 1.0f, - SourcePdf: 1.0f, - MaterialDelta: 0.0f, - PayloadHandle: 0); - var splat = FractalSdfSplat3DCompiler.FromProbe(probe, thickness: 1.0f); - - Assert.Equal(1.0f, FractalSdfSplat3DKernel.CompactWeight(splat, Vector3.Zero), 5); - Assert.Equal(0.0f, FractalSdfSplat3DKernel.CompactWeight(splat, new Vector3(2.0f, 0.0f, 0.0f)), 5); - Assert.True(FractalSdfSplat3DKernel.SignedDistance(splat, Vector3.Zero) < 0.0f); - Assert.Equal(0.0f, FractalSdfSplat3DKernel.SignedDistance(splat, new Vector3(2.0f, 0.0f, 0.0f)), 5); - } - - [Fact] - public void SdfSplat3DCompilerRejectsInvalidThickness() - { - var probe = new FractalProbeSample( - new AquariumFractalKey("domain/object"), - new AquariumFractalKey("node/object"), - Vector3.Zero, - BoundRadius: 1.0f, - TargetContribution: 1.0f, - SourcePdf: 1.0f, - MaterialDelta: 0.0f, - PayloadHandle: 0); - - var ex = Assert.Throws(() => FractalSdfSplat3DCompiler.FromProbe(probe, thickness: 0.0f)); - - Assert.Equal("thickness", ex.ParamName); - } - - [Fact] - public void SdfSplat3DCompilerRejectsDensityFormProbe() - { - var probe = new FractalProbeSample( - new AquariumFractalKey("domain/flame"), - new AquariumFractalKey("node/flame"), - Vector3.Zero, - BoundRadius: 1.0f, - TargetContribution: 1.0f, - SourcePdf: 1.0f, - MaterialDelta: 0.0f, - PayloadHandle: 0, - Encoding: AquariumFieldEncoding.Density); - - var ex = Assert.Throws(() => FractalSdfSplat3DCompiler.FromProbe(probe, thickness: 1.0f)); - - Assert.Equal("probe", ex.ParamName); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs deleted file mode 100644 index f7a26cb..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalSdfSplat3DContractTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Numerics; -using System.Runtime.InteropServices; -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalSdfSplat3DContractTests -{ - [Fact] - public void SdfSplat3DKeyIsStableAcrossDomainNodeAndPayload() - { - var key = new AquariumFractalSdfSplat3DKey( - new AquariumFractalKey("domain/object"), - new AquariumFractalKey("node/branch"), - payloadHandle: 17); - - Assert.Equal("domain/object:node/branch:sdf3d:000017", key.Value); - } - - [Fact] - public void SdfSplat3DKeyRejectsNegativePayloadHandle() - { - var ex = Assert.Throws(() => new AquariumFractalSdfSplat3DKey( - new AquariumFractalKey("domain/object"), - new AquariumFractalKey("node/branch"), - payloadHandle: -1)); - - Assert.Equal("payloadHandle", ex.ParamName); - } - - [Fact] - public void SdfSplat3DContractCarriesCompactSupportFields() - { - var splat = new AquariumFractalSdfSplat3D( - new AquariumFractalSdfSplat3DKey(new AquariumFractalKey("domain/object"), new AquariumFractalKey("node/branch"), 2), - Center: new Vector3(1.0f, 2.0f, 3.0f), - Orientation: Quaternion.Identity, - Radii: new Vector3(4.0f, 5.0f, 6.0f), - Falloff: 3.0f, - ShapePower: 0.75f, - DistanceOffset: -0.1f, - MaterialValue: 0.25f, - Confidence: 0.8f); - - Assert.Equal(new Vector3(4.0f, 5.0f, 6.0f), splat.Radii); - Assert.Equal(0.8f, splat.Confidence); - } - - [Fact] - public void PackedSdfSplat3DIsFixedSizeGpuPacket() - { - Assert.Equal(80, Marshal.SizeOf()); - } - - [Fact] - public void PackedReservoirTypesAreDistinctFixedSizeGpuPackets() - { - Assert.Equal(64, Marshal.SizeOf()); - Assert.Equal(64, Marshal.SizeOf()); - Assert.Equal(64, Marshal.SizeOf()); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalSelectedCutBuilderTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalSelectedCutBuilderTests.cs deleted file mode 100644 index a3faa61..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalSelectedCutBuilderTests.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalSelectedCutBuilderTests -{ - [Fact] - public void SelectedCutChoosesHighestScoresWithinBudget() - { - var summaries = new[] - { - Summary("node/cheap-high", maxHeightError: 2.0f, estimatedCost: 1.0f), - Summary("node/expensive", maxHeightError: 10.0f, estimatedCost: 10.0f), - Summary("node/cheap-low", maxHeightError: 0.25f, estimatedCost: 1.0f), - }; - - var cut = FractalSelectedCutBuilder.Build(summaries, _ => 4.0f, maxEstimatedCost: 2.0f); - - Assert.Equal(2, cut.Length); - Assert.Equal("node/cheap-high", cut[0].NodeKey.Value); - Assert.Equal("node/cheap-low", cut[1].NodeKey.Value); - } - - [Fact] - public void SelectedCutReturnsEmptyWhenBudgetIsZero() - { - var cut = FractalSelectedCutBuilder.Build([Summary("node/a", 1.0f, 1.0f)], _ => 1.0f, maxEstimatedCost: 0.0f); - - Assert.Empty(cut); - } - - [Fact] - public void SelectedCutFadeAndChildRequestFollowScoreThreshold() - { - var cut = FractalSelectedCutBuilder.Build( - [Summary("node/a", maxHeightError: 0.5f, estimatedCost: 1.0f)], - _ => 1.0f, - maxEstimatedCost: 1.0f, - childRequestScore: 2.0f); - - Assert.Single(cut); - Assert.Equal(0.25f, cut[0].Fade); - Assert.False(cut[0].RequestedChildren); - Assert.True(cut[0].UsesSummary); - } - - private static AquariumFractalSummary Summary(string key, float maxHeightError, float estimatedCost) - { - return new AquariumFractalSummary( - new AquariumFractalKey(key), - Vector4.Zero, - maxHeightError, - MaxMaterialDelta: 0.0f, - estimatedCost, - DescendantCount: 1); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalStochasticUpdateTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalStochasticUpdateTests.cs deleted file mode 100644 index 701bdb5..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalStochasticUpdateTests.cs +++ /dev/null @@ -1,75 +0,0 @@ -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalStochasticUpdateTests -{ - [Fact] - public void EstimatorUpdatesMeanVarianceConfidenceAndSampleAge() - { - var state = NewState("node/a"); - - state = FractalContributionEstimator.Observe(state, 2.0f, frameIndex: 10, resident: true); - state = FractalContributionEstimator.Observe(state, 4.0f, frameIndex: 12, resident: true); - - Assert.Equal(3.0f, state.MeanContribution); - Assert.Equal(2.0f, state.Variance); - Assert.Equal(2, state.SampleCount); - Assert.Equal(12, state.LastSampledFrame); - Assert.True(state.Confidence > 0.0f); - Assert.True(state.Resident); - } - - [Fact] - public void VisibleNodesKeepNonzeroUpdateProbability() - { - var state = NewState("node/a") with { Confidence = 1.0f, Variance = 0.0f, LastSampledFrame = 100 }; - - var probability = FractalStochasticUpdateScheduler.UpdateProbability(state, currentScore: 0.5f, frameIndex: 100); - - Assert.True(probability > 0.0); - } - - [Fact] - public void NearThresholdNodesReceiveExtraUpdatePressure() - { - var state = NewState("node/a") with { Confidence = 1.0f, Variance = 0.0f, LastSampledFrame = 100 }; - - var low = FractalStochasticUpdateScheduler.UpdateProbability(state, currentScore: 0.2f, frameIndex: 100); - var near = FractalStochasticUpdateScheduler.UpdateProbability(state, currentScore: 1.0f, frameIndex: 100); - - Assert.True(near > low); - } - - [Fact] - public void SchedulerIsDeterministicWithFakeRandomAndRespectsBudget() - { - var states = new[] - { - NewState("node/a") with { Variance = 1.0f }, - NewState("node/b") with { Variance = 1.0f }, - NewState("node/c") with { Variance = 1.0f }, - }; - var firstRandom = new TestFractalRandom(0.01, 0.01, 0.01); - var secondRandom = new TestFractalRandom(0.01, 0.01, 0.01); - - var first = FractalStochasticUpdateScheduler.SelectUpdates(states, _ => 1.0f, maxUpdates: 2, firstRandom, frameIndex: 10); - var second = FractalStochasticUpdateScheduler.SelectUpdates(states, _ => 1.0f, maxUpdates: 2, secondRandom, frameIndex: 10); - - Assert.Equal(first, second); - Assert.Equal(2, first.Length); - } - - private static AquariumContributionState NewState(string key) - { - return new AquariumContributionState( - new AquariumFractalKey(key), - MeanContribution: 0.0f, - Variance: 1.0f, - Confidence: 0.0f, - SampleCount: 0, - LastSampledFrame: 0, - Resident: false); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeGeneratorTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeGeneratorTests.cs deleted file mode 100644 index 727196b..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeGeneratorTests.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalStructuralProbeGeneratorTests -{ - [Fact] - public void StructuralProbeUsesSummaryBoundsAsLocalSupport() - { - var summary = Summary("node/a", new Vector4(-2.0f, -1.0f, 4.0f, 3.0f), maxHeightError: 1.0f); - var domain = new AquariumFractalKey("domain/tile"); - - var probe = FractalStructuralProbeGenerator.FromSummary(summary, domain, projectedPixelsPerWorldUnit: 8.0f, sourcePdf: 0.25f, payloadHandle: 17); - - Assert.Equal(domain, probe.DomainKey); - Assert.Equal(summary.NodeKey, probe.NodeKey); - Assert.Equal(new Vector3(1.0f, 1.0f, 0.0f), probe.LocalCenter); - Assert.InRange(probe.BoundRadius, 3.60f, 3.61f); - Assert.Equal(0.25f, probe.SourcePdf); - Assert.Equal(17, probe.PayloadHandle); - } - - [Fact] - public void StructuralProbeTargetComesFromProjectedContribution() - { - var summary = Summary("node/a", new Vector4(0.0f, 0.0f, 1.0f, 1.0f), maxHeightError: 2.0f, estimatedCost: 2.0f); - - var near = FractalStructuralProbeGenerator.FromSummary(summary, new AquariumFractalKey("domain/tile"), 8.0f, sourcePdf: 1.0f); - var far = FractalStructuralProbeGenerator.FromSummary(summary, new AquariumFractalKey("domain/tile"), 2.0f, sourcePdf: 1.0f); - - Assert.True(near.TargetContribution > far.TargetContribution); - } - - [Fact] - public void StructuralProbeCandidateClampsInvalidSourceProbability() - { - var summary = Summary("node/a", new Vector4(0.0f, 0.0f, 1.0f, 1.0f), maxHeightError: 1.0f); - - var candidate = FractalStructuralProbeGenerator.BuildCandidate(summary, new AquariumFractalKey("domain/tile"), 4.0f, sourceProbability: 0.0); - - Assert.Equal(candidate.Sample.TargetContribution, candidate.Target); - Assert.True(candidate.SourcePdf > 0.0f); - Assert.True(candidate.ImportanceWeight > candidate.Target); - } - - [Fact] - public void StructuralProbeDerivesDensityEncodingFromSummaryMask() - { - var summary = Summary( - "node/density", - new Vector4(0.0f, 0.0f, 1.0f, 1.0f), - maxHeightError: 1.0f, - formEncodingMask: AquariumFieldEncodingFlags.Density); - - var probe = FractalStructuralProbeGenerator.FromSummary(summary, new AquariumFractalKey("domain/volume"), 4.0f, sourcePdf: 1.0f); - - Assert.Equal(AquariumFieldLayer.Form, probe.Layer); - Assert.Equal(AquariumFieldEncoding.Density, probe.Encoding); - } - - private static AquariumFractalSummary Summary( - string key, - Vector4 bounds, - float maxHeightError, - float estimatedCost = 1.0f, - float maxMaterialDelta = 0.0f, - AquariumFieldEncodingFlags formEncodingMask = AquariumFieldEncodingFlags.Height) - { - return new AquariumFractalSummary( - new AquariumFractalKey(key), - bounds, - maxHeightError, - maxMaterialDelta, - estimatedCost, - DescendantCount: 1, - formEncodingMask); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeReservoirTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeReservoirTests.cs deleted file mode 100644 index 61385ad..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalStructuralProbeReservoirTests.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalStructuralProbeReservoirTests -{ - [Fact] - public void StructuralProbeReservoirBuildsFromSelectedCut() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var rootKey = new AquariumFractalKey("domain/tile/root"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, [ - Claim("claim/a", domainKey, rootKey, Vector2.Zero, Vector2.One), - ]); - var summaries = FractalSummaryBuilder.Build(tree); - var cut = FractalSelectedCutBuilder.Build(summaries, _ => 8.0f, maxEstimatedCost: 8.0f); - - var snapshot = FractalStructuralProbeReservoir.Build(tree, summaries, cut, 8.0f, new TestFractalRandom(0.0)); - - Assert.True(snapshot.HasSample); - Assert.Equal(domainKey, snapshot.DomainKey); - Assert.Equal(rootKey, snapshot.NodeKey); - Assert.Equal(Vector3.Zero, snapshot.LocalCenter); - Assert.Equal(1, snapshot.CandidateCount); - Assert.Equal(0, snapshot.PayloadHandle); - Assert.Equal(AquariumFieldLayer.Form, snapshot.Layer); - Assert.Equal(AquariumFieldEncoding.SignedDistance, snapshot.Encoding); - Assert.True(snapshot.TargetContribution > 0.0f); - Assert.True(snapshot.SourcePdf > 0.0f); - Assert.True(snapshot.WeightSum > 0.0f); - } - - [Fact] - public void StructuralProbeReservoirCanSelectTransparentDensityForm() - { - var domainKey = new AquariumFractalKey("domain/flame"); - var rootKey = new AquariumFractalKey("domain/flame/root"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.Object3D, default, Vector4.Zero, Vector4.Zero); - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, [ - Claim("claim/density", domainKey, rootKey, Vector2.Zero, Vector2.One, AquariumFractalPayloadKind.Density), - ]); - var summaries = FractalSummaryBuilder.Build(tree); - var cut = FractalSelectedCutBuilder.Build(summaries, _ => 8.0f, maxEstimatedCost: 8.0f); - - var snapshot = FractalStructuralProbeReservoir.Build( - tree, - summaries, - cut, - 8.0f, - new TestFractalRandom(0.0)); - var sample = snapshot.ToProbeSample(); - - Assert.True(snapshot.HasSample); - Assert.Equal(AquariumFieldLayer.Form, snapshot.Layer); - Assert.Equal(AquariumFieldEncoding.Density, snapshot.Encoding); - Assert.Equal(AquariumFieldEncoding.Density, sample.Encoding); - } - - [Fact] - public void StructuralProbeReservoirReturnsEmptyForEmptyCut() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, new AquariumFractalKey("domain/tile/root"), []); - - var snapshot = FractalStructuralProbeReservoir.Build(tree, [], [], 8.0f, new TestFractalRandom(0.0)); - - Assert.False(snapshot.HasSample); - Assert.Equal(0, snapshot.CandidateCount); - } - - private static AquariumBrushClaim Claim( - string key, - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - Vector2 center, - Vector2 radii, - AquariumFractalPayloadKind payloadKind = AquariumFractalPayloadKind.Height) - { - return new AquariumBrushClaim( - new AquariumFractalKey(key), - domainKey, - nodeKey, - payloadKind, - center, - radii, - RotationRadians: 0.0f, - Falloff: 4.0f, - ShapePower: 1.0f, - Amplitude: 1.0f, - Seed: 17, - Tags: "probe"); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalSummaryBuilderTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalSummaryBuilderTests.cs deleted file mode 100644 index 6b42db8..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalSummaryBuilderTests.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Grammar; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalSummaryBuilderTests -{ - [Fact] - public void SummaryConservativelyCoversFlatHeightClaims() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var rootKey = new AquariumFractalKey("domain/tile/root"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); - var claims = new[] - { - Claim("claim/a", domainKey, rootKey, Vector2.Zero, Vector2.One, 0.5f), - Claim("claim/b", domainKey, rootKey, new Vector2(3.0f, 0.0f), new Vector2(2.0f, 1.0f), -1.25f), - }; - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, claims); - - var summaries = FractalSummaryBuilder.Build(tree); - - Assert.Single(summaries); - Assert.Equal(rootKey, summaries[0].NodeKey); - Assert.Equal(new Vector4(-1.0f, -2.0f, 5.0f, 2.0f), summaries[0].BoundsMinMax); - Assert.Equal(1.75f, summaries[0].MaxHeightError); - Assert.Equal(AquariumFieldEncodingFlags.Height, summaries[0].FormEncodingMask); - Assert.Equal(2.0f, summaries[0].EstimatedCost); - Assert.Equal(2, summaries[0].DescendantCount); - } - - [Fact] - public void SummaryTreatsDensityAndExtinctionAsFormContribution() - { - var domainKey = new AquariumFractalKey("domain/volume"); - var rootKey = new AquariumFractalKey("domain/volume/root"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.Object3D, default, Vector4.Zero, Vector4.Zero); - var claims = new[] - { - Claim("claim/density", domainKey, rootKey, Vector2.Zero, Vector2.One, 0.5f, AquariumFractalPayloadKind.Density), - Claim("claim/extinction", domainKey, rootKey, new Vector2(3.0f, 0.0f), new Vector2(2.0f, 1.0f), 1.25f, AquariumFractalPayloadKind.Extinction), - }; - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, claims); - - var summary = Assert.Single(FractalSummaryBuilder.Build(tree)); - - Assert.Equal(1.75f, summary.MaxHeightError); - Assert.Equal(AquariumFieldEncodingFlags.Density | AquariumFieldEncodingFlags.Extinction, summary.FormEncodingMask); - } - - private static AquariumBrushClaim Claim( - string key, - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - Vector2 center, - Vector2 radii, - float amplitude, - AquariumFractalPayloadKind payloadKind = AquariumFractalPayloadKind.Height) - { - return new AquariumBrushClaim( - new AquariumFractalKey(key), - domainKey, - nodeKey, - payloadKind, - center, - radii, - RotationRadians: 0.0f, - Falloff: 3.0f, - ShapePower: 1.0f, - Amplitude: amplitude, - Seed: 0, - Tags: "summary"); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageContractTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageContractTests.cs deleted file mode 100644 index f0b3680..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageContractTests.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalSurfacePageContractTests -{ - [Fact] - public void SurfacePageKeyIsStableAndIncludesDomainNodeKindAndMip() - { - var key = new AquariumFractalSurfacePageKey( - new AquariumFractalKey("zyphos/tile/0"), - new AquariumFractalKey("zyphos/tile/0/forest"), - AquariumFractalSurfacePageKind.SignedDistance2D, - mipLevel: 3); - - Assert.Equal("zyphos/tile/0:zyphos/tile/0/forest:SignedDistance2D:mip03", key.Value); - Assert.Equal(key.Value, key.ToString()); - } - - [Fact] - public void SurfacePageKeyRejectsNegativeMip() - { - var ex = Assert.Throws(() => new AquariumFractalSurfacePageKey( - new AquariumFractalKey("domain"), - new AquariumFractalKey("node"), - AquariumFractalSurfacePageKind.Height, - mipLevel: -1)); - - Assert.Equal("mipLevel", ex.ParamName); - } - - [Fact] - public void SurfacePageContractCarriesRendererAgnosticPayloadMetadata() - { - var key = new AquariumFractalSurfacePageKey( - new AquariumFractalKey("domain"), - new AquariumFractalKey("node"), - AquariumFractalSurfacePageKind.Material, - mipLevel: 0); - - var page = new AquariumFractalSurfacePage( - key, - new Vector4(-1.0f, -2.0f, 3.0f, 4.0f), - Width: 128, - Height: 64, - PayloadHandle: 42, - MaxError: 0.125f); - - Assert.Equal(key, page.Key); - Assert.Equal(128, page.Width); - Assert.Equal(64, page.Height); - Assert.Equal(42, page.PayloadHandle); - Assert.Equal(0.125f, page.MaxError); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePagePlannerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePagePlannerTests.cs deleted file mode 100644 index f1c867d..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePagePlannerTests.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalSurfacePagePlannerTests -{ - [Fact] - public void SurfacePagePlannerBuildsStablePagesFromSelectedCut() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var rootKey = new AquariumFractalKey("domain/tile/root"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, [ - Claim("claim/a", domainKey, rootKey, Vector2.Zero, Vector2.One, amplitude: 2.0f), - ]); - var summaries = FractalSummaryBuilder.Build(tree); - var cut = FractalSelectedCutBuilder.Build(summaries, _ => 8.0f, maxEstimatedCost: 8.0f); - - var pages = FractalSurfacePagePlanner.Plan(tree, summaries, cut, AquariumFractalSurfacePageKind.SignedDistance2D, 128, 128); - - var page = Assert.Single(pages); - Assert.Equal(domainKey, page.Key.DomainKey); - Assert.Equal(rootKey, page.Key.NodeKey); - Assert.Equal(AquariumFractalSurfacePageKind.SignedDistance2D, page.Key.Kind); - Assert.Equal(128, page.Width); - Assert.Equal(128, page.Height); - Assert.Equal(0, page.PayloadHandle); - Assert.Equal(2.0f, page.MaxError); - } - - [Fact] - public void SurfacePagePlannerRejectsInvalidDimensions() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var rootKey = new AquariumFractalKey("domain/tile/root"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, []); - - var ex = Assert.Throws(() => FractalSurfacePagePlanner.Plan( - tree, - [], - [], - AquariumFractalSurfacePageKind.Height, - width: 0, - height: 128)); - - Assert.Equal("width", ex.ParamName); - } - - [Fact] - public void SurfacePagePlannerRejectsInvalidMipEvenForEmptyCut() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var rootKey = new AquariumFractalKey("domain/tile/root"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, []); - - var ex = Assert.Throws(() => FractalSurfacePagePlanner.Plan( - tree, - [], - [], - AquariumFractalSurfacePageKind.Height, - width: 128, - height: 128, - mipLevel: -1)); - - Assert.Equal("mipLevel", ex.ParamName); - } - - [Fact] - public void SurfacePagePlannerUsesKindSpecificErrorProxy() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var rootKey = new AquariumFractalKey("domain/tile/root"); - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); - var tree = FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, [ - Claim("claim/a", domainKey, rootKey, Vector2.Zero, Vector2.One, amplitude: 2.0f), - ]); - var summary = new AquariumFractalSummary( - rootKey, - new Vector4(-1.0f, -2.0f, 3.0f, 4.0f), - MaxHeightError: 0.25f, - MaxMaterialDelta: 0.75f, - EstimatedCost: 1.0f, - DescendantCount: 0); - var cut = new[] { new AquariumSelectedCut(rootKey, Score: 1.0f, Fade: 1.0f, UsesSummary: false, RequestedChildren: false) }; - - var height = FractalSurfacePagePlanner.Plan(tree, [summary], cut, AquariumFractalSurfacePageKind.Height, 128, 128); - var material = FractalSurfacePagePlanner.Plan(tree, [summary], cut, AquariumFractalSurfacePageKind.Material, 128, 128); - var confidence = FractalSurfacePagePlanner.Plan(tree, [summary], cut, AquariumFractalSurfacePageKind.Confidence, 128, 128); - - Assert.Equal(0.25f, Assert.Single(height).MaxError); - Assert.Equal(0.75f, Assert.Single(material).MaxError); - Assert.Equal(0.75f, Assert.Single(confidence).MaxError); - } - - private static AquariumBrushClaim Claim( - string key, - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - Vector2 center, - Vector2 radii, - float amplitude) - { - return new AquariumBrushClaim( - new AquariumFractalKey(key), - domainKey, - nodeKey, - AquariumFractalPayloadKind.Height, - center, - radii, - RotationRadians: 0.0f, - Falloff: 4.0f, - ShapePower: 1.0f, - Amplitude: amplitude, - Seed: 17, - Tags: "page"); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageRasterizerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageRasterizerTests.cs deleted file mode 100644 index 87698a4..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageRasterizerTests.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalSurfacePageRasterizerTests -{ - [Fact] - public void RasterizerLowersHeightPageFromShapedBrushClaims() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var rootKey = new AquariumFractalKey("domain/tile/root"); - var tree = Tree(domainKey, rootKey, Claim("claim/a", domainKey, rootKey, amplitude: 2.0f)); - var page = Page(domainKey, rootKey, AquariumFractalSurfacePageKind.Height, width: 3, height: 3); - - var payload = FractalSurfacePageRasterizer.Rasterize(tree, page); - - Assert.Equal(0.0f, payload.Samples[0]); - Assert.Equal(2.0f, payload.Samples[4], 5); - } - - [Fact] - public void RasterizerLowersSignedDistancePageFromBrushSupport() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var rootKey = new AquariumFractalKey("domain/tile/root"); - var tree = Tree(domainKey, rootKey, Claim("claim/a", domainKey, rootKey, amplitude: 1.0f)); - var page = Page(domainKey, rootKey, AquariumFractalSurfacePageKind.SignedDistance2D, width: 3, height: 3); - - var payload = FractalSurfacePageRasterizer.Rasterize(tree, page); - - Assert.True(payload.Samples[4] < 0.0f); - Assert.Equal(0.0f, payload.Samples[1], 5); - } - - [Fact] - public void RasterizerLowersConfidencePageFromEnvelopeCoverage() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var rootKey = new AquariumFractalKey("domain/tile/root"); - var tree = Tree(domainKey, rootKey, Claim("claim/a", domainKey, rootKey, amplitude: 1.0f)); - var page = Page(domainKey, rootKey, AquariumFractalSurfacePageKind.Confidence, width: 3, height: 3); - - var payload = FractalSurfacePageRasterizer.Rasterize(tree, page); - - Assert.Equal(1.0f, payload.Samples[4], 5); - Assert.Equal(0.0f, payload.Samples[0]); - } - - [Fact] - public void RasterizerRejectsUnknownPageNode() - { - var domainKey = new AquariumFractalKey("domain/tile"); - var rootKey = new AquariumFractalKey("domain/tile/root"); - var tree = Tree(domainKey, rootKey, Claim("claim/a", domainKey, rootKey, amplitude: 1.0f)); - var page = Page(domainKey, new AquariumFractalKey("domain/tile/missing"), AquariumFractalSurfacePageKind.Height, width: 3, height: 3); - - Assert.Throws(() => FractalSurfacePageRasterizer.Rasterize(tree, page)); - } - - private static FractalOwnershipTree Tree(AquariumFractalKey domainKey, AquariumFractalKey rootKey, AquariumBrushClaim claim) - { - var domain = new AquariumFractalDomain(domainKey, AquariumFractalDomainKind.CubeSphereTile, default, Vector4.Zero, Vector4.Zero); - return FractalOwnershipTreeBuilder.BuildFlatUnion(domain, rootKey, [claim]); - } - - private static AquariumBrushClaim Claim(string key, AquariumFractalKey domainKey, AquariumFractalKey nodeKey, float amplitude) - { - return new AquariumBrushClaim( - new AquariumFractalKey(key), - domainKey, - nodeKey, - AquariumFractalPayloadKind.Height, - Vector2.Zero, - Vector2.One, - RotationRadians: 0.0f, - Falloff: 4.0f, - ShapePower: 1.0f, - Amplitude: amplitude, - Seed: 13, - Tags: "raster"); - } - - private static AquariumFractalSurfacePage Page( - AquariumFractalKey domainKey, - AquariumFractalKey nodeKey, - AquariumFractalSurfacePageKind kind, - int width, - int height) - { - return new AquariumFractalSurfacePage( - new AquariumFractalSurfacePageKey(domainKey, nodeKey, kind, mipLevel: 0), - new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), - width, - height, - PayloadHandle: 0, - MaxError: 1.0f); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageResidencyPlannerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageResidencyPlannerTests.cs deleted file mode 100644 index 6619faf..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/FractalSurfacePageResidencyPlannerTests.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Lod; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class FractalSurfacePageResidencyPlannerTests -{ - [Fact] - public void SurfacePageResidencyRetainsBestErrorPerByteUnderBudget() - { - var expensive = Page("domain/a", "node/a", AquariumFractalSurfacePageKind.Material, width: 256, height: 256, maxError: 1.0f); - var cheap = Page("domain/a", "node/b", AquariumFractalSurfacePageKind.Height, width: 64, height: 64, maxError: 0.5f); - var store = new TestSurfacePageStore([expensive.Key, cheap.Key]); - - var plan = FractalSurfacePageResidencyPlanner.Plan( - [expensive, cheap], - store, - maxResidentBytes: FractalSurfacePageResidencyPlanner.EstimatedBytes(cheap), - maxRequests: 0); - - Assert.Equal([cheap.Key], plan.ResidentPages.Select(page => page.Key)); - Assert.Equal([expensive.Key], plan.EvictedPages.Select(page => page.Key)); - Assert.Equal([expensive.Key], store.Evictions); - Assert.Equal(FractalSurfacePageResidencyPlanner.EstimatedBytes(cheap), plan.ResidentBytes); - Assert.Empty(plan.RequestedPages); - } - - [Fact] - public void SurfacePageResidencyRequestsHighestValueMissingPages() - { - var low = Page("domain/a", "node/low", AquariumFractalSurfacePageKind.Material, width: 256, height: 256, maxError: 0.1f); - var high = Page("domain/a", "node/high", AquariumFractalSurfacePageKind.Height, width: 64, height: 64, maxError: 0.5f); - var store = new TestSurfacePageStore(); - - var plan = FractalSurfacePageResidencyPlanner.Plan([low, high], store, maxResidentBytes: 0, maxRequests: 1); - - Assert.Equal([high.Key], plan.RequestedPages.Select(page => page.Key)); - Assert.Equal([high.Key], store.Requests.Select(page => page.Key)); - Assert.Equal([low.Key, high.Key], plan.MissingPages.Select(page => page.Key)); - } - - [Fact] - public void SurfacePageResidencyRejectsNegativeBudgets() - { - var store = new TestSurfacePageStore(); - - var ex = Assert.Throws(() => FractalSurfacePageResidencyPlanner.Plan( - [], - store, - maxResidentBytes: -1, - maxRequests: 0)); - - Assert.Equal("maxResidentBytes", ex.ParamName); - } - - private static AquariumFractalSurfacePage Page( - string domainKey, - string nodeKey, - AquariumFractalSurfacePageKind kind, - int width, - int height, - float maxError) - { - return new AquariumFractalSurfacePage( - new AquariumFractalSurfacePageKey( - new AquariumFractalKey(domainKey), - new AquariumFractalKey(nodeKey), - kind, - mipLevel: 0), - Vector4.Zero, - width, - height, - PayloadHandle: 0, - maxError); - } - - private sealed class TestSurfacePageStore(IEnumerable? resident = null) : IFractalSurfacePageStore - { - private readonly HashSet residentKeys = resident?.Select(key => key.Value).ToHashSet(StringComparer.Ordinal) ?? []; - - public List Requests { get; } = []; - - public List Evictions { get; } = []; - - public bool IsResident(AquariumFractalSurfacePageKey key) - { - return residentKeys.Contains(key.Value); - } - - public void Request(AquariumFractalSurfacePage page) - { - Requests.Add(page); - } - - public void Evict(AquariumFractalSurfacePageKey key) - { - Evictions.Add(key); - residentKeys.Remove(key.Value); - } - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/HeightFieldBrushContractTests.cs b/tests/Aquarium.Engine.Fractal.Tests/HeightFieldBrushContractTests.cs deleted file mode 100644 index 6ec7fe4..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/HeightFieldBrushContractTests.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class HeightFieldBrushContractTests -{ - [Fact] - public void LegacyHeightFieldBrushConstructorDefaultsToCircularEnvelope() - { - var brush = new AquariumHeightFieldBrush(Vector2.Zero, 4.0f, 2.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f); - - Assert.Equal(0.0f, brush.RadiusY); - Assert.Equal(0.0f, brush.RotationRadians); - Assert.Equal(0.0f, brush.EnvelopeFalloff); - } - - [Fact] - public void ShapedHeightFieldBrushCanCarryAnisotropicEnvelopeFields() - { - var brush = new AquariumHeightFieldBrush( - Vector2.One, - 4.0f, - 0.75f, - -1.0f, - 0.0f, - 0.0f, - 0.0f, - 0.0f, - RadiusY: 2.0f, - RotationRadians: 0.5f, - EnvelopeFalloff: 4.0f); - - Assert.Equal(2.0f, brush.RadiusY); - Assert.Equal(0.5f, brush.RotationRadians); - Assert.Equal(4.0f, brush.EnvelopeFalloff); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/ProjectionTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ProjectionTests.cs deleted file mode 100644 index b1cb12f..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/ProjectionTests.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Projection; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class ProjectionTests -{ - private static readonly ICubeSphereProjection[] Projections = - [ - new NormalizeCubeSphereProjection(), - new TangentCubeSphereProjection(), - ]; - - [Fact] - public void ProjectionCandidatesReturnUnitSpherePoints() - { - foreach (var projection in Projections) - { - var point = projection.Project(new CubeFacePosition(CubeFace.PositiveZ, 0.35, -0.25)); - - Assert.Equal(1.0f, point.Length(), 5); - } - } - - [Fact] - public void FaceEdgesMeetAtTheSameProjectedPoints() - { - var edges = new (CubeFacePosition A, CubeFacePosition B)[] - { - (new CubeFacePosition(CubeFace.PositiveZ, 1.0, -0.5), new CubeFacePosition(CubeFace.PositiveX, -1.0, -0.5)), - (new CubeFacePosition(CubeFace.PositiveZ, -1.0, 0.25), new CubeFacePosition(CubeFace.NegativeX, 1.0, 0.25)), - (new CubeFacePosition(CubeFace.PositiveZ, 0.5, 1.0), new CubeFacePosition(CubeFace.PositiveY, 0.5, -1.0)), - (new CubeFacePosition(CubeFace.PositiveZ, -0.25, -1.0), new CubeFacePosition(CubeFace.NegativeY, -0.25, 1.0)), - }; - - foreach (var projection in Projections) - { - foreach (var (a, b) in edges) - { - AssertVectorNear(projection.Project(a), projection.Project(b), 0.000001f); - } - } - } - - [Fact] - public void TangentProjectionHasLowerSampledAreaSpreadThanNormalizeBaseline() - { - var normalize = ProjectionDistortionSampler.SampleFace(new NormalizeCubeSphereProjection(), CubeFace.PositiveZ, 16); - var tangent = ProjectionDistortionSampler.SampleFace(new TangentCubeSphereProjection(), CubeFace.PositiveZ, 16); - - Assert.True(tangent.RootMeanSquareRelativeAreaError < normalize.RootMeanSquareRelativeAreaError); - Assert.True(tangent.MeanAbsoluteRelativeAreaError < normalize.MeanAbsoluteRelativeAreaError); - } - - [Fact] - public void ProjectionReportNamesMeasuredDefault() - { - var report = ProjectionReport.BuildMarkdown(Projections, 8); - - Assert.Contains("| tangent | PositiveZ |", report); - Assert.Contains("Default for the first terrain slice: `tangent`.", report); - } - - [Fact] - public void CheckedInProjectionReportMatchesSampler() - { - var reportPath = Path.Combine(FindRepositoryRoot(), "research", "rendering", "fractal-projection-report.md"); - var expectedReport = ProjectionReport.BuildMarkdown(Projections, 16); - - Assert.Equal(NormalizeLineEndings(expectedReport), NormalizeLineEndings(File.ReadAllText(reportPath))); - } - - private static void AssertVectorNear(Vector3 actual, Vector3 expected, float tolerance) - { - Assert.InRange(Vector3.Distance(actual, expected), 0.0f, tolerance); - } - - private static string FindRepositoryRoot() - { - var directory = new DirectoryInfo(AppContext.BaseDirectory); - while (directory is not null) - { - if (File.Exists(Path.Combine(directory.FullName, "Aquarium.Engine.sln"))) - { - return directory.FullName; - } - - directory = directory.Parent; - } - - throw new DirectoryNotFoundException("Could not find Aquarium.Engine.sln."); - } - - private static string NormalizeLineEndings(string value) - { - return value.Replace("\r\n", "\n", StringComparison.Ordinal); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/ResampledImportanceReservoirTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ResampledImportanceReservoirTests.cs deleted file mode 100644 index 89a7793..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/ResampledImportanceReservoirTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -using Aquarium.Engine.Fractal.Temporal; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class ResampledImportanceReservoirTests -{ - [Fact] - public void ReservoirSelectsCandidateWithProbabilityProportionalToImportanceWeight() - { - var reservoir = new ResampledImportanceReservoir(); - - Assert.True(reservoir.Add(new ResampledImportanceCandidate("dim", 1.0f, 1.0f), randomUnit: 0.0)); - Assert.True(reservoir.Add(new ResampledImportanceCandidate("bright", 9.0f, 1.0f), randomUnit: 0.5)); - - Assert.Equal("bright", reservoir.SelectedSample); - Assert.Equal(10.0f, reservoir.WeightSum); - Assert.Equal(2, reservoir.CandidateCount); - Assert.InRange(reservoir.ContributionWeight, 0.55f, 0.56f); - } - - [Fact] - public void ReservoirRejectsInvalidOrZeroWeightCandidates() - { - var reservoir = new ResampledImportanceReservoir(); - - Assert.False(reservoir.Add(new ResampledImportanceCandidate("zero-target", 0.0f, 1.0f), randomUnit: 0.0)); - Assert.False(reservoir.Add(new ResampledImportanceCandidate("zero-pdf", 1.0f, 0.0f), randomUnit: 0.0)); - - Assert.False(reservoir.HasSample); - Assert.Equal(0.0f, reservoir.WeightSum); - Assert.Equal(0, reservoir.CandidateCount); - } - - [Fact] - public void ReservoirMergeCarriesSourceCandidateCountAndWeightSum() - { - var left = new ResampledImportanceReservoir(); - var right = new ResampledImportanceReservoir(); - - Assert.True(left.Add(new ResampledImportanceCandidate("left-a", 2.0f, 1.0f), randomUnit: 0.0)); - Assert.False(left.Add(new ResampledImportanceCandidate("left-b", 1.0f, 1.0f), randomUnit: 0.99)); - Assert.True(right.Add(new ResampledImportanceCandidate("right", 6.0f, 1.0f, 4), randomUnit: 0.0)); - - Assert.True(left.Merge(right, randomUnit: 0.25)); - - Assert.Equal("right", left.SelectedSample); - Assert.Equal(9.0f, left.WeightSum); - Assert.Equal(6, left.CandidateCount); - Assert.InRange(left.ContributionWeight, 0.24f, 0.26f); - } - - [Fact] - public void ReservoirRejectsOutOfRangeRandomUnits() - { - var reservoir = new ResampledImportanceReservoir(); - - Assert.Throws( - () => reservoir.Add(new ResampledImportanceCandidate("sample", 1.0f, 1.0f), randomUnit: 1.0)); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/TemporalGaussianAccumulatorTests.cs b/tests/Aquarium.Engine.Fractal.Tests/TemporalGaussianAccumulatorTests.cs deleted file mode 100644 index ca5485e..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/TemporalGaussianAccumulatorTests.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Temporal; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class TemporalGaussianAccumulatorTests -{ - [Fact] - public void AccumulatorPredictsBufferedMotionAndExposesHistoryWeight() - { - var accumulator = new TemporalGaussianAccumulator(accumulationWindowSeconds: 2.0f, presentationDelaySeconds: 0.5f, smoothing: 1.0f); - accumulator.Observe([ - Observation("ball", new Vector3(0.0f, 0.0f, 1.0f), time: 0.0f), - Observation("ball", new Vector3(1.0f, 0.0f, 1.0f), time: 1.0f), - ]); - - var field = accumulator.BuildField(renderTimeSeconds: 1.5f); - var gaussian = Assert.Single(field.Gaussians); - - Assert.Equal("ball", gaussian.StableKey); - Assert.Equal(new Vector3(1.0f, 0.0f, 1.0f), gaussian.Center); - Assert.Equal(new Vector3(1.0f, 0.0f, 0.0f), gaussian.Velocity); - Assert.InRange(gaussian.HistoryWeight, 0.99f, 1.0f); - } - - [Fact] - public void AccumulatorExpiresSamplesOutsideWindow() - { - var accumulator = new TemporalGaussianAccumulator(accumulationWindowSeconds: 1.0f, presentationDelaySeconds: 0.0f); - accumulator.Observe([Observation("old", Vector3.Zero, time: 0.0f)]); - - var field = accumulator.BuildField(renderTimeSeconds: 2.0f); - - Assert.Empty(field.Gaussians); - } - - [Fact] - public void KernelIsCompactAnisotropicAndSdfLike() - { - var accumulator = new TemporalGaussianAccumulator(accumulationWindowSeconds: 2.0f, presentationDelaySeconds: 0.0f); - accumulator.Observe([Observation("brush", Vector3.Zero, time: 0.0f, radii: new Vector3(2.0f, 1.0f, 1.0f))]); - var gaussian = Assert.Single(accumulator.BuildField(0.0f).Gaussians); - - Assert.Equal(1.0f, TemporalSdfGaussianKernel.CompactWeight(gaussian, Vector3.Zero), 6); - Assert.Equal(0.0f, TemporalSdfGaussianKernel.CompactWeight(gaussian, new Vector3(2.0f, 0.0f, 0.0f)), 6); - Assert.True(TemporalSdfGaussianKernel.CompactWeight(gaussian, new Vector3(1.5f, 0.0f, 0.0f)) > 0.0f); - Assert.True(TemporalSdfGaussianKernel.CompactWeight(gaussian, new Vector3(0.0f, 1.5f, 0.0f)) == 0.0f); - Assert.True(TemporalSdfGaussianKernel.SignedDistance(gaussian, Vector3.Zero) < 0.0f); - Assert.Equal(0.0f, TemporalSdfGaussianKernel.SignedDistance(gaussian, new Vector3(2.0f, 0.0f, 0.0f)), 5); - } - - private static TemporalGaussianObservation Observation( - string key, - Vector3 center, - float time, - Vector3? radii = null) - { - return new TemporalGaussianObservation( - key, - center, - radii ?? new Vector3(0.1f), - Quaternion.Identity, - new Vector4(1.0f), - Confidence: 1.0f, - ObservedTimeSeconds: time, - FieldId: 12); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/TemporalSpatialEvidenceLoweringTests.cs b/tests/Aquarium.Engine.Fractal.Tests/TemporalSpatialEvidenceLoweringTests.cs deleted file mode 100644 index 5773285..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/TemporalSpatialEvidenceLoweringTests.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Temporal; -using Aquarium.Engine.Render; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class TemporalSpatialEvidenceLoweringTests -{ - [Fact] - public void GaussianLoweringRoundTripsKernelPayload() - { - var observation = new TemporalGaussianObservation( - "gaussian/a", - Vector3.One, - new Vector3(0.2f, 0.3f, 0.4f), - Quaternion.Identity, - new Vector4(0.1f, 0.2f, 0.3f, 0.4f), - Confidence: 0.75f, - ObservedTimeSeconds: 12.0f, - Falloff: 5.0f, - ShapePower: 1.8f, - FieldId: 44); - - var lowered = TemporalSpatialEvidenceLowering.FromGaussianObservation(observation); - Assert.Equal(AquariumFieldLayer.Form, lowered.Layer); - Assert.Equal(AquariumFieldEncoding.Density, lowered.Encoding); - var sample = new TemporalSpatialEvidenceSample( - lowered.StableKey, - lowered.Center, - lowered.Center, - Vector3.Zero, - lowered.Radii, - lowered.Orientation, - lowered.Payload0, - lowered.Payload1, - lowered.Confidence, - HistoryWeight: 0.6f, - lowered.ObservedTimeSeconds, - lowered.FieldId, - lowered.Layer, - lowered.Encoding); - var gaussian = TemporalSpatialEvidenceLowering.ToTemporalGaussian(sample); - - Assert.Equal(observation.StableKey, gaussian.StableKey); - Assert.Equal(observation.ColorOpacity, gaussian.ColorOpacity); - Assert.Equal(5.0f, gaussian.Falloff); - Assert.Equal(1.8f, gaussian.ShapePower); - Assert.Equal(44, gaussian.FieldId); - } - - [Fact] - public void GpuFusionLoweringRoundTripsSeedPayload() - { - var seed = new AquariumGpuFusionSeed( - "fusion/a", - Vector3.One, - Vector3.Zero, - new Vector3(0.1f, 0.0f, 0.0f), - new Vector3(0.2f), - new Vector4(0.4f, 0.5f, 0.6f, 0.7f), - Confidence: 0.8f, - HistoryWeight: 0.65f, - Falloff: 4.4f, - ShapePower: 2.1f, - FieldId: 91); - - var lowered = TemporalSpatialEvidenceLowering.FromGpuFusionSeed(seed, observedTimeSeconds: 3.0f); - Assert.Equal(AquariumFieldLayer.Form, lowered.Layer); - Assert.Equal(AquariumFieldEncoding.Confidence, lowered.Encoding); - var sample = new TemporalSpatialEvidenceSample( - lowered.StableKey, - lowered.Center, - seed.PreviousCenter, - seed.Velocity, - lowered.Radii, - lowered.Orientation, - lowered.Payload0, - lowered.Payload1, - lowered.Confidence, - lowered.Payload1.Z, - lowered.ObservedTimeSeconds, - lowered.FieldId, - lowered.Layer, - lowered.Encoding); - var roundTrip = TemporalSpatialEvidenceLowering.ToGpuFusionSeed(sample); - - Assert.Equal(seed.StableKey, roundTrip.StableKey); - Assert.Equal(seed.ColorOpacity, roundTrip.ColorOpacity); - Assert.Equal(seed.Falloff, roundTrip.Falloff); - Assert.Equal(seed.ShapePower, roundTrip.ShapePower); - Assert.Equal(seed.FieldId, roundTrip.FieldId); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/TemporalSpatialEvidenceReservoirTests.cs b/tests/Aquarium.Engine.Fractal.Tests/TemporalSpatialEvidenceReservoirTests.cs deleted file mode 100644 index 2ba9084..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/TemporalSpatialEvidenceReservoirTests.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Fractal.Temporal; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class TemporalSpatialEvidenceReservoirTests -{ - [Fact] - public void ReservoirPredictsDelayedMotionForStableSpatialEvidence() - { - var reservoir = new TemporalSpatialEvidenceReservoir( - accumulationWindowSeconds: 2.0f, - presentationDelaySeconds: 0.5f, - smoothing: 1.0f); - - reservoir.Observe([ - Observation("feature/a", Vector3.Zero, time: 0.0f), - Observation("feature/a", new Vector3(1.0f, 0.0f, 0.0f), time: 1.0f), - ]); - - var sample = Assert.Single(reservoir.BuildSnapshot(renderTimeSeconds: 1.5f).Samples); - - Assert.Equal(new Vector3(1.0f, 0.0f, 0.0f), sample.Center); - Assert.Equal(new Vector3(1.0f, 0.0f, 0.0f), sample.Velocity); - Assert.InRange(sample.HistoryWeight, 0.99f, 1.0f); - } - - [Fact] - public void ReservoirExpiresSamplesOutsideWindow() - { - var reservoir = new TemporalSpatialEvidenceReservoir( - accumulationWindowSeconds: 1.0f, - presentationDelaySeconds: 0.0f); - reservoir.Observe([Observation("feature/old", Vector3.Zero, time: 0.0f)]); - - var snapshot = reservoir.BuildSnapshot(renderTimeSeconds: 2.0f); - - Assert.Empty(snapshot.Samples); - } - - [Fact] - public void ReservoirEvictsLowestConfidenceTracksWhenOverBudget() - { - var reservoir = new TemporalSpatialEvidenceReservoir( - accumulationWindowSeconds: 5.0f, - presentationDelaySeconds: 0.0f, - smoothing: 1.0f, - maxTrackCount: 2); - - reservoir.Observe([ - Observation("weak", Vector3.Zero, time: 0.0f, confidence: 0.2f), - Observation("strong", Vector3.One, time: 0.0f, confidence: 1.0f), - Observation("middle", new Vector3(2.0f), time: 0.0f, confidence: 0.6f), - ]); - - var keys = reservoir.BuildSnapshot(renderTimeSeconds: 0.0f).Samples.Select(sample => sample.StableKey).ToArray(); - - Assert.DoesNotContain("weak", keys); - Assert.Contains("strong", keys); - Assert.Contains("middle", keys); - } - - [Fact] - public void ReservoirPreservesRendererSpecificPayloadsWithoutOwningThem() - { - var reservoir = new TemporalSpatialEvidenceReservoir( - accumulationWindowSeconds: 5.0f, - presentationDelaySeconds: 0.0f); - var payload0 = new Vector4(0.2f, 0.4f, 0.6f, 0.8f); - var payload1 = new Vector4(4.0f, 1.5f, 0.0f, 0.0f); - - reservoir.Observe([Observation("feature/payload", Vector3.Zero, time: 0.0f, payload0: payload0, payload1: payload1)]); - - var sample = Assert.Single(reservoir.BuildSnapshot(renderTimeSeconds: 0.0f).Samples); - Assert.Equal(payload0, sample.Payload0); - Assert.Equal(payload1, sample.Payload1); - } - - [Fact] - public void ReservoirKeepsOpaqueAndTransparentFieldsAsSeparateTracks() - { - var reservoir = new TemporalSpatialEvidenceReservoir( - accumulationWindowSeconds: 5.0f, - presentationDelaySeconds: 0.0f); - - reservoir.Observe([ - Observation("feature/shared", Vector3.Zero, time: 0.0f, encoding: AquariumFieldEncoding.SignedDistance), - Observation("feature/shared", Vector3.One, time: 0.0f, encoding: AquariumFieldEncoding.Density), - ]); - - var samples = reservoir.BuildSnapshot(renderTimeSeconds: 0.0f).Samples; - - Assert.Equal(2, samples.Count); - Assert.Contains(samples, sample => sample.StableKey == "feature/shared" && sample.Encoding == AquariumFieldEncoding.SignedDistance); - Assert.Contains(samples, sample => sample.StableKey == "feature/shared" && sample.Encoding == AquariumFieldEncoding.Density); - } - - private static TemporalSpatialEvidenceObservation Observation( - string key, - Vector3 center, - float time, - float confidence = 1.0f, - Vector4? payload0 = null, - Vector4? payload1 = null, - AquariumFieldEncoding encoding = AquariumFieldEncoding.Density) - { - return new TemporalSpatialEvidenceObservation( - key, - center, - new Vector3(0.1f), - Quaternion.Identity, - payload0 ?? Vector4.One, - payload1 ?? Vector4.Zero, - confidence, - time, - FieldId: 3, - Encoding: encoding); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/TestDoubles.cs b/tests/Aquarium.Engine.Fractal.Tests/TestDoubles.cs deleted file mode 100644 index e9b11e5..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/TestDoubles.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Aquarium.Engine.Fractal; - -namespace Aquarium.Engine.Fractal.Tests; - -internal sealed class TestFractalClock(double timeSeconds, ulong frameIndex) : IFractalClock -{ - public double TimeSeconds { get; } = timeSeconds; - - public ulong FrameIndex { get; } = frameIndex; -} - -internal sealed class TestFractalDebugSink : IFractalDebugSink -{ - public Dictionary<(string Channel, string Key), double> Values { get; } = []; - - public void Record(string channel, string key, double value) - { - Values[(channel, key)] = value; - } -} - -internal sealed class TestFractalRandom(params double[] values) : IFractalRandom -{ - private int index; - - public double NextDouble() - { - if (values.Length == 0) - { - throw new InvalidOperationException("Test random has no values."); - } - - var value = values[index % values.Length]; - index++; - return value; - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/ZyphosCameraComposerTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ZyphosCameraComposerTests.cs deleted file mode 100644 index c9be793..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/ZyphosCameraComposerTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -using Aquarium.Zyphos; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class ZyphosCameraComposerTests -{ - [Fact] - public void PlanetFrameLooksAtZyphosCenter() - { - var shot = ZyphosCameraComposer.Compose(ZyphosSpatialDomainCatalog.Planet, -0.2f, 0.3f, 16.0f, 0.0f); - var orbitalCenter = ZyphosUmbrosSystem.ZyphosCenter + (ZyphosUmbrosSystem.UmbrosCenter(0.0f) - ZyphosUmbrosSystem.ZyphosCenter) * 0.5f; - - Assert.Equal(ZyphosUmbrosSystem.ZyphosCenter, shot.CameraTarget); - Assert.Equal(orbitalCenter, shot.ParentAnchor); - Assert.Equal(ZyphosUmbrosSystem.ZyphosCenter, shot.TrackedCenter); - Assert.Equal(ZyphosSpatialDomainCatalog.Orbital, shot.ParentDomainKey); - } - - [Fact] - public void UmbrosFrameKeepsParentAsCompositionAnchor() - { - var shot = ZyphosCameraComposer.Compose(ZyphosSpatialDomainCatalog.Umbros, -0.2f, 0.3f, 16.0f, 0.0f); - var orbitalCenter = ZyphosUmbrosSystem.ZyphosCenter + (ZyphosUmbrosSystem.UmbrosCenter(0.0f) - ZyphosUmbrosSystem.ZyphosCenter) * 0.5f; - - Assert.Equal(ZyphosUmbrosSystem.UmbrosCenter(0.0f), shot.CameraTarget); - Assert.Equal(orbitalCenter, shot.ParentAnchor); - Assert.Equal(ZyphosUmbrosSystem.UmbrosCenter(0.0f), shot.TrackedCenter); - Assert.True(shot.EffectiveDistance > ZyphosUmbrosSystem.CenterSeparation * 0.5f); - Assert.True(shot.EffectiveDistance < ZyphosUmbrosSystem.CenterSeparation); - } - - [Fact] - public void BinaryFrameTracksMidpointWhilePivotingAroundParent() - { - var shot = ZyphosCameraComposer.Compose(ZyphosSpatialDomainCatalog.Orbital, 0.1f, 0.4f, 16.0f, 0.0f); - var midpoint = ZyphosUmbrosSystem.ZyphosCenter + (ZyphosUmbrosSystem.UmbrosCenter(0.0f) - ZyphosUmbrosSystem.ZyphosCenter) * 0.5f; - - Assert.Equal(midpoint, shot.CameraTarget); - Assert.Equal(midpoint, shot.TrackedCenter); - } - - [Fact] - public void SolarFrameTargetsVisibleParentStar() - { - var shot = ZyphosCameraComposer.Compose(ZyphosSpatialDomainCatalog.Solar, 0.1f, 0.4f, 16.0f, 0.0f); - - Assert.Equal(ZyphosUmbrosSystem.PrimaryStarCenter(0.0f), shot.CameraTarget); - Assert.Equal(ZyphosUmbrosSystem.PrimaryStarCenter(0.0f), shot.TrackedCenter); - Assert.Null(shot.ParentDomainKey); - } - - [Fact] - public void LeafScaleDomainsCanZoomBelowPlanetaryDistance() - { - var shot = ZyphosCameraComposer.Compose(ZyphosSpatialDomainCatalog.CanopyLeaf, 0.1f, 0.4f, 0.1f, 0.0f); - - Assert.True(shot.MinimumDistance < 0.25f); - Assert.True(shot.EffectiveDistance < 1.0f); - } - - [Fact] - public void SurfaceTilePivotsThroughLatLongParent() - { - var shot = ZyphosCameraComposer.Compose(ZyphosSpatialDomainCatalog.TerrainTile, 0.1f, 0.4f, 16.0f, 0.0f); - - Assert.Equal(ZyphosSpatialDomainCatalog.ContinentArchipelago, shot.ParentDomainKey); - Assert.Equal(shot.TrackedCenter, shot.CameraTarget); - Assert.NotEqual(ZyphosUmbrosSystem.ZyphosCenter, shot.CameraTarget); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs deleted file mode 100644 index 693f10f..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/ZyphosFractalTerrainTests.cs +++ /dev/null @@ -1,124 +0,0 @@ -using Aquarium.Zyphos; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class ZyphosFractalTerrainTests -{ - [Fact] - public void ZyphosTerrainCompilesDslIntoRenderableBrushes() - { - var tree = ZyphosFractalTerrain.OwnershipTree; - var brushes = ZyphosFractalTerrain.HeightBrushes; - - Assert.EndsWith(".aquageo", ZyphosFractalTerrain.PatchPath, StringComparison.Ordinal); - Assert.True(File.Exists(ZyphosFractalTerrain.PatchPath), $"Expected copied aquageo patch at {ZyphosFractalTerrain.PatchPath}."); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.Solar && domain.Key.Value == "zyphos/parent-star"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.Orbital && domain.Key.Value == "zyphos/zyphos-umbros-orbit"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.Planetary && domain.Key.Value == "zyphos/umbros"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.LatLong && domain.Key.Value == "zyphos/planet-latlong"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.LatLong && domain.Key.Value == "zyphos/umbros-latlong"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.Surface2D && domain.Key.Value == "zyphos/equatorial-forest"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.Object3D && domain.Key.Value == "zyphos/canopy-leaf"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.Object3D && domain.Key.Value == "umbros/pebble-field"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.CubeSphereTile && domain.ParentKey.Value == "zyphos/canopy-leaf"); - Assert.Contains(tree.Domains, domain => domain.Kind == AquariumFractalDomainKind.CubeSphereTile && domain.ParentKey.Value == "umbros/pebble-field"); - Assert.Equal(new AquariumFractalKey("umbros/pebble-field"), tree.Domain.ParentKey); - Assert.Equal(7, tree.Nodes.Count); - Assert.Equal(61, tree.Claims.Count); - Assert.Equal(tree.Claims.Count(claim => claim.PayloadKind == AquariumFractalPayloadKind.Height), brushes.Length); - Assert.Contains(tree.Claims, claim => claim.PayloadKind == AquariumFractalPayloadKind.Density && claim.Tags == "flame-leaf"); - Assert.Contains(tree.Claims, claim => claim.Tags == "crater"); - Assert.Contains(tree.Claims, claim => claim.Tags == "ridge"); - Assert.Contains(tree.Claims, claim => claim.Tags == "shard"); - Assert.Contains(tree.Claims, claim => claim.Tags == "crown"); - Assert.Contains(tree.Claims, claim => claim.Tags == "leaf"); - Assert.Contains(tree.Claims, claim => claim.Tags == "flame-leaf"); - Assert.Contains(tree.Claims, claim => claim.Tags == "pebble"); - Assert.Contains(brushes, brush => brush.EnvelopeFalloff > 0.0f && brush.RadiusY > 0.0f); - } - - [Fact] - public void ZyphosFractalRenderPlanUsesCameraContributionPressure() - { - var nearShot = ZyphosCameraComposer.Compose(ZyphosSpatialDomainCatalog.CanopyLeaf, 0.1f, 0.4f, 0.1f, 0.0f); - var farShot = ZyphosCameraComposer.Compose(ZyphosSpatialDomainCatalog.Solar, 0.1f, 0.4f, 80.0f, 0.0f); - - var near = ZyphosFractalTerrain.BuildRenderPlan(nearShot); - var far = ZyphosFractalTerrain.BuildRenderPlan(farShot); - - Assert.True(near.PixelsPerWorld > far.PixelsPerWorld); - Assert.Equal(ZyphosFractalTerrain.SelectedCuts.Length, near.SelectedCuts.Length); - Assert.Equal(ZyphosFractalTerrain.HeightBrushes.Length, near.HeightBrushes.Length); - Assert.Contains("px-wu", near.Summary, StringComparison.Ordinal); - Assert.Contains("cpu updates", near.Summary, StringComparison.Ordinal); - Assert.Contains("gpu cost", near.Summary, StringComparison.Ordinal); - Assert.Contains("resident", near.Summary, StringComparison.Ordinal); - Assert.Contains("probe candidates", near.Summary, StringComparison.Ordinal); - Assert.Contains("surface payloads", near.Summary, StringComparison.Ordinal); - Assert.True(near.StructuralProbeReservoir.HasSample); - Assert.True(near.StructuralProbeReservoir.CandidateCount > 0); - Assert.True(near.StructuralProbeReservoir.WeightSum > 0.0f); - Assert.Single(near.StructuralSdfSplats); - Assert.Equal(near.StructuralProbeReservoir.NodeKey, near.StructuralSdfSplats[0].Key.NodeKey); - Assert.Equal(near.SelectedCuts.Length * 4, near.SurfacePages.Length); - Assert.Contains(near.SurfacePages, page => page.Key.Kind == AquariumFractalSurfacePageKind.SignedDistance2D); - Assert.True(near.SurfacePageResidency.ResidentPages.Count <= near.SurfacePages.Length); - Assert.True(near.SurfacePageResidency.ResidentBytes <= 2L * 1024L * 1024L); - Assert.True(near.SurfacePageResidency.RequestedPages.Count <= 8); - Assert.Equal(near.SurfacePageResidency.ResidentPages.Count, near.SurfacePagePayloads.Length); - Assert.All(near.SurfacePagePayloads, payload => Assert.Equal(payload.Page.Width * payload.Page.Height, payload.Samples.Length)); - Assert.True(near.ProjectedSurfaceSdfSplats.Length <= 64); - Assert.NotEmpty(near.ProjectedSurfaceSdfSplats); - Assert.All(near.SurfacePages, page => - { - Assert.Equal(128, page.Width); - Assert.Equal(128, page.Height); - Assert.Contains(near.SelectedCuts, cut => cut.NodeKey == page.Key.NodeKey); - }); - Assert.Empty(near.ResourcePlan.Residency.RequestedNodes); - Assert.True(MathF.Abs(near.HeightBrushes[0].Amplitude) * MathF.Max(near.HeightBrushes[0].Radius, near.HeightBrushes[0].RadiusY) >= - MathF.Abs(near.HeightBrushes[^1].Amplitude) * MathF.Max(near.HeightBrushes[^1].Radius, near.HeightBrushes[^1].RadiusY)); - } - - [Fact] - public void ZyphosSceneRequestsGpuFractalReservoirField() - { - var shot = ZyphosCameraComposer.Compose(ZyphosSpatialDomainCatalog.CanopyLeaf, 0.1f, 0.4f, 0.1f, 0.0f); - var scene = ZyphosSceneBuilder.Build(1.0f, 0.9f, ZyphosFractalTerrain.BuildRenderPlan(shot)); - - Assert.True(scene.FractalReservoirField.HasInput); - Assert.Equal(2_000_000, scene.FractalReservoirField.SplatCount); - Assert.Equal(50_000, scene.FractalReservoirField.SplatUpdatesPerFrame); - Assert.Equal(20_000, scene.FractalReservoirField.ReservoirUpdatesPerPass); - Assert.Equal(2, scene.FractalReservoirField.CandidatesPerReservoirUpdate); - Assert.Equal(ZyphosUmbrosSystem.ZyphosSurfaceRadius, scene.FractalReservoirField.WorldCenterRadius.W); - Assert.True(scene.FractalReservoirField.PriorityFocus.Z > 0.0f); - Assert.True(scene.FractalReservoirField.PriorityFocus.W > 0.0f); - Assert.NotEmpty(scene.FractalReservoirField.ProgramTransforms); - } - - [Fact] - public void ZyphosFractalPlanDebugDumpReportsResourceBudgets() - { - var shot = ZyphosCameraComposer.Compose(ZyphosSpatialDomainCatalog.CanopyLeaf, 0.1f, 0.4f, 0.1f, 0.0f); - var dump = ZyphosFractalTerrain.BuildPlanDebugDump(ZyphosFractalTerrain.BuildRenderPlan(shot)); - - Assert.Contains("Zyphos fractal resource plan", dump, StringComparison.Ordinal); - Assert.Contains("cpuUpdates:", dump, StringComparison.Ordinal); - Assert.Contains("gpuEstimatedCost:", dump, StringComparison.Ordinal); - Assert.Contains("ramResident:", dump, StringComparison.Ordinal); - Assert.Contains("ssdRequests:", dump, StringComparison.Ordinal); - Assert.Contains("evictions:", dump, StringComparison.Ordinal); - Assert.Contains("structuralProbe:", dump, StringComparison.Ordinal); - Assert.Contains("structuralProbeWeight:", dump, StringComparison.Ordinal); - Assert.Contains("structuralSdfSplats:", dump, StringComparison.Ordinal); - Assert.Contains("surfacePages:", dump, StringComparison.Ordinal); - Assert.Contains("surfacePageResident:", dump, StringComparison.Ordinal); - Assert.Contains("surfacePagePayloads:", dump, StringComparison.Ordinal); - Assert.Contains("projectedSurfaceSdfSplats:", dump, StringComparison.Ordinal); - Assert.Contains("gpuProgramTransforms:", dump, StringComparison.Ordinal); - Assert.Contains("surfacePageRequests:", dump, StringComparison.Ordinal); - Assert.Contains("surfacePageEvictions:", dump, StringComparison.Ordinal); - Assert.Contains("selected:", dump, StringComparison.Ordinal); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/ZyphosNamingTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ZyphosNamingTests.cs deleted file mode 100644 index 3559567..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/ZyphosNamingTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class ZyphosNamingTests -{ - [Fact] - public void ZyphosSourceDoesNotModelUmbrosAsMoon() - { - var root = FindRepositoryRoot(); - var zyphosFiles = Directory.GetFiles(Path.Combine(root, "src", "Aquarium.Zyphos"), "*.*", SearchOption.AllDirectories) - .Where(path => path.EndsWith(".cs", StringComparison.Ordinal) || path.EndsWith(".hlsl", StringComparison.Ordinal)) - .ToArray(); - - foreach (var file in zyphosFiles) - { - var text = File.ReadAllText(file); - Assert.DoesNotContain("Moon", text, StringComparison.Ordinal); - Assert.DoesNotContain("moon", text, StringComparison.Ordinal); - } - } - - private static string FindRepositoryRoot() - { - var directory = new DirectoryInfo(AppContext.BaseDirectory); - while (directory is not null) - { - if (File.Exists(Path.Combine(directory.FullName, "Aquarium.Engine.sln"))) - { - return directory.FullName; - } - - directory = directory.Parent; - } - - throw new DirectoryNotFoundException("Could not find Aquarium.Engine.sln."); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/ZyphosSpatialDomainCatalogTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ZyphosSpatialDomainCatalogTests.cs deleted file mode 100644 index 6e6e2aa..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/ZyphosSpatialDomainCatalogTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Aquarium.Zyphos; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class ZyphosSpatialDomainCatalogTests -{ - [Fact] - public void CatalogCoversAquageoDomainStack() - { - var catalogKeys = ZyphosSpatialDomainCatalog.Domains.Select(domain => domain.Key.Value).ToHashSet(); - - foreach (var domain in ZyphosFractalTerrain.OwnershipTree.Domains) - { - Assert.Contains(domain.Key.Value, catalogKeys); - } - } - - [Fact] - public void CatalogParentsPointAtDeclaredDomains() - { - var catalogKeys = ZyphosSpatialDomainCatalog.Domains.Select(domain => domain.Key).ToHashSet(); - - foreach (var domain in ZyphosSpatialDomainCatalog.Domains) - { - if (domain.ParentKey is { } parentKey) - { - Assert.Contains(parentKey, catalogKeys); - } - } - } - - [Fact] - public void ZyphosAndUmbrosBothExposeSurfaceAndTileChildren() - { - Assert.Contains(ZyphosSpatialDomainCatalog.ChildrenOf(ZyphosSpatialDomainCatalog.Planet), domain => domain.Key == ZyphosSpatialDomainCatalog.PlanetLatLong); - Assert.Contains(ZyphosSpatialDomainCatalog.ChildrenOf(ZyphosSpatialDomainCatalog.Umbros), domain => domain.Key == ZyphosSpatialDomainCatalog.UmbrosLatLong); - Assert.Contains(ZyphosSpatialDomainCatalog.ChildrenOf(ZyphosSpatialDomainCatalog.EquatorialForest), domain => domain.Key == ZyphosSpatialDomainCatalog.CanopyTree); - Assert.Contains(ZyphosSpatialDomainCatalog.ChildrenOf(ZyphosSpatialDomainCatalog.CanopyTree), domain => domain.Key == ZyphosSpatialDomainCatalog.CanopyLeaf); - Assert.Contains(ZyphosSpatialDomainCatalog.ChildrenOf(ZyphosSpatialDomainCatalog.PebbleField), domain => domain.Key == ZyphosSpatialDomainCatalog.PebbleFieldTile); - Assert.Contains(ZyphosSpatialDomainCatalog.ChildrenOf(ZyphosSpatialDomainCatalog.UmbrosBoulderField), domain => domain.Key == ZyphosSpatialDomainCatalog.UmbrosPebbleField); - Assert.Contains(ZyphosSpatialDomainCatalog.ChildrenOf(ZyphosSpatialDomainCatalog.UmbrosPebbleField), domain => domain.Key == ZyphosSpatialDomainCatalog.UmbrosBoulderPebbleTile); - } -} diff --git a/tests/Aquarium.Engine.Fractal.Tests/ZyphosUmbrosSystemTests.cs b/tests/Aquarium.Engine.Fractal.Tests/ZyphosUmbrosSystemTests.cs deleted file mode 100644 index 40cf950..0000000 --- a/tests/Aquarium.Engine.Fractal.Tests/ZyphosUmbrosSystemTests.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Numerics; -using Aquarium.Zyphos; - -namespace Aquarium.Engine.Fractal.Tests; - -public sealed class ZyphosUmbrosSystemTests -{ - [Fact] - public void UmbrosMatchesWorkingBinaryBaselineScale() - { - Assert.Equal(0.9f, ZyphosUmbrosSystem.UmbrosRadiusRatio); - Assert.Equal(8.0f, ZyphosUmbrosSystem.SeparationInZyphosRadii); - Assert.InRange(ZyphosUmbrosSystem.UmbrosAngularDiameterDegrees, 12.8f, 13.0f); - } - - [Fact] - public void UmbrosDirectionIsFixedInPlanetLocalFrame() - { - var firstDirection = ZyphosUmbrosSystem.UmbrosDirection(0.0f); - var laterDirection = ZyphosUmbrosSystem.UmbrosDirection(100.0f); - - Assert.Equal(Vector3.UnitX, firstDirection); - Assert.Equal(Vector3.UnitX, laterDirection); - } - - [Fact] - public void UmbrosCenterUsesFixedSkyBinarySeparation() - { - var offset = ZyphosUmbrosSystem.UmbrosCenter(0.0f) - ZyphosUmbrosSystem.ZyphosCenter; - var laterOffset = ZyphosUmbrosSystem.UmbrosCenter(100.0f) - ZyphosUmbrosSystem.ZyphosCenter; - - Assert.Equal(ZyphosUmbrosSystem.CenterSeparation, offset.Length(), 4); - Assert.Equal(offset, laterOffset); - Assert.True(ZyphosUmbrosSystem.CenterSeparation > ZyphosUmbrosSystem.ZyphosSurfaceRadius * 7.9f); - } -} diff --git a/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj b/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj deleted file mode 100644 index 63d3d04..0000000 --- a/tests/Aquarium.Engine.Tests/Aquarium.Engine.Tests.csproj +++ /dev/null @@ -1,25 +0,0 @@ - - - - net10.0 - enable - enable - false - - - - - - - - - - - - - - - - - - diff --git a/tests/Aquarium.Engine.Tests/GpuSensorFrameContractTests.cs b/tests/Aquarium.Engine.Tests/GpuSensorFrameContractTests.cs deleted file mode 100644 index 734fa52..0000000 --- a/tests/Aquarium.Engine.Tests/GpuSensorFrameContractTests.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System.Numerics; -using Aquarium.Engine.Render; - -namespace Aquarium.Engine.Tests; - -public sealed class GpuSensorFrameContractTests -{ - [Fact] - public void SceneStateCarriesSharedGpuSensorFrameAsRendererInput() - { - var frame = new AquariumGpuSensorFrame - { - AccumulationWindowSeconds = 18.0f, - PresentationDelaySeconds = 0.35f, - Cameras = - [ - new AquariumGpuSensorCamera( - "kiyo-pro-left", - AquariumGpuSensorKind.RgbCamera, - Matrix4x4.Identity, - Matrix4x4.Identity, - new Vector4(840.0f, 840.0f, 960.0f, 540.0f), - Vector4.Zero, - Vector4.Zero, - 1920, - 1080, - 0, - 1, - 10_000_000_000) - ], - ExternalTextures = - [ - new AquariumExternalGpuTexture( - new TextureHandle("kiyo-pro-left-bgra"), - new IntPtr(1234), - 1920, - 1080, - AquariumGpuSensorPixelFormat.Bgra8Unorm, - 10_000_000_000, - SharedHandleName: "LocalCastBridge/KiyoProLeft/Bgra") - ], - }; - - var scene = new AquariumSceneState { GpuSensorFrame = frame }; - - Assert.True(scene.GpuSensorFrame.HasInput); - Assert.Equal("kiyo-pro-left", scene.GpuSensorFrame.Cameras[0].SensorId); - Assert.Equal(AquariumGpuSensorPixelFormat.Bgra8Unorm, scene.GpuSensorFrame.ExternalTextures[0].PixelFormat); - Assert.Equal("LocalCastBridge/KiyoProLeft/Bgra", scene.GpuSensorFrame.ExternalTextures[0].SharedHandleName); - Assert.Equal(18.0f, scene.GpuSensorFrame.AccumulationWindowSeconds, 6); - } - - [Fact] - public void SceneStateCarriesAcousticTimingOracleWithRoomConstraints() - { - var acoustic = new AquariumAcousticFieldFrame - { - TimingOracleNs = 99_000_000_123, - TimingConfidence = 0.98f, - TimingUncertaintyMicroseconds = 2.5f, - AccumulationWindowSeconds = 6.0f, - PresentationDelaySeconds = 2.0f, - Constraints = - [ - new AquariumAcousticConstraint( - "ultrasonic-wall-return:front", - AquariumAcousticConstraintKind.UltrasonicReflector, - new Vector3(0.0f, 1.2f, 1.1f), - Vector3.Zero, - 0.18f, - 0.87f, - 99_000_000_123) - ], - }; - - var scene = new AquariumSceneState { AcousticFieldFrame = acoustic }; - - Assert.True(scene.AcousticFieldFrame.HasInput); - Assert.Equal(99_000_000_123, scene.AcousticFieldFrame.TimingOracleNs); - Assert.Equal(2.5f, scene.AcousticFieldFrame.TimingUncertaintyMicroseconds, 6); - Assert.Equal(AquariumAcousticConstraintKind.UltrasonicReflector, scene.AcousticFieldFrame.Constraints[0].Kind); - } - - [Fact] - public void SceneStateCarriesClapCalibrationEventAlignedToAcousticOracle() - { - var events = new AquariumCalibrationEventFrame - { - ClapEvents = - [ - new AquariumClapCalibrationEvent( - "clap:host:0001", - new Vector3(0.12f, 0.4f, 1.35f), - AcousticOracleNs: 123_456_789_000, - VisualObservedNs: 123_456_805_000, - TimingUncertaintyMicroseconds: 1.8f, - VisualConfidence: 0.82f, - AcousticConfidence: 0.97f) - ], - }; - - var scene = new AquariumSceneState { CalibrationEventFrame = events }; - - Assert.True(scene.CalibrationEventFrame.HasInput); - Assert.Equal(123_456_789_000, scene.CalibrationEventFrame.ClapEvents[0].AcousticOracleNs); - Assert.True(scene.CalibrationEventFrame.ClapEvents[0].AcousticConfidence > scene.CalibrationEventFrame.ClapEvents[0].VisualConfidence); - } -} diff --git a/tests/Aquarium.Engine.Tests/SynthPlaybackTests.cs b/tests/Aquarium.Engine.Tests/SynthPlaybackTests.cs deleted file mode 100644 index d0600ef..0000000 --- a/tests/Aquarium.Engine.Tests/SynthPlaybackTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Aquarium.Engine.Audio; -using AquaSynth.Faust; - -namespace Aquarium.Engine.Tests; - -public sealed class SynthPlaybackTests -{ - [Fact] - public void AquaSynthPatchCompilerCanRenderAudiblePatchForEnginePlayback() - { - const string script = """ - voice - wave=sine - freq=440 - gain=0.2 - attack=0.001 - sustain=0.06 - decay=0.12 - """; - - using var compiler = new AquaSynthPatchCompiler(); - if (!compiler.TryCompileScript(new AquaSynthCompileIdentity("engine_synth_smoke", "engine_synth_smoke", script), out var patch, out var error)) - { - if (error?.Contains("Faust toolchain not found", StringComparison.OrdinalIgnoreCase) == true || - error?.Contains("Faust DLL not found", StringComparison.OrdinalIgnoreCase) == true) - { - return; - } - - Assert.Fail($"AquaSynth patch compiler failed to render a tiny patch: {error}"); - } - - using (patch) - { - var samples = patch!.Render(1.0f); - Assert.True(samples.Length > 2048, $"Rendered too few samples: {samples.Length}."); - Assert.Contains(samples, sample => MathF.Abs(sample) > 0.001f); - Assert.InRange(samples.Max(sample => MathF.Abs(sample)), 0.001f, 1.0f); - } - } -} diff --git a/tests/Aquarium.LocalCast.Tests/Aquarium.LocalCast.Tests.csproj b/tests/Aquarium.LocalCast.Tests/Aquarium.LocalCast.Tests.csproj deleted file mode 100644 index e2be1d9..0000000 --- a/tests/Aquarium.LocalCast.Tests/Aquarium.LocalCast.Tests.csproj +++ /dev/null @@ -1,25 +0,0 @@ - - - - net10.0 - enable - enable - false - - - - - - - - - - - - - - - - - - diff --git a/tests/Aquarium.LocalCast.Tests/LocalCastNativeReservoirTests.cs b/tests/Aquarium.LocalCast.Tests/LocalCastNativeReservoirTests.cs deleted file mode 100644 index d82113d..0000000 --- a/tests/Aquarium.LocalCast.Tests/LocalCastNativeReservoirTests.cs +++ /dev/null @@ -1,123 +0,0 @@ -using System.Runtime.InteropServices; -using Aquarium.LocalCast; - -namespace Aquarium.LocalCast.Tests; - -public sealed class LocalCastNativeReservoirTests -{ - [Fact] - public void SampleKindIdsMatchLocalcastReservoirHeader() - { - Assert.Equal(0u, (uint)LocalCastNativeSampleKind.CameraFrame); - Assert.Equal(5u, (uint)LocalCastNativeSampleKind.AudioBlock); - Assert.Equal(8u, (uint)LocalCastNativeSampleKind.RenderPacket); - } - - [Fact] - public void SampleHandleLayoutMatchesNativeAbi() - { - Assert.Equal(48, Marshal.SizeOf()); - - var handle = new LocalCastNativeSampleHandle - { - SensorIdHash = 10, - TimestampNs = 20, - ArrivalNs = 21, - Sequence = 7, - PayloadHandle = 99, - Flags = LocalCastNativeSampleFlags.None, - }; - - Assert.True(handle.IsLive); - handle.Flags = LocalCastNativeSampleFlags.Diagnostic; - Assert.False(handle.IsLive); - } - - [Fact] - public void AudioBlockDescriptorLayoutMatchesNativeAbi() - { - Assert.Equal(40, Marshal.SizeOf()); - Assert.Equal(1u, (uint)LocalCastNativeAudioSampleFormat.Float32Interleaved); - - var descriptor = new LocalCastNativeAudioBlockDescriptor - { - DataHandle = 99, - FrameCount = 1024, - ChannelCount = 6, - SampleRateHz = 48_000, - SampleFormat = LocalCastNativeAudioSampleFormat.Float32Interleaved, - StartSample = 2_048, - ChannelLayoutHash = 77, - }; - - Assert.Equal(99u, descriptor.DataHandle); - Assert.Equal(1024u, descriptor.FrameCount); - Assert.Equal(6u, descriptor.ChannelCount); - Assert.Equal(48_000u, descriptor.SampleRateHz); - Assert.Equal(2_048u, descriptor.StartSample); - Assert.Equal(77u, descriptor.ChannelLayoutHash); - } - - [Fact] - public void RenderPacketDescriptorLayoutMatchesNativeAbi() - { - Assert.Equal(64, Marshal.SizeOf()); - - var descriptor = new LocalCastNativeRenderPacketDescriptor - { - PointBufferHandle = 99, - PointCount = 4096, - PointStrideBytes = 64, - TargetWidth = 1920, - TargetHeight = 1080, - SourceTimeMinNs = 1_000, - SourceTimeMaxNs = 2_000, - PresentTimeNs = 2_350, - AudioAlignmentTimeNs = 2_300, - MetadataHandle = 77, - }; - - Assert.Equal(99u, descriptor.PointBufferHandle); - Assert.Equal(4096u, descriptor.PointCount); - Assert.Equal(64u, descriptor.PointStrideBytes); - Assert.Equal(1920u, descriptor.TargetWidth); - Assert.Equal(1080u, descriptor.TargetHeight); - Assert.Equal(1_000u, descriptor.SourceTimeMinNs); - Assert.Equal(2_000u, descriptor.SourceTimeMaxNs); - Assert.Equal(2_350u, descriptor.PresentTimeNs); - Assert.Equal(2_300u, descriptor.AudioAlignmentTimeNs); - Assert.Equal(77u, descriptor.MetadataHandle); - } - - [Fact] - public void RenderPointLayoutMatchesNativeAbi() - { - Assert.Equal(56, Marshal.SizeOf()); - - var point = new LocalCastNativeRenderPoint - { - StableKeyHash = 0xCAFE, - SourceTimestampNs = 1_900, - X = 0.1f, - Y = 0.2f, - Z = 1.2f, - RadiusMeters = 0.03f, - Red = 0.7f, - Green = 0.6f, - Blue = 0.5f, - Alpha = 0.9f, - Confidence = 0.8f, - }; - - Assert.Equal(0xCAFEu, point.StableKeyHash); - Assert.Equal(1_900u, point.SourceTimestampNs); - Assert.Equal(0.03f, point.RadiusMeters); - } - - [Fact] - public void RuntimeStatusLayoutUsesNativeSizeCounts() - { - var expected = 16 + (10 * UIntPtr.Size); - Assert.Equal(expected, Marshal.SizeOf()); - } -} diff --git a/tests/Aquarium.LocalCast.Tests/LocalCastNativeVisualFrameSourceTests.cs b/tests/Aquarium.LocalCast.Tests/LocalCastNativeVisualFrameSourceTests.cs deleted file mode 100644 index 43b3c03..0000000 --- a/tests/Aquarium.LocalCast.Tests/LocalCastNativeVisualFrameSourceTests.cs +++ /dev/null @@ -1,390 +0,0 @@ -using System.Numerics; -using System.Runtime.InteropServices; -using Aquarium.LocalCast; - -namespace Aquarium.LocalCast.Tests; - -public sealed class LocalCastNativeVisualFrameSourceTests -{ - [Fact] - public void ReadsLatestRenderPacketFromNativeRuntimeThroughInjectedDecoder() - { - var sample = new LocalCastNativeSampleHandle - { - SensorIdHash = 11, - TimestampNs = 1_000, - ArrivalNs = 1_010, - Sequence = 7, - PayloadHandle = 99, - Flags = LocalCastNativeSampleFlags.None, - }; - var runtime = new FakeNativeRuntime(sample, renderPacketCount: 2); - var source = new LocalCastNativeVisualFrameSource( - runtime, - (LocalCastNativeSampleHandle handle, out LocalCastVisualFrame frame) => - { - frame = FrameFromPayload(handle.PayloadHandle, handle.TimestampNs); - return true; - }); - - Assert.True(source.TryReadLatest(out var frame)); - Assert.Equal(99, frame.FrameId); - Assert.Equal(1_000, frame.SourceTimeMaxNs); - Assert.Equal(1, runtime.ViewReadCount); - } - - [Fact] - public void RejectsMissingOrNonLiveRenderPacket() - { - var diagnostic = new LocalCastNativeSampleHandle - { - SensorIdHash = 11, - TimestampNs = 1_000, - ArrivalNs = 1_010, - Sequence = 7, - PayloadHandle = 99, - Flags = LocalCastNativeSampleFlags.Diagnostic, - }; - var source = new LocalCastNativeVisualFrameSource( - new FakeNativeRuntime(diagnostic, renderPacketCount: 1), - (LocalCastNativeSampleHandle _, out LocalCastVisualFrame frame) => - { - frame = FrameFromPayload(1, 1); - return true; - }); - - Assert.False(source.TryReadLatest(out _)); - - var empty = new LocalCastNativeVisualFrameSource( - new FakeNativeRuntime(diagnostic, renderPacketCount: 0), - (LocalCastNativeSampleHandle _, out LocalCastVisualFrame frame) => - { - frame = FrameFromPayload(1, 1); - return true; - }); - Assert.False(empty.TryReadLatest(out _)); - } - - [Fact] - public void DescriptorDecoderReadsTimingAndDelegatesPointBuffer() - { - var descriptor = new LocalCastNativeRenderPacketDescriptor - { - PointBufferHandle = 500, - PointCount = 1, - PointStrideBytes = 48, - TargetWidth = 1280, - TargetHeight = 720, - SourceTimeMinNs = 900, - SourceTimeMaxNs = 1_000, - PresentTimeNs = 1_050, - AudioAlignmentTimeNs = 1_025, - MetadataHandle = 77, - }; - var pointer = Marshal.AllocHGlobal(Marshal.SizeOf()); - try - { - Marshal.StructureToPtr(descriptor, pointer, false); - var sample = new LocalCastNativeSampleHandle - { - SensorIdHash = 11, - TimestampNs = 1_000, - ArrivalNs = 1_010, - Sequence = 42, - PayloadHandle = (ulong)pointer, - Flags = LocalCastNativeSampleFlags.None, - }; - var decoder = new LocalCastNativeRenderDescriptorDecoder( - (in LocalCastNativeRenderPacketDescriptor read, LocalCastNativeSampleHandle _, out IReadOnlyList points) => - { - Assert.Equal(500u, read.PointBufferHandle); - Assert.Equal(1u, read.PointCount); - points = - [ - new LocalCastVisualPoint( - "native:decoded", - new Vector3(0.2f, 0.1f, 1.0f), - 0.04f, - new Vector4(0.5f, 0.4f, 0.3f, 0.9f), - 0.7f, - 1_000), - ]; - return true; - }); - - Assert.True(decoder.TryDecode(sample, out var frame)); - Assert.Equal(42, frame.FrameId); - Assert.Equal(1_010, frame.CreatedMonotonicNs); - Assert.Equal(900, frame.SourceTimeMinNs); - Assert.Equal(1_000, frame.SourceTimeMaxNs); - Assert.Equal(1_050, frame.PresentTimeNs); - Assert.Equal(1_025, frame.AudioAlignmentTimeNs); - Assert.Equal(1280, frame.TargetWidth); - Assert.Equal(720, frame.TargetHeight); - Assert.Single(frame.Points); - } - finally - { - Marshal.FreeHGlobal(pointer); - } - } - - [Fact] - public void DescriptorDecoderRejectsNullPayloadAndPointDecoderFailure() - { - var decoder = new LocalCastNativeRenderDescriptorDecoder( - (in LocalCastNativeRenderPacketDescriptor _, LocalCastNativeSampleHandle _, out IReadOnlyList points) => - { - points = []; - return false; - }); - - Assert.False(decoder.TryDecode(new LocalCastNativeSampleHandle { Flags = LocalCastNativeSampleFlags.None }, out _)); - - var descriptor = new LocalCastNativeRenderPacketDescriptor(); - var pointer = Marshal.AllocHGlobal(Marshal.SizeOf()); - try - { - Marshal.StructureToPtr(descriptor, pointer, false); - Assert.False( - decoder.TryDecode( - new LocalCastNativeSampleHandle - { - PayloadHandle = (ulong)pointer, - Flags = LocalCastNativeSampleFlags.None, - }, - out _)); - } - finally - { - Marshal.FreeHGlobal(pointer); - } - } - - [Fact] - public void NativePointBufferDecoderReadsStridedPoints() - { - var points = new[] - { - new LocalCastNativeRenderPoint - { - StableKeyHash = 0xCAFE, - SourceTimestampNs = 1_900, - X = 0.1f, - Y = 0.2f, - Z = 1.2f, - RadiusMeters = 0.03f, - Red = 0.7f, - Green = 0.6f, - Blue = 0.5f, - Alpha = 0.9f, - Confidence = 0.8f, - }, - new LocalCastNativeRenderPoint - { - StableKeyHash = 0xBEEF, - SourceTimestampNs = 1_950, - X = -0.1f, - Y = 0.4f, - Z = 1.4f, - RadiusMeters = 0.04f, - Red = 0.2f, - Green = 0.3f, - Blue = 0.9f, - Alpha = 0.6f, - Confidence = 0.5f, - }, - }; - var pointSize = Marshal.SizeOf(); - var pointer = Marshal.AllocHGlobal(pointSize * points.Length); - try - { - for (var index = 0; index < points.Length; index++) - { - Marshal.StructureToPtr(points[index], IntPtr.Add(pointer, index * pointSize), false); - } - - var descriptor = new LocalCastNativeRenderPacketDescriptor - { - PointBufferHandle = (ulong)pointer, - PointCount = (uint)points.Length, - PointStrideBytes = (uint)pointSize, - }; - - Assert.True(LocalCastNativeRenderDescriptorDecoder.DecodeNativePointBuffer(in descriptor, default, out var decoded)); - Assert.Equal(2, decoded.Count); - Assert.Equal("native:000000000000cafe", decoded[0].StableKey); - Assert.Equal(new Vector3(0.1f, 0.2f, 1.2f), decoded[0].Position); - Assert.Equal(new Vector4(0.7f, 0.6f, 0.5f, 0.9f), decoded[0].ColorOpacity); - Assert.Equal(1_950, decoded[1].SourceTimestampNs); - } - finally - { - Marshal.FreeHGlobal(pointer); - } - } - - [Fact] - public void NativePointBufferDecoderRejectsMissingBufferAndShortStride() - { - var missing = new LocalCastNativeRenderPacketDescriptor - { - PointCount = 1, - PointStrideBytes = (uint)Marshal.SizeOf(), - }; - Assert.False(LocalCastNativeRenderDescriptorDecoder.DecodeNativePointBuffer(in missing, default, out _)); - - var empty = new LocalCastNativeRenderPacketDescriptor(); - Assert.True(LocalCastNativeRenderDescriptorDecoder.DecodeNativePointBuffer(in empty, default, out var points)); - Assert.Empty(points); - - var shortStride = new LocalCastNativeRenderPacketDescriptor - { - PointBufferHandle = 1, - PointCount = 1, - PointStrideBytes = 8, - }; - Assert.False(LocalCastNativeRenderDescriptorDecoder.DecodeNativePointBuffer(in shortStride, default, out _)); - } - - [Fact] - public void DefaultNativeSourceConstructorExposesDirectPointBuffer() - { - var nativePoint = new LocalCastNativeRenderPoint - { - StableKeyHash = 0xCAFE, - SourceTimestampNs = 1_900, - X = 0.1f, - Y = 0.2f, - Z = 1.2f, - RadiusMeters = 0.03f, - Red = 0.7f, - Green = 0.6f, - Blue = 0.5f, - Alpha = 0.9f, - Confidence = 0.8f, - }; - var pointSize = Marshal.SizeOf(); - var pointPointer = Marshal.AllocHGlobal(pointSize); - var descriptorPointer = Marshal.AllocHGlobal(Marshal.SizeOf()); - try - { - Marshal.StructureToPtr(nativePoint, pointPointer, false); - Marshal.StructureToPtr( - new LocalCastNativeRenderPacketDescriptor - { - PointBufferHandle = (ulong)pointPointer, - PointCount = 1, - PointStrideBytes = (uint)pointSize, - TargetWidth = 1920, - TargetHeight = 1080, - SourceTimeMinNs = 1_000, - SourceTimeMaxNs = 1_900, - PresentTimeNs = 2_000, - AudioAlignmentTimeNs = 1_950, - }, - descriptorPointer, - false); - var sample = new LocalCastNativeSampleHandle - { - SensorIdHash = 11, - TimestampNs = 1_900, - ArrivalNs = 1_910, - Sequence = 21, - PayloadHandle = (ulong)descriptorPointer, - Flags = LocalCastNativeSampleFlags.None, - }; - var source = new LocalCastNativeVisualFrameSource(new FakeNativeRuntime(sample, renderPacketCount: 1)); - - Assert.True(source.TryReadLatest(out var frame)); - Assert.Equal(21, frame.FrameId); - Assert.Equal(1920, frame.TargetWidth); - Assert.Empty(frame.Points); - Assert.True(frame.NativeGpuFusionPointBuffer.HasInput); - Assert.Equal(pointPointer, frame.NativeGpuFusionPointBuffer.Buffer); - Assert.Equal(1, frame.NativeGpuFusionPointBuffer.Count); - Assert.Equal(pointSize, frame.NativeGpuFusionPointBuffer.StrideBytes); - Assert.Equal(1, frame.PointCount); - } - finally - { - Marshal.FreeHGlobal(pointPointer); - Marshal.FreeHGlobal(descriptorPointer); - } - } - - private static LocalCastVisualFrame FrameFromPayload(ulong payloadHandle, ulong timestampNs) - { - return new LocalCastVisualFrame - { - SchemaVersion = LocalCastVisualStateReader.RenderFrameSchemaId, - FrameId = (long)payloadHandle, - CreatedMonotonicNs = (long)timestampNs, - SourceTimeMinNs = (long)timestampNs, - SourceTimeMaxNs = (long)timestampNs, - PresentTimeNs = (long)timestampNs, - AudioAlignmentTimeNs = (long)timestampNs, - SpoutSenderName = "LocalCastBridge Point Cloud", - TargetWidth = 1920, - TargetHeight = 1080, - Points = - [ - new LocalCastVisualPoint( - "native:point", - new Vector3(0.1f, 0.2f, 1.2f), - 0.03f, - new Vector4(0.7f, 0.6f, 0.5f, 0.9f), - 0.8f, - (long)timestampNs), - ], - }; - } - - private sealed class FakeNativeRuntime : ILocalCastNativeRuntime - { - private readonly LocalCastNativeSampleHandle sample; - private readonly UIntPtr renderPacketCount; - - public FakeNativeRuntime(LocalCastNativeSampleHandle sample, int renderPacketCount) - { - this.sample = sample; - this.renderPacketCount = (UIntPtr)renderPacketCount; - } - - public int ViewReadCount { get; private set; } - - public bool TryGetStatus(out LocalCastNativeRuntimeStatus status) - { - status = new LocalCastNativeRuntimeStatus - { - TotalSampleCount = renderPacketCount, - RenderPacketCount = renderPacketCount, - }; - return true; - } - - public bool TryReadSample(nuint index, out LocalCastNativeSampleKind kind, out LocalCastNativeSampleHandle sample) - { - kind = LocalCastNativeSampleKind.RenderPacket; - sample = this.sample; - return true; - } - - public bool TryReadViewSample(LocalCastNativeSampleKind kind, nuint index, out LocalCastNativeSampleHandle sample) - { - ViewReadCount++; - sample = this.sample; - return kind == LocalCastNativeSampleKind.RenderPacket && index + 1 == renderPacketCount; - } - - public bool TryReadLatestForSensor(LocalCastNativeSampleKind kind, ulong sensorIdHash, out LocalCastNativeSampleHandle sample) - { - sample = this.sample; - return true; - } - - public void Dispose() - { - } - } -} diff --git a/tests/Aquarium.LocalCast.Tests/LocalCastRuntimeSourceTests.cs b/tests/Aquarium.LocalCast.Tests/LocalCastRuntimeSourceTests.cs deleted file mode 100644 index 751b32e..0000000 --- a/tests/Aquarium.LocalCast.Tests/LocalCastRuntimeSourceTests.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System.Numerics; -using Aquarium.Engine; -using Aquarium.Engine.Render; -using Aquarium.Engine.Input; -using Aquarium.LocalCast; - -namespace Aquarium.LocalCast.Tests; - -public sealed class LocalCastRuntimeSourceTests -{ - [Fact] - public void RuntimeConsumesInjectedFrameSource() - { - var source = new FakeFrameSource(); - var runtime = new LocalCastRuntime(new AquariumRuntimeOptions(true, null), source); - - runtime.Update(0.016f, new InputState()); - var frame = runtime.Frame; - - Assert.Equal(1, source.ReadCount); - Assert.True(frame.Scene.GpuFusionField.Seeds.Count > 0); - } - - [Fact] - public void RuntimePublishesNativePointBufferWithoutManagedSeedMapping() - { - var source = new FakeFrameSource( - new AquariumGpuFusionPointBuffer((IntPtr)0x1000, 3, 56)); - var runtime = new LocalCastRuntime(new AquariumRuntimeOptions(true, null), source); - - runtime.Update(0.016f, new InputState()); - var frame = runtime.Frame; - - Assert.Empty(frame.Scene.GpuFusionField.Seeds); - Assert.True(frame.Scene.GpuFusionField.PointBuffer.HasInput); - Assert.Equal(3, frame.Scene.GpuFusionField.PointBuffer.Count); - Assert.Equal(56, frame.Scene.GpuFusionField.PointBuffer.StrideBytes); - Assert.Empty(frame.Scene.TemporalGaussianField.Gaussians); - } - - private sealed class FakeFrameSource : ILocalCastVisualFrameSource - { - private readonly AquariumGpuFusionPointBuffer pointBuffer; - - public FakeFrameSource(AquariumGpuFusionPointBuffer pointBuffer = default) - { - this.pointBuffer = pointBuffer; - } - - public int ReadCount { get; private set; } - - public string Description => "fake-native-source"; - - public bool TryReadLatest(out LocalCastVisualFrame frame) - { - ReadCount++; - frame = new LocalCastVisualFrame - { - SchemaVersion = LocalCastVisualStateReader.RenderFrameSchemaId, - FrameId = 10, - CreatedMonotonicNs = 100, - SourceTimeMinNs = 100, - SourceTimeMaxNs = 120, - PresentTimeNs = 160, - AudioAlignmentTimeNs = 160, - SpoutSenderName = "LocalCastBridge Point Cloud", - TargetWidth = 1920, - TargetHeight = 1080, - Points = - [ - new LocalCastVisualPoint( - "fake:point", - new Vector3(0.1f, 0.2f, 1.2f), - 0.03f, - new Vector4(0.7f, 0.6f, 0.5f, 0.9f), - 0.8f, - 120), - ], - NativeGpuFusionPointBuffer = pointBuffer, - }; - return true; - } - - public bool TryReadLatestClapEvents(out LocalCastClapCalibrationFrame frame) - { - frame = new LocalCastClapCalibrationFrame - { - SchemaVersion = LocalCastVisualStateReader.ClapEventsSchemaId, - FrameId = -1, - CreatedMonotonicNs = 0, - Events = [], - }; - return false; - } - } -} diff --git a/tests/Aquarium.LocalCast.Tests/LocalCastTemporalGaussianMapperTests.cs b/tests/Aquarium.LocalCast.Tests/LocalCastTemporalGaussianMapperTests.cs deleted file mode 100644 index baedc17..0000000 --- a/tests/Aquarium.LocalCast.Tests/LocalCastTemporalGaussianMapperTests.cs +++ /dev/null @@ -1,173 +0,0 @@ -using System.Numerics; -using Aquarium.LocalCast; - -namespace Aquarium.LocalCast.Tests; - -public sealed class LocalCastTemporalGaussianMapperTests -{ - [Fact] - public void MapsRenderPointsToTemporalGaussianObservations() - { - var frame = new LocalCastVisualFrame - { - SchemaVersion = LocalCastVisualStateReader.RenderFrameSchemaId, - FrameId = 42, - CreatedMonotonicNs = 1_000_000_000, - SourceTimeMinNs = 1_000_000_000, - SourceTimeMaxNs = 1_050_000_000, - PresentTimeNs = 1_350_000_000, - AudioAlignmentTimeNs = 1_350_000_000, - SpoutSenderName = "LocalCastBridge Point Cloud", - TargetWidth = 1920, - TargetHeight = 1080, - Points = - [ - new LocalCastVisualPoint( - "host-rgb:0:0", - new Vector3(0.25f, 0.1f, 1.2f), - 0.02f, - new Vector4(0.8f, 0.4f, 0.2f, 0.9f), - 0.75f, - 1_040_000_000) - ], - }; - - var mapper = new LocalCastTemporalGaussianMapper(); - var observations = mapper.Map(frame); - - Assert.Single(observations); - var observation = observations[0]; - Assert.Equal("host-rgb:0:0", observation.StableKey); - Assert.True(observation.Center != frame.Points[0].Position); - Assert.Equal(0.043f, observation.Radii.X, 3); - Assert.InRange(observation.ColorOpacity.W, 0.0f, 0.98f); - Assert.True(observation.ColorOpacity.X > frame.Points[0].ColorOpacity.X); - Assert.Equal(0.75f, observation.Confidence, 6); - Assert.True(observation.ShapePower > 1.0f); - } - - [Fact] - public void DoesNotDownsampleDenseCameraAndLeapClaimsInClientAdapter() - { - var points = new List(); - for (var index = 0; index < 5000; index++) - { - points.Add(new LocalCastVisualPoint( - index == 4500 ? "leap-motion:green:0:0" : $"room-rgb:{index}", - new Vector3(index * 0.001f, 0.0f, 1.0f), - 0.02f, - Vector4.One, - 0.8f, - 1_000_000_000 + index)); - } - - var mapper = new LocalCastTemporalGaussianMapper(); - var observations = mapper.Map(new LocalCastVisualFrame - { - SchemaVersion = LocalCastVisualStateReader.RenderFrameSchemaId, - FrameId = 1, - CreatedMonotonicNs = 1_000_000_000, - SourceTimeMinNs = 1_000_000_000, - SourceTimeMaxNs = 1_000_010_000, - PresentTimeNs = 1_350_000_000, - AudioAlignmentTimeNs = 1_350_000_000, - SpoutSenderName = "LocalCastBridge Point Cloud", - TargetWidth = 1920, - TargetHeight = 1080, - Points = points, - }); - - Assert.Equal(5000, observations.Count); - Assert.Contains(observations, observation => observation.StableKey == "leap-motion:green:0:0"); - Assert.Contains(observations, observation => observation.StableKey.StartsWith("room-rgb:", StringComparison.Ordinal)); - } - - [Fact] - public void MapsVisualPointsToGpuFusionSeedsWithoutClientDownsampling() - { - var points = new List(); - for (var index = 0; index < 8192; index++) - { - points.Add(new LocalCastVisualPoint( - index % 2 == 0 ? $"dense-rgb:{index}" : $"leap-motion:green:{index}", - new Vector3(index * 0.0001f, 0.0f, 1.0f), - 0.006f, - new Vector4(0.4f, 0.7f, 1.0f, 0.85f), - 0.9f, - 1_000_000_000 + index)); - } - - var field = new LocalCastGpuFusionMapper().Map(new LocalCastVisualFrame - { - SchemaVersion = LocalCastVisualStateReader.RenderFrameSchemaId, - FrameId = 2, - CreatedMonotonicNs = 1_000_000_000, - SourceTimeMinNs = 1_000_000_000, - SourceTimeMaxNs = 1_000_010_000, - PresentTimeNs = 1_350_000_000, - AudioAlignmentTimeNs = 1_350_000_000, - SpoutSenderName = "LocalCastBridge Point Cloud", - TargetWidth = 1920, - TargetHeight = 1080, - Points = points, - }); - - Assert.Equal(8192, field.Seeds.Count); - Assert.Contains(field.Seeds, seed => seed.StableKey.StartsWith("dense-rgb:", StringComparison.Ordinal)); - Assert.Contains(field.Seeds, seed => seed.ShapePower > 2.0f); - } - - [Fact] - public void GpuFusionAccumulatorRetainsStableSamplesAcrossHistoryWindow() - { - var accumulator = new LocalCastGpuFusionAccumulator(historySeconds: 10.0f, smoothing: 1.0f, maxSeedCount: 16); - accumulator.Observe(FrameWithPoint(1, "room-rgb:old", new Vector3(-0.2f, 0.0f, 1.0f), 1_000_000_000)); - accumulator.Observe(FrameWithPoint(2, "room-rgb:new", new Vector3(0.2f, 0.0f, 1.0f), 5_000_000_000)); - - var field = accumulator.BuildField(6.0f); - - Assert.Equal(2, field.Seeds.Count); - Assert.Contains(field.Seeds, seed => seed.StableKey == "room-rgb:old"); - Assert.Contains(field.Seeds, seed => seed.StableKey == "room-rgb:new"); - } - - [Fact] - public void GpuFusionAccumulatorExpiresSamplesOutsideHistoryWindow() - { - var accumulator = new LocalCastGpuFusionAccumulator(historySeconds: 2.0f, smoothing: 1.0f, maxSeedCount: 16); - accumulator.Observe(FrameWithPoint(1, "room-rgb:old", new Vector3(-0.2f, 0.0f, 1.0f), 1_000_000_000)); - accumulator.Observe(FrameWithPoint(2, "room-rgb:new", new Vector3(0.2f, 0.0f, 1.0f), 4_000_000_000)); - - var field = accumulator.BuildField(4.2f); - - Assert.Single(field.Seeds); - Assert.Equal("room-rgb:new", field.Seeds[0].StableKey); - } - - private static LocalCastVisualFrame FrameWithPoint(long frameId, string key, Vector3 position, long sourceTimeNs) - { - return new LocalCastVisualFrame - { - SchemaVersion = LocalCastVisualStateReader.RenderFrameSchemaId, - FrameId = frameId, - CreatedMonotonicNs = sourceTimeNs, - SourceTimeMinNs = sourceTimeNs, - SourceTimeMaxNs = sourceTimeNs, - PresentTimeNs = sourceTimeNs + 350_000_000, - AudioAlignmentTimeNs = sourceTimeNs + 350_000_000, - SpoutSenderName = "LocalCastBridge Point Cloud", - TargetWidth = 1920, - TargetHeight = 1080, - Points = - [ - new LocalCastVisualPoint( - key, - position, - 0.012f, - new Vector4(0.5f, 0.7f, 0.9f, 0.85f), - 0.9f, - sourceTimeNs) - ], - }; - } -} diff --git a/tests/Aquarium.LocalCast.Tests/LocalCastVisualStateReaderTests.cs b/tests/Aquarium.LocalCast.Tests/LocalCastVisualStateReaderTests.cs deleted file mode 100644 index a742290..0000000 --- a/tests/Aquarium.LocalCast.Tests/LocalCastVisualStateReaderTests.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System.Buffers; -using MessagePack; -using Aquarium.LocalCast; - -namespace Aquarium.LocalCast.Tests; - -public sealed class LocalCastVisualStateReaderTests -{ - [Fact] - public void ParsesPythonCultCacheRenderFrameStore() - { - var store = WriteStore(); - - Assert.True(LocalCastVisualStateReader.TryParseStore(store, out var frame)); - Assert.Equal(7, frame.FrameId); - Assert.Equal("LocalCastBridge Point Cloud", frame.SpoutSenderName); - var point = Assert.Single(frame.Points); - Assert.Equal("rgb:1", point.StableKey); - Assert.Equal(0.03f, point.RadiusMeters, 6); - } - - [Fact] - public void ParsesPythonCultCacheClapEventsStore() - { - var store = WriteStore(includeClapEvents: true); - - Assert.True(LocalCastVisualStateReader.TryParseClapEventsStore(store, out var frame)); - Assert.Equal(12, frame.FrameId); - var clap = Assert.Single(frame.Events); - Assert.Equal("clap:host:0001", clap.StableKey); - Assert.Equal(123_456_789_000L, clap.AcousticOracleNs); - Assert.Equal(1.8f, clap.TimingUncertaintyMicroseconds, 6); - Assert.True(clap.AcousticConfidence > clap.VisualConfidence); - } - - private static byte[] WriteStore(bool includeClapEvents = false) - { - var payload = WriteRenderFramePayload(); - var recordCount = includeClapEvents ? 2 : 1; - var buffer = new ArrayBufferWriter(); - var writer = new MessagePackWriter(buffer); - writer.WriteArrayHeader(recordCount); - writer.WriteMapHeader(4); - writer.Write("key"); - writer.Write(LocalCastVisualStateReader.LiveRenderFrameKey); - writer.Write("type"); - writer.Write(LocalCastVisualStateReader.RenderFrameType); - writer.Write("storedAt"); - writer.Write("2026-05-18T18:35:15Z"); - writer.Write("payload"); - writer.Write(payload); - if (includeClapEvents) - { - writer.WriteMapHeader(4); - writer.Write("key"); - writer.Write(LocalCastVisualStateReader.LiveClapEventsKey); - writer.Write("type"); - writer.Write(LocalCastVisualStateReader.ClapEventsType); - writer.Write("storedAt"); - writer.Write("2026-05-18T18:35:15Z"); - writer.Write("payload"); - writer.Write(WriteClapEventsPayload()); - } - writer.Flush(); - return buffer.WrittenMemory.ToArray(); - } - - private static byte[] WriteRenderFramePayload() - { - var buffer = new ArrayBufferWriter(); - var writer = new MessagePackWriter(buffer); - writer.WriteArrayHeader(11); - writer.Write(LocalCastVisualStateReader.RenderFrameSchemaId); - writer.Write(7L); - writer.Write(1_000_000L); - writer.Write(1_000_000L); - writer.Write(1_010_000L); - writer.Write(1_260_000L); - writer.Write(1_260_000L); - writer.Write("LocalCastBridge Point Cloud"); - writer.Write(1920); - writer.Write(1080); - writer.WriteArrayHeader(1); - writer.WriteArrayHeader(6); - writer.Write("rgb:1"); - writer.WriteArrayHeader(3); - writer.Write(0.1f); - writer.Write(0.2f); - writer.Write(1.2f); - writer.Write(0.03f); - writer.WriteArrayHeader(4); - writer.Write(0.7f); - writer.Write(0.6f); - writer.Write(0.5f); - writer.Write(0.9f); - writer.Write(0.8f); - writer.Write(1_010_000L); - writer.Flush(); - return buffer.WrittenMemory.ToArray(); - } - - private static byte[] WriteClapEventsPayload() - { - var buffer = new ArrayBufferWriter(); - var writer = new MessagePackWriter(buffer); - writer.WriteArrayHeader(4); - writer.Write(LocalCastVisualStateReader.ClapEventsSchemaId); - writer.Write(12L); - writer.Write(1_000_000L); - writer.WriteArrayHeader(1); - writer.WriteArrayHeader(8); - writer.Write("clap:host:0001"); - writer.WriteArrayHeader(3); - writer.Write(0.12f); - writer.Write(0.4f); - writer.Write(1.35f); - writer.Write(123_456_789_000L); - writer.Write(123_456_805_000L); - writer.Write(1.8f); - writer.Write(0.82f); - writer.Write(0.97f); - writer.WriteArrayHeader(1); - writer.WriteMapHeader(4); - writer.Write("sensorId"); - writer.Write("kiyo-pro"); - writer.Write("timestampNs"); - writer.Write(123_456_805_000L); - writer.Write("uv"); - writer.WriteArrayHeader(2); - writer.Write(320.0f); - writer.Write(240.0f); - writer.Write("score"); - writer.Write(0.9f); - writer.Flush(); - return buffer.WrittenMemory.ToArray(); - } -} diff --git a/tools/Aquarium.Fractal.Receipt/Aquarium.Fractal.Receipt.csproj b/tools/Aquarium.Fractal.Receipt/Aquarium.Fractal.Receipt.csproj deleted file mode 100644 index e00e6ce..0000000 --- a/tools/Aquarium.Fractal.Receipt/Aquarium.Fractal.Receipt.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - Exe - net10.0 - enable - enable - true - - - - - - - - - - - diff --git a/tools/Aquarium.Fractal.Receipt/Program.cs b/tools/Aquarium.Fractal.Receipt/Program.cs deleted file mode 100644 index 71437ff..0000000 --- a/tools/Aquarium.Fractal.Receipt/Program.cs +++ /dev/null @@ -1,1459 +0,0 @@ -using System.Diagnostics; -using System.Numerics; -using System.Runtime.InteropServices; -using System.Text.Json; -using System.Xml.Linq; -using Aquarium.Engine.Fractal; -using Aquarium.Engine.Fractal.Grammar; -using Aquarium.Engine.Fractal.Lod; -using Vortice.D3DCompiler; -using Vortice.Direct3D; -using Vortice.Direct3D12; -using Vortice.DXGI; - -var options = ReceiptOptions.Parse(args); -if (options.ReferencePpmPath is not null) -{ - RunReferencePpmReceipt(options); - return; -} - -if (options.FlamePath is not null) -{ - RunFlameHistogramReceipt(options); - return; -} - -var shaderSource = File.ReadAllText(options.ShaderPath); -using var runner = new GpuFractalSplatReceiptRunner(shaderSource); -var receipt = runner.Run(options); - -Directory.CreateDirectory(options.OutputDirectory); -var receiptStamp = DateTimeOffset.Now.ToString("yyyyMMdd-HHmmss"); -var receiptPath = Path.Combine(options.OutputDirectory, $"fractal-gpu-splat-receipt-{receiptStamp}.json"); -File.WriteAllText(receiptPath, JsonSerializer.Serialize(receipt, new JsonSerializerOptions { WriteIndented = true })); -var importReportPath = WriteProgramFlameImportReport(options, receiptStamp); - -Console.WriteLine("=== Aquarium Perfect Machine GPU Splat Receipt ==="); -Console.WriteLine($"adapter: {receipt.Adapter}"); -Console.WriteLine($"splats: {receipt.SplatCount:N0}"); -Console.WriteLine($"form reservoirs (SDF backend slice): {receipt.SdfReservoirCount:N0}"); -Console.WriteLine($"appearance reservoirs (PBR backend slice): {receipt.PbrReservoirCount:N0}"); -Console.WriteLine($"transport reservoirs (radiosity backend slice): {receipt.RadiosityReservoirCount:N0}"); -Console.WriteLine($"flame states: {receipt.FlameStateCount:N0}"); -Console.WriteLine($"ifs program transforms: {receipt.ProgramTransformCount:N0}"); -Console.WriteLine($"program mode: {DescribeProgramMode(receipt.ProgramMode)}"); -Console.WriteLine($"priority focus: {receipt.PriorityFocus.X:0.###},{receipt.PriorityFocus.Y:0.###} radius {receipt.PriorityFocus.Z:0.###} strength {receipt.PriorityFocus.W:0.###}"); -if (receipt.AdaptivePriorityFocus is not null) -{ - Console.WriteLine($"adaptive priority focus: {receipt.AdaptivePriorityFocus[0]:0.###},{receipt.AdaptivePriorityFocus[1]:0.###} radius {receipt.AdaptivePriorityFocus[2]:0.###} strength {receipt.AdaptivePriorityFocus[3]:0.###}"); -} -Console.WriteLine($"warmup splat updates/frame: {receipt.WarmupSplatUpdatesPerFrame:N0}"); -Console.WriteLine($"splat updates/frame: {receipt.SplatUpdatesPerFrame:N0}"); -Console.WriteLine($"candidates/pass: {receipt.CandidatesPerPass}"); -Console.WriteLine($"reservoir updates/pass/frame: {receipt.ReservoirUpdatesPerPass:N0}"); -Console.WriteLine($"reservoir full-coverage frames: {receipt.ReservoirFullCoverageFrames:0.0}"); -Console.WriteLine($"frames: {receipt.MeasuredFrames}"); -Console.WriteLine("shader: D3D12 compute, independent GPU-resident Form/Appearance/Transport reservoir passes"); -Console.WriteLine($"packed bytes/splat: {receipt.BytesPerSplat}"); -Console.WriteLine($"packed bytes/reservoir: {receipt.BytesPerReservoir}"); -Console.WriteLine($"packed bytes/flame state: {receipt.BytesPerFlameState}"); -Console.WriteLine($"gpu ms/frame total: {receipt.GpuMillisecondsPerFrame:0.000}"); -Console.WriteLine($"gpu equivalent fps: {receipt.GpuEquivalentFps:0.0}"); -Console.WriteLine($"gpu splats/sec: {receipt.GpuSplatsPerSecond:N0}"); -Console.WriteLine($"gpu reservoir candidates/sec: {receipt.GpuReservoirCandidatesPerSecond:N0}"); -Console.WriteLine($"cpu submit+wait ms/frame: {receipt.CpuSubmitAndWaitMillisecondsPerFrame:0.000}"); -Console.WriteLine($"readback checksum: 0x{receipt.ReadbackChecksum:X16}"); -if (importReportPath is not null) -{ - var report = FractalFlameFileParser.ParseFirstWithReport(File.ReadAllText(options.ProgramFlamePath!), unchecked((int)options.Seed)).Report; - Console.WriteLine($"flame import: accepted {report.AcceptedFieldCount:N0}, approximated {report.ApproximatedFieldCount:N0}, ignored {report.IgnoredFieldCount:N0}, rejected {report.RejectedFieldCount:N0}"); - Console.WriteLine($"flame import report: {importReportPath}"); -} -if (receipt.VisualParity is not null) -{ - Console.WriteLine($"visual parity reference: {receipt.VisualParity.ReferenceSource}"); - Console.WriteLine($"visual parity candidate: {receipt.VisualParity.CandidateSource}"); - Console.WriteLine($"visual parity density mass: {receipt.VisualParity.ComparedSamples:N0}/{receipt.VisualParity.ReferenceSamples:N0}"); - Console.WriteLine($"visual parity views: {receipt.VisualParity.Views.Count:N0}"); - Console.WriteLine($"visual parity bins: {receipt.VisualParity.Width}x{receipt.VisualParity.Height}"); - Console.WriteLine($"visual parity occupancy overlap: {receipt.VisualParity.OccupancyOverlapPercent:0.00}%"); - Console.WriteLine($"visual parity distribution score: {receipt.VisualParity.DistributionScorePercent:0.00}%"); - Console.WriteLine($"visual parity l1 distance: {receipt.VisualParity.L1Distance:0.000000}"); - Console.WriteLine($"visual parity rmse: {receipt.VisualParity.Rmse:0.000000}"); - Console.WriteLine($"visual parity cosine: {receipt.VisualParity.CosineSimilarity:0.000000}"); - foreach (var view in receipt.VisualParity.Views) - { - Console.WriteLine($"visual view {view.Name}: score {view.DistributionScorePercent:0.00}% / hits gpu {view.GpuHitCount:N0}, ref {view.ReferenceHitCount:N0} / starved bins {view.StarvedReferenceBins:N0} / under-mass {view.UnderrepresentedMassPercent:0.00}% / suggested focus {view.SuggestedPriorityFocus[0]:0.###},{view.SuggestedPriorityFocus[1]:0.###},{view.SuggestedPriorityFocus[2]:0.###},{view.SuggestedPriorityFocus[3]:0.###}"); - } -} -Console.WriteLine($"receipt: {receiptPath}"); - -static string DescribeProgramMode(int mode) -{ - return mode switch - { - 1 => "precomposed selected cut", - 2 => "flame 2D affine/variation program", - _ => "fallback hash IFS", - }; -} - -static void RunReferencePpmReceipt(ReceiptOptions options) -{ - var ppmBytes = File.ReadAllBytes(options.ReferencePpmPath!); - var image = FractalPpmImageReceiptBuilder.Build(ppmBytes); - var receipt = new ReferencePpmReceipt( - Path.GetFullPath(options.ReferencePpmPath!), - image.Width, - image.Height, - image.MaxChannelValue, - image.PixelCount, - image.NonBlackPixelCount, - image.RgbChecksum, - image.LuminanceChecksum); - - Directory.CreateDirectory(options.OutputDirectory); - var receiptPath = Path.Combine(options.OutputDirectory, $"fractal-reference-ppm-receipt-{DateTimeOffset.Now:yyyyMMdd-HHmmss}.json"); - File.WriteAllText(receiptPath, JsonSerializer.Serialize(receipt, new JsonSerializerOptions { WriteIndented = true })); - - Console.WriteLine("=== Aquarium External Flame Reference PPM Receipt ==="); - Console.WriteLine($"source: {receipt.SourcePath}"); - Console.WriteLine($"image: {receipt.Width}x{receipt.Height}"); - Console.WriteLine($"pixels: {receipt.PixelCount:N0}"); - Console.WriteLine($"non-black pixels: {receipt.NonBlackPixelCount:N0}"); - Console.WriteLine($"rgb checksum: 0x{receipt.RgbChecksum:X16}"); - Console.WriteLine($"luminance checksum: 0x{receipt.LuminanceChecksum:X16}"); - Console.WriteLine($"receipt: {receiptPath}"); -} - -static void RunFlameHistogramReceipt(ReceiptOptions options) -{ - var flameSource = File.ReadAllText(options.FlamePath!); - var parsed = FractalFlameFileParser.ParseFirstWithReport(flameSource, unchecked((int)options.Seed)); - var flame = parsed.Definition; - var points = FractalFlameChaosGame.Generate( - flame, - options.HistogramSamples, - options.HistogramBurnIn, - new FractalXorShiftRandom(options.Seed)); - var histogram = FractalPointHistogramBuilder.Build( - points, - options.HistogramWidth, - options.HistogramHeight, - options.HistogramBounds); - var checksum = histogram.Bins.Aggregate(2166136261u, (hash, value) => unchecked((hash ^ (uint)value) * 16777619u)); - var occupiedBins = histogram.Bins.Count(value => value > 0); - var receipt = new FlameHistogramReceipt( - Path.GetFullPath(options.FlamePath!), - flame.Name, - flame.Transforms.Count, - options.HistogramSamples, - options.HistogramBurnIn, - options.HistogramWidth, - options.HistogramHeight, - [ - options.HistogramBounds.X, - options.HistogramBounds.Y, - options.HistogramBounds.Z, - options.HistogramBounds.W, - ], - histogram.HitCount, - occupiedBins, - checksum); - - Directory.CreateDirectory(options.OutputDirectory); - var stamp = DateTimeOffset.Now.ToString("yyyyMMdd-HHmmss"); - var receiptPath = Path.Combine(options.OutputDirectory, $"fractal-flame-histogram-receipt-{stamp}.json"); - File.WriteAllText(receiptPath, JsonSerializer.Serialize(receipt, new JsonSerializerOptions { WriteIndented = true })); - var importReportPath = Path.Combine(options.OutputDirectory, $"fractal-flame-import-report-{stamp}.json"); - File.WriteAllText(importReportPath, JsonSerializer.Serialize(new FlameImportReportReceipt(Path.GetFullPath(options.FlamePath!), parsed.Report), new JsonSerializerOptions { WriteIndented = true })); - - Console.WriteLine("=== Aquarium Fractal Flame Histogram Receipt ==="); - Console.WriteLine($"flame: {receipt.FlameName}"); - Console.WriteLine($"source: {receipt.SourcePath}"); - Console.WriteLine($"xforms: {receipt.TransformCount:N0}"); - Console.WriteLine($"samples: {receipt.SampleCount:N0}"); - Console.WriteLine($"burn-in: {receipt.BurnIn:N0}"); - Console.WriteLine($"histogram: {receipt.Width}x{receipt.Height}"); - Console.WriteLine($"hits: {receipt.HitCount:N0}"); - Console.WriteLine($"occupied bins: {receipt.OccupiedBins:N0}"); - Console.WriteLine($"histogram checksum: 0x{receipt.Checksum:X8}"); - Console.WriteLine($"flame import: accepted {parsed.Report.AcceptedFieldCount:N0}, approximated {parsed.Report.ApproximatedFieldCount:N0}, ignored {parsed.Report.IgnoredFieldCount:N0}, rejected {parsed.Report.RejectedFieldCount:N0}"); - Console.WriteLine($"flame import report: {importReportPath}"); - Console.WriteLine($"receipt: {receiptPath}"); -} - -static string? WriteProgramFlameImportReport(ReceiptOptions options, string receiptStamp) -{ - if (options.ProgramFlamePath is null) - { - return null; - } - - var parsed = FractalFlameFileParser.ParseFirstWithReport(File.ReadAllText(options.ProgramFlamePath), unchecked((int)options.Seed)); - var reportPath = Path.Combine(options.OutputDirectory, $"fractal-flame-import-report-{receiptStamp}.json"); - File.WriteAllText(reportPath, JsonSerializer.Serialize(new FlameImportReportReceipt(Path.GetFullPath(options.ProgramFlamePath), parsed.Report), new JsonSerializerOptions { WriteIndented = true })); - return reportPath; -} - -internal sealed class GpuFractalSplatReceiptRunner : IDisposable -{ - private const int ThreadGroupSize = 256; - - private readonly ID3D12Device device; - private readonly ID3D12CommandQueue queue; - private readonly ID3D12CommandAllocator allocator; - private readonly ID3D12GraphicsCommandList commandList; - private readonly ID3D12Fence fence; - private readonly AutoResetEvent fenceEvent = new(false); - private readonly ID3D12RootSignature rootSignature; - private readonly ID3D12PipelineState splatPipelineState; - private readonly ID3D12PipelineState sdfPipelineState; - private readonly ID3D12PipelineState pbrPipelineState; - private readonly ID3D12PipelineState radiosityPipelineState; - private readonly string adapterName; - private ulong fenceValue; - - public GpuFractalSplatReceiptRunner(string shaderSource) - { - ArgumentException.ThrowIfNullOrWhiteSpace(shaderSource); - device = D3D12.D3D12CreateDevice(IntPtr.Zero, FeatureLevel.Level_11_0); - adapterName = ResolveAdapterName(); - queue = device.CreateCommandQueue(new CommandQueueDescription(CommandListType.Direct)); - allocator = device.CreateCommandAllocator(CommandListType.Direct); - commandList = device.CreateCommandList(0, CommandListType.Direct, allocator, null); - commandList.Close(); - fence = device.CreateFence(0); - rootSignature = CreateRootSignature(device); - splatPipelineState = CreatePipelineState(device, rootSignature, shaderSource, "D3D12FractalSplatReceiptCS"); - sdfPipelineState = CreatePipelineState(device, rootSignature, shaderSource, "D3D12SdfEnvelopeReservoirCS"); - pbrPipelineState = CreatePipelineState(device, rootSignature, shaderSource, "D3D12PbrMaterialReservoirCS"); - radiosityPipelineState = CreatePipelineState(device, rootSignature, shaderSource, "D3D12RadiosityReservoirCS"); - } - - public GpuFractalSplatReceipt Run(ReceiptOptions options) - { - var resolvedProgramTransforms = BuildReceiptProgram(options); - var resolvedProgramMode = resolvedProgramTransforms.Length > 0 ? options.ProgramMode : 0; - var splatStride = Marshal.SizeOf(); - var reservoirStride = Marshal.SizeOf(); - var flameStateStride = Marshal.SizeOf(); - var framePlan = FractalGpuReservoirBudgetPlanner.Plan( - options.SplatCount, - options.ReservoirUpdatesPerPass, - options.CandidatesPerPass, - splatStride, - reservoirStride); - var splatBytes = checked((ulong)splatStride * (ulong)options.SplatCount); - var reservoirBytes = checked((ulong)reservoirStride * (ulong)options.SplatCount); - var flameStateBytes = checked((ulong)flameStateStride * (ulong)options.SplatCount); - using var splats = CreateUavBuffer(splatBytes, "Aquarium Fractal Receipt GPU Splat Buffer"); - using var sdfReservoirs = CreateUavBuffer(reservoirBytes, "Aquarium Fractal Receipt SDF Reservoir Buffer"); - using var pbrReservoirs = CreateUavBuffer(reservoirBytes, "Aquarium Fractal Receipt PBR Reservoir Buffer"); - using var radiosityReservoirs = CreateUavBuffer(reservoirBytes, "Aquarium Fractal Receipt Radiosity Reservoir Buffer"); - using var flameStates = CreateUavBuffer(flameStateBytes, "Aquarium Fractal Receipt Flame Iteration State Buffer"); - using var programTransforms = CreateProgramTransformBuffer(resolvedProgramTransforms); - - var readbackSplatBytes = (ulong)Math.Min(options.ReadbackSplats, options.SplatCount) * (ulong)splatStride; - var readbackReservoirBytes = (ulong)Math.Min(options.ReadbackSplats, options.SplatCount) * (ulong)reservoirStride; - var totalReadbackBytes = readbackSplatBytes + (readbackReservoirBytes * 3UL); - using var readback = device.CreateCommittedResource(HeapType.Readback, ResourceDescription.Buffer(Math.Max(totalReadbackBytes, 1)), ResourceStates.CopyDest, null); - using var queryHeap = device.CreateQueryHeap(new QueryHeapDescription(QueryHeapType.Timestamp, 2u)); - using var queryReadback = device.CreateCommittedResource(HeapType.Readback, ResourceDescription.Buffer(16), ResourceStates.CopyDest, null); - - queue.GetTimestampFrequency(out var timestampFrequency); - var measuredGpuTicks = 0UL; - var measuredCpuTicks = 0L; - var measuredFrames = 0; - var currentPriorityFocus = options.PriorityFocus; - float[]? adaptivePriorityFocus = null; - - for (var frame = 0; frame < options.WarmupFrames + options.MeasuredFrames; frame++) - { - var splatDispatchCount = frame == 0 - ? options.SplatCount - : frame < options.WarmupFrames ? options.WarmupSplatUpdatesPerFrame : options.SplatUpdatesPerFrame; - allocator.Reset(); - commandList.Reset(allocator, splatPipelineState); - commandList.SetComputeRootSignature(rootSignature); - BindConstants(options, frame, resolvedProgramTransforms.Length, resolvedProgramMode, splatDispatchCount, currentPriorityFocus); - commandList.SetComputeRootUnorderedAccessView(1, splats.GPUVirtualAddress); - commandList.SetComputeRootUnorderedAccessView(2, sdfReservoirs.GPUVirtualAddress); - commandList.SetComputeRootUnorderedAccessView(3, pbrReservoirs.GPUVirtualAddress); - commandList.SetComputeRootUnorderedAccessView(4, radiosityReservoirs.GPUVirtualAddress); - commandList.SetComputeRootUnorderedAccessView(5, flameStates.GPUVirtualAddress); - commandList.SetComputeRootShaderResourceView(6, programTransforms.GPUVirtualAddress); - commandList.EndQuery(queryHeap, QueryType.Timestamp, 0); - Dispatch(splatPipelineState, splatDispatchCount); - commandList.ResourceBarrier(ResourceBarrier.BarrierUnorderedAccessView(splats)); - Dispatch(sdfPipelineState, options.ReservoirUpdatesPerPass); - Dispatch(pbrPipelineState, options.ReservoirUpdatesPerPass); - Dispatch(radiosityPipelineState, options.ReservoirUpdatesPerPass); - commandList.EndQuery(queryHeap, QueryType.Timestamp, 1); - commandList.ResolveQueryData(queryHeap, QueryType.Timestamp, 0, 2, queryReadback, 0); - - var isAdaptiveFocusFrame = options.AdaptiveFocus && frame == options.WarmupFrames - 1 && totalReadbackBytes > 0; - if ((isAdaptiveFocusFrame || frame == options.WarmupFrames + options.MeasuredFrames - 1) && totalReadbackBytes > 0) - { - CopyReceiptReadback(splats, sdfReservoirs, pbrReservoirs, radiosityReservoirs, readback, readbackSplatBytes, readbackReservoirBytes); - } - - commandList.Close(); - var cpuStart = Stopwatch.GetTimestamp(); - queue.ExecuteCommandList(commandList); - WaitForGpu(); - var cpuEnd = Stopwatch.GetTimestamp(); - - if (frame >= options.WarmupFrames) - { - measuredFrames++; - measuredCpuTicks += cpuEnd - cpuStart; - unsafe - { - var timestamps = (ulong*)queryReadback.Map(0); - measuredGpuTicks += timestamps[1] - timestamps[0]; - queryReadback.Unmap(0); - } - } - - if (isAdaptiveFocusFrame) - { - var warmupParity = BuildVisualParity( - options, - readback, - readbackSplatBytes, - readbackReservoirBytes, - reservoirStride, - (int)(readbackSplatBytes / (ulong)splatStride))!; - var focus = warmupParity.Views[0].SuggestedPriorityFocus; - adaptivePriorityFocus = focus; - currentPriorityFocus = new Vector4(focus[0], focus[1], focus[2], focus[3]); - } - } - - var checksum = totalReadbackBytes == 0 ? 0UL : Checksum(readback, (int)totalReadbackBytes); - var visualParity = totalReadbackBytes == 0 - ? null - : BuildVisualParity( - options, - readback, - readbackSplatBytes, - readbackReservoirBytes, - reservoirStride, - (int)(readbackSplatBytes / (ulong)splatStride)); - var gpuSeconds = measuredGpuTicks / (double)timestampFrequency; - var gpuMsPerFrame = gpuSeconds * 1000.0 / Math.Max(measuredFrames, 1); - var cpuMsPerFrame = measuredCpuTicks * 1000.0 / Stopwatch.Frequency / Math.Max(measuredFrames, 1); - var splatsPerSecond = options.SplatUpdatesPerFrame * (double)measuredFrames / Math.Max(gpuSeconds, 1.0e-12); - var reservoirCandidatesPerSecond = options.ReservoirUpdatesPerPass * 3.0 * options.CandidatesPerPass * measuredFrames / Math.Max(gpuSeconds, 1.0e-12); - - return new GpuFractalSplatReceipt( - adapterName, - options.SplatCount, - options.SplatCount, - options.SplatCount, - options.SplatCount, - options.SplatCount, - resolvedProgramTransforms.Length, - resolvedProgramMode, - options.PriorityFocus, - options.WarmupSplatUpdatesPerFrame, - options.SplatUpdatesPerFrame, - options.CandidatesPerPass, - options.ReservoirUpdatesPerPass, - framePlan.Passes[0].ExpectedFullCoverageFrames, - measuredFrames, - splatStride, - reservoirStride, - flameStateStride, - gpuMsPerFrame, - 1000.0 / Math.Max(gpuMsPerFrame, 1.0e-12), - splatsPerSecond, - reservoirCandidatesPerSecond, - cpuMsPerFrame, - checksum, - adaptivePriorityFocus, - visualParity); - - void Dispatch(ID3D12PipelineState state, int elementCount) - { - commandList.SetPipelineState(state); - commandList.Dispatch((uint)((elementCount + ThreadGroupSize - 1) / ThreadGroupSize), 1, 1); - } - } - - public void Dispose() - { - WaitForGpu(); - radiosityPipelineState.Dispose(); - pbrPipelineState.Dispose(); - sdfPipelineState.Dispose(); - splatPipelineState.Dispose(); - rootSignature.Dispose(); - fence.Dispose(); - commandList.Dispose(); - allocator.Dispose(); - queue.Dispose(); - device.Dispose(); - fenceEvent.Dispose(); - } - - private ID3D12Resource CreateUavBuffer(ulong bytes, string name) - { - var resource = device.CreateCommittedResource(HeapType.Default, ResourceDescription.Buffer(bytes, ResourceFlags.AllowUnorderedAccess), ResourceStates.UnorderedAccess, null); - resource.Name = name; - return resource; - } - - private ID3D12Resource CreateProgramTransformBuffer(AquariumPackedFractalIfsTransform[] transforms) - { - var stride = Marshal.SizeOf(); - var bytes = (ulong)(Math.Max(transforms.Length, 1) * stride); - var upload = device.CreateCommittedResource(HeapType.Upload, ResourceDescription.Buffer(bytes), ResourceStates.GenericRead, null); - upload.Name = "Aquarium Fractal Receipt IFS Program Upload Buffer"; - unsafe - { - var target = (AquariumPackedFractalIfsTransform*)upload.Map(0); - for (var index = 0; index < transforms.Length; index++) - { - target[index] = transforms[index]; - } - - upload.Unmap(0); - } - - var resource = device.CreateCommittedResource(HeapType.Default, ResourceDescription.Buffer(bytes), ResourceStates.CopyDest, null); - resource.Name = "Aquarium Fractal Receipt IFS Program Buffer"; - allocator.Reset(); - commandList.Reset(allocator, null); - commandList.CopyBufferRegion(resource, 0, upload, 0, bytes); - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(resource, ResourceStates.CopyDest, ResourceStates.NonPixelShaderResource)); - commandList.Close(); - queue.ExecuteCommandList(commandList); - WaitForGpu(); - upload.Dispose(); - return resource; - } - - private static AquariumPackedFractalIfsTransform[] BuildReceiptProgram(ReceiptOptions options) - { - if (options.ProgramFlamePath is not null) - { - var flame = FractalFlameFileParser.ParseFirst(File.ReadAllText(options.ProgramFlamePath), unchecked((int)options.Seed)); - return FractalGpuProgramCompiler.CompileFlame2D(flame, Math.Max(options.ProgramTransformCount, 1)); - } - - return BuildSyntheticReceiptProgram(options.ProgramTransformCount); - } - - private static AquariumPackedFractalIfsTransform[] BuildSyntheticReceiptProgram(int transformCount) - { - if (transformCount <= 0) - { - return [default]; - } - - var transforms = new AquariumPackedFractalIfsTransform[transformCount]; - for (var index = 0; index < transforms.Length; index++) - { - var phase = MathF.Tau * index / Math.Max(transformCount, 1); - var branch = new Vector2(MathF.Cos(phase), MathF.Sin(phase)); - var radius = 0.32f + (index % 5) * 0.035f; - var scale = 0.46f + (index % 3) * 0.035f; - var rotation = phase * 0.37f; - transforms[index] = new AquariumPackedFractalIfsTransform( - new Vector4(branch * 0.42f, scale, 0.18f + index * 0.013f), - new Vector4(radius, radius * 0.62f, rotation, 4.0f), - new Vector4((index + 1.0f) / (transformCount + 1.0f), index * 31 + 7, MathF.Cos(rotation), MathF.Sin(rotation)), - new Vector4(index % 6, 0.0f, 0.0f, 0.0f), - new Vector4(1.0f, 0.0f, 0.0f, 1.0f), - Vector4.Zero); - } - - return transforms; - } - - private void BindConstants(ReceiptOptions options, int frame, int programTransformCount, int programMode, int splatDispatchCount, Vector4 priorityFocus) - { - commandList.SetComputeRoot32BitConstant(0, (uint)options.SplatCount, 0); - commandList.SetComputeRoot32BitConstant(0, (uint)frame, 1); - commandList.SetComputeRoot32BitConstant(0, (uint)options.Depth, 2); - commandList.SetComputeRoot32BitConstant(0, options.Seed, 3); - commandList.SetComputeRoot32BitConstant(0, (uint)options.CandidatesPerPass, 4); - commandList.SetComputeRoot32BitConstant(0, (uint)options.ReservoirUpdatesPerPass, 5); - commandList.SetComputeRoot32BitConstant(0, (uint)programTransformCount, 6); - commandList.SetComputeRoot32BitConstant(0, (uint)programMode, 7); - commandList.SetComputeRoot32BitConstant(0, (uint)splatDispatchCount, 8); - commandList.SetComputeRoot32BitConstant(0, BitConverter.SingleToUInt32Bits(priorityFocus.X), 9); - commandList.SetComputeRoot32BitConstant(0, BitConverter.SingleToUInt32Bits(priorityFocus.Y), 10); - commandList.SetComputeRoot32BitConstant(0, BitConverter.SingleToUInt32Bits(priorityFocus.Z), 11); - commandList.SetComputeRoot32BitConstant(0, BitConverter.SingleToUInt32Bits(priorityFocus.W), 12); - } - - private void CopyReceiptReadback(ID3D12Resource splats, ID3D12Resource sdf, ID3D12Resource pbr, ID3D12Resource radiosity, ID3D12Resource readback, ulong splatBytes, ulong reservoirBytes) - { - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(splats, ResourceStates.UnorderedAccess, ResourceStates.CopySource)); - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(sdf, ResourceStates.UnorderedAccess, ResourceStates.CopySource)); - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(pbr, ResourceStates.UnorderedAccess, ResourceStates.CopySource)); - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(radiosity, ResourceStates.UnorderedAccess, ResourceStates.CopySource)); - commandList.CopyBufferRegion(readback, 0, splats, 0, splatBytes); - commandList.CopyBufferRegion(readback, splatBytes, sdf, 0, reservoirBytes); - commandList.CopyBufferRegion(readback, splatBytes + reservoirBytes, pbr, 0, reservoirBytes); - commandList.CopyBufferRegion(readback, splatBytes + (reservoirBytes * 2), radiosity, 0, reservoirBytes); - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(splats, ResourceStates.CopySource, ResourceStates.UnorderedAccess)); - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(sdf, ResourceStates.CopySource, ResourceStates.UnorderedAccess)); - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(pbr, ResourceStates.CopySource, ResourceStates.UnorderedAccess)); - commandList.ResourceBarrier(ResourceBarrier.BarrierTransition(radiosity, ResourceStates.CopySource, ResourceStates.UnorderedAccess)); - } - - private static unsafe VisualParityReceipt? BuildVisualParity( - ReceiptOptions options, - ID3D12Resource readback, - ulong readbackSplatBytes, - ulong readbackReservoirBytes, - int reservoirStride, - int readbackSplatCount) - { - if (!options.VisualParity || readbackSplatCount <= 0) - { - return null; - } - - var readbackReservoirCount = Math.Min( - readbackSplatCount, - (int)(readbackReservoirBytes / (ulong)reservoirStride)); - var views = options.VisualParityViews.Count > 0 - ? options.VisualParityViews - : [new VisualParityView("global", options.HistogramBounds)]; - ReferenceDensityImage? externalReference = options.ReferenceDensityPpmPath is null - ? null - : LoadReferenceDensityPpm(options.ReferenceDensityPpmPath, options.HistogramBounds); - var flameReferencePoints = externalReference is null - ? BuildCpuFlameReferencePoints(options) - : null; - var viewReceipts = new VisualParityViewReceipt[views.Count]; - var candidateHistograms = new FractalPointHistogram[views.Count]; - var candidateSource = "Aquarium SDF envelope reservoir density"; - var comparedSamples = 0; - var basePtr = readback.Map(0); - try - { - var reservoirs = (AquariumPackedSdfEnvelopeReservoir*)((byte*)basePtr + readbackSplatBytes); - for (var index = 0; index < views.Count; index++) - { - candidateHistograms[index] = BuildSdfEnvelopeDensityHistogram( - reservoirs, - readbackReservoirCount, - options.HistogramWidth, - options.HistogramHeight, - views[index].Bounds); - } - } - finally - { - readback.Unmap(0); - } - - for (var index = 0; index < views.Count; index++) - { - var referenceHistogram = externalReference is null - ? FractalPointHistogramBuilder.Build(flameReferencePoints!, options.HistogramWidth, options.HistogramHeight, views[index].Bounds) - : externalReference.Value.ToHistogram(options.HistogramWidth, options.HistogramHeight, views[index].Bounds); - viewReceipts[index] = BuildVisualParityView( - options, - views[index], - referenceHistogram, - candidateHistograms[index]); - comparedSamples = Math.Max(comparedSamples, candidateHistograms[index].HitCount); - } - - var primary = viewReceipts[0]; - return new VisualParityReceipt( - externalReference is null ? "Aquarium CPU flame oracle" : Path.GetFullPath(options.ReferenceDensityPpmPath!), - candidateSource, - comparedSamples, - externalReference?.TotalLuminance ?? options.VisualParityReferenceSamples, - options.HistogramWidth, - options.HistogramHeight, - primary.Bounds, - primary.ReferenceHitCount, - primary.GpuHitCount, - primary.ReferenceOccupiedBins, - primary.GpuOccupiedBins, - primary.SharedOccupiedBins, - primary.OccupancyOverlapPercent, - primary.L1Distance, - primary.Rmse, - primary.CosineSimilarity, - primary.DistributionScorePercent, - viewReceipts); - } - - private static unsafe FractalPointHistogram BuildSdfEnvelopeDensityHistogram( - AquariumPackedSdfEnvelopeReservoir* reservoirs, - int count, - int width, - int height, - Vector4 bounds) - { - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); - ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); - - var bins = new int[width * height]; - var spanX = MathF.Max(bounds.Z - bounds.X, 0.000001f); - var spanY = MathF.Max(bounds.W - bounds.Y, 0.000001f); - for (var index = 0; index < count; index++) - { - var reservoir = reservoirs[index]; - var centerRadius = reservoir.CenterRadius; - var radiiFalloff = reservoir.RadiiFalloff; - if (!IsFinite(centerRadius) || !IsFinite(radiiFalloff) || reservoir.WeightTargetCount.Z <= 0.0f) - { - continue; - } - - var centerX = centerRadius.X; - var centerY = centerRadius.Y; - var pixelRadiusX = spanX / width; - var pixelRadiusY = spanY / height; - var radiusX = MathF.Max(MathF.Max(MathF.Abs(radiiFalloff.X), MathF.Abs(centerRadius.W)), pixelRadiusX); - var radiusY = MathF.Max(MathF.Max(MathF.Abs(radiiFalloff.Y), MathF.Abs(centerRadius.W)), pixelRadiusY); - if (radiusX <= 0.0f || radiusY <= 0.0f) - { - continue; - } - - var minX = Math.Clamp((int)MathF.Floor(((centerX - radiusX) - bounds.X) / spanX * width), 0, width - 1); - var maxX = Math.Clamp((int)MathF.Ceiling(((centerX + radiusX) - bounds.X) / spanX * width), 0, width - 1); - var minY = Math.Clamp((int)MathF.Floor(((centerY - radiusY) - bounds.Y) / spanY * height), 0, height - 1); - var maxY = Math.Clamp((int)MathF.Ceiling(((centerY + radiusY) - bounds.Y) / spanY * height), 0, height - 1); - if (maxX < minX || maxY < minY) - { - continue; - } - - var targetCount = MathF.Max(reservoir.WeightTargetCount.Y, 1.0f); - var confidence = Math.Clamp(reservoir.Validation.X, 0.0f, 1.0f); - var baseMass = Math.Clamp((int)MathF.Ceiling(targetCount * MathF.Max(confidence, 0.125f)), 1, 16); - for (var y = minY; y <= maxY; y++) - { - var worldY = bounds.Y + ((y + 0.5f) / height) * spanY; - var dy = (worldY - centerY) / radiusY; - for (var x = minX; x <= maxX; x++) - { - var worldX = bounds.X + ((x + 0.5f) / width) * spanX; - var dx = (worldX - centerX) / radiusX; - var q = (dx * dx) + (dy * dy); - if (q > 1.0f) - { - continue; - } - - var shaped = 1.0f - q; - var mass = Math.Max(1, (int)MathF.Ceiling(baseMass * shaped * shaped)); - var binIndex = (y * width) + x; - bins[binIndex] = bins[binIndex] > int.MaxValue - mass - ? int.MaxValue - : bins[binIndex] + mass; - } - } - } - - return new FractalPointHistogram(width, height, bounds, bins); - } - - private static bool IsFinite(Vector4 value) - { - return float.IsFinite(value.X) - && float.IsFinite(value.Y) - && float.IsFinite(value.Z) - && float.IsFinite(value.W); - } - - private static VisualParityViewReceipt BuildVisualParityView( - ReceiptOptions options, - VisualParityView view, - FractalPointHistogram referenceHistogram, - FractalPointHistogram candidateHistogram) - { - WriteVisualParityImages(options, view.Name, referenceHistogram, candidateHistogram); - var metrics = CompareHistograms(referenceHistogram, candidateHistogram); - var suggestedFocus = FractalHistogramResidualFocus.Estimate(referenceHistogram, candidateHistogram); - return new VisualParityViewReceipt( - view.Name, - [ - view.Bounds.X, - view.Bounds.Y, - view.Bounds.Z, - view.Bounds.W, - ], - referenceHistogram.HitCount, - candidateHistogram.HitCount, - metrics.ReferenceOccupiedBins, - metrics.GpuOccupiedBins, - metrics.SharedOccupiedBins, - metrics.StarvedReferenceBins, - metrics.OccupancyOverlapPercent, - metrics.UnderrepresentedMassPercent, - metrics.OversampledMassPercent, - [ - suggestedFocus.X, - suggestedFocus.Y, - suggestedFocus.Z, - suggestedFocus.W, - ], - metrics.L1Distance, - metrics.Rmse, - metrics.CosineSimilarity, - metrics.DistributionScorePercent); - } - - private static Vector2[] BuildCpuFlameReferencePoints(ReceiptOptions options) - { - if (options.ProgramFlamePath is null) - { - throw new ArgumentException("Visual parity needs either --program-flame or --reference-density-ppm."); - } - - var flame = FractalFlameFileParser.ParseFirst(File.ReadAllText(options.ProgramFlamePath), unchecked((int)options.Seed)); - return FractalFlameChaosGame.Generate( - flame, - options.VisualParityReferenceSamples, - options.HistogramBurnIn, - new FractalXorShiftRandom(options.Seed)); - } - - private static ReferenceDensityImage LoadReferenceDensityPpm(string path, Vector4 bounds) - { - var bytes = File.ReadAllBytes(path); - var cursor = 0; - var magic = ReadPpmToken(bytes, ref cursor); - if (!magic.SequenceEqual("P6"u8)) - { - throw new FormatException("External density reference must be a binary P6 PPM image."); - } - - var width = ParsePositivePpmInt(ReadPpmToken(bytes, ref cursor), "width"); - var height = ParsePositivePpmInt(ReadPpmToken(bytes, ref cursor), "height"); - var max = ParsePositivePpmInt(ReadPpmToken(bytes, ref cursor), "max channel value"); - if (max > 255) - { - throw new FormatException("External density reference must be 8-bit PPM."); - } - - ConsumePpmWhitespace(bytes, ref cursor); - var expectedBytes = checked(width * height * 3); - if (bytes.Length - cursor < expectedBytes) - { - throw new FormatException("External density reference ended before all RGB pixels were present."); - } - - var luminance = new int[width * height]; - var total = 0L; - var pixels = bytes.AsSpan(cursor, expectedBytes); - for (var source = 0; source < pixels.Length; source += 3) - { - var r = pixels[source]; - var g = pixels[source + 1]; - var b = pixels[source + 2]; - var value = ((r * 54) + (g * 183) + (b * 19)) >> 8; - var pixelIndex = source / 3; - luminance[pixelIndex] = value; - total += value; - } - - return new ReferenceDensityImage(width, height, bounds, luminance, Math.Max(total, 1L)); - } - - private static ReadOnlySpan ReadPpmToken(ReadOnlySpan bytes, ref int cursor) - { - while (cursor < bytes.Length) - { - if (bytes[cursor] is (byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n') - { - cursor++; - continue; - } - - if (bytes[cursor] != (byte)'#') - { - break; - } - - while (cursor < bytes.Length && bytes[cursor] != (byte)'\n') - { - cursor++; - } - } - - var start = cursor; - while (cursor < bytes.Length && bytes[cursor] is not ((byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n' or (byte)'#')) - { - cursor++; - } - - if (cursor == start) - { - throw new FormatException("PPM header ended unexpectedly."); - } - - return bytes.Slice(start, cursor - start); - } - - private static void ConsumePpmWhitespace(ReadOnlySpan bytes, ref int cursor) - { - if (cursor >= bytes.Length || bytes[cursor] is not ((byte)' ' or (byte)'\t' or (byte)'\r' or (byte)'\n')) - { - throw new FormatException("PPM header is missing the pixel-data separator."); - } - - cursor++; - } - - private static int ParsePositivePpmInt(ReadOnlySpan token, string name) - { - var value = 0; - foreach (var digit in token) - { - if (digit is < (byte)'0' or > (byte)'9') - { - throw new FormatException($"PPM {name} is not an integer."); - } - - value = checked((value * 10) + digit - (byte)'0'); - } - - return value > 0 ? value : throw new FormatException($"PPM {name} must be positive."); - } - - private static void WriteVisualParityImages( - ReceiptOptions options, - string viewName, - FractalPointHistogram referenceHistogram, - FractalPointHistogram gpuHistogram) - { - if (options.VisualParityImageDirectory is null) - { - return; - } - - Directory.CreateDirectory(options.VisualParityImageDirectory); - var safeViewName = SanitizeFileSegment(viewName); - var safePrefix = SanitizeFileSegment(options.VisualParityImagePrefix); - WriteHistogramPpm( - Path.Combine(options.VisualParityImageDirectory, $"{safePrefix}-{safeViewName}-reference.ppm"), - referenceHistogram, - new Vector3(0.45f, 0.86f, 1.0f)); - WriteHistogramPpm( - Path.Combine(options.VisualParityImageDirectory, $"{safePrefix}-{safeViewName}-aquarium.ppm"), - gpuHistogram, - new Vector3(1.0f, 0.68f, 0.28f)); - } - - private static void WriteHistogramPpm(string path, FractalPointHistogram histogram, Vector3 color) - { - const int scale = 4; - var width = histogram.Width * scale; - var height = histogram.Height * scale; - var max = histogram.Bins.Max(); - using var stream = File.Create(path); - using var writer = new StreamWriter(stream, System.Text.Encoding.ASCII, leaveOpen: true); - writer.Write($"P6\n{width} {height}\n255\n"); - writer.Flush(); - var row = new byte[width * 3]; - for (var y = 0; y < height; y++) - { - Array.Clear(row); - var binY = histogram.Height - 1 - (y / scale); - for (var x = 0; x < width; x++) - { - var binX = x / scale; - var value = histogram.Bins[(binY * histogram.Width) + binX]; - var normalized = max <= 0 ? 0.0 : Math.Sqrt(Math.Log(1.0 + value) / Math.Log(1.0 + max)); - var offset = x * 3; - row[offset] = (byte)Math.Clamp((int)(normalized * color.X * 255.0), 0, 255); - row[offset + 1] = (byte)Math.Clamp((int)(normalized * color.Y * 255.0), 0, 255); - row[offset + 2] = (byte)Math.Clamp((int)(normalized * color.Z * 255.0), 0, 255); - } - - stream.Write(row); - } - } - - private static string SanitizeFileSegment(string value) - { - var chars = value.Select(ch => char.IsLetterOrDigit(ch) || ch is '-' or '_' ? ch : '-').ToArray(); - return new string(chars).Trim('-') is { Length: > 0 } sanitized ? sanitized : "view"; - } - - private static HistogramComparison CompareHistograms(FractalPointHistogram reference, FractalPointHistogram candidate) - { - if (reference.Width != candidate.Width || reference.Height != candidate.Height) - { - throw new ArgumentException("Histogram dimensions must match."); - } - - var referenceTotal = Math.Max(reference.HitCount, 1); - var candidateTotal = Math.Max(candidate.HitCount, 1); - var l1 = 0.0; - var squared = 0.0; - var dot = 0.0; - var referenceMagnitude = 0.0; - var candidateMagnitude = 0.0; - var referenceOccupied = 0; - var candidateOccupied = 0; - var sharedOccupied = 0; - var starvedReferenceBins = 0; - var underrepresentedMass = 0.0; - var oversampledMass = 0.0; - for (var index = 0; index < reference.Bins.Length; index++) - { - var referenceProbability = reference.Bins[index] / (double)referenceTotal; - var candidateProbability = candidate.Bins[index] / (double)candidateTotal; - var delta = referenceProbability - candidateProbability; - l1 += Math.Abs(delta); - underrepresentedMass += Math.Max(delta, 0.0); - oversampledMass += Math.Max(-delta, 0.0); - squared += delta * delta; - dot += referenceProbability * candidateProbability; - referenceMagnitude += referenceProbability * referenceProbability; - candidateMagnitude += candidateProbability * candidateProbability; - var referenceHas = reference.Bins[index] > 0; - var candidateHas = candidate.Bins[index] > 0; - referenceOccupied += referenceHas ? 1 : 0; - candidateOccupied += candidateHas ? 1 : 0; - sharedOccupied += referenceHas && candidateHas ? 1 : 0; - starvedReferenceBins += referenceHas && !candidateHas ? 1 : 0; - } - - var occupiedUnion = Math.Max(referenceOccupied + candidateOccupied - sharedOccupied, 1); - var cosine = dot / Math.Max(Math.Sqrt(referenceMagnitude * candidateMagnitude), 1.0e-12); - var rmse = Math.Sqrt(squared / reference.Bins.Length); - return new HistogramComparison( - referenceOccupied, - candidateOccupied, - sharedOccupied, - starvedReferenceBins, - sharedOccupied * 100.0 / occupiedUnion, - underrepresentedMass * 100.0, - oversampledMass * 100.0, - l1, - rmse, - cosine, - Math.Max(0.0, (1.0 - (l1 * 0.5)) * 100.0)); - } - - private void WaitForGpu() - { - fenceValue++; - queue.Signal(fence, fenceValue); - if (fence.CompletedValue < fenceValue) - { - fence.SetEventOnCompletion(fenceValue, fenceEvent.SafeWaitHandle.DangerousGetHandle()); - fenceEvent.WaitOne(); - } - } - - private string ResolveAdapterName() - { - using var factory = DXGI.CreateDXGIFactory1(); - for (var index = 0u; factory.EnumAdapterByGpuPreference(index, GpuPreference.HighPerformance, out IDXGIAdapter1? adapter).Success && adapter is not null; index++) - { - using (adapter) - { - var description = adapter.Description1; - if ((description.Flags & AdapterFlags.Software) == 0) - { - return description.Description; - } - } - } - - return "default D3D12 adapter"; - } - - private static ID3D12RootSignature CreateRootSignature(ID3D12Device device) - { - var rootParameters = new[] - { - new RootParameter(new RootConstants(0, 0, 13), ShaderVisibility.All), - new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(0, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(1, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(2, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(3, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.UnorderedAccessView, new RootDescriptor(4, 0), ShaderVisibility.All), - new RootParameter(RootParameterType.ShaderResourceView, new RootDescriptor(0, 0), ShaderVisibility.All), - }; - var description = new RootSignatureDescription(RootSignatureFlags.None, rootParameters, []); - return device.CreateRootSignature(0, in description, RootSignatureVersion.Version1); - } - - private static ID3D12PipelineState CreatePipelineState(ID3D12Device device, ID3D12RootSignature rootSignature, string shaderSource, string entry) - { - var shader = Compiler.Compile(shaderSource, entry, "D3D12FractalReservoirCompute.hlsl", "cs_5_0", ShaderFlags.OptimizationLevel3, EffectFlags.None); - return device.CreateComputePipelineState(new ComputePipelineStateDescription { RootSignature = rootSignature, ComputeShader = shader }); - } - - private static unsafe ulong Checksum(ID3D12Resource readback, int byteCount) - { - var data = (byte*)readback.Map(0); - var hash = 1469598103934665603UL; - for (var index = 0; index < byteCount; index++) - { - hash ^= data[index]; - hash *= 1099511628211UL; - } - - readback.Unmap(0); - return hash; - } - -} - -internal sealed record ReceiptOptions( - int SplatCount, - int WarmupSplatUpdatesPerFrame, - int SplatUpdatesPerFrame, - int WarmupFrames, - int MeasuredFrames, - int Depth, - uint Seed, - int CandidatesPerPass, - int ReservoirUpdatesPerPass, - int ProgramTransformCount, - int ProgramMode, - Vector4 PriorityFocus, - bool AdaptiveFocus, - int ReadbackSplats, - string ShaderPath, - string OutputDirectory, - string? FlamePath, - string? ReferencePpmPath, - string? ReferenceDensityPpmPath, - string? ProgramFlamePath, - int HistogramSamples, - int HistogramBurnIn, - int HistogramWidth, - int HistogramHeight, - Vector4 HistogramBounds, - bool VisualParity, - int VisualParityReferenceSamples, - IReadOnlyList VisualParityViews, - string? VisualParityImageDirectory, - string VisualParityImagePrefix) -{ - public static ReceiptOptions Parse(string[] args) - { - var options = new ReceiptOptions( - 2_000_000, - 2_000_000, - 2_000_000, - 30, - 120, - 8, - 0xA17EA11u, - 2, - 50_000, - 0, - 0, - Vector4.Zero, - false, - 64, - Path.Combine("src", "Aquarium.Engine", "Render", "Shaders", "D3D12FractalReservoirCompute.hlsl"), - Path.Combine("artifacts", "fractal-splat-receipts"), - null, - null, - null, - null, - 8192, - 64, - 64, - 64, - new Vector4(-8.0f, -8.0f, 8.0f, 8.0f), - false, - 1_000_000, - [], - null, - "visual-parity"); - for (var index = 0; index < args.Length; index++) - { - var arg = args[index]; - string Next() => index + 1 < args.Length ? args[++index] : throw new ArgumentException($"Missing value for {arg}."); - options = arg switch - { - "--splats" => options with { SplatCount = int.Parse(Next()) }, - "--warmup-splat-updates" => options with { WarmupSplatUpdatesPerFrame = int.Parse(Next()) }, - "--splat-updates" => options with { SplatUpdatesPerFrame = int.Parse(Next()) }, - "--warmup" => options with { WarmupFrames = int.Parse(Next()) }, - "--frames" => options with { MeasuredFrames = int.Parse(Next()) }, - "--depth" => options with { Depth = int.Parse(Next()) }, - "--seed" => options with { Seed = ParseUInt32(Next()) }, - "--candidates" => options with { CandidatesPerPass = int.Parse(Next()) }, - "--reservoir-updates" => options with { ReservoirUpdatesPerPass = int.Parse(Next()) }, - "--program-transforms" => options with { ProgramTransformCount = int.Parse(Next()), ProgramMode = 1 }, - "--program-flame" => options with { ProgramFlamePath = Next(), ProgramMode = 2 }, - "--priority-focus" => options with { PriorityFocus = ParseBounds(Next(), "Priority focus") }, - "--adaptive-focus" => options with { AdaptiveFocus = true, VisualParity = true }, - "--readback-splats" => options with { ReadbackSplats = int.Parse(Next()) }, - "--shader" => options with { ShaderPath = Next() }, - "--out" => options with { OutputDirectory = Next() }, - "--flame" => options with { FlamePath = Next() }, - "--reference-ppm" => options with { ReferencePpmPath = Next() }, - "--reference-density-ppm" => options with { ReferenceDensityPpmPath = Next(), VisualParity = true }, - "--histogram-samples" => options with { HistogramSamples = int.Parse(Next()) }, - "--histogram-burn-in" => options with { HistogramBurnIn = int.Parse(Next()) }, - "--histogram-size" => ParseHistogramSize(options, Next()), - "--histogram-bounds" => ParseHistogramBounds(options, Next()), - "--visual-parity" => options with { VisualParity = true }, - "--visual-parity-reference-samples" => options with { VisualParityReferenceSamples = int.Parse(Next()) }, - "--visual-parity-view" => AddVisualParityView(options, Next()), - "--visual-parity-image-dir" => options with { VisualParityImageDirectory = Next() }, - "--visual-parity-image-prefix" => options with { VisualParityImagePrefix = Next() }, - _ => throw new ArgumentException($"Unknown receipt option: {arg}"), - }; - } - - if (options.ReferencePpmPath is not null) - { - if (!File.Exists(options.ReferencePpmPath)) - { - throw new FileNotFoundException("Reference PPM file was not found.", options.ReferencePpmPath); - } - - return options; - } - - if (options.FlamePath is not null) - { - if (!File.Exists(options.FlamePath)) - { - throw new FileNotFoundException("Receipt flame file was not found.", options.FlamePath); - } - - if (options.HistogramSamples <= 0 || options.HistogramBurnIn < 0 || options.HistogramWidth <= 0 || options.HistogramHeight <= 0) - { - throw new ArgumentOutOfRangeException(nameof(args), "Flame histogram samples and dimensions must be positive; burn-in must not be negative."); - } - - return options; - } - - if (options.ProgramFlamePath is not null && !File.Exists(options.ProgramFlamePath)) - { - throw new FileNotFoundException("Receipt program flame file was not found.", options.ProgramFlamePath); - } - - if (options.ReferenceDensityPpmPath is not null && !File.Exists(options.ReferenceDensityPpmPath)) - { - throw new FileNotFoundException("External density reference PPM file was not found.", options.ReferenceDensityPpmPath); - } - - options = options.ProgramFlamePath is not null && options.ProgramTransformCount <= 0 - ? options with { ProgramTransformCount = int.MaxValue, ProgramMode = 2 } - : options; - options = options.ProgramMode == 0 && options.ProgramTransformCount > 0 - ? options with { ProgramMode = 1 } - : options; - - if (!File.Exists(options.ShaderPath)) - { - throw new FileNotFoundException("Receipt shader file was not found.", options.ShaderPath); - } - - if (options.VisualParity && options.ProgramFlamePath is null && options.ReferenceDensityPpmPath is null) - { - throw new ArgumentException("Visual parity requires --program-flame or --reference-density-ppm."); - } - - if (options.AdaptiveFocus && (options.WarmupFrames <= 0 || options.ReadbackSplats <= 0)) - { - throw new ArgumentException("Adaptive focus requires at least one warmup frame and positive readback splats."); - } - - if (options.SplatCount <= 0 || options.WarmupSplatUpdatesPerFrame <= 0 || options.WarmupSplatUpdatesPerFrame > options.SplatCount || options.SplatUpdatesPerFrame <= 0 || options.SplatUpdatesPerFrame > options.SplatCount || options.WarmupFrames < 0 || options.MeasuredFrames <= 0 || options.Depth <= 0 || options.CandidatesPerPass <= 0 || options.ReservoirUpdatesPerPass <= 0 || options.ReservoirUpdatesPerPass > options.SplatCount || options.ProgramTransformCount < 0 || options.ProgramMode < 0 || options.ProgramMode > 2 || options.ReadbackSplats < 0 || options.VisualParityReferenceSamples <= 0) - { - throw new ArgumentOutOfRangeException(nameof(args), "Splats, splat updates, frames, depth, candidates, and reservoir updates must be positive; splat/reservoir updates must not exceed splats; program transforms, warmup, and readback must not be negative."); - } - return options; - } - - private static ReceiptOptions ParseHistogramSize(ReceiptOptions options, string value) - { - var parts = value.Split('x', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - if (parts.Length != 2) - { - throw new ArgumentException("Histogram size must be WIDTHxHEIGHT."); - } - - return options with { HistogramWidth = int.Parse(parts[0]), HistogramHeight = int.Parse(parts[1]) }; - } - - private static ReceiptOptions ParseHistogramBounds(ReceiptOptions options, string value) - { - if (string.Equals(value, "flame-camera", StringComparison.OrdinalIgnoreCase)) - { - if (options.ProgramFlamePath is null) - { - throw new ArgumentException("Histogram bounds 'flame-camera' requires --program-flame to be parsed first."); - } - - return options with { HistogramBounds = LoadFlameCameraBounds(options.ProgramFlamePath) }; - } - - return options with { HistogramBounds = ParseBounds(value, "Histogram bounds") }; - } - - private static Vector4 LoadFlameCameraBounds(string flamePath) - { - var document = XDocument.Load(flamePath); - var flame = document.Descendants("flame").FirstOrDefault() - ?? throw new FormatException("Flame file does not contain a flame element."); - var size = ParseFloatList((string?)flame.Attribute("size"), expectedCount: 2, "flame size"); - var center = ParseOptionalFloatList((string?)flame.Attribute("center"), expectedCount: 2) - ?? [0.0f, 0.0f]; - var scale = ParseRequiredPositiveFloat((string?)flame.Attribute("scale"), "flame scale"); - var zoom = ParseOptionalFloat((string?)flame.Attribute("cam_zoom"), 1.0f); - var width = size[0] / MathF.Max(scale * zoom, 0.000001f); - var height = size[1] / MathF.Max(scale * zoom, 0.000001f); - return new Vector4( - center[0] - width * 0.5f, - center[1] - height * 0.5f, - center[0] + width * 0.5f, - center[1] + height * 0.5f); - } - - private static ReceiptOptions AddVisualParityView(ReceiptOptions options, string value) - { - var separator = value.IndexOf(':', StringComparison.Ordinal); - if (separator <= 0 || separator == value.Length - 1) - { - throw new ArgumentException("Visual parity view must be name:minX,minY,maxX,maxY."); - } - - var name = value[..separator]; - var bounds = ParseBounds(value[(separator + 1)..], "Visual parity view bounds"); - return options with { VisualParityViews = [.. options.VisualParityViews, new VisualParityView(name, bounds)] }; - } - - private static Vector4 ParseBounds(string value, string label) - { - var parts = value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - if (parts.Length != 4) - { - throw new ArgumentException($"{label} must be minX,minY,maxX,maxY."); - } - - return new Vector4( - float.Parse(parts[0], System.Globalization.CultureInfo.InvariantCulture), - float.Parse(parts[1], System.Globalization.CultureInfo.InvariantCulture), - float.Parse(parts[2], System.Globalization.CultureInfo.InvariantCulture), - float.Parse(parts[3], System.Globalization.CultureInfo.InvariantCulture)); - } - - private static float[] ParseFloatList(string? source, int expectedCount, string label) - { - if (string.IsNullOrWhiteSpace(source)) - { - throw new FormatException($"{label} must not be empty."); - } - - var values = source - .Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .Select(value => float.Parse(value, System.Globalization.CultureInfo.InvariantCulture)) - .ToArray(); - if (values.Length != expectedCount) - { - throw new FormatException($"{label} expected {expectedCount} values, got {values.Length}."); - } - - return values; - } - - private static float[]? ParseOptionalFloatList(string? source, int expectedCount) - { - return string.IsNullOrWhiteSpace(source) - ? null - : ParseFloatList(source, expectedCount, "optional float list"); - } - - private static float ParseRequiredPositiveFloat(string? source, string label) - { - if (string.IsNullOrWhiteSpace(source) - || !float.TryParse(source, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var value) - || value <= 0.0f) - { - throw new FormatException($"{label} must be positive."); - } - - return value; - } - - private static float ParseOptionalFloat(string? source, float fallback) - { - return string.IsNullOrWhiteSpace(source) - ? fallback - : float.Parse(source, System.Globalization.CultureInfo.InvariantCulture); - } - - private static uint ParseUInt32(string value) - { - return value.StartsWith("0x", StringComparison.OrdinalIgnoreCase) - ? Convert.ToUInt32(value[2..], 16) - : uint.Parse(value, System.Globalization.CultureInfo.InvariantCulture); - } -} - -internal sealed record FlameHistogramReceipt( - string SourcePath, - string FlameName, - int TransformCount, - int SampleCount, - int BurnIn, - int Width, - int Height, - float[] Bounds, - int HitCount, - int OccupiedBins, - uint Checksum); - -internal sealed record ReferencePpmReceipt( - string SourcePath, - int Width, - int Height, - int MaxChannelValue, - int PixelCount, - int NonBlackPixelCount, - ulong RgbChecksum, - ulong LuminanceChecksum); - -internal sealed record FlameImportReportReceipt( - string SourcePath, - FractalFlameImportReport Report); - -internal readonly record struct VisualParityView(string Name, Vector4 Bounds); - -internal readonly record struct ReferenceDensityImage( - int Width, - int Height, - Vector4 Bounds, - int[] Luminance, - long TotalLuminance) -{ - public FractalPointHistogram ToHistogram(int width, int height, Vector4 viewBounds) - { - var bins = new int[width * height]; - var sourceSpan = new Vector2(Bounds.Z - Bounds.X, Bounds.W - Bounds.Y); - var viewSpan = new Vector2(viewBounds.Z - viewBounds.X, viewBounds.W - viewBounds.Y); - for (var sourceY = 0; sourceY < Height; sourceY++) - { - var worldY = Bounds.Y + ((Height - 0.5f - sourceY) / Math.Max(Height, 1)) * sourceSpan.Y; - var v = (worldY - viewBounds.Y) / MathF.Max(viewSpan.Y, 0.000001f); - if (v < 0.0f || v >= 1.0f) - { - continue; - } - - var targetY = Math.Clamp((int)(v * height), 0, height - 1); - for (var sourceX = 0; sourceX < Width; sourceX++) - { - var value = Luminance[(sourceY * Width) + sourceX]; - if (value == 0) - { - continue; - } - - var worldX = Bounds.X + ((sourceX + 0.5f) / Math.Max(Width, 1)) * sourceSpan.X; - var u = (worldX - viewBounds.X) / MathF.Max(viewSpan.X, 0.000001f); - if (u < 0.0f || u >= 1.0f) - { - continue; - } - - var targetX = Math.Clamp((int)(u * width), 0, width - 1); - bins[(targetY * width) + targetX] += value; - } - } - - return new FractalPointHistogram(width, height, viewBounds, bins); - } -} - -internal sealed record VisualParityReceipt( - string ReferenceSource, - string CandidateSource, - int ComparedSamples, - long ReferenceSamples, - int Width, - int Height, - float[] Bounds, - int ReferenceHitCount, - int GpuHitCount, - int ReferenceOccupiedBins, - int GpuOccupiedBins, - int SharedOccupiedBins, - double OccupancyOverlapPercent, - double L1Distance, - double Rmse, - double CosineSimilarity, - double DistributionScorePercent, - IReadOnlyList Views); - -internal sealed record VisualParityViewReceipt( - string Name, - float[] Bounds, - int ReferenceHitCount, - int GpuHitCount, - int ReferenceOccupiedBins, - int GpuOccupiedBins, - int SharedOccupiedBins, - int StarvedReferenceBins, - double OccupancyOverlapPercent, - double UnderrepresentedMassPercent, - double OversampledMassPercent, - float[] SuggestedPriorityFocus, - double L1Distance, - double Rmse, - double CosineSimilarity, - double DistributionScorePercent); - -internal readonly record struct HistogramComparison( - int ReferenceOccupiedBins, - int GpuOccupiedBins, - int SharedOccupiedBins, - int StarvedReferenceBins, - double OccupancyOverlapPercent, - double UnderrepresentedMassPercent, - double OversampledMassPercent, - double L1Distance, - double Rmse, - double CosineSimilarity, - double DistributionScorePercent); - -internal sealed record GpuFractalSplatReceipt( - string Adapter, - int SplatCount, - int SdfReservoirCount, - int PbrReservoirCount, - int RadiosityReservoirCount, - int FlameStateCount, - int ProgramTransformCount, - int ProgramMode, - Vector4 PriorityFocus, - int WarmupSplatUpdatesPerFrame, - int SplatUpdatesPerFrame, - int CandidatesPerPass, - int ReservoirUpdatesPerPass, - double ReservoirFullCoverageFrames, - int MeasuredFrames, - int BytesPerSplat, - int BytesPerReservoir, - int BytesPerFlameState, - double GpuMillisecondsPerFrame, - double GpuEquivalentFps, - double GpuSplatsPerSecond, - double GpuReservoirCandidatesPerSecond, - double CpuSubmitAndWaitMillisecondsPerFrame, - ulong ReadbackChecksum, - float[]? AdaptivePriorityFocus, - VisualParityReceipt? VisualParity);