EdgeFlagPathRasterizer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /*
  2. * Copyright (c) 2023, MacDue <macdue@dueutil.tech>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Array.h>
  7. #include <AK/Debug.h>
  8. #include <AK/IntegralMath.h>
  9. #include <AK/Types.h>
  10. #include <LibGfx/AntiAliasingPainter.h>
  11. #include <LibGfx/EdgeFlagPathRasterizer.h>
  12. #if defined(AK_COMPILER_GCC)
  13. # pragma GCC optimize("O3")
  14. #endif
  15. // This a pretty naive implementation of edge-flag scanline AA.
  16. // The paper lists many possible optimizations, maybe implement one? (FIXME!)
  17. // https://mlab.taik.fi/~kkallio/antialiasing/EdgeFlagAA.pdf
  18. // This currently implements:
  19. // - The scanline buffer optimization (only allocate one scanline)
  20. // Possible other optimizations according to the paper:
  21. // - Using fixed point numbers
  22. // - Edge tracking
  23. // - Mask tracking
  24. // - Loop unrolling (compilers might handle this better now, the paper is from 2007)
  25. // Optimizations I think we could add:
  26. // - Using fast_u32_fills() for runs of solid colors
  27. // - Clipping the plotted edges earlier
  28. namespace Gfx {
  29. static Vector<Detail::Edge> prepare_edges(ReadonlySpan<FloatLine> lines, unsigned samples_per_pixel, FloatPoint origin)
  30. {
  31. Vector<Detail::Edge> edges;
  32. edges.ensure_capacity(lines.size());
  33. for (auto& line : lines) {
  34. auto p0 = line.a() - origin;
  35. auto p1 = line.b() - origin;
  36. p0.scale_by(1, samples_per_pixel);
  37. p1.scale_by(1, samples_per_pixel);
  38. i8 winding = -1;
  39. if (p0.y() > p1.y()) {
  40. swap(p0, p1);
  41. } else {
  42. winding = 1;
  43. }
  44. if (p0.y() == p1.y())
  45. continue;
  46. auto min_y = static_cast<int>(p0.y());
  47. auto max_y = static_cast<int>(p1.y());
  48. float start_x = p0.x();
  49. float end_x = p1.x();
  50. auto dx = end_x - start_x;
  51. auto dy = max_y - min_y;
  52. auto dxdy = dx / dy;
  53. edges.unchecked_append(Detail::Edge {
  54. start_x,
  55. min_y,
  56. max_y,
  57. dxdy,
  58. winding,
  59. nullptr });
  60. }
  61. return edges;
  62. }
  63. template<unsigned SamplesPerPixel>
  64. EdgeFlagPathRasterizer<SamplesPerPixel>::EdgeFlagPathRasterizer(IntSize size)
  65. : m_size(size.width() + 1, size.height() + 1)
  66. {
  67. m_scanline.resize(m_size.width());
  68. m_edge_table.resize(m_size.height());
  69. }
  70. template<unsigned SamplesPerPixel>
  71. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill(Painter& painter, Path const& path, Color color, Painter::WindingRule winding_rule, FloatPoint offset)
  72. {
  73. fill_internal(painter, path, color, winding_rule, offset);
  74. }
  75. template<unsigned SamplesPerPixel>
  76. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill(Painter& painter, Path const& path, PaintStyle const& style, float opacity, Painter::WindingRule winding_rule, FloatPoint offset)
  77. {
  78. style.paint(enclosing_int_rect(path.bounding_box()), [&](PaintStyle::SamplerFunction sampler) {
  79. if (opacity == 0.0f)
  80. return;
  81. if (opacity != 1.0f) {
  82. return fill_internal(
  83. painter, path, [=, sampler = move(sampler)](IntPoint point) {
  84. return sampler(point).with_opacity(opacity);
  85. },
  86. winding_rule, offset);
  87. }
  88. return fill_internal(painter, path, move(sampler), winding_rule, offset);
  89. });
  90. }
  91. template<unsigned SamplesPerPixel>
  92. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill_internal(Painter& painter, Path const& path, auto color_or_function, Painter::WindingRule winding_rule, FloatPoint offset)
  93. {
  94. // FIXME: Figure out how painter scaling works here...
  95. VERIFY(painter.scale() == 1);
  96. auto bounding_box = enclosing_int_rect(path.bounding_box().translated(offset));
  97. auto dest_rect = bounding_box.translated(painter.translation());
  98. auto origin = bounding_box.top_left().to_type<float>() - offset;
  99. m_blit_origin = dest_rect.top_left();
  100. m_clip = dest_rect.intersected(painter.clip_rect());
  101. if (m_clip.is_empty())
  102. return;
  103. auto& lines = path.split_lines();
  104. if (lines.is_empty())
  105. return;
  106. auto edges = prepare_edges(lines, SamplesPerPixel, origin);
  107. int min_scanline = m_size.height();
  108. int max_scanline = 0;
  109. for (auto& edge : edges) {
  110. int start_scanline = edge.min_y / SamplesPerPixel;
  111. int end_scanline = edge.max_y / SamplesPerPixel;
  112. // Create a linked-list of edges starting on this scanline:
  113. edge.next_edge = m_edge_table[start_scanline];
  114. m_edge_table[start_scanline] = &edge;
  115. min_scanline = min(min_scanline, start_scanline);
  116. max_scanline = max(max_scanline, end_scanline);
  117. }
  118. // FIXME: We could probably clip some of the egde plotting if we know it won't be shown.
  119. // Though care would have to be taken to ensure the active edges are correct at the first drawn scaline.
  120. auto for_each_sample = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, auto callback) {
  121. for (int y = start_subpixel_y; y < end_subpixel_y; y++) {
  122. int xi = static_cast<int>(edge.x + SubpixelSample::nrooks_subpixel_offsets[y]);
  123. if (xi < 0 || xi >= (int)m_scanline.size()) {
  124. // FIXME: For very low dxdy values, floating point error can push the sample outside the scanline.
  125. // This does not seem to make a visible difference most of the time (and is more likely from generated
  126. // paths, such as this 3D canvas demo: https://www.kevs3d.co.uk/dev/html5logo/).
  127. dbgln_if(FILL_PATH_DEBUG, "fill_path: Sample out of bounds: {} not in [0, {})", xi, m_scanline.size());
  128. return;
  129. }
  130. SampleType sample = 1 << y;
  131. callback(xi, y, sample);
  132. edge.x += edge.dxdy;
  133. }
  134. };
  135. Detail::Edge* active_edges = nullptr;
  136. if (winding_rule == Painter::WindingRule::EvenOdd) {
  137. auto plot_edge = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y) {
  138. for_each_sample(edge, start_subpixel_y, end_subpixel_y, [&](int xi, int, SampleType sample) {
  139. m_scanline[xi] ^= sample;
  140. });
  141. };
  142. for (int scanline = min_scanline; scanline <= max_scanline; scanline++) {
  143. active_edges = plot_edges_for_scanline(scanline, plot_edge, active_edges);
  144. accumulate_even_odd_scanline(painter, scanline, color_or_function);
  145. }
  146. } else {
  147. VERIFY(winding_rule == Painter::WindingRule::Nonzero);
  148. // Only allocate the winding buffer if needed.
  149. // NOTE: non-zero fills are a fair bit less efficient. So if you can do an even-odd fill do that :^)
  150. if (m_windings.is_empty())
  151. m_windings.resize(m_size.width());
  152. auto plot_edge = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y) {
  153. for_each_sample(edge, start_subpixel_y, end_subpixel_y, [&](int xi, int y, SampleType sample) {
  154. m_scanline[xi] |= sample;
  155. m_windings[xi].counts[y] += edge.winding;
  156. });
  157. };
  158. for (int scanline = min_scanline; scanline <= max_scanline; scanline++) {
  159. active_edges = plot_edges_for_scanline(scanline, plot_edge, active_edges);
  160. accumulate_non_zero_scanline(painter, scanline, color_or_function);
  161. }
  162. }
  163. }
  164. template<unsigned SamplesPerPixel>
  165. Color EdgeFlagPathRasterizer<SamplesPerPixel>::scanline_color(int scanline, int offset, u8 alpha, auto& color_or_function)
  166. {
  167. using ColorOrFunction = decltype(color_or_function);
  168. constexpr bool has_constant_color = IsSame<RemoveCVReference<ColorOrFunction>, Color>;
  169. auto color = [&] {
  170. if constexpr (has_constant_color) {
  171. return color_or_function;
  172. } else {
  173. return color_or_function({ offset, scanline });
  174. }
  175. }();
  176. return color.with_alpha(color.alpha() * alpha / 255);
  177. }
  178. template<unsigned SamplesPerPixel>
  179. Detail::Edge* EdgeFlagPathRasterizer<SamplesPerPixel>::plot_edges_for_scanline(int scanline, auto plot_edge, Detail::Edge* active_edges)
  180. {
  181. auto y_subpixel = [](int y) {
  182. return y & (SamplesPerPixel - 1);
  183. };
  184. auto* current_edge = active_edges;
  185. Detail::Edge* prev_edge = nullptr;
  186. // First iterate over the edge in the active edge table, these are edges added on earlier scanlines,
  187. // that have not yet reached their end scanline.
  188. while (current_edge) {
  189. int end_scanline = current_edge->max_y / SamplesPerPixel;
  190. if (scanline == end_scanline) {
  191. // This edge ends this scanline.
  192. plot_edge(*current_edge, 0, y_subpixel(current_edge->max_y));
  193. // Remove this edge from the AET
  194. current_edge = current_edge->next_edge;
  195. if (prev_edge)
  196. prev_edge->next_edge = current_edge;
  197. else
  198. active_edges = current_edge;
  199. } else {
  200. // This egde sticks around for a few more scanlines.
  201. plot_edge(*current_edge, 0, SamplesPerPixel);
  202. prev_edge = current_edge;
  203. current_edge = current_edge->next_edge;
  204. }
  205. }
  206. // Next, iterate over new edges for this line. If active_edges was null this also becomes the new
  207. // AET. Edges new will be appended here.
  208. current_edge = m_edge_table[scanline];
  209. while (current_edge) {
  210. int end_scanline = current_edge->max_y / SamplesPerPixel;
  211. if (scanline == end_scanline) {
  212. // This edge will end this scanlines (no need to add to AET).
  213. plot_edge(*current_edge, y_subpixel(current_edge->min_y), y_subpixel(current_edge->max_y));
  214. } else {
  215. // This edge will live on for a few more scanlines.
  216. plot_edge(*current_edge, y_subpixel(current_edge->min_y), SamplesPerPixel);
  217. // Add this edge to the AET
  218. if (prev_edge)
  219. prev_edge->next_edge = current_edge;
  220. else
  221. active_edges = current_edge;
  222. prev_edge = current_edge;
  223. }
  224. current_edge = current_edge->next_edge;
  225. }
  226. if (prev_edge)
  227. prev_edge->next_edge = nullptr;
  228. m_edge_table[scanline] = nullptr;
  229. return active_edges;
  230. }
  231. template<unsigned SamplesPerPixel>
  232. void EdgeFlagPathRasterizer<SamplesPerPixel>::write_pixel(Painter& painter, int scanline, int offset, SampleType sample, auto& color_or_function)
  233. {
  234. auto dest = IntPoint { offset, scanline } + m_blit_origin;
  235. if (!m_clip.contains_horizontally(dest.x()))
  236. return;
  237. // FIXME: We could detect runs of full coverage and use fast_u32_fills for those rather than many set_pixel() calls.
  238. auto coverage = SubpixelSample::compute_coverage(sample);
  239. if (coverage) {
  240. auto paint_color = scanline_color(scanline, offset, coverage_to_alpha(coverage), color_or_function);
  241. painter.set_physical_pixel(dest, paint_color, true);
  242. }
  243. }
  244. template<unsigned SamplesPerPixel>
  245. void EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_even_odd_scanline(Painter& painter, int scanline, auto& color_or_function)
  246. {
  247. auto dest_y = m_blit_origin.y() + scanline;
  248. if (!m_clip.contains_vertically(dest_y)) {
  249. // FIXME: This memset only really needs to be done on transition from clipped to not clipped,
  250. // or not at all if we properly clipped egde plotting.
  251. memset(m_scanline.data(), 0, sizeof(SampleType) * m_scanline.size());
  252. return;
  253. }
  254. SampleType sample = 0;
  255. for (int x = 0; x < m_size.width(); x += 1) {
  256. sample ^= m_scanline[x];
  257. write_pixel(painter, scanline, x, sample, color_or_function);
  258. m_scanline[x] = 0;
  259. }
  260. }
  261. template<unsigned SamplesPerPixel>
  262. void EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_non_zero_scanline(Painter& painter, int scanline, auto& color_or_function)
  263. {
  264. // NOTE: Same FIXMEs apply from accumulate_even_odd_scanline()
  265. auto dest_y = m_blit_origin.y() + scanline;
  266. if (!m_clip.contains_vertically(dest_y)) {
  267. memset(m_scanline.data(), 0, sizeof(SampleType) * m_scanline.size());
  268. memset(m_windings.data(), 0, sizeof(WindingCounts) * m_windings.size());
  269. return;
  270. }
  271. SampleType sample = 0;
  272. WindingCounts sum_winding = {};
  273. for (int x = 0; x < m_size.width(); x += 1) {
  274. if (auto edges = m_scanline[x]) {
  275. // We only need to process the windings when we hit some edges.
  276. for (auto y_sub = 0u; y_sub < SamplesPerPixel; y_sub++) {
  277. auto subpixel_bit = 1 << y_sub;
  278. if (edges & subpixel_bit) {
  279. auto winding = m_windings[x].counts[y_sub];
  280. auto previous_winding_count = sum_winding.counts[y_sub];
  281. sum_winding.counts[y_sub] += winding;
  282. // Toggle fill on change to/from zero
  283. if ((previous_winding_count == 0 && sum_winding.counts[y_sub] != 0)
  284. || (sum_winding.counts[y_sub] == 0 && previous_winding_count != 0)) {
  285. sample ^= subpixel_bit;
  286. }
  287. }
  288. }
  289. }
  290. write_pixel(painter, scanline, x, sample, color_or_function);
  291. m_scanline[x] = 0;
  292. m_windings[x] = {};
  293. }
  294. }
  295. static IntSize path_bounds(Gfx::Path const& path)
  296. {
  297. return enclosing_int_rect(path.bounding_box()).size();
  298. }
  299. // Note: The AntiAliasingPainter and Painter now perform the same antialiasing,
  300. // since it would be harder to turn it off for the standard painter.
  301. // The samples are reduced to 8 for Gfx::Painter though as a "speedy" option.
  302. void Painter::fill_path(Path const& path, Color color, WindingRule winding_rule)
  303. {
  304. EdgeFlagPathRasterizer<8> rasterizer(path_bounds(path));
  305. rasterizer.fill(*this, path, color, winding_rule);
  306. }
  307. void Painter::fill_path(Path const& path, PaintStyle const& paint_style, float opacity, Painter::WindingRule winding_rule)
  308. {
  309. EdgeFlagPathRasterizer<8> rasterizer(path_bounds(path));
  310. rasterizer.fill(*this, path, paint_style, opacity, winding_rule);
  311. }
  312. void AntiAliasingPainter::fill_path(Path const& path, Color color, Painter::WindingRule winding_rule)
  313. {
  314. EdgeFlagPathRasterizer<32> rasterizer(path_bounds(path));
  315. rasterizer.fill(m_underlying_painter, path, color, winding_rule, m_transform.translation());
  316. }
  317. void AntiAliasingPainter::fill_path(Path const& path, PaintStyle const& paint_style, float opacity, Painter::WindingRule winding_rule)
  318. {
  319. EdgeFlagPathRasterizer<32> rasterizer(path_bounds(path));
  320. rasterizer.fill(m_underlying_painter, path, paint_style, opacity, winding_rule, m_transform.translation());
  321. }
  322. template class EdgeFlagPathRasterizer<8>;
  323. template class EdgeFlagPathRasterizer<16>;
  324. template class EdgeFlagPathRasterizer<32>;
  325. }