AntiAliasingPainter.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. * Copyright (c) 2022, Ben Maxwell <macdue@dueutil.tech>
  4. * Copyright (c) 2022, Torsten Engelmann <engelTorsten@gmx.de>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #if defined(AK_COMPILER_GCC)
  9. # pragma GCC optimize("O3")
  10. #endif
  11. #include <AK/Function.h>
  12. #include <AK/NumericLimits.h>
  13. #include <LibGfx/AntiAliasingPainter.h>
  14. #include <LibGfx/Line.h>
  15. namespace Gfx {
  16. template<AntiAliasingPainter::FixmeEnableHacksForBetterPathPainting path_hacks>
  17. void AntiAliasingPainter::draw_anti_aliased_line(FloatPoint actual_from, FloatPoint actual_to, Color color, float thickness, Painter::LineStyle style, Color, LineLengthMode line_length_mode)
  18. {
  19. // FIXME: Implement this :P
  20. VERIFY(style == Painter::LineStyle::Solid);
  21. if (color.alpha() == 0)
  22. return;
  23. // FIMXE:
  24. // This is not a proper line drawing algorithm.
  25. // It's hack-ish AA rotated rectangle painting.
  26. // There's probably more optimal ways to achieve this
  27. // (though this still runs faster than the previous AA-line code)
  28. //
  29. // If you, reading this comment, know a better way that:
  30. // 1. Does not overpaint (i.e. painting a line with transparency looks correct)
  31. // 2. Has square end points (i.e. the line is a rectangle)
  32. // 3. Has good anti-aliasing
  33. // 4. Is less hacky than this
  34. //
  35. // Please delete this code and implement it!
  36. int int_thickness = AK::ceil(thickness);
  37. auto mapped_from = m_transform.map(actual_from);
  38. auto mapped_to = m_transform.map(actual_to);
  39. auto distance = mapped_to.distance_from(mapped_from);
  40. auto length = distance + (line_length_mode == LineLengthMode::PointToPoint);
  41. // Axis-aligned lines:
  42. if (mapped_from.y() == mapped_to.y()) {
  43. auto start_point = (mapped_from.x() < mapped_to.x() ? mapped_from : mapped_to).translated(0, -int_thickness / 2);
  44. return fill_rect(Gfx::FloatRect(start_point, { length, thickness }), color);
  45. }
  46. if (mapped_from.x() == mapped_to.x()) {
  47. auto start_point = (mapped_from.y() < mapped_to.y() ? mapped_from : mapped_to).translated(-int_thickness / 2, 0);
  48. return fill_rect(Gfx::FloatRect(start_point, { thickness, length }), color);
  49. }
  50. if constexpr (path_hacks == FixmeEnableHacksForBetterPathPainting::Yes) {
  51. // FIXME: SVG stoke_path() hack:
  52. // When painting stokes SVG asks for many very short lines...
  53. // These look better just painted as dots/AA rectangles
  54. // (Technically this should be rotated or a circle, but that currently gives worse results)
  55. if (distance < 1.0f)
  56. return fill_rect(Gfx::FloatRect::centered_at(mapped_from, { thickness, thickness }), color);
  57. }
  58. // The painting only works for the positive XY quadrant (because that is easier).
  59. // So flip things around until we're there:
  60. bool flip_x = false;
  61. bool flip_y = false;
  62. if (mapped_to.x() < mapped_from.x() && mapped_to.y() < mapped_from.y())
  63. swap(mapped_to, mapped_from);
  64. if ((flip_x = mapped_to.x() < mapped_from.x()))
  65. mapped_to.set_x(2 * mapped_from.x() - mapped_to.x());
  66. if ((flip_y = mapped_to.y() < mapped_from.y()))
  67. mapped_to.set_y(2 * mapped_from.y() - mapped_to.y());
  68. auto delta = mapped_to - mapped_from;
  69. auto line_angle_radians = AK::atan2(delta.y(), delta.x()) - 0.5f * AK::Pi<float>;
  70. float sin_inverse_angle;
  71. float cos_inverse_angle;
  72. AK::sincos(-line_angle_radians, sin_inverse_angle, cos_inverse_angle);
  73. auto inverse_rotate_point = [=](FloatPoint point) {
  74. return Gfx::FloatPoint(
  75. point.x() * cos_inverse_angle - point.y() * sin_inverse_angle,
  76. point.y() * cos_inverse_angle + point.x() * sin_inverse_angle);
  77. };
  78. Gfx::FloatRect line_rect({ -(thickness * 255) / 2.0f, 0 }, Gfx::FloatSize(thickness * 255, length * 255));
  79. auto gradient = delta.y() / delta.x();
  80. // Work out how long we need to scan along the X-axis to reach the other side of the line.
  81. // E.g. for a vertical line this would be `thickness', in general it is this:
  82. int scan_line_length = AK::ceil(AK::sqrt((gradient * gradient + 1) * thickness * thickness) / gradient);
  83. auto x_gradient = 1 / gradient;
  84. int x_step = floorf(x_gradient);
  85. float x_error = 0;
  86. float x_error_per_y = x_gradient - x_step;
  87. auto y_offset = int_thickness + 1;
  88. auto x_offset = int(x_gradient * y_offset);
  89. int const line_start_x = mapped_from.x();
  90. int const line_start_y = mapped_from.y();
  91. int const line_end_x = mapped_to.x();
  92. int const line_end_y = mapped_to.y();
  93. auto set_pixel = [=, this](int x, int y, Gfx::Color color) {
  94. // FIXME: The lines seem slightly off (<= 1px) when flipped.
  95. if (flip_x)
  96. x = 2 * line_start_x - x;
  97. if (flip_y)
  98. y = 2 * line_start_y - y;
  99. m_underlying_painter.set_pixel(x, y, color, true);
  100. };
  101. // Scan a bit extra to avoid issues from the x_error:
  102. int const overscan = max(x_step, 1) * 2 + 1;
  103. int x = line_start_x - x_offset;
  104. int const center_offset = (scan_line_length + 1) / 2;
  105. for (int y = line_start_y - y_offset; y < line_end_y + y_offset; y += 1) {
  106. for (int i = -overscan; i < scan_line_length + overscan; i++) {
  107. int scan_x_pos = x + i - center_offset;
  108. // Avoid scanning over pixels definitely outside the line:
  109. int dx = (line_start_x - int_thickness) - (scan_x_pos + 1);
  110. if (dx > 0) {
  111. i += dx;
  112. continue;
  113. }
  114. if (line_end_x + int_thickness <= scan_x_pos - 1)
  115. break;
  116. auto sample = inverse_rotate_point(Gfx::FloatPoint(scan_x_pos - line_start_x, y - line_start_y));
  117. Gfx::FloatRect sample_px(sample * 255, Gfx::FloatSize(255, 255));
  118. sample_px.intersect(line_rect);
  119. auto alpha = (sample_px.width() * sample_px.height()) / 255.0f;
  120. alpha = (alpha * color.alpha()) / 255;
  121. set_pixel(scan_x_pos, y, color.with_alpha(alpha));
  122. }
  123. x += x_step;
  124. x_error += x_error_per_y;
  125. if (x_error > 1.0f) {
  126. x_error -= 1.0f;
  127. x += 1;
  128. }
  129. }
  130. }
  131. void AntiAliasingPainter::draw_line_for_path(FloatPoint actual_from, FloatPoint actual_to, Color color, float thickness, Painter::LineStyle style, Color alternate_color, LineLengthMode line_length_mode)
  132. {
  133. draw_anti_aliased_line<FixmeEnableHacksForBetterPathPainting::Yes>(actual_from, actual_to, color, thickness, style, alternate_color, line_length_mode);
  134. }
  135. void AntiAliasingPainter::draw_dotted_line(IntPoint point1, IntPoint point2, Color color, int thickness)
  136. {
  137. // AA circles don't really work below a radius of 2px.
  138. if (thickness < 4)
  139. return m_underlying_painter.draw_line(point1, point2, color, thickness, Painter::LineStyle::Dotted);
  140. auto draw_spaced_dots = [&](int start, int end, auto to_point) {
  141. int step = thickness * 2;
  142. if (start > end)
  143. swap(start, end);
  144. int delta = end - start;
  145. int dots = delta / step;
  146. if (dots == 0)
  147. return;
  148. int fudge_per_dot = 0;
  149. int extra_fudge = 0;
  150. if (dots > 3) {
  151. // Fudge the numbers so the last dot is drawn at the `end' point (otherwise you can get lines cuts short).
  152. // You need at least a handful of dots to do this.
  153. int fudge = delta % step;
  154. fudge_per_dot = fudge / dots;
  155. extra_fudge = fudge % dots;
  156. }
  157. for (int dot = start; dot <= end; dot += (step + fudge_per_dot + (extra_fudge > 0))) {
  158. fill_circle(to_point(dot), thickness / 2, color);
  159. --extra_fudge;
  160. }
  161. };
  162. if (point1.y() == point2.y()) {
  163. draw_spaced_dots(point1.x(), point2.x(), [&](int dot_x) {
  164. return IntPoint { dot_x, point1.y() };
  165. });
  166. } else if (point1.x() == point2.x()) {
  167. draw_spaced_dots(point1.y(), point2.y(), [&](int dot_y) {
  168. return IntPoint { point1.x(), dot_y };
  169. });
  170. } else {
  171. TODO();
  172. }
  173. }
  174. void AntiAliasingPainter::draw_line(IntPoint actual_from, IntPoint actual_to, Color color, float thickness, Painter::LineStyle style, Color alternate_color, LineLengthMode line_length_mode)
  175. {
  176. draw_line(actual_from.to_type<float>(), actual_to.to_type<float>(), color, thickness, style, alternate_color, line_length_mode);
  177. }
  178. void AntiAliasingPainter::draw_line(FloatPoint actual_from, FloatPoint actual_to, Color color, float thickness, Painter::LineStyle style, Color alternate_color, LineLengthMode line_length_mode)
  179. {
  180. if (style == Painter::LineStyle::Dotted)
  181. return draw_dotted_line(actual_from.to_rounded<int>(), actual_to.to_rounded<int>(), color, static_cast<int>(round(thickness)));
  182. draw_anti_aliased_line<FixmeEnableHacksForBetterPathPainting::No>(actual_from, actual_to, color, thickness, style, alternate_color, line_length_mode);
  183. }
  184. // FIXME: In the fill_paths() m_transform.translation() throws away any other transforms
  185. // this currently does not matter -- but may in future.
  186. void AntiAliasingPainter::fill_path(Path const& path, Color color, Painter::WindingRule rule)
  187. {
  188. m_underlying_painter.antialiased_fill_path(path, color, rule, m_transform.translation());
  189. }
  190. void AntiAliasingPainter::fill_path(Path const& path, PaintStyle const& paint_style, Painter::WindingRule rule)
  191. {
  192. m_underlying_painter.antialiased_fill_path(path, paint_style, rule, m_transform.translation());
  193. }
  194. void AntiAliasingPainter::stroke_path(Path const& path, Color color, float thickness)
  195. {
  196. FloatPoint cursor;
  197. bool previous_was_line = false;
  198. FloatLine last_line;
  199. Optional<FloatLine> first_line;
  200. for (auto& segment : path.segments()) {
  201. switch (segment->type()) {
  202. case Segment::Type::Invalid:
  203. VERIFY_NOT_REACHED();
  204. case Segment::Type::MoveTo:
  205. cursor = segment->point();
  206. break;
  207. case Segment::Type::LineTo:
  208. draw_line(cursor, segment->point(), color, thickness);
  209. if (thickness > 1) {
  210. if (!first_line.has_value())
  211. first_line = FloatLine(cursor, segment->point());
  212. if (previous_was_line)
  213. stroke_segment_intersection(cursor, segment->point(), last_line, color, thickness);
  214. last_line.set_a(cursor);
  215. last_line.set_b(segment->point());
  216. }
  217. cursor = segment->point();
  218. break;
  219. case Segment::Type::QuadraticBezierCurveTo: {
  220. auto through = static_cast<QuadraticBezierCurveSegment const&>(*segment).through();
  221. draw_quadratic_bezier_curve(through, cursor, segment->point(), color, thickness);
  222. cursor = segment->point();
  223. break;
  224. }
  225. case Segment::Type::CubicBezierCurveTo: {
  226. auto& curve = static_cast<CubicBezierCurveSegment const&>(*segment);
  227. auto through_0 = curve.through_0();
  228. auto through_1 = curve.through_1();
  229. draw_cubic_bezier_curve(through_0, through_1, cursor, segment->point(), color, thickness);
  230. cursor = segment->point();
  231. break;
  232. }
  233. case Segment::Type::EllipticalArcTo:
  234. auto& arc = static_cast<EllipticalArcSegment const&>(*segment);
  235. draw_elliptical_arc(cursor, segment->point(), arc.center(), arc.radii(), arc.x_axis_rotation(), arc.theta_1(), arc.theta_delta(), color, thickness);
  236. cursor = segment->point();
  237. break;
  238. }
  239. previous_was_line = segment->type() == Segment::Type::LineTo;
  240. }
  241. // Check if the figure was started and closed as line at the same position.
  242. if (thickness > 1 && previous_was_line && path.segments().size() >= 2 && path.segments().first()->point() == cursor
  243. && (path.segments().first()->type() == Segment::Type::LineTo
  244. || (path.segments().first()->type() == Segment::Type::MoveTo && path.segments()[1]->type() == Segment::Type::LineTo))) {
  245. stroke_segment_intersection(first_line.value().a(), first_line.value().b(), last_line, color, thickness);
  246. }
  247. }
  248. void AntiAliasingPainter::draw_elliptical_arc(FloatPoint p1, FloatPoint p2, FloatPoint center, FloatSize radii, float x_axis_rotation, float theta_1, float theta_delta, Color color, float thickness, Painter::LineStyle style)
  249. {
  250. Painter::for_each_line_segment_on_elliptical_arc(p1, p2, center, radii, x_axis_rotation, theta_1, theta_delta, [&](FloatPoint fp1, FloatPoint fp2) {
  251. draw_line_for_path(fp1, fp2, color, thickness, style);
  252. });
  253. }
  254. void AntiAliasingPainter::draw_quadratic_bezier_curve(FloatPoint control_point, FloatPoint p1, FloatPoint p2, Color color, float thickness, Painter::LineStyle style)
  255. {
  256. Painter::for_each_line_segment_on_bezier_curve(control_point, p1, p2, [&](FloatPoint fp1, FloatPoint fp2) {
  257. draw_line_for_path(fp1, fp2, color, thickness, style);
  258. });
  259. }
  260. void AntiAliasingPainter::draw_cubic_bezier_curve(FloatPoint control_point_0, FloatPoint control_point_1, FloatPoint p1, FloatPoint p2, Color color, float thickness, Painter::LineStyle style)
  261. {
  262. Painter::for_each_line_segment_on_cubic_bezier_curve(control_point_0, control_point_1, p1, p2, [&](FloatPoint fp1, FloatPoint fp2) {
  263. draw_line_for_path(fp1, fp2, color, thickness, style);
  264. });
  265. }
  266. void AntiAliasingPainter::fill_rect(FloatRect const& float_rect, Color color)
  267. {
  268. // Draw the integer part of the rectangle:
  269. float right_x = float_rect.x() + float_rect.width();
  270. float bottom_y = float_rect.y() + float_rect.height();
  271. int x1 = ceilf(float_rect.x());
  272. int y1 = ceilf(float_rect.y());
  273. int x2 = floorf(right_x);
  274. int y2 = floorf(bottom_y);
  275. auto solid_rect = Gfx::IntRect::from_two_points({ x1, y1 }, { x2, y2 });
  276. m_underlying_painter.fill_rect(solid_rect, color);
  277. if (float_rect == solid_rect)
  278. return;
  279. // Draw the rest:
  280. float left_subpixel = x1 - float_rect.x();
  281. float top_subpixel = y1 - float_rect.y();
  282. float right_subpixel = right_x - x2;
  283. float bottom_subpixel = bottom_y - y2;
  284. float top_left_subpixel = top_subpixel * left_subpixel;
  285. float top_right_subpixel = top_subpixel * right_subpixel;
  286. float bottom_left_subpixel = bottom_subpixel * left_subpixel;
  287. float bottom_right_subpixel = bottom_subpixel * right_subpixel;
  288. auto subpixel = [&](float alpha) {
  289. return color.with_alpha(color.alpha() * alpha);
  290. };
  291. auto set_pixel = [&](int x, int y, float alpha) {
  292. m_underlying_painter.set_pixel(x, y, subpixel(alpha), true);
  293. };
  294. auto line_to_rect = [&](int x1, int y1, int x2, int y2) {
  295. return IntRect::from_two_points({ x1, y1 }, { x2 + 1, y2 + 1 });
  296. };
  297. set_pixel(x1 - 1, y1 - 1, top_left_subpixel);
  298. set_pixel(x2, y1 - 1, top_right_subpixel);
  299. set_pixel(x2, y2, bottom_right_subpixel);
  300. set_pixel(x1 - 1, y2, bottom_left_subpixel);
  301. m_underlying_painter.fill_rect(line_to_rect(x1, y1 - 1, x2 - 1, y1 - 1), subpixel(top_subpixel));
  302. m_underlying_painter.fill_rect(line_to_rect(x1, y2, x2 - 1, y2), subpixel(bottom_subpixel));
  303. m_underlying_painter.fill_rect(line_to_rect(x1 - 1, y1, x1 - 1, y2 - 1), subpixel(left_subpixel));
  304. m_underlying_painter.fill_rect(line_to_rect(x2, y1, x2, y2 - 1), subpixel(right_subpixel));
  305. }
  306. void AntiAliasingPainter::draw_ellipse(IntRect const& a_rect, Color color, int thickness)
  307. {
  308. // FIXME: Come up with an allocation-free version of this!
  309. // Using draw_line() for segments of an ellipse was attempted but gave really poor results :^(
  310. // There probably is a way to adjust the fill of draw_ellipse_part() to do this, but getting it rendering correctly is tricky.
  311. // The outline of the steps required to paint it efficiently is:
  312. // - Paint the outer ellipse without the fill (from the fill() lambda in draw_ellipse_part())
  313. // - Paint the inner ellipse, but in the set_pixel() invert the alpha values
  314. // - Somehow fill in the gap between the two ellipses (the tricky part to get right)
  315. // - Have to avoid overlapping pixels and accidentally painting over some of the edge pixels
  316. auto color_no_alpha = color;
  317. color_no_alpha.set_alpha(255);
  318. auto outline_ellipse_bitmap = ({
  319. auto bitmap = Bitmap::create(BitmapFormat::BGRA8888, a_rect.size());
  320. if (bitmap.is_error())
  321. return warnln("Failed to allocate temporary bitmap for antialiased outline ellipse!");
  322. bitmap.release_value();
  323. });
  324. auto outer_rect = a_rect;
  325. outer_rect.set_location({ 0, 0 });
  326. auto inner_rect = outer_rect.shrunken(thickness * 2, thickness * 2);
  327. Painter painter { outline_ellipse_bitmap };
  328. AntiAliasingPainter aa_painter { painter };
  329. aa_painter.fill_ellipse(outer_rect, color_no_alpha);
  330. aa_painter.fill_ellipse(inner_rect, color_no_alpha, BlendMode::AlphaSubtract);
  331. m_underlying_painter.blit(a_rect.location(), outline_ellipse_bitmap, outline_ellipse_bitmap->rect(), color.alpha() / 255.);
  332. }
  333. void AntiAliasingPainter::fill_circle(IntPoint center, int radius, Color color, BlendMode blend_mode)
  334. {
  335. if (radius <= 0)
  336. return;
  337. draw_ellipse_part(center, radius, radius, color, false, {}, blend_mode);
  338. }
  339. void AntiAliasingPainter::fill_ellipse(IntRect const& a_rect, Color color, BlendMode blend_mode)
  340. {
  341. auto center = a_rect.center();
  342. auto radius_a = a_rect.width() / 2;
  343. auto radius_b = a_rect.height() / 2;
  344. if (radius_a <= 0 || radius_b <= 0)
  345. return;
  346. if (radius_a == radius_b)
  347. return fill_circle(center, radius_a, color, blend_mode);
  348. auto x_paint_range = draw_ellipse_part(center, radius_a, radius_b, color, false, {}, blend_mode);
  349. // FIXME: This paints some extra fill pixels that are clipped
  350. draw_ellipse_part(center, radius_b, radius_a, color, true, x_paint_range, blend_mode);
  351. }
  352. FLATTEN AntiAliasingPainter::Range AntiAliasingPainter::draw_ellipse_part(
  353. IntPoint center, int radius_a, int radius_b, Color color, bool flip_x_and_y, Optional<Range> x_clip, BlendMode blend_mode)
  354. {
  355. /*
  356. Algorithm from: https://cs.uwaterloo.ca/research/tr/1984/CS-84-38.pdf
  357. This method can draw a whole circle with a whole circle in one call using
  358. 8-way symmetry, or an ellipse in two calls using 4-way symmetry.
  359. */
  360. center *= m_underlying_painter.scale();
  361. radius_a *= m_underlying_painter.scale();
  362. radius_b *= m_underlying_painter.scale();
  363. // If this is a ellipse everything can be drawn in one pass with 8 way symmetry
  364. bool const is_circle = radius_a == radius_b;
  365. // These happen to be the same here, but are treated separately in the paper:
  366. // intensity is the fill alpha
  367. int const intensity = 255;
  368. // 0 to subpixel_resolution is the range of alpha values for the circle edges
  369. int const subpixel_resolution = intensity;
  370. // Current pixel address
  371. int i = 0;
  372. int q = radius_b;
  373. // 1st and 2nd order differences of y
  374. int delta_y = 0;
  375. int delta2_y = 0;
  376. int const a_squared = radius_a * radius_a;
  377. int const b_squared = radius_b * radius_b;
  378. // Exact and predicted values of f(i) -- the ellipse equation scaled by subpixel_resolution
  379. int y = subpixel_resolution * radius_b;
  380. int y_hat = 0;
  381. // The value of f(i)*f(i)
  382. int f_squared = y * y;
  383. // 1st and 2nd order differences of f(i)*f(i)
  384. int delta_f_squared = (static_cast<int64_t>(b_squared) * subpixel_resolution * subpixel_resolution) / a_squared;
  385. int delta2_f_squared = -delta_f_squared - delta_f_squared;
  386. // edge_intersection_area/subpixel_resolution = percentage of pixel intersected by circle
  387. // (aka the alpha for the pixel)
  388. int edge_intersection_area = 0;
  389. int old_area = edge_intersection_area;
  390. auto predict = [&] {
  391. delta_y += delta2_y;
  392. // y_hat is the predicted value of f(i)
  393. y_hat = y + delta_y;
  394. };
  395. auto minimize = [&] {
  396. // Initialize the minimization
  397. delta_f_squared += delta2_f_squared;
  398. f_squared += delta_f_squared;
  399. int min_squared_error = y_hat * y_hat - f_squared;
  400. int prediction_overshot = 1;
  401. y = y_hat;
  402. // Force error negative
  403. if (min_squared_error > 0) {
  404. min_squared_error = -min_squared_error;
  405. prediction_overshot = -1;
  406. }
  407. // Minimize
  408. int previous_error = min_squared_error;
  409. while (min_squared_error < 0) {
  410. y += prediction_overshot;
  411. previous_error = min_squared_error;
  412. min_squared_error += y + y - prediction_overshot;
  413. }
  414. if (min_squared_error + previous_error > 0)
  415. y -= prediction_overshot;
  416. };
  417. auto correct = [&] {
  418. int error = y - y_hat;
  419. delta2_y += error;
  420. delta_y += error;
  421. };
  422. int min_paint_x = NumericLimits<int>::max();
  423. int max_paint_x = NumericLimits<int>::min();
  424. auto pixel = [&](int x, int y, int alpha) {
  425. if (alpha <= 0 || alpha > 255)
  426. return;
  427. if (flip_x_and_y)
  428. swap(x, y);
  429. if (x_clip.has_value() && x_clip->contains_inclusive(x))
  430. return;
  431. min_paint_x = min(x, min_paint_x);
  432. max_paint_x = max(x, max_paint_x);
  433. alpha = (alpha * color.alpha()) / 255;
  434. if (blend_mode == BlendMode::AlphaSubtract)
  435. alpha = ~alpha;
  436. auto pixel_color = color;
  437. pixel_color.set_alpha(alpha);
  438. m_underlying_painter.set_pixel(center + IntPoint { x, y }, pixel_color, blend_mode == BlendMode::Normal);
  439. };
  440. auto fill = [&](int x, int ymax, int ymin, int alpha) {
  441. while (ymin <= ymax) {
  442. pixel(x, ymin, alpha);
  443. ymin += 1;
  444. }
  445. };
  446. auto symmetric_pixel = [&](int x, int y, int alpha) {
  447. pixel(x, y, alpha);
  448. pixel(x, -y - 1, alpha);
  449. pixel(-x - 1, -y - 1, alpha);
  450. pixel(-x - 1, y, alpha);
  451. if (is_circle) {
  452. pixel(y, x, alpha);
  453. pixel(y, -x - 1, alpha);
  454. pixel(-y - 1, -x - 1, alpha);
  455. pixel(-y - 1, x, alpha);
  456. }
  457. };
  458. // These are calculated incrementally (as it is possibly a tiny bit faster)
  459. int ib_squared = 0;
  460. int qa_squared = q * a_squared;
  461. auto in_symmetric_region = [&] {
  462. // Main fix two stop cond here
  463. return is_circle ? i < q : ib_squared < qa_squared;
  464. };
  465. // Draws a 8 octants for a circle or 4 quadrants for a (partial) ellipse
  466. while (in_symmetric_region()) {
  467. predict();
  468. minimize();
  469. correct();
  470. old_area = edge_intersection_area;
  471. edge_intersection_area += delta_y;
  472. if (edge_intersection_area >= 0) {
  473. // Single pixel on perimeter
  474. symmetric_pixel(i, q, (edge_intersection_area + old_area) / 2);
  475. fill(i, q - 1, -q, intensity);
  476. fill(-i - 1, q - 1, -q, intensity);
  477. } else {
  478. // Two pixels on perimeter
  479. edge_intersection_area += subpixel_resolution;
  480. symmetric_pixel(i, q, old_area / 2);
  481. q -= 1;
  482. qa_squared -= a_squared;
  483. fill(i, q - 1, -q, intensity);
  484. fill(-i - 1, q - 1, -q, intensity);
  485. if (!is_circle || in_symmetric_region()) {
  486. symmetric_pixel(i, q, (edge_intersection_area + subpixel_resolution) / 2);
  487. if (is_circle) {
  488. fill(q, i - 1, -i, intensity);
  489. fill(-q - 1, i - 1, -i, intensity);
  490. }
  491. } else {
  492. edge_intersection_area += subpixel_resolution;
  493. }
  494. }
  495. i += 1;
  496. ib_squared += b_squared;
  497. }
  498. if (is_circle) {
  499. int alpha = edge_intersection_area / 2;
  500. pixel(q, q, alpha);
  501. pixel(-q - 1, q, alpha);
  502. pixel(-q - 1, -q - 1, alpha);
  503. pixel(q, -q - 1, alpha);
  504. }
  505. return Range { min_paint_x, max_paint_x };
  506. }
  507. void AntiAliasingPainter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, int radius)
  508. {
  509. fill_rect_with_rounded_corners(a_rect, color, radius, radius, radius, radius);
  510. }
  511. void AntiAliasingPainter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, int top_left_radius, int top_right_radius, int bottom_right_radius, int bottom_left_radius)
  512. {
  513. fill_rect_with_rounded_corners(a_rect, color,
  514. { top_left_radius, top_left_radius },
  515. { top_right_radius, top_right_radius },
  516. { bottom_right_radius, bottom_right_radius },
  517. { bottom_left_radius, bottom_left_radius });
  518. }
  519. void AntiAliasingPainter::fill_rect_with_rounded_corners(IntRect const& a_rect, Color color, CornerRadius top_left, CornerRadius top_right, CornerRadius bottom_right, CornerRadius bottom_left, BlendMode blend_mode)
  520. {
  521. if (!top_left && !top_right && !bottom_right && !bottom_left) {
  522. if (blend_mode == BlendMode::Normal)
  523. return m_underlying_painter.fill_rect(a_rect, color);
  524. else if (blend_mode == BlendMode::AlphaSubtract)
  525. return m_underlying_painter.clear_rect(a_rect, Color());
  526. }
  527. if (color.alpha() == 0)
  528. return;
  529. IntPoint top_left_corner {
  530. a_rect.x() + top_left.horizontal_radius,
  531. a_rect.y() + top_left.vertical_radius,
  532. };
  533. IntPoint top_right_corner {
  534. a_rect.x() + a_rect.width() - top_right.horizontal_radius,
  535. a_rect.y() + top_right.vertical_radius,
  536. };
  537. IntPoint bottom_left_corner {
  538. a_rect.x() + bottom_left.horizontal_radius,
  539. a_rect.y() + a_rect.height() - bottom_left.vertical_radius
  540. };
  541. IntPoint bottom_right_corner {
  542. a_rect.x() + a_rect.width() - bottom_right.horizontal_radius,
  543. a_rect.y() + a_rect.height() - bottom_right.vertical_radius
  544. };
  545. // All corners are centered at the same point, so this can be painted as a single ellipse.
  546. if (top_left_corner == top_right_corner && top_right_corner == bottom_left_corner && bottom_left_corner == bottom_right_corner)
  547. return fill_ellipse(a_rect, color, blend_mode);
  548. IntRect top_rect {
  549. a_rect.x() + top_left.horizontal_radius,
  550. a_rect.y(),
  551. a_rect.width() - top_left.horizontal_radius - top_right.horizontal_radius,
  552. top_left.vertical_radius
  553. };
  554. IntRect right_rect {
  555. a_rect.x() + a_rect.width() - top_right.horizontal_radius,
  556. a_rect.y() + top_right.vertical_radius,
  557. top_right.horizontal_radius,
  558. a_rect.height() - top_right.vertical_radius - bottom_right.vertical_radius
  559. };
  560. IntRect bottom_rect {
  561. a_rect.x() + bottom_left.horizontal_radius,
  562. a_rect.y() + a_rect.height() - bottom_right.vertical_radius,
  563. a_rect.width() - bottom_left.horizontal_radius - bottom_right.horizontal_radius,
  564. bottom_right.vertical_radius
  565. };
  566. IntRect left_rect {
  567. a_rect.x(),
  568. a_rect.y() + top_left.vertical_radius,
  569. bottom_left.horizontal_radius,
  570. a_rect.height() - top_left.vertical_radius - bottom_left.vertical_radius
  571. };
  572. IntRect inner = {
  573. left_rect.x() + left_rect.width(),
  574. left_rect.y(),
  575. a_rect.width() - left_rect.width() - right_rect.width(),
  576. a_rect.height() - top_rect.height() - bottom_rect.height()
  577. };
  578. if (blend_mode == BlendMode::Normal) {
  579. m_underlying_painter.fill_rect(top_rect, color);
  580. m_underlying_painter.fill_rect(right_rect, color);
  581. m_underlying_painter.fill_rect(bottom_rect, color);
  582. m_underlying_painter.fill_rect(left_rect, color);
  583. m_underlying_painter.fill_rect(inner, color);
  584. } else if (blend_mode == BlendMode::AlphaSubtract) {
  585. m_underlying_painter.clear_rect(top_rect, Color());
  586. m_underlying_painter.clear_rect(right_rect, Color());
  587. m_underlying_painter.clear_rect(bottom_rect, Color());
  588. m_underlying_painter.clear_rect(left_rect, Color());
  589. m_underlying_painter.clear_rect(inner, Color());
  590. }
  591. auto fill_corner = [&](auto const& ellipse_center, auto const& corner_point, CornerRadius const& corner) {
  592. PainterStateSaver save { m_underlying_painter };
  593. m_underlying_painter.add_clip_rect(IntRect::from_two_points(ellipse_center, corner_point));
  594. fill_ellipse(IntRect::centered_at(ellipse_center, { corner.horizontal_radius * 2, corner.vertical_radius * 2 }), color, blend_mode);
  595. };
  596. auto bounding_rect = a_rect.inflated(0, 1, 1, 0);
  597. if (top_left)
  598. fill_corner(top_left_corner, bounding_rect.top_left(), top_left);
  599. if (top_right)
  600. fill_corner(top_right_corner, bounding_rect.top_right(), top_right);
  601. if (bottom_left)
  602. fill_corner(bottom_left_corner, bounding_rect.bottom_left(), bottom_left);
  603. if (bottom_right)
  604. fill_corner(bottom_right_corner, bounding_rect.bottom_right(), bottom_right);
  605. }
  606. void AntiAliasingPainter::stroke_segment_intersection(FloatPoint current_line_a, FloatPoint current_line_b, FloatLine const& previous_line, Color color, float thickness)
  607. {
  608. // FIXME: This is currently drawn in slightly the wrong place most of the time.
  609. // FIXME: This is sometimes drawn when the intersection would not be visible anyway.
  610. // Starting point of the current line is where the last line ended... this is an intersection.
  611. auto intersection = current_line_a;
  612. // If both are straight lines we can simply draw a rectangle at the intersection (or nothing).
  613. auto current_vertical = current_line_a.x() == current_line_b.x();
  614. auto current_horizontal = current_line_a.y() == current_line_b.y();
  615. auto previous_vertical = previous_line.a().x() == previous_line.b().x();
  616. auto previous_horizontal = previous_line.a().y() == previous_line.b().y();
  617. if (previous_horizontal && current_horizontal)
  618. return;
  619. if (previous_vertical && current_vertical)
  620. return;
  621. if ((previous_horizontal || previous_vertical) && (current_horizontal || current_vertical)) {
  622. intersection = m_transform.map(current_line_a);
  623. // Note: int_thickness used here to match behaviour of draw_line()
  624. int int_thickness = AK::ceil(thickness);
  625. return fill_rect(FloatRect(intersection, { thickness, thickness }).translated(-int_thickness / 2), color);
  626. }
  627. auto previous_line_a = previous_line.a();
  628. float scale_to_move_current = (thickness / 2) / intersection.distance_from(current_line_b);
  629. float scale_to_move_previous = (thickness / 2) / intersection.distance_from(previous_line_a);
  630. // Move the point on the line by half of the thickness.
  631. float offset_current_edge_x = scale_to_move_current * (current_line_b.x() - intersection.x());
  632. float offset_current_edge_y = scale_to_move_current * (current_line_b.y() - intersection.y());
  633. float offset_prev_edge_x = scale_to_move_previous * (previous_line_a.x() - intersection.x());
  634. float offset_prev_edge_y = scale_to_move_previous * (previous_line_a.y() - intersection.y());
  635. // Rotate the point by 90 and 270 degrees to get the points for both edges.
  636. FloatPoint current_rotated_90deg(-offset_current_edge_y, offset_current_edge_x);
  637. FloatPoint previous_rotated_90deg(-offset_prev_edge_y, offset_prev_edge_x);
  638. auto current_rotated_270deg = intersection - current_rotated_90deg;
  639. auto previous_rotated_270deg = intersection - previous_rotated_90deg;
  640. // Translate coordinates to the intersection point.
  641. current_rotated_90deg += intersection;
  642. previous_rotated_90deg += intersection;
  643. FloatLine outer_line_current_90(current_rotated_90deg, current_line_b - (intersection - current_rotated_90deg));
  644. FloatLine outer_line_current_270(current_rotated_270deg, current_line_b - (intersection - current_rotated_270deg));
  645. FloatLine outer_line_prev_270(previous_rotated_270deg, previous_line_a - (intersection - previous_rotated_270deg));
  646. FloatLine outer_line_prev_90(previous_rotated_90deg, previous_line_a - (intersection - previous_rotated_90deg));
  647. auto edge_spike_90 = outer_line_current_90.intersected(outer_line_prev_270);
  648. Optional<FloatPoint> edge_spike_270;
  649. if (edge_spike_90.has_value()) {
  650. edge_spike_270 = intersection + (intersection - *edge_spike_90);
  651. } else {
  652. edge_spike_270 = outer_line_current_270.intersected(outer_line_prev_90);
  653. if (edge_spike_270.has_value())
  654. edge_spike_90 = intersection + (intersection - *edge_spike_270);
  655. }
  656. Path intersection_edge_path;
  657. intersection_edge_path.move_to(current_rotated_90deg);
  658. if (edge_spike_90.has_value())
  659. intersection_edge_path.line_to(*edge_spike_90);
  660. intersection_edge_path.line_to(previous_rotated_270deg);
  661. intersection_edge_path.line_to(current_rotated_270deg);
  662. if (edge_spike_270.has_value())
  663. intersection_edge_path.line_to(*edge_spike_270);
  664. intersection_edge_path.line_to(previous_rotated_90deg);
  665. intersection_edge_path.close();
  666. fill_path(intersection_edge_path, color);
  667. }
  668. }