SPB Git

Repository Public License

PulseCalibrationView.swift 20.8 KB 461 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/PulseBeat/PulseCalibrationView.swift10// Description      : Pulse Beat — the timing screen: tap along to a click to11//                    measure the latency of the current audio route (stored12//                    separately for Bluetooth), plus manual audio and visual13//                    offsets.14// Module           : Games15// Repository       : https://git.spboucher.ai/orix-arcade16// Created          : 2026-11-2217// Last Modified    : 2026-11-2218//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : Proprietary, all rights reserved (see license file)84// License File     : LICENSE85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import SwiftUI93import UIKit94import AVFoundation95import QuartzCore9697/// Plays the click track on the game's own transport and records taps on the same rendered timeline.98final class PulseCalibrationSession {99    private let transport: PulseTransport100    private(set) var clicks: [Double] = []101    private(set) var taps: [Double] = []102    private var prepared: PulsePrepared?103104    init(audio: AudioDirector) {105        transport = PulseTransport(audio: audio)106    }107108    var reportedLatency: Double { transport.timing.latency }109110    func start(audio: AudioDirector) {111        let track = PulseSynth.clickTrack(count: PulseCalibration.clickCount, interval: PulseCalibration.interval, lead: PulseCalibration.lead)112        clicks = track.clicks113        taps = []114        let ready = PulsePrepared(trackID: "calibration", buffer: audio.isRunning ? AudioDirector.makeBuffer(mono: track.samples) : nil,115                                  frames: track.samples.count, envelope: PulseEnvelope(), renderSeconds: 0)116        prepared = ready117        transport.timing = PulseTiming()118        transport.load(buffer: ready.buffer, frames: ready.frames)119        transport.start(fromFrame: 0, delay: 0.35)120    }121122    func stop() {123        transport.stop()124    }125126    func dispose() {127        transport.dispose()128        prepared = nil129    }130131    /// Records a tap by the timestamp of its touch event.132    func tap(atHost host: Double) {133        guard transport.isRunning else { return }134        taps.append(transport.rawPosition(atHost: host))135    }136137    /// Position the player is hearing right now, as far as the system knows.138    func heardNow() -> Double {139        transport.poll()140        return transport.rawPosition(atHost: CACurrentMediaTime()) - transport.timing.latency141    }142143    var isOver: Bool {144        guard let last = clicks.last, transport.isRunning else { return true }145        return transport.rawPosition(atHost: CACurrentMediaTime()) > last + PulseCalibration.interval146    }147148    var measurement: PulseCalibration.Measurement? { PulseCalibration.measure(taps: taps, clicks: clicks) }149}150151/// A surface that reports the timestamp of each touch-down event, which SwiftUI gestures do not expose.152struct PulseTapPad: UIViewRepresentable {153    let onTap: (TimeInterval) -> Void154155    final class Pad: UIView {156        var onTap: ((TimeInterval) -> Void)?157        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {158            for touch in touches { onTap?(touch.timestamp) }159        }160    }161162    func makeUIView(context: Context) -> Pad {163        let pad = Pad()164        pad.isMultipleTouchEnabled = true165        pad.backgroundColor = .clear166        pad.onTap = onTap167        pad.isAccessibilityElement = true168        pad.accessibilityLabel = "Tap pad"169        pad.accessibilityTraits = .allowsDirectInteraction170        return pad171    }172173    func updateUIView(_ pad: Pad, context: Context) { pad.onTap = onTap }174}175176struct PulseCalibrationView: View {177    let onDone: () -> Void178    @Environment(ArcadeServices.self) private var services179    @State private var session: PulseCalibrationSession?180    @State private var listening = false181    @State private var tapCount = 0182    @State private var measured: PulseCalibration.Measurement?183    @State private var proposal: Int?184    @State private var failed = false185    @State private var route = PulseRoute.current186187    private let accent = GameTheme.pulseBeat188189    var body: some View {190        let save = services.save.pulse191        let audible = services.audio.isRunning192        ZStack {193            AuroraBackground(theme: accent)194            VStack(spacing: 0) {195                HStack(spacing: OrixSpace.sm) {196                    OrixIconButton(systemImage: "chevron.left", label: "Back to tracks", action: close)197                        .accessibilityIdentifier("pulse-calibration-back")198                    VStack(alignment: .leading, spacing: 1) {199                        Text("Timing").font(OrixFont.title).foregroundStyle(OrixColor.textPrimary)200                        HStack(spacing: 5) {201                            Image(systemName: route.symbol).font(.system(size: 11, weight: .bold))202                            Text("\(route.title) · stored separately").font(OrixFont.caption)203                        }204                        .foregroundStyle(OrixColor.textSecondary)205                    }206                    Spacer()207                }208                .padding(.horizontal, OrixSpace.md)209                .padding(.top, OrixSpace.xs)210                .padding(.bottom, OrixSpace.sm)211212                ScrollView {213                    VStack(alignment: .leading, spacing: OrixSpace.md) {214                        tapAlong(save: save, audible: audible)215                        manual(save: save)216                    }217                    .padding(.horizontal, OrixSpace.md)218                    .padding(.bottom, OrixSpace.lg)219                }220                .scrollIndicators(.hidden)221                .scrollDisabled(listening)222            }223        }224        .onAppear { services.audio.setMusic(nil) }225        .onDisappear {226            session?.dispose()227            session = nil228        }229        .onReceive(NotificationCenter.default.publisher(for: AVAudioSession.routeChangeNotification).receive(on: DispatchQueue.main)) { _ in230            route = PulseRoute.current231            if listening { cancel() }232        }233        .task(id: listening) {234            guard listening else { return }235            while !Task.isCancelled, let session, !session.isOver {236                try? await Task.sleep(for: .milliseconds(60))237            }238            if !Task.isCancelled, listening { conclude() }239        }240    }241242    private func tapAlong(save: PulseBeatSave, audible: Bool) -> some View {243        VStack(alignment: .leading, spacing: OrixSpace.sm) {244            SectionHeader(title: "Tap along", trailing: save.isCalibrated(route: route.rawValue) ? "Calibrated" : "Not calibrated")245            Text(audible ? "You will hear \(PulseCalibration.clickCount) clicks. Listen to the first \(PulseCalibration.warmUp), then tap the pad exactly on each click you hear. Trust your ears, not the ring."246                         : "Sound is off, so there is no click to tap along to. You can still set the offsets by hand below.")247                .font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary).fixedSize(horizontal: false, vertical: true)248            ZStack {249                RoundedRectangle(cornerRadius: OrixRadius.lg, style: .continuous).fill(Color.black.opacity(0.35))250                RoundedRectangle(cornerRadius: OrixRadius.lg, style: .continuous).strokeBorder(listening ? accent.primary : OrixColor.stroke, lineWidth: listening ? 2 : 1)251                if listening, let session {252                    TimelineView(.animation) { _ in253                        PulseClickRing(heard: session.heardNow(), clicks: session.clicks, accent: accent)254                    }255                    PulseTapPad { stamp in256                        session.tap(atHost: stamp)257                        tapCount = session.taps.count258                        services.haptics.play(.tick)259                    }260                    .accessibilityIdentifier("pulse-tap-pad")261                    VStack {262                        Spacer()263                        Text("TAPS \(tapCount)").font(OrixFont.overline).tracking(1.6).foregroundStyle(OrixColor.textSecondary).padding(.bottom, OrixSpace.xs)264                    }265                    .allowsHitTesting(false)266                } else {267                    resultSummary(save: save)268                }269            }270            .frame(height: 190)271            if listening {272                OrixButton(title: "Cancel", kind: .secondary, action: cancel)273                    .accessibilityIdentifier("pulse-calibration-cancel")274            } else if let proposal {275                HStack(spacing: OrixSpace.xs) {276                    OrixButton(title: "Apply \(PulseFormat.signed(proposal)) ms", systemImage: "checkmark", theme: accent) { apply(proposal) }277                        .accessibilityIdentifier("pulse-calibration-apply")278                    OrixButton(title: "Again", kind: .secondary, action: begin)279                        .accessibilityIdentifier("pulse-calibration-again")280                }281            } else {282                OrixButton(title: audible ? "Start" : "Needs sound", systemImage: audible ? "play.fill" : "speaker.slash.fill",283                           kind: audible ? .primary : .secondary, theme: accent) {284                    if audible { begin() } else { services.haptics.play(.warning) }285                }286                .accessibilityIdentifier("pulse-calibration-start")287            }288        }289        .glassPanel(tint: accent.primary)290    }291292    @ViewBuilder293    private func resultSummary(save: PulseBeatSave) -> some View {294        VStack(spacing: 6) {295            if let measured, let proposal {296                Text("\(PulseFormat.signed(proposal)) ms").font(OrixFont.hud(40)).foregroundStyle(OrixColor.textPrimary)297                    .accessibilityIdentifier("pulse-calibration-result")298                Text("Your taps landed \(Int((measured.delay * 1000).rounded())) ms after the rendered click (steady to ±\(Int((measured.spread * 1000).rounded())) ms over \(measured.used) taps). The system reports \(Int(((session?.reportedLatency ?? 0) * 1000).rounded())) ms for this output.")299                    .font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary).multilineTextAlignment(.center)300            } else if failed {301                Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 26, weight: .bold)).foregroundStyle(OrixColor.gold)302                Text("Not enough steady taps to measure. Tap once on every click after the first \(PulseCalibration.warmUp).")303                    .font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary).multilineTextAlignment(.center)304            } else {305                Text("\(PulseFormat.signed(save.offsetMs(route: route.rawValue))) ms").font(OrixFont.hud(40)).foregroundStyle(OrixColor.textPrimary)306                Text("Current audio offset for \(route.title.lowercased())").font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary)307            }308        }309        .padding(OrixSpace.md)310    }311312    private func manual(save: PulseBeatSave) -> some View {313        VStack(alignment: .leading, spacing: OrixSpace.sm) {314            SectionHeader(title: "Fine tuning")315            stepper(title: "Audio offset", detail: "Always judged LATE? Lower it. Always EARLY? Raise it.", symbol: "waveform",316                    value: save.offsetMs(route: route.rawValue), limit: PulseBeatSave.offsetLimit, identifier: "pulse-offset") { value in317                services.store.update { $0.pulse.offsets[route.rawValue] = value }318            }319            Divider().overlay(OrixColor.stroke)320            stepper(title: "Visual offset", detail: "Notes reach the line after you hear them? Raise it.", symbol: "eye.fill",321                    value: save.visualOffsetMs, limit: PulseBeatSave.visualLimit, identifier: "pulse-visual") { value in322                services.store.update { $0.pulse.visualOffsetMs = value }323            }324            Text("\(PulseRules.windowsLabel). The audio offset moves the judgement; the visual offset only moves the picture.")325                .font(OrixFont.caption).foregroundStyle(OrixColor.textTertiary).fixedSize(horizontal: false, vertical: true)326        }327        .glassPanel(tint: accent.secondary)328    }329330    private func stepper(title: String, detail: String, symbol: String, value: Int, limit: Int, identifier: String, set: @escaping (Int) -> Void) -> some View {331        HStack(spacing: OrixSpace.sm) {332            Image(systemName: symbol).font(.system(size: 16, weight: .bold)).foregroundStyle(accent.primary).frame(width: 26)333            VStack(alignment: .leading, spacing: 2) {334                Text(title).font(OrixFont.body).foregroundStyle(OrixColor.textPrimary)335                Text(detail).font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary).fixedSize(horizontal: false, vertical: true)336            }337            Spacer(minLength: 4)338            HStack(spacing: 2) {339                stepButton("minus", label: "Lower \(title.lowercased()) by 5 milliseconds") { set((value - 5).clamped(-limit, limit)) }340                    .accessibilityIdentifier("\(identifier)-minus")341                Text(PulseFormat.signed(value)).font(OrixFont.hud(16)).foregroundStyle(OrixColor.textPrimary).frame(width: 46)342                    .accessibilityLabel("\(title) \(value) milliseconds")343                    .accessibilityIdentifier("\(identifier)-value")344                stepButton("plus", label: "Raise \(title.lowercased()) by 5 milliseconds") { set((value + 5).clamped(-limit, limit)) }345                    .accessibilityIdentifier("\(identifier)-plus")346            }347        }348        .frame(minHeight: OrixSpace.hit)349    }350351    private func stepButton(_ symbol: String, label: String, action: @escaping () -> Void) -> some View {352        Button {353            services.feedbackTap()354            action()355        } label: {356            Image(systemName: symbol).font(.system(size: 14, weight: .black)).foregroundStyle(OrixColor.textPrimary)357                .frame(width: 44, height: 44)358                .background(Color.white.opacity(0.09), in: Circle())359        }360        .buttonStyle(OrixPressStyle())361        .accessibilityLabel(label)362    }363364    // MARK: Flow365366    private func begin() {367        let created = session ?? PulseCalibrationSession(audio: services.audio)368        session = created369        measured = nil370        proposal = nil371        failed = false372        tapCount = 0373        route = PulseRoute.current374        services.audio.duckMusic(to: 1, over: 0.05)375        created.start(audio: services.audio)376        listening = true377    }378379    private func cancel() {380        session?.stop()381        listening = false382    }383384    private func conclude() {385        guard let session else { return }386        let result = session.measurement387        let latency = session.reportedLatency388        session.stop()389        listening = false390        if let result {391            measured = result392            proposal = PulseCalibration.offsetMs(delay: result.delay, reportedLatency: latency)393            services.audio.play(.confirm)394        } else {395            failed = true396            services.audio.play(.back)397            services.haptics.play(.warning)398        }399    }400401    private func apply(_ offset: Int) {402        let key = route.rawValue403        services.store.update {404            PulseProgress.setCalibration(offset, route: key, in: &$0.pulse)405            $0.pulse.calibrationPrompted = true406        }407        services.unlock("pulse.calibrated")408        services.haptics.play(.success)409        proposal = nil410        measured = nil411    }412413    private func close() {414        if listening { cancel() }415        onDone()416    }417}418419/// The ring in the tap pad: it closes on each click as the system believes it is heard. A guide only — the measurement uses the ears.420struct PulseClickRing: View {421    let heard: Double422    let clicks: [Double]423    let accent: GameTheme424425    var body: some View {426        Canvas { context, size in427            let center = CGPoint(x: size.width / 2, y: size.height / 2 - 6)428            let next = clicks.first { $0 >= heard }429            let last = clicks.last { $0 < heard }430            let done = clicks.filter { $0 < heard }.count431            let base: CGFloat = 34432            context.stroke(Path(ellipseIn: CGRect(x: center.x - base, y: center.y - base, width: base * 2, height: base * 2)),433                           with: .color(.white.opacity(0.85)), lineWidth: 3)434            if let next, !OrixAppearance.reduceMotion {435                let remaining = min(1, max(0, (next - heard) / PulseCalibration.interval))436                let radius = base + CGFloat(remaining) * 44437                context.stroke(Path(ellipseIn: CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2)),438                               with: .color(accent.primary.opacity(1 - remaining * 0.7)), lineWidth: 2.5)439            }440            if let last, heard - last < 0.14 {441                let flash = 1 - (heard - last) / 0.14442                context.fill(Path(ellipseIn: CGRect(x: center.x - base, y: center.y - base, width: base * 2, height: base * 2)),443                             with: .color(accent.secondary.opacity(0.8 * flash)))444            }445            // One dot per click; the warm-up clicks are hollow.446            let spacing: CGFloat = min(14, (size.width - 32) / CGFloat(max(clicks.count, 1)))447            let startX = center.x - spacing * CGFloat(clicks.count - 1) / 2448            for index in clicks.indices {449                let rect = CGRect(x: startX + CGFloat(index) * spacing - 3, y: 14, width: 6, height: 6)450                if index < PulseCalibration.warmUp {451                    context.stroke(Path(ellipseIn: rect), with: .color(.white.opacity(index < done ? 0.9 : 0.35)), lineWidth: 1.2)452                } else {453                    context.fill(Path(ellipseIn: rect), with: .color(index < done ? accent.primary : Color.white.opacity(0.25)))454                }455            }456        }457        .allowsHitTesting(false)458        .accessibilityHidden(true)459    }460}461
Files main
Menu

Theme