Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-svg

Source of release 0.9.1

0.9.1 / src / svg / picture_tests.lucb

#==============================================================================================
#
#   svg/picture_tests - Tests of the document tree, the value parsers and the full renderer
#
#==============================================================================================

## Draw `source` into `width` by `height` straight-alpha sRGB bytes (in the heap).
func draw_test(source: str, width: u32, height: u32) -> u8[]!:
    let picture = try load(source)
    defer picture.release()
    let pixels = try new u8[(usize)width * (usize)height * 4] --- in memory.heap
    errdefer free(pixels) in memory.heap
    try render(picture.value(), fit_transform(picture.value(), width, height), width, height, pixels)
    return pixels

## The RGBA of pixel (x, y) of a `width`-wide bitmap.
func rgba_at(pixels: const u8[], width: u32, x: u32, y: u32) -> u8[4]:
    let at = ((usize)y * (usize)width + (usize)x) * 4
    return [pixels[at], pixels[at + 1], pixels[at + 2], pixels[at + 3]]

func near_byte(value: u8, expected: i64, tolerance: i64) -> bool:
    return math.iabs((i64)value - expected) <= tolerance

# mark: Value parsers =========================================================================

test "numbers, lengths and angles parse as SVG writes them":
    assert((parse_number(" 1e2 ") else 0.0) == 100.0 and (parse_number("-.5") else 0.0) == -0.5)
    assert(parse_number("1px") == none and parse_number("") == none and parse_number(".") == none)
    let em = parse_length("2em") else error(invalid, "a length did not parse")
    assert(em.number == 2.0 and em.unit == Unit.em)
    let percent = parse_length("12.5%") else error(invalid, "a length did not parse")
    assert(percent.number == 12.5 and percent.unit == Unit.percent)
    assert((parse_angle("0.5turn") else 0.0) == 180.0 and (parse_angle("100grad") else 0.0) == 90.0)

test "transform lists compose every function and reject malformed ones":
    let m = parse_transform_list("translate(10 20) scale(2), rotate(90 1 1) skewX(45)") else error(invalid, "a transform did not parse")
    let p = m.map(1.0, 0.0)
    # skewX(45) keeps (1, 0); rotate(90) about (1, 1) takes it to (2, 1); scale and translate.
    assert(near(p.x, 14.0, 1e-9) and near(p.y, 22.0, 1e-9))
    assert(parse_transform_list("scale(1 2 3)") == none and parse_transform_list("rotate(1, 2)") == none)
    assert(parse_transform_list("translate(5)") != none and parse_transform_list("") != none)

test "viewBoxes and preserveAspectRatio fit a box into a viewport":
    let box = parse_view_box("0 0 100 50") else error(invalid, "a viewBox did not parse")
    assert(parse_view_box("0 0 -1 5") == none)
    let meet = parse_aspect_ratio("xMidYMid meet") else error(invalid, "an aspect did not parse")
    let fit = view_box_transform(box, meet, 200.0, 200.0)
    assert(fit.a == 2.0 and fit.f == 50.0)
    let slice = parse_aspect_ratio("xMinYMax slice") else error(invalid, "an aspect did not parse")
    let cover = view_box_transform(box, slice, 200.0, 200.0)
    assert(cover.a == 4.0 and cover.e == 0.0 and cover.f == 0.0)
    assert(parse_aspect_ratio("xMidYMid wrong") == none)

test "CSS colors parse in every form, with their alpha":
    let short_hex = parse_rgba("#0f08") else error(invalid, "a color did not parse")
    assert(short_hex.r == 0.0 and short_hex.g == 1.0 and near(short_hex.a, 136.0 / 255.0, 1e-12))
    let rgba = parse_rgba("rgba(0, 127, 0, 0.5)") else error(invalid, "a color did not parse")
    assert(near(rgba.g, 127.0 / 255.0, 1e-12) and rgba.a == 0.5)
    let modern = parse_rgba("rgb(255 0 0 / 25%)") else error(invalid, "a color did not parse")
    assert(modern.r == 1.0 and modern.a == 0.25)
    let hsl = parse_rgba("hsl(120, 100%, 25%)") else error(invalid, "a color did not parse")
    assert(hsl.r == 0.0 and near(hsl.g, 0.5, 1e-12) and hsl.b == 0.0)
    let hwb = parse_rgba("hwb(0 0% 0%)") else error(invalid, "a color did not parse")
    assert(hwb.r == 1.0 and hwb.g == 0.0)
    let lab_white = parse_rgba("lab(100 0 0)") else error(invalid, "a color did not parse")
    assert(near(lab_white.r, 1.0, 1e-3) and near(lab_white.g, 1.0, 1e-3) and near(lab_white.b, 1.0, 1e-3))
    let oklch = parse_rgba("oklch(0.628 0.2577 29.23)") else error(invalid, "a color did not parse")
    assert(near(oklch.r, 1.0, 0.01) and oklch.g < 0.05 and oklch.b < 0.05)
    let p3 = parse_rgba("color(display-p3 1 0 0)") else error(invalid, "a color did not parse")
    assert(near(p3.r, 1.0, 1e-9) and p3.g == 0.0)
    assert(parse_rgba("rgba(0, 50%, 0, 1)") == none and parse_rgba("transparent") != none and parse_rgba("currentColor") == none)

test "path data reads every command, stops at an error, and bounds are tight":
    var path = Path()
    defer path.release()
    let whole = try parse_path_data("M10 10 h10 v10 H10 z m5 5 l1 1 q2 2 4 0 t4 0 c1 1 2 2 3 3 s1 1 2 2 a5 5 0 0 1 10 0", &path)
    assert(whole and path.verb_count() > 10)
    var broken = Path()
    defer broken.release()
    let complete = try parse_path_data("M 0 0 L 10 0 L 10 x L 0 10", &broken)
    assert(not complete and broken.verb_count() == 2)
    var circle = Path()
    defer circle.release()
    try circle.move_to(10.0, 0.0)
    try circle.arc_to(10.0, 10.0, 0.0, false, true, -10.0, 0.0)
    try circle.arc_to(10.0, 10.0, 0.0, false, true, 10.0, 0.0)
    let bounds = circle.bounds() else error(invalid, "a path had no bounds")
    assert(near(bounds.y, -10.0, 1e-9) and near(bounds.h, 20.0, 1e-9) and near(bounds.w, 20.0, 1e-9))

# mark: The document tree =====================================================================

test "the tree keeps SVG elements, expands entities and resolves the cascade":
    let source = "<!DOCTYPE svg [<!ENTITY box \"<rect id='r' width='4' height='4'/>\"><!ENTITY red \"#f00\">]><svg:svg xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns:x=\"urn:x\"><style><![CDATA[ rect { fill: blue } #r { fill: green !important } svg > rect:first-child { stroke: red } ]]></style><svg:g fill=\"&red;\">&box;<x:rect/></svg:g><svg:rect class=\"a b\" style=\"fill: red\" fill=\"yellow\"/></svg:svg>"
    var tree = Tree()
    defer tree.release()
    try build_tree(source, &tree)
    let svg = tree.root_element()
    let group = tree.first_element_child(svg)
    assert(tree.tag(svg) == Tag.svg and tree.tag(group) == Tag.g)
    assert((tree.attribute(group, Attr.fill) else "") == "#f00")
    let rect = tree.element_by_id("r") else error(invalid, "the entity's rect is missing")
    # The rect from the entity: !important wins over the later style attribute's absence.
    assert((tree.attribute(rect, Attr.fill) else "") == "green" and tree.next_sibling(rect) == 0)
    let last = tree.next_sibling(group)
    assert((tree.attribute(last, Attr.fill) else "") == "red")

test "inherit takes the parent's value or the initial one, and use copies its target":
    var tree = Tree()
    defer tree.release()
    try build_tree("<svg xmlns=\"http://www.w3.org/2000/svg\"><g id=\"g\" stroke=\"red\"><rect id=\"a\" stroke=\"inherit\" opacity=\"inherit\"/></g><use href=\"#g\"/></svg>", &tree)
    let rect = tree.element_by_id("a") else error(invalid, "the rect is missing")
    assert((tree.attribute(rect, Attr.stroke) else "") == "red" and (tree.attribute(rect, Attr.opacity) else "") == "1")
    let use = tree.next_sibling(tree.element_by_id("g") else 0)
    let copy = tree.first_element_child(use)
    assert(tree.tag(copy) == Tag.g and tree.element_id(copy) == "" and tree.tag(tree.first_element_child(copy)) == Tag.rect)

# mark: Rendering =============================================================================

test "a rectangle fills its pixels exactly, and even-odd leaves its hole":
    let pixels = try draw_test("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\"><path fill-rule=\"evenodd\" fill=\"#00ff00\" d=\"M2 2h16v16H2z M6 6h8v8H6z\"/></svg>", 20, 20)
    defer free(pixels) in memory.heap
    let outer = rgba_at(pixels, 20, 3, 3)
    assert(outer[1] == 255 and outer[3] == 255 and outer[0] == 0)
    assert(rgba_at(pixels, 20, 10, 10)[3] == 0 and rgba_at(pixels, 20, 1, 1)[3] == 0)

test "group opacity composites the group as one layer, in sRGB":
    let pixels = try draw_test("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"10\" height=\"10\"><rect width=\"10\" height=\"10\" fill=\"white\"/><g opacity=\"0.5\"><rect width=\"10\" height=\"10\"/><rect width=\"10\" height=\"10\"/></g></svg>", 10, 10)
    defer free(pixels) in memory.heap
    # Black at half opacity over white, once (not twice), blended in sRGB: 128.
    let p = rgba_at(pixels, 10, 5, 5)
    assert(near_byte(p[0], 128, 1) and p[3] == 255)

test "a linear gradient spreads by reflection and repetition":
    let source = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"10\"><linearGradient id=\"g\" x2=\"0.5\" spreadMethod=\"reflect\"><stop offset=\"0\" stop-color=\"black\"/><stop offset=\"1\" stop-color=\"white\"/></linearGradient><rect width=\"40\" height=\"10\" fill=\"url(#g)\"/></svg>"
    let pixels = try draw_test(source, 40, 10)
    defer free(pixels) in memory.heap
    # Black at the left, white at the middle, black again at the right.
    assert(rgba_at(pixels, 40, 0, 5)[0] < 10 and rgba_at(pixels, 40, 20, 5)[0] > 240 and rgba_at(pixels, 40, 39, 5)[0] < 10)

test "clip paths, masks and use draw what they should":
    let source = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"30\" height=\"10\"><defs><clipPath id=\"c\"><rect width=\"5\" height=\"10\"/></clipPath><mask id=\"m\"><rect x=\"10\" width=\"10\" height=\"10\" fill=\"white\"/></mask><symbol id=\"s\" viewBox=\"0 0 1 1\"><rect width=\"1\" height=\"1\" fill=\"blue\"/></symbol></defs><rect width=\"10\" height=\"10\" fill=\"red\" clip-path=\"url(#c)\"/><rect x=\"10\" width=\"10\" height=\"10\" fill=\"lime\" mask=\"url(#m)\"/><use href=\"#s\" x=\"20\" width=\"10\" height=\"10\"/></svg>"
    let pixels = try draw_test(source, 30, 10)
    defer free(pixels) in memory.heap
    assert(rgba_at(pixels, 30, 2, 5)[0] == 255 and rgba_at(pixels, 30, 7, 5)[3] == 0)
    assert(rgba_at(pixels, 30, 15, 5)[1] == 255 and rgba_at(pixels, 30, 15, 5)[3] == 255)
    assert(rgba_at(pixels, 30, 25, 5)[2] == 255 and rgba_at(pixels, 30, 25, 5)[3] == 255)

test "strokes union their pieces: overlapping round caps keep soft edges":
    let pixels = try draw_test("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\"><path d=\"M10 10 h0\" stroke=\"black\" stroke-width=\"10\" stroke-linecap=\"round\"/></svg>", 20, 20)
    defer free(pixels) in memory.heap
    # Two caps on one point: the disc's edge stays partial rather than doubled.
    assert(rgba_at(pixels, 20, 10, 10)[3] == 255 and rgba_at(pixels, 20, 0, 0)[3] == 0)
    let edge = rgba_at(pixels, 20, 14, 7)[3]
    assert(edge > 0 and edge < 255)

test "patterns tile their content, in user space or the shape's box":
    let source = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"10\"><pattern id=\"p\" width=\"4\" height=\"4\" patternUnits=\"userSpaceOnUse\"><rect width=\"2\" height=\"4\" fill=\"blue\"/></pattern><pattern id=\"q\" width=\"0.5\" height=\"1\"><rect width=\"5\" height=\"10\" fill=\"red\"/></pattern><rect width=\"10\" height=\"10\" fill=\"url(#p)\"/><rect x=\"10\" width=\"10\" height=\"10\" fill=\"url(#q)\"/></svg>"
    let pixels = try draw_test(source, 20, 10)
    defer free(pixels) in memory.heap
    # Blue columns 0-1 and 4-5, empty 2-3 and 6-7.
    assert(rgba_at(pixels, 20, 0, 5)[2] == 255 and rgba_at(pixels, 20, 2, 5)[3] == 0 and rgba_at(pixels, 20, 5, 5)[2] == 255)
    # The second tile is half the box wide, its red rect at the start of each tile.
    assert(rgba_at(pixels, 20, 11, 5)[0] == 255 and rgba_at(pixels, 20, 16, 5)[0] == 255)

test "transform-origin moves the origin of a transform":
    let pixels = try draw_test("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\"><rect x=\"5\" y=\"5\" width=\"10\" height=\"10\" fill=\"lime\" transform=\"scale(0.5)\" transform-origin=\"center\"/></svg>", 20, 20)
    defer free(pixels) in memory.heap
    # Scaled about the viewport's centre (10, 10): the rect becomes 7.5..12.5.
    assert(rgba_at(pixels, 20, 10, 10)[3] == 255 and rgba_at(pixels, 20, 6, 6)[3] == 0 and rgba_at(pixels, 20, 3, 3)[3] == 0)

test "markers sit on a path's vertices, turned along it, painted with context-fill":
    let source = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"20\"><marker id=\"m\" markerWidth=\"4\" markerHeight=\"4\" refX=\"2\" refY=\"2\" markerUnits=\"userSpaceOnUse\" orient=\"auto\"><rect width=\"4\" height=\"2\" fill=\"context-stroke\"/></marker><path d=\"M5 10 H35\" stroke=\"blue\" stroke-width=\"0.1\" marker-start=\"url(#m)\" marker-end=\"url(#m)\"/></svg>"
    let pixels = try draw_test(source, 40, 20)
    defer free(pixels) in memory.heap
    # Each marker covers x ± 2 above the line (y 8..10), in the stroke's blue.
    assert(rgba_at(pixels, 40, 4, 8)[2] == 255 and rgba_at(pixels, 40, 34, 8)[2] == 255)
    assert(rgba_at(pixels, 40, 4, 11)[3] == 0 and rgba_at(pixels, 40, 20, 8)[3] == 0)
    assert(paint_order("markers stroke")[1] == 1 and paint_order("stroke stroke")[0] == 0 and paint_order("fill x")[0] == 0)

test "images draw PNG data URLs pixelated or smooth, and SVG images as vectors":
    let source = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"20\"><image width=\"20\" height=\"10\" image-rendering=\"pixelated\" href=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAYAAAD0In+KAAAADklEQVR4nGP4z8AAQv8BD/kD/YURmXYAAAAASUVORK5CYII=\"/><image x=\"20\" width=\"20\" height=\"20\" href=\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjxyZWN0IHdpZHRoPSI0IiBoZWlnaHQ9IjQiIGZpbGw9ImxpbWUiLz48L3N2Zz4=\"/></svg>"
    let pixels = try draw_test(source, 40, 20)
    defer free(pixels) in memory.heap
    # The 2 by 1 PNG fills 20 by 10: red on the left half, blue on the right.
    assert(rgba_at(pixels, 40, 3, 5)[0] == 255 and rgba_at(pixels, 40, 16, 5)[2] == 255 and rgba_at(pixels, 40, 5, 15)[3] == 0)
    assert(rgba_at(pixels, 40, 30, 10)[1] == 255 and rgba_at(pixels, 40, 30, 10)[3] == 255)
    var bytes = List[u8]()
    defer bytes.release()
    assert((try decode_base64("aGVs bG8=".bytes, &bytes)) and (str)bytes.view() == "hello")

test "filters: flood, offset, composite, blur and color matrix run in their color spaces":
    let source = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"20\"><filter id=\"f\" x=\"0\" y=\"0\" width=\"1\" height=\"1\"><feFlood flood-color=\"red\"/><feComposite in2=\"SourceAlpha\" operator=\"in\"/><feOffset dx=\"5\"/></filter><filter id=\"g\" color-interpolation-filters=\"sRGB\"><feColorMatrix type=\"matrix\" values=\"0 0 0 0 0  0 0 0 0 1  0 0 0 0 0  0 0 0 1 0\"/></filter><filter id=\"b\"><feGaussianBlur stdDeviation=\"2\"/></filter><rect width=\"10\" height=\"10\" filter=\"url(#f)\"/><rect x=\"20\" width=\"10\" height=\"10\" fill=\"blue\" filter=\"url(#g)\"/><rect x=\"10\" y=\"12\" width=\"20\" height=\"6\" filter=\"url(#b)\"/></svg>"
    let pixels = try draw_test(source, 40, 20)
    defer free(pixels) in memory.heap
    # The red flood, cut to the rect's alpha and moved 5 right, inside the filter region.
    assert(rgba_at(pixels, 40, 2, 5)[3] == 0 and rgba_at(pixels, 40, 7, 5)[0] == 255 and rgba_at(pixels, 40, 7, 5)[3] == 255)
    # The matrix turns blue into green.
    let green = rgba_at(pixels, 40, 25, 5)
    assert(green[1] == 255 and green[2] == 0)
    # The blur spreads the bar's edge.
    let edge = rgba_at(pixels, 40, 10, 15)[3]
    assert(edge > 40 and edge < 220 and rgba_at(pixels, 40, 20, 15)[3] > 200)