Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Arcade9// File : Games/PulseBeat/PulseViews.swift10// Description : Pulse Beat — SwiftUI flow: track and difficulty select11// with bests and unlocks, options, the run screen (loading,12// HUD, coach marks, pause handling, audio interruptions) and13// the results recap.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 AVFoundation9495struct PulseRunConfig: Equatable, Identifiable {96 let id = UUID()97 var trackID: String98 var difficulty: PulseDifficulty99}100101struct PulseRootView: View {102 let onExit: () -> Void103 @Environment(ArcadeServices.self) private var services104 @State private var run: PulseRunConfig?105 @State private var calibrating = false106 @State private var store = PulseTrackStore()107 @State private var loaded = false108109 var body: some View {110 ZStack {111 if let run {112 PulseRunView(config: run, services: services, store: store,113 onRetry: { self.run = PulseRunConfig(trackID: run.trackID, difficulty: run.difficulty) },114 onMenu: { withAnimation(.easeInOut(duration: 0.25)) { self.run = nil } },115 onExit: onExit)116 .id(run.id)117 .transition(.opacity)118 } else if calibrating {119 PulseCalibrationView(onDone: { withAnimation(.easeInOut(duration: 0.25)) { calibrating = false } })120 .transition(.opacity)121 } else {122 PulseMenuView(onStart: start, onCalibrate: { withAnimation(.easeInOut(duration: 0.25)) { calibrating = true } }, onExit: onExit)123 .transition(.opacity)124 }125 }126 .onAppear {127 guard !loaded else { return }128 loaded = true129 // `-ORIXAutoplay YES` starts a run played by the bot; `-ORIXLevel 1…5` picks the track and `-ORIXMode easy|normal|hard|expert`130 // the difficulty (both also work without the bot). `-ORIXScreen calibrate` opens the timing screen.131 guard LaunchOptions.game == .pulseBeat else { return }132 if LaunchOptions.string("Screen") == "calibrate" {133 calibrating = true134 return135 }136 let level = LaunchOptions.int("Level")137 let mode = LaunchOptions.string("Mode").flatMap { name in PulseDifficulty.allCases.first { $0.title.lowercased() == name.lowercased() } }138 if LaunchOptions.autoplay || level != nil || mode != nil {139 let index = ((level ?? 1) - 1).clamped(0, PulseLibrary.tracks.count - 1)140 run = PulseRunConfig(trackID: PulseLibrary.tracks[index].id, difficulty: mode ?? .normal)141 }142 }143 .onChange(of: run) { _, value in144 services.setResumeNote(value.flatMap { config in PulseLibrary.track(config.trackID).map { "\($0.title) · \(config.difficulty.title)" } })145 }146 .onDisappear { store.release() }147 }148149 private func start(_ track: String, _ difficulty: PulseDifficulty) {150 services.audio.play(.confirm)151 services.store.update {152 $0.pulse.lastTrack = track153 $0.pulse.lastDifficulty = difficulty.rawValue154 }155 withAnimation(.easeInOut(duration: 0.25)) { run = PulseRunConfig(trackID: track, difficulty: difficulty) }156 }157}158159// MARK: - Menu160161struct PulseMenuView: View {162 let onStart: (String, PulseDifficulty) -> Void163 let onCalibrate: () -> Void164 let onExit: () -> Void165 @Environment(ArcadeServices.self) private var services166 @State private var track = PulseLibrary.tracks[0].id167 @State private var difficulty = PulseDifficulty.easy168 @State private var loaded = false169170 private let accent = GameTheme.pulseBeat171172 var body: some View {173 let save = services.save.pulse174 let route = PulseRoute.current175 ZStack {176 AuroraBackground(theme: accent)177 VStack(spacing: 0) {178 HStack(spacing: OrixSpace.sm) {179 OrixIconButton(systemImage: "chevron.left", label: "Back to arcade", action: onExit)180 .accessibilityIdentifier("pulse-back")181 VStack(alignment: .leading, spacing: 1) {182 Text("Pulse Beat").font(OrixFont.title).foregroundStyle(OrixColor.textPrimary)183 Text(save.plays == 0 ? "Four lanes. One beat. Stay on it."184 : "\(save.notesHit.formatted()) notes hit · average accuracy \(String(format: "%.1f", save.averageAccuracy))%")185 .font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary)186 .accessibilityIdentifier("pulse-summary")187 }188 Spacer()189 OrixIconButton(systemImage: "tuningfork", label: "Timing and calibration", action: onCalibrate)190 .accessibilityIdentifier("pulse-calibrate")191 }192 .padding(.horizontal, OrixSpace.md)193 .padding(.top, OrixSpace.xs)194 .padding(.bottom, OrixSpace.sm)195196 ScrollView {197 VStack(alignment: .leading, spacing: OrixSpace.md) {198 if !save.calibrationPrompted, !save.isCalibrated(route: route.rawValue) { calibrationPrompt(route) }199 VStack(alignment: .leading, spacing: OrixSpace.xs) {200 SectionHeader(title: "Tracks", trailing: "\(save.unlockedTracks) of \(PulseLibrary.tracks.count) unlocked")201 ForEach(Array(PulseLibrary.tracks.enumerated()), id: \.element.id) { index, spec in202 PulseTrackCard(spec: spec, unlocked: save.isTrackUnlocked(index), selected: spec.id == track,203 best: save.best(spec.id, difficulty),204 requirement: max(0, PulseBeatSave.trackRequirements[index] - save.chartsCleared)) {205 services.feedbackTap()206 withAnimation(OrixMotion.snappy) { track = spec.id }207 }208 }209 }210 VStack(alignment: .leading, spacing: OrixSpace.xs) {211 SectionHeader(title: "Chart", trailing: "\(PulseLibrary.tracks[PulseLibrary.index(of: track)].title) · \(difficulty.title)")212 chartPanel(save)213 }214 optionsPanel(save, route: route)215 rulesPanel216 }217 .padding(.horizontal, OrixSpace.md)218 .padding(.bottom, OrixSpace.lg)219 }220 .scrollIndicators(.hidden)221222 VStack(spacing: OrixSpace.xs) {223 PulseDifficultyPicker(selection: $difficulty, expertUnlocked: save.isExpertUnlocked(track))224 startButton(save)225 }226 .padding(.horizontal, OrixSpace.md)227 .padding(.vertical, OrixSpace.xs)228 }229 }230 .onAppear {231 services.audio.setMusic(.pulseBeat)232 guard !loaded else { return }233 loaded = true234 track = save.lastTrack235 difficulty = save.difficulty236 }237 }238239 private func calibrationPrompt(_ route: PulseRoute) -> some View {240 VStack(alignment: .leading, spacing: OrixSpace.sm) {241 HStack(spacing: OrixSpace.sm) {242 Image(systemName: "tuningfork").font(.system(size: 20, weight: .bold)).foregroundStyle(accent.primary)243 VStack(alignment: .leading, spacing: 2) {244 Text("Tune your timing first").font(OrixFont.headline).foregroundStyle(OrixColor.textPrimary)245 Text("Tap along to a short click. It takes ten seconds and matters most with \(route == .bluetooth ? "the Bluetooth audio you are using now" : "Bluetooth headphones").")246 .font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary).fixedSize(horizontal: false, vertical: true)247 }248 }249 HStack(spacing: OrixSpace.xs) {250 OrixButton(title: "Calibrate", systemImage: "waveform", theme: accent) {251 services.store.update { $0.pulse.calibrationPrompted = true }252 onCalibrate()253 }254 .accessibilityIdentifier("pulse-prompt-calibrate")255 OrixButton(title: "Later", kind: .secondary) {256 withAnimation(OrixMotion.snappy) { services.store.update { $0.pulse.calibrationPrompted = true } }257 }258 .accessibilityIdentifier("pulse-prompt-later")259 }260 }261 .glassPanel(tint: accent.primary)262 }263264 private func chartPanel(_ save: PulseBeatSave) -> some View {265 let chart = PulseLibrary.chart(track, difficulty)266 let best = save.best(track, difficulty)267 return VStack(alignment: .leading, spacing: OrixSpace.xs) {268 HStack(spacing: OrixSpace.xs) {269 OrixChip(text: "LEVEL \(chart.level)", systemImage: "chart.bar.fill", tint: accent.primary, filled: true)270 OrixChip(text: "\(chart.notes.count) NOTES", tint: OrixColor.textPrimary)271 if chart.holds > 0 { OrixChip(text: "\(chart.holds) HOLDS", tint: OrixColor.cyan) }272 if chart.swipes > 0 { OrixChip(text: "\(chart.swipes) SWIPES", tint: OrixColor.gold) }273 }274 .lineLimit(1)275 .minimumScaleFactor(0.7)276 if let best, best.plays > 0 {277 HStack(spacing: OrixSpace.sm) {278 PulseGradeBadge(grade: best.pulseGrade, size: 38)279 VStack(alignment: .leading, spacing: 2) {280 Text("Best \(best.score.formatted())").font(OrixFont.headline).foregroundStyle(OrixColor.textPrimary)281 Text("\(String(format: "%.1f", Double(best.accuracy) / 10))% · combo \(best.maxCombo)\(best.allPerfect ? " · All Perfect" : best.fullCombo ? " · Full Combo" : "")")282 .font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary)283 }284 Spacer()285 }286 .accessibilityElement(children: .combine)287 .accessibilityIdentifier("pulse-chart-best")288 } else {289 Text("Not played yet.").font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary)290 }291 }292 .frame(maxWidth: .infinity, alignment: .leading)293 .glassPanel(tint: accent.secondary)294 }295296 private func optionsPanel(_ save: PulseBeatSave, route: PulseRoute) -> some View {297 VStack(alignment: .leading, spacing: OrixSpace.sm) {298 SectionHeader(title: "Options")299 HStack(spacing: OrixSpace.sm) {300 Image(systemName: "speedometer").font(.system(size: 16, weight: .bold)).foregroundStyle(accent.primary).frame(width: 26)301 Text("Note speed").font(OrixFont.body).foregroundStyle(OrixColor.textPrimary)302 Spacer()303 }304 OrixSegmented(options: PulseBeatSave.speeds.enumerated().map { (value: $0.offset, label: "×\(String(format: "%g", $0.element))") },305 selection: Binding(get: { save.speed }, set: { value in services.store.update { $0.pulse.speed = value } }), theme: accent)306 .accessibilityIdentifier("pulse-speed")307 OrixToggleRow(title: "Hit sounds", detail: "A soft tick on every note you hit.", systemImage: "speaker.wave.1.fill",308 isOn: Binding(get: { save.hitSounds }, set: { value in services.store.update { $0.pulse.hitSounds = value } }), tint: accent.primary)309 Button {310 services.feedbackTap()311 onCalibrate()312 } label: {313 HStack(spacing: OrixSpace.sm) {314 Image(systemName: route.symbol).font(.system(size: 16, weight: .bold)).foregroundStyle(accent.primary).frame(width: 26)315 VStack(alignment: .leading, spacing: 2) {316 Text("Timing").font(OrixFont.body).foregroundStyle(OrixColor.textPrimary)317 Text("\(route.title): \(PulseFormat.signed(save.offsetMs(route: route.rawValue))) ms\(save.isCalibrated(route: route.rawValue) ? "" : " (not calibrated)") · visual \(PulseFormat.signed(save.visualOffsetMs)) ms")318 .font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary)319 }320 Spacer()321 Image(systemName: "chevron.right").font(.system(size: 13, weight: .bold)).foregroundStyle(OrixColor.textTertiary)322 }323 .frame(minHeight: OrixSpace.hit)324 .contentShape(Rectangle())325 }326 .buttonStyle(OrixPressStyle())327 .accessibilityIdentifier("pulse-timing")328 }329 .glassPanel(tint: accent.primary)330 }331332 private var rulesPanel: some View {333 VStack(alignment: .leading, spacing: OrixSpace.xs) {334 SectionHeader(title: "How it is scored")335 rule("scope", "\(PulseRules.windowsLabel). The windows are the same on every difficulty.")336 rule("bolt.fill", "Combo multiplier: ×2 at \(PulseRules.comboTiers[0]), ×3 at \(PulseRules.comboTiers[1]), ×4 at \(PulseRules.comboTiers[2]). A Miss resets it.")337 rule("hand.point.up.left.fill", "Long notes are judged twice: on the press and on the release. Arrow notes need a flick after the tap.")338 rule("rosette", "Grades by accuracy: S 95% · A 90% · B 80% · C 65%. A chart is cleared from C.")339 }340 .glassPanel(tint: accent.secondary)341 }342343 private func rule(_ symbol: String, _ text: String) -> some View {344 HStack(alignment: .top, spacing: OrixSpace.sm) {345 Image(systemName: symbol).font(.system(size: 14, weight: .bold)).foregroundStyle(accent.primary).frame(width: 22)346 Text(text).font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary).fixedSize(horizontal: false, vertical: true)347 }348 .accessibilityElement(children: .combine)349 }350351 @ViewBuilder352 private func startButton(_ save: PulseBeatSave) -> some View {353 let index = PulseLibrary.index(of: track)354 let title = PulseLibrary.tracks[index].title355 if !save.isTrackUnlocked(index) {356 let missing = max(1, PulseBeatSave.trackRequirements[index] - save.chartsCleared)357 OrixButton(title: "Locked · clear \(missing) more chart\(missing == 1 ? "" : "s")", systemImage: "lock.fill", kind: .secondary) {358 services.haptics.play(.warning)359 }360 .accessibilityIdentifier("pulse-start")361 } else if difficulty == .expert, !save.isExpertUnlocked(track) {362 OrixButton(title: "Expert opens with a \(PulseBeatSave.expertGrade.title) on Hard", systemImage: "lock.fill", kind: .secondary) {363 services.haptics.play(.warning)364 }365 .accessibilityIdentifier("pulse-start")366 } else {367 OrixButton(title: "Play · \(title) · \(difficulty.title)", systemImage: "play.fill", theme: accent) { onStart(track, difficulty) }368 .accessibilityIdentifier("pulse-start")369 }370 }371}372373enum PulseFormat {374 static func signed(_ value: Int) -> String { value > 0 ? "+\(value)" : value < 0 ? "−\(-value)" : "0" }375 static func length(_ seconds: Double) -> String { "\(Int(seconds) / 60):\(String(format: "%02d", Int(seconds) % 60))" }376}377378struct PulseGradeBadge: View {379 let grade: PulseGrade380 var size: CGFloat = 34381382 var body: some View {383 Text(grade.title)384 .font(.system(size: size * 0.56, weight: .black, design: .rounded))385 .foregroundStyle(OrixColor.ink)386 .frame(width: size, height: size)387 .background(Color(hex: grade.hex), in: RoundedRectangle(cornerRadius: size * 0.28, style: .continuous))388 .accessibilityLabel("Grade \(grade.title)")389 }390}391392struct PulseTrackCard: View {393 let spec: PulseTrackSpec394 let unlocked: Bool395 let selected: Bool396 let best: PulseBest?397 let requirement: Int398 let action: () -> Void399400 var body: some View {401 let colorA = Color(hex: spec.hexA), colorB = Color(hex: spec.hexB)402 Button(action: action) {403 HStack(spacing: OrixSpace.sm) {404 ZStack {405 RoundedRectangle(cornerRadius: OrixRadius.sm, style: .continuous)406 .fill(LinearGradient(colors: [colorA, colorB], startPoint: .topLeading, endPoint: .bottomTrailing))407 Image(systemName: unlocked ? "waveform" : "lock.fill").font(.system(size: 20, weight: .black)).foregroundStyle(OrixColor.ink.opacity(0.85))408 }409 .frame(width: 50, height: 50)410 .saturation(unlocked ? 1 : 0.2)411 VStack(alignment: .leading, spacing: 2) {412 Text(spec.title).font(OrixFont.headline).foregroundStyle(OrixColor.textPrimary).lineLimit(1)413 Text("\(Int(spec.bpm)) BPM · \(spec.keyName) · \(PulseFormat.length(PulseLibrary.song(spec.id).duration))")414 .font(OrixFont.caption.monospacedDigit()).foregroundStyle(OrixColor.textSecondary).lineLimit(1).minimumScaleFactor(0.8)415 Text(unlocked ? spec.mood : "Clear \(requirement) more chart\(requirement == 1 ? "" : "s") to unlock")416 .font(OrixFont.overline).foregroundStyle(unlocked ? colorA : OrixColor.gold).lineLimit(1)417 }418 Spacer(minLength: 4)419 if let best, best.plays > 0 {420 VStack(spacing: 3) {421 PulseGradeBadge(grade: best.pulseGrade, size: 30)422 if best.fullCombo {423 Text(best.allPerfect ? "AP" : "FC").font(OrixFont.overline).foregroundStyle(OrixColor.gold)424 .accessibilityLabel(best.allPerfect ? "All Perfect" : "Full Combo")425 }426 }427 }428 }429 .padding(OrixSpace.sm)430 .background(Color.white.opacity(selected ? 0.12 : 0.05), in: RoundedRectangle(cornerRadius: OrixRadius.md, style: .continuous))431 .overlay(RoundedRectangle(cornerRadius: OrixRadius.md, style: .continuous)432 .strokeBorder(selected ? colorA : OrixColor.stroke, lineWidth: selected ? OrixBorder.selected : OrixBorder.hairline))433 .shadow(color: selected ? colorA.opacity(OrixGlow.opacity * 0.6) : .clear, radius: OrixGlow.soft)434 .contentShape(Rectangle())435 }436 .buttonStyle(OrixPressStyle())437 .accessibilityElement(children: .combine)438 .accessibilityAddTraits(selected ? .isSelected : [])439 .accessibilityIdentifier("pulse-track-\(spec.id)")440 }441}442443struct PulseDifficultyPicker: View {444 @Binding var selection: PulseDifficulty445 let expertUnlocked: Bool446 @Environment(ArcadeServices.self) private var services447448 var body: some View {449 HStack(spacing: 4) {450 ForEach(PulseDifficulty.allCases) { option in451 let selected = option == selection452 let locked = option == .expert && !expertUnlocked453 Button {454 services.feedbackTap()455 withAnimation(OrixMotion.snappy) { selection = option }456 } label: {457 HStack(spacing: 4) {458 if locked { Image(systemName: "lock.fill").font(.system(size: 10, weight: .black)) }459 Text(option.title).font(OrixFont.caption).lineLimit(1).minimumScaleFactor(0.7)460 }461 .foregroundStyle(selected ? OrixColor.ink : OrixColor.textSecondary)462 .frame(maxWidth: .infinity, minHeight: 44)463 .background(selected ? AnyShapeStyle(GameTheme.pulseBeat.gradient) : AnyShapeStyle(Color.clear), in: Capsule())464 .contentShape(Capsule())465 }466 .buttonStyle(.plain)467 .accessibilityLabel(locked ? "\(option.title), locked" : option.title)468 .accessibilityAddTraits(selected ? .isSelected : [])469 .accessibilityIdentifier("pulse-difficulty-\(option.title.lowercased())")470 }471 }472 .padding(4)473 .background(Color.white.opacity(0.07), in: Capsule())474 .overlay(Capsule().strokeBorder(OrixColor.stroke, lineWidth: 1))475 }476}477478// MARK: - Run479480struct PulseOutcome: Equatable {481 var result: PulseResult482 var report: PulseReport483}484485struct PulseRunView: View {486 let config: PulseRunConfig487 let store: PulseTrackStore488 let onRetry: () -> Void489 let onMenu: () -> Void490 let onExit: () -> Void491 @Environment(ArcadeServices.self) private var services492 @State private var session: GameSession493 @State private var model = PulseHUDModel()494 @State private var scene: PulseScene?495 @State private var outcome: PulseOutcome?496 @State private var notice: String?497 @State private var tutorial = false498499 init(config: PulseRunConfig, services: ArcadeServices, store: PulseTrackStore, onRetry: @escaping () -> Void, onMenu: @escaping () -> Void,500 onExit: @escaping () -> Void) {501 self.config = config502 self.store = store503 self.onRetry = onRetry504 self.onMenu = onMenu505 self.onExit = onExit506 _session = State(initialValue: GameSession(game: .pulseBeat, services: services))507 }508509 private var spec: PulseTrackSpec { PulseLibrary.track(config.trackID) ?? PulseLibrary.tracks[0] }510511 var body: some View {512 GameChrome(theme: .pulseBeat, title: spec.title, isPaused: session.pausedBinding, canPause: scene != nil && outcome == nil,513 pauseDetail: notice ?? "\(config.difficulty.title) · \(Int(spec.bpm)) BPM · resumes with a count-in",514 onRestart: restart, onExit: onExit) {515 ZStack {516 if let scene {517 GameSceneView(scene: scene, isPaused: session.isPaused)518 VStack(spacing: OrixSpace.sm) {519 PulseHUD(model: model, leftHanded: services.settings.leftHanded)520 if let coach = model.coach, outcome == nil {521 CoachMark(text: coach, systemImage: model.coachSymbol, theme: .pulseBeat)522 .transition(.opacity)523 .id(coach)524 .accessibilityIdentifier("pulse-coach")525 }526 Spacer()527 }528 .padding(.horizontal, OrixSpace.sm)529 .padding(.top, 6)530 .allowsHitTesting(false)531 } else {532 PulseLoadingView(spec: spec, difficulty: config.difficulty)533 }534 if let outcome { results(outcome) }535 }536 }537 .task { await prepare() }538 .onChange(of: session.isPaused) { _, paused in539 scene?.setPaused(paused)540 if !paused { notice = nil }541 }542 // A phone call or Siri, headphones pulled out, or the audio hardware changing: stop on the spot. Resuming restarts the track on the same frame.543 .onReceive(NotificationCenter.default.publisher(for: AVAudioSession.interruptionNotification).receive(on: DispatchQueue.main)) { note in544 if (note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt) == AVAudioSession.InterruptionType.began.rawValue {545 interrupt("Audio was interrupted · resumes with a count-in")546 }547 }548 .onReceive(NotificationCenter.default.publisher(for: AVAudioSession.routeChangeNotification).receive(on: DispatchQueue.main)) { note in549 let reason = (note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt).flatMap(AVAudioSession.RouteChangeReason.init(rawValue:))550 if reason == .oldDeviceUnavailable || reason == .newDeviceAvailable {551 interrupt("Audio output changed · timing for \(PulseRoute.current.title.lowercased()) applies on resume")552 }553 }554 .onReceive(NotificationCenter.default.publisher(for: .AVAudioEngineConfigurationChange).receive(on: DispatchQueue.main)) { _ in555 interrupt("Audio output changed · resumes with a count-in")556 }557 .onDisappear {558 session.exit()559 scene?.dispose()560 scene = nil561 }562 .animation(OrixMotion.decorative(OrixMotion.snappy), value: model.coach)563 }564565 private func interrupt(_ message: String) {566 guard scene != nil, outcome == nil, session.phase == .running else { return }567 notice = message568 session.pause()569 }570571 private func prepare() async {572 guard scene == nil else { return }573 session.load()574 services.audio.setMusic(nil)575 let auto = LaunchOptions.autoplay576 let teach = !services.save.pulse.tutorialDone && !auto577 tutorial = teach578 let prepared = await store.prepared(for: spec, playable: services.audio.isRunning)579 guard !Task.isCancelled, scene == nil else { return }580 session.loaded()581 scene = PulseScene(services: services, chart: PulseLibrary.chart(config.trackID, config.difficulty), prepared: prepared, autoplay: auto,582 tutorial: teach, model: model, onFinished: finish,583 onStall: { interrupt("Audio stopped · resumes with a count-in") })584 scene?.onAutoPause = {585 session.pause()586 Task {587 try? await Task.sleep(for: .milliseconds(2500))588 session.resume()589 }590 }591 session.start()592 }593594 private func restart() {595 guard let scene else { return }596 outcome = nil597 session.restart()598 scene.restart()599 }600601 private func finish(_ result: PulseResult) {602 var report = PulseReport()603 let wasTutorial = tutorial604 services.store.update {605 report = PulseProgress.apply(result, to: &$0.pulse)606 if wasTutorial { $0.pulse.tutorialDone = true }607 }608 PulseProgress.deliver(result, report: report, to: services)609 session.finish(success: result.cleared, score: result.tally.score,610 headline: "\(spec.title) · \(result.difficulty.title) · \(result.grade.title)", isRecord: report.isRecord)611 if !report.isRecord {612 services.audio.play(result.cleared ? .win : .fail)613 services.haptics.play(result.cleared ? .levelComplete : .failure)614 }615 if !report.newTracks.isEmpty || report.expertUnlocked { services.audio.play(.upgrade) }616 withAnimation(OrixMotion.decorative(OrixMotion.snappy)) { outcome = PulseOutcome(result: result, report: report) }617 }618619 private func results(_ outcome: PulseOutcome) -> some View {620 let result = outcome.result621 let tally = result.tally622 let mean = Int((tally.meanOffset * 1000).rounded())623 let timing: String624 if tally.offsetCount == 0 {625 timing = "–"626 } else if abs(mean) <= 5 {627 timing = "on the beat"628 } else {629 timing = "\(abs(mean)) ms \(mean < 0 ? "early" : "late") on average"630 }631 let rows = [632 ResultRow(label: "Accuracy", value: result.accuracyLabel, systemImage: "scope", highlight: result.grade >= .s),633 ResultRow(label: "Perfect · Great", value: "\(tally.perfects) · \(tally.counts[PulseJudgement.great.rawValue])", systemImage: "sparkles"),634 ResultRow(label: "Good · Miss", value: "\(tally.counts[PulseJudgement.good.rawValue]) · \(tally.misses)", systemImage: "xmark.circle"),635 ResultRow(label: "Best combo", value: "\(tally.maxCombo)", systemImage: "bolt.fill", highlight: result.fullCombo),636 ResultRow(label: "Timing", value: timing, systemImage: "metronome.fill"),637 ]638 var subtitle = "\(spec.title) · \(result.difficulty.title)"639 if let track = outcome.report.newTracks.last.flatMap(PulseLibrary.track) {640 subtitle = "New track unlocked: \(track.title)!"641 } else if outcome.report.expertUnlocked {642 subtitle = "Expert unlocked for \(spec.title)!"643 } else if result.allPerfect {644 subtitle += " · All Perfect"645 } else if result.fullCombo {646 subtitle += " · Full Combo"647 } else if !result.cleared {648 subtitle += " · reach a C (65%) to clear"649 }650 return ResultsCard(theme: .pulseBeat, title: "Grade \(result.grade.title)", subtitle: subtitle, stars: result.grade.stars, score: tally.score,651 isNewRecord: outcome.report.isRecord, success: result.cleared, rows: rows,652 primaryTitle: "Play Again", onPrimary: onRetry,653 secondaryTitle: "Tracks", secondaryIcon: "music.note.list", onSecondary: onMenu, onExit: onExit)654 }655}656657struct PulseHUD: View {658 let model: PulseHUDModel659 let leftHanded: Bool660661 var body: some View {662 let accent = GameTheme.pulseBeat663 VStack(spacing: 6) {664 HStack(spacing: 6) {665 if leftHanded { Spacer(minLength: 60) }666 HUDPill(systemImage: "star.fill", text: model.score.formatted(), tint: OrixColor.gold, label: "Score")667 .accessibilityIdentifier("pulse-score")668 HUDPill(systemImage: "scope", text: String(format: "%.1f%%", (model.accuracy * 1000).rounded(.down) / 10), tint: accent.primary, label: "Accuracy")669 .accessibilityIdentifier("pulse-accuracy")670 if !leftHanded { Spacer(minLength: 60) }671 }672 HStack(spacing: OrixSpace.xs) {673 Text(model.section.uppercased()).font(OrixFont.overline).tracking(1.4).foregroundStyle(OrixColor.textSecondary)674 .frame(width: 52, alignment: .leading)675 OrixProgressBar(fraction: model.progress, theme: accent, height: 4)676 .accessibilityLabel("Track progress")677 Text("×\(model.multiplier)").font(OrixFont.hud(13)).foregroundStyle(model.multiplier > 1 ? OrixColor.gold : OrixColor.textTertiary)678 .accessibilityLabel("Multiplier \(model.multiplier)")679 }680 .padding(.horizontal, 4)681 .padding(.trailing, leftHanded ? 0 : 56)682 .padding(.leading, leftHanded ? 56 : 0)683 }684 }685}686687struct PulseLoadingView: View {688 let spec: PulseTrackSpec689 let difficulty: PulseDifficulty690691 var body: some View {692 ZStack {693 AuroraBackground(theme: .pulseBeat)694 VStack(spacing: OrixSpace.md) {695 PulseEqualizer(colorA: Color(hex: spec.hexA), colorB: Color(hex: spec.hexB))696 .frame(width: 150, height: 64)697 VStack(spacing: 4) {698 Text(spec.title).font(OrixFont.title).foregroundStyle(OrixColor.textPrimary)699 Text("\(Int(spec.bpm)) BPM · \(spec.keyName) · \(difficulty.title)").font(OrixFont.caption).foregroundStyle(OrixColor.textSecondary)700 }701 Text("Synthesising the track…").font(OrixFont.overline).tracking(1.6).foregroundStyle(OrixColor.textTertiary)702 }703 .accessibilityElement(children: .combine)704 .accessibilityLabel("Synthesising \(spec.title)")705 .accessibilityIdentifier("pulse-loading")706 }707 }708}709710/// A row of bars that bounce while a track is being rendered. Still under Reduce Motion.711struct PulseEqualizer: View {712 let colorA: Color713 let colorB: Color714715 var body: some View {716 TimelineView(.animation(minimumInterval: 1.0 / 30, paused: OrixAppearance.reduceMotion)) { timeline in717 Canvas { context, size in718 let time = OrixAppearance.reduceMotion ? 1.2 : timeline.date.timeIntervalSinceReferenceDate719 let count = 9720 let slot = size.width / CGFloat(count)721 for index in 0..<count {722 let wave = 0.5 + 0.5 * sin(time * (4 + Double(index % 4)) + Double(index) * 0.9)723 let height = size.height * (0.18 + 0.82 * wave)724 let rect = CGRect(x: CGFloat(index) * slot + slot * 0.2, y: size.height - height, width: slot * 0.6, height: height)725 context.fill(Path(roundedRect: rect, cornerRadius: slot * 0.3),726 with: .linearGradient(Gradient(colors: [colorA, colorB]), startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: size.height)))727 }728 }729 }730 .accessibilityHidden(true)731 }732}733