Commit e36f7091df
Verified · cmc
Layout: unified · split
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +6 −183
| @@ -1,5 +1,4 @@ | |||
| 1 | import CoreGraphics | 1 | import CoreGraphics |
| 2 | import CoreText | ||
| 3 | import Foundation | 2 | import Foundation |
| 4 | import FoldCompiler | 3 | import FoldCompiler |
| 5 | import FoldFormat | 4 | import FoldFormat |
| @@ -537,199 +536,23 @@ public func segmentLength(_ segment: (SIMD2<Double>, SIMD2<Double>)) -> Double { | |||
| 537 | 536 | ||
| 538 | /// The canvas is square, this many pixels a side, white. | 537 | /// The canvas is square, this many pixels a side, white. |
| 539 | private let canvasSide = 480 | 538 | private let canvasSide = 480 |
| 540 | /// The model and its arrows fill the canvas inside these margins; the turn-over and rotate | ||
| 541 | /// symbols sit in the bottom one. | ||
| 542 | private let sideMargin = 48.0, bottomMargin = 96.0 | ||
| 543 | 539 | ||
| 544 | /// `diagram` drawn with `DiagramStyle.standard`, the model and its arrows fitted to the canvas. | 540 | /// `diagram` drawn by `drawDiagram` with `DiagramStyle.standard` on a white canvas. |
| 545 | public func render(_ diagram: Diagram) -> CGImage { | 541 | public func render(_ diagram: Diagram) -> CGImage { |
| 546 | let style = DiagramStyle.standard | ||
| 547 | let side = Double(canvasSide) | 542 | let side = Double(canvasSide) |
| 548 | let context = CGContext(data: nil, width: canvasSide, height: canvasSide, bitsPerComponent: 8, bytesPerRow: 0, | 543 | let context = CGContext(data: nil, width: canvasSide, height: canvasSide, bitsPerComponent: 8, bytesPerRow: 0, |
| 549 | space: CGColorSpace(name: CGColorSpace.sRGB)!, | 544 | space: CGColorSpace(name: CGColorSpace.sRGB)!, |
| 550 | bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! | 545 | bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! |
| 551 | context.setFillColor(gray: 1, alpha: 1) | 546 | context.setFillColor(gray: 1, alpha: 1) |
| 552 | context.fill(CGRect(x: 0, y: 0, width: side, height: side)) | 547 | context.fill(CGRect(x: 0, y: 0, width: side, height: side)) |
| 553 | 548 | drawDiagram(diagram, style: .standard, in: context, size: CGSize(width: side, height: side)) | |
| 554 | var points = diagram.edges.flatMap { [$0.from, $0.to] } | ||
| 555 | for arrow in diagram.arrows { | ||
| 556 | switch arrow { | ||
| 557 | case let .valleyFold(from, over, to), let .mountainFold(from, over, to), let .foldAndUnfold(from, over, to, _): | ||
| 558 | points += [from, over, to] | ||
| 559 | case let .technique(_, at, toward): | ||
| 560 | points += [at, toward] | ||
| 561 | case .turnOver, .rotate, .repeatMark: | ||
| 562 | break | ||
| 563 | } | ||
| 564 | } | ||
| 565 | let low = points.reduce(points.first ?? .zero, simd_min) | ||
| 566 | let high = points.reduce(points.first ?? .zero, simd_max) | ||
| 567 | let area = CGRect(x: sideMargin, y: bottomMargin, width: side - 2 * sideMargin, height: side - bottomMargin - sideMargin) | ||
| 568 | let extent = simd_max(high - low, SIMD2(repeating: 1e-9)) | ||
| 569 | let scale = min(area.width / extent.x, area.height / extent.y) | ||
| 570 | let offset = SIMD2(area.midX, area.midY) - scale * (low + high) / 2 | ||
| 571 | func pixel(_ p: SIMD2<Double>) -> CGPoint { | ||
| 572 | let q = offset + scale * p | ||
| 573 | return CGPoint(x: q.x, y: q.y) | ||
| 574 | } | ||
| 575 | |||
| 576 | context.setLineJoin(.round) | ||
| 577 | let layers: [(DiagramLine, Double, Double, [Double])] = [ | ||
| 578 | (.light, style.lightWidth, style.lightGrey, []), | ||
| 579 | (.solid, style.outlineWidth, 0, []), | ||
| 580 | (.dashed, style.creaseWidth, 0, style.valleyDash), | ||
| 581 | (.dashDot, style.creaseWidth, 0, style.mountainDash), | ||
| 582 | ] | ||
| 583 | for (line, width, grey, dash) in layers { | ||
| 584 | context.setStrokeColor(gray: grey, alpha: 1) | ||
| 585 | context.setLineWidth(width) | ||
| 586 | context.setLineCap(dash.isEmpty ? .round : .butt) | ||
| 587 | context.setLineDash(phase: 0, lengths: dash.map { CGFloat($0) }) | ||
| 588 | for edge in diagram.edges where edge.style == line { | ||
| 589 | context.move(to: pixel(edge.from)) | ||
| 590 | context.addLine(to: pixel(edge.to)) | ||
| 591 | } | ||
| 592 | context.strokePath() | ||
| 593 | } | ||
| 594 | context.setLineDash(phase: 0, lengths: []) | ||
| 595 | context.setLineCap(.round) | ||
| 596 | context.setStrokeColor(gray: 0, alpha: 1) | ||
| 597 | context.setLineWidth(style.arrowWidth) | ||
| 598 | |||
| 599 | let repeated = diagram.arrows.contains { if case .repeatMark = $0 { true } else { false } } | ||
| 600 | let symbolCentre = SIMD2(side / 2, bottomMargin / 2) | ||
| 601 | for arrow in diagram.arrows { | ||
| 602 | switch arrow { | ||
| 603 | case let .valleyFold(from, over, to): | ||
| 604 | drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .filled, returnHead: false, tick: repeated) | ||
| 605 | case let .mountainFold(from, over, to): | ||
| 606 | drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .hollowHalf, returnHead: false, tick: repeated) | ||
| 607 | case let .foldAndUnfold(from, over, to, mountain): | ||
| 608 | drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: mountain ? .hollowHalf : .filled, | ||
| 609 | returnHead: true, tick: repeated) | ||
| 610 | case let .technique(technique, at, toward): | ||
| 611 | let tip = vector(pixel(at)), direction = normalize(vector(pixel(toward)) - tip) | ||
| 612 | if technique == .petal { | ||
| 613 | let tail = tip - style.symbolSize * 1.5 * direction | ||
| 614 | let over = (tip + tail) / 2 + 0.3 * SIMD2(direction.y, -direction.x) * style.symbolSize * 1.5 | ||
| 615 | drawFoldArrow(context, style, point(tail), point(over), point(tip), head: .filled, returnHead: false, | ||
| 616 | tick: repeated) | ||
| 617 | } else { | ||
| 618 | drawPushArrow(context, style, tip: tip, direction: direction) | ||
| 619 | } | ||
| 620 | case let .turnOver(axis): | ||
| 621 | drawTurnOver(context, style, centre: symbolCentre, vertical: axis == .vertical) | ||
| 622 | case let .rotate(degrees): | ||
| 623 | drawRotate(context, style, centre: symbolCentre, degrees: degrees) | ||
| 624 | case .repeatMark: | ||
| 625 | break | ||
| 626 | } | ||
| 627 | } | ||
| 628 | return context.makeImage()! | 549 | return context.makeImage()! |
| 629 | } | 550 | } |
| 630 | 551 | ||
| 631 | private enum Head { case filled, hollowHalf, hollowFull } | 552 | /// The number of the image's pixels darker than mid-grey in any channel. |
| 632 | 553 | public func inkedPixels(_ image: CGImage) -> Int { | |
| 633 | private func vector(_ p: CGPoint) -> SIMD2<Double> { SIMD2(p.x, p.y) } | 554 | let bytes = rgba(image) |
| 634 | private func point(_ v: SIMD2<Double>) -> CGPoint { CGPoint(x: v.x, y: v.y) } | 555 | return (0..<(image.width * image.height)).count { p in (0..<3).contains { bytes[4 * p + $0] < 128 } } |
| 635 | |||
| 636 | /// A quadratic arc from `from` through `over` to `to`, its head at `to`; with `returnHead` a | ||
| 637 | /// hollow head at `from` pointing back; with `tick` a stroke across the shaft near its tail. | ||
| 638 | private func drawFoldArrow(_ context: CGContext, _ style: DiagramStyle, _ from: CGPoint, _ over: CGPoint, _ to: CGPoint, | ||
| 639 | head: Head, returnHead: Bool, tick: Bool) { | ||
| 640 | let a = vector(from), m = vector(over), b = vector(to) | ||
| 641 | let control = 2 * m - (a + b) / 2 | ||
| 642 | context.move(to: from) | ||
| 643 | context.addQuadCurve(to: to, control: point(control)) | ||
| 644 | context.strokePath() | ||
| 645 | // the barb of a half head goes on the outside of the arc | ||
| 646 | let outside = m - (a + b) / 2 | ||
| 647 | drawHead(context, style, head, tip: b, direction: normalize(b - control), outside: outside) | ||
| 648 | if returnHead { | ||
| 649 | drawHead(context, style, .hollowFull, tip: a, direction: normalize(a - control), outside: outside) | ||
| 650 | } | ||
| 651 | if tick { | ||
| 652 | let t = 0.25 | ||
| 653 | let p = (1 - t) * (1 - t) * a + 2 * t * (1 - t) * control + t * t * b | ||
| 654 | let tangent = normalize(2 * (1 - t) * (control - a) + 2 * t * (b - control)) | ||
| 655 | let across = SIMD2(-tangent.y, tangent.x) * style.headLength / 2 | ||
| 656 | context.move(to: point(p - across)) | ||
| 657 | context.addLine(to: point(p + across)) | ||
| 658 | context.strokePath() | ||
| 659 | } | ||
| 660 | } | ||
| 661 | |||
| 662 | private func drawHead(_ context: CGContext, _ style: DiagramStyle, _ head: Head, tip: SIMD2<Double>, | ||
| 663 | direction: SIMD2<Double>, outside: SIMD2<Double>) { | ||
| 664 | let back = tip - style.headLength * direction | ||
| 665 | var across = SIMD2(-direction.y, direction.x) * style.headWidth / 2 | ||
| 666 | if dot(across, outside) < 0 { across = -across } | ||
| 667 | let corners: [SIMD2<Double>] | ||
| 668 | switch head { | ||
| 669 | case .filled, .hollowFull: corners = [tip, back + across, back - across] | ||
| 670 | case .hollowHalf: corners = [tip, back + 2 * across, back] | ||
| 671 | } | ||
| 672 | context.addLines(between: corners.map(point)) | ||
| 673 | context.closePath() | ||
| 674 | context.setFillColor(gray: head == .filled ? 0 : 1, alpha: 1) | ||
| 675 | context.drawPath(using: .fillStroke) | ||
| 676 | } | ||
| 677 | |||
| 678 | /// The hollow push arrow, its tip at `tip`, with a notched tail. | ||
| 679 | private func drawPushArrow(_ context: CGContext, _ style: DiagramStyle, tip: SIMD2<Double>, direction: SIMD2<Double>) { | ||
| 680 | let s = style.symbolSize | ||
| 681 | let outline: [SIMD2<Double>] = [ | ||
| 682 | SIMD2(0, 0), SIMD2(-0.36, 0.3), SIMD2(-0.36, 0.12), SIMD2(-1, 0.12), | ||
| 683 | SIMD2(-0.86, 0), SIMD2(-1, -0.12), SIMD2(-0.36, -0.12), SIMD2(-0.36, -0.3), | ||
| 684 | ] | ||
| 685 | let across = SIMD2(-direction.y, direction.x) | ||
| 686 | context.addLines(between: outline.map { point(tip + s * ($0.x * direction + $0.y * across)) }) | ||
| 687 | context.closePath() | ||
| 688 | context.setFillColor(gray: 1, alpha: 1) | ||
| 689 | context.drawPath(using: .fillStroke) | ||
| 690 | } | ||
| 691 | |||
| 692 | /// The loop-the-loop arrow: left to right for a turn about the vertical axis, bottom to top about | ||
| 693 | /// the horizontal. | ||
| 694 | private func drawTurnOver(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2<Double>, vertical: Bool) { | ||
| 695 | // a prolate cycloid over one period, its loop above the line of travel, between straight tails | ||
| 696 | let a = style.symbolSize / (3 * .pi), b = 2 * a | ||
| 697 | let loop = (0...64).map { i -> SIMD2<Double> in | ||
| 698 | let u = -Double.pi + 2 * .pi * Double(i) / 64 | ||
| 699 | return SIMD2(a * u - b * sin(u), b * cos(u)) | ||
| 700 | } | ||
| 701 | let tail = SIMD2(style.symbolSize / 4, 0) | ||
| 702 | let path = [loop[0] - tail] + loop + [loop[64] + tail] | ||
| 703 | let place = { (p: SIMD2<Double>) in centre + (vertical ? p : SIMD2(-p.y, p.x)) } | ||
| 704 | context.addLines(between: path.map { point(place($0)) }) | ||
| 705 | context.strokePath() | ||
| 706 | let tip = place(path[path.count - 1]) | ||
| 707 | drawHead(context, style, .filled, tip: tip, direction: normalize(tip - place(loop[64])), outside: SIMD2(0, 1)) | ||
| 708 | } | ||
| 709 | |||
| 710 | /// Two arcs around a circle, counterclockwise for positive `degrees`, with the amount at the centre. | ||
| 711 | private func drawRotate(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2<Double>, degrees: Double) { | ||
| 712 | let r = style.symbolSize / 2 | ||
| 713 | let turn = degrees >= 0 ? 1.0 : -1.0 | ||
| 714 | let headAngle = style.headLength / r | ||
| 715 | for start in [Double.pi * 0.6, Double.pi * 1.6] { | ||
| 716 | let end = start + turn * Double.pi * 0.75, back = end - turn * headAngle | ||
| 717 | context.addArc(center: point(centre), radius: r, startAngle: start, endAngle: back, clockwise: turn < 0) | ||
| 718 | context.strokePath() | ||
| 719 | let tip = centre + r * SIMD2(cos(end), sin(end)), base = centre + r * SIMD2(cos(back), sin(back)) | ||
| 720 | drawHead(context, style, .filled, tip: tip, direction: normalize(tip - base), outside: tip - centre) | ||
| 721 | } | ||
| 722 | let label = String(format: "%g°", abs(degrees)) | ||
| 723 | let font = CTFontCreateWithName("Helvetica" as CFString, 14, nil) | ||
| 724 | let text = NSAttributedString(string: label, attributes: [ | ||
| 725 | NSAttributedString.Key(kCTFontAttributeName as String): font, | ||
| 726 | NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true, | ||
| 727 | ]) | ||
| 728 | let line = CTLineCreateWithAttributedString(text) | ||
| 729 | let bounds = CTLineGetBoundsWithOptions(line, .useOpticalBounds) | ||
| 730 | context.setFillColor(gray: 0, alpha: 1) | ||
| 731 | context.textPosition = CGPoint(x: centre.x - bounds.midX, y: centre.y - bounds.midY) | ||
| 732 | CTLineDraw(line, context) | ||
| 733 | } | 556 | } |
| 734 | 557 | ||
| 735 | /// Golden images differ from a render when any channel of any pixel differs by more than this, | 558 | /// Golden images differ from a render when any channel of any pixel differs by more than this, |
Packages/FoldKit/Sources/Notation/DiagramDrawing.swift added +209
| @@ -0,0 +1,209 @@ | |||
| 1 | import CoreGraphics | ||
| 2 | import CoreText | ||
| 3 | import Foundation | ||
| 4 | import simd | ||
| 5 | |||
| 6 | /// The model and its arrows fill the canvas inside these margins, in points; the turn-over and | ||
| 7 | /// rotate symbols sit in the bottom one. | ||
| 8 | private let sideMargin = 48.0, bottomMargin = 96.0 | ||
| 9 | |||
| 10 | /// Draws `diagram` into the rectangle from the origin to `size`, the model and its arrows fitted | ||
| 11 | /// inside the margins. | ||
| 12 | /// | ||
| 13 | /// The context's user space must be y-up with its origin at the bottom-left of the canvas, as in a | ||
| 14 | /// `CGBitmapContext`; a y-down context such as SwiftUI's `GraphicsContext.withCGContext` must be | ||
| 15 | /// flipped first (`translateBy(x: 0, y: height)`, `scaleBy(x: 1, y: -1)`). Nothing is drawn | ||
| 16 | /// behind the diagram: the caller fills the background, and hollow heads and the push arrow are | ||
| 17 | /// filled white. The context's graphics state is restored on return. | ||
| 18 | public func drawDiagram(_ diagram: Diagram, style: DiagramStyle, in context: CGContext, size: CGSize) { | ||
| 19 | context.saveGState() | ||
| 20 | defer { context.restoreGState() } | ||
| 21 | |||
| 22 | var points = diagram.edges.flatMap { [$0.from, $0.to] } | ||
| 23 | for arrow in diagram.arrows { | ||
| 24 | switch arrow { | ||
| 25 | case let .valleyFold(from, over, to), let .mountainFold(from, over, to), let .foldAndUnfold(from, over, to, _): | ||
| 26 | points += [from, over, to] | ||
| 27 | case let .technique(_, at, toward): | ||
| 28 | points += [at, toward] | ||
| 29 | case .turnOver, .rotate, .repeatMark: | ||
| 30 | break | ||
| 31 | } | ||
| 32 | } | ||
| 33 | let low = points.reduce(points.first ?? .zero, simd_min) | ||
| 34 | let high = points.reduce(points.first ?? .zero, simd_max) | ||
| 35 | let area = CGRect(x: sideMargin, y: bottomMargin, width: size.width - 2 * sideMargin, | ||
| 36 | height: size.height - bottomMargin - sideMargin) | ||
| 37 | let extent = simd_max(high - low, SIMD2(repeating: 1e-9)) | ||
| 38 | let scale = min(area.width / extent.x, area.height / extent.y) | ||
| 39 | let offset = SIMD2(area.midX, area.midY) - scale * (low + high) / 2 | ||
| 40 | func pixel(_ p: SIMD2<Double>) -> CGPoint { | ||
| 41 | let q = offset + scale * p | ||
| 42 | return CGPoint(x: q.x, y: q.y) | ||
| 43 | } | ||
| 44 | |||
| 45 | context.setLineJoin(.round) | ||
| 46 | let layers: [(DiagramLine, Double, Double, [Double])] = [ | ||
| 47 | (.light, style.lightWidth, style.lightGrey, []), | ||
| 48 | (.solid, style.outlineWidth, 0, []), | ||
| 49 | (.dashed, style.creaseWidth, 0, style.valleyDash), | ||
| 50 | (.dashDot, style.creaseWidth, 0, style.mountainDash), | ||
| 51 | ] | ||
| 52 | for (line, width, grey, dash) in layers { | ||
| 53 | context.setStrokeColor(gray: grey, alpha: 1) | ||
| 54 | context.setLineWidth(width) | ||
| 55 | context.setLineCap(dash.isEmpty ? .round : .butt) | ||
| 56 | context.setLineDash(phase: 0, lengths: dash.map { CGFloat($0) }) | ||
| 57 | for edge in diagram.edges where edge.style == line { | ||
| 58 | context.move(to: pixel(edge.from)) | ||
| 59 | context.addLine(to: pixel(edge.to)) | ||
| 60 | } | ||
| 61 | context.strokePath() | ||
| 62 | } | ||
| 63 | context.setLineDash(phase: 0, lengths: []) | ||
| 64 | context.setLineCap(.round) | ||
| 65 | context.setStrokeColor(gray: 0, alpha: 1) | ||
| 66 | context.setLineWidth(style.arrowWidth) | ||
| 67 | |||
| 68 | let repeated = diagram.arrows.contains { if case .repeatMark = $0 { true } else { false } } | ||
| 69 | let symbolCentre = SIMD2(size.width / 2, bottomMargin / 2) | ||
| 70 | for arrow in diagram.arrows { | ||
| 71 | switch arrow { | ||
| 72 | case let .valleyFold(from, over, to): | ||
| 73 | drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .filled, returnHead: false, tick: repeated) | ||
| 74 | case let .mountainFold(from, over, to): | ||
| 75 | drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: .hollowHalf, returnHead: false, tick: repeated) | ||
| 76 | case let .foldAndUnfold(from, over, to, mountain): | ||
| 77 | drawFoldArrow(context, style, pixel(from), pixel(over), pixel(to), head: mountain ? .hollowHalf : .filled, | ||
| 78 | returnHead: true, tick: repeated) | ||
| 79 | case let .technique(technique, at, toward): | ||
| 80 | let tip = vector(pixel(at)), direction = normalize(vector(pixel(toward)) - tip) | ||
| 81 | if technique == .petal { | ||
| 82 | let tail = tip - style.symbolSize * 1.5 * direction | ||
| 83 | let over = (tip + tail) / 2 + 0.3 * SIMD2(direction.y, -direction.x) * style.symbolSize * 1.5 | ||
| 84 | drawFoldArrow(context, style, point(tail), point(over), point(tip), head: .filled, returnHead: false, | ||
| 85 | tick: repeated) | ||
| 86 | } else { | ||
| 87 | drawPushArrow(context, style, tip: tip, direction: direction, tick: repeated) | ||
| 88 | } | ||
| 89 | case let .turnOver(axis): | ||
| 90 | drawTurnOver(context, style, centre: symbolCentre, vertical: axis == .vertical) | ||
| 91 | case let .rotate(degrees): | ||
| 92 | drawRotate(context, style, centre: symbolCentre, degrees: degrees) | ||
| 93 | case .repeatMark: | ||
| 94 | break | ||
| 95 | } | ||
| 96 | } | ||
| 97 | } | ||
| 98 | |||
| 99 | private enum Head { case filled, hollowHalf, hollowFull } | ||
| 100 | |||
| 101 | private func vector(_ p: CGPoint) -> SIMD2<Double> { SIMD2(p.x, p.y) } | ||
| 102 | private func point(_ v: SIMD2<Double>) -> CGPoint { CGPoint(x: v.x, y: v.y) } | ||
| 103 | |||
| 104 | /// A quadratic arc from `from` through `over` to `to`, its head at `to`; with `returnHead` a | ||
| 105 | /// hollow head at `from` pointing back; with `tick` a stroke across the shaft near its tail. | ||
| 106 | private func drawFoldArrow(_ context: CGContext, _ style: DiagramStyle, _ from: CGPoint, _ over: CGPoint, _ to: CGPoint, | ||
| 107 | head: Head, returnHead: Bool, tick: Bool) { | ||
| 108 | let a = vector(from), m = vector(over), b = vector(to) | ||
| 109 | let control = 2 * m - (a + b) / 2 | ||
| 110 | context.move(to: from) | ||
| 111 | context.addQuadCurve(to: to, control: point(control)) | ||
| 112 | context.strokePath() | ||
| 113 | // the barb of a half head goes on the outside of the arc | ||
| 114 | let outside = m - (a + b) / 2 | ||
| 115 | drawHead(context, style, head, tip: b, direction: normalize(b - control), outside: outside) | ||
| 116 | if returnHead { | ||
| 117 | drawHead(context, style, .hollowFull, tip: a, direction: normalize(a - control), outside: outside) | ||
| 118 | } | ||
| 119 | if tick { | ||
| 120 | let t = 0.25 | ||
| 121 | let p = (1 - t) * (1 - t) * a + 2 * t * (1 - t) * control + t * t * b | ||
| 122 | let tangent = normalize(2 * (1 - t) * (control - a) + 2 * t * (b - control)) | ||
| 123 | let across = SIMD2(-tangent.y, tangent.x) * style.headLength / 2 | ||
| 124 | context.move(to: point(p - across)) | ||
| 125 | context.addLine(to: point(p + across)) | ||
| 126 | context.strokePath() | ||
| 127 | } | ||
| 128 | } | ||
| 129 | |||
| 130 | private func drawHead(_ context: CGContext, _ style: DiagramStyle, _ head: Head, tip: SIMD2<Double>, | ||
| 131 | direction: SIMD2<Double>, outside: SIMD2<Double>) { | ||
| 132 | let back = tip - style.headLength * direction | ||
| 133 | var across = SIMD2(-direction.y, direction.x) * style.headWidth / 2 | ||
| 134 | if dot(across, outside) < 0 { across = -across } | ||
| 135 | let corners: [SIMD2<Double>] | ||
| 136 | switch head { | ||
| 137 | case .filled, .hollowFull: corners = [tip, back + across, back - across] | ||
| 138 | case .hollowHalf: corners = [tip, back + 2 * across, back] | ||
| 139 | } | ||
| 140 | context.addLines(between: corners.map(point)) | ||
| 141 | context.closePath() | ||
| 142 | context.setFillColor(gray: head == .filled ? 0 : 1, alpha: 1) | ||
| 143 | context.drawPath(using: .fillStroke) | ||
| 144 | } | ||
| 145 | |||
| 146 | /// The hollow push arrow, its tip at `tip`, with a notched tail; with `tick` a stroke across the | ||
| 147 | /// shaft near its tail, standing out of the shaft by half a head length on each side. | ||
| 148 | private func drawPushArrow(_ context: CGContext, _ style: DiagramStyle, tip: SIMD2<Double>, direction: SIMD2<Double>, | ||
| 149 | tick: Bool) { | ||
| 150 | let s = style.symbolSize | ||
| 151 | let outline: [SIMD2<Double>] = [ | ||
| 152 | SIMD2(0, 0), SIMD2(-0.36, 0.3), SIMD2(-0.36, 0.12), SIMD2(-1, 0.12), | ||
| 153 | SIMD2(-0.86, 0), SIMD2(-1, -0.12), SIMD2(-0.36, -0.12), SIMD2(-0.36, -0.3), | ||
| 154 | ] | ||
| 155 | let across = SIMD2(-direction.y, direction.x) | ||
| 156 | context.addLines(between: outline.map { point(tip + s * ($0.x * direction + $0.y * across)) }) | ||
| 157 | context.closePath() | ||
| 158 | context.setFillColor(gray: 1, alpha: 1) | ||
| 159 | context.drawPath(using: .fillStroke) | ||
| 160 | if tick { | ||
| 161 | let p = tip - 0.7 * s * direction, half = 0.12 * s + style.headLength / 2 | ||
| 162 | context.move(to: point(p - half * across)) | ||
| 163 | context.addLine(to: point(p + half * across)) | ||
| 164 | context.strokePath() | ||
| 165 | } | ||
| 166 | } | ||
| 167 | |||
| 168 | /// The loop-the-loop arrow: left to right for a turn about the vertical axis, bottom to top about | ||
| 169 | /// the horizontal. | ||
| 170 | private func drawTurnOver(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2<Double>, vertical: Bool) { | ||
| 171 | // a prolate cycloid over one period, its loop above the line of travel, between straight tails | ||
| 172 | let a = style.symbolSize / (3 * .pi), b = 2 * a | ||
| 173 | let loop = (0...64).map { i -> SIMD2<Double> in | ||
| 174 | let u = -Double.pi + 2 * .pi * Double(i) / 64 | ||
| 175 | return SIMD2(a * u - b * sin(u), b * cos(u)) | ||
| 176 | } | ||
| 177 | let tail = SIMD2(style.symbolSize / 4, 0) | ||
| 178 | let path = [loop[0] - tail] + loop + [loop[64] + tail] | ||
| 179 | let place = { (p: SIMD2<Double>) in centre + (vertical ? p : SIMD2(-p.y, p.x)) } | ||
| 180 | context.addLines(between: path.map { point(place($0)) }) | ||
| 181 | context.strokePath() | ||
| 182 | let tip = place(path[path.count - 1]) | ||
| 183 | drawHead(context, style, .filled, tip: tip, direction: normalize(tip - place(loop[64])), outside: SIMD2(0, 1)) | ||
| 184 | } | ||
| 185 | |||
| 186 | /// Two arcs around a circle, counterclockwise for positive `degrees`, with the amount at the centre. | ||
| 187 | private func drawRotate(_ context: CGContext, _ style: DiagramStyle, centre: SIMD2<Double>, degrees: Double) { | ||
| 188 | let r = style.symbolSize / 2 | ||
| 189 | let turn = degrees >= 0 ? 1.0 : -1.0 | ||
| 190 | let headAngle = style.headLength / r | ||
| 191 | for start in [Double.pi * 0.6, Double.pi * 1.6] { | ||
| 192 | let end = start + turn * Double.pi * 0.75, back = end - turn * headAngle | ||
| 193 | context.addArc(center: point(centre), radius: r, startAngle: start, endAngle: back, clockwise: turn < 0) | ||
| 194 | context.strokePath() | ||
| 195 | let tip = centre + r * SIMD2(cos(end), sin(end)), base = centre + r * SIMD2(cos(back), sin(back)) | ||
| 196 | drawHead(context, style, .filled, tip: tip, direction: normalize(tip - base), outside: tip - centre) | ||
| 197 | } | ||
| 198 | let label = String(format: "%g°", abs(degrees)) | ||
| 199 | let font = CTFontCreateWithName("Helvetica" as CFString, 14, nil) | ||
| 200 | let text = NSAttributedString(string: label, attributes: [ | ||
| 201 | NSAttributedString.Key(kCTFontAttributeName as String): font, | ||
| 202 | NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true, | ||
| 203 | ]) | ||
| 204 | let line = CTLineCreateWithAttributedString(text) | ||
| 205 | let bounds = CTLineGetBoundsWithOptions(line, .useOpticalBounds) | ||
| 206 | context.setFillColor(gray: 0, alpha: 1) | ||
| 207 | context.textPosition = CGPoint(x: centre.x - bounds.midX, y: centre.y - bounds.midY) | ||
| 208 | CTLineDraw(line, context) | ||
| 209 | } | ||
Packages/FoldKit/Tests/NotationTests/DiagramTests.swift +14 −1
| @@ -25,6 +25,7 @@ import FoldKitTestSupport | |||
| 25 | @Test func anEdgeUnderASeamIsHidden() throws { | 25 | @Test func anEdgeUnderASeamIsHidden() throws { |
| 26 | // quarters step 3 draws frame 2: e8 lies under the seam between f3 and f2 | 26 | // quarters step 3 draws frame 2: e8 lies under the seam between f3 and f2 |
| 27 | #expect(try !diagram("quarters.fold", step: 3).edges.contains { $0.edge == 8 }) | 27 | #expect(try !diagram("quarters.fold", step: 3).edges.contains { $0.edge == 8 }) |
| 28 | #expect(try diagram("quarters.fold", step: 3).edges.contains { $0.style == .dashed }) | ||
| 28 | } | 29 | } |
| 29 | 30 | ||
| 30 | @Test func boundaryEdgesAreSolid() throws { | 31 | @Test func boundaryEdgesAreSolid() throws { |
| @@ -39,11 +40,13 @@ import FoldKitTestSupport | |||
| 39 | @Test func creasesNotYetMetAreNotDrawnAtAll() throws { | 40 | @Test func creasesNotYetMetAreNotDrawnAtAll() throws { |
| 40 | // frame 0 carries the y = 1 creases too; step 1's diagram must not show them | 41 | // frame 0 carries the y = 1 creases too; step 1's diagram must not show them |
| 41 | #expect(try diagram("quarters.fold", step: 1).edges.allSatisfy { ![10, 11].contains($0.edge) }) | 42 | #expect(try diagram("quarters.fold", step: 1).edges.allSatisfy { ![10, 11].contains($0.edge) }) |
| 43 | #expect(try diagram("quarters.fold", step: 1).edges.contains { $0.style == .dashed }) | ||
| 42 | } | 44 | } |
| 43 | 45 | ||
| 44 | @Test func edgesOccludedByLayersAboveThemAreOmitted() throws { | 46 | @Test func edgesOccludedByLayersAboveThemAreOmitted() throws { |
| 45 | // occlusion step 3 draws frame 2: f0's raw edge from (2,2) to (2,0) is under the strip | 47 | // occlusion step 3 draws frame 2: f0's raw edge from (2,2) to (2,0) is under the strip |
| 46 | #expect(try !diagram("occlusion.fold", step: 3).edges.contains { $0.edge == 0 }) | 48 | #expect(try !diagram("occlusion.fold", step: 3).edges.contains { $0.edge == 0 }) |
| 49 | #expect(try diagram("occlusion.fold", step: 3).edges.contains { $0.style == .solid }) | ||
| 47 | } | 50 | } |
| 48 | 51 | ||
| 49 | @Test func anEdgePartlyOccludedIsClippedNotDropped() throws { | 52 | @Test func anEdgePartlyOccludedIsClippedNotDropped() throws { |
| @@ -82,8 +85,18 @@ import FoldKitTestSupport | |||
| 82 | #expect(try diagram("letter-sequential.fold", step: 2).arrows.contains(.repeatMark(of: 1))) | 85 | #expect(try diagram("letter-sequential.fold", step: 2).arrows.contains(.repeatMark(of: 1))) |
| 83 | } | 86 | } |
| 84 | 87 | ||
| 88 | @Test func aRepeatedPushArrowCarriesTheRepeatStroke() { | ||
| 89 | let square = [SIMD2<Double>(0, 0), SIMD2(1, 0), SIMD2(1, 1), SIMD2(0, 1)] | ||
| 90 | let edges = square.indices.map { DiagramEdge(edge: $0, from: square[$0], to: square[($0 + 1) % 4], style: .solid) } | ||
| 91 | let push = DiagramArrow.technique(.insideReverse, at: SIMD2(0.5, 0.5), toward: SIMD2(1, 0.5)) | ||
| 92 | let once = render(Diagram(edges: edges, arrows: [push])) | ||
| 93 | let repeated = render(Diagram(edges: edges, arrows: [push, .repeatMark(of: 1)])) | ||
| 94 | #expect(inkedPixels(repeated) > inkedPixels(once)) | ||
| 95 | } | ||
| 96 | |||
| 85 | @Test func everyStepMatchesItsGoldenImage() throws { | 97 | @Test func everyStepMatchesItsGoldenImage() throws { |
| 86 | for name in ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"] { | 98 | for name in ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "letter-technique", "quarters", |
| 99 | "occlusion"] { | ||
| 87 | let file = try FoldFile(contentsOf: fixture("\(name).fold")) | 100 | let file = try FoldFile(contentsOf: fixture("\(name).fold")) |
| 88 | for step in try readSteps(file) { | 101 | for step in try readSteps(file) { |
| 89 | try expectSnapshot(render(buildDiagram(file: file, step: step)), named: "\(name)-\(step.index)") | 102 | try expectSnapshot(render(buildDiagram(file: file, step: step)), named: "\(name)-\(step.index)") |
Packages/FoldKit/Tests/NotationTests/Snapshots/NOTATION.md +7 −7
| @@ -1,6 +1,6 @@ | |||
| 1 | # Notation | 1 | # Notation |
| 2 | 2 | ||
| 3 | Symbols drawn by `buildDiagram` and the test renderer, with their source. The reference is | 3 | Symbols chosen by `buildDiagram` and drawn by `drawDiagram`, with their source. The reference is |
| 4 | Randlett's conventions in *The Art of Origami* (1961) and the symbol set as summarised by | 4 | Randlett's conventions in *The Art of Origami* (1961) and the symbol set as summarised by |
| 5 | OrigamiUSA; where they differ, OrigamiUSA's is used. Sizes are `DiagramStyle.standard`, in | 5 | OrigamiUSA; where they differ, OrigamiUSA's is used. Sizes are `DiagramStyle.standard`, in |
| 6 | points. | 6 | points. |
| @@ -11,7 +11,7 @@ points. | |||
| 11 | | Crease made earlier, flat again | thin grey line, 1, grey 0.6 | OrigamiUSA (existing crease) | | 11 | | Crease made earlier, flat again | thin grey line, 1, grey 0.6 | OrigamiUSA (existing crease) | |
| 12 | | Valley fold | dashed line, 7 on 4 off | Randlett and OrigamiUSA agree | | 12 | | Valley fold | dashed line, 7 on 4 off | Randlett and OrigamiUSA agree | |
| 13 | | Mountain fold | dash-dot-dot line, 9 on, dots of 2, gaps of 3 | OrigamiUSA; Randlett uses dash-dot | | 13 | | Mountain fold | dash-dot-dot line, 9 on, dots of 2, gaps of 3 | OrigamiUSA; Randlett uses dash-dot | |
| 14 | | Hidden edge or crease | not drawn; x-ray lines are not used | Randlett and OrigamiUSA agree | | 14 | | Hidden edge or crease | not drawn | this project's choice, per the design document; Randlett and OrigamiUSA both define an x-ray (dotted) line, which is not used | |
| 15 | | Valley-fold arrow | curved arrow, filled full head | OrigamiUSA (filled head) | | 15 | | Valley-fold arrow | curved arrow, filled full head | OrigamiUSA (filled head) | |
| 16 | | Mountain-fold arrow | curved arrow, hollow half head, barb on the outside of the arc | Randlett and OrigamiUSA agree | | 16 | | Mountain-fold arrow | curved arrow, hollow half head, barb on the outside of the arc | Randlett and OrigamiUSA agree | |
| 17 | | Fold and unfold | curved arrow, fold head at the destination, hollow full head at the start pointing back | OrigamiUSA (double-headed form; the zig-zag form is not used) | | 17 | | Fold and unfold | curved arrow, fold head at the destination, hollow full head at the start pointing back | OrigamiUSA (double-headed form; the zig-zag form is not used) | |
| @@ -19,7 +19,7 @@ points. | |||
| 19 | | Petal fold | valley-fold arrow lifting the flap | OrigamiUSA | | 19 | | Petal fold | valley-fold arrow lifting the flap | OrigamiUSA | |
| 20 | | Turn over | loop-the-loop arrow: left to right for a vertical axis, bottom to top for a horizontal one | Randlett and OrigamiUSA agree | | 20 | | Turn over | loop-the-loop arrow: left to right for a vertical axis, bottom to top for a horizontal one | Randlett and OrigamiUSA agree | |
| 21 | | Rotate | two arcs around a circle with heads in the direction of turn, the amount in degrees at the centre | OrigamiUSA (amount written in the circle) | | 21 | | Rotate | two arcs around a circle with heads in the direction of turn, the amount in degrees at the centre | OrigamiUSA (amount written in the circle) | |
| 22 | | Repeat | one stroke across each fold arrow's shaft near its tail | OrigamiUSA (strokes count repetitions) | | 22 | | Repeat | one stroke across the shaft of each fold arrow and push arrow near its tail | OrigamiUSA (strokes count repetitions) | |
| 23 | 23 | ||
| 24 | Valley and mountain are as seen from the step's viewpoint, not FOLD's assignment. | 24 | Valley and mountain are as seen from the step's viewpoint, not FOLD's assignment. |
| 25 | 25 | ||
| @@ -30,7 +30,7 @@ step with several axes start from points spread along their creases so that they | |||
| 30 | technique's symbol sits at the midpoint of the step's first crease, pointing toward where that | 30 | technique's symbol sits at the midpoint of the step's first crease, pointing toward where that |
| 31 | axis's moving set ends. | 31 | axis's moving set ends. |
| 32 | 32 | ||
| 33 | The canvas is 480 × 480, white; the model and its arrows fill it inside 48-point margins, 96 at | 33 | `drawDiagram` fits the model and its arrows inside 48-point margins, 96 at the bottom, where the |
| 34 | the bottom, where the turn-over and rotate symbols sit. A render matches its golden image when no | 34 | turn-over and rotate symbols sit. The golden images are 480 × 480, white. A render matches its |
| 35 | channel of any pixel differs by more than 24 of 255. Missing images are recorded by the test, | 35 | golden image when no channel of any pixel differs by more than 24 of 255. Missing images are |
| 36 | which then fails; `FOLD_RECORD_SNAPSHOTS=1` records them all. | 36 | recorded by the test, which then fails; `FOLD_RECORD_SNAPSHOTS=1` records them all. |
Packages/FoldKit/Tests/NotationTests/Snapshots/letter-technique-1.png added
Binary file not shown.