EdgeFlagPathRasterizer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /*
  2. * Copyright (c) 2023-2024, 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 an implementation of edge-flag scanline AA, as described in:
  16. // https://mlab.taik.fi/~kkallio/antialiasing/EdgeFlagAA.pdf
  17. namespace Gfx {
  18. static Vector<Detail::Edge> prepare_edges(ReadonlySpan<FloatLine> lines, unsigned samples_per_pixel, FloatPoint origin,
  19. int top_clip_scanline, int bottom_clip_scanline, int& min_edge_y, int& max_edge_y)
  20. {
  21. Vector<Detail::Edge> edges;
  22. edges.ensure_capacity(lines.size());
  23. // The first visible y value.
  24. auto top_clip = top_clip_scanline * int(samples_per_pixel);
  25. // The last visible y value.
  26. auto bottom_clip = (bottom_clip_scanline + 1) * int(samples_per_pixel) - 1;
  27. min_edge_y = bottom_clip;
  28. max_edge_y = top_clip;
  29. for (auto& line : lines) {
  30. auto p0 = line.a() - origin;
  31. auto p1 = line.b() - origin;
  32. p0.scale_by(1, samples_per_pixel);
  33. p1.scale_by(1, samples_per_pixel);
  34. i8 winding = -1;
  35. if (p0.y() > p1.y()) {
  36. swap(p0, p1);
  37. } else {
  38. winding = 1;
  39. }
  40. if (p0.y() == p1.y())
  41. continue;
  42. auto min_y = static_cast<int>(p0.y());
  43. auto max_y = static_cast<int>(p1.y());
  44. // Clip edges that start below the bottom clip...
  45. if (min_y > bottom_clip)
  46. continue;
  47. // ...and edges that end before the top clip.
  48. if (max_y < top_clip)
  49. continue;
  50. auto start_x = p0.x();
  51. auto end_x = p1.x();
  52. auto dx = end_x - start_x;
  53. auto dy = max_y - min_y;
  54. if (dy == 0)
  55. continue;
  56. auto dxdy = dx / dy;
  57. // Trim off the non-visible portions of the edge.
  58. if (min_y < top_clip) {
  59. start_x += dxdy * (top_clip - min_y);
  60. min_y = top_clip;
  61. }
  62. if (max_y > bottom_clip) {
  63. max_y = bottom_clip;
  64. }
  65. min_edge_y = min(min_y, min_edge_y);
  66. max_edge_y = max(max_y, max_edge_y);
  67. edges.unchecked_append(Detail::Edge {
  68. start_x,
  69. min_y,
  70. max_y,
  71. dxdy,
  72. winding,
  73. nullptr });
  74. }
  75. return edges;
  76. }
  77. template<unsigned SamplesPerPixel>
  78. EdgeFlagPathRasterizer<SamplesPerPixel>::EdgeFlagPathRasterizer(IntSize size)
  79. : m_size(size.width() + 1, size.height() + 1)
  80. {
  81. // FIXME: Clip the scanline width to the visible section (tricky).
  82. m_scanline.resize(m_size.width());
  83. }
  84. template<unsigned SamplesPerPixel>
  85. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill(Painter& painter, Path const& path, Color color, Painter::WindingRule winding_rule, FloatPoint offset)
  86. {
  87. fill_internal(painter, path, color, winding_rule, offset);
  88. }
  89. template<unsigned SamplesPerPixel>
  90. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill(Painter& painter, Path const& path, PaintStyle const& style, float opacity, Painter::WindingRule winding_rule, FloatPoint offset)
  91. {
  92. style.paint(enclosing_int_rect(path.bounding_box()), [&](PaintStyle::SamplerFunction sampler) {
  93. if (opacity == 0.0f)
  94. return;
  95. if (opacity != 1.0f) {
  96. return fill_internal(
  97. painter, path, [=, sampler = move(sampler)](IntPoint point) {
  98. return sampler(point).with_opacity(opacity);
  99. },
  100. winding_rule, offset);
  101. }
  102. return fill_internal(painter, path, move(sampler), winding_rule, offset);
  103. });
  104. }
  105. template<unsigned SamplesPerPixel>
  106. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill_internal(Painter& painter, Path const& path, auto color_or_function, Painter::WindingRule winding_rule, FloatPoint offset)
  107. {
  108. // FIXME: Figure out how painter scaling works here...
  109. VERIFY(painter.scale() == 1);
  110. auto bounding_box = enclosing_int_rect(path.bounding_box().translated(offset));
  111. auto dest_rect = bounding_box.translated(painter.translation());
  112. auto origin = bounding_box.top_left().to_type<float>() - offset;
  113. m_blit_origin = dest_rect.top_left();
  114. m_clip = dest_rect.intersected(painter.clip_rect());
  115. if (m_clip.is_empty())
  116. return;
  117. auto& lines = path.split_lines();
  118. if (lines.is_empty())
  119. return;
  120. int min_edge_y = 0;
  121. int max_edge_y = 0;
  122. auto top_clip_scanline = m_clip.top() - m_blit_origin.y();
  123. auto bottom_clip_scanline = m_clip.bottom() - m_blit_origin.y() - 1;
  124. auto edges = prepare_edges(lines, SamplesPerPixel, origin, top_clip_scanline, bottom_clip_scanline, min_edge_y, max_edge_y);
  125. if (edges.is_empty())
  126. return;
  127. int min_scanline = min_edge_y / SamplesPerPixel;
  128. int max_scanline = max_edge_y / SamplesPerPixel;
  129. m_edge_table.set_scanline_range(min_scanline, max_scanline);
  130. for (auto& edge : edges) {
  131. // Create a linked-list of edges starting on this scanline:
  132. int start_scanline = edge.min_y / SamplesPerPixel;
  133. edge.next_edge = m_edge_table[start_scanline];
  134. m_edge_table[start_scanline] = &edge;
  135. }
  136. auto empty_edge_extent = [&] {
  137. return EdgeExtent { m_size.width() - 1, 0 };
  138. };
  139. auto for_each_sample = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, EdgeExtent& edge_extent, auto callback) {
  140. for (int y = start_subpixel_y; y < end_subpixel_y; y++) {
  141. auto xi = static_cast<int>(edge.x + SubpixelSample::nrooks_subpixel_offsets[y]);
  142. if (xi < 0 || size_t(xi) >= m_scanline.size()) {
  143. // FIXME: For very low dxdy values, floating point error can push the sample outside the scanline.
  144. // This does not seem to make a visible difference most of the time (and is more likely from generated
  145. // paths, such as this 3D canvas demo: https://www.kevs3d.co.uk/dev/html5logo/).
  146. dbgln_if(FILL_PATH_DEBUG, "fill_path: Sample out of bounds: {} not in [0, {})", xi, m_scanline.size());
  147. return;
  148. }
  149. SampleType sample = 1 << y;
  150. callback(xi, y, sample);
  151. edge.x += edge.dxdy;
  152. edge_extent.min_x = min(edge_extent.min_x, xi);
  153. edge_extent.max_x = max(edge_extent.max_x, xi);
  154. }
  155. };
  156. Detail::Edge* active_edges = nullptr;
  157. if (winding_rule == Painter::WindingRule::EvenOdd) {
  158. auto plot_edge = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, EdgeExtent& edge_extent) {
  159. for_each_sample(edge, start_subpixel_y, end_subpixel_y, edge_extent, [&](int xi, int, SampleType sample) {
  160. m_scanline[xi] ^= sample;
  161. });
  162. };
  163. for (int scanline = min_scanline; scanline <= max_scanline; scanline++) {
  164. auto edge_extent = empty_edge_extent();
  165. active_edges = plot_edges_for_scanline(scanline, plot_edge, edge_extent, active_edges);
  166. write_scanline<Painter::WindingRule::EvenOdd>(painter, scanline, edge_extent, color_or_function);
  167. }
  168. } else {
  169. VERIFY(winding_rule == Painter::WindingRule::Nonzero);
  170. // Only allocate the winding buffer if needed.
  171. // NOTE: non-zero fills are a fair bit less efficient. So if you can do an even-odd fill do that :^)
  172. if (m_windings.is_empty())
  173. m_windings.resize(m_size.width());
  174. auto plot_edge = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, EdgeExtent& edge_extent) {
  175. for_each_sample(edge, start_subpixel_y, end_subpixel_y, edge_extent, [&](int xi, int y, SampleType sample) {
  176. m_scanline[xi] |= sample;
  177. m_windings[xi].counts[y] += edge.winding;
  178. });
  179. };
  180. for (int scanline = min_scanline; scanline <= max_scanline; scanline++) {
  181. auto edge_extent = empty_edge_extent();
  182. active_edges = plot_edges_for_scanline(scanline, plot_edge, edge_extent, active_edges);
  183. write_scanline<Painter::WindingRule::Nonzero>(painter, scanline, edge_extent, color_or_function);
  184. }
  185. }
  186. }
  187. ALWAYS_INLINE static auto switch_on_color_or_function(auto& color_or_function, auto color_case, auto function_case)
  188. {
  189. using ColorOrFunction = decltype(color_or_function);
  190. constexpr bool has_constant_color = IsSame<RemoveCVReference<ColorOrFunction>, Color>;
  191. if constexpr (has_constant_color) {
  192. return color_case(color_or_function);
  193. } else {
  194. return function_case(color_or_function);
  195. }
  196. }
  197. template<unsigned SamplesPerPixel>
  198. Color EdgeFlagPathRasterizer<SamplesPerPixel>::scanline_color(int scanline, int offset, u8 alpha, auto& color_or_function)
  199. {
  200. auto color = switch_on_color_or_function(
  201. color_or_function, [](Color color) { return color; },
  202. [&](auto& function) {
  203. return function({ offset, scanline });
  204. });
  205. return color.with_alpha(color.alpha() * alpha / 255);
  206. }
  207. template<unsigned SamplesPerPixel>
  208. Detail::Edge* EdgeFlagPathRasterizer<SamplesPerPixel>::plot_edges_for_scanline(int scanline, auto plot_edge, EdgeExtent& edge_extent, Detail::Edge* active_edges)
  209. {
  210. auto y_subpixel = [](int y) {
  211. return y & (SamplesPerPixel - 1);
  212. };
  213. auto* current_edge = active_edges;
  214. Detail::Edge* prev_edge = nullptr;
  215. // First iterate over the edge in the active edge table, these are edges added on earlier scanlines,
  216. // that have not yet reached their end scanline.
  217. while (current_edge) {
  218. int end_scanline = current_edge->max_y / SamplesPerPixel;
  219. if (scanline == end_scanline) {
  220. // This edge ends this scanline.
  221. plot_edge(*current_edge, 0, y_subpixel(current_edge->max_y), edge_extent);
  222. // Remove this edge from the AET
  223. current_edge = current_edge->next_edge;
  224. if (prev_edge)
  225. prev_edge->next_edge = current_edge;
  226. else
  227. active_edges = current_edge;
  228. } else {
  229. // This edge sticks around for a few more scanlines.
  230. plot_edge(*current_edge, 0, SamplesPerPixel, edge_extent);
  231. prev_edge = current_edge;
  232. current_edge = current_edge->next_edge;
  233. }
  234. }
  235. // Next, iterate over new edges for this line. If active_edges was null this also becomes the new
  236. // AET. Edges new will be appended here.
  237. current_edge = m_edge_table[scanline];
  238. while (current_edge) {
  239. int end_scanline = current_edge->max_y / SamplesPerPixel;
  240. if (scanline == end_scanline) {
  241. // This edge will end this scanlines (no need to add to AET).
  242. plot_edge(*current_edge, y_subpixel(current_edge->min_y), y_subpixel(current_edge->max_y), edge_extent);
  243. } else {
  244. // This edge will live on for a few more scanlines.
  245. plot_edge(*current_edge, y_subpixel(current_edge->min_y), SamplesPerPixel, edge_extent);
  246. // Add this edge to the AET
  247. if (prev_edge)
  248. prev_edge->next_edge = current_edge;
  249. else
  250. active_edges = current_edge;
  251. prev_edge = current_edge;
  252. }
  253. current_edge = current_edge->next_edge;
  254. }
  255. if (prev_edge)
  256. prev_edge->next_edge = nullptr;
  257. m_edge_table[scanline] = nullptr;
  258. return active_edges;
  259. }
  260. template<unsigned SamplesPerPixel>
  261. void EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_even_odd_scanline(EdgeExtent edge_extent, auto sample_callback)
  262. {
  263. SampleType sample = 0;
  264. for (int x = edge_extent.min_x; x <= edge_extent.max_x; x += 1) {
  265. sample ^= m_scanline[x];
  266. sample_callback(x, sample);
  267. m_scanline[x] = 0;
  268. }
  269. }
  270. template<unsigned SamplesPerPixel>
  271. void EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_non_zero_scanline(EdgeExtent edge_extent, auto sample_callback)
  272. {
  273. SampleType sample = 0;
  274. WindingCounts sum_winding = {};
  275. for (int x = edge_extent.min_x; x <= edge_extent.max_x; x += 1) {
  276. if (auto edges = m_scanline[x]) {
  277. // We only need to process the windings when we hit some edges.
  278. for (auto y_sub = 0u; y_sub < SamplesPerPixel; y_sub++) {
  279. auto subpixel_bit = 1 << y_sub;
  280. if (edges & subpixel_bit) {
  281. auto winding = m_windings[x].counts[y_sub];
  282. auto previous_winding_count = sum_winding.counts[y_sub];
  283. sum_winding.counts[y_sub] += winding;
  284. // Toggle fill on change to/from zero.
  285. if (bool(previous_winding_count) ^ bool(sum_winding.counts[y_sub]))
  286. sample ^= subpixel_bit;
  287. }
  288. }
  289. }
  290. sample_callback(x, sample);
  291. m_scanline[x] = 0;
  292. m_windings[x] = {};
  293. }
  294. }
  295. template<unsigned SamplesPerPixel>
  296. template<Painter::WindingRule WindingRule, typename Callback>
  297. void EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_scanline(EdgeExtent edge_extent, Callback callback)
  298. {
  299. if constexpr (WindingRule == Painter::WindingRule::EvenOdd)
  300. accumulate_even_odd_scanline(edge_extent, callback);
  301. else
  302. accumulate_non_zero_scanline(edge_extent, callback);
  303. }
  304. template<unsigned SamplesPerPixel>
  305. void EdgeFlagPathRasterizer<SamplesPerPixel>::write_pixel(Painter& painter, int scanline, int offset, SampleType sample, auto& color_or_function)
  306. {
  307. if (!sample)
  308. return;
  309. auto dest = IntPoint { offset, scanline } + m_blit_origin;
  310. if (!m_clip.contains_horizontally(dest.x()))
  311. return;
  312. auto coverage = SubpixelSample::compute_coverage(sample);
  313. auto paint_color = scanline_color(scanline, offset, coverage_to_alpha(coverage), color_or_function);
  314. painter.set_physical_pixel(dest, paint_color, true);
  315. }
  316. template<unsigned SamplesPerPixel>
  317. void EdgeFlagPathRasterizer<SamplesPerPixel>::fast_fill_solid_color_span(Painter& painter, int scanline, int start, int end, Color color)
  318. {
  319. auto dest_y = scanline + m_blit_origin.y();
  320. auto start_x = max(m_clip.left(), start + m_blit_origin.x());
  321. auto end_x = min(m_clip.right() - 1, end + m_blit_origin.x());
  322. if (start_x > end_x)
  323. return;
  324. auto* dest_ptr = painter.target()->scanline(dest_y) + start_x;
  325. fast_u32_fill(dest_ptr, color.value(), end_x - start_x + 1);
  326. }
  327. template<unsigned SamplesPerPixel>
  328. template<Painter::WindingRule WindingRule>
  329. void EdgeFlagPathRasterizer<SamplesPerPixel>::write_scanline(Painter& painter, int scanline, EdgeExtent edge_extent, auto& color_or_function)
  330. {
  331. // Simple case: Handle each pixel individually.
  332. // Used for PaintStyle fills and semi-transparent colors.
  333. auto write_scanline_pixelwise = [&](auto& color_or_function) {
  334. accumulate_scanline<WindingRule>(edge_extent, [&](int x, SampleType sample) {
  335. write_pixel(painter, scanline, x, sample, color_or_function);
  336. });
  337. };
  338. // Fast fill case: Track spans of solid color and set the entire span via a fast_u32_fill().
  339. // Used for opaque colors (i.e. alpha == 255).
  340. auto write_scanline_with_fast_fills = [&](Color color) {
  341. if (color.alpha() != 255)
  342. return write_scanline_pixelwise(color);
  343. constexpr SampleType full_converage = NumericLimits<SampleType>::max();
  344. int full_converage_count = 0;
  345. accumulate_scanline<WindingRule>(edge_extent, [&](int x, SampleType sample) {
  346. if (sample == full_converage) {
  347. full_converage_count++;
  348. return;
  349. } else {
  350. write_pixel(painter, scanline, x, sample, color);
  351. }
  352. if (full_converage_count > 0) {
  353. fast_fill_solid_color_span(painter, scanline, x - full_converage_count, x - 1, color);
  354. full_converage_count = 0;
  355. }
  356. });
  357. if (full_converage_count > 0)
  358. fast_fill_solid_color_span(painter, scanline, edge_extent.max_x - full_converage_count, edge_extent.max_x, color);
  359. };
  360. switch_on_color_or_function(
  361. color_or_function, write_scanline_with_fast_fills, write_scanline_pixelwise);
  362. }
  363. static IntSize path_bounds(Gfx::Path const& path)
  364. {
  365. return enclosing_int_rect(path.bounding_box()).size();
  366. }
  367. // Note: The AntiAliasingPainter and Painter now perform the same antialiasing,
  368. // since it would be harder to turn it off for the standard painter.
  369. // The samples are reduced to 8 for Gfx::Painter though as a "speedy" option.
  370. void Painter::fill_path(Path const& path, Color color, WindingRule winding_rule)
  371. {
  372. EdgeFlagPathRasterizer<8> rasterizer(path_bounds(path));
  373. rasterizer.fill(*this, path, color, winding_rule);
  374. }
  375. void Painter::fill_path(Path const& path, PaintStyle const& paint_style, float opacity, Painter::WindingRule winding_rule)
  376. {
  377. EdgeFlagPathRasterizer<8> rasterizer(path_bounds(path));
  378. rasterizer.fill(*this, path, paint_style, opacity, winding_rule);
  379. }
  380. void AntiAliasingPainter::fill_path(Path const& path, Color color, Painter::WindingRule winding_rule)
  381. {
  382. EdgeFlagPathRasterizer<32> rasterizer(path_bounds(path));
  383. rasterizer.fill(m_underlying_painter, path, color, winding_rule, m_transform.translation());
  384. }
  385. void AntiAliasingPainter::fill_path(Path const& path, PaintStyle const& paint_style, float opacity, Painter::WindingRule winding_rule)
  386. {
  387. EdgeFlagPathRasterizer<32> rasterizer(path_bounds(path));
  388. rasterizer.fill(m_underlying_painter, path, paint_style, opacity, winding_rule, m_transform.translation());
  389. }
  390. template class EdgeFlagPathRasterizer<8>;
  391. template class EdgeFlagPathRasterizer<16>;
  392. template class EdgeFlagPathRasterizer<32>;
  393. }