diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 929c5c0e2..5714397b5 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -49,8 +49,25 @@ struct MusicTrack { /// Set by the decoder thread once the voice is in the mixer (or failed). ready: Arc, } +/// A sound the player could have heard (`SoundEventListener.onPlaySound`): +/// what the subtitle overlay needs. +#[derive(Clone, Debug, PartialEq)] +pub struct Heard { + /// The `subtitle` translation key of the sound event. + pub subtitle: String, + /// Where it played (None = relative to the listener, e.g. UI sounds). + pub at: Option<[f64; 3]>, + /// `SoundEngine.getRange`: infinite for relative and non-attenuated sounds. + pub range: f32, + pub looping: bool, +} pub struct Audio { _stream: Option, + /// `subtitle` keys of `sounds.json` events. + subtitles: HashMap, + /// Record `Heard` sounds (the subtitle overlay is listening). + pub record_heard: bool, + heard: Vec, mixer: Arc>, rate: u32, root: PathBuf, @@ -108,6 +125,7 @@ fn decode(path: &Path) -> Option<(Vec, u32)> { impl Audio { pub fn new(root: &Path) -> Self { let mut events = HashMap::new(); + let mut subtitles = HashMap::new(); if let Ok(text) = fs::read(root.join("assets/minecraft/sounds.json")) && let Ok(Value::Object(map)) = serde_json::from_slice::(&text) { @@ -135,6 +153,9 @@ impl Audio { }, }) .collect::>(); + if let Some(key) = def["subtitle"].as_str() { + subtitles.insert(format!("minecraft:{name}"), key.to_owned()); + } events.insert(format!("minecraft:{name}"), variants); } } @@ -151,6 +172,9 @@ impl Audio { }; Self { _stream: stream, + subtitles, + record_heard: false, + heard: Vec::new(), mixer, rate, root: root.to_owned(), @@ -279,12 +303,27 @@ impl Audio { } /// Play a sound event at a world position (None = non-positional UI sound). pub fn play(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) { - if self._stream.is_none() { - return; - } let Some(variant) = self.resolve(event, 0) else { return; }; + if self.record_heard + && let Some(key) = self.subtitles.get(event) + { + let range = if at.is_some() { + variant.attenuation * volume.max(1.0) + } else { + f32::INFINITY + }; + self.heard.push(Heard { + subtitle: key.clone(), + at, + range, + looping: false, + }); + } + if self._stream.is_none() { + return; + } let file = variant.name.trim_start_matches("minecraft:").to_owned(); let entry = self.cache.entry(file.clone()).or_insert_with(|| { decode( @@ -407,6 +446,10 @@ impl Audio { pub fn music_event(&self) -> Option<&str> { self.music.as_ref().map(|t| t.event.as_str()) } + /// The sounds played since the last call, for the subtitle overlay. + pub fn take_heard(&mut self) -> Vec { + std::mem::take(&mut self.heard) + } /// `SoundManager.updateCategoryVolume(MUSIC, gain)`. pub fn set_music_gain(&mut self, gain: f32) { if let Ok(mut m) = self.mixer.lock() { @@ -416,8 +459,18 @@ impl Audio { /// Play a relative (non-positional) tickable sound instance the caller /// keeps a handle to: ambient loops (`looping`) and sub-sounds. pub fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option { - self._stream.as_ref()?; let variant = self.resolve(event, 0)?; + if self.record_heard + && let Some(key) = self.subtitles.get(event) + { + self.heard.push(Heard { + subtitle: key.clone(), + at: None, + range: f32::INFINITY, + looping, + }); + } + self._stream.as_ref()?; let file = variant.name.trim_start_matches("minecraft:").to_owned(); let root = &self.root; let (samples, rate) = self diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index cfc0f639c..432f38d8d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -55,6 +55,7 @@ mod stats; mod stats_screen; mod storage; mod structures; +mod subtitle_hud; mod titles; mod tnt; mod totem; @@ -629,6 +630,7 @@ struct Game<'a> { mount: mounts::MountState, stats: stats::Stats, score: scoreboard::ScoreState, + subtitles: subtitle_hud::SubtitleState, adv: advancements::AdvState, stats_ui: stats_screen::StatsUi, adv_ui: advancements_screen::AdvUi, @@ -2823,6 +2825,7 @@ impl Game<'_> { self.draw_boss_bar(&mut batch); self.draw_titles(&mut batch); self.draw_scoreboard(&mut batch); + self.draw_subtitles(&mut batch); // Gui.renderVehicleHealth / the jump bar while riding a mount. let mounted = !self.creative && !spectator && self.draw_mount_hud(&mut batch, w, h); let atlas = &self.res.atlas; @@ -4369,6 +4372,7 @@ impl Game<'_> { self.position_rider(); self.tick_stats(); self.tick_scoreboard(); + self.tick_subtitles(); self.spawn_phantoms(); self.tick_advancements(); self.tick_player_model(); @@ -7690,6 +7694,7 @@ pub fn run() -> Result<()> { mount: Default::default(), stats: Default::default(), score: Default::default(), + subtitles: Default::default(), adv: Default::default(), stats_ui: Default::default(), adv_ui: Default::default(), diff --git a/crates/horizon-client/src/game/subtitle_hud.rs b/crates/horizon-client/src/game/subtitle_hud.rs new file mode 100644 index 000000000..c348f00c2 --- /dev/null +++ b/crates/horizon-client/src/game/subtitle_hud.rs @@ -0,0 +1,52 @@ +//! The subtitle overlay in the game (`Hud` -> `SubtitleOverlay`): sounds the +//! audio engine plays feed it, the HUD draws it. +use super::Game; +use horizon_client::{ + hud::HudBatch, + subtitles::{self, SubtitleOverlay}, +}; + +#[derive(Default)] +pub(super) struct SubtitleState { + overlay: SubtitleOverlay, + listening: bool, +} +impl Game<'_> { + /// Feed the sounds played since the last tick to the overlay while the + /// `showSubtitles` option is on. + pub(super) fn tick_subtitles(&mut self) { + let on = self.settings.show_subtitles; + self.audio.record_heard = on; + if !on { + if self.subtitles.listening { + self.subtitles.listening = false; + self.subtitles.overlay.clear(); + } + self.audio.take_heard(); + return; + } + self.subtitles.listening = true; + let now = subtitles::now_ms(); + let listener = self.audio.listener; + for heard in self.audio.take_heard() { + self.subtitles.overlay.on_play(&heard, listener, now); + } + self.subtitles + .overlay + .purge(f64::from(self.settings.notification_display_time), now); + } + pub(super) fn draw_subtitles(&self, batch: &mut HudBatch) { + if !self.settings.show_subtitles { + return; + } + self.subtitles.overlay.draw( + batch, + &self.res.atlas, + self.audio.listener, + self.yaw, + self.pitch, + f64::from(self.settings.notification_display_time), + subtitles::now_ms(), + ); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 6d12bb646..a0c9e5534 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -65,6 +65,7 @@ pub mod sprites; pub mod stations; pub mod streaming; pub mod structure_blocks; +pub mod subtitles; pub mod testgen; pub mod text; pub mod title; diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 68a85998e..a934e287e 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -63,6 +63,8 @@ pub enum Opt { AutoSuggestions, ReducedDebugInfo, HighContrast, + ShowSubtitles, + NotificationDisplayTime, ForceUnicode, JapaneseGlyphs, } @@ -147,6 +149,8 @@ impl Opt { Opt::AutoSuggestions => "options.autoSuggestCommands", Opt::ReducedDebugInfo => "options.reducedDebugInfo", Opt::HighContrast => "options.accessibility.high_contrast", + Opt::ShowSubtitles => "options.showSubtitles", + Opt::NotificationDisplayTime => "options.notifications.display_time", Opt::ForceUnicode => "options.forceUnicodeFont", Opt::JapaneseGlyphs => "options.japaneseGlyphVariants", } @@ -175,6 +179,7 @@ impl Opt { Opt::WeatherRadius => unit(s.weather_radius as f32, 3.0, 10.0), Opt::ChunkFade => unit(s.chunk_fade, 0.0, 2.0), Opt::MenuBlur => unit(s.menu_blur as f32, 0.0, 10.0), + Opt::NotificationDisplayTime => unit(s.notification_display_time, 0.5, 10.0), Opt::ChatOpacity => Kind::Slider(s.chat_opacity), Opt::TextBackgroundOpacity => Kind::Slider(s.text_background_opacity), Opt::ChatScale => Kind::Slider(s.chat_scale), @@ -294,6 +299,13 @@ impl Opt { chat_px(c, (s.chat_height_unfocused * 160.0 + 20.0).floor()) } Opt::ChatLineSpacing => percent(c, s.chat_line_spacing), + Opt::NotificationDisplayTime => generic( + c, + Text::tr( + "options.multiplier", + &[&format!("{:.1}", s.notification_display_time)], + ), + ), _ => generic(c, self.value_text(s)), } } @@ -356,6 +368,7 @@ impl Opt { Opt::AutoSuggestions => on_off(s.auto_suggestions), Opt::ReducedDebugInfo => on_off(s.reduced_debug_info), Opt::HighContrast => on_off(s.high_contrast), + Opt::ShowSubtitles => on_off(s.show_subtitles), Opt::ForceUnicode => on_off(s.force_unicode), Opt::JapaneseGlyphs => on_off(s.japanese_glyphs), _ => Text::empty(), @@ -383,6 +396,7 @@ impl Opt { Opt::WeatherRadius => s.weather_radius = step(3.0, 10.0) as i32, Opt::ChunkFade => s.chunk_fade = step(0.0, 40.0) / 20.0, Opt::MenuBlur => s.menu_blur = step(0.0, 10.0) as i32, + Opt::NotificationDisplayTime => s.notification_display_time = step(5.0, 100.0) / 10.0, Opt::ChatOpacity => s.chat_opacity = v, Opt::TextBackgroundOpacity => s.text_background_opacity = v, Opt::ChatScale => s.chat_scale = v, @@ -460,6 +474,7 @@ impl Opt { Opt::AutoSuggestions => s.auto_suggestions = !s.auto_suggestions, Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info, Opt::HighContrast => s.high_contrast = !s.high_contrast, + Opt::ShowSubtitles => s.show_subtitles = !s.show_subtitles, Opt::ForceUnicode => s.force_unicode = !s.force_unicode, Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs, _ => {} @@ -763,6 +778,7 @@ impl OptionsUi { let mut rows = vec![Row::Big(Opt::Volume(0))]; let others: Vec = (1..SOUND_SOURCES.len()).map(Opt::Volume).collect(); rows.extend(pairs(&others)); + rows.extend(pairs(&[Opt::ShowSubtitles])); rows } Page::Controls => { @@ -810,11 +826,13 @@ impl OptionsUi { Opt::ReducedDebugInfo, ]), Page::Accessibility => pairs(&[ + Opt::ShowSubtitles, Opt::HighContrast, Opt::MenuBlur, Opt::TextBackgroundOpacity, Opt::ChatOpacity, Opt::ChatLineSpacing, + Opt::NotificationDisplayTime, Opt::ViewBobbing, Opt::ToggleCrouch, Opt::ToggleSprint, diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 0ea0c7bdc..0fede6148 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -155,6 +155,10 @@ pub struct Settings { pub auto_suggestions: bool, pub reduced_debug_info: bool, pub high_contrast: bool, + /// `showSubtitles`: the closed-caption overlay. + pub show_subtitles: bool, + /// `notificationDisplayTime`: a multiplier for subtitle and toast times. + pub notification_display_time: f32, pub main_hand_left: bool, /// Enabled resource packs, bottom first (resourcePacks). pub resource_packs: Vec, @@ -219,6 +223,8 @@ impl Default for Settings { auto_suggestions: true, reduced_debug_info: false, high_contrast: false, + show_subtitles: false, + notification_display_time: 1.0, main_hand_left: false, resource_packs: vec!["vanilla".into()], keys: KeyBinds::default(), @@ -313,6 +319,10 @@ impl Settings { "autoSuggestions" => s.auto_suggestions = b(true), "reducedDebugInfo" => s.reduced_debug_info = b(false), "highContrast" => s.high_contrast = b(false), + "showSubtitles" => s.show_subtitles = b(false), + "notificationDisplayTime" => { + s.notification_display_time = f(1.0).clamp(0.5, 10.0); + } "mainHand" => s.main_hand_left = unquote(v) == "left", "resourcePacks" => s.resource_packs = parse_list(v), _ if k.starts_with("key_") => { @@ -405,6 +415,11 @@ impl Settings { ("toggleSprint".into(), self.toggle_sprint.to_string()), ("mouseSensitivity".into(), self.sensitivity.to_string()), ("highContrast".into(), self.high_contrast.to_string()), + ("showSubtitles".into(), self.show_subtitles.to_string()), + ( + "notificationDisplayTime".into(), + self.notification_display_time.to_string(), + ), ( "resourcePacks".into(), serde_json::to_string(&self.resource_packs).unwrap_or_else(|_| "[]".into()), @@ -526,4 +541,21 @@ mod tests { assert_eq!(again.fov, 90.0); assert_eq!(again.keys.get("key.jump"), "key.keyboard.j"); } + #[test] + fn subtitle_options() { + let s = Settings::parse("showSubtitles:true\nnotificationDisplayTime:2.5\n"); + assert!(s.show_subtitles); + assert_eq!(s.notification_display_time, 2.5); + let again = Settings::parse(&s.serialize()); + assert!(again.show_subtitles); + assert_eq!(again.notification_display_time, 2.5); + let d = Settings::parse(""); + assert!(!d.show_subtitles); + assert_eq!(d.notification_display_time, 1.0); + // The multiplier stays within the slider's range. + assert_eq!( + Settings::parse("notificationDisplayTime:50\n").notification_display_time, + 10.0 + ); + } } diff --git a/crates/horizon-client/src/subtitles.rs b/crates/horizon-client/src/subtitles.rs new file mode 100644 index 000000000..730750552 --- /dev/null +++ b/crates/horizon-client/src/subtitles.rs @@ -0,0 +1,332 @@ +//! The subtitle overlay (`SubtitleOverlay`): closed captions for the sounds +//! the player could hear, with direction arrows and a fade over the +//! notification display time. +use crate::{ + audio::Heard, + hud::{HudAtlas, HudBatch, rgba}, + text::Text, +}; + +/// How long a subtitle shows before it is dropped (milliseconds). +const DISPLAY_TIME: f64 = 3000.0; +/// Looping sounds stay at full brightness this long. +const LOOPING_FULL_BRIGHTNESS: f64 = 500.0; + +#[derive(Clone, Debug, PartialEq)] +struct PlayedAt { + location: [f64; 3], + time: u64, +} +#[derive(Clone, Debug)] +struct Subtitle { + key: String, + range: f32, + played: Vec, + looping: bool, +} +fn distance_sqr(a: [f64; 3], b: [f64; 3]) -> f64 { + (0..3).map(|i| (a[i] - b[i]).powi(2)).sum() +} +/// `Vec3.closerThan`. +fn closer_than(a: [f64; 3], b: [f64; 3], range: f32) -> bool { + distance_sqr(a, b) < f64::from(range) * f64::from(range) +} +impl Subtitle { + fn best_candidate(&self, position: [f64; 3]) -> Option<&PlayedAt> { + match self.played.len() { + 0 => None, + 1 => self.played.first(), + _ => self + .played + .iter() + .filter(|p| closer_than(p.location, position, self.range)) + .max_by(|a, b| { + a.time.cmp(&b.time).then_with(|| { + distance_sqr(a.location, position) + .total_cmp(&distance_sqr(b.location, position)) + }) + }), + } + } + fn audible_from(&self, camera: [f64; 3]) -> bool { + if self.range.is_infinite() { + return true; + } + self.best_candidate(camera) + .is_some_and(|p| closer_than(camera, p.location, self.range)) + } + fn still_active(&self, multiplier: f64, now: u64) -> bool { + let max_age = DISPLAY_TIME * multiplier; + self.played + .iter() + .any(|p| (now.saturating_sub(p.time) as f64) <= max_age) + } + /// `getBrightness`: fades from 255 to 75 over the display time. + fn brightness(&self, at: &PlayedAt, multiplier: f64, now: u64) -> i32 { + let full = if self.looping { + LOOPING_FULL_BRIGHTNESS + } else { + 0.0 + }; + let age = (now.saturating_sub(at.time) as f64 - full).max(0.0); + let t = (age / ((DISPLAY_TIME - full) * multiplier)) as f32; + let t = t.clamp(0.0, 1.0); + (255.0_f32 + (75.0_f32 - 255.0_f32) * t).floor() as i32 + } +} + +/// A row to draw. +#[derive(Clone, Debug, PartialEq)] +pub struct Row { + pub text: Text, + pub brightness: i32, + pub arrow: Arrow, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Arrow { + None, + Left, + Right, +} + +/// Milliseconds on a monotonic clock (`Util.getMillis`). +pub fn now_ms() -> u64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START + .get_or_init(std::time::Instant::now) + .elapsed() + .as_millis() as u64 +} +#[derive(Default)] +pub struct SubtitleOverlay { + subtitles: Vec, +} +impl SubtitleOverlay { + /// `onPlaySound`: a repeated subtitle refreshes its location. + pub fn on_play(&mut self, heard: &Heard, listener: [f64; 3], now: u64) { + let location = heard.at.unwrap_or(listener); + if let Some(s) = self.subtitles.iter_mut().find(|s| s.key == heard.subtitle) { + s.played.retain(|p| p.location != location); + s.played.push(PlayedAt { + location, + time: now, + }); + return; + } + self.subtitles.push(Subtitle { + key: heard.subtitle.clone(), + range: heard.range, + played: vec![PlayedAt { + location, + time: now, + }], + looping: heard.looping, + }); + } + pub fn clear(&mut self) { + self.subtitles.clear(); + } + /// `purgeOldInstances`: forget sounds older than the display time. + pub fn purge(&mut self, multiplier: f64, now: u64) { + let max_age = DISPLAY_TIME * multiplier; + for s in &mut self.subtitles { + s.played + .retain(|p| (now.saturating_sub(p.time) as f64) <= max_age); + } + } + /// The audible subtitles for a listener looking along `forward` with + /// `right` to the right, and the width the box needs. + pub fn rows( + &self, + position: [f64; 3], + forward: [f64; 3], + right: [f64; 3], + multiplier: f64, + now: u64, + ) -> Vec { + let mut out = Vec::new(); + for s in &self.subtitles { + if !(s.audible_from(position) && s.still_active(multiplier, now)) { + continue; + } + let Some(at) = s.best_candidate(position) else { + continue; + }; + let mut delta = [ + at.location[0] - position[0], + at.location[1] - position[1], + at.location[2] - position[2], + ]; + let length = distance_sqr(delta, [0.0; 3]).sqrt(); + if length >= 1.0e-4 { + delta = delta.map(|v| v / length); + } else { + delta = [0.0; 3]; + } + let dot = |a: [f64; 3]| a[0] * delta[0] + a[1] * delta[1] + a[2] * delta[2]; + let (rightness, forwardness) = (dot(right), dot(forward)); + let arrow = if forwardness > 0.5 { + Arrow::None + } else if rightness > 0.0 { + Arrow::Right + } else if rightness < 0.0 { + Arrow::Left + } else { + Arrow::None + }; + out.push(Row { + text: Text::translate(&s.key, &[]), + brightness: s.brightness(at, multiplier, now), + arrow, + }); + } + out + } + /// `extractRenderState`: the boxes at the bottom right. + #[allow(clippy::too_many_arguments)] + pub fn draw( + &self, + batch: &mut HudBatch, + atlas: &HudAtlas, + position: [f64; 3], + yaw: f32, + pitch: f32, + multiplier: f64, + now: u64, + ) { + let (forward, right) = listener_vectors(yaw, pitch); + let rows = self.rows(position, forward, right, multiplier, now); + if rows.is_empty() { + return; + } + let font = &atlas.font; + let mut width = rows + .iter() + .map(|r| font.width_text(&r.text)) + .fold(0.0_f32, f32::max); + width += font.width("<") + font.width(" ") + font.width(">") + font.width(" "); + let half_width = (width / 2.0).trunc(); + let background = rgba(0, 0, 0, (0.8 * 255.0) as u8); + for (row, r) in rows.iter().enumerate() { + let bx = batch.width - half_width - 2.0; + let by = batch.height - 35.0 - row as f32 * 10.0; + batch.fill( + atlas, + bx - half_width - 1.0, + by - 4.0 - 1.0, + half_width * 2.0 + 2.0, + 10.0, + background, + ); + let b = r.brightness.clamp(0, 255) as u8; + let color = rgba(b, b, b, 255); + match r.arrow { + Arrow::Right => { + batch.text( + atlas, + ">", + bx + half_width - font.width(">"), + by - 4.0, + color, + true, + ); + } + Arrow::Left => { + batch.text(atlas, "<", bx - half_width, by - 4.0, color, true); + } + Arrow::None => {} + } + let text_width = font.width_text(&r.text); + batch.text_styled( + atlas, + &r.text, + bx - (text_width / 2.0).trunc(), + by - 4.0, + color, + true, + ); + } + } +} +/// The listener's forward and right vectors for a Minecraft yaw and pitch +/// (degrees): `ListenerTransform.forward()` and `.right()`. +pub fn listener_vectors(yaw: f32, pitch: f32) -> ([f64; 3], [f64; 3]) { + let (yaw, pitch) = (f64::from(yaw).to_radians(), f64::from(pitch).to_radians()); + let (sy, cy, sp, cp) = (yaw.sin(), yaw.cos(), pitch.sin(), pitch.cos()); + ([-sy * cp, -sp, cy * cp], [-cy, 0.0, -sy]) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn heard(key: &str, at: Option<[f64; 3]>, range: f32) -> Heard { + Heard { + subtitle: key.into(), + at, + range, + looping: false, + } + } + const ORIGIN: [f64; 3] = [0.0; 3]; + + #[test] + fn arrows_follow_the_sound_direction() { + // Looking south (yaw 0): forward +z, right -x. + let (forward, right) = listener_vectors(0.0, 0.0); + assert_eq!(forward, [0.0, 0.0, 1.0]); + assert!((right[0] + 1.0).abs() < 1e-9); + let mut o = SubtitleOverlay::default(); + o.on_play(&heard("a", Some([0.0, 0.0, 5.0]), 16.0), ORIGIN, 0); + o.on_play(&heard("b", Some([-5.0, 0.0, 0.0]), 16.0), ORIGIN, 0); + o.on_play(&heard("c", Some([5.0, 0.0, 0.0]), 16.0), ORIGIN, 0); + let rows = o.rows(ORIGIN, forward, right, 1.0, 0); + let arrows: Vec = rows.iter().map(|r| r.arrow).collect(); + // in front, to the right (west is -x), to the left. + assert_eq!(arrows, vec![Arrow::None, Arrow::Right, Arrow::Left]); + } + + #[test] + fn range_fade_and_expiry() { + let mut o = SubtitleOverlay::default(); + let (f, r) = listener_vectors(0.0, 0.0); + o.on_play(&heard("near", Some([0.0, 0.0, 3.0]), 16.0), ORIGIN, 1000); + o.on_play(&heard("far", Some([0.0, 0.0, 40.0]), 16.0), ORIGIN, 1000); + let rows = o.rows(ORIGIN, f, r, 1.0, 1000); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].brightness, 255); + // Halfway through the display time the colour is halfway to 75. + let rows = o.rows(ORIGIN, f, r, 1.0, 2500); + assert_eq!(rows[0].brightness, 165); + // A longer notification time stretches the fade. + let rows = o.rows(ORIGIN, f, r, 2.0, 2500); + assert_eq!(rows[0].brightness, 210); + // Gone after three seconds. + assert!(o.rows(ORIGIN, f, r, 1.0, 4001).is_empty()); + } + + #[test] + fn repeats_refresh_instead_of_stacking() { + let mut o = SubtitleOverlay::default(); + let (f, r) = listener_vectors(0.0, 0.0); + o.on_play(&heard("a", Some([0.0, 0.0, 3.0]), 16.0), ORIGIN, 0); + o.on_play(&heard("a", Some([0.0, 0.0, 3.0]), 16.0), ORIGIN, 2000); + o.on_play(&heard("a", Some([0.0, 0.0, 4.0]), 16.0), ORIGIN, 2500); + let rows = o.rows(ORIGIN, f, r, 1.0, 3000); + assert_eq!(rows.len(), 1); + // The newest candidate in range is the reference for the fade. + assert_eq!(rows[0].brightness, 225); + } + + #[test] + fn looping_sounds_stay_bright_longer() { + let mut o = SubtitleOverlay::default(); + let (f, r) = listener_vectors(0.0, 0.0); + let mut h = heard("loop", None, f32::INFINITY); + h.looping = true; + o.on_play(&h, ORIGIN, 0); + assert_eq!(o.rows(ORIGIN, f, r, 1.0, 500)[0].brightness, 255); + // Non-positional sounds are always audible and never show an arrow. + assert_eq!(o.rows(ORIGIN, f, r, 1.0, 500)[0].arrow, Arrow::None); + } +}