// SaturationCurve.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Darwin /// The waveshaping curve applied per (oversampled) sample by ``OversampledSaturator``. /// /// Each case reproduces the nonlinearity a specific drive pedal used to build inline from /// stock generators, so moving that pedal onto the oversampled path is voicing-preserving: /// /// - `tanhPreGain` — `tanh(drive · x)`. Symmetric soft saturation with the drive applied /// *before* the `tanh` (the fuzz voicing: hard pre-gain squares the wave off). /// - `softClipNormalized` — `tanh(drive · x) / tanh(drive)`. The same curve normalised so a /// unity-drive signal passes near-linearly (the overdrive voicing). /// - `tanhPostGainHardClip(low:high:)` — `clip(tanh(x) · drive, low, high)`. A gentle `tanh` /// stage, post-gained by drive into a hard clipper (the distortion voicing). The hard clip /// is the dominant harmonic source and the reason this curve wants the highest oversampling /// factor. public enum SaturationCurve: Sendable { case tanhPreGain case softClipNormalized case tanhPostGainHardClip(low: Double, high: Double) /// Applies the curve to a single sample. /// /// - Parameters: /// - x: Input sample (already at the oversampled rate). /// - drive: Drive amount. The caller clamps this to a small positive floor so /// `softClipNormalized`'s `tanh(drive)` denominator is never zero. /// - Returns: The shaped sample. @inline(__always) func apply(_ x: Double, drive: Double) -> Double { switch self { case .tanhPreGain: return tanh(drive * x) case .softClipNormalized: return tanh(drive * x) / tanh(drive) case .tanhPostGainHardClip(let low, let high): let shaped: Double = tanh(x) * drive return Swift.min(high, Swift.max(low, shaped)) } } }