EdgeFlagPathRasterizer.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*
  2. * Copyright (c) 2023-2024, MacDue <macdue@dueutil.tech>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Memory.h>
  7. #include <AK/Types.h>
  8. #include <LibGfx/AntiAliasingPainter.h>
  9. #include <LibGfx/DeprecatedPainter.h>
  10. #include <LibGfx/EdgeFlagPathRasterizer.h>
  11. #if defined(AK_COMPILER_GCC)
  12. # pragma GCC optimize("O3")
  13. #endif
  14. // This an implementation of edge-flag scanline AA, as described in:
  15. // https://mlab.taik.fi/~kkallio/antialiasing/EdgeFlagAA.pdf
  16. namespace Gfx {
  17. static Vector<Detail::Edge> prepare_edges(ReadonlySpan<FloatLine> lines, unsigned samples_per_pixel, FloatPoint origin,
  18. int top_clip_scanline, int bottom_clip_scanline, int& min_edge_y, int& max_edge_y)
  19. {
  20. Vector<Detail::Edge> edges;
  21. edges.ensure_capacity(lines.size());
  22. // The first visible y value.
  23. auto top_clip = top_clip_scanline * int(samples_per_pixel);
  24. // The last visible y value.
  25. auto bottom_clip = (bottom_clip_scanline + 1) * int(samples_per_pixel);
  26. min_edge_y = bottom_clip;
  27. max_edge_y = top_clip;
  28. for (auto& line : lines) {
  29. auto p0 = line.a() - origin;
  30. auto p1 = line.b() - origin;
  31. p0.scale_by(1, samples_per_pixel);
  32. p1.scale_by(1, samples_per_pixel);
  33. i8 winding = -1;
  34. if (p0.y() > p1.y()) {
  35. swap(p0, p1);
  36. } else {
  37. winding = 1;
  38. }
  39. if (p0.y() == p1.y())
  40. continue;
  41. auto min_y = static_cast<int>(p0.y());
  42. auto max_y = static_cast<int>(p1.y());
  43. // Clip edges that start below the bottom clip...
  44. if (min_y > bottom_clip)
  45. continue;
  46. // ...and edges that end before the top clip.
  47. if (max_y < top_clip)
  48. continue;
  49. auto start_x = p0.x();
  50. auto end_x = p1.x();
  51. auto dx = end_x - start_x;
  52. auto dy = max_y - min_y;
  53. if (dy == 0)
  54. continue;
  55. auto dxdy = dx / dy;
  56. // Trim off the non-visible portions of the edge.
  57. if (min_y < top_clip) {
  58. start_x += dxdy * (top_clip - min_y);
  59. min_y = top_clip;
  60. }
  61. if (max_y > bottom_clip)
  62. max_y = bottom_clip;
  63. min_edge_y = min(min_y, min_edge_y);
  64. max_edge_y = max(max_y, max_edge_y);
  65. edges.unchecked_append(Detail::Edge {
  66. start_x,
  67. min_y,
  68. max_y,
  69. dxdy,
  70. winding,
  71. nullptr });
  72. }
  73. return edges;
  74. }
  75. template<unsigned SamplesPerPixel>
  76. EdgeFlagPathRasterizer<SamplesPerPixel>::EdgeFlagPathRasterizer(IntSize size)
  77. : m_size(size.width() + 1, size.height() + 1)
  78. {
  79. }
  80. template<unsigned SamplesPerPixel>
  81. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill(DeprecatedPainter& painter, DeprecatedPath const& path, Color color, WindingRule winding_rule, FloatPoint offset)
  82. {
  83. fill_internal(painter, path, color, winding_rule, offset);
  84. }
  85. template<unsigned SamplesPerPixel>
  86. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill(DeprecatedPainter& painter, DeprecatedPath const& path, PaintStyle const& style, float opacity, WindingRule winding_rule, FloatPoint offset)
  87. {
  88. style.paint(enclosing_int_rect(path.bounding_box()), [&](PaintStyle::SamplerFunction sampler) {
  89. if (opacity == 0.0f)
  90. return;
  91. if (opacity != 1.0f) {
  92. return fill_internal(
  93. painter, path, [=, sampler = move(sampler)](IntPoint point) {
  94. return sampler(point).with_opacity(opacity);
  95. },
  96. winding_rule, offset);
  97. }
  98. return fill_internal(painter, path, move(sampler), winding_rule, offset);
  99. });
  100. }
  101. template<unsigned SamplesPerPixel>
  102. void EdgeFlagPathRasterizer<SamplesPerPixel>::fill_internal(DeprecatedPainter& painter, DeprecatedPath const& path, auto color_or_function, WindingRule winding_rule, FloatPoint offset)
  103. {
  104. auto bounding_box = enclosing_int_rect(path.bounding_box().translated(offset));
  105. auto dest_rect = bounding_box.translated(painter.translation());
  106. auto origin = bounding_box.top_left().to_type<float>() - offset;
  107. m_blit_origin = dest_rect.top_left();
  108. m_clip = dest_rect.intersected(painter.clip_rect());
  109. // Only allocate enough to plot the parts of the scanline that could be visible.
  110. // Note: This can't clip the LHS.
  111. auto scanline_length = min(m_size.width(), m_clip.right() - m_blit_origin.x());
  112. if (scanline_length <= 0)
  113. return;
  114. m_scanline.resize(scanline_length);
  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()) [[likely]] {
  143. SampleType sample = 1 << y;
  144. callback(xi, y, sample);
  145. } else if (xi < 0) {
  146. if (edge.dxdy <= 0)
  147. return;
  148. } else {
  149. xi = m_scanline.size() - 1;
  150. }
  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 == 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<WindingRule::EvenOdd>(painter, scanline, edge_extent, color_or_function);
  167. }
  168. } else {
  169. VERIFY(winding_rule == 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_scanline.size());
  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<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. if (color.alpha() == 255)
  206. return color.with_alpha(alpha, AlphaType::Premultiplied);
  207. return color.with_alpha(color.alpha() * alpha / 255, AlphaType::Premultiplied);
  208. }
  209. template<unsigned SamplesPerPixel>
  210. __attribute__((hot)) Detail::Edge* EdgeFlagPathRasterizer<SamplesPerPixel>::plot_edges_for_scanline(int scanline, auto plot_edge, EdgeExtent& edge_extent, Detail::Edge* active_edges)
  211. {
  212. auto y_subpixel = [](int y) {
  213. return y & (SamplesPerPixel - 1);
  214. };
  215. auto* current_edge = active_edges;
  216. Detail::Edge* prev_edge = nullptr;
  217. // First iterate over the edge in the active edge table, these are edges added on earlier scanlines,
  218. // that have not yet reached their end scanline.
  219. while (current_edge) {
  220. int end_scanline = current_edge->max_y / SamplesPerPixel;
  221. if (scanline == end_scanline) {
  222. // This edge ends this scanline.
  223. plot_edge(*current_edge, 0, y_subpixel(current_edge->max_y), edge_extent);
  224. // Remove this edge from the AET
  225. current_edge = current_edge->next_edge;
  226. if (prev_edge)
  227. prev_edge->next_edge = current_edge;
  228. else
  229. active_edges = current_edge;
  230. } else {
  231. // This edge sticks around for a few more scanlines.
  232. plot_edge(*current_edge, 0, SamplesPerPixel, edge_extent);
  233. prev_edge = current_edge;
  234. current_edge = current_edge->next_edge;
  235. }
  236. }
  237. // Next, iterate over new edges for this line. If active_edges was null this also becomes the new
  238. // AET. Edges new will be appended here.
  239. current_edge = m_edge_table[scanline];
  240. while (current_edge) {
  241. int end_scanline = current_edge->max_y / SamplesPerPixel;
  242. if (scanline == end_scanline) {
  243. // This edge will end this scanlines (no need to add to AET).
  244. plot_edge(*current_edge, y_subpixel(current_edge->min_y), y_subpixel(current_edge->max_y), edge_extent);
  245. } else {
  246. // This edge will live on for a few more scanlines.
  247. plot_edge(*current_edge, y_subpixel(current_edge->min_y), SamplesPerPixel, edge_extent);
  248. // Add this edge to the AET
  249. if (prev_edge)
  250. prev_edge->next_edge = current_edge;
  251. else
  252. active_edges = current_edge;
  253. prev_edge = current_edge;
  254. }
  255. current_edge = current_edge->next_edge;
  256. }
  257. if (prev_edge)
  258. prev_edge->next_edge = nullptr;
  259. m_edge_table[scanline] = nullptr;
  260. return active_edges;
  261. }
  262. template<unsigned SamplesPerPixel>
  263. auto EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_even_odd_scanline(EdgeExtent edge_extent, auto init, auto sample_callback)
  264. {
  265. SampleType sample = init;
  266. VERIFY(edge_extent.min_x >= 0);
  267. VERIFY(edge_extent.max_x < static_cast<int>(m_scanline.size()));
  268. for (int x = edge_extent.min_x; x <= edge_extent.max_x; x++) {
  269. sample ^= m_scanline.data()[x];
  270. sample_callback(x, sample);
  271. m_scanline.data()[x] = 0;
  272. }
  273. return sample;
  274. }
  275. template<unsigned SamplesPerPixel>
  276. auto EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_non_zero_scanline(EdgeExtent edge_extent, auto init, auto sample_callback)
  277. {
  278. NonZeroAcc acc = init;
  279. VERIFY(edge_extent.min_x >= 0);
  280. VERIFY(edge_extent.max_x < static_cast<int>(m_scanline.size()));
  281. for (int x = edge_extent.min_x; x <= edge_extent.max_x; x++) {
  282. if (auto edges = m_scanline.data()[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.data()[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.data()[x] = 0;
  298. m_windings.data()[x] = {};
  299. }
  300. return acc;
  301. }
  302. template<unsigned SamplesPerPixel>
  303. template<WindingRule WindingRule, typename Callback>
  304. auto EdgeFlagPathRasterizer<SamplesPerPixel>::accumulate_scanline(EdgeExtent edge_extent, auto init, Callback callback)
  305. {
  306. if constexpr (WindingRule == 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<WindingRule WindingRule>
  330. FLATTEN __attribute__((hot)) void EdgeFlagPathRasterizer<SamplesPerPixel>::write_scanline(DeprecatedPainter& 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 == 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_coverage = NumericLimits<SampleType>::max();
  362. int full_coverage_count = 0;
  363. accumulate_scanline<WindingRule>(clipped_extent, acc, [&](int x, SampleType sample) {
  364. if (sample == full_coverage) {
  365. full_coverage_count++;
  366. return;
  367. } else {
  368. write_pixel(dest_format, dest_ptr, scanline, x, sample, color);
  369. }
  370. if (full_coverage_count > 0) {
  371. fast_fill_solid_color_span(dest_ptr, x - full_coverage_count, x - 1, color);
  372. full_coverage_count = 0;
  373. }
  374. });
  375. if (full_coverage_count > 0)
  376. fast_fill_solid_color_span(dest_ptr, clipped_extent.max_x - full_coverage_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::DeprecatedPath const& path)
  382. {
  383. return enclosing_int_rect(path.bounding_box()).size();
  384. }
  385. // Note: The AntiAliasingPainter and DeprecatedPainter 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::DeprecatedPainter though as a "speedy" option.
  388. void DeprecatedPainter::fill_path(DeprecatedPath 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 DeprecatedPainter::fill_path(DeprecatedPath const& path, PaintStyle const& paint_style, float opacity, 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(DeprecatedPath const& path, Color color, WindingRule winding_rule)
  399. {
  400. EdgeFlagPathRasterizer<32> rasterizer(path_bounds(path));
  401. rasterizer.fill(m_underlying_painter, path, color, winding_rule, {});
  402. }
  403. void AntiAliasingPainter::fill_path(DeprecatedPath const& path, PaintStyle const& paint_style, float opacity, WindingRule winding_rule)
  404. {
  405. EdgeFlagPathRasterizer<32> rasterizer(path_bounds(path));
  406. rasterizer.fill(m_underlying_painter, path, paint_style, opacity, winding_rule, {});
  407. }
  408. template class EdgeFlagPathRasterizer<8>;
  409. template class EdgeFlagPathRasterizer<16>;
  410. template class EdgeFlagPathRasterizer<32>;
  411. }