Path.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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(const FloatPoint& point, const FloatPoint& radii, double x_axis_rotation, bool large_arc, bool sweep)
  15. {
  16. auto next_point = point;
  17. double rx = radii.x();
  18. double ry = radii.y();
  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. }
  94. void Path::close()
  95. {
  96. if (m_segments.size() <= 1)
  97. return;
  98. auto& last_point = m_segments.last().point();
  99. for (ssize_t i = m_segments.size() - 1; i >= 0; --i) {
  100. auto& segment = m_segments[i];
  101. if (segment.type() == Segment::Type::MoveTo) {
  102. if (last_point == segment.point())
  103. return;
  104. append_segment<LineSegment>(segment.point());
  105. invalidate_split_lines();
  106. return;
  107. }
  108. }
  109. }
  110. void Path::close_all_subpaths()
  111. {
  112. if (m_segments.size() <= 1)
  113. return;
  114. invalidate_split_lines();
  115. Optional<FloatPoint> cursor, start_of_subpath;
  116. bool is_first_point_in_subpath { false };
  117. for (auto& segment : m_segments) {
  118. switch (segment.type()) {
  119. case Segment::Type::MoveTo: {
  120. if (cursor.has_value() && !is_first_point_in_subpath) {
  121. // This is a move from a subpath to another
  122. // connect the two ends of this subpath before
  123. // moving on to the next one
  124. VERIFY(start_of_subpath.has_value());
  125. append_segment<MoveSegment>(cursor.value());
  126. append_segment<LineSegment>(start_of_subpath.value());
  127. }
  128. is_first_point_in_subpath = true;
  129. cursor = segment.point();
  130. break;
  131. }
  132. case Segment::Type::LineTo:
  133. case Segment::Type::QuadraticBezierCurveTo:
  134. case Segment::Type::CubicBezierCurveTo:
  135. case Segment::Type::EllipticalArcTo:
  136. if (is_first_point_in_subpath) {
  137. start_of_subpath = cursor;
  138. is_first_point_in_subpath = false;
  139. }
  140. cursor = segment.point();
  141. break;
  142. case Segment::Type::Invalid:
  143. VERIFY_NOT_REACHED();
  144. break;
  145. }
  146. }
  147. }
  148. String Path::to_string() const
  149. {
  150. StringBuilder builder;
  151. builder.append("Path { ");
  152. for (auto& segment : m_segments) {
  153. switch (segment.type()) {
  154. case Segment::Type::MoveTo:
  155. builder.append("MoveTo");
  156. break;
  157. case Segment::Type::LineTo:
  158. builder.append("LineTo");
  159. break;
  160. case Segment::Type::QuadraticBezierCurveTo:
  161. builder.append("QuadraticBezierCurveTo");
  162. break;
  163. case Segment::Type::CubicBezierCurveTo:
  164. builder.append("CubicBezierCurveTo");
  165. break;
  166. case Segment::Type::EllipticalArcTo:
  167. builder.append("EllipticalArcTo");
  168. break;
  169. case Segment::Type::Invalid:
  170. builder.append("Invalid");
  171. break;
  172. }
  173. builder.appendff("({}", segment.point());
  174. switch (segment.type()) {
  175. case Segment::Type::QuadraticBezierCurveTo:
  176. builder.append(", ");
  177. builder.append(static_cast<const QuadraticBezierCurveSegment&>(segment).through().to_string());
  178. break;
  179. case Segment::Type::CubicBezierCurveTo:
  180. builder.append(", ");
  181. builder.append(static_cast<const CubicBezierCurveSegment&>(segment).through_0().to_string());
  182. builder.append(", ");
  183. builder.append(static_cast<const CubicBezierCurveSegment&>(segment).through_1().to_string());
  184. break;
  185. case Segment::Type::EllipticalArcTo: {
  186. auto& arc = static_cast<const EllipticalArcSegment&>(segment);
  187. builder.appendff(", {}, {}, {}, {}, {}",
  188. arc.radii().to_string().characters(),
  189. arc.center().to_string().characters(),
  190. arc.x_axis_rotation(),
  191. arc.theta_1(),
  192. arc.theta_delta());
  193. break;
  194. }
  195. default:
  196. break;
  197. }
  198. builder.append(") ");
  199. }
  200. builder.append("}");
  201. return builder.to_string();
  202. }
  203. void Path::segmentize_path()
  204. {
  205. Vector<SplitLineSegment> segments;
  206. float min_x = 0;
  207. float min_y = 0;
  208. float max_x = 0;
  209. float max_y = 0;
  210. auto add_point_to_bbox = [&](const Gfx::FloatPoint& point) {
  211. float x = point.x();
  212. float y = point.y();
  213. min_x = min(min_x, x);
  214. min_y = min(min_y, y);
  215. max_x = max(max_x, x);
  216. max_y = max(max_y, y);
  217. };
  218. auto add_line = [&](const auto& p0, const auto& p1) {
  219. float ymax = p0.y(), ymin = p1.y(), x_of_ymin = p1.x(), x_of_ymax = p0.x();
  220. auto slope = p0.x() == p1.x() ? 0 : ((float)(p0.y() - p1.y())) / ((float)(p0.x() - p1.x()));
  221. if (p0.y() < p1.y()) {
  222. swap(ymin, ymax);
  223. swap(x_of_ymin, x_of_ymax);
  224. }
  225. segments.append({ FloatPoint(p0.x(), p0.y()),
  226. FloatPoint(p1.x(), p1.y()),
  227. slope == 0 ? 0 : 1 / slope,
  228. x_of_ymin,
  229. ymax, ymin, x_of_ymax });
  230. add_point_to_bbox(p1);
  231. };
  232. FloatPoint cursor { 0, 0 };
  233. bool first = true;
  234. for (auto& segment : m_segments) {
  235. switch (segment.type()) {
  236. case Segment::Type::MoveTo:
  237. if (first) {
  238. min_x = segment.point().x();
  239. min_y = segment.point().y();
  240. max_x = segment.point().x();
  241. max_y = segment.point().y();
  242. } else {
  243. add_point_to_bbox(segment.point());
  244. }
  245. cursor = segment.point();
  246. break;
  247. case Segment::Type::LineTo: {
  248. add_line(cursor, segment.point());
  249. cursor = segment.point();
  250. break;
  251. }
  252. case Segment::Type::QuadraticBezierCurveTo: {
  253. auto& control = static_cast<QuadraticBezierCurveSegment&>(segment).through();
  254. Painter::for_each_line_segment_on_bezier_curve(control, cursor, segment.point(), [&](const FloatPoint& p0, const FloatPoint& p1) {
  255. add_line(p0, p1);
  256. });
  257. cursor = segment.point();
  258. break;
  259. }
  260. case Segment::Type::CubicBezierCurveTo: {
  261. auto& curve = static_cast<CubicBezierCurveSegment const&>(segment);
  262. auto& control_0 = curve.through_0();
  263. auto& control_1 = curve.through_1();
  264. Painter::for_each_line_segment_on_cubic_bezier_curve(control_0, control_1, cursor, segment.point(), [&](const FloatPoint& p0, const FloatPoint& p1) {
  265. add_line(p0, p1);
  266. });
  267. cursor = segment.point();
  268. break;
  269. }
  270. case Segment::Type::EllipticalArcTo: {
  271. auto& arc = static_cast<EllipticalArcSegment&>(segment);
  272. 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(), [&](const FloatPoint& p0, const FloatPoint& p1) {
  273. add_line(p0, p1);
  274. });
  275. cursor = segment.point();
  276. break;
  277. }
  278. case Segment::Type::Invalid:
  279. VERIFY_NOT_REACHED();
  280. }
  281. first = false;
  282. }
  283. // sort segments by ymax
  284. quick_sort(segments, [](const auto& line0, const auto& line1) {
  285. return line1.maximum_y < line0.maximum_y;
  286. });
  287. m_split_lines = move(segments);
  288. m_bounding_box = Gfx::FloatRect { min_x, min_y, max_x - min_x, max_y - min_y };
  289. }
  290. }