blit-ui 0.1.0

an experimental immediate-mode ui library
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
use crate::*;

/// target motion using a tween or a spring
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Animation {
    Tween(Tween),
    Spring(Spring),
}

impl Default for Animation {
    fn default() -> Self {
        Self::Tween(Tween::default())
    }
}

impl From<Tween> for Animation {
    fn from(tween: Tween) -> Self {
        Self::Tween(tween)
    }
}

impl From<Spring> for Animation {
    fn from(spring: Spring) -> Self {
        Self::Spring(spring)
    }
}

builder! {
    /// controls how scalar motion starts and retargets
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct AnimationOptions {
        new(),
        /// starting value when first registered with `Ui::animate`
        #[into]
        initial: Option<f32> = None,
        /// discards carried velocity when retargeting
        restart: bool = false,
        /// initial spring speed or fading tween momentum in coordinate units per second
        /// `None` carries the current velocity unless restarting
        /// `Some(v)` overrides it even when `v` is zero or `restart` is true
        /// zero removes carried momentum but a tween still follows its easing
        #[into]
        velocity: Option<f32> = None,
        /// seconds to hold the current value before moving toward a new target
        /// starts from rest unless `velocity` is set
        /// ignored by zero duration animations
        delay: f32 = 0.0,
    }
}

builder! {
    /// an easing curve with a duration specifying the time to reach the target
    #[derive(Clone, Copy, Debug, Default, PartialEq)]
    pub struct Tween {
        new(
            /// seconds to reach the target
            duration: f32,
            easing: Easing,
        ),
    }
}

builder! {
    /// a linear spring tuned by duration and bounce
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct Spring {
        new(
            /// undamped period in seconds controlling the response speed
            duration: f32,
            /// positive overshoots, zero is critically damped and negative is overdamped
            bounce: f32,
        ),
        rest_distance: f32 = 0.001,
        rest_speed: f32 = 0.001,
    }
}

impl Spring {
    /// stop when both distance and speed fall within these absolute tolerances
    pub const fn rest(mut self, distance: f32, speed: f32) -> Self {
        self.rest_distance = distance;
        self.rest_speed = speed;
        self
    }
}

builder! {
    /// applies an animation to selected layout properties
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct Motion {
        new(#[into] animation: Animation),
        properties: MotionProps = MotionProps::NONE,
        /// discards carried velocity when retargeting
        restart: bool = false,
        /// seconds to hold the current layout before moving toward a new one from rest
        /// ignored by zero duration animations
        delay: f32 = 0.0,
        /// while moving to a new parent or anchor, paints above everything under this target,
        /// which is ignored unless it was built before the node
        #[into]
        lift: Option<Id> = None,
    }
}

impl Motion {
    /// animate during window resize instead of snapping to the new layout
    pub fn resize(mut self) -> Self {
        self.properties |= MotionProps::RESIZE;
        self
    }

    pub fn x(mut self) -> Self {
        self.properties |= MotionProps::X;
        self
    }

    pub fn y(mut self) -> Self {
        self.properties |= MotionProps::Y;
        self
    }

    pub fn width(mut self) -> Self {
        self.properties |= MotionProps::WIDTH;
        self
    }

    pub fn height(mut self) -> Self {
        self.properties |= MotionProps::HEIGHT;
        self
    }

    pub fn position(mut self) -> Self {
        self.properties |= MotionProps::POSITION;
        self
    }

    pub fn size(mut self) -> Self {
        self.properties |= MotionProps::SIZE;
        self
    }

    pub fn layout(mut self) -> Self {
        self.properties |= MotionProps::LAYOUT;
        self
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MotionProps(u8);

impl MotionProps {
    pub const NONE: Self = Self(0);
    pub const X: Self = Self(1 << 0);
    pub const Y: Self = Self(1 << 1);
    pub const WIDTH: Self = Self(1 << 2);
    pub const HEIGHT: Self = Self(1 << 3);
    pub const RESIZE: Self = Self(1 << 4);
    pub const POSITION: Self = Self(Self::X.0 | Self::Y.0);
    pub const SIZE: Self = Self(Self::WIDTH.0 | Self::HEIGHT.0);
    pub const LAYOUT: Self = Self(Self::POSITION.0 | Self::SIZE.0);

    pub const fn intersects(self, other: Self) -> bool {
        self.0 & other.0 != 0
    }

    pub const fn intersection(self, other: Self) -> Self {
        Self(self.0 & other.0)
    }

    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

impl BitOr for MotionProps {
    type Output = Self;

    fn bitor(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }
}

impl BitOrAssign for MotionProps {
    fn bitor_assign(&mut self, other: Self) {
        self.0 |= other.0;
    }
}

/// easing as a cubic bezier or a function
#[derive(Clone, Copy, Debug)]
pub enum Easing {
    /// control points `[x1, y1, x2, y2]`
    /// x coordinates are between zero and one and y may overshoot
    Bezier([f32; 4]),
    /// receives progress in `0..=1` and returns `(value, slope)`
    /// value must start at zero and end at one
    /// slope is the derivative with respect to progress
    Function(fn(f32) -> (f32, f32)),
}

impl Easing {
    pub const LINEAR: Self = Self::Bezier([0.0, 0.0, 1.0, 1.0]);
    pub const EASE_IN_QUAD: Self = Self::Bezier([1.0 / 3.0, 0.0, 2.0 / 3.0, 1.0 / 3.0]);
    pub const EASE_OUT_QUAD: Self = Self::Bezier([1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0, 1.0]);
    pub const EASE: Self = Self::Bezier([0.25, 0.1, 0.25, 1.0]);
    pub const EASE_IN: Self = Self::Bezier([0.42, 0.0, 1.0, 1.0]);
    pub const EASE_OUT: Self = Self::Bezier([0.0, 0.0, 0.58, 1.0]);
    pub const EASE_IN_OUT: Self = Self::Bezier([0.42, 0.0, 0.58, 1.0]);
    pub const EASE_IN_CUBIC: Self = Self::Bezier([0.32, 0.0, 0.67, 0.0]);
    pub const EASE_OUT_CUBIC: Self = Self::Bezier([0.33, 1.0, 0.68, 1.0]);
    pub const EASE_IN_OUT_CUBIC: Self = Self::Bezier([0.65, 0.0, 0.35, 1.0]);
    pub const EASE_OUT_EXPO: Self = Self::Bezier([0.16, 1.0, 0.3, 1.0]);

    /// returns the eased value and its derivative
    /// bezier slopes are capped at 1000 in either direction
    #[inline]
    pub fn sample(self, value: f32) -> (f32, f32) {
        const MAX_SLOPE: f64 = 1000.0;

        let [x1, y1, x2, y2] = match self {
            Self::Bezier(points) => points,
            Self::Function(sample) => return sample(value),
        };
        if x1 == y1 && x2 == y2 {
            return (value, 1.0);
        }
        let [y1, y2] = [y1, y2].map(f64::from);
        let value = value as f64;
        let cy = 3.0 * y1;
        let by = 3.0 * (y2 - y1) - cy;
        let ay = 1.0 - cy - by;
        if x1 == 1.0 / 3.0 && x2 == 2.0 / 3.0 {
            // a linear time axis needs no inversion
            let amount = if value <= 0.0 {
                0.0
            } else if value >= 1.0 {
                1.0
            } else {
                ((ay * value + by) * value + cy) * value
            };
            let slope = ((3.0 * ay * value + 2.0 * by) * value + cy).clamp(-MAX_SLOPE, MAX_SLOPE);
            return (amount as f32, slope as f32);
        }
        let [x1, x2] = [x1, x2].map(f64::from);
        let cx = 3.0 * x1;
        let bx = 3.0 * (x2 - x1) - cx;
        let ax = 1.0 - cx - bx;
        let mut low = 0.0;
        let mut high = 1.0;
        let mut t = value.clamp(0.0, 1.0);
        for _ in 0..32 {
            let error = ((ax * t + bx) * t + cx) * t - value;
            let derivative = (3.0 * ax * t + 2.0 * bx) * t + cx;
            if error.abs() <= derivative.abs() * 1e-10 {
                break;
            }
            if error < 0.0 {
                low = t;
            } else {
                high = t;
            }
            let next = t - error / derivative;
            t = if next > low && next < high {
                next
            } else {
                (low + high) * 0.5
            };
        }
        let dx = (3.0 * ax * t + 2.0 * bx) * t + cx;
        let dy = (3.0 * ay * t + 2.0 * by) * t + cy;
        let slope = if dx > 0.0 {
            dy / dx
        } else if t == 0.0 && y1 == 0.0 && x2 > 0.0 {
            y2 / x2
        } else if t == 1.0 && y2 == 1.0 && x1 < 1.0 {
            (1.0 - y1) / (1.0 - x1)
        } else if dy == 0.0 {
            0.0
        } else {
            dy.signum() * MAX_SLOPE
        }
        .clamp(-MAX_SLOPE, MAX_SLOPE);
        let amount = if value <= 0.0 {
            0.0
        } else if value >= 1.0 {
            1.0
        } else {
            ((ay * t + by) * t + cy) * t
        };
        (amount as f32, slope as f32)
    }
}

impl PartialEq for Easing {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Bezier(a), Self::Bezier(b)) => a == b,
            (Self::Function(a), Self::Function(b)) => core::ptr::fn_addr_eq(*a, *b),
            _ => false,
        }
    }
}

impl Default for Easing {
    fn default() -> Self {
        Self::LINEAR
    }
}

//
// internals
//

pub struct AnimationState {
    pub call: Call,
    pub playback: Playback,
    pub seen: bool,
}

impl AnimationState {
    pub fn update(animations: &mut Vec<Self>, mut call: Call, initial: f32) -> &mut Self {
        let index = loop {
            match animations.binary_search_by_key(&call, |animation| animation.call) {
                Ok(index) if animations[index].seen => call.repeat += 1,
                Ok(index) => break index,
                Err(index) => {
                    animations.insert(
                        index,
                        Self {
                            call,
                            playback: Playback::Target(Animator::new([initial], Animation::default())),
                            seen: false,
                        },
                    );
                    break index;
                }
            }
        };
        let animation = &mut animations[index];
        animation.seen = true;
        animation
    }

    pub fn is_active(&self) -> bool {
        match &self.playback {
            Playback::Target(animator) => animator.is_active(),
            Playback::Loop { .. } => true,
        }
    }
}

pub enum Playback {
    Target(Animator<f32, 1>),
    Loop { tween: Tween, time: f64, value: f32 },
}

pub struct MotionState<T: Scalar> {
    pub id: Id,
    pub animator: Animator<T, 4>,
    pub properties: MotionProps,
    pub node: NodeId,
    pub initialized: bool,
    pub seen: bool,
    // moved to another reference and still settling
    pub flying: bool,
}

impl<T: Scalar> MotionState<T> {
    pub fn new(id: Id, node: NodeId) -> Self {
        Self {
            id,
            animator: Animator::new([T::ZERO; 4], Animation::default()),
            properties: MotionProps::NONE,
            node,
            initialized: false,
            seen: true,
            flying: false,
        }
    }

    pub fn is_active(&self) -> bool {
        self.animator.is_active()
    }

    pub fn advance(
        &mut self,
        target: Rect<T>,
        config: Motion,
        now: Duration,
        resized: bool,
        commit: bool,
    ) -> ([T; 4], MotionProps) {
        let targets = [target.x, target.y, target.width, target.height];
        let options = AnimationOptions {
            initial: None,
            restart: config.restart,
            velocity: None,
            delay: config.delay,
        };
        if !self.initialized || (resized && !config.properties.intersects(MotionProps::RESIZE)) {
            if commit {
                self.animator = Animator::new(targets, config.animation);
                self.initialized = true;
            }
            return (targets, MotionProps::NONE);
        }
        let properties = [MotionProps::X, MotionProps::Y, MotionProps::WIDTH, MotionProps::HEIGHT];
        let (mut values, active) = self.animator.advance(
            targets,
            properties.map(|p| config.properties.intersects(p)),
            config.animation,
            options,
            now,
            commit,
        );
        for (i, value) in values.iter_mut().enumerate().skip(2) {
            if *value < T::ZERO {
                *value = T::ZERO;
                if commit {
                    self.animator.clamp(i, T::ZERO, T::UNBOUNDED, now);
                }
            }
        }
        let mut animated = MotionProps::NONE;
        for (i, property) in properties.into_iter().enumerate() {
            if active[i] {
                animated |= property;
            }
        }
        (values, animated)
    }
}