Delegate synth rendering to AquaSynth
This commit is contained in:
parent
3d0d4b0080
commit
dcd38a0e64
13 changed files with 51 additions and 475 deletions
|
|
@ -35,8 +35,8 @@ 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 `AquariumSynth.Dsl` from the repo-local `packages` NuGet feed,
|
||||
not as a live project reference to `AquariumSynthCSharp`. This keeps Aquarium
|
||||
Aquarium consumes `AquaSynth.Dsl` from the repo-local `packages` NuGet feed,
|
||||
not as a live project reference to `AquaSynth`. 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:
|
||||
|
|
|
|||
BIN
packages/AquaSynth.Dsl.0.1.0-aquasynth.1.nupkg
Normal file
BIN
packages/AquaSynth.Dsl.0.1.0-aquasynth.1.nupkg
Normal file
Binary file not shown.
Binary file not shown.
|
|
@ -60,7 +60,7 @@ $requiredFiles = @(
|
|||
"Aquarium.Engine.exe",
|
||||
"Aquarium.Epiphany.dll",
|
||||
"Aquarium.Engine.Contracts.dll",
|
||||
"AquariumSynth.Dsl.dll",
|
||||
"AquaSynth.Dsl.dll",
|
||||
"Tools\Faust\lib\faust.dll",
|
||||
"Tools\Faust\share\faust\stdfaust.lib",
|
||||
"Assets\Aquarium-Engine-Icon.ico",
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ $ErrorActionPreference = "Stop"
|
|||
Set-StrictMode -Version Latest
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($SourceRoot)) {
|
||||
$SourceRoot = if ($env:AQUARIUM_FAUST_HOME) { $env:AQUARIUM_FAUST_HOME } else { "C:\Program Files\Faust" }
|
||||
$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)) {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
param(
|
||||
[string]$SynthRepo = "E:\Projects\AquariumSynthCSharp",
|
||||
[string]$SynthRepo = "E:\Projects\AquaSynth",
|
||||
[string]$Configuration = "Release"
|
||||
)
|
||||
|
||||
|
|
@ -7,14 +7,14 @@ $ErrorActionPreference = "Stop"
|
|||
|
||||
$root = Resolve-Path (Join-Path $PSScriptRoot "..")
|
||||
$feed = Join-Path $root "packages"
|
||||
$project = Join-Path $SynthRepo "src\AquariumSynth.Dsl\AquariumSynth.Dsl.csproj"
|
||||
$project = Join-Path $SynthRepo "src\AquaSynth.Dsl\AquaSynth.Dsl.csproj"
|
||||
|
||||
if (-not (Test-Path $project)) {
|
||||
throw "AquariumSynth.Dsl project not found at $project"
|
||||
throw "AquaSynth.Dsl project not found at $project"
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $feed | Out-Null
|
||||
dotnet pack $project -c $Configuration -o $feed
|
||||
|
||||
Write-Host "Packed AquariumSynth.Dsl into $feed"
|
||||
Write-Host "Packed AquaSynth.Dsl into $feed"
|
||||
Write-Host "If the package version changed, update src\Aquarium.Engine\Aquarium.Engine.csproj to match."
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Vortice.Direct2D1" Version="3.8.3" />
|
||||
<PackageReference Include="AquariumSynth.Dsl" Version="0.1.0-aquarium.1" />
|
||||
<PackageReference Include="AquaSynth.Dsl" Version="0.1.0-aquasynth.1" />
|
||||
<ProjectReference Include="..\Aquarium.Engine.Contracts\Aquarium.Engine.Contracts.csproj" />
|
||||
<PackageReference Include="Vortice.Direct3D11" Version="3.8.3" />
|
||||
<PackageReference Include="Vortice.Direct3D12" Version="3.8.3" />
|
||||
|
|
|
|||
|
|
@ -1,49 +1,21 @@
|
|||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Aquarium.Engine.Audio;
|
||||
using AquariumSynth.Dsl;
|
||||
using AquaSynth.Dsl;
|
||||
|
||||
namespace Aquarium.Engine.Audio;
|
||||
|
||||
internal sealed class AquariumSynthHost : IDisposable
|
||||
{
|
||||
private const int SampleRate = 44100;
|
||||
private const float CompileDebounceSeconds = 0.75f;
|
||||
|
||||
private readonly Dictionary<string, PatchRuntime> patches = new(StringComparer.Ordinal);
|
||||
private readonly WasapiAudioDevice audioDevice = new();
|
||||
private FaustNative? faust;
|
||||
private AquaSynthNativeCompiler? compiler;
|
||||
private string? faustLoadError;
|
||||
private float timeSeconds;
|
||||
|
||||
internal static bool TryRenderScriptWithNativeFaust(string name, string script, float gain, out float[] samples, out string? error)
|
||||
{
|
||||
samples = [];
|
||||
if (!FaustNative.TryLoad(out var native, out var loadError))
|
||||
{
|
||||
error = loadError;
|
||||
return false;
|
||||
}
|
||||
|
||||
using (native)
|
||||
{
|
||||
try
|
||||
{
|
||||
var patch = PatchScript.Parse(script);
|
||||
var export = FaustEmitter.Emit(patch, new FaustExportOptions(SafeFaustName(name)));
|
||||
using var compiled = native!.Compile(SafeFaustName(name), export.Source, EstimateDuration(patch));
|
||||
samples = compiled.Render(gain);
|
||||
error = null;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
var options = new AquaSynthNativeOptions(DspSourceDirectory: Path.Combine(AppContext.BaseDirectory, "Synth"));
|
||||
return AquaSynthNativeCompiler.TryRenderScript(name, script, gain, out samples, out error, options);
|
||||
}
|
||||
|
||||
public void Update(AquariumSynthDocument synth, float deltaSeconds)
|
||||
|
|
@ -58,7 +30,6 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
foreach (var patch in synth.Patches)
|
||||
{
|
||||
var runtime = GetRuntime(patch);
|
||||
runtime.StatusSink = patch.StatusSink;
|
||||
UpdatePatch(runtime, patch);
|
||||
PublishStatus(runtime, patch);
|
||||
var pendingFireReady = false;
|
||||
|
|
@ -97,7 +68,8 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
|
||||
private void UpdatePatch(PatchRuntime runtime, AquariumSynthPatch patch)
|
||||
{
|
||||
var desiredKey = CompileKey(patch);
|
||||
var identity = Identity(patch);
|
||||
var desiredKey = identity.CompileKey;
|
||||
if (runtime.DesiredKey != desiredKey)
|
||||
{
|
||||
runtime.DesiredKey = desiredKey;
|
||||
|
|
@ -119,33 +91,32 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
return;
|
||||
}
|
||||
|
||||
if (faust is null)
|
||||
if (compiler is null)
|
||||
{
|
||||
runtime.FailedKey = desiredKey;
|
||||
SetStatus(runtime, AquariumSynthPatchCompileState.Failed, faustLoadError ?? "bundled Faust toolchain not found", patch.FaustCompileRevision);
|
||||
SetStatus(runtime, AquariumSynthPatchCompileState.Failed, faustLoadError ?? "AquaSynth Faust toolchain not found", patch.FaustCompileRevision);
|
||||
return;
|
||||
}
|
||||
|
||||
StartCompile(runtime, patch, desiredKey, faust);
|
||||
StartCompile(runtime, patch, identity, desiredKey, compiler);
|
||||
}
|
||||
|
||||
private void StartCompile(PatchRuntime runtime, AquariumSynthPatch patch, string compileKey, FaustNative compiler)
|
||||
private void StartCompile(
|
||||
PatchRuntime runtime,
|
||||
AquariumSynthPatch patch,
|
||||
AquaSynthCompileIdentity identity,
|
||||
string compileKey,
|
||||
AquaSynthNativeCompiler activeCompiler)
|
||||
{
|
||||
SetStatus(runtime, AquariumSynthPatchCompileState.Compiling, "compiling Faust DSP", patch.FaustCompileRevision);
|
||||
var script = patch.Script;
|
||||
SetStatus(runtime, AquariumSynthPatchCompileState.Compiling, "compiling AquaSynth DSP", patch.FaustCompileRevision);
|
||||
var patchId = patch.Id;
|
||||
var patchName = SafeFaustName(patch.FaustName);
|
||||
var revision = patch.FaustCompileRevision;
|
||||
|
||||
runtime.CompileTask = Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var export = FaustEmitter.EmitScript(script, new FaustExportOptions(patchName));
|
||||
WriteDspSource(patchId, export.Source);
|
||||
var synthPatch = PatchScript.Parse(script);
|
||||
var duration = EstimateDuration(synthPatch);
|
||||
var compiled = compiler.Compile(patchName, export.Source, duration);
|
||||
var compiled = activeCompiler.CompileScript(identity);
|
||||
lock (runtime.Sync)
|
||||
{
|
||||
runtime.Compiled?.Dispose();
|
||||
|
|
@ -154,10 +125,10 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
runtime.FailedKey = "";
|
||||
runtime.SoundCache.Clear();
|
||||
runtime.CompileTask = null;
|
||||
runtime.SetStatus(AquariumSynthPatchCompileState.Ready, $"ready in {compiled.CompileMilliseconds:0} ms", revision, timeSeconds);
|
||||
runtime.SetStatus(AquariumSynthPatchCompileState.Ready, $"ready in {compiled.Manifest.CompileMilliseconds:0} ms", revision, timeSeconds);
|
||||
}
|
||||
|
||||
Console.WriteLine($"Aquarium synth patch `{patchId}` compiled with Faust in {compiled.CompileMilliseconds:0} ms.");
|
||||
Console.WriteLine($"Aquarium synth patch `{patchId}` compiled by AquaSynth in {compiled.Manifest.CompileMilliseconds:0} ms.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -172,7 +143,7 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
runtime.SetStatus(AquariumSynthPatchCompileState.Failed, ex.Message, revision, timeSeconds);
|
||||
}
|
||||
|
||||
Console.WriteLine($"Aquarium synth patch `{patchId}` Faust compile failed: {ex.Message}");
|
||||
Console.WriteLine($"Aquarium synth patch `{patchId}` AquaSynth compile failed: {ex.Message}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -180,6 +151,7 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
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)
|
||||
|
|
@ -188,6 +160,7 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
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))
|
||||
|
|
@ -202,25 +175,26 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
return;
|
||||
}
|
||||
|
||||
audioDevice.Play(sound.Samples, SampleRate);
|
||||
audioDevice.Play(sound.Samples, sampleRate);
|
||||
}
|
||||
|
||||
private void EnsureFaustLoaded()
|
||||
{
|
||||
if (faust is not null || faustLoadError is not null)
|
||||
if (compiler is not null || faustLoadError is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (FaustNative.TryLoad(out var loaded, out var error))
|
||||
var options = new AquaSynthNativeOptions(DspSourceDirectory: Path.Combine(AppContext.BaseDirectory, "Synth"));
|
||||
if (AquaSynthNativeCompiler.TryLoad(out var loaded, out var error, options))
|
||||
{
|
||||
faust = loaded;
|
||||
Console.WriteLine($"Aquarium Faust toolchain loaded: {loaded!.Version}");
|
||||
compiler = loaded;
|
||||
Console.WriteLine($"Aquarium AquaSynth Faust toolchain loaded: {loaded!.FaustVersion}");
|
||||
}
|
||||
else
|
||||
{
|
||||
faustLoadError = error;
|
||||
Console.WriteLine($"Aquarium Faust toolchain unavailable: {error}");
|
||||
Console.WriteLine($"Aquarium AquaSynth Faust toolchain unavailable: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -262,41 +236,8 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
return currentBeat > previousBeat;
|
||||
}
|
||||
|
||||
private static float EstimateDuration(SynthPatch patch)
|
||||
{
|
||||
var duration = patch.Voices.Count == 0
|
||||
? 0.05f
|
||||
: patch.Voices.Max(voice => voice.Envelope.DurationSeconds + 0.08f);
|
||||
return Math.Clamp(duration, 0.05f, 3.0f);
|
||||
}
|
||||
|
||||
private static void WriteDspSource(string patchId, string source)
|
||||
{
|
||||
var outputRoot = Path.Combine(AppContext.BaseDirectory, "Synth");
|
||||
Directory.CreateDirectory(outputRoot);
|
||||
File.WriteAllText(Path.Combine(outputRoot, $"{SafeFileName(patchId)}.dsp"), source);
|
||||
}
|
||||
|
||||
private static string CompileKey(AquariumSynthPatch patch)
|
||||
{
|
||||
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes($"{patch.FaustCompileRevision}\n{patch.FaustName}\n{patch.Script}"));
|
||||
return Convert.ToHexString(bytes);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
private static AquaSynthCompileIdentity Identity(AquariumSynthPatch patch) =>
|
||||
new(patch.Id, patch.FaustName, patch.Script, patch.FaustCompileRevision);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
|
|
@ -316,7 +257,7 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
}
|
||||
|
||||
audioDevice.Dispose();
|
||||
faust?.Dispose();
|
||||
compiler?.Dispose();
|
||||
}
|
||||
|
||||
private sealed class PatchRuntime(string id)
|
||||
|
|
@ -327,11 +268,10 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
public string ReadyKey { get; set; } = "";
|
||||
public string FailedKey { get; set; } = "";
|
||||
public float ScriptChangedAt { get; set; }
|
||||
public CompiledFaustPatch? Compiled { get; set; }
|
||||
public AquaSynthCompiledPatch? Compiled { get; set; }
|
||||
public Task? CompileTask { get; set; }
|
||||
public int LastFireRevision { get; set; }
|
||||
public bool PendingFire { get; set; }
|
||||
public Action<AquariumSynthPatchStatus>? StatusSink { get; set; }
|
||||
public AquariumSynthPatchCompileState State => Status.State;
|
||||
public AquariumSynthPatchStatus Status { get; private set; } = new(id, AquariumSynthPatchCompileState.Idle, "idle", 0, 0.0);
|
||||
|
||||
|
|
@ -342,369 +282,4 @@ internal sealed class AquariumSynthHost : IDisposable
|
|||
}
|
||||
|
||||
private sealed record CachedSound(float[] Samples);
|
||||
|
||||
private sealed class CompiledFaustPatch : IDisposable
|
||||
{
|
||||
private readonly FaustNative native;
|
||||
private readonly IntPtr factory;
|
||||
private readonly int outputCount;
|
||||
private readonly int frameCount;
|
||||
private bool disposed;
|
||||
|
||||
public CompiledFaustPatch(FaustNative native, IntPtr factory, int outputCount, int frameCount, double compileMilliseconds)
|
||||
{
|
||||
this.native = native;
|
||||
this.factory = factory;
|
||||
this.outputCount = Math.Max(outputCount, 1);
|
||||
this.frameCount = Math.Max(frameCount, 1);
|
||||
CompileMilliseconds = compileMilliseconds;
|
||||
}
|
||||
|
||||
public double CompileMilliseconds { get; }
|
||||
|
||||
public float[] Render(float gain)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
var dsp = native.CreateInstance(factory);
|
||||
try
|
||||
{
|
||||
native.InitInstance(dsp, SampleRate);
|
||||
var outputs = new float[outputCount][];
|
||||
var outputPointers = new IntPtr[outputCount];
|
||||
var handles = new GCHandle[outputCount];
|
||||
try
|
||||
{
|
||||
for (var channel = 0; channel < outputCount; channel++)
|
||||
{
|
||||
outputs[channel] = new float[frameCount];
|
||||
handles[channel] = GCHandle.Alloc(outputs[channel], GCHandleType.Pinned);
|
||||
outputPointers[channel] = handles[channel].AddrOfPinnedObject();
|
||||
}
|
||||
|
||||
var pointersHandle = GCHandle.Alloc(outputPointers, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
native.Compute(dsp, frameCount, IntPtr.Zero, pointersHandle.AddrOfPinnedObject());
|
||||
}
|
||||
finally
|
||||
{
|
||||
pointersHandle.Free();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var handle in handles)
|
||||
{
|
||||
if (handle.IsAllocated)
|
||||
{
|
||||
handle.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var mono = new float[frameCount];
|
||||
for (var index = 0; index < frameCount; index++)
|
||||
{
|
||||
var sample = 0.0f;
|
||||
for (var channel = 0; channel < outputCount; channel++)
|
||||
{
|
||||
sample += outputs[channel][index];
|
||||
}
|
||||
|
||||
mono[index] = Math.Clamp(sample / outputCount * gain, -1.0f, 1.0f);
|
||||
}
|
||||
|
||||
return mono;
|
||||
}
|
||||
finally
|
||||
{
|
||||
native.DeleteInstance(dsp);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
native.DeleteFactory(factory);
|
||||
disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FaustNative : IDisposable
|
||||
{
|
||||
private const int ErrorBufferBytes = 4096;
|
||||
|
||||
private readonly IntPtr library;
|
||||
private readonly CreateFactoryFromStringFn createFactoryFromString;
|
||||
private readonly DeleteFactoryFn deleteFactory;
|
||||
private readonly CreateInstanceFn createInstance;
|
||||
private readonly DeleteInstanceFn deleteInstance;
|
||||
private readonly InitInstanceFn initInstance;
|
||||
private readonly ComputeInstanceFn computeInstance;
|
||||
private readonly GetNumOutputsFn getNumOutputs;
|
||||
private readonly StartFactoriesFn startFactories;
|
||||
private readonly StopFactoriesFn stopFactories;
|
||||
private readonly string sharePath;
|
||||
private bool disposed;
|
||||
|
||||
private FaustNative(IntPtr library, string version, string sharePath)
|
||||
{
|
||||
this.library = library;
|
||||
Version = version;
|
||||
this.sharePath = sharePath;
|
||||
createFactoryFromString = Export<CreateFactoryFromStringFn>("createCDSPFactoryFromString");
|
||||
deleteFactory = Export<DeleteFactoryFn>("deleteCDSPFactory");
|
||||
createInstance = Export<CreateInstanceFn>("createCDSPInstance");
|
||||
deleteInstance = Export<DeleteInstanceFn>("deleteCDSPInstance");
|
||||
initInstance = Export<InitInstanceFn>("initCDSPInstance");
|
||||
computeInstance = Export<ComputeInstanceFn>("computeCDSPInstance");
|
||||
getNumOutputs = Export<GetNumOutputsFn>("getNumOutputsCDSPInstance");
|
||||
startFactories = Export<StartFactoriesFn>("startMTDSPFactories");
|
||||
stopFactories = Export<StopFactoriesFn>("stopMTDSPFactories");
|
||||
_ = startFactories();
|
||||
}
|
||||
|
||||
public string Version { get; }
|
||||
|
||||
public static bool TryLoad(out FaustNative? native, out string? error)
|
||||
{
|
||||
native = null;
|
||||
error = null;
|
||||
var home = FaustToolchain.Find();
|
||||
if (home is null)
|
||||
{
|
||||
error = "Faust toolchain not found. Expected Tools\\Faust beside Aquarium.Engine.exe or AQUARIUM_FAUST_HOME.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var dllPath = Path.Combine(home, "lib", "faust.dll");
|
||||
if (!File.Exists(dllPath))
|
||||
{
|
||||
error = $"Faust DLL not found at {dllPath}.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var binPath = Path.Combine(home, "bin");
|
||||
var libPath = Path.Combine(home, "lib");
|
||||
var path = Environment.GetEnvironmentVariable("PATH") ?? "";
|
||||
Environment.SetEnvironmentVariable("PATH", $"{libPath};{binPath};{path}");
|
||||
|
||||
try
|
||||
{
|
||||
var library = NativeLibrary.Load(dllPath);
|
||||
var getVersion = Marshal.GetDelegateForFunctionPointer<GetVersion>(NativeLibrary.GetExport(library, "getCLibFaustVersion"));
|
||||
var version = Marshal.PtrToStringUTF8(getVersion()) ?? "unknown";
|
||||
native = new FaustNative(library, version, Path.Combine(home, "share", "faust"));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public CompiledFaustPatch Compile(string name, string source, float durationSeconds)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(disposed, this);
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
using var args = new NativeStringArray(["-I", sharePath, "-single", "-ftz", "2", "-vec", "-lv", "1"]);
|
||||
using var nativeName = new NativeUtf8String(name);
|
||||
using var nativeSource = new NativeUtf8String(source);
|
||||
using var target = new NativeUtf8String("");
|
||||
var errorBuffer = Marshal.AllocHGlobal(ErrorBufferBytes);
|
||||
try
|
||||
{
|
||||
Span<byte> empty = stackalloc byte[ErrorBufferBytes];
|
||||
Marshal.Copy(empty.ToArray(), 0, errorBuffer, ErrorBufferBytes);
|
||||
var factory = createFactoryFromString(
|
||||
nativeName.Pointer,
|
||||
nativeSource.Pointer,
|
||||
args.Count,
|
||||
args.Pointer,
|
||||
target.Pointer,
|
||||
errorBuffer,
|
||||
-1);
|
||||
if (factory == IntPtr.Zero)
|
||||
{
|
||||
var message = Marshal.PtrToStringUTF8(errorBuffer) ?? "unknown Faust compile failure";
|
||||
throw new InvalidOperationException(message.Trim());
|
||||
}
|
||||
|
||||
var probe = createInstance(factory);
|
||||
if (probe == IntPtr.Zero)
|
||||
{
|
||||
deleteFactory(factory);
|
||||
throw new InvalidOperationException("Faust compiled but failed to create a DSP instance.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var outputs = Math.Max(getNumOutputs(probe), 1);
|
||||
var frames = Math.Max(1, (int)MathF.Ceiling(durationSeconds * SampleRate));
|
||||
stopwatch.Stop();
|
||||
return new CompiledFaustPatch(this, factory, outputs, frames, stopwatch.Elapsed.TotalMilliseconds);
|
||||
}
|
||||
finally
|
||||
{
|
||||
deleteInstance(probe);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(errorBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
public IntPtr CreateInstance(IntPtr factory)
|
||||
{
|
||||
var dsp = createInstance(factory);
|
||||
if (dsp == IntPtr.Zero)
|
||||
{
|
||||
throw new InvalidOperationException("failed to create Faust DSP instance");
|
||||
}
|
||||
|
||||
return dsp;
|
||||
}
|
||||
|
||||
public void DeleteFactory(IntPtr factory) => _ = deleteFactory(factory);
|
||||
|
||||
public void DeleteInstance(IntPtr dsp) => deleteInstance(dsp);
|
||||
|
||||
public void InitInstance(IntPtr dsp, int sampleRate) => initInstance(dsp, sampleRate);
|
||||
|
||||
public void Compute(IntPtr dsp, int count, IntPtr inputs, IntPtr outputs) => computeInstance(dsp, count, inputs, outputs);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
stopFactories();
|
||||
NativeLibrary.Free(library);
|
||||
disposed = true;
|
||||
}
|
||||
|
||||
private T Export<T>(string name)
|
||||
where T : Delegate
|
||||
{
|
||||
return Marshal.GetDelegateForFunctionPointer<T>(NativeLibrary.GetExport(library, name));
|
||||
}
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr GetVersion();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr CreateFactoryFromStringFn(IntPtr name, IntPtr content, int argc, IntPtr argv, IntPtr target, IntPtr error, int optLevel);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool DeleteFactoryFn(IntPtr factory);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate IntPtr CreateInstanceFn(IntPtr factory);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void DeleteInstanceFn(IntPtr dsp);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void InitInstanceFn(IntPtr dsp, int sampleRate);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void ComputeInstanceFn(IntPtr dsp, int count, IntPtr inputs, IntPtr outputs);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate int GetNumOutputsFn(IntPtr dsp);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate bool StartFactoriesFn();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void StopFactoriesFn();
|
||||
}
|
||||
|
||||
private static class FaustToolchain
|
||||
{
|
||||
public static string? Find()
|
||||
{
|
||||
var candidates = new[]
|
||||
{
|
||||
Environment.GetEnvironmentVariable("AQUARIUM_FAUST_HOME"),
|
||||
Path.Combine(AppContext.BaseDirectory, "Tools", "Faust"),
|
||||
@"C:\Program Files\Faust"
|
||||
};
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(candidate))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var root = Path.GetFullPath(candidate);
|
||||
if (File.Exists(Path.Combine(root, "lib", "faust.dll")) &&
|
||||
Directory.Exists(Path.Combine(root, "share", "faust")))
|
||||
{
|
||||
return root;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NativeUtf8String : IDisposable
|
||||
{
|
||||
public NativeUtf8String(string value)
|
||||
{
|
||||
Pointer = Marshal.StringToCoTaskMemUTF8(value);
|
||||
}
|
||||
|
||||
public IntPtr Pointer { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Pointer != IntPtr.Zero)
|
||||
{
|
||||
Marshal.FreeCoTaskMem(Pointer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NativeStringArray : IDisposable
|
||||
{
|
||||
private readonly NativeUtf8String[] strings;
|
||||
private readonly GCHandle handle;
|
||||
|
||||
public NativeStringArray(IReadOnlyList<string> values)
|
||||
{
|
||||
strings = values.Select(value => new NativeUtf8String(value)).ToArray();
|
||||
var pointers = strings.Select(value => value.Pointer).ToArray();
|
||||
Count = pointers.Length;
|
||||
handle = GCHandle.Alloc(pointers, GCHandleType.Pinned);
|
||||
Pointer = handle.AddrOfPinnedObject();
|
||||
}
|
||||
|
||||
public int Count { get; }
|
||||
|
||||
public IntPtr Pointer { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (handle.IsAllocated)
|
||||
{
|
||||
handle.Free();
|
||||
}
|
||||
|
||||
foreach (var value in strings)
|
||||
{
|
||||
value.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -64,10 +64,10 @@ public sealed class D3D12Renderer : IAquariumRenderer
|
|||
new(9, "SdfObject Identity"),
|
||||
new(10, "SdfObject Steps"),
|
||||
];
|
||||
private static readonly DebugUi.DebugUiOption[] SynthPresetOptions = AquariumSynth.Dsl.BuiltInScripts.ReferenceScripts()
|
||||
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 = AquariumSynth.Dsl.BuiltInScripts.ReferenceScripts().ToArray();
|
||||
private static readonly (string Family, string Name, string Script)[] SynthPresets = AquaSynth.Dsl.BuiltInScripts.ReferenceScripts().ToArray();
|
||||
|
||||
private readonly IDXGIFactory4 factory;
|
||||
private readonly ID3D12Device device;
|
||||
|
|
|
|||
|
|
@ -68,6 +68,7 @@
|
|||
{"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.Dsl 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-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"}
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ current_model:
|
|||
dependencies:
|
||||
cult_math: E:\Projects\CultMath
|
||||
cult_lib: E:\Projects\CultLib
|
||||
aquarium_synth_dsl: NuGet package AquariumSynth.Dsl 0.1.0-aquarium.1 from repo-local packages feed
|
||||
aqua_synth_dsl: NuGet package AquaSynth.Dsl 0.1.0-aquasynth.1 from repo-local packages feed
|
||||
docs:
|
||||
doctrine: docs/aquarium-engine-doctrine.md
|
||||
engine_client_boundary: docs/engine-client-boundary.md
|
||||
|
|
@ -83,7 +83,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 unified debug panel with tabs for Aquarium renderer controls, client-declared debug panels, terminal commands, and engine/client tooling surfaces.
|
||||
- Aquarium exposes an optional synth/audio hosting boundary through AquariumSynthDocument; Aquarium consumes AquariumSynth.Dsl as a pinned repo-local NuGet package so synth-agent construction cannot break Aquarium builds until the package is intentionally updated.
|
||||
- Aquarium exposes an optional synth/audio hosting boundary through AquariumSynthDocument; Aquarium consumes AquaSynth.Dsl as a pinned repo-local NuGet package so synth-agent construction cannot break Aquarium builds until the package is intentionally updated.
|
||||
- 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.
|
||||
- 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.
|
||||
|
|
@ -102,7 +102,7 @@ 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 AquariumSynth.Dsl only by packing a new version into packages and changing the pinned PackageReference version deliberately.
|
||||
- Update AquaSynth.Dsl only by packing a new version 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.
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@
|
|||
],
|
||||
"audio": [
|
||||
"Aquarium exposes an optional audio/synth hosting boundary through contracts; clients declare intent, Aquarium schedules playback and owns device/toolchain integration.",
|
||||
"Aquarium consumes AquariumSynth.Dsl as a pinned repo-local NuGet package. AquariumSynthCSharp owns synth internals and tests; update the package only by deliberate version bump so visual/renderer work can continue while synth construction changes underneath."
|
||||
"Aquarium consumes AquaSynth.Dsl as a pinned repo-local NuGet package. AquaSynth owns synth internals, native Faust compilation, generated DSP manifests, and tests; update the package only by deliberate version bump so visual/renderer work can continue while synth construction changes underneath."
|
||||
],
|
||||
"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.",
|
||||
|
|
|
|||
|
|
@ -11,8 +11,8 @@ Keep the engine/client boundary strict:
|
|||
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 AquariumSynth.Dsl as a pinned package in the repo-local
|
||||
`packages` feed. AquariumSynthCSharp owns synth internals and tests; update
|
||||
- Aquarium consumes AquaSynth.Dsl as a pinned package in the repo-local
|
||||
`packages` feed. AquaSynth owns synth internals and tests; update
|
||||
the package only through an intentional version bump.
|
||||
|
||||
The renderer work that matters next:
|
||||
|
|
|
|||
Loading…
Reference in a new issue