import FoldFormat import Folding import Foundation import Notation import Observation import simd /// One model being folded: the current step, its fold parameter `t` in 0...1, and the model /// view's orientation. Nothing here changes `t` on its own; the step changes only when the user /// completes it or opens another. Completing the last step finishes the model and locks it. @MainActor @Observable final class FoldSession { let model: FoldFile private(set) var step: FoldStep private(set) var interpolator: FoldInterpolator private(set) var diagram: Diagram private var order: LayerOrder var t = 0.0 { didSet { if t != oldValue { pose() } } } /// Whether the last step has been completed and no drag, adjustment or other step has since /// left `t` below 1. private(set) var isFinished = false /// Whether the finished model ignores drags and adjustment. Orbit and zoom still work. private(set) var isLocked = false /// How many times the model has been finished. private(set) var finishCount = 0 /// The unit vector from the camera's target toward its eye. var eyeDirection: SIMD3 { didSet { if eyeDirection != oldValue { sortClusters(); cachedMapping = nil } } } /// A unit vector perpendicular to `eyeDirection`. var up: SIMD3 { didSet { cachedMapping = nil } } /// The camera's vertical field of view in radians, which a pinch changes. var fieldOfView = FoldSession.defaultFieldOfView { didSet { cachedMapping = nil } } /// The paper view's size in points. var viewportSize = SIMD2(1.0, 1.0) { didSet { cachedMapping = nil } } private var aspect: Double { viewportSize.x / viewportSize.y } /// The render mesh at `t`. private(set) var meshPositions: [SIMD3] = [] /// The FOLD faces' clusters at `t`, back to front along the camera's view direction. private(set) var clusters: [CoplanarCluster] = [] /// The FOLD vertices at `t`. private var positions: [SIMD3] = [] /// The centre of the bounding box of the frame the step starts from. private var target: SIMD3 @ObservationIgnored private var cachedMapping: FoldParameterMapping? /// Half the flat sheet's diagonal, the radius the camera keeps in view. private let radius: Double private static let defaultFieldOfView = Double.pi / 6 /// The fields of view a pinch can reach, from about 2.5 times the default magnification to half of it. static let fieldOfViewRange = 0.21...0.98 /// `step` counts from 1. The camera starts at the step's authored viewpoint. init(model: FoldFile, step n: Int) throws { self.model = model let step = try readStep(n, in: model) self.step = step interpolator = FoldInterpolator(file: model, step: step) order = try LayerOrder.active(for: step, in: model) diagram = buildDiagram(file: model, step: step) let (low, high) = bounds(model.frames[0].verticesCoords) radius = length(high - low) / 2 target = startCentre(model, step) let eye = normalize(step.viewpoint.eye) eyeDirection = eye up = normalize(step.viewpoint.up - dot(step.viewpoint.up, eye) * eye) pose() } /// Moves to the next step at t = 0, seen from its viewpoint, once the current step is complete. /// Completing the last step finishes the model at t = 1 and locks it. func completeStep() { guard t == 1 else { return } if step.index + 1 < model.frames.count { open(step: step.index + 1) } else if !isFinished { isFinished = true isLocked = true finishCount += 1 } } /// Locks or unlocks a finished model. Unlocked, its last step can be dragged back to unfold it. func toggleLock() { guard isFinished else { return } isLocked.toggle() guard isLocked else { return } if let grab { t = grab.start } cancelDrag() } /// Leaves the finished state if `t` is below 1. private func settle() { if t < 1 { isFinished = false; isLocked = false } } /// Opens step `n`, counting from 1, at t = 0, seen from its viewpoint at the default zoom. A /// drag in progress no longer moves `t` or completes a step, and a finished model is no longer /// finished. Opening the current step leaves it as it is. A step that cannot be read leaves the /// session as it is and stops a Debug build. func open(step n: Int) { guard n != step.index else { return } cancelDrag() let next: FoldStep, nextOrder: LayerOrder do { next = try readStep(n, in: model) nextOrder = try LayerOrder.active(for: next, in: model) } catch { assertionFailure("step \(n) of \(model.fileTitle ?? "?"): \(error)") return } step = next interpolator = FoldInterpolator(file: model, step: next) order = nextOrder diagram = buildDiagram(file: model, step: next) target = startCentre(model, next) let eye = normalize(next.viewpoint.eye) eyeDirection = eye up = normalize(next.viewpoint.up - dot(next.viewpoint.up, eye) * eye) fieldOfView = Self.defaultFieldOfView cachedMapping = nil if t == 0 { pose() } else { t = 0 } settle() } /// What maps a one-finger drag's translation to `t`. private enum DragMapping { /// `position` is where the latest movement left the drag on the path. case fold(FoldParameterMapping, grabbedAt: SIMD2, position: FoldParameterMapping.Position) case reorient(ReorientMapping) } /// The current one-finger drag's mapping and `t` when it began, while one is in progress. @ObservationIgnored private var grab: (mapping: DragMapping, start: Double)? /// Two-finger gestures in progress. @ObservationIgnored private var orbits = 0 /// Whether a two-finger gesture began during the current drag. The drag then leaves `t` as it /// was when the drag began until the finger lifts, and does not complete the step. @ObservationIgnored private(set) var isDragSuspended = false /// Called when a one-finger drag on a fold step begins: the moving faces then follow the /// finger along `mapping`'s path. func beginFoldDrag() { guard !isLocked else { return } let mapping = self.mapping beginDrag(.fold(mapping, grabbedAt: mapping.point(at: t), position: mapping.position(at: t))) } /// Called when a one-finger drag on a turn-over or rotate step begins: its horizontal /// component then turns the model across its on-screen width, measured on the frame the step /// starts from, which a vertical turn-over would otherwise shrink to an edge midway. func beginReorientDrag() { guard !isLocked else { return } beginDrag(.reorient(ReorientMapping(positions: interpolator.positions(at: 0), camera: camera, viewportSize: viewportSize))) } private func beginDrag(_ mapping: DragMapping) { grab = (mapping, t) isDragSuspended = orbits > 0 } /// Moves `t` to where the drag's `translation` maps it, unless the drag is suspended. func drag(translation: SIMD2) { guard let grab, !isDragSuspended else { return } switch grab.mapping { case let .fold(mapping, grabbedAt, position): let next = mapping.position(grabbedAt: grabbedAt, translation: translation, current: mapping.isDegenerate ? mapping.position(at: grab.start) : position) self.grab?.mapping = .fold(mapping, grabbedAt: grabbedAt, position: next) t = next.t case let .reorient(mapping): t = mapping.parameter(translation: translation.x, current: grab.start) } } /// Called when the drag's finger lifts at `translation`: moves `t` there as `drag(translation:)` /// does, then completes the step unless the drag was suspended. func endDrag(translation: SIMD2) { drag(translation: translation) if !isDragSuspended { completeStep() } cancelDrag() } /// Called when the drag ends by any means, including cancellation. A finished model left below /// t = 1 is no longer finished. func cancelDrag() { grab = nil isDragSuspended = false settle() } /// Called when a two-finger gesture begins. A drag in progress is suspended and its effect on /// `t` undone. func beginOrbit() { orbits += 1 if let grab { t = grab.start isDragSuspended = true } } func endOrbit() { orbits = max(orbits - 1, 0) } /// Turns the view of the model by `angles` radians, as `Camera.orbited(by:)` does. func orbit(by angles: SIMD2) { let turned = camera.orbited(by: angles) eyeDirection = normalize(turned.eye - turned.target) up = turned.up } /// Magnifies the view of the model by `scale`, within `fieldOfViewRange`. func zoom(by scale: Double) { fieldOfView = camera.zoomed(by: scale, within: Self.fieldOfViewRange).fieldOfView } /// Moves `t` to the next multiple of 0.1 above it (`direction` 1) or below it (−1), within /// 0...1, for VoiceOver's adjustable action. Reaching 1 completes the step, as lifting the /// finger there does. func adjust(_ direction: Int) { guard !isLocked else { return } let tenths = direction > 0 ? (t * 10 + 1e-9).rounded(.down) + 1 : (t * 10 - 1e-9).rounded(.up) - 1 t = min(max(tenths, 0), 10) / 10 settle() if t == 1 { completeStep() } } /// Maps drags on the paper view to `t` for the current step, camera and view size. var mapping: FoldParameterMapping { if let cachedMapping { return cachedMapping } let mapping = FoldParameterMapping(file: model, step: step, camera: camera, viewportSize: viewportSize) cachedMapping = mapping return mapping } /// Looks at the step's start frame from `eyeDirection`, far enough that a sphere of `radius` /// about it fits the paper view at `aspect` at the default field of view. var camera: Camera { let half = Self.defaultFieldOfView / 2 let horizontalHalf = atan(tan(half) * aspect) let distance = radius / sin(min(half, horizontalHalf)) return Camera(eye: target + distance * eyeDirection, target: target, up: up, fieldOfView: fieldOfView) } private func pose() { positions = interpolator.positions(at: t) meshPositions = interpolator.meshPositions(at: t) sortClusters() } /// Membership and order come from one `LayerOrder.clusters` call, so both are recomputed when /// either `t` or the view direction changes. private func sortClusters() { clusters = order.clusters(positions: positions, faces: model.facesVertices, viewDirection: -eyeDirection) } } /// The centre of the bounding box of the frame `step` starts from. private func startCentre(_ model: FoldFile, _ step: FoldStep) -> SIMD3 { let (low, high) = bounds(model.frames[step.index - 1].verticesCoords) return (low + high) / 2 } private func bounds(_ points: [SIMD3]) -> (SIMD3, SIMD3) { points.dropFirst().reduce((points[0], points[0])) { (simd_min($0.0, $1), simd_max($0.1, $1)) } }