DeprecatedPath.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Math.h>
  7. #include <AK/StringBuilder.h>
  8. #include <LibGfx/BoundingBox.h>
  9. #include <LibGfx/DeprecatedPainter.h>
  10. #include <LibGfx/DeprecatedPath.h>
  11. namespace Gfx {
  12. void DeprecatedPath::approximate_elliptical_arc_with_cubic_beziers(FloatPoint center, FloatSize radii, float x_axis_rotation, float theta, float theta_delta)
  13. {
  14. float sin_x_rotation;
  15. float cos_x_rotation;
  16. AK::sincos(x_axis_rotation, sin_x_rotation, cos_x_rotation);
  17. auto arc_point_and_derivative = [&](float t, FloatPoint& point, FloatPoint& derivative) {
  18. float sin_angle;
  19. float cos_angle;
  20. AK::sincos(t, sin_angle, cos_angle);
  21. point = FloatPoint {
  22. center.x()
  23. + radii.width() * cos_x_rotation * cos_angle
  24. - radii.height() * sin_x_rotation * sin_angle,
  25. center.y()
  26. + radii.width() * sin_x_rotation * cos_angle
  27. + radii.height() * cos_x_rotation * sin_angle,
  28. };
  29. derivative = FloatPoint {
  30. -radii.width() * cos_x_rotation * sin_angle
  31. - radii.height() * sin_x_rotation * cos_angle,
  32. -radii.width() * sin_x_rotation * sin_angle
  33. + radii.height() * cos_x_rotation * cos_angle,
  34. };
  35. };
  36. auto approximate_arc_between = [&](float start_angle, float end_angle) {
  37. auto t = AK::tan((end_angle - start_angle) / 2);
  38. auto alpha = AK::sin(end_angle - start_angle) * ((AK::sqrt(4 + 3 * t * t) - 1) / 3);
  39. FloatPoint p1, d1;
  40. FloatPoint p2, d2;
  41. arc_point_and_derivative(start_angle, p1, d1);
  42. arc_point_and_derivative(end_angle, p2, d2);
  43. auto q1 = p1 + d1.scaled(alpha, alpha);
  44. auto q2 = p2 - d2.scaled(alpha, alpha);
  45. cubic_bezier_curve_to(q1, q2, p2);
  46. };
  47. // FIXME: Come up with a more mathematically sound step size (using some error calculation).
  48. auto step = theta_delta;
  49. int step_count = 1;
  50. while (fabs(step) > AK::Pi<float> / 4) {
  51. step /= 2;
  52. step_count *= 2;
  53. }
  54. float prev = theta;
  55. float t = prev + step;
  56. for (int i = 0; i < step_count; i++, prev = t, t += step)
  57. approximate_arc_between(prev, t);
  58. }
  59. void DeprecatedPath::elliptical_arc_to(FloatPoint point, FloatSize radii, float x_axis_rotation, bool large_arc, bool sweep)
  60. {
  61. auto next_point = point;
  62. double rx = radii.width();
  63. double ry = radii.height();
  64. double x_axis_rotation_s;
  65. double x_axis_rotation_c;
  66. AK::sincos(static_cast<double>(x_axis_rotation), x_axis_rotation_s, x_axis_rotation_c);
  67. FloatPoint last_point = this->last_point();
  68. // Step 1 of out-of-range radii correction
  69. if (rx == 0.0 || ry == 0.0) {
  70. append_segment<DeprecatedPathSegment::LineTo>(next_point);
  71. return;
  72. }
  73. // Step 2 of out-of-range radii correction
  74. if (rx < 0)
  75. rx *= -1.0;
  76. if (ry < 0)
  77. ry *= -1.0;
  78. // POSSIBLY HACK: Handle the case where both points are the same.
  79. auto same_endpoints = next_point == last_point;
  80. if (same_endpoints) {
  81. if (!large_arc) {
  82. // Nothing is going to be drawn anyway.
  83. return;
  84. }
  85. // Move the endpoint by a small amount to avoid division by zero.
  86. next_point.translate_by(0.01f, 0.01f);
  87. }
  88. // Find (cx, cy), theta_1, theta_delta
  89. // Step 1: Compute (x1', y1')
  90. auto x_avg = static_cast<double>(last_point.x() - next_point.x()) / 2.0;
  91. auto y_avg = static_cast<double>(last_point.y() - next_point.y()) / 2.0;
  92. auto x1p = x_axis_rotation_c * x_avg + x_axis_rotation_s * y_avg;
  93. auto y1p = -x_axis_rotation_s * x_avg + x_axis_rotation_c * y_avg;
  94. // Step 2: Compute (cx', cy')
  95. double x1p_sq = x1p * x1p;
  96. double y1p_sq = y1p * y1p;
  97. double rx_sq = rx * rx;
  98. double ry_sq = ry * ry;
  99. // Step 3 of out-of-range radii correction
  100. double lambda = x1p_sq / rx_sq + y1p_sq / ry_sq;
  101. double multiplier;
  102. if (lambda > 1.0) {
  103. auto lambda_sqrt = AK::sqrt(lambda);
  104. rx *= lambda_sqrt;
  105. ry *= lambda_sqrt;
  106. multiplier = 0.0;
  107. } else {
  108. double numerator = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
  109. double denominator = rx_sq * y1p_sq + ry_sq * x1p_sq;
  110. multiplier = AK::sqrt(AK::max(0., numerator) / denominator);
  111. }
  112. if (large_arc == sweep)
  113. multiplier *= -1.0;
  114. double cxp = multiplier * rx * y1p / ry;
  115. double cyp = multiplier * -ry * x1p / rx;
  116. // Step 3: Compute (cx, cy) from (cx', cy')
  117. x_avg = (last_point.x() + next_point.x()) / 2.0f;
  118. y_avg = (last_point.y() + next_point.y()) / 2.0f;
  119. double cx = x_axis_rotation_c * cxp - x_axis_rotation_s * cyp + x_avg;
  120. double cy = x_axis_rotation_s * cxp + x_axis_rotation_c * cyp + y_avg;
  121. double theta_1 = AK::atan2((y1p - cyp) / ry, (x1p - cxp) / rx);
  122. double theta_2 = AK::atan2((-y1p - cyp) / ry, (-x1p - cxp) / rx);
  123. auto theta_delta = theta_2 - theta_1;
  124. if (!sweep && theta_delta > 0.0) {
  125. theta_delta -= 2 * AK::Pi<double>;
  126. } else if (sweep && theta_delta < 0) {
  127. theta_delta += 2 * AK::Pi<double>;
  128. }
  129. approximate_elliptical_arc_with_cubic_beziers(
  130. { cx, cy },
  131. { rx, ry },
  132. x_axis_rotation,
  133. theta_1,
  134. theta_delta);
  135. }
  136. void DeprecatedPath::close()
  137. {
  138. // If there's no `moveto` starting this subpath assume the start is (0, 0).
  139. FloatPoint first_point_in_subpath = { 0, 0 };
  140. for (auto it = end(); it-- != begin();) {
  141. auto segment = *it;
  142. if (segment.command() == DeprecatedPathSegment::MoveTo) {
  143. first_point_in_subpath = segment.point();
  144. break;
  145. }
  146. }
  147. if (first_point_in_subpath != last_point())
  148. line_to(first_point_in_subpath);
  149. }
  150. void DeprecatedPath::close_all_subpaths()
  151. {
  152. auto it = begin();
  153. // Note: Get the end outside the loop as closing subpaths will move the end.
  154. auto end = this->end();
  155. while (it < end) {
  156. // If there's no `moveto` starting this subpath assume the start is (0, 0).
  157. FloatPoint first_point_in_subpath = { 0, 0 };
  158. auto segment = *it;
  159. if (segment.command() == DeprecatedPathSegment::MoveTo) {
  160. first_point_in_subpath = segment.point();
  161. ++it;
  162. }
  163. // Find the end of the current subpath.
  164. FloatPoint cursor = first_point_in_subpath;
  165. while (it < end) {
  166. auto segment = *it;
  167. if (segment.command() == DeprecatedPathSegment::MoveTo)
  168. break;
  169. cursor = segment.point();
  170. ++it;
  171. }
  172. // Close the subpath.
  173. if (first_point_in_subpath != cursor) {
  174. move_to(cursor);
  175. line_to(first_point_in_subpath);
  176. }
  177. }
  178. }
  179. ByteString DeprecatedPath::to_byte_string() const
  180. {
  181. // Dumps this path as an SVG compatible string.
  182. StringBuilder builder;
  183. if (is_empty() || m_commands.first() != DeprecatedPathSegment::MoveTo)
  184. builder.append("M 0,0"sv);
  185. for (auto segment : *this) {
  186. if (!builder.is_empty())
  187. builder.append(' ');
  188. switch (segment.command()) {
  189. case DeprecatedPathSegment::MoveTo:
  190. builder.append('M');
  191. break;
  192. case DeprecatedPathSegment::LineTo:
  193. builder.append('L');
  194. break;
  195. case DeprecatedPathSegment::QuadraticBezierCurveTo:
  196. builder.append('Q');
  197. break;
  198. case DeprecatedPathSegment::CubicBezierCurveTo:
  199. builder.append('C');
  200. break;
  201. }
  202. for (auto point : segment.points())
  203. builder.appendff(" {},{}", point.x(), point.y());
  204. }
  205. return builder.to_byte_string();
  206. }
  207. void DeprecatedPath::segmentize_path()
  208. {
  209. Vector<FloatLine> segments;
  210. FloatBoundingBox bounding_box;
  211. auto add_line = [&](auto const& p0, auto const& p1) {
  212. segments.append({ p0, p1 });
  213. bounding_box.add_point(p1);
  214. };
  215. FloatPoint cursor { 0, 0 };
  216. for (auto segment : *this) {
  217. switch (segment.command()) {
  218. case DeprecatedPathSegment::MoveTo:
  219. bounding_box.add_point(segment.point());
  220. break;
  221. case DeprecatedPathSegment::LineTo: {
  222. add_line(cursor, segment.point());
  223. break;
  224. }
  225. case DeprecatedPathSegment::QuadraticBezierCurveTo: {
  226. DeprecatedPainter::for_each_line_segment_on_bezier_curve(segment.through(), cursor, segment.point(), [&](FloatPoint p0, FloatPoint p1) {
  227. add_line(p0, p1);
  228. });
  229. break;
  230. }
  231. case DeprecatedPathSegment::CubicBezierCurveTo: {
  232. DeprecatedPainter::for_each_line_segment_on_cubic_bezier_curve(segment.through_0(), segment.through_1(), cursor, segment.point(), [&](FloatPoint p0, FloatPoint p1) {
  233. add_line(p0, p1);
  234. });
  235. break;
  236. }
  237. }
  238. cursor = segment.point();
  239. }
  240. m_split_lines = SplitLines { move(segments), bounding_box };
  241. }
  242. DeprecatedPath DeprecatedPath::copy_transformed(Gfx::AffineTransform const& transform) const
  243. {
  244. DeprecatedPath result;
  245. result.m_commands = m_commands;
  246. result.m_points.ensure_capacity(m_points.size());
  247. for (auto point : m_points)
  248. result.m_points.unchecked_append(transform.map(point));
  249. return result;
  250. }
  251. template<typename T>
  252. struct RoundTrip {
  253. RoundTrip(ReadonlySpan<T> span)
  254. : m_span(span)
  255. {
  256. }
  257. size_t size() const
  258. {
  259. return m_span.size() * 2 - 1;
  260. }
  261. T const& operator[](size_t index) const
  262. {
  263. // Follow the path:
  264. if (index < m_span.size())
  265. return m_span[index];
  266. // Then in reverse:
  267. if (index < size())
  268. return m_span[size() - index - 1];
  269. // Then wrap around again:
  270. return m_span[index - size() + 1];
  271. }
  272. private:
  273. ReadonlySpan<T> m_span;
  274. };
  275. DeprecatedPath DeprecatedPath::stroke_to_fill(float thickness) const
  276. {
  277. // Note: This convolves a polygon with the path using the algorithm described
  278. // in https://keithp.com/~keithp/talks/cairo2003.pdf (3.1 Stroking Splines via Convolution)
  279. VERIFY(thickness > 0);
  280. auto lines = split_lines();
  281. if (lines.is_empty())
  282. return DeprecatedPath {};
  283. // Paths can be disconnected, which a pain to deal with, so split it up.
  284. Vector<Vector<FloatPoint>> segments;
  285. segments.append({ lines.first().a() });
  286. for (auto& line : lines) {
  287. if (line.a() == segments.last().last()) {
  288. segments.last().append(line.b());
  289. } else {
  290. segments.append({ line.a(), line.b() });
  291. }
  292. }
  293. constexpr auto flatness = 0.15f;
  294. auto pen_vertex_count = 4;
  295. if (thickness > flatness) {
  296. pen_vertex_count = max(
  297. static_cast<int>(ceilf(AK::Pi<float>
  298. / acosf(1 - (2 * flatness) / thickness))),
  299. pen_vertex_count);
  300. }
  301. if (pen_vertex_count % 2 == 1)
  302. pen_vertex_count += 1;
  303. Vector<FloatPoint, 128> pen_vertices;
  304. pen_vertices.ensure_capacity(pen_vertex_count);
  305. // Generate vertices for the pen (going counterclockwise). The pen does not necessarily need
  306. // to be a circle (or an approximation of one), but other shapes are untested.
  307. float theta = 0;
  308. float theta_delta = (AK::Pi<float> * 2) / pen_vertex_count;
  309. for (int i = 0; i < pen_vertex_count; i++) {
  310. float sin_theta;
  311. float cos_theta;
  312. AK::sincos(theta, sin_theta, cos_theta);
  313. pen_vertices.unchecked_append({ cos_theta * thickness / 2, sin_theta * thickness / 2 });
  314. theta -= theta_delta;
  315. }
  316. auto wrapping_index = [](auto& vertices, auto index) {
  317. return vertices[(index + vertices.size()) % vertices.size()];
  318. };
  319. auto angle_between = [](auto p1, auto p2) {
  320. auto delta = p2 - p1;
  321. return atan2f(delta.y(), delta.x());
  322. };
  323. struct ActiveRange {
  324. float start;
  325. float end;
  326. bool in_range(float angle) const
  327. {
  328. // Note: Since active ranges go counterclockwise start > end unless we wrap around at 180 degrees
  329. return ((angle <= start && angle >= end)
  330. || (start < end && angle <= start)
  331. || (start < end && angle >= end));
  332. }
  333. };
  334. Vector<ActiveRange, 128> active_ranges;
  335. active_ranges.ensure_capacity(pen_vertices.size());
  336. for (auto i = 0; i < pen_vertex_count; i++) {
  337. active_ranges.unchecked_append({ angle_between(wrapping_index(pen_vertices, i - 1), pen_vertices[i]),
  338. angle_between(pen_vertices[i], wrapping_index(pen_vertices, i + 1)) });
  339. }
  340. auto clockwise = [](float current_angle, float target_angle) {
  341. if (target_angle < 0)
  342. target_angle += AK::Pi<float> * 2;
  343. if (current_angle < 0)
  344. current_angle += AK::Pi<float> * 2;
  345. if (target_angle < current_angle)
  346. target_angle += AK::Pi<float> * 2;
  347. return (target_angle - current_angle) <= AK::Pi<float>;
  348. };
  349. DeprecatedPath convolution;
  350. for (auto& segment : segments) {
  351. RoundTrip<FloatPoint> shape { segment };
  352. bool first = true;
  353. auto add_vertex = [&](auto v) {
  354. if (first) {
  355. convolution.move_to(v);
  356. first = false;
  357. } else {
  358. convolution.line_to(v);
  359. }
  360. };
  361. auto shape_idx = 0u;
  362. auto slope = [&] {
  363. return angle_between(shape[shape_idx], shape[shape_idx + 1]);
  364. };
  365. auto start_slope = slope();
  366. // Note: At least one range must be active.
  367. auto active = *active_ranges.find_first_index_if([&](auto& range) {
  368. return range.in_range(start_slope);
  369. });
  370. while (shape_idx < shape.size()) {
  371. add_vertex(shape[shape_idx] + pen_vertices[active]);
  372. auto slope_now = slope();
  373. auto range = active_ranges[active];
  374. if (range.in_range(slope_now)) {
  375. shape_idx++;
  376. } else {
  377. if (clockwise(slope_now, range.end)) {
  378. if (active == static_cast<size_t>(pen_vertex_count - 1))
  379. active = 0;
  380. else
  381. active++;
  382. } else {
  383. if (active == 0)
  384. active = pen_vertex_count - 1;
  385. else
  386. active--;
  387. }
  388. }
  389. }
  390. }
  391. return convolution;
  392. }
  393. }