Skip to main content

clairlune_render/
frame.rs

1//! Frame compositing: the baked background plus animated elements at time `t`.
2//! Particles snap to the cell grid (exact palette, small GIF diffs); sprites use
3//! integer nearest-neighbour scaling.
4//!
5//! The activity, character and prop art come through [`SceneArt`], so the same
6//! code plays live scenes (built-in art) and saved ones (their own copy).
7//!
8//! Every draw records the rectangle it writes, so [`IncrementalFrame`] can make
9//! the next frame from the last one by restoring and redrawing only those
10//! rectangles (the live wallpaper), and report what changed.
11
12use crate::IndexedImage;
13use crate::art::{BuiltinArt, SceneArt};
14use crate::atlas::GlyphAtlas;
15use crate::clock::{Clock, LoopScript, loop_track};
16use crate::palette::{IndexedPalette, LEVELS, ink_level};
17use crate::projectile::draw_projectile;
18use crate::tether::{Anchor, draw_tether};
19use clairlune_scene::anim::state_at;
20use clairlune_scene::graph::CHARACTER_BOX;
21use clairlune_scene::particles::{Preset, preset_particles};
22use clairlune_scene::{SceneGraph, SpriteInstance, SpriteKind};
23use clairlune_sprites::Frame;
24
25/// Composites one frame at `t_ms` over a baked background (live clock).
26pub fn render_frame(
27    background: &IndexedImage,
28    graph: &SceneGraph,
29    atlas: &GlyphAtlas,
30    palette: &IndexedPalette,
31    t_ms: u64,
32) -> IndexedImage {
33    render_frame_clocked(background, graph, atlas, palette, t_ms, Clock::Live)
34}
35
36/// Like [`render_frame`], with an explicit character clock: `Clock::Loop` makes
37/// the character follow the activity's loop script for a seamless GIF.
38pub fn render_frame_clocked(
39    background: &IndexedImage,
40    graph: &SceneGraph,
41    atlas: &GlyphAtlas,
42    palette: &IndexedPalette,
43    t_ms: u64,
44    clock: Clock,
45) -> IndexedImage {
46    let art = BuiltinArt::for_graph(graph);
47    render_frame_with_art(background, graph, atlas, palette, t_ms, clock, &art)
48}
49
50/// Composites one frame with the given art (built-in, or a saved scene's).
51pub fn render_frame_with_art(
52    background: &IndexedImage,
53    graph: &SceneGraph,
54    atlas: &GlyphAtlas,
55    palette: &IndexedPalette,
56    t_ms: u64,
57    clock: Clock,
58    art: &dyn SceneArt,
59) -> IndexedImage {
60    render_frame_for(
61        background,
62        graph,
63        graph.buddy,
64        atlas,
65        palette,
66        t_ms,
67        clock,
68        art,
69    )
70}
71
72/// [`render_frame_with_art`] with an explicit Buddy toggle, so a package need
73/// not hold a second copy of its [`SceneGraph`].
74#[allow(clippy::too_many_arguments)]
75pub(crate) fn render_frame_for(
76    background: &IndexedImage,
77    graph: &SceneGraph,
78    buddy: bool,
79    atlas: &GlyphAtlas,
80    palette: &IndexedPalette,
81    t_ms: u64,
82    clock: Clock,
83    art: &dyn SceneArt,
84) -> IndexedImage {
85    let mut img = background.clone();
86    let mut drawn = Vec::new();
87    compose(
88        &mut img, &mut drawn, graph, buddy, atlas, palette, t_ms, clock, art,
89    );
90    img
91}
92
93/// A rectangle of pixels, inside the image it belongs to.
94#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
95pub struct PixelRect {
96    pub x: u32,
97    pub y: u32,
98    pub w: u32,
99    pub h: u32,
100}
101
102impl PixelRect {
103    /// `[x0, x1) x [y0, y1)` clipped to a `width x height` image; `None` when
104    /// nothing is left.
105    pub(crate) fn clipped(
106        x0: i32,
107        y0: i32,
108        x1: i32,
109        y1: i32,
110        width: u32,
111        height: u32,
112    ) -> Option<Self> {
113        let (x0, y0) = (x0.max(0), y0.max(0));
114        let (x1, y1) = (x1.min(width as i32), y1.min(height as i32));
115        (x1 > x0 && y1 > y0).then(|| PixelRect {
116            x: x0 as u32,
117            y: y0 as u32,
118            w: (x1 - x0) as u32,
119            h: (y1 - y0) as u32,
120        })
121    }
122
123    pub fn contains(&self, x: u32, y: u32) -> bool {
124        x >= self.x && x < self.x + self.w && y >= self.y && y < self.y + self.h
125    }
126}
127
128/// A frame kept between calls: each new time redraws only what the last
129/// frame and this one draw over the background. The image always equals
130/// [`render_frame_with_art`] at the last time given.
131#[derive(Clone, Debug)]
132pub struct IncrementalFrame {
133    image: IndexedImage,
134    /// What the frame drew over the background (restored before the next).
135    drawn: Vec<PixelRect>,
136}
137
138impl IncrementalFrame {
139    /// Starts as the bare background (nothing drawn yet).
140    pub fn new(background: &IndexedImage) -> Self {
141        IncrementalFrame {
142            image: background.clone(),
143            drawn: Vec::new(),
144        }
145    }
146
147    pub fn image(&self) -> &IndexedImage {
148        &self.image
149    }
150
151    /// Rectangles drawn over the background on the current frame.
152    pub fn drawn(&self) -> &[PixelRect] {
153        &self.drawn
154    }
155
156    /// Moves to `t_ms` and returns the rectangles whose pixels may have
157    /// changed (sorted, without repeats): the only ones a copy of the last
158    /// frame needs, such as a GPU texture.
159    #[allow(clippy::too_many_arguments)]
160    pub fn advance(
161        &mut self,
162        background: &IndexedImage,
163        graph: &SceneGraph,
164        atlas: &GlyphAtlas,
165        palette: &IndexedPalette,
166        t_ms: u64,
167        clock: Clock,
168        art: &dyn SceneArt,
169    ) -> Vec<PixelRect> {
170        self.advance_for(
171            background,
172            graph,
173            graph.buddy,
174            atlas,
175            palette,
176            t_ms,
177            clock,
178            art,
179        )
180    }
181
182    #[allow(clippy::too_many_arguments)]
183    pub(crate) fn advance_for(
184        &mut self,
185        background: &IndexedImage,
186        graph: &SceneGraph,
187        buddy: bool,
188        atlas: &GlyphAtlas,
189        palette: &IndexedPalette,
190        t_ms: u64,
191        clock: Clock,
192        art: &dyn SceneArt,
193    ) -> Vec<PixelRect> {
194        debug_assert_eq!(
195            (background.width, background.height),
196            (self.image.width, self.image.height)
197        );
198        let w = self.image.width as usize;
199        for r in &self.drawn {
200            for y in r.y..r.y + r.h {
201                let a = y as usize * w + r.x as usize;
202                let b = a + r.w as usize;
203                self.image.pixels[a..b].copy_from_slice(&background.pixels[a..b]);
204            }
205        }
206        let mut drawn = Vec::with_capacity(self.drawn.len());
207        compose(
208            &mut self.image,
209            &mut drawn,
210            graph,
211            buddy,
212            atlas,
213            palette,
214            t_ms,
215            clock,
216            art,
217        );
218        let mut changed: Vec<PixelRect> = self.drawn.iter().chain(&drawn).copied().collect();
219        changed.sort_unstable();
220        changed.dedup();
221        self.drawn = drawn;
222        changed
223    }
224}
225
226impl IncrementalFrame {
227    /// Like [`IncrementalFrame::advance`] for a journey, whose background
228    /// itself moves: the whole frame is redrawn (the background at `t_ms`,
229    /// then everything over it) and reported as changed.
230    #[allow(clippy::too_many_arguments)]
231    pub fn advance_journey(
232        &mut self,
233        journey: &crate::JourneyBake,
234        still: &IndexedImage,
235        graph: &SceneGraph,
236        atlas: &GlyphAtlas,
237        palette: &IndexedPalette,
238        t_ms: u64,
239        clock: Clock,
240        art: &dyn SceneArt,
241    ) -> Vec<PixelRect> {
242        self.advance_journey_for(
243            journey,
244            still,
245            graph,
246            graph.buddy,
247            atlas,
248            palette,
249            t_ms,
250            clock,
251            art,
252        )
253    }
254
255    #[allow(clippy::too_many_arguments)]
256    pub(crate) fn advance_journey_for(
257        &mut self,
258        journey: &crate::JourneyBake,
259        still: &IndexedImage,
260        graph: &SceneGraph,
261        buddy: bool,
262        atlas: &GlyphAtlas,
263        palette: &IndexedPalette,
264        t_ms: u64,
265        clock: Clock,
266        art: &dyn SceneArt,
267    ) -> Vec<PixelRect> {
268        // Only the rows the land moves through change on their own; above
269        // them, what the last frame drew (the character, particles) goes
270        // back to the still background.
271        let w = self.image.width as usize;
272        let top = journey.band_top().min(self.image.height);
273        let above = |r: &PixelRect| -> Option<PixelRect> {
274            let y1 = (r.y + r.h).min(top);
275            (r.y < y1).then(|| PixelRect { h: y1 - r.y, ..*r })
276        };
277        for r in self.drawn.iter().filter_map(above) {
278            for y in r.y..r.y + r.h {
279                let a = y as usize * w + r.x as usize;
280                let b = a + r.w as usize;
281                self.image.pixels[a..b].copy_from_slice(&still.pixels[a..b]);
282            }
283        }
284        journey.draw_band(graph, still, t_ms, &mut self.image);
285        let mut drawn = Vec::with_capacity(self.drawn.len());
286        compose(
287            &mut self.image,
288            &mut drawn,
289            graph,
290            buddy,
291            atlas,
292            palette,
293            t_ms,
294            clock,
295            art,
296        );
297        let mut changed: Vec<PixelRect> =
298            self.drawn.iter().chain(&drawn).filter_map(above).collect();
299        if top < self.image.height {
300            changed.push(PixelRect {
301                x: 0,
302                y: top,
303                w: self.image.width,
304                h: self.image.height - top,
305            });
306        }
307        changed.sort_unstable();
308        changed.dedup();
309        self.drawn = drawn;
310        changed
311    }
312}
313
314/// Draws the animated elements at `t_ms` over `img` (the background, or a
315/// frame restored to it) and records each rectangle written in `drawn`.
316#[allow(clippy::too_many_arguments)]
317fn compose(
318    img: &mut IndexedImage,
319    drawn: &mut Vec<PixelRect>,
320    graph: &SceneGraph,
321    buddy: bool,
322    atlas: &GlyphAtlas,
323    palette: &IndexedPalette,
324    t_ms: u64,
325    clock: Clock,
326    art: &dyn SceneArt,
327) {
328    if clock == Clock::Smooth {
329        for p in graph.particles_in_grid(t_ms) {
330            draw_particle_at(img, drawn, graph, atlas, p.x, p.y, p.glyph, p.level, p.ink);
331        }
332    } else {
333        // Custom pre-baked scenes (no procedural activity, character or props)
334        // draw particles as overlays so snowflakes/rain never punch cell-sized
335        // holes through the underlying picture in stills or GIF exports.
336        let overlay = graph.activity.is_none()
337            && graph.character.is_none()
338            && graph.props.is_empty()
339            && graph.unattended.is_empty();
340        for (col, row, p) in graph.particles_at(t_ms) {
341            draw_particle(
342                img, drawn, graph, atlas, col, row, p.glyph, p.level, p.ink, overlay,
343            );
344        }
345    }
346    for sprite in &graph.props {
347        if sprite.kind != SpriteKind::Character {
348            draw_sprite(img, drawn, sprite, art, palette);
349        }
350    }
351    if buddy {
352        if let Some(track) = graph.character {
353            let sprite = match clock {
354                Clock::Loop(loop_ms) => graph.on_ground(loop_track(track, loop_ms).at(t_ms), t_ms),
355                _ => graph.on_ground(track.at(t_ms), t_ms),
356            };
357            if let Some(pose) = character_pose(graph, art, &sprite, t_ms, clock) {
358                // Effects go on top as an overlay (only the glyph's own pixels),
359                // so steam over a mug or sparkles over the hat stay visible.
360                draw_pose(img, drawn, &pose, palette);
361                draw_effects(img, drawn, graph, art, atlas, palette, &pose, t_ms, clock);
362            }
363        }
364    } else {
365        for sprite in &graph.unattended {
366            if sprite.kind != SpriteKind::Character {
367                draw_sprite(img, drawn, sprite, art, palette);
368            }
369        }
370    }
371}
372
373/// Draws a particle glyph in ember colour, or ink colour when `ink` (faint
374/// wisps such as steam). Normally it replaces its whole cell (background band,
375/// then the glyph); with `overlay` only the glyph's pixels are written.
376#[allow(clippy::too_many_arguments)]
377pub(crate) fn draw_particle(
378    img: &mut IndexedImage,
379    drawn: &mut Vec<PixelRect>,
380    graph: &SceneGraph,
381    atlas: &GlyphAtlas,
382    col: u32,
383    row: u32,
384    glyph: u8,
385    level: u8,
386    ink: bool,
387    overlay: bool,
388) {
389    let g = &graph.grid;
390    let shade =
391        ((u32::from(level.min(LEVELS)) * 255 + u32::from(LEVELS) / 2) / u32::from(LEVELS)) as u8;
392    let mask = atlas.mask(glyph);
393    let (x0, y0) = (g.origin_x + col * g.cell_w, g.origin_y + row * g.cell_h);
394    // Cells lie inside the image (the grid is laid out within it).
395    drawn.push(PixelRect {
396        x: x0,
397        y: y0,
398        w: g.cell_w,
399        h: g.cell_h,
400    });
401    let w = img.width as usize;
402    for my in 0..g.cell_h {
403        let y = y0 + my;
404        let rt = graph.lighting.row_terms(y);
405        for mx in 0..g.cell_w {
406            let x = x0 + mx;
407            let band = graph.lighting.band_in_row(&rt, x);
408            let lvl = ink_level(mask[(my * g.cell_w + mx) as usize], shade);
409            if overlay && lvl == 0 {
410                continue; // overlay: leave whatever is under the glyph
411            }
412            img.pixels[y as usize * w + x as usize] = match (lvl > 0, ink) {
413                (false, _) => band,
414                (true, false) => IndexedPalette::ember(band, lvl),
415                (true, true) => IndexedPalette::ink(band, lvl),
416            };
417        }
418    }
419}
420
421/// Draws a particle glyph centred on pixel `(cx, cy)` (`Clock::Smooth`): only
422/// the glyph's own pixels, over whatever is there, clipped to the image.
423#[allow(clippy::too_many_arguments)]
424pub(crate) fn draw_particle_at(
425    img: &mut IndexedImage,
426    drawn: &mut Vec<PixelRect>,
427    graph: &SceneGraph,
428    atlas: &GlyphAtlas,
429    cx: f64,
430    cy: f64,
431    glyph: u8,
432    level: u8,
433    ink: bool,
434) {
435    let g = &graph.grid;
436    let shade =
437        ((u32::from(level.min(LEVELS)) * 255 + u32::from(LEVELS) / 2) / u32::from(LEVELS)) as u8;
438    let mask = atlas.mask(glyph);
439    let x0 = (cx - f64::from(g.cell_w) / 2.0).round() as i32;
440    let y0 = (cy - f64::from(g.cell_h) / 2.0).round() as i32;
441    let x1 = x0 + g.cell_w as i32;
442    let y1 = y0 + g.cell_h as i32;
443    let Some(rect) = PixelRect::clipped(x0, y0, x1, y1, img.width, img.height) else {
444        return;
445    };
446    drawn.push(rect);
447    let w = img.width as usize;
448    for y in rect.y..rect.y + rect.h {
449        let my = (y as i32 - y0) as u32;
450        let rt = graph.lighting.row_terms(y);
451        for x in rect.x..rect.x + rect.w {
452            let mx = (x as i32 - x0) as u32;
453            let lvl = ink_level(mask[(my * g.cell_w + mx) as usize], shade);
454            if lvl == 0 {
455                continue;
456            }
457            let band = graph.lighting.band_in_row(&rt, x);
458            img.pixels[y as usize * w + x as usize] = if ink {
459                IndexedPalette::ink(band, lvl)
460            } else {
461                IndexedPalette::ember(band, lvl)
462            };
463        }
464    }
465}
466
467/// The still-frame time used for stills, thumbnails and the static wallpaper:
468/// the first moment at or after the scene's ember-based hero time (50 ms steps,
469/// up to 10 s) when the character shows the first frame of its activity's start
470/// state, so a still never catches a blink or a mid-gesture. Independent of the
471/// Buddy toggle, so toggling it keeps the same moment.
472pub fn hero_time(graph: &SceneGraph) -> u64 {
473    hero_time_with_art(graph, &BuiltinArt::for_graph(graph))
474}
475
476/// [`hero_time`] with the given art.
477pub fn hero_time_with_art(graph: &SceneGraph, art: &dyn SceneArt) -> u64 {
478    let base = graph.t_hero_ms;
479    let (Some(a), Some(_)) = (art.activity(), graph.character) else {
480        return base;
481    };
482    let character = art.character();
483    for k in 0..200u64 {
484        let t = base + k * 50;
485        let st = state_at(a, graph.seed, t, &|s| character.one_shot_ms(&a.id, s));
486        if st.state != a.animation.start {
487            continue;
488        }
489        let looping = a.animation.states.get(&st.state).is_some_and(|d| d.looping);
490        if let Some(anim) = character.animation(&a.id, &st.state)
491            && anim.frame_index_at(t - st.since_ms, looping) == 0
492        {
493            return t;
494        }
495    }
496    base
497}
498
499/// The character's current frame and where it sits on screen: the art's origin
500/// (feet row, body centre) aligned inside the layout box, mirrored when it faces
501/// left. All character art comes through `Character`.
502struct Pose<'a> {
503    frame: &'a Frame,
504    state: String,
505    /// Time into the state, in ms (thrown things fly on it).
506    elapsed: u64,
507    /// Screen pixel of the origin pixel's top-left corner.
508    x0: i32,
509    y0: i32,
510    sc: i32,
511    mirror: bool,
512}
513
514impl Pose<'_> {
515    /// Screen position of the centre of frame pixel `(col, row)`.
516    fn screen(&self, col: i32, row: i32) -> (i32, i32) {
517        let (ox, oy) = self.frame.origin();
518        let dx = (col - ox) * if self.mirror { -1 } else { 1 };
519        (
520            self.x0 + dx * self.sc + self.sc / 2,
521            self.y0 + (row - oy) * self.sc + self.sc / 2,
522        )
523    }
524}
525
526/// Picks the frame for the activity state at `t` (state machine when live, the
527/// loop script when looping) and places it.
528fn character_pose<'a>(
529    graph: &SceneGraph,
530    art: &'a dyn SceneArt,
531    s: &SpriteInstance,
532    t_ms: u64,
533    clock: Clock,
534) -> Option<Pose<'a>> {
535    let character = art.character();
536    let (anim, state, elapsed, looping) = match (art.activity(), clock) {
537        (Some(a), Clock::Loop(loop_ms)) => {
538            let script = LoopScript::new(a, character, loop_ms);
539            let (state, elapsed) = script.at(t_ms);
540            (
541                character.animation(&a.id, state),
542                state.to_string(),
543                elapsed,
544                true,
545            )
546        }
547        (Some(a), Clock::Live | Clock::Smooth) => {
548            let st = state_at(a, graph.seed, t_ms, &|state| {
549                character.one_shot_ms(&a.id, state)
550            });
551            let looping = a.animation.states.get(&st.state).is_some_and(|d| d.looping);
552            (
553                character.animation(&a.id, &st.state),
554                st.state.clone(),
555                t_ms - st.since_ms,
556                looping,
557            )
558        }
559        (None, _) => (
560            character.animation("", "idle"),
561            "idle".to_string(),
562            t_ms,
563            true,
564        ),
565    };
566    let frame = anim?.frame_at(elapsed, looping);
567    let sc = s.scale as i32;
568    Some(Pose {
569        frame,
570        state,
571        elapsed,
572        x0: s.x + (CHARACTER_BOX.0 as i32 / 2) * sc,
573        y0: s.y + (CHARACTER_BOX.1 as i32 - 1) * sc,
574        sc,
575        mirror: s.mirror,
576    })
577}
578
579/// The activity's `[[effects]]` for the current state, at their anchors on the
580/// current frame. Particles snap to cells like the embers, except with
581/// `Clock::Smooth`.
582#[allow(clippy::too_many_arguments)]
583fn draw_effects(
584    img: &mut IndexedImage,
585    drawn: &mut Vec<PixelRect>,
586    graph: &SceneGraph,
587    art: &dyn SceneArt,
588    atlas: &GlyphAtlas,
589    palette: &IndexedPalette,
590    pose: &Pose,
591    t_ms: u64,
592    clock: Clock,
593) {
594    let Some(a) = art.activity() else {
595        return;
596    };
597    let g = &graph.grid;
598    let dir = if pose.mirror { -1.0 } else { 1.0 };
599    for (i, e) in a.effects.iter().enumerate() {
600        if !e.active_in(&pose.state) {
601            continue;
602        }
603        if e.kind == "projectile" {
604            // Thrown from where the anchor is on the state's first frame, so
605            // the flight doesn't jump when the pose changes mid-air.
606            let first = art
607                .character()
608                .animation(&a.id, &pose.state)
609                .and_then(|an| an.frames.first())
610                .and_then(|f| f.anchors.get(&e.at).copied());
611            if let Some((ax, ay)) = first {
612                let (x, y) = pose.screen(ax, ay);
613                let anchor = Anchor {
614                    x,
615                    y,
616                    sc: pose.sc,
617                    dir: if pose.mirror { -1 } else { 1 },
618                    state: &pose.state,
619                };
620                draw_projectile(
621                    img,
622                    drawn,
623                    graph,
624                    atlas,
625                    palette,
626                    &e.preset,
627                    &anchor,
628                    pose.elapsed,
629                    clock,
630                );
631            }
632            continue;
633        }
634        if e.kind == "tether" {
635            if let Some(&(ax, ay)) = pose.frame.anchors.get(&e.at) {
636                let (x, y) = pose.screen(ax, ay);
637                let anchor = Anchor {
638                    x,
639                    y,
640                    sc: pose.sc,
641                    dir: if pose.mirror { -1 } else { 1 },
642                    state: &pose.state,
643                };
644                draw_tether(
645                    img, drawn, graph, atlas, palette, &e.preset, &anchor, t_ms, clock,
646                );
647            }
648            continue;
649        }
650        let (Some(&(ax, ay)), Some(preset)) =
651            (pose.frame.anchors.get(&e.at), Preset::from_id(&e.preset))
652        else {
653            continue;
654        };
655        let (cx, cy) = pose.screen(ax, ay);
656        let seed = graph.seed.wrapping_add(i as u64 + 1);
657        for p in preset_particles(preset, seed, t_ms, graph.pace) {
658            let x = f64::from(cx) + p.dx * dir * f64::from(pose.sc);
659            let y = f64::from(cy) + p.dy * f64::from(pose.sc);
660            if clock == Clock::Smooth {
661                let (gx0, gy0) = (f64::from(g.origin_x), f64::from(g.origin_y));
662                let inside = x >= gx0
663                    && y >= gy0
664                    && x < gx0 + f64::from(g.cols * g.cell_w)
665                    && y < gy0 + f64::from(g.rows * g.cell_h);
666                if inside {
667                    let steam = matches!(
668                        preset,
669                        Preset::Steam | Preset::SnowSpray | Preset::Bubbles | Preset::Drops
670                    );
671                    draw_particle_at(img, drawn, graph, atlas, x, y, p.glyph, p.level, steam);
672                }
673                continue;
674            }
675            let col = ((x - f64::from(g.origin_x)) / f64::from(g.cell_w)).floor();
676            let row = ((y - f64::from(g.origin_y)) / f64::from(g.cell_h)).floor();
677            if col < 0.0 || row < 0.0 || col >= f64::from(g.cols) || row >= f64::from(g.rows) {
678                continue;
679            }
680            draw_particle(
681                img,
682                drawn,
683                graph,
684                atlas,
685                col as u32,
686                row as u32,
687                p.glyph,
688                p.level,
689                matches!(
690                    preset,
691                    Preset::Steam | Preset::SnowSpray | Preset::Bubbles | Preset::Drops
692                ),
693                true,
694            );
695        }
696    }
697}
698
699fn draw_pose(
700    img: &mut IndexedImage,
701    drawn: &mut Vec<PixelRect>,
702    pose: &Pose,
703    palette: &IndexedPalette,
704) {
705    let f = pose.frame;
706    let (ox, oy) = f.origin();
707    let (x0, y0, sc, s) = (pose.x0, pose.y0, pose.sc, pose);
708    let (w, h) = (img.width as i32, img.height as i32);
709    // The frame's box on screen (mirroring flips it around the origin).
710    let (fw, fh) = (f.width as i32, f.height as i32);
711    let (left, right) = if s.mirror {
712        (x0 - (fw - 1 - ox) * sc, x0 + (ox + 1) * sc)
713    } else {
714        (x0 - ox * sc, x0 + (fw - ox) * sc)
715    };
716    if let Some(r) = PixelRect::clipped(
717        left,
718        y0 - oy * sc,
719        right,
720        y0 + (fh - oy) * sc,
721        img.width,
722        img.height,
723    ) {
724        drawn.push(r);
725    }
726    for row in 0..f.height {
727        for col in 0..f.width {
728            let Some(rgb) = f.pixel(col, row) else {
729                continue;
730            };
731            let idx = palette
732                .sprite_index(rgb)
733                .expect("character colour in palette");
734            let dx = (col as i32 - ox) * if s.mirror { -1 } else { 1 };
735            let px = x0 + dx * sc;
736            let py = y0 + (row as i32 - oy) * sc;
737            for y in py.max(0)..(py + sc).min(h) {
738                let line = (y * w) as usize;
739                for x in px.max(0)..(px + sc).min(w) {
740                    img.pixels[line + x as usize] = idx;
741                }
742            }
743        }
744    }
745}
746
747fn draw_sprite(
748    img: &mut IndexedImage,
749    drawn: &mut Vec<PixelRect>,
750    s: &SpriteInstance,
751    art: &dyn SceneArt,
752    palette: &IndexedPalette,
753) {
754    let Some(map) = art.prop(s.kind) else {
755        return;
756    };
757    let (w, h) = (img.width as i32, img.height as i32);
758    let scale = s.scale as i32;
759    let (mw, mh) = (map.width(), map.height());
760    if let Some(r) = PixelRect::clipped(
761        s.x,
762        s.y,
763        s.x + mw as i32 * scale,
764        s.y + mh as i32 * scale,
765        img.width,
766        img.height,
767    ) {
768        drawn.push(r);
769    }
770    for my in 0..mh {
771        for mx in 0..mw {
772            let sx = if s.mirror { mw - 1 - mx } else { mx };
773            let Some(rgb) = map.pixel(sx, my) else {
774                continue;
775            };
776            let idx = palette.sprite_index(rgb).expect("sprite colour in palette");
777            let px = s.x + mx as i32 * scale;
778            let py = s.y + my as i32 * scale;
779            for y in py.max(0)..(py + scale).min(h) {
780                let line = (y * w) as usize;
781                for x in px.max(0)..(px + scale).min(w) {
782                    img.pixels[line + x as usize] = idx;
783                }
784            }
785        }
786    }
787}