DeprecatedPath.cpp 18 KB

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