AntiAliasingPainter.cpp 33 KB

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