dymokomi/luce-browser-render
Source of release 0.6.1
0.6.1 / tests / raster / harness.lucb
#==============================================================================================
#
# harness - the integration test harness of the rasterizer
#
# DESCRIPTION:
# What tiny-skia's integration tests get from the test framework and the png-format
# feature: Pixmap::load_png (decode, then premultiply as tiny-skia does), the
# `assert_eq!(pixmap, expected)` comparison against a reference image, and a record
# of failures. A failed comparison writes the actual image to
# build/raster-failures/<test>.png.
#
# Copyright (c) 2020 Yevhenii Reizner (tiny-skia's tests)
# Copyright (c) 2026 the luce-browser authors.
# SPDX-License-Identifier: BSD-3-Clause (see LICENSE-tiny-skia)
#
#==============================================================================================
import c
import memory
from luce_std import files
import raster_png
from luce_browser_render import raster
import strings
## One test: a name and a function that records failures in the Test.
pub struct TestCase:
pub let name: str
pub let run: func(Test*) -> unit
## The state of the running test.
pub struct Test:
pub var name: str
pub var failures: u32
## Record a failure.
pub func fail(message: fmt):
print(f" FAIL {self.name}: {message}")
self.failures += 1
## Record a failure unless `condition`.
pub func check(condition: bool, message: str):
if not condition:
self.fail(message)
func path_buffer(buffer: u8[], text: fmt) -> c.str:
let s = strings.format(buffer, text) else trap("path too long")
return (c.str)s
## Pixmap::load_png: `image` is relative to tests/raster/images.
pub func load_png(image: str) -> raster.Pixmap:
var buffer: u8[512]
let path = path_buffer(buffer, f"tests/raster/images/{image}")
let bytes = files.read(path) else trap("cannot read the image")
defer bytes.release()
let decoded = raster_png.decode_rgba8(bytes.value) else trap("cannot decode the image")
let data = decoded.rgba
# Premultiply alpha.
#
# We cannon use RasterPipeline here, which is faster, because it produces slightly
# different results. Seems like Skia does the same.
var i: usize = 0
while i < data.length:
let a = data[i + 3]
data[i + 0] = raster.premultiply_u8(data[i + 0], a)
data[i + 1] = raster.premultiply_u8(data[i + 1], a)
data[i + 2] = raster.premultiply_u8(data[i + 2], a)
i += 4
let size = raster.IntSize.from_wh(decoded.width, decoded.height) else trap("invalid image size")
return raster.Pixmap.from_vec(data, size) else trap("failed to create a pixmap")
## Pixmap::encode_png + save: writes the pixmap (demultiplied) as a PNG.
pub func save_png(pixmap: const raster.Pixmap*, path: c.str):
var copy = pixmap.clone()
let data = copy.take_demultiplied()
defer free(data) in memory.heap
let encoded = raster_png.encode_rgba8(pixmap.width(), pixmap.height(), data) else trap("cannot encode")
defer free(encoded) in memory.heap
with memory.heap:
files.write(path, encoded) catch failure:
print(f" cannot write the failure image: {failure.message}")
## When not empty, every image a test renders is also written to `<save_dir>/<image>`
## (`run --save DIR`), for comparing with Skia's.
pub var save_dir: str
func save_actual(pixmap: const raster.Pixmap*, image: str):
with memory.heap:
files.create_directory(path_buffer_str(save_dir)) catch:
recover ()
# the image's directories, if any, one level at a time
for i in 0..<image.bytes.length:
if image.bytes[i] == '/':
var dir_buffer: u8[512]
let dir = path_buffer(dir_buffer, f"{save_dir}/{(str)image.bytes[..<i]}")
with memory.heap:
files.create_directory(dir) catch:
recover ()
var buffer: u8[512]
save_png(pixmap, path_buffer(buffer, f"{save_dir}/{image}"))
func path_buffer_str(text: str) -> c.str:
return (c.str)text
## `assert_eq!(pixmap, Pixmap::load_png(image))`.
pub func expect_png(t: Test*, pixmap: const raster.Pixmap*, image: str):
if save_dir.length > 0:
save_actual(pixmap, image)
var expected = load_png(image)
defer expected.release()
if pixmap.equals(&expected):
return
if pixmap.width() != expected.width() or pixmap.height() != expected.height():
t.fail(f"size {pixmap.width()}x{pixmap.height()} differs from {image} ({expected.width()}x{expected.height()})")
return
let a = pixmap.pixels()
let b = expected.pixels()
var differ: u32 = 0
var first: usize = 0
var max_delta: i32 = 0
for i in 0..<a.length:
if not a[i].equals(b[i]):
if differ == 0:
first = i
differ += 1
let deltas: i32[4] = [(i32)a[i].red() - (i32)b[i].red(), (i32)a[i].green() - (i32)b[i].green(), (i32)a[i].blue() - (i32)b[i].blue(), (i32)a[i].alpha() - (i32)b[i].alpha()]
for d in deltas:
let ad = d if d >= 0 else -d
if ad > max_delta:
max_delta = ad
let w = (usize)pixmap.width()
t.fail(f"{differ} pixels differ from {image} (max channel delta {max_delta}; first at {first % w},{first // w})")
with memory.heap:
files.create_directory("build") catch:
recover ()
files.create_directory("build/raster-failures") catch:
recover ()
var buffer: u8[512]
save_png(pixmap, path_buffer(buffer, f"build/raster-failures/{file_name(t.name)}.png"))
## Rust's `Drop` of a Stroke: frees its dash array.
pub func release_stroke(stroke: raster.Stroke*):
if let dash = stroke.dash:
var d = dash
d.release()
stroke.dash = none
## `pb.finish().is_none()`.
pub func finish_is_none(pb: raster.PathBuilder*) -> bool:
if let path = pb.finish():
var p = path
p.release()
return false
return true
## `pixmap.is_none()` for an optional pixmap (released when it is some).
pub func pixmap_is_none(pixmap: raster.Pixmap?) -> bool:
if let p = pixmap:
var pm = p
pm.release()
return false
return true
## `assert_eq!(actual, expected)` for optional rects.
pub func expect_rect(t: Test*, actual: raster.Rect?, expected: raster.Rect?):
if actual == none and expected == none:
return
let a = actual else trap("expected a rect")
let e = expected else trap("expected no rect")
if a.left() != e.left() or a.top() != e.top() or a.right() != e.right() or a.bottom() != e.bottom():
t.fail(f"rect ({a.left()}, {a.top()}, {a.right()}, {a.bottom()}) != ({e.left()}, {e.top()}, {e.right()}, {e.bottom()})")
func points_equal(a: raster.Point, b: raster.Point) -> bool:
return a.x == b.x and a.y == b.y
func segment_equals(a: raster.PathSegment, b: raster.PathSegment) -> bool:
match a:
.close:
match b:
.close: return true
_: return false
.move_to(p):
match b:
.move_to(q): return points_equal(p, q)
_: return false
.line_to(p):
match b:
.line_to(q): return points_equal(p, q)
_: return false
.quad_to(p1, p):
match b:
.quad_to(q1, q): return points_equal(p1, q1) and points_equal(p, q)
_: return false
.cubic_to(p1, p2, p):
match b:
.cubic_to(q1, q2, q): return points_equal(p1, q1) and points_equal(p2, q2) and points_equal(p, q)
_: return false
.conic_to(p1, p, w):
match b:
.conic_to(q1, q, v): return points_equal(p1, q1) and points_equal(p, q) and w == v
_: return false
## `assert_eq!(path.segments().collect::<Vec<_>>(), expected)`.
pub func expect_segments(t: Test*, path: const raster.Path*, expected: const raster.PathSegment[]):
var iter = path.segments()
var i: usize = 0
while let seg = iter.next():
if i >= expected.length:
t.fail("more segments than expected")
return
if not segment_equals(seg, expected[i]):
t.fail(f"segment {i} differs")
return
i += 1
if i != expected.length:
t.fail(f"{i} segments, expected {expected.length}")
## `assert_eq!(pixmap.pixel(x, y).unwrap(), expected)`.
pub func expect_pixel(t: Test*, pixmap: const raster.Pixmap*, x: u32, y: u32, expected: raster.PremultipliedColorU8):
let px = pixmap.pixel(x, y) else trap("no pixel")
if not px.equals(expected):
t.fail(f"pixel {x},{y} is ({px.red()}, {px.green()}, {px.blue()}, {px.alpha()}), expected ({expected.red()}, {expected.green()}, {expected.blue()}, {expected.alpha()})")
## `assert_eq!(pixmap.pixels(), expected)`.
pub func expect_pixels(t: Test*, pixmap: const raster.Pixmap*, expected: const raster.PremultipliedColorU8[]):
let pixels = pixmap.pixels()
if pixels.length != expected.length:
t.fail("pixel count differs")
return
for i in 0..<pixels.length:
if not pixels[i].equals(expected[i]):
let px = pixels[i]
t.fail(f"pixel {i} is ({px.red()}, {px.green()}, {px.blue()}, {px.alpha()})")
return
## `assert_eq!(mask, Mask::load_png(image))`: a grayscale reference.
pub func expect_mask_png(t: Test*, mask: const raster.Mask*, image: str):
var expected = load_png(image)
defer expected.release()
if mask.width() != expected.width() or mask.height() != expected.height():
t.fail(f"mask size differs from {image}")
return
let data = mask.data()
let pixels = expected.pixels()
var differ: u32 = 0
for i in 0..<data.length:
if data[i] != pixels[i].red():
differ += 1
if differ != 0:
t.fail(f"{differ} mask values differ from {image}")
## `StrokeDash::new(array, offset).is_some()`.
pub func dash_is_some(array: const f32[], offset: f32) -> bool:
if let dash = raster.StrokeDash.new_(array, offset):
var d = dash
d.release()
return true
return false
## A test name as a file name: `fill::quad` is `fill__quad`.
func file_name(name: str) -> str:
var i: usize = 0
let bytes = name.bytes
while i < bytes.length:
if bytes[i] == ':':
return file_name_buffer(name)
i += 1
return name
var name_storage: u8[256]
func file_name_buffer(name: str) -> str:
var n: usize = 0
for b in name.bytes:
if n + 1 >= name_storage.length:
break
name_storage[n] = '_' if b == ':' else b
n += 1
return (str)name_storage[..<n]