Skip to main content

waft_material/
ink_sparkle.rs

1//! Flutter counterpart: material_ui's `ink_sparkle.dart`.
2//!
3//! Dart's file reads the deprecated `Color.alpha` and its channels, and so does this one.
4#![allow(deprecated)]
5
6use std::f64::consts::PI;
7use std::hash::{BuildHasher, RandomState};
8use std::rc::Rc;
9use std::sync::{Arc, OnceLock};
10use std::time::Duration;
11
12use waft_animation::{
13    Animatable, AnimationBehavior, AnimationController, AnimationLocalListenersMixin,
14    AnimationLocalStatusListenersMixin, AnimationRef, AnimationStatus, AnimationStatusListener,
15    ConstantTween, CurveTween, Curves, Tween, TweenSequence, TweenSequenceItem,
16};
17use waft_embedder::{
18    Canvas, ClipOp, Color, FragmentProgram, FragmentShader, Matrix4, Offset, Paint, Shader,
19    TextDirection, UniformFloatSlot, UniformVec2Slot, UniformVec4Slot,
20};
21use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
22use waft_painting::{BorderRadius, ShapeBorder, ShapeBorderRef, get_as_translation};
23use waft_rendering::AnyRenderBox;
24
25use crate::ink_well::{
26    InteractiveInkFeatureData, InteractiveInkFeatureFactory, InteractiveInkFeatureFactoryRef,
27    InteractiveInkFeatureLeaf, InteractiveInkFeatureLeafData, InteractiveInkFeatureRef, clip_rrect,
28    rrect_from_rect_and_corners,
29};
30use crate::material::{
31    AnyMaterialInkController, InkFeature, InkFeatureData, InkFeatureLeaf, InkFeatureLeafData,
32    RectCallback,
33};
34
35/// Begin a Material 3 ink sparkle ripple, centered at the tap or click position
36/// relative to the `reference_box`.
37///
38/// To use this effect, pass an instance of [`InkSparkle::splash_factory`] to the
39/// `splash_factory` parameter of either the Material [`ThemeData`](crate::ThemeData) or any
40/// component that has a `splash_factory` parameter, such as buttons:
41///  - `ElevatedButton`
42///  - `TextButton`
43///  - `OutlinedButton`
44///
45/// The `controller` argument is typically obtained via
46/// `Material::of(app, context)`.
47///
48/// If `contained_ink_well` is true, then the effect will be sized to fit
49/// the well rectangle, and clipped to it when drawn. The well
50/// rectangle is the box returned by `rect_callback`, if provided, or
51/// otherwise is the bounds of the `reference_box`.
52///
53/// If `contained_ink_well` is false, then `rect_callback` should be null.
54/// The ink ripple is clipped only to the edges of the [`Material`](crate::Material).
55/// This is the default.
56///
57/// When the ripple is removed, `on_removed` will be called.
58///
59/// For typical use, pass the [`InkSparkle::splash_factory`] to the `splash_factory`
60/// parameter of a button style or [`ThemeData`](crate::ThemeData).
61pub struct InkSparkle {
62    ink_feature: InkFeatureData,
63    interactive_ink_feature: InteractiveInkFeatureData,
64
65    animation_controller: Option<Ref<AnimationController>>,
66
67    // The Android 12 version has these values calculated in the GLSL. They are
68    // constant for every pixel in the animation, so the Flutter implementation
69    // computes these animation values in software in order to simplify the shader
70    // implementation and provide better performance on most devices.
71    center: Option<AnimationRef<Offset>>,
72    radius_scale: Option<AnimationRef<f64>>,
73    alpha: Option<AnimationRef<f64>>,
74    sparkle_alpha: Option<AnimationRef<f64>>,
75
76    turbulence_seed: f64,
77
78    color: Color,
79    border_radius: BorderRadius,
80    target_radius: f64,
81    clip_callback: Option<RectCallback>,
82    text_direction: TextDirection,
83
84    fragment_shader: Option<FragmentShader>,
85    uniforms: Option<InkSparkleUniforms>,
86}
87
88impl InkSparkle {
89    const ANIMATION_DURATION: Duration = Duration::from_millis(617);
90    const TARGET_RADIUS_MULTIPLIER: f64 = 2.3;
91    const ROTATE_RIGHT: f64 = PI * 0.0078125;
92    const ROTATE_LEFT: f64 = -Self::ROTATE_RIGHT;
93    const NOISE_DENSITY: f64 = 2.1;
94
95    /// Begin a sparkly ripple effect, centered at `position` relative to
96    /// `reference_box`.
97    ///
98    /// The `color` defines the color of the splash itself. The sparkles are
99    /// always white.
100    ///
101    /// The `controller` argument is typically obtained via
102    /// `Material::of(app, context)`.
103    ///
104    /// `text_direction` is used by `custom_border` if it is non-null. This allows
105    /// the `custom_border`'s path to be properly defined if it was the path was
106    /// expressed in terms of "start" and "end" instead of
107    /// "left" and "right".
108    ///
109    /// If `contained_ink_well` is true, then the ripple will be sized to fit
110    /// the well rectangle, then clipped to it when drawn. The well
111    /// rectangle is the box returned by `rect_callback`, if provided, or
112    /// otherwise is the bounds of the `reference_box`.
113    ///
114    /// If `contained_ink_well` is false, then `rect_callback` should be null.
115    /// The ink ripple is clipped only to the edges of the [`Material`](crate::Material).
116    /// This is the default.
117    ///
118    /// Clipping can happen in 3 different ways:
119    ///  1. If `custom_border` is provided, it is used to determine the path for
120    ///     clipping.
121    ///  2. If `custom_border` is null, and `border_radius` is provided, then the
122    ///     canvas is clipped by an `RRect` created from `border_radius`.
123    ///  3. If `border_radius` is the default [`BorderRadius::ZERO`], then the canvas
124    ///     is clipped with `rect_callback`.
125    ///
126    /// When the ripple is removed, `on_removed` will be called.
127    ///
128    /// `turbulence_seed` can be passed if a non random seed should be used for
129    /// the turbulence and sparkles. By default, the seed is a random number
130    /// between 0.0 and 1000.0.
131    ///
132    /// Turbulence is an input to the shader and helps to provides a more natural,
133    ///  non-circular, "splash" effect.
134    ///
135    /// Sparkle randomization is also driven by the `turbulence_seed`. Sparkles are
136    /// identified in the shader as "noise", and the sparkles are derived from
137    /// pseudorandom triangular noise.
138    ///
139    /// Dart's default `contained_ink_well` is true.
140    #[allow(clippy::too_many_arguments)]
141    pub fn new(
142        app: &mut App,
143        controller: AnyMaterialInkController,
144        reference_box: AnyRenderBox,
145        color: Color,
146        position: Offset,
147        text_direction: TextDirection,
148        contained_ink_well: bool,
149        rect_callback: Option<RectCallback>,
150        border_radius: Option<BorderRadius>,
151        custom_border: Option<ShapeBorderRef>,
152        radius: Option<f64>,
153        on_removed: Option<Listener>,
154        turbulence_seed: Option<f64>,
155    ) -> Ref<InkSparkle> {
156        debug_assert!(contained_ink_well || rect_callback.is_none());
157        let target_radius = radius.unwrap_or_else(|| {
158            get_target_radius(
159                app,
160                reference_box,
161                contained_ink_well,
162                rect_callback.as_ref(),
163                position,
164            )
165        }) * Self::TARGET_RADIUS_MULTIPLIER;
166        let ink_feature = InkFeatureData::new(app, controller, reference_box, on_removed);
167        let this = app.create(InkSparkle {
168            ink_feature,
169            interactive_ink_feature: InteractiveInkFeatureData::new(color, custom_border),
170            animation_controller: None,
171            center: None,
172            radius_scale: None,
173            alpha: None,
174            sparkle_alpha: None,
175            turbulence_seed: 0.0,
176            color,
177            border_radius: border_radius.unwrap_or(BorderRadius::ZERO),
178            target_radius,
179            clip_callback: get_clip_callback(reference_box, contained_ink_well, rect_callback),
180            text_direction,
181            fragment_shader: None,
182            uniforms: None,
183        });
184        // InkSparkle will not be painted until the compilation completes.
185        InkSparkleFactory::initialize_shader();
186        controller.add_ink_feature(app, this.erase());
187        let handle = this.handle();
188
189        // Immediately begin animating the ink.
190        let vsync = controller.vsync(app);
191        let animation_controller = AnimationController::new(
192            app,
193            None,
194            Some(Self::ANIMATION_DURATION),
195            None,
196            0.0,
197            1.0,
198            AnimationBehavior::Normal,
199            vsync,
200        );
201        animation_controller.add_listener(app, controller.mark_needs_paint_listener());
202        animation_controller.add_status_listener(
203            app,
204            AnimationStatusListener::new(move |status, app| {
205                handle.handle_status_changed(app, status)
206            }),
207        );
208        animation_controller.forward(app, None);
209        let animation: AnimationRef<f64> = animation_controller.erase();
210
211        let fast_out_slow_in = CurveTween::new(app, Curves::fast_out_slow_in());
212        let one = ConstantTween::new(app, 1.0);
213        let radius_scale = TweenSequence::new(vec![
214            TweenSequenceItem::new(Rc::new(fast_out_slow_in.clone()), 75.0),
215            TweenSequenceItem::new(Rc::new(one.clone()), 25.0),
216        ])
217        .animate(app, animation.clone());
218
219        // Functionally equivalent to Android 12's SkSL:
220        //`return mix(u_touch, u_resolution, saturate(in_radius_scale * 2.0))`
221        let size = reference_box.size(app);
222        let center_tween = Tween::new(
223            app,
224            Some(Offset::new(position.dx(), position.dy())),
225            Some(Offset::new(size.width() / 2.0, size.height() / 2.0)),
226        );
227        let progress = Tween::new(app, Some(0.0), Some(1.0));
228        let center_progress = TweenSequence::new(vec![
229            TweenSequenceItem::new(Rc::new(progress.clone()), 50.0),
230            TweenSequenceItem::new(Rc::new(one.clone()), 50.0),
231        ])
232        .animate(app, radius_scale.clone());
233        let center = center_tween.animate(app, center_progress);
234
235        let fade_in = Tween::new(app, Some(0.0), Some(1.0));
236        let fade_out = Tween::new(app, Some(1.0), Some(0.0));
237        let alpha = TweenSequence::new(vec![
238            TweenSequenceItem::new(Rc::new(fade_in.clone()), 13.0),
239            TweenSequenceItem::new(Rc::new(one.clone()), 27.0),
240            TweenSequenceItem::new(Rc::new(fade_out.clone()), 60.0),
241        ])
242        .animate(app, animation.clone());
243
244        let sparkle_alpha = TweenSequence::new(vec![
245            TweenSequenceItem::new(Rc::new(fade_in.clone()), 13.0),
246            TweenSequenceItem::new(Rc::new(one.clone()), 27.0),
247            TweenSequenceItem::new(Rc::new(fade_out.clone()), 50.0),
248        ])
249        .animate(app, animation.clone());
250
251        // Creates an element of randomness so that ink emanating from the same
252        // pixel have slightly different rings and sparkles.
253        let mut turbulence_seed = turbulence_seed;
254        if cfg!(debug_assertions) {
255            // In tests, randomness can cause flakes. So if a seed has not
256            // already been specified (i.e. for the purpose of the test), set it to
257            // the constant turbulence seed.
258            turbulence_seed.get_or_insert(InkSparkleFactory::CONSTANT_SEED);
259        }
260        let turbulence_seed = turbulence_seed.unwrap_or_else(|| random_double() * 1000.0);
261
262        let sparkle = app.get_mut(handle);
263        sparkle.animation_controller = Some(animation_controller);
264        sparkle.radius_scale = Some(radius_scale);
265        sparkle.center = Some(center);
266        sparkle.alpha = Some(alpha);
267        sparkle.sparkle_alpha = Some(sparkle_alpha);
268        sparkle.turbulence_seed = turbulence_seed;
269        this
270    }
271
272    fn handle_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
273        if status.is_completed() {
274            InkFeatureLeaf::dispose(self, app);
275        }
276    }
277
278    fn animation_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
279        app.get(self)
280            .animation_controller
281            .handle()
282            .expect("created in new")
283    }
284
285    /// Used to specify this type of ink splash for an [`InkWell`](crate::InkWell),
286    /// [`InkResponse`](crate::InkResponse), material `Theme`, or `ButtonStyle`.
287    ///
288    /// Since no `turbulence_seed` is passed, the effect will be random for
289    /// subsequent presses in the same position.
290    ///
291    /// Dart's `static const`: every call hands out the same factory, so they compare equal.
292    pub fn splash_factory() -> InteractiveInkFeatureFactoryRef {
293        thread_local! {
294            static FACTORY: InteractiveInkFeatureFactoryRef =
295                Rc::new(InkSparkleFactory::new());
296        }
297        FACTORY.with(Rc::clone)
298    }
299
300    /// Used to specify this type of ink splash for an [`InkWell`](crate::InkWell),
301    /// [`InkResponse`](crate::InkResponse), material `Theme`, or `ButtonStyle`.
302    ///
303    /// Since a `turbulence_seed` is passed, the effect will not be random for
304    /// subsequent presses in the same position. This can be used for testing.
305    ///
306    /// Dart's `static const`: every call hands out the same factory, so they compare equal.
307    pub fn constant_turbulence_seed_splash_factory() -> InteractiveInkFeatureFactoryRef {
308        thread_local! {
309            static FACTORY: InteractiveInkFeatureFactoryRef =
310                Rc::new(InkSparkleFactory::constant_turbulence_seed());
311        }
312        FACTORY.with(Rc::clone)
313    }
314
315    fn width(self: Handle<Self>, app: &App) -> f64 {
316        InkFeature::reference_box(self, app).size(app).width()
317    }
318
319    fn height(self: Handle<Self>, app: &App) -> f64 {
320        InkFeature::reference_box(self, app).size(app).height()
321    }
322
323    /// All double values for uniforms come from the Android 12 ripple
324    /// implementation from the following files:
325    /// - <https://cs.android.com/android/platform/superproject/+/main:frameworks/base/graphics/java/android/graphics/drawable/RippleShader.java>
326    /// - <https://cs.android.com/android/platform/superproject/+/main:frameworks/base/graphics/java/android/graphics/drawable/RippleDrawable.java>
327    /// - <https://cs.android.com/android/platform/superproject/+/main:frameworks/base/graphics/java/android/graphics/drawable/RippleAnimationSession.java>
328    fn update_fragment_shader(self: Handle<Self>, app: &mut App) {
329        const TURBULENCE_SCALE: f64 = 1.5;
330        let sparkle = app.get(self);
331        let radius_scale = sparkle
332            .radius_scale
333            .as_ref()
334            .expect("created in new")
335            .value(app);
336        let alpha = sparkle.alpha.as_ref().expect("created in new").value(app);
337        let sparkle_alpha = sparkle
338            .sparkle_alpha
339            .as_ref()
340            .expect("created in new")
341            .value(app);
342        let center = sparkle.center.as_ref().expect("created in new").value(app);
343        let color = sparkle.color;
344        let target_radius = sparkle.target_radius;
345        let turbulence_phase = sparkle.turbulence_seed + radius_scale;
346        let noise_phase = turbulence_phase;
347        let rotation1 = turbulence_phase * Self::ROTATE_RIGHT + 1.7 * PI;
348        let rotation2 = turbulence_phase * Self::ROTATE_LEFT + 2.0 * PI;
349        let rotation3 = turbulence_phase * Self::ROTATE_RIGHT + 2.75 * PI;
350        let width = self.width(app);
351        let height = self.height(app);
352
353        let sparkle = app.get_mut(self);
354        let uniforms = sparkle.uniforms.expect("made with the shader");
355        let shader = sparkle
356            .fragment_shader
357            .as_mut()
358            .expect("made in paint_feature");
359        uniforms.color.set(
360            shader,
361            f64::from(color.red()) / 255.0,
362            f64::from(color.green()) / 255.0,
363            f64::from(color.blue()) / 255.0,
364            f64::from(color.alpha()) / 255.0,
365        );
366        // u_composite_1 packs u_alpha, u_sparkle_alpha, u_blur and u_radius_scale.
367        uniforms
368            .composite1
369            .set(shader, alpha, sparkle_alpha, 1.0, radius_scale);
370        uniforms.center.set(shader, center.dx(), center.dy());
371        uniforms.max_radius.set(shader, target_radius);
372        uniforms
373            .resolution_scale
374            .set(shader, 1.0 / width, 1.0 / height);
375        uniforms.noise_scale.set(
376            shader,
377            Self::NOISE_DENSITY / width,
378            Self::NOISE_DENSITY / height,
379        );
380        uniforms.noise_phase.set(shader, noise_phase / 1000.0);
381        uniforms.circle1.set(
382            shader,
383            TURBULENCE_SCALE * 0.5 + (turbulence_phase * 0.01 * (TURBULENCE_SCALE * 0.55).cos()),
384            TURBULENCE_SCALE * 0.5 + (turbulence_phase * 0.01 * (TURBULENCE_SCALE * 0.55).sin()),
385        );
386        uniforms.circle2.set(
387            shader,
388            TURBULENCE_SCALE * 0.2 + (turbulence_phase * -0.0066 * (TURBULENCE_SCALE * 0.45).cos()),
389            TURBULENCE_SCALE * 0.2 + (turbulence_phase * -0.0066 * (TURBULENCE_SCALE * 0.45).sin()),
390        );
391        uniforms.circle3.set(
392            shader,
393            TURBULENCE_SCALE + (turbulence_phase * -0.0066 * (TURBULENCE_SCALE * 0.35).cos()),
394            TURBULENCE_SCALE + (turbulence_phase * -0.0066 * (TURBULENCE_SCALE * 0.35).sin()),
395        );
396        uniforms
397            .rotation1
398            .set(shader, rotation1.cos(), rotation1.sin());
399        uniforms
400            .rotation2
401            .set(shader, rotation2.cos(), rotation2.sin());
402        uniforms
403            .rotation3
404            .set(shader, rotation3.cos(), rotation3.sin());
405    }
406
407    /// Transforms the canvas for an ink feature to be painted on the `canvas`.
408    ///
409    /// This should be called before painting ink features that do not use
410    /// `paint_ink_circle`.
411    ///
412    /// The `transform` argument is the [`Matrix4`] transform that typically
413    /// shifts the coordinate space of the canvas to the space in which
414    /// the ink feature is to be painted.
415    ///
416    /// For examples on how the function is used, see [`InkSparkle`] and `paint_ink_circle`.
417    fn transform_canvas(canvas: &mut Canvas, transform: &Matrix4) {
418        match get_as_translation(*transform) {
419            None => canvas.concat(transform),
420            Some(origin_offset) => {
421                canvas.translate(origin_offset.dx() as f32, origin_offset.dy() as f32)
422            }
423        }
424    }
425
426    /// Clips the canvas for an ink feature to be painted on the `canvas`.
427    ///
428    /// This should be called before painting ink features with `paint_feature`
429    /// that do not use `paint_ink_circle`.
430    ///
431    /// The `clip_callback` is the callback used to obtain the `Rect` used for clipping
432    /// the ink effect.
433    ///
434    /// If `clip_callback` is null, no clipping is performed on the ink circle.
435    ///
436    /// The `text_direction` is used by `custom_border` if it is non-null. This
437    /// allows the `custom_border`'s path to be properly defined if the path was
438    /// expressed in terms of "start" and "end" instead of "left" and "right".
439    ///
440    /// For examples on how the function is used, see [`InkSparkle`].
441    fn clip_canvas(
442        app: &App,
443        canvas: &mut Canvas,
444        clip_callback: &RectCallback,
445        text_direction: Option<TextDirection>,
446        custom_border: Option<&dyn ShapeBorder>,
447        border_radius: BorderRadius,
448    ) {
449        let rect = clip_callback(app);
450        if let Some(custom_border) = custom_border {
451            let path = custom_border.get_outer_path(rect, text_direction);
452            canvas.clip_path(path.as_valo(), path.fill_type, ClipOp::Intersect, true);
453        } else if border_radius != BorderRadius::ZERO {
454            clip_rrect(canvas, rrect_from_rect_and_corners(rect, border_radius));
455        } else {
456            canvas.clip_rect(rect, ClipOp::Intersect, true);
457        }
458    }
459}
460
461/// Dart's random `math.Random().nextDouble()`, from the entropy `RandomState` holds.
462fn random_double() -> f64 {
463    let bits = RandomState::new().hash_one(0u8) >> 11;
464    bits as f64 / (1u64 << 53) as f64
465}
466
467impl InkFeatureLeafData for InkSparkle {
468    fn ink_feature(&self) -> &InkFeatureData {
469        &self.ink_feature
470    }
471
472    fn ink_feature_mut(&mut self) -> &mut InkFeatureData {
473        &mut self.ink_feature
474    }
475}
476
477impl InteractiveInkFeatureLeafData for InkSparkle {
478    fn interactive_ink_feature(&self) -> &InteractiveInkFeatureData {
479        &self.interactive_ink_feature
480    }
481
482    fn interactive_ink_feature_mut(&mut self) -> &mut InteractiveInkFeatureData {
483        &mut self.interactive_ink_feature
484    }
485}
486
487impl InteractiveInkFeatureLeaf for InkSparkle {}
488
489impl InkFeatureLeaf for InkSparkle {
490    fn dispose(self: Handle<Self>, app: &mut App) {
491        let animation_controller = self.animation_controller(app);
492        animation_controller.stop(app, true);
493        animation_controller.dispose(app);
494        app.get_mut(self).fragment_shader = None;
495        InkFeature::dispose(self, app);
496    }
497
498    fn paint_feature(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, transform: &Matrix4) {
499        debug_assert!(self.animation_controller(app).is_animating(app));
500
501        // InkSparkle can only paint if its shader has been compiled.
502        let Some(program) = InkSparkleFactory::program() else {
503            // Skipping paintFeature because the shader it relies on is not ready to
504            // be used. InkSparkleFactory.initializeShader must complete
505            // before InkSparkle can paint.
506            return;
507        };
508
509        if app.get(self).fragment_shader.is_none() {
510            let fragment_shader = program.fragment_shader();
511            let uniforms = InkSparkleUniforms::new(&fragment_shader);
512            let sparkle = app.get_mut(self);
513            sparkle.fragment_shader = Some(fragment_shader);
514            sparkle.uniforms = Some(uniforms);
515        }
516
517        canvas.save();
518        InkSparkle::transform_canvas(canvas, transform);
519        let sparkle = app.get(self);
520        if let Some(clip_callback) = &sparkle.clip_callback {
521            InkSparkle::clip_canvas(
522                app,
523                canvas,
524                clip_callback,
525                Some(sparkle.text_direction),
526                sparkle.interactive_ink_feature.custom_border_ref(),
527                sparkle.border_radius,
528            );
529        }
530
531        self.update_fragment_shader(app);
532
533        let sparkle = app.get(self);
534        let paint = Paint::from_shader(Shader::from(
535            sparkle.fragment_shader.as_ref().expect("made above"),
536        ));
537        match &sparkle.clip_callback {
538            Some(clip_callback) => canvas.draw_rect(clip_callback(app), &paint),
539            None => canvas.draw_paint(&paint),
540        }
541        canvas.restore();
542    }
543}
544
545/// The uniforms declared in `shaders/ink_sparkle.wgsl`, Dart's `lib/shaders/ink_sparkle.frag`, looked up by name once
546/// so that [`InkSparkle`] only has to set their values on each frame.
547#[derive(Clone, Copy)]
548struct InkSparkleUniforms {
549    color: UniformVec4Slot,
550    composite1: UniformVec4Slot,
551    center: UniformVec2Slot,
552    max_radius: UniformFloatSlot,
553    resolution_scale: UniformVec2Slot,
554    noise_scale: UniformVec2Slot,
555    noise_phase: UniformFloatSlot,
556    circle1: UniformVec2Slot,
557    circle2: UniformVec2Slot,
558    circle3: UniformVec2Slot,
559    rotation1: UniformVec2Slot,
560    rotation2: UniformVec2Slot,
561    rotation3: UniformVec2Slot,
562}
563
564impl InkSparkleUniforms {
565    fn new(shader: &FragmentShader) -> InkSparkleUniforms {
566        let vec4 = |name: &str| {
567            shader
568                .get_uniform_vec4(name)
569                .expect("ink_sparkle.wgsl declares it")
570        };
571        let vec2 = |name: &str| {
572            shader
573                .get_uniform_vec2(name)
574                .expect("ink_sparkle.wgsl declares it")
575        };
576        let float = |name: &str| {
577            shader
578                .get_uniform_float(name, None)
579                .expect("ink_sparkle.wgsl declares it")
580        };
581        InkSparkleUniforms {
582            color: vec4("u_color"),
583            composite1: vec4("u_composite_1"),
584            center: vec2("u_center"),
585            max_radius: float("u_max_radius"),
586            resolution_scale: vec2("u_resolution_scale"),
587            noise_scale: vec2("u_noise_scale"),
588            noise_phase: float("u_noise_phase"),
589            circle1: vec2("u_circle1"),
590            circle2: vec2("u_circle2"),
591            circle3: vec2("u_circle3"),
592            rotation1: vec2("u_rotation1"),
593            rotation2: vec2("u_rotation2"),
594            rotation3: vec2("u_rotation3"),
595        }
596    }
597}
598
599/// Dart's `static bool _initCalled` and `static ui.FragmentProgram? _program`, one value here: the
600/// program is made in the first [`InkSparkleFactory::initialize_shader`] call, so the call having
601/// run and the program being there are one state. One program serves every thread, as the
602/// engine's registry caches one per asset.
603static PROGRAM: OnceLock<Arc<FragmentProgram>> = OnceLock::new();
604
605/// Dart's `_InkSparkleFactory`.
606#[derive(Debug)]
607struct InkSparkleFactory {
608    turbulence_seed: Option<f64>,
609}
610
611impl InkSparkleFactory {
612    const CONSTANT_SEED: f64 = 1337.0;
613
614    const fn new() -> InkSparkleFactory {
615        InkSparkleFactory {
616            turbulence_seed: None,
617        }
618    }
619
620    const fn constant_turbulence_seed() -> InkSparkleFactory {
621        InkSparkleFactory {
622            turbulence_seed: Some(InkSparkleFactory::CONSTANT_SEED),
623        }
624    }
625
626    /// Dart's `initializeShader`: makes the program from `ink_sparkle.wgsl`, Dart's
627    /// `packages/material_ui/shaders/ink_sparkle.frag`, on the first call.
628    fn initialize_shader() {
629        PROGRAM.get_or_init(|| {
630            FragmentProgram::from_wgsl(include_str!("shaders/ink_sparkle.wgsl"))
631                .expect("ink_sparkle.wgsl is a valid program")
632        });
633    }
634
635    /// Dart's `_program`: the compiled `ink_sparkle.wgsl`, once it has loaded.
636    fn program() -> Option<Arc<FragmentProgram>> {
637        PROGRAM.get().cloned()
638    }
639}
640
641impl InteractiveInkFeatureFactory for InkSparkleFactory {
642    fn create(
643        &self,
644        app: &mut App,
645        controller: AnyMaterialInkController,
646        reference_box: AnyRenderBox,
647        position: Offset,
648        color: Color,
649        text_direction: TextDirection,
650        contained_ink_well: bool,
651        rect_callback: Option<RectCallback>,
652        border_radius: Option<BorderRadius>,
653        custom_border: Option<ShapeBorderRef>,
654        radius: Option<f64>,
655        on_removed: Option<Listener>,
656    ) -> InteractiveInkFeatureRef {
657        InkSparkle::new(
658            app,
659            controller,
660            reference_box,
661            color,
662            position,
663            text_direction,
664            contained_ink_well,
665            rect_callback,
666            border_radius,
667            custom_border,
668            radius,
669            on_removed,
670            self.turbulence_seed,
671        )
672        .into_erased()
673    }
674}
675
676fn get_clip_callback(
677    reference_box: AnyRenderBox,
678    contained_ink_well: bool,
679    rect_callback: Option<RectCallback>,
680) -> Option<RectCallback> {
681    if let Some(rect_callback) = rect_callback {
682        debug_assert!(contained_ink_well);
683        return Some(rect_callback);
684    }
685    if contained_ink_well {
686        return Some(Rc::new(move |app| Offset::ZERO & reference_box.size(app)));
687    }
688    None
689}
690
691fn get_target_radius(
692    app: &App,
693    reference_box: AnyRenderBox,
694    _contained_ink_well: bool,
695    rect_callback: Option<&RectCallback>,
696    _position: Offset,
697) -> f64 {
698    let size = match rect_callback {
699        Some(rect_callback) => rect_callback(app).size(),
700        None => reference_box.size(app),
701    };
702    let d1 = size.bottom_right(Offset::ZERO).distance();
703    let d2 = (size.top_right(Offset::ZERO) - size.bottom_left(Offset::ZERO)).distance();
704    d1.max(d2) / 2.0
705}
706
707#[cfg(test)]
708mod tests {
709    use waft_embedder::valo;
710    use waft_widgets::{Center, Directionality, IntoWidget, SizedBox, WidgetRef};
711
712    use waft_widgets::testing::{WidgetTester, test_widgets};
713
714    use super::*;
715    use crate::elevated_button::ElevatedButton;
716    use crate::ink_well::{InkResponse, InkWell};
717    use crate::material::{Material, RenderInkFeatures};
718    use crate::test_support::PaintInspection;
719
720    fn frame<K>(child: impl IntoWidget<K>) -> WidgetRef {
721        Directionality::new(
722            TextDirection::Ltr,
723            Material::new().child(Center::new().child(child)),
724        )
725        .into_widget()
726    }
727
728    fn ink_features(tester: &WidgetTester) -> usize {
729        let render = tester.first::<RenderInkFeatures>();
730        render
731            .debug_ink_features(&tester.cell.borrow())
732            .unwrap_or_default()
733            .len()
734    }
735
736    /// The rects and the paints the material's ink draws with a fragment shader, each with that
737    /// shader.
738    fn shader_draws(
739        tester: &WidgetTester,
740    ) -> (
741        Vec<(waft_embedder::Rect, valo::RuntimeShader)>,
742        Vec<valo::RuntimeShader>,
743    ) {
744        let runtime = |paint: &valo::Paint| match &paint.shader {
745            Some(valo::Shader::Runtime(shader)) => Some(shader.clone()),
746            _ => None,
747        };
748        let list = tester.ink_list();
749        let mut rects = Vec::new();
750        let mut paints = Vec::new();
751        for op in list.ops() {
752            match op {
753                valo::Op::DrawRect { rect, paint, .. } => {
754                    let rect = waft_embedder::Rect::from_ltwh(
755                        f64::from(rect.x),
756                        f64::from(rect.y),
757                        f64::from(rect.width),
758                        f64::from(rect.height),
759                    );
760                    rects.extend(runtime(paint).map(|shader| (rect, shader)));
761                }
762                valo::Op::DrawPaint { paint, .. } => paints.extend(runtime(paint)),
763                _ => {}
764            }
765        }
766        (rects, paints)
767    }
768
769    /// How many rects and paints the material's ink draws, with a shader or without.
770    fn draw_counts(tester: &WidgetTester) -> (usize, usize) {
771        let list = tester.ink_list();
772        let rects = list
773            .ops()
774            .iter()
775            .filter(|op| matches!(op, valo::Op::DrawRect { .. }))
776            .count();
777        let paints = list
778            .ops()
779            .iter()
780            .filter(|op| matches!(op, valo::Op::DrawPaint { .. }))
781            .count();
782        (rects, paints)
783    }
784
785    /// The `count` floats of the uniform named `name` in `shader`'s bytes, read where WGSL lays
786    /// them out.
787    fn uniform(shader: &valo::RuntimeShader, name: &str, count: u32) -> Vec<f32> {
788        let field = shader
789            .effect
790            .uniforms()
791            .field(name)
792            .unwrap_or_else(|| panic!("ink_sparkle.wgsl declares {name}"));
793        (0..count)
794            .map(|component| {
795                let at = (field.offset + component * 4) as usize;
796                f32::from_le_bytes(shader.uniforms[at..at + 4].try_into().expect("four bytes"))
797            })
798            .collect()
799    }
800
801    fn assert_uniform(shader: &valo::RuntimeShader, name: &str, expected: &[f64]) {
802        let actual = uniform(shader, name, expected.len() as u32);
803        for (actual, expected) in actual.iter().zip(expected) {
804            waft_widgets::testing::assert_f32_equals(f64::from(*actual), *expected);
805        }
806    }
807
808    /// Dart's `InkSparkle in a Button compiles and does not crash`.
809    #[test]
810    fn ink_sparkle_in_a_button_compiles_and_does_not_crash() {
811        test_widgets(|tester| {
812            tester.pump_widget(frame(
813                ElevatedButton::new(
814                    Some(Listener::new(|_app| {})),
815                    Some(SizedBox::new().width(80.0).height(20.0)),
816                )
817                .style(
818                    ElevatedButton::style_from()
819                        .splash_factory(InkSparkle::splash_factory())
820                        .build(),
821                ),
822            ));
823            tester.tap_at(WidgetTester::SIZE.center(Offset::ZERO), 1);
824            tester.pump();
825            tester.pump_and_settle();
826            assert!(InkSparkleFactory::program().is_some());
827        });
828    }
829
830    /// Dart's `InkSparkle default splashFactory paints with drawRect when bounded`.
831    #[test]
832    fn ink_sparkle_default_splash_factory_paints_with_draw_rect_when_bounded() {
833        test_widgets(|tester| {
834            tester.pump_widget(frame(
835                InkWell::new()
836                    .splash_factory(InkSparkle::splash_factory())
837                    .child(SizedBox::new().width(80.0).height(20.0))
838                    .on_tap(Listener::new(|_app| {})),
839            ));
840            tester.tap_at(WidgetTester::SIZE.center(Offset::ZERO), 1);
841            tester.pump();
842            tester.pump_by(Duration::from_millis(200));
843
844            assert_eq!(draw_counts(tester).0, 1);
845            let (rects, _) = shader_draws(tester);
846            assert_eq!(
847                rects.iter().map(|(rect, _)| *rect).collect::<Vec<_>>(),
848                [waft_embedder::Rect::from_ltwh(0.0, 0.0, 80.0, 20.0)]
849            );
850
851            assert_eq!(ink_features(tester), 1);
852
853            tester.pump_and_settle();
854            // ink feature is disposed.
855            assert_eq!(ink_features(tester), 0);
856        });
857    }
858
859    /// Dart's `InkSparkle default splashFactory paints with drawPaint when unbounded`.
860    #[test]
861    fn ink_sparkle_default_splash_factory_paints_with_draw_paint_when_unbounded() {
862        test_widgets(|tester| {
863            tester.pump_widget(frame(
864                InkResponse::new()
865                    .splash_factory(InkSparkle::splash_factory())
866                    .child(SizedBox::new().width(80.0).height(20.0))
867                    .on_tap(Listener::new(|_app| {})),
868            ));
869            tester.tap_at(WidgetTester::SIZE.center(Offset::ZERO), 1);
870            tester.pump();
871            tester.pump_by(Duration::from_millis(200));
872
873            assert_eq!(draw_counts(tester).1, 1);
874            assert_eq!(shader_draws(tester).1.len(), 1);
875        });
876    }
877
878    /// What Dart's goldens show, as numbers: the uniforms `_updateFragmentShader` sets at 50
879    /// milliseconds into the animation of a sparkle with the constant turbulence seed, tapped
880    /// off the well's centre.
881    #[test]
882    fn the_sparkle_sets_its_uniforms_from_the_animation_and_the_constant_turbulence_seed() {
883        test_widgets(|tester| {
884            let color = Color::new(0x66AA3300);
885            tester.pump_widget(frame(
886                InkWell::new()
887                    .splash_factory(InkSparkle::constant_turbulence_seed_splash_factory())
888                    .splash_color(color)
889                    .child(SizedBox::new().width(80.0).height(20.0))
890                    .on_tap(Listener::new(|_app| {})),
891            ));
892            let well_center = WidgetTester::SIZE.center(Offset::ZERO);
893            tester.tap_at(well_center + Offset::new(-30.0, -5.0), 1);
894            tester.pump();
895            tester.pump_by(Duration::from_millis(50));
896
897            let (rects, _) = shader_draws(tester);
898            let [(_, shader)] = rects.as_slice() else {
899                panic!("one sparkle rect, not {}", rects.len());
900            };
901
902            let t = 50.0 / 617.0;
903            let radius_scale = Curves::fast_out_slow_in().transform(t / 0.75);
904            let alpha = t / 0.13;
905            let sparkle_alpha = t / (13.0 / 90.0);
906            let center_progress = radius_scale / 0.5;
907            let position = Offset::new(10.0, 5.0);
908            let center = position + (Offset::new(40.0, 10.0) - position) * center_progress;
909            let target_radius = (80.0f64.hypot(20.0) / 2.0) * 2.3;
910            let turbulence_phase = 1337.0 + radius_scale;
911            let rotation = |offset: f64, direction: f64| {
912                let angle = turbulence_phase * direction * PI * 0.0078125 + offset * PI;
913                [angle.cos(), angle.sin()]
914            };
915            let circle = |base: f64, speed: f64, scale: f64| {
916                [
917                    base + turbulence_phase * speed * scale.cos(),
918                    base + turbulence_phase * speed * scale.sin(),
919                ]
920            };
921
922            assert_uniform(
923                shader,
924                "u_color",
925                &[170.0 / 255.0, 51.0 / 255.0, 0.0, f64::from(0x66) / 255.0],
926            );
927            assert_uniform(
928                shader,
929                "u_composite_1",
930                &[alpha, sparkle_alpha, 1.0, radius_scale],
931            );
932            assert_uniform(shader, "u_center", &[center.dx(), center.dy()]);
933            assert_uniform(shader, "u_max_radius", &[target_radius]);
934            assert_uniform(shader, "u_resolution_scale", &[1.0 / 80.0, 1.0 / 20.0]);
935            assert_uniform(shader, "u_noise_scale", &[2.1 / 80.0, 2.1 / 20.0]);
936            assert_uniform(shader, "u_noise_phase", &[turbulence_phase / 1000.0]);
937            assert_uniform(shader, "u_circle1", &circle(0.75, 0.01, 1.5 * 0.55));
938            assert_uniform(shader, "u_circle2", &circle(0.3, -0.0066, 1.5 * 0.45));
939            assert_uniform(shader, "u_circle3", &circle(1.5, -0.0066, 1.5 * 0.35));
940            assert_uniform(shader, "u_rotation1", &rotation(1.7, 1.0));
941            assert_uniform(shader, "u_rotation2", &rotation(2.0, -1.0));
942            assert_uniform(shader, "u_rotation3", &rotation(2.75, 1.0));
943        });
944    }
945
946    /// `ink_sparkle.wgsl` declares the GLSL's uniforms in its order, so each slot is at the
947    /// float index Flutter's `ink_sparkle.frag` gives it.
948    #[test]
949    fn the_shader_keeps_the_glsl_float_index_of_every_uniform() {
950        InkSparkleFactory::initialize_shader();
951        let shader = InkSparkleFactory::program()
952            .expect("loaded")
953            .fragment_shader();
954        let index = |name: &str| {
955            shader
956                .get_uniform_float(name, Some(0))
957                .expect("ink_sparkle.wgsl declares it")
958                .shader_index()
959        };
960        let indices: Vec<usize> = [
961            "u_color",
962            "u_composite_1",
963            "u_center",
964            "u_max_radius",
965            "u_resolution_scale",
966            "u_noise_scale",
967            "u_noise_phase",
968            "u_circle1",
969            "u_circle2",
970            "u_circle3",
971            "u_rotation1",
972            "u_rotation2",
973            "u_rotation3",
974        ]
975        .into_iter()
976        .map(index)
977        .collect();
978        assert_eq!(indices, [0, 4, 8, 10, 11, 13, 15, 16, 18, 20, 22, 24, 26]);
979    }
980
981    /// Dart's `_InkSparkleFactory._program`: one program, loaded once, serves every sparkle.
982    #[test]
983    fn every_sparkle_draws_with_the_one_program() {
984        InkSparkleFactory::initialize_shader();
985        let first = InkSparkleFactory::program().expect("loaded");
986        InkSparkleFactory::initialize_shader();
987        assert!(Arc::ptr_eq(
988            &first,
989            &InkSparkleFactory::program().expect("loaded")
990        ));
991    }
992
993    #[test]
994    fn the_splash_factories_are_constants() {
995        assert!(Rc::ptr_eq(
996            &InkSparkle::splash_factory(),
997            &InkSparkle::splash_factory()
998        ));
999        assert!(Rc::ptr_eq(
1000            &InkSparkle::constant_turbulence_seed_splash_factory(),
1001            &InkSparkle::constant_turbulence_seed_splash_factory()
1002        ));
1003        assert!(!Rc::ptr_eq(
1004            &InkSparkle::splash_factory(),
1005            &InkSparkle::constant_turbulence_seed_splash_factory()
1006        ));
1007    }
1008}