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        for (col, row, p) in graph.particles_at(t_ms) {
334            draw_particle(
335                img, drawn, graph, atlas, col, row, p.glyph, p.level, p.ink, false,
336            );
337        }
338    }
339    for sprite in &graph.props {
340        if sprite.kind != SpriteKind::Character {
341            draw_sprite(img, drawn, sprite, art, palette);
342        }
343    }
344    if buddy {
345        if let Some(track) = graph.character {
346            let sprite = match clock {
347                Clock::Loop(loop_ms) => graph.on_ground(loop_track(track, loop_ms).at(t_ms), t_ms),
348                _ => graph.on_ground(track.at(t_ms), t_ms),
349            };
350            if let Some(pose) = character_pose(graph, art, &sprite, t_ms, clock) {
351                // Effects go on top as an overlay (only the glyph's own pixels),
352                // so steam over a mug or sparkles over the hat stay visible.
353                draw_pose(img, drawn, &pose, palette);
354                draw_effects(img, drawn, graph, art, atlas, palette, &pose, t_ms, clock);
355            }
356        }
357    } else {
358        for sprite in &graph.unattended {
359            if sprite.kind != SpriteKind::Character {
360                draw_sprite(img, drawn, sprite, art, palette);
361            }
362        }
363    }
364}
365
366/// Draws a particle glyph in ember colour, or ink colour when `ink` (faint
367/// wisps such as steam). Normally it replaces its whole cell (background band,
368/// then the glyph); with `overlay` only the glyph's pixels are written.
369#[allow(clippy::too_many_arguments)]
370pub(crate) fn draw_particle(
371    img: &mut IndexedImage,
372    drawn: &mut Vec<PixelRect>,
373    graph: &SceneGraph,
374    atlas: &GlyphAtlas,
375    col: u32,
376    row: u32,
377    glyph: u8,
378    level: u8,
379    ink: bool,
380    overlay: bool,
381) {
382    let g = &graph.grid;
383    let shade =
384        ((u32::from(level.min(LEVELS)) * 255 + u32::from(LEVELS) / 2) / u32::from(LEVELS)) as u8;
385    let mask = atlas.mask(glyph);
386    let (x0, y0) = (g.origin_x + col * g.cell_w, g.origin_y + row * g.cell_h);
387    // Cells lie inside the image (the grid is laid out within it).
388    drawn.push(PixelRect {
389        x: x0,
390        y: y0,
391        w: g.cell_w,
392        h: g.cell_h,
393    });
394    let w = img.width as usize;
395    for my in 0..g.cell_h {
396        let y = y0 + my;
397        let rt = graph.lighting.row_terms(y);
398        for mx in 0..g.cell_w {
399            let x = x0 + mx;
400            let band = graph.lighting.band_in_row(&rt, x);
401            let lvl = ink_level(mask[(my * g.cell_w + mx) as usize], shade);
402            if overlay && lvl == 0 {
403                continue; // overlay: leave whatever is under the glyph
404            }
405            img.pixels[y as usize * w + x as usize] = match (lvl > 0, ink) {
406                (false, _) => band,
407                (true, false) => IndexedPalette::ember(band, lvl),
408                (true, true) => IndexedPalette::ink(band, lvl),
409            };
410        }
411    }
412}
413
414/// Draws a particle glyph centred on pixel `(cx, cy)` (`Clock::Smooth`): only
415/// the glyph's own pixels, over whatever is there, clipped to the image.
416#[allow(clippy::too_many_arguments)]
417pub(crate) fn draw_particle_at(
418    img: &mut IndexedImage,
419    drawn: &mut Vec<PixelRect>,
420    graph: &SceneGraph,
421    atlas: &GlyphAtlas,
422    cx: f64,
423    cy: f64,
424    glyph: u8,
425    level: u8,
426    ink: bool,
427) {
428    let g = &graph.grid;
429    let shade =
430        ((u32::from(level.min(LEVELS)) * 255 + u32::from(LEVELS) / 2) / u32::from(LEVELS)) as u8;
431    let mask = atlas.mask(glyph);
432    let x0 = (cx - f64::from(g.cell_w) / 2.0).round() as i32;
433    let y0 = (cy - f64::from(g.cell_h) / 2.0).round() as i32;
434    let x1 = x0 + g.cell_w as i32;
435    let y1 = y0 + g.cell_h as i32;
436    let Some(rect) = PixelRect::clipped(x0, y0, x1, y1, img.width, img.height) else {
437        return;
438    };
439    drawn.push(rect);
440    let w = img.width as usize;
441    for y in rect.y..rect.y + rect.h {
442        let my = (y as i32 - y0) as u32;
443        let rt = graph.lighting.row_terms(y);
444        for x in rect.x..rect.x + rect.w {
445            let mx = (x as i32 - x0) as u32;
446            let lvl = ink_level(mask[(my * g.cell_w + mx) as usize], shade);
447            if lvl == 0 {
448                continue;
449            }
450            let band = graph.lighting.band_in_row(&rt, x);
451            img.pixels[y as usize * w + x as usize] = if ink {
452                IndexedPalette::ink(band, lvl)
453            } else {
454                IndexedPalette::ember(band, lvl)
455            };
456        }
457    }
458}
459
460/// The still-frame time used for stills, thumbnails and the static wallpaper:
461/// the first moment at or after the scene's ember-based hero time (50 ms steps,
462/// up to 10 s) when the character shows the first frame of its activity's start
463/// state, so a still never catches a blink or a mid-gesture. Independent of the
464/// Buddy toggle, so toggling it keeps the same moment.
465pub fn hero_time(graph: &SceneGraph) -> u64 {
466    hero_time_with_art(graph, &BuiltinArt::for_graph(graph))
467}
468
469/// [`hero_time`] with the given art.
470pub fn hero_time_with_art(graph: &SceneGraph, art: &dyn SceneArt) -> u64 {
471    let base = graph.t_hero_ms;
472    let (Some(a), Some(_)) = (art.activity(), graph.character) else {
473        return base;
474    };
475    let character = art.character();
476    for k in 0..200u64 {
477        let t = base + k * 50;
478        let st = state_at(a, graph.seed, t, &|s| character.one_shot_ms(&a.id, s));
479        if st.state != a.animation.start {
480            continue;
481        }
482        let looping = a.animation.states.get(&st.state).is_some_and(|d| d.looping);
483        if let Some(anim) = character.animation(&a.id, &st.state)
484            && anim.frame_index_at(t - st.since_ms, looping) == 0
485        {
486            return t;
487        }
488    }
489    base
490}
491
492/// The character's current frame and where it sits on screen: the art's origin
493/// (feet row, body centre) aligned inside the layout box, mirrored when it faces
494/// left. All character art comes through `Character`.
495struct Pose<'a> {
496    frame: &'a Frame,
497    state: String,
498    /// Time into the state, in ms (thrown things fly on it).
499    elapsed: u64,
500    /// Screen pixel of the origin pixel's top-left corner.
501    x0: i32,
502    y0: i32,
503    sc: i32,
504    mirror: bool,
505}
506
507impl Pose<'_> {
508    /// Screen position of the centre of frame pixel `(col, row)`.
509    fn screen(&self, col: i32, row: i32) -> (i32, i32) {
510        let (ox, oy) = self.frame.origin();
511        let dx = (col - ox) * if self.mirror { -1 } else { 1 };
512        (
513            self.x0 + dx * self.sc + self.sc / 2,
514            self.y0 + (row - oy) * self.sc + self.sc / 2,
515        )
516    }
517}
518
519/// Picks the frame for the activity state at `t` (state machine when live, the
520/// loop script when looping) and places it.
521fn character_pose<'a>(
522    graph: &SceneGraph,
523    art: &'a dyn SceneArt,
524    s: &SpriteInstance,
525    t_ms: u64,
526    clock: Clock,
527) -> Option<Pose<'a>> {
528    let character = art.character();
529    let (anim, state, elapsed, looping) = match (art.activity(), clock) {
530        (Some(a), Clock::Loop(loop_ms)) => {
531            let script = LoopScript::new(a, character, loop_ms);
532            let (state, elapsed) = script.at(t_ms);
533            (
534                character.animation(&a.id, state),
535                state.to_string(),
536                elapsed,
537                true,
538            )
539        }
540        (Some(a), Clock::Live | Clock::Smooth) => {
541            let st = state_at(a, graph.seed, t_ms, &|state| {
542                character.one_shot_ms(&a.id, state)
543            });
544            let looping = a.animation.states.get(&st.state).is_some_and(|d| d.looping);
545            (
546                character.animation(&a.id, &st.state),
547                st.state.clone(),
548                t_ms - st.since_ms,
549                looping,
550            )
551        }
552        (None, _) => (
553            character.animation("", "idle"),
554            "idle".to_string(),
555            t_ms,
556            true,
557        ),
558    };
559    let frame = anim?.frame_at(elapsed, looping);
560    let sc = s.scale as i32;
561    Some(Pose {
562        frame,
563        state,
564        elapsed,
565        x0: s.x + (CHARACTER_BOX.0 as i32 / 2) * sc,
566        y0: s.y + (CHARACTER_BOX.1 as i32 - 1) * sc,
567        sc,
568        mirror: s.mirror,
569    })
570}
571
572/// The activity's `[[effects]]` for the current state, at their anchors on the
573/// current frame. Particles snap to cells like the embers, except with
574/// `Clock::Smooth`.
575#[allow(clippy::too_many_arguments)]
576fn draw_effects(
577    img: &mut IndexedImage,
578    drawn: &mut Vec<PixelRect>,
579    graph: &SceneGraph,
580    art: &dyn SceneArt,
581    atlas: &GlyphAtlas,
582    palette: &IndexedPalette,
583    pose: &Pose,
584    t_ms: u64,
585    clock: Clock,
586) {
587    let Some(a) = art.activity() else {
588        return;
589    };
590    let g = &graph.grid;
591    let dir = if pose.mirror { -1.0 } else { 1.0 };
592    for (i, e) in a.effects.iter().enumerate() {
593        if !e.active_in(&pose.state) {
594            continue;
595        }
596        if e.kind == "projectile" {
597            // Thrown from where the anchor is on the state's first frame, so
598            // the flight doesn't jump when the pose changes mid-air.
599            let first = art
600                .character()
601                .animation(&a.id, &pose.state)
602                .and_then(|an| an.frames.first())
603                .and_then(|f| f.anchors.get(&e.at).copied());
604            if let Some((ax, ay)) = first {
605                let (x, y) = pose.screen(ax, ay);
606                let anchor = Anchor {
607                    x,
608                    y,
609                    sc: pose.sc,
610                    dir: if pose.mirror { -1 } else { 1 },
611                    state: &pose.state,
612                };
613                draw_projectile(
614                    img,
615                    drawn,
616                    graph,
617                    atlas,
618                    palette,
619                    &e.preset,
620                    &anchor,
621                    pose.elapsed,
622                    clock,
623                );
624            }
625            continue;
626        }
627        if e.kind == "tether" {
628            if let Some(&(ax, ay)) = pose.frame.anchors.get(&e.at) {
629                let (x, y) = pose.screen(ax, ay);
630                let anchor = Anchor {
631                    x,
632                    y,
633                    sc: pose.sc,
634                    dir: if pose.mirror { -1 } else { 1 },
635                    state: &pose.state,
636                };
637                draw_tether(
638                    img, drawn, graph, atlas, palette, &e.preset, &anchor, t_ms, clock,
639                );
640            }
641            continue;
642        }
643        let (Some(&(ax, ay)), Some(preset)) =
644            (pose.frame.anchors.get(&e.at), Preset::from_id(&e.preset))
645        else {
646            continue;
647        };
648        let (cx, cy) = pose.screen(ax, ay);
649        let seed = graph.seed.wrapping_add(i as u64 + 1);
650        for p in preset_particles(preset, seed, t_ms, graph.pace) {
651            let x = f64::from(cx) + p.dx * dir * f64::from(pose.sc);
652            let y = f64::from(cy) + p.dy * f64::from(pose.sc);
653            if clock == Clock::Smooth {
654                let (gx0, gy0) = (f64::from(g.origin_x), f64::from(g.origin_y));
655                let inside = x >= gx0
656                    && y >= gy0
657                    && x < gx0 + f64::from(g.cols * g.cell_w)
658                    && y < gy0 + f64::from(g.rows * g.cell_h);
659                if inside {
660                    let steam = matches!(
661                        preset,
662                        Preset::Steam | Preset::SnowSpray | Preset::Bubbles | Preset::Drops
663                    );
664                    draw_particle_at(img, drawn, graph, atlas, x, y, p.glyph, p.level, steam);
665                }
666                continue;
667            }
668            let col = ((x - f64::from(g.origin_x)) / f64::from(g.cell_w)).floor();
669            let row = ((y - f64::from(g.origin_y)) / f64::from(g.cell_h)).floor();
670            if col < 0.0 || row < 0.0 || col >= f64::from(g.cols) || row >= f64::from(g.rows) {
671                continue;
672            }
673            draw_particle(
674                img,
675                drawn,
676                graph,
677                atlas,
678                col as u32,
679                row as u32,
680                p.glyph,
681                p.level,
682                matches!(
683                    preset,
684                    Preset::Steam | Preset::SnowSpray | Preset::Bubbles | Preset::Drops
685                ),
686                true,
687            );
688        }
689    }
690}
691
692fn draw_pose(
693    img: &mut IndexedImage,
694    drawn: &mut Vec<PixelRect>,
695    pose: &Pose,
696    palette: &IndexedPalette,
697) {
698    let f = pose.frame;
699    let (ox, oy) = f.origin();
700    let (x0, y0, sc, s) = (pose.x0, pose.y0, pose.sc, pose);
701    let (w, h) = (img.width as i32, img.height as i32);
702    // The frame's box on screen (mirroring flips it around the origin).
703    let (fw, fh) = (f.width as i32, f.height as i32);
704    let (left, right) = if s.mirror {
705        (x0 - (fw - 1 - ox) * sc, x0 + (ox + 1) * sc)
706    } else {
707        (x0 - ox * sc, x0 + (fw - ox) * sc)
708    };
709    if let Some(r) = PixelRect::clipped(
710        left,
711        y0 - oy * sc,
712        right,
713        y0 + (fh - oy) * sc,
714        img.width,
715        img.height,
716    ) {
717        drawn.push(r);
718    }
719    for row in 0..f.height {
720        for col in 0..f.width {
721            let Some(rgb) = f.pixel(col, row) else {
722                continue;
723            };
724            let idx = palette
725                .sprite_index(rgb)
726                .expect("character colour in palette");
727            let dx = (col as i32 - ox) * if s.mirror { -1 } else { 1 };
728            let px = x0 + dx * sc;
729            let py = y0 + (row as i32 - oy) * sc;
730            for y in py.max(0)..(py + sc).min(h) {
731                let line = (y * w) as usize;
732                for x in px.max(0)..(px + sc).min(w) {
733                    img.pixels[line + x as usize] = idx;
734                }
735            }
736        }
737    }
738}
739
740fn draw_sprite(
741    img: &mut IndexedImage,
742    drawn: &mut Vec<PixelRect>,
743    s: &SpriteInstance,
744    art: &dyn SceneArt,
745    palette: &IndexedPalette,
746) {
747    let Some(map) = art.prop(s.kind) else {
748        return;
749    };
750    let (w, h) = (img.width as i32, img.height as i32);
751    let scale = s.scale as i32;
752    let (mw, mh) = (map.width(), map.height());
753    if let Some(r) = PixelRect::clipped(
754        s.x,
755        s.y,
756        s.x + mw as i32 * scale,
757        s.y + mh as i32 * scale,
758        img.width,
759        img.height,
760    ) {
761        drawn.push(r);
762    }
763    for my in 0..mh {
764        for mx in 0..mw {
765            let sx = if s.mirror { mw - 1 - mx } else { mx };
766            let Some(rgb) = map.pixel(sx, my) else {
767                continue;
768            };
769            let idx = palette.sprite_index(rgb).expect("sprite colour in palette");
770            let px = s.x + mx as i32 * scale;
771            let py = s.y + my as i32 * scale;
772            for y in py.max(0)..(py + scale).min(h) {
773                let line = (y * w) as usize;
774                for x in px.max(0)..(px + scale).min(w) {
775                    img.pixels[line + x as usize] = idx;
776                }
777            }
778        }
779    }
780}