app: cherry-pick rune's pause and sound fixes onto the checkout
Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch ported, carrying the four commits of upstream issues 1320 (a pause while a clip is layered holds the layer's picture and time) and 1325 (a video's sound is read ahead of the clock and leads it). Both were written against eb9f1104 and ported across the refactors since. The faults are the first two and the third in docs/rune-upstream.md; the app's workarounds in review.rs stay until the fixes arrive upstream.
This commit is contained in:
1 parent
80fef698ce
commit
5bf262b82b
3795 files changed
+663463
-28
No files matched your search
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "motion-bento"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
rune = { workspace = true, default-features = true, features = ["keys-overlay"] }
|
||||
rune-kit = { workspace = true, default-features = true }
|
||||
motion-bento-chaos = { path = "chaos" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
# Motion bento
|
||||
|
||||
A 1440×900 control center whose twelve tiles all move at once: a segmented scene picker, a
|
||||
thermostat ring, light switches, mixer faders, an XY pad, a card deck, an activity feed, and a
|
||||
bottom row of five tiles that reflow around whichever one has focus. A seeded chaos schedule taps
|
||||
them (a few times a second, with bursts of six to twelve taps 30–60 ms apart), so nearly every
|
||||
frame has springs in flight.
|
||||
|
||||
`chaos/` (`motion-bento-chaos`) holds everything that isn't Rune: the model, the schedule, the
|
||||
look (colours, grid, spring tunings) and the frame meter. It has no Rune dependency, so another
|
||||
toolkit can build the same window and play the same schedule.
|
||||
|
||||
```sh
|
||||
cargo run -p motion-bento --profile perf -- --seed 7 --duration 30 --intensity 1.5 --hud
|
||||
```
|
||||
|
||||
| Flag | Default | |
|
||||
| --- | --- | --- |
|
||||
| `--seed N` | 1 | Names one schedule, and every random choice its taps make. |
|
||||
| `--duration S` | 20 | Seconds of chaos. The window quits a second later. Rune's headless runs read it too. |
|
||||
| `--intensity X` | 1 | Scales the rate of taps: 2 is twice as many. |
|
||||
| `--variant NAME` | `default` | Spring tuning: `default`, `bouncy` or `stiff`. |
|
||||
| `--metrics PATH` | | Write the frame meter's JSON when the run ends (a headless run: at `--duration` + 1 s). |
|
||||
| `--hud` | off | Show the frame meter from the start. `H` toggles it. |
|
||||
| `--stay` | off | Keep the window open after the schedule ends. |
|
||||
| `--emit-script PATH` | | Write the schedule as a Rune headless script and exit. |
|
||||
| `--load N` | | Stress mode: a wall of N live controls instead of the bento. |
|
||||
| `--ramp A:B` | | Stress mode, growing from A to B controls by ×√2 a step. Sets `--duration` unless given. |
|
||||
| `--hold S` | 2.5 | Seconds a ramp spends at each step. |
|
||||
| `--naive` | off | Stress mode: build the whole wall again every frame instead of binding live values. |
|
||||
| `--frames PATH` | | Write every frame as CSV when the run ends: show time, load, build, work, start, and CPU time since the frame before (thread and process). |
|
||||
| `--hud-from PATH` | | Stress mode: the HUD replays a `--frames` CSV from an earlier run, so a capture run shows what a clean run measured at the same moment. |
|
||||
|
||||
## Stress mode
|
||||
|
||||
`--load` and `--ramp` swap the bento for a wall of controls (`chaos/src/stress.rs`): each a card
|
||||
with a glowing status dot, a name, a status word, a reading that changes every frame, a
|
||||
percentage, eight gradient bars that retarget every few hundred milliseconds, a progress track
|
||||
and a switch. The wall reshuffles every 2 s, one in twelve controls goes double width (reselected
|
||||
every 1.7 s), hues and statuses change on their own clocks, and a new control scales and fades in.
|
||||
What the wall shows is a pure function of the seed, the show time and the load, so the GPUI build
|
||||
draws the same wall frame for frame.
|
||||
|
||||
```sh
|
||||
motion-bento --seed 7 --ramp 32:1024 --frames ramp.csv --snap end.png --at 29.6 --size 1440x900 --scale 2 --fps 120
|
||||
```
|
||||
|
||||
With `--hud`, the header shows a frame-time readout and graph against the 120 Hz and 60 Hz budgets.
|
||||
|
||||
The wall is built the way a Rune app should build it (`src/stress/live.rs`): each card's inside is
|
||||
a `memo` built once per size, and its reading, bars, switch, progress and colours are `Live`
|
||||
values that `poll` sets, so the view runs and commits only when the wall reshuffles or grows.
|
||||
`--naive` (`src/stress/naive.rs`) rebuilds every card every frame, as a first port would.
|
||||
|
||||
## Headless
|
||||
|
||||
Every action is a tap on a keyed element (`Action::key`), so the schedule is also a script:
|
||||
|
||||
```sh
|
||||
motion-bento --seed 7 --duration 8 --emit-script chaos.json
|
||||
motion-bento --seed 7 --duration 8 --script chaos.json --video bento.mp4 --size 1440x900
|
||||
motion-bento --seed 7 --duration 8 --script chaos.json --tree end.json --at mark:end
|
||||
```
|
||||
|
||||
With a script, the window plays its taps instead of the schedule, and both reach the same state
|
||||
(`script_taps_reach_the_same_state_as_the_schedule`).
|
||||
|
||||
## The meter
|
||||
|
||||
Measured from `App::on_frame_encoded`, for drawn frames only:
|
||||
|
||||
- **work**: `update_ms + encode_ms`, from the frame's start (after its drawable came) until its
|
||||
commands were submitted: events, `poll`, the view, layout, paint, uploads and encode. CPU wall
|
||||
time, not GPU time.
|
||||
- **build**: `update_ms` alone: events, `poll`, the view, layout and paint, without the encode.
|
||||
The GPUI build can only time this part, so compare GPUI with this number.
|
||||
- **interval**: time between frame starts. A display-paced window starts each frame on a refresh,
|
||||
so this is the gap between frames on screen.
|
||||
- **late**: intervals over 1.5 refreshes (`FrameEncoded::refresh_hz`), and the refreshes they
|
||||
skipped. Gaps over 100 ms are the window resting, not late frames.
|
||||
- **CPU** and **footprint**: process CPU time over the run's wall time, and the physical footprint,
|
||||
from `procwatch`.
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "motion-bento-chaos"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
description = "The motion bento's shared parts: the seeded chaos schedule, the tiles' logical state, the springs and colours, and the frame meter. No UI framework."
|
||||
|
||||
[dependencies]
|
||||
procwatch = { workspace = true }
|
||||
|
||||
[target.'cfg(not(windows))'.dependencies]
|
||||
libc = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_System_Threading"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,169 @@
|
||||
//! The flags both builds share. Each build strips these and keeps the rest for its framework.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::stress::Load;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Config {
|
||||
/// Names one chaos schedule (and the random choices each action makes).
|
||||
pub seed: u64,
|
||||
/// Seconds of chaos. The window quits a second after it ends, writing metrics if asked.
|
||||
pub duration: f64,
|
||||
/// Scales how often things happen: 2 is twice the events.
|
||||
pub intensity: f64,
|
||||
/// Where to write the frame meter's JSON when the run ends.
|
||||
pub metrics: Option<PathBuf>,
|
||||
/// Show the frame meter over the window from the start (H toggles it).
|
||||
pub hud: bool,
|
||||
/// Write the schedule as a Rune script and exit.
|
||||
pub emit_script: Option<PathBuf>,
|
||||
/// A named look or spring tuning (`look::Variant`).
|
||||
pub variant: String,
|
||||
/// Keep the window open after the schedule ends instead of quitting.
|
||||
pub stay: bool,
|
||||
/// Stress mode (`--load N` or `--ramp A:B`): the wall of controls instead of the bento.
|
||||
pub load: Option<Load>,
|
||||
/// Where to write every frame's show time, load and times as CSV when the run ends.
|
||||
pub frames: Option<PathBuf>,
|
||||
/// Draw the stress HUD from this measured run's frames CSV instead of this run's own.
|
||||
pub hud_from: Option<PathBuf>,
|
||||
/// Build the whole view every frame, as a first port does, instead of each framework's
|
||||
/// idiomatic way (memoised cards and live values in Rune, per-card entities in GPUI).
|
||||
pub naive: bool,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Config {
|
||||
Config {
|
||||
seed: 1,
|
||||
duration: 20.0,
|
||||
intensity: 1.0,
|
||||
metrics: None,
|
||||
hud: false,
|
||||
emit_script: None,
|
||||
variant: "default".into(),
|
||||
stay: false,
|
||||
load: None,
|
||||
frames: None,
|
||||
hud_from: None,
|
||||
naive: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Takes the bento's own flags out of `args` (the program name first) and returns them with the
|
||||
/// rest. `--duration` is read and also kept, since Rune's headless runs use it for video length.
|
||||
pub fn parse(args: impl IntoIterator<Item = String>) -> Result<(Config, Vec<String>), String> {
|
||||
let mut config = Config::default();
|
||||
let mut rest = Vec::new();
|
||||
let mut args = args.into_iter();
|
||||
let (mut fixed, mut ramp, mut hold, mut timed) = (None, None, 2.5, false);
|
||||
fn value(flag: &str, next: Option<String>) -> Result<String, String> {
|
||||
next.ok_or_else(|| format!("{flag} needs a value"))
|
||||
}
|
||||
fn number<T: std::str::FromStr>(flag: &str, v: &str) -> Result<T, String> {
|
||||
v.parse().map_err(|_| format!("{flag}: not a number: {v}"))
|
||||
}
|
||||
while let Some(arg) = args.next() {
|
||||
let (flag, inline) = match arg.split_once('=') {
|
||||
Some((f, v)) if f.starts_with("--") => (f.to_string(), Some(v.to_string())),
|
||||
_ => (arg.clone(), None),
|
||||
};
|
||||
let take = |args: &mut dyn Iterator<Item = String>| match &inline {
|
||||
Some(v) => Ok(v.clone()),
|
||||
None => value(&flag, args.next()),
|
||||
};
|
||||
match flag.as_str() {
|
||||
"--seed" => config.seed = number(&flag, &take(&mut args)?)?,
|
||||
"--intensity" => {
|
||||
config.intensity = number(&flag, &take(&mut args)?)?;
|
||||
if !(config.intensity > 0.0) {
|
||||
return Err("--intensity must be above 0".into());
|
||||
}
|
||||
}
|
||||
"--duration" => {
|
||||
let v = take(&mut args)?;
|
||||
if v != "auto" {
|
||||
config.duration = number(&flag, &v)?;
|
||||
}
|
||||
timed = true;
|
||||
rest.push("--duration".into());
|
||||
rest.push(v);
|
||||
}
|
||||
"--metrics" => config.metrics = Some(take(&mut args)?.into()),
|
||||
"--emit-script" => config.emit_script = Some(take(&mut args)?.into()),
|
||||
"--variant" => config.variant = take(&mut args)?,
|
||||
"--load" => fixed = Some(number::<usize>(&flag, &take(&mut args)?)?.max(1)),
|
||||
"--ramp" => ramp = Some(take(&mut args)?),
|
||||
"--hold" => hold = number(&flag, &take(&mut args)?)?,
|
||||
"--frames" => config.frames = Some(take(&mut args)?.into()),
|
||||
"--hud-from" => {
|
||||
config.hud_from = Some(take(&mut args)?.into());
|
||||
config.hud = true;
|
||||
}
|
||||
"--hud" => config.hud = true,
|
||||
"--stay" => config.stay = true,
|
||||
"--naive" => config.naive = true,
|
||||
_ => rest.push(arg),
|
||||
}
|
||||
}
|
||||
config.load = match (fixed, ramp) {
|
||||
(Some(_), Some(_)) => return Err("--load and --ramp: pick one".into()),
|
||||
(Some(n), None) => Some(Load::Fixed(n)),
|
||||
(None, Some(r)) => Some(Load::parse_ramp(&r, hold)?),
|
||||
(None, None) => None,
|
||||
};
|
||||
// A ramp runs as long as its levels, unless told otherwise; Rune's headless runs read it too.
|
||||
if let (false, Some(d)) = (timed, config.load.as_ref().and_then(Load::duration)) {
|
||||
config.duration = d;
|
||||
rest.push("--duration".into());
|
||||
rest.push(format!("{d}"));
|
||||
}
|
||||
Ok((config, rest))
|
||||
}
|
||||
|
||||
/// The seconds between events on a quiet stretch, before intensity.
|
||||
pub fn gap(&self) -> (f64, f64) {
|
||||
(0.1 / self.intensity, 0.3 / self.intensity)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(s: &str) -> Vec<String> {
|
||||
s.split_whitespace().map(String::from).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn takes_its_own_flags_and_keeps_the_rest() {
|
||||
let (c, rest) =
|
||||
Config::parse(args("bento --seed 9 --snap a.png --intensity=2 --duration 4 --hud --naive --at 1")).unwrap();
|
||||
assert_eq!(c.seed, 9);
|
||||
assert!(c.naive);
|
||||
assert_eq!(c.intensity, 2.0);
|
||||
assert_eq!(c.duration, 4.0);
|
||||
assert!(c.hud);
|
||||
assert_eq!(rest, args("bento --snap a.png --duration 4 --at 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ramp_sets_the_duration_unless_given() {
|
||||
let (c, rest) = Config::parse(args("bento --ramp 16:64 --hold 2")).unwrap();
|
||||
assert_eq!(c.load.as_ref().map(|l| l.levels().to_vec()), Some(vec![16, 23, 32, 45, 64]));
|
||||
assert_eq!(c.duration, 10.6);
|
||||
assert_eq!(rest, args("bento --duration 10.6"));
|
||||
let (c, _) = Config::parse(args("bento --load 40 --duration 3")).unwrap();
|
||||
assert_eq!((c.load, c.duration), (Some(Load::Fixed(40)), 3.0));
|
||||
assert!(Config::parse(args("bento --load 4 --ramp 1:2")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_a_bad_number() {
|
||||
assert!(Config::parse(args("bento --seed x")).is_err());
|
||||
assert!(Config::parse(args("bento --intensity 0")).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
//! The stress HUD's numbers, shared so both builds show the same thing: the last [`GRAPH`]
|
||||
//! frames' build times against the 120 Hz and 60 Hz budgets, a big readout, and frame rate.
|
||||
//!
|
||||
//! Live, the HUD reads the frames the meter has seen, and its frame rate and misses are the
|
||||
//! window's. Replaying (`--hud-from`), it reads a measured run's per-frame CSV by show time, so a
|
||||
//! capture run, whose own frames the capture slows, shows what the clean run measured at the same
|
||||
//! moment; its frame rate is then what that CPU cost allows at 120 Hz, nothing presented.
|
||||
|
||||
use crate::meter::Meter;
|
||||
|
||||
pub const BUDGET_120: f32 = 1000.0 / 120.0;
|
||||
pub const BUDGET_60: f32 = 1000.0 / 60.0;
|
||||
/// Frames in the graph.
|
||||
pub const GRAPH: usize = 120;
|
||||
/// The graph's top, in ms.
|
||||
pub const GRAPH_MAX: f32 = 40.0;
|
||||
/// Frames the big readout takes the median of.
|
||||
const READOUT: usize = 15;
|
||||
|
||||
/// A measured run's frames: show time and build ms, by show time.
|
||||
pub struct Replay {
|
||||
samples: Vec<(f32, f32)>,
|
||||
}
|
||||
|
||||
impl Replay {
|
||||
/// Reads [`Meter::frames_csv`] output.
|
||||
pub fn load(path: &std::path::Path) -> Result<Replay, String> {
|
||||
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
let mut samples = Vec::new();
|
||||
for line in text.lines().skip(1) {
|
||||
let mut f = line.split(',');
|
||||
let (Some(t), Some(_), Some(ms)) = (f.next(), f.next(), f.next()) else { continue };
|
||||
if let (Ok(t), Ok(ms)) = (t.parse::<f32>(), ms.parse::<f32>())
|
||||
&& t.is_finite()
|
||||
{
|
||||
samples.push((t, ms));
|
||||
}
|
||||
}
|
||||
samples.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
Ok(Replay { samples })
|
||||
}
|
||||
|
||||
/// The frames at or before show time `t`.
|
||||
pub fn until(&self, t: f64) -> &[(f32, f32)] {
|
||||
let t = t as f32 + 1e-4;
|
||||
&self.samples[..self.samples.partition_point(|s| s.0 <= t)]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Readout {
|
||||
/// Oldest first, at most [`GRAPH`].
|
||||
pub graph: Vec<f32>,
|
||||
/// The median of the last few frames.
|
||||
pub ms: f32,
|
||||
pub p95: f32,
|
||||
pub fps: f32,
|
||||
/// Refreshes missed: live, all run; replayed, in the last second.
|
||||
pub missed: u32,
|
||||
pub source: &'static str,
|
||||
}
|
||||
|
||||
/// 0 within the 120 Hz budget, 1 within 60 Hz, 2 over.
|
||||
pub fn grade(ms: f32) -> usize {
|
||||
if ms <= BUDGET_120 {
|
||||
0
|
||||
} else if ms <= BUDGET_60 {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
}
|
||||
}
|
||||
|
||||
fn pct(v: &mut [f32], p: f32) -> f32 {
|
||||
if v.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
v.sort_by(f32::total_cmp);
|
||||
v[((v.len() - 1) as f32 * p).round() as usize]
|
||||
}
|
||||
|
||||
impl Readout {
|
||||
fn of(samples: impl Iterator<Item = (f32, f32)>) -> Readout {
|
||||
let graph: Vec<f32> = samples.map(|s| s.1).collect();
|
||||
let graph = graph[graph.len().saturating_sub(GRAPH)..].to_vec();
|
||||
let ms = pct(&mut graph[graph.len().saturating_sub(READOUT)..].to_vec(), 0.5);
|
||||
let p95 = pct(&mut graph.clone(), 0.95);
|
||||
Readout { graph, ms, p95, ..Default::default() }
|
||||
}
|
||||
|
||||
/// From a measured run: the frame rate this CPU cost allows at 120 Hz.
|
||||
pub fn replay(r: &Replay, t: f64) -> Readout {
|
||||
let mut out = Readout::of(r.until(t).iter().copied());
|
||||
let refreshes: u32 = out.graph.iter().map(|&ms| (ms / BUDGET_120).ceil().max(1.0) as u32).sum();
|
||||
out.missed = refreshes.saturating_sub(out.graph.len() as u32);
|
||||
out.fps = if refreshes > 0 { 120.0 * out.graph.len() as f32 / refreshes as f32 } else { 0.0 };
|
||||
out.source = "measured headless · live pending";
|
||||
out
|
||||
}
|
||||
|
||||
pub fn live(m: &Meter) -> Readout {
|
||||
let mut out = Readout::of(m.tail(GRAPH));
|
||||
let recent = m.recent();
|
||||
out.fps = recent.fps as f32;
|
||||
out.missed = recent.dropped as u32;
|
||||
out.source = "live window";
|
||||
out
|
||||
}
|
||||
|
||||
pub fn big(&self) -> String {
|
||||
format!("{:.1} ms", self.ms)
|
||||
}
|
||||
|
||||
pub fn detail(&self) -> String {
|
||||
format!("build + layout + paint · p95 {:.1}", self.p95)
|
||||
}
|
||||
|
||||
pub fn rate(&self) -> String {
|
||||
if self.source == "live window" {
|
||||
format!("{:.0} fps · missed {}", self.fps, self.missed)
|
||||
} else {
|
||||
format!("≈ {:.0} fps at 120 Hz · {} missed / s", self.fps, self.missed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_replay_counts_the_refreshes_slow_frames_miss() {
|
||||
let dir = std::env::temp_dir().join(format!("bento-hud-{}.csv", std::process::id()));
|
||||
let mut csv = String::from("show_s,load,build_ms,work_ms,start_s\n");
|
||||
for i in 0..240 {
|
||||
// Half the frames take two refreshes.
|
||||
csv.push_str(&format!("{},16,{},0,0\n", i as f32 / 120.0, if i % 2 == 0 { 4.0 } else { 12.0 }));
|
||||
}
|
||||
std::fs::write(&dir, csv).unwrap();
|
||||
let r = Replay::load(&dir).unwrap();
|
||||
std::fs::remove_file(dir).unwrap();
|
||||
assert_eq!(r.until(0.5).len(), 61);
|
||||
let out = Readout::replay(&r, 10.0);
|
||||
assert_eq!(out.graph.len(), GRAPH);
|
||||
assert_eq!(out.missed, 60);
|
||||
assert!((out.fps - 80.0).abs() < 0.01);
|
||||
assert_eq!((grade(4.0), grade(12.0), grade(20.0)), (0, 1, 2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//! The motion bento's shared parts, used by its Rune build and its GPUI build alike: the command
|
||||
//! line, a seeded RNG, the chaos schedule, the tiles' logical state ([`Model`]), the springs and
|
||||
//! colours both builds animate with, and the frame meter that writes `metrics.json`.
|
||||
//!
|
||||
//! Nothing here draws. Each framework turns a [`Model`] into its own view and animates the change
|
||||
//! from the last one with its own springs, using the durations and bounces in [`look`].
|
||||
|
||||
pub mod config;
|
||||
pub mod hud;
|
||||
pub mod look;
|
||||
pub mod meter;
|
||||
pub mod model;
|
||||
pub mod rng;
|
||||
pub mod schedule;
|
||||
pub mod stress;
|
||||
|
||||
pub use config::Config;
|
||||
pub use meter::Meter;
|
||||
pub use model::Action;
|
||||
pub use model::Model;
|
||||
pub use rng::Rng;
|
||||
pub use schedule::Event;
|
||||
pub use schedule::Player;
|
||||
pub use schedule::schedule;
|
||||
pub use schedule::script_json;
|
||||
@@ -0,0 +1,191 @@
|
||||
//! The look both builds share: colours as OKLCH, the grid's measurements, and the springs, as
|
||||
//! perceptual duration and bounce (SwiftUI's `Spring(duration:bounce:)`).
|
||||
|
||||
/// An OKLCH colour with alpha.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Lch {
|
||||
pub l: f32,
|
||||
pub c: f32,
|
||||
pub h: f32,
|
||||
pub a: f32,
|
||||
}
|
||||
|
||||
pub const fn lch(l: f32, c: f32, h: f32) -> Lch {
|
||||
Lch { l, c, h, a: 1.0 }
|
||||
}
|
||||
|
||||
impl Lch {
|
||||
pub const fn alpha(self, a: f32) -> Lch {
|
||||
Lch { a, ..self }
|
||||
}
|
||||
|
||||
/// OKLab (L, a, b): the space both builds interpolate colour in.
|
||||
pub fn lab(self) -> [f32; 3] {
|
||||
let h = self.h.to_radians();
|
||||
[self.l, self.c * h.cos(), self.c * h.sin()]
|
||||
}
|
||||
|
||||
/// Gamma-encoded sRGB, clamped to the gamut, with alpha.
|
||||
pub fn srgb(self) -> [f32; 4] {
|
||||
let [r, g, b] = lab_to_linear(self.lab());
|
||||
[encode(r), encode(g), encode(b), self.a]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lab_to_linear([l, a, b]: [f32; 3]) -> [f32; 3] {
|
||||
let l_ = l + 0.396_337_78 * a + 0.215_803_76 * b;
|
||||
let m_ = l - 0.105_561_346 * a - 0.063_854_17 * b;
|
||||
let s_ = l - 0.089_484_18 * a - 1.291_485_5 * b;
|
||||
let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
|
||||
[
|
||||
4.076_741_7 * l3 - 3.307_711_6 * m3 + 0.230_969_94 * s3,
|
||||
-1.268_438 * l3 + 2.609_757_4 * m3 - 0.341_319_38 * s3,
|
||||
-0.004_196_086_3 * l3 - 0.703_418_6 * m3 + 1.707_614_7 * s3,
|
||||
]
|
||||
}
|
||||
|
||||
/// Linear to gamma-encoded sRGB, clamped to 0..1.
|
||||
pub fn encode(x: f32) -> f32 {
|
||||
let x = x.clamp(0.0, 1.0);
|
||||
if x <= 0.003_130_8 { 12.92 * x } else { 1.055 * x.powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
|
||||
pub mod color {
|
||||
use super::{Lch, lch};
|
||||
|
||||
pub const ACCENT_HUE: f32 = 245.0;
|
||||
pub const BG: Lch = lch(0.155, 0.012, 260.0);
|
||||
pub const TILE: Lch = lch(0.205, 0.014, 258.0);
|
||||
pub const TILE_FOCUS: Lch = lch(0.235, 0.022, 252.0);
|
||||
pub const EDGE: Lch = lch(1.0, 0.0, 0.0).alpha(0.07);
|
||||
pub const WELL: Lch = lch(0.255, 0.014, 258.0);
|
||||
pub const WELL_HI: Lch = lch(0.31, 0.016, 258.0);
|
||||
pub const TEXT: Lch = lch(0.96, 0.005, 258.0);
|
||||
pub const TEXT_2: Lch = lch(0.72, 0.012, 258.0);
|
||||
pub const TEXT_3: Lch = lch(0.54, 0.014, 258.0);
|
||||
pub const ACCENT: Lch = lch(0.66, 0.17, ACCENT_HUE);
|
||||
pub const ACCENT_DIM: Lch = lch(0.66, 0.17, ACCENT_HUE).alpha(0.18);
|
||||
pub const ON_ACCENT: Lch = lch(0.99, 0.0, 0.0);
|
||||
pub const GOOD: Lch = lch(0.74, 0.15, 155.0);
|
||||
pub const WARM: Lch = lch(0.78, 0.14, 70.0);
|
||||
|
||||
/// Each scene's mood: its swatch, and the glow it casts on the header.
|
||||
pub const SCENE: [Lch; 4] = [
|
||||
lch(0.66, 0.17, ACCENT_HUE),
|
||||
lch(0.74, 0.13, 175.0),
|
||||
lch(0.78, 0.14, 70.0),
|
||||
lch(0.6, 0.17, 295.0),
|
||||
];
|
||||
}
|
||||
|
||||
/// The window and the grid, in points.
|
||||
pub mod grid {
|
||||
pub const WIDTH: f32 = 1440.0;
|
||||
pub const HEIGHT: f32 = 900.0;
|
||||
pub const PAD: f32 = 28.0;
|
||||
pub const GAP: f32 = 14.0;
|
||||
pub const HEADER: f32 = 64.0;
|
||||
pub const RADIUS: f32 = 18.0;
|
||||
pub const TILE_PAD: f32 = 18.0;
|
||||
/// Row heights below the header; the dock row takes what's left.
|
||||
pub const ROW1: f32 = 236.0;
|
||||
pub const ROW2: f32 = 262.0;
|
||||
/// The focused dock tile's share of the row against 1 for each other tile.
|
||||
pub const DOCK_FOCUS: f32 = 2.4;
|
||||
}
|
||||
|
||||
/// A spring as perceptual duration (seconds) and bounce, mass 1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Spring {
|
||||
pub duration: f32,
|
||||
pub bounce: f32,
|
||||
}
|
||||
|
||||
impl Spring {
|
||||
pub const fn new(duration: f32, bounce: f32) -> Spring {
|
||||
Spring { duration, bounce }
|
||||
}
|
||||
|
||||
/// ω = 2π / duration.
|
||||
pub fn omega(self) -> f32 {
|
||||
std::f32::consts::TAU / self.duration
|
||||
}
|
||||
|
||||
/// ζ = 1 − bounce (≥ 0), 1 / (1 + bounce) below.
|
||||
pub fn zeta(self) -> f32 {
|
||||
if self.bounce >= 0.0 { 1.0 - self.bounce } else { 1.0 / (1.0 + self.bounce) }
|
||||
}
|
||||
|
||||
/// k = ω².
|
||||
pub fn stiffness(self) -> f32 {
|
||||
self.omega() * self.omega()
|
||||
}
|
||||
|
||||
/// c = 2ζω.
|
||||
pub fn damping(self) -> f32 {
|
||||
2.0 * self.zeta() * self.omega()
|
||||
}
|
||||
}
|
||||
|
||||
/// The springs each kind of motion uses.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Springs {
|
||||
/// Tiles reflowing, cards and feed rows moving.
|
||||
pub layout: Spring,
|
||||
/// Controls: switches, segments, chips filling.
|
||||
pub snap: Spring,
|
||||
/// Shape and colour changes.
|
||||
pub morph: Spring,
|
||||
/// Things arriving with a little life.
|
||||
pub pop: Spring,
|
||||
/// The XY pad's puck and the mixer's faders.
|
||||
pub travel: Spring,
|
||||
}
|
||||
|
||||
impl Springs {
|
||||
/// `default` is the shipped tuning. `bouncy` and `stiff` exist for A/B runs.
|
||||
pub fn variant(name: &str) -> Springs {
|
||||
let base = Springs {
|
||||
layout: Spring::new(0.4, 0.0),
|
||||
snap: Spring::new(0.25, 0.0),
|
||||
morph: Spring::new(0.3, 0.16),
|
||||
pop: Spring::new(0.25, 0.15),
|
||||
travel: Spring::new(0.35, 0.12),
|
||||
};
|
||||
match name {
|
||||
"bouncy" => Springs {
|
||||
layout: Spring::new(0.5, 0.28),
|
||||
snap: Spring::new(0.3, 0.22),
|
||||
morph: Spring::new(0.45, 0.35),
|
||||
pop: Spring::new(0.35, 0.35),
|
||||
travel: Spring::new(0.5, 0.35),
|
||||
},
|
||||
"stiff" => Springs {
|
||||
layout: Spring::new(0.22, 0.0),
|
||||
snap: Spring::new(0.15, 0.0),
|
||||
morph: Spring::new(0.18, 0.0),
|
||||
pop: Spring::new(0.15, 0.0),
|
||||
travel: Spring::new(0.2, 0.0),
|
||||
},
|
||||
_ => base,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn accent_is_rune_blue() {
|
||||
let [r, g, b, _] = color::ACCENT.srgb();
|
||||
assert!(b > r && b > g && r < 0.4, "{r} {g} {b}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spring_constants_match_swiftui() {
|
||||
let s = Spring::new(0.5, 0.0);
|
||||
assert!((s.stiffness() - (4.0 * std::f32::consts::PI).powi(2)).abs() < 1e-3);
|
||||
assert!((s.damping() - 2.0 * 4.0 * std::f32::consts::PI).abs() < 1e-3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
//! The frame meter both builds feed, one call per drawn frame, so their numbers mean the same.
|
||||
//!
|
||||
//! It keeps each frame's start time, its CPU work (whatever span the build can time: see each
|
||||
//! build's README) and, where a build can split it out, the part that builds the frame: view,
|
||||
//! layout and paint, without the GPU encode. From those it derives frame-start intervals, missed frames (an interval over
|
||||
//! 1.5 refresh periods) and percentiles, and it samples the process's CPU time and memory from
|
||||
//! procwatch.
|
||||
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Frame {
|
||||
/// Seconds since the meter started.
|
||||
start: f64,
|
||||
work_ms: f32,
|
||||
/// NaN when the build can't split it out.
|
||||
build_ms: f32,
|
||||
/// The show time and load the app tagged the frame with ([`Meter::tag`]).
|
||||
show: f32,
|
||||
load: u32,
|
||||
/// CPU time since the frame before: this thread's, and the whole process's. Unlike the
|
||||
/// spans above, a busy machine that preempts the app doesn't add to them.
|
||||
cpu_ms: f32,
|
||||
proc_ms: f32,
|
||||
}
|
||||
|
||||
/// An interval longer than this is the window resting, not a slow frame.
|
||||
const IDLE_GAP: f64 = 0.1;
|
||||
|
||||
pub struct Meter {
|
||||
framework: String,
|
||||
refresh_hz: f64,
|
||||
t0: Instant,
|
||||
cpu0: f64,
|
||||
frames: Vec<Frame>,
|
||||
footprint_peak: u64,
|
||||
footprint_last: u64,
|
||||
footprint_at: f64,
|
||||
resident_last: u64,
|
||||
/// Seconds since the meter started that bound what [`Meter::summary`] counts.
|
||||
window: Option<(f64, f64)>,
|
||||
extra: Vec<(String, String)>,
|
||||
tag: (f32, u32),
|
||||
/// Thread and process CPU seconds at the last frame.
|
||||
cpu_last: (f64, f64),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Summary {
|
||||
pub frames: usize,
|
||||
pub seconds: f64,
|
||||
pub fps: f64,
|
||||
pub interval_ms: [f64; 4],
|
||||
pub work_ms: [f64; 4],
|
||||
/// View, layout and paint only; `None` when no frame reported it.
|
||||
pub build_ms: Option<[f64; 4]>,
|
||||
/// Intervals over 1.5 refresh periods.
|
||||
pub late: usize,
|
||||
/// Refreshes those late intervals skipped.
|
||||
pub dropped: usize,
|
||||
pub idle_gaps: usize,
|
||||
pub cpu_percent: f64,
|
||||
pub footprint_mb: f64,
|
||||
pub footprint_peak_mb: f64,
|
||||
pub resident_mb: f64,
|
||||
}
|
||||
|
||||
fn pct(sorted: &[f64], p: f64) -> f64 {
|
||||
if sorted.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let i = ((sorted.len() - 1) as f64 * p).round() as usize;
|
||||
sorted[i]
|
||||
}
|
||||
|
||||
/// p50, p95, p99 and max of `v`.
|
||||
fn spread(mut v: Vec<f64>) -> [f64; 4] {
|
||||
v.sort_by(f64::total_cmp);
|
||||
[pct(&v, 0.5), pct(&v, 0.95), pct(&v, 0.99), v.last().copied().unwrap_or(0.0)]
|
||||
}
|
||||
|
||||
fn cpu_seconds() -> f64 {
|
||||
procwatch::snapshot().map_or(0.0, |s| s.cpu_s)
|
||||
}
|
||||
|
||||
/// This thread's CPU seconds, and the process's (user and system), cheaply enough for every frame.
|
||||
#[cfg(windows)]
|
||||
fn cpu_now() -> (f64, f64) {
|
||||
use windows_sys::Win32::Foundation::FILETIME;
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentThread, GetProcessTimes, GetThreadTimes};
|
||||
let zero = || FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 };
|
||||
let secs = |f: FILETIME| ((f.dwHighDateTime as u64) << 32 | f.dwLowDateTime as u64) as f64 * 1e-7;
|
||||
let (mut created, mut exited, mut kernel, mut user) = (zero(), zero(), zero(), zero());
|
||||
// SAFETY: the pseudo-handles need no closing; each call only writes the structs it's given.
|
||||
let thread = if unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) } != 0 { secs(kernel) + secs(user) } else { f64::NAN };
|
||||
// SAFETY: as above.
|
||||
let process = if unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) } != 0 { secs(kernel) + secs(user) } else { f64::NAN };
|
||||
(thread, process)
|
||||
}
|
||||
|
||||
/// This thread's CPU seconds, and the process's (user and system), cheaply enough for every frame.
|
||||
#[cfg(not(windows))]
|
||||
fn cpu_now() -> (f64, f64) {
|
||||
let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
|
||||
// SAFETY: both calls only write the struct they're given.
|
||||
let thread = if unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut ts) } == 0 { ts.tv_sec as f64 + ts.tv_nsec as f64 * 1e-9 } else { f64::NAN };
|
||||
let mut ru = std::mem::MaybeUninit::<libc::rusage>::zeroed();
|
||||
// SAFETY: as above.
|
||||
let process = if unsafe { libc::getrusage(libc::RUSAGE_SELF, ru.as_mut_ptr()) } == 0 {
|
||||
// SAFETY: getrusage filled it.
|
||||
let ru = unsafe { ru.assume_init() };
|
||||
let tv = |t: libc::timeval| t.tv_sec as f64 + t.tv_usec as f64 * 1e-6;
|
||||
tv(ru.ru_utime) + tv(ru.ru_stime)
|
||||
} else {
|
||||
f64::NAN
|
||||
};
|
||||
(thread, process)
|
||||
}
|
||||
|
||||
impl Meter {
|
||||
pub fn new(framework: &str, refresh_hz: f64) -> Meter {
|
||||
let mut m = Meter {
|
||||
framework: framework.into(),
|
||||
refresh_hz,
|
||||
// motion-bento-chaos is a framework-independent native benchmark crate.
|
||||
#[allow(clippy::disallowed_methods)]
|
||||
t0: Instant::now(),
|
||||
cpu0: cpu_seconds(),
|
||||
frames: Vec::with_capacity(8192),
|
||||
footprint_peak: 0,
|
||||
footprint_last: 0,
|
||||
footprint_at: -1.0,
|
||||
resident_last: 0,
|
||||
window: None,
|
||||
extra: Vec::new(),
|
||||
tag: (f32::NAN, 0),
|
||||
cpu_last: cpu_now(),
|
||||
};
|
||||
m.sample_memory(0.0);
|
||||
m
|
||||
}
|
||||
|
||||
pub fn set_refresh(&mut self, hz: f64) {
|
||||
if hz > 1.0 {
|
||||
self.refresh_hz = hz;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn refresh_hz(&self) -> f64 {
|
||||
self.refresh_hz
|
||||
}
|
||||
|
||||
/// Seconds since the meter started.
|
||||
pub fn now(&self) -> f64 {
|
||||
self.t0.elapsed().as_secs_f64()
|
||||
}
|
||||
|
||||
pub fn seconds_at(&self, at: Instant) -> f64 {
|
||||
at.saturating_duration_since(self.t0).as_secs_f64()
|
||||
}
|
||||
|
||||
/// Restarts the CPU count from here, and counts only frames from now on.
|
||||
pub fn begin(&mut self) {
|
||||
let now = self.now();
|
||||
self.cpu0 = cpu_seconds();
|
||||
self.window = Some((now, f64::INFINITY));
|
||||
}
|
||||
|
||||
/// Stops counting frames from here.
|
||||
pub fn end(&mut self) {
|
||||
let now = self.now();
|
||||
if let Some((from, _)) = self.window {
|
||||
self.window = Some((from, now));
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a line to the JSON (a build's version, how it timed work).
|
||||
pub fn note(&mut self, key: &str, value: &str) {
|
||||
self.extra.push((key.into(), value.into()));
|
||||
}
|
||||
|
||||
/// One drawn frame that started at `start` and took `work_ms` of CPU.
|
||||
pub fn frame(&mut self, start: Instant, work_ms: f64) {
|
||||
self.push(start, work_ms, f32::NAN);
|
||||
}
|
||||
|
||||
/// One drawn frame whose `work_ms` includes `build_ms` of view, layout and paint.
|
||||
pub fn frame_with_build(&mut self, start: Instant, work_ms: f64, build_ms: f64) {
|
||||
self.push(start, work_ms, build_ms as f32);
|
||||
}
|
||||
|
||||
/// Tags the frames reported from here with the show time and load they drew.
|
||||
pub fn tag(&mut self, show: f64, load: usize) {
|
||||
self.tag = (show as f32, load as u32);
|
||||
}
|
||||
|
||||
fn push(&mut self, start: Instant, work_ms: f64, build_ms: f32) {
|
||||
let s = self.seconds_at(start);
|
||||
let (show, load) = self.tag;
|
||||
let cpu = cpu_now();
|
||||
let (cpu_ms, proc_ms) = (((cpu.0 - self.cpu_last.0) * 1000.0) as f32, ((cpu.1 - self.cpu_last.1) * 1000.0) as f32);
|
||||
self.cpu_last = cpu;
|
||||
self.frames.push(Frame { start: s, work_ms: work_ms as f32, build_ms, show, load, cpu_ms, proc_ms });
|
||||
if s - self.footprint_at >= 0.5 {
|
||||
self.sample_memory(s);
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_memory(&mut self, at: f64) {
|
||||
let u = procwatch::usage();
|
||||
self.footprint_last = u.footprint.unwrap_or(0);
|
||||
self.resident_last = u.resident.unwrap_or(0);
|
||||
self.footprint_peak = self.footprint_peak.max(self.footprint_last);
|
||||
self.footprint_at = at;
|
||||
}
|
||||
|
||||
fn counted(&self) -> &[Frame] {
|
||||
let Some((from, to)) = self.window else { return &self.frames };
|
||||
let a = self.frames.partition_point(|f| f.start < from);
|
||||
let b = self.frames.partition_point(|f| f.start <= to);
|
||||
&self.frames[a..b]
|
||||
}
|
||||
|
||||
fn summarise(&self, frames: &[Frame], seconds: f64, cpu_s: f64) -> Summary {
|
||||
let period = 1.0 / self.refresh_hz;
|
||||
let mut intervals = Vec::with_capacity(frames.len());
|
||||
let (mut late, mut dropped, mut idle_gaps) = (0, 0, 0);
|
||||
for w in frames.windows(2) {
|
||||
let iv = w[1].start - w[0].start;
|
||||
if iv > IDLE_GAP {
|
||||
idle_gaps += 1;
|
||||
continue;
|
||||
}
|
||||
intervals.push(iv * 1000.0);
|
||||
if iv > 1.5 * period {
|
||||
late += 1;
|
||||
dropped += ((iv / period).round() as usize).saturating_sub(1);
|
||||
}
|
||||
}
|
||||
let mb = |b: u64| b as f64 / 1_048_576.0;
|
||||
let builds: Vec<f64> = frames.iter().filter(|f| !f.build_ms.is_nan()).map(|f| f.build_ms as f64).collect();
|
||||
Summary {
|
||||
frames: frames.len(),
|
||||
seconds,
|
||||
fps: if seconds > 0.0 { frames.len() as f64 / seconds } else { 0.0 },
|
||||
interval_ms: spread(intervals),
|
||||
work_ms: spread(frames.iter().map(|f| f.work_ms as f64).collect()),
|
||||
build_ms: (!builds.is_empty()).then(|| spread(builds)),
|
||||
late,
|
||||
dropped,
|
||||
idle_gaps,
|
||||
cpu_percent: if seconds > 0.0 { 100.0 * cpu_s / seconds } else { 0.0 },
|
||||
footprint_mb: mb(self.footprint_last),
|
||||
footprint_peak_mb: mb(self.footprint_peak),
|
||||
resident_mb: mb(self.resident_last),
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole counted window. Reads the process's CPU time, so call it once at the end.
|
||||
pub fn summary(&mut self) -> Summary {
|
||||
let now = self.now();
|
||||
self.sample_memory(now);
|
||||
let (from, to) = self.window.unwrap_or((0.0, now));
|
||||
let seconds = to.min(now) - from;
|
||||
let cpu = cpu_seconds() - self.cpu0;
|
||||
self.summarise(self.counted(), seconds, cpu)
|
||||
}
|
||||
|
||||
/// The last second, for the HUD. CPU% there is left at 0: reading it costs a thread walk.
|
||||
pub fn recent(&self) -> Summary {
|
||||
let now = self.now();
|
||||
let a = self.frames.partition_point(|f| f.start < now - 1.0);
|
||||
let mut s = self.summarise(&self.frames[a..], 1.0, 0.0);
|
||||
let total = self.summarise(self.counted(), 1.0, 0.0);
|
||||
s.late = total.late;
|
||||
s.dropped = total.dropped;
|
||||
s
|
||||
}
|
||||
|
||||
/// Short HUD lines.
|
||||
pub fn hud(&self) -> [String; 4] {
|
||||
let s = self.recent();
|
||||
[
|
||||
format!("{} · {:.0} Hz display", self.framework, self.refresh_hz),
|
||||
format!("{:.0} fps · interval p95 {:.1} ms", s.fps, s.interval_ms[1]),
|
||||
format!("work p50 {:.2} · p95 {:.2} ms", s.work_ms[0], s.work_ms[1]),
|
||||
format!("missed {} · {:.0} MB", s.dropped, s.footprint_mb),
|
||||
]
|
||||
}
|
||||
|
||||
/// The summary as JSON, with the build's notes.
|
||||
pub fn json(&mut self) -> String {
|
||||
let s = self.summary();
|
||||
let arr = |v: [f64; 4]| format!("{{\"p50\": {:.3}, \"p95\": {:.3}, \"p99\": {:.3}, \"max\": {:.3}}}", v[0], v[1], v[2], v[3]);
|
||||
let mut out = String::from("{\n");
|
||||
out.push_str(&format!(" \"framework\": \"{}\",\n", self.framework));
|
||||
out.push_str(&format!(" \"refresh_hz\": {:.2},\n", self.refresh_hz));
|
||||
out.push_str(&format!(" \"seconds\": {:.3},\n", s.seconds));
|
||||
out.push_str(&format!(" \"frames\": {},\n", s.frames));
|
||||
out.push_str(&format!(" \"fps\": {:.2},\n", s.fps));
|
||||
out.push_str(&format!(" \"interval_ms\": {},\n", arr(s.interval_ms)));
|
||||
out.push_str(&format!(" \"work_ms\": {},\n", arr(s.work_ms)));
|
||||
if let Some(b) = s.build_ms {
|
||||
out.push_str(&format!(" \"build_ms\": {},\n", arr(b)));
|
||||
}
|
||||
out.push_str(&format!(" \"late_intervals\": {},\n", s.late));
|
||||
out.push_str(&format!(" \"dropped_frames\": {},\n", s.dropped));
|
||||
out.push_str(&format!(" \"idle_gaps\": {},\n", s.idle_gaps));
|
||||
out.push_str(&format!(" \"cpu_percent\": {:.2},\n", s.cpu_percent));
|
||||
out.push_str(&format!(" \"footprint_mb\": {:.2},\n", s.footprint_mb));
|
||||
out.push_str(&format!(" \"footprint_peak_mb\": {:.2},\n", s.footprint_peak_mb));
|
||||
out.push_str(&format!(" \"resident_mb\": {:.2}", s.resident_mb));
|
||||
for (k, v) in &self.extra {
|
||||
out.push_str(&format!(",\n \"{k}\": \"{}\"", v.replace('\\', "\\\\").replace('"', "\\\"")));
|
||||
}
|
||||
out.push_str("\n}\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// The last `n` frames' show time and build time (work where the build can't split it).
|
||||
pub fn tail(&self, n: usize) -> impl Iterator<Item = (f32, f32)> + '_ {
|
||||
self.frames[self.frames.len().saturating_sub(n)..].iter().map(|f| (f.show, if f.build_ms.is_nan() { f.work_ms } else { f.build_ms }))
|
||||
}
|
||||
|
||||
/// Every frame as CSV, one line each: `show_s,load,build_ms,work_ms,start_s,cpu_ms,proc_ms`
|
||||
/// (`cpu_ms` and `proc_ms` are the CPU time since the frame before, thread and process).
|
||||
pub fn frames_csv(&self) -> String {
|
||||
let mut out = String::from("show_s,load,build_ms,work_ms,start_s,cpu_ms,proc_ms\n");
|
||||
for f in &self.frames {
|
||||
out.push_str(&format!("{:.4},{},{:.4},{:.4},{:.4},{:.4},{:.4}\n", f.show, f.load, f.build_ms, f.work_ms, f.start, f.cpu_ms, f.proc_ms));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn write(&mut self, path: &std::path::Path) -> std::io::Result<()> {
|
||||
let json = self.json();
|
||||
std::fs::write(path, json)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn counts_late_frames_against_the_refresh() {
|
||||
let mut m = Meter::new("test", 120.0);
|
||||
let t0 = m.t0;
|
||||
let period = Duration::from_secs_f64(1.0 / 120.0);
|
||||
let mut at = t0;
|
||||
for i in 0..240 {
|
||||
// Every 60th frame takes three refreshes.
|
||||
at += if i % 60 == 59 { period * 3 } else { period };
|
||||
m.frame_with_build(at, 2.0, 1.5);
|
||||
}
|
||||
// A rest is not a miss.
|
||||
m.frame(at + Duration::from_millis(400), 2.0);
|
||||
let s = m.summarise(&m.frames, 2.0, 0.0);
|
||||
assert_eq!(s.late, 4);
|
||||
assert_eq!(s.dropped, 8);
|
||||
assert_eq!(s.idle_gaps, 1);
|
||||
assert!((s.interval_ms[0] - 1000.0 / 120.0).abs() < 0.01);
|
||||
assert_eq!(s.build_ms.map(|b| b[0]), Some(1.5));
|
||||
assert!(m.json().contains("\"dropped_frames\""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! The bento's logical state and the actions that change it.
|
||||
//!
|
||||
//! An [`Action`] carries only indices. Whatever randomness an action needs (a fader's new level,
|
||||
//! the puck's next spot) comes from that tile's own [`Rng`] inside the model, so two builds that
|
||||
//! apply the same actions in the same order hold the same state, whatever they draw.
|
||||
|
||||
use crate::rng::Rng;
|
||||
|
||||
pub const SCENES: [&str; 4] = ["Focus", "Relax", "Away", "Night"];
|
||||
pub const LIGHTS: [&str; 4] = ["Studio", "Desk lamp", "Hallway", "Porch"];
|
||||
pub const FADERS: [&str; 5] = ["Kick", "Bass", "Keys", "Vox", "FX"];
|
||||
pub const SCENE_NOTES: [&str; 4] = [
|
||||
"Cool, bright light. Notifications held.",
|
||||
"Warm light and something slow playing.",
|
||||
"Lights off, cameras armed, heat eased.",
|
||||
"Dim amber light. Quiet hours.",
|
||||
];
|
||||
pub const DOCK: [&str; 5] = ["Energy", "Genres", "Orb", "Transfers", "Visitors"];
|
||||
/// Each dock tile's key.
|
||||
pub const DOCK_KEYS: [&str; 5] = ["energy", "chips", "orb", "transfers", "visitors"];
|
||||
pub const CHIPS: [&str; 8] = ["Ambient", "Lo-fi", "Jazz", "Rain", "Synth", "Piano", "Cafe", "Forest"];
|
||||
/// Chips shown while the chip tile is collapsed.
|
||||
pub const CHIPS_FOLDED: usize = 4;
|
||||
pub const TRACKS: [(&str, &str); 8] = [
|
||||
("Night Drive", "Lumen"),
|
||||
("Paper Moons", "Hollow Coast"),
|
||||
("Glasshouse", "Ines Varga"),
|
||||
("Slow Orbit", "Kites"),
|
||||
("Low Tide", "Marlowe"),
|
||||
("Afterglow", "Sable Youth"),
|
||||
("Neon Rain", "Oda"),
|
||||
("Soft Static", "Fen"),
|
||||
];
|
||||
pub const QUEUE_LEN: usize = 4;
|
||||
pub const FEED_KINDS: [&str; 8] = [
|
||||
"Front door unlocked",
|
||||
"Motion in the hallway",
|
||||
"Washer finished",
|
||||
"Package delivered",
|
||||
"Living room at 21°",
|
||||
"Garage closed",
|
||||
"Doorbell rang",
|
||||
"Air purifier on",
|
||||
];
|
||||
pub const FEED_LEN: usize = 4;
|
||||
pub const FILES: [&str; 3] = ["mix-final.wav", "photos-oct.zip", "backup.tar"];
|
||||
pub const ENERGY_BARS: usize = 7;
|
||||
/// Recent visitor arrivals the visitors tile charts.
|
||||
pub const VISITS: usize = 12;
|
||||
/// The most visitors one arrival brings.
|
||||
pub const VISIT_MAX: u32 = 48;
|
||||
pub const TEMP_MIN: f32 = 16.0;
|
||||
pub const TEMP_MAX: f32 = 28.0;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Action {
|
||||
Scene(u8),
|
||||
TempUp,
|
||||
TempDown,
|
||||
Light(u8),
|
||||
Fader(u8),
|
||||
Puck,
|
||||
Queue,
|
||||
Feed,
|
||||
Focus(u8),
|
||||
Energy,
|
||||
ChipsMore,
|
||||
Chip(u8),
|
||||
Orb,
|
||||
Transfer(u8),
|
||||
Visitors,
|
||||
}
|
||||
|
||||
impl Action {
|
||||
/// The key of the element a person would tap for this action. Both builds key their elements
|
||||
/// this way, and the Rune script taps them.
|
||||
pub fn key(self) -> String {
|
||||
match self {
|
||||
Action::Scene(i) => format!("scene/seg{i}"),
|
||||
Action::TempUp => "thermo/up".into(),
|
||||
Action::TempDown => "thermo/down".into(),
|
||||
Action::Light(i) => format!("lights/light{i}"),
|
||||
Action::Fader(i) => format!("mixer/fader{i}"),
|
||||
Action::Puck => "xy/pad".into(),
|
||||
Action::Queue => "queue/head/skip".into(),
|
||||
Action::Feed => "feed/head/test".into(),
|
||||
Action::Focus(i) => format!("{}/head", DOCK_KEYS[i as usize % DOCK_KEYS.len()]),
|
||||
Action::Energy => "energy/bars".into(),
|
||||
Action::ChipsMore => "chips/head/more".into(),
|
||||
Action::Chip(i) => format!("chips/chip{i}"),
|
||||
Action::Orb => "orb/orb".into(),
|
||||
Action::Transfer(i) => format!("transfers/row{i}"),
|
||||
Action::Visitors => "visitors/count".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FeedItem {
|
||||
/// Unique for the run: the element's identity.
|
||||
pub id: u32,
|
||||
pub kind: usize,
|
||||
/// Minutes past the hour, for the time label.
|
||||
pub minute: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Card {
|
||||
pub id: u32,
|
||||
pub track: usize,
|
||||
}
|
||||
|
||||
/// One arrival of visitors: a bar in the visitors chart.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Visit {
|
||||
pub id: u32,
|
||||
pub count: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Orb {
|
||||
/// 0..1 of the largest size.
|
||||
pub size: f32,
|
||||
/// OKLCH hue in degrees.
|
||||
pub hue: f32,
|
||||
/// Corner radius as a fraction of the side: 0.5 is a circle.
|
||||
pub round: f32,
|
||||
/// Degrees, always growing so the spring turns one way.
|
||||
pub turn: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Model {
|
||||
/// Actions applied so far: the header's counter.
|
||||
pub events: u32,
|
||||
pub scene: usize,
|
||||
pub temp: f32,
|
||||
pub lights: [bool; 4],
|
||||
pub faders: [f32; 5],
|
||||
/// The XY pad's puck, 0..1 on each axis.
|
||||
pub puck: [f32; 2],
|
||||
/// Front card first.
|
||||
pub queue: Vec<Card>,
|
||||
/// Newest first.
|
||||
pub feed: Vec<FeedItem>,
|
||||
/// Which dock tile is wide.
|
||||
pub focus: usize,
|
||||
pub energy: [f32; ENERGY_BARS],
|
||||
/// Tenths of a kWh, so both builds print the same digits.
|
||||
pub kwh_tenths: u32,
|
||||
pub chips_open: bool,
|
||||
pub chips: [bool; 8],
|
||||
pub orb: Orb,
|
||||
pub transfers: [f32; 3],
|
||||
pub visitors: u32,
|
||||
/// Oldest first.
|
||||
pub visits: Vec<Visit>,
|
||||
next_id: u32,
|
||||
minute: u32,
|
||||
rng: [Rng; 8],
|
||||
}
|
||||
|
||||
const R_FADER: usize = 0;
|
||||
const R_PUCK: usize = 1;
|
||||
const R_QUEUE: usize = 2;
|
||||
const R_FEED: usize = 3;
|
||||
const R_ENERGY: usize = 4;
|
||||
const R_ORB: usize = 5;
|
||||
const R_TRANSFER: usize = 6;
|
||||
const R_VISITORS: usize = 7;
|
||||
|
||||
impl Model {
|
||||
pub fn new(seed: u64) -> Model {
|
||||
let rng = std::array::from_fn(|i| Rng::new(seed.wrapping_mul(0x2545_f491_4f6c_dd1d) ^ (i as u64 + 1)));
|
||||
let mut m = Model {
|
||||
events: 0,
|
||||
scene: 0,
|
||||
temp: 21.5,
|
||||
lights: [true, false, true, false],
|
||||
faders: [0.72, 0.58, 0.44, 0.66, 0.3],
|
||||
puck: [0.62, 0.38],
|
||||
queue: Vec::new(),
|
||||
feed: Vec::new(),
|
||||
focus: 0,
|
||||
energy: [0.42, 0.55, 0.38, 0.7, 0.62, 0.48, 0.8],
|
||||
kwh_tenths: 128,
|
||||
chips_open: false,
|
||||
chips: [true, false, true, false, false, false, false, false],
|
||||
orb: Orb { size: 0.8, hue: 245.0, round: 0.5, turn: 0.0 },
|
||||
transfers: [0.35, 0.7, 0.12],
|
||||
visitors: 1284,
|
||||
visits: Vec::new(),
|
||||
next_id: 0,
|
||||
minute: 2,
|
||||
rng,
|
||||
};
|
||||
for track in 0..QUEUE_LEN {
|
||||
let id = m.id();
|
||||
m.queue.push(Card { id, track });
|
||||
}
|
||||
for count in [12, 18, 9, 22, 30, 26, 14, 19, 33, 28, 21, 17] {
|
||||
let id = m.id();
|
||||
m.visits.push(Visit { id, count });
|
||||
}
|
||||
for kind in [2, 0, 5] {
|
||||
let id = m.id();
|
||||
m.minute += 3;
|
||||
m.feed.insert(0, FeedItem { id, kind, minute: m.minute });
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
fn id(&mut self) -> u32 {
|
||||
self.next_id += 1;
|
||||
self.next_id
|
||||
}
|
||||
|
||||
pub fn chips_shown(&self) -> usize {
|
||||
if self.chips_open { CHIPS.len() } else { CHIPS_FOLDED }
|
||||
}
|
||||
|
||||
pub fn energy_kwh(&self) -> String {
|
||||
format!("{}.{}", self.kwh_tenths / 10, self.kwh_tenths % 10)
|
||||
}
|
||||
|
||||
pub fn temp_label(&self) -> String {
|
||||
format!("{:.1}°", self.temp)
|
||||
}
|
||||
|
||||
/// 0..1 around the thermostat's ring.
|
||||
pub fn temp_fraction(&self) -> f32 {
|
||||
(self.temp - TEMP_MIN) / (TEMP_MAX - TEMP_MIN)
|
||||
}
|
||||
|
||||
pub fn apply(&mut self, action: Action) {
|
||||
self.events += 1;
|
||||
match action {
|
||||
Action::Scene(i) => self.scene = i as usize % SCENES.len(),
|
||||
Action::TempUp => self.temp = (self.temp + 0.5).min(TEMP_MAX),
|
||||
Action::TempDown => self.temp = (self.temp - 0.5).max(TEMP_MIN),
|
||||
Action::Light(i) => {
|
||||
let l = &mut self.lights[i as usize % 4];
|
||||
*l = !*l;
|
||||
}
|
||||
Action::Fader(i) => {
|
||||
let r = &mut self.rng[R_FADER];
|
||||
let f = &mut self.faders[i as usize % FADERS.len()];
|
||||
// Move far enough to see.
|
||||
let mut next = r.rangef(0.12, 0.96);
|
||||
if (next - *f).abs() < 0.2 {
|
||||
next = if *f > 0.5 { *f - 0.35 } else { *f + 0.35 };
|
||||
}
|
||||
*f = next;
|
||||
}
|
||||
Action::Puck => {
|
||||
let r = &mut self.rng[R_PUCK];
|
||||
self.puck = [r.rangef(0.08, 0.92), r.rangef(0.1, 0.9)];
|
||||
}
|
||||
Action::Queue => {
|
||||
self.queue.remove(0);
|
||||
let last = self.queue.last().map_or(0, |c| c.track);
|
||||
let track = (last + 1 + self.rng[R_QUEUE].below(TRACKS.len() - 1)) % TRACKS.len();
|
||||
let id = self.id();
|
||||
self.queue.push(Card { id, track });
|
||||
}
|
||||
Action::Feed => {
|
||||
let r = &mut self.rng[R_FEED];
|
||||
let kind = r.below(FEED_KINDS.len());
|
||||
self.minute = (self.minute + 1 + r.below(4) as u32) % 60;
|
||||
let id = self.id();
|
||||
self.feed.insert(0, FeedItem { id, kind, minute: self.minute });
|
||||
self.feed.truncate(FEED_LEN);
|
||||
}
|
||||
Action::Focus(i) => self.focus = i as usize % DOCK.len(),
|
||||
Action::Energy => {
|
||||
let r = &mut self.rng[R_ENERGY];
|
||||
for b in &mut self.energy {
|
||||
*b = r.rangef(0.15, 1.0);
|
||||
}
|
||||
self.kwh_tenths += 3 + r.below(23) as u32;
|
||||
}
|
||||
Action::ChipsMore => self.chips_open = !self.chips_open,
|
||||
Action::Chip(i) => {
|
||||
let c = &mut self.chips[i as usize % CHIPS.len()];
|
||||
*c = !*c;
|
||||
}
|
||||
Action::Orb => {
|
||||
let r = &mut self.rng[R_ORB];
|
||||
self.orb = Orb {
|
||||
size: r.rangef(0.55, 1.0),
|
||||
hue: (self.orb.hue + r.rangef(40.0, 140.0)) % 360.0,
|
||||
round: [0.5, 0.32, 0.22][r.below(3)],
|
||||
turn: self.orb.turn + [45.0, 90.0, 135.0][r.below(3)],
|
||||
};
|
||||
}
|
||||
Action::Transfer(i) => {
|
||||
let step = self.rng[R_TRANSFER].rangef(0.15, 0.4);
|
||||
let t = &mut self.transfers[i as usize % 3];
|
||||
*t = if *t >= 1.0 { 0.0 } else { (*t + step).min(1.0) };
|
||||
}
|
||||
Action::Visitors => {
|
||||
let count = 1 + self.rng[R_VISITORS].below(VISIT_MAX as usize) as u32;
|
||||
self.visitors += count;
|
||||
let id = self.id();
|
||||
self.visits.remove(0);
|
||||
self.visits.push(Visit { id, count });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_same_actions_give_the_same_state() {
|
||||
let actions = [Action::Fader(2), Action::Puck, Action::Queue, Action::Feed, Action::Orb, Action::Energy];
|
||||
let run = |seed| {
|
||||
let mut m = Model::new(seed);
|
||||
for a in actions.iter().chain(&actions) {
|
||||
m.apply(*a);
|
||||
}
|
||||
format!("{:?}", (m.faders, m.puck, m.queue, m.feed, m.orb, m.energy, m.kwh_tenths))
|
||||
};
|
||||
assert_eq!(run(3), run(3));
|
||||
assert_ne!(run(3), run(4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_keep_their_length() {
|
||||
let mut m = Model::new(1);
|
||||
for _ in 0..20 {
|
||||
m.apply(Action::Queue);
|
||||
m.apply(Action::Feed);
|
||||
m.apply(Action::Visitors);
|
||||
}
|
||||
assert_eq!(m.visits.len(), VISITS);
|
||||
assert_eq!(m.queue.len(), QUEUE_LEN);
|
||||
assert_eq!(m.feed.len(), FEED_LEN);
|
||||
let ids: std::collections::HashSet<u32> = m.queue.iter().map(|c| c.id).chain(m.feed.iter().map(|f| f.id)).collect();
|
||||
assert_eq!(ids.len(), QUEUE_LEN + FEED_LEN);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! SplitMix64: tiny, fast and identical on every platform, so a seed names one show everywhere.
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
pub fn new(seed: u64) -> Rng {
|
||||
Rng(seed ^ 0x9e37_79b9_7f4a_7c15)
|
||||
}
|
||||
|
||||
pub fn next_u64(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
/// Uniform in [0, 1).
|
||||
pub fn f64(&mut self) -> f64 {
|
||||
(self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
|
||||
/// Uniform in [lo, hi).
|
||||
pub fn range(&mut self, lo: f64, hi: f64) -> f64 {
|
||||
lo + (hi - lo) * self.f64()
|
||||
}
|
||||
|
||||
pub fn rangef(&mut self, lo: f32, hi: f32) -> f32 {
|
||||
self.range(lo as f64, hi as f64) as f32
|
||||
}
|
||||
|
||||
/// Uniform in 0..n.
|
||||
pub fn below(&mut self, n: usize) -> usize {
|
||||
((self.f64() * n as f64) as usize).min(n.saturating_sub(1))
|
||||
}
|
||||
|
||||
/// An index into `weights`, chosen in proportion to them.
|
||||
pub fn weighted(&mut self, weights: &[u32]) -> usize {
|
||||
let total: u32 = weights.iter().sum();
|
||||
let mut pick = (self.f64() * total as f64) as u32;
|
||||
for (i, w) in weights.iter().enumerate() {
|
||||
if pick < *w {
|
||||
return i;
|
||||
}
|
||||
pick -= w;
|
||||
}
|
||||
weights.len() - 1
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_seed_names_one_sequence() {
|
||||
let a: Vec<u64> = (0..4).map({
|
||||
let mut r = Rng::new(7);
|
||||
move |_| r.next_u64()
|
||||
}).collect();
|
||||
let b: Vec<u64> = (0..4).map({
|
||||
let mut r = Rng::new(7);
|
||||
move |_| r.next_u64()
|
||||
}).collect();
|
||||
assert_eq!(a, b);
|
||||
assert_ne!(Rng::new(8).next_u64(), a[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! The chaos schedule: a seeded list of timed actions, quiet stretches broken by bursts.
|
||||
//!
|
||||
//! The schedule plays the actions against its own [`Model`] as it picks them, so every action is
|
||||
//! one a person could take at that moment (a chip that's showing, a scene that isn't already on).
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::model::{Action, CHIPS, DOCK, FADERS, Model, SCENES};
|
||||
use crate::rng::Rng;
|
||||
|
||||
/// Chaos starts once the first frames have settled.
|
||||
pub const START: f64 = 0.6;
|
||||
/// A Rune script taps this long before the event's time and lifts at it, so the action lands at
|
||||
/// `t` in a recording.
|
||||
pub const TAP_LEAD: f64 = 0.01;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Event {
|
||||
pub t: f64,
|
||||
pub action: Action,
|
||||
}
|
||||
|
||||
// Relative odds per kind of action.
|
||||
const KINDS: [u32; 15] = [5, 4, 4, 9, 12, 8, 6, 8, 6, 6, 3, 8, 6, 8, 6];
|
||||
|
||||
fn pick(rng: &mut Rng, m: &Model) -> Action {
|
||||
let other = |rng: &mut Rng, n: usize, current: usize| ((current + 1 + rng.below(n - 1)) % n) as u8;
|
||||
match rng.weighted(&KINDS) {
|
||||
0 => Action::Scene(other(rng, SCENES.len(), m.scene)),
|
||||
1 => Action::TempUp,
|
||||
2 => Action::TempDown,
|
||||
3 => Action::Light(rng.below(4) as u8),
|
||||
4 => Action::Fader(rng.below(FADERS.len()) as u8),
|
||||
5 => Action::Puck,
|
||||
6 => Action::Queue,
|
||||
7 => Action::Feed,
|
||||
8 => Action::Focus(other(rng, DOCK.len(), m.focus)),
|
||||
9 => Action::Energy,
|
||||
10 => Action::ChipsMore,
|
||||
11 => Action::Chip(rng.below(m.chips_shown().min(CHIPS.len())) as u8),
|
||||
12 => Action::Orb,
|
||||
13 => Action::Transfer(rng.below(3) as u8),
|
||||
_ => Action::Visitors,
|
||||
}
|
||||
}
|
||||
|
||||
/// The run's actions in time order, from [`START`] to `config.duration`.
|
||||
pub fn schedule(config: &Config) -> Vec<Event> {
|
||||
let mut rng = Rng::new(config.seed);
|
||||
let mut model = Model::new(config.seed);
|
||||
let mut events = Vec::new();
|
||||
let (lo, hi) = config.gap();
|
||||
let mut t = START;
|
||||
let mut next_burst = START + rng.range(1.2, 2.2);
|
||||
while t < config.duration {
|
||||
let action = pick(&mut rng, &model);
|
||||
model.apply(action);
|
||||
events.push(Event { t, action });
|
||||
if t >= next_burst {
|
||||
// A burst: 6–12 actions 30–60 ms apart, then a breath.
|
||||
let n = 6 + rng.below(7);
|
||||
for _ in 0..n {
|
||||
t += rng.range(0.03, 0.06);
|
||||
if t >= config.duration {
|
||||
break;
|
||||
}
|
||||
let action = pick(&mut rng, &model);
|
||||
model.apply(action);
|
||||
events.push(Event { t, action });
|
||||
}
|
||||
t += rng.range(0.35, 0.6);
|
||||
next_burst = t + rng.range(2.0, 3.0);
|
||||
} else {
|
||||
t += rng.range(lo, hi);
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
/// The schedule as a Rune headless script: one tap per action at its key, and an `end` mark a
|
||||
/// second after the last so the springs settle on camera.
|
||||
pub fn script_json(config: &Config) -> String {
|
||||
let mut out = String::from("{\"events\": [\n");
|
||||
for e in schedule(config) {
|
||||
out.push_str(&format!(
|
||||
" {{\"t\": {:.4}, \"type\": \"tap\", \"key\": \"{}\", \"hold\": {TAP_LEAD}}},\n",
|
||||
e.t - TAP_LEAD,
|
||||
e.action.key()
|
||||
));
|
||||
}
|
||||
out.push_str(&format!(" {{\"t\": {:.4}, \"type\": \"mark\", \"name\": \"end\"}}\n]}}\n", config.duration + 1.0));
|
||||
out
|
||||
}
|
||||
|
||||
/// Plays a schedule against a clock: hands back each action once its time has come.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Player {
|
||||
events: Vec<Event>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl Player {
|
||||
pub fn new(config: &Config) -> Player {
|
||||
Player { events: schedule(config), next: 0 }
|
||||
}
|
||||
|
||||
/// The actions due by `t` seconds that haven't been handed out yet.
|
||||
pub fn due(&mut self, t: f64) -> impl Iterator<Item = Action> + '_ {
|
||||
let start = self.next;
|
||||
while self.next < self.events.len() && self.events[self.next].t <= t {
|
||||
self.next += 1;
|
||||
}
|
||||
self.events[start..self.next].iter().map(|e| e.action)
|
||||
}
|
||||
|
||||
pub fn done(&self) -> bool {
|
||||
self.next == self.events.len()
|
||||
}
|
||||
|
||||
/// The time of the next action, if any.
|
||||
pub fn next_at(&self) -> Option<f64> {
|
||||
self.events.get(self.next).map(|e| e.t)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.events.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.events.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn config(seed: u64, duration: f64, intensity: f64) -> Config {
|
||||
Config { seed, duration, intensity, ..Config::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_seed_names_one_schedule() {
|
||||
assert_eq!(schedule(&config(5, 10.0, 1.0)), schedule(&config(5, 10.0, 1.0)));
|
||||
assert_ne!(schedule(&config(5, 10.0, 1.0)), schedule(&config(6, 10.0, 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intensity_scales_the_rate_and_bursts_happen() {
|
||||
let calm = schedule(&config(1, 20.0, 1.0));
|
||||
let busy = schedule(&config(1, 20.0, 2.0));
|
||||
assert!(busy.len() as f64 > calm.len() as f64 * 1.4, "{} vs {}", busy.len(), calm.len());
|
||||
let tight = calm.windows(2).filter(|w| w[1].t - w[0].t < 0.07).count();
|
||||
assert!(tight >= 30, "bursts: {tight} tight gaps");
|
||||
assert!(calm.windows(2).all(|w| w[1].t > w[0].t && w[1].t - w[0].t >= 0.03 - 1e-9));
|
||||
assert!(calm.iter().all(|e| e.t >= START && e.t < 20.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_action_is_takeable() {
|
||||
let mut m = Model::new(2);
|
||||
for e in schedule(&config(2, 30.0, 3.0)) {
|
||||
match e.action {
|
||||
Action::Scene(i) => assert_ne!(i as usize, m.scene),
|
||||
Action::Focus(i) => assert_ne!(i as usize, m.focus),
|
||||
Action::Chip(i) => assert!((i as usize) < m.chips_shown()),
|
||||
_ => {}
|
||||
}
|
||||
m.apply(e.action);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_player_hands_out_each_action_once() {
|
||||
let c = config(3, 6.0, 1.0);
|
||||
let mut p = Player::new(&c);
|
||||
let mut seen = 0;
|
||||
let mut t = 0.0;
|
||||
while !p.done() {
|
||||
t += 1.0 / 120.0;
|
||||
seen += p.due(t).count();
|
||||
}
|
||||
assert_eq!(seen, schedule(&c).len());
|
||||
assert!(script_json(&c).contains("\"key\": \""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
//! Stress mode: a wall of live controls, each a small bento of its own, that all move at once,
|
||||
//! so both builds can be loaded until one of them misses its frames.
|
||||
//!
|
||||
//! `--load N` holds N controls. `--ramp A:B` steps from A controls to B, ×√2 a step, holding each
|
||||
//! for `--hold` seconds. Everything a control shows is a pure function of the seed, its id and the
|
||||
//! show time, so the two builds draw the same wall at the same moment without sharing anything
|
||||
//! but this module: each control's bars retarget every 0.16–0.46 s, its reading changes every
|
||||
//! frame, its switch flips, its tint drifts; every 1.7 s a twelfth of the wall goes wide and every
|
||||
//! 2 s the whole wall reshuffles, so every control flies to a new place.
|
||||
|
||||
use crate::look::{Lch, grid, lch};
|
||||
use crate::schedule::START;
|
||||
|
||||
/// Bars in each control's meter.
|
||||
pub const BARS: usize = 8;
|
||||
/// The header above the wall: the title, the load and the HUD.
|
||||
pub const HEADER: f32 = 120.0;
|
||||
/// Seconds between reshuffles of the whole wall.
|
||||
pub const SHUFFLE: f64 = 2.0;
|
||||
/// Seconds between changes of which controls are wide.
|
||||
pub const WIDE_EVERY: f64 = 1.7;
|
||||
/// One control in this many is wide.
|
||||
pub const WIDE_SHARE: usize = 12;
|
||||
pub const STATUS: [&str; 6] = ["Idle", "Heat", "Cool", "Boost", "Eco", "Auto"];
|
||||
pub const HUES: [f32; 5] = [245.0, 200.0, 290.0, 165.0, 70.0];
|
||||
/// A control's width over its height.
|
||||
const ASPECT: f32 = 1.5;
|
||||
|
||||
/// How many controls the wall holds over time.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Load {
|
||||
Fixed(usize),
|
||||
/// Each level for `hold` seconds, the first from [`START`].
|
||||
Ramp { levels: Vec<usize>, hold: f64 },
|
||||
}
|
||||
|
||||
impl Load {
|
||||
/// From `from` to `to` controls, ×√2 a step (rounded), `to` last.
|
||||
pub fn ramp(from: usize, to: usize, hold: f64) -> Load {
|
||||
let mut levels = Vec::new();
|
||||
let mut n = from.max(1) as f64;
|
||||
while (n.round() as usize) < to {
|
||||
levels.push(n.round() as usize);
|
||||
n *= std::f64::consts::SQRT_2;
|
||||
}
|
||||
levels.push(to.max(from.max(1)));
|
||||
Load::Ramp { levels, hold }
|
||||
}
|
||||
|
||||
/// `A:B`, as `--ramp` takes it.
|
||||
pub fn parse_ramp(spec: &str, hold: f64) -> Result<Load, String> {
|
||||
let (a, b) = spec.split_once(':').ok_or_else(|| format!("--ramp wants FROM:TO, got {spec}"))?;
|
||||
let n = |s: &str| s.trim().parse::<usize>().map_err(|_| format!("--ramp: not a count: {s}"));
|
||||
let (a, b) = (n(a)?, n(b)?);
|
||||
if a == 0 || b < a {
|
||||
return Err(format!("--ramp wants 0 < FROM ≤ TO, got {spec}"));
|
||||
}
|
||||
Ok(Load::ramp(a, b, hold))
|
||||
}
|
||||
|
||||
pub fn levels(&self) -> &[usize] {
|
||||
match self {
|
||||
Load::Fixed(n) => std::slice::from_ref(n),
|
||||
Load::Ramp { levels, .. } => levels,
|
||||
}
|
||||
}
|
||||
|
||||
/// The level index at show time `t`.
|
||||
pub fn step_at(&self, t: f64) -> usize {
|
||||
match self {
|
||||
Load::Fixed(_) => 0,
|
||||
Load::Ramp { levels, hold } => (((t - START).max(0.0) / hold) as usize).min(levels.len() - 1),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn at(&self, t: f64) -> usize {
|
||||
self.levels()[self.step_at(t)]
|
||||
}
|
||||
|
||||
/// The show a ramp needs: every level held once. `None` for a fixed load.
|
||||
pub fn duration(&self) -> Option<f64> {
|
||||
match self {
|
||||
Load::Fixed(_) => None,
|
||||
Load::Ramp { levels, hold } => Some(START + levels.len() as f64 * hold),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The wall's rectangle in window points, below the header.
|
||||
pub fn area() -> [f32; 4] {
|
||||
let y = grid::PAD - 8.0 + HEADER + grid::GAP;
|
||||
[grid::PAD, y, grid::WIDTH - 2.0 * grid::PAD, grid::HEIGHT - grid::PAD - y]
|
||||
}
|
||||
|
||||
/// A control's accent, its bars' top and bottom.
|
||||
pub fn tint(hue: f32) -> Lch {
|
||||
lch(0.72, 0.15, hue)
|
||||
}
|
||||
pub fn tint_hi(hue: f32) -> Lch {
|
||||
lch(0.82, 0.12, hue)
|
||||
}
|
||||
pub fn tint_lo(hue: f32) -> Lch {
|
||||
lch(0.52, 0.16, hue)
|
||||
}
|
||||
/// A hot control's card and edge.
|
||||
pub fn hot_fill(hue: f32) -> Lch {
|
||||
lch(0.235, 0.035, hue)
|
||||
}
|
||||
pub fn hot_edge(hue: f32) -> Lch {
|
||||
lch(0.72, 0.15, hue).alpha(0.55)
|
||||
}
|
||||
|
||||
/// One control at one moment.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Cell {
|
||||
pub id: u32,
|
||||
/// x, y, w, h in window points.
|
||||
pub rect: [f32; 4],
|
||||
pub wide: bool,
|
||||
pub hue: f32,
|
||||
pub on: bool,
|
||||
/// Its bars average over 0.6: the card takes its tint.
|
||||
pub hot: bool,
|
||||
/// 0..1 of the meter's height.
|
||||
pub bars: [f32; BARS],
|
||||
pub progress: f32,
|
||||
pub status: &'static str,
|
||||
reading: f64,
|
||||
}
|
||||
|
||||
impl Cell {
|
||||
pub fn name(&self) -> String {
|
||||
format!("Zone {}", self.id + 1)
|
||||
}
|
||||
|
||||
/// Changes every frame.
|
||||
pub fn reading(&self) -> String {
|
||||
format!("{:.2}", self.reading)
|
||||
}
|
||||
|
||||
pub fn percent(&self) -> String {
|
||||
format!("{:.0}%", self.progress * 100.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Every size inside a control, from the height of the wall's rows, so a control looks the same
|
||||
/// from 16 on the wall to a thousand, only smaller.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Metrics {
|
||||
/// The scale: 1 is a 100-point-tall control.
|
||||
pub u: f32,
|
||||
pub pad: f32,
|
||||
pub gap: f32,
|
||||
pub radius: f32,
|
||||
pub name: f32,
|
||||
pub reading: f32,
|
||||
pub small: f32,
|
||||
pub dot: f32,
|
||||
pub bar_gap: f32,
|
||||
pub bars_h: f32,
|
||||
pub foot_h: f32,
|
||||
pub track_h: f32,
|
||||
pub switch_w: f32,
|
||||
pub switch_h: f32,
|
||||
pub knob: f32,
|
||||
pub shadow_y: f32,
|
||||
pub shadow_blur: f32,
|
||||
}
|
||||
|
||||
/// Line height for a type size, as both builds set it.
|
||||
pub fn lh(size: f32) -> f32 {
|
||||
(size * 1.3).round()
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
pub fn for_height(h: f32) -> Metrics {
|
||||
let u = ((h / 100.0).clamp(0.25, 1.5) * 16.0).round() / 16.0;
|
||||
let (pad, gap, name, reading, small) = (7.0 * u, 4.0 * u, 11.0 * u, 16.0 * u, 10.0 * u);
|
||||
let foot_h = 12.0 * u;
|
||||
let bars_h = (h - 2.0 * pad - 3.0 * gap - lh(name) - lh(reading) - foot_h).max(2.0);
|
||||
Metrics {
|
||||
u,
|
||||
pad,
|
||||
gap,
|
||||
radius: 12.0 * u,
|
||||
name,
|
||||
reading,
|
||||
small,
|
||||
dot: 6.0 * u,
|
||||
bar_gap: 3.0 * u,
|
||||
bars_h,
|
||||
foot_h,
|
||||
track_h: 4.0 * u,
|
||||
switch_w: 22.0 * u,
|
||||
switch_h: 12.0 * u,
|
||||
knob: 10.0 * u,
|
||||
shadow_y: 4.0 * u,
|
||||
shadow_blur: 12.0 * u,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mix(seed: u64, id: u32, salt: u32, epoch: u64) -> u64 {
|
||||
let mut z = seed ^ (id as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ ((salt as u64) << 40) ^ epoch.wrapping_mul(0xd6e8_feb8_6659_fd93);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
fn unit(x: u64) -> f32 {
|
||||
(x >> 40) as f32 / (1u64 << 24) as f32
|
||||
}
|
||||
|
||||
fn epoch(t: f64, every: f64, phase: f32) -> u64 {
|
||||
(t / every + phase as f64).max(0.0).floor() as u64
|
||||
}
|
||||
|
||||
/// The wall: its controls at the last [`Wall::update`].
|
||||
pub struct Wall {
|
||||
seed: u64,
|
||||
cells: Vec<Cell>,
|
||||
/// Ids in the order they flow into the grid, for `order_epoch`.
|
||||
order: Vec<u32>,
|
||||
order_epoch: Option<(u64, usize)>,
|
||||
wide: Vec<bool>,
|
||||
wide_epoch: Option<(u64, usize)>,
|
||||
pub metrics: Metrics,
|
||||
pub cols: usize,
|
||||
pub rows: usize,
|
||||
}
|
||||
|
||||
impl Wall {
|
||||
pub fn new(seed: u64) -> Wall {
|
||||
Wall {
|
||||
seed,
|
||||
cells: Vec::new(),
|
||||
order: Vec::new(),
|
||||
order_epoch: None,
|
||||
wide: Vec::new(),
|
||||
wide_epoch: None,
|
||||
metrics: Metrics::for_height(100.0),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The controls by id: a control keeps its index for as long as it's on the wall.
|
||||
pub fn cells(&self) -> &[Cell] {
|
||||
&self.cells
|
||||
}
|
||||
|
||||
/// Moves the wall to show time `t` with `n` controls.
|
||||
pub fn update(&mut self, t: f64, n: usize) {
|
||||
let seed = self.seed;
|
||||
self.cells.truncate(n);
|
||||
while self.cells.len() < n {
|
||||
let id = self.cells.len() as u32;
|
||||
self.cells.push(Cell { id, rect: [0.0; 4], wide: false, hue: 0.0, on: false, hot: false, bars: [0.0; BARS], progress: 0.0, status: "", reading: 0.0 });
|
||||
}
|
||||
let e = epoch(t, SHUFFLE, 0.5);
|
||||
if self.order_epoch != Some((e, n)) {
|
||||
self.order_epoch = Some((e, n));
|
||||
self.order = (0..n as u32).collect();
|
||||
self.order.sort_unstable_by_key(|&id| mix(seed, id, 1, e));
|
||||
}
|
||||
let e = epoch(t, WIDE_EVERY, 0.0);
|
||||
if self.wide_epoch != Some((e, n)) {
|
||||
self.wide_epoch = Some((e, n));
|
||||
let k = n / WIDE_SHARE;
|
||||
let mut ids: Vec<u32> = (0..n as u32).collect();
|
||||
if k > 0 {
|
||||
ids.select_nth_unstable_by_key(k - 1, |&id| mix(seed, id, 2, e));
|
||||
}
|
||||
self.wide = vec![false; n];
|
||||
for &id in &ids[..k] {
|
||||
self.wide[id as usize] = true;
|
||||
}
|
||||
}
|
||||
for c in &mut self.cells {
|
||||
let id = c.id;
|
||||
let h = |salt: u32| unit(mix(seed, id, salt, 0));
|
||||
let eb = epoch(t, 0.16 + 0.3 * h(3) as f64, h(4));
|
||||
for (j, b) in c.bars.iter_mut().enumerate() {
|
||||
*b = 0.1 + 0.9 * unit(mix(seed, id, 100 + j as u32, eb));
|
||||
}
|
||||
let level = c.bars.iter().sum::<f32>() / BARS as f32;
|
||||
c.hot = level > 0.6;
|
||||
c.on = unit(mix(seed, id, 5, epoch(t, 0.7 + 1.2 * h(6) as f64, h(7)))) < 0.5;
|
||||
c.hue = HUES[(mix(seed, id, 8, epoch(t, 3.0, h(9))) % HUES.len() as u64) as usize];
|
||||
c.progress = ((t * (0.05 + 0.25 * h(10) as f64) + h(11) as f64).fract()) as f32;
|
||||
c.status = STATUS[(mix(seed, id, 12, epoch(t, 1.1, h(13))) % STATUS.len() as u64) as usize];
|
||||
c.reading = 20.0 + 980.0 * h(14) as f64 + t * (1.5 + 30.0 * h(15) as f64);
|
||||
c.wide = self.wide[id as usize];
|
||||
}
|
||||
self.flow();
|
||||
}
|
||||
|
||||
/// Places the controls in reading order: a wide control takes two columns, or one at a
|
||||
/// row's end. The rows are sized for `n + n / WIDE_SHARE` slots, so they never overflow.
|
||||
fn flow(&mut self) {
|
||||
let n = self.cells.len();
|
||||
let [ax, ay, aw, ah] = area();
|
||||
let slots = (n + n / WIDE_SHARE).max(1);
|
||||
let cols = (((slots as f32) * (aw / ah) / ASPECT).sqrt().round() as usize).clamp(1, slots);
|
||||
let rows = slots.div_ceil(cols);
|
||||
let gap = (10.0 * (40.0 / slots as f32).sqrt()).clamp(3.0, 12.0);
|
||||
let cw = (aw - gap * (cols - 1) as f32) / cols as f32;
|
||||
let ch = (ah - gap * (rows - 1) as f32) / rows as f32;
|
||||
self.metrics = Metrics::for_height(ch);
|
||||
self.cols = cols;
|
||||
self.rows = rows;
|
||||
let (mut col, mut row) = (0usize, 0usize);
|
||||
for &id in &self.order {
|
||||
let c = &mut self.cells[id as usize];
|
||||
let span = if c.wide && col + 2 <= cols { 2 } else { 1 };
|
||||
c.rect = [ax + col as f32 * (cw + gap), ay + row as f32 * (ch + gap), span as f32 * cw + (span - 1) as f32 * gap, ch];
|
||||
col += span;
|
||||
if col >= cols {
|
||||
col = 0;
|
||||
row += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_ramp_steps_by_root_two_and_ends_on_its_target() {
|
||||
let l = Load::parse_ramp("16:256", 2.5).unwrap();
|
||||
assert_eq!(l.levels(), [16, 23, 32, 45, 64, 91, 128, 181, 256]);
|
||||
assert_eq!(l.at(0.0), 16);
|
||||
assert_eq!(l.at(START + 2.5), 23);
|
||||
assert_eq!(l.at(1e6), 256);
|
||||
assert_eq!(l.duration(), Some(START + 9.0 * 2.5));
|
||||
assert!(Load::parse_ramp("8", 1.0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_wall_is_a_function_of_time_and_fits_its_area() {
|
||||
let [ax, ay, aw, ah] = area();
|
||||
for n in [1, 16, 91, 512] {
|
||||
let mut a = Wall::new(7);
|
||||
let mut b = Wall::new(7);
|
||||
for t in [0.0, 1.3, 2.71, 6.05] {
|
||||
a.update(t, n);
|
||||
}
|
||||
b.update(6.05, n);
|
||||
assert_eq!(a.cells(), b.cells(), "{n} controls");
|
||||
for c in a.cells() {
|
||||
let [x, y, w, h] = c.rect;
|
||||
assert!(x >= ax - 0.01 && y >= ay - 0.01 && x + w <= ax + aw + 0.01 && y + h <= ay + ah + 0.01, "{n}: {:?}", c.rect);
|
||||
}
|
||||
assert_eq!(a.cells().iter().filter(|c| c.wide).count(), n / WIDE_SHARE);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readings_change_every_frame() {
|
||||
let mut w = Wall::new(3);
|
||||
w.update(1.0, 32);
|
||||
let before: Vec<String> = w.cells().iter().map(Cell::reading).collect();
|
||||
w.update(1.0 + 1.0 / 120.0, 32);
|
||||
assert!(w.cells().iter().zip(&before).all(|(c, b)| c.reading() != *b));
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
//! The bottom row: five tiles that reflow so the focused one is wide.
|
||||
|
||||
use motion_bento_chaos::Action;
|
||||
use motion_bento_chaos::look::{color, grid, lch};
|
||||
use motion_bento_chaos::model::{CHIPS, DOCK, DOCK_KEYS, ENERGY_BARS, FILES, VISIT_MAX};
|
||||
use rune::{El, Transition, col, el, memo, row, spacer, text};
|
||||
use rune_kit::{Kit, RollingText};
|
||||
|
||||
use crate::State;
|
||||
use crate::style::{c, caption, font, nums, spring, tile};
|
||||
|
||||
const DAYS: [&str; ENERGY_BARS] = ["M", "T", "W", "T", "F", "S", "S"];
|
||||
|
||||
pub fn dock(s: &State, k: &Kit) -> El {
|
||||
let body_h = dock_h() - 2.0 * grid::TILE_PAD - 34.0;
|
||||
let mut dock = row().key("dock").w_full().h(dock_h()).gap(grid::GAP);
|
||||
for i in 0..DOCK.len() {
|
||||
let focused = s.m.focus == i;
|
||||
dock = dock.child(memo(DOCK_KEYS[i], (focused, version(s, i)), || {
|
||||
let (aside, body) = match i {
|
||||
0 => energy(s, k, body_h),
|
||||
1 => chips(s, k),
|
||||
2 => orb(s, k, body_h),
|
||||
3 => transfers(s, k),
|
||||
_ => visitors(s, k, body_h),
|
||||
};
|
||||
tile(DOCK_KEYS[i], DOCK[i], aside, body)
|
||||
.grow(if focused { grid::DOCK_FOCUS } else { 1.0 })
|
||||
.w(0.0)
|
||||
.h_full()
|
||||
.fill(c(if focused { color::TILE_FOCUS } else { color::TILE }))
|
||||
.border(1.0, c(if focused { color::ACCENT.alpha(0.45) } else { color::EDGE }))
|
||||
.clip_rounded(grid::RADIUS)
|
||||
.on_press(move |s: &mut State| s.act(Action::Focus(i as u8)))
|
||||
}));
|
||||
}
|
||||
dock
|
||||
}
|
||||
|
||||
/// What dock tile `i` shows of the model, as a memo version: f32s by their bits.
|
||||
fn version(s: &State, i: usize) -> Vec<u32> {
|
||||
let m = &s.m;
|
||||
match i {
|
||||
0 => m.energy.iter().map(|v| v.to_bits()).chain([m.kwh_tenths]).collect(),
|
||||
1 => m.chips.iter().map(|&c| c as u32).chain([m.chips_open as u32]).collect(),
|
||||
2 => [m.orb.size, m.orb.hue, m.orb.round, m.orb.turn].map(f32::to_bits).to_vec(),
|
||||
3 => m.transfers.map(f32::to_bits).to_vec(),
|
||||
_ => m.visits.iter().flat_map(|v| [v.id, v.count]).chain([m.visitors]).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dock_h() -> f32 {
|
||||
grid::HEIGHT - 2.0 * grid::PAD - grid::HEADER - grid::ROW1 - grid::ROW2 - 3.0 * grid::GAP
|
||||
}
|
||||
|
||||
fn energy(s: &State, k: &Kit, h: f32) -> (El, El) {
|
||||
let bars_h = h - 22.0;
|
||||
let mut bars = row().key("bars").w_full().h(bars_h).items_end().gap(6.0).on_press(|s: &mut State| s.act(Action::Energy));
|
||||
let mut days = row().w_full().gap(6.0);
|
||||
for (i, v) in s.m.energy.iter().enumerate() {
|
||||
let peak = s.m.energy.iter().cloned().fold(0.0, f32::max) == *v;
|
||||
bars = bars.child(
|
||||
el().grow(1.0)
|
||||
.w(0.0)
|
||||
.h(10.0 + v * (bars_h - 10.0))
|
||||
.radius(6.0)
|
||||
.gradient(c(if peak { lch(0.8, 0.13, 240.0) } else { lch(0.5, 0.1, 250.0) }), c(if peak { color::ACCENT } else { lch(0.36, 0.07, 255.0) }))
|
||||
.motion(spring(s.springs.travel)),
|
||||
);
|
||||
days = days.child(row().grow(1.0).w(0.0).center().child(caption(DAYS[i])));
|
||||
}
|
||||
let aside = RollingText::new("kwh", format!("{} kWh", s.m.energy_kwh())).value(s.m.kwh_tenths as f64).font(nums(12.0, 560.0)).color(c(color::TEXT_2)).build(k);
|
||||
(aside, col().w_full().gap(6.0).child(bars).child(days))
|
||||
}
|
||||
|
||||
fn chips(s: &State, _k: &Kit) -> (El, El) {
|
||||
let snap = spring(s.springs.snap);
|
||||
let mut wrap = row().w_full().flex_wrap().gap(6.0).motion(spring(s.springs.layout));
|
||||
for i in 0..s.m.chips_shown() {
|
||||
let on = s.m.chips[i];
|
||||
wrap = wrap.child(
|
||||
row()
|
||||
.key(format!("chip{i}"))
|
||||
.h(28.0)
|
||||
.px(12.0)
|
||||
.radius(14.0)
|
||||
.center()
|
||||
.fill(c(if on { color::ACCENT } else { color::WELL }))
|
||||
.border(1.0, c(if on { color::ACCENT.alpha(0.0) } else { color::EDGE }))
|
||||
.press_scale(0.94)
|
||||
.transition(Transition::scale(0.8))
|
||||
.on_press(move |s: &mut State| s.act(Action::Chip(i as u8)))
|
||||
.child(text(CHIPS[i]).font(font(13.0, 540.0)).color(c(if on { color::ON_ACCENT } else { color::TEXT_2 })).motion(snap))
|
||||
.motion(snap),
|
||||
);
|
||||
}
|
||||
let more = row()
|
||||
.key("more")
|
||||
.h(22.0)
|
||||
.px(8.0)
|
||||
.radius(11.0)
|
||||
.center()
|
||||
.hover(c(color::WELL))
|
||||
.on_press(|s: &mut State| s.act(Action::ChipsMore))
|
||||
.child(RollingText::new("more-label", if s.m.chips_open { "Less" } else { "More" }).font(font(12.0, 560.0)).color(c(color::ACCENT)).build(_k));
|
||||
(more, wrap)
|
||||
}
|
||||
|
||||
fn orb(s: &State, k: &Kit, h: f32) -> (El, El) {
|
||||
let o = s.m.orb;
|
||||
let side = 40.0 + o.size * (h - 50.0);
|
||||
let tint = lch(0.7, 0.16, o.hue);
|
||||
let shape = el()
|
||||
.key("orb")
|
||||
.size(side, side)
|
||||
.radius(o.round * side)
|
||||
.gradient(c(lch(0.84, 0.12, o.hue - 20.0)), c(lch(0.52, 0.19, o.hue + 25.0)))
|
||||
.shadow(10.0, 44.0, c(tint.alpha(0.55)))
|
||||
.rotate(o.turn.to_radians())
|
||||
.motion(spring(s.springs.morph))
|
||||
.on_press(|s: &mut State| s.act(Action::Orb))
|
||||
.child(el().size(side * 0.34, side * 0.34).absolute(side * 0.14, side * 0.14).radius(side * 0.17).fill(c(lch(1.0, 0.0, 0.0).alpha(0.28))));
|
||||
let aside = RollingText::new("hue", format!("{:.0}°", o.hue)).value(o.hue as f64).font(nums(12.0, 560.0)).color(c(color::TEXT_2)).build(k);
|
||||
(aside, row().w_full().h(h).center().child(shape))
|
||||
}
|
||||
|
||||
fn transfers(s: &State, k: &Kit) -> (El, El) {
|
||||
let travel = spring(s.springs.travel);
|
||||
let mut rows = col().w_full().gap(12.0);
|
||||
for (i, name) in FILES.iter().enumerate() {
|
||||
let p = s.m.transfers[i];
|
||||
let done = p >= 1.0;
|
||||
let label = if done { "Done".to_string() } else { format!("{:.0}%", p * 100.0) };
|
||||
rows = rows.child(
|
||||
col()
|
||||
.key(format!("row{i}"))
|
||||
.w_full()
|
||||
.gap(6.0)
|
||||
.on_press(move |s: &mut State| s.act(Action::Transfer(i as u8)))
|
||||
.child(
|
||||
row()
|
||||
.w_full()
|
||||
.center_y()
|
||||
.child(text(*name).font(font(13.0, 500.0)).color(c(color::TEXT)).truncate())
|
||||
.child(spacer())
|
||||
.child(RollingText::new(format!("pct{i}"), label).value(p as f64).font(nums(12.0, 560.0)).color(c(if done { color::GOOD } else { color::TEXT_2 })).trailing().build(k)),
|
||||
)
|
||||
.child(
|
||||
el().w_full().h(6.0).radius(3.0).fill(c(color::WELL)).child(
|
||||
el().w_frac(p.max(0.02)).h(6.0).radius(3.0).fill(c(if done { color::GOOD } else { color::ACCENT })).motion(travel),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
let active = s.m.transfers.iter().filter(|p| **p < 1.0).count();
|
||||
let aside = RollingText::new("active", format!("{active} active")).value(active as f64).font(font(12.0, 460.0)).color(c(color::TEXT_3)).build(k);
|
||||
(aside, rows)
|
||||
}
|
||||
|
||||
fn thousands(n: u32) -> String {
|
||||
let s = n.to_string();
|
||||
let mut out = String::new();
|
||||
for (i, ch) in s.chars().enumerate() {
|
||||
if i > 0 && (s.len() - i) % 3 == 0 {
|
||||
out.push(',');
|
||||
}
|
||||
out.push(ch);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn visitors(s: &State, k: &Kit, h: f32) -> (El, El) {
|
||||
let count = row()
|
||||
.key("count")
|
||||
.on_press(|s: &mut State| s.act(Action::Visitors))
|
||||
.child(RollingText::new("visitors", thousands(s.m.visitors)).value(s.m.visitors as f64).font(nums(40.0, 660.0)).color(c(color::TEXT)).build(k));
|
||||
let chart_h = h - 52.0 - 18.0 - 14.0;
|
||||
let newest = s.m.visits.last().map(|v| v.id);
|
||||
let mut chart = row().w_full().h(chart_h).items_end().gap(4.0).motion(spring(s.springs.layout));
|
||||
for v in &s.m.visits {
|
||||
let fresh = Some(v.id) == newest;
|
||||
chart = chart.child(
|
||||
el().key(format!("visit{}", v.id))
|
||||
.grow(1.0)
|
||||
.w(0.0)
|
||||
.h(4.0 + (chart_h - 4.0) * v.count as f32 / VISIT_MAX as f32)
|
||||
.radius(3.0)
|
||||
.fill(c(if fresh { color::GOOD } else { lch(0.4, 0.06, 160.0) }))
|
||||
.transition(Transition::scale_anchor(0.05, rune::Vec2::new(0.5, 1.0))),
|
||||
);
|
||||
}
|
||||
let body = col().gap(4.0).child(count).child(caption("Unique visitors today")).child(el().h(10.0)).child(chart);
|
||||
let live = row().gap(6.0).center_y().child(el().size(6.0, 6.0).radius(3.0).fill(c(color::GOOD))).child(caption("Live"));
|
||||
(live, body)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn thousands_groups_digits() {
|
||||
assert_eq!(super::thousands(1284), "1,284");
|
||||
assert_eq!(super::thousands(999), "999");
|
||||
assert_eq!(super::thousands(1_000_000), "1,000,000");
|
||||
}
|
||||
}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
//! Motion bento: a 1440×900 control center whose twelve tiles all move at once, driven by a
|
||||
//! seeded chaos schedule. The same schedule drives the GPUI build of the same window, so the two
|
||||
//! can be watched and measured side by side. See README.md.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod dock;
|
||||
mod stress;
|
||||
mod style;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod tiles_mid;
|
||||
mod tiles_top;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
use motion_bento_chaos::hud::{Readout, Replay};
|
||||
use motion_bento_chaos::look::{Springs, color, grid};
|
||||
use motion_bento_chaos::stress::Wall;
|
||||
use motion_bento_chaos::model::SCENES;
|
||||
use motion_bento_chaos::schedule::START;
|
||||
use motion_bento_chaos::{Action, Config, Meter, Model, Player, script_json};
|
||||
use rune::{AppSpec, Cx, El, FrameOutcome, Key, KeyEvent, Live, Tx, col, el, memo, row, spacer, text};
|
||||
use rune_kit::{Kit, RollingText};
|
||||
|
||||
use style::{c, caption, font, nums, spring};
|
||||
|
||||
static CONFIG: OnceLock<Config> = OnceLock::new();
|
||||
|
||||
thread_local! {
|
||||
static METER: RefCell<Option<Meter>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
pub fn config() -> &'static Config {
|
||||
CONFIG.get_or_init(Config::default)
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
pub m: Model,
|
||||
pub springs: Springs,
|
||||
/// The thermostat ring's drawn span, smoothed by its spring.
|
||||
pub ring: Live<[f32; 2]>,
|
||||
k: Kit,
|
||||
/// Plays the schedule from `poll`; `None` when a script's taps drive the window instead.
|
||||
player: Option<Player>,
|
||||
hud: bool,
|
||||
hud_lines: [String; 4],
|
||||
hud_at: f64,
|
||||
begun: bool,
|
||||
ended: bool,
|
||||
written: bool,
|
||||
/// Stress mode's wall, its show time, and the HUD's source and numbers.
|
||||
wall: Option<Wall>,
|
||||
t: f64,
|
||||
replay: Option<Replay>,
|
||||
readout: Option<Readout>,
|
||||
/// The live values the idiomatic wall binds; `None` with `--naive` or outside stress mode.
|
||||
live: Option<stress::Bindings>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn new() -> State {
|
||||
let cfg = config();
|
||||
let scripted = rune::tooling::headless_run().is_some_and(|r| r.script().is_some());
|
||||
let m = Model::new(cfg.seed);
|
||||
let mut k = Kit::neutral(true);
|
||||
k.c.bg_accent = c(color::ACCENT);
|
||||
State {
|
||||
ring: Live::new([0.0, m.temp_fraction()]),
|
||||
m,
|
||||
springs: Springs::variant(&cfg.variant),
|
||||
k,
|
||||
player: (!scripted && cfg.load.is_none()).then(|| Player::new(cfg)),
|
||||
hud: cfg.hud,
|
||||
hud_lines: Default::default(),
|
||||
hud_at: f64::NEG_INFINITY,
|
||||
begun: false,
|
||||
ended: false,
|
||||
written: false,
|
||||
wall: cfg.load.as_ref().map(|_| Wall::new(cfg.seed)),
|
||||
t: 0.0,
|
||||
replay: cfg.hud_from.as_ref().map(|p| Replay::load(p).unwrap_or_else(|e| panic!("--hud-from: {e}"))),
|
||||
readout: None,
|
||||
live: (cfg.load.is_some() && !cfg.naive).then(stress::Bindings::new),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn act(&mut self, action: Action) {
|
||||
self.m.apply(action);
|
||||
self.ring.set([0.0, self.m.temp_fraction()]);
|
||||
}
|
||||
|
||||
fn write_metrics(&mut self) {
|
||||
if self.written {
|
||||
return;
|
||||
}
|
||||
self.written = true;
|
||||
METER.with(|m| {
|
||||
let mut m = m.borrow_mut();
|
||||
let Some(m) = m.as_mut() else { return };
|
||||
m.end();
|
||||
if let Some(path) = &config().frames
|
||||
&& let Err(e) = std::fs::write(path, m.frames_csv())
|
||||
{
|
||||
eprintln!("motion-bento: writing {}: {e}", path.display());
|
||||
}
|
||||
if let Some(path) = &config().metrics
|
||||
&& let Err(e) = m.write(path)
|
||||
{
|
||||
eprintln!("motion-bento: writing {}: {e}", path.display());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(s: &mut State, t: f64, tx: &mut Tx) -> bool {
|
||||
let cfg = config();
|
||||
let mut changed = false;
|
||||
if let Some(p) = &mut s.player {
|
||||
let due: Vec<Action> = p.due(t).collect();
|
||||
if let Some(next) = p.next_at() {
|
||||
tx.wake_after(Duration::from_secs_f64((next - t).max(0.0)));
|
||||
}
|
||||
for a in due {
|
||||
s.act(a);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if let (Some(wall), Some(load)) = (&mut s.wall, &cfg.load) {
|
||||
let n = load.at(t);
|
||||
wall.update(t, n);
|
||||
s.t = t;
|
||||
METER.with(|m| m.borrow_mut().as_mut().map(|m| m.tag(t, n)));
|
||||
if s.hud {
|
||||
s.readout = match &s.replay {
|
||||
Some(r) => Some(Readout::replay(r, t)),
|
||||
None => METER.with(|m| m.borrow().as_ref().map(Readout::live)),
|
||||
};
|
||||
}
|
||||
tx.wake_after(Duration::ZERO);
|
||||
// Idiomatic: the bars, numbers and colours are live values; only a reshuffle or a new
|
||||
// level runs the view. Naive: every frame does.
|
||||
changed |= s.live.as_mut().is_none_or(|b| b.sync(wall, t, s.readout.as_ref()));
|
||||
}
|
||||
if !s.begun && t >= START {
|
||||
s.begun = true;
|
||||
METER.with(|m| m.borrow_mut().as_mut().map(Meter::begin));
|
||||
}
|
||||
if !s.ended && t >= cfg.duration {
|
||||
s.ended = true;
|
||||
METER.with(|m| m.borrow_mut().as_mut().map(Meter::end));
|
||||
}
|
||||
// Not `rune::is_headless()`: it reads the process's arguments, where `--variant` is ours.
|
||||
let headless = rune::tooling::headless_run().is_some();
|
||||
if !headless && !cfg.stay {
|
||||
if t >= cfg.duration + 1.0 {
|
||||
s.write_metrics();
|
||||
tx.quit();
|
||||
} else if s.ended || t >= cfg.duration {
|
||||
tx.wake_after(Duration::from_secs_f64((cfg.duration + 1.0 - t).max(0.0)));
|
||||
}
|
||||
}
|
||||
if headless && t >= cfg.duration + 1.0 {
|
||||
s.write_metrics();
|
||||
}
|
||||
if s.hud && s.wall.is_none() && !headless && t - s.hud_at >= 0.25 {
|
||||
s.hud_at = t;
|
||||
if let Some(lines) = METER.with(|m| m.borrow().as_ref().map(Meter::hud)) {
|
||||
changed |= lines != s.hud_lines;
|
||||
s.hud_lines = lines;
|
||||
}
|
||||
tx.wake_after(Duration::from_millis(250));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
fn on_key(s: &mut State, e: &KeyEvent, _tx: &mut Tx) -> bool {
|
||||
match &e.key {
|
||||
Key::Text(t) if t.eq_ignore_ascii_case("h") => {
|
||||
s.hud = !s.hud;
|
||||
s.readout = None;
|
||||
s.hud_at = f64::NEG_INFINITY;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn on_close(s: &mut State, _tx: &mut Tx) {
|
||||
s.write_metrics();
|
||||
}
|
||||
|
||||
fn header(s: &State) -> El {
|
||||
let k = &s.k;
|
||||
let mood = color::SCENE[s.m.scene];
|
||||
let scene = row()
|
||||
.h(34.0)
|
||||
.px(14.0)
|
||||
.gap(8.0)
|
||||
.radius(17.0)
|
||||
.center_y()
|
||||
.fill(c(color::TILE))
|
||||
.border(1.0, c(color::EDGE))
|
||||
.motion(spring(s.springs.layout))
|
||||
.child(el().size(10.0, 10.0).radius(5.0).fill(c(mood)).motion(spring(s.springs.morph)))
|
||||
.child(RollingText::new("head-scene", SCENES[s.m.scene]).value(s.m.scene as f64).font(font(13.0, 560.0)).color(c(color::TEXT)).build(k));
|
||||
let events = row()
|
||||
.gap(6.0)
|
||||
.center_y()
|
||||
.child(RollingText::new("events", s.m.events.to_string()).value(s.m.events as f64).font(nums(13.0, 600.0)).color(c(color::TEXT)).build(k))
|
||||
.child(caption("events"));
|
||||
row()
|
||||
.w_full()
|
||||
.h(grid::HEADER)
|
||||
.center_y()
|
||||
.gap(16.0)
|
||||
.child(
|
||||
col()
|
||||
.gap(2.0)
|
||||
.child(text("Studio").font(font(24.0, 680.0)).color(c(color::TEXT)))
|
||||
.child(caption("Control center · Friday evening")),
|
||||
)
|
||||
.child(spacer())
|
||||
.child(events)
|
||||
.child(scene)
|
||||
}
|
||||
|
||||
fn hud(s: &State) -> El {
|
||||
let mut lines = col()
|
||||
.key("hud")
|
||||
.absolute(grid::WIDTH - grid::PAD - 300.0, 12.0)
|
||||
.w(300.0)
|
||||
.padding(12.0)
|
||||
.gap(3.0)
|
||||
.radius(12.0)
|
||||
.fill(c(color::BG.alpha(0.92)))
|
||||
.border(1.0, c(color::ACCENT.alpha(0.4)))
|
||||
.raise();
|
||||
for l in &s.hud_lines {
|
||||
lines = lines.child(text(l.clone()).font(nums(11.0, 500.0).mono()).color(c(color::TEXT_2)));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn view(s: &State, _: &mut Cx<State>) -> El {
|
||||
if let Some(wall) = &s.wall {
|
||||
return stress::view(s, wall);
|
||||
}
|
||||
// Each tile builds again only when the part of the model it shows changes; the springs and
|
||||
// the kit never change.
|
||||
let (k, m) = (&s.k, &s.m);
|
||||
let mut root = col()
|
||||
.w(grid::WIDTH)
|
||||
.h(grid::HEIGHT)
|
||||
.px(grid::PAD)
|
||||
.pb(grid::PAD)
|
||||
.pt(grid::PAD - 8.0)
|
||||
.gap(grid::GAP)
|
||||
.fill(c(color::BG))
|
||||
.motion(spring(s.springs.layout))
|
||||
.child(memo("header", (m.scene, m.events), || header(s)))
|
||||
.child(
|
||||
row()
|
||||
.h(grid::ROW1)
|
||||
.gap(grid::GAP)
|
||||
.child(memo("scene", (m.scene, m.lights, m.chips, m.temp.to_bits()), || tiles_top::scenes(s, k)))
|
||||
.child(memo("thermo", m.temp.to_bits(), || tiles_top::thermostat(s, k)))
|
||||
.child(memo("lights", m.lights, || tiles_top::lights(s, k))),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.h(grid::ROW2)
|
||||
.gap(grid::GAP)
|
||||
.child(memo("mixer", m.faders.map(f32::to_bits), || tiles_mid::mixer(s, k)))
|
||||
.child(memo("xy", m.puck.map(f32::to_bits), || tiles_mid::xy(s, k)))
|
||||
.child(memo("queue", m.queue.iter().map(|c| (c.id, c.track)).collect::<Vec<_>>(), || tiles_mid::queue(s, k)))
|
||||
.child(memo("feed", m.feed.iter().map(|f| (f.id, f.kind, f.minute)).collect::<Vec<_>>(), || tiles_mid::feed(s, k))),
|
||||
)
|
||||
.child(dock::dock(s, k));
|
||||
if s.hud {
|
||||
root = root.child(hud(s));
|
||||
}
|
||||
root
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let (cfg, rest) = Config::parse(std::env::args()).unwrap_or_else(|e| {
|
||||
eprintln!("motion-bento: {e}");
|
||||
std::process::exit(2);
|
||||
});
|
||||
if let Some(path) = &cfg.emit_script {
|
||||
std::fs::write(path, script_json(&cfg)).unwrap_or_else(|e| panic!("writing {}: {e}", path.display()));
|
||||
return;
|
||||
}
|
||||
CONFIG.set(cfg).ok();
|
||||
METER.with(|m| {
|
||||
let mut meter = Meter::new("rune", 120.0);
|
||||
meter.note("work", "update_ms + encode_ms: events, poll, view, layout, paint, upload and encode, to submit");
|
||||
meter.note("build", "update_ms: events, poll, view, layout and paint");
|
||||
meter.note("variant", &config().variant);
|
||||
meter.note("seed", &config().seed.to_string());
|
||||
meter.note("mode", if config().naive { "naive" } else { "idiomatic" });
|
||||
*m.borrow_mut() = Some(meter);
|
||||
});
|
||||
let spec = AppSpec {
|
||||
poll: Some(poll),
|
||||
on_key: Some(on_key),
|
||||
min_size: Some((grid::WIDTH, grid::HEIGHT)),
|
||||
..AppSpec::new("Motion bento", (grid::WIDTH, grid::HEIGHT), State::new, view)
|
||||
};
|
||||
rune::App::new(spec)
|
||||
.args(rest.into_iter().skip(1))
|
||||
.on_close(on_close)
|
||||
.on_frame_encoded(|f| {
|
||||
let (FrameOutcome::Drawn, Some(start)) = (f.outcome(), f.started()) else { return };
|
||||
let build = f.update_ms().unwrap_or(0.0);
|
||||
let work = build + f.encode_ms().unwrap_or(0.0);
|
||||
METER.with(|m| {
|
||||
if let Some(m) = m.borrow_mut().as_mut() {
|
||||
if let Some(hz) = f.refresh_hz() {
|
||||
m.set_refresh(hz);
|
||||
}
|
||||
m.frame_with_build(start, work, build);
|
||||
}
|
||||
});
|
||||
})
|
||||
.run();
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//! The stress HUD built once, its numbers and graph bars live values.
|
||||
|
||||
use motion_bento_chaos::hud::{BUDGET_60, BUDGET_120, GRAPH, GRAPH_MAX, Readout};
|
||||
use motion_bento_chaos::look::{Lch, color, grid};
|
||||
use motion_bento_chaos::stress::HEADER;
|
||||
use rune::{Color, El, Live, LiveText, col, el, row, text};
|
||||
|
||||
use super::{GRAPH_H, GRAPH_W, HUD_W, OVER, grade_color};
|
||||
use crate::style::{c, caption, nums};
|
||||
|
||||
pub struct Hud {
|
||||
source: &'static str,
|
||||
big: LiveText,
|
||||
big_color: Live<Color>,
|
||||
detail: LiveText,
|
||||
rate: LiveText,
|
||||
bars: [(Live<[f32; 4]>, Live<Color>); GRAPH],
|
||||
}
|
||||
|
||||
impl Hud {
|
||||
pub fn new() -> Hud {
|
||||
Hud {
|
||||
source: "",
|
||||
big: LiveText::new(""),
|
||||
big_color: Live::new(c(color::GOOD)),
|
||||
detail: LiveText::new(""),
|
||||
rate: LiveText::new(""),
|
||||
bars: std::array::from_fn(|_| (Live::new([0.0; 4]), Live::new(c(color::GOOD)))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set(&mut self, r: &Readout) {
|
||||
self.source = r.source;
|
||||
self.big.set(r.big());
|
||||
self.big_color.set(c(grade_color(r.ms)));
|
||||
self.detail.set(r.detail());
|
||||
self.rate.set(r.rate());
|
||||
let bw = GRAPH_W / GRAPH as f32;
|
||||
for (i, (rect, fill)) in self.bars.iter().enumerate() {
|
||||
let ms = r.graph.get(i).copied().unwrap_or(0.0);
|
||||
let h = (ms / GRAPH_MAX).min(1.0) * GRAPH_H;
|
||||
rect.set([i as f32 * bw, GRAPH_H - h, bw, h]);
|
||||
fill.set(c(grade_color(ms)));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view(&self) -> El {
|
||||
let mut graph = el().size(GRAPH_W, GRAPH_H).absolute(0.0, 0.0);
|
||||
for (rect, fill) in &self.bars {
|
||||
graph = graph.child(el().absolute(0.0, 0.0).size(0.0, 0.0).fill(c(color::GOOD)).live_fill(fill).live_rect(rect));
|
||||
}
|
||||
let line = |ms: f32, col: Lch| el().size(GRAPH_W, 1.0).absolute(0.0, GRAPH_H - ms / GRAPH_MAX * GRAPH_H).fill(c(col));
|
||||
let label = |ms: f32, s: &str| text(s.to_owned()).font(nums(10.0, 560.0)).color(c(color::TEXT_2)).absolute(GRAPH_W + 6.0, GRAPH_H - ms / GRAPH_MAX * GRAPH_H - 7.0);
|
||||
let graph = el()
|
||||
.size(GRAPH_W + 40.0, GRAPH_H)
|
||||
.child(el().size(GRAPH_W, GRAPH_H).absolute(0.0, 0.0).radius(4.0).fill(c(color::WELL)))
|
||||
.child(graph)
|
||||
.child(line(BUDGET_120, color::ACCENT))
|
||||
.child(line(BUDGET_60, OVER))
|
||||
.child(label(BUDGET_120, "120 Hz"))
|
||||
.child(label(BUDGET_60, "60 Hz"));
|
||||
let small = |placeholder: &str, live: &LiveText| text(placeholder.to_owned()).font(nums(11.0, 500.0)).color(c(color::TEXT_2)).live_text(live);
|
||||
row()
|
||||
.key("hud")
|
||||
.absolute(grid::WIDTH - grid::PAD - HUD_W, grid::PAD - 8.0)
|
||||
.size(HUD_W, HEADER)
|
||||
.padding(12.0)
|
||||
.gap(14.0)
|
||||
.radius(14.0)
|
||||
.fill(c(color::TILE))
|
||||
.border(1.0, c(color::ACCENT.alpha(0.4)))
|
||||
.raise()
|
||||
.child(
|
||||
col()
|
||||
.w(HUD_W - GRAPH_W - 40.0 - 14.0 - 24.0)
|
||||
.gap(1.0)
|
||||
.child(caption(format!("Rune · {}", self.source)))
|
||||
.child(text("00.0 ms").font(nums(36.0, 700.0)).color(c(color::GOOD)).live_text_color(&self.big_color).live_text(&self.big))
|
||||
.child(small("build + layout + paint · p95 00.0", &self.detail))
|
||||
.child(small("≈ 000 fps at 120 Hz · 000 missed / s", &self.rate)),
|
||||
)
|
||||
.child(graph)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
//! The wall as Rune means it to be built. A control's card is built once for each size it takes
|
||||
//! (`memo`), and placed again only when the wall reshuffles. Everything that moves inside it, its
|
||||
//! reading, bars, switch, progress and colours, is a live value `poll` sets, so on most frames
|
||||
//! the view doesn't run and nothing commits.
|
||||
|
||||
use motion_bento_chaos::hud::Readout;
|
||||
use motion_bento_chaos::look::{Springs, color, grid};
|
||||
use motion_bento_chaos::stress::{self, BARS, Cell, HEADER, HUES, Metrics, Wall, lh};
|
||||
use rune::{Align, Color, El, Live, LiveText, Transition, col, el, memo, row, spacer, text};
|
||||
|
||||
use super::hud::Hud;
|
||||
use super::{HUD_W, KNOB, SWITCH_OFF};
|
||||
use crate::State;
|
||||
use crate::style::{c, caption, font, nums, spring};
|
||||
|
||||
/// One hue's colours, worked out once.
|
||||
struct Palette {
|
||||
tint: Color,
|
||||
glow: Color,
|
||||
hi: Color,
|
||||
lo: Color,
|
||||
hot_fill: Color,
|
||||
hot_edge: Color,
|
||||
}
|
||||
|
||||
/// What moves inside one control.
|
||||
struct Control {
|
||||
reading: LiveText,
|
||||
percent: LiveText,
|
||||
status: LiveText,
|
||||
tint: Live<Color>,
|
||||
glow: Live<Color>,
|
||||
hi: Live<Color>,
|
||||
lo: Live<Color>,
|
||||
card: Live<Color>,
|
||||
edge: Live<Color>,
|
||||
switch: Live<Color>,
|
||||
knob: Live<[f32; 2]>,
|
||||
bars: [Live<[f32; 4]>; BARS],
|
||||
progress: Live<[f32; 4]>,
|
||||
shown: (u32, &'static str),
|
||||
}
|
||||
|
||||
impl Control {
|
||||
fn new() -> Control {
|
||||
let unset = || Live::new(Color::TRANSPARENT);
|
||||
Control {
|
||||
reading: LiveText::new(""),
|
||||
percent: LiveText::new(""),
|
||||
status: LiveText::new(""),
|
||||
tint: unset(),
|
||||
glow: unset(),
|
||||
hi: unset(),
|
||||
lo: unset(),
|
||||
card: Live::new(c(color::TILE)),
|
||||
edge: Live::new(c(color::EDGE)),
|
||||
switch: Live::new(c(SWITCH_OFF)),
|
||||
knob: Live::new([0.0; 2]),
|
||||
bars: std::array::from_fn(|_| Live::new([0.0; 4])),
|
||||
progress: Live::new([0.0; 4]),
|
||||
shown: (u32::MAX, ""),
|
||||
}
|
||||
}
|
||||
|
||||
fn set(&mut self, cell: &Cell, m: &Metrics, p: &Palette) {
|
||||
let [_, _, w, _] = cell.rect;
|
||||
self.reading.set(cell.reading());
|
||||
let pct = (cell.progress * 100.0).round() as u32;
|
||||
if self.shown.0 != pct {
|
||||
self.percent.set(cell.percent());
|
||||
}
|
||||
if self.shown.1 != cell.status {
|
||||
self.status.set(cell.status);
|
||||
}
|
||||
self.shown = (pct, cell.status);
|
||||
self.tint.set(p.tint);
|
||||
self.glow.set(p.glow);
|
||||
self.hi.set(p.hi);
|
||||
self.lo.set(p.lo);
|
||||
let (card, edge) = if cell.hot { (p.hot_fill, p.hot_edge) } else { (c(color::TILE), c(color::EDGE)) };
|
||||
self.card.set(card);
|
||||
self.edge.set(edge);
|
||||
self.switch.set(if cell.on { p.tint } else { c(SWITCH_OFF) });
|
||||
let inset = (m.switch_h - m.knob) / 2.0;
|
||||
self.knob.set([if cell.on { m.switch_w - 2.0 * inset - m.knob } else { 0.0 }, 0.0]);
|
||||
let inner = w - 2.0 * m.pad;
|
||||
let bar_w = (inner - (BARS - 1) as f32 * m.bar_gap) / BARS as f32;
|
||||
for (j, (live, &b)) in self.bars.iter().zip(&cell.bars).enumerate() {
|
||||
let h = b * m.bars_h;
|
||||
live.set([j as f32 * (bar_w + m.bar_gap), m.bars_h - h, bar_w, h]);
|
||||
}
|
||||
let track = inner - 2.0 * m.gap - m.switch_w;
|
||||
self.progress.set([0.0, 0.0, cell.progress * track, m.track_h]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The live values the wall's view binds, and what it last built from.
|
||||
pub struct Bindings {
|
||||
palette: Vec<Palette>,
|
||||
controls: Vec<Control>,
|
||||
t: LiveText,
|
||||
pub(super) hud: Hud,
|
||||
/// The controls' rects the view last placed: a change needs a commit.
|
||||
built: Vec<[f32; 4]>,
|
||||
}
|
||||
|
||||
impl Bindings {
|
||||
pub fn new() -> Bindings {
|
||||
let palette = HUES
|
||||
.iter()
|
||||
.map(|&h| Palette {
|
||||
tint: c(stress::tint(h)),
|
||||
glow: c(stress::tint(h).alpha(0.8)),
|
||||
hi: c(stress::tint_hi(h)),
|
||||
lo: c(stress::tint_lo(h)),
|
||||
hot_fill: c(stress::hot_fill(h)),
|
||||
hot_edge: c(stress::hot_edge(h)),
|
||||
})
|
||||
.collect();
|
||||
Bindings { palette, controls: Vec::new(), t: LiveText::new(""), hud: Hud::new(), built: Vec::new() }
|
||||
}
|
||||
|
||||
/// Sets every live value to the wall at show time `t`. True when the wall's shape changed
|
||||
/// (a control came or went, or moved or resized), which only a commit can show.
|
||||
pub fn sync(&mut self, wall: &Wall, t: f64, readout: Option<&Readout>) -> bool {
|
||||
let cells = wall.cells();
|
||||
// Controls are never dropped, so a card a memo kept still binds its own values.
|
||||
while self.controls.len() < cells.len() {
|
||||
self.controls.push(Control::new());
|
||||
}
|
||||
for (cell, control) in cells.iter().zip(&mut self.controls) {
|
||||
let hue = HUES.iter().position(|&h| h == cell.hue).unwrap_or(0);
|
||||
control.set(cell, &wall.metrics, &self.palette[hue]);
|
||||
}
|
||||
self.t.set(format!("{t:.2} s"));
|
||||
if let Some(r) = readout {
|
||||
self.hud.set(r);
|
||||
}
|
||||
let moved = self.built.len() != cells.len() || cells.iter().zip(&self.built).any(|(c, r)| c.rect != *r);
|
||||
if moved {
|
||||
self.built.clear();
|
||||
self.built.extend(cells.iter().map(|c| c.rect));
|
||||
}
|
||||
moved
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view(s: &State, wall: &Wall, b: &Bindings) -> El {
|
||||
let mut root = el().w(grid::WIDTH).h(grid::HEIGHT).fill(c(color::BG)).child(header(s, wall, b));
|
||||
for (cell, control) in wall.cells().iter().zip(&b.controls) {
|
||||
root = root.child(card(&s.springs, cell, &wall.metrics, control));
|
||||
}
|
||||
if s.readout.is_some() {
|
||||
root = root.child(b.hud.view());
|
||||
}
|
||||
root
|
||||
}
|
||||
|
||||
fn header(s: &State, wall: &Wall, b: &Bindings) -> El {
|
||||
let cfg = crate::config();
|
||||
let load = cfg.load.as_ref();
|
||||
let steps = load.map_or(1, |l| l.levels().len());
|
||||
let n = wall.cells().len();
|
||||
// The view runs whenever the count changes, so the step it reads is current.
|
||||
let step = load.map_or(0, |l| l.step_at(s.t));
|
||||
col()
|
||||
.absolute(grid::PAD, grid::PAD - 8.0)
|
||||
.size(grid::WIDTH - 2.0 * grid::PAD - HUD_W - grid::GAP, HEADER)
|
||||
.gap(4.0)
|
||||
.child(
|
||||
row()
|
||||
.gap(10.0)
|
||||
.center_y()
|
||||
.child(text("Rune").font(font(24.0, 680.0)).color(c(color::ACCENT)))
|
||||
.child(text("stress wall").font(font(24.0, 680.0)).color(c(color::TEXT))),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.gap(4.0)
|
||||
.child(caption(format!("Seed {} · every control retargets, ticks and reflows at once · t", cfg.seed)))
|
||||
.child(text("00.00 s").font(nums(12.0, 460.0)).color(c(color::TEXT_3)).live_text(&b.t)),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.gap(10.0)
|
||||
.items_end()
|
||||
.child(text(format!("{n}")).font(nums(40.0, 700.0)).color(c(color::TEXT)))
|
||||
.child(text("live controls").font(font(16.0, 560.0)).color(c(color::TEXT_2)))
|
||||
.child(caption(format!("step {} of {steps} · {}×{} grid", step + 1, wall.cols, wall.rows))),
|
||||
)
|
||||
}
|
||||
|
||||
/// The card is placed on each commit; what's inside builds once per size.
|
||||
fn card(springs: &Springs, cell: &Cell, m: &Metrics, b: &Control) -> El {
|
||||
let [x, y, w, h] = cell.rect;
|
||||
let layout = spring(springs.layout);
|
||||
let id = cell.id;
|
||||
col()
|
||||
.key(format!("z{id}"))
|
||||
.absolute(x, y)
|
||||
.size(w, h)
|
||||
.padding(m.pad)
|
||||
.radius(m.radius)
|
||||
.fill(c(color::TILE))
|
||||
.live_fill(b.card.smooth(layout))
|
||||
.border(1.0, c(color::EDGE))
|
||||
.live_border(b.edge.smooth(layout))
|
||||
.shadow(m.shadow_y, m.shadow_blur, Color::BLACK.alpha(0.35))
|
||||
.clip_rounded(m.radius)
|
||||
.motion(layout)
|
||||
.transition(Transition::scale(0.85).combined(Transition::opacity()))
|
||||
.child(memo(format!("c{id}"), (w.to_bits(), h.to_bits()), || inside(springs, cell, m, b)))
|
||||
}
|
||||
|
||||
fn inside(springs: &Springs, cell: &Cell, m: &Metrics, b: &Control) -> El {
|
||||
let [_, _, w, _] = cell.rect;
|
||||
let (travel, snap) = (spring(springs.travel), spring(springs.snap));
|
||||
// Authored colours only until the first latch: the live values own them.
|
||||
let ink = c(color::ACCENT);
|
||||
let inner = w - 2.0 * m.pad;
|
||||
let bar_w = (inner - (BARS - 1) as f32 * m.bar_gap) / BARS as f32;
|
||||
let mut bars = el().w_full().h(m.bars_h);
|
||||
for live in &b.bars {
|
||||
bars = bars.child(
|
||||
el().absolute(0.0, 0.0)
|
||||
.size(bar_w, m.bars_h)
|
||||
.radius(2.0 * m.u)
|
||||
.gradient(ink, ink)
|
||||
.live_gradient(b.hi.smooth(travel), b.lo.smooth(travel))
|
||||
.live_rect(live.smooth(travel)),
|
||||
);
|
||||
}
|
||||
let inset = (m.switch_h - m.knob) / 2.0;
|
||||
let switch = el()
|
||||
.size(m.switch_w, m.switch_h)
|
||||
.radius(m.switch_h / 2.0)
|
||||
.fill(c(SWITCH_OFF))
|
||||
.live_fill(b.switch.smooth(snap))
|
||||
.child(el().size(m.knob, m.knob).absolute(inset, inset).radius(m.knob / 2.0).fill(c(KNOB)).live_offset(b.knob.smooth(snap)));
|
||||
let track = el()
|
||||
.grow(1.0)
|
||||
.h(m.track_h)
|
||||
.radius(m.track_h / 2.0)
|
||||
.fill(c(color::WELL))
|
||||
.child(el().absolute(0.0, 0.0).size(0.0, m.track_h).radius(m.track_h / 2.0).fill(ink).live_fill(&b.tint).live_rect(&b.progress));
|
||||
col()
|
||||
.w_full()
|
||||
.h_full()
|
||||
.gap(m.gap)
|
||||
.child(
|
||||
row()
|
||||
.h(lh(m.name))
|
||||
.gap(m.gap)
|
||||
.center_y()
|
||||
.child(
|
||||
el().size(m.dot, m.dot)
|
||||
.radius(m.dot / 2.0)
|
||||
.fill(ink)
|
||||
.live_fill(&b.tint)
|
||||
.shadow(0.0, 2.0 * m.dot, ink)
|
||||
.live_shadow(&b.glow),
|
||||
)
|
||||
.child(text(cell.name()).font(font(m.name, 520.0)).color(c(color::TEXT_2)))
|
||||
.child(spacer())
|
||||
.child(text("Boost").font(font(m.small, 600.0)).color(ink).align(Align::End).live_text_color(&b.tint).live_text(&b.status)),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.h(lh(m.reading))
|
||||
.center_y()
|
||||
.child(text("0000.00").font(nums(m.reading, 640.0)).color(c(color::TEXT)).live_text(&b.reading))
|
||||
.child(spacer())
|
||||
.child(text("100%").font(nums(m.small, 500.0)).color(c(color::TEXT_3)).align(Align::End).live_text(&b.percent)),
|
||||
)
|
||||
.child(bars)
|
||||
.child(row().w_full().h(m.foot_h).gap(2.0 * m.gap).center_y().child(track).child(switch))
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//! Stress mode's view: the wall of controls under a header with the load and, with `--hud`, the
|
||||
//! frame-time HUD. What the wall shows comes from `motion_bento_chaos::stress`; this only draws it.
|
||||
//!
|
||||
//! By default the wall is built the way Rune is meant to be used ([`live`]): memoised cards and
|
||||
//! live values, so a frame where only numbers, bars and colours move runs no view and commits
|
||||
//! nothing. `--naive` ([`naive`]) builds everything every frame.
|
||||
|
||||
mod hud;
|
||||
mod live;
|
||||
mod naive;
|
||||
|
||||
use motion_bento_chaos::hud::grade;
|
||||
use motion_bento_chaos::look::{Lch, color, lch};
|
||||
use motion_bento_chaos::stress::Wall;
|
||||
use rune::El;
|
||||
|
||||
pub use live::Bindings;
|
||||
|
||||
use crate::State;
|
||||
|
||||
const SWITCH_OFF: Lch = lch(0.44, 0.012, 258.0);
|
||||
const KNOB: Lch = lch(0.98, 0.0, 0.0);
|
||||
const OVER: Lch = lch(0.66, 0.2, 25.0);
|
||||
const HUD_W: f32 = 660.0;
|
||||
const GRAPH_W: f32 = 300.0;
|
||||
const GRAPH_H: f32 = 92.0;
|
||||
|
||||
pub fn grade_color(ms: f32) -> Lch {
|
||||
[color::GOOD, color::WARM, OVER][grade(ms)]
|
||||
}
|
||||
|
||||
pub fn view(s: &State, wall: &Wall) -> El {
|
||||
match &s.live {
|
||||
Some(b) => live::view(s, wall, b),
|
||||
None => naive::view(s, wall),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! `--naive`: the whole wall built again every frame, as a first port draws it. Every number,
|
||||
//! bar and colour that moves reruns the view and commits the whole tree.
|
||||
|
||||
use motion_bento_chaos::hud::{BUDGET_60, BUDGET_120, GRAPH, GRAPH_MAX, Readout};
|
||||
use motion_bento_chaos::look::{Lch, color, grid, lch};
|
||||
use motion_bento_chaos::stress::{self, Cell, HEADER, Metrics, Wall, lh};
|
||||
use rune::{El, Transition, col, el, row, spacer, text};
|
||||
|
||||
use super::{GRAPH_H, GRAPH_W, HUD_W, KNOB, OVER, SWITCH_OFF, grade_color};
|
||||
use crate::State;
|
||||
use crate::style::{c, caption, font, nums, spring};
|
||||
|
||||
pub fn view(s: &State, wall: &Wall) -> El {
|
||||
let mut root = el().w(grid::WIDTH).h(grid::HEIGHT).fill(c(color::BG)).child(header(s, wall));
|
||||
for cell in wall.cells() {
|
||||
root = root.child(control(s, cell, &wall.metrics));
|
||||
}
|
||||
if let Some(r) = &s.readout {
|
||||
root = root.child(hud(r));
|
||||
}
|
||||
root
|
||||
}
|
||||
|
||||
fn header(s: &State, wall: &Wall) -> El {
|
||||
let load = crate::config().load.as_ref();
|
||||
let steps = load.map_or(1, |l| l.levels().len());
|
||||
let step = load.map_or(0, |l| l.step_at(s.t));
|
||||
let n = wall.cells().len();
|
||||
col()
|
||||
.absolute(grid::PAD, grid::PAD - 8.0)
|
||||
.size(grid::WIDTH - 2.0 * grid::PAD - HUD_W - grid::GAP, HEADER)
|
||||
.gap(4.0)
|
||||
.child(
|
||||
row()
|
||||
.gap(10.0)
|
||||
.center_y()
|
||||
.child(text("Rune").font(font(24.0, 680.0)).color(c(color::ACCENT)))
|
||||
.child(text("stress wall").font(font(24.0, 680.0)).color(c(color::TEXT))),
|
||||
)
|
||||
.child(caption(format!("Seed {} · every control retargets, ticks and reflows at once · t {:.2} s", crate::config().seed, s.t)))
|
||||
.child(
|
||||
row()
|
||||
.gap(10.0)
|
||||
.items_end()
|
||||
.child(text(format!("{n}")).font(nums(40.0, 700.0)).color(c(color::TEXT)))
|
||||
.child(text("live controls").font(font(16.0, 560.0)).color(c(color::TEXT_2)))
|
||||
.child(caption(format!("step {} of {steps} · {}×{} grid", step + 1, wall.cols, wall.rows))),
|
||||
)
|
||||
}
|
||||
|
||||
fn control(s: &State, cell: &Cell, m: &Metrics) -> El {
|
||||
let [x, y, w, h] = cell.rect;
|
||||
let tint = stress::tint(cell.hue);
|
||||
let (fill, edge) = if cell.hot { (stress::hot_fill(cell.hue), stress::hot_edge(cell.hue)) } else { (color::TILE, color::EDGE) };
|
||||
let travel = spring(s.springs.travel);
|
||||
let snap = spring(s.springs.snap);
|
||||
let mut bars = row().w_full().h(m.bars_h).gap(m.bar_gap).items_end();
|
||||
for &b in &cell.bars {
|
||||
bars = bars.child(el().grow(1.0).h(b * m.bars_h).radius(2.0 * m.u).gradient(c(stress::tint_hi(cell.hue)), c(stress::tint_lo(cell.hue))).motion(travel));
|
||||
}
|
||||
let inset = (m.switch_h - m.knob) / 2.0;
|
||||
let switch = el()
|
||||
.size(m.switch_w, m.switch_h)
|
||||
.radius(m.switch_h / 2.0)
|
||||
.fill(c(if cell.on { tint } else { SWITCH_OFF }))
|
||||
.motion(snap)
|
||||
.child(el().size(m.knob, m.knob).absolute(if cell.on { m.switch_w - inset - m.knob } else { inset }, inset).radius(m.knob / 2.0).fill(c(KNOB)).motion(snap));
|
||||
let track = el()
|
||||
.grow(1.0)
|
||||
.h(m.track_h)
|
||||
.radius(m.track_h / 2.0)
|
||||
.fill(c(color::WELL))
|
||||
.child(el().w_frac(cell.progress).h(m.track_h).radius(m.track_h / 2.0).fill(c(tint)));
|
||||
col()
|
||||
.key(format!("z{}", cell.id))
|
||||
.absolute(x, y)
|
||||
.size(w, h)
|
||||
.padding(m.pad)
|
||||
.gap(m.gap)
|
||||
.radius(m.radius)
|
||||
.fill(c(fill))
|
||||
.border(1.0, c(edge))
|
||||
.shadow(m.shadow_y, m.shadow_blur, c(lch(0.0, 0.0, 0.0).alpha(0.35)))
|
||||
.clip_rounded(m.radius)
|
||||
.motion(spring(s.springs.layout))
|
||||
.transition(Transition::scale(0.85).combined(Transition::opacity()))
|
||||
.child(
|
||||
row()
|
||||
.h(lh(m.name))
|
||||
.gap(m.gap)
|
||||
.center_y()
|
||||
.child(el().size(m.dot, m.dot).radius(m.dot / 2.0).fill(c(tint)).shadow(0.0, 2.0 * m.dot, c(tint.alpha(0.8))))
|
||||
.child(text(cell.name()).font(font(m.name, 520.0)).color(c(color::TEXT_2)))
|
||||
.child(spacer())
|
||||
.child(text(cell.status).font(font(m.small, 600.0)).color(c(tint))),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.h(lh(m.reading))
|
||||
.center_y()
|
||||
.child(text(cell.reading()).font(nums(m.reading, 640.0)).color(c(color::TEXT)))
|
||||
.child(spacer())
|
||||
.child(text(cell.percent()).font(nums(m.small, 500.0)).color(c(color::TEXT_3))),
|
||||
)
|
||||
.child(bars)
|
||||
.child(row().w_full().h(m.foot_h).gap(2.0 * m.gap).center_y().child(track).child(switch))
|
||||
}
|
||||
|
||||
fn hud(r: &Readout) -> El {
|
||||
let bw = GRAPH_W / GRAPH as f32;
|
||||
let mut graph = row().size(GRAPH_W, GRAPH_H).items_end();
|
||||
for &ms in &r.graph {
|
||||
graph = graph.child(el().w(bw).h((ms / GRAPH_MAX).min(1.0) * GRAPH_H).fill(c(grade_color(ms))));
|
||||
}
|
||||
let line = |ms: f32, col: Lch| el().size(GRAPH_W, 1.0).absolute(0.0, GRAPH_H - ms / GRAPH_MAX * GRAPH_H).fill(c(col));
|
||||
let label = |ms: f32, s: &str| text(s.to_owned()).font(nums(10.0, 560.0)).color(c(color::TEXT_2)).absolute(GRAPH_W + 6.0, GRAPH_H - ms / GRAPH_MAX * GRAPH_H - 7.0);
|
||||
let graph = el()
|
||||
.size(GRAPH_W + 40.0, GRAPH_H)
|
||||
.child(el().size(GRAPH_W, GRAPH_H).absolute(0.0, 0.0).radius(4.0).fill(c(color::WELL)))
|
||||
.child(graph.absolute(0.0, 0.0))
|
||||
.child(line(BUDGET_120, color::ACCENT))
|
||||
.child(line(BUDGET_60, OVER))
|
||||
.child(label(BUDGET_120, "120 Hz"))
|
||||
.child(label(BUDGET_60, "60 Hz"));
|
||||
row()
|
||||
.key("hud")
|
||||
.absolute(grid::WIDTH - grid::PAD - HUD_W, grid::PAD - 8.0)
|
||||
.size(HUD_W, HEADER)
|
||||
.padding(12.0)
|
||||
.gap(14.0)
|
||||
.radius(14.0)
|
||||
.fill(c(color::TILE))
|
||||
.border(1.0, c(color::ACCENT.alpha(0.4)))
|
||||
.raise()
|
||||
.child(
|
||||
col()
|
||||
.w(HUD_W - GRAPH_W - 40.0 - 14.0 - 24.0)
|
||||
.gap(1.0)
|
||||
.child(caption(format!("Rune · {}", r.source)))
|
||||
.child(text(r.big()).font(nums(36.0, 700.0)).color(c(grade_color(r.ms))))
|
||||
.child(text(r.detail()).font(nums(11.0, 500.0)).color(c(color::TEXT_2)))
|
||||
.child(text(r.rate()).font(nums(11.0, 500.0)).color(c(color::TEXT_2))),
|
||||
)
|
||||
.child(graph)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! The shared look in Rune terms: colours, type and the tile frame every tile sits in.
|
||||
|
||||
use motion_bento_chaos::look::{self, Lch, color, grid};
|
||||
use rune::{Color, El, TextStyle, col, oklcha, row, spacer, text};
|
||||
|
||||
pub fn c(l: Lch) -> Color {
|
||||
oklcha(l.l, l.c, l.h, l.a)
|
||||
}
|
||||
|
||||
pub fn spring(s: look::Spring) -> rune::Spring {
|
||||
rune::Spring::new(s.duration, s.bounce)
|
||||
}
|
||||
|
||||
pub fn font(size: f32, weight: f32) -> TextStyle {
|
||||
TextStyle::new(size, weight).lh((size * 1.3).round())
|
||||
}
|
||||
|
||||
/// Tabular figures, so changing numbers don't jitter sideways.
|
||||
pub fn nums(size: f32, weight: f32) -> TextStyle {
|
||||
font(size, weight).features("'tnum' 1")
|
||||
}
|
||||
|
||||
pub fn title(s: &str) -> El {
|
||||
text(s).font(font(13.0, 560.0)).color(c(color::TEXT_2))
|
||||
}
|
||||
|
||||
pub fn caption(s: impl Into<String>) -> El {
|
||||
text(s.into()).font(font(12.0, 460.0)).color(c(color::TEXT_3))
|
||||
}
|
||||
|
||||
/// A tile: a rounded card with a title row (title on the left, `aside` on the right) over `body`.
|
||||
pub fn tile(key: &str, name: &str, aside: El, body: El) -> El {
|
||||
col()
|
||||
.key(key.to_owned())
|
||||
.radius(grid::RADIUS)
|
||||
.fill(c(color::TILE))
|
||||
.border(1.0, c(color::EDGE))
|
||||
.padding(grid::TILE_PAD)
|
||||
.gap(14.0)
|
||||
.child(row().key("head").h(20.0).center_y().gap(8.0).child(title(name)).child(spacer()).child(aside))
|
||||
.child(body)
|
||||
}
|
||||
|
||||
/// Column width in the 4-column grid.
|
||||
pub fn col_w() -> f32 {
|
||||
(grid::WIDTH - 2.0 * grid::PAD - 3.0 * grid::GAP) / 4.0
|
||||
}
|
||||
|
||||
/// A tile's inside width for a span of `cols` columns.
|
||||
pub fn inner_w(cols: f32) -> f32 {
|
||||
col_w() * cols + grid::GAP * (cols - 1.0) - 2.0 * grid::TILE_PAD
|
||||
}
|
||||
|
||||
/// A tile's body height for a row of height `h`.
|
||||
pub fn inner_h(h: f32) -> f32 {
|
||||
h - 2.0 * grid::TILE_PAD - 20.0 - 14.0
|
||||
}
|
||||
|
||||
/// A rounded button in the well colour.
|
||||
pub fn well_button(key: &str, label: &str, w: f32, h: f32) -> El {
|
||||
row()
|
||||
.key(key.to_owned())
|
||||
.size(w, h)
|
||||
.radius(h * 0.32)
|
||||
.center()
|
||||
.fill(c(color::WELL))
|
||||
.border(1.0, c(color::EDGE))
|
||||
.hover(c(color::WELL_HI))
|
||||
.press(c(color::WELL_HI))
|
||||
.press_scale(0.94)
|
||||
.child(text(label.to_owned()).font(font(15.0, 560.0)).color(c(color::TEXT)))
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use motion_bento_chaos::schedule::{TAP_LEAD, schedule};
|
||||
use motion_bento_chaos::{Config, Model};
|
||||
use rune::{Env, Runtime};
|
||||
|
||||
use super::{State, view};
|
||||
use motion_bento_chaos::look::grid;
|
||||
|
||||
/// Taps every scheduled action's key the way the headless script does, and checks the window's
|
||||
/// model after each tap against the model the schedule simulated. A tap that lands on the wrong
|
||||
/// element, or on none, shows up as the first action where the two part.
|
||||
#[test]
|
||||
fn script_taps_reach_the_same_state_as_the_schedule() {
|
||||
for seed in [1, 2, 3] {
|
||||
let cfg = Config { seed, duration: 12.0, ..Config::default() };
|
||||
let mut rt = Runtime::new(State::new(), view, (grid::WIDTH, grid::HEIGHT), Env { system_dark: true, scale: 1.0 });
|
||||
rt.state.player = None;
|
||||
rt.state.m = Model::new(seed);
|
||||
let mut want = Model::new(seed);
|
||||
let dt = 1.0 / 60.0;
|
||||
let mut t = 0.0;
|
||||
rt.frame(0.0);
|
||||
for (n, e) in schedule(&cfg).into_iter().enumerate() {
|
||||
while t + dt <= e.t - TAP_LEAD {
|
||||
t += dt;
|
||||
rt.frame(dt);
|
||||
}
|
||||
let key = e.action.key();
|
||||
let (x, y) = rt.find(&key).unwrap_or_else(|| panic!("seed {seed}: event {n} at {:.3}: no element {key}", e.t));
|
||||
rt.pointer_move(x, y);
|
||||
rt.pointer_down(x, y);
|
||||
t += dt;
|
||||
rt.frame(dt);
|
||||
rt.pointer_up(x, y);
|
||||
rt.frame(0.0);
|
||||
want.apply(e.action);
|
||||
assert_eq!(
|
||||
format!("{:?}", rt.state.m),
|
||||
format!("{want:?}"),
|
||||
"seed {seed}: event {n} at {:.3}: tapping {key} ({x:.0}, {y:.0}) for {:?}",
|
||||
e.t,
|
||||
e.action
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! The middle row: the mixer, the XY pad, the play queue and the activity feed.
|
||||
|
||||
use motion_bento_chaos::Action;
|
||||
use motion_bento_chaos::look::{color, grid, lch};
|
||||
use motion_bento_chaos::model::{FADERS, FEED_KINDS, TRACKS};
|
||||
use rune::{Edge, El, Shape, Transition, canvas, col, el, row, spacer, text};
|
||||
use rune_kit::{Kit, RollingText};
|
||||
|
||||
use crate::State;
|
||||
use crate::style::{c, caption, font, inner_h, inner_w, nums, spring, tile};
|
||||
|
||||
const TRACK_H: f32 = 132.0;
|
||||
|
||||
fn tile_w() -> f32 {
|
||||
inner_w(1.0) + 2.0 * grid::TILE_PAD
|
||||
}
|
||||
|
||||
pub fn mixer(s: &State, k: &Kit) -> El {
|
||||
let travel = spring(s.springs.travel);
|
||||
let mut faders = row().w_full().h(inner_h(grid::ROW2)).justify_between();
|
||||
for (i, name) in FADERS.iter().enumerate() {
|
||||
let v = s.m.faders[i];
|
||||
let h = 12.0 + v * (TRACK_H - 12.0);
|
||||
let track = el()
|
||||
.size(30.0, TRACK_H)
|
||||
.child(el().size(8.0, TRACK_H).absolute(11.0, 0.0).radius(4.0).fill(c(color::WELL)))
|
||||
.child(
|
||||
el().size(8.0, h)
|
||||
.absolute(11.0, TRACK_H - h)
|
||||
.radius(4.0)
|
||||
.gradient(c(lch(0.74, 0.14, 240.0)), c(color::ACCENT))
|
||||
.motion(travel),
|
||||
)
|
||||
.child(
|
||||
el().size(30.0, 12.0)
|
||||
.absolute(0.0, TRACK_H - h - 6.0)
|
||||
.radius(6.0)
|
||||
.fill(c(color::TEXT))
|
||||
.shadow(2.0, 6.0, c(lch(0.0, 0.0, 0.0).alpha(0.5)))
|
||||
.motion(travel),
|
||||
);
|
||||
faders = faders.child(
|
||||
col()
|
||||
.key(format!("fader{i}"))
|
||||
.items_center()
|
||||
.gap(8.0)
|
||||
.on_press(move |s: &mut State| s.act(Action::Fader(i as u8)))
|
||||
.child(RollingText::new(format!("level{i}"), format!("{:.0}", v * 100.0)).value(v as f64).font(nums(12.0, 560.0)).color(c(color::TEXT_2)).build(k))
|
||||
.child(track)
|
||||
.child(caption(*name)),
|
||||
);
|
||||
}
|
||||
let live = row()
|
||||
.gap(6.0)
|
||||
.center_y()
|
||||
.child(el().size(6.0, 6.0).radius(3.0).fill(c(color::GOOD)))
|
||||
.child(caption("Live"));
|
||||
tile("mixer", "Mixer", live, faders).w(tile_w())
|
||||
}
|
||||
|
||||
fn grid_lines(w: f32, h: f32) -> Shape {
|
||||
let line = c(lch(1.0, 0.0, 0.0).alpha(0.06));
|
||||
let mut s = Shape::new();
|
||||
for i in 1..4 {
|
||||
let x = w * i as f32 / 4.0;
|
||||
let y = h * i as f32 / 4.0;
|
||||
s = s.line([x, 0.0], [x, h], 1.0, rune::LineCap::Butt, line).line([0.0, y], [w, y], 1.0, rune::LineCap::Butt, line);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
pub fn xy(s: &State, k: &Kit) -> El {
|
||||
let travel = spring(s.springs.travel);
|
||||
let (w, h) = (inner_w(1.0), inner_h(grid::ROW2));
|
||||
let [px, py] = s.m.puck;
|
||||
let (x, y) = (px * w, py * h);
|
||||
let pad = el()
|
||||
.key("pad")
|
||||
.size(w, h)
|
||||
.radius(14.0)
|
||||
.fill(c(color::WELL))
|
||||
.border(1.0, c(color::EDGE))
|
||||
.clip_rounded(14.0)
|
||||
.on_press(|s: &mut State| s.act(Action::Puck))
|
||||
.child(canvas(grid_lines(w, h)).size(w, h).absolute(0.0, 0.0))
|
||||
.child(el().size(1.0, h).absolute(x, 0.0).fill(c(color::ACCENT.alpha(0.35))).motion(travel))
|
||||
.child(el().size(w, 1.0).absolute(0.0, y).fill(c(color::ACCENT.alpha(0.35))).motion(travel))
|
||||
.child(el().size(96.0, 96.0).absolute(x - 48.0, y - 48.0).radius(48.0).fill(c(color::ACCENT.alpha(0.28))).blur(18.0).motion(travel))
|
||||
.child(
|
||||
el().size(24.0, 24.0)
|
||||
.absolute(x - 12.0, y - 12.0)
|
||||
.radius(12.0)
|
||||
.fill(c(color::ACCENT))
|
||||
.border(3.0, c(color::TEXT))
|
||||
.shadow(3.0, 10.0, c(lch(0.0, 0.0, 0.0).alpha(0.45)))
|
||||
.motion(travel),
|
||||
);
|
||||
let readout = row()
|
||||
.gap(10.0)
|
||||
.child(RollingText::new("cutoff", format!("{:.0} Hz", 200.0 + px * 7800.0)).value(px as f64).font(nums(12.0, 500.0)).color(c(color::TEXT_3)).build(k))
|
||||
.child(RollingText::new("res", format!("Q {:.1}", 0.5 + (1.0 - py) * 9.5)).value((1.0 - py) as f64).font(nums(12.0, 500.0)).color(c(color::TEXT_3)).build(k));
|
||||
tile("xy", "Filter", readout, pad).w(tile_w())
|
||||
}
|
||||
|
||||
/// The queue's card art: a two-tone gradient per track.
|
||||
fn art(track: usize) -> El {
|
||||
let hue = (track as f32 * 47.0 + 200.0) % 360.0;
|
||||
el().size(64.0, 64.0)
|
||||
.radius(12.0)
|
||||
.linear_gradient(135f32.to_radians(), [(0.0, c(lch(0.72, 0.15, hue))), (1.0, c(lch(0.42, 0.14, (hue + 50.0) % 360.0)))])
|
||||
}
|
||||
|
||||
pub const CARD_H: f32 = 140.0;
|
||||
/// How far each card behind the front one sits lower, and how much smaller it is.
|
||||
pub const PEEK: f32 = 14.0;
|
||||
pub const SHRINK: f32 = 0.05;
|
||||
|
||||
pub fn queue(s: &State, _k: &Kit) -> El {
|
||||
let layout = spring(s.springs.layout);
|
||||
let w = inner_w(1.0);
|
||||
let h = inner_h(grid::ROW2);
|
||||
let mut deck = el().w(w).h(h);
|
||||
// Back to front, so the front card paints last.
|
||||
for (depth, card) in s.m.queue.iter().enumerate().rev() {
|
||||
let d = depth as f32;
|
||||
let front = depth == 0;
|
||||
let (title, artist) = TRACKS[card.track];
|
||||
let shade = lch(0.29 - 0.025 * d, 0.018, 258.0);
|
||||
let progress = 0.18 + 0.09 * (card.id % 7) as f32;
|
||||
let info = col()
|
||||
.gap(14.0)
|
||||
.w_full()
|
||||
.opacity(if front { 1.0 } else { 0.0 })
|
||||
.child(
|
||||
row()
|
||||
.gap(14.0)
|
||||
.center_y()
|
||||
.child(art(card.track))
|
||||
.child(
|
||||
col()
|
||||
.gap(3.0)
|
||||
.child(text(title).font(font(16.0, 620.0)).color(c(color::TEXT)))
|
||||
.child(text(artist).font(font(13.0, 460.0)).color(c(color::TEXT_2))),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
col()
|
||||
.gap(6.0)
|
||||
.child(el().w_full().h(4.0).radius(2.0).fill(c(color::WELL_HI)).child(el().w_frac(progress).h(4.0).radius(2.0).fill(c(color::TEXT_2))))
|
||||
.child(
|
||||
row()
|
||||
.child(text(format!("{}:{:02}", (progress * 220.0) as u32 / 60, (progress * 220.0) as u32 % 60)).font(nums(11.0, 500.0)).color(c(color::TEXT_3)))
|
||||
.child(spacer())
|
||||
.child(text("3:40").font(nums(11.0, 500.0)).color(c(color::TEXT_3))),
|
||||
),
|
||||
);
|
||||
deck = deck.child(
|
||||
col()
|
||||
.key(format!("card{}", card.id))
|
||||
.size(w, CARD_H)
|
||||
.absolute(0.0, d * PEEK)
|
||||
.scale(1.0 - d * SHRINK)
|
||||
.radius(16.0)
|
||||
.fill(c(shade))
|
||||
.border(1.0, c(color::EDGE))
|
||||
.shadow(6.0, 18.0, c(lch(0.0, 0.0, 0.0).alpha(0.35)))
|
||||
.padding(16.0)
|
||||
.motion(layout)
|
||||
.transition(Transition::asymmetric(
|
||||
Transition::scale(0.9),
|
||||
Transition::move_edge(Edge::Trailing).combined(Transition::opacity()),
|
||||
))
|
||||
.child(info),
|
||||
);
|
||||
}
|
||||
let skip = row()
|
||||
.key("skip")
|
||||
.h(24.0)
|
||||
.px(10.0)
|
||||
.radius(12.0)
|
||||
.center()
|
||||
.fill(c(color::ACCENT_DIM))
|
||||
.hover(c(color::ACCENT.alpha(0.28)))
|
||||
.press_scale(0.94)
|
||||
.on_press(|s: &mut State| s.act(Action::Queue))
|
||||
.child(text("Skip").font(font(12.0, 600.0)).color(c(color::ACCENT)));
|
||||
tile("queue", "Up next", skip, deck).w(tile_w())
|
||||
}
|
||||
|
||||
const KIND_HUES: [f32; 8] = [245.0, 30.0, 155.0, 70.0, 200.0, 265.0, 330.0, 175.0];
|
||||
|
||||
pub fn feed(s: &State, _k: &Kit) -> El {
|
||||
let mut rows = col().w_full().gap(6.0);
|
||||
for item in &s.m.feed {
|
||||
let hue = KIND_HUES[item.kind % KIND_HUES.len()];
|
||||
rows = rows.child(
|
||||
row()
|
||||
.key(format!("item{}", item.id))
|
||||
.h(40.0)
|
||||
.w_full()
|
||||
.px(12.0)
|
||||
.gap(10.0)
|
||||
.radius(12.0)
|
||||
.center_y()
|
||||
.fill(c(color::WELL))
|
||||
.transition(Transition::asymmetric(
|
||||
Transition::offset(0.0, -12.0).combined(Transition::opacity()),
|
||||
Transition::scale(0.96),
|
||||
))
|
||||
.child(el().size(8.0, 8.0).radius(4.0).fill(c(lch(0.72, 0.15, hue))))
|
||||
.child(text(FEED_KINDS[item.kind]).font(font(13.0, 500.0)).color(c(color::TEXT)).truncate())
|
||||
.child(spacer())
|
||||
.child(text(format!("9:{:02}", item.minute)).font(nums(12.0, 460.0)).color(c(color::TEXT_3))),
|
||||
);
|
||||
}
|
||||
let test = row()
|
||||
.key("test")
|
||||
.h(24.0)
|
||||
.px(10.0)
|
||||
.radius(12.0)
|
||||
.center()
|
||||
.fill(c(color::WELL))
|
||||
.hover(c(color::WELL_HI))
|
||||
.press_scale(0.94)
|
||||
.on_press(|s: &mut State| s.act(Action::Feed))
|
||||
.child(text("Test alert").font(font(12.0, 560.0)).color(c(color::TEXT_2)));
|
||||
tile("feed", "Activity", test, rows.motion(spring(s.springs.layout))).w(tile_w())
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
//! The top row: scenes, the thermostat and the lights.
|
||||
|
||||
use motion_bento_chaos::Action;
|
||||
use motion_bento_chaos::look::{color, grid};
|
||||
use motion_bento_chaos::model::{LIGHTS, SCENE_NOTES, SCENES};
|
||||
use rune::{El, LineCap, Shape, canvas, col, el, row, spacer, text};
|
||||
use rune_kit::{Kit, RollingText, Switch};
|
||||
|
||||
use crate::State;
|
||||
use crate::style::{c, caption, font, inner_h, inner_w, nums, spring, tile, well_button};
|
||||
|
||||
const SEG_H: f32 = 44.0;
|
||||
const SEG_PAD: f32 = 4.0;
|
||||
|
||||
pub fn scenes(s: &State, k: &Kit) -> El {
|
||||
let m = &s.m;
|
||||
let mood = color::SCENE[m.scene];
|
||||
let w = inner_w(2.0);
|
||||
let seg_w = (w - 2.0 * SEG_PAD) / SCENES.len() as f32;
|
||||
let snap = spring(s.springs.snap);
|
||||
let morph = spring(s.springs.morph);
|
||||
|
||||
let mut segments = row()
|
||||
.w(w)
|
||||
.h(SEG_H)
|
||||
.radius(12.0)
|
||||
.fill(c(color::WELL))
|
||||
.border(1.0, c(color::EDGE))
|
||||
.padding(SEG_PAD)
|
||||
.child(
|
||||
el().size(seg_w, SEG_H - 2.0 * SEG_PAD)
|
||||
.absolute(SEG_PAD + seg_w * m.scene as f32, SEG_PAD)
|
||||
.radius(9.0)
|
||||
.fill(c(mood))
|
||||
.shadow(4.0, 14.0, c(mood.alpha(0.45)))
|
||||
.motion(snap),
|
||||
);
|
||||
for (i, name) in SCENES.iter().enumerate() {
|
||||
let on = i == m.scene;
|
||||
segments = segments.child(
|
||||
row()
|
||||
.key(format!("seg{i}"))
|
||||
.grow(1.0)
|
||||
.h_full()
|
||||
.center()
|
||||
.on_press(move |s: &mut State| s.act(Action::Scene(i as u8)))
|
||||
.child(text(*name).font(font(14.0, 560.0)).color(c(if on { color::ON_ACCENT } else { color::TEXT_2 })).motion(snap)),
|
||||
);
|
||||
}
|
||||
|
||||
let lights_on = m.lights.iter().filter(|l| **l).count();
|
||||
let picked = m.chips.iter().filter(|c| **c).count();
|
||||
let stat = |label: &str, value: String| {
|
||||
col()
|
||||
.gap(2.0)
|
||||
.padding(10.0)
|
||||
.w(118.0)
|
||||
.radius(12.0)
|
||||
.fill(c(color::WELL))
|
||||
.child(caption(label))
|
||||
.child(RollingText::new(format!("stat-{label}"), value).font(nums(16.0, 600.0)).color(c(color::TEXT)).build(k))
|
||||
};
|
||||
let summary = row()
|
||||
.h(inner_h(grid::ROW1) - SEG_H - 16.0)
|
||||
.w(w)
|
||||
.center_y()
|
||||
.gap(10.0)
|
||||
.child(
|
||||
// The mood's glow, sliding under the summary toward the picked segment.
|
||||
el().size(260.0, 90.0)
|
||||
.absolute(-30.0 + seg_w * m.scene as f32 * 0.55, 6.0)
|
||||
.radius(45.0)
|
||||
.fill(c(mood.alpha(0.22)))
|
||||
.blur(36.0)
|
||||
.motion(morph),
|
||||
)
|
||||
.child(
|
||||
col()
|
||||
.gap(4.0)
|
||||
.grow(1.0)
|
||||
.child(RollingText::new("scene-name", SCENES[m.scene]).value(m.scene as f64).font(font(30.0, 650.0)).color(c(color::TEXT)).build(k))
|
||||
.child(text(SCENE_NOTES[m.scene]).font(font(13.0, 460.0)).color(c(color::TEXT_2))),
|
||||
)
|
||||
.child(stat("Lights", format!("{lights_on} of 4")))
|
||||
.child(stat("Target", m.temp_label()))
|
||||
.child(stat("Genres", picked.to_string()));
|
||||
|
||||
let swatch = row()
|
||||
.gap(8.0)
|
||||
.center_y()
|
||||
.child(caption("Mood"))
|
||||
.child(el().size(14.0, 14.0).radius(7.0).fill(c(mood)).shadow(0.0, 8.0, c(mood.alpha(0.6))).motion(morph));
|
||||
tile("scene", "Scenes", swatch, col().gap(16.0).child(segments).child(summary)).w(inner_w(2.0) + 2.0 * grid::TILE_PAD)
|
||||
}
|
||||
|
||||
/// The thermostat ring's arc: 270° from the lower left, clockwise, as points.
|
||||
fn arc(size: f32, inset: f32) -> Vec<[f32; 2]> {
|
||||
let r = size / 2.0 - inset;
|
||||
let (a0, sweep) = (135f32.to_radians(), 270f32.to_radians());
|
||||
(0..=96)
|
||||
.map(|i| {
|
||||
let a = a0 + sweep * i as f32 / 96.0;
|
||||
[size / 2.0 + r * a.cos(), size / 2.0 + r * a.sin()]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub const RING: f32 = 150.0;
|
||||
|
||||
pub fn thermostat(s: &State, k: &Kit) -> El {
|
||||
let m = &s.m;
|
||||
let points = arc(RING, 9.0);
|
||||
let track = Shape::new().stroke_with(points.clone(), false, 10.0, LineCap::Round, c(color::WELL_HI));
|
||||
let fill = Shape::new().stroke_with(points, false, 10.0, LineCap::Round, c(color::ACCENT));
|
||||
let ring = el()
|
||||
.size(RING, RING)
|
||||
.child(canvas(track).size(RING, RING).absolute(0.0, 0.0))
|
||||
.child(canvas(fill).size(RING, RING).absolute(0.0, 0.0).live_trim(s.ring.smooth(spring(s.springs.travel))))
|
||||
.child(
|
||||
col()
|
||||
.size(RING, RING)
|
||||
.absolute(0.0, 0.0)
|
||||
.center()
|
||||
.gap(0.0)
|
||||
.child(RollingText::new("temp", m.temp_label()).value(m.temp as f64).font(nums(34.0, 640.0)).color(c(color::TEXT)).build(k))
|
||||
.child(caption("Target")),
|
||||
);
|
||||
let heating = m.temp > 21.0;
|
||||
let aside = row()
|
||||
.gap(6.0)
|
||||
.center_y()
|
||||
.child(el().size(8.0, 8.0).radius(4.0).fill(c(if heating { color::WARM } else { color::ACCENT })).motion(spring(s.springs.morph)))
|
||||
.child(RollingText::new("mode", if heating { "Heating" } else { "Cooling" }).font(font(12.0, 460.0)).color(c(color::TEXT_3)).build(k));
|
||||
let buttons = col()
|
||||
.gap(10.0)
|
||||
.child(well_button("up", "+", 52.0, 44.0).on_press(|s: &mut State| s.act(Action::TempUp)))
|
||||
.child(well_button("down", "−", 52.0, 44.0).on_press(|s: &mut State| s.act(Action::TempDown)));
|
||||
let body = row().h(inner_h(grid::ROW1)).center_y().gap(14.0).child(ring).child(spacer()).child(buttons);
|
||||
tile("thermo", "Thermostat", aside, body).w(inner_w(1.0) + 2.0 * grid::TILE_PAD)
|
||||
}
|
||||
|
||||
pub fn lights(s: &State, k: &Kit) -> El {
|
||||
let m = &s.m;
|
||||
let on = m.lights.iter().filter(|l| **l).count();
|
||||
let mut rows = col().gap(4.0);
|
||||
for (i, name) in LIGHTS.iter().enumerate() {
|
||||
let lit = m.lights[i];
|
||||
rows = rows.child(
|
||||
row()
|
||||
.h(34.0)
|
||||
.center_y()
|
||||
.gap(12.0)
|
||||
.child(
|
||||
el().size(10.0, 10.0)
|
||||
.radius(5.0)
|
||||
.fill(c(if lit { color::WARM } else { color::WELL_HI }))
|
||||
.shadow(0.0, 10.0, c(if lit { color::WARM.alpha(0.7) } else { color::WARM.alpha(0.0) }))
|
||||
.motion(spring(s.springs.snap)),
|
||||
)
|
||||
.child(text(*name).font(font(14.0, 500.0)).color(c(if lit { color::TEXT } else { color::TEXT_2 })))
|
||||
.child(spacer())
|
||||
.child(
|
||||
Switch::new(lit)
|
||||
.label(*name)
|
||||
.hide_label()
|
||||
.on_toggle(move |s: &mut State| s.act(Action::Light(i as u8)))
|
||||
.build(k)
|
||||
.key(format!("light{i}")),
|
||||
),
|
||||
);
|
||||
}
|
||||
let aside = RollingText::new("lights-on", format!("{on} on")).value(on as f64).font(font(12.0, 460.0)).color(c(color::TEXT_3)).build(k);
|
||||
tile("lights", "Lights", aside, rows).w(inner_w(1.0) + 2.0 * grid::TILE_PAD)
|
||||
}
|
||||
Reference in new issue
Block a user