347 lines
14 KiB
Rust
347 lines
14 KiB
Rust
//! Procedural visual effects with Capri's constants: glitch schedule, CRT shader and lens,
|
|
//! dimming feather, float, sleep caption and dance sway.
|
|
use std::sync::Arc;
|
|
|
|
use eframe::egui::{self, Color32, ColorImage, Pos2, Rect, TextureId};
|
|
use eframe::egui_glow;
|
|
use eframe::glow::{self, HasContext};
|
|
use parking_lot::Mutex;
|
|
|
|
use crate::teleport::Lcg;
|
|
|
|
/// Glitch strength and offset at `now`; all times in ms.
|
|
pub struct Glitch {
|
|
pub strength: f32,
|
|
pub x: f32,
|
|
pub y: f32,
|
|
}
|
|
|
|
fn envelope(age: f64) -> f32 {
|
|
match age {
|
|
a if !(0.0..=820.0).contains(&a) => 0.0,
|
|
a if a < 85.0 => 0.96,
|
|
a if a < 170.0 => 0.22,
|
|
a if a < 310.0 => 0.86,
|
|
a if a < 430.0 => 0.08,
|
|
a => (0.48 * (1.0 - (a - 430.0) / 390.0)) as f32,
|
|
}
|
|
}
|
|
|
|
pub fn glitch(now: f64, burst_at: f64, amount: f32, interval_ms: f64, events: bool) -> Glitch {
|
|
if amount <= 0.0 {
|
|
return Glitch { strength: 0.0, x: 0.0, y: 0.0 };
|
|
}
|
|
let cycle = (now / interval_ms).floor();
|
|
let mut schedule = Lcg::new((cycle as i64 + 2078) as u32);
|
|
let ambient_age = now - cycle * interval_ms - (0.2 + schedule.next() as f64 * 0.6) * interval_ms;
|
|
let ambient = envelope(ambient_age) * 0.8;
|
|
let strength = (if events { envelope(now - burst_at) } else { 0.0 }).max(ambient) * amount;
|
|
let seed = (now / 56.0).floor() as u32;
|
|
let mut random = Lcg::new(seed);
|
|
Glitch { strength, x: (random.next() - 0.5) * 22.0 * strength, y: (random.next() - 0.5) * 5.0 * strength }
|
|
}
|
|
|
|
/// Milliseconds until the glitch needs another frame: now during a burst, else the next ambient burst.
|
|
pub fn glitch_wait_ms(now: f64, burst_at: f64, interval_ms: f64) -> f64 {
|
|
let start = |cycle: f64| cycle * interval_ms + (0.2 + Lcg::new((cycle as i64 + 2078) as u32).next() as f64 * 0.6) * interval_ms;
|
|
let cycle = (now / interval_ms).floor();
|
|
let ambient = start(cycle);
|
|
if (0.0..=820.0).contains(&(now - burst_at)) || (0.0..=820.0).contains(&(now - ambient)) {
|
|
return 33.0;
|
|
}
|
|
let next = if now < ambient { ambient } else { start(cycle + 1.0) };
|
|
(next - now).clamp(33.0, 60_000.0)
|
|
}
|
|
|
|
/// Bursts are coalesced: a new request fires only 6 s after the previous event.
|
|
pub fn request_burst(last_event: &mut f64, now: f64) {
|
|
if now - *last_event >= 6000.0 {
|
|
*last_event = now;
|
|
}
|
|
}
|
|
|
|
pub fn float_offset(now: f64, amplitude: f32, period_s: f32) -> f32 {
|
|
let phase = (now / (period_s as f64 * 1000.0)) as f32 * std::f32::consts::TAU;
|
|
amplitude * (phase.sin() * 0.75 + (phase * 0.53 + 1.4).sin() * 0.25)
|
|
}
|
|
|
|
/// `Zzz.` caption: three letters from a 3-bit counter, then 1-3 dots.
|
|
pub fn sleep_caption(elapsed_ms: f64) -> String {
|
|
let tick = (elapsed_ms.max(0.0) / 500.0).floor() as u64;
|
|
let mask = (tick / 3) % 8;
|
|
let letters: String = (0..3).map(|bit| if mask & (1 << bit) != 0 { 'Z' } else { 'z' }).collect();
|
|
letters + &".".repeat((tick % 3) as usize + 1)
|
|
}
|
|
|
|
/// Inverse CRT lens: where a window point samples the sprite.
|
|
pub const CRT_CURVATURE: f32 = 0.036;
|
|
pub fn screen_sample(p: Pos2, lens: Rect) -> Pos2 {
|
|
let x = (p.x - lens.min.x) / lens.width() * 2.0 - 1.0;
|
|
let y = (p.y - lens.min.y) / lens.height() * 2.0 - 1.0;
|
|
let scale = 1.0 + CRT_CURVATURE * (x * x + y * y);
|
|
Pos2::new(lens.min.x + (x * scale + 1.0) * lens.width() / 2.0, lens.min.y + (y * scale + 1.0) * lens.height() / 2.0)
|
|
}
|
|
|
|
#[allow(clippy::excessive_precision, reason = "Abramowitz-Stegun constants as in Capri")]
|
|
fn erf(value: f32) -> f32 {
|
|
let (sign, x) = (value.signum(), value.abs());
|
|
let t = 1.0 / (1.0 + 0.3275911 * x);
|
|
sign * (1.0 - ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * (-x * x).exp())
|
|
}
|
|
|
|
/// Gaussian edge feather of the dimming shade.
|
|
pub fn feather(distance: f32, radius: f32) -> f32 {
|
|
if radius <= 0.0 || distance >= radius {
|
|
return 1.0;
|
|
}
|
|
if distance <= 0.0 {
|
|
return 0.0;
|
|
}
|
|
((erf(distance / radius * 6.0 - 3.0) - erf(-3.0)) / (erf(3.0) - erf(-3.0))).clamp(0.0, 1.0)
|
|
}
|
|
|
|
/// Dimming mask: black with feathered alpha, at most 1024 px wide.
|
|
pub fn dimming_image(width: f32, height: f32, softness: f32) -> ColorImage {
|
|
let scale = (1024.0 / width.max(height).max(1.0)).min(1.0);
|
|
let (w, h) = (((width * scale).round() as usize).max(1), ((height * scale).round() as usize).max(1));
|
|
let radius = softness.min(width / 2.0).min(height / 2.0);
|
|
let xs: Vec<f32> = (0..w).map(|i| feather(i.min(w - 1 - i) as f32 / scale, radius)).collect();
|
|
let mut pixels = Vec::with_capacity(w * h);
|
|
for y in 0..h {
|
|
let a = feather(y.min(h - 1 - y) as f32 / scale, radius);
|
|
pixels.extend(xs.iter().map(|x| Color32::from_black_alpha((255.0 * a * x).round() as u8)));
|
|
}
|
|
ColorImage::new([w, h], pixels)
|
|
}
|
|
|
|
/// Music sway in degrees (legacy beat clock at `bpm`), held on twos at 12 fps.
|
|
pub fn dance_angle(now_ms: f64, bpm: f32, amount: f32) -> f32 {
|
|
let held = (now_ms / (1000.0 / 12.0)).floor() * (1000.0 / 12.0);
|
|
let beats = (held / 60000.0 * bpm as f64) as f32;
|
|
let (two_pi, pi) = (std::f32::consts::TAU, std::f32::consts::PI);
|
|
amount * ((two_pi * beats).sin() * 0.85 + (pi * beats).sin() * 0.22)
|
|
}
|
|
|
|
/// Presence signal labels and colours.
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
pub enum Signal {
|
|
Online,
|
|
Input,
|
|
Thinking,
|
|
Receiving,
|
|
Speaking,
|
|
Listening,
|
|
Sleeping,
|
|
}
|
|
|
|
impl Signal {
|
|
pub fn label(self) -> &'static str {
|
|
match self {
|
|
Signal::Online => "ONLINE",
|
|
Signal::Input => "TEXT INPUT",
|
|
Signal::Thinking => "THINKING",
|
|
Signal::Receiving => "RECEIVING",
|
|
Signal::Speaking => "SPEAKING",
|
|
Signal::Listening => "LISTENING",
|
|
Signal::Sleeping => "SLEEPING",
|
|
}
|
|
}
|
|
pub fn color(self) -> Color32 {
|
|
match self {
|
|
Signal::Thinking | Signal::Receiving | Signal::Speaking => crate::theme::ACID,
|
|
Signal::Sleeping => crate::theme::VIOLET,
|
|
_ => crate::theme::cyan(),
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---- CRT portrait shader (`crt-screen.mjs`), one pass through an egui_glow callback ----
|
|
|
|
const FRAGMENT: &str = r#"
|
|
uniform sampler2D image;
|
|
uniform vec2 screen;
|
|
uniform float ppp;
|
|
uniform vec4 portrait;
|
|
uniform vec4 avatar;
|
|
uniform float time;
|
|
uniform float glitch;
|
|
uniform float motion;
|
|
uniform float curvature;
|
|
float noise(vec2 p){return fract(sin(dot(p,vec2(127.1,311.7)))*43758.5453);}
|
|
vec4 sampleImage(vec2 p){
|
|
vec2 st=(p-avatar.xy)/avatar.zw;
|
|
if(st.x<0.||st.x>1.||st.y<0.||st.y>1.)return vec4(0.);
|
|
return texture2D(image,st);
|
|
}
|
|
void main(){
|
|
vec2 pixel=vec2(gl_FragCoord.x,screen.y-gl_FragCoord.y)/ppp;
|
|
vec2 st=(pixel-portrait.xy)/portrait.zw;
|
|
if(min(st.x,st.y)<0.||max(st.x,st.y)>1.)discard;
|
|
vec2 q=st*2.-1.;
|
|
vec2 warped=q*(1.+curvature*dot(q,q));
|
|
vec2 p=(warped*.5+.5)*portrait.zw+portrait.xy;
|
|
float row=floor(st.y*27.);
|
|
float seed=floor(time*17.);
|
|
float damaged=step(.69,noise(vec2(row,seed)));
|
|
p.x+=glitch*damaged*(noise(vec2(row+6.,seed))-.5)*48.;
|
|
p.x+=motion*sin(st.y*83.+time*1.3)*.32;
|
|
float split=.48+glitch*(1.4+damaged*6.);
|
|
vec4 center=sampleImage(p);
|
|
vec4 red=sampleImage(p+vec2(split,0.));
|
|
vec4 blue=sampleImage(p-vec2(split,0.));
|
|
float a=max(center.a,max(red.a,blue.a));
|
|
vec3 rgb=vec3(red.r,center.g,blue.b);
|
|
float scan=.86+.14*cos(pixel.y*2.094395);
|
|
vec3 phosphor=vec3(1.-.065*sin(pixel.x*2.094395),1.-.065*sin(pixel.x*2.094395+2.09),1.-.065*sin(pixel.x*2.094395+4.18));
|
|
float vignette=1.-.14*dot(q,q);
|
|
float flicker=1.+motion*.009*sin(time*8.2);
|
|
rgb*=scan*phosphor*vignette*1.13*flicker;
|
|
rgb+=vec3(.02,.035,.03)*noise(pixel+seed)*a;
|
|
gl_FragColor=vec4(rgb,a);
|
|
}"#;
|
|
|
|
struct Crt {
|
|
program: glow::Program,
|
|
vao: glow::VertexArray,
|
|
buffer: glow::Buffer,
|
|
}
|
|
|
|
/// `None` until first use, `Some(None)` when the shader is unavailable (plain sprite fallback).
|
|
static CRT: Mutex<Option<Option<Arc<Crt>>>> = Mutex::new(None);
|
|
|
|
unsafe fn compile(gl: &glow::Context) -> Result<Crt, String> {
|
|
unsafe {
|
|
let version = egui_glow::ShaderVersion::get(gl);
|
|
let new = version.is_new_shader_interface();
|
|
let header = format!(
|
|
"{}#ifdef GL_ES\nprecision highp float;\n#endif\n{}",
|
|
version.version_declaration(),
|
|
if new { "#define VARYING_IN in\n#define VARYING_OUT out\n#define ATTR in\n" } else { "#define VARYING_IN varying\n#define VARYING_OUT varying\n#define ATTR attribute\n" }
|
|
);
|
|
let fragment_header = if new { "out vec4 crt_color;\n#define gl_FragColor crt_color\n#define texture2D texture\n" } else { "" };
|
|
let vertex = format!("{header}ATTR vec2 position;\nvoid main(){{gl_Position=vec4(position,0.,1.);}}");
|
|
let fragment = format!("{header}{fragment_header}{FRAGMENT}");
|
|
let program = gl.create_program()?;
|
|
for (kind, source) in [(glow::VERTEX_SHADER, vertex), (glow::FRAGMENT_SHADER, fragment)] {
|
|
let shader = gl.create_shader(kind)?;
|
|
gl.shader_source(shader, &source);
|
|
gl.compile_shader(shader);
|
|
if !gl.get_shader_compile_status(shader) {
|
|
return Err(gl.get_shader_info_log(shader));
|
|
}
|
|
gl.attach_shader(program, shader);
|
|
gl.delete_shader(shader);
|
|
}
|
|
gl.bind_attrib_location(program, 0, "position");
|
|
gl.link_program(program);
|
|
if !gl.get_program_link_status(program) {
|
|
return Err(gl.get_program_info_log(program));
|
|
}
|
|
let vao = gl.create_vertex_array()?;
|
|
let buffer = gl.create_buffer()?;
|
|
gl.bind_vertex_array(Some(vao));
|
|
gl.bind_buffer(glow::ARRAY_BUFFER, Some(buffer));
|
|
let quad: [f32; 8] = [-1., -1., 1., -1., -1., 1., 1., 1.];
|
|
let bytes: Vec<u8> = quad.iter().flat_map(|f| f.to_ne_bytes()).collect();
|
|
gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, &bytes, glow::STATIC_DRAW);
|
|
gl.enable_vertex_attrib_array(0);
|
|
gl.vertex_attrib_pointer_f32(0, 2, glow::FLOAT, false, 0, 0);
|
|
gl.bind_vertex_array(None);
|
|
Ok(Crt { program, vao, buffer })
|
|
}
|
|
}
|
|
|
|
pub struct CrtParams {
|
|
pub texture: TextureId,
|
|
/// Lens rectangle (portrait viewport) and sprite rectangle, in logical px.
|
|
pub portrait: Rect,
|
|
pub avatar: Rect,
|
|
pub time: f32,
|
|
pub glitch: f32,
|
|
pub reduced: bool,
|
|
}
|
|
|
|
/// Paints the sprite through the CRT shader. Returns false when the shader is unavailable
|
|
/// (the caller then paints the plain sprite).
|
|
pub fn paint_crt(painter: &egui::Painter, p: CrtParams) -> bool {
|
|
if matches!(*CRT.lock(), Some(None)) {
|
|
return false;
|
|
}
|
|
let callback = egui_glow::CallbackFn::new(move |info, glow_painter| {
|
|
let gl = glow_painter.gl();
|
|
let crt = CRT
|
|
.lock()
|
|
.get_or_insert_with(|| match unsafe { compile(gl) } {
|
|
Ok(c) => Some(Arc::new(c)),
|
|
Err(e) => {
|
|
tracing::warn!("CRT shader unavailable: {e}");
|
|
None
|
|
}
|
|
})
|
|
.clone();
|
|
let (Some(crt), Some(texture)) = (crt, glow_painter.texture(p.texture)) else { return };
|
|
unsafe {
|
|
gl.use_program(Some(crt.program));
|
|
gl.bind_vertex_array(Some(crt.vao));
|
|
gl.active_texture(glow::TEXTURE0);
|
|
gl.bind_texture(glow::TEXTURE_2D, Some(texture));
|
|
let u = |name: &str| gl.get_uniform_location(crt.program, name);
|
|
gl.uniform_1_i32(u("image").as_ref(), 0);
|
|
gl.uniform_2_f32(u("screen").as_ref(), info.screen_size_px[0] as f32, info.screen_size_px[1] as f32);
|
|
gl.uniform_1_f32(u("ppp").as_ref(), info.pixels_per_point);
|
|
let r = |r: Rect| [r.min.x, r.min.y, r.width(), r.height()];
|
|
let [a, b, c, d] = r(p.portrait);
|
|
gl.uniform_4_f32(u("portrait").as_ref(), a, b, c, d);
|
|
let [a, b, c, d] = r(p.avatar);
|
|
gl.uniform_4_f32(u("avatar").as_ref(), a, b, c, d);
|
|
gl.uniform_1_f32(u("time").as_ref(), if p.reduced { 0.0 } else { p.time });
|
|
gl.uniform_1_f32(u("glitch").as_ref(), p.glitch);
|
|
gl.uniform_1_f32(u("motion").as_ref(), if p.reduced { 0.0 } else { 1.0 });
|
|
gl.uniform_1_f32(u("curvature").as_ref(), CRT_CURVATURE);
|
|
gl.draw_arrays(glow::TRIANGLE_STRIP, 0, 4);
|
|
gl.bind_vertex_array(None);
|
|
let _ = crt.buffer;
|
|
}
|
|
});
|
|
painter.add(egui::PaintCallback { rect: p.portrait, callback: Arc::new(callback) });
|
|
true
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn glitch_envelope_and_schedule() {
|
|
assert_eq!(envelope(-1.0), 0.0);
|
|
assert_eq!(envelope(50.0), 0.96);
|
|
assert_eq!(envelope(200.0), 0.86);
|
|
assert!((envelope(625.0) - 0.24).abs() < 1e-3);
|
|
// An event 50 ms ago at full strength wins over ambient bursts.
|
|
let g = glitch(1_000_050.0, 1_000_000.0, 1.0, 35_000.0, true);
|
|
assert!(g.strength >= 0.96 && g.x.abs() <= 11.0 * g.strength);
|
|
assert_eq!(glitch(5.0, 0.0, 0.0, 35_000.0, true).strength, 0.0);
|
|
let mut last = 0.0;
|
|
request_burst(&mut last, 7000.0);
|
|
request_burst(&mut last, 9000.0);
|
|
assert_eq!(last, 7000.0);
|
|
}
|
|
|
|
#[test]
|
|
fn captions_lens_feather() {
|
|
assert_eq!(sleep_caption(0.0), "zzz.");
|
|
assert_eq!(sleep_caption(1600.0), "Zzz.");
|
|
assert_eq!(sleep_caption(2100.0), "Zzz..");
|
|
assert_eq!(sleep_caption(3000.0), "zZz.");
|
|
let lens = Rect::from_min_size(Pos2::ZERO, [100.0, 100.0].into());
|
|
assert_eq!(screen_sample(Pos2::new(50.0, 50.0), lens), Pos2::new(50.0, 50.0));
|
|
assert!(screen_sample(Pos2::new(100.0, 100.0), lens).x > 100.0);
|
|
assert_eq!(feather(0.0, 10.0), 0.0);
|
|
assert!((feather(5.0, 10.0) - 0.5).abs() < 0.01);
|
|
assert_eq!(feather(10.0, 10.0), 1.0);
|
|
let img = dimming_image(2048.0, 100.0, 20.0);
|
|
assert_eq!(img.size, [1024, 50]);
|
|
assert!(dance_angle(0.0, 110.0, 1.0).abs() < 1e-6);
|
|
}
|
|
}
|