Skip to main content

rm2k/
event.rs

1//! Allocation-free iteration over event and move-route command lists.
2//!
3//! [`EventCommandIter`] and [`MoveCommandIter`] walk a command list, handing back each command as
4//! a borrowed view into the input buffer: no `Vec`, no string copies, no allocator. For embedded
5//! consumers that walk a map's events, match command codes, and read strings.
6//!
7//! Event command lists are the format's oddest corner. They carry **no element count and no
8//! length prefix of their own** - the list ends at four consecutive zero bytes, which is what a
9//! command with `code == 0` looks like. Each command is:
10//!
11//! ```text
12//! varint(code) varint(indent) varint(len) len*u8 varint(n) n*varint
13//! ```
14//!
15//! Move routes are framed differently again: no terminator and no count, they simply run to the
16//! end of the enclosing chunk, and each command's payload shape depends on its own code.
17
18use crate::{
19    cursor::{ChunkIter, Ctx, Cursor, ListWalker},
20    diag::DiagKind,
21    wire,
22};
23
24/// One event command, borrowed from the input buffer.
25#[derive(Clone, Debug)]
26pub struct EventCommandRef<'a> {
27    /// The command code.
28    pub code: i32,
29    /// Nesting depth inside conditional branches and loops.
30    pub indent: i32,
31    /// The command's string operand, **verbatim**. Never transcoded; see the crate docs.
32    pub string: &'a [u8],
33    /// The raw parameter bytes, decoded lazily by [`params`](EventCommandRef::params).
34    params: &'a [u8],
35    /// How many parameters are actually in `params`: the header's count, or fewer if the payload
36    /// ran out first.
37    param_count: u32,
38}
39
40impl<'a> EventCommandRef<'a> {
41    /// Iterate the command's integer parameters.
42    ///
43    /// Decoded on demand, not collected: most consumers read one or two parameters of the few
44    /// codes they care about, and never touch the rest.
45    #[must_use]
46    #[inline]
47    pub const fn params(&self) -> ParamIter<'a> {
48        ParamIter {
49            cur: Cursor::new(self.params),
50            left: self.param_count,
51        }
52    }
53
54    /// The parameter at `index`, or `None` if the command has fewer.
55    ///
56    /// `O(index)`: compressed integers are not fixed width, so there is no direct indexing. Fine
57    /// for the small indices real code uses; iterate [`params`](EventCommandRef::params) for all.
58    #[must_use]
59    #[inline]
60    pub fn param(&self, index: usize) -> Option<i32> {
61        self.params().nth(index)
62    }
63
64    /// How many parameters the command holds. A header declaring more than the payload has room
65    /// for reports only those present (plus a [`DiagKind::ShortChunk`]),
66    /// so this is always safe to size a buffer from.
67    #[must_use]
68    #[inline]
69    pub const fn param_count(&self) -> u32 {
70        self.param_count
71    }
72
73    /// The undecoded parameter bytes.
74    ///
75    /// For carrying the parameters somewhere before decoding them. The C API returns this span so
76    /// `rm2k_event_command_param` can decode on demand without keeping the iterator alive.
77    #[must_use]
78    #[inline]
79    pub const fn raw_params(&self) -> &'a [u8] {
80        self.params
81    }
82}
83
84/// Lazily decodes an event command's integer parameters.
85#[derive(Clone, Debug)]
86pub struct ParamIter<'a> {
87    cur: Cursor<'a>,
88    left: u32,
89}
90
91impl Iterator for ParamIter<'_> {
92    type Item = i32;
93
94    #[inline]
95    fn next(&mut self) -> Option<i32> {
96        if self.left == 0 {
97            return None;
98        }
99        self.left -= 1;
100        // `left` never exceeds what the payload holds (see `EventCommandIter::next`), so the
101        // varint is always there.
102        Some(self.cur.varint().map_or(0, |v| v.value as i32))
103    }
104
105    #[inline]
106    fn size_hint(&self) -> (usize, Option<usize>) {
107        (self.left as usize, Some(self.left as usize))
108    }
109}
110
111impl ExactSizeIterator for ParamIter<'_> {}
112
113/// Walks an event command list.
114///
115/// Not an [`Iterator`], for the same reason as
116/// [`ChunkIter`]: advancing needs a [`Ctx`] to report recovery into,
117/// and `Iterator::next` has nowhere to put one.
118#[derive(Clone, Debug)]
119pub struct EventCommandIter<'a> {
120    cur: Cursor<'a>,
121    done: bool,
122}
123
124impl<'a> EventCommandIter<'a> {
125    /// Walk the command list in a chunk payload beginning at file offset `base`.
126    #[must_use]
127    #[inline]
128    pub const fn new(data: &'a [u8], base: u32) -> Self {
129        Self {
130            cur: Cursor::with_base(data, base),
131            done: false,
132        }
133    }
134
135    /// Bytes left after the list terminated.
136    #[must_use]
137    #[inline]
138    pub fn tail(&self) -> &'a [u8] {
139        self.cur.remaining()
140    }
141
142    /// Yield the next command, or `None` at the terminator or end of payload.
143    #[must_use]
144    pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<EventCommandRef<'a>> {
145        if self.done || self.cur.is_empty() {
146            self.done = true;
147            return None;
148        }
149
150        // A zero code is the terminator. The list ends with four zero bytes, being a command
151        // whose code, indent, string length and parameter count are all zero.
152        if self.cur.peek() == Some(0) {
153            self.cur.skip(4);
154            self.done = true;
155            return None;
156        }
157
158        let offset = self.cur.offset();
159        let Some(code) = self.cur.varint() else {
160            self.recover(ctx, offset);
161            return None;
162        };
163        // Only the terminator carries code 0, and it was caught above by its first byte. Any other
164        // route to 0 (an overlong or non-canonical encoding) would be written back as that
165        // terminator and cut the list short on the next load, so the list ends here instead.
166        if code.value == 0 {
167            self.recover(ctx, offset);
168            return None;
169        }
170        let Some(indent) = self.cur.varint() else {
171            self.recover(ctx, offset);
172            return None;
173        };
174        let Some(string) = self.cur.lstring() else {
175            self.recover(ctx, offset);
176            return None;
177        };
178        let Some(param_count) = self.cur.varint() else {
179            self.recover(ctx, offset);
180            return None;
181        };
182
183        // Parameters are compressed integers, so their extent is found by scanning, once here. That
184        // keeps `ParamIter` a plain decode with no bounds bookkeeping.
185        //
186        // The count is the file's claim: a command can declare billions of parameters in a few
187        // bytes, and `ParamIter` is exact-size, so collecting it would allocate for all of them.
188        // Only parameters actually present are counted.
189        let params_start = self.cur.pos();
190        let mut present = 0;
191        while present < param_count.value {
192            if self.cur.varint().is_none() {
193                ctx.report("EventCommand", 0, offset, DiagKind::ShortChunk);
194                break;
195            }
196            present += 1;
197        }
198        let params_end = self.cur.pos();
199        let params = self.cur.buf().get(params_start..params_end).unwrap_or(&[]);
200
201        Some(EventCommandRef {
202            code: code.value as i32,
203            indent: indent.value as i32,
204            string,
205            params,
206            param_count: present,
207        })
208    }
209
210    /// Resynchronize after a malformed command.
211    ///
212    /// The list has no framing to fall back on, so scan forward for 4 zero bytes.
213    fn recover(&mut self, ctx: &mut Ctx<'_>, offset: u32) {
214        ctx.report("EventCommand", 0, offset, DiagKind::EventListCorrupt);
215        let mut zeros = 0;
216        while let Some(byte) = self.cur.u8() {
217            zeros = if byte == 0 { zeros + 1 } else { 0 };
218            if zeros == 4 {
219                break;
220            }
221        }
222        self.done = true;
223    }
224}
225
226/// One move-route command, borrowed from the input buffer.
227///
228/// Unlike an event command, a move command's payload shape depends on its own code: most codes
229/// carry nothing, two carry one integer, and two carry a string followed by one or three integers.
230#[derive(Clone, Debug, Default)]
231pub struct MoveCommandRef<'a> {
232    /// The command code. See [`move_code`] for the ones that carry operands.
233    pub code: i32,
234    /// The string operand, verbatim. Empty for every code that does not carry one.
235    pub string: &'a [u8],
236    /// First integer operand, or `0`.
237    pub parameter_a: i32,
238    /// Second integer operand, or `0`.
239    pub parameter_b: i32,
240    /// Third integer operand, or `0`.
241    pub parameter_c: i32,
242}
243
244/// The move-route command codes whose payload is not empty.
245///
246/// Only these four change how many bytes a move command occupies, so they are the only ones the
247/// codec names.
248pub mod move_code {
249    /// Turns a switch on; carries one integer.
250    pub const SWITCH_ON: i32 = 32;
251    /// Turns a switch off; carries one integer.
252    pub const SWITCH_OFF: i32 = 33;
253    /// Changes the event's sprite; carries a string and one integer.
254    pub const CHANGE_GRAPHIC: i32 = 34;
255    /// Plays a sound effect; carries a string and three integers.
256    pub const PLAY_SOUND_EFFECT: i32 = 35;
257}
258
259/// Walks a move route's command list.
260///
261/// The list has neither a count nor a terminator: it runs to the end of the enclosing chunk.
262#[derive(Clone, Debug)]
263pub struct MoveCommandIter<'a> {
264    cur: Cursor<'a>,
265}
266
267impl<'a> MoveCommandIter<'a> {
268    /// Walk the move commands in a chunk payload beginning at file offset `base`.
269    #[must_use]
270    #[inline]
271    pub const fn new(data: &'a [u8], base: u32) -> Self {
272        Self {
273            cur: Cursor::with_base(data, base),
274        }
275    }
276
277    /// Yield the next command, or `None` at the end of the payload.
278    #[must_use]
279    pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<MoveCommandRef<'a>> {
280        if self.cur.is_empty() {
281            return None;
282        }
283
284        let offset = self.cur.offset();
285        let code = self.cur.varint()?.value as i32;
286        let mut out = MoveCommandRef {
287            code,
288            ..MoveCommandRef::default()
289        };
290
291        let ok = match code {
292            move_code::SWITCH_ON | move_code::SWITCH_OFF => self.read_ints(&mut out, 1),
293            move_code::CHANGE_GRAPHIC => self.read_string(&mut out) && self.read_ints(&mut out, 1),
294            move_code::PLAY_SOUND_EFFECT => self.read_string(&mut out) && self.read_ints(&mut out, 3),
295            _ => true,
296        };
297
298        if !ok {
299            ctx.report("MoveCommand", 0, offset, DiagKind::ShortChunk);
300        }
301        Some(out)
302    }
303
304    fn read_string(&mut self, out: &mut MoveCommandRef<'a>) -> bool {
305        match self.cur.lstring() {
306            Some(s) => {
307                out.string = s;
308                true
309            }
310            None => false,
311        }
312    }
313
314    fn read_ints(&mut self, out: &mut MoveCommandRef<'a>, count: usize) -> bool {
315        for slot in [&mut out.parameter_a, &mut out.parameter_b, &mut out.parameter_c]
316            .into_iter()
317            .take(count)
318        {
319            match self.cur.varint() {
320                Some(v) => *slot = v.value as i32,
321                None => return false,
322            }
323        }
324        true
325    }
326}
327
328/// Encoded length of one event command.
329///
330/// Exposed so a caller sizing a buffer for [`SliceSink`](crate::sink::SliceSink) can do it
331/// without allocating.
332#[must_use]
333pub fn event_command_len(code: i32, indent: i32, string_len: usize, params: &[i32]) -> u32 {
334    let mut total = wire::varint_len(code as u32)
335        + wire::varint_len(indent as u32)
336        + wire::varint_len(string_len as u32)
337        + string_len as u32
338        + wire::varint_len(params.len() as u32);
339    for &p in params {
340        total += wire::varint_len(p as u32);
341    }
342    total
343}
344
345/// The chunk ids on the route from a file root down to a command list.
346///
347/// Reaching an event command means walking `Map` -> `Event` -> `EventPage` -> commands. The core
348/// tier has no typed structs for that (they need `alloc`), so the few ids on the route are named
349/// here rather than hardcoded by callers.
350///
351/// Deliberately not the full set: liblcf generates 2 960 lines of chunk-id enums across four
352/// `chunks.h` files, and nothing in the core tier needs the other ~1 190 ids. For any other chunk,
353/// use the `alloc` tier's typed structs.
354pub mod path {
355    /// `Map::events` - a list of `Event`.
356    pub const MAP_EVENTS: u32 = 0x51;
357    /// `Event::pages` - a list of `EventPage`.
358    pub const EVENT_PAGES: u32 = 0x05;
359    /// `EventPage::event_commands`.
360    pub const EVENT_PAGE_COMMANDS: u32 = 0x34;
361
362    /// `Database::commonevents` - a list of `CommonEvent`.
363    pub const DATABASE_COMMON_EVENTS: u32 = 0x19;
364    /// `CommonEvent::event_commands`.
365    pub const COMMON_EVENT_COMMANDS: u32 = 0x16;
366
367    /// `Database::troops` - a list of `Troop`.
368    pub const DATABASE_TROOPS: u32 = 0x0F;
369    /// `Troop::pages` - a list of `TroopPage`.
370    pub const TROOP_PAGES: u32 = 0x0B;
371    /// `TroopPage::event_commands`.
372    pub const TROOP_PAGE_COMMANDS: u32 = 0x0C;
373}
374
375/// Where a command list was found.
376#[derive(Clone, Copy, Debug, Eq, PartialEq)]
377pub struct CommandListAt<'a> {
378    /// Id of the owning event, common event or troop.
379    pub owner_id: i32,
380    /// Id of the owning page, or `0` for a common event, which has no pages.
381    pub page_id: i32,
382    /// The command list's payload.
383    pub commands: &'a [u8],
384    /// File-absolute offset of `commands`.
385    pub offset: u32,
386}
387
388impl<'a> CommandListAt<'a> {
389    /// Walk the commands.
390    ///
391    /// Not `iter`: the result is not an [`Iterator`], since advancing needs a [`Ctx`] to report
392    /// recovery into.
393    #[must_use]
394    #[inline]
395    pub const fn commands(&self) -> EventCommandIter<'a> {
396        EventCommandIter::new(self.commands, self.offset)
397    }
398}
399
400/// Which nesting shape a root's command lists have.
401#[derive(Clone, Copy, Debug)]
402enum Shape {
403    /// Root -> list -> page -> commands (maps, troops).
404    Paged { outer: u32, pages: u32, commands: u32 },
405    /// Root -> list -> commands (common events).
406    Flat { outer: u32, commands: u32 },
407}
408
409/// Finds every event command list under a file root, without allocating.
410///
411/// What makes the core tier usable for real work. liblcf cannot express it: reaching one map's
412/// commands means parsing the whole `rpg::Map` into `std::vector`s, copying every string. Here the
413/// traversal is spans into the caller's buffer, so it runs on a microcontroller against a
414/// memory-mapped file.
415///
416/// ```
417/// # use rm2k::{event::CommandLists, Ctx, Engine, NullSink};
418/// # let map_body: &[u8] = &[0];
419/// let mut sink = NullSink;
420/// let mut ctx = Ctx::new(Engine::R2K, &mut sink);
421/// let mut lists = CommandLists::in_map(map_body, 0, &mut ctx);
422/// while let Some(list) = lists.next(&mut ctx) {
423///     let mut commands = list.commands();
424///     while let Some(command) = commands.next(&mut ctx) {
425///         let _ = (command.code, command.string);
426///     }
427/// }
428/// ```
429#[derive(Clone, Debug)]
430pub struct CommandLists<'a> {
431    shape: Shape,
432    outer: Option<ListWalker<'a>>,
433    inner: Option<ListWalker<'a>>,
434    owner_id: i32,
435    name: &'static str,
436}
437
438impl<'a> CommandLists<'a> {
439    /// Every command list in a map, from its root chunk stream.
440    ///
441    /// `body` is the map's chunk stream: what [`load_map`](crate::file::load_map) parses, minus the
442    /// file header.
443    #[must_use]
444    pub fn in_map(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>) -> Self {
445        Self::start(
446            body,
447            base,
448            ctx,
449            "Map",
450            Shape::Paged {
451                outer: path::MAP_EVENTS,
452                pages: path::EVENT_PAGES,
453                commands: path::EVENT_PAGE_COMMANDS,
454            },
455        )
456    }
457
458    /// Every common event's command list, from a database's chunk stream.
459    #[must_use]
460    pub fn in_common_events(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>) -> Self {
461        Self::start(
462            body,
463            base,
464            ctx,
465            "CommonEvent",
466            Shape::Flat {
467                outer: path::DATABASE_COMMON_EVENTS,
468                commands: path::COMMON_EVENT_COMMANDS,
469            },
470        )
471    }
472
473    /// Every troop page's command list, from a database's chunk stream.
474    #[must_use]
475    pub fn in_battle_events(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>) -> Self {
476        Self::start(
477            body,
478            base,
479            ctx,
480            "Troop",
481            Shape::Paged {
482                outer: path::DATABASE_TROOPS,
483                pages: path::TROOP_PAGES,
484                commands: path::TROOP_PAGE_COMMANDS,
485            },
486        )
487    }
488
489    fn start(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>, name: &'static str, shape: Shape) -> Self {
490        let outer_id = match shape {
491            Shape::Paged { outer, .. } | Shape::Flat { outer, .. } => outer,
492        };
493        let outer = ChunkIter::find(body, base, outer_id, ctx, name)
494            .map(|chunk| ListWalker::new(chunk.data, chunk.offset, ctx, name));
495        Self {
496            shape,
497            outer,
498            inner: None,
499            owner_id: 0,
500            name,
501        }
502    }
503
504    /// Yield the next command list.
505    #[must_use]
506    pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<CommandListAt<'a>> {
507        loop {
508            // Drain the current owner's pages before advancing to the next owner.
509            if let Some(inner) = self.inner.as_mut() {
510                if let Some(page) = inner.next(ctx) {
511                    let Shape::Paged { commands, .. } = self.shape else {
512                        unreachable!("inner walker only exists for a paged shape")
513                    };
514                    if let Some(chunk) = page.find(commands, ctx, self.name) {
515                        return Some(CommandListAt {
516                            owner_id: self.owner_id,
517                            page_id: page.id,
518                            commands: chunk.data,
519                            offset: chunk.offset,
520                        });
521                    }
522                    continue;
523                }
524                self.inner = None;
525            }
526
527            let owner = self.outer.as_mut()?.next(ctx)?;
528            self.owner_id = owner.id;
529
530            match self.shape {
531                Shape::Flat { commands, .. } => {
532                    if let Some(chunk) = owner.find(commands, ctx, self.name) {
533                        return Some(CommandListAt {
534                            owner_id: owner.id,
535                            page_id: 0,
536                            commands: chunk.data,
537                            offset: chunk.offset,
538                        });
539                    }
540                }
541                Shape::Paged { pages, .. } => {
542                    if let Some(chunk) = owner.find(pages, ctx, self.name) {
543                        self.inner = Some(ListWalker::new(chunk.data, chunk.offset, ctx, self.name));
544                    }
545                }
546            }
547        }
548    }
549}