Skip to content
Source
Sign inSign up
samwillis/jerry
Open History to see the last commit

ExplorerScene.swift

582 lines33.5 KB

1import AppKit
2import SpriteKit
3import ExpeditionCore
4​
5@MainActor
6final class ExplorerScene: SKScene {
7 private let explorer = ExplorerRig()
8 private let debug = SKNode()
9 private let rope = SKShapeNode()
10 private let shotRope = SKShapeNode()
11 private let hook = SKShapeNode()
12 private let props = ExpeditionProps()
13 private let marcherLayer = MarcherLayer()
14 private var marcherCoach: MarcherCoach?
15 private var marcherPlanning = false
16 private var marcherGeneration = 0
17 private let controlMarker = SKShapeNode()
18 private let pointerExtension = SKShapeNode()
19 private let aimGuide = SKShapeNode()
20 private var grappleAiming = false
21 private var aimPoint: CGPoint?
22 private var aimDirection = CGPoint.zero
23 private(set) var idleExplorationEnabled = true
24 private var runWhenExploring = false
25 private var fasterRopeWork = false
26 private var startedOnWindow = false
27 private var startedRopeDemo = false
28 private var startedActivityDemo = false
29 private var tracedState = ""
30 private var frameSamples: [Double] = []
31 private var lastInputFrame: CGRect?
32 private var lastInputState = ""
33 var playbackRate: Double = 1
34 private let debugLabel = SKLabelNode(fontNamed: "Menlo")
35 private let terrainGuides = SKNode()
36 private var terrain: TerrainSnapshot?
37 private var geometryUnavailable = true
38 private var usableFrame = CGRect.zero
39 private var expeditionPaused = false
40 private var interaction: ExplorerInteraction?
41 private var rawTerrain: TerrainSnapshot?
42 private(set) var agentMode = false
43 var agentReading = false
44 var agentCelebrating = false
45 private var photoHiddenNodes: [(SKNode, Bool)] = []
46 private let photoMoment = SKLabelNode()
47 var agentPhotoBounds: CGRect { explorer.calculateAccumulatedFrame().insetBy(dx: -12, dy: -20) }
48 var agentClimbSample: (height: Double, climbing: Bool)? {
49 guard let interaction else { return nil }
50 return (interaction.position.y, [.climbing, .ropeClimbing, .traversingEdge].contains(interaction.state))
51 }
52 func setPhotoMoment(_ active: Bool) {
53 guard agentCelebrating != active else { return }
54 agentCelebrating = active
55 if active {
56 photoHiddenNodes = [debug, terrainGuides, controlMarker, pointerExtension, aimGuide].map { ($0, $0.isHidden) }
57 photoHiddenNodes.forEach { $0.0.isHidden = true }
58 } else {
59 photoHiddenNodes.forEach { $0.0.isHidden = $0.1 }; photoHiddenNodes = []
60 }
61 if photoMoment.parent == nil { _ = NotebookTheme.journalFont(18); photoMoment.fontName = "Caveat-Regular"; addChild(photoMoment); photoMoment.fontSize = 18; photoMoment.fontColor = NotebookTheme.ink; photoMoment.zPosition = 999 }
62 photoMoment.text = "One for the journal!"; photoMoment.isHidden = !active
63 }
64 var agentTarget: CGPoint?
65 #if DEBUG
66 var agentDiagnostic: String { "\(interaction?.position ?? .zero) \(interaction?.state.rawValue ?? "none") ceiling=\(interaction?.agentCeilingHanging ?? false)" }
67 #endif
68 var agentHandPoint: CGPoint? {
69 guard let interaction else { return nil }
70 if let target = agentTarget, agentAtTarget { return target }
71 return .init(x: interaction.controlClickPoint.x, y: interaction.controlClickPoint.y)
72 }
73 var agentAtTarget: Bool {
74 guard let interaction, let target = agentTarget else { return false }
75 let localX = (target.x - interaction.position.x) * interaction.facing
76 let localY = target.y - interaction.position.y + interaction.controlPointerDrop
77 let shoulderY = explorer.shoulderHeight
78 return localX >= -8 && localX <= 36 && hypot(localX - 10, localY - shoulderY) < 29
79 && (interaction.ropeSession.map { hypot($0.body.velocity.x, $0.body.velocity.y) < 24 } ?? true)
80 }
81 func setAgentMode(_ enabled: Bool) {
82 guard agentMode != enabled else { return }
83 agentMode = enabled; agentTarget = nil; agentReading = false; setPhotoMoment(false)
84 // Marchers mode pauses during an AI task; its artwork returns when the level resumes.
85 if enabled { marcherLayer.isHidden = true }
86 interaction?.setKeyboardControl(enabled)
87 interaction?.setIdleExploration(false)
88 if enabled { interaction?.updateBounds(.init(minimum: .init(x: 24, y: 0), maximum: .init(x: size.width - 24, y: size.height - 76))) }
89 else { interaction?.updateBounds(.init(minimum: .init(x: usableFrame.minX + 24, y: usableFrame.minY + 2), maximum: .init(x: usableFrame.maxX - 24, y: usableFrame.maxY - 76))) }
90 let snapshot = rawTerrain; terrain = nil; updateTerrain(snapshot)
91 }
92 private var previousUpdateTime: TimeInterval?
93 private var lastTerrainReadTime: TimeInterval?
94 var onFrame: (() -> Void)?
95 var onPlacementChanged: ((CGRect, String) -> Void)?
96​
97 override init(size: CGSize) {
98 super.init(size: size)
99 backgroundColor = .clear
100 scaleMode = .resizeFill
101 addChild(marcherLayer)
102 addChild(rope); addChild(shotRope)
103 shotRope.strokeColor = .init(calibratedRed: 0.72, green: 0.57, blue: 0.32, alpha: 1); shotRope.lineWidth = 1.2; shotRope.zPosition = 1
104 rope.strokeColor = .init(calibratedRed: 0.72, green: 0.57, blue: 0.32, alpha: 1)
105 rope.lineWidth = 1.2
106 rope.zPosition = 1 // Over the jacket, beneath the foreground rope grips.
107 addChild(explorer)
108 let hookPath = CGMutablePath()
109 hookPath.move(to: .init(x: -5, y: 0)); hookPath.addLine(to: .init(x: 4, y: 0))
110 hookPath.move(to: .init(x: 0, y: 0)); hookPath.addQuadCurve(to: .init(x: 1, y: 5), control: .init(x: 7, y: 5))
111 hookPath.move(to: .init(x: 0, y: 0)); hookPath.addQuadCurve(to: .init(x: 1, y: -5), control: .init(x: 7, y: -5))
112 hook.path = hookPath; hook.strokeColor = NSColor(calibratedWhite: 0.13, alpha: 1); hook.lineWidth = 2.4; hook.isHidden = true
113 let metal = SKShapeNode(path: hookPath)
114 metal.strokeColor = NSColor(calibratedWhite: 0.78, alpha: 1); metal.lineWidth = 1.2
115 hook.addChild(metal)
116 addChild(hook)
117 addChild(props)
118 let crosshair = CGMutablePath()
119 crosshair.addEllipse(in: .init(x: -5, y: -5, width: 10, height: 10))
120 crosshair.move(to: .init(x: -9, y: 0)); crosshair.addLine(to: .init(x: 9, y: 0))
121 crosshair.move(to: .init(x: 0, y: -9)); crosshair.addLine(to: .init(x: 0, y: 9))
122 controlMarker.path = crosshair
123 controlMarker.strokeColor = .systemPink; controlMarker.lineWidth = 1.5
124 controlMarker.zPosition = 100; controlMarker.isHidden = true
125 addChild(controlMarker)
126 pointerExtension.strokeColor = .systemPink; pointerExtension.lineWidth = 1.2; pointerExtension.zPosition = 99; addChild(pointerExtension)
127 aimGuide.lineWidth = 1; aimGuide.zPosition = 90; aimGuide.isHidden = true
128 addChild(aimGuide)
129 addChild(debug)
130 debug.isHidden = true
131 }
132​
133 required init?(coder: NSCoder) { fatalError("Use init(size:)") }
134​
135 func layout(in usableFrame: CGRect) {
136 self.usableFrame = usableFrame
137 terrain = nil
138 let safeOrigins = ExplorerInteraction.Bounds(
139 minimum: .init(x: agentMode ? 24 : usableFrame.minX + 24, y: agentMode ? 0 : usableFrame.minY + 2),
140 maximum: .init(x: agentMode ? size.width - 24 : usableFrame.maxX - 24, y: agentMode ? size.height - 76 : usableFrame.maxY - 76)
141 )
142 if interaction == nil {
143 interaction = ExplorerInteraction(position: .init(x: usableFrame.midX, y: usableFrame.minY + 12), bounds: safeOrigins)
144 } else {
145 interaction?.updateBounds(safeOrigins)
146 }
147 interaction?.autonomous = true
148 interaction?.runsMission = idleExplorationEnabled && marcherCoach == nil
149 interaction?.setIdleExploration(idleExplorationEnabled && marcherCoach == nil)
150 interaction?.setRunWhenExploring(runWhenExploring)
151 interaction?.setFasterRopeWork(fasterRopeWork)
152 applyPlacement()
153 }
154​
155 func resetExpedition() {
156 interaction = nil
157 previousUpdateTime = nil
158 let previousTerrain = terrain
159 layout(in: usableFrame)
160 if let previousTerrain { updateTerrain(previousTerrain) }
161 }
162​
163 var keyboardClickPoint: CGPoint? {
164 guard let interaction, interaction.keyboardControlEnabled else { return nil }
165 let point = interaction.controlClickPoint
166 return .init(x: point.x, y: point.y)
167 }
168 func setKeyboardControl(_ enabled: Bool) {
169 interaction?.setKeyboardControl(enabled)
170 if !enabled { setGrappleAiming(false) }
171 applyPlacement()
172 }
173 func setIdleExploration(_ enabled: Bool) {
174 idleExplorationEnabled = enabled
175 // Marchers mode keeps Jerry's attention on the line; wandering resumes when it ends.
176 if marcherCoach == nil { interaction?.setIdleExploration(enabled) }
177 applyPlacement()
178 }
179​
180 var marchersActive: Bool { marcherCoach != nil }
181 var marchersStatus: String? { marcherCoach?.status }
182 func setMarchersMode(_ enabled: Bool) {
183 guard enabled != (marcherCoach != nil) else { return }
184 marcherGeneration += 1
185 marcherPlanning = false
186 if enabled {
187 let snapshot = (agentMode ? nil : terrain) ?? TerrainSnapshot(windows: [], viewport: WorldRect(x: usableFrame.minX, y: usableFrame.minY + 2, width: usableFrame.width, height: max(0, usableFrame.height - 2)))
188 var coach = MarcherCoach(terrain: snapshot)
189 coach.plansInline = false
190 marcherCoach = coach
191 interaction?.setIdleExploration(false)
192 } else {
193 marcherCoach = nil
194 if !agentMode { interaction?.setIdleExploration(idleExplorationEnabled) }
195 }
196 marcherLayer.update(coach: marcherCoach)
197 applyPlacement()
198 }
199 /// Where Jerry signals skills from: his raised hand.
200 private var marcherHand: WorldPoint? {
201 guard let interaction else { return nil }
202 return WorldPoint(x: interaction.position.x + interaction.facing * 8, y: interaction.position.y + 52)
203 }
204 private func advanceMarchers(by elapsed: Double) {
205 guard marcherCoach != nil, !agentMode, elapsed > 0 else { return }
206 marcherCoach!.advance(by: elapsed, hand: marcherHand)
207 if let terrain, interaction != nil, interaction?.keyboardControlEnabled == false {
208 marcherCoach!.steer(&interaction!, terrain: terrain, by: elapsed)
209 }
210 if !marcherPlanning, let request = marcherCoach!.nextPlanningRequest() {
211 // The look-ahead search runs off the main thread; the level keeps moving meanwhile.
212 marcherPlanning = true
213 let generation = marcherGeneration
214 Task.detached(priority: .utility) { [weak self] in
215 let plan = request.solve()
216 await self?.receiveMarcherPlan(plan, for: request, generation: generation)
217 }
218 }
219 marcherLayer.update(coach: marcherCoach)
220 }
221 private func receiveMarcherPlan(_ plan: MarcherPlan?, for request: MarcherPlanningRequest, generation: Int) {
222 guard generation == marcherGeneration else { return }
223 marcherPlanning = false
224 marcherCoach?.receive(plan, for: request)
225 }
226 func setGrappleAiming(_ enabled: Bool) {
227 grappleAiming = enabled; aimGuide.isHidden = !enabled
228 aimDirection = .zero
229 if enabled, let interaction {
230 let suggestion = interaction.suggestedGrappleAim()
231 aimPoint = suggestion.map { .init(x: $0.x, y: $0.y) }
232 ?? .init(x: interaction.position.x, y: min(usableFrame.maxY, interaction.position.y + 240))
233 }
234 applyPlacement()
235 }
236 func setAimDirection(_ x: Double, _ y: Double) { aimDirection = .init(x: x, y: y) }
237 private func updateGrappleAim(by elapsed: Double = 0) {
238 guard grappleAiming, let point = aimPoint else { return }
239 let distance = max(1, hypot(aimDirection.x, aimDirection.y))
240 let step = min(0.1, max(0, elapsed)) * 320 / distance
241 aimPoint = .init(x: min(usableFrame.maxX - 24, max(usableFrame.minX + 24, point.x + aimDirection.x * step)),
242 y: min(usableFrame.maxY, max(usableFrame.minY, point.y + aimDirection.y * step)))
243 }
244 @discardableResult func fireAimedGrapple() -> Bool {
245 updateGrappleAim()
246 guard let aimPoint else { return false }
247 let result = interaction?.fireGrapple(toward: .init(x: aimPoint.x, y: aimPoint.y)) ?? false
248 applyPlacement(); return result
249 }
250 func setRunWhenExploring(_ enabled: Bool) { runWhenExploring = enabled; interaction?.setRunWhenExploring(enabled) }
251 func setFasterRopeWork(_ enabled: Bool) { fasterRopeWork = enabled; interaction?.setFasterRopeWork(enabled) }
252 func setControlPointerLowered(_ held: Bool) { interaction?.setControlPointerLowered(held) }
253 func setControlCrouch(_ held: Bool) { interaction?.setControlCrouch(held) }
254 func setControlFastPace(_ fast: Bool) { interaction?.setControlFastPace(fast) }
255 func setControlDirection(_ x: Double, _ y: Double) { interaction?.setControlDirection(horizontal: x, vertical: y) }
256 func controlJump() { interaction?.controlJump(); applyPlacement() }
257 func controlGrapple() { interaction?.controlGrapple(); applyPlacement() }
258​
259 var attachedWindowID: UInt32? { interaction?.attachedWindowID }
260 var activityStatus: String { interaction?.activityStatus ?? "Preparing terrain…" }
261 var availableActivities: Set<ExplorerActivity> { interaction?.availableActivities ?? [] }
262 func requestActivity(_ activity: ExplorerActivity) {
263 interaction?.requestActivity(activity)
264 applyPlacement()
265 }
266​
267 func setExpeditionPaused(_ paused: Bool) {
268 expeditionPaused = paused
269 previousUpdateTime = nil
270 applyPlacement()
271 }
272​
273 func beginDrag(at point: CGPoint) {
274 if let position = interaction?.position {
275 explorer.grabPoint = CGPoint(x: point.x - position.x, y: point.y - position.y)
276 }
277 interaction?.beginDrag(at: .init(x: point.x, y: point.y), time: ProcessInfo.processInfo.systemUptime)
278 applyPlacement()
279 }
280​
281 func drag(to point: CGPoint) {
282 interaction?.drag(to: .init(x: point.x, y: point.y), time: ProcessInfo.processInfo.systemUptime)
283 applyPlacement()
284 }
285​
286 func endDrag() {
287 interaction?.endDrag(on: terrain)
288 applyPlacement()
289 if interaction?.state == .settling, interaction?.attachment != nil { explorer.land(strength: 0.5) }
290 }
291​
292 func updateTerrain(_ snapshot: TerrainSnapshot?, geometrySampleElapsed: TimeInterval? = nil) {
293 let now = ProcessInfo.processInfo.systemUptime
294 let sampleElapsed = geometrySampleElapsed ?? (lastTerrainReadTime.map { max(1.0 / 120, now - $0) } ?? 0.1)
295 lastTerrainReadTime = now
296 let unavailable = snapshot == nil
297 // If window-server metadata fails, retain only the guaranteed rescue boundaries.
298 rawTerrain = snapshot
299 var next = snapshot ?? TerrainSnapshot(windows: [], viewport: WorldRect(x: usableFrame.minX, y: usableFrame.minY + 2, width: usableFrame.width, height: max(0, usableFrame.height - 2)))
300 if agentMode {
301 // The physical display rim supplies a fallback line when no window is
302 // above a menu/Dock control. It uses the same grappling/rope solver.
303 let rim = DesktopWindow(id: UInt32.max, frame: .init(x: 0, y: size.height - 1, width: size.width, height: 1))
304 next = TerrainSnapshot(windows: [rim] + next.windows, viewport: .init(x: 0, y: 0, width: size.width, height: size.height), features: next.features)
305 }
306 guard terrain != next || geometryUnavailable != unavailable else { return }
307 terrain = next
308 geometryUnavailable = unavailable
309 #if DEBUG
310 if !startedOnWindow, ProcessInfo.processInfo.arguments.contains("--start-on-window") {
311 let initialSurfaces = ProcessInfo.processInfo.arguments.contains("--start-low") ? next.surfaces.sorted { $0.start.y < $1.start.y } : next.surfaces
312 for surface in initialSurfaces where surface.id.edge == .top {
313 if let (_, point) = TerrainSupport.attach(at: .init(x: (surface.start.x + surface.end.x) / 2, y: surface.start.y), in: next) {
314 let safe = ExplorerInteraction.Bounds(minimum: .init(x: usableFrame.minX + 24, y: usableFrame.minY + 2), maximum: .init(x: usableFrame.maxX - 24, y: usableFrame.maxY - 76))
315 interaction = ExplorerInteraction(position: point, bounds: safe)
316 interaction?.autonomous = true
317 interaction?.runsMission = !ProcessInfo.processInfo.arguments.contains("--movement-only") && !ProcessInfo.processInfo.arguments.contains("--rope-demo")
318 startedOnWindow = true
319 break
320 }
321 }
322 }
323 #endif
324 interaction?.updateTerrain(next, sampleElapsed: sampleElapsed)
325 if !agentMode { marcherCoach?.updateTerrain(next) }
326 #if DEBUG
327 if !startedActivityDemo, let argument = ProcessInfo.processInfo.arguments.first(where: { $0.hasPrefix("--activity=") }),
328 let activity = ExplorerActivity(rawValue: String(argument.dropFirst("--activity=".count))) {
329 startedActivityDemo = interaction?.requestActivity(activity) == true
330 }
331 if !startedRopeDemo, ProcessInfo.processInfo.arguments.contains("--rope-demo"), let anchor = interaction?.attachment {
332 let steps = NavigationGraph(terrain: next).route(from: anchor, seed: 0, allowParachute: false)
333 if steps.contains(where: { $0.kind == .abseiling }) { startedRopeDemo = interaction?.follow(steps) == true }
334 }
335 #endif
336 rebuildTerrainGuides()
337 applyPlacement()
338 }
339​
340 private func rebuildTerrainGuides() {
341 terrainGuides.removeAllChildren()
342 guard let terrain else { return }
343 for surface in terrain.surfaces {
344 let path = CGMutablePath()
345 path.move(to: CGPoint(x: surface.start.x, y: surface.start.y))
346 path.addLine(to: CGPoint(x: surface.end.x, y: surface.end.y))
347 let line = SKShapeNode(path: path)
348 line.strokeColor = surface.id.edge.isInternal ? (surface.id.edge == .ledge ? .systemGreen : (surface.id.edge == .horizontalCrack ? .systemOrange : .systemPurple)) : surface.id.owner == .screen ? .systemTeal : (surface.id.edge == .top ? .systemGreen : .systemPink)
349 line.lineWidth = 2
350 terrainGuides.addChild(line)
351 }
352 }
353​
354 override func update(_ currentTime: TimeInterval) {
355 onFrame?()
356 let rawElapsed = previousUpdateTime.map { max(currentTime - $0, 0) } ?? 0
357 let elapsed = min(rawElapsed, 0.25)
358 previousUpdateTime = currentTime
359 guard !expeditionPaused else { return }
360 if agentMode, let target = agentTarget { interaction?.steerAgent(towardHand: .init(x: target.x, y: target.y)) }
361 updateGrappleAim(by: elapsed)
362 let previousState = interaction?.state
363 let previousLandingCount = interaction?.landingCount
364 interaction?.advance(by: elapsed * playbackRate)
365 advanceMarchers(by: elapsed * playbackRate)
366 #if DEBUG
367 if ProcessInfo.processInfo.arguments.contains("--freeze-grapple"), interaction?.state == .grappling, (interaction?.ropeSession?.age ?? 0) > 0.15 { setExpeditionPaused(true) }
368 if ProcessInfo.processInfo.arguments.contains("--freeze-swing"), interaction?.state == .swinging, interaction?.ropeSession?.isTakingUp == false, (interaction?.ropeSession?.age ?? 0) > 0.5 { setExpeditionPaused(true) }
369 if ProcessInfo.processInfo.arguments.contains("--freeze-rope"), let interaction,
370 interaction.state == .abseiling, let anchor = interaction.ropeAnchor,
371 interaction.position.y < anchor.y - 90 {
372 setExpeditionPaused(true)
373 }
374 #endif
375 if let interaction, interaction.landingCount != previousLandingCount {
376 explorer.land(strength: min(1, max(0.4, interaction.lastLandingSpeed / JumpAnimation.launchSpeed)))
377 } else if previousState == .recovering, interaction?.state == .settling { explorer.land() }
378 // Mission beats also change while the explorer is standing still.
379 applyPlacement()
380 explorer.render(delta: elapsed * playbackRate)
381 #if DEBUG
382 if rawElapsed > 0, ProcessInfo.processInfo.arguments.contains("--performance-report") {
383 frameSamples.append(rawElapsed)
384 if frameSamples.count == 300 {
385 let sorted = frameSamples.sorted()
386 func nodes(_ node: SKNode) -> Int { 1 + node.children.reduce(0) { $0 + nodes($1) } }
387 print(String(format: "PERFORMANCE %.1f fps · p95 %.1f ms · max %.1f ms · %d nodes", 300 / frameSamples.reduce(0, +), sorted[284] * 1000, sorted.last! * 1000, nodes(self)))
388 frameSamples.removeAll(keepingCapacity: true)
389 fflush(stdout)
390 }
391 }
392 let trace = "\(interaction?.state.rawValue ?? "none") · \(interaction?.mission.stage.rawValue ?? "none") · \(interaction?.mission.completedExpeditions ?? 0)"
393 if tracedState != trace, ProcessInfo.processInfo.arguments.contains("--trace-movement") {
394 tracedState = trace
395 print("EXPEDITION \(trace) @ \(interaction?.position ?? .zero)")
396 fflush(stdout)
397 }
398 #endif
399 }
400​
401 private func applyPlacement() {
402 guard let interaction else { return }
403 controlMarker.isHidden = agentCelebrating || !interaction.keyboardControlEnabled
404 if let point = keyboardClickPoint { controlMarker.position = point }
405 explorer.position = CGPoint(x: interaction.position.x, y: interaction.position.y)
406 var motion: ExplorerMotion
407 switch interaction.state {
408 case .transferringHold: motion = .climbing
409 case .dropping: motion = .launching
410 case .held: motion = .held
411 case .recovering: motion = .parachuting
412 case .preparingJump, .jumping: motion = .jumping
413 case .walking: motion = .walking
414 case .running: motion = .running
415 case .climbing: motion = .climbing
416 case .abseiling: motion = .abseiling
417 case .grappling: motion = .grappling
418 case .swinging: motion = .ropeSwinging
419 case .ropeClimbing: motion = .ropeClimbing
420 case .traversingEdge: motion = interaction.edgeMotion ?? .idle
421 default: motion = .idle
422 }
423 let stage = interaction.mission.stage
424 let stationary = interaction.state == .idle || interaction.state == .settling
425 if stationary, let edge = interaction.attachment?.edge, edge == .left || edge == .right { motion = .climbing }
426 if stationary, [.spotting, .investigating, .revealing, .updatingMap].contains(stage) { motion = .investigating }
427 let target = interaction.mission.target.flatMap { anchor in terrain.flatMap { TerrainSupport.resolve(anchor, in: $0) } }
428 var facing = interaction.facing
429 if stationary, let target { facing = target.x >= interaction.position.x ? 1 : -1 }
430 if stationary, !agentMode, let signal = marcherCoach?.signals.last { facing = signal.to.x >= interaction.position.x ? 1 : -1 }
431 explorer.xScale = facing
432 explorer.setShadowOcclusion(windows: terrain?.windows.map {
433 .init(x: $0.frame.minX, y: $0.frame.minY, width: $0.frame.width, height: $0.frame.height)
434 } ?? [], from: self)
435 explorer.tuning = interaction.walkingTuning
436 explorer.synchronizedTime = interaction.edgeMotion.map { interaction.edgeProgress * EdgeTraversal.duration($0) }
437 ?? (motion == .walking ? interaction.walkingTime : (motion == .climbing && !stationary ? interaction.climbingTime - floor(interaction.climbingTime / 2) * 2 : nil))
438 if motion == .running { explorer.synchronizedTime = interaction.runningTime }
439 explorer.usingBinoculars = !agentCelebrating && interaction.state != .held && (agentReading || (stationary && stage == .spotting))
440 explorer.crouchAmount = interaction.canCrouch ? interaction.crouchBlend : 0
441 explorer.jumpPose = interaction.dropPose ?? interaction.keyboardJumpPose
442 explorer.crackPose = interaction.internalClimbingPose
443 explorer.handTargets = nil
444 explorer.footTargets = nil
445 explorer.ropePose = nil
446 explorer.usesHarnessPivot = false
447 let aimedTarget = grappleAiming ? aimPoint.map { interaction.aimedGrappleTarget(toward: .init(x: $0.x, y: $0.y)) } ?? nil : nil
448 let gunTarget = interaction.grappleTarget ?? (grappleAiming ? (aimedTarget ?? aimPoint.map { WorldPoint(x: $0.x, y: $0.y) }) : nil)
449 if grappleAiming, let aimPoint {
450 let target = aimedTarget ?? .init(x: aimPoint.x, y: aimPoint.y)
451 let path = CGMutablePath()
452 path.move(to: .init(x: interaction.position.x, y: interaction.position.y + 46))
453 path.addLine(to: .init(x: target.x, y: target.y))
454 path.addEllipse(in: .init(x: target.x - 7, y: target.y - 7, width: 14, height: 14))
455 aimGuide.path = path; aimGuide.strokeColor = aimedTarget == nil ? .systemOrange : .systemGreen
456 }
457 explorer.grappleAim = gunTarget.map { .init(x: ($0.x - interaction.position.x) * facing, y: $0.y - interaction.position.y) }
458 if let session = interaction.ropeSession, let guide = interaction.ropeGuide, session.mode != .supported && session.mode != .firing {
459 let path = guide.taut(toward: session.body.position)
460 let dx = (path.sideTangent.x - session.body.position.x) * facing, dy = path.sideTangent.y - session.body.position.y
461 let length = max(0.001, hypot(dx, dy))
462 explorer.ropePose = RopeAnimation.pose(mode: session.mode, direction: .init(x: dx / length, y: dy / length), velocity: .init(x: session.body.velocity.x * facing, y: session.body.velocity.y), pullTime: session.pullTime)
463 explorer.usesHarnessPivot = true
464 }
465 if motion == .climbing && !interaction.internalClimbing {
466 let contacts = ClimbingContacts(heightAlongWall: interaction.heightAlongWall)
467 explorer.handTargets = (contacts.leftHand, contacts.rightHand)
468 explorer.footTargets = (contacts.leftFoot, contacts.rightFoot)
469 }
470 if stationary, stage == .updatingMap {
471 explorer.handTargets = (.init(x: -1, y: 43), .init(x: 16, y: 44))
472 }
473 let ropeGripHeight = interaction.ropeAnchor.map { min(61, max(0, $0.y - 16 - interaction.position.y)) } ?? 61
474 if motion == .abseiling && interaction.ropeSession == nil {
475 explorer.handTargets = (.init(x: 0, y: ropeGripHeight), .init(x: 8, y: ropeGripHeight + 1))
476 }
477 if interaction.agentCeilingHanging {
478 var pose = CrackAnimation.pose(horizontal: true, time: interaction.climbingTime, offset: interaction.position.x * facing)
479 pose.hips.y += 12; pose.leftHand.y += 18; pose.rightHand.y += 18
480 explorer.crackPose = pose; explorer.ropePose = nil; explorer.handTargets = nil; explorer.footTargets = nil
481 }
482 if agentMode, !agentCelebrating, let target = agentTarget, agentAtTarget {
483 let hand = WorldPoint(x: (target.x - interaction.position.x) * facing, y: target.y - interaction.position.y + interaction.controlPointerDrop)
484 explorer.handTargets = (.init(x: -8, y: interaction.agentCeilingHanging ? 76 : (interaction.ropeSession == nil ? 44 : 61)), hand)
485 }
486 if agentCelebrating, stationary, interaction.ropeSession == nil, !interaction.agentCeilingHanging,
487 interaction.attachment?.edge != .left, interaction.attachment?.edge != .right {
488 explorer.handTargets = (.init(x: -18, y: 75), .init(x: 20, y: 78))
489 }
490 if let signal = marcherCoach?.signals.last, signal.age < 0.45, !agentMode, interaction.ropeSession == nil, motion != .climbing {
491 // Point at the marcher who is getting the skill.
492 let shoulder = explorer.shoulderHeight
493 let dx = (signal.to.x - interaction.position.x) * facing, dy = signal.to.y - interaction.position.y - shoulder
494 let length = max(1, hypot(dx, dy))
495 explorer.handTargets = (.init(x: -6, y: 40), .init(x: 4 + dx / length * 24, y: shoulder + dy / length * 24))
496 }
497 photoMoment.position = .init(x: interaction.position.x, y: interaction.position.y + 112)
498 if interaction.hasPendingGrapple { explorer.handTargets = (.init(x: -4, y: 61), .init(x: 20, y: 46)) }
499 pointerExtension.isHidden = agentCelebrating || interaction.controlPointerDrop < 1
500 if !pointerExtension.isHidden {
501 let tip = agentMode && agentAtTarget ? agentTarget! : CGPoint(x: interaction.controlClickPoint.x, y: interaction.controlClickPoint.y)
502 controlMarker.position = tip
503 let extensionPath = CGMutablePath(); extensionPath.move(to: .init(x: tip.x, y: tip.y + interaction.controlPointerDrop)); extensionPath.addLine(to: tip)
504 pointerExtension.path = extensionPath
505 }
506 props.update(mission: interaction.mission, explorer: interaction.position, target: target, facing: facing, viewport: usableFrame, held: interaction.state == .held)
507 explorer.select(motion)
508 explorer.render(delta: 0)
509 rope.isHidden = interaction.ropeAnchor == nil && interaction.hookPosition == nil
510 hook.isHidden = interaction.ropeSession == nil
511 let path = CGMutablePath()
512 let flyingPath = CGMutablePath()
513 if let flying = interaction.hookPosition, let target = interaction.grappleTarget {
514 let muzzle = explorer.grappleMuzzle(in: self)
515 flyingPath.move(to: muzzle)
516 flyingPath.addQuadCurve(to: .init(x: flying.x, y: flying.y), control: .init(x: (muzzle.x + flying.x) / 2, y: (muzzle.y + flying.y) / 2 - 8))
517 hook.position = .init(x: flying.x, y: flying.y)
518 hook.zRotation = atan2(target.y - flying.y, target.x - flying.x)
519 }
520 if let support = interaction.ropeGuide {
521 let grip = interaction.ropeSession?.body.position ?? WorldPoint(x: interaction.position.x, y: interaction.position.y + ropeGripHeight)
522 let guide = interaction.edgeMotion == .lowering ? support : support.taut(toward: grip)
523 func cg(_ point: WorldPoint) -> CGPoint { .init(x: point.x, y: point.y) }
524 path.addEllipse(in: .init(x: guide.anchor.x - 2, y: guide.anchor.y - 1, width: 4, height: 2))
525 path.move(to: cg(guide.anchor)); path.addLine(to: cg(guide.topTangent))
526 path.addCurve(to: cg(guide.sideTangent), control1: cg(guide.control1), control2: cg(guide.control2))
527 if interaction.edgeMotion == .lowering {
528 path.addLine(to: .init(x: guide.sideTangent.x, y: guide.sideTangent.y - 50))
529 } else {
530 let slack = max(0, (interaction.ropeSession?.body.length ?? guide.length(to: grip)) - guide.length(to: grip))
531 if slack > 1 {
532 let dx = grip.x - guide.sideTangent.x, dy = grip.y - guide.sideTangent.y
533 // Preserve the corner's outgoing tangent even when the free line bows.
534 path.addCurve(to: cg(grip), control1: .init(x: guide.sideTangent.x + dx / 3, y: guide.sideTangent.y + dy / 3), control2: .init(x: guide.sideTangent.x + dx * 2 / 3, y: guide.sideTangent.y + dy * 2 / 3 - min(60, slack)))
535 } else { path.addLine(to: cg(grip)) }
536 path.addEllipse(in: .init(x: grip.x - 1.5, y: grip.y - 1.5, width: 3, height: 3))
537 path.move(to: cg(grip)); path.addLine(to: .init(x: grip.x, y: max(agentMode ? 0 : usableFrame.minY, interaction.position.y - 16)))
538 }
539 if interaction.hookPosition == nil { hook.position = cg(guide.anchor); hook.zRotation = -.pi / 2 }
540 }
541 rope.path = path; shotRope.path = flyingPath; shotRope.isHidden = interaction.hookPosition == nil
542​
543 let hitFrame = CGRect(x: explorer.position.x - 24, y: explorer.position.y - 1, width: 48, height: 76)
544 if hitFrame != lastInputFrame || interaction.state.rawValue != lastInputState {
545 onPlacementChanged?(hitFrame, interaction.state.rawValue)
546 lastInputFrame = hitFrame
547 lastInputState = interaction.state.rawValue
548 }
549 if !debug.isHidden { rebuildDebug() }
550 }
551​
552 func setDebugVisible(_ visible: Bool) {
553 debug.isHidden = !visible
554 rebuildDebug()
555 }
556​
557 private func rebuildDebug() {
558 debug.removeAllChildren()
559 debug.addChild(terrainGuides)
560 let outline = SKShapeNode(rect: usableFrame.insetBy(dx: 3, dy: 3))
561 outline.strokeColor = .systemTeal
562 outline.lineWidth = 1
563 debug.addChild(outline)
564 let bounds = SKShapeNode(rect: CGRect(x: explorer.position.x - 24, y: explorer.position.y - 1, width: 48, height: 76))
565 bounds.strokeColor = .systemYellow
566 bounds.lineWidth = 1
567 debug.addChild(bounds)
568 let count = terrain?.windows.filter(\.canClimb).count ?? 0
569 let status = geometryUnavailable ? "GEOMETRY UNAVAILABLE" : "\(count) WINDOWS · \(terrain?.surfaces.count ?? 0) EDGES"
570 debugLabel.text = "PROTOTYPE · \(expeditionPaused ? "PAUSED" : "RUNNING") · \(interaction?.state.rawValue.uppercased() ?? "IDLE") · \(status)"
571 debugLabel.fontSize = 11
572 debugLabel.fontColor = .white
573 debugLabel.horizontalAlignmentMode = .left
574 debugLabel.verticalAlignmentMode = .center
575 debugLabel.position = CGPoint(x: usableFrame.minX + 20, y: usableFrame.maxY - 24)
576 let backing = SKShapeNode(rect: CGRect(x: usableFrame.minX + 12, y: usableFrame.maxY - 40, width: min(650, usableFrame.width - 24), height: 32), cornerRadius: 6)
577 backing.fillColor = NSColor.black.withAlphaComponent(0.8)
578 backing.strokeColor = .clear
579 debug.addChild(backing)
580 debug.addChild(debugLabel)
581 }