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