import simd /// An inside reverse fold of a multi-layer flap on a flat-folded frame, set up for bending. /// /// The flap is folded on its spine (a straight line in the frame), its layers split into a near /// half (toward `normal`, the viewer) and a far half. The reverse crease runs from `vertex`, on the /// spine, along `crease` in the paper's plane; the tip is beyond it. The near layers open by /// turning about the spine toward the viewer by α; at the vertex the four creases (body spine, tip /// spine and the two layers' reverse creases) form decision 0001's degree-4 vertex, rigid on two /// branches: the tip opened with its layers (unreversed) and the tip reversed between them. struct ReverseFold { var model: Model let frame: Int let vertex: V3 /// Along the spine from the vertex toward the body. let spine: V3 /// Along the reverse crease from the vertex, in the paper's plane. let crease: V3 /// The paper's normal toward the viewer, the side the near layers open to. let normal: V3 let tipNear: Set let tipFar: Set /// Near faces on the flap's side of the spine's line, not in the tip. let nearSide: Set /// Near faces across the spine's line (they must bend or crease along it to open). let across: Set /// Everything else: the far half and the near faces beyond the spine's line. let rest: Set /// Rotation turning the near layers by α toward the viewer about the spine. func opening(_ alpha: Double) -> simd_quatd { // the sign that lifts the crease's in-plane offset from the spine toward the viewer let side = normalize(crease - dot(crease, spine) * spine) let q = simd_quatd(angle: alpha * .pi / 180, axis: spine) return dot(q.act(side), normal) >= 0 || alpha == 0 ? q : simd_quatd(angle: -alpha * .pi / 180, axis: spine) } /// The tip's two rigid motions with the near layers opened by α: unreversed (the tip turns with /// its layers) or reversed (each layer of the tip turned about its own reverse crease so that /// the tip's spine meets in the plane bisecting the opened layers). func tip(alpha: Double, reversed: Bool) -> (near: (V3) -> V3, far: (V3) -> V3) { let open = opening(alpha) let v = vertex guard reversed else { return ({ v + open.act($0 - v) }, { $0 }) } let cn = open.act(crease), c = crease let w = -spine let gamma: Double if alpha < 1e-9 { gamma = .pi } else { let wPerp = w - dot(w, cn) * cn let p = dot(wPerp, c), q = dot(cross(cn, wPerp), c) gamma = 2 * atan2(q, p) } let turnNear = simd_quatd(angle: gamma, axis: cn) * open let u = turnNear.act(w) // the far layer turns about its crease to bring the tip spine to u let a = w - dot(w, c) * c, b = u - dot(u, c) * c let gammaFar = atan2(dot(cross(a, b), c), dot(a, b)) let turnFar = simd_quatd(angle: gammaFar, axis: c) return ({ v + turnNear.act($0 - v) }, { v + turnFar.act($0 - v) }) } } /// The reverse fold's measurements on one mesh, for one choice of what bends. struct ReverseRun { var openStrain = 0.0, popStrain = 0.0, closeStrain = 0.0 var openPrincipal = 0.0, popPrincipal = 0.0, closePrincipal = 0.0 var openCollisions = 0, popCollisions = 0, closeCollisions = 0 var firstCollision: (phase: String, s: Double, faces: (Int, Int))? var tipInside = false var endError = 0.0 var worst: (strain: Double, rest: Double, at: V2) = (0, 0, .zero) var arapChange = 0.0 } /// Open by α_max over the first third, pop the tip between the layers over the second (decision /// 0002's per-face slerp, the rest held), close on the reversed branch over the last. Faces in /// `free` bend by as-rigid-as-possible solves at every sample; the tip's faces follow the rigid /// branch for the current α; every other face holds frame n − 1's place. func runReverse(_ r: ReverseFold, mesh: Mesh, alphaMax: Double, free: Set, samples: Int = 24, collisionDepth: Double, iterations: Int = 60) -> ReverseRun { let model = r.model let x0 = mesh.pose(model.positions(r.frame)) let tipNear = mesh.vertices(of: r.tipNear), tipFar = mesh.vertices(of: r.tipFar) let freeVertices = mesh.vertices(of: free).subtracting(tipNear).subtracting(tipFar) .subtracting(mesh.vertices(of: Set(model.faces.indices).subtracting(free).subtracting(r.tipNear).subtracting(r.tipFar))) let fixed = Set(mesh.rest.indices).subtracting(freeVertices) let fit = EdgeFit(mesh: mesh, fixed: fixed) let edges = mesh.edges let size = model.size var run = ReverseRun() func handles(_ alpha: Double, reversed: Bool, onto x: [V3]) -> [V3] { let (near, far) = r.tip(alpha: alpha, reversed: reversed) var out = x for v in fixed { out[v] = x0[v] } for v in tipFar { out[v] = far(x0[v]) } for v in tipNear { out[v] = near(x0[v]) } return out } // the free vertices' guess: turned with the opening, about the spine func predict(_ x: [V3], from a0: Double, to a1: Double) -> [V3] { let q = r.opening(a1) * r.opening(a0).inverse var out = x let nearSide = mesh.vertices(of: r.nearSide) for v in freeVertices where nearSide.contains(v) { out[v] = r.vertex + q.act(x[v] - r.vertex) } return out } func measure(_ x: [V3], phase: String, s: Double, strain s0: inout Double, principal p0: inout Double, collisions c0: inout Int) { let e = strain(x, mesh, edges: edges) if e > run.worst.strain { run.worst = worstEdge(x, mesh, edges: edges) } s0 = max(s0, e) p0 = max(p0, principalStrain(x, mesh)) let hits = meshCollisions(x, mesh, size: size, depth: collisionDepth) c0 += hits.count if let h = hits.first, run.firstCollision == nil { run.firstCollision = (phase, s, (mesh.faceOf[h.0], mesh.faceOf[h.1])) } } // open var x = x0 var alpha = 0.0 for k in 1...samples { let a = alphaMax * Double(k) / Double(samples) x = handles(a, reversed: false, onto: predict(x, from: alpha, to: a)) let solved = fit.arap(x, iterations: iterations, tolerance: 1e-10 * size) x = solved.x run.arapChange = max(run.arapChange, solved.change) alpha = a measure(x, phase: "open", s: Double(k) / Double(samples), strain: &run.openStrain, principal: &run.openPrincipal, collisions: &run.openCollisions) } let opened = x // pop: the tip's faces turn by slerp, everything else held as opened let popped = handles(alphaMax, reversed: true, onto: opened) let popFit = EdgeFit(mesh: mesh, fixed: Set(mesh.rest.indices).subtracting(tipNear.union(tipFar) .subtracting(mesh.vertices(of: Set(model.faces.indices).subtracting(r.tipNear).subtracting(r.tipFar))))) let blend = Blend(popFit, from: opened, to: popped) for k in 1.., upper: Set, lower: Set, normal: V3) -> Bool { let n = normalize(normal) let a = normalize(abs(n.x) < 0.9 ? cross(n, V3(1, 0, 0)) : cross(n, V3(0, 1, 0))), b = cross(n, a) func flat(_ p: V3) -> V2 { V2(dot(p, a), dot(p, b)) } func height(_ t: SIMD3, over q: V2) -> Double? { let p = [x[t.x], x[t.y], x[t.z]] let f = p.map(flat) let d = cross2(f[1] - f[0], f[2] - f[0]) guard abs(d) > 1e-14 else { return nil } let l1 = cross2(q - f[0], f[2] - f[0]) / d, l2 = cross2(f[1] - f[0], q - f[0]) / d guard l1 >= 0, l2 >= 0, l1 + l2 <= 1 else { return nil } return dot(p[0] + l1 * (p[1] - p[0]) + l2 * (p[2] - p[0]), n) } var inside = 0 for (k, t) in mesh.triangles.enumerated() where tip.contains(mesh.faceOf[k]) { let c = (x[t.x] + x[t.y] + x[t.z]) / 3 let q = flat(c), h = dot(c, n) var below = false, aboveOK = true, sawAbove = false for (j, u) in mesh.triangles.enumerated() { let f = mesh.faceOf[j] if lower.contains(f), let z = height(u, over: q), z < h { below = true } if upper.contains(f), let z = height(u, over: q) { sawAbove = true if z <= h { aboveOK = false } } } if below && sawAbove && aboveOK { inside += 1 } } return inside > 0 }