OXYGENHUB
# 0a3b244b748f oxygenhub / crates / backdrop / src / sky.rs
19.1 KiB · Rust · last changed feat(web): a denser sky, every change and run a mark; short links; the name above (refs #157) 22 days ago source blame history raw
1
//! Your sky (docs/backgrounds.md §5): the dashboard's scene, its layout
2
//! and its motion, with no browser in it so it is tested natively.
3
//!
4
//! Each repository is a cluster placed by a hash of its name, so a
5
//! viewer's sky is the same on every visit; its events of the last 30 days
6
//! orbit it as marks, brightest when newest, shaped by kind. The cursor
7
//! lights marks near it without moving them, and joins the lit marks of
8
//! one repository in the order they happened.
9
10
use std::f32::consts::TAU;
11
12
/// How far the cursor lights marks, in CSS pixels (§4).
13
pub const LIGHT_RADIUS: f32 = 140.0;
14
/// Seconds a mark takes to light, and to fade.
15
const LIT_IN: f32 = 0.15;
16
const LIT_OUT: f32 = 0.6;
17
/// The fastest a mark drifts, in CSS pixels a second.
18
pub const MAX_SPEED: f32 = 12.0;
19
/// How far each depth layer shifts against the cursor, front to back.
20
const PARALLAX: [f32; 3] = [6.0, 3.0, 1.0];
21
/// The longest link: only marks that happened one after another and sit
22
/// near each other are joined, so a busy repository reads as a
23
/// constellation, not a scribble.
24
const LINK_MAX: f32 = 70.0;
25
/// Links fade when the cursor has rested this long, in seconds.
26
const LINK_REST: f32 = 2.0;
27
/// A resting cursor this near a cluster's core names it, after this long.
28
const LABEL_NEAR: f32 = 90.0;
29
const LABEL_REST: f32 = 0.4;
30
/// Events older than this many days are not drawn.
31
pub const DAYS: f32 = 30.0;
32
/// The most marks one push makes (one a change), and in all.
33
const PER_PUSH: u32 = 40;
34
const MAX_MARKS: usize = 3000;
35
36
/// What a mark stands for, which decides its shape.
37
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38
pub enum Kind {
39
    Push,
40
    Proposal,
41
    Issue,
42
    Release,
43
    /// A Flow run.
44
    Run,
45
    /// The repository itself, its cluster's core.
46
    Repo,
47
}
48
49
impl Kind {
50
    /// The code the page's data uses: 0 a push's change, 1 a proposal
51
    /// event, 2 an issue event, 3 a release, 4 a Flow run.
52
    pub fn from_code(code: u32) -> Kind {
53
        match code {
54
            1 => Kind::Proposal,
55
            2 => Kind::Issue,
56
            3 => Kind::Release,
57
            4 => Kind::Run,
58
            _ => Kind::Push,
59
        }
60
    }
61
62
    /// The shape the fragment shader draws: 0 dot, 1 diamond, 2 ring,
63
    /// 3 four-point star, 4 thin ring (a repository), 5 square.
64
    pub fn shape(self) -> f32 {
65
        match self {
66
            Kind::Push => 0.0,
67
            Kind::Proposal => 1.0,
68
            Kind::Issue => 2.0,
69
            Kind::Release => 3.0,
70
            Kind::Repo => 4.0,
71
            Kind::Run => 5.0,
72
        }
73
    }
74
75
    /// Its radius in CSS pixels.
76
    fn size(self) -> f32 {
77
        match self {
78
            Kind::Push => 2.0,
79
            Kind::Run => 2.2,
80
            Kind::Proposal => 3.2,
81
            Kind::Issue => 3.0,
82
            Kind::Release => 4.2,
83
            Kind::Repo => 6.0,
84
        }
85
    }
86
}
87
88
/// One repository, as the page gives it.
89
#[derive(Clone, Debug)]
90
pub struct Repo {
91
    pub name: String,
92
}
93
94
/// One event, as the page gives it: its repository (an index into the
95
/// repositories), its kind, how old it is, and how many marks it makes (a
96
/// push's changes; one otherwise).
97
#[derive(Clone, Copy, Debug)]
98
pub struct Event {
99
    pub repo: usize,
100
    pub kind: Kind,
101
    pub age_days: f32,
102
    pub n: u32,
103
}
104
105
/// A repository's place: a fraction of the view, and a depth layer.
106
#[derive(Clone, Debug)]
107
pub struct Cluster {
108
    pub name: String,
109
    pub fx: f32,
110
    pub fy: f32,
111
    pub layer: usize,
112
}
113
114
/// One drawn mark, orbiting its cluster.
115
#[derive(Clone, Debug)]
116
pub struct Mark {
117
    pub cluster: usize,
118
    pub kind: Kind,
119
    /// Its place in its cluster's history, 0 the newest; the core is 0
120
    /// too and has radius 0.
121
    pub order: u32,
122
    pub radius: f32,
123
    pub angle: f32,
124
    /// Radians a second, signed.
125
    pub speed: f32,
126
    /// 1 for today, fading to 0.3 for a month ago.
127
    pub bright: f32,
128
    /// How lit it is now, 0 to 1.
129
    pub lit: f32,
130
}
131
132
/// Straight RGBA, 0 to 1, as the page's tokens give them.
133
pub type Rgba = [f32; 4];
134
135
/// The three backdrop tokens (§3).
136
#[derive(Clone, Copy, Debug, PartialEq)]
137
pub struct Colours {
138
    pub mark: Rgba,
139
    pub lit: Rgba,
140
    pub link: Rgba,
141
}
142
143
/// The scene.
144
pub struct Sky {
145
    pub clusters: Vec<Cluster>,
146
    pub marks: Vec<Mark>,
147
    /// The view, in CSS pixels.
148
    pub w: f32,
149
    pub h: f32,
150
    /// Where the cursor is, if it is over the page.
151
    pub cursor: Option<(f32, f32)>,
152
    /// Seconds since the cursor last moved.
153
    pub rested: f32,
154
    /// Still (reduced motion, or the viewer's choice): no drift, no
155
    /// parallax, and marks light at once.
156
    pub still: bool,
157
    parallax: [(f32, f32); 3],
158
    link_fade: f32,
159
}
160
161
/// FNV-1a: a small, stable hash, so a repository's place never changes.
162
pub fn hash(s: &str) -> u64 {
163
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
164
    for b in s.as_bytes() {
165
        h ^= *b as u64;
166
        h = h.wrapping_mul(0x0100_0000_01b3);
167
    }
168
    h
169
}
170
171
/// A number from 0 to 1 from bits of a hash.
172
fn unit(h: u64, shift: u32) -> f32 {
173
    ((h >> shift) & 0xffff) as f32 / 65536.0
174
}
175
176
impl Sky {
177
    /// The sky of `repos` and their `events` (newest first, as the page
178
    /// lists them), in a view of `w` by `h` CSS pixels.
179
    pub fn new(repos: &[Repo], events: &[Event], w: f32, h: f32, still: bool) -> Sky {
180
        // The most active repositories in front, the quiet ones behind.
181
        let mut activity = vec![0u32; repos.len()];
182
        for e in events {
183
            if e.repo < repos.len() && e.age_days <= DAYS {
184
                activity[e.repo] += 1;
185
            }
186
        }
187
        let mut rank: Vec<usize> = (0..repos.len()).collect();
188
        rank.sort_by_key(|&i| std::cmp::Reverse(activity[i]));
189
        let mut layer = vec![2usize; repos.len()];
190
        for (pos, &i) in rank.iter().enumerate() {
191
            layer[i] = (pos * 3 / repos.len().max(1)).min(2);
192
        }
193
        let clusters: Vec<Cluster> = repos
194
            .iter()
195
            .enumerate()
196
            .map(|(i, r)| {
197
                let h = hash(&r.name);
198
                // Around the page, mostly in its margins: a ring from a
199
                // quarter to just past half of the view out.
200
                let a = unit(h, 0) * TAU;
201
                let d = 0.25 + 0.3 * unit(h, 16).sqrt();
202
                Cluster {
203
                    name: r.name.clone(),
204
                    fx: (0.5 + d * a.cos()).clamp(0.03, 0.97),
205
                    fy: (0.5 + 0.9 * d * a.sin()).clamp(0.05, 0.95),
206
                    layer: layer[i],
207
                }
208
            })
209
            .collect();
210
        let mut marks: Vec<Mark> = Vec::new();
211
        for i in 0..clusters.len() {
212
            marks.push(Mark { cluster: i, kind: Kind::Repo, order: 0, radius: 0.0, angle: 0.0, speed: 0.0, bright: 0.9, lit: 0.0 });
213
        }
214
        // Each event's marks: a push is a dot for each change it brought.
215
        let expanded: Vec<Event> = events
216
            .iter()
217
            .filter(|e| e.repo < repos.len() && e.age_days <= DAYS)
218
            .flat_map(|e| std::iter::repeat_n(*e, if e.kind == Kind::Push { e.n.clamp(1, PER_PUSH) as usize } else { 1 }))
219
            .take(MAX_MARKS)
220
            .collect();
221
        // A busy repository gets more lanes, so its marks spread out.
222
        let mut count = vec![0u32; repos.len()];
223
        for e in &expanded {
224
            count[e.repo] += 1;
225
        }
226
        let mut seen = vec![0u32; repos.len()];
227
        for e in &expanded {
228
            let k = seen[e.repo];
229
            seen[e.repo] += 1;
230
            let lanes = (6 + count[e.repo] / 30).min(14);
231
            let h = hash(&format!("{}#{k}", repos[e.repo].name));
232
            // Each repository turns one way; its marks keep their lanes, so
233
            // two clusters' streams cross without touching.
234
            let dir = if hash(&repos[e.repo].name) & 1 == 0 { 1.0 } else { -1.0 };
235
            let radius = 20.0 + (k % lanes) as f32 * 9.0 + unit(h, 0) * 6.0;
236
            let speed = dir * (MAX_SPEED / radius).min(0.25) * (0.5 + 0.5 * unit(h, 16));
237
            marks.push(Mark {
238
                cluster: e.repo,
239
                kind: e.kind,
240
                order: k,
241
                radius,
242
                angle: unit(h, 32) * TAU,
243
                speed,
244
                bright: 1.0 - 0.7 * (e.age_days / DAYS).clamp(0.0, 1.0),
245
                lit: 0.0,
246
            });
247
        }
248
        Sky { clusters, marks, w, h, cursor: None, rested: 0.0, still, parallax: [(0.0, 0.0); 3], link_fade: 0.0 }
249
    }
250
251
    pub fn resize(&mut self, w: f32, h: f32) {
252
        self.w = w;
253
        self.h = h;
254
    }
255
256
    /// The cursor moved to `(x, y)`, or left the page.
257
    pub fn point(&mut self, at: Option<(f32, f32)>) {
258
        self.cursor = at;
259
        self.rested = 0.0;
260
    }
261
262
    /// Where cluster `c`'s core is now.
263
    pub fn core(&self, c: usize) -> (f32, f32) {
264
        let cl = &self.clusters[c];
265
        let (px, py) = self.parallax[cl.layer];
266
        (cl.fx * self.w + px, cl.fy * self.h + py)
267
    }
268
269
    /// Where mark `m` is now.
270
    pub fn position(&self, m: &Mark) -> (f32, f32) {
271
        let (cx, cy) = self.core(m.cluster);
272
        (cx + m.angle.cos() * m.radius, cy + m.angle.sin() * m.radius)
273
    }
274
275
    /// Move the scene on by `dt` seconds.
276
    pub fn step(&mut self, dt: f32) {
277
        let dt = dt.clamp(0.0, 0.1);
278
        self.rested += dt;
279
        if !self.still {
280
            for m in &mut self.marks {
281
                m.angle = (m.angle + m.speed * dt) % TAU;
282
            }
283
            let ease = 1.0 - (-dt * 4.0).exp();
284
            for (l, p) in self.parallax.iter_mut().enumerate() {
285
                let (tx, ty) = match self.cursor {
286
                    Some((x, y)) if self.w > 0.0 && self.h > 0.0 => {
287
                        (-(x - self.w / 2.0) / (self.w / 2.0) * PARALLAX[l], -(y - self.h / 2.0) / (self.h / 2.0) * PARALLAX[l])
288
                    }
289
                    _ => (0.0, 0.0),
290
                };
291
                p.0 += (tx - p.0) * ease;
292
                p.1 += (ty - p.1) * ease;
293
            }
294
        }
295
        let lit_targets: Vec<f32> = self
296
            .marks
297
            .iter()
298
            .map(|m| match self.cursor {
299
                Some((x, y)) => {
300
                    let (mx, my) = self.position(m);
301
                    if (mx - x).hypot(my - y) <= LIGHT_RADIUS {
302
                        1.0
303
                    } else {
304
                        0.0
305
                    }
306
                }
307
                None => 0.0,
308
            })
309
            .collect();
310
        for (m, target) in self.marks.iter_mut().zip(lit_targets) {
311
            m.lit = if self.still {
312
                target
313
            } else if target > m.lit {
314
                (m.lit + dt / LIT_IN).min(target)
315
            } else {
316
                (m.lit - dt / LIT_OUT).max(target)
317
            };
318
        }
319
        let fade_to = if self.cursor.is_some() && self.rested < LINK_REST { 1.0 } else { 0.0 };
320
        self.link_fade = if self.still {
321
            fade_to
322
        } else if fade_to > self.link_fade {
323
            (self.link_fade + dt / LIT_IN).min(1.0)
324
        } else {
325
            (self.link_fade - dt / LIT_OUT).max(0.0)
326
        };
327
    }
328
329
    /// Whether anything is still changing: a frame is worth drawing.
330
    pub fn busy(&self) -> bool {
331
        !self.still || self.marks.iter().any(|m| m.lit > 0.0 && m.lit < 1.0) || (self.link_fade > 0.0 && self.link_fade < 1.0)
332
    }
333
334
    /// One instance per mark: centre x, y and radius in CSS pixels, its
335
    /// shape, and its colour premultiplied, 8 floats each.
336
    pub fn instances(&self, c: &Colours, out: &mut Vec<f32>) {
337
        out.clear();
338
        for m in &self.marks {
339
            let (x, y) = self.position(m);
340
            let rest = [c.mark[0], c.mark[1], c.mark[2], c.mark[3] * m.bright];
341
            let col = mix(rest, c.lit, m.lit);
342
            let size = m.kind.size() * (1.0 + 0.35 * m.lit);
343
            out.extend_from_slice(&[x, y, size, m.kind.shape(), col[0] * col[3], col[1] * col[3], col[2] * col[3], col[3]]);
344
        }
345
    }
346
347
    /// The links among lit marks: each repository's lit marks in the order
348
    /// they happened, its core to its newest lit mark. Two vertices a
349
    /// link, x, y and a premultiplied colour each, 6 floats a vertex.
350
    pub fn links(&self, c: &Colours, out: &mut Vec<f32>) {
351
        out.clear();
352
        if self.link_fade <= 0.0 {
353
            return;
354
        }
355
        for ci in 0..self.clusters.len() {
356
            let mut lit: Vec<&Mark> = self.marks.iter().filter(|m| m.cluster == ci && m.lit > 0.05).collect();
357
            lit.sort_by_key(|m| (m.kind != Kind::Repo, m.order));
358
            for pair in lit.windows(2) {
359
                let (a, b) = (self.position(pair[0]), self.position(pair[1]));
360
                if (a.0 - b.0).hypot(a.1 - b.1) > LINK_MAX {
361
                    continue;
362
                }
363
                let alpha = c.link[3] * pair[0].lit.min(pair[1].lit) * self.link_fade;
364
                let col = [c.link[0] * alpha, c.link[1] * alpha, c.link[2] * alpha, alpha];
365
                out.extend_from_slice(&[a.0, a.1, col[0], col[1], col[2], col[3], b.0, b.1, col[0], col[1], col[2], col[3]]);
366
            }
367
        }
368
    }
369
370
    /// How far a cluster's marks reach from its core.
371
    fn reach(&self, c: usize) -> f32 {
372
        self.marks.iter().filter(|m| m.cluster == c).map(|m| m.radius).fold(0.0, f32::max)
373
    }
374
375
    /// The name to show for a resting cursor, and where: centred just
376
    /// above the nearest cluster within reach, clear of its marks.
377
    pub fn label(&self) -> Option<(&str, f32, f32)> {
378
        let (x, y) = self.cursor?;
379
        if self.rested < LABEL_REST {
380
            return None;
381
        }
382
        (0..self.clusters.len())
383
            .map(|i| (i, self.core(i)))
384
            .map(|(i, (cx, cy))| (i, cx, cy, (cx - x).hypot(cy - y)))
385
            .filter(|t| t.3 <= LABEL_NEAR)
386
            .min_by(|a, b| a.3.total_cmp(&b.3))
387
            .map(|(i, cx, cy, _)| (self.clusters[i].name.as_str(), cx, cy - self.reach(i) - 10.0))
388
    }
389
}
390
391
fn mix(a: Rgba, b: Rgba, t: f32) -> Rgba {
392
    let t = t.clamp(0.0, 1.0);
393
    [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, a[3] + (b[3] - a[3]) * t]
394
}
395
396
/// A computed CSS colour: `rgb(r, g, b)`, `rgba(r, g, b, a)` or
397
/// `color(srgb r g b / a)`, as browsers report them.
398
pub fn parse_colour(s: &str) -> Option<Rgba> {
399
    let s = s.trim();
400
    if let Some(inner) = s.strip_prefix("color(srgb").and_then(|r| r.strip_suffix(')')) {
401
        let (rgb, a) = match inner.split_once('/') {
402
            Some((rgb, a)) => (rgb, a.trim().parse().ok()?),
403
            None => (inner, 1.0),
404
        };
405
        let v: Vec<f32> = rgb.split_whitespace().map(|x| x.parse().ok()).collect::<Option<_>>()?;
406
        return (v.len() == 3).then(|| [v[0], v[1], v[2], a]);
407
    }
408
    let inner = s.strip_prefix("rgba(").or_else(|| s.strip_prefix("rgb("))?.strip_suffix(')')?;
409
    let v: Vec<f32> = inner.split([',', ' ', '/']).filter(|x| !x.is_empty()).map(|x| x.trim().parse().ok()).collect::<Option<_>>()?;
410
    match v.len() {
411
        3 => Some([v[0] / 255.0, v[1] / 255.0, v[2] / 255.0, 1.0]),
412
        4 => Some([v[0] / 255.0, v[1] / 255.0, v[2] / 255.0, v[3]]),
413
        _ => None,
414
    }
415
}
416
417
#[cfg(test)]
418
mod tests {
419
    use super::*;
420
421
    fn sky(still: bool) -> Sky {
422
        let repos = vec![Repo { name: "andy/hub".into() }, Repo { name: "andy/oxygen".into() }];
423
        let events = vec![
424
            Event { repo: 0, kind: Kind::Push, age_days: 0.0, n: 3 },
425
            Event { repo: 0, kind: Kind::Proposal, age_days: 2.0, n: 1 },
426
            Event { repo: 1, kind: Kind::Release, age_days: 29.0, n: 1 },
427
            Event { repo: 1, kind: Kind::Issue, age_days: 45.0, n: 1 },
428
        ];
429
        Sky::new(&repos, &events, 1600.0, 900.0, still)
430
    }
431
432
    #[test]
433
    fn a_sky_is_the_same_on_every_visit() {
434
        let (a, b) = (sky(false), sky(false));
435
        assert_eq!(a.clusters[0].fx, b.clusters[0].fx);
436
        assert_eq!(a.clusters[1].fy, b.clusters[1].fy);
437
        // A core per repository, a dot per change pushed, and one mark per
438
        // other event of the last 30 days.
439
        assert_eq!(a.marks.len(), 2 + 3 + 1 + 1);
440
        assert!(a.marks.iter().all(|m| m.kind != Kind::Issue), "older than 30 days: not drawn");
441
        let newest = a.marks.iter().find(|m| m.kind == Kind::Push).unwrap();
442
        let old = a.marks.iter().find(|m| m.kind == Kind::Release).unwrap();
443
        assert!(newest.bright > old.bright, "newer is brighter");
444
        assert_eq!(a.clusters[0].layer, 0, "the busiest in front");
445
    }
446
447
    #[test]
448
    fn marks_drift_slowly_and_the_cursor_lights_without_pulling() {
449
        let mut s = sky(false);
450
        for m in &s.marks {
451
            assert!(m.speed.abs() * m.radius <= MAX_SPEED + 0.01, "at most 12 px a second");
452
        }
453
        let target = s.position(&s.marks[2]);
454
        let radii: Vec<f32> = s.marks.iter().map(|m| m.radius).collect();
455
        s.point(Some(target));
456
        for _ in 0..30 {
457
            s.step(1.0 / 60.0);
458
        }
459
        assert!(s.marks[2].lit > 0.99, "lit near the cursor");
460
        assert_eq!(radii, s.marks.iter().map(|m| m.radius).collect::<Vec<_>>(), "nothing is pulled");
461
        let mut links = Vec::new();
462
        let colours = Colours { mark: [0.5, 0.5, 0.5, 0.2], lit: [0.0, 0.4, 0.9, 0.7], link: [0.0, 0.4, 0.9, 0.3] };
463
        s.links(&colours, &mut links);
464
        assert!(!links.is_empty() && links.len() % 12 == 0, "lit marks of one repository are joined");
465
        // Resting fades the links; leaving fades the light.
466
        for _ in 0..240 {
467
            s.step(1.0 / 60.0);
468
        }
469
        s.links(&colours, &mut links);
470
        assert!(links.is_empty(), "a resting cursor's links fade");
471
        s.point(None);
472
        for _ in 0..60 {
473
            s.step(1.0 / 60.0);
474
        }
475
        assert!(s.marks.iter().all(|m| m.lit == 0.0));
476
    }
477
478
    #[test]
479
    fn still_means_no_drift_and_instant_light() {
480
        let mut s = sky(true);
481
        let before: Vec<f32> = s.marks.iter().map(|m| m.angle).collect();
482
        let at = s.position(&s.marks[2]);
483
        s.point(Some(at));
484
        s.step(1.0 / 60.0);
485
        assert_eq!(before, s.marks.iter().map(|m| m.angle).collect::<Vec<_>>());
486
        assert_eq!(s.marks[2].lit, 1.0);
487
        assert!(!s.busy(), "nothing left to animate");
488
    }
489
490
    #[test]
491
    fn instances_are_premultiplied_and_a_resting_cursor_names_a_cluster() {
492
        let mut s = sky(false);
493
        let colours = Colours { mark: [1.0, 1.0, 1.0, 0.5], lit: [0.0, 0.0, 1.0, 1.0], link: [0.0, 0.0, 1.0, 0.3] };
494
        let mut inst = Vec::new();
495
        s.instances(&colours, &mut inst);
496
        assert_eq!(inst.len(), s.marks.len() * 8);
497
        let core = &inst[0..8];
498
        assert!((core[4] - core[7]).abs() < 1e-6 && core[7] < 0.5, "premultiplied, dimmed by brightness");
499
        let (cx, cy) = s.core(1);
500
        s.point(Some((cx + 10.0, cy)));
501
        assert!(s.label().is_none(), "not while moving");
502
        for _ in 0..10 {
503
            s.step(0.05);
504
        }
505
        assert_eq!(s.label().map(|l| l.0), Some("andy/oxygen"));
506
    }
507
508
    #[test]
509
    fn computed_colours_parse() {
510
        assert_eq!(parse_colour("rgb(9, 105, 218)"), Some([9.0 / 255.0, 105.0 / 255.0, 218.0 / 255.0, 1.0]));
511
        assert_eq!(parse_colour("rgba(0, 240, 255, 0.75)").map(|c| c[3]), Some(0.75));
512
        assert_eq!(parse_colour("color(srgb 0 0.5 1 / 0.2)"), Some([0.0, 0.5, 1.0, 0.2]));
513
        assert_eq!(parse_colour("rgb(1 2 3 / 0.5)").map(|c| c[3]), Some(0.5));
514
        assert!(parse_colour("transparent").is_none());
515
    }
516
}