Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

7.9 KB
Raw Blame
//! Nitro profile effects: the animated pictures Discord lays over a profile
//! card. Each effect is a shop product (`/collectibles-products/<sku>`) with
//! a few layers, every layer an animated PNG as wide as the card with its own
//! place on the effect's clock. Follows Discord web's player (module 971217,
//! read 2026-12-01).

use super::RustCord;
use discord::model::Id;
use eframe::egui::{self, vec2, Color32, Rect, Ui};
use serde_json::Value;

/// Discord holds an effect back this long after the profile opens.
const INTRO_DELAY_MS: f64 = 500.0;
/// How far the effect fades while the pointer is on the profile, and how fast.
const HOVER_OPACITY: f32 = 0.35;
const HOVER_FADE_S: f32 = 0.6;
/// `animationType`: a persistent effect leaves a still picture while it
/// can't play; an intermittent one shows nothing then.
const PERSISTENT: u64 = 1;

/// Where an effect is on its clock: (which effect, which opening, start).
type Clock = (u64, u64, f64);

/// What a layer does `time` ms into the effect.
#[derive(Debug, PartialEq)]
enum Phase {
    /// Showing, this far into its own animation; `looping` when it simply
    /// repeats with no pause.
    Showing { at: f64, looping: bool },
    /// Hidden, for this long (None: for good).
    Hidden(Option<f64>),
}

/// Discord's rule for one layer: nothing before `start`; a layer that doesn't
/// loop goes away after `duration`; one that loops with a delay plays for
/// `duration` out of every `duration + delay`.
fn phase(time: f64, start: f64, duration: f64, looped: bool, loop_delay: f64) -> Phase {
    if time < start {
        return Phase::Hidden(Some(start - time));
    }
    let at = time - start;
    if !looped {
        return if at > duration { Phase::Hidden(None) } else { Phase::Showing { at, looping: false } };
    }
    if loop_delay <= 0.0 {
        return Phase::Showing { at, looping: true };
    }
    let cycle = duration + loop_delay;
    let at = at % cycle;
    if at > duration {
        Phase::Hidden(Some(cycle - at))
    } else {
        Phase::Showing { at, looping: false }
    }
}

impl RustCord {
    /// The profile effect `user` wears (in `guild`), asking Discord what it
    /// is made of the first time.
    pub(super) fn want_profile_effect(&mut self, user: Id, guild: Option<Id>) -> Option<Id> {
        let sku = self.profile_for(user, guild)?.profile_effect()?;
        let locale = discord::http::account_locale().unwrap_or_else(|| "en-US".into());
        self.api_get_once(&format!("effect:{sku}"), format!("/collectibles-products/{sku}?locale={locale}"));
        Some(sku)
    }

    /// Draws effect `sku` over `rect`, a profile card: on top of what is in
    /// it, never taking the pointer. `opening` tells one showing of the card
    /// from the next (the effect starts over), `slot` one card from another
    /// on screen; `hovered` is whether the pointer is on the profile.
    pub(super) fn paint_profile_effect(&self, ui: &mut Ui, rect: Rect, sku: Id, opening: u64, slot: u8, hovered: bool) {
        let Some(Ok(product)) = self.api_results.get(&format!("effect:{sku}")) else { return };
        let Some(item) = product["items"].as_array().and_then(|items| items.iter().find(|i| i["effects"].is_array())) else { return };
        let mut layers: Vec<&Value> = item["effects"].as_array().map(|l| l.iter().collect()).unwrap_or_default();
        layers.sort_by_key(|l| l["zIndex"].as_i64().unwrap_or(0));
        let ctx = ui.ctx().clone();
        let fade = ctx.animate_bool_with_time(egui::Id::new(("profile_effect_hover", slot)), hovered, HOVER_FADE_S);
        let tint = Color32::WHITE.gamma_multiply(1.0 - (1.0 - HOVER_OPACITY) * fade);
        let mut canvas = ui.new_child(egui::UiBuilder::new().max_rect(rect));
        canvas.set_clip_rect(rect.intersect(ui.clip_rect()));
        // As wide as the card, as tall as the picture's shape makes it.
        let draw = |canvas: &Ui, uri: String, layer: Option<&Value>| {
            let size = egui::Image::new(uri.clone()).load_for_size(&ctx, rect.size()).ok().and_then(|p| p.size()).unwrap_or(vec2(450.0, 880.0));
            let offset = layer.map_or(vec2(0.0, 0.0), |l| vec2(l["position"]["x"].as_f64().unwrap_or(0.0) as f32, l["position"]["y"].as_f64().unwrap_or(0.0) as f32));
            let at = Rect::from_min_size(rect.min + offset, vec2(rect.width(), rect.width() * size.y / size.x.max(1.0)));
            egui::Image::new(uri).tint(tint).paint_at(canvas, at);
        };

        // Discord plays effects in its focused window only.
        if !super::animating() {
            let reduced = super::REDUCED_MOTION.load(std::sync::atomic::Ordering::Relaxed);
            if reduced || item["animationType"].as_u64() == Some(PERSISTENT) {
                if let Some(still) = item["reducedMotionSrc"].as_str().filter(|s| !s.is_empty()) {
                    draw(&canvas, still.to_string(), None);
                }
            }
            return;
        }

        // The clock starts once every layer is ready to play.
        let now = ctx.input(|i| i.time);
        let clock_id = egui::Id::new(("profile_effect_clock", slot));
        // Each layer decoded as wide as the card is on screen, not at its own size.
        let card_px = rect.width() * ctx.pixels_per_point();
        let key = |src: &str| crate::video::effect_key(src, card_px);
        let ready = layers.iter().filter_map(|l| l["src"].as_str()).all(|src| crate::video::frame_at(&ctx, &key(src), 0, false).is_some());
        let clock = ctx.data(|d| d.get_temp::<Clock>(clock_id)).filter(|c| ready && c.0 == sku.0 && c.1 == opening);
        let Some((_, _, start)) = clock else {
            ctx.data_mut(|d| d.insert_temp::<Clock>(clock_id, (sku.0, opening, now)));
            return;
        };
        let time = (now - start) * 1000.0 - INTRO_DELAY_MS;
        let mut wake: Option<f64> = None;
        for layer in layers {
            let Some(src) = layer["src"].as_str() else { continue };
            let num = |key: &str| layer[key].as_f64().unwrap_or(0.0);
            match phase(time, num("start"), num("duration"), layer["loop"].as_bool().unwrap_or(false), num("loopDelay")) {
                Phase::Showing { at, looping } => {
                    if let Some(uri) = crate::video::frame_at(&ctx, &key(src), at as u64, looping) {
                        draw(&canvas, uri, Some(layer));
                    }
                    // (A layer at its last frame asks for nothing: come back when it ends.)
                    if !looping {
                        wake = Some(wake.map_or(num("duration") - at, |w| w.min(num("duration") - at)));
                    }
                }
                Phase::Hidden(Some(ms)) => wake = Some(wake.map_or(ms, |w| w.min(ms))),
                Phase::Hidden(None) => {}
            }
        }
        if let Some(ms) = wake {
            ctx.request_repaint_after(std::time::Duration::from_secs_f64((ms.max(0.0) + 1.0) / 1000.0));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_layer_waits_plays_and_goes() {
        // An intro: plays once from 0 for 4.9 s.
        assert_eq!(phase(-500.0, 0.0, 4904.0, false, 0.0), Phase::Hidden(Some(500.0)));
        assert_eq!(phase(1000.0, 0.0, 4904.0, false, 0.0), Phase::Showing { at: 1000.0, looping: false });
        assert_eq!(phase(5000.0, 0.0, 4904.0, false, 0.0), Phase::Hidden(None));
    }

    #[test]
    fn a_looping_layer_rests_between_plays() {
        // Plays 4906 ms out of every 7906, first at 7906.
        let at = |time| phase(time, 7906.0, 4906.0, true, 3000.0);
        assert_eq!(at(7000.0), Phase::Hidden(Some(906.0)));
        assert_eq!(at(7906.0 + 100.0), Phase::Showing { at: 100.0, looping: false });
        assert_eq!(at(7906.0 + 5906.0), Phase::Hidden(Some(2000.0)));
        assert_eq!(at(7906.0 + 7906.0 + 50.0), Phase::Showing { at: 50.0, looping: false });
        // With no delay it just repeats.
        assert_eq!(phase(9000.0, 0.0, 4000.0, true, 0.0), Phase::Showing { at: 9000.0, looping: true });
    }
}