diff --git a/program/AppMode.cs b/program/AppMode.cs index 7f2c8a7..c4af777 100644 --- a/program/AppMode.cs +++ b/program/AppMode.cs @@ -4,6 +4,7 @@ public static class AppMode { /// false = current single-map mode, true = legacy 7-region mode. + /// Set once in Program.Main from the --legacy argument, before any UI exists. public static bool Legacy = false; public static string CasesCsv @@ -11,10 +12,10 @@ get { return SoundWindow.AppFile(Legacy ? "cases_old.csv" : "cases.csv"); } } + // Legacy looks in its own folder first and falls back to the shared one, + // so files only need to exist once. private static string MapDir { get { return Legacy ? "map_old" : "map"; } } - // private static string SoundDir { get { return Legacy ? "sound_old" : "sound"; } } - /// Shared by both modes: legacy and current read from the same folder. - private const string SoundDir = "sound"; + private static string SoundDir { get { return Legacy ? "sound_old" : "sound"; } } /// CSV value -> absolute path. Returns null for "none"/empty. public static string ResolveMap(string csvValue) { return Resolve(csvValue, MapDir, "map"); } @@ -25,12 +26,32 @@ if (string.IsNullOrWhiteSpace(csvValue)) return null; if (csvValue.Trim().Equals("none", StringComparison.OrdinalIgnoreCase)) return null; - string file = Path.GetFileName(csvValue.Trim()); + string file = Path.GetFileName(csvValue.Trim().Replace('\\', '/')); // Python CSVs may use Windows paths string path = SoundWindow.AppFile(Path.Combine(dir, file)); - if (!File.Exists(path) && Legacy) // shared asset fallback - path = SoundWindow.AppFile(Path.Combine(fallbackDir, file)); + if (!File.Exists(path) && dir != fallbackDir) // shared asset fallback + { + string shared = SoundWindow.AppFile(Path.Combine(fallbackDir, file)); + if (File.Exists(shared)) return shared; + } - return path; + // Linux is case-sensitive; the Python data came from Windows. + if (!File.Exists(path)) + { + string ci = FindIgnoreCase(dir, file) ?? FindIgnoreCase(fallbackDir, file); + if (ci != null) return ci; + } + + return path; // may not exist; callers log the missing file + } + + private static string FindIgnoreCase(string dir, string file) + { + string full = SoundWindow.AppFile(dir); + if (!Directory.Exists(full)) return null; + foreach (string f in Directory.GetFiles(full)) + if (string.Equals(Path.GetFileName(f), file, StringComparison.OrdinalIgnoreCase)) + return f; + return null; } } \ No newline at end of file diff --git a/program/AudioEngine.cs b/program/AudioEngine.cs index 8b763b8..0995efb 100644 --- a/program/AudioEngine.cs +++ b/program/AudioEngine.cs @@ -16,9 +16,19 @@ public float Gain; } + private class SharedBuffer + { + public int Id; + public int Refs; + } + private AudioContext _context; private readonly Dictionary _voices = new Dictionary(StringComparer.OrdinalIgnoreCase); + // One AL buffer per WAV file, shared by every voice that plays it + // (legacy cases often use the same file for several regions). + private readonly Dictionary _buffers = + new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly object _lock = new object(); public event Action Log; @@ -40,7 +50,6 @@ } /// Load + start looping at gain 0. Idempotent per key. - /// Load + start looping at gain 0. Idempotent per key. public Voice Warm(string wavPath) { return Warm(wavPath, wavPath); } public Voice Warm(string wavPath, string key) @@ -54,14 +63,12 @@ lock (_lock) { Voice v; - if (_voices.TryGetValue(key, out v)) return v; // ← key, not wavPath + if (_voices.TryGetValue(key, out v)) return v; + int buf = 0; try { - WavFile w = WavFile.Load(wavPath); - - int buf = AL.GenBuffer(); - AL.BufferData(buf, w.Format, w.Data, w.Data.Length, w.SampleRate); + buf = AcquireBuffer(wavPath); int src = AL.GenSource(); AL.Source(src, ALSourcei.Buffer, buf); @@ -72,18 +79,88 @@ CheckError("Warm " + Path.GetFileName(wavPath)); v = new Voice { Path = wavPath, Buffer = buf, Source = src, Gain = 0f }; - _voices[key] = v; // ← key - Emit("Warmed " + Path.GetFileName(wavPath) + " [" + key + "]"); + _voices[key] = v; + Emit("Warmed " + Path.GetFileName(wavPath) + " [" + key + "] voices=" + _voices.Count); return v; } catch (Exception ex) { + if (buf != 0) ReleaseBuffer(wavPath); Emit("Load failed " + wavPath + ": " + ex.Message); return null; } } } + private int AcquireBuffer(string wavPath) + { + SharedBuffer sb; + if (_buffers.TryGetValue(wavPath, out sb)) { sb.Refs++; return sb.Id; } + + WavFile w = WavFile.Load(wavPath); + int buf = AL.GenBuffer(); + AL.BufferData(buf, w.Format, w.Data, w.Data.Length, w.SampleRate); + CheckError("BufferData " + Path.GetFileName(wavPath)); + + _buffers[wavPath] = new SharedBuffer { Id = buf, Refs = 1 }; + return buf; + } + + private void ReleaseBuffer(string wavPath) + { + SharedBuffer sb; + if (!_buffers.TryGetValue(wavPath, out sb)) return; + if (--sb.Refs > 0) return; + AL.DeleteBuffer(sb.Id); + _buffers.Remove(wavPath); + } + + /// Stops and frees every voice whose key starts with prefix. + /// Legacy uses "R" so each case's 7 region voices don't pile up + /// (every source keeps looping and being mixed, even at gain 0). + public void ReleaseWhereKeyStarts(string prefix) + { + lock (_lock) + { + var dead = new List(); + foreach (var kv in _voices) + if (kv.Key.StartsWith(prefix, StringComparison.Ordinal)) dead.Add(kv.Key); + + foreach (string k in dead) + { + Voice v = _voices[k]; + AL.SourceStop(v.Source); + AL.Source(v.Source, ALSourcei.Buffer, 0); // detach before the buffer can be deleted + AL.DeleteSource(v.Source); + ReleaseBuffer(v.Path); + _voices.Remove(k); + if (v == _main) _main = null; + } + + if (dead.Count > 0) + Emit("Released " + dead.Count + " voice(s) '" + prefix + "*' voices=" + _voices.Count); + } + } + + /// Rewinds the given voices and starts them in ONE OpenAL call, so they + /// share sample position 0. Gains are left as they are (normally 0). + public void RestartTogether(IList voices) + { + if (voices == null || voices.Count == 0) return; + + var ids = new List(); + foreach (var v in voices) if (v != null) ids.Add(v.Source); + if (ids.Count == 0) return; + + int[] arr = ids.ToArray(); + lock (_lock) + { + AL.SourceRewind(arr.Length, arr); + AL.SourcePlay(arr.Length, arr); + CheckError("RestartTogether"); + } + } + /// Replaces SourceVoice.SetVolume. Linear 0..1. public void SetGain(Voice v, float gain) { @@ -169,10 +246,13 @@ foreach (var v in _voices.Values) { AL.SourceStop(v.Source); + AL.Source(v.Source, ALSourcei.Buffer, 0); AL.DeleteSource(v.Source); - AL.DeleteBuffer(v.Buffer); } _voices.Clear(); + + foreach (var b in _buffers.Values) AL.DeleteBuffer(b.Id); + _buffers.Clear(); } if (_context != null) { _context.Dispose(); _context = null; } } diff --git a/program/MapWindow.cs b/program/MapWindow.cs index 8f86a6f..b82d581 100644 --- a/program/MapWindow.cs +++ b/program/MapWindow.cs @@ -35,6 +35,8 @@ // cursor calibration public double MarginX = 0.0; public double MarginY = 0.0; + public bool MirrorX = false; // flip cursor horizontally for this size:view + public bool MirrorY = false; public Tune Clone() { return (Tune)MemberwiseClone(); } } @@ -70,22 +72,28 @@ Seed("L:left", -14.0, -110.0, 0.80, 0.40, 15, 1.050, 0.0, 5.0, 0.70); // ── XL ── (converted from the old XL_* deltas: L_offset − delta) - Seed("XL:front", 7.0, 17.0, 2.30, 1.05, 50, 1.060, -4.0, -14.0, 0.70); + // XL front/right/left cursors are mirrored (was hardcoded in TryGetCursorBodyPoint). + Seed("XL:front", 7.0, 17.0, 2.30, 1.05, 50, 1.060, -4.0, -14.0, 0.70, true); Seed("XL:back", 5.0, 10.0, 1.95, 0.90, 40, 1.090, 2.0, -7.0, 0.70); - Seed("XL:right", 10.0, -108.0, 0.80, 0.40, 40, 1.010, -32.0, 71.0, 0.70); - Seed("XL:left", -4.0, -101.0, 0.80, 0.40, 40, 1.050, 0.0, 5.0, 0.70); + Seed("XL:right", 10.0, -108.0, 0.80, 0.40, 40, 1.010, -32.0, 71.0, 0.70, true); + Seed("XL:left", -4.0, -101.0, 0.80, 0.40, 40, 1.050, 0.0, 5.0, 0.70, true); } private void Seed(string key, double ox, double oy, double size, double cluster, - double fitMargin, double zoom, double mx, double my, double alpha) + double fitMargin, double zoom, double mx, double my, double alpha, + bool mirrorX = false) { _tunes[key] = new Tune { OffsetX = ox, OffsetY = oy, SizeScale = size, Cluster = cluster, - FitMargin = fitMargin, MapZoom = zoom, MapX = mx, MapY = my, MapAlpha = alpha + FitMargin = fitMargin, MapZoom = zoom, MapX = mx, MapY = my, MapAlpha = alpha, + MirrorX = mirrorX }; } + /// Shows up in the log at startup, so you can tell which MapWindow.cs is running. + private const string BuildTag = "2026-10-20 fixes (legacy RFID, body reload, calib, multi-voice)"; + private const int CircleDiameter = 50; private const int MapSize = 546; // Form2: new Bitmap(mapImage, 546, 546) @@ -118,7 +126,9 @@ [UI] private Label BreathWaveHeader = null; [UI] private Button MapExplainButton = null; [UI] private Switch ShowVolumeMapSwitch = null; - [UI] private CheckButton HideMetersCheck = null; + [UI] private CheckButton HideMetersCheck = null; // old glade only + [UI] private Switch ShowPointListSwitch = null; // new glade: ON = legacy meters shown + [UI] private Box ShowPointListSwitchRow = null; // hidden outside legacy (nothing to list) private readonly Language _lang; // private readonly SoundLooper _sound = new SoundLooper(); @@ -171,7 +181,7 @@ RegexOptions.Compiled); private string _bodyPath = "(none)"; private string _mapPath = "(none)"; - + public event EventHandler BackRequested; @@ -185,6 +195,7 @@ private Label _tunerInfo, _tunerKey; private readonly Dictionary _spins = new Dictionary(); private CheckButton _tShowBody, _tShowMap, _tShowCircles, _tGuides; + private CheckButton _tMirrorX, _tMirrorY; private ComboBoxText _tFitCombo; private bool _building; private bool _keysHooked; @@ -195,12 +206,16 @@ private bool ShowCircles { get { return (_tShowCircles == null || _tShowCircles.Active) && (ShowNumbersSwitch == null || ShowNumbersSwitch.Active); } } private bool ShowGuides { get { return _tGuides != null && _tGuides.Active; } } - + // ── debug state ── private uint _debugSweepId; private int _debugLevel; private int _debugStep = 5; + // ── debug mouse probe ── + private bool _mouseProbe; // true while the left button is held on the map + private double _mouseBx, _mouseBy; // probe point, BODY PIXELS + // ── waveform boxes ── private WaveData _heartWave, _breathWave; private double _heartCursor = -1, _breathCursor = -1; // 0..1, -1 = hidden @@ -215,6 +230,7 @@ { builder.Autoconnect(this); _arduino = arduino; + Logger.Write("map", "MapWindow build " + BuildTag); SeedDefaults(); LoadCalibFile(false); // calib.txt overrides seeds if present @@ -277,8 +293,6 @@ // ── signals ─────────────────────────────────────────────────── MapArea.Drawn += OnMapDrawn; - // HeartWaveArea.Drawn += (o, a) => DrawWave(a, HeartWaveArea, 0.86, 0.22, 0.20); - // BreathWaveArea.Drawn += (o, a) => DrawWave(a, BreathWaveArea, 0.21, 0.57, 0.78); HeartWaveArea.Drawn += (o, a) => DrawWave(a, HeartWaveArea, _heartWave, _heartCursor, 0.86, 0.22, 0.20); BreathWaveArea.Drawn += (o, a) => DrawWave(a, BreathWaveArea, _breathWave, _breathCursor, 0.21, 0.57, 0.78); MapBackButton.Clicked += OnBackClicked; @@ -294,11 +308,25 @@ HookView(ViewRightRadio, "right"); HookView(ViewLeftRadio, "left"); - // HideCircleCheck.Toggled += (s, e) => MapArea.QueueDraw(); if (ShowNumbersSwitch != null) ShowNumbersSwitch.AddNotification("active", (o, a) => MapArea.QueueDraw()); if (ShowVolumeMapSwitch != null) ShowVolumeMapSwitch.AddNotification("active", (o, a) => MapArea.QueueDraw()); + if (ShowPointListSwitch != null) + ShowPointListSwitch.AddNotification("active", (o, a) => + { + Logger.Write("map", "point list " + (ShowPointListSwitch.Active ? "ON" : "OFF") + + (AppMode.Legacy ? "" : " (no effect: not legacy mode)")); + MapArea.QueueDraw(); + }); + + // The point list is the legacy 7-region meter panel. Current mode has + // no equivalent, so the switch is hidden there instead of doing nothing. + if (ShowPointListSwitchRow != null) + { + ShowPointListSwitchRow.NoShowAll = true; + ShowPointListSwitchRow.Visible = AppMode.Legacy; + } if (BlackAudioSwitch != null) BlackAudioSwitch.AddNotification("active", (o, a) => { @@ -315,7 +343,9 @@ // Ctrl+T anywhere, or Ctrl+double-click on the map, opens the tuner. MapArea.Realized += (s, e) => HookKeys(); - MapArea.AddEvents((int)Gdk.EventMask.ButtonPressMask); + MapArea.AddEvents((int)(Gdk.EventMask.ButtonPressMask | + Gdk.EventMask.ButtonReleaseMask | + Gdk.EventMask.Button1MotionMask)); MapArea.ButtonPressEvent += (o, a) => { if (a.Event.Type == Gdk.EventType.TwoButtonPress && @@ -323,11 +353,31 @@ ToggleTuner(); }; + // Debug mode: hold the left button on the map to hear that spot. + MapArea.ButtonPressEvent += (o, a) => + { + if (!AppConfig.DebugMode || a.Event.Button != 1) return; + if (a.Event.Type != Gdk.EventType.ButtonPress) return; // ignore double-click + if ((a.Event.State & Gdk.ModifierType.ControlMask) != 0) return; // Ctrl = tuner + MouseProbe(a.Event.X, a.Event.Y); + }; + MapArea.MotionNotifyEvent += (o, a) => + { + if (_mouseProbe) MouseProbe(a.Event.X, a.Event.Y); + }; + MapArea.ButtonReleaseEvent += (o, a) => + { + if (!_mouseProbe || a.Event.Button != 1) return; + _mouseProbe = false; + _lastPx = _lastPy = -1; + UpdateAudioFromPosition(); // mutes, unless a real tag is on the jacket + MapArea.QueueDraw(); + }; + _sound.Log += msg => Logger.Write("sound", msg); if (!_sound.Init()) - Logger.Write("sound", "OpenAL init failed — session will be silent"); - // _sound.Init(); - // NEW — live position feed + Logger.Write("sound", "OpenAL init failed — session will be silent"); + // live position feed _arduino.LineReceived += OnArduinoLine; _watchdogId = GLib.Timeout.Add(WATCHDOG_MS, OnTagWatchdog); _arduino.ConnectionChanged += OnArduinoConnectionChanged; @@ -375,7 +425,10 @@ // ARDUINO POSITION // ══════════════════════════════════════════════════════════════════ - private void OnArduinoLine(string line) + /// Parses every line the same way in BOTH modes. The legacy/current + /// split happens later, in UpdateAudioFromPosition — a legacy branch + /// here would run before the position is parsed and mute everything. + private void OnArduinoLine(string line) { var fullMatches = FullRx.Matches(line); var avgMatch = AvgRx.Match(line); @@ -386,22 +439,8 @@ _highlighted.Clear(); - Logger.Write("chip", "raw='" + line + "' fullMatches=" + fullMatches.Count + // NEW - " avgMatch=" + avgMatch.Success); - - if (AppMode.Legacy) - { - // For legacy mode, we need to process the position first before applying audio - double bx, by; - if (!_hasPosition || !TryGetCursorBodyPoint(out bx, out by)) - { - MuteRegions(); - return; - } - - if (_case != null) ApplyRegionAudio(bx, by); - return; // skip the single-voice path entirely - } + Logger.Write("chip", "raw='" + line + "' fullMatches=" + fullMatches.Count + + " avgMatch=" + avgMatch.Success); if (avgMatch.Success) { @@ -431,7 +470,6 @@ } } - // if (!havePosition) return; // status/mode line, not a coordinate line if (!havePosition) { // Reader explicitly says there's nothing there -> clear now, don't @@ -442,20 +480,20 @@ return; } - _lastPosLine = DateTime.Now; // NEW — feeds the watchdog + _lastPosLine = DateTime.Now; // feeds the watchdog _currentX = x; _currentY = y; _currentZ = z; - _hasPosition = _highlighted.Count > 0; // NEW — marker only shows when a chip is actually on the target + _hasPosition = _highlighted.Count > 0; // marker only shows when a chip is actually on the target string newView = DetermineViewFromZ(z); if (newView != _view) SwitchViewFromArduino(newView); MapArea.QueueDraw(); - UpdateAudioFromPosition(); - } + UpdateAudioFromPosition(); // legacy and current both branch from here + } private static float ParseF(string s) { @@ -474,10 +512,26 @@ private void UpdateAudioFromPosition() { + // ── legacy: 7 region voices mixed by UV position ── + if (AppMode.Legacy) + { + double lbx, lby; + if (_case == null || (!_hasPosition && !_mouseProbe) || + !TryGetCursorBodyPoint(out lbx, out lby)) + { + MuteRegions(); + _audible = false; + return; + } + ApplyRegionAudio(lbx, lby); + return; + } + + // ── current: one voice, level from the colour map ── if (_caseVoice == null) return; double bx, by; - if (!_hasPosition || !TryGetCursorBodyPoint(out bx, out by)) + if ((!_hasPosition && !_mouseProbe) || !TryGetCursorBodyPoint(out bx, out by)) { MuteVoices(); return; @@ -520,12 +574,14 @@ private void MuteVoices() { _audible = false; - _lastPx = _lastPy = -1; + _lastPx = _lastPy = -1; _sound.SetGain(_caseVoice, 0f); if (_heart1 != null) _sound.SetGain(_heart1, 0f); if (_heart2 != null) _sound.SetGain(_heart2, 0f); if (_breath != null) _sound.SetGain(_breath, 0f); + MuteRegions(); // legacy voices too; no-op in current mode } + /// Form2's TimestampTimer_Tick. The reader going quiet is not an event — /// nothing arrives to tell us the tag left, so we have to notice ourselves. private bool OnTagWatchdog() @@ -544,24 +600,32 @@ _highlighted.Clear(); _hasPosition = false; _currentX = _currentY = _currentZ = 0f; - MuteVoices(); + if (_mouseProbe) UpdateAudioFromPosition(); // debug click still held + else MuteVoices(); MapArea.QueueDraw(); } - /// Maps the live Arduino (x,y) into BODY PIXELS using the same - /// bounding-box scale/offset DrawCircles uses, so the cursor tracks - /// the same coordinate frame as the numbered circles. - private bool TryGetCursorBodyPoint(out double bx, out double by) + // ── circle / cursor geometry ─────────────────────────────────────── + + /// Everything DrawCircles derives from the jacket CSV, in BODY PIXELS. + /// The cursor uses the same numbers so it lands on the same circles. + private struct CircleGeom { - bx = by = 0; - if (!_hasPosition || _jacket == null || _body == null) return false; + public double Scale, OffsetX, OffsetY, AvgX, AvgY; + public int PanelW, PanelH; + } + + private bool TryGetCircleGeom(out CircleGeom g) + { + g = new CircleGeom(); + if (_jacket == null || _body == null) return false; var circles = _jacket.Get(JacketSize, _view); if (circles.Count == 0) return false; var t = T; - int panelW = _body.Width; - int panelH = _body.Height; + g.PanelW = _body.Width; + g.PanelH = _body.Height; float minX = float.MaxValue, maxX = float.MinValue; float minY = float.MaxValue, maxY = float.MinValue; @@ -573,28 +637,54 @@ if (c.Y > maxY) maxY = c.Y; } - double availW = panelW - t.FitMargin, availH = panelH - t.FitMargin; + double availW = g.PanelW - t.FitMargin, availH = g.PanelH - t.FitMargin; const double circleRadius = 2.1 / 2; double dataW = (maxX - minX) + circleRadius * 2; double dataH = (maxY - minY) + circleRadius * 2; if (dataW <= 0 || dataH <= 0) return false; - double scale = Math.Min(availW / dataW, availH / dataH) * 0.9; + g.Scale = Math.Min(availW / dataW, availH / dataH) * 0.9; + g.OffsetX = (g.PanelW - (maxX - minX) * g.Scale) / 2 - minX * g.Scale; + g.OffsetY = (g.PanelH - (maxY - minY) * g.Scale) / 2 - minY * g.Scale; - double offsetX = (panelW - (maxX - minX) * scale) / 2 - minX * scale; - double offsetY = (panelH - (maxY - minY) * scale) / 2 - minY * scale; + // cluster centroid, in already-offset space + foreach (var c in circles) + { + g.AvgX += c.X * g.Scale + g.OffsetX - t.OffsetX; + g.AvgY += c.Y * g.Scale + g.OffsetY - t.OffsetY; + } + g.AvgX /= circles.Count; + g.AvgY /= circles.Count; + return true; + } + + /// Live Arduino (x,y) -> BODY PIXELS, through the same scale / offset / + /// cluster steps DrawOneCircle applies, then MarginX/Y and mirror. + /// In debug mode a held mouse button overrides the tag. + private bool TryGetCursorBodyPoint(out double bx, out double by) + { + if (_mouseProbe) { bx = _mouseBx; by = _mouseBy; return true; } + + bx = by = 0; + if (!_hasPosition) return false; + + CircleGeom g; + if (!TryGetCircleGeom(out g)) return false; + + var t = T; // Form2: raw Arduino units run ~50x smaller than CSV/circle units. - bx = (_currentX * 50 + t.MarginX) * scale + offsetX; - by = (_currentY * 50 + t.MarginY) * scale + offsetY; + bx = (_currentX * 50 + t.MarginX) * g.Scale + g.OffsetX - t.OffsetX; + by = (_currentY * 50 + t.MarginY) * g.Scale + g.OffsetY - t.OffsetY; - if (JacketSize == "XL" && (_view == "front" || _view == "right" || _view == "left")) + if (Math.Abs(t.Cluster - 1.0) > 0.001) { - double centerX = panelW / 2.0; - double offsetFromCenter = bx - centerX; - bx = centerX - offsetFromCenter; + bx = g.AvgX + (bx - g.AvgX) * t.Cluster; + by = g.AvgY + (by - g.AvgY) * t.Cluster; } + if (t.MirrorX) bx = g.PanelW - bx; + if (t.MirrorY) by = g.PanelH - by; return true; } @@ -603,7 +693,6 @@ const double size = 14; cr.NewPath(); - // cr.SetSourceRGBA(1.0, 0.0, 0.0, 0.9); //red not that visible cr.SetSourceRGBA(1.0, 0.85, 0.0, 0.95); //yellow cr.LineWidth = 2.5; cr.MoveTo(x - size, y); @@ -651,10 +740,13 @@ MapCaseLabel.Text = title ?? "-"; DisposePixbufs(); - _body = LoadBody(); - + ReloadBody(); // logs which body image was loaded + if (AppMode.Legacy) { + // Voices from a previous current-mode case must not answer the tag. + _caseVoice = _heart1 = _heart2 = _breath = null; + LoadRegions(def); var overlay = BuildRegionOverlay(MapSize, MapSize); _mapRaw = overlay != null ? overlay.Copy() : null; @@ -663,13 +755,12 @@ } else { - // _map = LoadMap(MapPathForView()); _map = LoadMap(MapPathForView(), MapNeedsMirror()); } MapArea.QueueDraw(); UpdateTunerInfo(); - + if (!AppMode.Legacy) { _caseVoice = _sound.Warm(SoundWindow.AppFile(def.SoundPath)); @@ -682,24 +773,33 @@ if (BreathSoundEnabled) _breath = _sound.Warm(AppMode.ResolveSound("SND200.wav")); - _sound.MuteAll(); // everything loops silently until a tag lands } - LoadWaveforms(def); - _playClock.Restart(); // voices were just warmed -> loop position 0 + LoadWaveforms(def); + + // Start every voice of this case from sample 0 in one OpenAL call, and + // the waveform clock with them. Warm() starts each source as soon as its + // file is loaded, and cached voices are wherever they were left, so + // without this the regions (and the cursor) are out of step. + var group = new List(); + if (AppMode.Legacy) foreach (var r in _regions) group.Add(r.Voice); + else { group.Add(_caseVoice); group.Add(_heart1); group.Add(_heart2); group.Add(_breath); } + _sound.RestartTogether(group); + _playClock.Restart(); StartWaveTimer(); _lastPx = _lastPy = -1; - StartDebugSweep(); + StartDebugSweep(); - Logger.Write("case", "open: " + title + " | map=" + MapPathForView()); + Logger.Write("case", "open: " + title + " | map=" + _mapPath + + (AppMode.Legacy ? " | legacy regions=" + _regions.Count : "")); } public void StopSession() { - StopDebugSweep(); - MuteRegions(); // NEW: stop legacy audio too - // _sound.Stop(); + StopDebugSweep(); + _mouseProbe = false; + MuteRegions(); // stop legacy audio too _sound.MuteAll(); // keep voices warm — re-entry is instant StopWaveTimer(); _lastPx = _lastPy = -1; @@ -800,7 +900,6 @@ cr.Translate(mx, my); cr.Scale(sx, sy); Gdk.CairoHelper.SetSourcePixbuf(cr, src, 0, 0); - // Guard the existing map-overlay draw with (!AppMode.Legacy || _showRegions) if (!AppMode.Legacy || _showRegions) cr.PaintWithAlpha(T.MapAlpha); cr.Restore(); @@ -835,12 +934,14 @@ } cr.Restore(); - // NEW — screen-space readout, unaffected by the body scale/translate above + // screen-space readout, unaffected by the body scale/translate above if (_hasPosition) - DrawCoordHud(cr, w, h); //show the coordinate on top of the image + DrawCoordHud(cr, w, h); - // At the very end, before args.RetVal = true, add: - bool hideMeters = HideMetersCheck == null || HideMetersCheck.Active; + // New glade replaced HideMetersCheck with ShowPointListSwitch (ON = shown). + bool hideMeters = HideMetersCheck != null ? HideMetersCheck.Active + : ShowPointListSwitch != null ? !ShowPointListSwitch.Active + : true; if (AppMode.Legacy && _regions.Count > 0 && !hideMeters) DrawRegionMeters(cr); @@ -849,52 +950,16 @@ private void DrawCircles(Cairo.Context cr) { - if (_jacket == null || _body == null) return; + CircleGeom g; + if (!TryGetCircleGeom(out g)) return; var circles = _jacket.Get(JacketSize, _view); - if (circles.Count == 0) return; - var t = T; - // "panel" is the body pixbuf — Form2's gridPictureBox was 546x546 - int panelW = _body.Width; - int panelH = _body.Height; - - float minX = float.MaxValue, maxX = float.MinValue; - float minY = float.MaxValue, maxY = float.MinValue; - foreach (var c in circles) - { - if (c.X < minX) minX = c.X; - if (c.X > maxX) maxX = c.X; - if (c.Y < minY) minY = c.Y; - if (c.Y > maxY) maxY = c.Y; - } - - double availW = panelW - t.FitMargin, availH = panelH - t.FitMargin; - const double circleRadius = 2.1 / 2; - double dataW = (maxX - minX) + circleRadius * 2; - double dataH = (maxY - minY) + circleRadius * 2; - if (dataW <= 0 || dataH <= 0) return; - - double scale = Math.Min(availW / dataW, availH / dataH) * 0.9; - - double offsetX = (panelW - (maxX - minX) * scale) / 2 - minX * scale; - double offsetY = (panelH - (maxY - minY) * scale) / 2 - minY * scale; - - // cluster centroid, in already-offset space - double avgX = 0, avgY = 0; - foreach (var c in circles) - { - avgX += c.X * scale + offsetX - t.OffsetX; - avgY += c.Y * scale + offsetY - t.OffsetY; - } - avgX /= circles.Count; - avgY /= circles.Count; - cr.SelectFontFace("Sans", Cairo.FontSlant.Normal, Cairo.FontWeight.Bold); foreach (var c in circles) - DrawOneCircle(cr, c, t, scale, offsetX, offsetY, avgX, avgY); + DrawOneCircle(cr, c, t, g.Scale, g.OffsetX, g.OffsetY, g.AvgX, g.AvgY); } private void DrawOneCircle(Cairo.Context cr, Circle c, Tune t, @@ -956,7 +1021,7 @@ { _tuner = new Window("MapWindow tuner — Ctrl+T to close"); _tuner.SetDefaultSize(430, 760); - _tuner.DeleteEvent += (o, a) => { _tuner = null; }; + _tuner.DeleteEvent += (o, a) => { _tuner = null; _tMirrorX = _tMirrorY = null; }; var scroll = new ScrolledWindow(); var col = new Box(Orientation.Vertical, 4); @@ -1000,6 +1065,26 @@ AddSpin(col, "MarginX", "Margin X (raw units)", -2000, 2000, 1, 0); AddSpin(col, "MarginY", "Margin Y (raw units)", -2000, 2000, 1, 0); + _tMirrorX = new CheckButton("Mirror X (flip cursor horizontally)"); + _tMirrorX.Toggled += (s, e) => + { + if (_building) return; + T.MirrorX = _tMirrorX.Active; + _lastPx = _lastPy = -1; + MapArea.QueueDraw(); + }; + col.PackStart(_tMirrorX, false, false, 0); + + _tMirrorY = new CheckButton("Mirror Y (flip cursor vertically)"); + _tMirrorY.Toggled += (s, e) => + { + if (_building) return; + T.MirrorY = _tMirrorY.Active; + _lastPx = _lastPy = -1; + MapArea.QueueDraw(); + }; + col.PackStart(_tMirrorY, false, false, 0); + col.PackStart(Header("Display"), false, false, 0); _tShowBody = Chk(col, "Show body", true); _tShowMap = Chk(col, "Show map", true); @@ -1011,10 +1096,13 @@ imgRow.PackStart(Btn("Reload images", () => { ReloadBody(); - if (_map != null) { _map.Dispose(); _map = null; } - if (_mapRaw != null) { _mapRaw.Dispose(); _mapRaw = null; } - // _map = LoadMap(MapPathForView()); - _map = LoadMap(MapPathForView(), MapNeedsMirror()); + if (AppMode.Legacy) RebuildLegacyMap(); + else + { + if (_map != null) { _map.Dispose(); _map = null; } + if (_mapRaw != null) { _mapRaw.Dispose(); _mapRaw = null; } + _map = LoadMap(MapPathForView(), MapNeedsMirror()); + } UpdateTunerInfo(); MapArea.QueueDraw(); }), true, true, 0); @@ -1122,6 +1210,7 @@ { if (_building) return; SetField(field, sb.Value); + _lastPx = _lastPy = -1; UpdateTunerInfo(); MapArea.QueueDraw(); }; @@ -1143,8 +1232,8 @@ case "MapY": t.MapY = v; break; case "MapAlpha": t.MapAlpha = v; break; case "FitMargin": t.FitMargin = v; break; - case "MarginX": t.MarginX = v; break; - case "MarginY": t.MarginY = v; break; + case "MarginX": t.MarginX = v; break; + case "MarginY": t.MarginY = v; break; } } @@ -1162,8 +1251,8 @@ case "MapY": return t.MapY; case "MapAlpha": return t.MapAlpha; case "FitMargin": return t.FitMargin; - case "MarginX": return t.MarginX; - case "MarginY": return t.MarginY; + case "MarginX": return t.MarginX; + case "MarginY": return t.MarginY; } return 0; } @@ -1173,6 +1262,8 @@ if (_tuner == null) return; _building = true; foreach (var kv in _spins) kv.Value.Value = GetField(kv.Key); + if (_tMirrorX != null) _tMirrorX.Active = T.MirrorX; + if (_tMirrorY != null) _tMirrorY.Active = T.MirrorY; if (_tunerKey != null) _tunerKey.Markup = "Editing: " + TuneKey + ""; _building = false; } @@ -1193,6 +1284,9 @@ else sb.Append(" [MISSING]"); sb.AppendLine(); + if (AppMode.Legacy) + sb.Append("legacy regions: ").Append(_regions.Count).AppendLine("/7"); + double mx, my, mw, mh; if (MapRect(out mx, out my, out mw, out mh)) sb.AppendFormat(CultureInfo.InvariantCulture, @@ -1304,6 +1398,7 @@ } /// Paste this straight over SeedDefaults() to bake values into the build. + /// Margins live in calib.txt, not in the seed. private string DumpSeed() { var inv = CultureInfo.InvariantCulture; @@ -1317,16 +1412,20 @@ if (!_tunes.ContainsKey(k)) continue; var t = _tunes[k]; sb.AppendFormat(inv, - " Seed(\"{0}\", {1:F1}, {2:F1}, {3:F2}, {4:F2}, {5:F0}, {6:F3}, {7:F1}, {8:F1}, {9:F2});\n", + " Seed(\"{0}\", {1:F1}, {2:F1}, {3:F2}, {4:F2}, {5:F0}, {6:F3}, {7:F1}, {8:F1}, {9:F2}{10});\n", k, t.OffsetX, t.OffsetY, t.SizeScale, t.Cluster, - t.FitMargin, t.MapZoom, t.MapX, t.MapY, t.MapAlpha); + t.FitMargin, t.MapZoom, t.MapX, t.MapY, t.MapAlpha, + t.MirrorX ? ", true" : ""); } sb.AppendLine("}"); sb.AppendLine("// _mapFit = MapFit." + _mapFit + ";"); return sb.ToString(); } - // ── calib.txt (same tab format CalibrationWindow writes) ── + // ── calib.txt (CalibrationWindow tab format + cursor columns) ── + // 0 size:view 1 offsetX 2 offsetY 3 sizeScale 4 cluster 5 mapZoom + // 6 mapX 7 mapY 8 mapAlpha 9 fitMargin + // 10 marginX 11 marginY 12 mirrorX 13 mirrorY (optional — old files have 10 columns) private static string CalibPath { get { return SoundWindow.AppFile("calib.txt"); } } @@ -1340,7 +1439,7 @@ } var inv = CultureInfo.InvariantCulture; - int n = 0; + int n = 0, withMargins = 0; foreach (string line in File.ReadAllLines(p)) { if (line.StartsWith("#") || line.Trim().Length == 0) continue; @@ -1349,7 +1448,11 @@ try { + string key = f[0].Trim(); var t = new Tune(); + // Keep the seeded mirror unless the file says otherwise. + if (_tunes.ContainsKey(key)) { t.MirrorX = _tunes[key].MirrorX; t.MirrorY = _tunes[key].MirrorY; } + t.OffsetX = double.Parse(f[1], inv); t.OffsetY = double.Parse(f[2], inv); t.SizeScale = double.Parse(f[3], inv); @@ -1359,14 +1462,23 @@ t.MapY = double.Parse(f[7], inv); t.MapAlpha = double.Parse(f[8], inv); t.FitMargin = double.Parse(f[9], inv); - _tunes[f[0]] = t; + if (f.Length > 10) t.MarginX = double.Parse(f[10], inv); + if (f.Length > 11) t.MarginY = double.Parse(f[11], inv); + if (f.Length > 12) t.MirrorX = f[12].Trim() == "1"; + if (f.Length > 13) t.MirrorY = f[13].Trim() == "1"; + if (f.Length > 11) withMargins++; + + _tunes[key] = t; n++; } - catch { } + catch (Exception ex) + { + Logger.Write("tune", "bad calib line '" + line + "': " + ex.Message); + } } - Logger.Write("tune", "loaded " + n + " entries from " + p); - if (verbose) Emit("loaded " + n + " entries from " + p + + Logger.Write("tune", "loaded " + n + " entries (" + withMargins + " with cursor margins) from " + p); + if (verbose) Emit("loaded " + n + " entries (" + withMargins + " with cursor margins) from " + p + "\ncalib.txt zoom values assume FitBody mode."); } @@ -1374,7 +1486,7 @@ { var inv = CultureInfo.InvariantCulture; var sb = new StringBuilder(); - sb.AppendLine("# size:view offsetX offsetY sizeScale cluster mapZoom mapX mapY mapAlpha fitMargin"); + sb.AppendLine("# size:view offsetX offsetY sizeScale cluster mapZoom mapX mapY mapAlpha fitMargin marginX marginY mirrorX mirrorY"); foreach (var kv in _tunes) { var t = kv.Value; @@ -1385,14 +1497,18 @@ t.SizeScale.ToString(inv), t.Cluster.ToString(inv), t.MapZoom.ToString(inv), t.MapX.ToString(inv), t.MapY.ToString(inv), t.MapAlpha.ToString(inv), - t.FitMargin.ToString(inv) + t.FitMargin.ToString(inv), t.MarginX.ToString(inv), + t.MarginY.ToString(inv), + t.MirrorX ? "1" : "0", t.MirrorY ? "1" : "0" })); } try { + // keep the previous file once, in case something goes wrong + if (File.Exists(CalibPath)) File.Copy(CalibPath, CalibPath + ".bak", true); File.WriteAllText(CalibPath, sb.ToString()); - Emit("saved " + CalibPath); + Emit("saved " + CalibPath + " (previous copy: calib.txt.bak)"); } catch (Exception ex) { Emit("save failed: " + ex.Message); } } @@ -1405,20 +1521,18 @@ _view = view; ReloadBody(); - - if (_map != null) { _map.Dispose(); _map = null; } - if (_mapRaw != null) { _mapRaw.Dispose(); _mapRaw = null; } - // _map = LoadMap(MapPathForView()); - _map = LoadMap(MapPathForView(), MapNeedsMirror()); + _lastPx = _lastPy = -1; if (AppMode.Legacy) { RebuildLegacyMap(); + SyncSpins(); UpdateTunerInfo(); MapArea.QueueDraw(); Logger.Write("view", "-> " + view + " (legacy)"); return; } + if (_map != null) { _map.Dispose(); _map = null; } if (_mapRaw != null) { _mapRaw.Dispose(); _mapRaw = null; } _map = LoadMap(MapPathForView(), MapNeedsMirror()); @@ -1429,16 +1543,15 @@ Logger.Write("view", "-> " + view); } + /// Swaps the BACKGROUND image for the current view + skeleton/jacket. + /// The sound map is rebuilt by SetView, not here. private void ReloadBody() { - if (AppMode.Legacy) - RebuildLegacyMap(); - else - { - if (_map != null) { _map.Dispose(); _map = null; } - if (_mapRaw != null) { _mapRaw.Dispose(); _mapRaw = null; } - _map = LoadMap(MapPathForView(), MapNeedsMirror()); - } + if (_body != null) { _body.Dispose(); _body = null; } + _body = LoadBody(); + Logger.Write("body", "-> " + _bodyPath + + (_body != null ? " [" + _body.Width + "x" + _body.Height + "]" : " [MISSING]")); + _lastPx = _lastPy = -1; UpdateTunerInfo(); MapArea.QueueDraw(); } @@ -1446,17 +1559,19 @@ private Gdk.Pixbuf LoadBody() { string stem = BodyStem(); - string full = SoundWindow.AppFile(Path.Combine("map", stem + ".png")); - _bodyPath = "map/" + stem + ".png"; - if (!File.Exists(full)) + foreach (string ext in new[] { ".png", ".jpg", ".jpeg", ".bmp" }) { - Logger.Write("body", "not found: map/" + stem + ".png"); - ListFolderOnce("map"); - return null; + string full = SoundWindow.AppFile(Path.Combine("map", stem + ext)); + if (!File.Exists(full)) continue; + _bodyPath = "map/" + stem + ext; + return Load(full); } - return Load(full); + _bodyPath = "map/" + stem + ".png"; + Logger.Write("body", "not found: map/" + stem + " (.png/.jpg/.bmp)"); + ListFolderOnce("map"); + return null; } private static void ListFolderOnce(string rel) @@ -1550,7 +1665,7 @@ var keyed = raw.AddAlpha(true, 0, 0, 0); raw.Dispose(); - if (mirror) + if (mirror) { var flipped = keyed.Flip(true); keyed.Dispose(); @@ -1591,11 +1706,10 @@ _arduino.LineReceived -= OnArduinoLine; _arduino.ConnectionChanged -= OnArduinoConnectionChanged; if (_watchdogId != 0) { GLib.Source.Remove(_watchdogId); _watchdogId = 0; } - - // NEW: cleanup legacy regions + foreach (var r in _regions) r.Dispose(); _regions.Clear(); - + _sound.Dispose(); DisposePixbufs(); if (_tuner != null) { _tuner.Destroy(); _tuner = null; } @@ -1671,14 +1785,35 @@ _debugSweepId = 0; Logger.Write("sound", "debug volume sweep stopped"); } - + + /// Debug mode: the mouse stands in for the RFID tag. Widget coords are + /// converted to BODY PIXELS with the inverse of OnMapDrawn's transform. + private void MouseProbe(double wx, double wy) + { + if (_body == null) return; + + int w = MapArea.AllocatedWidth, h = MapArea.AllocatedHeight; + double s = Math.Min((double)w / _body.Width, (double)h / _body.Height); + double ox = (w - _body.Width * s) / 2.0; + double oy = (h - _body.Height * s) / 2.0; + + _mouseBx = (wx - ox) / s; + _mouseBy = (wy - oy) / s; + _mouseProbe = true; + + Logger.Write("debug", string.Format(CultureInfo.InvariantCulture, + "mouse probe body({0:F0},{1:F0})", _mouseBx, _mouseBy)); + + UpdateAudioFromPosition(); + MapArea.QueueDraw(); + } + private void DrawWave(DrawnArgs args, DrawingArea area, WaveData wave, double cursor,double r, double g, double b) { var cr = args.Cr; int w = area.AllocatedWidth, h = area.AllocatedHeight; double mid = h / 2.0; - // cr.SetSourceRGB(0.85, 0.85, 0.85); cr.SetSourceRGB(0.965, 0.969, 0.976); cr.Rectangle(0, 0, w, h); cr.Fill(); @@ -1776,41 +1911,6 @@ return w; } - // private void LoadWaveforms(CaseDefinition def) - // { - // _heartCursor = _breathCursor = -1; - - // WaveData caseWave = LoadWave(def.SoundPath); - - // if (def.IsHeart) - // { - // _heartWave = caseWave; - // _breathWave = LoadWave("sound/SND200.wav"); // default breath sound - // _heartLive = true; - // _breathLive = BreathSoundEnabled; // only "playing" if that voice was warmed - // } - // else - // { - // _breathWave = caseWave; - // _heartWave = LoadWave("sound/SND100.wav"); // default heart sound - // _breathLive = true; - // _heartLive = HeartSoundEnabled; - // } - - // HeartWaveArea.QueueDraw(); - // BreathWaveArea.QueueDraw(); - // } - - // private static WaveData LoadWave(string rel) - // { - // string err; - // WaveData w = WaveData.Load(SoundWindow.AppFile(rel), out err); - // if (w == null) Logger.Write("wave", "load failed " + rel + ": " + err); - // else Logger.Write("wave", "loaded " + rel + " (" + - // w.Duration.ToString("F2", CultureInfo.InvariantCulture) + " s)"); - // return w; - // } - private void StartWaveTimer() { if (_waveTimerId != 0) return; @@ -1826,19 +1926,7 @@ if (BreathWaveArea != null) BreathWaveArea.QueueDraw(); } - // private bool OnWaveTick() - // { - // if (!_audible) return true; // muted: cursor stays frozen - - // double t = _playClock.Elapsed.TotalSeconds; - // _heartCursor = CursorFor(_heartWave, t); - // _breathCursor = CursorFor(_breathWave, t); - - // HeartWaveArea.QueueDraw(); - // BreathWaveArea.QueueDraw(); - // return true; - // } - private bool OnWaveTick() + private bool OnWaveTick() { if (!_audible) { @@ -1900,6 +1988,9 @@ _sound.MuteAll(); foreach (var r in _regions) r.Dispose(); _regions.Clear(); + // Free the previous case's region voices. Every OpenAL source keeps + // looping and being mixed even at gain 0, so they must not pile up. + _sound.ReleaseWhereKeyStarts("R"); for (int k = 0; k < 7; k++) { @@ -1907,7 +1998,7 @@ string sndPath = AppMode.ResolveSound(def.RegionSounds[k]); if (mapPath == null || sndPath == null) continue; // region disabled - var pb = Load(mapPath); // existing helper + var pb = Load(mapPath); if (pb == null) { Logger.Write("map", "region " + RegionLabels[k] + " map missing: " + mapPath); @@ -1915,7 +2006,12 @@ } var voice = _sound.Warm(sndPath, "R" + k + ":" + sndPath); - if (voice == null) { pb.Dispose(); continue; } + if (voice == null) + { + Logger.Write("sound", "region " + RegionLabels[k] + " sound failed: " + sndPath); + pb.Dispose(); + continue; + } _sound.SetGain(voice, 0f); var rs = new RegionSound @@ -1937,7 +2033,7 @@ private void ApplyRegionAudio(double bx, double by) { double u, v; - if (!BodyToMapUV(bx, by, out u, out v)) { MuteRegions(); return; } + if (!BodyToMapUV(bx, by, out u, out v)) { MuteRegions(); _audible = false; return; } if (_view == "back") u = 1.0 - u; // mirrored front map foreach (var r in _regions) r.Volume = r.VolumeAt(u, v); @@ -1952,11 +2048,13 @@ } foreach (var r in _regions) _sound.SetGain(r.Voice, r.Volume); + _audible = _regions.Exists(r => r.Volume > 0f); // drives the waveform cursors MapArea.QueueDraw(); // repaint the meters } private void MuteRegions() { + if (_regions.Count == 0) return; foreach (var r in _regions) { r.Volume = 0f; _sound.SetGain(r.Voice, 0f); } MapArea.QueueDraw(); } @@ -2053,51 +2151,6 @@ cr.Restore(); } - // private void DrawRegionMeters(Cairo.Context cr) - // { - // const double rowH = 18, barX = 92, barW = 120, pad = 10; - // double y0 = pad; - - // cr.Save(); - // cr.SetSourceRGBA(1, 1, 1, 0.82); - // cr.Rectangle(pad - 4, y0 - 4, barX + barW + 8, 7 * rowH + 8); - // cr.Fill(); - - // cr.SelectFontFace("Sans", Cairo.FontSlant.Normal, Cairo.FontWeight.Normal); - // cr.SetFontSize(11); - - // for (int k = 0; k < 7; k++) - // { - // RegionSound r = _regions.Find(rs => rs.Index == k); - // double vol = (r != null && r.Enabled) ? r.Volume : 0.0; - // double y = y0 + k * rowH; - - // cr.SetSourceRGB(0.15, 0.15, 0.15); - // cr.MoveTo(pad, y + rowH - 5); - // cr.ShowText(RegionLabels[k]); - // cr.NewPath(); - - // cr.SetSourceRGB(0.86, 0.86, 0.86); - // cr.Rectangle(barX, y + 3, barW, 11); - // cr.Fill(); - - // if (r != null) - // { - // byte[] c = RegionColors[k]; - // cr.SetSourceRGB(c[0] / 255.0, c[1] / 255.0, c[2] / 255.0); - // cr.Rectangle(barX, y + 3, barW * vol, 11); - // cr.Fill(); - // } - // else - // { - // cr.SetSourceRGB(0.6, 0.6, 0.6); - // cr.MoveTo(barX, y + 8.5); cr.LineTo(barX + barW, y + 8.5); - // cr.LineWidth = 1; cr.Stroke(); - // } - // } - // cr.Restore(); - // } - /// Legacy: rebuild the 7-region composite for the current view. /// Back = mirrored front (same as Form2's CreateFlippedImage fallback). private void RebuildLegacyMap() @@ -2120,29 +2173,4 @@ foreach (var r in _regions) r.Enabled = shown; if (!shown) MuteRegions(); } - - // private void AddHideLabelsOption() - // { - // if (_hideLabelsCheck != null || ShowVolumeMapSwitch == null) return; - - // _hideLabelsCheck = new CheckButton(_lang != null && _lang.IsEnglish ? "Hide labels" : "ラベルを隠す"); - // _hideLabelsCheck.StyleContext.AddClass("mappage"); - // _hideLabelsCheck.Toggled += (s, e) => - // { - // _showRegionLabels = !_hideLabelsCheck.Active; - // MapArea.QueueDraw(); - // }; - - // var box = HideMapCheck.Parent as Box; - // if (box != null) - // { - // box.PackStart(_hideLabelsCheck, false, false, 0); - // box.ReorderChild(_hideLabelsCheck, Array.IndexOf(box.Children, HideMapCheck) + 1); - // } - // else if (HideMapCheck.Parent is Container) - // ((Container)HideMapCheck.Parent).Add(_hideLabelsCheck); - - // _hideLabelsCheck.Show(); - // } - } \ No newline at end of file diff --git a/program/WavFile.cs b/program/WavFile.cs index 0ac207b..ba90981 100644 --- a/program/WavFile.cs +++ b/program/WavFile.cs @@ -9,6 +9,10 @@ public ALFormat Format; // Al.FORMAT_* public int SampleRate; + private const short FORMAT_PCM = 1; + private const short FORMAT_FLOAT = 3; + private const short FORMAT_EXTENSIBLE = unchecked((short)0xFFFE); + public static WavFile Load(string path) { using (var fs = File.OpenRead(path)) @@ -18,7 +22,7 @@ br.ReadInt32(); if (new string(br.ReadChars(4)) != "WAVE") throw new Exception("Not WAVE: " + path); - short channels = 0, bits = 0; + short format = FORMAT_PCM, channels = 0, bits = 0; int rate = 0; byte[] data = null; @@ -29,27 +33,49 @@ if (id == "fmt ") { - br.ReadInt16(); // audio format (1 = PCM) + format = br.ReadInt16(); // 1 = PCM, 3 = float, 0xFFFE = extensible channels = br.ReadInt16(); rate = br.ReadInt32(); - br.ReadInt32(); // byte rate - br.ReadInt16(); // block align + br.ReadInt32(); // byte rate + br.ReadInt16(); // block align bits = br.ReadInt16(); - if (len > 16) br.ReadBytes(len - 16); + int rest = len - 16; + + // WAVE_FORMAT_EXTENSIBLE: the real format is the first + // 2 bytes of the SubFormat GUID, 8 bytes further in. + if (format == FORMAT_EXTENSIBLE && rest >= 10) + { + br.ReadInt16(); // cbSize + br.ReadInt16(); // valid bits + br.ReadInt32(); // channel mask + format = br.ReadInt16(); // SubFormat (first 2 bytes) + rest -= 10; + } + if (rest > 0) br.ReadBytes(rest); } else if (id == "data") { + if (len < 0 || len > fs.Length - fs.Position) len = (int)(fs.Length - fs.Position); data = br.ReadBytes(len); } else { - br.ReadBytes(len); // skip unknown chunk + br.ReadBytes(len); // skip unknown chunk } - if ((len & 1) == 1) br.ReadByte(); // chunks are word-aligned + if ((len & 1) == 1 && fs.Position < fs.Length) br.ReadByte(); // chunks are word-aligned } if (data == null) throw new Exception("No data chunk: " + path); + if (channels != 1 && channels != 2) + throw new Exception("Unsupported WAV: " + channels + " channels (" + path + ")"); + + // OpenAL core only takes 8/16-bit. Convert anything wider to 16-bit. + if (format == FORMAT_FLOAT && bits == 32) { data = Float32To16(data); bits = 16; } + else if (format == FORMAT_PCM && bits == 24) { data = Int24To16(data); bits = 16; } + else if (format == FORMAT_PCM && bits == 32) { data = Int32To16(data); bits = 16; } + else if (format != FORMAT_PCM) + throw new Exception("Unsupported WAV encoding " + format + " (" + path + ")"); ALFormat fmt; if (channels == 1 && bits == 8) fmt = ALFormat.Mono8; @@ -58,7 +84,51 @@ else if (channels == 2 && bits == 16) fmt = ALFormat.Stereo16; else throw new Exception("Unsupported WAV: " + channels + "ch " + bits + "bit"); + // a partial last frame makes alBufferData fail + int frame = channels * bits / 8; + if (data.Length % frame != 0) + Array.Resize(ref data, data.Length - data.Length % frame); + return new WavFile { Data = data, Format = fmt, SampleRate = rate }; } } + + private static byte[] Int24To16(byte[] src) + { + int n = src.Length / 3; + var dst = new byte[n * 2]; + for (int i = 0; i < n; i++) + { + dst[i * 2] = src[i * 3 + 1]; // drop the lowest byte + dst[i * 2 + 1] = src[i * 3 + 2]; + } + return dst; + } + + private static byte[] Int32To16(byte[] src) + { + int n = src.Length / 4; + var dst = new byte[n * 2]; + for (int i = 0; i < n; i++) + { + dst[i * 2] = src[i * 4 + 2]; // keep the top 16 bits + dst[i * 2 + 1] = src[i * 4 + 3]; + } + return dst; + } + + private static byte[] Float32To16(byte[] src) + { + int n = src.Length / 4; + var dst = new byte[n * 2]; + for (int i = 0; i < n; i++) + { + float f = BitConverter.ToSingle(src, i * 4); + if (f > 1f) f = 1f; else if (f < -1f) f = -1f; + short s = (short)Math.Round(f * 32767f); + dst[i * 2] = (byte)(s & 0xFF); + dst[i * 2 + 1] = (byte)((s >> 8) & 0xFF); + } + return dst; + } } \ No newline at end of file