EdgeFlagPathRasterizer.cpp 18 KB

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