libgm 0.8.0

A tool for unpacking and modding GameMaker games
Documentation
// SPDX-License-Identifier: GPL-3.0-only
//! Contains GameMaker IDE Version types and abstractions to check and set versions.

use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;

use crate::prelude::*;
use crate::wad::elem::GMElement;
use crate::wad::load::reader::DataReader;
use crate::wad::save::writer::DataWriter;

/// A GameMaker Version, denoting the version of the IDE this game was created in.
///
/// This version struct is not updated by YoYo Games since GMS 2 and is
/// is stuck on `2.0.0.0` for modern versions.
/// If you need the format version of the data file, check out [`GMVersion`].
///
/// For GameMaker: Studio 1 versions, the version format is `1.0.0.BUILD`,
/// where BUILD is the internal build number of that version (yes, the minor 1-4 is not written).
/// The majority of build numbers were not released.
/// These numbers were bumped frequently in development, so they go into the hundereds.
/// They had a *stable* and *beta* branch: Beta releases were released as their actual build number,
/// whereas stable releases were relased as the build number plus 1000.
///
/// After that, they released GameMaker Studio 2.
/// They bumped this version one last time to `2.0.0.0`, where it's now stuck forever.
/// You can only retrieve an approximate version using version detection tricks, see [`GMVersion`] for that.
#[derive(Clone, Copy, PartialEq)]
pub struct IdeVersion {
    /// The most significant version part.
    ///
    /// For GameMaker: Studio 1, this will be 1.
    /// For GameMaker Studio 2, this will be 2 (and every other part will be 0).
    pub major: u32,

    /// The second-most significant version part.
    ///
    /// Always zero.
    pub minor: u32,

    /// The third-most significant version part.
    ///
    /// Always zero.
    pub release: u32,

    /// The fourth-most (least) significant version part.
    ///
    /// This is the actual relevant number for GameMaker: Studio 1.
    pub build: u32,
}

impl IdeVersion {
    pub const GMS2: Self = Self::new(2, 0, 0, 0);

    #[must_use]
    pub const fn new(major: u32, minor: u32, release: u32, build: u32) -> Self {
        Self { major, minor, release, build }
    }

    #[must_use]
    pub const fn is_beta(self) -> bool {
        self.major == 1 && self.build < 1000
    }
}

impl GMElement for IdeVersion {
    fn deserialize(reader: &mut DataReader) -> Result<Self> {
        let major = reader.read_u32()?;
        let minor = reader.read_u32()?;
        let release = reader.read_u32()?;
        let build = reader.read_u32()?;
        Ok(Self { major, minor, release, build })
    }

    fn serialize(&self, writer: &mut DataWriter) -> Result<()> {
        writer.write_u32(self.major);
        writer.write_u32(self.minor);
        writer.write_u32(self.release);
        writer.write_u32(self.build);
        Ok(())
    }
}

impl fmt::Debug for IdeVersion {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}.{}.{}.{}", self.major, self.minor, self.release, self.build)
    }
}

impl Display for IdeVersion {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let major = self.major;
        let minor = self.minor;
        let release = self.release;
        let build = self.build;

        if major == 1 {
            return if let Some(minor) = gms1_minor_by_build(build) {
                write!(f, "1.{minor}.{build}")
            } else {
                write!(f, "1.X.{build}")
            };
        }

        write!(f, "{major}.{minor}")?;
        if release != 0 || build != 0 {
            write!(f, ".{release}")?;
            if build != 0 {
                write!(f, ".{build}")?;
            }
        }
        Ok(())
    }
}

/// The version of this GameMaker data file format.
///
/// This should correspond to the WAD ("bytecode") version specified in the `GEN8` chunk,
/// until GameMaker Studio 2, where they got lazy and stopped bumping it (stuck on WAD 17).
/// Since they also don't update the GameMaker [IDE version](IdeVersion) anymore,
/// GameMaker unpacking tools like LibGM have to resort to
/// manual version detection (which sucks).
/// We can detect the approximate IDE version a game was made in,
/// which is referred to as "format version".
/// It is usually named after the first IDE version which has these format changes.
///
/// > NOTE: some of this information may be incorrect.
/// > I am not a GameMaker OG, I am desperately trying to find information on these old versions and documenting them.
///
/// Pre-GameMaker Studio versions (Mark Overmars times), such as 8.1, are not included here.
/// This GameMaker data file / WAD format was introduced in GameMaker Studio, which is what this library can parse and modify.
/// Previous (Pre-Studio) versions used a completly different way of storing game assets, and LibGM does not support them.
///
/// <https://web.archive.org/web/20150304025626/https://store.yoyogames.com/downloads/gm-studio/release-notes-studio.html>
///
/// GameMaker: Studio includes versions 1.1-1.4 and 2.0-2.3.
/// In the `GEN8` chunk, they stored the versions as `1.0.0.BUILD`,
/// where BUILD is the internal build number of that version (yes, the minor 1-4 is not written).
/// The majority of build numbers were not released. These numbers were bumped frequently in development, so they go into the hundereds.
/// They had a *stable* and *beta* branch: Beta releases were released as their actual build number,
/// whereas stable releases were relased as the build number plus 1000.
///
/// Then, they introduced GameMaker Studio 2, which changed lots of stuff
/// (least notably, removing the colon in "GameMaker: Studio").
/// They god rid of their shitty build-number versioning and actually had normal SemVer-like versioning for a while.
/// The last GameMaker Studio 2 version was 2.3 (i think) which also changed lots of stuff, most notably for GML.
/// Unfortunately, they also slowly stopped updating the WAD and IDE version fields in `GEN8`:
/// The IDE Version is now stuck on `2.0.0.0` forever.
/// The WAD version was stuck on 16 for a while. They bumped it one last time to 17, where it stayed stuck forever.
///
/// After that, they got rid of the "Studio" in the name and renamed it to just "GameMaker"
/// (same name as in Pre-Studio times, which is kind of confusing).
/// They switched their versioning system to the current `YYYY.MM.P.B`. Here is an excerpt from <https://gms-updates.gmclan.org/>:
/// > - YYYY - YEAR of release (2022 or higher)
/// > - MM - MONTH on which it was released (usually end of); beta versions are numbered as MONTH * 100 (not relevant for LibGM)
/// > - P - number of PATCH/fix (0 if it was first release)
/// > - B - total number of internal builds since May 2022 (last reset of build number was short before 2022.5 release, not every build is released to public)
/// > So, for example: 2022.6.1.53 means Update #1 for version released at end of June(6) 2022, 53rd build in total (since May 2022).
/// > There are no releases in July and December because of Holiday season peak.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
// DOCME: it would be really great if people could document which features all of these versions added :D
pub enum GMVersion {
    // !!! MAKE SURE TO ADJUST wad_version WHEN ADDING NEW PRE-WAD17 VERSIONS !!!
    /// * WAD Version 12
    /// * GameMaker Studio 1.X.867
    ///
    /// The oldest known version to me.
    /// (There are probably older versions, I'll add them when I encounter one.)
    Wad12,

    /// * WAD Version 13
    /// * GameMaker Studio 1.4 Stable: 1135, 1451
    Wad13,

    /// * WAD Version 14
    /// * GameMaker Studio 1.4 Stable: 1464, 1474, 1499, 1567, 1598, 1657
    /// * GameMaker Studio 1.4 Beta: 420, 500
    Wad14,

    /// * WAD Version 14
    /// * GameMaker Studio 1.4 Stable: 1567
    /// * GameMaker Studio 1.4 Beta: 500
    ///
    /// Already has Product ID data in EXTN.
    /// Selected Beta Build in <https://archive.org/download/GMStudio1.4.x/GMStudio-Installer-1.4.1567.exe>
    Wad14Beta,

    /// * WAD Version 15
    /// * GameMaker Studio 1.4 Stable: 1683, 1690, 1711, 1747, 1749, 1750, 1763
    /// * GameMaker Studio 1.4 Beta: 460, 477, 533
    /// * GameMaker Studio 2.0.0.0 (?????? TODO: investigate)
    Wad15,

    /// * WAD Version 16
    /// * GameMaker Studio 1.4 Stable: 1539, 1767, 1772, 1773, 1778, 1804
    /// * GameMaker Studio 1.4 Beta: 551
    Wad16,

    /// * WAD Version 16
    /// * GameMaker Studio 1.4 Stable: 9999
    /// * Maybe Studio 2.0?
    ///
    /// Has padding bytes at the end of chunks.
    Wad16Pad,

    /// * GameMaker Studio 2
    /// * WAD Version 16
    GMS2,

    /// * GameMaker Studio 2.0.6
    /// * WAD Version 16
    GMS2_0_6,

    /// * GameMaker Studio 2.2.1
    /// * WAD Version 17 (now forever)
    GMS2_2_1,
    GMS2_2_2_302,
    GMS2_3,
    GMS2_3_1,
    GMS2_3_2,
    GMS2_3_6,

    /// * GameMaker 2022.1
    /// * WAD Version 17
    ///
    /// They dropped the "Studio" in the name here and switched
    /// to a yet another different versioning system.
    GM2022_1,
    GM2022_2,
    GM2022_3,
    GM2022_5,
    GM2022_6,
    GM2022_8,

    /// * GameMaker 2022.9
    ///
    /// Same file format / features as initial 2022 LTS (2022.0.0).
    /// This is confirmed in <https://gamemaker.io/en/blog/release-2022-0#:~:text=2022%2E9>.
    GM2022_9,

    /// * GameMaker 2022 LTS: 2022.0.3
    ///
    /// **WARNING**: This is non-linear:
    /// this only introduces some features that 2022.9 - 2023.4 didn't have,
    /// but still lacks other features from 2023.1 - 2023.4.
    /// It is similar to Non-LTS 2023.6.
    ///
    /// TODO: what about 2022.0.1 and 2022.0.2 LTS?
    Lts2022_0_3,

    /// * GameMaker 2023.1
    /// * Introduces features that 2022.0.3 LTS lacks.
    GM2023_1,

    /// * GameMaker 2023.2
    /// * Introduces features that 2022.0.3 LTS lacks.
    GM2023_2,

    /// * GameMaker 2023.4
    /// * Introduces features that 2022.0.3 LTS lacks.
    GM2023_4,

    /// * GameMaker 2023.6
    ///
    /// Introduces "Line Height" for Fonts, which is also available in 2022.0.3 LTS.
    GM2023_6,

    GM2023_8,
    GM2023_11,
    GM2024_2,
    GM2024_4,
    GM2024_6,
    GM2024_8,
    GM2024_11,
    GM2024_13,
    GM2024_14,
    GM2024_14_1,

    /// * GameMaker 2026 LTS
    ///
    /// Probably the last ever GameMaker version for this WAD file format.
    GM2026_1,
}

impl GMVersion {
    /// The WAD/bytecode version of this format version.
    #[must_use]
    pub const fn wad_version(self) -> u8 {
        match self {
            Self::Wad12 => 12,
            Self::Wad13 => 13,
            Self::Wad14 | Self::Wad14Beta => 14,
            Self::Wad15 => 15,
            Self::Wad16 | Self::Wad16Pad | Self::GMS2 | Self::GMS2_0_6 => 16,
            _ => 17,
        }
    }
}

impl Display for GMVersion {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        let s = match self {
            Self::Wad12 => "WAD 12",
            Self::Wad13 => "WAD 13",
            Self::Wad14 => "WAD 14",
            Self::Wad14Beta => "WAD 14 (Beta)",
            Self::Wad15 => "WAD 15",
            Self::Wad16 => "WAD 16 (pre-GMS 2)",
            Self::Wad16Pad => "WAD 16 (GMS 1.4.9999+)",
            Self::GMS2 => "GMS 2",
            Self::GMS2_0_6 => "GMS 2.0.6",
            Self::GMS2_2_1 => "GMS 2.2.1",
            Self::GMS2_2_2_302 => "GMS 2.2.2.302",
            Self::GMS2_3 => "GMS 2.3",
            Self::GMS2_3_1 => "GMS 2.3.1",
            Self::GMS2_3_2 => "GMS 2.3.2",
            Self::GMS2_3_6 => "GMS 2.3.6",
            Self::GM2022_1 => "2022.1",
            Self::GM2022_2 => "2022.2",
            Self::GM2022_3 => "2022.3",
            Self::GM2022_5 => "2022.5",
            Self::GM2022_6 => "2022.6",
            Self::GM2022_8 => "2022.8",
            Self::GM2022_9 => "2022.9", // or 2022.0.0 LTS
            Self::Lts2022_0_3 => "2022.0.3 LTS",
            Self::GM2023_1 => "2023.1",
            Self::GM2023_2 => "2023.2",
            Self::GM2023_4 => "2023.4",
            Self::GM2023_6 => "2022.6",
            Self::GM2023_8 => "2023.8",
            Self::GM2023_11 => "2023.11",
            Self::GM2024_2 => "2024.2",
            Self::GM2024_4 => "2024.4",
            Self::GM2024_6 => "2024.6",
            Self::GM2024_8 => "2024.8",
            Self::GM2024_11 => "2024.11",
            Self::GM2024_13 => "2024.13",
            Self::GM2024_14 => "2024.14",
            Self::GM2024_14_1 => "2024.14.1",
            Self::GM2026_1 => "2026.1 LTS",
        };
        f.write_str(s)
    }
}

/// Gets the minor version part (1.X) of a GameMaker: Studio 1 build number.
///
/// Build numbers are stored in `GEN8` unlike the version minor,
/// so you can use this function to restore the missing version part.
///
/// Returns 0, 1, 2, 3 or 4 for publicly released build numbers. Returns [`None`] for everything else.
///
/// Note that build numbers were reset in GameMaker Studio 2,
/// so make sure the provided build number is actually from GM:S 1 times.
///
/// TODO: for some reason, betas in 1.4 also use numbers less than 1000? why bruh
///
/// These are the build number ranges for publicly released builds:
/// * 1.0: 23 - 342
/// * 1.1: 412 - 1089
/// * 1.2: 1113 - 1279
/// * 1.3: 1307 - 1386
/// * 1.4: 1398 - 1804, 9999
///
/// Note: Missing numbers between ends and starts are internal builds, so it's unknown which minor they belong to.
#[must_use]
#[rustfmt::skip]
pub const fn gms1_minor_by_build(build_number: u32) -> Option<u8> {
    match build_number {
        23 | 31 | 52 | 83 | 95 | 97 | 98 | 114 | 125 | 128 | 129 | 131 | 142 | 144 | 153 | 183 | 187 | 191 | 198 | 202 | 210 | 217 | 230 | 231 | 240 | 249 | 253 | 263 | 282 | 292 | 298 | 299 | 303 | 305 | 316 | 327 | 342 => Some(0),
        412 | 416 | 450 | 469 | 513 | 522 | 533 | 560 | 609 | 615 | 622 | 666 | 676 | 690 | 694 | 711 | 734 | 750 | 754 | 867 | 872 | 913 | 917 | 929 | 964 | 1013 | 1044 | 1058 | 1076 | 1089 => Some(1),
        1113 | 1130 | 1135 | 1146 | 1150 | 1161 | 1214 | 1220 | 1224 | 1262 | 1264 | 1279 => Some(2),
        1307 | 1312 | 1336 | 1344 | 1347 | 1354 | 1373 | 1379 | 1386 => Some(3),
        1398 | 1451 | 1474 | 1499 | 1514 | 1522 | 1542 | 1556 | 1567 | 1598 | 1629 | 1657 | 1675 | 1683 | 1690 | 1711 | 1749 | 1757 | 1760 | 1763 | 1767 | 1772 | 1773 | 1788 | 1804 | 9999 => Some(4),
        _ => None,
    }
}