Repository Public License
1// ORIX Arcade2// File: ArcadeCore/ArcadeScene.swift3// Description: SpriteKit base scene — fixed-step ticking, automatic effect scaling, screen shake, pooled particle bursts, floating text, cached textures and frame-time logging.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SpriteKit8import UIKit910/// Frame-time statistics for one scene, written to Documents when `-ORIXPerfLog YES` is set.11nonisolated struct PerfReport: Codable, Sendable {12 var name: String13 var frames: Int14 var seconds: Double15 var averageMs: Double16 var p95Ms: Double17 var p99Ms: Double18 var maxMs: Double19 var averageFPS: Double20 var finalEffectScale: Double2122 static func make(name: String, frameTimes: [Double], effectScale: Double) -> PerfReport {23 let sorted = frameTimes.sorted()24 let total = frameTimes.reduce(0, +)25 func percentile(_ p: Double) -> Double { sorted.isEmpty ? 0 : sorted[min(sorted.count - 1, Int(Double(sorted.count) * p))] * 1000 }26 return PerfReport(name: name, frames: sorted.count, seconds: total,27 averageMs: sorted.isEmpty ? 0 : total / Double(sorted.count) * 1000,28 p95Ms: percentile(0.95), p99Ms: percentile(0.99), maxMs: (sorted.last ?? 0) * 1000,29 averageFPS: total > 0 ? Double(sorted.count) / total : 0, finalEffectScale: effectScale)30 }31}3233/// Textures drawn once in code and cached (the app ships no bitmap art).34enum TextureFactory {35 private static var cache: [String: SKTexture] = [:]3637 static func texture(_ key: String, size: CGSize, draw: (CGContext, CGSize) -> Void) -> SKTexture {38 if let cached = cache[key] { return cached }39 let format = UIGraphicsImageRendererFormat()40 format.scale = min(UIScreen.main.scale, 3)41 let image = UIGraphicsImageRenderer(size: size, format: format).image { draw($0.cgContext, size) }42 let texture = SKTexture(image: image)43 cache[key] = texture44 return texture45 }4647 static var softDot: SKTexture {48 texture("softDot", size: CGSize(width: 24, height: 24)) { ctx, size in49 let colors = [UIColor.white.cgColor, UIColor.white.withAlphaComponent(0).cgColor] as CFArray50 let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors, locations: [0.15, 1])!51 let c = CGPoint(x: size.width / 2, y: size.height / 2)52 ctx.drawRadialGradient(gradient, startCenter: c, startRadius: 0, endCenter: c, endRadius: size.width / 2, options: [])53 }54 }5556 static var chip: SKTexture {57 texture("chip", size: CGSize(width: 10, height: 10)) { ctx, size in58 ctx.setFillColor(UIColor.white.cgColor)59 ctx.addPath(UIBezierPath(roundedRect: CGRect(origin: .zero, size: size), cornerRadius: 2).cgPath)60 ctx.fillPath()61 }62 }6364 /// Rounded rectangle with a vertical two-colour gradient and a soft top highlight.65 static func roundedRect(size: CGSize, radius: CGFloat, top: UIColor, bottom: UIColor, stroke: UIColor? = nil) -> SKTexture {66 let key = "rr-\(Int(size.width))x\(Int(size.height))-\(Int(radius))-\(top.hexKey)-\(bottom.hexKey)-\(stroke?.hexKey ?? "n")"67 return texture(key, size: size) { ctx, size in68 let rect = CGRect(origin: .zero, size: size).insetBy(dx: 0.5, dy: 0.5)69 let path = UIBezierPath(roundedRect: rect, cornerRadius: radius).cgPath70 ctx.saveGState()71 ctx.addPath(path)72 ctx.clip()73 let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: [top.cgColor, bottom.cgColor] as CFArray, locations: [0, 1])!74 ctx.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 0, y: size.height), options: [])75 ctx.setFillColor(UIColor.white.withAlphaComponent(0.18).cgColor)76 ctx.fill(CGRect(x: 0, y: 0, width: size.width, height: max(1.5, size.height * 0.12)))77 ctx.restoreGState()78 if let stroke {79 ctx.addPath(path)80 ctx.setStrokeColor(stroke.cgColor)81 ctx.setLineWidth(1)82 ctx.strokePath()83 }84 }85 }86}8788extension UIColor {89 var hexKey: String {90 var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 091 getRed(&r, green: &g, blue: &b, alpha: &a)92 return String(format: "%02x%02x%02x%02x", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255))93 }9495 func lighter(_ amount: CGFloat) -> UIColor { blended(with: .white, amount) }96 func darker(_ amount: CGFloat) -> UIColor { blended(with: .black, amount) }9798 func blended(with other: UIColor, _ t: CGFloat) -> UIColor {99 var r1: CGFloat = 0, g1: CGFloat = 0, b1: CGFloat = 0, a1: CGFloat = 0100 var r2: CGFloat = 0, g2: CGFloat = 0, b2: CGFloat = 0, a2: CGFloat = 0101 getRed(&r1, green: &g1, blue: &b1, alpha: &a1)102 other.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)103 return UIColor(red: r1 + (r2 - r1) * t, green: g1 + (g2 - g1) * t, blue: b1 + (b2 - b1) * t, alpha: a1)104 }105}106107extension SKLabelNode {108 /// Label in the rounded system font used across the app.109 static func orixLabel(_ text: String, size: CGFloat, color: UIColor, weight: UIFont.Weight = .heavy) -> SKLabelNode {110 let label = SKLabelNode()111 label.attributedText = NSAttributedString(string: text, attributes: [.font: OrixFont.rounded(size, weight: weight), .foregroundColor: color])112 return label113 }114}115116/// Base class for the three games' scenes.117///118/// Subclasses put gameplay nodes under `world` (so screen shake moves them, not the HUD) and override `tick(dt:)`.119/// The scene uses `.resizeFill`: its size is the view size in points, origin bottom-left. Lay out in `layout()`.120class ArcadeScene: SKScene {121 let services: ArcadeServices122 let perfName: String123 /// Gameplay content; shaken by `shake(_:)`.124 let world = SKNode()125 /// Safe-area insets of the hosting view, in points. `layout()` is called again when they change.126 var safeInsets = UIEdgeInsets.zero { didSet { if safeInsets != oldValue, size.width > 0 { layout() } } }127 /// 0.35…1 multiplier for particle counts and decorative effects; lowered automatically when frames run long.128 private(set) var effectScale: CGFloat = 1129 var reduceMotion: Bool { OrixAppearance.reduceMotion }130131 private var lastUpdate: TimeInterval = 0132 private var window: [Double] = []133 private var allFrames: [Double] = []134 private var lastPerfWrite: TimeInterval = 0135 private var liveEmitters = 0136 private var shakeTime: TimeInterval = 0137 private var shakeStrength: CGFloat = 0138 private let logPerf = LaunchOptions.perfLog139140 init(services: ArcadeServices, perfName: String) {141 self.services = services142 self.perfName = perfName143 super.init(size: CGSize(width: 390, height: 844))144 scaleMode = .resizeFill145 anchorPoint = .zero146 backgroundColor = UIColor(hex: OrixColor.Hex.midnight)147 addChild(world)148 effectScale = qualityCap149 }150151 @available(*, unavailable)152 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not used") }153154 private var qualityCap: CGFloat {155 switch services.settings.effects {156 case .high: 1157 case .low: 0.4158 case .auto: ProcessInfo.processInfo.isLowPowerModeEnabled ? 0.6 : 1159 }160 }161162 override func didChangeSize(_ oldSize: CGSize) {163 super.didChangeSize(oldSize)164 if size.width > 0, size.height > 0 { layout() }165 }166167 /// Override to position nodes for the current `size` and `safeInsets`.168 func layout() {}169170 /// Override for gameplay. `dt` is clamped to 1/20 s so a hitch never teleports the simulation.171 func tick(dt: TimeInterval) {}172173 final override func update(_ currentTime: TimeInterval) {174 let raw = lastUpdate == 0 ? 1.0 / 60 : currentTime - lastUpdate175 lastUpdate = currentTime176 // After a pause the first delta is huge: treat it as a single normal frame.177 let dt = raw > 0.5 ? 1.0 / 60 : min(raw, 1.0 / 20)178 if raw <= 0.5 { trackFrame(raw, now: currentTime) }179 updateShake(dt)180 tick(dt: dt)181 }182183 // MARK: Performance governor184185 private func trackFrame(_ frame: Double, now: TimeInterval) {186 window.append(frame)187 if logPerf, allFrames.count < 200_000 { allFrames.append(frame) }188 if window.count >= 90 {189 let average = window.reduce(0, +) / Double(window.count)190 window.removeAll(keepingCapacity: true)191 if services.settings.effects == .auto {192 if average > 1.0 / 48 { effectScale = max(0.35, effectScale - 0.2) }193 else if average < 1.0 / 57 { effectScale = min(qualityCap, effectScale + 0.05) }194 } else {195 effectScale = qualityCap196 }197 }198 if logPerf, now - lastPerfWrite > 4 {199 lastPerfWrite = now200 writePerfReport()201 }202 }203204 func writePerfReport() {205 guard logPerf, !allFrames.isEmpty else { return }206 let report = PerfReport.make(name: perfName, frameTimes: allFrames, effectScale: Double(effectScale))207 let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("perf-\(perfName).json")208 let encoder = JSONEncoder()209 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]210 try? encoder.encode(report).write(to: url, options: .atomic)211 }212213 override func willMove(from view: SKView) {214 super.willMove(from: view)215 writePerfReport()216 }217218 // MARK: Effects219220 /// Shakes the `world` node. `strength` 0…1 is scaled by the player's shake setting; ignored under Reduce Motion.221 func shake(_ strength: CGFloat) {222 let scaled = strength * CGFloat(services.settings.shakeIntensity)223 guard scaled > 0.01, !reduceMotion else { return }224 shakeStrength = max(shakeStrength, min(scaled, 1))225 shakeTime = 0.32226 }227228 private func updateShake(_ dt: TimeInterval) {229 guard shakeTime > 0 else { return }230 shakeTime -= dt231 if shakeTime <= 0 {232 shakeStrength = 0233 world.position = worldRestPosition234 return235 }236 let falloff = CGFloat(shakeTime / 0.32)237 let amplitude = 14 * shakeStrength * falloff238 world.position = CGPoint(x: worldRestPosition.x + .random(in: -amplitude...amplitude),239 y: worldRestPosition.y + .random(in: -amplitude...amplitude))240 }241242 /// Where `world` sits when not shaking. Subclasses that scroll the world should update this instead of `world.position`.243 var worldRestPosition = CGPoint.zero { didSet { if shakeTime <= 0 { world.position = worldRestPosition } } }244245 /// One-shot particle burst. Counts scale with `effectScale`; concurrent emitters are capped.246 func burst(at point: CGPoint, in parent: SKNode? = nil, color: UIColor, count: Int = 18, speed: CGFloat = 160,247 lifetime: CGFloat = 0.6, scale: CGFloat = 0.5, gravity: CGFloat = -300, texture: SKTexture? = nil, spread: CGFloat = .pi * 2,248 angle: CGFloat = .pi / 2, additive: Bool = true) {249 let scaledCount = Int((CGFloat(count) * effectScale).rounded())250 guard scaledCount > 0, liveEmitters < 14 else { return }251 let emitter = SKEmitterNode()252 emitter.particleTexture = texture ?? TextureFactory.softDot253 emitter.numParticlesToEmit = scaledCount254 emitter.particleBirthRate = CGFloat(scaledCount) / 0.04255 emitter.particleLifetime = lifetime256 emitter.particleLifetimeRange = lifetime * 0.5257 emitter.particleSpeed = speed258 emitter.particleSpeedRange = speed * 0.7259 emitter.emissionAngle = angle260 emitter.emissionAngleRange = spread261 emitter.yAcceleration = gravity262 emitter.particleScale = scale263 emitter.particleScaleRange = scale * 0.5264 emitter.particleScaleSpeed = -scale / max(lifetime, 0.1) * 0.7265 emitter.particleAlphaSpeed = -1 / max(lifetime, 0.1)266 emitter.particleRotationRange = .pi267 emitter.particleRotationSpeed = 3268 emitter.particleColor = color269 emitter.particleColorBlendFactor = 1270 emitter.particleBlendMode = additive ? .add : .alpha271 emitter.position = point272 emitter.zPosition = 500273 (parent ?? world).addChild(emitter)274 liveEmitters += 1275 emitter.run(.sequence([.wait(forDuration: Double(lifetime) * 1.6 + 0.1), .removeFromParent()])) { [weak self] in276 self?.liveEmitters -= 1277 }278 }279280 /// Small text that floats up and fades ("+120", "Close call!").281 func floatText(_ text: String, at point: CGPoint, in parent: SKNode? = nil, color: UIColor = .white, size: CGFloat = 18) {282 let label = SKLabelNode.orixLabel(text, size: size, color: color)283 label.position = point284 label.zPosition = 600285 label.verticalAlignmentMode = .center286 (parent ?? world).addChild(label)287 let rise: CGFloat = reduceMotion ? 0 : 38288 label.setScale(reduceMotion ? 1 : 0.6)289 label.run(.sequence([290 .group([.moveBy(x: 0, y: rise, duration: 0.7), .scale(to: 1, duration: 0.14), .sequence([.wait(forDuration: 0.42), .fadeOut(withDuration: 0.28)])]),291 .removeFromParent(),292 ]))293 }294}295