Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXFeatureGraph/Tests/ORIXFeatureGraphTests/RenderTests.swift3// Description: Off-screen rendering — pixel proof that no stroke crosses an asymptote or a jump, and screenshots of the screen layouts.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import SwiftUI9import Testing10import ORIXExpression11import ORIXGraph12import ORIXUI13@testable import ORIXFeatureGraph1415#if canImport(UIKit)16@MainActor @Suite struct RenderTests {17 static let width = 400.0, height = 300.01819 /// Renders one function with the main renderer (grid, axes, no curve labels, no asymptote guides) and returns the bitmap.20 private func plot(_ text: String, guides: Bool = false) throws -> (Bitmap, GraphModel) {21 let m = makeModel([text], width: RenderTests.width, height: RenderTests.height)22 m.showCurveLabels = false23 m.showAsymptotes = guides24 _ = m.setWindow(xMin: -10, xMax: 10, yMin: -7.5, yMax: 7.5)25 m.sampleAllNow()26 let out = try #require(render(GraphSceneView(scene: m.scene()), width: RenderTests.width, height: RenderTests.height))27 try? out.png.write(to: shotsDirectory().appendingPathComponent("render-\(text.replacingOccurrences(of: "/", with: "over")).png"))28 return (out.bitmap, m)29 }3031 private func column(_ m: GraphModel, _ x: Double, _ b: Bitmap) -> Int { Int((m.viewport.screenX(x) * b.scale).rounded()) }3233 @Test func sineIsDrawnAlongItsPath() throws {34 let (b, m) = try plot("sin(x)")35 let c = rgb(ORIXColor.series[0])36 #expect(b.width == 800 && b.height == 600)37 for x in stride(from: -9.5, through: 9.5, by: 0.37) {38 let s = m.viewport.toScreen(Point2(x, sin(x)))39 #expect(b.hasColor(nearX: Int(s.x * b.scale), y: Int(s.y * b.scale), radius: 3, color: c), "missing at x = \(x)")40 }41 // And nowhere else: far above and below the curve there is no curve colour.42 for x in stride(from: -9.5, through: 9.5, by: 0.9) {43 let s = m.viewport.toScreen(Point2(x, sin(x) + 3))44 #expect(!b.hasColor(nearX: Int(s.x * b.scale), y: Int(s.y * b.scale), radius: 3, color: c))45 }46 }4748 @Test func reciprocalHasNoStrokeAtItsAsymptote() throws {49 let (b, m) = try plot("1/x")50 let c = rgb(ORIXColor.series[0])51 #expect(b.count(color: c) > 1500)52 // A line joining the two branches would be a 600-pixel run in the column of x = 0.53 #expect(b.longestVerticalRun(x: column(m, 0, b), color: c) < 12)54 // The branches themselves are there, on both sides.55 for x in [-4.0, -1, 1, 4] {56 let s = m.viewport.toScreen(Point2(x, 1 / x))57 #expect(b.hasColor(nearX: Int(s.x * b.scale), y: Int(s.y * b.scale), radius: 3, color: c))58 }59 }6061 @Test func tangentHasNoStrokeAtAnyAsymptote() throws {62 let (b, m) = try plot("tan(x)")63 let c = rgb(ORIXColor.series[0])64 var poles = 065 for k in -4...3 {66 let x = (Double(k) + 0.5) * Double.pi67 guard abs(x) < 10 else { continue }68 poles += 169 #expect(b.longestVerticalRun(x: column(m, x, b), color: c) < 12, "stroke at the pole x = \(x)")70 }71 #expect(poles == 6)72 // Sanity of the method: a steep but continuous stretch next to a pole *is* a long run somewhere nearby.73 let near = (0..<b.width).map { b.longestVerticalRun(x: max(1, min($0, b.width - 2)), color: c) }.max()!74 #expect(near > 60)75 }7677 @Test func floorHasNoRisers() throws {78 let (b, m) = try plot("floor(x)")79 let c = rgb(ORIXColor.series[0])80 // One unit is 40 pixels here: a riser would be a 40-pixel run in the column of each integer.81 for n in -7...7 {82 #expect(b.longestVerticalRun(x: column(m, Double(n), b), color: c) < 10, "riser at x = \(n)")83 }84 // The treads are drawn.85 for n in -7...6 {86 let s = m.viewport.toScreen(Point2(Double(n) + 0.5, Double(n)))87 #expect(b.hasColor(nearX: Int(s.x * b.scale), y: Int(s.y * b.scale), radius: 3, color: c))88 }89 }9091 @Test func asymptoteGuidesAreLighterThanTheCurve() throws {92 let (b, m) = try plot("1/x", guides: true)93 let c = rgb(ORIXColor.series[0])94 // The guide is dashed and faint: it never reads as the curve.95 #expect(b.longestVerticalRun(x: column(m, 0, b), color: c) < 12)96 }9798 @Test func aliasedFunctionIsABandWithANotice() throws {99 let (b, m) = try plot("sin(1000x)")100 let g = m.geometries[m.entries[0].id]!.geometry101 #expect(!g.bands.isEmpty)102 #expect(m.notices.contains { $0.kind == .aliased && $0.message.contains("Oscillates faster than the screen can show") })103 // A translucent band: the curve colour at full strength is (almost) absent, a lighter tint fills the strip −1…1.104 let full = rgb(ORIXColor.series[0])105 let s = m.viewport.toScreen(Point2(3.3, 0.5))106 let p = b.pixel(Int(s.x * b.scale), Int(s.y * b.scale))107 #expect(p.r > full.r + 40 && p.b > 200 && p.r < 250)108 }109110 @Test func implicitUnreliableNoticeIsSurfaced() {111 let m = makeModel(["(x - y)^2 = 0", "x^2 + y^2 = 16"], width: 400, height: 400)112 m.sampleAllNow()113 #expect(m.notices.contains { $0.entryIndex == 0 && $0.kind == .unreliable })114 #expect(!m.notices.contains { $0.entryIndex == 1 })115 let circle = m.geometries[m.entries[1].id]!.geometry116 #expect(circle.polylines.count == 1 && circle.polylines[0].isClosed)117 }118119 @Test func holeMarkerAndInequalityAndRegionsRender() throws {120 let m = makeModel(["sin(x)/x", "y < -2"], width: 400, height: 300)121 m.showCurveLabels = false122 _ = m.setWindow(xMin: -10, xMax: 10, yMin: -7.5, yMax: 7.5)123 m.sampleAllNow()124 #expect(m.geometries[m.entries[0].id]!.geometry.holes.count == 1)125 var r = AnalysisRequest(kind: .integral, entryID: m.entries[0].id)126 r.a = 0.5; r.b = 6127 m.run(r)128 let out = try #require(render(GraphSceneView(scene: m.scene()), width: 400, height: 300))129 try? out.png.write(to: shotsDirectory().appendingPathComponent("render-overlays.png"))130 let b = out.bitmap131 let surface = rgb(ORIXColor.surface)132 // The open circle of the removable singularity has the canvas colour at its centre.133 let hole = m.viewport.toScreen(Point2(0, 1))134 #expect(b.isNear(Int(hole.x * 2), Int(hole.y * 2), surface, tolerance: 30))135 // The half-plane y < −2 is tinted, the other side is not.136 let inside = m.viewport.toScreen(Point2(-7.3, -5.3)), outside = m.viewport.toScreen(Point2(-7.3, 5.3))137 #expect(!b.isNear(Int(inside.x * 2), Int(inside.y * 2), surface, tolerance: 12))138 #expect(b.isNear(Int(outside.x * 2), Int(outside.y * 2), surface, tolerance: 12))139 // The positive region under the curve is shaded.140 let under = m.viewport.toScreen(Point2(1.3, 0.35))141 #expect(!b.isNear(Int(under.x * 2), Int(under.y * 2), surface, tolerance: 12))142 }143144 @Test func darkAppearanceUsesTheDarkTokens() throws {145 let m = makeModel(["sin(x)"], width: 400, height: 300)146 m.sampleAllNow()147 let out = try #require(render(GraphSceneView(scene: m.scene()), width: 400, height: 300, scheme: .dark))148 let background = rgb(ORIXColor.surface, dark: true)149 #expect(out.bitmap.isNear(6, 6, background, tolerance: 40))150 #expect(out.bitmap.count(color: rgb(ORIXColor.series[0], dark: true)) > 500)151 }152153 @Test func exportProducesAnOpaquePNGWithLegend() throws {154 let m = GraphModel(app: makeApp(), section: "2d", demo: true)155 let data = try #require(GraphExporter.png(model: m, title: "Demo graph", colorScheme: .light, scale: 2))156 #expect(data.starts(with: [0x89, 0x50, 0x4E, 0x47]))157 let image = try #require(UIImage(data: data))158 #expect(image.size.width * image.scale >= 1800)159 #expect(image.cgImage?.alphaInfo == CGImageAlphaInfo.noneSkipLast || image.cgImage?.alphaInfo == CGImageAlphaInfo.noneSkipFirst || image.cgImage?.alphaInfo == CGImageAlphaInfo.none)160 try data.write(to: shotsDirectory().appendingPathComponent("export-demo.png"))161 }162163 @Test func surfaceRendersWithHolesWhereTheEngineDroppedTriangles() throws {164 let m = makeModel([])165 m.mode = "3d"166 _ = m.setDomain3D(xMin: -2, xMax: 2, yMin: -2, yMax: 2)167 let id = m.addSurface(text: "sqrt(1 - x^2 - y^2)")168 m.camera = Camera3D(yaw: -.pi / 3, pitch: 1.2, distance: 4.5)169 m.sampleSurfacesNow()170 #expect(m.surfaceMeshes[id]!.droppedTriangles > 0)171 let out = try #require(render(Surface3DSceneView(scene: m.surfaceScene()), width: 400, height: 400))172 try? out.png.write(to: shotsDirectory().appendingPathComponent("render-3d-hemisphere.png"))173 // Outside the unit disc nothing is drawn: a point of the floor far from the dome keeps the canvas colour (or a grid line), never a ramp colour.174 let scene = m.surfaceScene()175 let corner = scene.camera(for: CGSize(width: 400, height: 400)).project(scene.bounds.unit(Point3(1.7, 1.7, 0)), width: 400, height: 400)!.screen176 let p = out.bitmap.pixel(Int(corner.x * 2), Int(corner.y * 2))177 #expect(p.r > 200 && p.g > 200 && p.b > 200)178 // The top of the dome is drawn in a ramp colour (not white).179 let top = scene.camera(for: CGSize(width: 400, height: 400)).project(scene.bounds.unit(Point3(0, 0, 1)), width: 400, height: 400)!.screen180 let q = out.bitmap.pixel(Int(top.x * 2), Int(top.y * 2))181 #expect(q.b < 160)182 }183}184185/// Not assertions about pixels: these write the pictures the engineer looks at (phone light / dark, iPad three zones, 3D).186@MainActor @Suite(.serialized) struct ScreenshotTests {187 private func shot(_ name: String, section: String, width: CGFloat, height: CGFloat, regular: Bool, scheme: ColorScheme, tab: PanelTab = .analysis,188 configure: (GraphModel, GraphUIState) -> Void = { _, _ in }) async throws {189 let app = makeApp()190 let model = GraphModel(app: app, section: section, demo: true)191 model.sampleSurfacesNow()192 let ui = GraphUIState()193 ui.tab = tab194 configure(model, ui)195 let view = GraphRoot(model: model, ui: ui)196 .environment(app)197 .environment(\.horizontalSizeClass, regular ? .regular : .compact)198 .environment(\.verticalSizeClass, height < 500 ? .compact : .regular)199 let png = try #require(await snapshot(view, width: width, height: height, scheme: scheme))200 try png.write(to: shotsDirectory().appendingPathComponent(name + ".png"))201 #expect(model.hasCanvasSize || section == "3d")202 }203204 @Test func phoneLight() async throws { try await shot("phone-light", section: "2d", width: 393, height: 760, regular: false, scheme: .light, tab: .expressions) }205 @Test func phoneDarkAnalysis() async throws { try await shot("phone-dark", section: "2d", width: 393, height: 760, regular: false, scheme: .dark) { _, ui in ui.detent = 2 } }206 @Test func phoneKeyboard() async throws { try await shot("phone-keyboard", section: "2d", width: 393, height: 760, regular: false, scheme: .light, tab: .keyboard) }207 @Test func phoneSliders() async throws { try await shot("phone-sliders", section: "2d", width: 393, height: 760, regular: false, scheme: .light, tab: .sliders) }208 @Test func phoneLandscape() async throws { try await shot("phone-landscape", section: "2d", width: 800, height: 370, regular: false, scheme: .light) { _, ui in ui.landscapePanel = true } }209 @Test func padThreeZones() async throws { try await shot("pad-light", section: "2d", width: 1180, height: 760, regular: true, scheme: .light) { m, _ in m.traceMode = true } }210 @Test func padDark() async throws { try await shot("pad-dark", section: "2d", width: 1180, height: 760, regular: true, scheme: .dark) }211 @Test func surface3D() async throws { try await shot("phone-3d", section: "3d", width: 393, height: 760, regular: false, scheme: .light, tab: .expressions) }212 @Test func padSurface3D() async throws {213 try await shot("pad-3d", section: "3d", width: 1180, height: 760, regular: true, scheme: .dark) { m, _ in214 m.contours = true; m.sampleSurfacesNow()215 m.placeProbe(x: 1.5, y: -1, entryID: m.surfaces[0].id)216 }217 }218 @Test func padWireframe() async throws {219 try await shot("pad-3d-wireframe", section: "3d", width: 1180, height: 760, regular: true, scheme: .light) { m, _ in220 m.setSurfaceText(m.surfaces[0].id, "1/(x^2+y^2)"); m.wireframe = true; m.sampleSurfacesNow()221 }222 }223 /// The public entry point inside its own NavigationStack, with the pending-expression hand-off on appear.224 @Test func publicScreen() async throws {225 let app = makeApp()226 app.pendingGraphExpression = "cos(2x)"227 let png = try #require(await snapshot(GraphScreen(section: "2d", demo: true).environment(app), width: 393, height: 852, scheme: .light, settle: .milliseconds(900)))228 try png.write(to: shotsDirectory().appendingPathComponent("screen-public.png"))229 #expect(app.pendingGraphExpression == nil)230 }231232 @Test func previewCell() throws {233 let request = GraphPreviewRequest(expressions: ["tan(x)", "x^2/8 - 2"], xMin: -6, xMax: 6)234 let out = try #require(render(GraphPreviewFactory.provider.make(request), width: 320, height: 200))235 try out.png.write(to: shotsDirectory().appendingPathComponent("preview.png"))236 }237}238#endif239