hex/src/rune_ui/onboarding_kit/sfx.rs
Kit Langton c84998da53
feat(onboarding): the first run is one story, from a bad conversation to your first words (#1501)
* Onboarding: slower Without Hex comedy with a start button, a real conversation, and one focus at a time

* Onboarding comedy v2: Launch Room, visible slip, rewind into Hex

Jay's question is up before the click and the first reply comes 0.35 s after
it. The deady/dead slip holds long enough to read, then Return flashes red
with a heavy clunk. The scene is one iMessage group: the removal is a red pill
that wipes a frantic draft mid-word and locks the field. With Hex rewinds the
disaster, melts the keys down to the lit shortcut, and raises the HUD before
the key goes down. The caret no longer sits under a word as it lands. Adds
original chat sounds, a score counted in whole seconds with a chime, and a
live first run that waits for Continue.

* Onboarding comedy v3: one-way melt, clean act breaks, upward rewind, Skip

* Test that Skip appears two seconds in and leaves the comedy

* Fill the keyboard's pocket back in once the HUD has gone

* Onboarding comedy v4 engine: presenting pill, tapbacks, heartbeat, slow motion and the autocorrect slam

* Onboarding: scenes as plain-text files, with a celebration in With Hex

Each scene sets its own room, people, pill, ending and With Hex payoff
(replies, tapbacks, status pills, confetti and fireworks with their own
sounds). The validator reports line-numbered mistakes and the limits a
scene can hold.

* Scenes: document the limits and the folder check

* Onboarding: tapbacks stay on the line above, the pill keeps its own row, and With Hex can change it

* Polish the practice game: themed messages, transcript and high score, real Dot scope, logo build, Replay onboarding

* Scene folder check prints every scene's length

* Flush the ready soundtrack once the logo is built

* Scenes: only the theme's colours, and a clear error for any other

* Check the whole Advanced fold, down to Replay onboarding

* C-plus: v3's scene with the over-the-top With Hex

* Drop the whole-pixel bob now that Rune glides text with its box

* Onboarding chat: the real Messages sounds from macOS, pill in the header

Received, sent and each tapback's sound load at run time from macOS's own files, peak-matched to Hex's stand-ins, which still play where a file is missing and off macOS. The presenting pill moves into the conversation header, level with the title.

* Follow the dictation/ move, and keep a resized golden's render for CI

* Onboarding: keep Reply::Lines' shape so the game's card is untouched

The autocorrect mark goes to chat() as its own argument, and notice() draws sent_bubbles again as dev does.

* Golden: the whole Advanced fold, down to Replay onboarding

* Onboarding comedy: Model M typing, a real heartbeat, three triumph takes

The Without Hex keys are now cut from a CC0 recording of an IBM Model M
(scripts/sounds/comedy/SOURCE.md): eight presses at three pitches, a
deeper space bar and a heavier delete, each at a slightly different level,
whatever key sound the reader picked. The heartbeat is a synthesized
lub-dub under the clicks (HEX_ONBOARDING_HEARTBEAT=off drops it), and
HEX_ONBOARDING_TRIUMPH=1..3 picks brass, a chime run, or a cheer and pop.
scripts/sounds/comedy.py rebuilds them all.

* Follow dev: audio::input_level, and drop Labs' last icon_row import

* Onboarding comedy: tapbacks drawn like Messages

Round badges on the bubble's top corner with a ring in the card's colour
and two tail dots, grey for other people and blue for the reader's own,
every glyph a vector shape including the two-line HA HA. Stacks put the
newest on top. Prototypes/Onboarding/Tapbacks shows them all.

* Move the game's pieces into game/ and its share card into game/share.rs for the code-shape gate

* Labs: hold Paste last dictation to pick recent dictations (macOS)

* Unify the first run: Without Hex, microphone, the practice game, Accessibility

* Let the first run story play itself, game included

* Count the sound cues' third field in the logo-build tests

* Sound the comedy's triumph on the game's first score; Hex Test.app opens the new first run

* Move the stories' side panel into stories/side.rs for the code-shape gate

* First run: play the scripted With Hex payoff after Without Hex; start the heartbeat at the first typo

* Onboarding round 2: Launch Room inbox row, Messages-style senders, ending hold, float-off grants, idle HUD pill, Launch at login on Ready, Settings guide reopen

* Start the heartbeat at the first sent typo, much quieter

* Open the Launch Room like an island: a pointer clicks the row and it grows into the chat

Every first run autoplays: the row arrives with two even rings, a scripted
pointer glides in and presses it, and the row grows into the conversation
(width first, then height, on one straight path) while the group's faces,
the title and Jay's question fly over as themselves. The rest fades in once
the flights clear. Reduce Motion fades instead.

* Add a replay strip to the first run in test and debug builds

Restart, Back one beat, Joke (cycles the bundled scenes) and a fake
download speed (real, 100 Mbps, 25 Mbps; Restart downloads again at it).
Every build logs how long the download showed for. The swearing scenes A
and B are only in builds with hex_dev_onboarding (debug or HEX_TEST_BUILD=1).

* First run: Watch another one while the model downloads

Almost ready shows the download as a quiet bar with its size and time
left, and a button that plays one of three short Without Hex sketches.
The bar moves to the top pill while one plays; a finished download goes
on to the game at the sketch's next stop, after a reply has gone out.
The button goes once all three have played.

* First run: a whole-run story with a slow download and a sketch

* Onboarding: sound for the whole first run, the Launch Room opens itself, and a motion gate

- SfxTrack::clear keeps cues already fired, so the offline track keeps its first 73 s; the scripted game, the words and the cards burning get cues.
- The download pill no longer flies over the words it passes; the Launch Room opens itself 5 s after it parks.
- A motion gate over the first run in dark, light and Reduce Motion, plus a pixel check of the conversation opening: fixes its surface blinking as the plate hands over, Jay's doubled typing dots, the badge's one-frame pop and the preview's text swap.

* Onboarding: the Launch Room's click taps, whether a person or the pointer clicks

* Rune e6371c48: the motion gate checks what the first run paints

- Bump rune, rune-kit, rune-theme-opencode and rune-motion to e6371c48 (rune#71); nix outputHash follows.
- Mark the first run's deliberate motion where it's written (tapback bounces, the badge pop, keys, the game's shake) and narrow the allowlist to scoped, capped rows.
- The empty avatar slot keeps its border while its fill fades, so the ring no longer vanishes a frame early.

* Onboarding: the first run's clock runs on drawn frames, and its later pipelines warm on a thread (t1328)

* Onboarding: call out keyboard and voice-first modes, punch in on autocorrect, prototype first-screen backdrops

* Onboarding: drop the first-screen backdrop prototypes (t1328)

* Onboarding: prototype a bigger HUD and an up-next row on Setting up Hex (t1328)

* Onboarding: the Linux tests' page helper knows the two permission steps (t1328)

* Onboarding goldens: the voice-first chip beside the heading (t1328)

* Onboarding: first-screen prototype shows download size and an on-device note (t1328)

* Onboarding: the first screen shows download size and that your voice stays on this Mac (t1328)

* Onboarding: a failed download drops the size and privacy line; goldens for the first screen (t1328)

* Onboarding: drop the render scratch the branch carried

673 frames and one-off scripts under .render/ were the scratch of the
session that built this, not part of the change.

* Keep render scratch and scene stills out of the tree

* Onboarding: the scene tests that need a dev-only scene skip release builds

A and B swear, so release builds leave them out of the bundle; two tests
still asked for A by name and panicked where it was missing (the Nix
package's test run).

* Onboarding: goldens from the Linux run after the merge

Seventeen onboarding renders moved: the first screen's download size and
privacy line, the mic line from #1420, and dark text that sits a few pixels
lower with dev's Rune pin.

* Onboarding: a tighter opening and fireworks that light the page

The first run's Setting up Hex holds a second, then the Launch Room's
conversation is there as the download flies up: Jay's messages land in
it with their sounds instead of on an inbox row a pointer clicks open.
The Keyboard mode stamp goes (the heading's chip says it), Without Hex's
heading is one line, and the privacy line also shows on the microphone
step.

With Hex's fireworks move to the GPU: three shells rise on trails and
burst beside the conversation into a few hundred sparks each, white-hot
to hue to crackling embers under drag and gravity. Each burst lights
the page under it for a moment, multiplying what's drawn so surfaces
brighten by their own colour and the dark page barely does. Reduce
Motion gets one soft flash. The shipping scene drops its confetti.

* Onboarding: sketches keep their own opening; the motion gate follows the shorter intro

Sketches built their scenes from the first run's timing, so its shorter
opening reached them. The slow-download fixture lands the model 6.8 s
sooner, as much as the intro shrank, so the gate's windows see the same
story; the practice game's shake can still be moving as the handoff
window ends.

* Fireworks: stars light as they leave the break, the shell's glitter is quieter, and the page light fades with no edge

* Onboarding: fireworks in depth, and three compositions to compare

Fireworks burst in two layers. Far shells sit behind the conversation,
smaller, dimmer and softer, lighting it a little; near shells draw in
front, bigger and brighter, their sparks falling across the card's
edges for a moment and their light hitting it hard, with their cores
kept beside it. A break opens as a bloom: packed stars share its light
until the shell has spread, since sRGB-encoded blending adds a hundred
faint stars up to a white disc.

The demo's composition is now a layout the run picks, as it picks its
scene, with three playground variants beside today's: A, a tighter
centre (one two-line heading for both scenes, a larger conversation,
the keyboard tucked under it, Skip in the corner); B, a split (the
mode, a big title and one line in a left column, the conversation and
its keyboard on the right, the fireworks in the open page); and C, a
laptop (the conversation as its screen, the keyboard on its deck).
Today's layout is unchanged.

* Onboarding: the score pill hugs its count, and a near burst's break stays compact

The practice game's score pill was a fixed 112 pt with its content left
aligned, so "1 destroyed" sat 12 pt from its left edge and about 40 pt
from its right. It's now as wide as its number and label need, with
12 pt either side in every language, and the share card folds back to
that width. A near burst's bloom no longer spreads into a wide, faint,
whitish disc that read as smoke. Headless renders take
HEX_RENDER_LANGUAGE to check copy in another language.

* feedback: the onboarding's cues in their own file, under the size limit

* Onboarding: the card's landing nudge is a kick, and the motion gate gets the time it needs

* Onboarding: goldens after dev's language-switch change and the microphone step's privacy line; the playground's two-line heading stays English

* Onboarding motion: the game's idle pill fades on its clock, sent bubbles leave the field whole, and the Accessibility helper line fades out

From per-frame traces of the whole scripted run:

- The practice game's stage lands every change at once, so the idle
  pill's springs never ran: it vanished and reappeared in one frame at
  every take, and when the score card came and went. Its fade and
  settle are now worked out on the game's clock, from when the scope
  last came or went, and it steps aside with the chrome.
- A sent line is launched out of the field, but its bubble faded in on
  its own, so each send started as a ghost of the text it left (five
  sends in Without Hex, the spoken answer in With Hex). The bubble now
  enters with its line.
- The escaping Accessibility panel dropped its "Accessibility helper"
  line in one frame; it fades as the panel starts to move.

* Onboarding motion: the idle pill's spring is settled before the first take, not NaN

* Onboarding motion: a sent bubble's words leave the field at full strength too

* Onboarding fireworks: a burst opens on a point of light, not a grey disc

The bang was a wide glow at a quarter of white, which sRGB-encoded
blending flattens into a grey-beige disc for three frames before the
stars show. It is now small and brighter than white, gone as they open.
On light pages the bursts' tint has a soft shoulder instead of a flat
plateau of colour, and sparks paint a deeper hue so gold shows on white.

* Onboarding copy: the certificate's sentence, the game's full stop, Accessibility's row on one line

- "I hereby certify that I have completed Hex onboarding."
- The game's lead ends its sentence, as every other lead does.
- Accessibility's row drops "in any app", which the line above it
  says: allowed, it wrapped and left "app" alone on a second line.
- The permission pages' headings are translated like their titles.

* Onboarding: alignment and one main action

- Skip steps aside while autocorrect's camera is pushed in: the
  keyboard swelled down over it.
- The score card's two lines sit on the middle of the number.
- The score pill is as tall as Done beside it.
- Hex is ready keeps one contrast button: beside Start using Hex,
  Launch at login is a neutral one.

* Onboarding pacing: Setting up Hex holds long enough to read, the removal holds once

Setting up Hex held 1.0 s before the download flew up; 1.6 s reads.
The first run held the removal for the scene's own 2.0 s and 1.6 s
more, 3.6 s of silence; now 2.8 s.

The game's screen shake is marked where it's written, a kick and
steps, rather than allowed by where a gate window happens to end.

* Onboarding: the certificate in its own file, and no unused import

The motion fixes took game.rs past its size ceiling and left Spring
imported with no use; the certificate moves out to game/certificate.rs.

* Onboarding goldens: the game's full stop, and Launch at login beside Start using Hex
2026-11-09 17:29:51 -08:00

705 lines
26 KiB
Rust

//! Sound schedule for `"Prototypes/Onboarding/First run"`:
//!
//! - Auditionable typing key-sound candidates ([`KeySoundStyle`]: `Mechanical
//! clack` default, `Taptic tick`, `Muted felt`, `Soft warm`, and `Silent
//! typing`), never repeating an adjacent sample, each press at its own
//! pitch and level.
//! - Tactile shortcut keycap press and release (`⌥` down / up).
//! - Hex's real `#292` `DictationStart`, `DictationStop`, and `DictationDone`
//! tones and the ready logo's three rising notes, played through
//! [`crate::feedback`], respecting
//! the user's sound set and feedback volume (`volume == 0` is silent;
//! `reduced_motion` never suppresses sound).
//! - Quiet motion landing cues: the hexagon mark, permission rows ticking to
//! `Allowed`, the Accessibility helper detaching and docking beside System
//! Settings, and `"Almost ready"`.
//! - Words shooting out of the HUD ([`WordHits`]: a few varied flicks a
//! burst, not one a word) and the game's cards burning away.
//! - Optional offline WAV export (`HEX_ONBOARDING_AUDIO_OUT`) so headless
//! `--video` renders produce a frame-accurate 48 kHz soundtrack without ever
//! opening an audio output device.
use std::path::Path;
use super::fixture::Take;
use super::hex_meter::BUILD_AT;
use super::hud_stage::DONE_DELAY;
use super::{permissions, scene_script, triumph, typing};
use crate::feedback::{
self, CLACK_KEYS, KeySoundStyle, OnboardingTone, SoundSet, TRIUMPHS, Tapback, Tone,
};
/// The heartbeat's level, in percent, calm and in full panic: well under
/// the keys and the dings.
const HEART_QUIET: f32 = 10.0;
const HEART_LOUD: f32 = 28.0;
/// The triumph candidate a render plays, `HEX_ONBOARDING_TRIUMPH=1..3`
/// (the first by default) until one is chosen.
fn triumph_take() -> u8 {
std::env::var("HEX_ONBOARDING_TRIUMPH")
.ok()
.and_then(|v| v.parse::<u8>().ok())
.filter(|n| (1..=TRIUMPHS).contains(n))
.map_or(0, |n| n - 1)
}
/// Whether the heartbeat plays under the panic; `HEX_ONBOARDING_HEARTBEAT=off`
/// renders the comedy without it to compare.
fn heartbeat_on() -> bool {
std::env::var("HEX_ONBOARDING_HEARTBEAT").map_or(true, |v| v != "off")
}
/// A fixed scramble of `seed`, so each press's pitch and level vary the same
/// way on every run.
fn scramble(seed: usize) -> usize {
let mut x = seed.wrapping_mul(0x9E37_79B9).wrapping_add(0x7F4A_7C15);
x ^= x >> 15;
x = x.wrapping_mul(0x2C1B_3C6D);
x ^ (x >> 12)
}
/// The sound of the tapback drawn as `glyph`.
fn tapback(glyph: typing::Glyph) -> Tone {
use typing::Glyph;
Tone::Onboarding(OnboardingTone::Tapback(match glyph {
Glyph::Heart => Tapback::Heart,
Glyph::ThumbsUp => Tapback::ThumbsUp,
Glyph::ThumbsDown => Tapback::ThumbsDown,
Glyph::Haha => Tapback::Haha,
Glyph::Bang => Tapback::Exclamation,
Glyph::Question => Tapback::Question,
}))
}
/// The shortest gap between two word flicks: a burst of words sounds a few
/// of them, not every one.
const WORD_GAP: f64 = 0.15;
/// The word flicks one burst has sounded.
pub(crate) struct WordHits {
last: f64,
n: usize,
}
impl Default for WordHits {
fn default() -> Self {
Self {
last: f64::NEG_INFINITY,
n: 0,
}
}
}
#[derive(Default)]
pub(crate) struct SfxTrack {
pub(crate) style: KeySoundStyle,
/// Each cue's time, tone, and percent of its level.
cues: Vec<(f64, Tone, u8)>,
fired: usize,
almost_ready_scheduled: bool,
flushed: bool,
}
impl SfxTrack {
/// Drops every cue still to come. What already played stays on the
/// record the offline soundtrack is mixed from.
pub(crate) fn clear(&mut self) {
self.cues.truncate(self.fired);
self.almost_ready_scheduled = false;
self.flushed = false;
}
pub(crate) fn has_pending(&self, now: f64) -> bool {
self.cues
.get(self.fired)
.is_some_and(|&(at, ..)| at <= now + 1.0)
}
/// Switches the active typing sound candidate (including any unfired
/// strokes already queued) and plays a short 5-stroke typing cadence so
/// the candidate can be heard immediately on click.
pub(crate) fn set_style_and_preview(&mut self, style: KeySoundStyle, now: f64) {
self.style = style;
for (_, tone, _) in &mut self.cues[self.fired..] {
*tone = match *tone {
Tone::Onboarding(OnboardingTone::Key(_, v)) => {
Tone::Onboarding(OnboardingTone::Key(style, v))
}
Tone::Onboarding(OnboardingTone::KeySpace(_)) => {
Tone::Onboarding(OnboardingTone::KeySpace(style))
}
Tone::Onboarding(OnboardingTone::KeyBackspace(_)) => {
Tone::Onboarding(OnboardingTone::KeyBackspace(style))
}
other => other,
};
}
if style == KeySoundStyle::Silent {
return;
}
for (dt, cue) in [
(0.005, OnboardingTone::Key(style, 0)),
(0.082, OnboardingTone::Key(style, 2)),
(0.152, OnboardingTone::Key(style, 4)),
(0.228, OnboardingTone::Key(style, 1)),
(0.312, OnboardingTone::KeySpace(style)),
] {
self.push(now + dt, Tone::Onboarding(cue));
}
}
fn push(&mut self, at: f64, tone: Tone) {
self.push_at(at, tone, 100);
}
fn push_at(&mut self, at: f64, tone: Tone, percent: u8) {
self.cues.push((at, tone, percent));
let start = self.fired.min(self.cues.len());
self.cues[start..]
.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
}
/// Initial `"Setting up Hex"` hexagon bloom.
pub(crate) fn on_download_start(&mut self, now: f64) {
self.push(now + 0.08, Tone::Onboarding(OnboardingTone::Hexagon));
}
/// `"Without Hex"` waiting to start: the hexagon settles into the top
/// pill.
pub(crate) fn on_parked(&mut self, now: f64, had_model: bool) {
if !had_model {
self.push(now + 0.12, Tone::Onboarding(OnboardingTone::Hexagon));
}
// Jay's messages landing on the Launch Room's row.
for at in super::inbox::DINGS {
self.push(now + at, Tone::Onboarding(OnboardingTone::Incoming));
}
}
/// The Launch Room opening at `now`, by a click or by itself: the
/// click's tap, and no more dings if its row hadn't finished.
pub(crate) fn on_opened(&mut self, now: f64) {
let incoming = Tone::Onboarding(OnboardingTone::Incoming);
let fired = self.fired.min(self.cues.len());
let mut kept = self.cues.split_off(fired);
kept.retain(|&(_, tone, _)| tone != incoming);
self.cues.extend(kept);
self.push(now, Tone::Onboarding(OnboardingTone::ShortcutDown));
}
/// The conversation on screen already, `"Without Hex"` from `from`:
/// the lines from before it land in it, each with its sound, in place
/// of the row's dings.
pub(crate) fn on_arrivals(&mut self, from: f64, scene: &typing::Scene) {
let incoming = Tone::Onboarding(OnboardingTone::Incoming);
let fired = self.fired.min(self.cues.len());
let mut kept = self.cues.split_off(fired);
kept.retain(|&(_, tone, _)| tone != incoming);
self.cues.extend(kept);
for line in scene.lines().iter().filter(|l| l.at < 0.0) {
self.push(from + line.at, incoming);
}
}
/// `"Without Hex"` from `from`: every keystroke, harder as panic builds
/// (a space-bar thud under the tap), a soft send, Jay's messages, a
/// deadpan tick on `"Read"`, and the selected set's error on removal.
/// The keys are always the mechanical clack, whatever the reader picked
/// for their own typing: this is someone else's keyboard.
pub(crate) fn on_without_hex(&mut self, from: f64, scene: &typing::Scene) {
let style = KeySoundStyle::Clack;
let mut prev_variant: Option<u8> = None;
let mut prev_at = None;
for (i, stroke) in scene.strokes().iter().enumerate() {
let at = from + stroke.at;
// Autocorrect changes the draft without a key, and keys mashed
// together (an elbow) land as one.
if stroke.key.is_empty() || prev_at == Some(stroke.at) {
continue;
}
prev_at = Some(stroke.at);
// Calm typing sits under the chat sounds; panic brings it up,
// and no two presses land quite alike.
let wobble = (scramble(i) % 17) as f64 - 8.0;
let level = (62.0 + 28.0 * stroke.panic + wobble)
.round()
.clamp(0.0, 100.0) as u8;
let tone = match stroke.key {
"space" | "return" => OnboardingTone::KeySpace(style),
"delete" => OnboardingTone::KeyBackspace(style),
key => {
let hash = key
.bytes()
.fold(0usize, |acc, b| acc.wrapping_mul(31) + usize::from(b));
let presses = if style == KeySoundStyle::Clack {
CLACK_KEYS
} else {
6
};
let mut v = ((i * 5 + hash) % usize::from(presses)) as u8;
if prev_variant == Some(v) {
v = (v + 1) % presses;
}
prev_variant = Some(v);
if style == KeySoundStyle::Clack {
v += CLACK_KEYS * (scramble(i + hash) % 3) as u8;
}
OnboardingTone::Key(style, v)
}
};
self.push_at(at, Tone::Onboarding(tone), level);
// The finger slipping onto Return lands with a heavy clunk.
if stroke.key == "return" && scene.flash(stroke.at + 1e-3, "return") > 0.0 {
self.push(
at + 0.004,
Tone::Onboarding(OnboardingTone::KeyBackspace(style)),
);
}
if stroke.hard && matches!(tone, OnboardingTone::Key(..)) {
self.push_at(
at + 0.004,
Tone::Onboarding(OnboardingTone::KeySpace(style)),
level,
);
}
}
// Lines from before the conversation opened were already there.
for line in scene.lines().iter().filter(|l| l.at >= 0.0) {
let at = from + line.at;
match line.who {
typing::Who::Them(_) | typing::Who::Status => {
self.push(at, Tone::Onboarding(OnboardingTone::Incoming))
}
typing::Who::You => self.push(at + 0.03, Tone::Onboarding(OnboardingTone::Sent)),
typing::Who::System => self.push(at, Tone::Error),
}
}
for at in scene.reads() {
self.push(from + at, Tone::Onboarding(OnboardingTone::Read));
}
for tap in scene.all_taps() {
self.push(from + tap.at, tapback(tap.glyph));
}
// The heartbeat rises under the clicks and stops dead at the removal.
let beats = if heartbeat_on() {
scene.heartbeats()
} else {
Vec::new()
};
for beat in beats {
let tone = if beat.slow {
OnboardingTone::HeartbeatSlow
} else {
OnboardingTone::Heartbeat
};
let level = (HEART_QUIET + (HEART_LOUD - HEART_QUIET) * beat.level).round() as u8;
self.push_at(from + beat.at, Tone::Onboarding(tone), level);
}
for &(start, _) in scene.slows() {
self.push(from + start, Tone::Onboarding(OnboardingTone::SlowDown));
}
for at in scene.slams() {
self.push(from + at, Tone::Onboarding(OnboardingTone::Slam));
}
}
/// The story winding back into `"With Hex"`, and `"Voice-first mode"`
/// called.
pub(crate) fn on_rewind(&mut self, now: f64) {
self.push(now, Tone::Onboarding(OnboardingTone::Rewind));
self.push(
now + super::versus::VOICE_CALL_AT,
Tone::Onboarding(OnboardingTone::ModeVoice),
);
}
/// `"With Hex"`'s payoff from the shortcut at `from`: the answer
/// sending, each tapback and reply, and a triumphant sting under the
/// first celebration, each with its own sound.
pub(crate) fn on_hex_reply(&mut self, from: f64, beats: &triumph::HexBeats) {
self.push(from + beats.send, Tone::Onboarding(OnboardingTone::Sent));
for &(at, glyph) in &beats.taps {
self.push(from + at, tapback(glyph));
}
for (at, said) in &beats.lines {
let tone = match said {
triumph::Said::You(_) => OnboardingTone::Sent,
_ => OnboardingTone::Incoming,
};
self.push(from + at, Tone::Onboarding(tone));
}
if let Some(&(at, _)) = beats.effects.first() {
self.push(
from + at,
Tone::Onboarding(OnboardingTone::Triumph(triumph_take())),
);
}
for &(at, effect) in &beats.effects {
match effect {
scene_script::Effect::Confetti => {
self.push(from + at, Tone::Onboarding(OnboardingTone::Confetti))
}
// Each shell whistles up and booms.
scene_script::Effect::Fireworks => {
for (after, level) in super::fireworks::launches() {
self.push_at(
from + at + after,
Tone::Onboarding(OnboardingTone::Fireworks),
level,
);
}
}
}
}
}
/// `"With Hex"` or scripted `"Your turn"` dictation: physical shortcut
/// down, real `DictationStart`, then shortcut up, `DictationStop`, and
/// `DictationDone`.
pub(crate) fn on_voice_take(&mut self, start: f64, take: &Take) {
self.push(start, Tone::Onboarding(OnboardingTone::ShortcutDown));
self.push(start + 0.032, Tone::DictationStart);
let release = start + take.release;
self.push(release, Tone::Onboarding(OnboardingTone::ShortcutUp));
self.push(release + 0.024, Tone::DictationStop);
self.push(release + DONE_DELAY, Tone::DictationDone);
}
pub(crate) fn on_live_shortcut_down(&mut self, now: f64) {
self.push(now, Tone::Onboarding(OnboardingTone::ShortcutDown));
self.push(now + 0.028, Tone::DictationStart);
}
pub(crate) fn on_live_shortcut_up(&mut self, now: f64) {
self.push(now, Tone::Onboarding(OnboardingTone::ShortcutUp));
self.push(now + 0.020, Tone::DictationStop);
}
pub(crate) fn on_live_dictation_landed(&mut self, now: f64) {
self.push(now, Tone::DictationDone);
}
/// Words leaving the HUD at `launches`: a flick on the first, then on
/// each at least [`WORD_GAP`] after the last, never the same twice
/// running, each at its own level.
pub(crate) fn on_words(
&mut self,
launches: impl IntoIterator<Item = f64>,
hits: &mut WordHits,
) {
for at in launches {
if at - hits.last < WORD_GAP {
continue;
}
hits.last = at;
let level = 72 + (scramble(hits.n) % 24) as u8;
self.push_at(
at,
Tone::Onboarding(OnboardingTone::Word((hits.n % 3) as u8)),
level,
);
hits.n += 1;
}
}
/// A card struck at `at`, burning away.
pub(crate) fn on_burn(&mut self, at: f64) {
self.push(at, Tone::Onboarding(OnboardingTone::Burn));
}
/// The microphone step: a tick as macOS's prompt grants it.
pub(crate) fn on_microphone(&mut self, from: f64) {
self.push(
from + permissions::MIC_GRANT,
Tone::Onboarding(OnboardingTone::PermissionTick),
);
}
/// The Accessibility step: the guide escaping Hex's card, then a tick
/// as the switch goes on.
pub(crate) fn on_accessibility(&mut self, from: f64) {
let from = from - permissions::AX_SHIFT;
self.push(
from + permissions::AX_ESCAPE + 0.18,
Tone::Onboarding(OnboardingTone::PanelEscape),
);
self.push(
from + permissions::AX_GRANT,
Tone::Onboarding(OnboardingTone::PermissionTick),
);
}
/// Launch at login turning on: the same tick as a permission's switch.
pub(crate) fn on_login(&mut self, now: f64) {
self.push(now, Tone::Onboarding(OnboardingTone::PermissionTick));
}
/// `"With Hex"`'s score landing.
pub(crate) fn on_score(&mut self, now: f64) {
self.push(now + 0.05, Tone::Onboarding(OnboardingTone::AlmostReady));
}
/// The practice game's first score card: the comedy's triumph take.
pub(crate) fn on_game_score(&mut self, at: f64) {
self.push(
at,
Tone::Onboarding(OnboardingTone::Triumph(triumph_take())),
);
}
/// `"Almost ready"` waiting screen (fires at most once per run).
pub(crate) fn on_almost_ready(&mut self, now: f64) {
if !self.almost_ready_scheduled {
self.almost_ready_scheduled = true;
self.push(now + 0.06, Tone::Onboarding(OnboardingTone::AlmostReady));
}
}
/// `"Hex is ready"` finale: one rising note as each of the logo's
/// hexagons lands, resolving on the last; Reduced Motion shows the logo
/// built, with only the last.
pub(crate) fn on_ready(&mut self, now: f64, reduced: bool) {
if reduced {
self.push(now, Tone::Onboarding(OnboardingTone::Build(2)));
return;
}
for (i, at) in BUILD_AT.into_iter().enumerate() {
self.push(now + at, Tone::Onboarding(OnboardingTone::Build(i as u8)));
}
}
/// Interactive capsule tap (language or shortcut toggle).
pub(crate) fn on_capsule_tap(&self) {
feedback::play(Tone::Onboarding(OnboardingTone::ShortcutDown));
}
/// Advances playback to `now`, dispatching every newly-reached cue to
/// [`feedback::play`] (no-op when headless or volume is 0).
pub(crate) fn advance_to(&mut self, now: f64) {
while let Some(&(at, tone, percent)) = self.cues.get(self.fired) {
if at > now + 1e-4 {
break;
}
self.fired += 1;
feedback::play_at(tone, percent);
}
}
pub(crate) fn fired_cues(&self) -> &[(f64, Tone, u8)] {
&self.cues[..self.fired]
}
/// Writes the fired soundtrack offline when `HEX_ONBOARDING_AUDIO_OUT` is set.
pub(crate) fn flush_offline_if_requested(&mut self, fallback_secs: f64) {
if self.flushed {
return;
}
let Ok(path) = std::env::var("HEX_ONBOARDING_AUDIO_OUT") else {
return;
};
if path.is_empty() || self.fired == 0 {
return;
}
self.flushed = true;
let duration_secs = std::env::var("HEX_ONBOARDING_AUDIO_SECS")
.ok()
.and_then(|v| v.parse::<f64>().ok())
.unwrap_or(fallback_secs)
.max(fallback_secs);
let gain = std::env::var("HEX_ONBOARDING_AUDIO_GAIN")
.ok()
.and_then(|v| v.parse::<f32>().ok())
.unwrap_or(0.88)
.clamp(0.0, 1.0);
if let Err(error) = feedback::mix_offline_wav(
Path::new(&path),
self.fired_cues(),
SoundSet::Signature,
gain,
duration_secs,
) {
tracing::warn!(%error, path, "could not write offline onboarding audio");
}
}
}
#[cfg(test)]
mod tests {
use super::super::fixture::ANSWER_JAY;
use super::*;
#[test]
fn typing_clacks_never_repeat_an_adjacent_key_sample() {
let scene = typing::Scene::default();
let mut track = SfxTrack::default();
track.on_without_hex(0.5, &scene);
track.advance_to(60.0);
let mut last_key: Option<u8> = None;
let mut key_count = 0;
let mut back_count = 0;
let mut sent = 0;
let mut read = 0;
for &(_, tone, _) in track.fired_cues() {
match tone {
Tone::Onboarding(OnboardingTone::Key(_, v)) => {
assert_ne!(last_key, Some(v), "adjacent key clacks repeated Key({v})");
last_key = Some(v);
key_count += 1;
}
Tone::Onboarding(OnboardingTone::KeyBackspace(_)) => {
last_key = None;
back_count += 1;
}
Tone::Onboarding(OnboardingTone::Sent) => sent += 1,
Tone::Onboarding(OnboardingTone::Read) => read += 1,
_ => {}
}
}
assert!(key_count >= 18, "{key_count}");
// Every delete, and the clunk under each slip onto Return.
let deletes = scene.strokes().iter().filter(|s| s.key == "delete").count();
let slips = scene
.strokes()
.iter()
.filter(|s| s.key == "return" && scene.flash(s.at + 1e-3, "return") > 0.0)
.count();
assert_eq!(back_count, deletes + slips);
assert_eq!(sent, scene.sent(scene.duration()));
assert_eq!(read, scene.reads().count());
assert!(track.fired_cues().iter().any(|&(_, t, _)| t == Tone::Error));
}
#[test]
fn without_hex_clacks_whatever_key_sound_was_picked() {
let scene = typing::Scene::default();
let mut track = SfxTrack {
style: KeySoundStyle::Silent,
..SfxTrack::default()
};
track.on_without_hex(0.0, &scene);
track.advance_to(60.0);
let styles: Vec<KeySoundStyle> = track
.fired_cues()
.iter()
.filter_map(|&(_, tone, _)| match tone {
Tone::Onboarding(
OnboardingTone::Key(style, _)
| OnboardingTone::KeySpace(style)
| OnboardingTone::KeyBackspace(style),
) => Some(style),
_ => None,
})
.collect();
assert!(!styles.is_empty());
assert!(styles.iter().all(|&s| s == KeySoundStyle::Clack));
}
#[test]
fn tapbacks_tick_and_the_heartbeat_stops_dead_at_the_removal() {
let scene = typing::Scene::default();
let mut track = SfxTrack::default();
track.on_without_hex(0.0, &scene);
track.advance_to(60.0);
let count = |cue: OnboardingTone| {
track
.fired_cues()
.iter()
.filter(|&&(_, t, _)| t == Tone::Onboarding(cue))
.count()
};
let taps = Tapback::ALL.map(|k| count(OnboardingTone::Tapback(k)));
assert_eq!(taps.iter().sum::<usize>(), scene.all_taps().len());
assert_eq!(count(OnboardingTone::Slam), scene.slams().count());
let removal = scene.removal().unwrap();
let hearts: Vec<&(f64, Tone, u8)> = track
.fired_cues()
.iter()
.filter(|&&(_, t, _)| t == Tone::Onboarding(OnboardingTone::Heartbeat))
.collect();
assert!(hearts.len() >= 10);
let noticed = scene.noticed().unwrap();
assert!(
hearts.iter().all(|&&(at, ..)| at >= noticed),
"silent until the first typo goes out"
);
assert!(
hearts
.iter()
.all(|&&(at, ..)| at + typing::BEAT_LEN <= removal)
);
assert!(
hearts.first().unwrap().2 < hearts.last().unwrap().2,
"it rises"
);
}
#[test]
fn panic_strokes_land_harder() {
let scene = typing::Scene::default();
let mut track = SfxTrack::default();
track.on_without_hex(0.0, &scene);
track.advance_to(60.0);
let first = scene.strokes()[0].at;
let last = scene
.strokes()
.iter()
.rev()
.find(|s| s.hard && s.key.len() == 1)
.unwrap()
.at;
let thuds = |at: f64| {
track
.fired_cues()
.iter()
.filter(|&&(t, tone, _)| {
(t - at).abs() < 0.01
&& matches!(tone, Tone::Onboarding(OnboardingTone::KeySpace(_)))
})
.count()
};
assert_eq!(thuds(first), 0);
assert_eq!(thuds(last), 1);
}
#[test]
fn voice_and_permission_cues_include_real_dictation_tones_and_motion_beats() {
let mut track = SfxTrack::default();
track.on_download_start(0.0);
track.on_voice_take(10.0, &ANSWER_JAY);
track.on_microphone(14.0);
track.on_accessibility(17.0);
track.on_almost_ready(21.5);
track.on_ready(28.0, false);
track.advance_to(30.0);
let tones: Vec<Tone> = track.fired_cues().iter().map(|&(_, t, _)| t).collect();
assert!(tones.contains(&Tone::Onboarding(OnboardingTone::ShortcutDown)));
assert!(tones.contains(&Tone::DictationStart));
assert!(tones.contains(&Tone::Onboarding(OnboardingTone::ShortcutUp)));
assert!(tones.contains(&Tone::DictationStop));
assert!(tones.contains(&Tone::DictationDone));
assert!(tones.contains(&Tone::Onboarding(OnboardingTone::PanelEscape)));
assert!(tones.contains(&Tone::Onboarding(OnboardingTone::PermissionTick)));
assert!(tones.contains(&Tone::Onboarding(OnboardingTone::AlmostReady)));
let built: Vec<i64> = track
.fired_cues()
.iter()
.filter(|(_, t, _)| matches!(t, Tone::Onboarding(OnboardingTone::Build(_))))
.map(|&(at, _, _)| ((at - 28.0) * 1000.0).round() as i64)
.collect();
assert_eq!(built, [0, 150, 300], "rising notes 150 ms apart");
}
#[test]
fn reduce_motion_finishes_the_logo_on_one_note() {
let mut track = SfxTrack::default();
track.on_ready(1.0, true);
track.advance_to(5.0);
assert_eq!(
track.fired_cues(),
[(1.0, Tone::Onboarding(OnboardingTone::Build(2)), 100)]
);
}
}