app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

@@ -0,0 +1 @@
/failures/
+48
View File
@@ -0,0 +1,48 @@
[package]
name = "rune-ref"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Scalar CPU reference renderer for Rune's device-pixel instance stream."
autotests = false
[features]
gpu = ["dep:rune", "dep:rune-fx", "dep:wgpu"]
[dependencies]
libm = { version = "=0.2.16", default-features = false, features = ["force-soft-floats"] }
blake3 = { workspace = true }
half = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
rune = { workspace = true, default-features = true, optional = true }
rune-fx = { workspace = true, optional = true }
wgpu = { workspace = true, optional = true }
[dev-dependencies]
proptest = "1"
[target.'cfg(target_os = "linux")'.dev-dependencies]
gungraun = "=0.20.0"
[[bench]]
name = "instructions"
harness = false
[[test]]
name = "alloc"
[[test]]
name = "differential"
[[test]]
name = "fx_blend"
[[test]]
name = "parity"
[[test]]
name = "reference"
[lints]
workspace = true
+32
View File
@@ -0,0 +1,32 @@
#[cfg(target_os = "linux")]
use gungraun::{
Callgrind, EventKind, LibraryBenchmarkConfig, library_benchmark, library_benchmark_group, main,
};
#[cfg(target_os = "linux")]
fn setup() -> (rune_ref::Scene, rune_ref::Frame) {
let scene = rune_ref::generate::seeded(24, 5);
let mut frame = rune_ref::Frame::new(scene.width, scene.height, false);
frame.render(&scene);
(scene, frame)
}
#[cfg(target_os = "linux")]
#[library_benchmark(setup = setup)]
fn steady_frame(
(scene, mut frame): (rune_ref::Scene, rune_ref::Frame),
) -> (rune_ref::Scene, rune_ref::Frame) {
frame.render(std::hint::black_box(&scene));
std::hint::black_box((scene, frame))
}
#[cfg(target_os = "linux")]
library_benchmark_group!(name = reference, benchmarks = steady_frame);
#[cfg(target_os = "linux")]
main!(
config = LibraryBenchmarkConfig::default()
.tool(Callgrind::default().soft_limits([(EventKind::Ir, 0.5)])),
library_benchmark_groups = reference
);
#[cfg(not(target_os = "linux"))]
fn main() {
eprintln!("skipping instruction benchmark: Linux and Valgrind required");
}
+11
View File
@@ -0,0 +1,11 @@
fn main() {
let hashes: Vec<_> = (0..16)
.map(|seed| {
let scene = rune_ref::generate::seeded(seed, 8);
let mut frame = rune_ref::Frame::new(scene.width, scene.height, false);
frame.render(&scene);
(seed, frame.hash())
})
.collect();
println!("{}", serde_json::to_string_pretty(&hashes).unwrap());
}
+18
View File
@@ -0,0 +1,18 @@
[
[0, "36f6aefc4d7c36910ee798986eb39062edc40385728f9aefe9c11b665daa1478"],
[1, "270fb4349cc80c4eaa97e9dd4346f91cbd6fad2e235d0983cd6fd466e54e0675"],
[2, "146ccdad62888e39c5ccbc07d8ce81c0d493505be05e11cf7ecf9daed79c562c"],
[3, "4c768398c7899a038e6ea5890112819b118e2df31175c9ca9fbaf95712782818"],
[4, "2f1dd0f326dbf98c5bd57d06adae49f2c819a3cdffc9e5f75651755ee1139aa4"],
[5, "dcdbd7d410d5aa542330a9ab2f6ab7ebc202ea653b268d34c2aab52de9d61cb8"],
[6, "9001ab24ecfe59e3f6716e06a95027a985579e0bacdfdda36400b49452cef6d1"],
[7, "a459d7aefe2ef5004891c59c8dd110e1a1d5b38aa862af7eedd2483dcbb5ab07"],
[8, "6cffd2911ab5b6c5dbba4add0da485a9a9fc7f950255f956577b8329fb6e9f96"],
[9, "6091f51afe00ffdca47ce48195d9987913b3295d65b375c5bf42372e561e3a82"],
[10, "385a43a7a3d8a30b37cc94e1e7461f3187fa28a5a9bdbafd0117e20d0ed2c643"],
[11, "a359ef5267bd87b3977f91fea6ac53a64edf5e4b7a7e2308dca03c191b609d7e"],
[12, "71c9655fb9dac08bcbc6b1eb149b445b73e48181d1227e1cdcd2697dd0bb7a91"],
[13, "d0c29bdf1e073d56b326fd70ec02cdaa3699de771d3f0f3874ba1d70d46938d0"],
[14, "b9e355a0653b0581759327bc5a8c4a40c80e8c5c6b17992c75578a958212a605"],
[15, "e42a98b4aba1b188c6579c9f2b2b5fa1a292b166ecf27c0a9f62cd40f9eec26e"]
]
+9
View File
@@ -0,0 +1,9 @@
# Differential regressions
Commit minimized JSON scenes here once a finding is understood. The GPU test
replays every JSON file with a 2-LSB channel cap and zero outlier pixels. Proptest
writes the final minimized scene to `../failures/minimized.json`; replay with:
```sh
cargo run -p rune-ref --features gpu -- --scene PATH --diff --blame 12,17
```
File diff suppressed because it is too large. Load diff
+55
View File
@@ -0,0 +1,55 @@
//! Scalar W3C separable blending oracle. Inputs and outputs are premultiplied in the
//! caller's working colour space; light with RGB greater than alpha must be normalized first.
#[derive(Clone, Copy, Debug)]
pub enum Separable {
Multiply,
Screen,
Overlay,
SoftLight,
}
pub fn composite(mode: Separable, src: [f32; 4], dst: [f32; 4]) -> [f32; 4] {
let (sa, da) = (src[3], dst[3]);
let mut out = [0.0; 4];
for c in 0..3 {
let s = if sa > 0.0 { src[c] / sa } else { 0.0 };
let b = if da > 0.0 { dst[c] / da } else { 0.0 };
let blended = match mode {
Separable::Multiply => b * s,
Separable::Screen => b + s - b * s,
Separable::Overlay if b <= 0.5 => 2.0 * b * s,
Separable::Overlay => 1.0 - 2.0 * (1.0 - b) * (1.0 - s),
Separable::SoftLight if s <= 0.5 => b - (1.0 - 2.0 * s) * b * (1.0 - b),
Separable::SoftLight => {
let d = if b <= 0.25 {
((16.0 * b - 12.0) * b + 4.0) * b
} else {
libm::sqrtf(b.max(0.0))
};
b + (2.0 * s - 1.0) * (d - b)
}
};
out[c] = src[c] * (1.0 - da) + sa * da * blended + dst[c] * (1.0 - sa);
}
out[3] = sa + da * (1.0 - sa);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn transparent_backdrops_preserve_the_source_in_every_mode() {
let src = [0.12, 0.24, 0.06, 0.3];
for mode in [
Separable::Multiply,
Separable::Screen,
Separable::Overlay,
Separable::SoftLight,
] {
assert_eq!(composite(mode, src, [0.0; 4]), src);
}
}
}
+241
View File
@@ -0,0 +1,241 @@
//! One bounded decoder shared by proptest, corpus generation and CLI replay.
//! Each 32-byte record shrinks independently; deleting records deletes primitives.
use crate::{Atlas, NO_CLIP, Primitive, Scene};
pub fn scene(records: &[[u8; 32]]) -> Scene {
let mut scene = Scene {
width: 64,
height: 64,
clear: [0.025, 0.04, 0.06, 1.0],
primitives: Vec::new(),
atlas: Atlas {
width: 32,
height: 32,
data: (0..1024)
.map(|n| ((n * 73 + n / 32 * 19) % 256) as u8)
.collect(),
},
};
for (index, b) in records.iter().take(32).enumerate() {
let a = b[9] as f32 / 255.0;
let color = |start: usize| {
[
b[start] as f32 / 255.0 * a,
b[start + 1] as f32 / 255.0 * a,
b[start + 2] as f32 / 255.0 * a,
a,
]
};
let kind = (b[0] % 5) as f32;
let mut p = Primitive {
node: index as u32 + 1,
source: format!("generated/{index}"),
rect: [
b[1] as f32 / 4.0 - 8.0,
b[2] as f32 / 4.0 - 8.0,
1.0 + (b[3] % 128) as f32 / 4.0,
1.0 + (b[4] % 128) as f32 / 4.0,
],
radii: std::array::from_fn(|n| b[20 + n] as f32 / 8.0),
fill: color(6),
border: color(10),
params: [
b[13] as f32 / 32.0,
kind,
b[14] as f32 / 32.0,
0.7 + b[15] as f32 / 255.0,
],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0.0; 4],
fade_origin: None,
turn: None,
clip_radii: None,
};
if b[16] & 1 != 0 {
p.clip = [
b[17] as f32 / 8.0,
b[18] as f32 / 8.0,
32.0 + b[19] as f32 / 8.0,
32.0 + b[24] as f32 / 8.0,
];
p.fade = std::array::from_fn(|n| (b[25 + n] % 32) as f32 / 4.0);
}
match kind as u32 {
1 => p.radii = [p.radii[0]; 4],
2 => {
// Atlas glyphs carry neither corner radii nor outline/LCD flags and read page 0.
p.radii = [0.0; 4];
// params[0] turns a glyph. At arbitrary angles a rotated edge can pass within
// the rasterizer's sub-pixel precision of a pixel centre, where it and the
// oracle's inside test may disagree by a whole pixel. Quarter turns have their
// own test.
p.params[0] = 0.0;
p.params[2] = 0.0;
// Guard texels keep all textureLoad taps defined on every backend.
p.uv = [1.0, 1.0, 0.0, 0.0];
p.rect[2] = 1.0 + (b[3] % 24) as f32;
p.rect[3] = 1.0 + (b[4] % 24) as f32;
if b[16] & 2 != 0 {
p.uv[2] = p.rect[2];
p.uv[3] = p.rect[3];
let scale = 0.5 + (b[29] % 8) as f32 / 4.0;
p.rect[2] *= scale;
p.rect[3] *= scale;
}
}
3 => {
p.uv = [
b[30] as f32 / 32.0 - 4.0,
b[31] as f32 / 32.0 - 4.0,
0.0,
0.0,
]
}
// Kinds 2 and 3 are the only other readers of bytes 29..32.
4 => p.uv = color(29),
_ => {}
}
scene.primitives.push(p);
}
scene
}
/// Stable SplitMix64 corpus, independent of proptest's evolving RNG algorithm.
pub fn seeded(seed: u64, count: usize) -> Scene {
let mut state = seed;
let records: Vec<[u8; 32]> = (0..count.min(32))
.map(|_| {
std::array::from_fn(|_| {
state = state.wrapping_add(0x9e3779b97f4a7c15);
let mut z = state;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
(z ^ (z >> 31)) as u8
})
})
.collect();
scene(&records)
}
/// `seeded`, with every primitive redrawn as a dashed border ring (kind 10). A separate corpus,
/// so adding the kind left the canonical hashes of `seeded` alone.
pub fn dashed(seed: u64, count: usize) -> Scene {
let mut scene = seeded(seed, count);
for p in &mut scene.primitives {
let b = |n: usize| (p.radii[n % 4] * 8.0 + p.rect[n % 4] * 4.0) as u32;
let bw = 0.5 + (b(0) % 8) as f32 * 0.25;
p.params = [bw, 10.0, if b(1) % 4 == 0 { p.params[2] } else { 0.0 }, 1.0];
let dash = 1.0 + (b(2) % 24) as f32 * 0.5;
let mut gap = 1.0 + (b(3) % 16) as f32 * 0.5;
// Avoid exact half-integer `total / nominal`, where a 1-ULP GPU reciprocal division
// can flip `floor(total / nominal + 0.5)` by a whole dash period.
let h = bw * 0.5;
let m = (p.rect[2] * 0.5).min(p.rect[3] * 0.5);
let rc = p.radii.map(|r| (r.abs().min(m) - h).max(0.0));
let total = (p.rect[2] - bw - rc[0] - rc[1]).max(0.0)
+ (p.rect[3] - bw - rc[1] - rc[2]).max(0.0)
+ (p.rect[2] - bw - rc[2] - rc[3]).max(0.0)
+ (p.rect[3] - bw - rc[3] - rc[0]).max(0.0)
+ rc.iter().map(|r| r * 1.5707964).sum::<f32>();
let periods = total / (dash + gap);
if (periods - libm::floorf(periods) - 0.5).abs() < 1e-3 {
gap += 0.25;
}
p.uv = [dash, gap, (b(1) % 32) as f32 * 0.75 - 6.0, 0.0];
if b(0) % 3 == 0 { p.border = p.fill; }
}
scene
}
/// `seeded`, with every primitive redrawn as a radial or angled linear gradient (kind 11),
/// including multi-stop open band edges (`+ 2.0` on `t0` / `t1`).
pub fn radial(seed: u64, count: usize) -> Scene {
let mut scene = seeded(seed, count);
let mut out = Vec::with_capacity(scene.primitives.len() * 2);
for mut p in scene.primitives {
let b = |n: usize| (p.radii[n % 4] * 8.0 + p.rect[n % 4] * 4.0) as u32;
let t0 = (b(0) % 4) as f32 * 0.1;
let t1 = (t0 + 0.35 + (b(1) % 6) as f32 * 0.1).min(1.0);
let soft = if b(1) % 4 == 0 { p.params[2] } else { 0.0 };
p.uv = if b(0) % 4 == 0 {
let angle = (b(2) % 16) as f32 * (std::f32::consts::TAU / 16.0);
let (dx, dy) = (libm::sinf(angle), -libm::cosf(angle));
let span = (dx.abs() * p.rect[2] + dy.abs() * p.rect[3]).max(1.0);
[dx / span, dy / span, 0.0, 0.0]
} else {
let cx = (0.2 + (b(2) % 7) as f32 * 0.1) * p.rect[2];
let cy = (0.2 + (b(3) % 7) as f32 * 0.1) * p.rect[3];
let rx = (4.0 + (b(0) % 24) as f32).max(1.0);
let ry = if b(1) % 2 == 0 { rx } else { (4.0 + (b(1) % 24) as f32).max(1.0) };
[cx, cy, rx, ry]
};
if b(2) % 2 == 0 {
let t_mid = 0.5 * (t0 + t1);
let mid = [
0.5 * (p.fill[0] + p.border[0]),
0.5 * (p.fill[1] + p.border[1]),
0.5 * (p.fill[2] + p.border[2]),
0.5 * (p.fill[3] + p.border[3]),
];
let mut inner = p.clone();
inner.border = mid;
inner.params = [t0, 11.0, soft, t_mid + 2.0];
out.push(inner);
p.fill = mid;
p.params = [t_mid + 2.0, 11.0, soft, t1];
out.push(p);
} else {
p.params = [t0, 11.0, soft, t1];
out.push(p);
}
}
scene.primitives = out;
scene
}
pub fn translate(scene: &mut Scene, x: f32, y: f32) {
for p in &mut scene.primitives {
p.rect[0] += x;
p.rect[1] += y;
if p.clip != NO_CLIP {
p.clip[0] += x;
p.clip[2] += x;
p.clip[1] += y;
p.clip[3] += y;
}
if let Some(origin) = &mut p.fade_origin
&& *origin != NO_CLIP
{
origin[0] += x;
origin[2] += x;
origin[1] += y;
origin[3] += y;
}
if let Some(turn) = &mut p.turn {
turn[1] += x;
turn[2] += y;
}
match p.params[1] as u32 {
5 => {
p.radii[0] += x;
p.radii[1] += y;
p.radii[2] += x;
p.radii[3] += y;
}
6 => {
p.radii[0] += x;
p.radii[1] += y;
p.radii[2] += x;
p.radii[3] += y;
p.uv[0] += x;
p.uv[1] += y;
}
8 if p.params[3] == 0.0 && p.radii[3] > 0.0 => {
p.radii[0] += x;
p.radii[1] += y;
}
_ => {}
}
}
}
+159
View File
@@ -0,0 +1,159 @@
//! Adapter to the production renderer. No copied WGSL or substitute GPU pipeline.
use crate::{Primitive, Scene};
use rune::{
render::{Gpu, Instance, OFFSCREEN_FORMAT, Offscreen, Renderer},
text::{ATLAS_SIZE, TextSystem},
};
impl Primitive {
/// Capture an application's emitted primitive with its inspector metadata.
pub fn from_instance(p: &Instance, node: u32, source: String) -> Self {
let (fade, offset) = rune::render::unpack_fade(p.fade);
Self {
node,
source,
rect: p.rect,
radii: p.radii,
fill: p.fill,
// A layer has no border paint; preserve its signed per-corner rounded-clip radii here,
// and its turn in `turn`.
border: if p.params[1] == 8.0 { rune::render::unpack_clip_radii(p.fade[3]) } else { p.border },
params: p.params,
uv: p.uv,
clip: p.clip,
fade,
fade_origin: Some(std::array::from_fn(|e| p.clip[e] + offset[e] * fade[e].abs() * if e < 2 { -1.0 } else { 1.0 })),
turn: (p.params[1] == 8.0 && p.border[1] != 0.0).then_some([p.border[1], p.border[2], p.border[3]]),
clip_radii: (p.params[1] != 8.0 && p.fade[3] != 0).then(|| rune::render::unpack_clip_radii(p.fade[3])),
}
}
}
impl From<&Primitive> for Instance {
fn from(p: &Primitive) -> Self {
let mut instance = Self {
rect: p.rect,
// `Scene` carries one grayscale R8 glyph atlas and no outline store; clear legacy
// non-zero `radii` and `params[2]` on glyphs so Windfoil never routes them to
// `outline_glyph`, `lcd_mask`, or secondary atlas pages.
radii: if p.params[1] == 2.0 { [0.0; 4] } else { p.radii },
fill: p.fill,
border: if p.params[1] == 8.0 {
let [a, x, y] = p.turn.unwrap_or([0.0; 3]);
[0.0, a, x, y]
} else {
p.border
},
params: if p.params[1] == 2.0 { [p.params[0], p.params[1], 0.0, p.params[3]] } else { p.params },
uv: p.uv,
clip: p.clip,
fade: rune::render::pack_fade(p.fade, p.fade_origin.unwrap_or(p.clip), p.clip),
};
if p.params[1] == 8.0 {
instance.fade[3] = rune::render::pack_clip_radii(p.clip, p.clip_radii.unwrap_or(p.border));
} else if let Some(radii) = p.clip_radii {
instance.fade[3] = rune::render::pack_clip_radii(p.clip, radii);
}
instance
}
}
pub struct GpuRenderer {
gpu: Gpu,
renderer: Renderer,
text: TextSystem,
}
impl Default for GpuRenderer {
fn default() -> Self {
let gpu = Gpu::new(Gpu::instance(), None);
eprintln!("reference adapter: {:?}", gpu.adapter.get_info());
let renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT);
Self {
gpu,
renderer,
text: TextSystem::default(),
}
}
}
impl GpuRenderer {
pub fn render(&mut self, scene: &Scene) -> Vec<u8> {
scene.validate().expect("valid differential scene");
let atlas = &mut self.text.atlas;
atlas.data.clear();
atlas.data.resize((ATLAS_SIZE * ATLAS_SIZE) as usize, 0);
for y in 0..scene.atlas.height as usize {
let n = scene.atlas.width as usize;
atlas.data[y * ATLAS_SIZE as usize..y * ATLAS_SIZE as usize + n]
.copy_from_slice(&scene.atlas.data[y * n..(y + 1) * n]);
}
atlas.dirty = Some((0, ATLAS_SIZE));
let instances: Vec<Instance> = scene.primitives.iter().map(Instance::from).collect();
self.renderer.prepare(
&self.gpu.device,
&self.gpu.queue,
atlas,
&instances,
(scene.width, scene.height),
);
let target = Offscreen::new(&self.gpu.device, scene.width, scene.height);
let mut encoder = self.gpu.device.create_command_encoder(&Default::default());
self.renderer.draw(&mut encoder, &target.view, scene.clear);
target.copy(&mut encoder);
self.gpu.queue.submit([encoder.finish()]);
target.read(&self.gpu.device)
}
}
/// Add a pinned-font text run, then freeze its atlas into the replay scene.
/// Shaping is deliberately outside the oracle: this lane tests glyph sampling.
pub fn text_run(scene: &mut Scene, seed: u64) {
let mut text = TextSystem::default();
let strings = ["Rune ffi", "Ág jW", "012345", "a\u{301} test"];
let style = rune::tok::TextStyle::new(9.0 + (seed % 15) as f32, 400.0);
let layout = text.layout_rich(
strings[seed as usize % strings.len()],
&[],
style,
1.0,
Some(60.0),
);
let mut quads = Vec::new();
text.glyphs_for_layout(&layout, 1.0, [2.0, 2.0], true, &mut quads);
// Keep synthetic atlas texels used by earlier generated glyphs in a separate region.
for p in &mut scene.primitives {
if p.params[1] == 2.0 {
p.uv[0] += 960.0;
p.uv[1] += 960.0;
}
}
for y in 0..scene.atlas.height.min(32) as usize {
let n = scene.atlas.width.min(32) as usize;
let start = (y + 960) * ATLAS_SIZE as usize + 960;
text.atlas.data[start..start + n].copy_from_slice(
&scene.atlas.data[y * scene.atlas.width as usize..y * scene.atlas.width as usize + n],
);
}
let first = scene.primitives.len() as u32 + 1;
for (n, q) in quads.iter().enumerate() {
scene.primitives.push(Primitive {
node: first + n as u32,
source: format!("text/{seed}/byte-{}", q.byte),
rect: q.rect,
radii: [0.0; 4],
fill: [0.7, 0.6, 0.5, 0.8],
border: [0.0; 4],
params: [0.0, 2.0, 0.0, 0.85],
uv: [q.uv[0], q.uv[1], 0.0, 0.0],
clip: crate::NO_CLIP,
fade: [0.0; 4],
fade_origin: None,
turn: None,
clip_radii: None,
});
}
scene.atlas = crate::Atlas {
width: ATLAS_SIZE,
height: ATLAS_SIZE,
data: text.atlas.data,
};
}
+274
View File
@@ -0,0 +1,274 @@
//! Bounded layer planning matching `rune::render::layers` and `Instance::layer_bounds`.
use crate::{NO_CLIP, Primitive};
use libm::{ceilf, cosf, floorf, roundf, sinf};
/// Maximum offscreen dimension for a cached subtree (`layers::MAX_CACHE_DIM`).
const MAX_CACHE_DIM: f32 = 4096.0;
#[derive(Clone, Copy)]
pub(crate) struct LayerCtx {
pub(crate) viewport: (u32, u32),
pub(crate) limit: [f32; 4],
pub(crate) free: bool,
pub(crate) frame: [f32; 4],
}
impl LayerCtx {
pub(crate) fn root(viewport: (u32, u32)) -> Self {
Self {
viewport,
limit: NO_CLIP,
free: false,
frame: [0.0; 4],
}
}
pub(crate) fn inline_child(self, clip: [f32; 4]) -> Self {
if self.free {
Self {
frame: [
self.frame[0].max(clip[0]),
self.frame[1].max(clip[1]),
self.frame[2].min(clip[2]),
self.frame[3].min(clip[3]),
],
..self
}
} else {
Self {
limit: [
clip[0].max(self.limit[0]),
clip[1].max(self.limit[1]),
clip[2].min(self.limit[2]),
clip[3].min(self.limit[3]),
],
..self
}
}
}
}
pub(crate) struct PlannedScope {
pub(crate) child_ctx: LayerCtx,
/// Integer-aligned target edges `[x0, y0, x1, y1]` in device pixels.
pub(crate) target: [i32; 4],
/// Edges propagated to an enclosing uncached parent (after any turn).
pub(crate) outer: [f32; 4],
pub(crate) visible: bool,
}
pub(crate) fn find_layer_close(primitives: &[Primitive], start: usize, end: usize) -> usize {
let mut depth = 1usize;
let mut close = start + 1;
while close < end && depth > 0 {
if primitives[close].params[1] == 8.0 {
depth += 1;
} else if primitives[close].params[1] == 9.0 {
depth -= 1;
}
if depth > 0 {
close += 1;
}
}
close
}
/// Whether a layer's clip matches a hardware scissor (`layers/plan.rs` `is_scissor_clip`).
pub(crate) fn is_scissor_clip(clip: [f32; 4], fade: [f32; 4]) -> bool {
clip == NO_CLIP || (fade == [0.0; 4] && clip.iter().all(|&v| (v - roundf(v)).abs() < 1e-3))
}
/// Upright bounds of edges `r` (`[x0, y0, x1, y1]`) turned `angle` radians clockwise about `p`.
pub(crate) fn turned_bounds(r: [f32; 4], angle: f32, p: [f32; 2]) -> [f32; 4] {
let (sn, c) = (sinf(angle), cosf(angle));
let mut out = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY];
for (x, y) in [(r[0], r[1]), (r[2], r[1]), (r[0], r[3]), (r[2], r[3])] {
let (dx, dy) = (x - p[0], y - p[1]);
let (qx, qy) = (p[0] + c * dx - sn * dy, p[1] + sn * dx + c * dy);
out = [out[0].min(qx), out[1].min(qy), out[2].max(qx), out[3].max(qy)];
}
out
}
fn union(a: &mut [f32; 4], b: [f32; 4]) {
if b[2] <= b[0] || b[3] <= b[1] {
return;
}
a[0] = a[0].min(b[0]);
a[1] = a[1].min(b[1]);
a[2] = a[2].max(b[2]);
a[3] = a[3].max(b[3]);
}
fn clamp_band(rect: [f32; 4], uv: [f32; 4], b: [f32; 4]) -> [f32; 4] {
let x0 = b[0].max(rect[0] + uv[0]);
let y0 = b[1].max(rect[1] + uv[1]);
let x1 = b[2].min(rect[0] - uv[2]).max(x0);
let y1 = b[3].min(rect[1] + uv[3]).max(y0);
[x0, y0, x1, y1]
}
/// Device-pixel bounds `[x0, y0, x1, y1]` a non-scope primitive contributes to an enclosing
/// uncached layer (`instance.rs` `layer_bounds_non_scope`).
fn primitive_layer_bounds(p: &Primitive) -> [f32; 4] {
let kind = p.params[1] as u32;
let b = if kind == 2 {
if p.params[0] != 0.0 {
let (sn, cs) = (sinf(p.params[0]), cosf(p.params[0]));
let w = cs.abs() * p.rect[2] + sn.abs() * p.rect[3];
let h = sn.abs() * p.rect[2] + cs.abs() * p.rect[3];
let x0 = p.rect[0] + (p.rect[2] - w) * 0.5;
let y0 = p.rect[1] + (p.rect[3] - h) * 0.5;
[x0, y0, x0 + w, y0 + h]
} else {
[p.rect[0], p.rect[1], p.rect[0] + p.rect[2], p.rect[1] + p.rect[3]]
}
} else {
let grow = match kind {
1 => 1.0 + p.params[2] * 3.0,
3 | 5 | 6 => 1.0,
12 => 1.0 + p.params[2],
_ => 1.0 + p.params[2] * 2.0,
};
let grown = [
p.rect[0] - grow,
p.rect[1] - grow,
p.rect[0] + p.rect[2] + grow,
p.rect[1] + p.rect[3] + grow,
];
if kind <= 1 && p.uv[2] < 0.0 {
clamp_band(p.rect, p.uv, grown)
} else {
grown
}
};
[
b[0].max(p.clip[0]),
b[1].max(p.clip[1]),
b[2].min(p.clip[2]),
b[3].min(p.clip[3]),
]
}
/// Plans a layer scope at `start` (`close` is its matching kind 9) matching `layers.rs`.
pub(crate) fn plan_scope(
primitives: &[Primitive],
start: usize,
close: usize,
parent: LayerCtx,
) -> PlannedScope {
let p = &primitives[start];
let turn = p.turn.filter(|t| t[0] != 0.0).map(|[a, px, py]| (a, [px, py]));
let free = turn.is_some() || parent.free;
let frame = if free {
let outer = if parent.free {
parent.frame
} else {
[0.0, 0.0, parent.viewport.0 as f32, parent.viewport.1 as f32]
};
let shown = [
outer[0].max(p.clip[0]),
outer[1].max(p.clip[1]),
outer[2].min(p.clip[2]),
outer[3].min(p.clip[3]),
];
match turn {
Some((angle, pivot)) if shown[2] > shown[0] && shown[3] > shown[1] => {
turned_bounds(shown, -angle, pivot)
}
_ => shown,
}
} else {
[0.0; 4]
};
let limit = if parent.free { NO_CLIP } else { parent.limit };
let child_limit = if free {
NO_CLIP
} else {
[
p.clip[0].max(limit[0]),
p.clip[1].max(limit[1]),
p.clip[2].min(limit[2]),
p.clip[3].min(limit[3]),
]
};
let child_ctx = LayerCtx {
viewport: parent.viewport,
limit: child_limit,
free,
frame,
};
let cached = p.params[3] == 1.0;
let mut edges = [p.rect[0], p.rect[1], p.rect[0] + p.rect[2], p.rect[1] + p.rect[3]];
if !cached {
let mut cursor = start + 1;
while cursor < close {
let child = &primitives[cursor];
if child.params[1] == 8.0 {
let sub_close = find_layer_close(primitives, cursor, close);
let sub = plan_scope(primitives, cursor, sub_close, child_ctx);
union(&mut edges, sub.outer);
cursor = sub_close + 1;
} else if child.params[1] == 9.0 {
cursor += 1;
} else {
union(&mut edges, primitive_layer_bounds(child));
cursor += 1;
}
}
}
let vis = if free {
[
floorf(edges[0].max(frame[0])),
floorf(edges[1].max(frame[1])),
ceilf(edges[2].min(frame[2])),
ceilf(edges[3].min(frame[3])),
]
} else {
[
floorf(edges[0].max(p.clip[0].max(limit[0])).max(0.0)),
floorf(edges[1].max(p.clip[1].max(limit[1])).max(0.0)),
ceilf(edges[2].min(p.clip[2].min(limit[2])).min(parent.viewport.0 as f32)),
ceilf(edges[3].min(p.clip[3].min(limit[3])).min(parent.viewport.1 as f32)),
]
};
let mut visible = true;
let target_edges = if cached {
if vis[2] <= vis[0] || vis[3] <= vis[1] {
visible = false;
}
let full = [floorf(edges[0]), floorf(edges[1]), ceilf(edges[2]), ceilf(edges[3])];
if full[2] - full[0] <= MAX_CACHE_DIM && full[3] - full[1] <= MAX_CACHE_DIM {
full
} else {
vis
}
} else {
vis
};
if target_edges[2] <= target_edges[0] || target_edges[3] <= target_edges[1] {
visible = false;
}
let outer = match turn {
Some((angle, pivot)) if target_edges[2] > target_edges[0] && target_edges[3] > target_edges[1] => {
turned_bounds(target_edges, angle, pivot)
}
_ => target_edges,
};
PlannedScope {
child_ctx,
target: [
target_edges[0] as i32,
target_edges[1] as i32,
target_edges[2] as i32,
target_edges[3] as i32,
],
outer,
visible,
}
}
+540
View File
@@ -0,0 +1,540 @@
//! Scalar oracle for Rune's device-pixel instance stream, not a vector rasterizer.
//! Basic operations use strict Rust f32 semantics (no mul_add or fast-math); all
//! transcendentals use pinned libm. The canonical output is sRGB RGBA8, quantized
//! after each source-over operation, including clear. See research/24.
#![forbid(unsafe_code)]
pub mod blend;
pub mod generate;
#[cfg(feature = "gpu")]
pub mod gpu;
mod layer;
mod shader;
use serde::{Deserialize, Serialize};
pub const NO_CLIP: [f32; 4] = [-1e6, -1e6, 1e6, 1e6];
/// Same payload as rune::render::Instance; independent so the CPU lane has no
/// window, GPU, system-font or platform dependency. Source metadata is a sidecar.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Primitive {
pub node: u32,
pub source: String,
pub rect: [f32; 4],
pub radii: [f32; 4],
pub fill: [f32; 4],
/// Border paint; for a layer (kind 8), signed per-corner clip radii `[tl, tr, br, bl]`.
pub border: [f32; 4],
pub params: [f32; 4],
pub uv: [f32; 4],
pub clip: [f32; 4],
pub fade: [f32; 4],
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fade_origin: Option<[f32; 4]>,
/// For a layer (kind 8), `[turn, pivot_x, pivot_y]`: the composite turns `turn` radians
/// clockwise about the pivot (device pixels).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub turn: Option<[f32; 3]>,
/// Signed per-corner rounded-clip radii `[tl, tr, br, bl]` (`Instance::fade[3]`). Layers
/// also carry theirs in `border` for saved replays.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub clip_radii: Option<[f32; 4]>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Atlas {
pub width: u32,
pub height: u32,
pub data: Vec<u8>,
}
impl Atlas {
pub(crate) fn load(&self, x: i32, y: i32) -> f32 {
if x < 0 || y < 0 || x >= self.width as i32 || y >= self.height as i32 {
return 0.0;
}
self.data[(y as u32 * self.width + x as u32) as usize] as f32 / 255.0
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Scene {
pub width: u32,
pub height: u32,
pub clear: [f32; 4],
pub primitives: Vec<Primitive>,
pub atlas: Atlas,
}
/// The deepest nesting of layer scopes `validate` accepts.
const MAX_LAYER_DEPTH: usize = 16;
impl Scene {
/// Reject malformed replay files before CPU allocation or GPU upload.
pub fn validate(&self) -> Result<(), String> {
if self.width == 0 || self.height == 0 || self.width > 4096 || self.height > 4096 {
return Err("viewport must be 1..=4096".into());
}
if self.primitives.len() > 65536
|| self.atlas.width == 0
|| self.atlas.height == 0
|| self.atlas.width > 2048
|| self.atlas.height > 2048
|| self.atlas.data.len() != self.atlas.width as usize * self.atlas.height as usize
{
return Err("invalid atlas or primitive count".into());
}
let color = |c: &[f32; 4]| {
c.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))
&& c[..3].iter().all(|v| *v <= c[3])
};
if !color(&self.clear) {
return Err("clear must be premultiplied linear RGBA".into());
}
let mut layer_depth = 0usize;
for p in &self.primitives {
if p.params[1] == 8.0 {
// Each open scope holds a full-frame buffer, and the compositor has no layer blur.
if layer_depth == MAX_LAYER_DEPTH || p.params[2] != 0.0 {
return Err(format!("unsupported layer {} ({})", p.node, p.source));
}
if !matches!(p.params[0], 0.0 | 1.0) || !matches!(p.params[3], 0.0 | 1.0)
|| (p.params[3] == 1.0 && p.radii.iter().chain(p.uv.iter())
.any(|v| !v.is_finite() || !(0.0..=65535.0).contains(v) || v.fract() != 0.0))
{
return Err(format!("invalid layer {} ({})", p.node, p.source));
}
layer_depth += 1;
} else if p.params[1] == 9.0 {
if layer_depth == 0 {
return Err(format!("unbalanced layer end {} ({})", p.node, p.source));
}
layer_depth -= 1;
}
if [
p.rect, p.radii, p.fill, p.border, p.params, p.uv, p.clip, p.fade, p.fade_origin.unwrap_or(p.clip),
]
.iter()
.flatten()
.any(|v| !v.is_finite() || v.abs() > 1e6)
// Triangles (kind 6), layers (kind 8, expanded by children), layer ends (kind 9)
// and effect slots (kind 12) may have an empty rect.
|| (!matches!(p.params[1] as u32, 6 | 8 | 9 | 12) && (p.rect[2] <= 0.0 || p.rect[3] <= 0.0))
|| p.rect[2] < 0.0
|| p.rect[3] < 0.0
// A negative fade width is a linear ramp.
// Negative corner radii select Apple continuous corners (`sd_continuous`).
// A layer's `radii` are its hole, whose centre may lie anywhere.
|| (p.params[1] == 8.0 && p.params[3] == 0.0 && (p.radii[2] < 0.0 || p.radii[3] < p.radii[2]))
// Kinds 7 (image) and 13 (backdrop blur) are not implemented in the scalar oracle
// and stay rejected.
|| !(0..=6).chain([8, 9, 10, 11, 12]).any(|k| p.params[1] == k as f32)
// A glyph's params[0] is a signed turn; an inset shadow's params[0] is a signed spread.
|| (p.params[0] < 0.0 && !matches!(p.params[1] as u32, 2 | 3))
|| p.params[2] < 0.0
|| !color(&p.fill)
|| (if p.params[1] == 8.0 {
p.border.iter().any(|&v| v < 0.0) && p.border.iter().any(|&v| v > 0.0)
} else if p.params[1] == 12.0 {
// Effect slots carry their 32-bit mark as two 16-bit floats in `border[0..2]`.
false
} else {
!color(&p.border)
})
|| p.clip_radii.is_some_and(|r| {
r.iter().any(|v| !v.is_finite() || v.abs() > 1e6)
|| (r.iter().any(|&v| v < 0.0) && r.iter().any(|&v| v > 0.0))
})
|| p.turn.is_some_and(|t| {
p.params[1] != 8.0
|| p.params[3] == 1.0
|| t[0] == 0.0
|| t.iter().any(|v| !v.is_finite() || v.abs() > 1e6)
})
|| (p.params[1] == 1.0 && p.uv[2] > 0.0 && p.uv[3] <= 0.0)
|| (p.params[1] == 4.0 && !color(&p.uv))
|| (p.params[1] == 10.0 && (p.uv[0] <= 0.0 || p.uv[1] <= 0.0))
|| (p.params[1] == 11.0 && (p.uv[2] < 0.0 || p.uv[3] < 0.0 || (p.uv[2] > 0.0) != (p.uv[3] > 0.0)))
|| (p.params[1] == 2.0 && (p.params[3] <= 0.0 || p.uv.iter().any(|v| *v < 0.0)))
{
return Err(format!("invalid primitive {} ({})", p.node, p.source));
}
}
if layer_depth != 0 {
return Err("unclosed layer scope".into());
}
Ok(())
}
}
pub struct Frame {
pub width: u32,
pub height: u32,
pub rgba: Vec<u8>,
/// Last contributing primitive index, not nearest geometry. None = clear.
pub owners: Option<Vec<Option<usize>>>,
}
impl Frame {
pub fn new(width: u32, height: u32, provenance: bool) -> Self {
assert!(width > 0 && height > 0 && width <= 4096 && height <= 4096);
let n = width as usize * height as usize;
Self {
width,
height,
rgba: vec![0; n * 4],
owners: provenance.then(|| vec![None; n]),
}
}
/// No allocations after Frame construction unless isolated/cached layers are present. Scene must pass validate().
pub fn render(&mut self, scene: &Scene) {
assert_eq!((self.width, self.height), (scene.width, scene.height));
let clear = encode(scene.clear);
for pixel in self.rgba.as_chunks_mut::<4>().0 {
pixel.copy_from_slice(&clear);
}
if let Some(ids) = &mut self.owners {
ids.fill(None);
}
Self::render_range(
Target {
origin: [0, 0],
size: (self.width, self.height),
scissor: [0, 0, self.width, self.height],
pixels: TargetPixels::Srgb(&mut self.rgba),
},
self.owners.as_deref_mut(),
scene,
0..scene.primitives.len(),
layer::LayerCtx::root((self.width, self.height)),
false,
);
}
fn render_range(
mut target: Target<'_>,
mut owners: Option<&mut [Option<usize>]>,
scene: &Scene,
range: std::ops::Range<usize>,
ctx: layer::LayerCtx,
additive: bool,
) {
let (mut cursor, end) = (range.start, range.end);
let [ox, oy] = target.origin;
let (tw, th) = target.size;
let scissor = target.scissor;
while cursor < end {
let p = &scene.primitives[cursor];
if p.params[1] == 8.0 {
let close = layer::find_layer_close(&scene.primitives, cursor, end);
let clip_radii = p.clip_radii.unwrap_or(p.border);
let inline = !additive
&& p.params[3] == 0.0
&& p.fill[3] == 1.0
&& p.params[0] == 0.0
&& p.params[2] == 0.0
&& shader::pack_clip_radii(p.clip, clip_radii) == 0
&& layer::is_scissor_clip(p.clip, p.fade)
&& p.radii[3] == 0.0
&& p.turn.is_none();
if inline {
let sub_scissor = if p.clip == NO_CLIP {
scissor
} else {
let edge = |v: f32, o: i32, max: u32| (v - o as f32).clamp(0.0, max as f32) as u32;
[
edge(libm::floorf(p.clip[0]), ox, tw).max(scissor[0]),
edge(libm::floorf(p.clip[1]), oy, th).max(scissor[1]),
edge(libm::ceilf(p.clip[2]), ox, tw).min(scissor[2]),
edge(libm::ceilf(p.clip[3]), oy, th).min(scissor[3]),
]
};
if sub_scissor[2] > sub_scissor[0] && sub_scissor[3] > sub_scissor[1] {
Self::render_range(
target.reborrow(sub_scissor),
owners.as_deref_mut(),
scene,
cursor + 1..close,
ctx.inline_child(p.clip),
false,
);
}
} else if p.fill[3] > 0.0 {
let scope = layer::plan_scope(&scene.primitives, cursor, close, ctx);
if scope.visible {
let [lx, ly, rx, ry] = scope.target;
let (lw, lh) = ((rx - lx) as u32, (ry - ly) as u32);
// Isolated layers accumulate in linear float (matching GPU Rgba16Float);
// PlusLighter blends children additively inside and saturates before compositing.
let layer_additive = p.params[0] == 1.0;
let mut layer_buf = vec![[0.0f32; 4]; (lw * lh) as usize];
let mut layer_owners = owners.as_ref().map(|_| vec![None; (lw * lh) as usize]);
Self::render_range(
Target {
origin: [lx, ly],
size: (lw, lh),
scissor: [0, 0, lw, lh],
pixels: TargetPixels::Linear(&mut layer_buf),
},
layer_owners.as_deref_mut(),
scene,
cursor + 1..close,
scope.child_ctx,
layer_additive,
);
let turn = p.turn.filter(|t| t[0] != 0.0).map(|[a, px, py]| (a, libm::sinf(a), libm::cosf(a), [px, py]));
let (x0, y0, x1, y1) = match turn {
Some((angle, _, _, pivot)) => {
let quad = layer::turned_bounds(
[lx as f32 - 1.0, ly as f32 - 1.0, rx as f32 + 1.0, ry as f32 + 1.0],
angle,
pivot,
);
let edge = |v: f32, o: i32, max: u32| (v - o as f32).clamp(0.0, max as f32) as u32;
(
edge(libm::floorf(quad[0]), ox, tw).max(scissor[0]),
edge(libm::floorf(quad[1]), oy, th).max(scissor[1]),
edge(libm::ceilf(quad[2]), ox, tw).min(scissor[2]),
edge(libm::ceilf(quad[3]), oy, th).min(scissor[3]),
)
}
None => (
((lx - ox).max(0) as u32).max(scissor[0]),
((ly - oy).max(0) as u32).max(scissor[1]),
((rx - ox).max(0) as u32).min(scissor[2]),
((ry - oy).max(0) as u32).min(scissor[3]),
),
};
let alpha = p.fill[3].clamp(0.0, 1.0);
for y in y0..y1 {
let sy = (oy + y as i32) as f32 + 0.5;
for x in x0..x1 {
let sx = (ox + x as i32) as f32 + 0.5;
let cov = alpha * shader::layer_clip_coverage(p, [sx, sy]);
if cov <= 0.0 {
continue;
}
let at = (y * tw + x) as usize;
let (src, src_owner) = match turn {
Some((_, sn, cs, pivot)) => {
let (qx, qy) = (sx - pivot[0], sy - pivot[1]);
let (ux, uy) = (
pivot[0] + cs * qx + sn * qy - lx as f32 - 0.5,
pivot[1] + cs * qy - sn * qx - ly as f32 - 0.5,
);
let (bx, by) = (libm::floorf(ux), libm::floorf(uy));
let (fx, fy) = (ux - bx, uy - by);
let texel = |tx: i32, ty: i32| -> [f32; 4] {
if tx < 0 || ty < 0 || tx >= lw as i32 || ty >= lh as i32 {
return [0.0; 4];
}
let c = layer_buf[(ty as u32 * lw + tx as u32) as usize];
if layer_additive { c.map(|v| v.clamp(0.0, 1.0)) } else { c }
};
let (ix, iy) = (bx as i32, by as i32);
let (a, b) = (texel(ix, iy), texel(ix + 1, iy));
let (c, d) = (texel(ix, iy + 1), texel(ix + 1, iy + 1));
let color = std::array::from_fn(|k| {
let top = a[k] * (1.0 - fx) + b[k] * fx;
let bottom = c[k] * (1.0 - fx) + d[k] * fx;
top * (1.0 - fy) + bottom * fy
});
let owner = layer_owners.as_ref().and_then(|l_ids| {
let pick = |tx: i32, ty: i32| -> Option<usize> {
if tx < 0 || ty < 0 || tx >= lw as i32 || ty >= lh as i32 {
return None;
}
l_ids[(ty as u32 * lw + tx as u32) as usize]
};
let (nx, ny) = (libm::roundf(ux) as i32, libm::roundf(uy) as i32);
pick(nx, ny)
.or_else(|| pick(ix, iy))
.or_else(|| pick(ix + 1, iy))
.or_else(|| pick(ix, iy + 1))
.or_else(|| pick(ix + 1, iy + 1))
});
(color, owner)
}
None => {
let l_at = (((oy + y as i32 - ly) as u32) * lw + ((ox + x as i32 - lx) as u32)) as usize;
let c = layer_buf[l_at];
let color = if layer_additive { c.map(|v| v.clamp(0.0, 1.0)) } else { c };
let owner = layer_owners.as_ref().and_then(|l_ids| l_ids[l_at]);
(color, owner)
}
};
let col = src.map(|c| c * cov);
if col[3] <= 0.0 {
continue;
}
target.blend(at, col, additive);
if let Some(ids) = owners.as_deref_mut() {
ids[at] = src_owner.or(Some(cursor));
}
}
}
}
}
cursor = close + 1;
continue;
}
if p.params[1] == 9.0 {
cursor += 1;
continue;
}
for y in scissor[1]..scissor[3] {
let sy = (oy + y as i32) as f32 + 0.5;
for x in scissor[0]..scissor[2] {
let sx = (ox + x as i32) as f32 + 0.5;
let col = shader::fragment(p, &scene.atlas, [sx, sy]);
if col[3] <= 0.0 {
continue;
}
let at = (y * tw + x) as usize;
target.blend(at, col, additive);
if let Some(ids) = owners.as_deref_mut() {
ids[at] = Some(cursor);
}
}
}
cursor += 1;
}
}
pub fn hash(&self) -> String {
blake3::hash(&self.rgba).to_hex().to_string()
}
pub fn blame<'a>(&self, scene: &'a Scene, x: u32, y: u32) -> Option<&'a Primitive> {
if x >= self.width || y >= self.height {
return None;
}
let index = self.owners.as_ref()?[(y * self.width + x) as usize]?;
scene.primitives.get(index)
}
}
struct Target<'a> {
origin: [i32; 2],
size: (u32, u32),
scissor: [u32; 4],
pixels: TargetPixels<'a>,
}
enum TargetPixels<'a> {
Srgb(&'a mut [u8]),
Linear(&'a mut [[f32; 4]]),
}
impl Target<'_> {
fn reborrow(&mut self, scissor: [u32; 4]) -> Target<'_> {
Target {
origin: self.origin,
size: self.size,
scissor,
pixels: match &mut self.pixels {
TargetPixels::Srgb(s) => TargetPixels::Srgb(s),
TargetPixels::Linear(l) => TargetPixels::Linear(l),
},
}
}
fn blend(&mut self, at: usize, col: [f32; 4], additive: bool) {
let combine = |dst: [f32; 4]| -> [f32; 4] {
if additive {
std::array::from_fn(|c| col[c] + dst[c])
} else {
std::array::from_fn(|c| col[c] + dst[c] * (1.0 - col[3]))
}
};
match &mut self.pixels {
TargetPixels::Srgb(rgba) => {
let dst = decode(rgba[at * 4..at * 4 + 4].try_into().unwrap());
rgba[at * 4..at * 4 + 4].copy_from_slice(&encode(combine(dst)));
}
TargetPixels::Linear(buf) => {
buf[at] = combine(buf[at]);
}
}
}
}
fn encode(c: [f32; 4]) -> [u8; 4] {
std::array::from_fn(|i| {
let v = c[i].clamp(0.0, 1.0);
let v = if i == 3 {
v
} else if v <= 0.0031308 {
v * 12.92
} else {
1.055 * libm::powf(v, 1.0 / 2.4) - 0.055
};
libm::roundf(v * 255.0) as u8
})
}
fn decode(c: [u8; 4]) -> [f32; 4] {
std::array::from_fn(|i| {
let v = c[i] as f32 / 255.0;
if i == 3 {
v
} else if v <= 0.04045 {
v / 12.92
} else {
libm::powf((v + 0.055) / 1.055, 2.4)
}
})
}
#[derive(Debug, Serialize)]
pub struct Difference {
pub max_channel: u8,
pub outlier_pixels: usize,
pub first: Option<PixelBlame>,
}
#[derive(Debug, Serialize)]
pub struct PixelBlame {
pub x: u32,
pub y: u32,
pub expected: [u8; 4],
pub actual: [u8; 4],
pub node: Option<u32>,
pub source: Option<String>,
}
/// Strict per-channel gate; no outlier allowance, no average that hides a bad edge.
pub fn compare(scene: &Scene, cpu: &Frame, gpu: &[u8], tolerance: u8) -> Difference {
assert_eq!(cpu.rgba.len(), gpu.len());
let mut diff = Difference {
max_channel: 0,
outlier_pixels: 0,
first: None,
};
for (at, (a, b)) in cpu
.rgba
.as_chunks::<4>()
.0
.iter()
.zip(gpu.as_chunks::<4>().0)
.enumerate()
{
let d = a.iter().zip(b).map(|(a, b)| a.abs_diff(*b)).max().unwrap();
diff.max_channel = diff.max_channel.max(d);
if d <= tolerance {
continue;
}
diff.outlier_pixels += 1;
if diff.first.is_none() {
let (x, y) = (at as u32 % cpu.width, at as u32 / cpu.width);
let p = cpu.blame(scene, x, y);
diff.first = Some(PixelBlame {
x,
y,
expected: *a,
actual: *b,
node: p.map(|p| p.node),
source: p.map(|p| p.source.clone()),
});
}
}
diff
}
+52
View File
@@ -0,0 +1,52 @@
#![forbid(unsafe_code)]
use rune_ref::{Frame, Scene, generate};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().skip(1).collect();
let value = |flag: &str| {
args.iter()
.position(|s| s == flag)
.and_then(|n| args.get(n + 1))
};
let scene: Scene = if let Some(path) = value("--scene") {
serde_json::from_slice(&std::fs::read(path)?)?
} else {
generate::seeded(
value("--seed").map(|s| s.parse()).transpose()?.unwrap_or(0),
8,
)
};
scene.validate()?;
let mut frame = Frame::new(scene.width, scene.height, true);
frame.render(&scene);
println!("blake3={}", frame.hash());
if let Some(path) = value("--save") {
std::fs::write(path, serde_json::to_vec_pretty(&scene)?)?;
}
if let Some(xy) = value("--blame") {
let (x, y) = xy.split_once(',').ok_or("--blame expects x,y")?;
let (x, y): (u32, u32) = (x.parse()?, y.parse()?);
if x >= scene.width || y >= scene.height {
return Err("pixel outside viewport".into());
}
match frame.blame(&scene, x, y) {
Some(p) => println!("node={} source={} kind={}", p.node, p.source, p.params[1]),
None => println!("clear"),
}
}
if args.iter().any(|a| a == "--diff") {
#[cfg(not(feature = "gpu"))]
return Err("--diff requires --features gpu".into());
#[cfg(feature = "gpu")]
{
let actual = rune_ref::gpu::GpuRenderer::default().render(&scene);
let report = rune_ref::compare(&scene, &frame, &actual, 2);
println!("{}", serde_json::to_string_pretty(&report)?);
if report.outlier_pixels > 0 {
return Err("GPU differs from reference".into());
}
}
}
Ok(())
}
+618
View File
@@ -0,0 +1,618 @@
//! Deliberately scalar transcription of shader.wgsl. No shared shader generator:
//! keeping the implementations independent catches changes to either lane.
use crate::{Atlas, Primitive};
use libm::{atan2f, cosf, expf, floorf, powf, roundf, sinf, sqrtf};
fn clamp(x: f32) -> f32 {
x.clamp(0.0, 1.0)
}
fn mix(a: f32, b: f32, t: f32) -> f32 {
a * (1.0 - t) + b * t
}
fn sd(p: [f32; 2], h: [f32; 2], radii: [f32; 4]) -> f32 {
let index = if p[0] > 0.0 {
if p[1] > 0.0 { 2 } else { 1 }
} else if p[1] > 0.0 {
3
} else {
0
};
if radii[index] < 0.0 {
return sd_continuous(p, h, (-radii[index]).min(h[0].min(h[1])));
}
let r = radii[index].min(h[0].min(h[1]));
let q = [p[0].abs() - h[0] + r, p[1].abs() - h[1] + r];
let a = q[0].max(0.0);
let b = q[1].max(0.0);
q[0].max(q[1]).min(0.0) + sqrtf(a * a + b * b) - r
}
/// Apple's continuous corner: from (K·r, K·r) inside the corner, the curve lies K·r·g(u) away.
fn sd_continuous(p: [f32; 2], h: [f32; 2], r: f32) -> f32 {
let e = 1.528_664_8 * r;
let q = [h[0] - p[0].abs(), h[1] - p[1].abs()];
let v = [e - q[0], e - q[1]];
if v[0] <= 0.0 || v[1] <= 0.0 {
return (-q[0]).max(-q[1]);
}
let u = atan2f(v[1], v[0]) * (4.0 / std::f32::consts::PI) - 1.0;
let u2 = u * u;
let g = 1.146_022_9 + u2 * (-0.375_731_6 + u2 * (0.307_966_1 - 0.077_243_54 * u2));
sqrtf(v[0] * v[0] + v[1] * v[1]) - e * g
}
/// Matches WGSL `sign(r) * max(abs(r) - cut, 0.0)`: zero stays zero even when `cut < 0.0`.
fn inset_radius(r: f32, cut: f32) -> f32 {
if r == 0.0 {
0.0
} else {
(r.abs() - cut).max(0.0).copysign(r)
}
}
fn ramp(d: f32, fade: f32) -> f32 {
if fade == 0.0 {
return clamp(d + 0.5);
}
let x = clamp(d / fade.abs());
if fade < 0.0 { x } else { x * x * (3.0 - 2.0 * x) }
}
fn erf(x: f32) -> f32 {
let s = if x > 0.0 {
1.0
} else if x < 0.0 {
-1.0
} else {
0.0
};
let a = x.abs();
let r = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
let r = r * r;
s - s / (r * r)
}
fn shadow(p: [f32; 2], h: [f32; 2], sigma: f32, corner: f32) -> f32 {
let lo = p[1] - h[1];
let hi = p[1] + h[1];
let start = (-3.0 * sigma).clamp(lo, hi);
let end = (3.0 * sigma).clamp(lo, hi);
let step = (end - start) / 4.0;
let mut y = start + step * 0.5;
let mut v = 0.0;
for _ in 0..4 {
let delta = (h[1] - corner - (p[1] - y).abs()).min(0.0);
let curved = h[0] - corner + sqrtf((corner * corner - delta * delta).max(0.0));
let scale = sqrtf(0.5) / sigma;
let left = 0.5 + 0.5 * erf((p[0] - curved) * scale);
let right = 0.5 + 0.5 * erf((p[0] + curved) * scale);
let gaussian =
expf(-(y * y) / (2.0 * sigma * sigma)) / (sqrtf(2.0 * std::f32::consts::PI) * sigma);
v += (right - left) * gaussian * step;
y += step;
}
v
}
/// Coverage of a stroke segment from `a` to `b`, `hw` half width, round or butt caps
/// (`shader.wgsl` `segment`).
fn segment(p: [f32; 2], a: [f32; 2], b: [f32; 2], hw: f32, round: bool) -> f32 {
let w = hw.max(0.5);
let weight = (hw * 2.0).min(1.0);
let ab = [b[0] - a[0], b[1] - a[1]];
let len = sqrtf(ab[0] * ab[0] + ab[1] * ab[1]);
let ap = [p[0] - a[0], p[1] - a[1]];
let d = if len < 1e-4 {
if !round {
return 0.0;
}
sqrtf(ap[0] * ap[0] + ap[1] * ap[1]) - w
} else {
let dir = [ab[0] / len, ab[1] / len];
let along = ap[0] * dir[0] + ap[1] * dir[1];
if round {
let t = along.clamp(0.0, len);
let dx = ap[0] - dir[0] * t;
let dy = ap[1] - dir[1] * t;
sqrtf(dx * dx + dy * dy) - w
} else {
let across = (dir[0] * ap[1] - dir[1] * ap[0]).abs();
let q = [(along - len * 0.5).abs() - len * 0.5, across - w];
let mx = q[0].max(0.0);
let my = q[1].max(0.0);
q[0].max(q[1]).min(0.0) + sqrtf(mx * mx + my * my)
}
};
clamp(0.5 - d) * weight
}
/// Signed distance from `p` to edge `a -> b`, positive on `c`'s side (`shader.wgsl` `edge`).
fn edge(p: [f32; 2], a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> f32 {
let e = [b[0] - a[0], b[1] - a[1]];
let l = sqrtf(e[0] * e[0] + e[1] * e[1]).max(1e-6);
let n = [-e[1] / l, e[0] / l];
let s = if (c[0] - a[0]) * n[0] + (c[1] - a[1]) * n[1] >= 0.0 {
1.0
} else {
-1.0
};
((p[0] - a[0]) * n[0] + (p[1] - a[1]) * n[1]) * s
}
/// Tie-breaking shared-edge ownership (`shader.wgsl` `owns`).
fn owns(p: [f32; 2], a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> bool {
let swap = a[0] > b[0] || (a[0] == b[0] && a[1] > b[1]);
let (lo, hi) = if swap { (b, a) } else { (a, b) };
let e = [hi[0] - lo[0], hi[1] - lo[1]];
let side = e[0] * (c[1] - lo[1]) - e[1] * (c[0] - lo[0]);
let v = e[0] * (p[1] - lo[1]) - e[1] * (p[0] - lo[0]);
if side > 0.0 { v >= 0.0 } else { v < 0.0 }
}
/// Antialiased coverage across a boundary edge `a -> b` (`shader.wgsl` `soft`).
fn soft(p: [f32; 2], a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> f32 {
let d = edge(p, a, b, c);
let e = [b[0] - a[0], b[1] - a[1]];
let t = ((p[0] - a[0]) * e[0] + (p[1] - a[1]) * e[1]) / (e[0] * e[0] + e[1] * e[1]).max(1e-6);
if !(0.0..=1.0).contains(&t) {
return if d >= 0.0 { 1.0 } else { 0.0 };
}
clamp(d + 0.5)
}
/// Filled triangle coverage with per-edge antialiasing bitmask (`shader.wgsl` `triangle`).
fn triangle(p: [f32; 2], a: [f32; 2], b: [f32; 2], c: [f32; 2], aa: u32) -> f32 {
let mut cov = 1.0;
if (aa & 1) == 1 {
cov *= soft(p, a, b, c);
} else if !owns(p, a, b, c) {
return 0.0;
}
if (aa & 2) == 2 {
cov *= soft(p, b, c, a);
} else if !owns(p, b, c, a) {
return 0.0;
}
if (aa & 4) == 4 {
cov *= soft(p, c, a, b);
} else if !owns(p, c, a, b) {
return 0.0;
}
cov
}
fn ring_arc(p: [f32; 2], size: [f32; 2], radii: [f32; 4], bw: f32) -> (f32, f32) {
let h = bw * 0.5;
let m = (size[0] * 0.5).min(size[1] * 0.5);
let rc = radii.map(|r| (r.abs().min(m) - h).max(0.0));
let e = rc.map(|r| r + h);
let arc = rc.map(|r| r * 1.5707964);
let s_tr = (size[0] - bw - rc[0] - rc[1]).max(0.0);
let s_right = s_tr + arc[1];
let s_br = s_right + (size[1] - bw - rc[1] - rc[2]).max(0.0);
let s_bottom = s_br + arc[2];
let s_bl = s_bottom + (size[0] - bw - rc[2] - rc[3]).max(0.0);
let s_left = s_bl + arc[3];
let s_tl = s_left + (size[1] - bw - rc[3] - rc[0]).max(0.0);
let top = p[0] - e[0];
let right = s_right + p[1] - e[1];
let bottom = s_bottom + size[0] - e[2] - p[0];
let left = s_left + size[1] - e[3] - p[1];
let s = if p[0] > size[0] * 0.5 {
if p[1] > size[1] * 0.5 {
let v = [p[0] - (size[0] - e[2]), p[1] - (size[1] - e[2])];
if v[0] > 0.0 && v[1] > 0.0 { s_br + atan2f(v[1], v[0]) * rc[2] }
else if size[0] - p[0] < size[1] - p[1] { right } else { bottom }
} else {
let v = [p[0] - (size[0] - e[1]), p[1] - e[1]];
if v[0] > 0.0 && v[1] < 0.0 { s_tr + atan2f(v[0], -v[1]) * rc[1] }
else if size[0] - p[0] < p[1] { right } else { top }
}
} else if p[1] > size[1] * 0.5 {
let v = [p[0] - e[3], p[1] - (size[1] - e[3])];
if v[0] < 0.0 && v[1] > 0.0 { s_bl + atan2f(-v[0], v[1]) * rc[3] }
else if p[0] < size[1] - p[1] { left } else { bottom }
} else {
let v = [p[0] - e[0], p[1] - e[0]];
if v[0] < 0.0 && v[1] < 0.0 { s_tl + atan2f(-v[1], -v[0]) * rc[0] }
else if p[0] < p[1] { left } else { top }
};
(s, s_tl + arc[0])
}
fn dash_cov(s: f32, total: f32, d: [f32; 3]) -> f32 {
let nominal = d[0] + d[1];
let k = total.max(0.001) / ((floorf(total / nominal + 0.5)).max(1.0) * nominal);
let period = nominal * k;
let dash = d[0] * k;
let a = s + d[2] * k - dash * 0.5;
let m = a - period * floorf(a / period + 0.5);
clamp(dash * 0.5 - m.abs() + 0.5)
}
/// A border over its own background, as CSS paints one (shader.wgsl `border_over`).
#[allow(clippy::too_many_arguments)]
fn border_over(fill: [f32; 4], edge: [f32; 4], d: f32, inner_d: f32, soft: f32, bw: f32, opacity: f32, shrink: bool) -> [f32; 4] {
let cov = clamp(0.5 - d / (soft * 2.0));
let ring = (cov - clamp(0.5 - inner_d / (soft * 2.0))).max(0.0);
let hide = clamp(edge[3] / opacity.clamp(1e-6, 1.0));
let pull = if shrink && hide > 0.999 { bw * 0.5 } else { 0.0 };
let under = clamp(0.5 - (d + pull) / (soft * 2.0));
std::array::from_fn(|c| edge[c] * ring + fill[c] * (under * (1.0 - hide * ring)))
}
/// How much of the pixel at `p` the box covers: the exact area at a square corner, the distance
/// estimate at a rounded one (shader.wgsl `box_cov`).
fn box_cov(p: [f32; 2], h: [f32; 2], radii: [f32; 4]) -> f32 {
let r = if p[0] > 0.0 {
if p[1] > 0.0 { radii[2] } else { radii[1] }
} else if p[1] > 0.0 {
radii[3]
} else {
radii[0]
};
if r == 0.0 {
let e = |a: usize| clamp(h[a].min(p[a] + 0.5) - (-h[a]).max(p[a] - 0.5));
return e(0) * e(1);
}
clamp(0.5 - sd(p, h, radii))
}
pub(crate) fn fragment(i: &Primitive, atlas: &Atlas, screen: [f32; 2]) -> [f32; 4] {
let kind = i.params[1] as u32;
// An effect slot (kind 12) holds a compositor's place in the stream and covers no pixels.
if kind == 12 {
return [0.0; 4];
}
// A glyph's params[0] turns its quad clockwise about the rect centre. Undo the turn so
// bounds and sampling run in the glyph's own frame; the clip stays on screen.
let rotated = kind == 2 && i.params[0] != 0.0;
let p = if rotated {
let (s, c) = (sinf(i.params[0]), cosf(i.params[0]));
let center = [i.rect[0] + i.rect[2] * 0.5, i.rect[1] + i.rect[3] * 0.5];
let d = [screen[0] - center[0], screen[1] - center[1]];
[center[0] + (c * d[0] + s * d[1]), center[1] + (c * d[1] - s * d[0])]
} else {
screen
};
let grow = match kind {
1 => i.params[2] * 3.0 + 1.0,
2 => 0.0,
3 | 5 | 6 => 1.0,
_ => 1.0 + i.params[2] * 2.0,
};
let mut lo = [i.rect[0] - grow, i.rect[1] - grow];
let mut hi = [lo[0] + (i.rect[2] + 2.0 * grow), lo[1] + (i.rect[3] + 2.0 * grow)];
// One band of a big shadow or border ring rasterizes only its window (`shader.wgsl` `base_vs`).
if kind <= 1 && i.uv[2] < 0.0 {
lo = [lo[0].max(i.rect[0] + i.uv[0]), lo[1].max(i.rect[1] + i.uv[1])];
hi = [hi[0].min(i.rect[0] - i.uv[2]).max(lo[0]), hi[1].min(i.rect[1] + i.uv[3]).max(lo[1])];
}
// Rasterization bounds matter for glyphs, bands and very soft shadows. Pixel centers,
// half-open right/bottom edges, matching the two axis-aligned GPU triangles.
if p[0] < lo[0] || p[1] < lo[1] || p[0] >= hi[0] || p[1] >= hi[1] {
return [0.0; 4];
}
let h = [i.rect[2] * 0.5, i.rect[3] * 0.5];
let q = [p[0] - (i.rect[0] + h[0]), p[1] - (i.rect[1] + h[1])];
let mut col = [0.0; 4];
match kind {
0 => {
let d = sd(q, h, i.radii);
let soft = i.params[2].max(0.5);
let bw = i.params[0];
if bw > 0.0 {
// Per-side widths (top, right, bottom, left) in `uv`; a band window has uv[2] < 0.
let w = i.uv;
let sides = w[2] >= 0.0 && w != [0.0; 4];
let inner_d = if sides {
let ih = [(h[0] - (w[1] + w[3]) * 0.5).max(0.0), (h[1] - (w[0] + w[2]) * 0.5).max(0.0)];
let at = [q[0] - (w[3] - w[1]) * 0.5, q[1] - (w[0] - w[2]) * 0.5];
let cut = [w[0].max(w[3]), w[0].max(w[1]), w[2].max(w[1]), w[2].max(w[3])];
sd(at, ih, std::array::from_fn(|n| inset_radius(i.radii[n], cut[n])))
} else {
d + bw
};
col = border_over(i.fill, i.border, d, inner_d, soft, bw, i.params[3], !sides && i.radii != [0.0; 4]);
} else {
col = i.fill.map(|c| c * clamp(0.5 - d / (soft * 2.0)));
}
}
1 => {
let mut cov = shadow(q, h, i.params[2].max(0.01), i.radii[0].abs().min(h[0].min(h[1])));
if i.uv[2] > 0.0 {
let hole = [i.uv[2] * 0.5, i.uv[3] * 0.5];
let at = [p[0] - (i.rect[0] + i.uv[0] + hole[0]), p[1] - (i.rect[1] + i.uv[1] + hole[1])];
cov *= clamp(0.5 + sd(at, hole, [i.radii[3]; 4]));
}
col = i.fill.map(|c| c * cov);
}
2 => {
let cov = if i.uv[2] > 0.0 || rotated {
let span = if i.uv[2] > 0.0 { [i.uv[2], i.uv[3]] } else { [i.rect[2], i.rect[3]] };
let px = (p[0] - i.rect[0]) * span[0] / i.rect[2] - 0.5;
let py = (p[1] - i.rect[1]) * span[1] / i.rect[3] - 0.5;
let x = (i.uv[0] + floorf(px)) as i32;
let y = (i.uv[1] + floorf(py)) as i32;
let fx = px - floorf(px);
let fy = py - floorf(py);
mix(
mix(atlas.load(x, y), atlas.load(x + 1, y), fx),
mix(atlas.load(x, y + 1), atlas.load(x + 1, y + 1), fx),
fy,
)
} else {
atlas.load(
(i.uv[0] + floorf(p[0] - i.rect[0])) as i32,
(i.uv[1] + floorf(p[1] - i.rect[1])) as i32,
)
};
col = i.fill.map(|c| c * powf(cov, i.params[3]));
}
3 => {
let cov = box_cov(q, h, i.radii);
let spread = i.params[0];
let ih = h.map(|v| (v - spread).max(0.0));
let q = [q[0] - i.uv[0], q[1] - i.uv[1]];
let lit = if i.params[2] < 0.3 {
box_cov(q, ih, i.radii.map(|r| inset_radius(r, spread)))
} else {
shadow(
q,
ih,
i.params[2],
(i.radii[0].abs() - spread).min(ih[0].min(ih[1])).max(0.0),
)
};
col = i.fill.map(|c| c * cov * (1.0 - clamp(lit)));
}
4 => {
let d = sd(q, h, i.radii);
let soft = i.params[2].max(0.5);
let bw = i.params[0];
let t = clamp((p[1] - i.rect[1]) / i.rect[3].max(1.0));
col = if bw > 0.0 {
let edge = std::array::from_fn(|c| mix(i.border[c], i.uv[c], t));
border_over(i.fill, edge, d, d + bw, soft, bw, i.params[3], i.radii != [0.0; 4])
} else {
let cov = clamp(0.5 - d / (soft * 2.0));
std::array::from_fn(|c| mix(i.fill[c], i.uv[c], t) * cov)
};
}
5 => {
let cov = segment(
screen,
[i.radii[0], i.radii[1]],
[i.radii[2], i.radii[3]],
i.params[0],
i.params[2] > 0.5,
);
col = i.fill.map(|c| c * cov);
}
6 => {
let cov = triangle(
screen,
[i.radii[0], i.radii[1]],
[i.radii[2], i.radii[3]],
[i.uv[0], i.uv[1]],
(i.params[0] + 0.5) as u32,
);
col = i.fill.map(|c| c * cov);
}
10 => {
let d = sd(q, h, i.radii);
let soft = i.params[2].max(0.5);
let ring = clamp(0.5 - d / (soft * 2.0)) - clamp(0.5 - (d + i.params[0]) / (soft * 2.0));
let t = clamp((p[1] - i.rect[1]) / i.rect[3].max(1.0));
let local = [p[0] - i.rect[0], p[1] - i.rect[1]];
let (s, total) = ring_arc(local, [i.rect[2], i.rect[3]], i.radii, i.params[0]);
let cov = ring * dash_cov(s, total, [i.uv[0], i.uv[1], i.uv[2]]);
col = std::array::from_fn(|c| mix(i.fill[c], i.border[c], t) * cov);
}
11 => {
let d = sd(q, h, i.radii);
let soft = i.params[2].max(0.5);
let cov = clamp(0.5 - d / (soft * 2.0));
let t0_raw = i.params[0];
let t1_raw = i.params[3];
let lower_open = t0_raw >= 1.5;
let upper_open = t1_raw >= 1.5;
let t0 = if lower_open { t0_raw - 2.0 } else { t0_raw };
let t1 = if upper_open { t1_raw - 2.0 } else { t1_raw };
let t = if i.uv[2] > 0.0 {
let dx = (p[0] - i.rect[0] - i.uv[0]) / i.uv[2];
let dy = (p[1] - i.rect[1] - i.uv[1]) / i.uv[3];
sqrtf(dx * dx + dy * dy)
} else {
0.5 + (q[0] * i.uv[0] + q[1] * i.uv[1])
};
if !((lower_open && t < t0) || (upper_open && t >= t1)) {
let u = if t1 <= t0 + 1e-6 {
if t >= t0 { 1.0 } else { 0.0 }
} else {
clamp((t - t0) / (t1 - t0))
};
col = std::array::from_fn(|c| mix(i.fill[c], i.border[c], u) * cov);
}
}
_ => panic!("unsupported primitive kind"),
}
let clip = clip_coverage(i, screen);
col.map(|c| c * clip)
}
pub(crate) fn layer_clip_coverage(i: &Primitive, screen: [f32; 2]) -> f32 {
clip_coverage(i, screen) * if i.params[3] == 0.0 { hole_alpha(screen, i.radii) } else { 1.0 }
}
/// A layer's round hole (`El::cutout_circle`): centre `h[0..2]`, clear within `h[2]`, whole from
/// `h[3]`, linear between and at least a pixel wide; none when `h[3]` is zero.
fn hole_alpha(p: [f32; 2], h: [f32; 4]) -> f32 {
if h[3] <= 0.0 { return 1.0; }
let (dx, dy) = (p[0] - h[0], p[1] - h[1]);
clamp((sqrtf(dx * dx + dy * dy) - (h[2] + h[3]) * 0.5) / (h[3] - h[2]).max(1.0) + 0.5)
}
/// Matches `instance.rs::pack_clip_radii` so CPU clipping sees the same packed quantization
/// (`0.5` px / `2.0` px mixed steps, clamped to half the shorter clip side) as `clip.wgsl`.
pub(crate) fn pack_clip_radii(clip: [f32; 4], radii: [f32; 4]) -> u32 {
let half = ((clip[2] - clip[0]).min(clip[3] - clip[1]) * 0.5).max(0.0);
let clamped = radii.map(|radius| {
let r = radius.abs().min(half).min(f32::from_bits(0x5fff_ffff));
if radius < 0.0 && r > 0.0 { -r } else { r }
});
if clamped[0] == clamped[1] && clamped[1] == clamped[2] && clamped[2] == clamped[3] {
return if clamped[0] == 0.0 { 0 } else { clamped[0].to_bits() };
}
let continuous = clamped.iter().any(|&r| r < 0.0);
let max_r = clamped.iter().fold(0.0f32, |m, r| m.max(r.abs()));
let coarse = max_r > 63.5;
let inv_step = if coarse { 0.5 } else { 2.0 };
let mut bits = 0x6000_0000u32
| if continuous { 0x8000_0000 } else { 0 }
| if coarse { 0x1000_0000 } else { 0 };
for (idx, r) in clamped.into_iter().enumerate() {
let q = roundf(r.abs() * inv_step).clamp(0.0, 127.0) as u32;
bits |= q << (idx * 7);
}
bits
}
fn unpack_clip_radii(w: u32) -> [f32; 4] {
if w == 0 {
return [0.0; 4];
}
if (w & 0x6000_0000) != 0x6000_0000 {
return [f32::from_bits(w); 4];
}
let step = if (w & 0x1000_0000) != 0 { 2.0 } else { 0.5 };
let sign = if (w & 0x8000_0000) != 0 { -1.0 } else { 1.0 };
std::array::from_fn(|idx| {
let q = (w >> (idx * 7)) & 0x7f;
if q == 0 { 0.0 } else { q as f32 * step * sign }
})
}
fn clip_coverage(i: &Primitive, screen: [f32; 2]) -> f32 {
let origin = i.fade_origin.unwrap_or(i.clip);
let p = screen;
let hard = [p[0] - i.clip[0], p[1] - i.clip[1], i.clip[2] - p[0], i.clip[3] - p[1]];
let mut alpha: f32 = (0..4).map(|edge| {
let width = half::f16::from_f32(i.fade[edge].clamp(-65504.0, 65504.0)).to_f32();
let distance = if edge < 2 { i.clip[edge] - origin[edge] } else { origin[edge] - i.clip[edge] };
let w = i.fade[edge].abs();
let offset = if w > 0.0 { (distance / w).clamp(0.0, 1.0) } else { 0.0 };
let offset = libm::floorf(offset * 255.0 + 0.5) / 255.0;
if offset >= 1.0 { ramp(hard[edge], 0.0) }
else if offset > 0.0 { ramp(hard[edge], 0.0).min(ramp(hard[edge] + offset * width.abs(), width)) }
else { ramp(hard[edge], width) }
}).product();
let radii = if i.params[1] == 8.0 { i.clip_radii.unwrap_or(i.border) } else { i.clip_radii.unwrap_or([0.0; 4]) };
let packed = pack_clip_radii(i.clip, radii);
if packed != 0 {
let half = [(i.clip[2] - i.clip[0]) * 0.5, (i.clip[3] - i.clip[1]) * 0.5];
let q = [p[0] - i.clip[0] - half[0], p[1] - i.clip[1] - half[1]];
alpha *= clamp(0.5 - sd(q, half, unpack_clip_radii(packed)));
}
alpha
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_negative_fade_ramps_linearly_and_a_positive_one_eases() {
for (d, linear) in [(0.0, 0.0), (4.0, 0.25), (8.0, 0.5), (12.0, 0.75), (16.0, 1.0), (20.0, 1.0)] {
assert!((ramp(d, -16.0) - linear).abs() < 1e-6, "linear at {d}: {}", ramp(d, -16.0));
}
assert!((ramp(4.0, 16.0) - 0.15625).abs() < 1e-6, "smoothstep a quarter in");
assert_eq!(ramp(8.0, 16.0), ramp(8.0, -16.0), "both are half way at the middle");
}
// Walking the ring's centre line clockwise, arc length grows by the distance walked and
// comes back round to zero after exactly the line's length.
#[test]
fn ring_arc_walks_the_centre_line() {
for (size, radii, bw) in [
([40.0f32, 20.0], [10.0f32; 4], 2.0f32),
([30.0, 30.0], [0.0, 6.0, 15.0, 3.0], 1.0),
([50.0, 12.0], [6.0; 4], 0.5),
([24.0, 18.0], [0.0; 4], 1.5),
] {
let h = bw * 0.5;
let rc = radii.map(|r: f32| (r.min(size[0].min(size[1]) * 0.5) - h).max(0.0));
let (_, total) = ring_arc([size[0] * 0.5, h], size, radii, bw);
let expected = 2.0 * (size[0] + size[1] - 2.0 * bw)
- (2.0 - std::f32::consts::FRAC_PI_2) * rc.iter().sum::<f32>();
assert!((total - expected).abs() < 1e-3, "{total} vs {expected}");
// Sample the centre line by marching a point round the inset rounded rect.
let mut points = Vec::new();
let steps = 400;
for n in 0..steps {
let angle = n as f32 / steps as f32 * std::f32::consts::TAU;
let dir = [libm::sinf(angle), -libm::cosf(angle)];
// Ray from the centre to the centre line: bisect on the ring's centre distance.
let (mut lo, mut hi) = (0.0, size[0] + size[1]);
for _ in 0..60 {
let mid = (lo + hi) * 0.5;
let q = [dir[0] * mid, dir[1] * mid];
if sd(q, [size[0] * 0.5, size[1] * 0.5], radii) + h < 0.0 { lo = mid } else { hi = mid }
}
points.push([size[0] * 0.5 + dir[0] * lo, size[1] * 0.5 + dir[1] * lo]);
}
// Each step advances s by the chord, or up to a corner's detour where the line turns
// sharply, and the steps add up to one trip round.
let mut trip = 0.0;
for n in 1..=steps {
let (a, b) = (points[n - 1], points[n % steps]);
let chord = sqrtf((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2));
let ds = (ring_arc(b, size, radii, bw).0 - ring_arc(a, size, radii, bw).0).rem_euclid(total);
assert!(ds > chord - 1e-3 && ds < chord * 1.5 + 1e-3, "{size:?} {radii:?} step {n}: {ds} vs {chord}");
trip += ds;
}
assert!((trip - total).abs() < 1e-2, "{trip} vs {total}");
}
}
#[test]
fn dash_pattern_closes_at_the_seam() {
for total in [37.3, 100.0, 251.9, 3.0] {
for d in [[4.0, 3.0, 0.0], [6.0, 2.5, 1.7], [10.0, 10.0, -4.0]] {
for n in 0..50 {
let s = n as f32 * 0.37;
assert!((dash_cov(s, total, d) - dash_cov(s + total, total, d)).abs() < 1e-3);
assert!((dash_cov(s, total, d) - dash_cov(s - total, total, d)).abs() < 1e-3);
}
}
}
// With no phase the pattern starts on a dash: half covered at s = 0, full just after.
assert!((dash_cov(0.0, 100.0, [4.0, 3.0, 0.0]) - 0.5).abs() < 1e-4);
assert_eq!(dash_cov(1.0, 100.0, [4.0, 3.0, 0.0]), 1.0);
// One nominal period of phase is one whole stretched period.
for n in 0..50 {
let s = n as f32 * 1.3;
assert!((dash_cov(s, 100.0, [4.0, 3.0, 7.0]) - dash_cov(s, 100.0, [4.0, 3.0, 0.0])).abs() < 1e-3);
}
}
#[test]
fn pack_clip_radii_matches_uniform_fine_coarse_and_continuous_encoding() {
let clip = [0.0, 0.0, 600.0, 600.0];
assert_eq!(pack_clip_radii(clip, [0.0; 4]), 0);
// Uniform corners round-trip as exact f32 bits.
let uniform = pack_clip_radii(clip, [-12.25; 4]);
assert_eq!(unpack_clip_radii(uniform), [-12.25; 4]);
// Mixed corners <= 63.5 px quantize to 0.5 px steps.
let fine = pack_clip_radii(clip, [10.2, 4.8, 0.0, 63.4]);
assert_eq!(unpack_clip_radii(fine), [10.0, 5.0, 0.0, 63.5]);
// Mixed corners > 63.5 px quantize to 2.0 px steps and saturate at 254 px.
let coarse = pack_clip_radii(clip, [-71.3, -280.0, 0.0, -13.1]);
assert_eq!(unpack_clip_radii(coarse), [-72.0, -254.0, 0.0, -14.0]);
// Radii clamp to half the shorter clip side.
let small_clip = [0.0, 0.0, 20.0, 40.0];
assert_eq!(unpack_clip_radii(pack_clip_radii(small_clip, [50.0, 12.0, 15.0, 10.0])), [10.0; 4]);
}
#[test]
fn inset_radius_keeps_zero_corners_square_under_negative_spread() {
assert_eq!(inset_radius(0.0, -4.0), 0.0);
assert_eq!(inset_radius(6.0, -4.0), 10.0);
assert_eq!(inset_radius(-6.0, -4.0), -10.0);
assert_eq!(inset_radius(-6.0, 8.0), -0.0);
}
}
+45
View File
@@ -0,0 +1,45 @@
#![allow(unsafe_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
struct Counting;
thread_local! { static ALLOCS: Cell<usize> = const { Cell::new(0) }; }
fn bump() {
ALLOCS.with(|c| c.set(c.get() + 1));
}
// SAFETY: forwards every allocation call to `System`, only counting allocations on this thread.
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
bump();
// SAFETY: delegates allocation with the caller's layout to `System`.
unsafe { System.alloc(l) }
}
unsafe fn alloc_zeroed(&self, l: Layout) -> *mut u8 {
bump();
// SAFETY: delegates zeroed allocation with the caller's layout to `System`.
unsafe { System.alloc_zeroed(l) }
}
unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
// SAFETY: delegates deallocation of `p` and `l` to `System`.
unsafe { System.dealloc(p, l) }
}
unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
bump();
// SAFETY: delegates reallocation of `p`, `l` and `n` to `System`.
unsafe { System.realloc(p, l, n) }
}
}
#[global_allocator]
static A: Counting = Counting;
#[test]
fn steady_reference_frames_allocate_nothing() {
let scene = rune_ref::generate::seeded(24, 8);
let mut frame = rune_ref::Frame::new(64, 64, true);
frame.render(&scene);
let before = ALLOCS.with(Cell::get);
for _ in 0..30 {
frame.render(std::hint::black_box(&scene));
}
assert_eq!(ALLOCS.with(Cell::get) - before, 0);
}
+791
View File
@@ -0,0 +1,791 @@
#![cfg(feature = "gpu")]
use proptest::{
prelude::*,
test_runner::{Config, FileFailurePersistence, TestError, TestRunner},
};
use rune_ref::{
Frame, Primitive, Scene, compare, generate,
gpu::{GpuRenderer, text_run},
};
use std::{cell::RefCell, path::PathBuf};
// A provisional 2-LSB cap per primitive; measured maxima and backend in research/24.
// Composite has its own 2-LSB cap, never multiplied by primitive count.
const BUDGET: [u8; 5] = [2, 2, 2, 2, 2];
fn check(gpu: &mut GpuRenderer, scene: &Scene, tolerance: u8) -> Result<u8, String> {
let mut cpu = Frame::new(scene.width, scene.height, true);
cpu.render(scene);
let actual = gpu.render(scene);
let diff = compare(scene, &cpu, &actual, tolerance);
if diff.outlier_pixels > 0 {
Err(serde_json::to_string(&diff).unwrap())
} else {
Ok(diff.max_channel)
}
}
fn save(name: &str, scene: &Scene) {
let dir = std::env::var_os("RUNE_REF_FAILURES")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("failures"));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join(format!("{name}.json"));
std::fs::write(&path, serde_json::to_vec_pretty(scene).unwrap()).unwrap();
eprintln!("saved replay {}", path.display());
}
#[test]
fn cpu_gpu_corpus() {
let mut gpu = GpuRenderer::default();
let mut maxima = [0u8; 6];
for seed in 0..128 {
let scene = generate::seeded(seed, 8);
for primitive in &scene.primitives {
let mut single = scene.clone();
single.primitives = vec![primitive.clone()];
let kind = primitive.params[1] as usize;
match check(&mut gpu, &single, BUDGET[kind]) {
Ok(max) => maxima[kind] = maxima[kind].max(max),
Err(e) => {
save(&format!("seed-{seed}-kind-{kind}"), &single);
panic!("{e}");
}
}
}
match check(&mut gpu, &scene, 2) {
Ok(max) => maxima[5] = maxima[5].max(max),
Err(e) => {
save(&format!("seed-{seed}-composite"), &scene);
panic!("{e}");
}
}
}
for seed in 0..16 {
let mut scene = generate::seeded(seed, 4);
text_run(&mut scene, seed);
if let Err(e) = check(&mut gpu, &scene, 2) {
save(&format!("text-{seed}"), &scene);
panic!("{e}");
}
}
eprintln!("METRIC channel_max_rect_shadow_glyph_inset_gradient_composite={maxima:?}");
}
#[test]
fn cpu_gpu_proptest() {
let gpu = RefCell::new(GpuRenderer::default());
let mut runner = TestRunner::new(Config {
cases: 128,
max_shrink_iters: 2048,
failure_persistence: Some(Box::new(FileFailurePersistence::Direct(
"tests/differential.proptest-regressions",
))),
..Config::default()
});
let strategy = prop::collection::vec(any::<[u8; 32]>(), 1..9);
let result = runner.run(&strategy, |records| {
let scene = generate::scene(&records);
check(&mut gpu.borrow_mut(), &scene, 2).map_err(TestCaseError::fail)?;
Ok(())
});
if let Err(TestError::Fail(reason, records)) = &result {
save("minimized", &generate::scene(records));
eprintln!("minimized differential failure: {reason}");
}
assert!(result.is_ok(), "{result:?}");
}
#[test]
fn saved_regressions() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("regressions");
let mut gpu = GpuRenderer::default();
for entry in std::fs::read_dir(root).unwrap() {
let path = entry.unwrap().path();
if path.extension().and_then(|s| s.to_str()) != Some("json") {
continue;
}
let scene: Scene = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
scene.validate().unwrap();
assert!(check(&mut gpu, &scene, 2).is_ok(), "{}", path.display());
}
}
// Quarter turns about a centre on the pixel grid keep every turned edge half a pixel from the
// nearest pixel centre and every sample on a texel centre, so rasterizer and oracle agree.
// The clipped pass cuts the turned footprint unevenly, so a clip in the glyph's own frame differs.
#[test]
fn rotated_glyphs() {
use std::f32::consts::{FRAC_PI_2, PI};
let mut gpu = GpuRenderer::default();
let clips = [
(rune_ref::NO_CLIP, [0.0; 4]),
([24.5, 15.25, 40.0, 26.75], [3.0, 0.0, 0.0, 2.5]),
];
for (n, angle) in [FRAC_PI_2, PI, PI + FRAC_PI_2, -FRAC_PI_2].into_iter().enumerate() {
for uv in [[1.0, 1.0, 0.0, 0.0], [1.0, 1.0, 8.0, 5.0]] {
for (c, (clip, fade)) in clips.into_iter().enumerate() {
let mut scene = generate::scene(&[]);
scene.primitives.push(Primitive {
node: 1,
source: format!("rotated/{n}"),
rect: [20.0, 17.0, 16.0, 10.0],
radii: [0.0; 4],
fill: [0.7, 0.6, 0.5, 0.8],
border: [0.0; 4],
params: [angle, 2.0, 0.0, 1.0],
uv,
clip,
fade,
fade_origin: None,
turn: None,
clip_radii: None,
});
if let Err(e) = check(&mut gpu, &scene, 2) {
save(&format!("rotated-{n}-{}-clip-{c}", uv[2]), &scene);
panic!("{e}");
}
}
}
}
}
#[test]
fn gpu_metamorphic() {
let mut gpu = GpuRenderer::default();
let close = |a: &[u8], b: &[u8]| {
assert_eq!(a.len(), b.len());
assert!(
a.iter().zip(b).all(|(a, b)| a.abs_diff(*b) <= 2),
"metamorphic pixel mismatch"
);
};
for seed in 0..32 {
let scene = generate::seeded(seed, 8);
let original = gpu.render(&scene);
let mut shifted = scene.clone();
shifted.width += 4;
shifted.height += 6;
generate::translate(&mut shifted, 4.0, 6.0);
let actual = gpu.render(&shifted);
for y in 0..64 {
close(
&original[y * 256..(y + 1) * 256],
&actual[((y + 6) * 68 + 4) * 4..((y + 6) * 68 + 68) * 4],
);
}
let mut transparent = scene.clone();
for mut p in scene.primitives.clone() {
p.fill = [0.0; 4];
p.border = [0.0; 4];
if p.params[1] == 4.0 {
p.uv = [0.0; 4];
}
transparent.primitives.push(p);
}
assert_eq!(original, gpu.render(&transparent));
let mut full = scene.clone();
for p in &mut full.primitives {
p.clip = rune_ref::NO_CLIP;
p.fade = [0.0; 4];
}
let unclipped = gpu.render(&full);
for p in &mut full.primitives {
p.clip = [0.0, 0.0, 64.0, 64.0];
}
close(&unclipped, &gpu.render(&full));
let mut disjoint = scene.clone();
for p in &mut disjoint.primitives {
p.clip = [0.0, 0.0, 31.0, 64.0];
p.fade = [0.0; 4];
}
let n = disjoint.primitives.len();
for mut p in scene.primitives.clone() {
p.rect[0] += 32.0;
p.clip = [32.0, 0.0, 64.0, 64.0];
p.fade = [0.0; 4];
disjoint.primitives.push(p);
}
let first = gpu.render(&disjoint);
disjoint.primitives.rotate_left(n);
assert_eq!(first, gpu.render(&disjoint));
}
}
#[test]
fn cpu_gpu_dashed() {
let mut gpu = GpuRenderer::default();
let mut max = 0;
for seed in 0..64 {
let scene = generate::dashed(seed, 8);
for (n, primitive) in scene.primitives.iter().enumerate() {
let mut single = scene.clone();
single.primitives = vec![primitive.clone()];
match check(&mut gpu, &single, 2) {
Ok(m) => max = max.max(m),
Err(e) => {
save(&format!("dashed-{seed}-{n}"), &single);
panic!("{e}");
}
}
}
if let Err(e) = check(&mut gpu, &scene, 2) {
save(&format!("dashed-{seed}-composite"), &scene);
panic!("{e}");
}
}
eprintln!("METRIC channel_max_dashed={max}");
}
#[test]
fn cpu_gpu_effect_slots() {
let mut gpu = GpuRenderer::default();
for seed in 0..16 {
let mut scene = generate::seeded(seed, 8);
let mut slots = scene.primitives.clone();
for slot in &mut slots {
slot.fill = [0.0, 0.0, 0.0, 1.0];
slot.border = [0.0; 4];
slot.params = [0.0, 12.0, 6.0, 1.0];
slot.uv = [0.0; 4];
}
scene.primitives.extend(slots);
scene.primitives.rotate_right(4);
if let Err(e) = check(&mut gpu, &scene, 2) {
save(&format!("effect-{seed}"), &scene);
panic!("{e}");
}
}
}
#[test]
fn cpu_gpu_radial() {
let mut gpu = GpuRenderer::default();
let mut max = 0;
for seed in 0..64 {
let scene = generate::radial(seed, 8);
for (n, primitive) in scene.primitives.iter().enumerate() {
let mut single = scene.clone();
single.primitives = vec![primitive.clone()];
match check(&mut gpu, &single, 2) {
Ok(m) => max = max.max(m),
Err(e) => {
save(&format!("radial-{seed}-{n}"), &single);
panic!("{e}");
}
}
}
if let Err(e) = check(&mut gpu, &scene, 2) {
save(&format!("radial-{seed}-composite"), &scene);
panic!("{e}");
}
}
// Multi-stop radial gradient split into two non-overlapping band segments at t = 0.5.
let mut multi = generate::scene(&[]);
let base = Primitive {
node: 1,
source: "radial/multi-0".into(),
rect: [8.0, 8.0, 48.0, 48.0],
radii: [12.0; 4],
fill: [0.8, 0.2, 0.1, 0.9],
border: [0.2, 0.7, 0.4, 0.9],
params: [0.0, 11.0, 0.0, 2.5],
uv: [24.0, 24.0, 24.0, 20.0],
clip: rune_ref::NO_CLIP,
fade: [0.0; 4],
fade_origin: None,
turn: None,
clip_radii: None,
};
let outer = Primitive {
node: 2,
source: "radial/multi-1".into(),
fill: base.border,
border: [0.05, 0.1, 0.3, 0.4],
params: [2.5, 11.0, 0.0, 1.0],
..base.clone()
};
multi.primitives = vec![base, outer];
match check(&mut gpu, &multi, 2) {
Ok(m) => max = max.max(m),
Err(e) => {
save("radial-multi", &multi);
panic!("{e}");
}
}
eprintln!("METRIC channel_max_radial={max}");
}
#[test]
fn cpu_gpu_cached_subtrees() {
use rune::{Color, Cx, El, Env, Runtime, col, el, text};
let mut gpu = GpuRenderer::default();
let build_scene = |cached: bool| {
fn view(cached: &bool, _: &mut Cx<bool>) -> El {
let mut card = col()
.size(48.0, 44.0)
.padding(4.0)
.gap(3.0)
.fill(Color { r: 0.18, g: 0.24, b: 0.36, a: 1.0 })
.radius(8.0)
.border(1.0, Color { r: 0.45, g: 0.62, b: 0.88, a: 1.0 })
.child(text("Rune").color(Color::WHITE))
.child(
el().size(36.0, 12.0)
.fill(Color { r: 0.85, g: 0.32, b: 0.28, a: 0.85 })
.radius(4.0),
);
if *cached {
card = card.cache();
}
col()
.size(64.0, 64.0)
.padding(8.0)
.fill(Color { r: 0.06, g: 0.08, b: 0.12, a: 1.0 })
.child(card)
}
let mut rt = Runtime::new(cached, view, (64.0, 64.0), Env { scale: 1.0, system_dark: true });
rt.frame(0.0);
let primitives = rt
.instances
.iter()
.enumerate()
.map(|(idx, inst)| Primitive::from_instance(inst, idx as u32 + 1, format!("cache/{idx}")))
.collect();
Scene {
width: 64,
height: 64,
clear: [0.025, 0.04, 0.06, 1.0],
primitives,
atlas: rune_ref::Atlas {
width: rune::text::ATLAS_SIZE,
height: rune::text::ATLAS_SIZE,
data: rt.text.atlas.data.clone(),
},
}
};
let uncached = build_scene(false);
let cached = build_scene(true);
assert!(
cached.primitives.iter().any(|p| p.params[1] == 8.0 && p.params[3] == 1.0),
"cached scene must emit KIND_LAYER with cache marker"
);
check(&mut gpu, &uncached, 2).expect("uncached CPU vs GPU");
check(&mut gpu, &cached, 2).expect("cached CPU vs GPU");
let gpu_uncached = gpu.render(&uncached);
let gpu_cached = gpu.render(&cached);
let mut cpu_uncached = Frame::new(64, 64, true);
cpu_uncached.render(&uncached);
let diff = compare(&cached, &cpu_uncached, &gpu_cached, 2);
assert_eq!(diff.outlier_pixels, 0, "cached GPU vs uncached CPU: {diff:?}");
for (a, b) in gpu_uncached.iter().zip(&gpu_cached) {
assert!(a.abs_diff(*b) <= 1, "cached vs uncached GPU mismatch: {a} vs {b}");
}
// A scrolled multi-line text culls offscreen lines by band and clips overhanging ink at the
// viewport edges identically on CPU and GPU.
fn scrolled(_: &(), _: &mut Cx<()>) -> El {
let lines = (0..40).map(|i| format!("Line {i:02} rune")).collect::<Vec<_>>().join("\n");
col()
.size(64.0, 64.0)
.padding(6.0)
.fill(Color { r: 0.06, g: 0.08, b: 0.12, a: 1.0 })
.child(
col()
.w_full()
.h(52.0)
.scroll(rune::ScrollSpec { stick_bottom: false })
.child(text(lines).font(rune::TextStyle::new(11.0, 400.0).lh(14.0)).color(Color::WHITE)),
)
}
let mut rt = Runtime::new((), scrolled, (64.0, 64.0), Env { scale: 1.0, system_dark: true });
rt.frame(0.0);
rt.wheel(32.0, 32.0, -145.0);
rt.frame(1.0 / 60.0);
let scrolled_scene = Scene {
width: 64,
height: 64,
clear: [0.025, 0.04, 0.06, 1.0],
primitives: rt
.instances
.iter()
.enumerate()
.map(|(idx, inst)| Primitive::from_instance(inst, idx as u32 + 1, format!("scroll/{idx}")))
.collect(),
atlas: rune_ref::Atlas {
width: rune::text::ATLAS_SIZE,
height: rune::text::ATLAS_SIZE,
data: rt.text.atlas.data.clone(),
},
};
check(&mut gpu, &scrolled_scene, 2).expect("scrolled multi-line text CPU vs GPU");
}
#[test]
fn cpu_gpu_cached_rounded_clip() {
use rune::render::{Instance, LayerSpec};
let mut scene = generate::scene(&[]);
scene.width = 32;
scene.height = 32;
let begin = Instance::begin_layer([0.0, 0.0, 24.0, 24.0], [0.0, 0.0, 24.0, 24.0],
LayerSpec { clip_radius: 8.0, ..Default::default() });
let mut paint = generate::scene(&[[255; 32]]).primitives.into_iter().next().unwrap();
paint.rect = [0.0, 0.0, 24.0, 24.0];
paint.radii = [0.0; 4];
paint.fill = [1.0; 4];
paint.border = [0.0; 4];
paint.params = [0.0; 4];
paint.clip = rune_ref::NO_CLIP;
paint.fade = [0.0; 4];
paint.fade_origin = None;
scene.primitives = vec![Primitive::from_instance(&begin, 1, "rounded".into()), paint.clone(),
Primitive::from_instance(&Instance::end_layer(), 3, "end".into())];
assert_eq!(f32::from_bits(Instance::from(&scene.primitives[0]).fade[3]), 8.0,
"replay capture must preserve the rounded clip, not compare two square layers");
let mut gpu = GpuRenderer::default();
check(&mut gpu, &scene, 2).expect("rounded layer survives replay capture");
let mut mixed = Instance::begin_layer([0.0, 0.0, 24.0, 24.0], [0.0, 0.0, 24.0, 24.0], LayerSpec::default());
mixed.fade[3] = rune::render::pack_clip_radii(mixed.clip, [-10.0, -10.0, 0.0, -4.0]);
scene.primitives = vec![Primitive::from_instance(&mixed, 1, "mixed-continuous".into()), paint,
Primitive::from_instance(&Instance::end_layer(), 3, "end".into())];
assert_eq!(scene.primitives[0].border, [-10.0, -10.0, 0.0, -4.0]);
check(&mut gpu, &scene, 2).expect("mixed continuous-corner layer matches CPU oracle");
}
#[test]
fn cpu_gpu_turned_layers() {
use rune::{Color, Cx, El, Env, Runtime, col, el, text};
let mut gpu = GpuRenderer::default();
// A card with text, a border, a shadow and a child, turned; one nested in another, and
// one under a clip, so the layer's clip applies after the turn.
fn view(angle: &f32, _: &mut Cx<f32>) -> El {
let card = |a: f32| col()
.size(30.0, 22.0)
.padding(3.0)
.fill(Color { r: 0.18, g: 0.24, b: 0.36, a: 1.0 })
.radius(5.0)
.border(1.0, Color { r: 0.45, g: 0.62, b: 0.88, a: 1.0 })
.shadow(2.0, 4.0, Color::BLACK.alpha(0.4))
.child(text("Ru").color(Color::WHITE))
.rotate(a);
col()
.size(64.0, 64.0)
.padding(4.0)
.gap(2.0)
.fill(Color { r: 0.06, g: 0.08, b: 0.12, a: 1.0 })
.child(card(*angle).origin(0.5, 1.0))
.child(el().size(56.0, 30.0).clip_rounded(4.0).child(card(-*angle).child(
el().size(8.0, 8.0).fill(Color { r: 0.85, g: 0.32, b: 0.28, a: 0.85 }).rotate(*angle * 2.0),
)))
}
for (n, angle) in [0.3f32, -1.1, std::f32::consts::FRAC_PI_2, 2.6].into_iter().enumerate() {
let mut rt = Runtime::new(angle, view, (64.0, 64.0), Env { scale: 1.0, system_dark: true });
rt.frame(0.0);
let primitives: Vec<Primitive> = rt
.instances
.iter()
.enumerate()
.map(|(idx, inst)| Primitive::from_instance(inst, idx as u32 + 1, format!("turned/{idx}")))
.collect();
assert!(primitives.iter().any(|p| p.params[1] == 8.0 && p.turn.is_some_and(|t| t[0] == angle)), "a turned layer");
let scene = Scene {
width: 64,
height: 64,
clear: [0.025, 0.04, 0.06, 1.0],
primitives,
atlas: rune_ref::Atlas {
width: rune::text::ATLAS_SIZE,
height: rune::text::ATLAS_SIZE,
data: rt.text.atlas.data.clone(),
},
};
if let Err(e) = check(&mut gpu, &scene, 2) {
save(&format!("turned-{n}"), &scene);
panic!("{e}");
}
}
}
#[test]
fn cpu_gpu_plus_lighter_layers() {
use rune::render::{Blend, Instance, KIND_RECT, LayerSpec, NO_CLIP};
let mut gpu = GpuRenderer::default();
let mut scene = generate::scene(&[]);
scene.width = 48;
scene.height = 48;
// Coloured background, then a PlusLighter dissolve layer with opacity 0.7 containing two
// overlapping rects whose sum saturates past 1.0, plus a nested opaque SourceOver layer
// (which must isolate rather than flatten into the additive parent).
let bg = Instance {
rect: [0.0, 0.0, 48.0, 48.0],
radii: [0.0; 4],
fill: [0.1, 0.2, 0.5, 1.0],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
};
let layer_open = Instance::begin_layer(
[4.0, 4.0, 40.0, 40.0],
NO_CLIP,
LayerSpec { opacity: 0.7, blend: Blend::PlusLighter, ..Default::default() },
);
let child_a = Instance {
rect: [6.0, 6.0, 26.0, 26.0],
radii: [4.0; 4],
fill: [0.6, 0.15, 0.05, 0.65],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
};
let child_b = Instance {
rect: [16.0, 16.0, 26.0, 26.0],
radii: [4.0; 4],
fill: [0.55, 0.45, 0.1, 0.6],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
};
let inner_open = Instance::begin_layer([12.0, 24.0, 20.0, 16.0], NO_CLIP, LayerSpec::default());
let inner_a = Instance {
rect: [12.0, 24.0, 14.0, 14.0],
radii: [0.0; 4],
fill: [0.0, 0.4, 0.0, 0.5],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
};
let inner_b = Instance {
rect: [18.0, 26.0, 14.0, 14.0],
radii: [0.0; 4],
fill: [0.0, 0.4, 0.3, 0.5],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
};
let instances = [
bg,
layer_open,
child_a,
child_b,
inner_open,
inner_a,
inner_b,
Instance::end_layer(),
Instance::end_layer(),
];
scene.primitives = instances
.iter()
.enumerate()
.map(|(i, inst)| Primitive::from_instance(inst, i as u32 + 1, format!("plus-lighter/{i}")))
.collect();
if let Err(e) = check(&mut gpu, &scene, 2) {
save("plus-lighter", &scene);
panic!("{e}");
}
}
#[test]
fn cpu_gpu_continuous_corners() {
use rune::render::{Instance, KIND_GRADIENT, KIND_INSET, KIND_RECT, NO_CLIP};
let mut gpu = GpuRenderer::default();
let mut scene = generate::scene(&[]);
scene.width = 64;
scene.height = 64;
let rect = Instance {
rect: [4.0, 4.0, 26.0, 26.0],
radii: [-8.0; 4],
fill: [0.7, 0.2, 0.3, 0.9],
border: [0.9, 0.8, 0.2, 0.9],
params: [2.0, KIND_RECT, 0.0, 0.9],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
};
let grad = Instance {
rect: [34.0, 4.0, 26.0, 26.0],
radii: [-10.0, 0.0, -6.0, 4.0],
fill: [0.2, 0.6, 0.9, 1.0],
border: [0.0; 4],
params: [0.0, KIND_GRADIENT, 0.0, 1.0],
uv: [0.1, 0.2, 0.6, 1.0],
clip: NO_CLIP,
fade: [0; 4],
};
let inset = Instance {
rect: [8.0, 34.0, 48.0, 24.0],
radii: [-7.0; 4],
fill: [0.0, 0.0, 0.0, 0.6],
border: [0.0; 4],
params: [2.0, KIND_INSET, 3.0, 1.0],
uv: [1.0, 2.0, 0.0, 0.0],
clip: NO_CLIP,
fade: [0; 4],
};
scene.primitives = [rect, grad, inset]
.iter()
.enumerate()
.map(|(i, inst)| Primitive::from_instance(inst, i as u32 + 1, format!("continuous/{i}")))
.collect();
scene.validate().expect("continuous-corner primitives must validate");
if let Err(e) = check(&mut gpu, &scene, 2) {
save("continuous-corners", &scene);
panic!("{e}");
}
}
#[test]
fn cpu_gpu_linear_fade_offset() {
use rune::render::{Instance, KIND_RECT, pack_fade};
let mut gpu = GpuRenderer::default();
let mut scene = generate::scene(&[]);
scene.width = 64;
scene.height = 64;
let clip = [12.0, 10.0, 52.0, 54.0];
// Negative widths select linear ramps; origin lies outside clip on all four edges so the
// ramp starts partially progressed at the hard clip boundary.
let fade_widths = [-16.0, -12.0, -20.0, -10.0];
let origin = [4.0, 4.0, 62.0, 59.0];
let inst = Instance {
rect: [0.0, 0.0, 64.0, 64.0],
radii: [0.0; 4],
fill: [0.85, 0.45, 0.2, 1.0],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip,
fade: pack_fade(fade_widths, origin, clip),
};
let prim = Primitive::from_instance(&inst, 1, "linear-fade-offset".into());
// Round-trip must preserve the packed origin offsets, not flip them across the clip edge.
let roundtrip = Instance::from(&prim);
assert_eq!(roundtrip.fade[2], inst.fade[2], "linear fade origin offsets must survive round-trip");
scene.primitives = vec![prim];
if let Err(e) = check(&mut gpu, &scene, 2) {
save("linear-fade-offset", &scene);
panic!("{e}");
}
}
#[test]
fn cpu_gpu_rounded_clip_on_primitive() {
use rune::render::{Instance, KIND_RECT, pack_clip_radii};
let mut gpu = GpuRenderer::default();
let mut scene = generate::scene(&[]);
scene.width = 64;
scene.height = 64;
let clip_a = [4.0, 4.0, 28.0, 28.0];
let mut rect_a = Instance {
rect: [0.0, 0.0, 32.0, 32.0],
radii: [0.0; 4],
fill: [0.9, 0.3, 0.2, 1.0],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: clip_a,
fade: [0; 4],
};
rect_a.fade[3] = pack_clip_radii(clip_a, [10.0; 4]);
let clip_b = [32.0, 4.0, 60.0, 32.0];
let mut rect_b = Instance {
rect: [28.0, 0.0, 36.0, 36.0],
radii: [0.0; 4],
fill: [0.2, 0.75, 0.4, 1.0],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: clip_b,
fade: [0; 4],
};
rect_b.fade[3] = pack_clip_radii(clip_b, [-10.0, -6.0, 0.0, -8.0]);
let prim_a = Primitive::from_instance(&rect_a, 1, "rounded-clip-uniform".into());
let prim_b = Primitive::from_instance(&rect_b, 2, "rounded-clip-mixed".into());
assert_eq!(Instance::from(&prim_a).fade[3], rect_a.fade[3], "uniform rounded clip must survive round-trip");
assert_eq!(Instance::from(&prim_b).fade[3], rect_b.fade[3], "mixed continuous rounded clip must survive round-trip");
scene.primitives = vec![prim_a, prim_b];
if let Err(e) = check(&mut gpu, &scene, 2) {
save("rounded-clip-primitive", &scene);
panic!("{e}");
}
}
#[test]
fn cpu_gpu_turned_plus_lighter_saturates_before_interpolation() {
use rune::render::{Blend, Instance, KIND_RECT, LayerSpec, NO_CLIP};
let mut gpu = GpuRenderer::default();
let make = |children: &[Instance]| -> Scene {
let mut scene = generate::scene(&[]);
scene.width = 48;
scene.height = 48;
scene.clear = [0.02, 0.04, 0.08, 1.0];
let open = Instance::begin_layer(
[12.0, 12.0, 24.0, 24.0],
NO_CLIP,
LayerSpec { opacity: 0.8, blend: Blend::PlusLighter, ..Default::default() },
)
.turned(0.4, [24.0, 24.0]);
let mut all = vec![open];
all.extend_from_slice(children);
all.push(Instance::end_layer());
scene.primitives = all
.iter()
.enumerate()
.map(|(i, inst)| Primitive::from_instance(inst, i as u32 + 1, format!("turned-add/{i}")))
.collect();
scene
};
let box_inst = |fill: [f32; 4]| Instance {
rect: [12.0, 12.0, 24.0, 24.0],
radii: [0.0; 4],
fill,
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
};
// Two overlapping [0.8, 0.2, 0.0, 0.8] rects sum to [1.6, 0.4, 0.0, 1.6], which saturates to
// [1.0, 0.4, 0.0, 1.0]. Saturation must happen before the turned layer's bilinear sampling.
let single = make(&[box_inst([1.0, 0.4, 0.0, 1.0])]);
let doubled = make(&[box_inst([0.8, 0.2, 0.0, 0.8]), box_inst([0.8, 0.2, 0.0, 0.8])]);
let mut cpu_single = Frame::new(48, 48, true);
cpu_single.render(&single);
let mut cpu_doubled = Frame::new(48, 48, true);
cpu_doubled.render(&doubled);
let cpu_diff = compare(&doubled, &cpu_single, &cpu_doubled.rgba, 1);
assert_eq!(cpu_diff.outlier_pixels, 0, "rune-ref turned PlusLighter clamped after interpolation: {cpu_diff:?}");
let gpu_single = gpu.render(&single);
let gpu_doubled = gpu.render(&doubled);
let mut gpu_max = 0u8;
let mut gpu_worst = None;
for y in 0..48u32 {
for x in 0..48u32 {
let i = ((y * 48 + x) * 4) as usize;
let a = [gpu_single[i], gpu_single[i + 1], gpu_single[i + 2], gpu_single[i + 3]];
let b = [gpu_doubled[i], gpu_doubled[i + 1], gpu_doubled[i + 2], gpu_doubled[i + 3]];
let d = (0..4).map(|k| a[k].abs_diff(b[k])).max().unwrap();
if d > gpu_max {
gpu_max = d;
gpu_worst = Some((x, y, a, b));
}
}
}
assert!(gpu_max <= 1, "GPU turned PlusLighter clamped after interpolation: max={gpu_max} worst={gpu_worst:?}");
if let Err(e) = check(&mut gpu, &doubled, 2) {
save("turned-plus-lighter", &doubled);
panic!("{e}");
}
}
+207
View File
@@ -0,0 +1,207 @@
#![cfg(feature = "gpu")]
use rune::color::{srgb_decode, srgb_encode};
use rune::render::{Gpu, Offscreen};
use rune_fx::*;
use rune_ref::blend::{Separable, composite};
fn render(
gpu: &Gpu,
fx: &mut FxRenderer,
format: wgpu::TextureFormat,
clear: [f32; 4],
layers: &[FxLayer],
mode: FxBlend,
srgb: bool,
backdrop: Option<&wgpu::TextureView>,
) -> Vec<u8> {
let target = Offscreen::with_format(&gpu.device, 96, 96, format);
fx.prepare_with_slots(
&gpu.device,
&gpu.queue,
&FxFrame {
viewport: [96, 96],
scale: 1.0,
layers,
backdrop,
sources: &[],
},
&[FxSlot::default().blend(mode).backdrop_srgb(srgb)],
);
let mut enc = gpu.device.create_command_encoder(&Default::default());
{
let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target.view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: clear[0] as f64,
g: clear[1] as f64,
b: clear[2] as f64,
a: clear[3] as f64,
}),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
fx.draw_all(&mut pass, layers, None);
}
target.copy(&mut enc);
gpu.queue.submit([enc.finish()]);
target.read(&gpu.device)
}
#[test]
fn soft_glow_coverage_matches_reference_blending_in_both_spaces() {
let gpu = Gpu::headless();
let modes = [
(FxBlend::Multiply, Separable::Multiply),
(FxBlend::Screen, Separable::Screen),
(FxBlend::Overlay, Separable::Overlay),
(FxBlend::SoftLight, Separable::SoftLight),
];
for srgb in [false, true] {
let format = if srgb {
wgpu::TextureFormat::Rgba8Unorm
} else {
wgpu::TextureFormat::Rgba8UnormSrgb
};
let mut fx = FxRenderer::new(&gpu.device, format, FxOptions::default());
fx.set_srgb_blend(srgb);
let decode = |p: &[u8]| -> [f32; 4] {
std::array::from_fn(|c| {
let v = p[c] as f32 / 255.0;
if c < 3 && !srgb { srgb_decode(v) } else { v }
})
};
for opacity in [0.35, 1.0] {
let layers = [Fx::glow(GlowParams {
color: rgb(0xc85a14),
core: rgb(0xe88c28),
radius: 10.0,
reach: 2.5,
intensity: 0.8,
occlusion: 1.0,
..Default::default()
})
.on(Shape::rounded(32.0, 32.0, 32.0, 32.0, 10.0))
.at(0.5)
.opacity(opacity)];
// Normal with occlusion=1 yields the same premultiplied source as separable modes.
let source = render(
&gpu,
&mut fx,
format,
[0.0; 4],
&layers,
FxBlend::Normal,
srgb,
None,
);
for (rgb, alpha) in [
([0.98, 0.97, 0.95], 1.0),
([0.3, 0.6, 0.8], 1.0),
([0.3, 0.6, 0.8], 0.35),
([0.0; 3], 0.0),
] {
let clear = std::array::from_fn(|c| {
if c == 3 {
alpha
} else {
(if srgb { rgb[c] } else { srgb_decode(rgb[c]) }) * alpha
}
});
let backdrop = gpu.device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 96,
height: 96,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let backdrop_view = backdrop.create_view(&Default::default());
let bytes = render(
&gpu,
&mut fx,
format,
clear,
&[],
FxBlend::Normal,
srgb,
None,
);
// Upload exactly the quantized pixels used by the destination.
gpu.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &backdrop,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
&bytes,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(96 * 4),
rows_per_image: Some(96),
},
wgpu::Extent3d {
width: 96,
height: 96,
depth_or_array_layers: 1,
},
);
for (mode, oracle) in modes {
let actual = render(
&gpu,
&mut fx,
format,
clear,
&layers,
mode,
srgb,
Some(&backdrop_view),
);
let mut partial = 0;
for ((src, dst), got) in source
.chunks_exact(4)
.zip(bytes.chunks_exact(4))
.zip(actual.chunks_exact(4))
{
let src = decode(src);
partial += usize::from(src[3] > 0.02 && src[3] < 0.3);
let want = composite(oracle, src, decode(dst));
for c in 0..4 {
let v = if c < 3 && !srgb {
srgb_encode(want[c])
} else {
want[c]
};
let want = (v * 255.0).round().clamp(0.0, 255.0) as u8;
assert!(
got[c].abs_diff(want) <= 3,
"{mode:?} srgb={srgb} opacity={opacity} backdrop alpha={alpha} channel={c}: {} vs {want}",
got[c]
);
}
}
assert!(
partial > 100,
"exercise soft edges, not just opaque centres"
);
}
}
}
}
}
+358
View File
@@ -0,0 +1,358 @@
#![cfg(feature = "gpu")]
use rune::render::{
Blend, Instance, KIND_EFFECT, KIND_INSET, KIND_RECT, KIND_SEGMENT, KIND_SHADOW, KIND_TRIANGLE,
LayerSpec, NO_CLIP, pack_clip_radii,
};
use rune_ref::{Frame, Primitive, Scene, compare, generate, gpu::GpuRenderer};
fn check(gpu: &mut GpuRenderer, scene: &Scene, tolerance: u8) {
scene.validate().expect("scene must validate");
let mut cpu = Frame::new(scene.width, scene.height, true);
cpu.render(scene);
let actual = gpu.render(scene);
let diff = compare(scene, &cpu, &actual, tolerance);
assert_eq!(diff.outlier_pixels, 0, "CPU vs GPU mismatch: {diff:?}");
}
fn from_instances(width: u32, height: u32, instances: &[Instance]) -> Scene {
let mut scene = generate::scene(&[]);
scene.width = width;
scene.height = height;
scene.primitives = instances
.iter()
.enumerate()
.map(|(i, inst)| Primitive::from_instance(inst, i as u32 + 1, format!("parity/{i}")))
.collect();
scene
}
fn zero_instance() -> Instance {
Instance {
rect: [0.0; 4],
radii: [0.0; 4],
fill: [0.0; 4],
border: [0.0; 4],
params: [0.0; 4],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
}
}
#[test]
fn cpu_gpu_banded_rects_and_shadows() {
let mut gpu = GpuRenderer::default();
let ring = Instance {
rect: [8.0, 8.0, 48.0, 48.0],
radii: [-8.0; 4],
border: [0.85, 0.35, 0.2, 0.9],
params: [3.0, KIND_RECT, 0.0, 0.9],
..zero_instance()
};
let shadow = Instance {
rect: [14.0, 14.0, 36.0, 36.0],
radii: [6.0; 4],
fill: [0.0, 0.0, 0.0, 0.6],
params: [0.0, KIND_SHADOW, 3.0, 1.0],
..zero_instance()
};
let bands = |inst: Instance, q: [f32; 4], hole: [f32; 4]| -> Vec<Instance> {
let [qx0, qy0, qx1, qy1] = q;
let [hx0, hy0, hx1, hy1] = hole;
[
[qx0, qy0, qx1, hy0],
[qx0, hy0, hx0, hy1],
[hx1, hy0, qx1, hy1],
[qx0, hy1, qx1, qy1],
]
.into_iter()
.map(|[x0, y0, x1, y1]| Instance { uv: [x0, y0, -x1, y1], ..inst })
.collect()
};
let ring_bands = bands(ring, [-1.0, -1.0, 49.0, 49.0], [16.0, 16.0, 32.0, 32.0]);
let shadow_bands = bands(shadow, [-10.0, -10.0, 46.0, 46.0], [8.0, 8.0, 28.0, 28.0]);
check(&mut gpu, &from_instances(64, 64, &ring_bands), 2);
check(&mut gpu, &from_instances(64, 64, &shadow_bands), 2);
check(&mut gpu, &from_instances(64, 64, &[shadow_bands[0], ring_bands[1]]), 2);
}
#[test]
fn cpu_gpu_segments_and_triangles() {
let mut gpu = GpuRenderer::default();
let instances = [
// Round-cap diagonal stroke
Instance {
rect: [4.0, 4.0, 30.0, 24.0],
radii: [8.0, 8.0, 30.0, 24.0],
fill: [0.9, 0.35, 0.15, 0.95],
params: [2.25, KIND_SEGMENT, 1.0, 1.0],
..zero_instance()
},
// Butt-cap hairline (< 1 px wide)
Instance {
rect: [32.0, 4.0, 26.0, 20.0],
radii: [36.0, 10.0, 54.0, 18.0],
fill: [0.16, 0.68, 0.4, 0.8],
params: [0.3, KIND_SEGMENT, 0.0, 1.0],
..zero_instance()
},
// Zero-length round-cap dot
Instance {
rect: [42.0, 20.0, 12.0, 12.0],
radii: [48.0, 26.0, 48.0, 26.0],
fill: [0.9, 0.85, 0.2, 1.0],
params: [3.0, KIND_SEGMENT, 1.0, 1.0],
..zero_instance()
},
// Two triangles sharing an interior hard edge (seam-free ownership)
Instance {
rect: [8.0, 32.0, 24.0, 24.0],
radii: [8.0, 32.0, 32.0, 32.0],
uv: [32.0, 56.0, 0.0, 0.0],
fill: [0.175, 0.315, 0.63, 0.7],
params: [3.0, KIND_TRIANGLE, 0.0, 1.0],
..zero_instance()
},
Instance {
rect: [8.0, 32.0, 24.0, 24.0],
radii: [8.0, 32.0, 32.0, 56.0],
uv: [8.0, 56.0, 0.0, 0.0],
fill: [0.175, 0.315, 0.63, 0.7],
params: [6.0, KIND_TRIANGLE, 0.0, 1.0],
..zero_instance()
},
// Clipped triangle with all edges antialiased
Instance {
rect: [34.0, 32.0, 24.0, 24.0],
radii: [46.0, 33.0, 57.0, 55.0],
uv: [35.0, 52.0, 0.0, 0.0],
fill: [0.72, 0.17, 0.55, 0.85],
params: [7.0, KIND_TRIANGLE, 0.0, 1.0],
clip: [38.0, 36.0, 54.0, 53.0],
..zero_instance()
},
];
check(&mut gpu, &from_instances(64, 64, &instances), 2);
}
#[test]
fn cpu_gpu_negative_spread_inset_shadows() {
let mut gpu = GpuRenderer::default();
let instances = [
// Sharp negative-spread inset on square corners (must stay square, not round to +|spread|)
Instance {
rect: [4.0, 4.0, 26.0, 26.0],
radii: [0.0; 4],
fill: [0.68, 0.2, 0.12, 0.8],
params: [-4.0, KIND_INSET, 0.0, 1.0],
uv: [0.0, 6.0, 0.0, 0.0],
..zero_instance()
},
// Blurred negative-spread inset on circular corners
Instance {
rect: [34.0, 4.0, 26.0, 26.0],
radii: [6.0; 4],
fill: [0.12, 0.56, 0.34, 0.75],
params: [-2.0, KIND_INSET, 3.0, 1.0],
uv: [3.0, 4.0, 0.0, 0.0],
..zero_instance()
},
// Sharp negative-spread inset on continuous corners
Instance {
rect: [10.0, 34.0, 44.0, 24.0],
radii: [-6.0; 4],
fill: [0.14, 0.28, 0.63, 0.7],
params: [-3.0, KIND_INSET, 0.0, 1.0],
uv: [-4.0, 5.0, 0.0, 0.0],
..zero_instance()
},
];
check(&mut gpu, &from_instances(64, 64, &instances), 2);
}
#[test]
fn cpu_gpu_mixed_clip_radii_quantization() {
let mut gpu = GpuRenderer::default();
// Fractional mixed radii (0.5 px step) on a direct Primitive (not round-tripped from Instance)
let mut fine = generate::scene(&[]);
fine.width = 64;
fine.height = 64;
fine.primitives = vec![Primitive {
node: 1,
source: "clip-fine".into(),
rect: [0.0, 0.0, 64.0, 64.0],
radii: [0.0; 4],
fill: [0.9, 0.4, 0.2, 1.0],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: [4.0, 4.0, 60.0, 60.0],
fade: [0.0; 4],
fade_origin: None,
turn: None,
clip_radii: Some([10.3, 4.7, 0.0, 8.2]),
}];
check(&mut gpu, &fine, 2);
// Coarse mixed radii (> 63.5 px -> 2.0 px step) and negative continuous sign
let mut coarse = generate::scene(&[]);
coarse.width = 200;
coarse.height = 200;
coarse.primitives = vec![Primitive {
node: 1,
source: "clip-coarse".into(),
rect: [0.0, 0.0, 200.0, 200.0],
radii: [0.0; 4],
fill: [0.2, 0.7, 0.9, 1.0],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: [10.0, 10.0, 190.0, 190.0],
fade: [0.0; 4],
fade_origin: None,
turn: None,
clip_radii: Some([-71.3, -13.1, 0.0, -40.7]),
}];
check(&mut gpu, &coarse, 2);
}
#[test]
fn cpu_gpu_layer_expansion_offscreen_turns_and_scissor_inline() {
let mut gpu = GpuRenderer::default();
// 1. Uncached opacity layer with small initial rect containing a child + outer drop shadow.
let expanded = [
Instance::begin_layer(
[24.0, 24.0, 8.0, 8.0],
NO_CLIP,
LayerSpec { opacity: 0.65, ..Default::default() },
),
Instance {
rect: [16.0, 16.0, 28.0, 24.0],
radii: [6.0; 4],
fill: [0.0, 0.0, 0.0, 0.7],
params: [0.0, KIND_SHADOW, 5.0, 1.0],
..zero_instance()
},
Instance {
rect: [16.0, 16.0, 28.0, 24.0],
radii: [6.0; 4],
fill: [0.8, 0.3, 0.2, 1.0],
params: [0.0, KIND_RECT, 0.0, 1.0],
..zero_instance()
},
Instance::end_layer(),
];
check(&mut gpu, &from_instances(64, 64, &expanded), 2);
// 2. Uncached layer with empty initial rect [24, 24, 0, 0].
let empty_seed = [
Instance::begin_layer(
[24.0, 24.0, 0.0, 0.0],
NO_CLIP,
LayerSpec { opacity: 0.5, blend: Blend::PlusLighter, ..Default::default() },
),
Instance {
rect: [10.0, 10.0, 26.0, 26.0],
radii: [4.0; 4],
fill: [0.7, 0.2, 0.1, 0.7],
params: [0.0, KIND_RECT, 0.0, 1.0],
..zero_instance()
},
Instance {
rect: [20.0, 20.0, 26.0, 26.0],
radii: [4.0; 4],
fill: [0.14, 0.42, 0.56, 0.7],
params: [0.0, KIND_RECT, 0.0, 1.0],
..zero_instance()
},
Instance::end_layer(),
];
check(&mut gpu, &from_instances(64, 64, &empty_seed), 2);
// 3. Turned layer whose upright content starts at x < 0 and rotates into the viewport.
let offscreen_turn = [
Instance::begin_layer([-12.0, 22.0, 24.0, 16.0], NO_CLIP, LayerSpec::default())
.turned(std::f32::consts::FRAC_PI_2, [16.0, 30.0]),
Instance {
rect: [-12.0, 22.0, 24.0, 16.0],
radii: [4.0; 4],
fill: [0.2, 0.85, 0.45, 1.0],
params: [0.0, KIND_RECT, 0.0, 1.0],
..zero_instance()
},
Instance::end_layer(),
];
check(&mut gpu, &from_instances(64, 64, &offscreen_turn), 2);
// 4. Integer-clipped opaque layer (`Disposition::Inline` with hardware scissor) with overlapping children.
let mut scissored_inner = Instance::begin_layer(
[10.0, 10.0, 32.0, 32.0],
[12.0, 12.0, 40.0, 40.0],
LayerSpec { opacity: 0.7, ..Default::default() },
);
scissored_inner.fade[3] = pack_clip_radii(scissored_inner.clip, [8.0; 4]);
let scissored = [
Instance::begin_layer([8.0, 8.0, 48.0, 48.0], [8.0, 8.0, 48.0, 48.0], LayerSpec::default()),
Instance {
rect: [0.0, 0.0, 64.0, 64.0],
fill: [0.2, 0.1, 0.3, 0.5],
params: [0.0, KIND_RECT, 0.0, 1.0],
..zero_instance()
},
scissored_inner,
Instance {
rect: [4.0, 4.0, 56.0, 56.0],
fill: [0.72, 0.48, 0.08, 0.8],
params: [0.0, KIND_RECT, 0.0, 1.0],
..zero_instance()
},
Instance::end_layer(),
Instance::end_layer(),
];
check(&mut gpu, &from_instances(64, 64, &scissored), 2);
}
#[test]
fn cpu_gpu_effect_slot_with_mark_and_legacy_glyph_radii() {
let mut gpu = GpuRenderer::default();
let mark: u32 = 0x1234_5678;
let slot = Instance {
rect: [8.0, 8.0, 24.0, 24.0],
fill: [0.0, 0.0, 0.0, 1.0],
border: [(mark & 0xFFFF) as f32, (mark >> 16) as f32, 0.0, 0.0],
params: [1.0, KIND_EFFECT, 4.0, 1.0],
uv: [-3.0, 7.5, 1.0, 0.25],
..zero_instance()
};
let bg = Instance {
rect: [4.0, 4.0, 40.0, 40.0],
fill: [0.3, 0.5, 0.8, 1.0],
params: [0.0, KIND_RECT, 0.0, 1.0],
..zero_instance()
};
check(&mut gpu, &from_instances(64, 64, &[bg, slot]), 2);
// A legacy glyph primitive with non-zero radii and params[2] must still render via page-0 atlas.
let mut glyph_scene = generate::scene(&[]);
glyph_scene.primitives = vec![Primitive {
node: 1,
source: "legacy-glyph".into(),
rect: [12.0, 12.0, 16.0, 16.0],
radii: [12.0, 8.0, 4.0, 2.0],
fill: [0.8, 0.7, 0.5, 0.9],
border: [0.0; 4],
params: [0.0, 2.0, 3.5, 1.2],
uv: [1.0, 1.0, 0.0, 0.0],
clip: NO_CLIP,
fade: [0.0; 4],
fade_origin: None,
turn: None,
clip_radii: None,
}];
let inst = Instance::from(&glyph_scene.primitives[0]);
assert_eq!(inst.radii, [0.0; 4]);
assert_eq!(inst.params[2], 0.0);
check(&mut gpu, &glyph_scene, 2);
}
+599
View File
@@ -0,0 +1,599 @@
use proptest::prelude::*;
use rune_ref::{Frame, NO_CLIP, Scene, generate};
fn render(s: &Scene) -> Frame {
s.validate().unwrap();
let mut f = Frame::new(s.width, s.height, true);
f.render(s);
f
}
proptest! {
#![proptest_config(ProptestConfig { cases: 128,
failure_persistence: Some(Box::new(proptest::test_runner::FileFailurePersistence::Direct("tests/reference.proptest-regressions"))),
..ProptestConfig::default() })]
#[test]
fn metamorphic(records in prop::collection::vec(any::<[u8;32]>(), 0..8)) {
let scene = generate::scene(&records);
let original = render(&scene);
let mut shifted = scene.clone();
shifted.width += 4; shifted.height += 6;
generate::translate(&mut shifted, 4.0, 6.0);
let actual = render(&shifted);
for y in 0..scene.height as usize {
let a = &original.rgba[y * scene.width as usize * 4..(y+1) * scene.width as usize * 4];
let start = ((y + 6) * shifted.width as usize + 4) * 4;
prop_assert_eq!(a, &actual.rgba[start..start+a.len()]);
}
// Transparent primitives preserve both bytes and provenance.
let mut transparent = scene.clone();
for mut p in scene.primitives.clone() {
p.fill = [0.0;4]; p.border = [0.0;4];
if p.params[1] == 4.0 { p.uv = [0.0;4]; }
transparent.primitives.push(p);
}
let actual = render(&transparent);
prop_assert_eq!(&original.rgba, &actual.rgba);
prop_assert_eq!(&original.owners, &actual.owners);
// Full viewport clip equals no clip at all pixel centers, including edges.
let mut full = scene.clone();
for p in &mut full.primitives { p.clip = NO_CLIP; p.fade = [0.0;4]; }
let unclipped = render(&full);
for p in &mut full.primitives { p.clip = [0.0,0.0,64.0,64.0]; }
prop_assert_eq!(unclipped.rgba, render(&full).rgba);
// Two independently generated groups separated by hard clips cannot interact.
let mut disjoint = scene.clone();
for p in &mut disjoint.primitives { p.clip = [0.0,0.0,31.0,64.0]; p.fade = [0.0;4]; }
let left_count = disjoint.primitives.len();
for mut p in scene.primitives.clone() {
p.rect[0] += 32.0;
p.clip = [32.0,0.0,64.0,64.0]; p.fade = [0.0;4];
disjoint.primitives.push(p);
}
let a = render(&disjoint);
disjoint.primitives.rotate_left(left_count);
prop_assert_eq!(a.rgba, render(&disjoint).rgba);
}
}
#[test]
fn provenance_and_diff_name_the_source() {
let mut s = generate::scene(&[[0; 32]]);
let p = &mut s.primitives[0];
p.rect = [2.0, 2.0, 10.0, 10.0];
p.fill = [1.0; 4];
let f = render(&s);
assert_eq!(f.blame(&s, 5, 5).unwrap().source, "generated/0");
assert!(f.blame(&s, 63, 63).is_none());
let mut bad = f.rgba.clone();
bad[(5 * 64 + 5) * 4] = 0;
let diff = rune_ref::compare(&s, &f, &bad, 2);
assert_eq!(diff.outlier_pixels, 1);
assert_eq!(diff.first.unwrap().node, Some(1));
}
#[test]
fn canonical_hashes() {
let expected: Vec<(u64, String)> =
serde_json::from_str(include_str!("../goldens.json")).unwrap();
assert!(!expected.is_empty(), "canonical hashes must be recorded");
for (seed, hash) in expected {
assert_eq!(
render(&generate::seeded(seed, 8)).hash(),
hash,
"seed {seed}"
);
}
}
#[test]
fn dashed_rings_translate_and_stay_inside_their_ring() {
for seed in 0..32 {
let scene = generate::dashed(seed, 8);
let original = render(&scene);
let mut shifted = scene.clone();
shifted.width += 4; shifted.height += 6;
generate::translate(&mut shifted, 4.0, 6.0);
let actual = render(&shifted);
for y in 0..64 {
assert_eq!(&original.rgba[y * 256..(y + 1) * 256], &actual.rgba[((y + 6) * 68 + 4) * 4..((y + 6) * 68 + 68) * 4]);
}
// Dashes only ever take coverage away from the solid ring.
for p in &scene.primitives {
let mut one = scene.clone();
one.primitives = vec![p.clone()];
let dashed = render(&one);
one.primitives[0].params[1] = 4.0;
one.primitives[0].uv = one.primitives[0].border;
one.primitives[0].border = one.primitives[0].fill;
one.primitives[0].fill = [0.0; 4];
let solid = render(&one);
for (n, (d, s)) in dashed.owners.as_ref().unwrap().iter().zip(solid.owners.as_ref().unwrap()).enumerate() {
assert!(d.is_none() || s.is_some(), "seed {seed}: pixel {n} dashed outside the ring");
}
}
}
}
#[test]
fn effect_slots_are_accepted_and_draw_nothing() {
for seed in 0..16 {
let scene = generate::seeded(seed, 8);
let mut slotted = scene.clone();
for (n, p) in scene.primitives.iter().enumerate().rev() {
let mut slot = p.clone();
slot.source = format!("effect/{n}");
slot.fill = [0.0, 0.0, 0.0, 1.0];
slot.border = [0.0; 4];
slot.params = [0.0, 12.0, 6.0, 1.0];
slot.uv = [0.0; 4];
if n % 3 == 0 { slot.rect[2] = 0.0; }
slotted.primitives.insert(n, slot);
}
let (a, b) = (render(&scene), render(&slotted));
assert_eq!(a.rgba, b.rgba, "seed {seed}");
assert!(b.owners.unwrap().iter().flatten().all(|&i| slotted.primitives[i].params[1] != 12.0));
}
}
// Only the glyph's top-left 4x4 texels are lit. On screen (y down), a positive quarter turn
// carries them clockwise to the top-right and a negative one to the bottom-left.
#[test]
fn glyph_rotation_turns_clockwise_and_clips_on_screen() {
use std::f32::consts::FRAC_PI_2;
let glyph = |angle: f32, clip: [f32; 4]| {
let mut s = generate::scene(&[]);
s.atlas.data.fill(0);
for y in 1..5 {
s.atlas.data[y * 32 + 1..y * 32 + 5].fill(255);
}
let mut p = generate::scene(&[[0; 32]]).primitives.remove(0);
p.rect = [20.0, 20.0, 16.0, 16.0];
p.radii = [0.0; 4];
p.fill = [1.0; 4];
p.params = [angle, 2.0, 0.0, 1.0];
p.uv = [1.0, 1.0, 0.0, 0.0];
p.clip = clip;
s.primitives.push(p);
render(&s)
};
let lit = |f: &Frame, x: u32, y: u32| f.rgba[((y * 64 + x) * 4) as usize] == 255;
let cw = glyph(FRAC_PI_2, NO_CLIP);
let ccw = glyph(-FRAC_PI_2, NO_CLIP);
assert_ne!(cw.rgba, ccw.rgba);
assert!(lit(&cw, 34, 21) && !lit(&cw, 21, 34) && !lit(&cw, 21, 21));
assert!(lit(&ccw, 21, 34) && !lit(&ccw, 34, 21) && !lit(&ccw, 21, 21));
// The clip keeps the screen's right half, where the turned texels land.
let clipped = glyph(FRAC_PI_2, [28.0, NO_CLIP[1], NO_CLIP[2], NO_CLIP[3]]);
assert!(lit(&clipped, 34, 21) && !lit(&clipped, 21, 34));
}
fn layer(kind: f32, blur: f32) -> rune_ref::Primitive {
rune_ref::Primitive {
node: 1,
source: "layer".into(),
rect: if kind == 9.0 { [0.0; 4] } else { [0.0, 0.0, 8.0, 8.0] },
radii: [0.0; 4],
fill: [0.0, 0.0, 0.0, if kind == 9.0 { 0.0 } else { 1.0 }],
border: [0.0; 4],
params: [0.0, kind, blur, 0.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0.0; 4],
fade_origin: None,
turn: None,
clip_radii: None,
}
}
#[test]
fn validate_rejects_layers_it_cannot_render() {
let base = generate::scene(&[]);
let with = |primitives: Vec<rune_ref::Primitive>| Scene { primitives, ..base.clone() };
with(vec![layer(8.0, 0.0), layer(9.0, 0.0)]).validate().unwrap();
assert!(with(vec![layer(9.0, 0.0)]).validate().is_err(), "unbalanced end");
assert!(with(vec![layer(8.0, 0.0)]).validate().is_err(), "unclosed scope");
let mut malformed = layer(8.0, 0.0);
malformed.params[3] = 2.0;
assert!(with(vec![malformed, layer(9.0, 0.0)]).validate().is_err(), "invalid cache flag");
let mut turned = layer(8.0, 0.0);
turned.turn = Some([0.4, 4.0, 4.0]);
with(vec![turned.clone(), layer(9.0, 0.0)]).validate().unwrap();
// A turned subtree never opens a cache, so a turned cache record is malformed.
turned.params[3] = 1.0;
assert!(with(vec![turned, layer(9.0, 0.0)]).validate().is_err(), "turned cache");
// The CPU compositor has no layer blur, so a blurred layer would render unblurred.
assert!(with(vec![layer(8.0, 2.0), layer(9.0, 0.0)]).validate().is_err(), "blurred layer");
// Each nested scope holds a full-frame buffer while it renders, so nesting is bounded.
let deep: Vec<_> = (0..1000).map(|_| layer(8.0, 0.0)).chain((0..1000).map(|_| layer(9.0, 0.0))).collect();
assert!(with(deep).validate().is_err(), "unbounded nesting");
}
#[test]
fn validate_accepts_continuous_corners_and_rejects_unimplemented_kinds() {
let base = generate::scene(&[]);
let mut rect = generate::scene(&[[0; 32]]).primitives.remove(0);
rect.params = [0.0, 0.0, 0.0, 1.0];
rect.rect = [4.0, 4.0, 24.0, 24.0];
rect.radii = [-6.0; 4];
rect.fill = [0.8, 0.2, 0.1, 1.0];
rect.border = [0.0; 4];
rect.clip = [2.0, 2.0, 30.0, 30.0];
rect.clip_radii = Some([-4.0, -4.0, 0.0, -4.0]);
Scene { primitives: vec![rect.clone()], ..base.clone() }.validate().unwrap();
// Mixed positive and negative clip radii cannot be packed and are rejected.
let mut mixed_sign_clip = rect.clone();
mixed_sign_clip.clip_radii = Some([-4.0, 4.0, 0.0, 0.0]);
assert!(Scene { primitives: vec![mixed_sign_clip], ..base.clone() }.validate().is_err());
// Kinds 7 (image) and 13 (backdrop blur) are not implemented here.
for kind in [7.0, 13.0] {
let mut unsupported = rect.clone();
unsupported.params[1] = kind;
assert!(Scene { primitives: vec![unsupported], ..base.clone() }.validate().is_err(), "kind {kind} must be rejected");
}
}
fn plain_prim(kind: f32) -> rune_ref::Primitive {
rune_ref::Primitive {
node: 1,
source: "test".into(),
rect: [0.0, 0.0, 16.0, 16.0],
radii: [0.0; 4],
fill: [0.0; 4],
border: [0.0; 4],
params: [0.0, kind, 0.0, 1.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0.0; 4],
fade_origin: None,
turn: None,
clip_radii: None,
}
}
#[test]
fn banded_rects_and_shadows_rasterize_only_their_window() {
let mut scene = generate::scene(&[]);
scene.width = 64;
scene.height = 64;
scene.clear = [0.0, 0.0, 0.0, 1.0];
// Full 40x40 border ring at (12, 12) vs four non-overlapping bands around the inner 20x20 hole.
let mut whole = plain_prim(0.0);
whole.rect = [12.0, 12.0, 40.0, 40.0];
whole.radii = [4.0; 4];
whole.border = [0.8, 0.4, 0.2, 1.0];
whole.params = [3.0, 0.0, 0.0, 1.0];
let mut banded_ring = scene.clone();
let (qx0, qy0, qx1, qy1) = (-1.0f32, -1.0f32, 41.0f32, 41.0f32);
let (hx0, hy0, hx1, hy1) = (10.0f32, 10.0f32, 30.0f32, 30.0f32);
for (idx, [x0, y0, x1, y1]) in [
[qx0, qy0, qx1, hy0],
[qx0, hy0, hx0, hy1],
[hx1, hy0, qx1, hy1],
[qx0, hy1, qx1, qy1],
]
.into_iter()
.enumerate()
{
let mut band = whole.clone();
band.node = idx as u32 + 1;
band.uv = [x0, y0, -x1, y1];
banded_ring.primitives.push(band);
}
scene.primitives = vec![whole];
let expected = render(&scene);
let actual = render(&banded_ring);
assert_eq!(expected.rgba, actual.rgba, "4-band border ring must match unbanded ring");
// A single banded shadow must leave pixels outside its band window untouched (even inside the rect).
let mut sh = plain_prim(1.0);
sh.rect = [12.0, 12.0, 40.0, 40.0];
sh.radii = [4.0; 4];
sh.fill = [0.0, 0.0, 0.8, 0.8];
sh.params = [0.0, 1.0, 3.0, 1.0];
sh.uv = [-10.0, -10.0, -50.0, 8.0]; // top band only: y < 20
let top_only = render(&Scene { primitives: vec![sh], ..scene.clone() });
let top_px = &top_only.rgba[(15 * 64 + 32) * 4..(15 * 64 + 32) * 4 + 4];
let bottom_px = &top_only.rgba[(48 * 64 + 32) * 4..(48 * 64 + 32) * 4 + 4];
assert!(top_px[2] > 50, "top band must shade inside its window: {top_px:?}");
assert_eq!(bottom_px, &[0, 0, 0, 255], "top band must not shade outside its window");
}
#[test]
fn segments_and_triangles_render_and_translate() {
let mut scene = generate::scene(&[]);
scene.width = 48;
scene.height = 48;
scene.clear = [0.0, 0.0, 0.0, 1.0];
let mut seg_round = plain_prim(5.0);
seg_round.rect = [4.0, 4.0, 20.0, 12.0];
seg_round.radii = [8.0, 8.0, 20.0, 12.0];
seg_round.fill = [1.0, 0.0, 0.0, 1.0];
seg_round.params = [1.5, 5.0, 1.0, 1.0];
let mut seg_butt = plain_prim(5.0);
seg_butt.node = 2;
seg_butt.rect = [24.0, 4.0, 18.0, 12.0];
seg_butt.radii = [28.0, 10.0, 38.0, 10.0];
seg_butt.fill = [0.0, 1.0, 0.0, 1.0];
seg_butt.params = [0.25, 5.0, 0.0, 1.0]; // hairline < 1px
// Two right triangles forming a 16x16 square [8..24, 20..36] with a shared diagonal (hard edge).
let mut tri_a = plain_prim(6.0);
tri_a.node = 3;
tri_a.rect = [8.0, 20.0, 16.0, 16.0];
tri_a.radii = [8.0, 20.0, 24.0, 20.0];
tri_a.uv = [24.0, 36.0, 0.0, 0.0];
tri_a.fill = [0.0, 0.0, 0.5, 0.5];
tri_a.params = [3.0, 6.0, 0.0, 1.0]; // bits 0 (a->b) and 1 (b->c) antialiased; c->a hard
let mut tri_b = plain_prim(6.0);
tri_b.node = 4;
tri_b.rect = [8.0, 20.0, 16.0, 16.0];
tri_b.radii = [8.0, 20.0, 24.0, 36.0];
tri_b.uv = [8.0, 36.0, 0.0, 0.0];
tri_b.fill = [0.0, 0.0, 0.5, 0.5];
tri_b.params = [6.0, 6.0, 0.0, 1.0]; // bits 1 (b->c) and 2 (c->a) antialiased; a->b hard
scene.primitives = vec![seg_round, seg_butt, tri_a, tri_b];
let frame = render(&scene);
// Every interior pixel of the square—including every pixel along the shared diagonal—must be
// painted exactly once at 0.5 linear blue (sRGB ~188), with no crack and no double-blend seam.
for y in 22..34usize {
for x in 10..22usize {
let px = &frame.rgba[(y * 48 + x) * 4..(y * 48 + x) * 4 + 4];
assert!(px[2].abs_diff(188) <= 1, "shared diagonal seam at ({x},{y}): {px:?}");
}
}
// Translation invariance shifts segment endpoints and triangle vertices with the scene.
let mut shifted = scene.clone();
shifted.width += 5;
shifted.height += 3;
generate::translate(&mut shifted, 5.0, 3.0);
let actual = render(&shifted);
for y in 0..48usize {
let row = &frame.rgba[y * 48 * 4..(y + 1) * 48 * 4];
let start = ((y + 3) * 53 + 5) * 4;
assert_eq!(row, &actual.rgba[start..start + row.len()]);
}
}
#[test]
fn inset_shadow_supports_negative_spread_and_keeps_square_corners_square() {
let mut scene = generate::scene(&[]);
scene.width = 48;
scene.height = 48;
scene.clear = [0.0, 0.0, 0.0, 1.0];
let mut inset = plain_prim(3.0);
inset.rect = [8.0, 8.0, 32.0, 32.0];
inset.radii = [0.0; 4];
inset.fill = [1.0, 1.0, 1.0, 1.0];
// Sharp inset shadow shifted down by 6 px with negative spread -4 px: lit inner box expands
// to 40x40 centered at (24, 30), so top 2 px of the box [8..10) are shadowed and corners stay
// square (no bogus 4 px rounding of the bottom corners).
inset.params = [-4.0, 3.0, 0.0, 1.0];
inset.uv = [0.0, 6.0, 0.0, 0.0];
scene.primitives = vec![inset];
let frame = render(&scene);
let top_edge = &frame.rgba[(8 * 48 + 24) * 4..(8 * 48 + 24) * 4 + 4];
let bottom_left_corner = &frame.rgba[(39 * 48 + 8) * 4..(39 * 48 + 8) * 4 + 4];
let bottom_right_corner = &frame.rgba[(39 * 48 + 39) * 4..(39 * 48 + 39) * 4 + 4];
assert_eq!(top_edge, &[255, 255, 255, 255], "top strip must receive the offset inset shadow");
assert_eq!(bottom_left_corner, &[0, 0, 0, 255], "square corner must stay square under negative spread");
assert_eq!(bottom_right_corner, &[0, 0, 0, 255], "square corner must stay square under negative spread");
}
#[test]
fn effect_slots_with_nonzero_mark_validate_and_draw_nothing() {
let mut scene = generate::scene(&[]);
let mut slot = plain_prim(12.0);
slot.rect = [4.0, 4.0, 24.0, 24.0];
slot.fill = [0.0, 0.0, 0.0, 1.0];
// Real `EffectSite::mark` payload: low/high 16-bit halves in `border[0..2]`.
slot.border = [0x5678 as f32, 0x1234 as f32, 0.0, 0.0];
slot.params = [1.0, 12.0, 8.0, 2.0];
slot.uv = [-12.5, 42.0, 0.75, 100.0];
scene.primitives = vec![slot];
let frame = render(&scene);
assert!(frame.owners.unwrap().iter().all(Option::is_none));
}
#[test]
fn uncached_and_turned_layers_expand_to_children_and_offscreen_upright_content() {
let mut scene = generate::scene(&[]);
scene.width = 48;
scene.height = 48;
scene.clear = [0.0, 0.0, 0.0, 1.0];
// Uncached opacity-0.5 layer with empty initial rect [20, 20, 0, 0] containing a rect + shadow:
// must expand to include both child rect and its shadow (matching `layers.rs`).
let mut open = layer(8.0, 0.0);
open.rect = [20.0, 20.0, 0.0, 0.0];
open.fill = [0.0, 0.0, 0.0, 0.5];
let mut child = plain_prim(0.0);
child.node = 2;
child.rect = [8.0, 8.0, 20.0, 20.0];
child.fill = [1.0, 0.0, 0.0, 1.0];
scene.primitives = vec![open, child.clone(), layer(9.0, 0.0)];
let frame = render(&scene);
let inside_child = &frame.rgba[(12 * 48 + 12) * 4..(12 * 48 + 12) * 4 + 4];
assert!(inside_child[0].abs_diff(188) <= 1, "uncached layer must expand to child: {inside_child:?}");
// Cached layer (`params[3] == 1.0`) must NOT expand past its declared `rect`.
let mut cached_open = layer(8.0, 0.0);
cached_open.rect = [20.0, 20.0, 16.0, 16.0];
cached_open.params[3] = 1.0;
let cached = render(&Scene {
primitives: vec![cached_open, child, layer(9.0, 0.0)],
..scene.clone()
});
assert_eq!(&cached.rgba[(12 * 48 + 12) * 4..(12 * 48 + 12) * 4 + 4], &[0, 0, 0, 255],
"cached layer must keep its declared bounds");
assert_eq!(&cached.rgba[(22 * 48 + 22) * 4..(22 * 48 + 22) * 4 + 4], &[255, 0, 0, 255]);
// Turned layer whose upright child sits at x = -12..0 and rotates +90° clockwise about (12, 24)
// into the visible viewport around (12, 0..12).
let mut turned = layer(8.0, 0.0);
turned.rect = [-12.0, 20.0, 12.0, 8.0];
turned.turn = Some([std::f32::consts::FRAC_PI_2, 12.0, 24.0]);
let mut offscreen_child = plain_prim(0.0);
offscreen_child.node = 7;
offscreen_child.source = "offscreen-child".into();
offscreen_child.rect = [-12.0, 20.0, 12.0, 8.0];
offscreen_child.fill = [0.0, 1.0, 0.0, 1.0];
let turned_scene = Scene {
primitives: vec![turned, offscreen_child, layer(9.0, 0.0)],
..scene.clone()
};
let turned_frame = render(&turned_scene);
// Upright (-6, 24) rotated +90° CW about (12, 24) lands at (12, 6).
let rotated_px = &turned_frame.rgba[(6 * 48 + 12) * 4..(6 * 48 + 12) * 4 + 4];
assert_eq!(rotated_px, &[0, 255, 0, 255], "off-viewport upright child must turn into view");
assert_eq!(turned_frame.blame(&turned_scene, 12, 6).unwrap().node, 7,
"turned layer blame must resolve through the inverse turn to the child");
}
#[test]
fn mixed_clip_radii_quantize_to_packed_abi_steps() {
let mut scene = generate::scene(&[]);
scene.width = 64;
scene.height = 64;
scene.clear = [0.0, 0.0, 0.0, 1.0];
let mut a = plain_prim(0.0);
a.rect = [0.0, 0.0, 64.0, 64.0];
a.fill = [1.0, 1.0, 1.0, 1.0];
a.clip = [0.0, 0.0, 64.0, 64.0];
a.clip_radii = Some([10.2, 4.8, 0.0, 0.0]);
let mut b = a.clone();
// 10.2 rounds to 10.0, 4.8 rounds to 5.0 at 0.5 px mixed resolution.
b.clip_radii = Some([10.0, 5.0, 0.0, 0.0]);
let fa = render(&Scene { primitives: vec![a], ..scene.clone() });
let fb = render(&Scene { primitives: vec![b], ..scene });
assert_eq!(fa.rgba, fb.rgba, "mixed clip radii must match packed 0.5 px steps");
}
#[test]
fn generated_glyphs_have_clean_radii_and_page_zero() {
for seed in 0..32 {
let scene = generate::seeded(seed, 16);
for p in &scene.primitives {
if p.params[1] == 2.0 {
assert_eq!(p.radii, [0.0; 4], "seed {seed}: glyph radii must be zero");
assert_eq!(p.params[2], 0.0, "seed {seed}: glyph page must be zero");
}
}
}
}
#[test]
fn translate_moves_fade_origin_turn_pivot_and_layer_hole() {
let mut scene = generate::scene(&[]);
scene.width = 48;
scene.height = 48;
scene.clear = [0.0, 0.0, 0.0, 1.0];
let mut faded = plain_prim(0.0);
faded.rect = [4.0, 4.0, 24.0, 24.0];
faded.fill = [0.9, 0.3, 0.2, 1.0];
faded.clip = [8.0, 8.0, 28.0, 28.0];
faded.fade = [-12.0, 0.0, 0.0, 0.0];
faded.fade_origin = Some([2.0, 8.0, 28.0, 28.0]);
let mut hole_layer = layer(8.0, 0.0);
hole_layer.rect = [20.0, 20.0, 20.0, 20.0];
hole_layer.radii = [30.0, 30.0, 4.0, 6.0];
let mut hole_child = plain_prim(0.0);
hole_child.node = 2;
hole_child.rect = [20.0, 20.0, 20.0, 20.0];
hole_child.fill = [0.2, 0.8, 0.4, 1.0];
let mut turned = layer(8.0, 0.0);
turned.rect = [24.0, 4.0, 12.0, 12.0];
turned.turn = Some([0.5, 30.0, 10.0]);
let mut turned_child = plain_prim(0.0);
turned_child.node = 3;
turned_child.rect = [24.0, 4.0, 12.0, 12.0];
turned_child.fill = [0.2, 0.4, 0.9, 1.0];
scene.primitives = vec![
faded,
hole_layer,
hole_child,
layer(9.0, 0.0),
turned,
turned_child,
layer(9.0, 0.0),
];
let original = render(&scene);
let mut shifted = scene.clone();
shifted.width += 6;
shifted.height += 4;
generate::translate(&mut shifted, 6.0, 4.0);
let actual = render(&shifted);
for y in 0..48usize {
let row = &original.rgba[y * 48 * 4..(y + 1) * 48 * 4];
let start = ((y + 4) * 54 + 6) * 4;
assert_eq!(row, &actual.rgba[start..start + row.len()]);
}
}
#[test]
fn plus_lighter_blends_additively_inside_saturates_and_composites_source_over() {
let mut scene = generate::scene(&[]);
scene.width = 16;
scene.height = 16;
scene.clear = [0.0, 0.0, 0.5, 1.0];
let mut open = layer(8.0, 0.0);
open.rect = [0.0, 0.0, 16.0, 16.0];
open.params[0] = 1.0; // PlusLighter
open.fill = [0.0, 0.0, 0.0, 0.5]; // 50% layer opacity
let mut child = generate::scene(&[[0; 32]]).primitives.remove(0);
child.rect = [0.0, 0.0, 16.0, 16.0];
child.radii = [0.0; 4];
child.params = [0.0, 0.0, 0.0, 1.0];
child.border = [0.0; 4];
child.clip = NO_CLIP;
child.fade = [0.0; 4];
child.fill = [0.6, 0.0, 0.0, 0.6];
// Two identical children sum to [1.2, 0, 0, 1.2], saturate to [1, 0, 0, 1], then multiply by
// opacity 0.5 -> [0.5, 0, 0, 0.5], composited source-over [0, 0, 0.5, 1] -> [0.5, 0, 0.25, 1].
scene.primitives = vec![open, child.clone(), child, layer(9.0, 0.0)];
let frame = render(&scene);
let px = &frame.rgba[(8 * 16 + 8) * 4..(8 * 16 + 8) * 4 + 4];
// srgb_encode(0.5) * 255 = 188, srgb_encode(0.25) * 255 = 137.
assert!(px[0].abs_diff(188) <= 1 && px[1] == 0 && px[2].abs_diff(137) <= 1 && px[3] == 255, "got {px:?}");
}
#[test]
fn rounded_clip_clips_ordinary_primitive_corners() {
let mut scene = generate::scene(&[]);
scene.width = 32;
scene.height = 32;
scene.clear = [0.0, 0.0, 0.0, 1.0];
let mut rect = generate::scene(&[[0; 32]]).primitives.remove(0);
rect.rect = [0.0, 0.0, 32.0, 32.0];
rect.radii = [0.0; 4];
rect.fill = [1.0, 1.0, 1.0, 1.0];
rect.border = [0.0; 4];
rect.params = [0.0, 0.0, 0.0, 1.0];
rect.clip = [0.0, 0.0, 32.0, 32.0];
rect.fade = [0.0; 4];
rect.clip_radii = Some([12.0; 4]);
scene.primitives = vec![rect];
let frame = render(&scene);
let corner = &frame.rgba[0..4];
let center = &frame.rgba[(16 * 32 + 16) * 4..(16 * 32 + 16) * 4 + 4];
assert_eq!(corner, &[0, 0, 0, 255], "rounded clip must cut the corner");
assert_eq!(center, &[255, 255, 255, 255], "centre stays filled");
}