spikes/bending/Sources/Bending/MeshCase.swift

00ea029d0652da12d0f4237769e7020b72cfa7f3
fold/spikes/bending/Sources/Bending/MeshCase.swift history · blame · raw

112 lines · 6209 bytes

4 symbols in this file
  1import FoldCompiler
  2import FoldFormat
  3import Folding
  4import Foundation
  5import simd
  6
  7let fixtures = URL(fileURLWithPath: #filePath)
  8    .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
  9    .deletingLastPathComponent().deletingLastPathComponent()
 10    .appendingPathComponent("Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures")
 11
 12/// Decision 0002's reverse-fold fixture, compiled by FoldKit (open to 30° by default).
 13func compiledReverseFixture(openAngle: Double? = nil) throws -> FoldFile {
 14    var script = try FoldScript(contentsOf: fixtures.appendingPathComponent("reverse.foldscript"))
 15    if let openAngle {
 16        var steps = script.steps
 17        let s = steps[1]
 18        steps[1] = ScriptStep(kind: s.kind, technique: s.technique, instruction: s.instruction, creases: s.creases,
 19                              movingSide: s.movingSide, angles: s.angles, peakAngles: s.peakAngles,
 20                              faceOrders: s.faceOrders, spine: s.spine, openAngle: openAngle)
 21        script = FoldScript(creasePattern: script.creasePattern, title: script.title, steps: steps)
 22    }
 23    return try compile(script, pattern: FoldFile(contentsOf: fixtures.appendingPathComponent("reverse-cp.fold")))
 24}
 25
 26/// Per FOLD face, its rotation from pose a to pose b, from its widest corners (as FoldKit's pop).
 27func faceTurns(_ model: Model, _ a: [V3], _ b: [V3]) -> [simd_quatd] {
 28    model.faces.map { corners in
 29        let c = widest(corners.map { model.flat[$0] }).map { corners[$0] }
 30        func frame(_ p: [V3]) -> simd_double3x3 {
 31            let along = normalize(p[1] - p[0]), n = normalize(cross(p[1] - p[0], p[2] - p[0]))
 32            return simd_double3x3(columns: (along, cross(n, along), n))
 33        }
 34        var q = simd_quatd(frame(c.map { b[$0] }) * frame(c.map { a[$0] }).transpose)
 35        if q.real < 0 { q = simd_quatd(vector: -q.vector) }
 36        return q
 37    }
 38}
 39
 40func meshCase() throws {
 41    print("## Render meshes")
 42    print("")
 43    print("Spacing h = the crease pattern's longer side / 32 unless stated.")
 44    print("")
 45    // the 0002 fixture's pop
 46    for angle in [30.0, 10.0] {
 47        let file = try compiledReverseFixture(openAngle: angle)
 48        let model = Model(file)
 49        let step = try readStep(2, in: file)
 50        let interp = FoldInterpolator(file: file, step: step)
 51        let pop = step.pop!
 52        let samples = (0...64).map { pop.phases.lowerBound + Double($0) / 64 * (pop.phases.upperBound - pop.phases.lowerBound) }
 53        let production = samples.map { Folding.strain(interp.meshPositions(at: $0), mesh: interp.mesh) }.max()!
 54        print("### 0002 fixture (4×2 flap), opened to \(Int(angle))°: FoldKit's pop strain \(pct(production))")
 55        print("")
 56        print("| mesh | h | vertices | triangles | shortest edge | smallest angle | pop edge strain | pop principal strain | collisions in the pop |")
 57        print("|---|---|---|---|---|---|---|---|---|")
 58        let open = interp.positions(at: pop.phases.lowerBound)
 59        for divisions in [32.0, 64.0] {
 60            for kind in MeshKind.allCases {
 61                let h = model.size / divisions
 62                let mesh = buildMesh(kind, model, spacing: h)
 63                let st = mesh.stats
 64                let held = Set(model.faces.indices).subtracting(step.movingFaceUnion)
 65                let fit = EdgeFit(mesh: mesh, fixed: mesh.vertices(of: held))
 66                let turns = faceTurns(model, open, pop.popped)
 67                let blend = Blend(fit, from: mesh.pose(open), to: mesh.pose(pop.popped), turns: mesh.faceOf.map { turns[$0] })
 68                let edges = mesh.edges
 69                var worst = 0.0, principal = 0.0, collisions = 0
 70                for k in 0...64 {
 71                    let x = blend.at(Double(k) / 64)
 72                    worst = max(worst, strain(x, mesh, edges: edges))
 73                    principal = max(principal, principalStrain(x, mesh))
 74                    if k > 0 && k < 64 { collisions += meshCollisions(x, mesh, size: model.size, depth: 1e-9).count }
 75                }
 76                print("| \(kind.rawValue) | 1/\(Int(divisions)) | \(st.vertices) | \(st.triangles) | \(sci(st.shortestEdge)) | \(f1(st.smallestAngle))° | \(pct(worst)) | \(pct(principal)) | \(collisions) |")
 77            }
 78        }
 79        print("")
 80    }
 81
 82    // the crane's neck pop (raised crease, rigid opening on a bend line) on each mesh
 83    let neck = try craneStages().neck
 84    print("### Crane neck pop (raised crease, opened by a turn of the near side on a bend line), slerp pop")
 85    print("")
 86    print("| mesh | vertices | shortest edge | α | pop edge strain | pop principal strain | worst edge (rest length, where) |")
 87    print("|---|---|---|---|---|---|---|")
 88    for kind in MeshKind.allCases {
 89        let mesh = buildMesh(kind, neck.model, spacing: neck.model.size / 32)
 90        for alpha in [160.0, 150.0] {
 91            let run = runStage(neck, mesh: mesh, alphaMax: alpha, samples: 16, collisionDepth: 1e-3 * neck.model.size / 32)
 92            let w = run.worst
 93            print("| \(kind.rawValue) | \(mesh.rest.count) | \(sci(mesh.stats.shortestEdge)) | \(Int(alpha))° | \(pct(run.popStrain)) | \(pct(run.popPrincipal)) | \(sci(w.rest)) at (\(f3(w.at.x)), \(f3(w.at.y))) |")
 94        }
 95    }
 96    print("")
 97
 98    for (name, title) in [("crane-1-12.fold", "Crane crease pattern (with the neck creases)"),
 99                          ("sampan-long-1-13.fold", "Long-form sampan crease pattern")] {
100        let model = try Model(named: name)
101        print("### \(title): \(model.flat.count) vertices, \(model.faces.count) faces; shortest crease \(sci(model.edges.map { simd_distance(model.flat[$0[0]], model.flat[$0[1]]) }.min()!))")
102        print("")
103        print("| mesh | vertices | triangles | shortest edge | shortest / h | smallest angle |")
104        print("|---|---|---|---|---|---|")
105        let h = model.size / 32
106        for kind in MeshKind.allCases {
107            let st = buildMesh(kind, model, spacing: h).stats
108            print("| \(kind.rawValue) | \(st.vertices) | \(st.triangles) | \(sci(st.shortestEdge)) | \(f3(st.shortestEdge / h)) | \(f1(st.smallestAngle))° |")
109        }
110        print("")
111    }
112}