aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-assets/src/object_descriptions.rs
blob: 59c4e88e2829c7b56b4f350d1dcbea070e28798a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//! Short names from the original object's description library.

use crate::ui_configuration::read;
use fparkan_nres::{decode, NresDocument, ReadProfile};
use fparkan_vfs::Vfs;

const DESCRIPTION: u32 = u32::from_le_bytes(*b"DSCR");

pub struct ObjectDescriptions(NresDocument);

impl ObjectDescriptions {
    pub fn load(vfs: &dyn Vfs) -> Result<Self, String> {
        decode(read(vfs, "objects.dlb")?, ReadProfile::Strict)
            .map(Self)
            .map_err(|error| error.to_string())
    }

    /// The catalogue's `#1` field, kept in the game's text encoding.
    #[must_use]
    pub fn short_name(&self, prototype: &[u8]) -> Option<&[u8]> {
        let id = self.0.find_bytes(prototype)?;
        if self.0.entry(id)?.meta().type_id != DESCRIPTION {
            return None;
        }
        short_name(self.0.payload(id).ok()?)
    }
}

fn short_name(description: &[u8]) -> Option<&[u8]> {
    description
        .split(|&byte| matches!(byte, b'\n' | b'\r' | 0))
        .find_map(|line| line.strip_prefix(b"#1").filter(|name| !name.is_empty()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use fparkan_vfs::DirectoryVfs;

    #[test]
    fn keeps_the_short_name_bytes_and_ignores_the_long_name() {
        assert_eq!(
            short_name(b"//catalogue\r\n#1MRL 1\r\n#2long name\0"),
            Some(b"MRL 1".as_slice())
        );
        assert_eq!(short_name(b"#2long name only\r\n"), None);
    }

    #[test]
    #[ignore = "requires licensed corpus"]
    fn original_flying_warbot_prototypes_use_the_native_short_names() {
        let root = std::env::var_os("FPARKAN_CORPUS_PART1_ROOT").expect("licensed corpus");
        let descriptions = ObjectDescriptions::load(&DirectoryVfs::new(root)).unwrap();
        assert_eq!(
            descriptions.short_name(b"E_GUN_MC_21"),
            Some(b"MDRLas".as_slice())
        );
        assert_eq!(
            descriptions.short_name(b"e_gun_ml_10"),
            Some(b"MML9S".as_slice())
        );
    }
}