Path.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Function.h>
  7. #include <AK/HashTable.h>
  8. #include <AK/Math.h>
  9. #include <AK/QuickSort.h>
  10. #include <AK/StringBuilder.h>
  11. #include <LibGfx/Painter.h>
  12. #include <LibGfx/Path.h>
  13. namespace Gfx {
  14. void Path::elliptical_arc_to(FloatPoint point, FloatSize radii, float x_axis_rotation, bool large_arc, bool sweep)
  15. {
  16. auto next_point = point;
  17. double rx = radii.width();
  18. double ry = radii.height();
  19. double x_axis_rotation_s;
  20. double x_axis_rotation_c;
  21. AK::sincos(static_cast<double>(x_axis_rotation), x_axis_rotation_s, x_axis_rotation_c);
  22. // Find the last point
  23. FloatPoint last_point { 0, 0 };
  24. if (!m_segments.is_empty())
  25. last_point = m_segments.last()->point();
  26. // Step 1 of out-of-range radii correction
  27. if (rx == 0.0 || ry == 0.0) {
  28. append_segment<LineSegment>(next_point);
  29. return;
  30. }
  31. // Step 2 of out-of-range radii correction
  32. if (rx < 0)
  33. rx *= -1.0;
  34. if (ry < 0)
  35. ry *= -1.0;
  36. // POSSIBLY HACK: Handle the case where both points are the same.
  37. auto same_endpoints = next_point == last_point;
  38. if (same_endpoints) {
  39. if (!large_arc) {
  40. // Nothing is going to be drawn anyway.
  41. return;
  42. }
  43. // Move the endpoint by a small amount to avoid division by zero.
  44. next_point.translate_by(0.01f, 0.01f);
  45. }
  46. // Find (cx, cy), theta_1, theta_delta
  47. // Step 1: Compute (x1', y1')
  48. auto x_avg = static_cast<double>(last_point.x() - next_point.x()) / 2.0;
  49. auto y_avg = static_cast<double>(last_point.y() - next_point.y()) / 2.0;
  50. auto x1p = x_axis_rotation_c * x_avg + x_axis_rotation_s * y_avg;
  51. auto y1p = -x_axis_rotation_s * x_avg + x_axis_rotation_c * y_avg;
  52. // Step 2: Compute (cx', cy')
  53. double x1p_sq = x1p * x1p;
  54. double y1p_sq = y1p * y1p;
  55. double rx_sq = rx * rx;
  56. double ry_sq = ry * ry;
  57. // Step 3 of out-of-range radii correction
  58. double lambda = x1p_sq / rx_sq + y1p_sq / ry_sq;
  59. double multiplier;
  60. if (lambda > 1.0) {
  61. auto lambda_sqrt = AK::sqrt(lambda);
  62. rx *= lambda_sqrt;
  63. ry *= lambda_sqrt;
  64. multiplier = 0.0;
  65. } else {
  66. double numerator = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
  67. double denominator = rx_sq * y1p_sq + ry_sq * x1p_sq;
  68. multiplier = AK::sqrt(numerator / denominator);
  69. }
  70. if (large_arc == sweep)
  71. multiplier *= -1.0;
  72. double cxp = multiplier * rx * y1p / ry;
  73. double cyp = multiplier * -ry * x1p / rx;
  74. // Step 3: Compute (cx, cy) from (cx', cy')
  75. x_avg = (last_point.x() + next_point.x()) / 2.0f;
  76. y_avg = (last_point.y() + next_point.y()) / 2.0f;
  77. double cx = x_axis_rotation_c * cxp - x_axis_rotation_s * cyp + x_avg;
  78. double cy = x_axis_rotation_s * cxp + x_axis_rotation_c * cyp + y_avg;
  79. double theta_1 = AK::atan2((y1p - cyp) / ry, (x1p - cxp) / rx);
  80. double theta_2 = AK::atan2((-y1p - cyp) / ry, (-x1p - cxp) / rx);
  81. auto theta_delta = theta_2 - theta_1;
  82. if (!sweep && theta_delta > 0.0) {
  83. theta_delta -= 2 * AK::Pi<double>;
  84. } else if (sweep && theta_delta < 0) {
  85. theta_delta += 2 * AK::Pi<double>;
  86. }
  87. elliptical_arc_to(
  88. next_point,
  89. { cx, cy },
  90. { rx, ry },
  91. x_axis_rotation,
  92. theta_1,
  93. theta_delta,
  94. large_arc,
  95. sweep);
  96. }
  97. void Path::close()
  98. {
  99. if (m_segments.size() <= 1)
  100. return;
  101. auto last_point = m_segments.last()->point();
  102. for (ssize_t i = m_segments.size() - 1; i >= 0; --i) {
  103. auto& segment = m_segments[i];
  104. if (segment->type() == Segment::Type::MoveTo) {
  105. if (last_point == segment->point())
  106. return;
  107. append_segment<LineSegment>(segment->point());
  108. invalidate_split_lines();
  109. return;
  110. }
  111. }
  112. }
  113. void Path::close_all_subpaths()
  114. {
  115. if (m_segments.size() <= 1)
  116. return;
  117. invalidate_split_lines();
  118. Optional<FloatPoint> cursor, start_of_subpath;
  119. bool is_first_point_in_subpath { false };
  120. auto close_previous_subpath = [&] {
  121. if (cursor.has_value() && !is_first_point_in_subpath) {
  122. // This is a move from a subpath to another
  123. // connect the two ends of this subpath before
  124. // moving on to the next one
  125. VERIFY(start_of_subpath.has_value());
  126. append_segment<MoveSegment>(cursor.value());
  127. append_segment<LineSegment>(start_of_subpath.value());
  128. }
  129. };
  130. auto segment_count = m_segments.size();
  131. for (size_t i = 0; i < segment_count; i++) {
  132. // Note: We need to use m_segments[i] as append_segment() may invalidate any references.
  133. switch (m_segments[i]->type()) {
  134. case Segment::Type::MoveTo: {
  135. close_previous_subpath();
  136. is_first_point_in_subpath = true;
  137. cursor = m_segments[i]->point();
  138. break;
  139. }
  140. case Segment::Type::LineTo:
  141. case Segment::Type::QuadraticBezierCurveTo:
  142. case Segment::Type::CubicBezierCurveTo:
  143. case Segment::Type::EllipticalArcTo:
  144. if (is_first_point_in_subpath) {
  145. start_of_subpath = cursor;
  146. is_first_point_in_subpath = false;
  147. }
  148. cursor = m_segments[i]->point();
  149. break;
  150. case Segment::Type::Invalid:
  151. VERIFY_NOT_REACHED();
  152. break;
  153. }
  154. }
  155. if (m_segments.last()->type() != Segment::Type::MoveTo)
  156. close_previous_subpath();
  157. }
  158. DeprecatedString Path::to_deprecated_string() const
  159. {
  160. StringBuilder builder;
  161. builder.append("Path { "sv);
  162. for (auto& segment : m_segments) {
  163. switch (segment->type()) {
  164. case Segment::Type::MoveTo:
  165. builder.append("MoveTo"sv);
  166. break;
  167. case Segment::Type::LineTo:
  168. builder.append("LineTo"sv);
  169. break;
  170. case Segment::Type::QuadraticBezierCurveTo:
  171. builder.append("QuadraticBezierCurveTo"sv);
  172. break;
  173. case Segment::Type::CubicBezierCurveTo:
  174. builder.append("CubicBezierCurveTo"sv);
  175. break;
  176. case Segment::Type::EllipticalArcTo:
  177. builder.append("EllipticalArcTo"sv);
  178. break;
  179. case Segment::Type::Invalid:
  180. builder.append("Invalid"sv);
  181. break;
  182. }
  183. builder.appendff("({}", segment->point());
  184. switch (segment->type()) {
  185. case Segment::Type::QuadraticBezierCurveTo:
  186. builder.append(", "sv);
  187. builder.append(static_cast<QuadraticBezierCurveSegment const&>(*segment).through().to_deprecated_string());
  188. break;
  189. case Segment::Type::CubicBezierCurveTo:
  190. builder.append(", "sv);
  191. builder.append(static_cast<CubicBezierCurveSegment const&>(*segment).through_0().to_deprecated_string());
  192. builder.append(", "sv);
  193. builder.append(static_cast<CubicBezierCurveSegment const&>(*segment).through_1().to_deprecated_string());
  194. break;
  195. case Segment::Type::EllipticalArcTo: {
  196. auto& arc = static_cast<EllipticalArcSegment const&>(*segment);
  197. builder.appendff(", {}, {}, {}, {}, {}",
  198. arc.radii().to_deprecated_string().characters(),
  199. arc.center().to_deprecated_string().characters(),
  200. arc.x_axis_rotation(),
  201. arc.theta_1(),
  202. arc.theta_delta());
  203. break;
  204. }
  205. default:
  206. break;
  207. }
  208. builder.append(") "sv);
  209. }
  210. builder.append('}');
  211. return builder.to_deprecated_string();
  212. }
  213. void Path::segmentize_path()
  214. {
  215. Vector<FloatLine> segments;
  216. float min_x = 0;
  217. float min_y = 0;
  218. float max_x = 0;
  219. float max_y = 0;
  220. bool first = true;
  221. auto add_point_to_bbox = [&](Gfx::FloatPoint point) {
  222. float x = point.x();
  223. float y = point.y();
  224. if (first) {
  225. min_x = max_x = x;
  226. min_y = max_y = y;
  227. first = false;
  228. } else {
  229. min_x = min(min_x, x);
  230. min_y = min(min_y, y);
  231. max_x = max(max_x, x);
  232. max_y = max(max_y, y);
  233. }
  234. };
  235. auto add_line = [&](auto const& p0, auto const& p1) {
  236. segments.append({ p0, p1 });
  237. add_point_to_bbox(p1);
  238. };
  239. FloatPoint cursor { 0, 0 };
  240. for (auto& segment : m_segments) {
  241. switch (segment->type()) {
  242. case Segment::Type::MoveTo:
  243. add_point_to_bbox(segment->point());
  244. cursor = segment->point();
  245. break;
  246. case Segment::Type::LineTo: {
  247. add_line(cursor, segment->point());
  248. cursor = segment->point();
  249. break;
  250. }
  251. case Segment::Type::QuadraticBezierCurveTo: {
  252. auto control = static_cast<QuadraticBezierCurveSegment const&>(*segment).through();
  253. Painter::for_each_line_segment_on_bezier_curve(control, cursor, segment->point(), [&](FloatPoint p0, FloatPoint p1) {
  254. add_line(p0, p1);
  255. });
  256. cursor = segment->point();
  257. break;
  258. }
  259. case Segment::Type::CubicBezierCurveTo: {
  260. auto& curve = static_cast<CubicBezierCurveSegment const&>(*segment);
  261. auto control_0 = curve.through_0();
  262. auto control_1 = curve.through_1();
  263. Painter::for_each_line_segment_on_cubic_bezier_curve(control_0, control_1, cursor, segment->point(), [&](FloatPoint p0, FloatPoint p1) {
  264. add_line(p0, p1);
  265. });
  266. cursor = segment->point();
  267. break;
  268. }
  269. case Segment::Type::EllipticalArcTo: {
  270. auto& arc = static_cast<EllipticalArcSegment const&>(*segment);
  271. Painter::for_each_line_segment_on_elliptical_arc(cursor, arc.point(), arc.center(), arc.radii(), arc.x_axis_rotation(), arc.theta_1(), arc.theta_delta(), [&](FloatPoint p0, FloatPoint p1) {
  272. add_line(p0, p1);
  273. });
  274. cursor = segment->point();
  275. break;
  276. }
  277. case Segment::Type::Invalid:
  278. VERIFY_NOT_REACHED();
  279. }
  280. first = false;
  281. }
  282. m_split_lines = move(segments);
  283. m_bounding_box = Gfx::FloatRect { min_x, min_y, max_x - min_x, max_y - min_y };
  284. }
  285. Path Path::copy_transformed(Gfx::AffineTransform const& transform) const
  286. {
  287. Path result;
  288. for (auto const& segment : m_segments) {
  289. switch (segment->type()) {
  290. case Segment::Type::MoveTo:
  291. result.move_to(transform.map(segment->point()));
  292. break;
  293. case Segment::Type::LineTo: {
  294. result.line_to(transform.map(segment->point()));
  295. break;
  296. }
  297. case Segment::Type::QuadraticBezierCurveTo: {
  298. auto const& quadratic_segment = static_cast<QuadraticBezierCurveSegment const&>(*segment);
  299. result.quadratic_bezier_curve_to(transform.map(quadratic_segment.through()), transform.map(segment->point()));
  300. break;
  301. }
  302. case Segment::Type::CubicBezierCurveTo: {
  303. auto const& cubic_segment = static_cast<CubicBezierCurveSegment const&>(*segment);
  304. result.cubic_bezier_curve_to(transform.map(cubic_segment.through_0()), transform.map(cubic_segment.through_1()), transform.map(segment->point()));
  305. break;
  306. }
  307. case Segment::Type::EllipticalArcTo: {
  308. auto const& arc_segment = static_cast<EllipticalArcSegment const&>(*segment);
  309. auto det_negative = transform.determinant() < 0;
  310. result.elliptical_arc_to(
  311. transform.map(segment->point()),
  312. transform.map(arc_segment.center()),
  313. transform.map(arc_segment.radii()),
  314. arc_segment.x_axis_rotation() + transform.rotation(),
  315. det_negative ? AK::Pi<float> * 2 - arc_segment.theta_1() : arc_segment.theta_1(),
  316. det_negative ? -arc_segment.theta_delta() : arc_segment.theta_delta(),
  317. arc_segment.large_arc(),
  318. det_negative ? !arc_segment.sweep() : arc_segment.sweep());
  319. break;
  320. }
  321. case Segment::Type::Invalid:
  322. VERIFY_NOT_REACHED();
  323. }
  324. }
  325. return result;
  326. }
  327. void Path::add_path(Path const& other)
  328. {
  329. m_segments.extend(other.m_segments);
  330. invalidate_split_lines();
  331. }
  332. template<typename T>
  333. struct RoundTrip {
  334. RoundTrip(ReadonlySpan<T> span)
  335. : m_span(span)
  336. {
  337. }
  338. size_t size() const
  339. {
  340. return m_span.size() * 2 - 1;
  341. }
  342. T const& operator[](size_t index) const
  343. {
  344. // Follow the path:
  345. if (index < m_span.size())
  346. return m_span[index];
  347. // Then in reverse:
  348. if (index < size())
  349. return m_span[size() - index - 1];
  350. // Then wrap around again:
  351. return m_span[index - size() + 1];
  352. }
  353. private:
  354. ReadonlySpan<T> m_span;
  355. };
  356. Path Path::stroke_to_fill(float thickness) const
  357. {
  358. // Note: This convolves a polygon with the path using the algorithm described
  359. // in https://keithp.com/~keithp/talks/cairo2003.pdf (3.1 Stroking Splines via Convolution)
  360. auto& lines = split_lines();
  361. if (lines.is_empty())
  362. return Path {};
  363. // Paths can be disconnected, which a pain to deal with, so split it up.
  364. Vector<Vector<FloatPoint>> segments;
  365. segments.append({ lines.first().a() });
  366. for (auto& line : lines) {
  367. if (line.a() == segments.last().last()) {
  368. segments.last().append(line.b());
  369. } else {
  370. segments.append({ line.a(), line.b() });
  371. }
  372. }
  373. // Note: This is the same as the tolerance from bezier curve splitting.
  374. constexpr auto flatness = 0.015f;
  375. auto pen_vertex_count = max(
  376. static_cast<int>(ceilf(AK::Pi<float> / acosf(1 - (2 * flatness) / thickness))), 4);
  377. if (pen_vertex_count % 2 == 1)
  378. pen_vertex_count += 1;
  379. Vector<FloatPoint, 128> pen_vertices;
  380. pen_vertices.ensure_capacity(pen_vertex_count);
  381. // Generate vertices for the pen (going counterclockwise). The pen does not necessarily need
  382. // to be a circle (or an approximation of one), but other shapes are untested.
  383. float theta = 0;
  384. float theta_delta = (AK::Pi<float> * 2) / pen_vertex_count;
  385. for (int i = 0; i < pen_vertex_count; i++) {
  386. float sin_theta;
  387. float cos_theta;
  388. AK::sincos(theta, sin_theta, cos_theta);
  389. pen_vertices.unchecked_append({ cos_theta * thickness / 2, sin_theta * thickness / 2 });
  390. theta -= theta_delta;
  391. }
  392. auto wrapping_index = [](auto& vertices, auto index) {
  393. return vertices[(index + vertices.size()) % vertices.size()];
  394. };
  395. auto angle_between = [](auto p1, auto p2) {
  396. auto delta = p2 - p1;
  397. return atan2f(delta.y(), delta.x());
  398. };
  399. struct ActiveRange {
  400. float start;
  401. float end;
  402. bool in_range(float angle) const
  403. {
  404. // Note: Since active ranges go counterclockwise start > end unless we wrap around at 180 degrees
  405. return ((angle <= start && angle >= end)
  406. || (start < end && angle <= start)
  407. || (start < end && angle >= end));
  408. }
  409. };
  410. Vector<ActiveRange, 128> active_ranges;
  411. active_ranges.ensure_capacity(pen_vertices.size());
  412. for (auto i = 0; i < pen_vertex_count; i++) {
  413. active_ranges.unchecked_append({ angle_between(wrapping_index(pen_vertices, i - 1), pen_vertices[i]),
  414. angle_between(pen_vertices[i], wrapping_index(pen_vertices, i + 1)) });
  415. }
  416. auto clockwise = [](float current_angle, float target_angle) {
  417. if (target_angle < 0)
  418. target_angle += AK::Pi<float> * 2;
  419. if (current_angle < 0)
  420. current_angle += AK::Pi<float> * 2;
  421. if (target_angle < current_angle)
  422. target_angle += AK::Pi<float> * 2;
  423. return (target_angle - current_angle) <= AK::Pi<float>;
  424. };
  425. Path convolution;
  426. for (auto& segment : segments) {
  427. RoundTrip<FloatPoint> shape { segment };
  428. bool first = true;
  429. auto add_vertex = [&](auto v) {
  430. if (first) {
  431. convolution.move_to(v);
  432. first = false;
  433. } else {
  434. convolution.line_to(v);
  435. }
  436. };
  437. auto shape_idx = 0u;
  438. auto slope = [&] {
  439. return angle_between(shape[shape_idx], shape[shape_idx + 1]);
  440. };
  441. auto start_slope = slope();
  442. // Note: At least one range must be active.
  443. auto active = *active_ranges.find_first_index_if([&](auto& range) {
  444. return range.in_range(start_slope);
  445. });
  446. while (shape_idx < shape.size()) {
  447. add_vertex(shape[shape_idx] + pen_vertices[active]);
  448. auto slope_now = slope();
  449. auto range = active_ranges[active];
  450. if (range.in_range(slope_now)) {
  451. shape_idx++;
  452. } else {
  453. if (clockwise(slope_now, range.end)) {
  454. if (active == static_cast<size_t>(pen_vertex_count - 1))
  455. active = 0;
  456. else
  457. active++;
  458. } else {
  459. if (active == 0)
  460. active = pen_vertex_count - 1;
  461. else
  462. active--;
  463. }
  464. }
  465. }
  466. }
  467. return convolution;
  468. }
  469. }