Skip to content

Truly independent web browser

LibGfx: Find the vertices of polylines that follow a path

Jelle Raaijmakers75e7d3358130
diff --git a/Libraries/LibGfx/Path.h b/Libraries/LibGfx/Path.h
index 304d9ac4a75..d0aa4df8395 100644
--- a/Libraries/LibGfx/Path.h
+++ b/Libraries/LibGfx/Path.h
@@ -27,6 +27,12 @@ struct PointAlongPath {
FloatVector2 tangent;
};
+struct PathVertex {
+ FloatPoint point;
+ float distance;
+ FloatVector2 direction;
+};
+
class PathImpl {
public:
AK_ALLOC_WITH_KMALLOC;
@@ -55,6 +61,7 @@ public:
virtual Gfx::FloatRect bounding_box() const = 0;
virtual float length() const = 0;
virtual Optional<PointAlongPath> point_at_length(float distance) const = 0;
+ virtual Vector<PathVertex> vertices() const = 0;
virtual void set_fill_type(Gfx::WindingRule winding_rule) = 0;
virtual bool contains(FloatPoint point, Gfx::WindingRule) const = 0;
@@ -123,6 +130,7 @@ public:
Gfx::FloatRect bounding_box() const { return impl().bounding_box(); }
float length() const { return impl().length(); }
Optional<PointAlongPath> point_at_length(float distance) const { return impl().point_at_length(distance); }
+ Vector<PathVertex> vertices() const { return impl().vertices(); }
bool contains(FloatPoint point, Gfx::WindingRule winding_rule) const { return impl().contains(point, winding_rule); }
void set_fill_type(Gfx::WindingRule winding_rule) { impl().set_fill_type(winding_rule); }
diff --git a/Libraries/LibGfx/PathSkia.cpp b/Libraries/LibGfx/PathSkia.cpp
index f797373c716..9dd5074f948 100644
--- a/Libraries/LibGfx/PathSkia.cpp
+++ b/Libraries/LibGfx/PathSkia.cpp
@@ -6,6 +6,8 @@
#define AK_DONT_REPLACE_STD
+#include <AK/GenericShorthands.h>
+#include <AK/Math.h>
#include <AK/Span.h>
#include <AK/TypeCasts.h>
#include <LibGfx/Font/Font.h>
@@ -212,6 +214,12 @@ void PathImplSkia::glyph_run(GlyphRun const& glyph_run)
// times as precisely instead.
static constexpr SkScalar path_measure_resolution_scale = 16;
+// The furthest that the lines between points along a curve stay off it when Skia measures the curve.
+static constexpr float path_measure_tolerance = 0.5f / path_measure_resolution_scale;
+
+// The most lines with which to follow a single curve, which bounds the number of vertices of a huge curve.
+static constexpr u32 maximum_line_count_along_curve = 4096;
+
NonnullOwnPtr<PathImpl> PathImplSkia::place_glyph_runs_along(ReadonlySpan<NonnullRefPtr<GlyphRun>> glyph_runs, float offset) const
{
SkPathMeasure path_measure(sk_path(), false, path_measure_resolution_scale);
@@ -339,6 +347,149 @@ Optional<PointAlongPath> PathImplSkia::point_at_length(float distance) const
return PointAlongPath { { start.x(), start.y() }, { 0, 0 } };
}
+// The number of lines with which to start following a curve, by Wang's formula: the square root of the largest second
+// difference of its control points, scaled by its degree, over the tolerance. That keeps lines between points at equal
+// parameter steps within the tolerance of the curve, and depends on how much the curve bends rather than on how long it
+// is.
+static u32 line_count_to_follow_curve(SkPathIter::Rec const& segment)
+{
+ auto const& points = segment.fPoints;
+ auto second_difference = [&](size_t index) {
+ return SkPoint::Length(points[index].x() - 2 * points[index + 1].x() + points[index + 2].x(),
+ points[index].y() - 2 * points[index + 1].y() + points[index + 2].y());
+ };
+
+ float scaled_second_difference = 0;
+ switch (segment.fVerb) {
+ case SkPathVerb::kQuad:
+ scaled_second_difference = second_difference(0) / 4;
+ break;
+ case SkPathVerb::kConic:
+ // A conic with a weight of at most 1, like the arcs of SVG paths, bends no more than the quadratic with the same
+ // control points.
+ scaled_second_difference = max(1.f, segment.conicWeight()) * second_difference(0) / 4;
+ break;
+ case SkPathVerb::kCubic:
+ scaled_second_difference = 3 * max(second_difference(0), second_difference(1)) / 4;
+ break;
+ default:
+ return 1;
+ }
+ auto line_count = AK::ceil(AK::sqrt(static_cast<double>(scaled_second_difference) / path_measure_tolerance));
+ return static_cast<u32>(clamp(line_count, 1., static_cast<double>(maximum_line_count_along_curve)));
+}
+
+struct CurveToFollow {
+ SkPathMeasure& measure;
+ float distance_to_curve;
+ Vector<PathVertex>& vertices;
+ u32 remaining_line_count;
+};
+
+// Appends the vertices between two points along a curve, splitting the line between them in half for as long as the
+// curve passes further than the tolerance from it halfway, or until the curve has as many lines as it may have.
+static void follow_curve_between(CurveToFollow& curve, float start_distance, FloatPoint start_point, float end_distance, FloatPoint end_point)
+{
+ if (curve.remaining_line_count == 0)
+ return;
+ auto middle_distance = (start_distance + end_distance) / 2;
+ SkPoint position;
+ SkVector tangent;
+ if (!curve.measure.getPosTan(middle_distance, &position, &tangent))
+ return;
+ FloatPoint middle_point { position.x(), position.y() };
+ if (middle_point.distance_from((start_point + end_point) / 2) <= path_measure_tolerance)
+ return;
+
+ --curve.remaining_line_count;
+ follow_curve_between(curve, start_distance, start_point, middle_distance, middle_point);
+ curve.vertices.append({ middle_point, curve.distance_to_curve + middle_distance, { tangent.x(), tangent.y() } });
+ follow_curve_between(curve, middle_distance, middle_point, end_distance, end_point);
+}
+
+// The vertices of polylines through the ends of the segments of the path, with their distance along it. Along a curved
+// segment, the polylines pass through points along the curve that keep them within path_measure_tolerance of it. The
+// gaps between the subpaths do not add to the distance, so a subpath starts at the distance its predecessor ends at. A
+// path without length is only its start point.
+Vector<PathVertex> PathImplSkia::vertices() const
+{
+ auto to_point = [](SkPoint point) { return FloatPoint { point.x(), point.y() }; };
+
+ // Each vertex has the unit tangent of the path there as its direction. Where the path changes direction at once,
+ // the vertex appears twice: with the direction in which the path arrives, and with the one in which it leaves. A
+ // subpath start that no segment with length leaves from has no direction.
+ Vector<PathVertex> vertices;
+ float distance = 0;
+ auto iterator = sk_path().iter();
+ while (auto segment = iterator.next()) {
+ auto const& points = segment->fPoints;
+ SkPathBuilder segment_builder;
+ segment_builder.moveTo(points[0]);
+ switch (segment->fVerb) {
+ case SkPathVerb::kMove:
+ vertices.append({ to_point(points[0]), distance, {} });
+ continue;
+ case SkPathVerb::kLine:
+ case SkPathVerb::kClose:
+ segment_builder.lineTo(points[1]);
+ break;
+ case SkPathVerb::kQuad:
+ segment_builder.quadTo(points[1], points[2]);
+ break;
+ case SkPathVerb::kConic:
+ segment_builder.conicTo(points[1], points[2], segment->conicWeight());
+ break;
+ case SkPathVerb::kCubic:
+ segment_builder.cubicTo(points[1], points[2], points[3]);
+ break;
+ }
+
+ // A segment without length has no direction, and leaves the path where it was.
+ SkPathMeasure segment_measure(segment_builder.detach(), false, path_measure_resolution_scale);
+ auto segment_length = segment_measure.getLength();
+ if (segment_length <= 0)
+ continue;
+ auto direction_at = [&](float distance_in_segment) {
+ SkVector tangent;
+ if (!segment_measure.getPosTan(distance_in_segment, nullptr, &tangent))
+ return FloatVector2 {};
+ return FloatVector2 { tangent.x(), tangent.y() };
+ };
+
+ auto start_direction = direction_at(0);
+ if (vertices.last().direction == FloatVector2 {})
+ vertices.last().direction = start_direction;
+ else if (vertices.last().direction != start_direction)
+ vertices.append({ to_point(points[0]), distance, start_direction });
+
+ auto line_count = line_count_to_follow_curve(*segment);
+ CurveToFollow curve { segment_measure, distance, vertices, maximum_line_count_along_curve - line_count };
+ auto previous_distance = 0.f;
+ auto previous_point = to_point(points[0]);
+ for (u32 line = 1; line <= line_count; ++line) {
+ auto distance_in_segment = segment_length * static_cast<float>(line) / static_cast<float>(line_count);
+ SkPoint position;
+ SkVector tangent;
+ if (line == line_count)
+ position = points.back();
+ else if (!segment_measure.getPosTan(distance_in_segment, &position, &tangent))
+ continue;
+ follow_curve_between(curve, previous_distance, previous_point, distance_in_segment, to_point(position));
+ if (line < line_count)
+ vertices.append({ to_point(position), distance + distance_in_segment, { tangent.x(), tangent.y() } });
+ previous_distance = distance_in_segment;
+ previous_point = to_point(position);
+ }
+ distance += segment_length;
+ vertices.append({ to_point(points.back()), distance, direction_at(segment_length) });
+ }
+
+ // Skia's iterator leaves out a move that ends the path.
+ if (vertices.is_empty() && sk_path().countPoints() > 0)
+ vertices.append({ to_point(sk_path().getPoint(0)), 0, {} });
+ return vertices;
+}
+
bool PathImplSkia::contains(FloatPoint point, Gfx::WindingRule winding_rule) const
{
SkPath temp_path = sk_path();
diff --git a/Libraries/LibGfx/PathSkia.h b/Libraries/LibGfx/PathSkia.h
index d50bea98636..b7526ad019b 100644
--- a/Libraries/LibGfx/PathSkia.h
+++ b/Libraries/LibGfx/PathSkia.h
@@ -41,6 +41,7 @@ public:
virtual Gfx::FloatRect bounding_box() const override;
virtual float length() const override;
virtual Optional<PointAlongPath> point_at_length(float distance) const override;
+ virtual Vector<PathVertex> vertices() const override;
virtual bool contains(FloatPoint point, Gfx::WindingRule) const override;
virtual void set_fill_type(Gfx::WindingRule winding_rule) override;
diff --git a/Tests/LibGfx/TestPath.cpp b/Tests/LibGfx/TestPath.cpp
index d7216804d02..1225a9d8b56 100644
--- a/Tests/LibGfx/TestPath.cpp
+++ b/Tests/LibGfx/TestPath.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Math.h>
#include <LibGfx/Path.h>
#include <LibTest/TestCase.h>
@@ -63,3 +64,87 @@ TEST_CASE(point_at_length_of_a_path_without_length)
EXPECT(!Gfx::Path {}.point_at_length(0).has_value());
}
+
+static void expect_vertices(Gfx::Path const& path, Vector<Gfx::PathVertex> const& expected_vertices)
+{
+ auto vertices = path.vertices();
+ VERIFY(vertices.size() == expected_vertices.size());
+ for (size_t i = 0; i < vertices.size(); ++i) {
+ EXPECT_APPROXIMATE_WITH_ERROR(vertices[i].point.x(), expected_vertices[i].point.x(), 0.0001f);
+ EXPECT_APPROXIMATE_WITH_ERROR(vertices[i].point.y(), expected_vertices[i].point.y(), 0.0001f);
+ EXPECT_APPROXIMATE_WITH_ERROR(vertices[i].distance, expected_vertices[i].distance, 0.0001f);
+ EXPECT_APPROXIMATE_WITH_ERROR(vertices[i].direction.x(), expected_vertices[i].direction.x(), 0.0001f);
+ EXPECT_APPROXIMATE_WITH_ERROR(vertices[i].direction.y(), expected_vertices[i].direction.y(), 0.0001f);
+ }
+}
+
+TEST_CASE(vertices_of_subpaths_of_lines)
+{
+ Gfx::Path path;
+ path.move_to({ 0, 0 });
+ path.line_to({ 10, 0 });
+ path.line_to({ 10, 10 });
+ path.close();
+ path.move_to({ 50, 50 });
+ path.line_to({ 60, 50 });
+
+ auto diagonal = AK::sqrt(200.f);
+ auto inverse_sqrt_2 = 1 / AK::sqrt(2.f);
+ expect_vertices(path,
+ {
+ { { 0, 0 }, 0, { 1, 0 } },
+ { { 10, 0 }, 10, { 1, 0 } },
+ { { 10, 0 }, 10, { 0, 1 } },
+ { { 10, 10 }, 20, { 0, 1 } },
+ { { 10, 10 }, 20, { -inverse_sqrt_2, -inverse_sqrt_2 } },
+ { { 0, 0 }, 20 + diagonal, { -inverse_sqrt_2, -inverse_sqrt_2 } },
+ { { 50, 50 }, 20 + diagonal, { 1, 0 } },
+ { { 60, 50 }, 30 + diagonal, { 1, 0 } },
+ });
+}
+
+TEST_CASE(vertices_along_curves)
+{
+ Gfx::Path path;
+ path.move_to({ 0, 0 });
+ path.quadratic_bezier_curve_to({ 50, 0 }, { 100, 0 });
+ expect_vertices(path, { { { 0, 0 }, 0, { 1, 0 } }, { { 100, 0 }, 100, { 1, 0 } } });
+
+ Gfx::Path long_path;
+ long_path.move_to({ 0, 0 });
+ long_path.quadratic_bezier_curve_to({ 10'000'000, 0 }, { 20'000'000, 0 });
+ expect_vertices(long_path, { { { 0, 0 }, 0, { 1, 0 } }, { { 20'000'000, 0 }, 20'000'000, { 1, 0 } } });
+
+ Gfx::Path circle;
+ circle.move_to({ 10, 0 });
+ circle.arc_to({ -10, 0 }, 10, false, true);
+ circle.arc_to({ 10, 0 }, 10, false, true);
+ auto vertices = circle.vertices();
+ EXPECT(vertices.size() > 40);
+ for (auto const& vertex : vertices) {
+ EXPECT_APPROXIMATE_WITH_ERROR(vertex.point.distance_from({ 0, 0 }), 10.f, 0.001f);
+ EXPECT_APPROXIMATE_WITH_ERROR(vertex.direction.length(), 1.f, 0.001f);
+ EXPECT_APPROXIMATE_WITH_ERROR(vertex.direction.dot({ vertex.point.x(), vertex.point.y() }), 0.f, 0.01f);
+ }
+ for (size_t i = 1; i < vertices.size(); ++i) {
+ auto midpoint = (vertices[i - 1].point + vertices[i].point) / 2;
+ EXPECT(midpoint.distance_from({ 0, 0 }) > 10.f - 0.5f / 16);
+ }
+ EXPECT_APPROXIMATE(vertices.first().point.x(), 10.f);
+ EXPECT_APPROXIMATE(vertices.last().point.x(), 10.f);
+ EXPECT_APPROXIMATE_WITH_ERROR(vertices.last().distance, 20 * AK::Pi<float>, 0.05f);
+}
+
+TEST_CASE(vertices_of_a_path_without_length)
+{
+ Gfx::Path path;
+ path.move_to({ 10, 20 });
+ expect_vertices(path, { { { 10, 20 }, 0, {} } });
+
+ Gfx::Path zero_length_line;
+ zero_length_line.move_to({ 10, 20 });
+ zero_length_line.line_to({ 10, 20 });
+ expect_vertices(zero_length_line, { { { 10, 20 }, 0, {} } });
+
+ expect_vertices(Gfx::Path {}, {});
+}