GradientPainting.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. /*
  2. * Copyright (c) 2022-2023, MacDue <macdue@dueutil.tech>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Math.h>
  7. #include <LibGfx/Gradients.h>
  8. #include <LibGfx/PaintStyle.h>
  9. #include <LibGfx/Painter.h>
  10. #if defined(AK_COMPILER_GCC)
  11. # pragma GCC optimize("O3")
  12. #endif
  13. namespace Gfx {
  14. // Note: This file implements the CSS/Canvas gradients for LibWeb according to the spec.
  15. // Please do not make ad-hoc changes that may break spec compliance!
  16. static float color_stop_step(ColorStop const& previous_stop, ColorStop const& next_stop, float position)
  17. {
  18. if (position < previous_stop.position)
  19. return 0;
  20. if (position > next_stop.position)
  21. return 1;
  22. // For any given point between the two color stops,
  23. // determine the point’s location as a percentage of the distance between the two color stops.
  24. // Let this percentage be P.
  25. auto stop_length = next_stop.position - previous_stop.position;
  26. // FIXME: Avoids NaNs... Still not quite correct?
  27. if (stop_length <= 0)
  28. return 1;
  29. auto p = (position - previous_stop.position) / stop_length;
  30. if (!next_stop.transition_hint.has_value())
  31. return p;
  32. if (*next_stop.transition_hint >= 1)
  33. return 0;
  34. if (*next_stop.transition_hint <= 0)
  35. return 1;
  36. // Let C, the color weighting at that point, be equal to P^(logH(.5)).
  37. auto c = AK::pow(p, AK::log<float>(0.5) / AK::log(*next_stop.transition_hint));
  38. // The color at that point is then a linear blend between the colors of the two color stops,
  39. // blending (1 - C) of the first stop and C of the second stop.
  40. return c;
  41. }
  42. enum class UsePremultipliedAlpha {
  43. Yes,
  44. No
  45. };
  46. class GradientLine {
  47. public:
  48. GradientLine(int gradient_length, ReadonlySpan<ColorStop> color_stops, Optional<float> repeat_length, UsePremultipliedAlpha use_premultiplied_alpha = UsePremultipliedAlpha::Yes)
  49. : m_repeat_mode(repeat_length.has_value() ? RepeatMode::Repeat : RepeatMode::None)
  50. , m_start_offset(round_to<int>((repeating() ? color_stops.first().position : 0.0f) * gradient_length))
  51. , m_color_stops(color_stops)
  52. , m_use_premultiplied_alpha(use_premultiplied_alpha)
  53. {
  54. // Avoid generating excessive amounts of colors when the not enough shades to fill that length.
  55. auto necessary_length = min<int>((color_stops.size() - 1) * 255, gradient_length);
  56. m_sample_scale = float(necessary_length) / gradient_length;
  57. // Note: color_count will be < gradient_length for repeating gradients.
  58. auto color_count = round_to<int>(repeat_length.value_or(1.0f) * necessary_length);
  59. m_gradient_line_colors.resize(color_count);
  60. for (int loc = 0; loc < color_count; loc++) {
  61. auto relative_loc = float(loc + m_start_offset) / necessary_length;
  62. Color gradient_color = color_blend(color_stops[0].color, color_stops[1].color,
  63. color_stop_step(color_stops[0], color_stops[1], relative_loc));
  64. for (size_t i = 1; i < color_stops.size() - 1; i++) {
  65. gradient_color = color_blend(gradient_color, color_stops[i + 1].color,
  66. color_stop_step(color_stops[i], color_stops[i + 1], relative_loc));
  67. }
  68. m_gradient_line_colors[loc] = gradient_color;
  69. if (gradient_color.alpha() < 255)
  70. m_requires_blending = true;
  71. }
  72. }
  73. Color color_blend(Color a, Color b, float amount) const
  74. {
  75. // Note: color.mixed_with() performs premultiplied alpha mixing when necessary as defined in:
  76. // https://drafts.csswg.org/css-images/#coloring-gradient-line
  77. if (m_use_premultiplied_alpha == UsePremultipliedAlpha::Yes)
  78. return a.mixed_with(b, amount);
  79. return a.interpolate(b, amount);
  80. }
  81. Color get_color(i64 index) const
  82. {
  83. if (index < 0)
  84. return m_color_stops.first().color;
  85. if (index >= static_cast<i64>(m_gradient_line_colors.size()))
  86. return m_color_stops.last().color;
  87. return m_gradient_line_colors[index];
  88. }
  89. Color sample_color(float loc) const
  90. {
  91. if (!isfinite(loc))
  92. return Color();
  93. if (m_sample_scale != 1.0f)
  94. loc *= m_sample_scale;
  95. auto repeat_wrap_if_required = [&](i64 loc) {
  96. if (m_repeat_mode != RepeatMode::None) {
  97. auto current_loc = loc + m_start_offset;
  98. auto gradient_len = static_cast<i64>(m_gradient_line_colors.size());
  99. if (m_repeat_mode == RepeatMode::Repeat) {
  100. auto color_loc = current_loc % gradient_len;
  101. return color_loc < 0 ? gradient_len + color_loc : color_loc;
  102. } else if (m_repeat_mode == RepeatMode::Reflect) {
  103. auto color_loc = AK::abs(current_loc % gradient_len);
  104. auto repeats = current_loc / gradient_len;
  105. return (repeats & 1) ? gradient_len - color_loc : color_loc;
  106. }
  107. }
  108. return loc;
  109. };
  110. auto int_loc = static_cast<i64>(floor(loc));
  111. auto blend = loc - int_loc;
  112. auto color = get_color(repeat_wrap_if_required(int_loc));
  113. // Blend between the two neighboring colors (this fixes some nasty aliasing issues at small angles)
  114. if (blend >= 0.004f)
  115. color = color_blend(color, get_color(repeat_wrap_if_required(int_loc + 1)), blend);
  116. return color;
  117. }
  118. void paint_into_physical_rect(Painter& painter, IntRect rect, auto location_transform)
  119. {
  120. auto clipped_rect = rect.intersected(painter.clip_rect() * painter.scale());
  121. auto start_offset = clipped_rect.location() - rect.location();
  122. for (int y = 0; y < clipped_rect.height(); y++) {
  123. for (int x = 0; x < clipped_rect.width(); x++) {
  124. auto pixel = sample_color(location_transform(x + start_offset.x(), y + start_offset.y()));
  125. painter.set_physical_pixel(clipped_rect.location().translated(x, y), pixel, m_requires_blending);
  126. }
  127. }
  128. }
  129. bool repeating() const
  130. {
  131. return m_repeat_mode != RepeatMode::None;
  132. }
  133. enum class RepeatMode {
  134. None,
  135. Repeat,
  136. Reflect
  137. };
  138. void set_repeat_mode(RepeatMode repeat_mode)
  139. {
  140. // Note: A gradient can be set to repeating without a repeat length.
  141. // The repeat length is used for CSS gradients but not for SVG gradients.
  142. m_repeat_mode = repeat_mode;
  143. }
  144. private:
  145. RepeatMode m_repeat_mode { RepeatMode::None };
  146. int m_start_offset { 0 };
  147. float m_sample_scale { 1 };
  148. ReadonlySpan<ColorStop> m_color_stops {};
  149. UsePremultipliedAlpha m_use_premultiplied_alpha { UsePremultipliedAlpha::Yes };
  150. Vector<Color, 1024> m_gradient_line_colors;
  151. bool m_requires_blending = false;
  152. };
  153. template<typename TransformFunction>
  154. struct Gradient {
  155. Gradient(GradientLine gradient_line, TransformFunction transform_function)
  156. : m_gradient_line(move(gradient_line))
  157. , m_transform_function(move(transform_function))
  158. {
  159. }
  160. void paint(Painter& painter, IntRect rect)
  161. {
  162. m_gradient_line.paint_into_physical_rect(painter, rect, m_transform_function);
  163. }
  164. template<typename CoordinateType = int>
  165. auto sample_function()
  166. {
  167. return [this](Point<CoordinateType> point) {
  168. return m_gradient_line.sample_color(m_transform_function(point.x(), point.y()));
  169. };
  170. }
  171. GradientLine& gradient_line()
  172. {
  173. return m_gradient_line;
  174. }
  175. private:
  176. GradientLine m_gradient_line;
  177. TransformFunction m_transform_function;
  178. };
  179. static auto create_linear_gradient(IntRect const& physical_rect, ReadonlySpan<ColorStop> color_stops, float angle, Optional<float> repeat_length)
  180. {
  181. float normalized_angle = normalized_gradient_angle_radians(angle);
  182. float sin_angle, cos_angle;
  183. AK::sincos(normalized_angle, sin_angle, cos_angle);
  184. // Full length of the gradient
  185. auto gradient_length = calculate_gradient_length(physical_rect.size(), sin_angle, cos_angle);
  186. IntPoint offset { cos_angle * (gradient_length / 2), sin_angle * (gradient_length / 2) };
  187. auto center = physical_rect.translated(-physical_rect.location()).center();
  188. auto start_point = center - offset;
  189. // Rotate gradient line to be horizontal
  190. auto rotated_start_point_x = start_point.x() * cos_angle - start_point.y() * -sin_angle;
  191. GradientLine gradient_line(gradient_length, color_stops, repeat_length);
  192. return Gradient {
  193. move(gradient_line),
  194. [=](int x, int y) {
  195. return (x * cos_angle - (physical_rect.height() - y) * -sin_angle) - rotated_start_point_x;
  196. }
  197. };
  198. }
  199. static auto create_conic_gradient(ReadonlySpan<ColorStop> color_stops, FloatPoint center_point, float start_angle, Optional<float> repeat_length, UsePremultipliedAlpha use_premultiplied_alpha = UsePremultipliedAlpha::Yes)
  200. {
  201. // FIXME: Do we need/want sub-degree accuracy for the gradient line?
  202. GradientLine gradient_line(360, color_stops, repeat_length, use_premultiplied_alpha);
  203. float normalized_start_angle = (360.0f - start_angle) + 90.0f;
  204. // The flooring can make gradients that want soft edges look worse, so only floor if we have hard edges.
  205. // Which makes sure the hard edge stay hard edges :^)
  206. bool should_floor_angles = false;
  207. for (size_t i = 0; i < color_stops.size() - 1; i++) {
  208. if (color_stops[i + 1].position - color_stops[i].position <= 0.01f) {
  209. should_floor_angles = true;
  210. break;
  211. }
  212. }
  213. return Gradient {
  214. move(gradient_line),
  215. [=](int x, int y) {
  216. auto point = FloatPoint { x, y } - center_point;
  217. // FIXME: We could probably get away with some approximation here:
  218. auto loc = fmod((AK::to_degrees(AK::atan2(point.y(), point.x())) + 360.0f + normalized_start_angle), 360.0f);
  219. return should_floor_angles ? floor(loc) : loc;
  220. }
  221. };
  222. }
  223. static auto create_radial_gradient(IntRect const& physical_rect, ReadonlySpan<ColorStop> color_stops, IntPoint center, IntSize size, Optional<float> repeat_length, Optional<float> rotation_angle = {})
  224. {
  225. // A conservative guesstimate on how many colors we need to generate:
  226. auto max_dimension = max(physical_rect.width(), physical_rect.height());
  227. auto max_visible_gradient = max(max_dimension / 2, min(size.width(), max_dimension));
  228. GradientLine gradient_line(max_visible_gradient, color_stops, repeat_length);
  229. auto center_point = FloatPoint { center }.translated(0.5, 0.5);
  230. AffineTransform rotation_transform;
  231. if (rotation_angle.has_value()) {
  232. auto angle_as_radians = AK::to_radians(rotation_angle.value());
  233. rotation_transform.rotate_radians(angle_as_radians);
  234. }
  235. return Gradient {
  236. move(gradient_line),
  237. [=](int x, int y) {
  238. // FIXME: See if there's a more efficient calculation we do there :^)
  239. auto point = FloatPoint(x, y) - center_point;
  240. if (rotation_angle.has_value())
  241. point.transform_by(rotation_transform);
  242. auto gradient_x = point.x() / size.width();
  243. auto gradient_y = point.y() / size.height();
  244. return AK::sqrt(gradient_x * gradient_x + gradient_y * gradient_y) * max_visible_gradient;
  245. }
  246. };
  247. }
  248. void Painter::fill_rect_with_linear_gradient(IntRect const& rect, ReadonlySpan<ColorStop> color_stops, float angle, Optional<float> repeat_length)
  249. {
  250. auto a_rect = to_physical(rect);
  251. if (a_rect.intersected(clip_rect() * scale()).is_empty())
  252. return;
  253. auto linear_gradient = create_linear_gradient(a_rect, color_stops, angle, repeat_length);
  254. linear_gradient.paint(*this, a_rect);
  255. }
  256. static FloatPoint pixel_center(IntPoint point)
  257. {
  258. return point.to_type<float>().translated(0.5f, 0.5f);
  259. }
  260. void Painter::fill_rect_with_conic_gradient(IntRect const& rect, ReadonlySpan<ColorStop> color_stops, IntPoint center, float start_angle, Optional<float> repeat_length)
  261. {
  262. auto a_rect = to_physical(rect);
  263. if (a_rect.intersected(clip_rect() * scale()).is_empty())
  264. return;
  265. // Translate position/center to the center of the pixel (avoids some funky painting)
  266. auto center_point = pixel_center(center * scale());
  267. auto conic_gradient = create_conic_gradient(color_stops, center_point, start_angle, repeat_length);
  268. conic_gradient.paint(*this, a_rect);
  269. }
  270. void Painter::fill_rect_with_radial_gradient(IntRect const& rect, ReadonlySpan<ColorStop> color_stops, IntPoint center, IntSize size, Optional<float> repeat_length, Optional<float> rotation_angle)
  271. {
  272. auto a_rect = to_physical(rect);
  273. if (a_rect.intersected(clip_rect() * scale()).is_empty())
  274. return;
  275. auto radial_gradient = create_radial_gradient(a_rect, color_stops, center * scale(), size * scale(), repeat_length, rotation_angle);
  276. radial_gradient.paint(*this, a_rect);
  277. }
  278. // TODO: Figure out how to handle scale() here... Not important while not supported by fill_path()
  279. void LinearGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  280. {
  281. VERIFY(color_stops().size() > 2);
  282. auto linear_gradient = create_linear_gradient(physical_bounding_box, color_stops(), m_angle, repeat_length());
  283. paint(linear_gradient.sample_function());
  284. }
  285. void ConicGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  286. {
  287. VERIFY(color_stops().size() > 2);
  288. (void)physical_bounding_box;
  289. auto conic_gradient = create_conic_gradient(color_stops(), pixel_center(m_center), m_start_angle, repeat_length());
  290. paint(conic_gradient.sample_function());
  291. }
  292. void RadialGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  293. {
  294. VERIFY(color_stops().size() > 2);
  295. auto radial_gradient = create_radial_gradient(physical_bounding_box, color_stops(), m_center, m_size, repeat_length());
  296. paint(radial_gradient.sample_function());
  297. }
  298. // The following implements the gradient fill/stoke styles for the HTML canvas: https://html.spec.whatwg.org/multipage/canvas.html#fill-and-stroke-styles
  299. static auto make_sample_non_relative(IntPoint draw_location, auto sample)
  300. {
  301. return [=, sample = move(sample)](IntPoint point) { return sample(point.translated(draw_location)); };
  302. }
  303. static auto make_linear_gradient_between_two_points(FloatPoint p0, FloatPoint p1, ReadonlySpan<ColorStop> color_stops, Optional<float> repeat_length)
  304. {
  305. auto delta = p1 - p0;
  306. auto angle = AK::atan2(delta.y(), delta.x());
  307. float sin_angle, cos_angle;
  308. AK::sincos(angle, sin_angle, cos_angle);
  309. int gradient_length = ceilf(p1.distance_from(p0));
  310. auto rotated_start_point_x = p0.x() * cos_angle - p0.y() * -sin_angle;
  311. return Gradient {
  312. GradientLine(gradient_length, color_stops, repeat_length, UsePremultipliedAlpha::No),
  313. [=](int x, int y) {
  314. return (x * cos_angle - y * -sin_angle) - rotated_start_point_x;
  315. }
  316. };
  317. }
  318. void CanvasLinearGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  319. {
  320. // If x0 = x1 and y0 = y1, then the linear gradient must paint nothing.
  321. if (m_p0 == m_p1)
  322. return;
  323. if (color_stops().is_empty())
  324. return;
  325. if (color_stops().size() < 2)
  326. return paint([this](IntPoint) { return color_stops().first().color; });
  327. auto linear_gradient = make_linear_gradient_between_two_points(m_p0, m_p1, color_stops(), repeat_length());
  328. paint(make_sample_non_relative(physical_bounding_box.location(), linear_gradient.sample_function()));
  329. }
  330. static GradientLine::RepeatMode svg_spread_method_to_repeat_mode(SVGGradientPaintStyle::SpreadMethod spread_method)
  331. {
  332. switch (spread_method) {
  333. case SVGGradientPaintStyle::SpreadMethod::Pad:
  334. return GradientLine::RepeatMode::None;
  335. case SVGGradientPaintStyle::SpreadMethod::Reflect:
  336. return GradientLine::RepeatMode::Reflect;
  337. case SVGGradientPaintStyle::SpreadMethod::Repeat:
  338. return GradientLine::RepeatMode::Repeat;
  339. default:
  340. VERIFY_NOT_REACHED();
  341. }
  342. }
  343. void SVGGradientPaintStyle::set_gradient_transform(AffineTransform transform)
  344. {
  345. // Note: The scaling is removed so enough points on the gradient line are generated.
  346. // Otherwise, if you scale a tiny path the gradient looks pixelated.
  347. m_scale = 1.0f;
  348. if (auto inverse = transform.inverse(); inverse.has_value()) {
  349. auto transform_scale = transform.scale();
  350. m_scale = max(transform_scale.x(), transform_scale.y());
  351. m_inverse_transform = AffineTransform {}.scale(m_scale, m_scale).multiply(*inverse);
  352. } else {
  353. m_inverse_transform = OptionalNone {};
  354. }
  355. }
  356. void SVGLinearGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  357. {
  358. if (color_stops().is_empty())
  359. return;
  360. // If ‘x1’ = ‘x2’ and ‘y1’ = ‘y2’, then the area to be painted will be painted as
  361. // a single color using the color and opacity of the last gradient stop.
  362. if (m_p0 == m_p1)
  363. return paint([this](IntPoint) { return color_stops().last().color; });
  364. if (color_stops().size() < 2)
  365. return paint([this](IntPoint) { return color_stops().first().color; });
  366. float scale = gradient_transform_scale();
  367. auto linear_gradient = make_linear_gradient_between_two_points(
  368. m_p0.scaled(scale, scale), m_p1.scaled(scale, scale),
  369. color_stops(), repeat_length());
  370. linear_gradient.gradient_line().set_repeat_mode(
  371. svg_spread_method_to_repeat_mode(spread_method()));
  372. paint([&, sampler = linear_gradient.sample_function<float>()](IntPoint target_point) {
  373. auto point = target_point.translated(physical_bounding_box.location()).to_type<float>();
  374. if (auto inverse_transform = scale_adjusted_inverse_gradient_transform(); inverse_transform.has_value())
  375. point = inverse_transform->map(point);
  376. return sampler(point);
  377. });
  378. }
  379. void CanvasConicGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  380. {
  381. if (color_stops().is_empty())
  382. return;
  383. if (color_stops().size() < 2)
  384. return paint([this](IntPoint) { return color_stops().first().color; });
  385. // Follows the same rendering rule as CSS 'conic-gradient' and it is equivalent to CSS
  386. // 'conic-gradient(from adjustedStartAnglerad at xpx ypx, angularColorStopList)'.
  387. // Here:
  388. // adjustedStartAngle is given by startAngle + π/2;
  389. auto conic_gradient = create_conic_gradient(color_stops(), m_center, m_start_angle + 90.0f, repeat_length(), UsePremultipliedAlpha::No);
  390. paint(make_sample_non_relative(physical_bounding_box.location(), conic_gradient.sample_function()));
  391. }
  392. static auto create_radial_gradient_between_two_circles(Gfx::FloatPoint start_center, float start_radius, Gfx::FloatPoint end_center, float end_radius, ReadonlySpan<ColorStop> color_stops, Optional<float> repeat_length)
  393. {
  394. bool reverse_gradient = end_radius < start_radius;
  395. if (reverse_gradient) {
  396. swap(end_radius, start_radius);
  397. swap(end_center, start_center);
  398. }
  399. // FIXME: Handle the start_radius == end_radius special case separately.
  400. // This hack is not quite correct.
  401. if (end_radius - start_radius < 1)
  402. end_radius += 1;
  403. // Spec steps: Useless for writing an actual implementation (give it a go :P):
  404. //
  405. // 2. Let x(ω) = (x1-x0)ω + x0
  406. // Let y(ω) = (y1-y0)ω + y0
  407. // Let r(ω) = (r1-r0)ω + r0
  408. // Let the color at ω be the color at that position on the gradient
  409. // (with the colors coming from the interpolation and extrapolation described above).
  410. //
  411. // 3. For all values of ω where r(ω) > 0, starting with the value of ω nearest to positive infinity and
  412. // ending with the value of ω nearest to negative infinity, draw the circumference of the circle with
  413. // radius r(ω) at position (x(ω), y(ω)), with the color at ω, but only painting on the parts of the
  414. // bitmap that have not yet been painted on by earlier circles in this step for this rendering of the gradient.
  415. auto center_dist = end_center.distance_from(start_center);
  416. bool inner_contained = ((center_dist + start_radius) < end_radius);
  417. auto start_point = start_center;
  418. if (start_radius != 0) {
  419. // Set the start point to the focal point.
  420. auto f = end_radius / (end_radius - start_radius);
  421. auto one_minus_f = 1 - f;
  422. start_point = start_center.scaled(f) + end_center.scaled(one_minus_f);
  423. }
  424. // This is just an approximate upperbound (the gradient line class will shorten this if necessary).
  425. int gradient_length = AK::ceil(center_dist + end_radius + start_radius);
  426. GradientLine gradient_line(gradient_length, color_stops, repeat_length, UsePremultipliedAlpha::No);
  427. // If you can simplify this please do, this is "best guess" implementation due to lack of specification.
  428. // It was implemented to visually match chrome/firefox in all cases:
  429. // - Start circle inside end circle
  430. // - Start circle outside end circle
  431. // - Start circle radius == end circle radius
  432. // - Start circle larger than end circle (inside end circle)
  433. // - Start circle larger than end circle (outside end circle)
  434. // - Start circle or end circle radius == 0
  435. auto circle_distance_finder = [=](auto radius, auto center) {
  436. auto radius2 = radius * radius;
  437. auto delta = center - start_point;
  438. auto delta_xy = delta.x() * delta.y();
  439. auto dx2_factor = radius2 - delta.y() * delta.y();
  440. auto dy2_factor = radius2 - delta.x() * delta.x();
  441. return [=](bool positive_root, auto vec) {
  442. // This works out the distance to the nearest point on the circle
  443. // in the direction of the "vec" vector.
  444. auto dx2 = vec.x() * vec.x();
  445. auto dy2 = vec.y() * vec.y();
  446. auto root = sqrtf(dx2 * dx2_factor + dy2 * dy2_factor
  447. + 2 * vec.x() * vec.y() * delta_xy);
  448. auto dot = vec.x() * delta.x() + vec.y() * delta.y();
  449. return ((positive_root ? root : -root) + dot) / (dx2 + dy2);
  450. };
  451. };
  452. auto end_circle_dist = circle_distance_finder(end_radius, end_center);
  453. auto start_circle_dist = [=, dist = circle_distance_finder(start_radius, start_center)](bool positive_root, auto vec) {
  454. if (start_center == start_point)
  455. return start_radius;
  456. return dist(positive_root, vec);
  457. };
  458. return Gradient {
  459. move(gradient_line),
  460. [=](float x, float y) {
  461. auto loc = [&] {
  462. FloatPoint point { x, y };
  463. // Add a little to avoid division by zero at the focal point.
  464. if (point == start_point)
  465. point += FloatPoint { 0.001f, 0.001f };
  466. // The "vec" (unit) vector points from the focal point to the current point.
  467. auto dist = point.distance_from(start_point);
  468. auto vec = (point - start_point) / dist;
  469. bool use_positive_root = inner_contained || reverse_gradient;
  470. auto dist_end = end_circle_dist(use_positive_root, vec);
  471. auto dist_start = start_circle_dist(use_positive_root, vec);
  472. // FIXME: Returning nan is a hack for "Don't paint me!"
  473. if (dist_end < 0)
  474. return AK::NaN<float>;
  475. if (dist_end - dist_start < 0)
  476. return float(gradient_length);
  477. return (dist - dist_start) / (dist_end - dist_start);
  478. }();
  479. if (reverse_gradient)
  480. loc = 1.0f - loc;
  481. return loc * gradient_length;
  482. }
  483. };
  484. }
  485. void CanvasRadialGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  486. {
  487. // 1. If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing. Return.
  488. if (m_start_center == m_end_center && m_start_radius == m_end_radius)
  489. return;
  490. if (color_stops().is_empty())
  491. return;
  492. if (color_stops().size() < 2)
  493. return paint([this](IntPoint) { return color_stops().first().color; });
  494. if (m_end_radius == 0 && m_start_radius == 0)
  495. return;
  496. auto radial_gradient = create_radial_gradient_between_two_circles(m_start_center, m_start_radius, m_end_center, m_end_radius, color_stops(), repeat_length());
  497. paint(make_sample_non_relative(physical_bounding_box.location(), radial_gradient.sample_function()));
  498. }
  499. void SVGRadialGradientPaintStyle::paint(IntRect physical_bounding_box, PaintFunction paint) const
  500. {
  501. // FIXME: Ensure this handles all the edge cases of SVG gradients.
  502. if (color_stops().is_empty())
  503. return;
  504. if (color_stops().size() < 2 || (m_end_radius == 0 && m_start_radius == 0))
  505. return paint([this](IntPoint) { return color_stops().last().color; });
  506. float scale = gradient_transform_scale();
  507. auto radial_gradient = create_radial_gradient_between_two_circles(
  508. m_start_center.scaled(scale, scale), m_start_radius * scale, m_end_center.scaled(scale, scale), m_end_radius * scale,
  509. color_stops(), repeat_length());
  510. radial_gradient.gradient_line().set_repeat_mode(
  511. svg_spread_method_to_repeat_mode(spread_method()));
  512. paint([&, sampler = radial_gradient.sample_function<float>()](IntPoint target_point) {
  513. auto point = target_point.translated(physical_bounding_box.location()).to_type<float>();
  514. if (auto inverse_transform = scale_adjusted_inverse_gradient_transform(); inverse_transform.has_value())
  515. point = inverse_transform->map(point);
  516. return sampler(point);
  517. });
  518. }
  519. }