Path.cpp 17 KB

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