Commit 10af936c92
Verified · cmc
Layout: unified · split
App/Sources/FoldGesture.swift added +42
| @@ -0,0 +1,42 @@ | ||
| 1 | import FoldFormat | |
| 2 | import Folding | |
| 3 | import SwiftUI | |
| 4 | ||
| 5 | extension View { | |
| 6 | /// Lets a one-finger drag anywhere on the view drive the session's fold step: the moving faces | |
| 7 | /// follow the finger along their screen path, and the step completes when the finger lifts at | |
| 8 | /// t = 1. Releasing below 1 leaves the paper where it is. | |
| 9 | func foldGesture(_ session: FoldSession) -> some View { | |
| 10 | modifier(FoldGesture(session: session)) | |
| 11 | } | |
| 12 | } | |
| 13 | ||
| 14 | private struct FoldGesture: ViewModifier { | |
| 15 | let session: FoldSession | |
| 16 | @GestureState private var grab: Grab? | |
| 17 | ||
| 18 | /// The mapping, the moving faces' screen point and t when the drag began. | |
| 19 | private struct Grab { | |
| 20 | let mapping: FoldParameterMapping | |
| 21 | let point: SIMD2<Double> | |
| 22 | let t: Double | |
| 23 | } | |
| 24 | ||
| 25 | func body(content: Content) -> some View { | |
| 26 | let folds = session.step.kind == .fold || session.step.kind == .foldAndUnfold | |
| 27 | content.gesture(drag, isEnabled: folds) | |
| 28 | } | |
| 29 | ||
| 30 | private var drag: some Gesture { | |
| 31 | DragGesture() | |
| 32 | .updating($grab) { value, grab, _ in | |
| 33 | let start = grab ?? Grab(mapping: session.mapping, point: session.mapping.point(at: session.t), t: session.t) | |
| 34 | grab = start | |
| 35 | session.t = start.mapping.parameter( | |
| 36 | grabbedAt: start.point, | |
| 37 | translation: SIMD2(value.translation.width, value.translation.height), | |
| 38 | current: start.mapping.isDegenerate ? start.t : session.t) | |
| 39 | } | |
| 40 | .onEnded { _ in session.completeStep() } | |
| 41 | } | |
| 42 | } | |
App/Sources/FoldSession.swift +50 −12
| @@ -6,26 +6,32 @@ import Observation | ||
| 6 | 6 | import simd |
| 7 | 7 | |
| 8 | 8 | /// One model being folded: the current step, its fold parameter `t` in 0...1, and the model |
| 9 | /// view's orientation. Nothing here changes `t` or the step on its own. | |
| 9 | /// view's orientation. Nothing here changes `t` on its own; the step changes only when the user | |
| 10 | /// completes it. | |
| 10 | 11 | @MainActor @Observable |
| 11 | 12 | final class FoldSession { |
| 12 | 13 | let model: FoldFile |
| 13 | let step: FoldStep | |
| 14 | let interpolator: FoldInterpolator | |
| 15 | let diagram: Diagram | |
| 16 | private let order: LayerOrder | |
| 14 | private(set) var step: FoldStep | |
| 15 | private(set) var interpolator: FoldInterpolator | |
| 16 | private(set) var diagram: Diagram | |
| 17 | private var order: LayerOrder | |
| 17 | 18 | |
| 18 | 19 | var t = 0.0 { |
| 19 | 20 | didSet { if t != oldValue { pose() } } |
| 20 | 21 | } |
| 21 | 22 | /// The unit vector from the camera's target toward its eye. |
| 22 | 23 | var eyeDirection: SIMD3<Double> { |
| 23 | didSet { if eyeDirection != oldValue { sortClusters() } } | |
| 24 | didSet { if eyeDirection != oldValue { sortClusters(); cachedMapping = nil } } | |
| 24 | 25 | } |
| 25 | 26 | /// A unit vector perpendicular to `eyeDirection`. |
| 26 | var up: SIMD3<Double> | |
| 27 | /// The paper view's width over its height. | |
| 28 | var aspect = 1.0 | |
| 27 | var up: SIMD3<Double> { | |
| 28 | didSet { cachedMapping = nil } | |
| 29 | } | |
| 30 | /// The paper view's size in points. | |
| 31 | var viewportSize = SIMD2(1.0, 1.0) { | |
| 32 | didSet { cachedMapping = nil } | |
| 33 | } | |
| 34 | private var aspect: Double { viewportSize.x / viewportSize.y } | |
| 29 | 35 | |
| 30 | 36 | /// The render mesh at `t`. |
| 31 | 37 | private(set) var meshPositions: [SIMD3<Double>] = [] |
| @@ -34,7 +40,8 @@ final class FoldSession { | ||
| 34 | 40 | /// The FOLD vertices at `t`. |
| 35 | 41 | private var positions: [SIMD3<Double>] = [] |
| 36 | 42 | /// The centre of the bounding box of the frame the step starts from. |
| 37 | private let target: SIMD3<Double> | |
| 43 | private var target: SIMD3<Double> | |
| 44 | @ObservationIgnored private var cachedMapping: FoldParameterMapping? | |
| 38 | 45 | /// Half the flat sheet's diagonal, the radius the camera keeps in view. |
| 39 | 46 | private let radius: Double |
| 40 | 47 | private static let fieldOfView = Double.pi / 6 |
| @@ -49,14 +56,39 @@ final class FoldSession { | ||
| 49 | 56 | diagram = buildDiagram(file: model, step: step) |
| 50 | 57 | let (low, high) = bounds(model.frames[0].verticesCoords) |
| 51 | 58 | radius = length(high - low) / 2 |
| 52 | let (start, end) = bounds(model.frames[n - 1].verticesCoords) | |
| 53 | target = (start + end) / 2 | |
| 59 | target = startCentre(model, step) | |
| 54 | 60 | let eye = normalize(step.viewpoint.eye) |
| 55 | 61 | eyeDirection = eye |
| 56 | 62 | up = normalize(step.viewpoint.up - dot(step.viewpoint.up, eye) * eye) |
| 57 | 63 | pose() |
| 58 | 64 | } |
| 59 | 65 | |
| 66 | /// Moves to the next step at t = 0, seen from its viewpoint, once the current step is complete. | |
| 67 | /// After the last step the finished model stays at t = 1. | |
| 68 | func completeStep() { | |
| 69 | guard t == 1, step.index + 1 < model.frames.count, | |
| 70 | let next = try? readStep(step.index + 1, in: model), | |
| 71 | let nextOrder = try? LayerOrder.active(for: next, in: model) else { return } | |
| 72 | step = next | |
| 73 | interpolator = FoldInterpolator(file: model, step: next) | |
| 74 | order = nextOrder | |
| 75 | diagram = buildDiagram(file: model, step: next) | |
| 76 | target = startCentre(model, next) | |
| 77 | let eye = normalize(next.viewpoint.eye) | |
| 78 | eyeDirection = eye | |
| 79 | up = normalize(next.viewpoint.up - dot(next.viewpoint.up, eye) * eye) | |
| 80 | cachedMapping = nil | |
| 81 | t = 0 | |
| 82 | } | |
| 83 | ||
| 84 | /// Maps drags on the paper view to `t` for the current step, camera and view size. | |
| 85 | var mapping: FoldParameterMapping { | |
| 86 | if let cachedMapping { return cachedMapping } | |
| 87 | let mapping = FoldParameterMapping(file: model, step: step, camera: camera, viewportSize: viewportSize) | |
| 88 | cachedMapping = mapping | |
| 89 | return mapping | |
| 90 | } | |
| 91 | ||
| 60 | 92 | /// Looks at the step's start frame from `eyeDirection`, far enough that a sphere of `radius` |
| 61 | 93 | /// about it fits the paper view at `aspect`. |
| 62 | 94 | var camera: Camera { |
| @@ -79,6 +111,12 @@ final class FoldSession { | ||
| 79 | 111 | } |
| 80 | 112 | } |
| 81 | 113 | |
| 114 | /// The centre of the bounding box of the frame `step` starts from. | |
| 115 | private func startCentre(_ model: FoldFile, _ step: FoldStep) -> SIMD3<Double> { | |
| 116 | let (low, high) = bounds(model.frames[step.index - 1].verticesCoords) | |
| 117 | return (low + high) / 2 | |
| 118 | } | |
| 119 | ||
| 82 | 120 | private func bounds(_ points: [SIMD3<Double>]) -> (SIMD3<Double>, SIMD3<Double>) { |
| 83 | 121 | points.dropFirst().reduce((points[0], points[0])) { (simd_min($0.0, $1), simd_max($0.1, $1)) } |
| 84 | 122 | } |
App/Sources/StepView.swift +22 −1
| @@ -55,10 +55,31 @@ struct StepView: View { | ||
| 55 | 55 | PaperView(positions: session.meshPositions, mesh: session.interpolator.mesh, clusters: session.clusters, |
| 56 | 56 | camera: session.camera) |
| 57 | 57 | .onGeometryChange(for: CGSize.self) { $0.size } action: { size in |
| 58 | if size.height > 0 { session.aspect = size.width / size.height } | |
| 58 | if size.width > 0 && size.height > 0 { session.viewportSize = SIMD2(size.width, size.height) } | |
| 59 | 59 | } |
| 60 | .foldGesture(session) | |
| 60 | 61 | .accessibilityElement() |
| 61 | 62 | .accessibilityLabel(session.step.instruction) |
| 63 | .accessibilityValue(session.t.formatted(.percent.precision(.fractionLength(0)))) | |
| 62 | 64 | .accessibilityIdentifier("fold.paper") |
| 65 | .overlay(alignment: .topLeading) { | |
| 66 | if Self.isUITesting { foldPath(session) } | |
| 67 | } | |
| 68 | } | |
| 69 | ||
| 70 | private static let isUITesting = ProcessInfo.processInfo.arguments.contains("-UITesting") | |
| 71 | ||
| 72 | /// For UI tests: the fold path's samples, each as x,y normalised to the paper view's frame. | |
| 73 | private func foldPath(_ session: FoldSession) -> some View { | |
| 74 | let mapping = session.mapping, size = session.viewportSize | |
| 75 | let value = mapping.path.map { p in | |
| 76 | String(format: "%.5f,%.5f", p.x / size.x, p.y / size.y) | |
| 77 | }.joined(separator: " ") | |
| 78 | return Color.clear | |
| 79 | .frame(width: 1, height: 1) | |
| 80 | .allowsHitTesting(false) | |
| 81 | .accessibilityElement() | |
| 82 | .accessibilityValue(value) | |
| 83 | .accessibilityIdentifier("fold.path") | |
| 63 | 84 | } |
| 64 | 85 | } |
App/UITests/FoldGestureTests.swift added +57
| @@ -0,0 +1,57 @@ | ||
| 1 | import XCTest | |
| 2 | ||
| 3 | final class FoldGestureTests: XCTestCase { | |
| 4 | override func setUp() { | |
| 5 | continueAfterFailure = false | |
| 6 | } | |
| 7 | ||
| 8 | func testCompletingAStepAdvancesToTheNext() { | |
| 9 | let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch() | |
| 10 | app.buttons["Cup"].tap() | |
| 11 | completeCurrentFold(app) // drag along the moving facet's path to t = 1, then lift | |
| 12 | XCTAssertEqual(app.staticTexts["step.index"].label, "2") | |
| 13 | } | |
| 14 | ||
| 15 | func testReleasingPartwayLeavesTheStepWhereItIs() { | |
| 16 | let app = XCUIApplication(); app.launchArguments = ["-UITesting"]; app.launch() | |
| 17 | app.buttons["Cup"].tap() | |
| 18 | dragCurrentFold(app, to: 0.5) | |
| 19 | let released = app.otherElements["fold.paper"].value as? String | |
| 20 | sleep(2) | |
| 21 | XCTAssertEqual(app.staticTexts["step.index"].label, "1") | |
| 22 | XCTAssertEqual(app.otherElements["fold.paper"].value as? String, released) | |
| 23 | XCTAssertNotEqual(released, "0%") | |
| 24 | } | |
| 25 | } | |
| 26 | ||
| 27 | /// Drags the current step's moving faces along their path to its end, then lifts. | |
| 28 | func completeCurrentFold(_ app: XCUIApplication) { | |
| 29 | dragCurrentFold(app, to: 1) | |
| 30 | } | |
| 31 | ||
| 32 | /// Drags the current step's moving faces along their path, read from `fold.path` (the app must be | |
| 33 | /// launched with `-UITesting`), to `fraction` of it, then lifts. Each drag is one straight | |
| 34 | /// press-and-drag through a quarter of the path's samples; a drag to the end continues 30 points | |
| 35 | /// past it. | |
| 36 | func dragCurrentFold(_ app: XCUIApplication, to fraction: Double) { | |
| 37 | let paper = app.otherElements["fold.paper"] | |
| 38 | let marker = app.descendants(matching: .any)["fold.path"] | |
| 39 | XCTAssertTrue(marker.waitForExistence(timeout: 5)) | |
| 40 | let samples = (marker.value as? String ?? "").split(separator: " ").map { pair in | |
| 41 | let xy = pair.split(separator: ",").map { Double($0)! } | |
| 42 | return CGVector(dx: xy[0], dy: xy[1]) | |
| 43 | } | |
| 44 | XCTAssertFalse(samples.isEmpty) | |
| 45 | let size = paper.frame.size | |
| 46 | let last = Int((fraction * Double(samples.count - 1)).rounded()) | |
| 47 | let stops = Array(stride(from: 0, to: last, by: 32)) + [last] | |
| 48 | for (a, b) in zip(stops, stops.dropFirst()) { | |
| 49 | var end = paper.coordinate(withNormalizedOffset: samples[b]) | |
| 50 | if b == samples.count - 1 { | |
| 51 | let dx = (samples[b].dx - samples[a].dx) * size.width, dy = (samples[b].dy - samples[a].dy) * size.height | |
| 52 | let length = max((dx * dx + dy * dy).squareRoot(), 1) | |
| 53 | end = end.withOffset(CGVector(dx: dx / length * 30, dy: dy / length * 30)) | |
| 54 | } | |
| 55 | paper.coordinate(withNormalizedOffset: samples[a]).press(forDuration: 0.1, thenDragTo: end) | |
| 56 | } | |
| 57 | } | |
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +31
| @@ -619,3 +619,34 @@ private func rgba(_ image: CGImage) -> [UInt8] { | ||
| 619 | 619 | } |
| 620 | 620 | return bytes |
| 621 | 621 | } |
| 622 | ||
| 623 | /// The fold parameter mapping for step `step` (counted from 1) of a fixture, looking at the step's | |
| 624 | /// start frame from its viewpoint, two sheet sizes away, in an 800 × 600 viewport. | |
| 625 | public func mapping(_ fixtureName: String, step: Int) throws -> FoldParameterMapping { | |
| 626 | let file = try FoldFile(contentsOf: fixture(fixtureName)) | |
| 627 | let s = try readStep(step, in: file) | |
| 628 | let points = file.frames[step - 1].verticesCoords | |
| 629 | let centre = (points.dropFirst().reduce(points[0], simd_min) + points.dropFirst().reduce(points[0], simd_max)) / 2 | |
| 630 | let camera = Camera(eye: centre + normalize(s.viewpoint.eye) * 2 * sheetSize(file), target: centre, | |
| 631 | up: s.viewpoint.up, fieldOfView: .pi / 4) | |
| 632 | return FoldParameterMapping(file: file, step: s, camera: camera, viewportSize: SIMD2(800, 600)) | |
| 633 | } | |
| 634 | ||
| 635 | /// `half.fold`'s step 1 stopped at 30°, seen along the chord of its moving face's centroid, so the | |
| 636 | /// centroid travels almost along the view direction. | |
| 637 | public func mappingForFoldTowardTheCamera() throws -> FoldParameterMapping { | |
| 638 | let file = try FoldFile(contentsOf: fixture("half.fold")) | |
| 639 | let full = try readStep(1, in: file) | |
| 640 | let a = full.axes[0] | |
| 641 | let step = FoldStep(index: 1, kind: .fold, instruction: full.instruction, | |
| 642 | axes: [FoldAxis(edge: a.edge, origin: a.origin, direction: a.direction, | |
| 643 | movingFaces: a.movingFaces, startAngle: 0, endAngle: 30)], | |
| 644 | viewpoint: full.viewpoint) | |
| 645 | // f1's centroid turns about x = 1 from (1.5, 1, 0) to (1 + 0.5 cos 30°, 1, 0.5 sin 30°) | |
| 646 | let start = SIMD3(1.5, 1, 0.0) | |
| 647 | let end = SIMD3(1 + 0.5 * cos(Double.pi / 6), 1, 0.5 * sin(Double.pi / 6)) | |
| 648 | let middle = (start + end) / 2 | |
| 649 | let camera = Camera(eye: middle + normalize(end - start) * 4, target: middle, up: SIMD3(0, 1, 0), | |
| 650 | fieldOfView: .pi / 4) | |
| 651 | return FoldParameterMapping(file: file, step: step, camera: camera, viewportSize: SIMD2(800, 600)) | |
| 652 | } | |
Packages/FoldKit/Sources/Folding/FoldParameterMapping.swift added +142
| @@ -0,0 +1,142 @@ | ||
| 1 | import FoldFormat | |
| 2 | import simd | |
| 3 | ||
| 4 | /// Maps a drag on the paper view to the fold parameter of a step, so the moving faces follow the | |
| 5 | /// finger. Screen points are UIKit's: origin top left, y down, in a viewport of `viewportSize`. | |
| 6 | /// | |
| 7 | /// The faces followed are the step's first moving set; in a non-rigid step that is the flap beyond | |
| 8 | /// the reverse creases. Their centroid is projected at the depth of the camera's target, so that a | |
| 9 | /// face nearing the eye as it lands flat does not overshoot its end on screen and leave t = 1 | |
| 10 | /// unreachable by a finger dragged past it. | |
| 11 | public struct FoldParameterMapping: Sendable { | |
| 12 | /// The centroid's screen point at 129 evenly spaced values of t. | |
| 13 | public let path: [SIMD2<Double>] | |
| 14 | /// Whether the path is under 8 points long, so a drag along it cannot control the fold. | |
| 15 | public let isDegenerate: Bool | |
| 16 | ||
| 17 | /// The search polyline: `path`'s samples with the segment boundaries added. | |
| 18 | private let ts: [Double] | |
| 19 | private let points: [SIMD2<Double>] | |
| 20 | /// Index ranges of `ts` searched one at a time, in order: the whole step, the out and return | |
| 21 | /// halves of a fold-and-unfold, or the open, pop and close phases of a non-rigid step. | |
| 22 | private let segments: [ClosedRange<Int>] | |
| 23 | private let centroid: Centroid | |
| 24 | ||
| 25 | private static let samples = 129 | |
| 26 | private static let minimumLength = 8.0 | |
| 27 | /// Points dragged down for the whole step when the path is degenerate. | |
| 28 | private static let fallbackThrow = 160.0 | |
| 29 | /// How far past the best point so far the search continues, in points. | |
| 30 | private static let slack = 8.0 | |
| 31 | /// How near its segment's end a point counts as the end, in points. | |
| 32 | private static let endTolerance = 0.5 | |
| 33 | ||
| 34 | public init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) { | |
| 35 | let centroid = Centroid(file: file, step: step, camera: camera, viewportSize: viewportSize) | |
| 36 | self.centroid = centroid | |
| 37 | ||
| 38 | let boundaries: [Double] | |
| 39 | if step.nonRigid, let pop = step.pop { | |
| 40 | boundaries = [0, pop.phases.lowerBound, pop.phases.upperBound, 1] | |
| 41 | } else if step.kind == .foldAndUnfold { | |
| 42 | boundaries = [0, 0.5, 1] | |
| 43 | } else { | |
| 44 | boundaries = [0, 1] | |
| 45 | } | |
| 46 | let n = Double(Self.samples - 1) | |
| 47 | let grid = (0..<Self.samples).map { Double($0) / n } | |
| 48 | ts = Array(Set(grid + boundaries)).sorted() | |
| 49 | var segments: [ClosedRange<Int>] = [] | |
| 50 | for (a, b) in zip(boundaries, boundaries.dropFirst()) where a < b { | |
| 51 | segments.append(ts.firstIndex(of: a)!...ts.firstIndex(of: b)!) | |
| 52 | } | |
| 53 | self.segments = segments | |
| 54 | ||
| 55 | points = ts.map(centroid.point(at:)) | |
| 56 | path = grid.map(centroid.point(at:)) | |
| 57 | isDegenerate = zip(path, path.dropFirst()).reduce(0) { $0 + distance($1.0, $1.1) } < Self.minimumLength | |
| 58 | } | |
| 59 | ||
| 60 | /// The followed faces' centroid at `t`, in screen points. | |
| 61 | public func point(at t: Double) -> SIMD2<Double> { centroid.point(at: t) } | |
| 62 | ||
| 63 | /// The parameter, in 0...1, whose centroid is nearest `grabbedAt + translation`, where | |
| 64 | /// `grabbedAt` is the centroid's screen point when the drag began. The search walks the path | |
| 65 | /// outward from `current`, within the segment `current` is in: a fold-and-unfold's return half | |
| 66 | /// once `current` reaches 0.5, a non-rigid step's next phase once `current` reaches the end of | |
| 67 | /// the one before. A point within half a point of its segment's end on screen is the end, so a | |
| 68 | /// segment whose path turns back at its end can be finished. | |
| 69 | /// | |
| 70 | /// When the path is degenerate the drag's downward component advances the fold over 160 | |
| 71 | /// points from `current`, which is then the parameter when the drag began. | |
| 72 | public func parameter(grabbedAt: SIMD2<Double>, translation: SIMD2<Double>, current: Double) -> Double { | |
| 73 | let current = min(max(current, 0), 1) | |
| 74 | if isDegenerate { return min(max(current + translation.y / Self.fallbackThrow, 0), 1) } | |
| 75 | ||
| 76 | let target = grabbedAt + translation | |
| 77 | let segment = segments.last { ts[$0.lowerBound] <= current }! | |
| 78 | // the polyline edge from point i to point i + 1 holding current | |
| 79 | var start = segment.lowerBound | |
| 80 | while start + 1 < segment.upperBound && ts[start + 1] <= current { start += 1 } | |
| 81 | ||
| 82 | func nearest(onEdge i: Int) -> (t: Double, point: SIMD2<Double>, distance: Double) { | |
| 83 | let a = points[i], d = points[i + 1] - points[i] | |
| 84 | let lengthSquared = dot(d, d) | |
| 85 | let u = lengthSquared > 0 ? min(max(dot(target - a, d) / lengthSquared, 0), 1) : 0 | |
| 86 | return ((1 - u) * ts[i] + u * ts[i + 1], a + u * d, distance(a + u * d, target)) | |
| 87 | } | |
| 88 | var best = nearest(onEdge: start) | |
| 89 | for direction in [1, -1] { | |
| 90 | var i = start + direction | |
| 91 | while i >= segment.lowerBound && i < segment.upperBound { | |
| 92 | let candidate = nearest(onEdge: i) | |
| 93 | if candidate.distance < best.distance { | |
| 94 | best = candidate | |
| 95 | } else if candidate.distance > best.distance + Self.slack { | |
| 96 | break | |
| 97 | } | |
| 98 | i += direction | |
| 99 | } | |
| 100 | } | |
| 101 | let end = segment.upperBound | |
| 102 | return distance(best.point, points[end]) <= Self.endTolerance ? ts[end] : best.t | |
| 103 | } | |
| 104 | } | |
| 105 | ||
| 106 | /// The area centroid of the followed faces, projected to screen points. | |
| 107 | private struct Centroid: Sendable { | |
| 108 | let interpolator: FoldInterpolator | |
| 109 | /// Fan triangles of the faces, with their areas in frame 0. | |
| 110 | let triangles: [(SIMD3<Int>, Double)] | |
| 111 | let viewProjection: simd_double4x4 | |
| 112 | /// Clip-space w of the camera's target. | |
| 113 | let depth: Double | |
| 114 | let viewportSize: SIMD2<Double> | |
| 115 | ||
| 116 | init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2<Double>) { | |
| 117 | interpolator = FoldInterpolator(file: file, step: step) | |
| 118 | let faces = step.axes.first.map { Array($0.movingFaces) } ?? Array(file.facesVertices.indices) | |
| 119 | let flat = file.frames[0].verticesCoords | |
| 120 | triangles = faces.flatMap { f in | |
| 121 | let face = file.facesVertices[f] | |
| 122 | return (1..<face.count - 1).map { i in | |
| 123 | (SIMD3(face[0], face[i], face[i + 1]), | |
| 124 | length(cross(flat[face[i]] - flat[face[0]], flat[face[i + 1]] - flat[face[0]])) / 2) | |
| 125 | } | |
| 126 | } | |
| 127 | viewProjection = camera.viewProjection(aspect: viewportSize.x / viewportSize.y) | |
| 128 | depth = (viewProjection * SIMD4(camera.target, 1)).w | |
| 129 | self.viewportSize = viewportSize | |
| 130 | } | |
| 131 | ||
| 132 | func point(at t: Double) -> SIMD2<Double> { | |
| 133 | let positions = interpolator.positions(at: t) | |
| 134 | var sum = SIMD3<Double>.zero, area = 0.0 | |
| 135 | for (v, a) in triangles { | |
| 136 | sum += a * (positions[v.x] + positions[v.y] + positions[v.z]) / 3 | |
| 137 | area += a | |
| 138 | } | |
| 139 | let clip = viewProjection * SIMD4(sum / area, 1) | |
| 140 | return SIMD2((clip.x / depth + 1) / 2 * viewportSize.x, (1 - clip.y / depth) / 2 * viewportSize.y) | |
| 141 | } | |
| 142 | } | |
Packages/FoldKit/Tests/FoldingTests/FoldParameterTests.swift added +61
| @@ -0,0 +1,61 @@ | ||
| 1 | import FoldKitTestSupport | |
| 2 | import Folding | |
| 3 | import simd | |
| 4 | import Testing | |
| 5 | ||
| 6 | @Test func theFacetTracksTheFinger() throws { | |
| 7 | let m = try mapping("half.fold", step: 1) // viewed from above | |
| 8 | let target = m.path[32] // t = 0.25 | |
| 9 | let t = m.parameter(grabbedAt: m.path[0], translation: target - m.path[0], current: 0) | |
| 10 | #expect(abs(t - 0.25) < 0.01) | |
| 11 | } | |
| 12 | ||
| 13 | @Test func dragPerpendicularToThePathDoesNotAdvanceTheFold() throws { | |
| 14 | let m = try mapping("half.fold", step: 1) | |
| 15 | let along = simd_normalize(m.path[1] - m.path[0]) | |
| 16 | let perp = SIMD2(-along.y, along.x) | |
| 17 | #expect(m.parameter(grabbedAt: m.path[0], translation: perp * 50, current: 0) < 0.01) | |
| 18 | } | |
| 19 | ||
| 20 | @Test func parameterIsClampedToUnitRange() throws { | |
| 21 | let m = try mapping("half.fold", step: 1) | |
| 22 | let along = simd_normalize(m.path[128] - m.path[0]) | |
| 23 | #expect(m.parameter(grabbedAt: m.path[0], translation: along * 100_000, current: 0) == 1) | |
| 24 | #expect(m.parameter(grabbedAt: m.path[0], translation: along * -100_000, current: 0) == 0) | |
| 25 | } | |
| 26 | ||
| 27 | @Test func headOnFoldIsReportedDegenerate() throws { | |
| 28 | #expect(try mappingForFoldTowardTheCamera().isDegenerate) | |
| 29 | } | |
| 30 | ||
| 31 | @Test func degenerateMappingFallsBackToVerticalDrag() throws { | |
| 32 | let m = try mappingForFoldTowardTheCamera() | |
| 33 | #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 50), current: 0) > 0.1) | |
| 34 | } | |
| 35 | ||
| 36 | @Test func theMappingIsNeverInfinitelySensitive() throws { | |
| 37 | let m = try mappingForFoldTowardTheCamera() | |
| 38 | #expect(m.parameter(grabbedAt: .zero, translation: SIMD2(0, 1), current: 0) < 0.2) | |
| 39 | } | |
| 40 | ||
| 41 | @Test func aNonRigidStepIsDraggedPhaseByPhase() throws { | |
| 42 | // following the path's own samples in order reaches t = 1 without ever going back | |
| 43 | let m = try FoldParameterMapping(file: compiled("reverse"), step: readSteps(compiled("reverse"))[1], | |
| 44 | camera: Camera(eye: SIMD3(2, 1, 8), target: SIMD3(2, 1, 0), up: SIMD3(0, 1, 0), fieldOfView: .pi / 4), | |
| 45 | viewportSize: SIMD2(800, 600)) | |
| 46 | var t = 0.0 | |
| 47 | for p in m.path.dropFirst() { | |
| 48 | let next = m.parameter(grabbedAt: m.path[0], translation: p - m.path[0], current: t) | |
| 49 | #expect(next >= t - 1e-9) | |
| 50 | t = next | |
| 51 | } | |
| 52 | #expect(t > 0.99) | |
| 53 | } | |
| 54 | ||
| 55 | @Test func foldAndUnfoldGoesOutThenBack() throws { | |
| 56 | let m = try mapping("quarters.fold", step: 1) | |
| 57 | let atPeak = m.parameter(grabbedAt: m.path[0], translation: m.path[64] - m.path[0], current: 0) | |
| 58 | #expect(abs(atPeak - 0.5) < 0.01) | |
| 59 | let back = m.parameter(grabbedAt: m.path[0], translation: .zero, current: atPeak) | |
| 60 | #expect(back > 0.99) | |
| 61 | } | |