SPB Git

Repository Public License

PulseScene.swift 48.7 KB 1,102 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/PulseBeat/PulseScene.swift10// Description      : Pulse Beat — SpriteKit scene: the neon note highway in11//                    perspective, multi-touch input stamped on the audio12//                    timeline, the autoplay bot, hit lighting, particles, the13//                    judgement readout, the count-in and the music-reactive14//                    background.15// Module           : Games16// Repository       : https://git.spboucher.ai/orix-arcade17// Created          : 2026-11-2218// Last Modified    : 2026-11-2219//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : Proprietary, all rights reserved (see license file)85// License File     : LICENSE86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import SpriteKit94import UIKit95import Observation9697/// What the SwiftUI HUD shows. The scene writes it on gameplay events, never every frame.98@Observable99final class PulseHUDModel {100    var score = 0101    var combo = 0102    var multiplier = 1103    var accuracy = 1.0104    var progress = 0.0105    var section = ""106    var coach: String?107    var coachSymbol = "hand.tap.fill"108}109110/// Perspective of the highway: a note `p` of the way from the hit line (0) to the horizon (1) sits at `fraction(p)` of the screen distance.111nonisolated struct PulseHighway: Sendable, Equatable {112    var centerX: CGFloat = 195113    var hitY: CGFloat = 130114    var horizonY: CGFloat = 640115    var halfBottom: CGFloat = 180116    var halfTop: CGFloat = 60117    /// Strength of the foreshortening.118    var curve: CGFloat = 1.5119120    var laneWidth: CGFloat { halfBottom / 2 }121122    func fraction(_ p: CGFloat) -> CGFloat { p >= 0 ? p * (1 + curve) / (1 + curve * p) : p * (1 + curve) }123    func y(fraction f: CGFloat) -> CGFloat { hitY + (horizonY - hitY) * f }124    func scale(fraction f: CGFloat) -> CGFloat { max(0.05, 1 - (1 - halfTop / halfBottom) * f) }125    /// Screen x of a lane coordinate (0 = left edge of the highway, 4 = right edge) at a screen fraction.126    func x(lane: CGFloat, fraction f: CGFloat) -> CGFloat { centerX + (lane - 2) * laneWidth * scale(fraction: f) }127    func point(lane: CGFloat, fraction f: CGFloat) -> CGPoint { CGPoint(x: x(lane: lane, fraction: f), y: y(fraction: f)) }128    /// Lane under a touch at `x` (judged at the hit line, where the thumbs are).129    func lane(atX x: CGFloat) -> Int { Int(((x - (centerX - halfBottom)) / laneWidth).rounded(.down)).clamped(0, PulseChartBuilder.lanes - 1) }130}131132enum PulseArt {133    static let laneHex: [UInt32] = [0xFF4FD8, 0x7C8CFF, 0x4DF0FF, 0xFFD166]134    static func laneColor(_ lane: Int) -> UIColor { UIColor(hex: laneHex[lane.clamped(0, laneHex.count - 1)]) }135    static let tierHex: [UInt32] = [0x5B8CFF, 0x4DF0FF, 0xF94CFF, 0xFFD166]136137    /// The shape that identifies a lane when colour assist is on: circle, diamond, square, triangle.138    static func lanePath(_ lane: Int, radius r: CGFloat) -> CGPath {139        let path = CGMutablePath()140        switch lane {141        case 0:142            path.addEllipse(in: CGRect(x: -r, y: -r, width: r * 2, height: r * 2))143        case 1:144            path.addLines(between: [CGPoint(x: 0, y: r * 1.2), CGPoint(x: r * 1.2, y: 0), CGPoint(x: 0, y: -r * 1.2), CGPoint(x: -r * 1.2, y: 0)])145            path.closeSubpath()146        case 2:147            path.addRect(CGRect(x: -r * 0.9, y: -r * 0.9, width: r * 1.8, height: r * 1.8))148        default:149            path.addLines(between: [CGPoint(x: 0, y: r * 1.1), CGPoint(x: r * 1.15, y: -r * 0.9), CGPoint(x: -r * 1.15, y: -r * 0.9)])150            path.closeSubpath()151        }152        return path153    }154155    /// A note gem, drawn once per lane, kind and width.156    static func gem(lane: Int, kind: PulseNoteKind, swipe: PulseSwipe?, width: CGFloat, assist: Bool) -> SKTexture {157        let height: CGFloat = kind == .swipe ? 30 : 24158        let pad: CGFloat = 10159        let size = CGSize(width: width + pad * 2, height: height + pad * 2)160        let key = "pulse-gem-\(lane)-\(kind.rawValue)-\(swipe?.rawValue ?? -1)-\(Int(width))-\(assist ? 1 : 0)"161        return TextureFactory.texture(key, size: size) { ctx, size in162            let color = laneColor(lane)163            let body = CGRect(x: pad, y: pad, width: width, height: height)164            let path = UIBezierPath(roundedRect: body, cornerRadius: height / 2).cgPath165            ctx.saveGState()166            ctx.setShadow(offset: .zero, blur: 9, color: color.withAlphaComponent(0.95).cgColor)167            ctx.addPath(path)168            ctx.setFillColor(color.cgColor)169            ctx.fillPath()170            ctx.restoreGState()171            ctx.saveGState()172            ctx.addPath(path)173            ctx.clip()174            let top = kind == .swipe ? UIColor.white : color.lighter(0.55)175            let bottom = kind == .swipe ? color.lighter(0.5) : color.darker(0.18)176            let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: [top.cgColor, bottom.cgColor] as CFArray, locations: [0, 1])!177            ctx.drawLinearGradient(gradient, start: CGPoint(x: 0, y: body.minY), end: CGPoint(x: 0, y: body.maxY), options: [])178            ctx.restoreGState()179            ctx.addPath(UIBezierPath(roundedRect: body.insetBy(dx: 1.5, dy: 1.5), cornerRadius: height / 2 - 1.5).cgPath)180            ctx.setStrokeColor(UIColor.white.withAlphaComponent(0.9).cgColor)181            ctx.setLineWidth(1.6)182            ctx.strokePath()183            let c = CGPoint(x: body.midX, y: body.midY)184            let ink = UIColor(hex: 0x120A2E)185            switch kind {186            case .swipe:187                // Arrow. The context is flipped (y grows downwards), so "up" points to smaller y.188                ctx.saveGState()189                ctx.translateBy(x: c.x, y: c.y)190                switch swipe ?? .up {191                case .up: break192                case .left: ctx.rotate(by: -.pi / 2)193                case .right: ctx.rotate(by: .pi / 2)194                }195                let arrow = CGMutablePath()196                arrow.move(to: CGPoint(x: 0, y: -10))197                arrow.addLine(to: CGPoint(x: 10, y: 1))198                arrow.addLine(to: CGPoint(x: 4, y: 1))199                arrow.addLine(to: CGPoint(x: 4, y: 10))200                arrow.addLine(to: CGPoint(x: -4, y: 10))201                arrow.addLine(to: CGPoint(x: -4, y: 1))202                arrow.addLine(to: CGPoint(x: -10, y: 1))203                arrow.closeSubpath()204                ctx.addPath(arrow)205                ctx.setFillColor(ink.cgColor)206                ctx.fillPath()207                ctx.restoreGState()208            case .hold:209                ctx.setFillColor(UIColor.white.withAlphaComponent(0.95).cgColor)210                ctx.fill(CGRect(x: c.x - width * 0.22, y: c.y - 2, width: width * 0.44, height: 4))211            case .tap:212                if assist {213                    ctx.saveGState()214                    ctx.translateBy(x: c.x, y: c.y)215                    ctx.scaleBy(x: 1, y: -1)216                    ctx.addPath(lanePath(lane, radius: 6))217                    ctx.setFillColor(ink.cgColor)218                    ctx.fillPath()219                    ctx.restoreGState()220                }221            }222        }223    }224225    static func sky(size: CGSize, hexA: UInt32, hexB: UInt32, horizon: CGFloat) -> SKTexture {226        let key = "pulse-sky-\(Int(size.width))x\(Int(size.height))-\(hexA)-\(hexB)-\(Int(horizon))"227        return TextureFactory.texture(key, size: size) { ctx, size in228            let space = CGColorSpaceCreateDeviceRGB()229            let top = UIColor(hex: 0x05030F), mid = UIColor(hex: GameTheme.pulseBeat.deepHex).blended(with: UIColor(hex: hexB), 0.22), low = UIColor(hex: 0x07040F)230            let split = max(0.1, min(0.9, 1 - horizon / size.height))231            let gradient = CGGradient(colorsSpace: space, colors: [top.cgColor, mid.cgColor, low.cgColor] as CFArray, locations: [0, split, 1])!232            ctx.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 0, y: size.height), options: [])233            // Stars above the horizon.234            var rng = SeededRNG(seed: UInt64(hexA) &+ 99)235            for _ in 0..<70 {236                let x = rng.unit() * size.width, y = rng.unit() * size.height * split * 0.95, r = 0.4 + rng.unit() * 0.9237                ctx.setFillColor(UIColor.white.withAlphaComponent(0.25 + 0.5 * rng.unit()).cgColor)238                ctx.fillEllipse(in: CGRect(x: x, y: y, width: r * 2, height: r * 2))239            }240        }241    }242243    /// The striped sun on the horizon.244    static func sun(diameter: CGFloat, hexA: UInt32, hexB: UInt32) -> SKTexture {245        let size = CGSize(width: diameter, height: diameter)246        return TextureFactory.texture("pulse-sun-\(Int(diameter))-\(hexA)-\(hexB)", size: size) { ctx, size in247            ctx.addEllipse(in: CGRect(origin: .zero, size: size))248            ctx.clip()249            let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: [UIColor(hex: hexA).lighter(0.25).cgColor, UIColor(hex: hexB).cgColor] as CFArray,250                                      locations: [0, 1])!251            ctx.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 0, y: size.height), options: [])252            ctx.setBlendMode(.clear)253            var y = size.height * 0.5254            var thickness: CGFloat = 2255            while y < size.height {256                ctx.fill(CGRect(x: 0, y: y, width: size.width, height: thickness))257                y += thickness + 9258                thickness += 1.3259            }260        }261    }262}263264final class PulseScene: ArcadeScene {265    private enum Phase { case idle, playing, paused, finished }266267    let chart: PulseChart268    private let song: PulseSong269    private let prepared: PulsePrepared270    private let transport: PulseTransport271    private let model: PulseHUDModel272    private let autoplay: Bool273    private let tutorial: Bool274    private let colorAssist = OrixAppearance.colorAssist275    private var onFinished: ((PulseResult) -> Void)?276    private var onStall: (() -> Void)?277    /// `-ORIXPauseAt <seconds>` (with the bot): asks the run view to pause there and resume by itself, to exercise pause and count-in unattended.278    var onAutoPause: (() -> Void)?279    private var autoPauseAt = LaunchOptions.int("PauseAt").map(Double.init)280281    private(set) var run: PulseRun282    private var phase = Phase.idle283    private var began = false284    private var highway = PulseHighway()285    private var lookahead = 1.6286    private var hitSounds = true287    private var endTime = 0.0288    private var lastJudged = -10.0289    private var pausedFrame = 0290291    // Count-in.292    private var countInEnd = -Double.infinity293    private var countInBeat = 0.5294    private var countInShown = -2295    private var countInIsStart = true296297    // Input.298    private var touchIDs: [ObjectIdentifier: (id: Int, start: CGPoint, lane: Int, flicked: Bool)] = [:]299    private var nextTouchID = 1_000_000300    private var botInputs: [PulseInput] = []301    private var botIndex = 0302    private var botPressed: [Int: Int] = [:]303304    // Nodes.305    private let backdrop = SKNode()306    private let road = SKNode()307    private let noteLayer = SKNode()308    private let overlay = SKNode()309    private var glow: SKSpriteNode?310    private var sun: SKSpriteNode?311    private var bars: [SKSpriteNode] = []312    private var edges: [SKShapeNode] = []313    private var flashes: [SKShapeNode] = []314    private var receptors: [SKShapeNode] = []315    private var beatLines: [SKSpriteNode] = []316    private var groundLines: [SKSpriteNode] = []317    private var hitLine: SKSpriteNode?318    private var gems: [Int: SKSpriteNode] = [:]319    private var tails: [Int: SKShapeNode] = [:]320    private var spawnIndex = 0321    private let judgementLabel = SKLabelNode()322    private let timingLabel = SKLabelNode()323    private let comboLabel = SKLabelNode()324    private let comboCaption = SKLabelNode()325    private let countLabel = SKLabelNode()326    private var lastBeat = -1327    private var lastProgressPush = -1.0328    private var pressed = [Int](repeating: 0, count: PulseChartBuilder.lanes)329    private var tier = 1330    private var coachNotes: [(index: Int, text: String, symbol: String)] = []331    private var coachCursor = 0332333    init(services: ArcadeServices, chart: PulseChart, prepared: PulsePrepared, autoplay: Bool, tutorial: Bool, model: PulseHUDModel,334         onFinished: @escaping (PulseResult) -> Void, onStall: @escaping () -> Void) {335        self.chart = chart336        self.song = PulseLibrary.song(chart.trackID)337        self.prepared = prepared338        self.transport = PulseTransport(audio: services.audio)339        self.model = model340        self.autoplay = autoplay341        self.tutorial = tutorial342        self.onFinished = onFinished343        self.onStall = onStall344        self.run = PulseRun(chart: chart)345        super.init(services: services, perfName: "pulseBeat")346        backgroundColor = UIColor(hex: 0x05030F)347        backdrop.zPosition = -50348        road.zPosition = 0349        noteLayer.zPosition = 100350        overlay.zPosition = 300351        world.addChild(backdrop)352        world.addChild(road)353        world.addChild(noteLayer)354        world.addChild(overlay)355        for label in [judgementLabel, timingLabel, comboLabel, comboCaption, countLabel] {356            label.verticalAlignmentMode = .center357            label.horizontalAlignmentMode = .center358            overlay.addChild(label)359        }360        transport.load(buffer: prepared.buffer, frames: prepared.frames)361        endTime = min(chart.duration - 0.4, chart.lastEnd + 2.4)362        if tutorial {363            let lines: [(PulseNoteKind, String, String)] = [364                (.tap, "Tap the lane when a note reaches the line.", "hand.tap.fill"),365                (.hold, "Long note: press, and keep holding to the end of the tail.", "hand.point.up.left.fill"),366                (.swipe, "Arrow note: tap on the beat, then flick the way it points.", "arrow.up"),367            ]368            for (kind, text, symbol) in lines {369                if let index = chart.notes.firstIndex(where: { $0.kind == kind }) { coachNotes.append((index, text, symbol)) }370            }371            coachNotes.sort { $0.index < $1.index }372        }373        if services.audio.isRunning { services.audio.register(custom: "pulse.hit", mono: PulseSynth.hitSound()) }374    }375376    override func didMove(to view: SKView) {377        super.didMove(to: view)378        view.isMultipleTouchEnabled = true379        if !began {380            began = true381            begin()382        }383    }384385    /// Breaks every cycle and frees the player node. The scene cannot be used afterwards.386    func dispose() {387        phase = .finished388        writeClockReport()389        transport.dispose()390        onFinished = nil391        onStall = nil392        onAutoPause = nil393        removeAllActions()394        world.removeAllChildren()395        gems.removeAll()396        tails.removeAll()397    }398399    // MARK: Run control400401    private func applyOptions() {402        let save = services.save.pulse403        lookahead = 2.0 / save.noteSpeed404        hitSounds = save.hitSounds405        transport.timing.offset = Double(save.offsetMs(route: PulseRoute.current.rawValue)) / 1000406        transport.timing.visualOffset = Double(save.visualOffsetMs) / 1000407    }408409    private func begin() {410        run = PulseRun(chart: chart)411        for node in gems.values { node.removeFromParent() }412        for node in tails.values { node.removeFromParent() }413        gems.removeAll()414        tails.removeAll()415        spawnIndex = 0416        botIndex = 0417        botPressed.removeAll()418        touchIDs.removeAll()419        pressed = [Int](repeating: 0, count: PulseChartBuilder.lanes)420        lastBeat = -1421        lastProgressPush = -1422        coachCursor = 0423        tier = 1424        model.score = 0425        model.combo = 0426        model.multiplier = 1427        model.accuracy = 1428        model.progress = 0429        model.coach = nil430        model.section = song.section(at: 0).title431        if autoplay { botInputs = PulseBot.inputs(for: chart, seed: LaunchOptions.seed ?? 7) }432        applyOptions()433        updateCombo(animated: false)434        setEdgeTier(1)435        // The lobby loop fades out first; then the music bus is opened again for the track.436        let audio = services.audio437        audio.setMusic(nil)438        Task { [weak self] in439            try? await Task.sleep(for: .milliseconds(450))440            guard self != nil else { return }441            audio.duckMusic(to: 1, over: 0.08)442        }443        let preRoll = 1.2444        transport.start(fromFrame: 0, delay: preRoll)445        countInEnd = transport.timing.judged(raw: 0)446        countInBeat = preRoll447        countInShown = -2448        countInIsStart = true449        phase = .playing450    }451452    func restart() {453        guard phase != .idle else { return }454        transport.stop()455        begin()456    }457458    /// Bound to the session: pausing stops the track on the frame being heard; resuming restarts it there after a count-in.459    func setPaused(_ paused: Bool) {460        if paused {461            guard phase == .playing else { return }462            pausedFrame = transport.pause()463            run.suspendHolds()464            touchIDs.removeAll()465            pressed = [Int](repeating: 0, count: PulseChartBuilder.lanes)466            phase = .paused467        } else {468            guard phase == .paused else { return }469            applyOptions()470            services.audio.duckMusic(to: 1, over: 0.08)471            let beats = 3.0472            let beat = max(song.beatDuration, 0.4)473            transport.start(fromFrame: pausedFrame, delay: beats * beat)474            countInEnd = transport.timing.judged(raw: transport.clock.basePosition)475            countInBeat = beat476            countInShown = -2477            countInIsStart = false478            phase = .playing479        }480    }481482    private func finish() {483        guard phase == .playing else { return }484        phase = .finished485        run.advance(to: chart.duration + 1)486        var result = run.result487        result.autoplay = autoplay488        writeClockReport()489        let audio = services.audio490        audio.duckMusic(to: 0, over: 0.5)491        let transport = transport492        Task {493            try? await Task.sleep(for: .milliseconds(600))494            transport.stop()495        }496        model.progress = 1497        model.coach = nil498        comboLabel.isHidden = true499        comboCaption.isHidden = true500        onFinished?(result)501    }502503    /// With `-ORIXPerfLog YES`: what the audio clock measured during the run, next to the frame-time report.504    private func writeClockReport() {505        guard LaunchOptions.perfLog else { return }506        let report: [String: Double] = [507            "usingAudio": transport.usingAudio ? 1 : 0,508            "observations": Double(transport.clock.observations),509            "largestErrorMs": transport.clock.largestError * 1000,510            "reportedLatencyMs": transport.timing.latency * 1000,511            "renderSeconds": prepared.renderSeconds,512            "bufferBytes": Double(prepared.bytes),513            "trackSeconds": chart.duration,514        ]515        let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("pulse-clock.json")516        if let data = try? JSONSerialization.data(withJSONObject: report, options: [.prettyPrinted, .sortedKeys]) { try? data.write(to: url, options: .atomic) }517    }518519    // MARK: Layout520521    override func layout() {522        let w = size.width, h = size.height523        highway.centerX = w / 2524        highway.halfBottom = min(w / 2 - 4, 230)525        highway.halfTop = highway.halfBottom * 0.3526        highway.hitY = safeInsets.bottom + max(96, h * 0.155)527        highway.horizonY = h - safeInsets.top - max(150, h * 0.2)528        buildStatic()529    }530531    private func setText(_ label: SKLabelNode, _ text: String, size: CGFloat, color: UIColor, weight: UIFont.Weight = .black) {532        label.attributedText = NSAttributedString(string: text, attributes: [.font: OrixFont.rounded(size, weight: weight), .foregroundColor: color])533    }534535    private func lanePolygon(_ lane: CGFloat, to next: CGFloat, from f0: CGFloat, to f1: CGFloat) -> CGPath {536        let path = CGMutablePath()537        path.addLines(between: [highway.point(lane: lane, fraction: f0), highway.point(lane: next, fraction: f0),538                                highway.point(lane: next, fraction: f1), highway.point(lane: lane, fraction: f1)])539        path.closeSubpath()540        return path541    }542543    private func buildStatic() {544        backdrop.removeAllChildren()545        road.removeAllChildren()546        bars.removeAll()547        edges.removeAll()548        flashes.removeAll()549        receptors.removeAll()550        beatLines.removeAll()551        groundLines.removeAll()552        let w = size.width, h = size.height553        let spec = song.spec554        let bottomFraction = -highway.hitY / (highway.horizonY - highway.hitY)555556        let sky = SKSpriteNode(texture: PulseArt.sky(size: size, hexA: spec.hexA, hexB: spec.hexB, horizon: highway.horizonY), size: size)557        sky.position = CGPoint(x: w / 2, y: h / 2)558        sky.zPosition = -10559        backdrop.addChild(sky)560561        let diameter = min(w * 0.36, 150)562        let sunNode = SKSpriteNode(texture: PulseArt.sun(diameter: diameter, hexA: spec.hexA, hexB: spec.hexB), size: CGSize(width: diameter, height: diameter))563        sunNode.position = CGPoint(x: w / 2, y: highway.horizonY + diameter * 0.12)564        sunNode.zPosition = -8565        sunNode.alpha = 0.92566        backdrop.addChild(sunNode)567        sun = sunNode568569        let glowNode = SKSpriteNode(texture: TextureFactory.softDot, size: CGSize(width: w * 1.5, height: w * 0.9))570        glowNode.position = CGPoint(x: w / 2, y: highway.horizonY)571        glowNode.color = UIColor(hex: spec.hexA)572        glowNode.colorBlendFactor = 1573        glowNode.blendMode = .add574        glowNode.alpha = 0.3575        glowNode.zPosition = -9576        backdrop.addChild(glowNode)577        glow = glowNode578579        // Spectrum bars along the horizon, on both sides of the road.580        let count = 16581        let barWidth = w / CGFloat(count) * 0.62582        for index in 0..<count {583            let bar = SKSpriteNode(texture: TextureFactory.chip, size: CGSize(width: barWidth, height: 10))584            bar.anchorPoint = CGPoint(x: 0.5, y: 0)585            bar.position = CGPoint(x: (CGFloat(index) + 0.5) * w / CGFloat(count), y: highway.horizonY - 1)586            bar.color = UIColor(hex: spec.hexA).blended(with: UIColor(hex: spec.hexB), CGFloat(index) / CGFloat(count - 1))587            bar.colorBlendFactor = 1588            bar.alpha = 0.55589            bar.zPosition = -7590            backdrop.addChild(bar)591            bars.append(bar)592        }593594        // The ground and the road.595        let ground = SKSpriteNode(color: UIColor(hex: 0x06040F), size: CGSize(width: w, height: highway.horizonY))596        ground.anchorPoint = .zero597        ground.zPosition = -6598        backdrop.addChild(ground)599600        // The floor on both sides: lines running to the same vanishing point as the road.601        let floor = CGMutablePath()602        for lane in stride(from: -9, through: 13, by: 1) where lane < 0 || lane > 4 {603            floor.move(to: highway.point(lane: CGFloat(lane), fraction: bottomFraction))604            floor.addLine(to: highway.point(lane: CGFloat(lane), fraction: 1))605        }606        let grid = SKShapeNode(path: floor)607        grid.strokeColor = UIColor(hex: spec.hexB).withAlphaComponent(0.22)608        grid.lineWidth = 1609        grid.zPosition = -5610        backdrop.addChild(grid)611        for _ in 0..<12 {612            let line = SKSpriteNode(color: UIColor(hex: spec.hexB), size: CGSize(width: w, height: 1))613            line.zPosition = -5614            line.isHidden = true615            backdrop.addChild(line)616            groundLines.append(line)617        }618        let horizonLine = SKSpriteNode(color: UIColor(hex: spec.hexA), size: CGSize(width: w, height: 2))619        horizonLine.position = CGPoint(x: w / 2, y: highway.horizonY)620        horizonLine.zPosition = -4621        backdrop.addChild(horizonLine)622623        let body = SKShapeNode(path: lanePolygon(0, to: 4, from: bottomFraction, to: 1))624        body.fillColor = UIColor(hex: 0x0B0720)625        body.strokeColor = .clear626        body.zPosition = 1627        road.addChild(body)628        for lane in 0..<PulseChartBuilder.lanes {629            let tint = SKShapeNode(path: lanePolygon(CGFloat(lane), to: CGFloat(lane + 1), from: bottomFraction, to: 1))630            tint.fillColor = PulseArt.laneColor(lane).withAlphaComponent(0.06)631            tint.strokeColor = .clear632            tint.zPosition = 2633            road.addChild(tint)634            let flash = SKShapeNode(path: lanePolygon(CGFloat(lane), to: CGFloat(lane + 1), from: bottomFraction, to: 1))635            flash.fillColor = PulseArt.laneColor(lane)636            flash.strokeColor = .clear637            flash.blendMode = .add638            flash.alpha = 0639            flash.zPosition = 3640            road.addChild(flash)641            flashes.append(flash)642        }643        for divider in 1..<PulseChartBuilder.lanes {644            let path = CGMutablePath()645            path.move(to: highway.point(lane: CGFloat(divider), fraction: bottomFraction))646            path.addLine(to: highway.point(lane: CGFloat(divider), fraction: 1))647            let line = SKShapeNode(path: path)648            line.strokeColor = UIColor.white.withAlphaComponent(0.13)649            line.lineWidth = 1650            line.zPosition = 4651            road.addChild(line)652        }653        for side in [CGFloat(0), 4] {654            let path = CGMutablePath()655            path.move(to: highway.point(lane: side, fraction: bottomFraction))656            path.addLine(to: highway.point(lane: side, fraction: 1))657            let edge = SKShapeNode(path: path)658            edge.lineWidth = 2.5659            edge.glowWidth = OrixAppearance.highContrast ? 0 : 5660            edge.zPosition = 6661            road.addChild(edge)662            edges.append(edge)663        }664        setEdgeTier(tier)665666        for _ in 0..<12 {667            let line = SKSpriteNode(texture: TextureFactory.chip, size: CGSize(width: 10, height: 2))668            line.zPosition = 5669            line.isHidden = true670            road.addChild(line)671            beatLines.append(line)672        }673674        let lineNode = SKSpriteNode(color: UIColor.white.withAlphaComponent(0.9), size: CGSize(width: highway.halfBottom * 2, height: 3))675        lineNode.position = CGPoint(x: highway.centerX, y: highway.hitY)676        lineNode.zPosition = 8677        road.addChild(lineNode)678        hitLine = lineNode679        let gemWidth = highway.laneWidth * 0.84680        for lane in 0..<PulseChartBuilder.lanes {681            let receptor = SKShapeNode(rectOf: CGSize(width: gemWidth, height: 26), cornerRadius: 13)682            receptor.position = highway.point(lane: CGFloat(lane) + 0.5, fraction: 0)683            receptor.strokeColor = PulseArt.laneColor(lane)684            receptor.lineWidth = 2.5685            receptor.fillColor = PulseArt.laneColor(lane).withAlphaComponent(0.14)686            receptor.zPosition = 9687            road.addChild(receptor)688            receptors.append(receptor)689            if colorAssist {690                let glyph = SKShapeNode(path: PulseArt.lanePath(lane, radius: 6))691                glyph.fillColor = PulseArt.laneColor(lane)692                glyph.strokeColor = .clear693                glyph.zPosition = 1694                receptor.addChild(glyph)695            }696        }697698        let mid = highway.y(fraction: 0.5)699        judgementLabel.position = CGPoint(x: highway.centerX, y: highway.hitY + 78)700        timingLabel.position = CGPoint(x: highway.centerX, y: highway.hitY + 52)701        comboLabel.position = CGPoint(x: highway.centerX, y: mid + 34)702        comboCaption.position = CGPoint(x: highway.centerX, y: mid + 2)703        countLabel.position = CGPoint(x: highway.centerX, y: mid + 90)704        updateCombo(animated: false)705    }706707    private func setEdgeTier(_ value: Int) {708        tier = value709        let color = UIColor(hex: PulseArt.tierHex[(value - 1).clamped(0, PulseArt.tierHex.count - 1)])710        for edge in edges { edge.strokeColor = color }711    }712713    // MARK: Frame714715    override func tick(dt: TimeInterval) {716        guard phase == .playing else { return }717        transport.poll()718        let host = CACurrentMediaTime()719        let judged = transport.judgedPosition(atHost: host)720        lastJudged = judged721722        if autoplay {723            while botIndex < botInputs.count, botInputs[botIndex].time <= judged {724                let input = botInputs[botIndex]725                botIndex += 1726                switch input.action {727                case .down(let lane):728                    botPressed[input.touch] = lane729                    press(lane, down: true)730                case .up:731                    if let lane = botPressed.removeValue(forKey: input.touch) { press(lane, down: false) }732                case .flick:733                    break734                }735                handle(run.apply(input))736            }737        }738        handle(run.advance(to: judged))739740        if transport.isStalled {741            onStall?()742            return743        }744        updateCountIn(judged)745        let visual = transport.timing.visual(judged: judged)746        updateNotes(visual)747        updateBackdrop(visual, dt: dt)748        updateCoach(visual)749        if judged - lastProgressPush > 0.25 {750            lastProgressPush = judged751            model.progress = (judged / max(endTime, 1)).clamped(0, 1)752            let title = song.section(at: max(0, judged)).title753            if model.section != title { model.section = title }754        }755        if let at = autoPauseAt, autoplay, judged >= at {756            autoPauseAt = nil757            onAutoPause?()758        }759        if judged >= endTime { finish() }760    }761762    private func updateCountIn(_ judged: Double) {763        let remaining = countInEnd - judged764        guard remaining > 0 else {765            if countInShown != -1 {766                countInShown = -1767                countLabel.run(.sequence([.fadeOut(withDuration: 0.15), .hide()]))768            }769            return770        }771        let number = countInIsStart ? 0 : min(3, Int((remaining / countInBeat).rounded(.up)))772        guard number != countInShown || countLabel.isHidden else { return }773        countInShown = number774        countLabel.removeAllActions()775        countLabel.isHidden = false776        countLabel.alpha = 1777        setText(countLabel, countInIsStart ? "READY" : "\(number)", size: countInIsStart ? 34 : 64, color: .white)778        if !reduceMotion {779            countLabel.setScale(1.35)780            countLabel.run(.scale(to: 1, duration: 0.18))781        }782        if !countInIsStart {783            services.audio.play(.countdown, pitch: number == 1 ? 1.5 : 1)784            services.haptics.play(.tick)785        }786    }787788    private func place(_ node: SKNode, lane: Int, p: Double) {789        let f = highway.fraction(CGFloat(p))790        node.position = highway.point(lane: CGFloat(lane) + 0.5, fraction: f)791        node.setScale(highway.scale(fraction: f))792        node.zPosition = CGFloat(50 - p * 40)793        node.alpha = CGFloat(((1 - p) / 0.1).clamped(0, 1))794    }795796    private func updateNotes(_ visual: Double) {797        let gemWidth = highway.laneWidth * 0.84798        while spawnIndex < chart.notes.count, chart.notes[spawnIndex].time < visual + lookahead {799            let index = spawnIndex800            spawnIndex += 1801            guard !run.isResolved(index) else { continue }802            let note = chart.notes[index]803            let gem = SKSpriteNode(texture: PulseArt.gem(lane: note.lane, kind: note.kind, swipe: note.swipe, width: gemWidth, assist: colorAssist))804            noteLayer.addChild(gem)805            gems[index] = gem806            if note.isHold {807                let tail = SKShapeNode()808                tail.fillColor = PulseArt.laneColor(note.lane).withAlphaComponent(0.42)809                tail.strokeColor = PulseArt.laneColor(note.lane).lighter(0.35)810                tail.lineWidth = 1.5811                tail.zPosition = 5812                noteLayer.addChild(tail)813                tails[index] = tail814            }815        }816        var finished: [Int] = []817        for (index, gem) in gems {818            if run.isResolved(index) {819                finished.append(index)820                continue821            }822            let note = chart.notes[index]823            let held = run.isHeld(index)824            let p = held ? 0 : (note.time - visual) / lookahead825            if p < -0.3 {826                gem.isHidden = true827            } else {828                gem.isHidden = false829                place(gem, lane: note.lane, p: p)830            }831            if let tail = tails[index] {832                let f0 = highway.fraction(CGFloat(max(p, -0.3)))833                let f1 = highway.fraction(CGFloat(min(max((note.end - visual) / lookahead, -0.3), 1)))834                if f1 > f0 {835                    let inset: CGFloat = 0.27836                    tail.path = lanePolygon(CGFloat(note.lane) + inset, to: CGFloat(note.lane) + 1 - inset, from: f0, to: f1)837                    tail.fillColor = PulseArt.laneColor(note.lane).withAlphaComponent(held ? 0.85 : 0.42)838                    tail.isHidden = false839                } else {840                    tail.isHidden = true841                }842            }843        }844        for index in finished {845            gems.removeValue(forKey: index)?.removeFromParent()846            tails.removeValue(forKey: index)?.removeFromParent()847        }848        // A lane stays lit while its hold is down.849        let lit = run.heldLanes850        for lane in lit where flashes.indices.contains(lane) && flashes[lane].alpha < 0.22 { flashes[lane].alpha = 0.22 }851    }852853    private func updateBackdrop(_ visual: Double, dt: TimeInterval) {854        let beat = song.beatDuration855        // Beat lines scrolling down the road: the grid of the music made visible.856        let first = Int((max(visual, 0) / beat).rounded(.up))857        var used = 0858        var k = first859        while used < beatLines.count, Double(k) * beat < visual + lookahead {860            let p = (Double(k) * beat - visual) / lookahead861            let f = highway.fraction(CGFloat(p))862            let line = beatLines[used]863            let bar = k % 4 == 0864            line.isHidden = false865            line.position = CGPoint(x: highway.centerX, y: highway.y(fraction: f))866            line.size = CGSize(width: highway.halfBottom * 2 * highway.scale(fraction: f), height: bar ? 2 : 1)867            line.alpha = CGFloat((bar ? 0.3 : 0.13) * ((1 - p) / 0.15).clamped(0, 1))868            if used < groundLines.count {869                let ground = groundLines[used]870                ground.isHidden = false871                ground.position = CGPoint(x: size.width / 2, y: line.position.y)872                ground.alpha = CGFloat((bar ? 0.3 : 0.14) * ((1 - p) / 0.15).clamped(0, 1))873            }874            used += 1875            k += 1876        }877        for index in used..<beatLines.count {878            beatLines[index].isHidden = true879            if index < groundLines.count { groundLines[index].isHidden = true }880        }881        for flash in flashes where flash.alpha > 0 { flash.alpha = max(0, flash.alpha - CGFloat(dt) * 2.8) }882883        let envelope = prepared.envelope884        let low = reduceMotion ? 0.4 : envelope.value(envelope.low, at: visual)885        let barCount = bars.count886        for (index, bar) in bars.enumerated() {887            let value: Double888            if reduceMotion {889                value = 0.3890            } else {891                // Low frequencies in the middle, highs at the edges, each bar reading the envelope a few milliseconds apart.892                let spread = abs(Double(index) - Double(barCount - 1) / 2) / (Double(barCount) / 2)893                let lag = visual - Double(index % 5) * 0.018894                value = envelope.value(envelope.low, at: lag) * (1 - spread) + envelope.value(envelope.high, at: lag) * spread * 0.9895                    + envelope.value(envelope.mid, at: lag) * 0.25896            }897            bar.size.height = 5 + CGFloat(value) * 62 * effectScale898        }899        glow?.alpha = CGFloat(0.22 + 0.4 * low)900        guard visual >= 0, !reduceMotion else { return }901        let beatPhase = visual / beat902        let pulse = exp(-5 * (beatPhase - beatPhase.rounded(.down)))903        sun?.setScale(1 + 0.035 * CGFloat(pulse))904        hitLine?.alpha = CGFloat(0.7 + 0.3 * pulse)905        let index = Int(beatPhase.rounded(.down))906        if index != lastBeat {907            lastBeat = index908            let section = song.section(at: visual)909            guard section == .drop || index % 4 == 0, visual < endTime else { return }910            // Beat-synchronised sparks rise from the horizon, alternating sides.911            let side: CGFloat = index % 2 == 0 ? 0 : 4912            burst(at: highway.point(lane: side, fraction: 1), color: UIColor(hex: index % 2 == 0 ? song.spec.hexA : song.spec.hexB),913                  count: section == .drop ? 7 : 4, speed: 70, lifetime: 0.7, scale: 0.28, gravity: 40, spread: .pi * 0.7, angle: .pi / 2)914        }915    }916917    private func updateCoach(_ visual: Double) {918        guard tutorial, coachCursor < coachNotes.count else {919            if model.coach != nil { model.coach = nil }920            return921        }922        let entry = coachNotes[coachCursor]923        let note = chart.notes[entry.index]924        if visual > note.end + 0.5 {925            coachCursor += 1926            model.coach = nil927        } else if visual > note.time - 3.2, model.coach != entry.text {928            model.coachSymbol = entry.symbol929            model.coach = entry.text930        }931    }932933    // MARK: Feedback934935    private func press(_ lane: Int, down: Bool) {936        guard receptors.indices.contains(lane) else { return }937        pressed[lane] = max(0, pressed[lane] + (down ? 1 : -1))938        receptors[lane].fillColor = PulseArt.laneColor(lane).withAlphaComponent(pressed[lane] > 0 ? 0.55 : 0.14)939    }940941    private func updateCombo(animated: Bool) {942        let combo = run.tally.combo943        if combo >= 5 {944            setText(comboLabel, "\(combo)", size: 46, color: UIColor.white.withAlphaComponent(0.5))945            setText(comboCaption, "COMBO  ×\(run.multiplier)", size: 13, color: UIColor(hex: PulseArt.tierHex[(run.multiplier - 1).clamped(0, 3)]), weight: .heavy)946            comboLabel.isHidden = false947            comboCaption.isHidden = false948            if animated, !reduceMotion {949                comboLabel.removeAllActions()950                comboLabel.setScale(1.14)951                comboLabel.run(.scale(to: 1, duration: 0.09))952            }953        } else {954            comboLabel.isHidden = true955            comboCaption.isHidden = true956        }957    }958959    private func showJudgement(_ judgement: PulseJudgement, offset: Double?) {960        setText(judgementLabel, judgement.title, size: 26, color: UIColor(hex: judgement.hex))961        judgementLabel.removeAllActions()962        judgementLabel.alpha = 1963        judgementLabel.setScale(reduceMotion ? 1 : 1.18)964        judgementLabel.run(.group([.scale(to: 1, duration: 0.08), .sequence([.wait(forDuration: 0.42), .fadeOut(withDuration: 0.2)])]))965        timingLabel.removeAllActions()966        if let offset, judgement != .perfect, judgement != .miss {967            let ms = Int((abs(offset) * 1000).rounded())968            setText(timingLabel, offset < 0 ? "◀ EARLY \(ms) ms" : "LATE \(ms) ms ▶", size: 13,969                    color: offset < 0 ? UIColor(hex: 0x4DD8FF) : UIColor(hex: 0xFF8A5C), weight: .heavy)970            timingLabel.alpha = 1971            timingLabel.run(.sequence([.wait(forDuration: 0.5), .fadeOut(withDuration: 0.2)]))972        } else {973            timingLabel.alpha = 0974        }975    }976977    private func handle(_ events: [PulseEvent]) {978        guard !events.isEmpty else { return }979        var scored = false980        for event in events {981            switch event {982            case .judged(_, let lane, let judgement, let offset, let part, let combo, _):983                scored = true984                showJudgement(judgement, offset: offset)985                let receptor = highway.point(lane: CGFloat(lane) + 0.5, fraction: 0)986                if judgement == .miss {987                    if part != .tail || combo == 0 { services.audio.play(.miss, volume: 0.3) }988                    if flashes.indices.contains(lane) {989                        flashes[lane].fillColor = UIColor(hex: PulseJudgement.miss.hex)990                        flashes[lane].alpha = 0.22991                    }992                } else {993                    if flashes.indices.contains(lane) {994                        flashes[lane].fillColor = PulseArt.laneColor(lane)995                        flashes[lane].alpha = judgement == .perfect ? 0.6 : 0.4996                    }997                    burst(at: receptor, color: judgement == .perfect ? UIColor(hex: PulseJudgement.perfect.hex) : PulseArt.laneColor(lane),998                          count: judgement == .perfect ? 12 : judgement == .great ? 8 : 5, speed: part == .tail ? 220 : 170, lifetime: 0.4, scale: 0.32,999                          gravity: -120, spread: .pi * 0.9, angle: .pi / 2)1000                    if receptors.indices.contains(lane), !reduceMotion {1001                        receptors[lane].removeAllActions()1002                        receptors[lane].setScale(1.16)1003                        receptors[lane].run(.scale(to: 1, duration: 0.1))1004                    }1005                    if hitSounds, part != .tail {1006                        services.audio.play(custom: "pulse.hit", pitch: judgement == .perfect ? 1.12 : 1, volume: judgement == .perfect ? 0.5 : 0.36)1007                    }1008                    services.haptics.play(judgement == .perfect ? .impact(0.55) : judgement == .great ? .impact(0.3) : .tick)1009                }1010            case .holdTick(_, let lane):1011                scored = true1012                burst(at: highway.point(lane: CGFloat(lane) + 0.5, fraction: 0), color: PulseArt.laneColor(lane).lighter(0.4), count: 3, speed: 120, lifetime: 0.3,1013                      scale: 0.22, gravity: 0, spread: .pi * 0.6, angle: .pi / 2)1014            case .comboBreak(let lost):1015                if lost >= 20 {1016                    shake(0.22)1017                    for edge in edges {1018                        edge.removeAllActions()1019                        edge.strokeColor = UIColor(hex: PulseJudgement.miss.hex)1020                    }1021                    run(.sequence([.wait(forDuration: 0.25), .run { [weak self] in self?.setEdgeTier(1) }]))1022                    services.haptics.play(.failure)1023                }1024            case .milestone(let combo):1025                floatText("\(combo) COMBO", at: CGPoint(x: highway.centerX, y: comboLabel.position.y + 52), in: overlay, color: UIColor(hex: 0xFFE14D), size: 24)1026                burst(at: comboLabel.position, in: overlay, color: UIColor(hex: PulseArt.tierHex[(run.multiplier - 1).clamped(0, 3)]), count: 26, speed: 260,1027                      lifetime: 0.7, scale: 0.4, gravity: -80)1028                services.audio.play(.combo, pitch: Float(min(1 + Double(combo) / 400, 1.6)), volume: 0.6)1029                services.haptics.play(.combo(min(combo / 25, 8)))1030            case .multiplier(let value):1031                setEdgeTier(value)1032                if value > 1 {1033                    floatText("×\(value)", at: CGPoint(x: highway.centerX, y: comboCaption.position.y - 44), in: overlay,1034                              color: UIColor(hex: PulseArt.tierHex[(value - 1).clamped(0, 3)]), size: 20)1035                }1036            case .ghost(let lane):1037                if flashes.indices.contains(lane), flashes[lane].alpha < 0.1 {1038                    flashes[lane].fillColor = PulseArt.laneColor(lane)1039                    flashes[lane].alpha = 0.11040                }1041            case .swipeFailed(_, let lane):1042                floatText("FLICK!", at: highway.point(lane: CGFloat(lane) + 0.5, fraction: 0.12), in: overlay, color: .white, size: 15)1043            }1044        }1045        if scored {1046            let tally = run.tally1047            if model.score != tally.score { model.score = tally.score }1048            if model.combo != tally.combo {1049                model.combo = tally.combo1050                updateCombo(animated: true)1051            }1052            if model.multiplier != run.multiplier { model.multiplier = run.multiplier }1053            if abs(model.accuracy - tally.accuracy) > 0.0004 { model.accuracy = tally.accuracy }1054        }1055    }10561057    // MARK: Touches10581059    /// The audio-timeline position a touch happened at: its own timestamp, not the frame it was delivered in.1060    private func stamp(_ touch: UITouch) -> Double { transport.judgedPosition(atHost: touch.timestamp) }10611062    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {1063        guard phase == .playing, !autoplay else { return }1064        for touch in touches {1065            let location = touch.location(in: self)1066            let lane = highway.lane(atX: location.x)1067            let id = nextTouchID1068            nextTouchID += 11069            touchIDs[ObjectIdentifier(touch)] = (id, location, lane, false)1070            press(lane, down: true)1071            handle(run.touchDown(id, lane: lane, at: stamp(touch)))1072        }1073    }10741075    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {1076        guard phase == .playing, !autoplay else { return }1077        for touch in touches {1078            guard var entry = touchIDs[ObjectIdentifier(touch)], !entry.flicked else { continue }1079            let location = touch.location(in: self)1080            let dx = location.x - entry.start.x, dy = location.y - entry.start.y1081            guard dx * dx + dy * dy >= 18 * 18 else { continue }1082            let direction: PulseSwipe? = dy > abs(dx) * 0.9 ? .up : abs(dx) > abs(dy) ? (dx < 0 ? .left : .right) : nil1083            guard let direction else { continue }1084            entry.flicked = true1085            touchIDs[ObjectIdentifier(touch)] = entry1086            handle(run.flick(entry.id, direction: direction, at: stamp(touch)))1087        }1088    }10891090    private func release(_ touches: Set<UITouch>) {1091        for touch in touches {1092            guard let entry = touchIDs.removeValue(forKey: ObjectIdentifier(touch)) else { continue }1093            press(entry.lane, down: false)1094            guard phase == .playing else { continue }1095            handle(run.touchUp(entry.id, at: stamp(touch)))1096        }1097    }10981099    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { release(touches) }1100    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { release(touches) }1101}1102
Files main
Menu

Theme