SPB Git

Repository Public License

TrafficSim.swift 31.5 KB 753 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/TrafficMayhem/TrafficSim.swift10// Description      : Traffic Mayhem — deterministic traffic simulation: vehicle11//                    state machine, fair spawning, collision detection and12//                    prediction, scoring, difficulty and the autoplay bot.13// Module           : Games14// Repository       : https://git.spboucher.ai/orix-arcade15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//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 VehicleKind: Int, CaseIterable, Sendable, Codable {94    case car, sport, bus, truck, ambulance9596    var name: String {97        switch self {98        case .car: "Car"99        case .sport: "Sports car"100        case .bus: "Bus"101        case .truck: "Truck"102        case .ambulance: "Ambulance"103        }104    }105106    var length: Double { [26, 26, 46, 54, 32][rawValue] }107    var width: Double { [14, 14, 16, 16, 15][rawValue] }108    /// Speed held while crossing, in logical units per second.109    var cruise: Double { [150, 215, 105, 90, 175][rawValue] }110    var accel: Double { [260, 430, 130, 100, 300][rawValue] }111    var approach: Double { [120, 135, 100, 95, 130][rawValue] }112    var value: Int { [10, 15, 20, 25, 30][rawValue] }113    var patienceFactor: Double { [1, 1, 1.1, 1.2, 0.5][rawValue] }114    var radius: Double { width / 2 }115    /// Centres of the circles that approximate the body, along its length.116    var circleOffsets: [Double] {117        switch self {118        case .car, .sport: [-6, 0, 6]119        case .bus: [-15, -5, 5, 15]120        case .truck: [-19, -9.5, 0, 9.5, 19]121        case .ambulance: [-8.5, 0, 8.5]122        }123    }124}125126nonisolated enum VehicleState: Sendable, Equatable {127    /// Driving up to the stop line or to the back of the queue.128    case approaching129    /// Stopped at the stop line, losing patience.130    case waiting131    /// Sent through (or free-flowing): never stops until it has left the junction.132    case crossing133    /// Past the junction; scored and driving away.134    case cleared135}136137nonisolated struct TrafficVehicle: Sendable, Equatable, Identifiable {138    let id: Int139    let kind: VehicleKind140    let lane: Int141    let path: Int142    let exitLane: Int143    let autonomous: Bool144    let tint: Int145    var s: Double146    var v: Double147    var cruise: Double148    var accel: Double149    var state: VehicleState150    var patience: Double151    var patienceMax: Double152    var warned = false153    var closeCall = false154    var minGap = Double.infinity155156    var half: Double { kind.length / 2 }157    var patienceFraction: Double { patienceMax.isFinite && patienceMax > 0 ? max(0, patience / patienceMax) : 1 }158}159160nonisolated enum TrafficEvent: Sendable, Equatable {161    case spawned(id: Int)162    case launched(id: Int)163    case cleared(id: Int, points: Int, closeCall: Bool, streak: Int, at: Vec2)164    case crashed(a: Int, b: Int, at: Vec2, forgiven: Bool)165    case impatient(id: Int)166    case stormedOff(id: Int, at: Vec2)167    case heartLost(remaining: Int)168    case stage(Int)169    case tutorial(step: Int?)170    case over(TrafficSim.OverReason)171}172173nonisolated enum TrafficScoring {174    static let closeCallGap = 4.0175176    /// ×1 for a streak of 0–4, ×2 for 5–9 … capped at ×5.177    static func multiplier(streak: Int) -> Int { min(5, 1 + max(0, streak) / 5) }178179    /// Points for one safely cleared vehicle. `streakBefore` is the streak before this vehicle counted.180    static func points(kind: VehicleKind, streakBefore: Int, closeCall: Bool) -> Int {181        let base = kind.value * multiplier(streak: streakBefore)182        return closeCall ? base + base / 2 : base183    }184185    static func survivalBonus(mode: TrafficSim.Mode, elapsed: Double) -> Int { mode == .endless ? Int(elapsed) * 2 : 0 }186}187188nonisolated struct TrafficDifficulty: Sendable, Equatable {189    var stage: Int190    var spawnInterval: Double191    var patience: Double192    var turns: Bool193    /// Spawn weight per `VehicleKind.rawValue`.194    var weights: [Double]195    var throughInterval: Double196197    /// Vehicles cleared at which stages 1…6 begin.198    static let stageThresholds = [0, 5, 12, 21, 32, 45]199    static let maxStage = 6200201    static func make(layout: TrafficLayout, mode: TrafficSim.Mode, cleared: Int, elapsed: Double) -> TrafficDifficulty {202        var stage = 1203        var ramp = 0.0204        var interval: Double205        switch mode {206        case .endless:207            for (index, threshold) in stageThresholds.enumerated() where cleared >= threshold { stage = index + 1 }208            ramp = min(max(Double(cleared - 45) / 120, 0), 1)209            interval = [2.6, 2.3, 2.0, 1.8, 1.6, 1.45][stage - 1] - 0.45 * ramp210            // Rush-hour waves from the last stage on: six busy seconds out of every twenty-eight.211            if stage >= maxStage, elapsed.truncatingRemainder(dividingBy: 28) < 6 { interval *= 0.62 }212        case .rush:213            stage = 4214            ramp = min(max(elapsed / rushRamp, 0), 1)215            interval = 1.3 - 0.35 * ramp216        }217        let i = stage - 1218        var weights = [1.0, 0, 0, 0, 0]219        if stage >= 3 { weights[VehicleKind.bus.rawValue] = 0.16 }220        if stage >= 4 { weights[VehicleKind.sport.rawValue] = 0.2 }221        if stage >= 5 { weights[VehicleKind.ambulance.rawValue] = 0.09 }222        if stage >= 6 { weights[VehicleKind.truck.rawValue] = 0.12 }223        return TrafficDifficulty(224            stage: stage,225            spawnInterval: interval * layout.spawnScale,226            patience: [15.0, 14, 13, 12, 11, 10][i] - 2.5 * (mode == .endless ? ramp : 0) + layout.patienceBonus,227            turns: stage >= 2,228            weights: weights,229            throughInterval: [2.7, 2.4, 2.1, 1.9, 1.7, 1.5][i] - 0.2 * ramp)230    }231232    static let rushRamp = 60.0233234    /// Headline and hint shown when a stage begins (stage 2…6).235    static func announcement(layout: TrafficLayout, stage: Int) -> (title: String, detail: String)? {236        switch stage {237        case 2: layout.id == 1 ? ("Turn pocket", "Main Street drivers now turn into the side road.") : ("Turn signals", "Watch the blinkers — some drivers turn.")238        case 3: ("Buses", "Long and slow. Give them room.")239        case 4: ("Sports cars", "Quick off the line.")240        case 5: ("Ambulance", "Never keep a siren waiting.")241        case 6: ("Rush hour", "Trucks join and traffic thickens.")242        default: nil243        }244    }245}246247nonisolated struct TrafficPrediction: Sendable, Equatable {248    var safe: Bool249    var collisionAt: Vec2?250    /// Closest approach to another moving vehicle while crossing.251    var minGap: Double252    /// Seconds until the vehicle has cleared the junction (or until the predicted crash).253    var time: Double254}255256nonisolated struct TrafficSim: Sendable {257    enum Mode: String, Codable, Sendable, CaseIterable { case endless, rush }258    enum OverReason: Sendable, Equatable { case hearts, timeUp }259260    /// Fixed simulation step: results never depend on the display frame rate.261    static let h = 1.0 / 60262    static let rushDuration = 60.0263    static let startHearts = 3264    static let followGap = 5.0265    /// A vehicle can be sent once its front is within this distance of the stop line.266    static let launchReach = 230.0267268    let layout: TrafficLayout269    let mode: Mode270    private(set) var vehicles: [TrafficVehicle] = []271    private(set) var elapsed = 0.0272    private(set) var score = 0273    private(set) var cleared = 0274    private(set) var streak = 0275    private(set) var bestStreak = 0276    private(set) var closeCalls = 0277    private(set) var hearts = TrafficSim.startHearts278    private(set) var heartsLost = 0279    private(set) var stage = 1280    private(set) var over: OverReason?281    /// 0…2 while the first-run tutorial is active, `nil` otherwise.282    private(set) var tutorialStep: Int?283284    private var rng: SeededRNG285    private var nextID = 1286    private var accumulator = 0.0287    private var spawnTimer = 1.0288    private var throughTimers: [Int: Double] = [:]289    private var tutorialSpawned = false290    private var tutorialTimer = 0.0291    private var predicting = false292293    init(layout: TrafficLayout, mode: Mode, seed: UInt64, tutorial: Bool = false) {294        self.layout = layout295        self.mode = mode296        rng = SeededRNG(seed: seed)297        tutorialStep = tutorial && layout.id == 0 && mode == .endless ? 0 : nil298        stage = difficulty.stage299        for lane in layout.lanes where lane.autonomous { throughTimers[lane.id] = 1.5 + Double(lane.id) * 0.4 }300    }301302    // MARK: Read-only state303304    var difficulty: TrafficDifficulty { TrafficDifficulty.make(layout: layout, mode: mode, cleared: cleared, elapsed: elapsed) }305    var multiplier: Int { TrafficScoring.multiplier(streak: streak) }306    var timeLeft: Double { mode == .rush ? max(0, Self.rushDuration - elapsed) : .infinity }307    var survivalBonus: Int { TrafficScoring.survivalBonus(mode: mode, elapsed: elapsed) }308    var finalScore: Int { score + survivalBonus }309    var isOver: Bool { over != nil }310311    struct Snapshot: Equatable, Sendable {312        var vehicles: [TrafficVehicle]313        var elapsed: Double314        var score: Int315        var hearts: Int316        var streak: Int317        var rng: SeededRNG318    }319320    var snapshot: Snapshot { Snapshot(vehicles: vehicles, elapsed: elapsed, score: score, hearts: hearts, streak: streak, rng: rng) }321322    func vehicle(_ id: Int) -> TrafficVehicle? { vehicles.first { $0.id == id } }323    func path(of vehicle: TrafficVehicle) -> TrafficPath { layout.paths[vehicle.path] }324    func position(of vehicle: TrafficVehicle) -> Vec2 { layout.paths[vehicle.path].point(at: vehicle.s) }325    func heading(of vehicle: TrafficVehicle) -> Double { layout.paths[vehicle.path].heading(at: vehicle.s) }326327    /// The vehicle at the head of a controlled lane's queue, if any.328    func leader(ofLane lane: Int) -> TrafficVehicle? {329        vehicles.first { $0.lane == lane && !$0.autonomous && ($0.state == .approaching || $0.state == .waiting) }330    }331332    func canLaunch(_ id: Int) -> Bool {333        guard over == nil, let v = vehicle(id), !v.autonomous, v.state == .approaching || v.state == .waiting,334              leader(ofLane: v.lane)?.id == id else { return false }335        return layout.paths[v.path].stopS - (v.s + v.half) <= Self.launchReach336    }337338    /// Lane leaders that can be sent right now.339    var launchable: [TrafficVehicle] {340        layout.controlledLanes.compactMap { leader(ofLane: $0.id) }.filter { canLaunch($0.id) }341    }342343    // MARK: Player input344345    /// Sends the vehicle through the junction. Returns false when it is not a launchable lane leader.346    @discardableResult347    mutating func launch(_ id: Int) -> Bool {348        var events: [TrafficEvent] = []349        return launch(id, events: &events)350    }351352    @discardableResult353    mutating func launch(_ id: Int, events: inout [TrafficEvent]) -> Bool {354        guard canLaunch(id), let index = vehicles.firstIndex(where: { $0.id == id }) else { return false }355        vehicles[index].state = .crossing356        events.append(.launched(id: id))357        return true358    }359360    // MARK: Stepping361362    /// Advances by `dt` seconds of wall time in fixed steps and returns what happened.363    mutating func advance(_ dt: Double) -> [TrafficEvent] {364        var events: [TrafficEvent] = []365        guard over == nil, dt > 0 else { return events }366        accumulator += dt367        while accumulator >= Self.h, over == nil {368            accumulator -= Self.h369            step(&events)370        }371        return events372    }373374    private mutating func step(_ events: inout [TrafficEvent]) {375        let h = Self.h376        elapsed += h377        if !predicting { direct(&events) }378        guard over == nil else { return }379380        var remove: Set<Int> = []381        for i in vehicles.indices { move(i, &events, &remove) }382383        // Collisions and near misses between vehicles that are inside a junction.384        let moving = vehicles.indices.filter { vehicles[$0].state == .crossing && !remove.contains(vehicles[$0].id) }385        if moving.count > 1 {386            let poses = moving.map { i -> (Vec2, Vec2) in387                let p = layout.paths[vehicles[i].path]388                let heading = p.heading(at: vehicles[i].s)389                return (p.point(at: vehicles[i].s), Vec2(x: cos(heading), y: sin(heading)))390            }391            for a in 0..<moving.count {392                for b in (a + 1)..<moving.count {393                    let ia = moving[a], ib = moving[b]394                    let va = vehicles[ia], vb = vehicles[ib]395                    if va.lane == vb.lane || (va.autonomous && vb.autonomous) { continue }396                    if remove.contains(va.id) || remove.contains(vb.id) { continue }397                    let reach = va.half + vb.half + 14398                    guard poses[a].0.distance(to: poses[b].0) < reach else { continue }399                    let (gap, point) = Self.bodyGap(va.kind, poses[a], vb.kind, poses[b])400                    if gap < -0.08 * (va.kind.radius + vb.kind.radius) {401                        remove.insert(va.id)402                        remove.insert(vb.id)403                        crash(va, vb, at: point, &events)404                    } else {405                        vehicles[ia].minGap = min(vehicles[ia].minGap, gap)406                        vehicles[ib].minGap = min(vehicles[ib].minGap, gap)407                        if gap < TrafficScoring.closeCallGap {408                            // One bonus per near miss: it goes to the player-sent vehicle that entered last.409                            let target = va.autonomous ? ib : vb.autonomous ? ia : (va.id > vb.id ? ia : ib)410                            vehicles[target].closeCall = true411                        }412                    }413                }414            }415        }416        if !remove.isEmpty { vehicles.removeAll { remove.contains($0.id) } }417    }418419    /// Smallest distance between the two bodies (negative when overlapping) and the midpoint of the closest circles.420    static func bodyGap(_ ka: VehicleKind, _ a: (Vec2, Vec2), _ kb: VehicleKind, _ b: (Vec2, Vec2)) -> (Double, Vec2) {421        var best = Double.infinity422        var point = a.0423        let radii = ka.radius + kb.radius424        for oa in ka.circleOffsets {425            let pa = a.0 + a.1 * oa426            for ob in kb.circleOffsets {427                let pb = b.0 + b.1 * ob428                let gap = pa.distance(to: pb) - radii429                if gap < best {430                    best = gap431                    point = (pa + pb) * 0.5432                }433            }434        }435        return (best, point)436    }437438    private func predecessor(of index: Int) -> Int? {439        var j = index - 1440        while j >= 0 {441            if vehicles[j].lane == vehicles[index].lane { return j }442            j -= 1443        }444        return nil445    }446447    private mutating func move(_ i: Int, _ events: inout [TrafficEvent], _ remove: inout Set<Int>) {448        let h = Self.h449        var v = vehicles[i]450        let path = layout.paths[v.path]451        let pred = predecessor(of: i).map { vehicles[$0] }452453        switch v.state {454        case .approaching, .waiting:455            let stopCenter = path.stopS - v.half456            var target = stopCenter457            if let pred, pred.state != .cleared { target = min(target, pred.s - pred.half - v.half - Self.followGap) }458            let distance = target - v.s459            if distance <= 0.3 {460                v.v = 0461                if distance > 0 { v.s = target }462                v.state = abs(v.s - stopCenter) < 0.6 ? .waiting : .approaching463            } else {464                let desired = min(v.kind.approach, (2 * 300 * distance).squareRoot())465                v.v = min(v.v + 420 * h, desired)466                v.s = min(target, v.s + v.v * h)467                v.state = .approaching468            }469            if v.state == .waiting, !predicting, v.patienceMax.isFinite {470                v.patience -= h471                if !v.warned, v.patience <= v.patienceMax * 0.3 {472                    v.warned = true473                    events.append(.impatient(id: v.id))474                }475                if v.patience <= 0 {476                    remove.insert(v.id)477                    events.append(.stormedOff(id: v.id, at: path.point(at: v.s)))478                    loseHeart(&events)479                }480            }481482        case .crossing, .cleared:483            let isCleared = v.state == .cleared484            let desired = isCleared ? max(v.cruise, 170) : v.cruise485            let accel = isCleared ? max(v.accel, 260) : v.accel486            var cap = Double.infinity487            if !isCleared, let pred, pred.state == .crossing {488                let gap = (pred.s - pred.half) - (v.s + v.half) - Self.followGap489                cap = min(cap, max(0, pred.v + gap * 4))490            }491            // Fall in behind vehicles already driving away on the same exit lane.492            let myD = v.s - path.exitS493            for other in vehicles where other.state == .cleared && other.exitLane == v.exitLane && other.id != v.id {494                let otherD = other.s - layout.paths[other.path].exitS495                guard otherD > myD else { continue }496                let gap = (otherD - other.half) - (myD + v.half) - Self.followGap497                cap = min(cap, max(0, other.v + gap * 4))498            }499            v.v = min(v.v + accel * h, desired, cap)500            v.s += v.v * h501            if !isCleared, v.s - v.half >= path.exitS {502                v.state = .cleared503                if !v.autonomous, !predicting {504                    let points = TrafficScoring.points(kind: v.kind, streakBefore: streak, closeCall: v.closeCall)505                    score += points506                    cleared += 1507                    streak += 1508                    bestStreak = max(bestStreak, streak)509                    if v.closeCall { closeCalls += 1 }510                    events.append(.cleared(id: v.id, points: points, closeCall: v.closeCall, streak: streak, at: path.point(at: v.s)))511                }512            }513            if v.s >= path.length - 1 { remove.insert(v.id) }514        }515        vehicles[i] = v516    }517518    private mutating func crash(_ a: TrafficVehicle, _ b: TrafficVehicle, at point: Vec2, _ events: inout [TrafficEvent]) {519        let forgiven = (tutorialStep ?? 2) < 2520        events.append(.crashed(a: a.id, b: b.id, at: point, forgiven: forgiven))521        guard !predicting else { return }522        if forgiven {523            tutorialSpawned = false524        } else {525            loseHeart(&events)526        }527    }528529    private mutating func loseHeart(_ events: inout [TrafficEvent]) {530        guard !predicting, over == nil else { return }531        hearts -= 1532        heartsLost += 1533        streak = 0534        events.append(.heartLost(remaining: hearts))535        if hearts <= 0 {536            over = .hearts537            events.append(.over(.hearts))538        }539    }540541    // MARK: Director — stages, tutorial and spawning542543    private mutating func direct(_ events: inout [TrafficEvent]) {544        let h = Self.h545        if mode == .rush, elapsed >= Self.rushDuration {546            over = .timeUp547            events.append(.over(.timeUp))548            return549        }550        let d = difficulty551        if d.stage > stage {552            stage = d.stage553            events.append(.stage(stage))554        }555556        if let step = tutorialStep {557            switch step {558            case 0:559                if !tutorialSpawned, elapsed > 0.5 {560                    spawn(kind: .car, path: layout.lanes[0].paths[0], patience: .infinity, &events)561                    tutorialSpawned = true562                }563                if cleared >= 1 {564                    tutorialStep = 1565                    tutorialSpawned = false566                    events.append(.tutorial(step: 1))567                }568            case 1:569                let busy = vehicles.contains { $0.state != .cleared }570                if !tutorialSpawned, !busy {571                    spawn(kind: .car, path: layout.lanes[3].paths[0], patience: .infinity, &events)572                    spawn(kind: .car, path: layout.lanes[0].paths[0], patience: .infinity, &events)573                    tutorialSpawned = true574                } else if tutorialSpawned, !busy, cleared < 3 {575                    tutorialSpawned = false // one got through, the pair is gone: send a fresh pair576                }577                if cleared >= 3 {578                    tutorialStep = 2579                    tutorialTimer = 9580                    spawnTimer = 0.6581                    events.append(.tutorial(step: 2))582                }583            default:584                tutorialTimer -= h585                if tutorialTimer <= 0 {586                    tutorialStep = nil587                    events.append(.tutorial(step: nil))588                }589            }590            if step < 2 { return }591        }592593        spawnTimer -= h594        if spawnTimer <= 0 {595            spawnControlled(d, &events)596            spawnTimer = d.spawnInterval * rng.double(in: 0.75...1.25)597        }598        if layout.throughPeriod > 0 { spawnThrough(d, &events) }599    }600601    private func queueLength(_ lane: Int) -> Int {602        vehicles.reduce(0) { $0 + ($1.lane == lane && ($1.state == .approaching || $1.state == .waiting) ? 1 : 0) }603    }604605    /// True when a new vehicle of `kind` fits at the start of the lane without touching the last one.606    private func entryClear(lane: Int, kind: VehicleKind) -> Bool {607        guard let last = vehicles.last(where: { $0.lane == lane }) else { return true }608        return last.s - last.half > kind.length / 2 + Self.followGap + 6609    }610611    private mutating func pickKind(_ d: TrafficDifficulty) -> VehicleKind {612        var weights = d.weights613        if vehicles.contains(where: { $0.kind == .ambulance }) { weights[VehicleKind.ambulance.rawValue] = 0 }614        var roll = rng.unit() * weights.reduce(0, +)615        for kind in VehicleKind.allCases {616            roll -= weights[kind.rawValue]617            if roll < 0 { return kind }618        }619        return .car620    }621622    private mutating func spawnControlled(_ d: TrafficDifficulty, _ events: inout [TrafficEvent]) {623        let kind = pickKind(d)624        var options: [(lane: TrafficLane, weight: Double)] = []625        for lane in layout.lanes where !lane.autonomous && lane.openStage <= d.stage {626            let count = queueLength(lane.id)627            guard count < lane.maxQueue, entryClear(lane: lane.id, kind: kind) else { continue }628            options.append((lane, Double(lane.maxQueue - count)))629        }630        guard !options.isEmpty else { return } // every queue is full: nothing spawns, nothing is forced on the player631        var roll = rng.unit() * options.reduce(0) { $0 + $1.weight }632        var chosen = options[0].lane633        for option in options {634            roll -= option.weight635            if roll < 0 { chosen = option.lane; break }636        }637        var pathID = chosen.paths[0]638        if chosen.paths.count > 1, d.turns, rng.chance(0.5) {639            pathID = chosen.paths[rng.int(in: 1...(chosen.paths.count - 1))]640        }641        // Ambulances are impatient, but never so much that a player cannot react.642        let patience = kind == .ambulance ? max(5, d.patience * kind.patienceFactor) : d.patience * kind.patienceFactor643        spawn(kind: kind, path: pathID, patience: patience, &events)644    }645646    private mutating func spawnThrough(_ d: TrafficDifficulty, _ events: inout [TrafficEvent]) {647        let h = Self.h648        let phase = elapsed.truncatingRemainder(dividingBy: layout.throughPeriod)649        let flowing = phase < layout.throughPeriod - layout.throughGap650        // Through traffic yields to a siren: nothing new enters while an ambulance is still waiting to cross.651        let siren = vehicles.contains { $0.kind == .ambulance && !$0.autonomous && ($0.state == .approaching || $0.state == .waiting) }652        for lane in layout.lanes where lane.autonomous {653            var timer = (throughTimers[lane.id] ?? 0) - h654            if timer <= 0 {655                var kind = VehicleKind.car656                if d.stage >= 3, rng.chance(0.14) { kind = .bus }657                if d.stage >= 4, rng.chance(0.16) { kind = .sport }658                if d.stage >= 6, rng.chance(0.1) { kind = .truck }659                if flowing, !siren, entryClear(lane: lane.id, kind: kind), throughIsSafe(kind: kind, path: lane.paths[0]) {660                    spawn(kind: kind, path: lane.paths[0], patience: .infinity, autonomous: true, &events)661                    timer = d.throughInterval * rng.double(in: 0.7...1.5)662                } else {663                    timer = 0.25664                }665            }666            throughTimers[lane.id] = timer667        }668    }669670    /// Speed of free-flowing traffic: uniform so the guaranteed gap arrives intact (sports cars run a little faster).671    static func throughSpeed(_ kind: VehicleKind) -> Double { kind == .sport ? 185 : 150 }672673    @discardableResult674    private mutating func spawn(kind: VehicleKind, path pathID: Int, patience: Double, autonomous: Bool = false, _ events: inout [TrafficEvent]) -> Int {675        let path = layout.paths[pathID]676        let speed = autonomous ? Self.throughSpeed(kind) : kind.approach677        let vehicle = TrafficVehicle(id: nextID, kind: kind, lane: path.lane, path: pathID, exitLane: path.exitLane, autonomous: autonomous,678                                     tint: rng.int(in: 0...6), s: 0, v: speed, cruise: autonomous ? speed : kind.cruise, accel: kind.accel,679                                     state: autonomous ? .crossing : .approaching, patience: patience, patienceMax: patience)680        nextID += 1681        vehicles.append(vehicle)682        events.append(.spawned(id: vehicle.id))683        return vehicle.id684    }685686    // MARK: Prediction687688    /// Simulates sending `id` now, against every vehicle already moving, and reports whether it gets through.689    func predict(launching id: Int) -> TrafficPrediction {690        var copy = self691        copy.predicting = true692        guard copy.launch(id) else { return TrafficPrediction(safe: false, collisionAt: nil, minGap: 0, time: 0) }693        return copy.runPrediction(for: id)694    }695696    private mutating func runPrediction(for id: Int) -> TrafficPrediction {697        var events: [TrafficEvent] = []698        var time = 0.0699        while time < 16 {700            events.removeAll(keepingCapacity: true)701            step(&events)702            time += Self.h703            for event in events {704                if case .crashed(let a, let b, let point, _) = event, a == id || b == id {705                    return TrafficPrediction(safe: false, collisionAt: point, minGap: 0, time: time)706                }707            }708            guard let v = vehicle(id) else { break }709            if v.state == .cleared { return TrafficPrediction(safe: true, collisionAt: nil, minGap: v.minGap, time: time) }710        }711        return TrafficPrediction(safe: true, collisionAt: nil, minGap: .infinity, time: time)712    }713714    /// Fair-spawn check: a through vehicle only enters if it cannot hit anything already inside the junction.715    private func throughIsSafe(kind: VehicleKind, path: Int) -> Bool {716        var copy = self717        copy.predicting = true718        var sink: [TrafficEvent] = []719        let id = copy.spawn(kind: kind, path: path, patience: .infinity, autonomous: true, &sink)720        return copy.runPrediction(for: id).safe721    }722}723724/// Plays safely by asking the collision predictor before every launch. Used for autoplay, soak tests and as proof of fairness.725nonisolated enum TrafficBot {726    /// Vehicles to send right now, most urgent first.727    static func choose(_ sim: TrafficSim, margin: Double = 5, reach: Double = 80) -> [Int] {728        var work = sim729        var chosen: [Int] = []730        let candidates = work.launchable.sorted {731            let a = $0.kind == .ambulance ? -1 : $0.patienceFraction * $0.patienceMax732            let b = $1.kind == .ambulance ? -1 : $1.patienceFraction * $1.patienceMax733            return a < b734        }735        var blockedUrgent = false736        for candidate in candidates {737            let path = work.path(of: candidate)738            guard path.stopS - (candidate.s + candidate.half) <= reach else { continue }739            let urgent = candidate.patienceMax.isFinite && candidate.patience < 5740            // While an urgent driver is stuck, keep the junction free for them instead of feeding more traffic in.741            if blockedUrgent, !urgent { continue }742            let prediction = work.predict(launching: candidate.id)743            if prediction.safe, prediction.minGap >= margin {744                work.launch(candidate.id)745                chosen.append(candidate.id)746            } else if urgent {747                blockedUrgent = true748            }749        }750        return chosen751    }752}753
Files main
Menu

Theme