Commit 669f4308fa
Verified · cmc
Layout: unified · split
App/Sources/DiagramCanvas.swift added +27
| @@ -0,0 +1,27 @@ | |||
| 1 | import Notation | ||
| 2 | import SwiftUI | ||
| 3 | |||
| 4 | /// A step's diagram, drawn by Notation's `drawDiagram` on a white ground. | ||
| 5 | struct DiagramCanvas: View { | ||
| 6 | let diagram: Diagram | ||
| 7 | let style: DiagramStyle | ||
| 8 | |||
| 9 | init(diagram: Diagram, style: DiagramStyle) { | ||
| 10 | self.diagram = diagram | ||
| 11 | self.style = style | ||
| 12 | } | ||
| 13 | |||
| 14 | var body: some View { | ||
| 15 | Canvas { context, size in | ||
| 16 | context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(.white)) | ||
| 17 | context.withCGContext { cg in | ||
| 18 | cg.translateBy(x: 0, y: size.height) | ||
| 19 | cg.scaleBy(x: 1, y: -1) | ||
| 20 | drawDiagram(diagram, style: style, in: cg, size: size) | ||
| 21 | } | ||
| 22 | } | ||
| 23 | .accessibilityElement() | ||
| 24 | .accessibilityAddTraits(.isImage) | ||
| 25 | .accessibilityIdentifier("diagram") | ||
| 26 | } | ||
| 27 | } | ||
App/Sources/FoldApp.swift added +10
| @@ -0,0 +1,10 @@ | |||
| 1 | import SwiftUI | ||
| 2 | |||
| 3 | @main | ||
| 4 | struct FoldApp: App { | ||
| 5 | var body: some Scene { | ||
| 6 | WindowGroup { | ||
| 7 | ModelListView() | ||
| 8 | } | ||
| 9 | } | ||
| 10 | } | ||
App/Sources/FoldSession.swift added +84
| @@ -0,0 +1,84 @@ | |||
| 1 | import FoldFormat | ||
| 2 | import Folding | ||
| 3 | import Foundation | ||
| 4 | import Notation | ||
| 5 | import Observation | ||
| 6 | import simd | ||
| 7 | |||
| 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. | ||
| 10 | @MainActor @Observable | ||
| 11 | final class FoldSession { | ||
| 12 | let model: FoldFile | ||
| 13 | let step: FoldStep | ||
| 14 | let interpolator: FoldInterpolator | ||
| 15 | let diagram: Diagram | ||
| 16 | private let order: LayerOrder | ||
| 17 | |||
| 18 | var t = 0.0 { | ||
| 19 | didSet { if t != oldValue { pose() } } | ||
| 20 | } | ||
| 21 | /// The unit vector from the camera's target toward its eye. | ||
| 22 | var eyeDirection: SIMD3<Double> { | ||
| 23 | didSet { if eyeDirection != oldValue { sortClusters() } } | ||
| 24 | } | ||
| 25 | /// 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 | ||
| 29 | |||
| 30 | /// The render mesh at `t`. | ||
| 31 | private(set) var meshPositions: [SIMD3<Double>] = [] | ||
| 32 | /// The FOLD faces' clusters at `t`, back to front along the camera's view direction. | ||
| 33 | private(set) var clusters: [CoplanarCluster] = [] | ||
| 34 | /// The FOLD vertices at `t`. | ||
| 35 | private var positions: [SIMD3<Double>] = [] | ||
| 36 | /// The centre of the bounding box of the frame the step starts from. | ||
| 37 | private let target: SIMD3<Double> | ||
| 38 | /// Half the flat sheet's diagonal, the radius the camera keeps in view. | ||
| 39 | private let radius: Double | ||
| 40 | private static let fieldOfView = Double.pi / 6 | ||
| 41 | |||
| 42 | /// `step` counts from 1. The camera starts at the step's authored viewpoint. | ||
| 43 | init(model: FoldFile, step n: Int) throws { | ||
| 44 | self.model = model | ||
| 45 | let step = try readStep(n, in: model) | ||
| 46 | self.step = step | ||
| 47 | interpolator = FoldInterpolator(file: model, step: step) | ||
| 48 | order = try LayerOrder.active(for: step, in: model) | ||
| 49 | diagram = buildDiagram(file: model, step: step) | ||
| 50 | let (low, high) = bounds(model.frames[0].verticesCoords) | ||
| 51 | radius = length(high - low) / 2 | ||
| 52 | let (start, end) = bounds(model.frames[n - 1].verticesCoords) | ||
| 53 | target = (start + end) / 2 | ||
| 54 | let eye = normalize(step.viewpoint.eye) | ||
| 55 | eyeDirection = eye | ||
| 56 | up = normalize(step.viewpoint.up - dot(step.viewpoint.up, eye) * eye) | ||
| 57 | pose() | ||
| 58 | } | ||
| 59 | |||
| 60 | /// Looks at the step's start frame from `eyeDirection`, far enough that a sphere of `radius` | ||
| 61 | /// about it fits the paper view at `aspect`. | ||
| 62 | var camera: Camera { | ||
| 63 | let half = Self.fieldOfView / 2 | ||
| 64 | let horizontalHalf = atan(tan(half) * aspect) | ||
| 65 | let distance = radius / sin(min(half, horizontalHalf)) | ||
| 66 | return Camera(eye: target + distance * eyeDirection, target: target, up: up, fieldOfView: Self.fieldOfView) | ||
| 67 | } | ||
| 68 | |||
| 69 | private func pose() { | ||
| 70 | positions = interpolator.positions(at: t) | ||
| 71 | meshPositions = interpolator.meshPositions(at: t) | ||
| 72 | sortClusters() | ||
| 73 | } | ||
| 74 | |||
| 75 | /// Membership and order come from one `LayerOrder.clusters` call, so both are recomputed when | ||
| 76 | /// either `t` or the view direction changes. | ||
| 77 | private func sortClusters() { | ||
| 78 | clusters = order.clusters(positions: positions, faces: model.facesVertices, viewDirection: -eyeDirection) | ||
| 79 | } | ||
| 80 | } | ||
| 81 | |||
| 82 | private func bounds(_ points: [SIMD3<Double>]) -> (SIMD3<Double>, SIMD3<Double>) { | ||
| 83 | points.dropFirst().reduce((points[0], points[0])) { (simd_min($0.0, $1), simd_max($0.1, $1)) } | ||
| 84 | } | ||
App/Sources/Info.plist added +22
| @@ -0,0 +1,22 @@ | |||
| 1 | <?xml version="1.0" encoding="UTF-8"?> | ||
| 2 | <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | ||
| 3 | <plist version="1.0"> | ||
| 4 | <dict> | ||
| 5 | <key>CFBundleDevelopmentRegion</key> | ||
| 6 | <string>$(DEVELOPMENT_LANGUAGE)</string> | ||
| 7 | <key>CFBundleExecutable</key> | ||
| 8 | <string>$(EXECUTABLE_NAME)</string> | ||
| 9 | <key>CFBundleIdentifier</key> | ||
| 10 | <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> | ||
| 11 | <key>CFBundleInfoDictionaryVersion</key> | ||
| 12 | <string>6.0</string> | ||
| 13 | <key>CFBundleName</key> | ||
| 14 | <string>$(PRODUCT_NAME)</string> | ||
| 15 | <key>CFBundlePackageType</key> | ||
| 16 | <string>APPL</string> | ||
| 17 | <key>CFBundleShortVersionString</key> | ||
| 18 | <string>$(MARKETING_VERSION)</string> | ||
| 19 | <key>CFBundleVersion</key> | ||
| 20 | <string>$(CURRENT_PROJECT_VERSION)</string> | ||
| 21 | </dict> | ||
| 22 | </plist> | ||
App/Sources/ModelListView.swift added +30
| @@ -0,0 +1,30 @@ | |||
| 1 | import FoldFormat | ||
| 2 | import Models | ||
| 3 | import SwiftUI | ||
| 4 | |||
| 5 | /// The shipped models by title. Choosing one opens it at step 1. | ||
| 6 | struct ModelListView: View { | ||
| 7 | private let models: [FoldFile] | ||
| 8 | |||
| 9 | init() { | ||
| 10 | models = (try? ModelLibrary.all()) ?? [] | ||
| 11 | } | ||
| 12 | |||
| 13 | var body: some View { | ||
| 14 | NavigationStack { | ||
| 15 | Group { | ||
| 16 | if models.isEmpty { | ||
| 17 | ContentUnavailableView("No Models", systemImage: "square.dashed") | ||
| 18 | } else { | ||
| 19 | List(models.indices, id: \.self) { i in | ||
| 20 | NavigationLink(models[i].fileTitle ?? "Untitled", value: i) | ||
| 21 | } | ||
| 22 | } | ||
| 23 | } | ||
| 24 | .navigationTitle("Models") | ||
| 25 | .navigationDestination(for: Int.self) { i in | ||
| 26 | StepView(model: models[i], step: 1) | ||
| 27 | } | ||
| 28 | } | ||
| 29 | } | ||
| 30 | } | ||
App/Sources/PaperView.swift added +60
| @@ -0,0 +1,60 @@ | |||
| 1 | import Folding | ||
| 2 | import MetalKit | ||
| 3 | import Renderer | ||
| 4 | import SwiftUI | ||
| 5 | |||
| 6 | /// The folding model, drawn by `PaperRenderer` into an `MTKView` that redraws only when its | ||
| 7 | /// inputs change. `positions` are render mesh positions, from `FoldInterpolator.meshPositions(at:)`. | ||
| 8 | struct PaperView: UIViewRepresentable { | ||
| 9 | let positions: [SIMD3<Double>] | ||
| 10 | let mesh: RenderMesh | ||
| 11 | let clusters: [CoplanarCluster] | ||
| 12 | let camera: Camera | ||
| 13 | |||
| 14 | init(positions: [SIMD3<Double>], mesh: RenderMesh, clusters: [CoplanarCluster], camera: Camera) { | ||
| 15 | self.positions = positions | ||
| 16 | self.mesh = mesh | ||
| 17 | self.clusters = clusters | ||
| 18 | self.camera = camera | ||
| 19 | } | ||
| 20 | |||
| 21 | func makeCoordinator() -> Coordinator { Coordinator() } | ||
| 22 | |||
| 23 | func makeUIView(context: Context) -> MTKView { | ||
| 24 | let view = MTKView(frame: .zero, device: context.coordinator.renderer?.device) | ||
| 25 | view.isPaused = true | ||
| 26 | view.enableSetNeedsDisplay = true | ||
| 27 | view.isOpaque = false | ||
| 28 | view.backgroundColor = .clear | ||
| 29 | view.delegate = context.coordinator | ||
| 30 | return view | ||
| 31 | } | ||
| 32 | |||
| 33 | func updateUIView(_ view: MTKView, context: Context) { | ||
| 34 | context.coordinator.paper = self | ||
| 35 | view.setNeedsDisplay() | ||
| 36 | } | ||
| 37 | |||
| 38 | @MainActor | ||
| 39 | final class Coordinator: NSObject, MTKViewDelegate { | ||
| 40 | let renderer = MTLCreateSystemDefaultDevice().flatMap { try? PaperRenderer(device: $0) } | ||
| 41 | var paper: PaperView? | ||
| 42 | |||
| 43 | func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { | ||
| 44 | view.setNeedsDisplay() | ||
| 45 | } | ||
| 46 | |||
| 47 | func draw(in view: MTKView) { | ||
| 48 | guard let renderer, let paper, let drawable = view.currentDrawable else { return } | ||
| 49 | do { | ||
| 50 | try renderer.render(positions: paper.positions, mesh: paper.mesh, clusters: paper.clusters, | ||
| 51 | camera: paper.camera, into: drawable.texture) | ||
| 52 | } catch { | ||
| 53 | return | ||
| 54 | } | ||
| 55 | guard let present = renderer.commandQueue.makeCommandBuffer() else { return } | ||
| 56 | present.present(drawable) | ||
| 57 | present.commit() | ||
| 58 | } | ||
| 59 | } | ||
| 60 | } | ||
App/Sources/StepView.swift added +64
| @@ -0,0 +1,64 @@ | |||
| 1 | import FoldFormat | ||
| 2 | import Notation | ||
| 3 | import SwiftUI | ||
| 4 | |||
| 5 | /// One step of a model: its diagram, captioned with the step's instruction, beside the folding | ||
| 6 | /// model on a regular-width screen and above it on a compact one. | ||
| 7 | struct StepView: View { | ||
| 8 | private let title: String | ||
| 9 | @State private var session: FoldSession? | ||
| 10 | @Environment(\.horizontalSizeClass) private var horizontalSizeClass | ||
| 11 | @Environment(\.verticalSizeClass) private var verticalSizeClass | ||
| 12 | |||
| 13 | /// `step` counts from 1. | ||
| 14 | init(model: FoldFile, step: Int) { | ||
| 15 | title = model.fileTitle ?? "Untitled" | ||
| 16 | _session = State(initialValue: try? FoldSession(model: model, step: step)) | ||
| 17 | } | ||
| 18 | |||
| 19 | var body: some View { | ||
| 20 | Group { | ||
| 21 | if let session { | ||
| 22 | let sideBySide = horizontalSizeClass == .regular || verticalSizeClass == .compact | ||
| 23 | let layout = sideBySide ? AnyLayout(HStackLayout(spacing: 0)) : AnyLayout(VStackLayout(spacing: 0)) | ||
| 24 | layout { | ||
| 25 | diagram(session) | ||
| 26 | paper(session) | ||
| 27 | } | ||
| 28 | } else { | ||
| 29 | ContentUnavailableView("This Model Can't Be Shown", systemImage: "exclamationmark.triangle") | ||
| 30 | } | ||
| 31 | } | ||
| 32 | .navigationTitle(title) | ||
| 33 | .navigationBarTitleDisplayMode(.inline) | ||
| 34 | } | ||
| 35 | |||
| 36 | private func diagram(_ session: FoldSession) -> some View { | ||
| 37 | VStack(alignment: .leading, spacing: 0) { | ||
| 38 | DiagramCanvas(diagram: session.diagram, style: .standard) | ||
| 39 | .accessibilityLabel("Diagram of step \(session.step.index)") | ||
| 40 | HStack(alignment: .firstTextBaseline, spacing: 12) { | ||
| 41 | Text("\(session.step.index)") | ||
| 42 | .font(.title.bold()) | ||
| 43 | .monospacedDigit() | ||
| 44 | .accessibilityIdentifier("step.index") | ||
| 45 | Text(session.step.instruction) | ||
| 46 | .fixedSize(horizontal: false, vertical: true) | ||
| 47 | .accessibilityIdentifier("diagram.caption") | ||
| 48 | } | ||
| 49 | .frame(maxWidth: .infinity, alignment: .leading) | ||
| 50 | .padding() | ||
| 51 | } | ||
| 52 | } | ||
| 53 | |||
| 54 | private func paper(_ session: FoldSession) -> some View { | ||
| 55 | PaperView(positions: session.meshPositions, mesh: session.interpolator.mesh, clusters: session.clusters, | ||
| 56 | camera: session.camera) | ||
| 57 | .onGeometryChange(for: CGSize.self) { $0.size } action: { size in | ||
| 58 | if size.height > 0 { session.aspect = size.width / size.height } | ||
| 59 | } | ||
| 60 | .accessibilityElement() | ||
| 61 | .accessibilityLabel(session.step.instruction) | ||
| 62 | .accessibilityIdentifier("fold.paper") | ||
| 63 | } | ||
| 64 | } | ||
App/UITests/StepNavigationTests.swift added +26
| @@ -0,0 +1,26 @@ | |||
| 1 | import XCTest | ||
| 2 | |||
| 3 | final class StepNavigationTests: XCTestCase { | ||
| 4 | override func setUp() { | ||
| 5 | continueAfterFailure = false | ||
| 6 | } | ||
| 7 | |||
| 8 | func testCupOpensAtStepOne() { | ||
| 9 | let app = XCUIApplication(); app.launch() | ||
| 10 | app.buttons["Cup"].tap() | ||
| 11 | XCTAssertEqual(app.staticTexts["step.index"].label, "1") | ||
| 12 | } | ||
| 13 | |||
| 14 | func testStepNeverAdvancesWithoutTheUserCompletingTheFold() { | ||
| 15 | let app = XCUIApplication(); app.launch() | ||
| 16 | app.buttons["Cup"].tap() | ||
| 17 | sleep(3) | ||
| 18 | XCTAssertEqual(app.staticTexts["step.index"].label, "1") | ||
| 19 | } | ||
| 20 | |||
| 21 | func testTheDiagramIsCaptionedWithTheStepsInstruction() { | ||
| 22 | let app = XCUIApplication(); app.launch() | ||
| 23 | app.buttons["Cup"].tap() | ||
| 24 | XCTAssertTrue(app.staticTexts["diagram.caption"].label.hasPrefix("Valley fold")) | ||
| 25 | } | ||
| 26 | } | ||
App/project.yml added +62
| @@ -0,0 +1,62 @@ | |||
| 1 | name: Fold | ||
| 2 | options: | ||
| 3 | bundleIdPrefix: sh.krz | ||
| 4 | deploymentTarget: | ||
| 5 | iOS: "26.0" | ||
| 6 | packages: | ||
| 7 | FoldKit: | ||
| 8 | path: ../Packages/FoldKit | ||
| 9 | targets: | ||
| 10 | Fold: | ||
| 11 | type: application | ||
| 12 | platform: iOS | ||
| 13 | scheme: | ||
| 14 | testTargets: [FoldUITests] | ||
| 15 | sources: | ||
| 16 | - Sources | ||
| 17 | dependencies: | ||
| 18 | - package: FoldKit | ||
| 19 | product: FoldFormat | ||
| 20 | - package: FoldKit | ||
| 21 | product: Folding | ||
| 22 | - package: FoldKit | ||
| 23 | product: Models | ||
| 24 | - package: FoldKit | ||
| 25 | product: Notation | ||
| 26 | - package: FoldKit | ||
| 27 | product: Renderer | ||
| 28 | info: | ||
| 29 | path: Sources/Info.plist | ||
| 30 | properties: | ||
| 31 | CFBundleShortVersionString: $(MARKETING_VERSION) | ||
| 32 | CFBundleVersion: $(CURRENT_PROJECT_VERSION) | ||
| 33 | settings: | ||
| 34 | base: | ||
| 35 | PRODUCT_BUNDLE_IDENTIFIER: sh.krz.fold | ||
| 36 | DEVELOPMENT_TEAM: ZCNAX3VL9D | ||
| 37 | CODE_SIGN_STYLE: Automatic | ||
| 38 | SWIFT_VERSION: "6.0" | ||
| 39 | TARGETED_DEVICE_FAMILY: "1,2" | ||
| 40 | MARKETING_VERSION: "1.0.0" | ||
| 41 | CURRENT_PROJECT_VERSION: "1" | ||
| 42 | GENERATE_INFOPLIST_FILE: YES | ||
| 43 | INFOPLIST_KEY_CFBundleDisplayName: Fold | ||
| 44 | INFOPLIST_KEY_ITSAppUsesNonExemptEncryption: NO | ||
| 45 | INFOPLIST_KEY_UILaunchScreen_Generation: YES | ||
| 46 | INFOPLIST_KEY_UIApplicationSceneManifest_Generation: YES | ||
| 47 | INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone: UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight | ||
| 48 | INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad: UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight | ||
| 49 | FoldUITests: | ||
| 50 | type: bundle.ui-testing | ||
| 51 | platform: iOS | ||
| 52 | sources: [UITests] | ||
| 53 | dependencies: | ||
| 54 | - target: Fold | ||
| 55 | settings: | ||
| 56 | base: | ||
| 57 | PRODUCT_BUNDLE_IDENTIFIER: sh.krz.fold.uitests | ||
| 58 | DEVELOPMENT_TEAM: ZCNAX3VL9D | ||
| 59 | CODE_SIGN_STYLE: Automatic | ||
| 60 | SWIFT_VERSION: "5.0" | ||
| 61 | TARGETED_DEVICE_FAMILY: "1,2" | ||
| 62 | GENERATE_INFOPLIST_FILE: YES | ||
Packages/FoldKit/Package.swift +1 −1
| @@ -18,7 +18,7 @@ let package = Package( | |||
| 18 | .target(name: "FoldFormat"), | 18 | .target(name: "FoldFormat"), |
| 19 | .target(name: "Folding", dependencies: ["FoldFormat"]), | 19 | .target(name: "Folding", dependencies: ["FoldFormat"]), |
| 20 | .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]), | 20 | .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]), |
| 21 | .target(name: "Models", dependencies: ["FoldFormat"], resources: [.copy("Resources")]), | 21 | .target(name: "Models", dependencies: ["FoldFormat"], resources: [.process("Resources")]), |
| 22 | .target(name: "Notation", dependencies: ["FoldFormat", "Folding"]), | 22 | .target(name: "Notation", dependencies: ["FoldFormat", "Folding"]), |
| 23 | .target(name: "Renderer", dependencies: ["Folding"], resources: [.copy("Shaders.metal")]), | 23 | .target(name: "Renderer", dependencies: ["Folding"], resources: [.copy("Shaders.metal")]), |
| 24 | .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]), | 24 | .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]), |
Packages/FoldKit/Sources/Models/ModelLibrary.swift +3 −2
| @@ -27,8 +27,9 @@ public enum ModelLibrary { | |||
| 27 | return try FoldFile(contentsOf: url) | 27 | return try FoldFile(contentsOf: url) |
| 28 | } | 28 | } |
| 29 | 29 | ||
| 30 | /// The resource directory the package copies in. | 30 | /// The resource bundle's directory, where the package places `Resources/`'s files. A bundle |
| 31 | /// holding a directory named `Resources` fails code signing on iOS. | ||
| 31 | private static var directory: URL { | 32 | private static var directory: URL { |
| 32 | Bundle.module.url(forResource: "Resources", withExtension: nil)! | 33 | Bundle.module.resourceURL! |
| 33 | } | 34 | } |
| 34 | } | 35 | } |
Packages/FoldKit/Sources/Renderer/PaperRenderer.swift +23 −1
| @@ -37,6 +37,10 @@ public final class PaperRenderer { | |||
| 37 | /// Per colour pixel format, the pipeline that draws colour and the one that draws depth only. | 37 | /// Per colour pixel format, the pipeline that draws colour and the one that draws depth only. |
| 38 | private var pipelines: [MTLPixelFormat: (colour: MTLRenderPipelineState, depth: MTLRenderPipelineState)] = [:] | 38 | private var pipelines: [MTLPixelFormat: (colour: MTLRenderPipelineState, depth: MTLRenderPipelineState)] = [:] |
| 39 | private var depthTexture: MTLTexture? | 39 | private var depthTexture: MTLTexture? |
| 40 | /// The vertex buffer, reused while it is large enough. | ||
| 41 | private var vertexBuffer: MTLBuffer? | ||
| 42 | /// The last frame's commands, which read `vertexBuffer`. | ||
| 43 | private var lastFrame: MTLCommandBuffer? | ||
| 40 | 44 | ||
| 41 | private struct PaperVertex { | 45 | private struct PaperVertex { |
| 42 | var position: SIMD3<Float> | 46 | var position: SIMD3<Float> |
| @@ -82,7 +86,7 @@ public final class PaperRenderer { | |||
| 82 | faceColours: [SIMD4<Float>]? = nil, into target: MTLTexture) throws { | 86 | faceColours: [SIMD4<Float>]? = nil, into target: MTLTexture) throws { |
| 83 | let (vertices, ranges) = groupedVertices(positions: positions, mesh: mesh) | 87 | let (vertices, ranges) = groupedVertices(positions: positions, mesh: mesh) |
| 84 | let pipeline = try pipelines(for: target.pixelFormat) | 88 | let pipeline = try pipelines(for: target.pixelFormat) |
| 85 | guard let buffer = device.makeBuffer(bytes: vertices, length: vertices.count * MemoryLayout<PaperVertex>.stride), | 89 | guard let buffer = vertexBuffer(holding: vertices), |
| 86 | let depth = depthTexture(width: target.width, height: target.height), | 90 | let depth = depthTexture(width: target.width, height: target.height), |
| 87 | let commands = commandQueue.makeCommandBuffer() else { throw RendererError.allocationFailed } | 91 | let commands = commandQueue.makeCommandBuffer() else { throw RendererError.allocationFailed } |
| 88 | 92 | ||
| @@ -136,6 +140,20 @@ public final class PaperRenderer { | |||
| 136 | } | 140 | } |
| 137 | encoder.endEncoding() | 141 | encoder.endEncoding() |
| 138 | commands.commit() | 142 | commands.commit() |
| 143 | lastFrame = commands | ||
| 144 | } | ||
| 145 | |||
| 146 | /// `vertexBuffer` filled with `vertices`, after the last frame has finished reading it; a new | ||
| 147 | /// one when it is too small. | ||
| 148 | private func vertexBuffer(holding vertices: [PaperVertex]) -> MTLBuffer? { | ||
| 149 | let length = vertices.count * MemoryLayout<PaperVertex>.stride | ||
| 150 | lastFrame?.waitUntilCompleted() | ||
| 151 | if (vertexBuffer?.length ?? 0) < length { | ||
| 152 | vertexBuffer = device.makeBuffer(length: length, options: .storageModeShared) | ||
| 153 | } | ||
| 154 | guard let vertexBuffer else { return nil } | ||
| 155 | memcpy(vertexBuffer.contents(), vertices, length) | ||
| 156 | return vertexBuffer | ||
| 139 | } | 157 | } |
| 140 | 158 | ||
| 141 | /// Three vertices per triangle, each with its triangle's normal, grouped by FOLD face; and | 159 | /// Three vertices per triangle, each with its triangle's normal, grouped by FOLD face; and |
| @@ -179,7 +197,11 @@ public final class PaperRenderer { | |||
| 179 | let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: width, | 197 | let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: width, |
| 180 | height: height, mipmapped: false) | 198 | height: height, mipmapped: false) |
| 181 | descriptor.usage = .renderTarget | 199 | descriptor.usage = .renderTarget |
| 200 | #if os(iOS) | ||
| 201 | descriptor.storageMode = .memoryless | ||
| 202 | #else | ||
| 182 | descriptor.storageMode = .private | 203 | descriptor.storageMode = .private |
| 204 | #endif | ||
| 183 | depthTexture = device.makeTexture(descriptor: descriptor) | 205 | depthTexture = device.makeTexture(descriptor: descriptor) |
| 184 | return depthTexture | 206 | return depthTexture |
| 185 | } | 207 | } |