Skip to content

Lightpanda: the headless browser designed for AI and automation

Add re-usable buffer (instead of frame.arena) to limit memory usage

Karl Seguin952a860119da
diff --git a/src/browser/tests/element/svg/geometry.html b/src/browser/tests/element/svg/geometry.html
index 0e143b375..e3d67b71f 100644
--- a/src/browser/tests/element/svg/geometry.html
+++ b/src/browser/tests/element/svg/geometry.html
@@ -12,6 +12,13 @@
<path id=arc d="M0 0 A80 20 45 1 1 100 100"></path>
<path id=partial d="M10 10 L20 20 30"></path>
<path id=moves d="M0 0 10 10 20 0"></path>
+ <path id=overshoot d="M0 0 C0 -50 0 150 0 100"></path>
+ <g id=unresolved>
+ <rect x="0" y="0" width="10" height="10"></rect>
+ <use href="#circle"></use>
+ <image x="40" y="40" width="10" height="10"></image>
+ <svg x="0" y="0" width="10" height="10"><rect width="5" height="5"></rect></svg>
+ </g>
<g id=transformed transform="translate(10 20)">
<rect x="0" y="0" width="10" height="5"></rect>
<g transform="scale(2)"><circle cx="10" cy="10" r="2"></circle></g>
@@ -66,7 +73,9 @@
testing.expectEqual(20, box.y);
testing.expectEqual(35, box.width);
testing.expectEqual(40, box.height);
- testing.expectEqual(true, box instanceof DOMRect);
+ // SVG2 and Chrome return a DOMRect. Firefox returns its own legacy SVGRect,
+ // which does not inherit from DOMRect.
+ testing.expectEqual(true, box instanceof (window.SVGRect ?? DOMRect));
box = $('#circle').getBBox();
testing.expectEqual(40, box.x);
@@ -92,13 +101,20 @@
testing.expectEqual(17, box.width);
testing.expectEqual(9, box.height);
- box = $('#circle').getBBox({fill: false});
- testing.expectEqual(0, box.width);
- testing.expectError('NotSupportedError', () => $('#circle').getBBox({stroke: true}));
+ // Chrome declares no parameter at all and Firefox's flags degenerate to the
+ // fill geometry, so the options are inert in every engine.
+ testing.expectEqual(20, $('#circle').getBBox({fill: false}).width);
+ testing.expectEqual(20, $('#circle').getBBox({stroke: true}).width);
$('#circle').setAttribute('r', '-2');
testing.expectEqual(0, $('#circle').getBBox().width);
$('#circle').setAttribute('r', '10');
+
+ // Nested viewports, <use> and <image> contribute no geometry here, but they
+ // must not make the whole box unavailable.
+ box = $('#unresolved').getBBox();
+ testing.expectEqual(true, box.width >= 10);
+ testing.expectEqual(true, box.height >= 10);
}
</script>
@@ -126,6 +142,12 @@
testing.expectEqual(true, box.x < 0);
testing.expectEqual(true, box.width > 100);
testing.expectEqual(true, box.height >= 100);
+
+ // Both control points are collinear with the chord, so the curve overshoots
+ // the endpoints along it.
+ box = $('#overshoot').getBBox();
+ testing.expectEqual(0, box.width);
+ testing.expectEqual('-8.1', box.y.toFixed(1));
}
</script>
@@ -133,7 +155,8 @@
{
testing.expectEqual(5, $('#line').getTotalLength());
let point = $('#line').getPointAtLength(2.5);
- testing.expectEqual(true, point instanceof DOMPoint);
+ // As with getBBox, Firefox returns its legacy SVGPoint instead of a DOMPoint.
+ testing.expectEqual(true, point instanceof (window.SVGPoint ?? DOMPoint));
testing.expectEqual(2.5, point.x);
testing.expectEqual(4, point.y);
point = $('#line').getPointAtLength(-100);
@@ -150,11 +173,27 @@
testing.expectEqual(true, Math.abs(point.y - 75) < 0.01);
// pathLength calibrates author distance, not these native geometry methods.
- cubic.pathLength.baseVal.value = 10;
+ cubic.pathLength.baseVal = 10;
testing.expectEqual(true, Math.abs(cubic.getTotalLength() - 200) < 0.01);
}
</script>
+<script id=overshootLengthFirefoxDiverges>
+{
+ // #overshoot's control points are collinear with its chord, so flattening on
+ // their distance to the chord *line* sees a flat curve and measures the 100
+ // unit chord. Firefox does exactly that; Chrome measures the curve, and
+ // 132.38 is the true arc length, so we follow Chrome. Its own bounding box
+ // above is analytic in every engine, which is why only length disagrees.
+ const overshoot = $('#overshoot');
+ testing.expectEqual('132', overshoot.getTotalLength().toFixed(0));
+ // The curve leaves the start heading away from the chord, so four units along
+ // it sits four units below y=0. Firefox reports +4, on the chord.
+ const point = overshoot.getPointAtLength(4);
+ testing.expectEqual('-4.0', point.y.toFixed(1));
+}
+</script>
+
<script id=containerTransforms>
{
const box = $('#transformed').getBBox();
diff --git a/src/browser/webapi/element/svg/Geometry.zig b/src/browser/webapi/element/svg/Geometry.zig
index e1b4df58a..b4338f689 100644
--- a/src/browser/webapi/element/svg/Geometry.zig
+++ b/src/browser/webapi/element/svg/Geometry.zig
@@ -118,7 +118,7 @@ pub fn buildPath(self: *Geometry, frame: *Frame) !PathData.Path {
fn value(length: *AnimatedLength, frame: *Frame) ?f64 {
const base = length.getBaseVal();
- if (base.getUnitType() == 0) return null;
+ if (!base.hasKnownUnit()) return null;
const result = base.getValue(frame);
return if (std.math.isFinite(result)) result else null;
}
diff --git a/src/browser/webapi/element/svg/Graphics.zig b/src/browser/webapi/element/svg/Graphics.zig
index 70a6e7b27..c4dd4c08f 100644
--- a/src/browser/webapi/element/svg/Graphics.zig
+++ b/src/browser/webapi/element/svg/Graphics.zig
@@ -87,18 +87,10 @@ pub const JsApi = struct {
pub const getBBox = bridge.function(Graphics.getBBox, .{});
};
-const BoundingBoxOptions = struct {
- fill: bool = true,
- stroke: bool = false,
- markers: bool = false,
- clipped: bool = false,
-};
-
-pub fn getBBox(self: *Graphics, options_: ?BoundingBoxOptions, frame: *Frame) !*DOMRect {
- const options = options_ orelse BoundingBoxOptions{};
- if (options.stroke or options.markers or options.clipped) return error.NotSupported;
- if (!options.fill) return DOMRect.create(.{}, frame._factory);
-
+// SVGBoundingBoxOptions is not modelled: Chrome declares no parameter at all
+// and Firefox's flags degenerate to the fill geometry, so both engines answer
+// every call with the fill box.
+pub fn getBBox(self: *Graphics, frame: *Frame) !*DOMRect {
var bounds: PathData.Bounds = .{};
switch (self._type) {
.geometry => |geometry| {
@@ -106,10 +98,13 @@ pub fn getBBox(self: *Graphics, options_: ?BoundingBoxOptions, frame: *Frame) !*
defer path.deinit(frame.local_arena);
bounds = path.bounds(.{});
},
- .g, .a, .svg => try accumulateChildren(self, .{}, &bounds, frame),
- .defs, .use, .image => return error.InvalidStateError,
+ .g, .a, .svg => try accumulateChildren(self, .{}, &bounds, frame, 0),
+ .defs, .use, .image => {},
}
- if (bounds.isEmpty()) return DOMRect.create(.{}, frame._factory);
+ if (bounds.isEmpty()) {
+ return DOMRect.create(.{}, frame._factory);
+ }
+
return DOMRect.create(.{
.x = bounds.min_x,
.y = bounds.min_y,
@@ -118,7 +113,13 @@ pub fn getBBox(self: *Graphics, options_: ?BoundingBoxOptions, frame: *Frame) !*
}, frame._factory);
}
-fn accumulateChildren(parent: *Graphics, matrix: PathData.Matrix, bounds: *PathData.Bounds, frame: *Frame) !void {
+const MAX_NESTING_DEPTH = 512;
+
+fn accumulateChildren(parent: *Graphics, matrix: PathData.Matrix, bounds: *PathData.Bounds, frame: *Frame, depth: usize) !void {
+ if (depth == MAX_NESTING_DEPTH) {
+ return;
+ }
+
var child = parent.asNode().firstChild();
while (child) |node| : (child = node.nextSibling()) {
const element = node.is(Element) orelse continue;
@@ -133,9 +134,11 @@ fn accumulateChildren(parent: *Graphics, matrix: PathData.Matrix, bounds: *PathD
defer path.deinit(frame.local_arena);
bounds.merge(path.bounds(child_matrix));
},
- .g, .a => try accumulateChildren(graphics, child_matrix, bounds, frame),
- .defs => {},
- .svg, .use, .image => return error.InvalidStateError,
+ .g, .a => try accumulateChildren(graphics, child_matrix, bounds, frame, depth + 1),
+ // <defs> never renders. Nested viewports, <use> and <image> have
+ // geometry we cannot resolve yet, so they contribute nothing rather
+ // than making the whole box unavailable.
+ .defs, .svg, .use, .image => {},
}
}
}
@@ -143,7 +146,9 @@ fn accumulateChildren(parent: *Graphics, matrix: PathData.Matrix, bounds: *PathD
fn transformMatrix(element: *Element) PathData.Matrix {
const raw = element.getAttributeSafe(comptime .wrap("transform")) orelse return .{};
const trimmed = std.mem.trim(u8, raw, " \t\r\n");
- if (trimmed.len == 0 or std.mem.eql(u8, trimmed, "none")) return .{};
+ if (trimmed.len == 0 or std.mem.eql(u8, trimmed, "none")) {
+ return .{};
+ }
var matrix = DOMMatrixReadOnly.identity();
var iterator = DOMMatrixReadOnly.TransformFunctionIterator{ .input = trimmed, .allow_comma = true };
diff --git a/src/browser/webapi/svg/AnimatedNumber.zig b/src/browser/webapi/svg/AnimatedNumber.zig
index 7973f50fe..e96684772 100644
--- a/src/browser/webapi/svg/AnimatedNumber.zig
+++ b/src/browser/webapi/svg/AnimatedNumber.zig
@@ -1,9 +1,20 @@
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU Affero General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
const std = @import("std");
const lp = @import("lightpanda");
@@ -16,23 +27,13 @@ const AnimatedNumber = @This();
_element: *Element,
_attr_name: lp.String,
-_allow_percentage: bool,
pub const Kind = enum {
path_length,
- offset,
fn attributeName(self: Kind) lp.String {
return switch (self) {
.path_length => comptime .wrap("pathLength"),
- .offset => comptime .wrap("offset"),
- };
- }
-
- fn allowsPercentage(self: Kind) bool {
- return switch (self) {
- .path_length => false,
- .offset => true,
};
}
};
@@ -52,7 +53,6 @@ pub fn getOrCreate(element: *Element, kind: Kind, frame: *Frame) !*AnimatedNumbe
gop.value_ptr.* = try frame._factory.create(AnimatedNumber{
._element = element,
._attr_name = kind.attributeName(),
- ._allow_percentage = kind.allowsPercentage(),
});
}
return gop.value_ptr.*;
@@ -63,9 +63,11 @@ pub fn getBaseVal(self: *const AnimatedNumber) f32 {
}
pub fn setBaseVal(self: *AnimatedNumber, value: f32, frame: *Frame) !void {
- if (!std.math.isFinite(value)) return error.TypeError;
- const serialized = try std.fmt.allocPrint(frame.call_arena, "{d}", .{value});
- try self._element.setAttributeSafe(self._attr_name, lp.String.wrap(serialized), frame);
+ if (!std.math.isFinite(value)) {
+ return error.TypeError;
+ }
+ const serialized = try std.fmt.allocPrint(frame.local_arena, "{d}", .{value});
+ try self._element.setAttributeSafe(self._attr_name, .wrap(serialized), frame);
}
pub fn getAnimVal(self: *const AnimatedNumber) f32 {
@@ -75,10 +77,7 @@ pub fn getAnimVal(self: *const AnimatedNumber) f32 {
fn currentValue(self: *const AnimatedNumber) f32 {
const raw = self._element.getAttributeSafe(self._attr_name) orelse return 0;
const trimmed = std.mem.trim(u8, raw, " \t\r\n\x0c");
- const value = if (self._allow_percentage and std.mem.endsWith(u8, trimmed, "%"))
- (std.fmt.parseFloat(f32, trimmed[0 .. trimmed.len - 1]) catch return 0) / 100
- else
- std.fmt.parseFloat(f32, trimmed) catch return 0;
+ const value = std.fmt.parseFloat(f32, trimmed) catch return 0;
return if (std.math.isFinite(value)) value else 0;
}
diff --git a/src/browser/webapi/svg/Length.zig b/src/browser/webapi/svg/Length.zig
index 45a81ddbb..86274696d 100644
--- a/src/browser/webapi/svg/Length.zig
+++ b/src/browser/webapi/svg/Length.zig
@@ -73,6 +73,13 @@ pub fn getUnitType(self: *Length) u16 {
return @intFromEnum(self._unit);
}
+// An attribute SVG could not parse reports the unknown unit type. Callers that
+// need geometry substitute the property's default instead.
+pub fn hasKnownUnit(self: *Length) bool {
+ self.syncFromAttribute();
+ return self._unit != .unknown;
+}
+
pub fn getValue(self: *Length, frame: *Frame) f64 {
self.syncFromAttribute();
return self._value * self.unitToUserUnits(self._unit, frame);
diff --git a/src/browser/webapi/svg/Number.zig b/src/browser/webapi/svg/Number.zig
index c1c547d26..75aea8663 100644
--- a/src/browser/webapi/svg/Number.zig
+++ b/src/browser/webapi/svg/Number.zig
@@ -17,53 +17,27 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
const std = @import("std");
-const lp = @import("lightpanda");
const js = @import("../../js/js.zig");
const Frame = @import("../../Frame.zig");
-const Element = @import("../Element.zig");
const Number = @This();
_value: f32 = 0,
-_element: ?*Element = null,
-_attr_name: lp.String = .empty,
-_read_only: bool = false,
pub fn detached(frame: *Frame) !*Number {
return frame._factory.create(Number{});
}
-pub fn reflected(element: *Element, attr_name: lp.String, read_only: bool, frame: *Frame) !*Number {
- return frame._factory.create(Number{
- ._element = element,
- ._attr_name = attr_name,
- ._read_only = read_only,
- });
-}
-
-pub fn getValue(self: *Number) f32 {
- self.syncFromAttribute();
+pub fn getValue(self: *const Number) f32 {
return self._value;
}
-pub fn setValue(self: *Number, value: f32, frame: *Frame) !void {
- if (self._read_only) return error.NoModificationAllowed;
- if (!std.math.isFinite(value)) return error.TypeError;
+pub fn setValue(self: *Number, value: f32) !void {
+ // WebIDL float is restricted, and the bridge does not police that for us.
+ if (!std.math.isFinite(value)) {
+ return error.TypeError;
+ }
self._value = value;
- const element = self._element orelse return;
- const serialized = try std.fmt.allocPrint(frame.call_arena, "{d}", .{value});
- try element.setAttributeSafe(self._attr_name, lp.String.wrap(serialized), frame);
-}
-
-fn syncFromAttribute(self: *Number) void {
- const element = self._element orelse return;
- const raw = element.getAttributeSafe(self._attr_name) orelse {
- self._value = 0;
- return;
- };
- const trimmed = std.mem.trim(u8, raw, " \t\r\n\x0c");
- self._value = std.fmt.parseFloat(f32, trimmed) catch 0;
- if (!std.math.isFinite(self._value)) self._value = 0;
}
pub const JsApi = struct {
diff --git a/src/browser/webapi/svg/PathData.zig b/src/browser/webapi/svg/PathData.zig
index 69d2b0f88..9031ede7e 100644
--- a/src/browser/webapi/svg/PathData.zig
+++ b/src/browser/webapi/svg/PathData.zig
@@ -1,10 +1,20 @@
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
// This program is free software: you can redistribute it and/or modify
-// it under the terms of the GNU Affero General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
const std = @import("std");
const Allocator = std.mem.Allocator;
@@ -139,33 +149,58 @@ pub const Path = struct {
}
pub fn appendArc(self: *Path, start: Point, rx: f64, ry: f64, rotation: f64, large: bool, sweep: bool, end: Point, allocator: Allocator) !void {
- if (self.first_point == null) self.first_point = start;
- if (pointsEqual(start, end)) return;
- if (rx == 0 or ry == 0) return self.appendLine(start, end, allocator);
+ if (self.first_point == null) {
+ self.first_point = start;
+ }
+ if (pointsEqual(start, end)) {
+ return;
+ }
+ if (rx == 0 or ry == 0) {
+ return self.appendLine(start, end, allocator);
+ }
+
const arc = endpointArc(start, rx, ry, rotation, large, sweep, end) orelse
return self.appendLine(start, end, allocator);
+
try self.segments.append(allocator, .{ .arc = arc });
}
pub fn bounds(self: *const Path, matrix: Matrix) Bounds {
var result: Bounds = .{};
- for (self.segments.items) |segment| includeSegmentBounds(&result, segment, matrix);
+ for (self.segments.items) |segment| {
+ includeSegmentBounds(&result, segment, matrix);
+ }
return result;
}
pub fn totalLength(self: *const Path, allocator: Allocator) !f64 {
+ // One buffer for every segment: growing a fresh list per segment leaves
+ // each intermediate copy behind in the arena.
+ var points: std.ArrayList(Point) = .empty;
+ defer points.deinit(allocator);
+
var total: f64 = 0;
- for (self.segments.items) |segment| total += try segmentLength(segment, allocator);
+ for (self.segments.items) |segment| {
+ points.clearRetainingCapacity();
+ try flatten(segment, &points, allocator);
+ for (points.items[0 .. points.items.len - 1], points.items[1..]) |a, b| {
+ total += distance(a, b);
+ }
+ }
return total;
}
pub fn pointAtLength(self: *const Path, requested: f64, allocator: Allocator) !Point {
- if (self.segments.items.len == 0) return self.first_point orelse .{ .x = 0, .y = 0 };
+ if (self.segments.items.len == 0) {
+ return self.first_point orelse .{ .x = 0, .y = 0 };
+ }
+
+ var points: std.ArrayList(Point) = .empty;
+ defer points.deinit(allocator);
var remaining = @max(requested, 0);
for (self.segments.items, 0..) |segment, segment_index| {
- var points: std.ArrayList(Point) = .empty;
- defer points.deinit(allocator);
+ points.clearRetainingCapacity();
try flatten(segment, &points, allocator);
for (points.items[0 .. points.items.len - 1], points.items[1..]) |a, b| {
@@ -181,7 +216,9 @@ pub const Path = struct {
remaining -= length;
}
- if (segment_index + 1 == self.segments.items.len) return segment.end();
+ if (segment_index + 1 == self.segments.items.len) {
+ return segment.end();
+ }
}
unreachable;
}
@@ -226,7 +263,9 @@ pub fn parse(input: []const u8, allocator: Allocator) !Path {
const cmd = command.?;
const kind = upper(cmd);
- if (!saw_moveto and kind != 'M') break;
+ if (!saw_moveto and kind != 'M') {
+ break;
+ }
const relative = std.ascii.isLower(cmd);
const allow_first_comma = !command_fresh;
@@ -345,31 +384,44 @@ const Parser = struct {
}
fn skipWhitespace(self: *Parser) void {
- while (!self.atEnd() and isWhitespace(self.peek())) self.index += 1;
+ while (!self.atEnd() and isWhitespace(self.peek())) {
+ self.index += 1;
+ }
}
fn separator(self: *Parser, allow_comma: bool) bool {
self.skipWhitespace();
if (!self.atEnd() and self.peek() == ',') {
- if (!allow_comma) return false;
+ if (!allow_comma) {
+ return false;
+ }
self.index += 1;
self.skipWhitespace();
- if (self.atEnd() or self.peek() == ',') return false;
+ if (self.atEnd() or self.peek() == ',') {
+ return false;
+ }
}
return true;
}
fn number(self: *Parser, allow_comma: bool) ?f64 {
- if (!self.separator(allow_comma)) return null;
+ if (!self.separator(allow_comma)) {
+ return null;
+ }
const start = self.index;
- if (self.atEnd()) return null;
+
+ if (self.atEnd()) {
+ return null;
+ }
if (self.peek() == '+' or self.peek() == '-') self.index += 1;
var digits: usize = 0;
while (!self.atEnd() and std.ascii.isDigit(self.peek())) : (self.index += 1) digits += 1;
if (!self.atEnd() and self.peek() == '.') {
self.index += 1;
- while (!self.atEnd() and std.ascii.isDigit(self.peek())) : (self.index += 1) digits += 1;
+ while (!self.atEnd() and std.ascii.isDigit(self.peek())) : (self.index += 1) {
+ digits += 1;
+ }
}
if (digits == 0) {
self.index = start;
@@ -448,7 +500,9 @@ fn distance(a: Point, b: Point) f64 {
fn endpointArc(start: Point, rx_input: f64, ry_input: f64, rotation_degrees: f64, large: bool, sweep: bool, end: Point) ?Arc {
var rx = @abs(rx_input);
var ry = @abs(ry_input);
- if (rx == 0 or ry == 0 or pointsEqual(start, end)) return null;
+ if (rx == 0 or ry == 0 or pointsEqual(start, end)) {
+ return null;
+ }
const rotation = @mod(rotation_degrees, 360.0) * std.math.pi / 180.0;
const cosine = @cos(rotation);
@@ -469,9 +523,13 @@ fn endpointArc(start: Point, rx_input: f64, ry_input: f64, rotation_degrees: f64
const ry2 = ry * ry;
const numerator = @max(0, rx2 * ry2 - rx2 * y_prime * y_prime - ry2 * x_prime * x_prime);
const denominator = rx2 * y_prime * y_prime + ry2 * x_prime * x_prime;
- if (denominator == 0) return null;
+ if (denominator == 0) {
+ return null;
+ }
var coefficient = @sqrt(numerator / denominator);
- if (large == sweep) coefficient = -coefficient;
+ if (large == sweep) {
+ coefficient = -coefficient;
+ }
const center_prime = Point{
.x = coefficient * rx * y_prime / ry,
@@ -492,8 +550,12 @@ fn endpointArc(start: Point, rx_input: f64, ry_input: f64, rotation_degrees: f64
};
const theta = std.math.atan2(first.y, first.x);
var delta = std.math.atan2(first.x * second.y - first.y * second.x, first.x * second.x + first.y * second.y);
- if (sweep and delta < 0) delta += tau;
- if (!sweep and delta > 0) delta -= tau;
+ if (sweep and delta < 0) {
+ delta += tau;
+ }
+ if (!sweep and delta > 0) {
+ delta -= tau;
+ }
return .{
.start = start,
@@ -513,34 +575,25 @@ fn includeSegmentBounds(bounds: *Bounds, segment: Segment, matrix: Matrix) void
switch (segment) {
.line => {},
- .quadratic => |quadratic| {
- includeQuadraticExtremum(bounds, quadratic.start.x, quadratic.control.x, quadratic.end.x, quadratic, matrix);
- includeQuadraticExtremum(bounds, quadratic.start.y, quadratic.control.y, quadratic.end.y, quadratic, matrix);
- includeTransformedQuadraticExtrema(bounds, quadratic, matrix);
- },
+ .quadratic => |quadratic| includeTransformedQuadraticExtrema(bounds, quadratic, matrix),
.cubic => |cubic| includeTransformedCubicExtrema(bounds, cubic, matrix),
.arc => |arc| includeArcExtrema(bounds, arc, matrix),
}
}
-// The direct-axis roots help the identity case and are harmless duplicates for
-// transformed paths. The transformed roots below are authoritative.
-fn includeQuadraticExtremum(bounds: *Bounds, p0: f64, p1: f64, p2: f64, quadratic: Quadratic, matrix: Matrix) void {
- const denominator = p0 - 2.0 * p1 + p2;
- if (@abs(denominator) < 1e-14) return;
- const t = (p0 - p1) / denominator;
- if (t > 0 and t < 1) bounds.include(matrix.apply(evalQuadratic(quadratic, t)));
-}
-
fn includeTransformedQuadraticExtrema(bounds: *Bounds, quadratic: Quadratic, matrix: Matrix) void {
const p0 = matrix.apply(quadratic.start);
const p1 = matrix.apply(quadratic.control);
const p2 = matrix.apply(quadratic.end);
for ([_][3]f64{ .{ p0.x, p1.x, p2.x }, .{ p0.y, p1.y, p2.y } }) |values| {
const denominator = values[0] - 2.0 * values[1] + values[2];
- if (@abs(denominator) < 1e-14) continue;
+ if (@abs(denominator) < 1e-14) {
+ continue;
+ }
const t = (values[0] - values[1]) / denominator;
- if (t > 0 and t < 1) bounds.include(matrix.apply(evalQuadratic(quadratic, t)));
+ if (t > 0 and t < 1) {
+ bounds.include(matrix.apply(evalQuadratic(quadratic, t)));
+ }
}
}
@@ -555,7 +608,9 @@ fn includeTransformedCubicExtrema(bounds: *Bounds, cubic: Cubic, matrix: Matrix)
const c = values[1] - values[0];
for (quadraticRoots(a, b, c)) |root| {
const t = root orelse continue;
- if (t > 0 and t < 1) bounds.include(matrix.apply(evalCubic(cubic, t)));
+ if (t > 0 and t < 1) {
+ bounds.include(matrix.apply(evalCubic(cubic, t)));
+ }
}
}
}
@@ -576,30 +631,41 @@ fn includeArcExtrema(bounds: *Bounds, arc: Arc, matrix: Matrix) void {
for (transformed) |coefficients| {
const candidate = std.math.atan2(coefficients[1], coefficients[0]);
for ([_]f64{ candidate, candidate + std.math.pi }) |angle| {
- if (angleInSweep(angle, arc.theta, arc.delta)) bounds.include(matrix.apply(evalArc(arc, angle)));
+ if (angleInSweep(angle, arc.theta, arc.delta)) {
+ bounds.include(matrix.apply(evalArc(arc, angle)));
+ }
}
}
}
fn quadraticRoots(a: f64, b: f64, c: f64) [2]?f64 {
if (@abs(a) < 1e-14) {
- if (@abs(b) < 1e-14) return .{ null, null };
+ if (@abs(b) < 1e-14) {
+ return .{ null, null };
+ }
return .{ -c / b, null };
}
const discriminant = b * b - 4.0 * a * c;
- if (discriminant < 0) return .{ null, null };
+ if (discriminant < 0) {
+ return .{ null, null };
+ }
+
const root = @sqrt(discriminant);
return .{ (-b + root) / (2.0 * a), (-b - root) / (2.0 * a) };
}
fn angleInSweep(angle: f64, start: f64, delta: f64) bool {
- if (delta >= 0) return positiveAngle(angle - start) <= delta + 1e-12;
+ if (delta >= 0) {
+ return positiveAngle(angle - start) <= delta + 1e-12;
+ }
return positiveAngle(start - angle) <= -delta + 1e-12;
}
fn positiveAngle(angle: f64) f64 {
var result = @mod(angle, tau);
- if (result < 0) result += tau;
+ if (result < 0) {
+ result += tau;
+ }
return result;
}
@@ -630,46 +696,63 @@ fn evalArc(arc: Arc, angle: f64) Point {
};
}
-fn segmentLength(segment: Segment, allocator: Allocator) !f64 {
- var points: std.ArrayList(Point) = .empty;
- defer points.deinit(allocator);
- try flatten(segment, &points, allocator);
-
- var total: f64 = 0;
- for (points.items[0 .. points.items.len - 1], points.items[1..]) |a, b| total += distance(a, b);
- return total;
-}
-
const flatten_tolerance = 0.001;
+// Above roughly a thousand user units, absolute tolerance costs subdivisions
+// nobody can observe, so it scales with the segment instead.
+const flatten_relative_tolerance = 1e-6;
const flatten_depth = 18;
fn flatten(segment: Segment, points: *std.ArrayList(Point), allocator: Allocator) !void {
try points.append(allocator, segment.start());
switch (segment) {
.line => |line| try points.append(allocator, line.end),
- .quadratic => |quadratic| try flattenQuadratic(quadratic, points, allocator, 0),
- .cubic => |cubic| try flattenCubic(cubic, points, allocator, 0),
- .arc => |arc| try flattenArc(arc, arc.theta, arc.theta + arc.delta, arc.start, arc.end, points, allocator, 0),
+ .quadratic => |quadratic| {
+ const legs = distance(quadratic.start, quadratic.control) + distance(quadratic.control, quadratic.end);
+ try flattenQuadratic(quadratic, toleranceFor(legs), points, allocator, 0);
+ },
+ .cubic => |cubic| {
+ const legs = distance(cubic.start, cubic.control1) +
+ distance(cubic.control1, cubic.control2) +
+ distance(cubic.control2, cubic.end);
+ try flattenCubic(cubic, toleranceFor(legs), points, allocator, 0);
+ },
+ .arc => |arc| try flattenArc(
+ arc,
+ toleranceFor(@abs(arc.delta) * @max(arc.rx, arc.ry)),
+ arc.theta,
+ arc.theta + arc.delta,
+ arc.start,
+ arc.end,
+ points,
+ allocator,
+ 0,
+ ),
}
}
-fn flattenQuadratic(segment: Quadratic, points: *std.ArrayList(Point), allocator: Allocator, depth: usize) !void {
- if (depth >= flatten_depth or pointLineDistance(segment.control, segment.start, segment.end) <= flatten_tolerance) {
+fn toleranceFor(size: f64) f64 {
+ return @max(flatten_tolerance, size * flatten_relative_tolerance);
+}
+
+fn flattenQuadratic(segment: Quadratic, tolerance: f64, points: *std.ArrayList(Point), allocator: Allocator, depth: usize) !void {
+ if (depth >= flatten_depth or pointSegmentDistance(segment.control, segment.start, segment.end) <= tolerance) {
return points.append(allocator, segment.end);
}
const a = Point.midpoint(segment.start, segment.control);
const b = Point.midpoint(segment.control, segment.end);
const middle = Point.midpoint(a, b);
- try flattenQuadratic(.{ .start = segment.start, .control = a, .end = middle }, points, allocator, depth + 1);
- try flattenQuadratic(.{ .start = middle, .control = b, .end = segment.end }, points, allocator, depth + 1);
+ try flattenQuadratic(.{ .start = segment.start, .control = a, .end = middle }, tolerance, points, allocator, depth + 1);
+ try flattenQuadratic(.{ .start = middle, .control = b, .end = segment.end }, tolerance, points, allocator, depth + 1);
}
-fn flattenCubic(segment: Cubic, points: *std.ArrayList(Point), allocator: Allocator, depth: usize) !void {
+fn flattenCubic(segment: Cubic, tolerance: f64, points: *std.ArrayList(Point), allocator: Allocator, depth: usize) !void {
const flatness = @max(
- pointLineDistance(segment.control1, segment.start, segment.end),
- pointLineDistance(segment.control2, segment.start, segment.end),
+ pointSegmentDistance(segment.control1, segment.start, segment.end),
+ pointSegmentDistance(segment.control2, segment.start, segment.end),
);
- if (depth >= flatten_depth or flatness <= flatten_tolerance) return points.append(allocator, segment.end);
+ if (depth >= flatten_depth or flatness <= tolerance) {
+ return points.append(allocator, segment.end);
+ }
const a = Point.midpoint(segment.start, segment.control1);
const b = Point.midpoint(segment.control1, segment.control2);
@@ -677,57 +760,89 @@ fn flattenCubic(segment: Cubic, points: *std.ArrayList(Point), allocator: Alloca
const d = Point.midpoint(a, b);
const e = Point.midpoint(b, c);
const middle = Point.midpoint(d, e);
- try flattenCubic(.{ .start = segment.start, .control1 = a, .control2 = d, .end = middle }, points, allocator, depth + 1);
- try flattenCubic(.{ .start = middle, .control1 = e, .control2 = c, .end = segment.end }, points, allocator, depth + 1);
+ try flattenCubic(.{ .start = segment.start, .control1 = a, .control2 = d, .end = middle }, tolerance, points, allocator, depth + 1);
+ try flattenCubic(.{ .start = middle, .control1 = e, .control2 = c, .end = segment.end }, tolerance, points, allocator, depth + 1);
}
-fn flattenArc(arc: Arc, start_angle: f64, end_angle: f64, start: Point, end: Point, points: *std.ArrayList(Point), allocator: Allocator, depth: usize) !void {
+fn flattenArc(arc: Arc, tolerance: f64, start_angle: f64, end_angle: f64, start: Point, end: Point, points: *std.ArrayList(Point), allocator: Allocator, depth: usize) !void {
const middle_angle = (start_angle + end_angle) / 2.0;
const middle = evalArc(arc, middle_angle);
- if (depth >= flatten_depth or pointLineDistance(middle, start, end) <= flatten_tolerance) {
+ if (depth >= flatten_depth or pointSegmentDistance(middle, start, end) <= tolerance) {
return points.append(allocator, end);
}
- try flattenArc(arc, start_angle, middle_angle, start, middle, points, allocator, depth + 1);
- try flattenArc(arc, middle_angle, end_angle, middle, end, points, allocator, depth + 1);
+ try flattenArc(arc, tolerance, start_angle, middle_angle, start, middle, points, allocator, depth + 1);
+ try flattenArc(arc, tolerance, middle_angle, end_angle, middle, end, points, allocator, depth + 1);
}
-fn pointLineDistance(point: Point, start: Point, end: Point) f64 {
+// Distance to the chord as a segment, not as an infinite line: control points
+// collinear with the chord but past its ends make a curve that overshoots, and
+// the distance to the line would call it flat and measure the chord instead.
+fn pointSegmentDistance(point: Point, start: Point, end: Point) f64 {
const dx = end.x - start.x;
const dy = end.y - start.y;
- const denominator = std.math.hypot(dx, dy);
- if (denominator == 0) return distance(point, start);
- return @abs(dy * point.x - dx * point.y + end.x * start.y - end.y * start.x) / denominator;
+ const length_squared = dx * dx + dy * dy;
+ if (length_squared == 0) {
+ return distance(point, start);
+ }
+ const projection = ((point.x - start.x) * dx + (point.y - start.y) * dy) / length_squared;
+ const clamped = std.math.clamp(projection, 0, 1);
+ return distance(point, .{ .x = start.x + clamped * dx, .y = start.y + clamped * dy });
}
+const testing = @import("../../../testing.zig");
+
test "path parser preserves complete packs before an error" {
- var path = try parse("M10 10 L20 20 30", std.testing.allocator);
- defer path.deinit(std.testing.allocator);
- try std.testing.expectEqual(@as(usize, 1), path.segments.items.len);
+ var path = try parse("M10 10 L20 20 30", testing.allocator);
+ defer path.deinit(testing.allocator);
+ try testing.expectEqual(1, path.segments.items.len);
const bounds = path.bounds(.{});
- try std.testing.expectEqual(@as(f64, 10), bounds.min_x);
- try std.testing.expectEqual(@as(f64, 20), bounds.max_x);
+ try testing.expectEqual(10, bounds.min_x);
+ try testing.expectEqual(20, bounds.max_x);
}
test "moveto coordinate pairs become lines and malformed exponents stop" {
- var path = try parse("M0 0 10 10 20 1e L99 99", std.testing.allocator);
- defer path.deinit(std.testing.allocator);
- try std.testing.expectEqual(@as(usize, 1), path.segments.items.len);
- try std.testing.expectEqual(Point{ .x = 10, .y = 10 }, path.segments.items[0].end());
+ var path = try parse("M0 0 10 10 20 1e L99 99", testing.allocator);
+ defer path.deinit(testing.allocator);
+ try testing.expectEqual(1, path.segments.items.len);
+ try testing.expectEqual(Point{ .x = 10, .y = 10 }, path.segments.items[0].end());
}
test "rotated arc bounds use ellipse derivative extrema" {
- var path = try parse("M0 0 A80 20 45 1 1 100 100", std.testing.allocator);
- defer path.deinit(std.testing.allocator);
+ var path = try parse("M0 0 A80 20 45 1 1 100 100", testing.allocator);
+ defer path.deinit(testing.allocator);
const bounds = path.bounds(.{});
- try std.testing.expect(bounds.min_x < 0);
- try std.testing.expect(bounds.max_y >= 100);
+ try testing.expectEqual(true, bounds.min_x < 0);
+ try testing.expectEqual(true, bounds.max_y >= 100);
}
test "length and point lookup share adaptive geometry" {
- var path = try parse("M0 0 C0 100 100 100 100 0", std.testing.allocator);
- defer path.deinit(std.testing.allocator);
- const length = try path.totalLength(std.testing.allocator);
- const middle = try path.pointAtLength(length / 2.0, std.testing.allocator);
- try std.testing.expectApproxEqAbs(@as(f64, 50), middle.x, 0.01);
- try std.testing.expectApproxEqAbs(@as(f64, 75), middle.y, 0.01);
+ var path = try parse("M0 0 C0 100 100 100 100 0", testing.allocator);
+ defer path.deinit(testing.allocator);
+ const length = try path.totalLength(testing.allocator);
+ try testing.expectDelta(200, length, 0.01);
+ const middle = try path.pointAtLength(length / 2.0, testing.allocator);
+ try testing.expectDelta(50, middle.x, 0.01);
+ try testing.expectDelta(75, middle.y, 0.01);
+}
+
+test "curves overshooting a collinear chord are still subdivided" {
+ // Both control points sit on the line through the endpoints, so a
+ // distance-to-chord test would report these as flat and measure the chord.
+ var cubic = try parse("M0 0 C0 -50 0 150 0 100", testing.allocator);
+ defer cubic.deinit(testing.allocator);
+ try testing.expectDelta(132.38, try cubic.totalLength(testing.allocator), 0.01);
+
+ var quadratic = try parse("M0 0 Q0 200 0 100", testing.allocator);
+ defer quadratic.deinit(testing.allocator);
+ try testing.expectDelta(166.67, try quadratic.totalLength(testing.allocator), 0.01);
+}
+
+test "large geometry stays within the subdivision budget" {
+ var path = try parse("M0 0 A1e8 1e8 45 1 1 100 100", testing.allocator);
+ defer path.deinit(testing.allocator);
+
+ var points: std.ArrayList(Point) = .empty;
+ defer points.deinit(testing.allocator);
+ try flatten(path.segments.items[0], &points, testing.allocator);
+ try testing.expectEqual(true, points.items.len < 2048);
}