libgm 0.8.0

A tool for unpacking and modding GameMaker games
Documentation
// SPDX-License-Identifier: GPL-3.0-only
use std::collections::HashMap;

use crate::prelude::*;
use crate::util::fmt::typename;
use crate::wad::GMVersion;
use crate::wad::data::Endianness;
use crate::wad::data::GMData;
use crate::wad::elem::GMComplexElement;
use crate::wad::elem::GMElement;
use crate::wad::save::pointers::Pointer;

// The Default value should never be read.
// This can only happen if there are zero existent chunks, though.
#[derive(Debug, Clone, Default)]
pub struct LastChunk {
    pub length_pos: u32,
    pub padding_start_pos: u32,
}

#[derive(Debug)]
pub struct DataWriter<'a> {
    /// The [`GMData`] to serialize.
    pub gm_data: &'a GMData,

    /// The raw data being generated.
    pub raw_data: Vec<u8>,

    /// Pairs data positions of pointer placeholders with the memory address of
    /// the GameMaker element they're pointing to.
    pub(super) pointer_placeholder_positions: Vec<(u32, Pointer)>,

    /// Maps memory addresses of GameMaker elements to their resolved data position.
    pub(super) pointer_resource_positions: HashMap<Pointer, u32>,

    /// Tracks where each function is used throughout the game data.
    /// Will be populated when code is serialized.
    /// - Outer Vec: Indexed by function index from `gm_data.functions`
    /// - Inner Vec: List of written positions for each occurrence
    pub function_occurrences: Vec<Vec<u32>>,

    /// Tracks where each variable is used throughout the game data.
    /// Will be populated when code is serialized.
    /// - Outer Vec: Indexed by variable index from `gm_data.variables`
    /// - Inner Vec: List of `(written_position | ref_type << 24)` for each occurrence
    pub variable_occurrences: Vec<Vec<u32>>,

    pub last_chunk: LastChunk,
}

impl<'a> DataWriter<'a> {
    pub fn new(gm_data: &'a GMData) -> Self {
        let approximated_size: usize = (f64::from(gm_data.meta.original_data_size) * 1.05) as usize;

        Self {
            gm_data,
            raw_data: Vec::with_capacity(approximated_size),
            pointer_placeholder_positions: Vec::new(),
            pointer_resource_positions: HashMap::new(),
            function_occurrences: vec![Vec::new(); gm_data.functions.len()],
            variable_occurrences: vec![Vec::new(); gm_data.variables.len()],
            last_chunk: LastChunk::default(),
        }
    }

    #[inline]
    #[must_use]
    pub fn finish(self) -> Vec<u8> {
        self.raw_data
    }

    /// The current length (aka. "position") of the internal buffer.
    #[inline]
    pub const fn pos(&self) -> u32 {
        self.raw_data.len() as u32
    }

    #[inline]
    #[must_use]
    pub const fn version(&self) -> GMVersion {
        self.gm_data.meta.version
    }

    /// Pads the internal buffer with zero bytes until its length is aligned to
    /// `alignment`.
    ///
    /// This adds zero bytes until `self.len()` is a multiple of `alignment`.
    #[inline]
    pub fn align(&mut self, alignment: u32) {
        while !self.pos().is_multiple_of(alignment) {
            self.write_u8(0);
        }
    }

    /// Appends the given bytes to the internal data buffer.
    #[inline]
    pub fn write_bytes(&mut self, data: &[u8]) {
        // It's really funny how this function is a one-liner whereas
        // reading bytes needs like 50 lines to be handled correctly...
        self.raw_data.extend_from_slice(data);
    }

    #[inline]
    pub fn write_elem<T: GMElement>(&mut self, elem: &T) -> Result<()> {
        self.write_elem_ctx(elem, ())
    }

    #[inline]
    pub fn write_elem_ctx<T: GMComplexElement>(
        &mut self,
        elem: &T,
        write_context: T::WriteContext,
    ) -> Result<()> {
        elem.serialize_complex(self, write_context)
            .ctx(|| format!("serializing {}", typename::<T>()))
    }

    /// Overwrites bytes at the given position in the internal data buffer.
    ///
    /// Useful for patching data like lengths or offsets after serialization.
    fn patch_bytes(&mut self, bytes: &[u8], position: u32) -> Result<()> {
        let start = position as usize;
        let end = start + bytes.len();
        if let Some(mut_slice) = self.raw_data.get_mut(start..end) {
            mut_slice.copy_from_slice(bytes);
            return Ok(());
        }
        Err(err!(
            "Could not overwrite {} bytes at position {} in data with length {}; out of bounds",
            bytes.len(),
            position,
            self.raw_data.len(),
        ))
    }

    /// Overwrites a 32-bit unsigned integer at the specified written data position.
    ///
    /// Useful for patching fixed-size numeric values like lengths or offsets
    /// after serialization. For writing regular pointer lists normally, see
    /// [`Self::write_pointer_list`].
    pub fn patch_u32(&mut self, number: u32, position: u32) -> Result<()> {
        let bytes: [u8; 4] = match self.gm_data.meta.endianness {
            Endianness::Little => number.to_le_bytes(),
            Endianness::Big => number.to_be_bytes(),
        };
        self.patch_bytes(&bytes, position).ctx(|| {
            format!("overwriting 32-bit number {number} at target data position {position}")
        })
    }

    /// Overwrites a 32-bit number at the specified data position with the
    /// current data position (length). The data position is calculated via
    /// `pointer_list_pos + (4 * element_index)` which is suitable for
    /// overwriting pointer in a pointer list.
    ///
    /// For overwriting other numbers, see [`Self::overwrite_u32`].
    /// For writing regular pointer lists normally, see
    /// [`Self::write_pointer_list`].
    #[inline]
    pub fn patch_pointer_list(
        &mut self,
        pointer_list_start_pos: u32,
        element_index: usize,
    ) -> Result<()> {
        let number: u32 = self.pos();
        let position: u32 = pointer_list_start_pos + 4 * element_index as u32;
        self.patch_u32(number, position).ctx(|| {
            format!(
                "overwriting pointer for element index {element_index} of pointer list with start \
                 position {pointer_list_start_pos}"
            )
        })
    }

    /// Writes a GameMaker boolean as a 32-bit integer.
    ///
    /// Writes `0` if `false` or `1` if `true`.
    #[inline]
    pub fn write_bool32(&mut self, boolean: bool) {
        self.write_u32(boolean as u32);
    }
}