Path.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Function.h>
  27. #include <AK/HashTable.h>
  28. #include <AK/QuickSort.h>
  29. #include <AK/StringBuilder.h>
  30. #include <LibGfx/Painter.h>
  31. #include <LibGfx/Path.h>
  32. #include <math.h>
  33. namespace Gfx {
  34. void Path::elliptical_arc_to(const FloatPoint& point, const FloatPoint& radii, double x_axis_rotation, bool large_arc, bool sweep)
  35. {
  36. auto next_point = point;
  37. double rx = radii.x();
  38. double ry = radii.y();
  39. double x_axis_rotation_c = cos(x_axis_rotation);
  40. double x_axis_rotation_s = sin(x_axis_rotation);
  41. // Find the last point
  42. FloatPoint last_point { 0, 0 };
  43. if (!m_segments.is_empty())
  44. last_point = m_segments.last().point();
  45. // Step 1 of out-of-range radii correction
  46. if (rx == 0.0 || ry == 0.0) {
  47. append_segment<LineSegment>(next_point);
  48. return;
  49. }
  50. // Step 2 of out-of-range radii correction
  51. if (rx < 0)
  52. rx *= -1.0;
  53. if (ry < 0)
  54. ry *= -1.0;
  55. // POSSIBLY HACK: Handle the case where both points are the same.
  56. auto same_endpoints = next_point == last_point;
  57. if (same_endpoints) {
  58. if (!large_arc) {
  59. // Nothing is going to be drawn anyway.
  60. return;
  61. }
  62. // Move the endpoint by a small amount to avoid division by zero.
  63. next_point.move_by(0.01f, 0.01f);
  64. }
  65. // Find (cx, cy), theta_1, theta_delta
  66. // Step 1: Compute (x1', y1')
  67. auto x_avg = static_cast<double>(last_point.x() - next_point.x()) / 2.0;
  68. auto y_avg = static_cast<double>(last_point.y() - next_point.y()) / 2.0;
  69. auto x1p = x_axis_rotation_c * x_avg + x_axis_rotation_s * y_avg;
  70. auto y1p = -x_axis_rotation_s * x_avg + x_axis_rotation_c * y_avg;
  71. // Step 2: Compute (cx', cy')
  72. double x1p_sq = pow(x1p, 2.0);
  73. double y1p_sq = pow(y1p, 2.0);
  74. double rx_sq = pow(rx, 2.0);
  75. double ry_sq = pow(ry, 2.0);
  76. // Step 3 of out-of-range radii correction
  77. double lambda = x1p_sq / rx_sq + y1p_sq / ry_sq;
  78. double multiplier;
  79. if (lambda > 1.0) {
  80. auto lambda_sqrt = sqrt(lambda);
  81. rx *= lambda_sqrt;
  82. ry *= lambda_sqrt;
  83. multiplier = 0.0;
  84. } else {
  85. double numerator = rx_sq * ry_sq - rx_sq * y1p_sq - ry_sq * x1p_sq;
  86. double denominator = rx_sq * y1p_sq + ry_sq * x1p_sq;
  87. multiplier = sqrt(numerator / denominator);
  88. }
  89. if (large_arc == sweep)
  90. multiplier *= -1.0;
  91. double cxp = multiplier * rx * y1p / ry;
  92. double cyp = multiplier * -ry * x1p / rx;
  93. // Step 3: Compute (cx, cy) from (cx', cy')
  94. x_avg = (last_point.x() + next_point.x()) / 2.0f;
  95. y_avg = (last_point.y() + next_point.y()) / 2.0f;
  96. double cx = x_axis_rotation_c * cxp - x_axis_rotation_s * cyp + x_avg;
  97. double cy = x_axis_rotation_s * cxp + x_axis_rotation_c * cyp + y_avg;
  98. double theta_1 = atan2((y1p - cyp) / ry, (x1p - cxp) / rx);
  99. double theta_2 = atan2((-y1p - cyp) / ry, (-x1p - cxp) / rx);
  100. auto theta_delta = theta_2 - theta_1;
  101. if (!sweep && theta_delta > 0.0) {
  102. theta_delta -= 2 * M_PI;
  103. } else if (sweep && theta_delta < 0) {
  104. theta_delta += 2 * M_PI;
  105. }
  106. elliptical_arc_to(
  107. next_point,
  108. { cx, cy },
  109. { rx, ry },
  110. x_axis_rotation,
  111. theta_1,
  112. theta_delta);
  113. }
  114. void Path::close()
  115. {
  116. if (m_segments.size() <= 1)
  117. return;
  118. invalidate_split_lines();
  119. auto& last_point = m_segments.last().point();
  120. for (ssize_t i = m_segments.size() - 1; i >= 0; --i) {
  121. auto& segment = m_segments[i];
  122. if (segment.type() == Segment::Type::MoveTo) {
  123. if (last_point == segment.point())
  124. return;
  125. append_segment<LineSegment>(segment.point());
  126. return;
  127. }
  128. }
  129. }
  130. void Path::close_all_subpaths()
  131. {
  132. if (m_segments.size() <= 1)
  133. return;
  134. invalidate_split_lines();
  135. Optional<FloatPoint> cursor, start_of_subpath;
  136. bool is_first_point_in_subpath { false };
  137. for (auto& segment : m_segments) {
  138. switch (segment.type()) {
  139. case Segment::Type::MoveTo: {
  140. if (cursor.has_value() && !is_first_point_in_subpath) {
  141. // This is a move from a subpath to another
  142. // connect the two ends of this subpath before
  143. // moving on to the next one
  144. VERIFY(start_of_subpath.has_value());
  145. append_segment<MoveSegment>(cursor.value());
  146. append_segment<LineSegment>(start_of_subpath.value());
  147. }
  148. is_first_point_in_subpath = true;
  149. cursor = segment.point();
  150. break;
  151. }
  152. case Segment::Type::LineTo:
  153. case Segment::Type::QuadraticBezierCurveTo:
  154. case Segment::Type::EllipticalArcTo:
  155. if (is_first_point_in_subpath) {
  156. start_of_subpath = cursor;
  157. is_first_point_in_subpath = false;
  158. }
  159. cursor = segment.point();
  160. break;
  161. case Segment::Type::Invalid:
  162. VERIFY_NOT_REACHED();
  163. break;
  164. }
  165. }
  166. }
  167. String Path::to_string() const
  168. {
  169. StringBuilder builder;
  170. builder.append("Path { ");
  171. for (auto& segment : m_segments) {
  172. switch (segment.type()) {
  173. case Segment::Type::MoveTo:
  174. builder.append("MoveTo");
  175. break;
  176. case Segment::Type::LineTo:
  177. builder.append("LineTo");
  178. break;
  179. case Segment::Type::QuadraticBezierCurveTo:
  180. builder.append("QuadraticBezierCurveTo");
  181. break;
  182. case Segment::Type::EllipticalArcTo:
  183. builder.append("EllipticalArcTo");
  184. break;
  185. case Segment::Type::Invalid:
  186. builder.append("Invalid");
  187. break;
  188. }
  189. builder.appendf("(%s", segment.point().to_string().characters());
  190. switch (segment.type()) {
  191. case Segment::Type::QuadraticBezierCurveTo:
  192. builder.append(", ");
  193. builder.append(static_cast<const QuadraticBezierCurveSegment&>(segment).through().to_string());
  194. break;
  195. case Segment::Type::EllipticalArcTo: {
  196. auto& arc = static_cast<const EllipticalArcSegment&>(segment);
  197. builder.appendff(", {}, {}, {}, {}, {}",
  198. arc.radii().to_string().characters(),
  199. arc.center().to_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(") ");
  209. }
  210. builder.append("}");
  211. return builder.to_string();
  212. }
  213. void Path::segmentize_path()
  214. {
  215. Vector<SplitLineSegment> segments;
  216. float min_x = 0;
  217. float min_y = 0;
  218. float max_x = 0;
  219. float max_y = 0;
  220. auto add_point_to_bbox = [&](const Gfx::FloatPoint& point) {
  221. float x = point.x();
  222. float y = point.y();
  223. min_x = min(min_x, x);
  224. min_y = min(min_y, y);
  225. max_x = max(max_x, x);
  226. max_y = max(max_y, y);
  227. };
  228. auto add_line = [&](const auto& p0, const auto& p1) {
  229. float ymax = p0.y(), ymin = p1.y(), x_of_ymin = p1.x(), x_of_ymax = p0.x();
  230. auto slope = p0.x() == p1.x() ? 0 : ((float)(p0.y() - p1.y())) / ((float)(p0.x() - p1.x()));
  231. if (p0.y() < p1.y()) {
  232. swap(ymin, ymax);
  233. swap(x_of_ymin, x_of_ymax);
  234. }
  235. segments.append({ FloatPoint(p0.x(), p0.y()),
  236. FloatPoint(p1.x(), p1.y()),
  237. slope == 0 ? 0 : 1 / slope,
  238. x_of_ymin,
  239. ymax, ymin, x_of_ymax });
  240. add_point_to_bbox(p1);
  241. };
  242. FloatPoint cursor { 0, 0 };
  243. bool first = true;
  244. for (auto& segment : m_segments) {
  245. switch (segment.type()) {
  246. case Segment::Type::MoveTo:
  247. if (first) {
  248. min_x = segment.point().x();
  249. min_y = segment.point().y();
  250. max_x = segment.point().x();
  251. max_y = segment.point().y();
  252. } else {
  253. add_point_to_bbox(segment.point());
  254. }
  255. cursor = segment.point();
  256. break;
  257. case Segment::Type::LineTo: {
  258. add_line(cursor, segment.point());
  259. cursor = segment.point();
  260. break;
  261. }
  262. case Segment::Type::QuadraticBezierCurveTo: {
  263. auto& control = static_cast<QuadraticBezierCurveSegment&>(segment).through();
  264. Painter::for_each_line_segment_on_bezier_curve(control, 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. }