diff --git a/Sources/LyrebirdShoeGaze/Pedals/KarplusResonatorPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/KarplusResonatorPedal.swift index 7e9f532..c499c95 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/KarplusResonatorPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/KarplusResonatorPedal.swift @@ -25,9 +25,11 @@ import LyrebirdUI /// Wraps Lyrebird's `KarplusStrong` run fully wet; the base `Pedal` `mix` sets the blend of the /// ringing bank against the dry note (an even mix by default). /// -/// The root can be set two ways (the **Tuning** selector): **Free** sweeps the continuous **Tune** -/// Hz knob; **Note** tunes the root to a musical pitch chosen with the **Note** (C…B) and **Octave** -/// selectors in equal temperament (A4 = 440 Hz, so A3 = 220 Hz). +/// The root can be set two ways, chosen by the **Tuning** switch: **Free** sweeps the continuous +/// **Tune** Hz knob; **Pitched** tunes the root to a musical note chosen with a single **Root** +/// selector that steps through every semitone from E1 up to E5 (the top of the treble staff), +/// captioned by name and octave (`E1`, `A3`, `E5`) in equal temperament (A4 = 440 Hz, so A3 = 220). +/// In **Pitched** the Tune Hz knob is ignored; in **Free** the Root selector is hidden. /// /// ## Knobs /// - `tune`: Root frequency of the string bank in Hz (used in **Free** tuning). Range `[40, 660]` @@ -37,11 +39,13 @@ import LyrebirdUI /// - `sensitivity`: How readily playing plucks the strings. Range `[0, 1]`: higher = lower trigger /// threshold, so quieter notes still excite the bank. /// +/// ## Switch +/// - `tuning`: Root source — **Free** (the Tune Hz knob) or **Pitched** (the Root selector). Rebuilds. +/// /// ## Selectors (all rebuild on change) /// - `voicing`: Chord the four strings are tuned to: Drone, Octaves, Shimmer. -/// - `tuning`: Root source — Free (the Tune Hz knob) or Note (the Note + Octave selectors). -/// - `note`: Pitch class of the root in **Note** tuning: C … B. -/// - `octave`: Octave of the root in **Note** tuning: `1 … 6`. +/// - `pitchedNote`: Root note in **Pitched** tuning — a chromatic stop from E1 to E5 (shown only in +/// **Pitched** mode). The value is the MIDI note number; A3 (MIDI 57) = 220 Hz. public final class KarplusResonatorPedal: Pedal { /// One-line description shown in the picker and info panel. @@ -66,14 +70,13 @@ public final class KarplusResonatorPedal: Pedal { /// Selected voicing index into ``voicings``. A knob-picker selector; rebuilds on change. @UIParam public var voicing: Double = 0.0 - /// Root-tuning source: `0` = Free (the Tune Hz knob), `1` = Note (the Note + Octave selectors). + /// Root-tuning source: `0` = Free (the Tune Hz knob), `1` = Pitched (the Root selector). A + /// two-position switch; rebuilds on change. @UIParam public var tuning: Double = 0.0 - /// Pitch class of the root in Note tuning: `0` = C … `11` = B. A knob-picker; rebuilds on change. - @UIParam public var note: Double = 9.0 // A - - /// Octave of the root in Note tuning (`1 … 6`). A knob-picker; rebuilds on change. - @UIParam public var octave: Double = 3.0 // A3 = 220 Hz by default + /// Root note in Pitched tuning, as a MIDI note number. A chromatic selector stepping E1 (MIDI 28) + /// to E5 (MIDI 76); rebuilds on change. Defaults to A3 (MIDI 57) = 220 Hz. + @UIParam public var pitchedNote: Double = 57.0 // A3 = 220 Hz by default // MARK: - Voicings @@ -98,37 +101,46 @@ public final class KarplusResonatorPedal: Pedal { // MARK: - Note tuning - /// Tuning-source values written by the ``tuning`` selector. + /// Tuning-source values written by the ``tuning`` switch. private static let tuningFreeValue: Double = 0.0 - private static let tuningNoteValue: Double = 1.0 + private static let tuningPitchedValue: Double = 1.0 - /// Pitch-class captions for the ``note`` selector, index `0 … 11`. + /// Pitch-class captions, index `0 … 11` (C … B). private static let pitchClassNames: [String] = [ "C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B", ] - /// Octaves offered by the ``octave`` selector (the value stored is the octave number itself). - private static let octaveChoices: [Int] = [1, 2, 3, 4, 5, 6] - /// Equal-temperament reference: A4 = 440 Hz is MIDI note 69, 12 semitones per octave. private static let referenceFrequency: Double = 440.0 private static let referenceMidiNote: Int = 69 private static let semitonesPerOctave: Int = 12 - /// Equal-tempered frequency in Hz for a pitch class (`0 = C … 11 = B`) and octave, using the - /// scientific-pitch convention where C4 is middle C (MIDI 60), so A3 (pitch class `9`, octave - /// `3`) is MIDI 57 → 220 Hz. + /// Lowest Pitched root — E1 (MIDI 28, ≈ 41 Hz), a low bass E mirroring the Free knob's floor. + private static let lowestMidiNote: Int = 28 + /// Highest Pitched root — E5 (MIDI 76, ≈ 659 Hz), the top space of the treble staff. + private static let highestMidiNote: Int = 76 + + /// Equal-tempered frequency in Hz for a MIDI note number, using A4 = 440 Hz (MIDI 69). A3 + /// (MIDI 57) → 220 Hz; C4 (middle C, MIDI 60) → 261.63 Hz. /// - /// - Parameters: - /// - pitchClass: `0 … 11` (C … B). - /// - octave: Scientific-pitch octave number. + /// - Parameter midi: MIDI note number. /// - Returns: The note's frequency in Hz. - static func noteFrequency(pitchClass: Int, octave: Int) -> Double { - let midiNote: Int = (octave + 1) * semitonesPerOctave + pitchClass - let semitonesFromReference: Double = Double(midiNote - referenceMidiNote) / Double(semitonesPerOctave) + static func frequency(forMidiNote midi: Int) -> Double { + let semitonesFromReference: Double = Double(midi - referenceMidiNote) / Double(semitonesPerOctave) return referenceFrequency * pow(2.0, semitonesFromReference) } + /// Name-plus-octave caption for a MIDI note number in scientific-pitch convention (MIDI 60 = C4), + /// e.g. MIDI 57 → `"A3"`, MIDI 76 → `"E5"`. + /// + /// - Parameter midi: MIDI note number (expected `lowestMidiNote … highestMidiNote`). + /// - Returns: The note's caption. + static func caption(forMidiNote midi: Int) -> String { + let pitchClass: Int = ((midi % semitonesPerOctave) + semitonesPerOctave) % semitonesPerOctave + let octaveNumber: Int = midi / semitonesPerOctave - 1 + return pitchClassNames[pitchClass] + String(octaveNumber) + } + // MARK: - Constants /// Pedal returns the bank fully wet; the base `mix` blends it against the dry note. An even mix @@ -136,9 +148,10 @@ public final class KarplusResonatorPedal: Pedal { private static let defaultMix: Double = 0.5 /// Maximum delay time for each string, in seconds — sizes the Karplus delay line. Covers the - /// lowest resonator across both tuning modes: the lowest Note root is C1 (≈ 32.7 Hz), and the - /// Octaves voicing drops a string half an octave below that (≈ 16.4 Hz, a ~0.061 s period), so - /// `0.08 s` leaves margin. `KarplusStrong` clamps any lower frequency to the line length anyway. + /// lowest resonator across both tuning modes: the lowest root is ≈ 40 Hz (Free floor, or the + /// Pitched E1 ≈ 41 Hz), and the Octaves voicing drops a string a full octave below that + /// (ratio 0.5 → ≈ 20 Hz, a ~0.05 s period), so `0.08 s` leaves margin. `KarplusStrong` clamps any lower + /// frequency to the line length anyway. private let maxStringDelayTime: Double = 0.08 /// Feedback (ring length) mapped from `sustain = 0`: a short, plucky decay. @@ -197,30 +210,48 @@ public final class KarplusResonatorPedal: Pedal { ] } + // MARK: - Switch + + public override var effectSwitches: [PedalSwitch] { + [ + // Picks the root source. Rebuilds: it swaps the build-time root (live Tune knob vs a fixed + // note Hz) and toggles whether the Root selector is shown. + PedalSwitch( + label: "Tuning", + node: $tuning, + options: [ + PedalSwitch.Option(title: "Free", value: KarplusResonatorPedal.tuningFreeValue), + PedalSwitch.Option(title: "Pitched", value: KarplusResonatorPedal.tuningPitchedValue), + ], + rebuildsOnChange: true + ), + ] + } + // MARK: - Selectors public override var effectSelectors: [PedalSelectorKnob] { let voicingStops: [PedalSelectorKnob.Stop] = KarplusResonatorPedal.voicings.enumerated().map { index, voicing in PedalSelectorKnob.Stop(title: voicing.title, value: Double(index)) } - let tuningStops: [PedalSelectorKnob.Stop] = [ - PedalSelectorKnob.Stop(title: "Free", value: KarplusResonatorPedal.tuningFreeValue), - PedalSelectorKnob.Stop(title: "Note", value: KarplusResonatorPedal.tuningNoteValue), - ] - let noteStops: [PedalSelectorKnob.Stop] = KarplusResonatorPedal.pitchClassNames.enumerated().map { index, name in - PedalSelectorKnob.Stop(title: name, value: Double(index)) - } - let octaveStops: [PedalSelectorKnob.Stop] = KarplusResonatorPedal.octaveChoices.map { octaveValue in - PedalSelectorKnob.Stop(title: String(octaveValue), value: Double(octaveValue)) - } - return [ - // Each selector feeds a build-time structural choice (voicing ratios size each string's - // delay line; the tuning root picks the live knob vs a fixed Hz), so each rebuilds. + // Voicing always shows and stays at selector index 0 — so a preset's positional selector + // values line up regardless of tuning mode. The Root selector is appended only in Pitched + // mode (and `tuning` is restored in the switch pass before this one, so the count matches). + var selectors: [PedalSelectorKnob] = [ + // Voicing ratios size each string's delay line, so it is a build-time structural choice. PedalSelectorKnob(label: "Voicing", node: $voicing, stops: voicingStops, rebuildsOnChange: true), - PedalSelectorKnob(label: "Tuning", node: $tuning, stops: tuningStops, rebuildsOnChange: true), - PedalSelectorKnob(label: "Note", node: $note, stops: noteStops, rebuildsOnChange: true), - PedalSelectorKnob(label: "Octave", node: $octave, stops: octaveStops, rebuildsOnChange: true), ] + if Int(tuning.rounded()) == Int(KarplusResonatorPedal.tuningPitchedValue) { + let rootStops: [PedalSelectorKnob.Stop] = + (KarplusResonatorPedal.lowestMidiNote ... KarplusResonatorPedal.highestMidiNote).map { midi in + PedalSelectorKnob.Stop(title: KarplusResonatorPedal.caption(forMidiNote: midi), value: Double(midi)) + } + // The chosen note sets a fixed root Hz folded into the graph at build time, so it rebuilds. + selectors.append( + PedalSelectorKnob(label: "Root", node: $pitchedNote, stops: rootStops, rebuildsOnChange: true) + ) + } + return selectors } // MARK: - Init @@ -251,12 +282,14 @@ public final class KarplusResonatorPedal: Pedal { let ratios: [Double] = KarplusResonatorPedal.voicings[index].ratios // Root source (read at build time, so switching rebuilds). Free: the live Tune Hz knob. - // Note: a fixed equal-tempered frequency from the Note + Octave selectors. + // Pitched: a fixed equal-tempered frequency from the Root note selector. let rootFreq: any ValidGeneratorInput - if Int(tuning.rounded()) == Int(KarplusResonatorPedal.tuningNoteValue) { - let pitchClass: Int = min(max(0, Int(note.rounded())), KarplusResonatorPedal.pitchClassNames.count - 1) - let octaveValue: Int = Int(octave.rounded()) - rootFreq = KarplusResonatorPedal.noteFrequency(pitchClass: pitchClass, octave: octaveValue) + if Int(tuning.rounded()) == Int(KarplusResonatorPedal.tuningPitchedValue) { + let midiNote: Int = min( + max(KarplusResonatorPedal.lowestMidiNote, Int(pitchedNote.rounded())), + KarplusResonatorPedal.highestMidiNote + ) + rootFreq = KarplusResonatorPedal.frequency(forMidiNote: midiNote) } else { rootFreq = $tune } diff --git a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift index b1d89f2..5ebf939 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift @@ -92,6 +92,12 @@ extension Pedal { /// always applied regardless of any count mismatch. Presets saved before a given control existed /// carry an empty array for it, leaving those controls at their defaults. /// + /// **Pass order is contractual: switches are restored before selectors.** A pedal whose selector + /// *set* depends on a switch value (e.g. ``KarplusResonatorPedal``, whose Root note selector + /// appears only in the Pitched tuning mode) relies on `tuning` being written in the switch pass + /// before `effectSelectors` is re-read in the selector pass, so the mode-dependent selector exists + /// to receive its value. Do not reorder these passes without revisiting such pedals. + /// /// - Parameter rawState: The state to restore. The `state.type` is not validated against /// `displayName` — the caller is responsible for matching types before calling this method. public func applyState(_ rawState: PedalState) { diff --git a/Tests/LyrebirdShoeGazeTests/KarplusResonatorPedalTests.swift b/Tests/LyrebirdShoeGazeTests/KarplusResonatorPedalTests.swift index be35e73..b247b54 100644 --- a/Tests/LyrebirdShoeGazeTests/KarplusResonatorPedalTests.swift +++ b/Tests/LyrebirdShoeGazeTests/KarplusResonatorPedalTests.swift @@ -364,53 +364,76 @@ struct KarplusResonatorPedalTests { // MARK: - Wiring - @Test func exposesKnobsAndSelectors() throws { + @Test func exposesControls() throws { let pedal: KarplusResonatorPedal = KarplusResonatorPedal() #expect(pedal.effectKnobs.map { $0.label } == ["Tune", "Sustain", "Tone", "Sensitivity"]) - let selectors: [PedalSelectorKnob] = pedal.effectSelectors - #expect(selectors.map { $0.label } == ["Voicing", "Tuning", "Note", "Octave"]) - #expect(selectors.first?.stops.map { $0.title } == ["Drone", "Octaves", "Shimmer"]) - let tuning: PedalSelectorKnob? = selectors.first { $0.label == "Tuning" } - #expect(tuning?.stops.map { $0.title } == ["Free", "Note"]) - let note: PedalSelectorKnob? = selectors.first { $0.label == "Note" } - #expect(note?.stops.count == 12) - #expect(note?.stops.first?.title == "C") + // One Tuning switch, Free/Pitched. + #expect(pedal.effectSwitches.map { $0.label } == ["Tuning"]) + let tuning: PedalSwitch? = pedal.effectSwitches.first { $0.label == "Tuning" } + #expect(tuning?.options.map { $0.title } == ["Free", "Pitched"]) + #expect(tuning?.rebuildsOnChange == true) + // Default (Free) shows only the Voicing selector — the Root note knob is hidden. + #expect(pedal.effectSelectors.map { $0.label } == ["Voicing"]) + #expect(pedal.effectSelectors.first?.stops.map { $0.title } == ["Drone", "Octaves", "Shimmer"]) + + // Pitched reveals the Root chromatic selector at index 1, spanning E1 … E5. + pedal.tuning = 1.0 + #expect(pedal.effectSelectors.map { $0.label } == ["Voicing", "Root"]) + let root: PedalSelectorKnob? = pedal.effectSelectors.first { $0.label == "Root" } + #expect(root?.stops.count == 49) // MIDI 28 … 76 inclusive + #expect(root?.stops.first?.title == "E1") + #expect(root?.stops.last?.title == "E5") } - @Test func noteFrequencyMapsEqualTemperament() throws { - // A4 = 440, so A3 = 220 and A4 = 440; C4 (middle C, MIDI 60) ≈ 261.63. - #expect(abs(KarplusResonatorPedal.noteFrequency(pitchClass: 9, octave: 3) - 220.0) < 0.01) - #expect(abs(KarplusResonatorPedal.noteFrequency(pitchClass: 9, octave: 4) - 440.0) < 0.01) - #expect(abs(KarplusResonatorPedal.noteFrequency(pitchClass: 0, octave: 4) - 261.6256) < 0.01) + @Test func frequencyMapsEqualTemperament() throws { + // A4 = 440 (MIDI 69), so A3 (MIDI 57) = 220; C4 (middle C, MIDI 60) ≈ 261.63. + #expect(abs(KarplusResonatorPedal.frequency(forMidiNote: 57) - 220.0) < 0.01) + #expect(abs(KarplusResonatorPedal.frequency(forMidiNote: 69) - 440.0) < 0.01) + #expect(abs(KarplusResonatorPedal.frequency(forMidiNote: 60) - 261.6256) < 0.01) + #expect(KarplusResonatorPedal.caption(forMidiNote: 28) == "E1") + #expect(KarplusResonatorPedal.caption(forMidiNote: 57) == "A3") + #expect(KarplusResonatorPedal.caption(forMidiNote: 76) == "E5") + #expect(KarplusResonatorPedal.caption(forMidiNote: 61) == "C♯4") // sharp pitch class } - @Test func noteModeTunesTheRootToThePitch() throws { - // Tuning = Note, A3, Drone voicing → the ring's fundamental sits at 220 Hz regardless of the - // 110 Hz pluck or the Tune Hz knob. + @Test func pitchedModeTunesTheRootToThePitch() throws { + // Tuning = Pitched, A3 (MIDI 57), Drone voicing → the ring's fundamental sits at 220 Hz + // regardless of the 110 Hz pluck or the Tune Hz knob. let out: [Float] = try renderPluck { pedal in pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6 - pedal.tune = 60.0 // deliberately off, to prove Note overrides it - pedal.tuning = 1.0; pedal.note = 9.0; pedal.octave = 3.0 + pedal.tune = 60.0 // deliberately off, to prove Pitched overrides it + pedal.tuning = 1.0; pedal.pitchedNote = 57.0 } let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 400.0) - #expect(abs(f - 220.0) / 220.0 < 0.1, "Note A3 should ring near 220 Hz, got \(f)") + #expect(abs(f - 220.0) / 220.0 < 0.1, "Pitched A3 should ring near 220 Hz, got \(f)") } - @Test func noteModeOctaveRaisesThePitch() throws { - // A3 vs A4 — one octave up should roughly double the ring fundamental. + @Test func pitchedModeOctaveRaisesThePitch() throws { + // A3 (MIDI 57) vs A4 (MIDI 69) — one octave up should roughly double the ring fundamental. let a3: [Float] = try renderPluck { pedal in pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6 - pedal.tuning = 1.0; pedal.note = 9.0; pedal.octave = 3.0 + pedal.tuning = 1.0; pedal.pitchedNote = 57.0 } let a4: [Float] = try renderPluck { pedal in pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6 - pedal.tuning = 1.0; pedal.note = 9.0; pedal.octave = 4.0 + pedal.tuning = 1.0; pedal.pitchedNote = 69.0 } let f3: Double = fundamentalHz(a3, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 700.0) let f4: Double = fundamentalHz(a4, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 700.0) #expect(f4 > f3 * 1.5, "A4 should ring well above A3: a4 \(f4) vs a3 \(f3)") } + @Test func pitchedModeReachesTrebleStaffTop() throws { + // The Root selector's top stop is E5 (MIDI 76 ≈ 659 Hz). Drone voicing shares the root period. + let e5: Double = 659.25 + let out: [Float] = try renderPluck { pedal in + pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6 + pedal.tuning = 1.0; pedal.pitchedNote = 76.0; pedal.voicing = 0.0 + } + let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 300.0, maxHz: 900.0) + #expect(abs(f - e5) / e5 < 0.1, "Pitched E5 should ring near \(e5) Hz, got \(f)") + } + @Test func presetRoundTripPreservesControls() throws { let pedal: KarplusResonatorPedal = KarplusResonatorPedal() pedal.tune = 123.4 @@ -418,9 +441,8 @@ struct KarplusResonatorPedalTests { pedal.tone = 0.6 pedal.sensitivity = 0.3 pedal.voicing = 2.0 - pedal.tuning = 1.0 - pedal.note = 4.0 - pedal.octave = 5.0 + pedal.tuning = 1.0 // Pitched, so the Root selector is captured + pedal.pitchedNote = 64.0 // E4 let state: PedalState = pedal.captureState() let restored: KarplusResonatorPedal = KarplusResonatorPedal() @@ -432,8 +454,38 @@ struct KarplusResonatorPedalTests { #expect(restored.sensitivity == 0.3) #expect(restored.voicing == 2.0) #expect(restored.tuning == 1.0) - #expect(restored.note == 4.0) - #expect(restored.octave == 5.0) + #expect(restored.pitchedNote == 64.0) + } + + @Test func freeStateRestoresOntoAPitchedPedal() throws { + // A Free preset applied to an instance already in Pitched mode: the switch pass writes + // tuning = 0 before effectSelectors is re-read, so the selector list collapses to [Voicing] + // and the stale Root value is dropped — no positional corruption. + let saved: KarplusResonatorPedal = KarplusResonatorPedal() // defaults to Free + saved.voicing = 1.0 + saved.tune = 200.0 + let state: PedalState = saved.captureState() + #expect(state.selectorValues.count == 1, "a Free preset should carry only the Voicing selector") + + let target: KarplusResonatorPedal = KarplusResonatorPedal() + target.tuning = 1.0 // put it in Pitched first + target.pitchedNote = 76.0 + target.applyState(state) + + #expect(target.tuning == 0.0, "restoring a Free preset should return the switch to Free") + #expect(target.voicing == 1.0) + #expect(target.tune == 200.0) + #expect(target.effectSelectors.map { $0.label } == ["Voicing"]) + } + + @Test func pitchedNoteClampsOutOfRange() throws { + // A pitchedNote past the Root selector's E1…E5 window still rings (clamped at build time), + // never crashing or going silent. + let out: [Float] = try renderPluck { pedal in + pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6 + pedal.tuning = 1.0; pedal.pitchedNote = 200.0 // far above E5 + } + #expect(hasNonSilentOutput(out), "out-of-range pitchedNote should clamp and still ring") } @Test func registeredInBuiltInRegistry() throws {