Path.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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, double 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_c = AK::cos(x_axis_rotation);
  20. double x_axis_rotation_s = AK::sin(x_axis_rotation);
  21. // Find the last point
  22. FloatPoint last_point { 0, 0 };
  23. if (!m_segments.is_empty())
  24. last_point = m_segments.last()->point();
  25. // Step 1 of out-of-range radii correction
  26. if (rx == 0.0 || ry == 0.0) {
  27. append_segment<LineSegment>(next_point);
  28. return;
  29. }
  30. // Step 2 of out-of-range radii correction
  31. if (rx < 0)
  32. rx *= -1.0;
  33. if (ry < 0)
  34. ry *= -1.0;
  35. // POSSIBLY HACK: Handle the case where both points are the same.
  36. auto same_endpoints = next_point == last_point;
  37. if (same_endpoints) {
  38. if (!large_arc) {
  39. // Nothing is going to be drawn anyway.
  40. return;
  41. }
  42. // Move the endpoint by a small amount to avoid division by zero.
  43. next_point.translate_by(0.01f, 0.01f);
  44. }
  45. // Find (cx, cy), theta_1, theta_delta
  46. // Step 1: Compute (x1', y1')
  47. auto x_avg = static_cast<double>(last_point.x() - next_point.x()) / 2.0;
  48. auto y_avg = static_cast<double>(last_point.y() - next_point.y()) / 2.0;
  49. auto x1p = x_axis_rotation_c * x_avg + x_axis_rotation_s * y_avg;
  50. auto y1p = -x_axis_rotation_s * x_avg + x_axis_rotation_c * y_avg;
  51. // Step 2: Compute (cx', cy')
  52. double x1p_sq = x1p * x1p;
  53. double y1p_sq = y1p * y1p;
  54. double rx_sq = rx * rx;
  55. double ry_sq = ry * ry;
  56. // Step 3 of out-of-range radii correction
  57. double lambda = x1p_sq / rx_sq + y1p_sq / ry_sq;
  58. double multiplier;
  59. if (lambda > 1.0) {
  60. auto lambda_sqrt = AK::sqrt(lambda);
  61. rx *= lambda_sqrt;
  62. ry *= lambda_sqrt;
  63. multiplier = 0.0;
  64. } else {
  65. double numerator = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
  66. double denominator = rx_sq * y1p_sq + ry_sq * x1p_sq;
  67. multiplier = AK::sqrt(numerator / denominator);
  68. }
  69. if (large_arc == sweep)
  70. multiplier *= -1.0;
  71. double cxp = multiplier * rx * y1p / ry;
  72. double cyp = multiplier * -ry * x1p / rx;
  73. // Step 3: Compute (cx, cy) from (cx', cy')
  74. x_avg = (last_point.x() + next_point.x()) / 2.0f;
  75. y_avg = (last_point.y() + next_point.y()) / 2.0f;
  76. double cx = x_axis_rotation_c * cxp - x_axis_rotation_s * cyp + x_avg;
  77. double cy = x_axis_rotation_s * cxp + x_axis_rotation_c * cyp + y_avg;
  78. double theta_1 = AK::atan2((y1p - cyp) / ry, (x1p - cxp) / rx);
  79. double theta_2 = AK::atan2((-y1p - cyp) / ry, (-x1p - cxp) / rx);
  80. auto theta_delta = theta_2 - theta_1;
  81. if (!sweep && theta_delta > 0.0) {
  82. theta_delta -= 2 * M_PI;
  83. } else if (sweep && theta_delta < 0) {
  84. theta_delta += 2 * M_PI;
  85. }
  86. elliptical_arc_to(
  87. next_point,
  88. { cx, cy },
  89. { rx, ry },
  90. x_axis_rotation,
  91. theta_1,
  92. theta_delta,
  93. large_arc,
  94. sweep);
  95. }
  96. void Path::close()
  97. {
  98. if (m_segments.size() <= 1)
  99. return;
  100. auto last_point = m_segments.last()->point();
  101. for (ssize_t i = m_segments.size() - 1; i >= 0; --i) {
  102. auto& segment = m_segments[i];
  103. if (segment->type() == Segment::Type::MoveTo) {
  104. if (last_point == segment->point())
  105. return;
  106. append_segment<LineSegment>(segment->point());
  107. invalidate_split_lines();
  108. return;
  109. }
  110. }
  111. }
  112. void Path::close_all_subpaths()
  113. {
  114. if (m_segments.size() <= 1)
  115. return;
  116. invalidate_split_lines();
  117. Optional<FloatPoint> cursor, start_of_subpath;
  118. bool is_first_point_in_subpath { false };
  119. auto segment_count = m_segments.size();
  120. for (size_t i = 0; i < segment_count; i++) {
  121. // Note: We need to use m_segments[i] as append_segment() may invalidate any references.
  122. switch (m_segments[i]->type()) {
  123. case Segment::Type::MoveTo: {
  124. if (cursor.has_value() && !is_first_point_in_subpath) {
  125. // This is a move from a subpath to another
  126. // connect the two ends of this subpath before
  127. // moving on to the next one
  128. VERIFY(start_of_subpath.has_value());
  129. append_segment<MoveSegment>(cursor.value());
  130. append_segment<LineSegment>(start_of_subpath.value());
  131. }
  132. is_first_point_in_subpath = true;
  133. cursor = m_segments[i]->point();
  134. break;
  135. }
  136. case Segment::Type::LineTo:
  137. case Segment::Type::QuadraticBezierCurveTo:
  138. case Segment::Type::CubicBezierCurveTo:
  139. case Segment::Type::EllipticalArcTo:
  140. if (is_first_point_in_subpath) {
  141. start_of_subpath = cursor;
  142. is_first_point_in_subpath = false;
  143. }
  144. cursor = m_segments[i]->point();
  145. break;
  146. case Segment::Type::Invalid:
  147. VERIFY_NOT_REACHED();
  148. break;
  149. }
  150. }
  151. }
  152. DeprecatedString Path::to_deprecated_string() const
  153. {
  154. StringBuilder builder;
  155. builder.append("Path { "sv);
  156. for (auto& segment : m_segments) {
  157. switch (segment->type()) {
  158. case Segment::Type::MoveTo:
  159. builder.append("MoveTo"sv);
  160. break;
  161. case Segment::Type::LineTo:
  162. builder.append("LineTo"sv);
  163. break;
  164. case Segment::Type::QuadraticBezierCurveTo:
  165. builder.append("QuadraticBezierCurveTo"sv);
  166. break;
  167. case Segment::Type::CubicBezierCurveTo:
  168. builder.append("CubicBezierCurveTo"sv);
  169. break;
  170. case Segment::Type::EllipticalArcTo:
  171. builder.append("EllipticalArcTo"sv);
  172. break;
  173. case Segment::Type::Invalid:
  174. builder.append("Invalid"sv);
  175. break;
  176. }
  177. builder.appendff("({}", segment->point());
  178. switch (segment->type()) {
  179. case Segment::Type::QuadraticBezierCurveTo:
  180. builder.append(", "sv);
  181. builder.append(static_cast<QuadraticBezierCurveSegment const&>(*segment).through().to_deprecated_string());
  182. break;
  183. case Segment::Type::CubicBezierCurveTo:
  184. builder.append(", "sv);
  185. builder.append(static_cast<CubicBezierCurveSegment const&>(*segment).through_0().to_deprecated_string());
  186. builder.append(", "sv);
  187. builder.append(static_cast<CubicBezierCurveSegment const&>(*segment).through_1().to_deprecated_string());
  188. break;
  189. case Segment::Type::EllipticalArcTo: {
  190. auto& arc = static_cast<EllipticalArcSegment const&>(*segment);
  191. builder.appendff(", {}, {}, {}, {}, {}",
  192. arc.radii().to_deprecated_string().characters(),
  193. arc.center().to_deprecated_string().characters(),
  194. arc.x_axis_rotation(),
  195. arc.theta_1(),
  196. arc.theta_delta());
  197. break;
  198. }
  199. default:
  200. break;
  201. }
  202. builder.append(") "sv);
  203. }
  204. builder.append('}');
  205. return builder.to_deprecated_string();
  206. }
  207. void Path::segmentize_path()
  208. {
  209. Vector<SplitLineSegment> segments;
  210. float min_x = 0;
  211. float min_y = 0;
  212. float max_x = 0;
  213. float max_y = 0;
  214. auto add_point_to_bbox = [&](Gfx::FloatPoint point) {
  215. float x = point.x();
  216. float y = point.y();
  217. min_x = min(min_x, x);
  218. min_y = min(min_y, y);
  219. max_x = max(max_x, x);
  220. max_y = max(max_y, y);
  221. };
  222. auto add_line = [&](auto const& p0, auto const& p1) {
  223. float ymax = p0.y(), ymin = p1.y(), x_of_ymin = p1.x(), x_of_ymax = p0.x();
  224. auto slope = p0.x() == p1.x() ? 0 : ((float)(p0.y() - p1.y())) / ((float)(p0.x() - p1.x()));
  225. if (p0.y() < p1.y()) {
  226. swap(ymin, ymax);
  227. swap(x_of_ymin, x_of_ymax);
  228. }
  229. segments.append({ FloatPoint(p0.x(), p0.y()),
  230. FloatPoint(p1.x(), p1.y()),
  231. slope == 0 ? 0 : 1 / slope,
  232. x_of_ymin,
  233. ymax, ymin, x_of_ymax });
  234. add_point_to_bbox(p1);
  235. };
  236. FloatPoint cursor { 0, 0 };
  237. bool first = true;
  238. for (auto& segment : m_segments) {
  239. switch (segment->type()) {
  240. case Segment::Type::MoveTo:
  241. if (first) {
  242. min_x = segment->point().x();
  243. min_y = segment->point().y();
  244. max_x = segment->point().x();
  245. max_y = segment->point().y();
  246. } else {
  247. add_point_to_bbox(segment->point());
  248. }
  249. cursor = segment->point();
  250. break;
  251. case Segment::Type::LineTo: {
  252. add_line(cursor, segment->point());
  253. cursor = segment->point();
  254. break;
  255. }
  256. case Segment::Type::QuadraticBezierCurveTo: {
  257. auto control = static_cast<QuadraticBezierCurveSegment const&>(*segment).through();
  258. Painter::for_each_line_segment_on_bezier_curve(control, cursor, segment->point(), [&](FloatPoint p0, FloatPoint p1) {
  259. add_line(p0, p1);
  260. });
  261. cursor = segment->point();
  262. break;
  263. }
  264. case Segment::Type::CubicBezierCurveTo: {
  265. auto& curve = static_cast<CubicBezierCurveSegment const&>(*segment);
  266. auto control_0 = curve.through_0();
  267. auto control_1 = curve.through_1();
  268. Painter::for_each_line_segment_on_cubic_bezier_curve(control_0, control_1, cursor, segment->point(), [&](FloatPoint p0, FloatPoint p1) {
  269. add_line(p0, p1);
  270. });
  271. cursor = segment->point();
  272. break;
  273. }
  274. case Segment::Type::EllipticalArcTo: {
  275. auto& arc = static_cast<EllipticalArcSegment const&>(*segment);
  276. 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) {
  277. add_line(p0, p1);
  278. });
  279. cursor = segment->point();
  280. break;
  281. }
  282. case Segment::Type::Invalid:
  283. VERIFY_NOT_REACHED();
  284. }
  285. first = false;
  286. }
  287. // sort segments by ymax
  288. quick_sort(segments, [](auto const& line0, auto const& line1) {
  289. return line1.maximum_y < line0.maximum_y;
  290. });
  291. m_split_lines = move(segments);
  292. m_bounding_box = Gfx::FloatRect { min_x, min_y, max_x - min_x, max_y - min_y };
  293. }
  294. Path Path::copy_transformed(Gfx::AffineTransform const& transform) const
  295. {
  296. Path result;
  297. for (auto const& segment : m_segments) {
  298. switch (segment->type()) {
  299. case Segment::Type::MoveTo:
  300. result.move_to(transform.map(segment->point()));
  301. break;
  302. case Segment::Type::LineTo: {
  303. result.line_to(transform.map(segment->point()));
  304. break;
  305. }
  306. case Segment::Type::QuadraticBezierCurveTo: {
  307. auto const& quadratic_segment = static_cast<QuadraticBezierCurveSegment const&>(*segment);
  308. result.quadratic_bezier_curve_to(transform.map(quadratic_segment.through()), transform.map(segment->point()));
  309. break;
  310. }
  311. case Segment::Type::CubicBezierCurveTo: {
  312. auto const& cubic_segment = static_cast<CubicBezierCurveSegment const&>(*segment);
  313. result.cubic_bezier_curve_to(transform.map(cubic_segment.through_0()), transform.map(cubic_segment.through_1()), transform.map(segment->point()));
  314. break;
  315. }
  316. case Segment::Type::EllipticalArcTo: {
  317. auto const& arc_segment = static_cast<EllipticalArcSegment const&>(*segment);
  318. result.elliptical_arc_to(
  319. transform.map(segment->point()),
  320. transform.map(arc_segment.center()),
  321. transform.map(arc_segment.radii()),
  322. arc_segment.x_axis_rotation(),
  323. arc_segment.theta_1(),
  324. arc_segment.theta_delta(),
  325. arc_segment.large_arc(),
  326. arc_segment.sweep());
  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. }