EdgeFlagPathRasterizer.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. }
  82. template<unsigned SamplesPerPixel>
  83. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill(Painter& painter, Path const& path, Color color, Painter::WindingRule winding_rule, FloatPoint offset)
  84. {
  85. fill_internal(painter, path, color, winding_rule, offset);
  86. }
  87. template<unsigned SamplesPerPixel>
  88. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill(Painter& painter, Path const& path, PaintStyle const& style, float opacity, Painter::WindingRule winding_rule, FloatPoint offset)
  89. {
  90. style.paint(enclosing_int_rect(path.bounding_box()), [&](PaintStyle::SamplerFunction sampler) {
  91. if (opacity == 0.0f)
  92. return;
  93. if (opacity != 1.0f) {
  94. return fill_internal(
  95. painter, path, [=, sampler = move(sampler)](IntPoint point) {
  96. return sampler(point).with_opacity(opacity);
  97. },
  98. winding_rule, offset);
  99. }
  100. return fill_internal(painter, path, move(sampler), winding_rule, offset);
  101. });
  102. }
  103. template<unsigned SamplesPerPixel>
  104. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill_internal(Painter& painter, Path const& path, auto color_or_function, Painter::WindingRule winding_rule, FloatPoint offset)
  105. {
  106. // FIXME: Figure out how painter scaling works here...
  107. VERIFY(painter.scale() == 1);
  108. auto bounding_box = enclosing_int_rect(path.bounding_box().translated(offset));
  109. auto dest_rect = bounding_box.translated(painter.translation());
  110. auto origin = bounding_box.top_left().to_type<float>() - offset;
  111. m_blit_origin = dest_rect.top_left();
  112. m_clip = dest_rect.intersected(painter.clip_rect());
  113. // Only allocate enough to plot the parts of the scanline that could be visible.
  114. // Note: This can't clip the LHS.
  115. auto scanline_length = min(m_size.width(), m_clip.right() - m_blit_origin.x());
  116. if (scanline_length <= 0)
  117. return;
  118. m_scanline.resize(scanline_length);
  119. if (m_clip.is_empty())
  120. return;
  121. auto& lines = path.split_lines();
  122. if (lines.is_empty())
  123. return;
  124. int min_edge_y = 0;
  125. int max_edge_y = 0;
  126. auto top_clip_scanline = m_clip.top() - m_blit_origin.y();
  127. auto bottom_clip_scanline = m_clip.bottom() - m_blit_origin.y() - 1;
  128. auto edges = prepare_edges(lines, SamplesPerPixel, origin, top_clip_scanline, bottom_clip_scanline, min_edge_y, max_edge_y);
  129. if (edges.is_empty())
  130. return;
  131. int min_scanline = min_edge_y / SamplesPerPixel;
  132. int max_scanline = max_edge_y / SamplesPerPixel;
  133. m_edge_table.set_scanline_range(min_scanline, max_scanline);
  134. for (auto& edge : edges) {
  135. // Create a linked-list of edges starting on this scanline:
  136. int start_scanline = edge.min_y / SamplesPerPixel;
  137. edge.next_edge = m_edge_table[start_scanline];
  138. m_edge_table[start_scanline] = &edge;
  139. }
  140. auto empty_edge_extent = [&] {
  141. return EdgeExtent { m_size.width() - 1, 0 };
  142. };
  143. auto for_each_sample = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, EdgeExtent& edge_extent, auto callback) {
  144. for (int y = start_subpixel_y; y < end_subpixel_y; y++) {
  145. auto xi = static_cast<int>(edge.x + SubpixelSample::nrooks_subpixel_offsets[y]);
  146. if (xi >= 0 && size_t(xi) < m_scanline.size()) [[likely]] {
  147. SampleType sample = 1 << y;
  148. callback(xi, y, sample);
  149. } else if (xi < 0) {
  150. if (edge.dxdy <= 0)
  151. return;
  152. } else {
  153. xi = m_scanline.size() - 1;
  154. }
  155. edge.x += edge.dxdy;
  156. edge_extent.min_x = min(edge_extent.min_x, xi);
  157. edge_extent.max_x = max(edge_extent.max_x, xi);
  158. }
  159. };
  160. Detail::Edge* active_edges = nullptr;
  161. if (winding_rule == Painter::WindingRule::EvenOdd) {
  162. auto plot_edge = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, EdgeExtent& edge_extent) {
  163. for_each_sample(edge, start_subpixel_y, end_subpixel_y, edge_extent, [&](int xi, int, SampleType sample) {
  164. m_scanline[xi] ^= sample;
  165. });
  166. };
  167. for (int scanline = min_scanline; scanline <= max_scanline; scanline++) {
  168. auto edge_extent = empty_edge_extent();
  169. active_edges = plot_edges_for_scanline(scanline, plot_edge, edge_extent, active_edges);
  170. write_scanline<Painter::WindingRule::EvenOdd>(painter, scanline, edge_extent, color_or_function);
  171. }
  172. } else {
  173. VERIFY(winding_rule == Painter::WindingRule::Nonzero);
  174. // Only allocate the winding buffer if needed.
  175. // NOTE: non-zero fills are a fair bit less efficient. So if you can do an even-odd fill do that :^)
  176. if (m_windings.is_empty())
  177. m_windings.resize(m_scanline.size());
  178. auto plot_edge = [&](Detail::Edge& edge, int start_subpixel_y, int end_subpixel_y, EdgeExtent& edge_extent) {
  179. for_each_sample(edge, start_subpixel_y, end_subpixel_y, edge_extent, [&](int xi, int y, SampleType sample) {
  180. m_scanline[xi] |= sample;
  181. m_windings[xi].counts[y] += edge.winding;
  182. });
  183. };
  184. for (int scanline = min_scanline; scanline <= max_scanline; scanline++) {
  185. auto edge_extent = empty_edge_extent();
  186. active_edges = plot_edges_for_scanline(scanline, plot_edge, edge_extent, active_edges);
  187. write_scanline<Painter::WindingRule::Nonzero>(painter, scanline, edge_extent, color_or_function);
  188. }
  189. }
  190. }
  191. ALWAYS_INLINE static auto switch_on_color_or_function(auto& color_or_function, auto color_case, auto function_case)
  192. {
  193. using ColorOrFunction = decltype(color_or_function);
  194. constexpr bool has_constant_color = IsSame<RemoveCVReference<ColorOrFunction>, Color>;
  195. if constexpr (has_constant_color) {
  196. return color_case(color_or_function);
  197. } else {
  198. return function_case(color_or_function);
  199. }
  200. }
  201. template<unsigned SamplesPerPixel>
  202. Color EdgeFlagPathRasterizer<SamplesPerPixel>::scanline_color(int scanline, int offset, u8 alpha, auto& color_or_function)
  203. {
  204. auto color = switch_on_color_or_function(
  205. color_or_function, [](Color color) { return color; },
  206. [&](auto& function) {
  207. return function({ offset, scanline });
  208. });
  209. if (color.alpha() == 255)
  210. return color.with_alpha(alpha);
  211. return color.with_alpha(color.alpha() * alpha / 255);
  212. }
  213. template<unsigned SamplesPerPixel>
  214. __attribute__((hot)) Detail::Edge* EdgeFlagPathRasterizer<SamplesPerPixel>::plot_edges_for_scanline(int scanline, auto plot_edge, EdgeExtent& edge_extent, Detail::Edge* active_edges)
  215. {
  216. auto y_subpixel = [](int y) {
  217. return y & (SamplesPerPixel - 1);
  218. };
  219. auto* current_edge = active_edges;
  220. Detail::Edge* prev_edge = nullptr;
  221. // First iterate over the edge in the active edge table, these are edges added on earlier scanlines,
  222. // that have not yet reached their end scanline.
  223. while (current_edge) {
  224. int end_scanline = current_edge->max_y / SamplesPerPixel;
  225. if (scanline == end_scanline) {
  226. // This edge ends this scanline.
  227. plot_edge(*current_edge, 0, y_subpixel(current_edge->max_y), edge_extent);
  228. // Remove this edge from the AET
  229. current_edge = current_edge->next_edge;
  230. if (prev_edge)
  231. prev_edge->next_edge = current_edge;
  232. else
  233. active_edges = current_edge;
  234. } else {
  235. // This edge sticks around for a few more scanlines.
  236. plot_edge(*current_edge, 0, SamplesPerPixel, edge_extent);
  237. prev_edge = current_edge;
  238. current_edge = current_edge->next_edge;
  239. }
  240. }
  241. // Next, iterate over new edges for this line. If active_edges was null this also becomes the new
  242. // AET. Edges new will be appended here.
  243. current_edge = m_edge_table[scanline];
  244. while (current_edge) {
  245. int end_scanline = current_edge->max_y / SamplesPerPixel;
  246. if (scanline == end_scanline) {
  247. // This edge will end this scanlines (no need to add to AET).
  248. plot_edge(*current_edge, y_subpixel(current_edge->min_y), y_subpixel(current_edge->max_y), edge_extent);
  249. } else {
  250. // This edge will live on for a few more scanlines.
  251. plot_edge(*current_edge, y_subpixel(current_edge->min_y), SamplesPerPixel, edge_extent);
  252. // Add this edge to the AET
  253. if (prev_edge)
  254. prev_edge->next_edge = current_edge;
  255. else
  256. active_edges = current_edge;
  257. prev_edge = current_edge;
  258. }
  259. current_edge = current_edge->next_edge;
  260. }
  261. if (prev_edge)
  262. prev_edge->next_edge = nullptr;
  263. m_edge_table[scanline] = nullptr;
  264. return active_edges;
  265. }
  266. template<unsigned SamplesPerPixel>
  267. auto EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_even_odd_scanline(EdgeExtent edge_extent, auto init, auto sample_callback)
  268. {
  269. SampleType sample = init;
  270. for (int x = edge_extent.min_x; x <= edge_extent.max_x; x += 1) {
  271. sample ^= m_scanline[x];
  272. sample_callback(x, sample);
  273. m_scanline[x] = 0;
  274. }
  275. return sample;
  276. }
  277. template<unsigned SamplesPerPixel>
  278. auto EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_non_zero_scanline(EdgeExtent edge_extent, auto init, auto sample_callback)
  279. {
  280. NonZeroAcc acc = init;
  281. for (int x = edge_extent.min_x; x <= edge_extent.max_x; x += 1) {
  282. if (auto edges = m_scanline[x]) {
  283. // We only need to process the windings when we hit some edges.
  284. for (auto y_sub = 0u; y_sub < SamplesPerPixel; y_sub++) {
  285. auto subpixel_bit = 1 << y_sub;
  286. if (edges & subpixel_bit) {
  287. auto winding = m_windings[x].counts[y_sub];
  288. auto previous_winding_count = acc.winding.counts[y_sub];
  289. acc.winding.counts[y_sub] += winding;
  290. // Toggle fill on change to/from zero.
  291. if (bool(previous_winding_count) ^ bool(acc.winding.counts[y_sub]))
  292. acc.sample ^= subpixel_bit;
  293. }
  294. }
  295. }
  296. sample_callback(x, acc.sample);
  297. m_scanline[x] = 0;
  298. m_windings[x] = {};
  299. }
  300. return acc;
  301. }
  302. template<unsigned SamplesPerPixel>
  303. template<Painter::WindingRule WindingRule, typename Callback>
  304. auto EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_scanline(EdgeExtent edge_extent, auto init, Callback callback)
  305. {
  306. if constexpr (WindingRule == Painter::WindingRule::EvenOdd)
  307. return accumulate_even_odd_scanline(edge_extent, init, callback);
  308. else
  309. return accumulate_non_zero_scanline(edge_extent, init, callback);
  310. }
  311. template<unsigned SamplesPerPixel>
  312. void EdgeFlagPathRasterizer<SamplesPerPixel>::write_pixel(BitmapFormat format, ARGB32* scanline_ptr, int scanline, int offset, SampleType sample, auto& color_or_function)
  313. {
  314. if (!sample)
  315. return;
  316. auto dest_x = offset + m_blit_origin.x();
  317. auto coverage = SubpixelSample::compute_coverage(sample);
  318. auto paint_color = scanline_color(scanline, offset, coverage_to_alpha(coverage), color_or_function);
  319. scanline_ptr[dest_x] = color_for_format(format, scanline_ptr[dest_x]).blend(paint_color).value();
  320. }
  321. template<unsigned SamplesPerPixel>
  322. void EdgeFlagPathRasterizer<SamplesPerPixel>::fast_fill_solid_color_span(ARGB32* scanline_ptr, int start, int end, Color color)
  323. {
  324. auto start_x = start + m_blit_origin.x();
  325. auto end_x = end + m_blit_origin.x();
  326. fast_u32_fill(scanline_ptr + start_x, color.value(), end_x - start_x + 1);
  327. }
  328. template<unsigned SamplesPerPixel>
  329. template<Painter::WindingRule WindingRule>
  330. FLATTEN __attribute__((hot)) void EdgeFlagPathRasterizer<SamplesPerPixel>::write_scanline(Painter& painter, int scanline, EdgeExtent edge_extent, auto& color_or_function)
  331. {
  332. // Handle scanline clipping.
  333. auto left_clip = m_clip.left() - m_blit_origin.x();
  334. EdgeExtent clipped_extent { max(left_clip, edge_extent.min_x), edge_extent.max_x };
  335. if (clipped_extent.min_x > clipped_extent.max_x) {
  336. // Fully clipped. Unfortunately we still need to zero the scanline data.
  337. edge_extent.memset_extent(m_scanline.data(), 0);
  338. if constexpr (WindingRule == Painter::WindingRule::Nonzero)
  339. edge_extent.memset_extent(m_windings.data(), 0);
  340. return;
  341. }
  342. // Accumulate non-visible section (without plotting pixels).
  343. auto acc = accumulate_scanline<WindingRule>(EdgeExtent { edge_extent.min_x, left_clip - 1 }, initial_acc<WindingRule>(), [](int, SampleType) {
  344. // Do nothing!
  345. });
  346. // Get pointer to current scanline pixels.
  347. auto dest_format = painter.target()->format();
  348. auto dest_ptr = painter.target()->scanline(scanline + m_blit_origin.y());
  349. // Simple case: Handle each pixel individually.
  350. // Used for PaintStyle fills and semi-transparent colors.
  351. auto write_scanline_pixelwise = [&](auto& color_or_function) {
  352. accumulate_scanline<WindingRule>(clipped_extent, acc, [&](int x, SampleType sample) {
  353. write_pixel(dest_format, dest_ptr, scanline, x, sample, color_or_function);
  354. });
  355. };
  356. // Fast fill case: Track spans of solid color and set the entire span via a fast_u32_fill().
  357. // Used for opaque colors (i.e. alpha == 255).
  358. auto write_scanline_with_fast_fills = [&](Color color) {
  359. if (color.alpha() != 255)
  360. return write_scanline_pixelwise(color);
  361. constexpr SampleType full_converage = NumericLimits<SampleType>::max();
  362. int full_converage_count = 0;
  363. accumulate_scanline<WindingRule>(clipped_extent, acc, [&](int x, SampleType sample) {
  364. if (sample == full_converage) {
  365. full_converage_count++;
  366. return;
  367. } else {
  368. write_pixel(dest_format, dest_ptr, scanline, x, sample, color);
  369. }
  370. if (full_converage_count > 0) {
  371. fast_fill_solid_color_span(dest_ptr, x - full_converage_count, x - 1, color);
  372. full_converage_count = 0;
  373. }
  374. });
  375. if (full_converage_count > 0)
  376. fast_fill_solid_color_span(dest_ptr, clipped_extent.max_x - full_converage_count + 1, clipped_extent.max_x, color);
  377. };
  378. switch_on_color_or_function(
  379. color_or_function, write_scanline_with_fast_fills, write_scanline_pixelwise);
  380. }
  381. static IntSize path_bounds(Gfx::Path const& path)
  382. {
  383. return enclosing_int_rect(path.bounding_box()).size();
  384. }
  385. // Note: The AntiAliasingPainter and Painter now perform the same antialiasing,
  386. // since it would be harder to turn it off for the standard painter.
  387. // The samples are reduced to 8 for Gfx::Painter though as a "speedy" option.
  388. void Painter::fill_path(Path const& path, Color color, WindingRule winding_rule)
  389. {
  390. EdgeFlagPathRasterizer<8> rasterizer(path_bounds(path));
  391. rasterizer.fill(*this, path, color, winding_rule);
  392. }
  393. void Painter::fill_path(Path const& path, PaintStyle const& paint_style, float opacity, Painter::WindingRule winding_rule)
  394. {
  395. EdgeFlagPathRasterizer<8> rasterizer(path_bounds(path));
  396. rasterizer.fill(*this, path, paint_style, opacity, winding_rule);
  397. }
  398. void AntiAliasingPainter::fill_path(Path const& path, Color color, Painter::WindingRule winding_rule)
  399. {
  400. EdgeFlagPathRasterizer<32> rasterizer(path_bounds(path));
  401. rasterizer.fill(m_underlying_painter, path, color, winding_rule, m_transform.translation());
  402. }
  403. void AntiAliasingPainter::fill_path(Path const& path, PaintStyle const& paint_style, float opacity, Painter::WindingRule winding_rule)
  404. {
  405. EdgeFlagPathRasterizer<32> rasterizer(path_bounds(path));
  406. rasterizer.fill(m_underlying_painter, path, paint_style, opacity, winding_rule, m_transform.translation());
  407. }
  408. template class EdgeFlagPathRasterizer<8>;
  409. template class EdgeFlagPathRasterizer<16>;
  410. template class EdgeFlagPathRasterizer<32>;
  411. }