// 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.importSwiftUI/// How a piece of paper was separated from the rest of it.publicenumPaperEdge: 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`.publicfunc amplitude(in scale: ThemeScale) -> CGFloat {switchself {case .cut: returnPaperShapeKnobs.paperShapeCutAmplitudecase .torn: returnPaperShapeKnobs.paperShapeTornAmplitudecase .receipt: returnPaperShapeKnobs.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)switchself {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<CGFloat> {switchself {case .torn: returnPaperShapeKnobs.paperShapeTornFeatureMin...PaperShapeKnobs.paperShapeTornFeatureMaxcase .cut, .receipt: returnPaperShapeKnobs.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)switchself {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 {switchself {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)? {switchself {case .receipt:return (depth: PaperShapeKnobs.paperShapePerforationDepth, pitch: PaperShapeKnobs.paperShapePerforationPitch)case .cut, .torn: returnnil } }/// The perforation at THIS size, for the same reason the amplitude scales.func perforation(for size: CGSize, in scale: ThemeScale) -> (depth: CGFloat, pitch: CGFloat)? {guardlet declared = perforation(in: scale) else { returnnil }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.structPaperWear {/// 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: CGFloatprivatelet wave: PaperNoiseprivatelet ripple: PaperNoiseprivatelet nicks: PaperNoiseprivatelet envelope: PaperNoise/// The octaves' weights, the envelope's floor and the nicks' power, from/// the theme's `paper_shape_*` knobs.privatelet waveWeight: Doubleprivatelet rippleWeight: Doubleprivatelet nickWeight: Doubleprivatelet nickPower: Doubleprivatelet 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.privatelet peak: Doubleinit(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.lanelet 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())returnPaperNoise(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.publicstructPaperShape: InsettableShape {publiclet edge: PaperEdgepubliclet 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.publiclet scale: ThemeScalepubliclet family: ThemeFamilyprivatevar insetBy: CGFloat = 0publicinit(edge: PaperEdge = .cut, seed: String, theme: Theme) {self.edge = edgeself.seed = seedself.scale = theme.scaleself.family = theme.family }publicfunc inset(by amount: CGFloat) -> PaperShape {var copy = self copy.insetBy += amountreturn copy }/// The four corners, clockwise from the top left — the index each one's/// seeded salt is stepped by.enumCorner: Int, CaseIterable {case topLeft, topRight, bottomRight, bottomLeft }/// The four sides, clockwise from the top — the index each one's wear is/// seeded by.enumSide: Int {case top, right, bottom, left }publicfunc path(in bounds: CGRect) -> Path {let rect = bounds.insetBy(dx: insetBy, dy: insetBy)let smallest = PaperShapeKnobs.paperShapeMinSideguard rect.width > smallest, rect.height > smallest else { returnPath(rect) }if family == .plain {let corner = min(scale.radius(for: rect.size), min(rect.width, rect.height) * 0.5)returnPath(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)iflet 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.lanelet shareMin = Double(PaperShapeKnobs.paperShapeCornerShareMin)let shareRange = Double(PaperShapeKnobs.paperShapeCornerShareRange)let a = shareMin + PaperNoise.unit(seed: seed, salt: salt) * shareRangelet 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.privatefunc walk( _ path: inoutPath, 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.paperShapeTaperRampfor step in1...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)) * taperlet x = from.x + (to.x - from.x) * unit + inward.dx * bitelet 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.privatefunc turn(_ path: inoutPath, 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.privatefunc zigzag( _ path: inoutPath, from: CGPoint, to: CGPoint, perforation: (depth: CGFloat, pitch: CGFloat) ) {let span = from.x - to.xguard span > perforation.pitch else { path.addLine(to: to)return }let teeth = max(1, Int((span / perforation.pitch).rounded()))for tooth in1...teeth {let unit = CGFloat(tooth) / CGFloat(teeth)let x = from.x - span * unitlet 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`).enumPaperShapeKnobs {staticlet paperShapeCornerCeilingMin: CGFloat = 2staticlet paperShapeCornerPull: CGFloat = 0.5staticlet paperShapeCornerShareMin: CGFloat = 0.35staticlet paperShapeCornerShareRange: CGFloat = 0.65staticlet paperShapeCutAmplitude: CGFloat = 0.4staticlet paperShapeCutAmplitudeFraction: CGFloat = 0.0035staticlet paperShapeCutAmplitudeMin: CGFloat = 0.12staticlet paperShapeCutCornerWearFraction: CGFloat = 0.03staticlet paperShapeCutCornerWearMax: CGFloat = 4staticlet paperShapeCutCornerWearMin: CGFloat = 0.8staticlet paperShapeCutFeatureMax: CGFloat = 70staticlet paperShapeCutFeatureMin: CGFloat = 34staticlet paperShapeCutStepDivisor: CGFloat = 6staticlet paperShapeCutStepMin: CGFloat = 5staticlet paperShapeEnvelopeDivisor: CGFloat = 0.42staticlet paperShapeEnvelopeFloor: CGFloat = 0.3staticlet paperShapeEnvelopeMinPoints = 2staticlet paperShapeMinSide: CGFloat = 4staticlet paperShapeNickDivisor: CGFloat = 6staticlet paperShapeNickMinPoints = 4staticlet paperShapeNickPower: CGFloat = 6staticlet paperShapeNickWeight: CGFloat = 0.5staticlet paperShapePeakShare: CGFloat = 0.95staticlet paperShapePerforationDepth: CGFloat = 4staticlet paperShapePerforationDepthFraction: CGFloat = 0.035staticlet paperShapePerforationDepthMin: CGFloat = 1.2staticlet paperShapePerforationPitch: CGFloat = 9staticlet paperShapePerforationPitchFraction: CGFloat = 0.085staticlet paperShapePerforationPitchMin: CGFloat = 6staticlet paperShapeReceiptAmplitude: CGFloat = 0.4staticlet paperShapeRippleDivisor: CGFloat = 2.6staticlet paperShapeRippleMinPoints = 3staticlet paperShapeRippleWeight: CGFloat = 0.22staticlet paperShapeTaperRamp: CGFloat = 5staticlet paperShapeTornAmplitude: CGFloat = 4staticlet paperShapeTornAmplitudeFraction: CGFloat = 0.024staticlet paperShapeTornAmplitudeMin: CGFloat = 0.9staticlet paperShapeTornCornerWearFraction: CGFloat = 0.034staticlet paperShapeTornCornerWearMax: CGFloat = 4.5staticlet paperShapeTornCornerWearMin: CGFloat = 1staticlet paperShapeTornFeatureMax: CGFloat = 40staticlet paperShapeTornFeatureMin: CGFloat = 18staticlet paperShapeTornStepDivisor: CGFloat = 24staticlet paperShapeTornStepMin: CGFloat = 1staticlet paperShapeWalkMinLength: CGFloat = 2staticlet paperShapeWalkMinSteps = 2staticlet paperShapeWaveDivisor: CGFloat = 1staticlet paperShapeWaveMinPoints = 2staticlet paperShapeWaveWeight: CGFloat = 0.55}