// The outline of a piece of paper. Three edges, one shape, no picture. // // A rounded rectangle is a rounded rectangle: put nine of them on a screen and // the eye reads a table. What makes the reference pictures read as PAPER is that // every sheet's edge is slightly its own — a guillotine leaves straight sides // and worn corners, a torn sheet leaves a deckle, a receipt leaves a // perforation. So the outline is a path whose edges and corners are perturbed by // `PaperNoise`, seeded by the record's id: deterministic, so the same record is // the same sheet for ever, and different, so no two sheets on a screen are the // same sheet. // // THE TWO MISTAKES THIS FILE HAS ALREADY MADE, both found by looking at a // screenshot beside the photographs, and both worth writing down: // // 1. A SINGLE OCTAVE OF NOISE IS A SCALLOP. One noise ring sampled along an // edge gives features of one size at one spacing, and twelve cards wearing // it read as twelve doilies — the same frilled outline on every sheet. A // real deckle is LONG soft waves (18–40 points between features) with a // few small nicks in them, so the edge is three octaves: a long wave, a // ripple at a third of its length, and a nick ring raised to a high power // so it is flat almost everywhere and bites hard in one or two places. Over // all three sits an ENVELOPE — a slower ring still — so the tear is deep // along one stretch and nearly flush along another, which is what stops two // seeds looking like the same edge shifted along. // // 2. A CUT EDGE IS STRAIGHT. A guillotine does not wander: an index card's // sides are straight to well under half a point, and ALL its visible wear // is at the four corners, which are rounded, softened and not quite the // same as each other. So `.cut` keeps a whisper of drift (≤0.4pt) on its // sides and spends its wear on the corners: each corner takes its own // seeded pair of distances along the two sides it joins, so the curve is // asymmetric, and its control point is pulled inward so the corner reads // as worn rather than as a drawn radius. // // THE WEAR ONLY EVER GOES INWARD. A sheet never exceeds the frame it was given — // a nibble is paper taken away, not paper added — so the path is always inside // its rect, laying out and clipping like any other shape. // // The `.receipt` bottom is a TRIANGULAR WAVE, not noise: a perforation is // machine-made and regular, and drawing it as wobble is the "too skeuomorphic" // failure the language rules name. import SwiftUI /// How a piece of paper was separated from the rest of it. public enum PaperEdge: String, CaseIterable, Sendable { /// Cut: an index card, a note, a printed sheet. Straight sides, worn /// corners. **This is the default a screen should reach for** — notes and /// todo cards are cut. case cut /// Torn: a slip off a pad, the decide queue's card, a summary. A deckle. case torn /// A receipt or a stub: cut on three sides, perforated along the bottom. case receipt /// The deepest a nibble may EVER bite, in points — the ceiling, and the /// bound `PaperShapeTests` holds. The theme's `paper_shape_*_amplitude`. public func amplitude(in scale: ThemeScale) -> CGFloat { switch self { case .cut: return PaperShapeKnobs.paperShapeCutAmplitude case .torn: return PaperShapeKnobs.paperShapeTornAmplitude case .receipt: return PaperShapeKnobs.paperShapeReceiptAmplitude } } /// The deepest a nibble bites into a sheet of THIS size: a fraction of the /// sheet's shorter side, floored so a thumbnail still shows an edge and /// capped at `amplitude` so a full page does not grow a frill. /// /// A fraction rather than a constant, because the constant was the first /// version of this and it was wrong in the way the caps' rule warns about: a /// 4pt deckle on a 60pt-tall card is a doily, and the same 4pt on a /// 700pt sheet is invisible. An object owns its geometry as fractions of its /// own size. func amplitude(for size: CGSize, in scale: ThemeScale) -> CGFloat { let shorter = min(size.width, size.height) let ceiling = amplitude(in: scale) switch self { case .cut, .receipt: return min( ceiling, max(PaperShapeKnobs.paperShapeCutAmplitudeMin, shorter * PaperShapeKnobs.paperShapeCutAmplitudeFraction)) case .torn: return min( ceiling, max(PaperShapeKnobs.paperShapeTornAmplitudeMin, shorter * PaperShapeKnobs.paperShapeTornAmplitudeFraction)) } } /// How far apart the edge's features are, in points — the long octave's /// wavelength, picked inside this range by the seed so two sheets do not /// wave at the same rate. /// /// A tear's features are LONG: the reference pictures show two or three /// waves down a card's side, not twenty. A cut edge's "features" are longer /// still, which is another way of saying it is straight. func featureSpan(in scale: ThemeScale) -> ClosedRange { switch self { case .torn: return PaperShapeKnobs.paperShapeTornFeatureMin...PaperShapeKnobs.paperShapeTornFeatureMax case .cut, .receipt: return PaperShapeKnobs.paperShapeCutFeatureMin...PaperShapeKnobs.paperShapeCutFeatureMax } } /// How deep the corners are worn, at this size. The wear a guillotine and a /// pocket leave: 2–4 points on a card, less on a thumbnail, never more than /// a corner's worth on a page. func cornerWear(for size: CGSize, in scale: ThemeScale) -> CGFloat { let shorter = min(size.width, size.height) switch self { case .cut, .receipt: return min( PaperShapeKnobs.paperShapeCutCornerWearMax, max(PaperShapeKnobs.paperShapeCutCornerWearMin, shorter * PaperShapeKnobs.paperShapeCutCornerWearFraction)) case .torn: return min( PaperShapeKnobs.paperShapeTornCornerWearMax, max(PaperShapeKnobs.paperShapeTornCornerWearMin, shorter * PaperShapeKnobs.paperShapeTornCornerWearFraction)) } } /// How far apart the samples along an edge are laid, given the long /// octave's wavelength. A deckle needs a far busier walk than a cut edge, /// which is nearly straight and can be drawn in long segments. func sampleStep(wavelength: CGFloat, in scale: ThemeScale) -> CGFloat { switch self { case .torn: return max(PaperShapeKnobs.paperShapeTornStepMin, wavelength / PaperShapeKnobs.paperShapeTornStepDivisor) case .cut, .receipt: return max(PaperShapeKnobs.paperShapeCutStepMin, wavelength / PaperShapeKnobs.paperShapeCutStepDivisor) } } /// The perforation's tooth depth and pitch, in points. Only `.receipt` /// has one. func perforation(in scale: ThemeScale) -> (depth: CGFloat, pitch: CGFloat)? { switch self { case .receipt: return (depth: PaperShapeKnobs.paperShapePerforationDepth, pitch: PaperShapeKnobs.paperShapePerforationPitch) case .cut, .torn: return nil } } /// The perforation at THIS size, for the same reason the amplitude scales. func perforation(for size: CGSize, in scale: ThemeScale) -> (depth: CGFloat, pitch: CGFloat)? { guard let declared = perforation(in: scale) else { return nil } let shorter = min(size.width, size.height) return ( depth: min( declared.depth, max(PaperShapeKnobs.paperShapePerforationDepthMin, shorter * PaperShapeKnobs.paperShapePerforationDepthFraction)), pitch: max( PaperShapeKnobs.paperShapePerforationPitchMin, min(declared.pitch, shorter * PaperShapeKnobs.paperShapePerforationPitchFraction)) ) } } /// One side's wear, as a function of how far along it you are. /// /// Three octaves and an envelope, all seeded off the sheet's id and the side's /// index. Its own type because the arithmetic is the design and belongs /// somewhere a test can call it without drawing anything. struct PaperWear { /// The deepest this side may bite — the ceiling the profile is scaled to. let amplitude: CGFloat /// How far apart to lay samples along the side. let step: CGFloat /// The long octave's wavelength, in points. let wavelength: CGFloat private let wave: PaperNoise private let ripple: PaperNoise private let nicks: PaperNoise private let envelope: PaperNoise /// The octaves' weights, the envelope's floor and the nicks' power, from /// the theme's `paper_shape_*` knobs. private let waveWeight: Double private let rippleWeight: Double private let nickWeight: Double private let nickPower: Double private let envelopeFloor: Double /// What the three octaves and the envelope reach TOGETHER in practice — /// a shade under the arithmetic maximum (`paper_shape_peak_share` of the /// three weights' sum), because three independent rings and an envelope /// never all peak at the same point of one edge. The profile is divided /// by it, so the amplitude stays a true ceiling (the `min(1,…)` below /// takes the once-in-a-while overshoot) without every tear being drawn at /// half the depth it was given. private let peak: Double init(edge: PaperEdge, seed: String, side: Int, length: CGFloat, size: CGSize, scale: ThemeScale) { amplitude = edge.amplitude(for: size, in: scale) let salt = PaperSalt.wave &+ UInt64(side) &* SeededNoise.lane let span = edge.featureSpan(in: scale) // A local, not the property: the ring builder below must capture a // value, or it captures `self` before `self` is initialised. let lambda = span.lowerBound + CGFloat(PaperNoise.unit(seed: seed, salt: salt)) * (span.upperBound - span.lowerBound) wavelength = lambda step = edge.sampleStep(wavelength: lambda, in: scale) // A ring per octave, its control-point count set so ONE walk of the // ring is one pass along this side at that octave's wavelength. func ring(_ divisor: CGFloat, _ minimum: Int, _ pepper: UInt64) -> PaperNoise { let features = Int((length / (lambda / divisor)).rounded()) return PaperNoise(seed: seed, salt: salt ^ pepper, count: max(minimum, features)) } wave = ring( PaperShapeKnobs.paperShapeWaveDivisor, PaperShapeKnobs.paperShapeWaveMinPoints, PaperSalt.longWave) ripple = ring( PaperShapeKnobs.paperShapeRippleDivisor, PaperShapeKnobs.paperShapeRippleMinPoints, PaperSalt.ripple) nicks = ring( PaperShapeKnobs.paperShapeNickDivisor, PaperShapeKnobs.paperShapeNickMinPoints, PaperSalt.nicks) envelope = ring( PaperShapeKnobs.paperShapeEnvelopeDivisor, PaperShapeKnobs.paperShapeEnvelopeMinPoints, PaperSalt.envelope) waveWeight = Double(PaperShapeKnobs.paperShapeWaveWeight) rippleWeight = Double(PaperShapeKnobs.paperShapeRippleWeight) nickWeight = Double(PaperShapeKnobs.paperShapeNickWeight) nickPower = Double(PaperShapeKnobs.paperShapeNickPower) envelopeFloor = Double(PaperShapeKnobs.paperShapeEnvelopeFloor) peak = Double(PaperShapeKnobs.paperShapePeakShare) * (waveWeight + rippleWeight + nickWeight) } /// How far in the edge has been eaten at `unit` (0…1 along the side). func bite(at unit: Double) -> CGFloat { // `paper_shape_envelope_floor`…+1: the stretch of edge that is nearly // flush, and the stretch that is deeply torn. let strength = envelopeFloor + envelope.value(at: unit) let raw = strength * (wave.value(at: unit) * waveWeight + ripple.value(at: unit) * rippleWeight // The nicks: flat almost everywhere, hard in one or two places. + pow(nicks.value(at: unit), nickPower) * nickWeight) return amplitude * CGFloat(min(1, raw / peak)) } } /// The outline itself. /// /// `InsettableShape`, so a caller can `strokeBorder` it: a sheet's rim is drawn /// INSIDE its own outline, and a centred stroke would put half the rim outside /// the frame the sheet was given. public struct PaperShape: InsettableShape { public let edge: PaperEdge public let seed: String /// The theme's corner, and whether its family cuts paper at all — a /// shape cannot read the environment, so the view that cuts it hands the /// theme over. A flat family's object is a plain rounded rectangle at the /// theme's radius: no wear, no deckle, no tear. public let scale: ThemeScale public let family: ThemeFamily private var insetBy: CGFloat = 0 public init(edge: PaperEdge = .cut, seed: String, theme: Theme) { self.edge = edge self.seed = seed self.scale = theme.scale self.family = theme.family } public func inset(by amount: CGFloat) -> PaperShape { var copy = self copy.insetBy += amount return copy } /// The four corners, clockwise from the top left — the index each one's /// seeded salt is stepped by. enum Corner: Int, CaseIterable { case topLeft, topRight, bottomRight, bottomLeft } /// The four sides, clockwise from the top — the index each one's wear is /// seeded by. enum Side: Int { case top, right, bottom, left } public func path(in bounds: CGRect) -> Path { let rect = bounds.insetBy(dx: insetBy, dy: insetBy) let smallest = PaperShapeKnobs.paperShapeMinSide guard rect.width > smallest, rect.height > smallest else { return Path(rect) } if family == .plain { let corner = min(scale.radius(for: rect.size), min(rect.width, rect.height) * 0.5) return Path(roundedRect: rect, cornerRadius: corner, style: .continuous) } // The four corners, clockwise from the top left. `arriving` is measured // along the side that reaches the corner, `leaving` along the side that // starts at it — two different numbers, which is what makes a worn // corner read as worn rather than as a radius. let topLeft = corner(at: Corner.topLeft.rawValue, rect: rect) let topRight = corner(at: Corner.topRight.rawValue, rect: rect) let bottomRight = corner(at: Corner.bottomRight.rawValue, rect: rect) let bottomLeft = corner(at: Corner.bottomLeft.rawValue, rect: rect) var path = Path() let start = CGPoint(x: rect.minX + topLeft.leaving, y: rect.minY) path.move(to: start) // Top: left to right, biting DOWN. walk( &path, from: start, to: CGPoint(x: rect.maxX - topRight.arriving, y: rect.minY), inward: CGVector(dx: 0, dy: 1), side: Side.top.rawValue, size: rect.size ) turn( &path, at: CGPoint(x: rect.maxX, y: rect.minY), pull: CGVector(dx: -topRight.pull, dy: topRight.pull), to: CGPoint(x: rect.maxX, y: rect.minY + topRight.leaving) ) // Right: top to bottom, biting LEFT. walk( &path, from: CGPoint(x: rect.maxX, y: rect.minY + topRight.leaving), to: CGPoint(x: rect.maxX, y: rect.maxY - bottomRight.arriving), inward: CGVector(dx: -1, dy: 0), side: Side.right.rawValue, size: rect.size ) turn( &path, at: CGPoint(x: rect.maxX, y: rect.maxY), pull: CGVector(dx: -bottomRight.pull, dy: -bottomRight.pull), to: CGPoint(x: rect.maxX - bottomRight.leaving, y: rect.maxY) ) // Bottom: right to left, biting UP — or the perforation. let bottomStart = CGPoint(x: rect.maxX - bottomRight.leaving, y: rect.maxY) let bottomEnd = CGPoint(x: rect.minX + bottomLeft.arriving, y: rect.maxY) if let perforation = edge.perforation(for: rect.size, in: scale) { zigzag(&path, from: bottomStart, to: bottomEnd, perforation: perforation) } else { walk( &path, from: bottomStart, to: bottomEnd, inward: CGVector(dx: 0, dy: -1), side: Side.bottom.rawValue, size: rect.size ) } turn( &path, at: CGPoint(x: rect.minX, y: rect.maxY), pull: CGVector(dx: bottomLeft.pull, dy: -bottomLeft.pull), to: CGPoint(x: rect.minX, y: rect.maxY - bottomLeft.leaving) ) // Left: bottom to top, biting RIGHT. walk( &path, from: CGPoint(x: rect.minX, y: rect.maxY - bottomLeft.leaving), to: CGPoint(x: rect.minX, y: rect.minY + topLeft.arriving), inward: CGVector(dx: 1, dy: 0), side: Side.left.rawValue, size: rect.size ) turn( &path, at: CGPoint(x: rect.minX, y: rect.minY), pull: CGVector(dx: topLeft.pull, dy: topLeft.pull), to: start ) path.closeSubpath() return path } /// One corner's two distances and how far its control point is pulled in. /// /// `index` is clockwise from the top left. Both distances are the shape's /// radius plus a seeded share of the corner's wear, so no two corners of a /// sheet are the same and no two sheets wear the same four. func corner(at index: Int, rect: CGRect) -> (arriving: CGFloat, leaving: CGFloat, pull: CGFloat) { let radius = scale.radius(for: rect.size) let wear = edge.cornerWear(for: rect.size, in: scale) let salt = PaperSalt.corner &+ UInt64(index) &* SeededNoise.lane let shareMin = Double(PaperShapeKnobs.paperShapeCornerShareMin) let shareRange = Double(PaperShapeKnobs.paperShapeCornerShareRange) let a = shareMin + PaperNoise.unit(seed: seed, salt: salt) * shareRange let b = shareMin + PaperNoise.unit(seed: seed, salt: salt ^ PaperSalt.cornerLeaving) * shareRange // Never more than a side can spare, or two corners would meet in the // middle of a short edge and the walk between them would run backwards. let ceiling = max(PaperShapeKnobs.paperShapeCornerCeilingMin, min(rect.width, rect.height) * 0.5 - 1) return ( arriving: min(ceiling, radius + wear * CGFloat(a)), leaving: min(ceiling, radius + wear * CGFloat(b)), pull: wear * PaperShapeKnobs.paperShapeCornerPull ) } /// One side, sampled and nibbled inward. private func walk( _ path: inout Path, from: CGPoint, to: CGPoint, inward: CGVector, side: Int, size: CGSize ) { let length = hypot(to.x - from.x, to.y - from.y) guard length > PaperShapeKnobs.paperShapeWalkMinLength else { path.addLine(to: to) return } let wear = PaperWear(edge: edge, seed: seed, side: side, length: length, size: size, scale: scale) let steps = max(PaperShapeKnobs.paperShapeWalkMinSteps, Int((length / wear.step).rounded())) let ramp = PaperShapeKnobs.paperShapeTaperRamp for step in 1...steps { let unit = CGFloat(step) / CGFloat(steps) // The ends are eased back to the corner points, or a sheet's // corners would drift and the curves would not meet the sides. let taper = min(1, min(unit, 1 - unit) * ramp) let bite = wear.bite(at: Double(unit)) * taper let x = from.x + (to.x - from.x) * unit + inward.dx * bite let y = from.y + (to.y - from.y) * unit + inward.dy * bite path.addLine(to: CGPoint(x: x, y: y)) } } /// A corner: a quadratic whose control point is the rectangle's own corner, /// pulled inward by the wear. Pulling it in is what turns a drawn radius /// into a corner something has rubbed against. private func turn(_ path: inout Path, at rectCorner: CGPoint, pull: CGVector, to: CGPoint) { path.addQuadCurve( to: to, control: CGPoint(x: rectCorner.x + pull.dx, y: rectCorner.y + pull.dy) ) } /// The perforation: a regular triangular wave, right to left. private func zigzag( _ path: inout Path, from: CGPoint, to: CGPoint, perforation: (depth: CGFloat, pitch: CGFloat) ) { let span = from.x - to.x guard span > perforation.pitch else { path.addLine(to: to) return } let teeth = max(1, Int((span / perforation.pitch).rounded())) for tooth in 1...teeth { let unit = CGFloat(tooth) / CGFloat(teeth) let x = from.x - span * unit let peak = CGPoint( x: x + span / CGFloat(teeth) * 0.5, y: from.y - perforation.depth ) path.addLine(to: peak) path.addLine(to: CGPoint(x: x, y: from.y)) } path.addLine(to: to) } } /// The sizes, counts and timings PaperShape draws with: Swift's own, beside /// their reader — a theme sets only its tokens (`scale.tokens`). enum PaperShapeKnobs { static let paperShapeCornerCeilingMin: CGFloat = 2 static let paperShapeCornerPull: CGFloat = 0.5 static let paperShapeCornerShareMin: CGFloat = 0.35 static let paperShapeCornerShareRange: CGFloat = 0.65 static let paperShapeCutAmplitude: CGFloat = 0.4 static let paperShapeCutAmplitudeFraction: CGFloat = 0.0035 static let paperShapeCutAmplitudeMin: CGFloat = 0.12 static let paperShapeCutCornerWearFraction: CGFloat = 0.03 static let paperShapeCutCornerWearMax: CGFloat = 4 static let paperShapeCutCornerWearMin: CGFloat = 0.8 static let paperShapeCutFeatureMax: CGFloat = 70 static let paperShapeCutFeatureMin: CGFloat = 34 static let paperShapeCutStepDivisor: CGFloat = 6 static let paperShapeCutStepMin: CGFloat = 5 static let paperShapeEnvelopeDivisor: CGFloat = 0.42 static let paperShapeEnvelopeFloor: CGFloat = 0.3 static let paperShapeEnvelopeMinPoints = 2 static let paperShapeMinSide: CGFloat = 4 static let paperShapeNickDivisor: CGFloat = 6 static let paperShapeNickMinPoints = 4 static let paperShapeNickPower: CGFloat = 6 static let paperShapeNickWeight: CGFloat = 0.5 static let paperShapePeakShare: CGFloat = 0.95 static let paperShapePerforationDepth: CGFloat = 4 static let paperShapePerforationDepthFraction: CGFloat = 0.035 static let paperShapePerforationDepthMin: CGFloat = 1.2 static let paperShapePerforationPitch: CGFloat = 9 static let paperShapePerforationPitchFraction: CGFloat = 0.085 static let paperShapePerforationPitchMin: CGFloat = 6 static let paperShapeReceiptAmplitude: CGFloat = 0.4 static let paperShapeRippleDivisor: CGFloat = 2.6 static let paperShapeRippleMinPoints = 3 static let paperShapeRippleWeight: CGFloat = 0.22 static let paperShapeTaperRamp: CGFloat = 5 static let paperShapeTornAmplitude: CGFloat = 4 static let paperShapeTornAmplitudeFraction: CGFloat = 0.024 static let paperShapeTornAmplitudeMin: CGFloat = 0.9 static let paperShapeTornCornerWearFraction: CGFloat = 0.034 static let paperShapeTornCornerWearMax: CGFloat = 4.5 static let paperShapeTornCornerWearMin: CGFloat = 1 static let paperShapeTornFeatureMax: CGFloat = 40 static let paperShapeTornFeatureMin: CGFloat = 18 static let paperShapeTornStepDivisor: CGFloat = 24 static let paperShapeTornStepMin: CGFloat = 1 static let paperShapeWalkMinLength: CGFloat = 2 static let paperShapeWalkMinSteps = 2 static let paperShapeWaveDivisor: CGFloat = 1 static let paperShapeWaveMinPoints = 2 static let paperShapeWaveWeight: CGFloat = 0.55 }