Files
sizzletracker-android/ios/app/FX/Editor/Bespoke/WavetableBespoke.swift
T
ReactorcoremeltdownandClaude Opus 5.5 435305e42a iOS 0.5.0: hand-built editors (Tape Delay, Tape Engine, Mix Tightener, Granular scope, Wavetable tables, Grain Cloud source)
Effect visualisation through the C++ effect, engine and AU; custom wavetables and
grain sources load and persist with the song; the app's slot editor hosts the
file picker for bespoke views.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:01:14 +01:00

164 lines
7.6 KiB
Swift

// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
import UniformTypeIdentifiers
/// The Wavetable's own pieces inside its generic cards (Android's WavetableEditor.kt):
/// each oscillator card draws that oscillator's table, and Oscillator 1's card
/// carries LOAD TABLE, because a loaded WAV becomes the "Custom" table and is
/// selected on oscillator 1.
@MainActor
enum WavetableBespoke {
static func preview(osc: Int, tone: Color, model: DeviceModel) -> AnyView? {
AnyView(WavetablePreview(osc: osc, tone: tone, model: model))
}
static func loadTableAction(tone: Color, model: DeviceModel) -> AnyView? {
AnyView(LoadTableAction(model: model))
}
/// What the preview draws of a table: up to 16 of its frames, 128 points each.
struct Curves {
let frames: Int
let rows: [(points: [Float], frame: Int)]
}
/// Curves by table (a factory name, or a custom sample id + frame length):
/// tables are immutable once built, so each is read and thinned out once.
private static var cache: [String: Curves] = [:]
static func curves(key: String, osc: Int, data: DeviceDataSource?) -> Curves? {
if let c = cache[key] { return c }
guard let t = data?.wavetableFrames(osc: osc), t.frames > 0, t.size >= 128,
t.data.count >= t.frames * t.size else { return nil }
let n = t.size, step = Swift.max(1, t.frames / 16)
let rows = stride(from: 0, to: t.frames, by: step).map { f -> (points: [Float], frame: Int) in
((0..<128).map { i in t.data[f * n + i * n / 128] }, f)
}
let c = Curves(frames: t.frames, rows: rows)
if cache.count > 64 { cache.removeAll() }
cache[key] = c
return c
}
/// The table oscillator [osc] plays, and the key its curves are cached under.
static func tableKey(osc: Int, model: DeviceModel) -> (name: String, custom: Bool, key: String) {
let name = model.choice("o\(osc)table")
guard name == "Custom" else { return (name, false, "F|" + name) }
let id = model.data?.hiddenValue("sfSample") ?? ""
return (name, true, "C|\(id)|\(model.choice("wtframe"))")
}
/// Native floats from a bridge call's bytes.
static func floats(_ d: Data) -> [Float] { d.withUnsafeBytes { Array($0.bindMemory(to: Float.self)) } }
}
/// Every frame of oscillator [osc]'s table stacked back to front, the one at its POSITION lit.
struct WavetablePreview: View {
let osc: Int
let tone: Color
@ObservedObject var model: DeviceModel
/// Bumped while the table is being built, to look again.
@State private var retry = 0
var body: some View {
let (name, custom, key) = WavetableBespoke.tableKey(osc: osc, model: model)
let curves = WavetableBespoke.curves(key: key, osc: osc, data: model.data)
let unloaded = custom && model.data?.hiddenValue("sfSample") == nil
let caption = curves.map { "\(custom ? "your table" : name) · \($0.frames) frames" }
?? (unloaded ? "Custom · no table loaded" : "\(name) (preparing…)")
let pos = model.value("o\(osc)pos")
ZStack(alignment: .topLeading) {
if let c = curves {
Canvas { ctx, size in draw(c, pos: pos, in: ctx, size: size) }
}
Text(caption).font(Theme.mono(9)).foregroundColor(Theme.dim)
.padding(.horizontal, 4).padding(.vertical, 2)
}
.frame(maxWidth: .infinity, minHeight: 72, maxHeight: 72)
.background(Theme.background)
.overlay(Rectangle().stroke(Theme.grid, lineWidth: 1))
.task(id: retry) {
guard curves == nil, !unloaded, retry < 60 else { return }
try? await Task.sleep(nanoseconds: 300_000_000)
retry += 1
}
}
private func draw(_ c: WavetableBespoke.Curves, pos: Float, in ctx: GraphicsContext, size: CGSize) {
let k = c.rows.count
let rowH = size.height * 0.45
let lit = Int(pos * Float(c.frames - 1) + 0.5)
let near = Swift.max(1, c.frames / k)
let w = size.width * 0.76
for idx in stride(from: k - 1, through: 0, by: -1) {
let row = c.rows[idx]
let depth = k > 1 ? CGFloat(idx) / CGFloat(k - 1) : 0
let x0 = size.width * 0.04 + depth * size.width * 0.18
let yMid = size.height * 0.72 - depth * size.height * 0.45
let on = abs(row.frame - lit) * 2 <= near
let n = row.points.count
var path = Path()
for i in 0..<n {
let p = CGPoint(x: x0 + w * CGFloat(i) / CGFloat(n), y: yMid - CGFloat(row.points[i]) * rowH * 0.5)
if i == 0 { path.move(to: p) } else { path.addLine(to: p) }
}
ctx.stroke(path, with: .color(on ? tone : Theme.text.opacity(0.25)), lineWidth: on ? 1.5 : 0.75)
}
}
}
/// LOAD TABLE in Oscillator 1's title: a Serum / WaveEdit / power-of-two-frame WAV
/// becomes the "Custom" table and is selected on oscillator 1.
struct LoadTableAction: View {
@ObservedObject var model: DeviceModel
@State private var pickerShown = false
@Environment(\.deviceFilePicker) private var hostPicker
@State private var importError: String?
var body: some View {
Text("+ LOAD TABLE").font(Theme.mono(11)).foregroundColor(Theme.accent)
.padding(.horizontal, 8).padding(.vertical, 3)
.overlay(Rectangle().stroke(Theme.accent.opacity(0.6), lineWidth: 1))
.contentShape(Rectangle())
.onTapGesture { if let pick = hostPicker { pick { url in load(url) } } else { pickerShown = true } }
// The completion needs nothing but the picked URL (iOS 15 resets the
// presentation binding before calling it).
.fileImporter(isPresented: $pickerShown, allowedContentTypes: [.wav, .audio, .data],
allowsMultipleSelection: false) { result in
guard case .success(let urls) = result, let url = urls.first else { return }
load(url)
}
.alert("Import failed", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } }),
actions: { Button("OK") { importError = nil } }, message: { Text(importError ?? "") })
}
private func load(_ url: URL) {
guard let data = model.data else { importError = "Not available here yet."; return }
if let err = data.loadFile(url, kind: "wavetable") { importError = err; return }
// The slot now plays Custom on oscillator 1 at the detected frame length;
// show that (the backend has written the same values).
select("o1table", "Custom")
if let frame = data.hiddenValue("wtframe") { select("wtframe", frame) }
}
private func select(_ key: String, _ choice: String) {
if let i = model.params[key]?.choices.firstIndex(of: choice) { model.set(key, Float(i)) }
}
}
// MARK: - plug-in backend
extension AUDataSource {
/// The built-in tables (the extension has no sample store for a custom one yet).
func wavetableFrames(osc: Int) -> (frames: Int, size: Int, data: [Float])? {
guard let p = au.parameterTree?.allParameters.first(where: { $0.identifier == "o\(osc)table" }),
let names = p.valueStrings, !names.isEmpty else { return nil }
let name = names[Swift.max(0, Swift.min(names.count - 1, Int(p.value.rounded())))]
var frames = 0, size = 0
guard let d = SizzleDeviceAU.factoryWavetable(named: name, blocking: Snapshot.active, frames: &frames, size: &size)
else { return nil }
return (frames, size, WavetableBespoke.floats(d))
}
}