FillPathImplementation.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. * Copyright (c) 2023, MacDue <macdue@dueutil.tech>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/QuickSort.h>
  9. #include <LibGfx/Color.h>
  10. #include <LibGfx/Painter.h>
  11. #include <LibGfx/Path.h>
  12. #if defined(AK_COMPILER_GCC)
  13. # pragma GCC optimize("O3")
  14. #endif
  15. namespace Gfx {
  16. template<typename T, typename TColorOrFunction>
  17. ALWAYS_INLINE void Painter::draw_scanline_for_fill_path(int y, T x_start, T x_end, TColorOrFunction color)
  18. {
  19. // Fill path should scale the scanlines before calling this.
  20. VERIFY(scale() == 1);
  21. constexpr bool is_floating_point = IsSameIgnoringCV<T, float>;
  22. constexpr bool has_constant_color = IsSameIgnoringCV<TColorOrFunction, Color>;
  23. int x1 = 0;
  24. int x2 = 0;
  25. u8 left_subpixel_alpha = 0;
  26. u8 right_subpixel_alpha = 0;
  27. if constexpr (is_floating_point) {
  28. x1 = ceilf(x_start);
  29. x2 = floorf(x_end);
  30. left_subpixel_alpha = (x1 - x_start) * 255;
  31. right_subpixel_alpha = (x_end - x2) * 255;
  32. x1 -= left_subpixel_alpha > 0;
  33. x2 += right_subpixel_alpha > 0;
  34. } else {
  35. x1 = x_start;
  36. x2 = x_end;
  37. }
  38. IntRect scanline(x1, y, x2 - x1, 1);
  39. scanline = scanline.translated(translation());
  40. auto clipped = scanline.intersected(clip_rect());
  41. if (clipped.is_empty())
  42. return;
  43. auto get_color = [&](int offset) {
  44. if constexpr (has_constant_color) {
  45. return color;
  46. } else {
  47. return color(offset);
  48. }
  49. };
  50. if constexpr (is_floating_point) {
  51. // Paint left and right subpixels (then remove them from the scanline).
  52. auto get_color_with_alpha = [&](int offset, u8 alpha) {
  53. auto color_at_offset = get_color(offset);
  54. u8 color_alpha = (alpha * color_at_offset.alpha()) / 255;
  55. return color_at_offset.with_alpha(color_alpha);
  56. };
  57. if (clipped.left() == scanline.left() && left_subpixel_alpha)
  58. set_physical_pixel(clipped.top_left(), get_color_with_alpha(0, left_subpixel_alpha), true);
  59. if (clipped.right() == scanline.right() && right_subpixel_alpha)
  60. set_physical_pixel(clipped.top_right(), get_color_with_alpha(scanline.width(), right_subpixel_alpha), true);
  61. clipped.shrink(0, right_subpixel_alpha > 0, 0, left_subpixel_alpha > 0);
  62. }
  63. if constexpr (has_constant_color) {
  64. if (color.alpha() == 255) {
  65. // Speedy path: Constant color and no alpha blending.
  66. fast_u32_fill(m_target->scanline(clipped.y()) + clipped.x(), color.value(), clipped.width());
  67. return;
  68. }
  69. }
  70. for (int x = clipped.x(); x <= clipped.right(); x++) {
  71. set_physical_pixel({ x, clipped.y() }, get_color(x - scanline.x()), true);
  72. }
  73. }
  74. [[maybe_unused]] inline void approximately_place_on_int_grid(FloatPoint ffrom, FloatPoint fto, IntPoint& from, IntPoint& to, Optional<IntPoint> previous_to)
  75. {
  76. auto diffs = fto - ffrom;
  77. // Truncate all first (round down).
  78. from = ffrom.to_type<int>();
  79. to = fto.to_type<int>();
  80. // There are 16 possible configurations, by deciding to round each
  81. // coord up or down (and there are four coords, from.x from.y to.x to.y)
  82. // we will simply choose one which most closely matches the correct slope
  83. // with the following heuristic:
  84. // - if the x diff is positive or zero (that is, a right-to-left slant), round 'from.x' up and 'to.x' down.
  85. // - if the x diff is negative (that is, a left-to-right slant), round 'from.x' down and 'to.x' up.
  86. // Note that we do not need to touch the 'y' attribute, as that is our scanline.
  87. if (diffs.x() >= 0) {
  88. from.set_x(from.x() + 1);
  89. } else {
  90. to.set_x(to.x() + 1);
  91. }
  92. if (previous_to.has_value() && from.x() != previous_to.value().x()) // The points have to line up, since we're using these lines to fill a shape.
  93. from.set_x(previous_to.value().x());
  94. }
  95. template<Painter::FillPathMode fill_path_mode, typename ColorOrFunction>
  96. void Painter::fill_path_impl(Path const& path, ColorOrFunction color, Gfx::Painter::WindingRule winding_rule, Optional<FloatPoint> offset)
  97. {
  98. using GridCoordinateType = Conditional<fill_path_mode == FillPathMode::PlaceOnIntGrid, int, float>;
  99. using PointType = Point<GridCoordinateType>;
  100. auto draw_scanline = [&](int y, GridCoordinateType x1, GridCoordinateType x2) {
  101. const auto draw_offset = offset.value_or({ 0, 0 });
  102. const auto draw_origin = (path.bounding_box().top_left() + draw_offset).to_type<int>();
  103. // FIMXE: Offset is added here to handle floating point translations in the AA painter,
  104. // really this should be done there but this function is a bit too specialised.
  105. y = floorf(y + draw_offset.y());
  106. x1 += draw_offset.x();
  107. x2 += draw_offset.x();
  108. if (x1 > x2)
  109. swap(x1, x2);
  110. if constexpr (IsSameIgnoringCV<ColorOrFunction, Color>) {
  111. draw_scanline_for_fill_path(y, x1, x2 + 1, color);
  112. } else {
  113. draw_scanline_for_fill_path(y, x1, x2 + 1, [&](int offset) {
  114. return color(IntPoint(x1 + offset, y) - draw_origin);
  115. });
  116. }
  117. };
  118. auto const& segments = path.split_lines();
  119. if (segments.size() == 0)
  120. return;
  121. Vector<Path::SplitLineSegment> active_list;
  122. active_list.ensure_capacity(segments.size());
  123. // first, grab the segments for the very first scanline
  124. GridCoordinateType first_y = path.bounding_box().bottom_right().y() + 1;
  125. GridCoordinateType last_y = path.bounding_box().top_left().y() - 1;
  126. float scanline = first_y;
  127. size_t last_active_segment { 0 };
  128. for (auto& segment : segments) {
  129. if (segment.maximum_y != scanline)
  130. break;
  131. active_list.append(segment);
  132. ++last_active_segment;
  133. }
  134. auto is_inside_shape = [winding_rule](int winding_number) {
  135. if (winding_rule == Gfx::Painter::WindingRule::Nonzero)
  136. return winding_number != 0;
  137. if (winding_rule == Gfx::Painter::WindingRule::EvenOdd)
  138. return winding_number % 2 == 0;
  139. VERIFY_NOT_REACHED();
  140. };
  141. auto increment_winding = [winding_rule](int& winding_number, PointType const& from, PointType const& to) {
  142. if (winding_rule == Gfx::Painter::WindingRule::EvenOdd) {
  143. ++winding_number;
  144. return;
  145. }
  146. if (winding_rule == Gfx::Painter::WindingRule::Nonzero) {
  147. if (from.dy_relative_to(to) < 0)
  148. ++winding_number;
  149. else
  150. --winding_number;
  151. return;
  152. }
  153. VERIFY_NOT_REACHED();
  154. };
  155. while (scanline >= last_y) {
  156. Optional<PointType> previous_to;
  157. if (active_list.size()) {
  158. // sort the active list by 'x' from right to left
  159. quick_sort(active_list, [](auto const& line0, auto const& line1) {
  160. return line1.x < line0.x;
  161. });
  162. if constexpr (fill_path_mode == FillPathMode::PlaceOnIntGrid && FILL_PATH_DEBUG) {
  163. if ((int)scanline % 10 == 0) {
  164. draw_text(Gfx::Rect<GridCoordinateType>(active_list.last().x - 20, scanline, 20, 10), DeprecatedString::number((int)scanline));
  165. }
  166. }
  167. if (active_list.size() > 1) {
  168. auto winding_number { winding_rule == Gfx::Painter::WindingRule::Nonzero ? 1 : 0 };
  169. for (size_t i = 1; i < active_list.size(); ++i) {
  170. auto& previous = active_list[i - 1];
  171. auto& current = active_list[i];
  172. PointType from, to;
  173. PointType truncated_from { previous.x, scanline };
  174. PointType truncated_to { current.x, scanline };
  175. if constexpr (fill_path_mode == FillPathMode::PlaceOnIntGrid) {
  176. approximately_place_on_int_grid({ previous.x, scanline }, { current.x, scanline }, from, to, previous_to);
  177. } else {
  178. from = truncated_from;
  179. to = truncated_to;
  180. }
  181. if (is_inside_shape(winding_number)) {
  182. // The points between this segment and the previous are
  183. // inside the shape
  184. dbgln_if(FILL_PATH_DEBUG, "y={}: {} at {}: {} -- {}", scanline, winding_number, i, from, to);
  185. draw_scanline(floorf(scanline), from.x(), to.x());
  186. }
  187. auto is_passing_through_maxima = scanline == previous.maximum_y
  188. || scanline == previous.minimum_y
  189. || scanline == current.maximum_y
  190. || scanline == current.minimum_y;
  191. auto is_passing_through_vertex = false;
  192. if (is_passing_through_maxima) {
  193. is_passing_through_vertex = previous.x == current.x;
  194. }
  195. if (!is_passing_through_vertex || previous.inverse_slope * current.inverse_slope < 0)
  196. increment_winding(winding_number, truncated_from, truncated_to);
  197. // update the x coord
  198. active_list[i - 1].x -= active_list[i - 1].inverse_slope;
  199. }
  200. active_list.last().x -= active_list.last().inverse_slope;
  201. } else {
  202. auto point = PointType(active_list[0].x, scanline);
  203. draw_scanline(floorf(scanline), point.x(), point.x());
  204. // update the x coord
  205. active_list.first().x -= active_list.first().inverse_slope;
  206. }
  207. }
  208. --scanline;
  209. // remove any edge that goes out of bound from the active list
  210. for (size_t i = 0, count = active_list.size(); i < count; ++i) {
  211. if (scanline <= active_list[i].minimum_y) {
  212. active_list.remove(i);
  213. --count;
  214. --i;
  215. }
  216. }
  217. for (size_t j = last_active_segment; j < segments.size(); ++j, ++last_active_segment) {
  218. auto& segment = segments[j];
  219. if (segment.maximum_y < scanline)
  220. break;
  221. if (segment.minimum_y >= scanline)
  222. continue;
  223. active_list.append(segment);
  224. }
  225. }
  226. }
  227. void Painter::fill_path(Path const& path, Color color, WindingRule winding_rule)
  228. {
  229. VERIFY(scale() == 1); // FIXME: Add scaling support.
  230. fill_path_impl<FillPathMode::PlaceOnIntGrid>(path, color, winding_rule);
  231. }
  232. void Painter::fill_path(Path const& path, PaintStyle const& paint_style, Painter::WindingRule rule)
  233. {
  234. VERIFY(scale() == 1); // FIXME: Add scaling support.
  235. paint_style.paint(enclosing_int_rect(path.bounding_box()), [&](PaintStyle::SamplerFunction sampler) {
  236. fill_path_impl<FillPathMode::PlaceOnIntGrid>(path, move(sampler), rule);
  237. });
  238. }
  239. void Painter::antialiased_fill_path(Path const& path, Color color, WindingRule rule, FloatPoint translation)
  240. {
  241. VERIFY(scale() == 1); // FIXME: Add scaling support.
  242. fill_path_impl<FillPathMode::AllowFloatingPoints>(path, color, rule, translation);
  243. }
  244. void Painter::antialiased_fill_path(Path const& path, PaintStyle const& paint_style, WindingRule rule, FloatPoint translation)
  245. {
  246. VERIFY(scale() == 1); // FIXME: Add scaling support.
  247. paint_style.paint(enclosing_int_rect(path.bounding_box()), [&](PaintStyle::SamplerFunction sampler) {
  248. fill_path_impl<FillPathMode::AllowFloatingPoints>(path, move(sampler), rule, translation);
  249. });
  250. }
  251. }