GradientPainting.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. * Copyright (c) 2022, MacDue <macdue@dueutil.tech>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Checked.h>
  7. #include <AK/Math.h>
  8. #include <LibGfx/Gamma.h>
  9. #include <LibGfx/Line.h>
  10. #include <LibWeb/CSS/StyleValue.h>
  11. #include <LibWeb/Painting/GradientPainting.h>
  12. namespace Web::Painting {
  13. static float normalized_gradient_angle_radians(float gradient_angle)
  14. {
  15. // Adjust angle so 0 degrees is bottom
  16. float real_angle = 90 - gradient_angle;
  17. return real_angle * (AK::Pi<float> / 180);
  18. }
  19. template<typename T>
  20. static float calculate_gradient_length(Gfx::Size<T> gradient_size, float sin_angle, float cos_angle)
  21. {
  22. return AK::fabs(gradient_size.height().value() * sin_angle) + AK::fabs(gradient_size.width().value() * cos_angle);
  23. }
  24. template<typename T>
  25. static float calculate_gradient_length(Gfx::Size<T> gradient_size, float gradient_angle)
  26. {
  27. float angle = normalized_gradient_angle_radians(gradient_angle);
  28. float sin_angle, cos_angle;
  29. AK::sincos(angle, sin_angle, cos_angle);
  30. return calculate_gradient_length(gradient_size, sin_angle, cos_angle);
  31. }
  32. static ColorStopData resolve_color_stop_positions(auto const& color_stop_list, auto resolve_position_to_float, bool repeating)
  33. {
  34. VERIFY(color_stop_list.size() >= 2);
  35. ColorStopList resolved_color_stops;
  36. auto color_stop_length = [&](auto& stop) {
  37. return stop.color_stop.second_position.has_value() ? 2 : 1;
  38. };
  39. size_t expanded_size = 0;
  40. for (auto& stop : color_stop_list)
  41. expanded_size += color_stop_length(stop);
  42. resolved_color_stops.ensure_capacity(expanded_size);
  43. for (auto& stop : color_stop_list) {
  44. auto resolved_stop = ColorStop { .color = stop.color_stop.color };
  45. for (int i = 0; i < color_stop_length(stop); i++)
  46. resolved_color_stops.append(resolved_stop);
  47. }
  48. // 1. If the first color stop does not have a position, set its position to 0%.
  49. resolved_color_stops.first().position = 0;
  50. // If the last color stop does not have a position, set its position to 100%
  51. resolved_color_stops.last().position = 1.0f;
  52. // 2. If a color stop or transition hint has a position that is less than the
  53. // specified position of any color stop or transition hint before it in the list,
  54. // set its position to be equal to the largest specified position of any color stop
  55. // or transition hint before it.
  56. auto max_previous_color_stop_or_hint = resolved_color_stops[0].position;
  57. auto resolve_stop_position = [&](auto& position) {
  58. float value = resolve_position_to_float(position);
  59. value = max(value, max_previous_color_stop_or_hint);
  60. max_previous_color_stop_or_hint = value;
  61. return value;
  62. };
  63. // Move this step somewhere generic (since I think this code can be mostly reused for conic gradients)
  64. size_t resolved_index = 0;
  65. for (auto& stop : color_stop_list) {
  66. if (stop.transition_hint.has_value())
  67. resolved_color_stops[resolved_index].transition_hint = resolve_stop_position(stop.transition_hint->value);
  68. if (stop.color_stop.position.has_value())
  69. resolved_color_stops[resolved_index].position = resolve_stop_position(*stop.color_stop.position);
  70. if (stop.color_stop.second_position.has_value())
  71. resolved_color_stops[++resolved_index].position = resolve_stop_position(*stop.color_stop.second_position);
  72. ++resolved_index;
  73. }
  74. // 3. If any color stop still does not have a position, then, for each run of adjacent color stops
  75. // without positions, set their positions so that they are evenly spaced between the preceding
  76. // and following color stops with positions.
  77. // Note: Though not mentioned anywhere in the specification transition hints are counted as "color stops with positions".
  78. size_t i = 1;
  79. auto find_run_end = [&] {
  80. auto color_stop_has_position = [](auto& color_stop) {
  81. return color_stop.transition_hint.has_value() || isfinite(color_stop.position);
  82. };
  83. while (i < color_stop_list.size() - 1 && !color_stop_has_position(resolved_color_stops[i])) {
  84. i++;
  85. }
  86. return i;
  87. };
  88. while (i < resolved_color_stops.size() - 1) {
  89. auto& stop = resolved_color_stops[i];
  90. if (!isfinite(stop.position)) {
  91. auto run_start = i - 1;
  92. auto start_position = resolved_color_stops[i++].transition_hint.value_or(resolved_color_stops[run_start].position);
  93. auto run_end = find_run_end();
  94. auto end_position = resolved_color_stops[run_end].transition_hint.value_or(resolved_color_stops[run_end].position);
  95. auto spacing = (end_position - start_position) / (run_end - run_start);
  96. for (auto j = run_start + 1; j < run_end; j++) {
  97. resolved_color_stops[j].position = start_position + (j - run_start) * spacing;
  98. }
  99. }
  100. i++;
  101. }
  102. // Determine the location of the transition hint as a percentage of the distance between the two color stops,
  103. // denoted as a number between 0 and 1, where 0 indicates the hint is placed right on the first color stop,
  104. // and 1 indicates the hint is placed right on the second color stop.
  105. for (size_t i = 1; i < resolved_color_stops.size(); i++) {
  106. auto& color_stop = resolved_color_stops[i];
  107. auto& previous_color_stop = resolved_color_stops[i - 1];
  108. if (color_stop.transition_hint.has_value()) {
  109. auto stop_length = color_stop.position - previous_color_stop.position;
  110. color_stop.transition_hint = stop_length > 0 ? (*color_stop.transition_hint - previous_color_stop.position) / stop_length : 0;
  111. }
  112. }
  113. Optional<float> repeat_length = {};
  114. if (repeating)
  115. repeat_length = resolved_color_stops.last().position - resolved_color_stops.first().position;
  116. return { resolved_color_stops, repeat_length };
  117. }
  118. LinearGradientData resolve_linear_gradient_data(Layout::Node const& node, CSSPixelSize gradient_size, CSS::LinearGradientStyleValue const& linear_gradient)
  119. {
  120. auto gradient_angle = linear_gradient.angle_degrees(gradient_size.to_type<float>());
  121. auto gradient_length_px = calculate_gradient_length(gradient_size, gradient_angle);
  122. auto gradient_length = CSS::Length::make_px(gradient_length_px);
  123. auto resolved_color_stops = resolve_color_stop_positions(
  124. linear_gradient.color_stop_list(), [&](auto const& length_percentage) {
  125. return length_percentage.resolved(node, gradient_length).to_px(node) / gradient_length_px;
  126. },
  127. linear_gradient.is_repeating());
  128. return { gradient_angle, resolved_color_stops };
  129. }
  130. ConicGradientData resolve_conic_gradient_data(Layout::Node const& node, CSS::ConicGradientStyleValue const& conic_gradient)
  131. {
  132. CSS::Angle one_turn(360.0f, CSS::Angle::Type::Deg);
  133. auto resolved_color_stops = resolve_color_stop_positions(
  134. conic_gradient.color_stop_list(), [&](auto const& angle_percentage) {
  135. return angle_percentage.resolved(node, one_turn).to_degrees() / one_turn.to_degrees();
  136. },
  137. conic_gradient.is_repeating());
  138. return { conic_gradient.angle_degrees(), resolved_color_stops };
  139. }
  140. RadialGradientData resolve_radial_gradient_data(Layout::Node const& node, CSSPixelSize gradient_size, CSS::RadialGradientStyleValue const& radial_gradient)
  141. {
  142. // Start center, goes right to ending point, where the gradient line intersects the ending shape
  143. auto gradient_length = CSS::Length::make_px(gradient_size.width());
  144. auto resolved_color_stops = resolve_color_stop_positions(
  145. radial_gradient.color_stop_list(), [&](auto const& length_percentage) {
  146. return length_percentage.resolved(node, gradient_length).to_px(node) / gradient_size.width().value();
  147. },
  148. radial_gradient.is_repeating());
  149. return { resolved_color_stops };
  150. }
  151. static float color_stop_step(ColorStop const& previous_stop, ColorStop const& next_stop, float position)
  152. {
  153. if (position < previous_stop.position)
  154. return 0;
  155. if (position > next_stop.position)
  156. return 1;
  157. // For any given point between the two color stops,
  158. // determine the point’s location as a percentage of the distance between the two color stops.
  159. // Let this percentage be P.
  160. auto stop_length = next_stop.position - previous_stop.position;
  161. // FIXME: Avoids NaNs... Still not quite correct?
  162. if (stop_length <= 0)
  163. return 1;
  164. auto p = (position - previous_stop.position) / stop_length;
  165. if (!next_stop.transition_hint.has_value())
  166. return p;
  167. if (*next_stop.transition_hint >= 1)
  168. return 0;
  169. if (*next_stop.transition_hint <= 0)
  170. return 1;
  171. // Let C, the color weighting at that point, be equal to P^(logH(.5)).
  172. auto c = AK::pow(p, AK::log<float>(0.5) / AK::log(*next_stop.transition_hint));
  173. // The color at that point is then a linear blend between the colors of the two color stops,
  174. // blending (1 - C) of the first stop and C of the second stop.
  175. return c;
  176. }
  177. class GradientLine {
  178. public:
  179. GradientLine(int gradient_length, ColorStopData const& color_stops)
  180. : m_repeating { color_stops.repeat_length.has_value() }
  181. , m_start_offset { round_to<int>((m_repeating ? color_stops.list.first().position : 0.0f) * gradient_length) }
  182. {
  183. // Note: color_count will be < gradient_length for repeating gradients.
  184. auto color_count = round_to<int>(color_stops.repeat_length.value_or(1.0f) * gradient_length);
  185. m_gradient_line_colors.resize(color_count);
  186. // Note: color.mixed_with() performs premultiplied alpha mixing when necessary as defined in:
  187. // https://drafts.csswg.org/css-images/#coloring-gradient-line
  188. auto& stop_list = color_stops.list;
  189. for (int loc = 0; loc < color_count; loc++) {
  190. auto relative_loc = float(loc + m_start_offset) / gradient_length;
  191. Gfx::Color gradient_color = stop_list[0].color.mixed_with(
  192. stop_list[1].color,
  193. color_stop_step(stop_list[0], stop_list[1], relative_loc));
  194. for (size_t i = 1; i < stop_list.size() - 1; i++) {
  195. gradient_color = gradient_color.mixed_with(
  196. stop_list[i + 1].color,
  197. color_stop_step(stop_list[i], stop_list[i + 1], relative_loc));
  198. }
  199. m_gradient_line_colors[loc] = gradient_color;
  200. }
  201. }
  202. Gfx::Color get_color(i64 index) const
  203. {
  204. return m_gradient_line_colors[clamp(index, 0, m_gradient_line_colors.size() - 1)];
  205. }
  206. Gfx::Color sample_color(float loc) const
  207. {
  208. auto repeat_wrap_if_required = [&](i64 loc) {
  209. if (m_repeating)
  210. return (loc + m_start_offset) % static_cast<i64>(m_gradient_line_colors.size());
  211. return loc;
  212. };
  213. auto int_loc = static_cast<i64>(floor(loc));
  214. auto blend = loc - int_loc;
  215. auto color = get_color(repeat_wrap_if_required(int_loc));
  216. // Blend between the two neighbouring colors (this fixes some nasty aliasing issues at small angles)
  217. if (blend >= 0.004f)
  218. color = color.mixed_with(get_color(repeat_wrap_if_required(int_loc + 1)), blend);
  219. return color;
  220. }
  221. void paint_into_rect(Gfx::Painter& painter, DevicePixelRect rect, auto location_transform)
  222. {
  223. for (DevicePixels y = 0; y < rect.height(); y++) {
  224. for (DevicePixels x = 0; x < rect.width(); x++) {
  225. auto gradient_color = sample_color(location_transform(x, y));
  226. painter.set_pixel((rect.x() + x).value(), (rect.y() + y).value(), gradient_color, gradient_color.alpha() < 255);
  227. }
  228. }
  229. }
  230. private:
  231. bool m_repeating;
  232. int m_start_offset;
  233. Vector<Gfx::Color, 1024> m_gradient_line_colors;
  234. };
  235. void paint_linear_gradient(PaintContext& context, DevicePixelRect const& gradient_rect, LinearGradientData const& data)
  236. {
  237. float angle = normalized_gradient_angle_radians(data.gradient_angle);
  238. float sin_angle, cos_angle;
  239. AK::sincos(angle, sin_angle, cos_angle);
  240. // Full length of the gradient
  241. auto gradient_length = calculate_gradient_length(gradient_rect.size(), sin_angle, cos_angle);
  242. DevicePixelPoint offset { cos_angle * (gradient_length / 2), sin_angle * (gradient_length / 2) };
  243. auto center = gradient_rect.translated(-gradient_rect.location()).center();
  244. auto start_point = center.to_type<int>() - offset.to_type<int>();
  245. // Rotate gradient line to be horizontal
  246. auto rotated_start_point_x = start_point.x() * cos_angle - start_point.y() * -sin_angle;
  247. GradientLine gradient_line(gradient_length, data.color_stops);
  248. gradient_line.paint_into_rect(context.painter(), gradient_rect, [&](DevicePixels x, DevicePixels y) {
  249. return (x.value() * cos_angle - (gradient_rect.height() - y).value() * -sin_angle) - rotated_start_point_x;
  250. });
  251. }
  252. void paint_conic_gradient(PaintContext& context, DevicePixelRect const& gradient_rect, ConicGradientData const& data, DevicePixelPoint position)
  253. {
  254. // FIXME: Do we need/want sub-degree accuracy for the gradient line?
  255. GradientLine gradient_line(360, data.color_stops);
  256. float start_angle = (360.0f - data.start_angle) + 90.0f;
  257. // Translate position/center to the center of the pixel (avoids some funky painting)
  258. auto center_point = Gfx::FloatPoint { position.to_type<int>() }.translated(0.5, 0.5);
  259. // The flooring can make gradients that want soft edges look worse, so only floor if we have hard edges.
  260. // Which makes sure the hard edge stay hard edges :^)
  261. bool should_floor_angles = false;
  262. auto& color_stops = data.color_stops.list;
  263. for (size_t i = 0; i < color_stops.size() - 1; i++) {
  264. if (color_stops[i + 1].position - color_stops[i].position <= 0.01f) {
  265. should_floor_angles = true;
  266. break;
  267. }
  268. }
  269. gradient_line.paint_into_rect(context.painter(), gradient_rect, [&](DevicePixels x, DevicePixels y) {
  270. auto point = Gfx::FloatPoint { x.value(), y.value() } - center_point;
  271. // FIXME: We could probably get away with some approximation here:
  272. auto loc = fmod((AK::atan2(point.y(), point.x()) * 180.0f / AK::Pi<float> + 360.0f + start_angle), 360.0f);
  273. return should_floor_angles ? floor(loc) : loc;
  274. });
  275. }
  276. void paint_radial_gradient(PaintContext& context, DevicePixelRect const& gradient_rect, RadialGradientData const& data, DevicePixelPoint center, DevicePixelSize size)
  277. {
  278. // A conservative guesstimate on how many colors we need to generate:
  279. auto max_dimension = max(gradient_rect.width(), gradient_rect.height());
  280. auto max_visible_gradient = max(max_dimension / 2, min(size.width(), max_dimension.value())).value();
  281. GradientLine gradient_line(max_visible_gradient, data.color_stops);
  282. auto center_point = Gfx::FloatPoint { center.to_type<int>() }.translated(0.5, 0.5);
  283. gradient_line.paint_into_rect(context.painter(), gradient_rect, [&](DevicePixels x, DevicePixels y) {
  284. // FIXME: See if there's a more efficient calculation we do there :^)
  285. auto point = Gfx::FloatPoint(x.value(), y.value()) - center_point;
  286. auto gradient_x = point.x() / size.width().value();
  287. auto gradient_y = point.y() / size.height().value();
  288. return AK::sqrt(gradient_x * gradient_x + gradient_y * gradient_y) * max_visible_gradient;
  289. });
  290. }
  291. }