Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Arcade9// File : Games/PulseBeat/PulseChart.swift10// Description : Pulse Beat — note charts: types, the deterministic rules11// that derive four difficulties from a composed track's own12// events, and the playability checker.13// Module : Games14// Repository : https://git.spboucher.ai/orix-arcade15// Created : 2026-11-2216// Last Modified : 2026-11-2217//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : Proprietary, all rights reserved (see license file)83// License File : LICENSE84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation9293nonisolated enum PulseDifficulty: Int, CaseIterable, Codable, Sendable, Identifiable {94 case easy, normal, hard, expert95 var id: Int { rawValue }9697 var title: String {98 switch self {99 case .easy: "Easy"100 case .normal: "Normal"101 case .hard: "Hard"102 case .expert: "Expert"103 }104 }105106 /// Share of a track's mastery that a perfect run on this difficulty is worth.107 var masteryWeight: Double {108 switch self {109 case .easy: 0.4110 case .normal: 0.65111 case .hard: 0.85112 case .expert: 1113 }114 }115}116117nonisolated enum PulseNoteKind: Int, Codable, Sendable { case tap, hold, swipe }118119nonisolated enum PulseSwipe: Int, Codable, Sendable, CaseIterable {120 case up, left, right121 var symbol: String {122 switch self {123 case .up: "arrow.up"124 case .left: "arrow.left"125 case .right: "arrow.right"126 }127 }128}129130/// Where a note comes from in the music. Used by tests and by the lane rules.131nonisolated enum PulseSource: Int, Codable, Sendable { case lead, snare, kick, bass, arp }132133nonisolated struct PulseNote: Sendable, Equatable {134 /// Seconds from the start of the audio at which the note crosses the hit line.135 var time: Double136 /// Release time of a hold; equal to `time` for taps and swipes.137 var end: Double138 var lane: Int139 var kind: PulseNoteKind140 var swipe: PulseSwipe?141 var step: Int142 var endStep: Int143 var source: PulseSource144145 var isHold: Bool { kind == .hold }146 /// 0 for the two left lanes, 1 for the two right lanes: the thumb that plays the note.147 var hand: Int { lane < 2 ? 0 : 1 }148}149150nonisolated struct PulseChart: Sendable, Equatable {151 var trackID: String152 var difficulty: PulseDifficulty153 var bpm: Double154 /// Length of the audio in seconds.155 var duration: Double156 var notes: [PulseNote]157158 var holds: Int { notes.filter(\.isHold).count }159 var swipes: Int { notes.filter { $0.kind == .swipe }.count }160 /// Judgements a full run produces: one per tap or swipe, two per hold (head and release).161 var judgements: Int { notes.count + holds }162 var lastEnd: Double { notes.map(\.end).max() ?? 0 }163 var firstTime: Double { notes.first?.time ?? 0 }164 /// Simultaneous pairs.165 var doubles: Int {166 var count = 0167 for i in notes.indices.dropFirst() where notes[i].step == notes[i - 1].step { count += 1 }168 return count169 }170171 var notesPerSecond: Double {172 let span = lastEnd - firstTime173 return span > 0 ? Double(notes.count) / span : 0174 }175176 /// 1…15 rating shown in the track list, from note density and the share of technical notes.177 var level: Int {178 let technical = Double(holds + swipes + doubles * 2) / Double(max(notes.count, 1))179 return Int((notesPerSecond * 2.1 * (1 + technical * 0.5)).rounded()).clamped(1, 15)180 }181}182183nonisolated struct PulseChartRules: Sendable, Equatable {184 /// Notes may only start on multiples of this many sixteenths.185 var grid: Int186 /// Musical weight a step needs to become a note.187 var minimumWeight: Double188 /// Seconds between any two different note times.189 var gap: Double190 /// Seconds between two notes played by the same thumb.191 var handGap: Double192 /// Shortest sustained note that becomes a hold, in seconds.193 var holdMinimum: Double194 /// Bars between two swipes; 0 disables them except on section starts.195 var swipeSpacingBars: Int196 var doublesOnDownbeats: Bool197 var doublesOnAccents: Bool198 var doublesOnCrashes: Bool199 /// While a hold is down nothing else is charted (Easy).200 var holdsBlockEverything: Bool201202 static func rules(for difficulty: PulseDifficulty) -> PulseChartRules {203 switch difficulty {204 case .easy:205 PulseChartRules(grid: 4, minimumWeight: 2, gap: 0.44, handGap: 0.44, holdMinimum: 1.0, swipeSpacingBars: 0,206 doublesOnDownbeats: false, doublesOnAccents: false, doublesOnCrashes: false, holdsBlockEverything: true)207 case .normal:208 PulseChartRules(grid: 2, minimumWeight: 2, gap: 0.26, handGap: 0.3, holdMinimum: 0.85, swipeSpacingBars: 4,209 doublesOnDownbeats: false, doublesOnAccents: false, doublesOnCrashes: true, holdsBlockEverything: false)210 case .hard:211 PulseChartRules(grid: 1, minimumWeight: 1.5, gap: 0.15, handGap: 0.2, holdMinimum: 0.6, swipeSpacingBars: 2,212 doublesOnDownbeats: false, doublesOnAccents: true, doublesOnCrashes: true, holdsBlockEverything: false)213 case .expert:214 PulseChartRules(grid: 1, minimumWeight: 0.75, gap: 0.09, handGap: 0.13, holdMinimum: 0.5, swipeSpacingBars: 1,215 doublesOnDownbeats: true, doublesOnAccents: true, doublesOnCrashes: true, holdsBlockEverything: false)216 }217 }218}219220nonisolated enum PulseChartBuilder {221 /// No note before this many seconds of audio: the player always gets a lead-in.222 static let leadIn = 2.0223 /// No note (or hold release) in the last seconds of audio.224 static let leadOut = 2.5225 static let lanes = 4226227 private struct Candidate {228 var step: Int229 var weight = 0.0230 var lead: PulseTone?231 var bass: PulseTone?232 var arp: PulseTone?233 var kick = false234 var snare = false235 var crash = false236 var accent = false237 }238239 static func build(_ song: PulseSong, difficulty: PulseDifficulty) -> PulseChart {240 let rules = PulseChartRules.rules(for: difficulty)241 let step = song.stepDuration242 var table: [Int: Candidate] = [:]243 func with(_ s: Int, _ mutate: (inout Candidate) -> Void) {244 var candidate = table[s] ?? Candidate(step: s)245 mutate(&candidate)246 table[s] = candidate247 }248 for tone in song.lead {249 with(tone.step) { $0.lead = tone; $0.weight += 3 + (tone.accent ? 1 : 0); $0.accent = $0.accent || tone.accent }250 }251 for hit in song.snares { with(hit.step) { $0.snare = true; $0.weight += hit.velocity >= 0.7 ? 2 : 1 } }252 for hit in song.kicks { with(hit.step) { $0.kick = true; $0.weight += hit.step % 16 == 0 ? 2 : 1.5 } }253 for crash in song.crashes { with(crash) { $0.crash = true; $0.weight += 3 } }254 for tone in song.bass { with(tone.step) { $0.bass = tone; $0.weight += 1 } }255 for tone in song.arp {256 let quiet = song.section(atStep: tone.step) == .intro || song.section(atStep: tone.step) == .breakdown257 with(tone.step) { $0.arp = tone; $0.weight += quiet && tone.step % 4 == 0 ? 2 : 0.75 }258 }259260 // 1. Which steps become notes: the heaviest first, never two closer than the difficulty's gap.261 let latest = song.duration - leadOut262 let eligible = table.values.filter {263 $0.step % rules.grid == 0 && $0.weight >= rules.minimumWeight && song.time($0.step) >= leadIn && song.time($0.step) <= latest264 }.sorted { $0.weight != $1.weight ? $0.weight > $1.weight : $0.step < $1.step }265 var taken: [Int] = []266 let gapSteps = rules.gap / step267 for candidate in eligible where !taken.contains(where: { abs(Double($0 - candidate.step)) < gapSteps - 1e-9 }) {268 taken.append(candidate.step)269 }270 taken.sort()271272 // 2. Strong beats that become doubles, decided from the music alone so the notes around them can make room.273 func wantsDouble(_ candidate: Candidate) -> Bool {274 let s = candidate.step275 let section = song.section(atStep: s)276 let phrase = s / 32277 if rules.doublesOnCrashes, candidate.crash { return true }278 if rules.doublesOnAccents, candidate.accent, candidate.kick, phrase % 2 == 1 { return true }279 guard rules.doublesOnDownbeats, section == .drop || section == .verse else { return false }280 if s % 16 == 0, candidate.kick, !candidate.accent { return true }281 return section == .drop && s % 16 == 8 && candidate.lead != nil && (candidate.kick || candidate.snare)282 }283 let doubleSteps = taken.filter { table[$0].map(wantsDouble) ?? false }284285 // 3. Lanes, note types and playability, in time order.286 var notes: [PulseNote] = []287 var handFree = [-10.0, -10.0]288 var everythingFree = -10.0289 var cursor = 1290 var lastPitch: Int?291 var snareSide = 0, kickSide = 0292 var lastSwipeBar = -10_000293 var doubleCursor = 0294 let leadSteps = song.lead.map(\.step)295 let epsilon = 1e-9296297 func place(_ note: PulseNote) {298 notes.append(note)299 handFree[note.hand] = note.end + rules.handGap300 if note.isHold, rules.holdsBlockEverything { everythingFree = note.end + rules.gap }301 }302303 for s in taken {304 guard let candidate = table[s] else { continue }305 let time = song.time(s)306 if time < everythingFree - epsilon { continue }307 while doubleCursor < doubleSteps.count, doubleSteps[doubleCursor] <= s { doubleCursor += 1 }308 let nextDouble: Double? = doubleCursor < doubleSteps.count ? song.time(doubleSteps[doubleCursor]) : nil309 var isDouble = doubleSteps.contains(s)310 // Both thumbs must be free for a double: the note just before one gives way.311 if !isDouble, let nextDouble, nextDouble - time < rules.handGap - epsilon { continue }312 if isDouble, time < handFree[0] - epsilon || time < handFree[1] - epsilon { isDouble = false }313 let source: PulseSource = candidate.lead != nil ? .lead : candidate.snare ? .snare : candidate.kick ? .kick : candidate.bass != nil ? .bass : .arp314315 // Desired lane: melodies follow their contour, drums keep to their own lanes.316 var lane: Int317 let pitched = candidate.lead ?? (candidate.snare || candidate.kick ? nil : candidate.bass ?? candidate.arp)318 if let tone = pitched {319 if let previous = lastPitch {320 let delta = tone.midi - previous321 if delta > 0 { cursor += delta >= 5 ? 2 : 1 } else if delta < 0 { cursor -= delta <= -5 ? 2 : 1 }322 // Bounce off the edges instead of sticking to them.323 if cursor > lanes - 1 { cursor = 2 * (lanes - 1) - cursor }324 if cursor < 0 { cursor = -cursor }325 cursor = cursor.clamped(0, lanes - 1)326 }327 lastPitch = tone.midi328 lane = cursor329 } else if candidate.snare {330 lane = snareSide == 0 ? 0 : 3331 snareSide = 1 - snareSide332 } else {333 lane = kickSide == 0 ? 1 : 2334 kickSide = 1 - kickSide335 }336 if time < handFree[lane < 2 ? 0 : 1] - epsilon {337 lane = lanes - 1 - lane338 if time < handFree[lane < 2 ? 0 : 1] - epsilon { continue }339 }340341 var kind = PulseNoteKind.tap342 var endStep = s343 var swipe: PulseSwipe?344 let bar = s / 16345 if !isDouble {346 // Swipes on section starts (Easy) and on the first note of every other phrase.347 let spaced = rules.swipeSpacingBars > 0 && bar - lastSwipeBar >= rules.swipeSpacingBars348 let wantsSwipe = (candidate.crash && !rules.doublesOnCrashes) || (candidate.accent && !candidate.crash && spaced && (s / 32) % 2 == 0)349 if wantsSwipe {350 if difficulty == .easy {351 swipe = .up352 } else if let tone = candidate.lead, let index = leadSteps.firstIndex(of: s), index + 1 < song.lead.count {353 let next = song.lead[index + 1].midi354 swipe = next > tone.midi ? .right : next < tone.midi ? .left : .up355 } else {356 swipe = .up357 }358 kind = .swipe359 lastSwipeBar = bar360 } else if let tone = candidate.lead, Double(tone.length) * step >= rules.holdMinimum {361 // Holds from sustained lead notes, released a little before the note ends and well before the next double.362 var length = min(tone.length - (tone.length >= 8 ? 2 : 1), 32)363 let limit = min(latest, (nextDouble ?? .infinity) - rules.handGap)364 while length > 0, song.time(s + length) > limit + epsilon { length -= 1 }365 if length > 0, Double(length) * step >= rules.holdMinimum * 0.75 - epsilon {366 kind = .hold367 endStep = s + length368 }369 }370 }371372 place(PulseNote(time: time, end: song.time(endStep), lane: lane, kind: kind, swipe: swipe, step: s, endStep: endStep, source: source))373 if isDouble {374 place(PulseNote(time: time, end: time, lane: lanes - 1 - lane, kind: .tap, swipe: nil, step: s, endStep: s,375 source: candidate.kick ? .kick : candidate.snare ? .snare : source))376 }377 }378 notes.sort { $0.step != $1.step ? $0.step < $1.step : $0.lane < $1.lane }379 return PulseChart(trackID: song.spec.id, difficulty: difficulty, bpm: song.spec.bpm, duration: song.duration, notes: notes)380 }381382 /// Every way a chart could be unplayable. Empty for all shipped charts (checked by the unit tests).383 static func problems(in chart: PulseChart) -> [String] {384 let rules = PulseChartRules.rules(for: chart.difficulty)385 var issues: [String] = []386 let epsilon = 1e-6387 if chart.notes.isEmpty { issues.append("no notes") }388 for (index, note) in chart.notes.enumerated() {389 if note.lane < 0 || note.lane >= lanes { issues.append("note \(index): lane \(note.lane)") }390 if note.time < leadIn - epsilon { issues.append("note \(index): starts before the lead-in") }391 if note.end > chart.duration - leadOut + epsilon { issues.append("note \(index): ends too close to the end of the track") }392 if note.isHold != (note.end > note.time) { issues.append("note \(index): hold flag and length disagree") }393 if (note.kind == .swipe) != (note.swipe != nil) { issues.append("note \(index): swipe flag and direction disagree") }394 if index > 0, chart.notes[index - 1].time > note.time + epsilon { issues.append("note \(index): out of order") }395 }396 // Simultaneous notes: at most two, one for each thumb.397 let groups = Dictionary(grouping: chart.notes, by: \.step)398 for (step, group) in groups where group.count > 1 {399 if group.count > 2 { issues.append("step \(step): \(group.count) simultaneous notes") }400 if Set(group.map(\.hand)).count != group.count { issues.append("step \(step): simultaneous notes on one thumb") }401 }402 // Each thumb: enough time between notes, and nothing else while it holds.403 for hand in 0..<2 {404 let own = chart.notes.filter { $0.hand == hand }405 for (a, b) in zip(own, own.dropFirst()) where b.time - a.end < rules.handGap - epsilon {406 issues.append("hand \(hand): \(b.time - a.end) s after the note at \(a.time)")407 }408 }409 for lane in 0..<lanes {410 let own = chart.notes.filter { $0.lane == lane }411 for (a, b) in zip(own, own.dropFirst()) where b.time <= a.end + epsilon {412 issues.append("lane \(lane): overlap at \(b.time)")413 }414 }415 // Distinct note times keep the difficulty's minimum spacing.416 let times = Array(Set(chart.notes.map(\.step))).sorted()417 let stepDuration = 15 / chart.bpm418 for (a, b) in zip(times, times.dropFirst()) where Double(b - a) * stepDuration < rules.gap - epsilon {419 issues.append("steps \(a) and \(b) closer than \(rules.gap) s")420 }421 return issues422 }423}424