takumi 1.7.0

Render UI component trees to images.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
use std::{f32::consts::TAU, fmt};

use cssparser::{Parser, Token, match_ignore_ascii_case};
use tiny_skia::PremultipliedColorU8;
use typed_builder::TypedBuilder;

use super::gradient_utils::{
  GradientOverlayTile, adaptive_lut_size_with_visible_samples, build_color_lut_with_interpolation,
  resolve_stops_along_axis,
};
use crate::{
  layout::style::{
    Angle, BackgroundPosition, ColorInput, ColorInterpolationMethod, CssDescriptorKind, CssToken,
    FromCss, GradientStop, Length, MakeComputed, ObjectPosition, ParseResult, ResolvedGradientStop,
    StopPosition, ToCss, unexpected_token,
  },
  rendering::{RenderContext, Sizing},
};

const LUT_INDEX_BOUNDARY_EPSILON: f32 = 0.001;

/// Represents a CSS conic-gradient.
#[derive(Debug, Clone, PartialEq, TypedBuilder)]
#[non_exhaustive]
pub struct ConicGradient {
  /// Whether the gradient repeats beyond the last stop.
  #[builder(default)]
  pub repeating: bool,
  /// The starting angle of the gradient (default 0deg = from top).
  #[builder(default)]
  pub from_angle: Angle,
  /// Center position (default 50% 50%).
  #[builder(default)]
  pub center: ObjectPosition,
  /// The color interpolation method used between stops.
  #[builder(default)]
  pub interpolation: ColorInterpolationMethod,
  /// Gradient color stops.
  #[builder(setter(into))]
  pub stops: Box<[GradientStop]>,
}

impl MakeComputed for ConicGradient {
  fn make_computed(&mut self, sizing: &Sizing) {
    self.center.make_computed(sizing);
    self.stops.make_computed(sizing);
  }
}

/// Precomputed data for repeated sampling of a `ConicGradient`.
#[derive(Debug, Clone)]
pub(crate) struct ConicGradientTile {
  /// Target width in pixels.
  pub width: u32,
  /// Target height in pixels.
  pub height: u32,
  /// Center X coordinate in pixels.
  pub cx: f32,
  /// Center Y coordinate in pixels.
  pub cy: f32,
  /// Starting angle in radians (CSS 0deg = from top, clockwise).
  pub start_rad: f32,
  /// Whether this gradient repeats.
  pub repeating: bool,
  /// First resolved stop position in degrees, used as repeating origin.
  pub repeat_start_deg: f32,
  /// Repeat period in degrees.
  pub repeat_period_deg: f32,
  /// Scale converting an adjusted angle in radians to LUT index.
  pub angle_to_lut_scale: f32,
  /// Whether every LUT entry has alpha = 255.
  pub fully_opaque: bool,
  /// Pre-computed color lookup table for fast gradient sampling.
  /// Maps normalized angle [0.0, 1.0] (fraction of full turn) to color.
  pub color_lut: Vec<PremultipliedColorU8>,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct ConicGradientRowState {
  dx: f32,
  dy: f32,
  lut_len: usize,
}

impl ConicGradientTile {
  fn visible_angle_samples(width: u32, height: u32, cx: f32, cy: f32) -> usize {
    let max_dx = cx.max(width as f32 - cx);
    let max_dy = cy.max(height as f32 - cy);
    (max_dx.hypot(max_dy) * TAU).ceil() as usize + 1
  }

  #[inline(always)]
  fn angle_from_top_normalized(dx: f32, dy: f32) -> f32 {
    let angle = dx.atan2(-dy);
    if angle < 0.0 { angle + TAU } else { angle }
  }

  #[inline(always)]
  fn adjusted_angle(&self, angle_from_top: f32) -> f32 {
    let adjusted = angle_from_top - self.start_rad;
    if adjusted < 0.0 {
      adjusted + TAU
    } else {
      adjusted
    }
  }

  #[inline(always)]
  fn stable_floor_index(scaled_position: f32, max_index: usize) -> usize {
    let nearest = scaled_position.round();
    let sample = if (scaled_position - nearest).abs() <= LUT_INDEX_BOUNDARY_EPSILON {
      nearest
    } else {
      scaled_position.floor()
    };
    (sample as usize).min(max_index)
  }

  #[inline(always)]
  fn stable_round_index(scaled_position: f32, max_index: usize) -> usize {
    let floor = scaled_position.floor();
    let fraction = scaled_position - floor;
    let sample = if fraction >= 0.5 - LUT_INDEX_BOUNDARY_EPSILON {
      floor + 1.0
    } else {
      floor
    };
    (sample as usize).min(max_index)
  }

  #[inline(always)]
  pub(crate) fn lut_index_for_adjusted_angle_with_len(
    &self,
    adjusted_angle: f32,
    lut_len: usize,
  ) -> usize {
    if lut_len <= 1 {
      return 0;
    }

    let max_index = lut_len - 1;
    if self.repeating && self.repeat_period_deg > 1e-6 {
      let degrees = adjusted_angle / TAU * 360.0;
      let wrapped = (degrees - self.repeat_start_deg).rem_euclid(self.repeat_period_deg);
      Self::stable_round_index(wrapped * self.angle_to_lut_scale, max_index)
    } else {
      Self::stable_floor_index(adjusted_angle * self.angle_to_lut_scale, max_index)
    }
  }

  /// Builds a drawing context from a conic gradient and a target viewport.
  pub fn new(gradient: &ConicGradient, width: u32, height: u32, context: &RenderContext) -> Self {
    let cx = Length::from(gradient.center.0.x).to_px(&context.sizing, width as f32);
    let cy = Length::from(gradient.center.0.y).to_px(&context.sizing, height as f32);

    let start_rad = gradient.from_angle.to_radians().rem_euclid(TAU);

    // Resolve stop percentages against one full turn (360deg).
    let resolved_stops = resolve_stops_along_axis(&gradient.stops, 360.0, context);

    let (repeating, repeat_start_deg, repeat_period_deg, lut_axis_length_deg, lut_resolved_stops) =
      if gradient.repeating
        && let (Some(first), Some(last)) = (resolved_stops.first(), resolved_stops.last())
      {
        let repeat_start_deg = first.position;
        let repeat_period_deg = (last.position - first.position).max(0.0);
        if repeat_period_deg > 1e-6 {
          let shifted = resolved_stops
            .iter()
            .map(|stop| ResolvedGradientStop {
              color: stop.color,
              position: stop.position - repeat_start_deg,
            })
            .collect();
          (
            true,
            repeat_start_deg,
            repeat_period_deg,
            repeat_period_deg,
            shifted,
          )
        } else {
          (false, 0.0, 0.0, 360.0, resolved_stops)
        }
      } else {
        (false, 0.0, 0.0, 360.0, resolved_stops)
      };

    let lut_size = adaptive_lut_size_with_visible_samples(
      Self::visible_angle_samples(width, height, cx, cy),
      lut_axis_length_deg,
      &lut_resolved_stops,
    );
    let color_lut = build_color_lut_with_interpolation(
      &lut_resolved_stops,
      lut_axis_length_deg,
      lut_size,
      gradient.interpolation.color_space,
      gradient.interpolation.hue_direction,
    );
    let lut_len = color_lut.len();
    let angle_to_lut_scale = if repeating && repeat_period_deg > 1e-6 && lut_len > 1 {
      (lut_len - 1) as f32 / repeat_period_deg
    } else if lut_len == 0 {
      0.0
    } else {
      lut_len as f32 / TAU
    };

    let fully_opaque = color_lut.iter().all(|p| p.alpha() == u8::MAX);

    ConicGradientTile {
      width,
      height,
      cx,
      cy,
      start_rad,
      repeating,
      repeat_start_deg,
      repeat_period_deg,
      angle_to_lut_scale,
      fully_opaque,
      color_lut,
    }
  }
}

impl GradientOverlayTile for ConicGradientTile {
  type RowState = ConicGradientRowState;

  #[inline(always)]
  fn width(&self) -> u32 {
    self.width
  }

  #[inline(always)]
  fn height(&self) -> u32 {
    self.height
  }

  #[inline(always)]
  fn lut_len(&self) -> usize {
    self.color_lut.len()
  }

  #[inline(always)]
  fn sample_at(&self, lut_idx: usize) -> PremultipliedColorU8 {
    self.color_lut[lut_idx]
  }

  #[inline(always)]
  fn sample_pixel(&self, x: u32, y: u32) -> PremultipliedColorU8 {
    if self.color_lut.is_empty() {
      return PremultipliedColorU8::TRANSPARENT;
    }

    if self.color_lut.len() == 1 {
      return self.color_lut[0];
    }

    let dx = x as f32 - self.cx;
    let dy = y as f32 - self.cy;
    if dx.abs() <= f32::EPSILON && dy.abs() <= f32::EPSILON {
      return self.color_lut[0];
    }

    let angle_from_top = Self::angle_from_top_normalized(dx, dy);
    let adjusted = self.adjusted_angle(angle_from_top);
    let lut_idx = self.lut_index_for_adjusted_angle_with_len(adjusted, self.color_lut.len());

    self.color_lut[lut_idx]
  }

  #[inline(always)]
  fn begin_row(&self, src_x_start: u32, src_y: u32, lut_len: usize) -> Self::RowState {
    ConicGradientRowState {
      dx: src_x_start as f32 - self.cx,
      dy: src_y as f32 - self.cy,
      lut_len,
    }
  }

  #[inline(always)]
  fn next_lut_index(&self, row_state: &mut Self::RowState) -> usize {
    let lut_idx = if row_state.dx.abs() <= f32::EPSILON && row_state.dy.abs() <= f32::EPSILON {
      0
    } else {
      let angle_from_top = Self::angle_from_top_normalized(row_state.dx, row_state.dy);
      let adjusted_angle = self.adjusted_angle(angle_from_top);
      self.lut_index_for_adjusted_angle_with_len(adjusted_angle, row_state.lut_len)
    };
    row_state.dx += 1.0;
    lut_idx
  }

  #[inline(always)]
  fn fully_opaque(&self) -> bool {
    self.fully_opaque
  }
}

fn parse_conic_stop_position<'i>(input: &mut Parser<'i, '_>) -> ParseResult<'i, StopPosition> {
  let location = input.current_source_location();
  let token = input.next()?;

  match token {
    Token::Percentage { unit_value, .. } => {
      Ok(StopPosition(Length::Percentage(*unit_value * 100.0)))
    }
    Token::Number { value, .. } if (0.0..=1.0).contains(value) => {
      Ok(StopPosition(Length::Percentage(*value * 100.0)))
    }
    Token::Dimension { value, unit, .. } => {
      let degrees = match_ignore_ascii_case! { unit,
        "deg" => *value,
        "grad" => *value * 0.9,
        "rad" => value.to_degrees(),
        "turn" => *value * 360.0,
        _ => return Err(unexpected_token!(StopPosition, location, token)),
      };

      Ok(StopPosition(Length::Percentage(degrees / 360.0 * 100.0)))
    }
    _ => Err(unexpected_token!(StopPosition, location, token)),
  }
}

fn parse_conic_gradient_stops<'i>(
  input: &mut Parser<'i, '_>,
) -> ParseResult<'i, Vec<GradientStop>> {
  let mut stops = Vec::new();

  loop {
    if let Ok(hint) = input.try_parse(parse_conic_stop_position) {
      stops.push(GradientStop::Hint(hint));
    } else {
      let color = ColorInput::from_css(input)?;
      let first_position = input.try_parse(parse_conic_stop_position).ok();
      let second_position = if first_position.is_some() {
        input.try_parse(parse_conic_stop_position).ok()
      } else {
        None
      };

      match (first_position, second_position) {
        (Some(first_position), Some(second_position)) => {
          stops.push(GradientStop::ColorHint {
            color,
            hint: Some(first_position),
          });
          stops.push(GradientStop::ColorHint {
            color,
            hint: Some(second_position),
          });
        }
        _ => {
          stops.push(GradientStop::ColorHint {
            color,
            hint: first_position,
          });
        }
      }
    }

    if input.try_parse(Parser::expect_comma).is_err() {
      break;
    }
  }

  Ok(stops)
}

impl<'i> FromCss<'i> for ConicGradient {
  fn from_css(input: &mut Parser<'i, '_>) -> ParseResult<'i, ConicGradient> {
    let location = input.current_source_location();
    let name = input.expect_function()?.to_owned();
    let repeating = match_ignore_ascii_case! { &name,
      "conic-gradient" => false,
      "repeating-conic-gradient" => true,
      _ => return Err(unexpected_token!(location, &Token::Function(name))),
    };

    input.parse_nested_block(|input| {
      let mut from_angle: Option<Angle> = None;
      let mut center: Option<ObjectPosition> = None;
      let mut interpolation = ColorInterpolationMethod::default();

      // Parse optional "from <angle>" and/or "at <position>" before the comma
      loop {
        // Try "from <angle>"
        if input.try_parse(|i| i.expect_ident_matching("from")).is_ok() {
          from_angle = Some(Angle::from_css(input)?);
          continue;
        }

        // Try "at <position>"
        if input.try_parse(|i| i.expect_ident_matching("at")).is_ok() {
          center = Some(BackgroundPosition::from_css(input)?);
          continue;
        }

        if let Ok(parsed_interpolation) = input.try_parse(ColorInterpolationMethod::from_css) {
          interpolation = parsed_interpolation;
          continue;
        }

        // Consume the comma separator if present
        input.try_parse(Parser::expect_comma).ok();
        break;
      }

      let stops = parse_conic_gradient_stops(input)?;

      Ok(ConicGradient {
        repeating,
        from_angle: from_angle.unwrap_or(Angle::zero()),
        center: center.unwrap_or_default(),
        interpolation,
        stops: stops.into_boxed_slice(),
      })
    })
  }

  const VALID_TOKENS: &'static [CssToken] =
    &[CssToken::Descriptor(CssDescriptorKind::ConicGradientFn)];
}

impl ToCss for ConicGradient {
  fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
    let name = if self.repeating {
      "repeating-conic-gradient"
    } else {
      "conic-gradient"
    };
    dest.write_str(name)?;
    dest.write_char('(')?;
    let mut first = true;

    // Build "from <angle> at <center>" as a temp buffer
    let mut params_buf = String::new();
    if self.from_angle != Angle::zero() {
      params_buf.push_str("from ");
      self.from_angle.to_css(&mut params_buf)?;
    }
    let mut center_buf = String::new();
    self.center.to_css(&mut center_buf)?;
    let is_center_default = center_buf == "center center" || center_buf == "50% 50%";
    if !is_center_default {
      if !params_buf.is_empty() {
        params_buf.push(' ');
      }
      params_buf.push_str("at ");
      params_buf.push_str(&center_buf);
    }
    if !params_buf.is_empty() {
      dest.write_str(&params_buf)?;
      first = false;
    }

    let mut interp_buf = String::new();
    self.interpolation.to_css(&mut interp_buf)?;
    if !interp_buf.is_empty() {
      if !first {
        dest.write_str(", ")?;
      }
      dest.write_str(&interp_buf)?;
      first = false;
    }

    for stop in self.stops.iter() {
      if !first {
        dest.write_str(", ")?;
      }
      stop.to_css(dest)?;
      first = false;
    }

    dest.write_char(')')
  }
}

#[cfg(test)]
mod tests {
  use color::{ColorSpaceTag, HueDirection};
  use tiny_skia::ColorU8;

  use super::*;
  use crate::layout::Viewport;
  use crate::layout::style::{Color, Length, SpacePair, StopPosition};
  use crate::{GlobalContext, rendering::RenderContext};
  #[test]
  fn test_parse_conic_gradient_basic() {
    let gradient = ConicGradient::from_str("conic-gradient(#ff0000, #0000ff)");

    assert_eq!(
      gradient,
      Ok(ConicGradient {
        repeating: false,
        from_angle: Angle::zero(),
        center: ObjectPosition::default(),
        interpolation: ColorInterpolationMethod::default(),
        stops: [
          GradientStop::ColorHint {
            color: Color([255, 0, 0, 255]).into(),
            hint: None,
          },
          GradientStop::ColorHint {
            color: Color([0, 0, 255, 255]).into(),
            hint: None,
          },
        ]
        .into(),
      })
    );
  }

  #[test]
  fn test_parse_conic_gradient_with_interpolation_color_space() {
    assert_eq!(
      ConicGradient::from_str("conic-gradient(in oklab, red, blue)"),
      Ok(ConicGradient {
        repeating: false,
        from_angle: Angle::zero(),
        center: ObjectPosition::default(),
        interpolation: ColorInterpolationMethod {
          color_space: ColorSpaceTag::Oklab,
          hue_direction: HueDirection::Shorter,
        },
        stops: [
          GradientStop::ColorHint {
            color: Color::from_rgb(0xff0000).into(),
            hint: None,
          },
          GradientStop::ColorHint {
            color: Color::from_rgb(0x0000ff).into(),
            hint: None,
          },
        ]
        .into(),
      })
    );
  }

  #[test]
  fn test_parse_conic_gradient_with_stops() {
    assert_eq!(
      ConicGradient::from_str("conic-gradient(#ff0000 0%, #00ff00 50%, #0000ff 100%)"),
      Ok(ConicGradient {
        repeating: false,
        from_angle: Angle::zero(),
        center: ObjectPosition::default(),
        interpolation: ColorInterpolationMethod::default(),
        stops: [
          GradientStop::ColorHint {
            color: Color([255, 0, 0, 255]).into(),
            hint: Some(StopPosition(Length::Percentage(0.0))),
          },
          GradientStop::ColorHint {
            color: Color([0, 255, 0, 255]).into(),
            hint: Some(StopPosition(Length::Percentage(50.0))),
          },
          GradientStop::ColorHint {
            color: Color([0, 0, 255, 255]).into(),
            hint: Some(StopPosition(Length::Percentage(100.0))),
          },
        ]
        .into(),
      })
    );
  }

  #[test]
  fn test_parse_conic_gradient_with_double_position_color_stop() {
    assert_eq!(
      ConicGradient::from_str("conic-gradient(red 10% 20%, blue)"),
      Ok(ConicGradient {
        repeating: false,
        from_angle: Angle::zero(),
        center: ObjectPosition::default(),
        interpolation: ColorInterpolationMethod::default(),
        stops: [
          GradientStop::ColorHint {
            color: Color::from_rgb(0xff0000).into(),
            hint: Some(StopPosition(Length::Percentage(10.0))),
          },
          GradientStop::ColorHint {
            color: Color::from_rgb(0xff0000).into(),
            hint: Some(StopPosition(Length::Percentage(20.0))),
          },
          GradientStop::ColorHint {
            color: Color::from_rgb(0x0000ff).into(),
            hint: None,
          },
        ]
        .into(),
      })
    );
  }

  #[test]
  fn test_parse_conic_gradient_with_angle_stops() {
    assert_eq!(
      ConicGradient::from_str("conic-gradient(red 0deg, lime 180deg, blue 1turn)"),
      Ok(ConicGradient {
        repeating: false,
        from_angle: Angle::zero(),
        center: ObjectPosition::default(),
        interpolation: ColorInterpolationMethod::default(),
        stops: [
          GradientStop::ColorHint {
            color: Color::from_rgb(0xff0000).into(),
            hint: Some(StopPosition(Length::Percentage(0.0))),
          },
          GradientStop::ColorHint {
            color: Color::from_rgb(0x00ff00).into(),
            hint: Some(StopPosition(Length::Percentage(50.0))),
          },
          GradientStop::ColorHint {
            color: Color::from_rgb(0x0000ff).into(),
            hint: Some(StopPosition(Length::Percentage(100.0))),
          },
        ]
        .into(),
      })
    );
  }

  #[test]
  fn test_parse_conic_gradient_with_double_angle_stop() {
    assert_eq!(
      ConicGradient::from_str("conic-gradient(red 0deg 90deg, blue)"),
      Ok(ConicGradient {
        repeating: false,
        from_angle: Angle::zero(),
        center: ObjectPosition::default(),
        interpolation: ColorInterpolationMethod::default(),
        stops: [
          GradientStop::ColorHint {
            color: Color::from_rgb(0xff0000).into(),
            hint: Some(StopPosition(Length::Percentage(0.0))),
          },
          GradientStop::ColorHint {
            color: Color::from_rgb(0xff0000).into(),
            hint: Some(StopPosition(Length::Percentage(25.0))),
          },
          GradientStop::ColorHint {
            color: Color::from_rgb(0x0000ff).into(),
            hint: None,
          },
        ]
        .into(),
      })
    );
  }

  #[test]
  fn test_parse_conic_gradient_complex() {
    let gradient = ConicGradient::from_str("conic-gradient(from 90deg at 25% 75%, red, blue)");

    assert_eq!(
      gradient,
      Ok(ConicGradient {
        repeating: false,
        from_angle: Angle::new(90.0),
        center: BackgroundPosition::<false>(SpacePair::from_pair(
          Length::Percentage(25.0).into(),
          Length::Percentage(75.0).into()
        )),
        interpolation: ColorInterpolationMethod::default(),
        stops: [
          GradientStop::ColorHint {
            color: Color([255, 0, 0, 255]).into(),
            hint: None,
          },
          GradientStop::ColorHint {
            color: Color([0, 0, 255, 255]).into(),
            hint: None,
          },
        ]
        .into(),
      })
    );
  }

  #[test]
  fn test_conic_gradient_top_pixel_is_first_color() {
    let gradient = ConicGradient::builder()
      .stops([
        GradientStop::ColorHint {
          color: Color([255, 0, 0, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(0.0))),
        },
        GradientStop::ColorHint {
          color: Color([0, 0, 255, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(100.0))),
        },
      ])
      .build();

    let context = GlobalContext::default();
    let render_context = RenderContext::new_test(&context, Viewport::new((100, 100)));
    let tile = ConicGradientTile::new(&gradient, 100, 100, &render_context);

    // Top center (50, 0) should be red (start of gradient)
    let color_top = tile.sample_pixel(50, 0).demultiply();
    assert_eq!(color_top, ColorU8::from_rgba(255, 0, 0, 255));
  }

  #[test]
  fn test_conic_gradient_hard_stops() {
    // Simulate the card cost gradient: 3 colors with hard stops
    let gradient = ConicGradient::builder()
      .stops([
        GradientStop::ColorHint {
          color: Color([255, 0, 0, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(0.0))),
        },
        GradientStop::ColorHint {
          color: Color([255, 0, 0, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(33.0))),
        },
        GradientStop::ColorHint {
          color: Color([0, 255, 0, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(33.0))),
        },
        GradientStop::ColorHint {
          color: Color([0, 255, 0, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(66.0))),
        },
        GradientStop::ColorHint {
          color: Color([0, 0, 255, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(66.0))),
        },
        GradientStop::ColorHint {
          color: Color([0, 0, 255, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(100.0))),
        },
      ])
      .build();

    let context = GlobalContext::default();
    let render_context = RenderContext::new_test(&context, Viewport::new((100, 100)));
    let tile = ConicGradientTile::new(&gradient, 100, 100, &render_context);

    // Top-center should be red
    let top = tile.sample_pixel(50, 0).demultiply();
    assert_eq!(top, ColorU8::from_rgba(255, 0, 0, 255));

    // Bottom should be green (roughly 180deg = 50% of turn, within the 33%–66% green zone)
    let bottom = tile.sample_pixel(50, 99).demultiply();
    assert_eq!(bottom, ColorU8::from_rgba(0, 255, 0, 255));
  }

  #[test]
  fn test_repeating_conic_gradient_quadrants() {
    let gradient = ConicGradient::builder()
      .repeating(true)
      .stops([
        GradientStop::ColorHint {
          color: Color([255, 0, 0, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(0.0))),
        },
        GradientStop::ColorHint {
          color: Color([255, 0, 0, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(25.0))),
        },
        GradientStop::ColorHint {
          color: Color([0, 0, 255, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(25.0))),
        },
        GradientStop::ColorHint {
          color: Color([0, 0, 255, 255]).into(),
          hint: Some(StopPosition(Length::Percentage(50.0))),
        },
      ])
      .build();

    let context = GlobalContext::default();
    let render_context = RenderContext::new_test(&context, Viewport::new((40, 40)));
    let tile = ConicGradientTile::new(&gradient, 40, 40, &render_context);

    assert_eq!(
      [
        tile.sample_pixel(25, 15).demultiply(),
        tile.sample_pixel(25, 25).demultiply(),
        tile.sample_pixel(15, 25).demultiply(),
        tile.sample_pixel(15, 15).demultiply(),
      ],
      [
        ColorU8::from_rgba(255, 0, 0, 255),
        ColorU8::from_rgba(0, 0, 255, 255),
        ColorU8::from_rgba(255, 0, 0, 255),
        ColorU8::from_rgba(0, 0, 255, 255),
      ]
    );
  }

  #[test]
  fn test_conic_gradient_lut_index_snaps_near_floor_boundary() {
    assert_eq!(ConicGradientTile::stable_floor_index(127.9995, 360), 128);
    assert_eq!(ConicGradientTile::stable_floor_index(127.998, 360), 127);
  }

  #[test]
  fn test_conic_gradient_lut_index_snaps_near_round_boundary() {
    assert_eq!(ConicGradientTile::stable_round_index(127.4995, 360), 128);
    assert_eq!(ConicGradientTile::stable_round_index(127.498, 360), 127);
  }
}