Expose Aquarium synth patch API

This commit is contained in:
Meta Vens 2026-05-12 06:21:46 +01:00
commit 727bfd0042
17 changed files with 564 additions and 1 deletions

View file

@ -11,6 +11,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aquarium.Engine", "src\Aqua
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}") = "AquariumSynth.Dsl", "..\AquariumSynthCSharp\src\AquariumSynth.Dsl\AquariumSynth.Dsl.csproj", "{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}"
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}"
@ -73,6 +75,18 @@ Global
{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
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Debug|x64.ActiveCfg = Debug|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Debug|x64.Build.0 = Debug|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Debug|x86.ActiveCfg = Debug|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Debug|x86.Build.0 = Debug|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Release|Any CPU.Build.0 = Release|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Release|x64.ActiveCfg = Release|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Release|x64.Build.0 = Release|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.Release|x86.ActiveCfg = Release|Any CPU
{4C3D0CEB-83B9-4A5F-9514-6E07061E5674}.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

View file

@ -4,5 +4,6 @@
<Project Path="src/Aquarium.Engine/Aquarium.Engine.csproj" />
<Project Path="src/Aquarium.Epiphany/Aquarium.Epiphany.csproj" />
<Project Path="src/Aquarium.Sample.Minimal/Aquarium.Sample.Minimal.csproj" />
<Project Path="../AquariumSynthCSharp/src/AquariumSynth.Dsl/AquariumSynth.Dsl.csproj" />
</Folder>
</Solution>

View file

@ -58,6 +58,7 @@ $requiredFiles = @(
"Aquarium.Engine.exe",
"Aquarium.Epiphany.dll",
"Aquarium.Engine.Contracts.dll",
"AquariumSynth.Dsl.dll",
"Assets\Aquarium-Engine-Icon.ico",
"Assets\Fonts\Montserrat[wght].ttf",
"Assets\Fonts\UbuntuSans[wdth,wght].ttf",

View file

@ -1,3 +1,4 @@
using Aquarium.Engine.Audio;
using Aquarium.Engine.Input;
using Aquarium.Engine.Render;
using Aquarium.Engine.Ui;
@ -16,6 +17,8 @@ public interface IAquariumRuntime : IDisposable
AquariumUiDocument Ui { get; }
AquariumSynthDocument Synth { get; }
void Start();
void Update(float deltaSeconds, InputState input);

View file

@ -0,0 +1,40 @@
namespace Aquarium.Engine.Audio;
public sealed class AquariumSynthDocument
{
private readonly List<AquariumSynthPatch> patches = [];
public static AquariumSynthDocument Empty { get; } = new();
public bool Enabled { get; init; } = true;
public float MasterGain { get; init; } = 0.55f;
public IReadOnlyList<AquariumSynthPatch> Patches => patches;
public AquariumSynthDocument Patch(
string id,
string script,
AquariumSynthTrigger trigger,
float gain = 1.0f,
int faustCompileRevision = 0,
string? faustName = null)
{
patches.Add(new AquariumSynthPatch(id, script, trigger, gain, faustCompileRevision, faustName ?? id));
return this;
}
}
public sealed record AquariumSynthPatch(
string Id,
string Script,
AquariumSynthTrigger Trigger,
float Gain = 1.0f,
int FaustCompileRevision = 0,
string FaustName = "aquarium_patch");
public readonly record struct AquariumSynthTrigger(float IntervalSeconds, float PhaseSeconds = 0.0f)
{
public static AquariumSynthTrigger Repeat(float intervalSeconds, float phaseSeconds = 0.0f) =>
new(MathF.Max(0.001f, intervalSeconds), phaseSeconds);
}

View file

@ -8,6 +8,7 @@ public sealed class InputState
private readonly HashSet<KeyCode> pressedKeys = [];
private readonly HashSet<MouseButton> downMouseButtons = [];
private readonly HashSet<MouseButton> pressedMouseButtons = [];
private readonly List<char> textInput = [];
public Vector2 MousePosition { get; private set; }
@ -15,6 +16,8 @@ public sealed class InputState
public float WheelDelta { get; private set; }
public IReadOnlyList<char> TextInput => textInput;
public bool LeftMouseDown => IsMouseDown(MouseButton.Left);
public bool MiddleMouseDown => IsMouseDown(MouseButton.Middle);
@ -35,6 +38,7 @@ public sealed class InputState
WheelDelta = 0.0f;
pressedKeys.Clear();
pressedMouseButtons.Clear();
textInput.Clear();
}
public void SetMousePosition(Vector2 position)
@ -81,6 +85,11 @@ public sealed class InputState
downKeys.Remove(key);
}
}
public void AddTextInput(char value)
{
textInput.Add(value);
}
}
public enum MouseButton
@ -108,4 +117,6 @@ public enum KeyCode
Digit9,
RenderDebugCycle,
DebugUiToggle,
Backspace,
Enter,
}

View file

@ -66,6 +66,12 @@ public sealed class AquariumUiPanelBuilder(List<AquariumUiControl> controls)
controls.Add(new AquariumUiOptions(label, read, write, options, tooltip, isVisible));
return this;
}
public AquariumUiPanelBuilder Text(string label, Func<string> read, Action<string> write, string? tooltip = null, Func<bool>? isVisible = null)
{
controls.Add(new AquariumUiText(label, read, write, tooltip, isVisible));
return this;
}
}
public readonly record struct AquariumUiOption(int Value, string Label);
@ -92,3 +98,6 @@ public sealed record AquariumUiIntSlider(string Label, Func<int> Read, Action<in
public sealed record AquariumUiOptions(string Label, Func<int> Read, Action<int> Write, IReadOnlyList<AquariumUiOption> Options, string? Tooltip = null, Func<bool>? IsVisible = null)
: AquariumUiControl(Label, Tooltip, IsVisible);
public sealed record AquariumUiText(string Label, Func<string> Read, Action<string> Write, string? Tooltip = null, Func<bool>? IsVisible = null)
: AquariumUiControl(Label, Tooltip, IsVisible);

View file

@ -12,6 +12,7 @@
<ItemGroup>
<PackageReference Include="Vortice.Direct2D1" Version="3.8.3" />
<ProjectReference Include="..\Aquarium.Engine.Contracts\Aquarium.Engine.Contracts.csproj" />
<ProjectReference Include="..\..\..\AquariumSynthCSharp\src\AquariumSynth.Dsl\AquariumSynth.Dsl.csproj" />
<PackageReference Include="Vortice.Direct3D11" Version="3.8.3" />
<PackageReference Include="Vortice.Direct3D12" Version="3.8.3" />
<PackageReference Include="Vortice.D3DCompiler" Version="3.8.3" />

View file

@ -1,4 +1,5 @@
using System.Diagnostics;
using Aquarium.Engine.Audio;
using Aquarium.Engine.Input;
using Aquarium.Engine.Platform;
using Aquarium.Engine.Render;
@ -19,6 +20,7 @@ public static class AquariumHost
var iconPath = Path.Combine(AppContext.BaseDirectory, "Assets", "Aquarium-Engine-Icon.ico");
using var window = Win32Window.Create("Aquarium Engine", width, height, input, iconPath, visible: !runtime.Options.Headless);
window.PaintSplash("Aquarium", "Preparing runtime state");
using var synthHost = new AquariumSynthHost();
using var renderer = CreateRenderer(
window.Handle,
window.ClientWidth,
@ -51,6 +53,7 @@ public static class AquariumHost
ApplyRendererDebugInput(renderer, input);
SyncRendererSettingsToRuntime(renderer, runtimeLoader.Runtime);
runtimeLoader.Update(deltaSeconds, input);
synthHost.Update(runtimeLoader.Runtime.Synth, deltaSeconds);
if (!ReferenceEquals(settingsRuntime, runtimeLoader.Runtime))
{
settingsRuntime = runtimeLoader.Runtime;

View file

@ -0,0 +1,327 @@
using System.Runtime.InteropServices;
using Aquarium.Engine.Audio;
using AquariumSynth.Dsl;
namespace Aquarium.Engine.Audio;
internal sealed class AquariumSynthHost : IDisposable
{
private const int SampleRate = 44100;
private const int ChannelCount = 1;
private const int BitsPerSample = 16;
private const int MaxPlayingSounds = 16;
private readonly Dictionary<string, CachedSound> cache = new(StringComparer.Ordinal);
private readonly Dictionary<string, int> faustCompileRevisions = new(StringComparer.Ordinal);
private readonly List<PlayingSound> playing = [];
private float timeSeconds;
public void Update(AquariumSynthDocument synth, float deltaSeconds)
{
timeSeconds += Math.Max(deltaSeconds, 0.0f);
if (!synth.Enabled)
{
return;
}
foreach (var patch in synth.Patches)
{
RequestFaustCompileIfNeeded(patch);
if (ShouldTrigger(patch.Trigger, timeSeconds - deltaSeconds, timeSeconds))
{
Play(patch, synth.MasterGain);
}
}
}
private void RequestFaustCompileIfNeeded(AquariumSynthPatch patch)
{
if (patch.FaustCompileRevision <= 0)
{
return;
}
if (faustCompileRevisions.TryGetValue(patch.Id, out var revision) && revision >= patch.FaustCompileRevision)
{
return;
}
faustCompileRevisions[patch.Id] = patch.FaustCompileRevision;
var script = patch.Script;
var patchId = patch.Id;
var faustName = patch.FaustName;
_ = Task.Run(async () =>
{
try
{
var export = FaustEmitter.EmitScript(script, new FaustExportOptions(SafeFaustName(faustName)));
var outputRoot = Path.Combine(AppContext.BaseDirectory, "Synth");
Directory.CreateDirectory(outputRoot);
var dspPath = Path.Combine(outputRoot, $"{SafeFileName(patchId)}.dsp");
var csharpPath = Path.Combine(outputRoot, $"{SafeFileName(patchId)}.cs");
await File.WriteAllTextAsync(dspPath, export.Source);
var validation = await FaustCompiler.CompileAsync(
export.Source,
new FaustCompileOptions(FaustTargetLanguage.CSharp, csharpPath));
if (validation is null)
{
Console.WriteLine($"Aquarium synth patch `{patchId}` exported Faust DSP; Faust compiler not found.");
}
else if (validation.Success)
{
Console.WriteLine($"Aquarium synth patch `{patchId}` compiled Faust C# output.");
}
else
{
Console.WriteLine($"Aquarium synth patch `{patchId}` Faust compile failed: {validation.Stderr}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Aquarium synth patch `{patchId}` Faust export failed: {ex.Message}");
}
});
}
private bool ShouldTrigger(AquariumSynthTrigger trigger, float previousTime, float currentTime)
{
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 void Play(AquariumSynthPatch patch, float masterGain)
{
var sound = GetSound(patch, masterGain);
if (sound.Bytes.Length == 0)
{
return;
}
while (playing.Count >= MaxPlayingSounds)
{
playing[0].Dispose();
playing.RemoveAt(0);
}
var instance = new PlayingSound(sound.Bytes);
playing.Add(instance);
instance.Play();
}
private CachedSound GetSound(AquariumSynthPatch patch, float masterGain)
{
var cacheKey = $"{patch.Id}:{patch.Gain}:{masterGain}:{patch.Script}";
if (cache.TryGetValue(cacheKey, out var cached))
{
return cached;
}
try
{
var synthPatch = PatchScript.Parse(patch.Script);
var samples = SynthPatchRenderer.Render(synthPatch, patch.Gain * masterGain, SampleRate);
cached = new CachedSound(WriteWav(samples));
}
catch (Exception ex)
{
Console.WriteLine($"Aquarium synth patch `{patch.Id}` failed: {ex.Message}");
cached = new CachedSound([]);
}
cache[cacheKey] = cached;
return cached;
}
private static byte[] WriteWav(ReadOnlySpan<float> samples)
{
var dataBytes = checked(samples.Length * sizeof(short));
using var stream = new MemoryStream(44 + dataBytes);
using var writer = new BinaryWriter(stream);
writer.Write("RIFF"u8);
writer.Write(36 + dataBytes);
writer.Write("WAVE"u8);
writer.Write("fmt "u8);
writer.Write(16);
writer.Write((short)1);
writer.Write((short)ChannelCount);
writer.Write(SampleRate);
writer.Write(SampleRate * ChannelCount * BitsPerSample / 8);
writer.Write((short)(ChannelCount * BitsPerSample / 8));
writer.Write((short)BitsPerSample);
writer.Write("data"u8);
writer.Write(dataBytes);
foreach (var sample in samples)
{
writer.Write((short)Math.Clamp(sample * short.MaxValue, short.MinValue, short.MaxValue));
}
return stream.ToArray();
}
private static string SafeFaustName(string value)
{
var chars = value.Select(ch => char.IsLetterOrDigit(ch) ? ch : '_').ToArray();
var name = new string(chars).Trim('_');
return string.IsNullOrWhiteSpace(name) ? "aquarium_patch" : name;
}
private static string SafeFileName(string value)
{
var invalid = Path.GetInvalidFileNameChars().ToHashSet();
var chars = value.Select(ch => invalid.Contains(ch) ? '_' : ch).ToArray();
var name = new string(chars).Trim();
return string.IsNullOrWhiteSpace(name) ? "aquarium_patch" : name;
}
public void Dispose()
{
foreach (var sound in playing)
{
sound.Dispose();
}
playing.Clear();
}
private sealed record CachedSound(byte[] Bytes);
private sealed class PlayingSound : IDisposable
{
private readonly GCHandle handle;
public PlayingSound(byte[] bytes)
{
handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
}
public void Play()
{
_ = PlaySound(handle.AddrOfPinnedObject(), IntPtr.Zero, PlaySoundFlags.Memory | PlaySoundFlags.Async | PlaySoundFlags.NoDefault);
}
public void Dispose()
{
if (handle.IsAllocated)
{
handle.Free();
}
}
}
[Flags]
private enum PlaySoundFlags : uint
{
Async = 0x0001,
Memory = 0x0004,
NoDefault = 0x0002,
}
[DllImport("winmm.dll", SetLastError = true)]
private static extern bool PlaySound(IntPtr pszSound, IntPtr hmod, PlaySoundFlags fdwSound);
}
internal static class SynthPatchRenderer
{
public static float[] Render(SynthPatch patch, float gain, int sampleRate)
{
var duration = patch.Voices.Count == 0
? 0.0f
: patch.Voices.Max(voice => voice.Envelope.DurationSeconds + 0.08f);
duration = Math.Clamp(duration, 0.05f, 3.0f);
var samples = new float[(int)MathF.Ceiling(duration * sampleRate)];
var random = new Random(1337);
for (var index = 0; index < samples.Length; index++)
{
var t = index / (float)sampleRate;
var value = 0.0f;
foreach (var voice in patch.Voices)
{
value += RenderVoice(voice, t, random);
}
value *= patch.Gain * gain;
samples[index] = patch.SoftClip ? MathF.Tanh(value * 1.35f) : Math.Clamp(value, -1.0f, 1.0f);
}
return samples;
}
private static float RenderVoice(Voice voice, float timeSeconds, Random random)
{
var envelope = EnvelopeAt(voice.Envelope, timeSeconds);
if (envelope <= 0.0f)
{
return 0.0f;
}
var frequency = MathF.Max(
voice.Pitch.MinFrequencyHz,
voice.Oscillator.FrequencyHz * MathF.Pow(2.0f, voice.Pitch.RampPerSecond * timeSeconds + 0.5f * voice.Pitch.DeltaRampPerSecond * timeSeconds * timeSeconds));
if (voice.Pitch.VibratoDepth > 0.0f && timeSeconds >= voice.Pitch.VibratoDelaySeconds)
{
frequency *= 1.0f + MathF.Sin(MathF.Tau * (timeSeconds - voice.Pitch.VibratoDelaySeconds) * voice.Pitch.VibratoHz) * voice.Pitch.VibratoDepth;
}
if (voice.Arpeggio is { } arpeggio && timeSeconds >= arpeggio.DelaySeconds)
{
frequency *= arpeggio.Multiplier;
}
var phase = Frac(timeSeconds * frequency + voice.Oscillator.Phase);
var value = voice.Oscillator.Waveform switch
{
Waveform.Sine => MathF.Sin(MathF.Tau * phase),
Waveform.Square => phase < voice.Oscillator.Duty ? -0.5f : 0.5f,
Waveform.Sawtooth => phase * 2.0f - 1.0f,
Waveform.Triangle => 1.0f - 4.0f * MathF.Abs(phase - 0.5f),
Waveform.Noise => random.NextSingle() * 2.0f - 1.0f,
_ => 0.0f,
};
if (voice.Color.TremoloDepth > 0.0f && voice.Color.TremoloHz > 0.0f)
{
value *= 1.0f - Math.Clamp(voice.Color.TremoloDepth, 0.0f, 1.0f) * (0.5f + 0.5f * MathF.Sin(MathF.Tau * voice.Color.TremoloHz * timeSeconds));
}
var drive = Math.Clamp(voice.Color.Drive, 0.0f, 1.0f);
if (drive > 0.0f)
{
var amount = 1.0f + drive * 12.0f;
value = MathF.Tanh(value * amount) / MathF.Tanh(amount);
}
return value * envelope * voice.Gain;
}
private static float EnvelopeAt(Envelope envelope, float timeSeconds)
{
if (timeSeconds < 0.0f)
{
return 0.0f;
}
if (envelope.AttackSeconds > 0.0f && timeSeconds < envelope.AttackSeconds)
{
return timeSeconds / envelope.AttackSeconds;
}
var sustainStart = envelope.AttackSeconds;
if (timeSeconds < sustainStart + envelope.SustainSeconds)
{
var sustainT = envelope.SustainSeconds <= 0.0f ? 1.0f : (timeSeconds - sustainStart) / envelope.SustainSeconds;
return 1.0f + (1.0f - sustainT) * 2.0f * envelope.Punch;
}
var decayStart = sustainStart + envelope.SustainSeconds;
if (timeSeconds < decayStart + envelope.DecaySeconds)
{
return 1.0f - (timeSeconds - decayStart) / MathF.Max(envelope.DecaySeconds, 0.0001f);
}
return 0.0f;
}
private static float Frac(float value) => value - MathF.Floor(value);
}

View file

@ -11,6 +11,7 @@ public sealed class Win32Window : IDisposable
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;
@ -62,6 +63,8 @@ public sealed class Win32Window : IDisposable
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_RETURN = 0x0D;
private const int WHEEL_DELTA = 120;
private readonly WndProc windowProcedure;
@ -159,6 +162,9 @@ public sealed class Win32Window : IDisposable
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);
@ -685,6 +691,21 @@ public sealed class Win32Window : IDisposable
case VK_F2:
input.SetKey(KeyCode.DebugUiToggle, isDown);
break;
case VK_BACK:
input.SetKey(KeyCode.Backspace, isDown);
break;
case VK_RETURN:
input.SetKey(KeyCode.Enter, 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);
}
}

View file

@ -31,6 +31,7 @@ internal sealed class DebugUi
private readonly float panelWidth;
private int? activeSliderId;
private int? activeControlId;
private int? focusedTextId;
private bool closeButtonHovered;
private bool closeButtonActive;
private Rect panelBounds;
@ -101,6 +102,9 @@ internal sealed class DebugUi
options.Tooltip,
() => options.Visible));
break;
case AquariumUiText text:
controls.Add(new TextControl(text.Label, text.Read, text.Write, text.Tooltip, () => text.Visible));
break;
}
}
@ -115,6 +119,7 @@ internal sealed class DebugUi
{
WantsMouse = false;
activeSliderId = null;
focusedTextId = null;
return;
}
@ -148,16 +153,19 @@ internal sealed class DebugUi
if (!input.IsMousePressed(MouseButton.Left))
{
ApplyTextInput(input);
return;
}
if (closeButtonHovered)
{
IsVisible = false;
focusedTextId = null;
return;
}
DebugUiControl? clickedControl = null;
focusedTextId = null;
for (var index = controls.Count - 1; index >= 0; index--)
{
var control = controls[index];
@ -174,6 +182,11 @@ internal sealed class DebugUi
control.Click(mousePosition);
activeControlId = control.Id;
control.IsActive = true;
if (control is TextControl)
{
focusedTextId = control.Id;
}
if (control is SliderControl slider)
{
activeSliderId = slider.Id;
@ -191,6 +204,21 @@ internal sealed class DebugUi
control.DismissTransientState();
}
}
ApplyTextInput(input);
}
private void ApplyTextInput(InputState input)
{
if (focusedTextId is not { } textId)
{
return;
}
if (controls.FirstOrDefault(control => control.Id == textId) is TextControl textControl)
{
textControl.ApplyTextInput(input);
}
}
public void Draw(
@ -399,6 +427,12 @@ internal sealed class DebugUi
controls.Add(new OptionControl(label, read, write, options, tooltip, isVisible));
return this;
}
public DebugUiPanel Text(string label, Func<string> read, Action<string> write, string? tooltip = null, Func<bool>? isVisible = null)
{
controls.Add(new TextControl(label, read, write, tooltip, isVisible));
return this;
}
}
public readonly record struct DebugUiOption(int Value, string Label);
@ -705,6 +739,71 @@ internal sealed class DebugUi
}
}
private sealed class TextControl(string label, Func<string> read, Action<string> write, string? tooltip, Func<bool>? isVisible)
: DebugUiControl(label, tooltip, isVisible)
{
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 override void Draw(
ID2D1RenderTarget target,
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 abstract class SliderControl(string label, string? tooltip, Func<bool>? isVisible) : DebugUiControl(label, tooltip, isVisible)
{
private const float ThumbRadius = 4.0f;

View file

@ -1,5 +1,6 @@
using System.Numerics;
using Aquarium.Engine;
using Aquarium.Engine.Audio;
using Aquarium.Engine.Input;
using Aquarium.Engine.Render;
using Aquarium.Engine.Ui;
@ -22,6 +23,9 @@ public sealed class AquariumRuntime : IAquariumRuntime
private float secondsSinceStateSave;
private bool graphicsSettingsDirty;
private bool timePaused;
private string patchScript = "v w=sin f=440 g=.18 a=.002 s=.05 d=.35 pu=.28;v w=tri f=880 g=.04 s=.03 d=.28";
private int patchRate = 4;
private int faustCompileRevision;
public AquariumRuntime(AquariumRuntimeOptions options)
{
@ -48,7 +52,11 @@ public sealed class AquariumRuntime : IAquariumRuntime
.Section("Runtime")
.Toggle("Pause Time", () => timePaused, value => timePaused = value, "Stops Epiphany simulation time while leaving the renderer alive.")
.Slider("Time", () => timeSeconds, value => timeSeconds = MathF.Max(0.0f, value), 0.0f, 720.0f, "0.0", "Scrubs Epiphany simulation time.")
.Button("Flush State", FlushState, "Writes current Epiphany runtime state to CultCache."));
.Button("Flush State", FlushState, "Writes current Epiphany runtime state to CultCache.")
.Section("Synth")
.Text("Patch", () => patchScript, value => patchScript = value, "Aquarium patch DSL. Enter inserts ';'.")
.Slider("Rate", () => patchRate, value => patchRate = Math.Clamp(value, 1, 12), 1, 12, "Triggers per 16 seconds.")
.Button("Compile Faust", () => faustCompileRevision++, "Exports Faust DSP and compiles C# output when Faust is installed."));
}
public AquariumRuntimeOptions Options { get; }
@ -57,6 +65,18 @@ public sealed class AquariumRuntime : IAquariumRuntime
public AquariumUiDocument Ui { get; }
public AquariumSynthDocument Synth => new AquariumSynthDocument
{
MasterGain = 0.42f,
Enabled = true
}.Patch(
"epiphany-editor",
patchScript,
AquariumSynthTrigger.Repeat(16.0f / Math.Max(patchRate, 1)),
1.0f,
faustCompileRevision,
"epiphany_editor");
public AquariumFrame Frame => new(ViewFrame, cameraRig.Position, timeSeconds);
public GraphicsSettings GraphicsSettings

View file

@ -1,5 +1,6 @@
using System.Numerics;
using Aquarium.Engine;
using Aquarium.Engine.Audio;
using Aquarium.Engine.Input;
using Aquarium.Engine.Render;
using Aquarium.Engine.Ui;
@ -18,6 +19,8 @@ public sealed class MinimalRuntime : IAquariumRuntime
public AquariumUiDocument Ui { get; } = AquariumUiDocument.Empty;
public AquariumSynthDocument Synth { get; } = AquariumSynthDocument.Empty;
public AquariumFrame Frame => new(
new ViewFrame(Vector2.Zero, 24.0f),
new Vector3(0.0f, -10.0f, 7.0f),

View file

@ -54,3 +54,4 @@
{"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-12T06:15:00+01:00","topic":"synth-composition-contract","lesson":"Aquarium synth integration should mirror the UI boundary: clients declare patch scripts and trigger policy through AquariumSynthDocument, while Aquarium.Engine hosts preview playback and Faust export/compile requests. The current editor sound path is intentionally a pre-rendered preview; optimized realtime Faust DSP loading remains a separate engine-hosting pass, not something to smuggle into the DSL or client.","files":["src/Aquarium.Engine.Contracts/Audio/AquariumSynth.cs","src/Aquarium.Engine/Audio/AquariumSynthHost.cs","src/Aquarium.Epiphany/AquariumRuntime.cs","state/memory.json"],"source":"synth API integration pass"}

View file

@ -22,6 +22,7 @@ current_model:
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
runtime_loader: src/Aquarium.Engine/Runtime/ClientRuntimeLoader.cs
dev_reload: scripts/dev-reload.ps1
dev_watch: scripts/dev-watch.ps1
@ -39,6 +40,7 @@ current_model:
dependencies:
cult_math: E:\Projects\CultMath
cult_lib: E:\Projects\CultLib
aquarium_synth_dsl: E:\Projects\AquariumSynthCSharp\src\AquariumSynth.Dsl
docs:
doctrine: docs/aquarium-engine-doctrine.md
engine_client_boundary: docs/engine-client-boundary.md
@ -76,6 +78,7 @@ renderer_state:
- 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 debug UI panel with code-first controls bound to renderer state.
- AquariumSynthDocument exposes client-declared patch scripts, trigger cadence, gain, and Faust compile revision; Aquarium.Engine hosts editor preview playback and writes Faust DSP/generated output when requested.
- 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.
- Bundled blue-noise texture assets are retained for future dithering/noise work even though the removed medium path no longer samples them.
@ -94,6 +97,7 @@ next_actions:
- 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.
- Grow renderer debug controls through the Direct2D/DirectWrite overlay path.
- Replace synth preview playback with generated Faust DSP loading when the optimized realtime host is ready.
- Follow research/rendering/hdr-pbr-presentation.md before changing HDR exposure, bloom, tonemapping, or display transforms.
- Follow docs/tsr-inspired-taa-spec.md when changing current temporal diagnostics.
- Promote future runtime knobs into typed CultCache documents before they become process folklore.

View file

@ -73,6 +73,11 @@
"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.Engine.Contracts exposes AquariumSynthDocument as the client-facing synth composition surface. Clients declare patch scripts, trigger cadence, gain, and Faust compile revision; Aquarium.Engine owns patch preview playback, Faust DSP export, and eventual optimized DSP hosting.",
"AquariumSynth.Dsl is the patch language dependency. Keep the DSL parser and Faust emitter in the synth library; Aquarium should host and schedule patches through contracts rather than baking client sound policy into the engine.",
"Current Aquarium synth playback is a pre-rendered preview path for editor experimentation. Faust export and compile requests write DSP and generated output when Faust is installed, but generated realtime DSP loading is still the next optimization pass. Do not overclaim it as complete."
],
"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.",