feat(ui): Audio tab — live volume sliders driving OpenAL engine
Phase L.0 (cont.) — second tab on the Settings shell, in the Easy-wins
build order. Audio is the live-preview poster child: dragging a slider
is audible immediately, Save persists, Cancel reverts and the engine
catches up on the next frame.
AudioSettings record: Master / Music / Sfx / Ambient (all 0..1 floats).
Defaults match the OpenAlAudioEngine constructor values exactly so a
user who never opens the tab gets identical behaviour to the
pre-Phase-L env-var-only world (Master=1.0, Music=0.7, Sfx=1.0,
Ambient=0.8).
SettingsStore grows LoadAudio / SaveAudio + a generic SaveSection
helper that consolidates the unknown-top-level-key preservation logic.
Display and Audio sections coexist in settings.json:
{ "version": 1, "display": { ... }, "audio": { ... } }
Saving one section preserves the other on disk; a future Gameplay /
Chat / Character section drops in the same way without touching
existing data.
SettingsVM gains a parallel audio state machine (audioPersisted /
audioDraft / SetAudio / onSaveAudio callback). HasUnsavedChanges
covers all three buckets now (keybinds + display + audio); Save /
Cancel / ResetAll are atomic across all of them.
GameWindow wiring is the live-preview mechanism — every render frame
pushes the VM's AudioDraft into _audioEngine.MasterVolume etc. Cheap
(four float assignments) and unconditional. SetListener still applies
MasterVolume each frame too via the existing Phase E.2 code path, so
listener gain stays in sync. Persisted audio is applied to the engine
ONCE at startup before the first frame so the user's saved values
take effect before any sound plays — startup-time apply happens during
the same SettingsVM construction site that does the LoadDisplay +
LoadAudio.
SettingsPanel.RenderAudioTab replaces the L.0-shell placeholder — four
SliderFloat calls clamped to [0, 1], plus a footer note explaining the
live-preview UX. The "Coming soon" placeholder test was retargeted
from "Audio" to "Gameplay" since Audio is no longer a placeholder.
16 new tests:
· AudioSettings record (3) — defaults pin engine constants, value
equality, with-expressions
· SettingsStore audio round-trip (5) — missing-file → defaults,
round-trip all fields, partial-file per-field fallback, save-audio-
preserves-display, save-display-preserves-audio
· SettingsVM audio state (5) — initial draft tracks persisted,
SetAudio marks dirty, Save invokes audio callback, Cancel reverts,
ResetAllToDefaults covers audio
· SettingsPanel audio tab (3) — four sliders render only when active,
no SliderFloat emitted on inactive tabs, slider range is [0, 1]
dotnet build green (0 warnings); dotnet test 1,262 / 1,262 green
(243 Core.Net + 346 UI.Abstractions + 673 Core).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
382f0ad3fa
commit
53b1878c5c
9 changed files with 461 additions and 47 deletions
|
|
@ -901,12 +901,24 @@ public sealed class GameWindow : IDisposable
|
|||
// the same OnLoad path (see _inputDispatcher field).
|
||||
if (_inputDispatcher is not null)
|
||||
{
|
||||
// L.0 — settings.json (display + future audio / gameplay /
|
||||
// L.0 — settings.json (display + audio + future gameplay /
|
||||
// chat / character tabs). Coexists with keybinds.json,
|
||||
// which keeps its own load/save path.
|
||||
var settingsStore = new AcDream.UI.Abstractions.Panels.Settings.SettingsStore(
|
||||
AcDream.UI.Abstractions.Panels.Settings.SettingsStore.DefaultPath());
|
||||
var persistedDisplay = settingsStore.LoadDisplay();
|
||||
var persistedAudio = settingsStore.LoadAudio();
|
||||
|
||||
// Apply persisted audio to the engine BEFORE the panel
|
||||
// host starts pushing per-frame so the first frame uses
|
||||
// the user's saved values instead of engine defaults.
|
||||
if (_audioEngine is not null && _audioEngine.IsAvailable)
|
||||
{
|
||||
_audioEngine.MasterVolume = persistedAudio.Master;
|
||||
_audioEngine.MusicVolume = persistedAudio.Music;
|
||||
_audioEngine.SfxVolume = persistedAudio.Sfx;
|
||||
_audioEngine.AmbientVolume = persistedAudio.Ambient;
|
||||
}
|
||||
|
||||
_settingsVm = new AcDream.UI.Abstractions.Panels.Settings.SettingsVM(
|
||||
persisted: _keyBindings,
|
||||
|
|
@ -941,6 +953,21 @@ public sealed class GameWindow : IDisposable
|
|||
{
|
||||
Console.WriteLine($"settings: display save failed: {ex.Message}");
|
||||
}
|
||||
},
|
||||
persistedAudio: persistedAudio,
|
||||
onSaveAudio: audio =>
|
||||
{
|
||||
try
|
||||
{
|
||||
settingsStore.SaveAudio(audio);
|
||||
Console.WriteLine(
|
||||
"settings: audio saved to "
|
||||
+ AcDream.UI.Abstractions.Panels.Settings.SettingsStore.DefaultPath());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"settings: audio save failed: {ex.Message}");
|
||||
}
|
||||
});
|
||||
_settingsPanel = new AcDream.UI.Abstractions.Panels.Settings.SettingsPanel(_settingsVm);
|
||||
_panelHost.Register(_settingsPanel);
|
||||
|
|
@ -4105,6 +4132,22 @@ public sealed class GameWindow : IDisposable
|
|||
System.Numerics.Matrix4x4.Invert(camera.View, out var invView);
|
||||
var camPos = new System.Numerics.Vector3(invView.M41, invView.M42, invView.M43);
|
||||
|
||||
// L.0 Audio tab: push the SettingsVM's live AudioDraft into the
|
||||
// engine each frame, so volume sliders preview audibly while
|
||||
// the user drags. Cancel reverts the draft and the engine
|
||||
// catches up on the very next frame; Save persists to
|
||||
// settings.json without changing engine state (already
|
||||
// applied). Cheap enough to run unconditionally on every
|
||||
// tick — four float assignments.
|
||||
if (_audioEngine is not null && _audioEngine.IsAvailable && _settingsVm is not null)
|
||||
{
|
||||
var a = _settingsVm.AudioDraft;
|
||||
_audioEngine.MasterVolume = a.Master;
|
||||
_audioEngine.MusicVolume = a.Music;
|
||||
_audioEngine.SfxVolume = a.Sfx;
|
||||
_audioEngine.AmbientVolume = a.Ambient;
|
||||
}
|
||||
|
||||
// Phase E.2 audio: update listener pose so 3D sounds pan/attenuate
|
||||
// correctly relative to where we're looking.
|
||||
if (_audioEngine is not null && _audioEngine.IsAvailable)
|
||||
|
|
|
|||
28
src/AcDream.UI.Abstractions/Panels/Settings/AudioSettings.cs
Normal file
28
src/AcDream.UI.Abstractions/Panels/Settings/AudioSettings.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
namespace AcDream.UI.Abstractions.Panels.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Audio mixer preferences persisted to <c>settings.json</c>. Drives the
|
||||
/// existing Phase E.2 OpenAL engine — the host wires these values into
|
||||
/// <c>OpenAlAudioEngine.MasterVolume</c> / <c>SfxVolume</c> /
|
||||
/// <c>MusicVolume</c> / <c>AmbientVolume</c> on Save and on startup.
|
||||
///
|
||||
/// <para>
|
||||
/// Defaults match the engine's hard-coded starting values so a user
|
||||
/// who never opens the Audio tab gets identical behaviour to the
|
||||
/// previous env-var-only world.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed record AudioSettings(
|
||||
float Master,
|
||||
float Music,
|
||||
float Sfx,
|
||||
float Ambient)
|
||||
{
|
||||
/// <summary>Values used on first launch. Mirror the engine's
|
||||
/// constructor-default Volume properties.</summary>
|
||||
public static AudioSettings Default { get; } = new(
|
||||
Master: 1.0f,
|
||||
Music: 0.7f,
|
||||
Sfx: 1.0f,
|
||||
Ambient: 0.8f);
|
||||
}
|
||||
|
|
@ -88,7 +88,7 @@ public sealed class SettingsPanel : IPanel
|
|||
}
|
||||
if (renderer.BeginTabItem("Audio"))
|
||||
{
|
||||
RenderPlaceholder(renderer, "Audio");
|
||||
RenderAudioTab(renderer);
|
||||
renderer.EndTabItem();
|
||||
}
|
||||
if (renderer.BeginTabItem("Gameplay"))
|
||||
|
|
@ -239,6 +239,39 @@ public sealed class SettingsPanel : IPanel
|
|||
+ "preview live as you drag; Cancel reverts to the saved value.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Render the Audio tab — four volume sliders (Master / Music / SFX /
|
||||
/// Ambient). Volumes update <i>live</i>: the host pushes the VM's
|
||||
/// AudioDraft into the running OpenAL engine each frame, so dragging
|
||||
/// a slider is audible immediately. Cancel reverts the draft and the
|
||||
/// engine catches up on the next frame.
|
||||
/// </summary>
|
||||
private void RenderAudioTab(IPanelRenderer renderer)
|
||||
{
|
||||
var a = _vm.AudioDraft;
|
||||
|
||||
float master = a.Master;
|
||||
if (renderer.SliderFloat("Master", ref master, 0f, 1f))
|
||||
_vm.SetAudio(a with { Master = master });
|
||||
|
||||
float music = a.Music;
|
||||
if (renderer.SliderFloat("Music", ref music, 0f, 1f))
|
||||
_vm.SetAudio(a with { Music = music });
|
||||
|
||||
float sfx = a.Sfx;
|
||||
if (renderer.SliderFloat("SFX", ref sfx, 0f, 1f))
|
||||
_vm.SetAudio(a with { Sfx = sfx });
|
||||
|
||||
float ambient = a.Ambient;
|
||||
if (renderer.SliderFloat("Ambient", ref ambient, 0f, 1f))
|
||||
_vm.SetAudio(a with { Ambient = ambient });
|
||||
|
||||
renderer.Spacing();
|
||||
renderer.TextWrapped(
|
||||
"Volume changes preview live as you drag. Save persists the "
|
||||
+ "values to settings.json; Cancel reverts to the saved values.");
|
||||
}
|
||||
|
||||
private void RenderSection(IPanelRenderer renderer, string label, InputAction[] actions)
|
||||
{
|
||||
// Movement defaults open; other sections collapsed for first-run UX.
|
||||
|
|
|
|||
|
|
@ -82,11 +82,79 @@ public sealed class SettingsStore
|
|||
/// builds don't silently drop them.
|
||||
/// </summary>
|
||||
public void SaveDisplay(DisplaySettings display)
|
||||
=> SaveSection("display", BuildDisplayObject(display));
|
||||
|
||||
/// <summary>
|
||||
/// Load Audio settings. Same fall-back behaviour as
|
||||
/// <see cref="LoadDisplay"/>: missing file → defaults, missing fields
|
||||
/// → per-field defaults, corrupt JSON → defaults.
|
||||
/// </summary>
|
||||
public AudioSettings LoadAudio()
|
||||
{
|
||||
if (!File.Exists(_path)) return AudioSettings.Default;
|
||||
try
|
||||
{
|
||||
using var stream = File.OpenRead(_path);
|
||||
var doc = JsonDocument.Parse(stream);
|
||||
var root = doc.RootElement;
|
||||
if (!root.TryGetProperty("audio", out var audio)
|
||||
|| audio.ValueKind != JsonValueKind.Object)
|
||||
return AudioSettings.Default;
|
||||
|
||||
var d = AudioSettings.Default;
|
||||
return new AudioSettings(
|
||||
Master: ReadFloat(audio, "master", d.Master),
|
||||
Music: ReadFloat(audio, "music", d.Music),
|
||||
Sfx: ReadFloat(audio, "sfx", d.Sfx),
|
||||
Ambient: ReadFloat(audio, "ambient", d.Ambient));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"settings: failed to load {_path}: {ex.Message} — using defaults");
|
||||
return AudioSettings.Default;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Save Audio settings, preserving every other top-level key
|
||||
/// (display, future gameplay/chat/character). Same round-trip
|
||||
/// guarantee as <see cref="SaveDisplay"/>.
|
||||
/// </summary>
|
||||
public void SaveAudio(AudioSettings audio)
|
||||
=> SaveSection("audio", BuildAudioObject(audio));
|
||||
|
||||
private static SortedDictionary<string, object> BuildDisplayObject(DisplaySettings d)
|
||||
=> new(StringComparer.Ordinal)
|
||||
{
|
||||
["fieldOfView"] = d.FieldOfView,
|
||||
["fullscreen"] = d.Fullscreen,
|
||||
["gamma"] = d.Gamma,
|
||||
["resolution"] = d.Resolution,
|
||||
["showFps"] = d.ShowFps,
|
||||
["vsync"] = d.VSync,
|
||||
};
|
||||
|
||||
private static SortedDictionary<string, object> BuildAudioObject(AudioSettings a)
|
||||
=> new(StringComparer.Ordinal)
|
||||
{
|
||||
["ambient"] = a.Ambient,
|
||||
["master"] = a.Master,
|
||||
["music"] = a.Music,
|
||||
["sfx"] = a.Sfx,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Generic atomic-section save: writes the named section and preserves
|
||||
/// all other top-level keys from the existing file, replacing only the
|
||||
/// version + the targeted section. Avoids duplication between the
|
||||
/// per-section Save methods.
|
||||
/// </summary>
|
||||
private void SaveSection(string sectionName, SortedDictionary<string, object> sectionPayload)
|
||||
{
|
||||
var dir = Path.GetDirectoryName(_path);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
|
||||
// Preserve any non-display top-level keys from the existing file.
|
||||
// Preserve any non-target top-level keys from the existing file.
|
||||
var preservedKeys = new SortedDictionary<string, string>(StringComparer.Ordinal);
|
||||
if (File.Exists(_path))
|
||||
{
|
||||
|
|
@ -96,7 +164,7 @@ public sealed class SettingsStore
|
|||
var doc = JsonDocument.Parse(stream);
|
||||
foreach (var prop in doc.RootElement.EnumerateObject())
|
||||
{
|
||||
if (prop.Name == "display" || prop.Name == "version") continue;
|
||||
if (prop.Name == sectionName || prop.Name == "version") continue;
|
||||
preservedKeys[prop.Name] = prop.Value.GetRawText();
|
||||
}
|
||||
}
|
||||
|
|
@ -108,28 +176,19 @@ public sealed class SettingsStore
|
|||
}
|
||||
}
|
||||
|
||||
var displayObj = new SortedDictionary<string, object>(StringComparer.Ordinal)
|
||||
{
|
||||
["fieldOfView"] = display.FieldOfView,
|
||||
["fullscreen"] = display.Fullscreen,
|
||||
["gamma"] = display.Gamma,
|
||||
["resolution"] = display.Resolution,
|
||||
["showFps"] = display.ShowFps,
|
||||
["vsync"] = display.VSync,
|
||||
};
|
||||
|
||||
// Build the output by hand so preserved-keys keep their raw JSON.
|
||||
var sb = new System.Text.StringBuilder();
|
||||
sb.Append('{').AppendLine();
|
||||
sb.Append(" \"display\": ")
|
||||
.Append(JsonSerializer.Serialize(displayObj, new JsonSerializerOptions { WriteIndented = true })
|
||||
.Replace("\n", "\n "))
|
||||
.Append(',').AppendLine();
|
||||
// Preserved keys come first (sorted by name) then the section, then
|
||||
// version last. Preserves alphabetical-style top-level ordering.
|
||||
foreach (var kv in preservedKeys)
|
||||
{
|
||||
sb.Append(" \"").Append(kv.Key).Append("\": ")
|
||||
.Append(kv.Value).Append(',').AppendLine();
|
||||
}
|
||||
sb.Append(" \"").Append(sectionName).Append("\": ")
|
||||
.Append(JsonSerializer.Serialize(sectionPayload, new JsonSerializerOptions { WriteIndented = true })
|
||||
.Replace("\n", "\n "))
|
||||
.Append(',').AppendLine();
|
||||
sb.Append(" \"version\": ").Append(CurrentSchemaVersion).AppendLine();
|
||||
sb.Append('}').AppendLine();
|
||||
|
||||
|
|
|
|||
|
|
@ -36,6 +36,11 @@ public sealed class SettingsVM
|
|||
private DisplaySettings _displayDraft;
|
||||
private readonly Action<DisplaySettings> _onSaveDisplay;
|
||||
|
||||
// L.0 — Audio tab. Same shape as Display.
|
||||
private AudioSettings _audioPersisted;
|
||||
private AudioSettings _audioDraft;
|
||||
private readonly Action<AudioSettings> _onSaveAudio;
|
||||
|
||||
/// <summary>The action currently being rebound, or null when idle.</summary>
|
||||
public InputAction? RebindInProgress { get; private set; }
|
||||
|
||||
|
|
@ -58,26 +63,36 @@ public sealed class SettingsVM
|
|||
/// rebinds are pending.</summary>
|
||||
public bool HasUnsavedChanges
|
||||
=> !KeyBindingsEqual(_persisted, _draft)
|
||||
|| _displayPersisted != _displayDraft;
|
||||
|| _displayPersisted != _displayDraft
|
||||
|| _audioPersisted != _audioDraft;
|
||||
|
||||
/// <summary>The current Display draft. Panel reads from here;
|
||||
/// mutation goes through <see cref="SetDisplay"/>.</summary>
|
||||
public DisplaySettings DisplayDraft => _displayDraft;
|
||||
|
||||
/// <summary>The current Audio draft. Panel reads from here;
|
||||
/// mutation goes through <see cref="SetAudio"/>.</summary>
|
||||
public AudioSettings AudioDraft => _audioDraft;
|
||||
|
||||
public SettingsVM(
|
||||
KeyBindings persisted,
|
||||
InputDispatcher dispatcher,
|
||||
Action<KeyBindings> onSave,
|
||||
DisplaySettings persistedDisplay,
|
||||
Action<DisplaySettings> onSaveDisplay)
|
||||
Action<DisplaySettings> onSaveDisplay,
|
||||
AudioSettings persistedAudio,
|
||||
Action<AudioSettings> onSaveAudio)
|
||||
{
|
||||
_persisted = persisted ?? throw new ArgumentNullException(nameof(persisted));
|
||||
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
|
||||
_onSave = onSave ?? throw new ArgumentNullException(nameof(onSave));
|
||||
_displayPersisted = persistedDisplay ?? throw new ArgumentNullException(nameof(persistedDisplay));
|
||||
_onSaveDisplay = onSaveDisplay ?? throw new ArgumentNullException(nameof(onSaveDisplay));
|
||||
_audioPersisted = persistedAudio ?? throw new ArgumentNullException(nameof(persistedAudio));
|
||||
_onSaveAudio = onSaveAudio ?? throw new ArgumentNullException(nameof(onSaveAudio));
|
||||
_draft = CloneBindings(persisted);
|
||||
_displayDraft = persistedDisplay;
|
||||
_audioDraft = persistedAudio;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -90,6 +105,18 @@ public sealed class SettingsVM
|
|||
_displayDraft = value ?? throw new ArgumentNullException(nameof(value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replace the entire Audio draft with <paramref name="value"/>.
|
||||
/// Live audio preview is achieved at the host layer by pushing
|
||||
/// <see cref="AudioDraft"/> into the running OpenAL engine each frame
|
||||
/// — this method only mutates VM state. Cancel reverts the draft and
|
||||
/// the host's next-frame push restores the pre-edit engine volumes.
|
||||
/// </summary>
|
||||
public void SetAudio(AudioSettings value)
|
||||
{
|
||||
_audioDraft = value ?? throw new ArgumentNullException(nameof(value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Begin rebinding <paramref name="action"/>. The supplied
|
||||
/// <paramref name="original"/> binding will be removed when the new
|
||||
|
|
@ -199,6 +226,7 @@ public sealed class SettingsVM
|
|||
{
|
||||
_draft = KeyBindings.RetailDefaults();
|
||||
_displayDraft = DisplaySettings.Default;
|
||||
_audioDraft = AudioSettings.Default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -213,8 +241,10 @@ public sealed class SettingsVM
|
|||
{
|
||||
_onSave(_draft);
|
||||
_onSaveDisplay(_displayDraft);
|
||||
_onSaveAudio(_audioDraft);
|
||||
_persisted = CloneBindings(_draft);
|
||||
_displayPersisted = _displayDraft;
|
||||
_audioPersisted = _audioDraft;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -226,6 +256,7 @@ public sealed class SettingsVM
|
|||
{
|
||||
_draft = CloneBindings(_persisted);
|
||||
_displayDraft = _displayPersisted;
|
||||
_audioDraft = _audioPersisted;
|
||||
CancelRebind();
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue