import FoldFormat import Folding import simd /// The parts of `edge`, projected orthographically along `viewpoint`, that are not inside the /// union of the faces above either of its faces in `frame`. /// /// A face is above an edge's face when it follows that face in their cluster's back-to-front list, /// `order.clusters` read looking along −`eye`. A face in neither of their clusters is above the /// edge where it lies nearer the eye; a face seen edge-on covers nothing. An edge on the outer /// boundary of the union stays visible; one under the seam between two upper faces, covered on /// both sides, does not. Where an upper face overlying one of the edge's faces meets a neighbour /// across a flat edge along the edge, the neighbour covers its side of that seam. public func visibleSegments(of edge: Int, frame: FoldFrame, file: FoldFile, order: LayerOrder, viewpoint: Viewpoint) -> [(SIMD2, SIMD2)] { Occlusion(frame: frame, file: file, order: order, viewpoint: viewpoint).visibleSegments(of: edge) } /// Orthographic projection onto the screen plane of a viewpoint: x along `right`, y along `up`. struct ViewProjection { let right: SIMD3 let up: SIMD3 init(_ viewpoint: Viewpoint) { let eye = normalize(viewpoint.eye) right = normalize(cross(viewpoint.up, eye)) up = cross(eye, right) } func callAsFunction(_ p: SIMD3) -> SIMD2 { SIMD2(dot(p, right), dot(p, up)) } } /// One frame projected for a viewpoint, with each face's occluders. struct Occlusion { let points: [SIMD2] let edgesVertices: [[Int]] let edgeFaces: [[Int]] /// Each face's projected outline, counterclockwise. let outlines: [[SIMD2]] /// Each face's followers in its cluster. let above: [[Int]] /// Each face's cluster. let cluster: [Int] /// Each face's neighbours across an interior edge flat in the frame, with that edge. let flatNeighbours: [[(face: Int, edge: Int)]] let positions: [SIMD3] let facesVertices: [[Int]] let normals: [SIMD3] /// The unit vector toward the eye. let eye: SIMD3 let tolerance: Double init(frame: FoldFrame, file: FoldFile, order: LayerOrder, viewpoint: Viewpoint) { let project = ViewProjection(viewpoint) let points = frame.verticesCoords.map(project.callAsFunction) self.points = points edgesVertices = file.edgesVertices edgeFaces = edgesFaces(file) outlines = file.facesVertices.map { corners in let outline = corners.map { points[$0] } return signedArea(outline) < 0 ? outline.reversed() : outline } var above = Array(repeating: [Int](), count: file.facesVertices.count) var cluster = Array(repeating: 0, count: file.facesVertices.count) let clusters = order.clusters(positions: frame.verticesCoords, faces: file.facesVertices, viewDirection: -viewpoint.eye) for (k, members) in clusters.enumerated() { for (i, face) in members.faces.enumerated() { above[face] = Array(members.faces[(i + 1)...]) cluster[face] = k } } self.above = above self.cluster = cluster var flatNeighbours = Array(repeating: [(face: Int, edge: Int)](), count: file.facesVertices.count) for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && abs(frame.edgesFoldAngle[e]) <= 1e-9 { flatNeighbours[faces[0]].append((faces[1], e)) flatNeighbours[faces[1]].append((faces[0], e)) } self.flatNeighbours = flatNeighbours positions = frame.verticesCoords facesVertices = file.facesVertices normals = faceNormals(positions: frame.verticesCoords, faces: file.facesVertices) eye = normalize(viewpoint.eye) let low = points.reduce(points.first ?? .zero, simd_min) let high = points.reduce(points.first ?? .zero, simd_max) tolerance = max(length(high - low), 1) * 1e-9 } func endpoints(of edge: Int) -> (SIMD2, SIMD2) { (points[edgesVertices[edge][0]], points[edgesVertices[edge][1]]) } func visibleSegments(of edge: Int) -> [(SIMD2, SIMD2)] { let (a, b) = endpoints(of: edge) guard length(b - a) > tolerance else { return [] } let occluders = Set(edgeFaces[edge].flatMap { above[$0] }) var covers = occluders.sorted().compactMap { cover(a, b, by: outlines[$0]) } // an occluder lying over one of the edge's faces continues across a flat edge along the // edge into the same layer of paper: under that seam the neighbour covers its side too let overlying = Set(edgeFaces[edge].flatMap { h in above[h].filter { convexPolygonsOverlap(outlines[$0], outlines[h], tolerance: tolerance) } }) let seamed = Set(overlying.flatMap { f in flatNeighbours[f].filter { alongEdge($0.edge, edge) }.map(\.face) }).subtracting(occluders).subtracting(edgeFaces[edge]) covers += seamed.sorted().compactMap { f in cover(a, b, by: outlines[f]).flatMap { $0.side == .both ? nil : $0 } } let own = Set(edgeFaces[edge].map { cluster[$0] }) for f in outlines.indices where !own.contains(cluster[f]) { guard let c = cover(a, b, by: outlines[f]), let nearer = nearer(f, than: edge) else { continue } let low = max(c.range.lowerBound, nearer.lowerBound), high = min(c.range.upperBound, nearer.upperBound) if high - low > tolerance / length(b - a) { covers.append((low...high, c.side)) } } // between consecutive cut points coverage is constant; test each piece's midpoint let cuts = Set([0.0, 1.0] + covers.flatMap { [$0.range.lowerBound, $0.range.upperBound] }).sorted() var visible: [ClosedRange] = [] for (t0, t1) in zip(cuts, cuts.dropFirst()) where t1 > t0 { let t = (t0 + t1) / 2 let sides = covers.filter { $0.range.contains(t) }.map(\.side) let hidden = sides.contains(.both) || (sides.contains(.left) && sides.contains(.right)) if hidden { continue } if let last = visible.last, last.upperBound == t0 { visible[visible.count - 1] = last.lowerBound...t1 } else { visible.append(t0...t1) } } let minimum = tolerance / length(b - a) return visible.filter { $0.upperBound - $0.lowerBound > minimum } .map { (a + $0.lowerBound * (b - a), a + $0.upperBound * (b - a)) } } /// Whether edge `e` lies on the line of edge `other` in the frame and shares a stretch of it. private func alongEdge(_ e: Int, _ other: Int) -> Bool { let a = positions[edgesVertices[other][0]], b = positions[edgesVertices[other][1]] let (p, q) = (positions[edgesVertices[e][0]], positions[edgesVertices[e][1]]) let d = b - a, length2 = length_squared(d) guard length2 > 0 else { return false } let off = [p, q].map { length(cross(d, $0 - a)) / length2.squareRoot() } guard off.allSatisfy({ $0 <= tolerance }) else { return false } let s = dot(p - a, d) / length2, t = dot(q - a, d) / length2 return min(max(s, t), 1) - max(min(s, t), 0) > tolerance / length2.squareRoot() } enum Side { case left, right, both } /// The parameters of `edge` at which face `f`'s plane lies nearer the eye along the view, or /// nil where it nowhere does or `f` is seen edge-on. private func nearer(_ f: Int, than edge: Int) -> ClosedRange? { let n = normals[f], facing = dot(n, eye) guard abs(facing) > 1e-9 else { return nil } let corner = positions[facesVertices[f][0]] let (p, q) = (positions[edgesVertices[edge][0]], positions[edgesVertices[edge][1]]) // how far toward the eye the face's plane is from the edge's point at t: d0 + (d1 − d0) t let d0 = dot(n, corner - p) / facing, d1 = dot(n, corner - q) / facing switch (d0 > tolerance, d1 > tolerance) { case (true, true): return 0...1 case (false, false): return nil case (true, false): return 0...((d0 - tolerance) / (d0 - d1)) case (false, true): return ((tolerance - d0) / (d1 - d0))...1 } } /// The parameters of the segment `a`–`b` the counterclockwise convex `polygon` covers, and on /// which side: both sides where the segment crosses its open interior, one side where the /// segment lies along one of its sides. private func cover(_ a: SIMD2, _ b: SIMD2, by polygon: [SIMD2]) -> (range: ClosedRange, side: Side)? { let d = b - a var low = 0.0, high = 1.0 var side = Side.both for i in polygon.indices { let p = polygon[i], s = polygon[(i + 1) % polygon.count] - p let sideLength = length(s) guard sideLength > tolerance else { continue } // distance inside this side's line at parameter t: c0 + c1 t let c0 = perpDot(s, a - p) / sideLength, c1 = perpDot(s, d) / sideLength if abs(c0) <= tolerance && abs(c0 + c1) <= tolerance { side = dot(s, d) > 0 ? .left : .right continue } if c1 == 0 { if c0 <= 0 { return nil } } else if c1 > 0 { low = max(low, -c0 / c1) } else { high = min(high, -c0 / c1) } } return high - low > tolerance / length(d) ? (low...high, side) : nil } } func perpDot(_ u: SIMD2, _ v: SIMD2) -> Double { u.x * v.y - u.y * v.x } func signedArea(_ p: [SIMD2]) -> Double { p.indices.reduce(0) { sum, i in sum + perpDot(p[i], p[(i + 1) % p.count]) / 2 } }