Add first fractal DSL compiler
This commit is contained in:
parent
c856689a85
commit
d02533fe22
4 changed files with 315 additions and 2 deletions
|
|
@ -215,14 +215,14 @@ 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.
|
||||
- [ ] Implement operations: `Union`, `Subtract`, `Common`, `Repeat`, `Refine`, `Capture`, `Bind`.
|
||||
- [x] Implement operations: `Union`, `Subtract`, `Common`, `Repeat`, `Refine`, `Capture`, `Bind`.
|
||||
- [ ] Implement operation bounds.
|
||||
- [x] Add flattening compiler to shaped 2D brush packets.
|
||||
- [ ] Add debug dump for authored tree and flattened packets.
|
||||
|
||||
Tests:
|
||||
|
||||
- seeded grammar determinism;
|
||||
- [x] seeded grammar determinism;
|
||||
- stable keys across equivalent expansion;
|
||||
- union/subtract/common bounds;
|
||||
- flattening golden packets;
|
||||
|
|
|
|||
265
src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs
Normal file
265
src/Aquarium.Engine.Fractal/Grammar/FractalDslCompiler.cs
Normal file
|
|
@ -0,0 +1,265 @@
|
|||
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;
|
||||
var claims = new List<AquariumBrushClaim>();
|
||||
|
||||
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 "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]);
|
||||
rootKey = FractalStableKeyBuilder.Child(domainKey, "root");
|
||||
domain = new AquariumFractalDomain(
|
||||
domainKey,
|
||||
AquariumFractalDomainKind.CubeSphereTile,
|
||||
default,
|
||||
new Vector4((float)tile.Face, tile.Level, tile.X, tile.Y),
|
||||
Vector4.Zero);
|
||||
break;
|
||||
case "height":
|
||||
EnsureDomain(domain, lineIndex);
|
||||
EnsureTokenCount(tokens, 12, lineIndex);
|
||||
claims.Add(ParseHeight(tokens, rootKey, lineIndex, claims.Count));
|
||||
break;
|
||||
case "ifs":
|
||||
EnsureDomain(domain, lineIndex);
|
||||
EnsureTokenCount(tokens, 15, lineIndex);
|
||||
AddIfsClaims(tokens, rootKey, lineIndex, claims);
|
||||
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 <face> <level> <x> <y> <path>` line before claims.");
|
||||
}
|
||||
|
||||
return FractalOwnershipTreeBuilder.BuildFlatUnion(domain.Value, rootKey, claims);
|
||||
}
|
||||
|
||||
private static AquariumBrushClaim ParseHeight(string[] tokens, AquariumFractalKey rootKey, int lineIndex, int claimIndex)
|
||||
{
|
||||
var name = tokens[1];
|
||||
return HeightClaim(
|
||||
rootKey,
|
||||
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 void AddIfsClaims(string[] tokens, AquariumFractalKey rootKey, int lineIndex, List<AquariumBrushClaim> 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(rootKey, name, center, radii, levels, branches, childScale, spread, rotationStep, falloff, shapePower, amplitude, seed, tags, claims);
|
||||
}
|
||||
|
||||
private static void EmitIfsLevel(
|
||||
AquariumFractalKey rootKey,
|
||||
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<AquariumBrushClaim> claims)
|
||||
{
|
||||
var level = claims.Count;
|
||||
claims.Add(HeightClaim(rootKey, $"{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(
|
||||
rootKey,
|
||||
name,
|
||||
center + offset,
|
||||
nextRadii,
|
||||
levelsRemaining - 1,
|
||||
branches,
|
||||
childScale,
|
||||
spread,
|
||||
rotationStep,
|
||||
falloff,
|
||||
shapePower,
|
||||
amplitude * childScale,
|
||||
seed + 31 + branch,
|
||||
tags,
|
||||
claims);
|
||||
}
|
||||
}
|
||||
|
||||
private static AquariumBrushClaim HeightClaim(
|
||||
AquariumFractalKey rootKey,
|
||||
string name,
|
||||
int claimIndex,
|
||||
Vector2 center,
|
||||
Vector2 radii,
|
||||
float rotationRadians,
|
||||
float falloff,
|
||||
float shapePower,
|
||||
float amplitude,
|
||||
int seed,
|
||||
string tags)
|
||||
{
|
||||
return new AquariumBrushClaim(
|
||||
FractalStableKeyBuilder.Child(rootKey, $"claim/{claimIndex:0000}/{name}"),
|
||||
rootKey,
|
||||
rootKey,
|
||||
AquariumFractalPayloadKind.Height,
|
||||
center,
|
||||
radii,
|
||||
rotationRadians,
|
||||
falloff,
|
||||
shapePower,
|
||||
amplitude,
|
||||
seed,
|
||||
tags);
|
||||
}
|
||||
|
||||
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 CubeFace ParseFace(string value, int lineIndex)
|
||||
{
|
||||
if (Enum.TryParse<CubeFace>(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;
|
||||
}
|
||||
}
|
||||
|
|
@ -129,3 +129,4 @@
|
|||
{"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"}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,47 @@
|
|||
using Aquarium.Engine.Fractal.Grammar;
|
||||
|
||||
namespace Aquarium.Engine.Fractal.Tests;
|
||||
|
||||
public sealed class FractalDslCompilerTests
|
||||
{
|
||||
[Fact]
|
||||
public void DslCompilesHeightClaimsIntoSemanticTree()
|
||||
{
|
||||
const string source = """
|
||||
tile PositiveZ 0 0 0 zyphos/terrain
|
||||
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(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 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 DslRejectsClaimsBeforeTile()
|
||||
{
|
||||
const string source = "height orphan 0 0 1 1 0 3 1 1 0 tag";
|
||||
|
||||
Assert.Throws<FormatException>(() => FractalDslCompiler.Compile(source));
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue