tiger_pkg/
package.rs

1use std::{
2    fmt::{Display, Formatter},
3    io::{Read, Seek},
4    str::FromStr,
5    sync::Arc,
6};
7
8use anyhow::{anyhow, ensure};
9use binrw::{BinRead, Endian};
10
11use crate::{d2_shared::PackageNamedTagEntry, TagHash};
12
13pub trait ReadSeek: Read + Seek {}
14impl<R: Read + Seek> ReadSeek for R {}
15
16#[derive(Clone, Debug, bincode::Decode, bincode::Encode)]
17pub struct UEntryHeader {
18    pub reference: u32,
19    pub file_type: u8,
20    pub file_subtype: u8,
21    pub starting_block: u32,
22    pub starting_block_offset: u32,
23    pub file_size: u32,
24}
25
26#[derive(Clone)]
27pub struct UHashTableEntry {
28    pub hash64: u64,
29    pub hash32: TagHash,
30    pub reference: TagHash,
31}
32
33#[derive(BinRead, Debug, Copy, Clone)]
34#[br(repr = u16)]
35pub enum PackageLanguage {
36    None = 0,
37    English = 1,
38    French = 2,
39    Italian = 3,
40    German = 4,
41    Spanish = 5,
42    Japanese = 6,
43    Portuguese = 7,
44    Russian = 8,
45    Polish = 9,
46    SimplifiedChinese = 10,
47    TraditionalChinese = 11,
48    SpanishLatAm = 12,
49    Korean = 13,
50}
51
52impl PackageLanguage {
53    pub fn english_or_none(&self) -> bool {
54        matches!(self, Self::None | Self::English)
55    }
56}
57
58pub trait Package: Send + Sync {
59    fn endianness(&self) -> binrw::Endian;
60
61    fn pkg_id(&self) -> u16;
62    fn patch_id(&self) -> u16;
63
64    /// Every hash64 in this package.
65    /// Does not apply to Destiny 1
66    fn hash64_table(&self) -> Vec<UHashTableEntry>;
67
68    fn named_tags(&self) -> Vec<PackageNamedTagEntry>;
69
70    fn entries(&self) -> &[UEntryHeader];
71
72    fn entry(&self, index: usize) -> Option<UEntryHeader>;
73
74    fn language(&self) -> PackageLanguage;
75
76    fn platform(&self) -> PackagePlatform;
77
78    /// Gets/reads a specific block from the file.
79    /// It's recommended that the implementation caches blocks to prevent re-reads
80    fn get_block(&self, index: usize) -> anyhow::Result<Arc<Vec<u8>>>;
81
82    /// Reads the entire specified entry's data
83    fn read_entry(&self, index: usize) -> anyhow::Result<Vec<u8>> {
84        let _span = tracing::debug_span!("Package::read_entry").entered();
85        let entry = self
86            .entry(index)
87            .ok_or(anyhow!("Entry index is out of range"))?;
88
89        let mut buffer = Vec::with_capacity(entry.file_size as usize);
90        let mut current_offset = 0usize;
91        let mut current_block = entry.starting_block;
92
93        while current_offset < entry.file_size as usize {
94            let remaining_bytes = entry.file_size as usize - current_offset;
95            let block_data = self.get_block(current_block as usize)?;
96
97            if current_block == entry.starting_block {
98                let block_start_offset = entry.starting_block_offset as usize;
99                let block_remaining = block_data.len() - block_start_offset;
100                let copy_size = if block_remaining < remaining_bytes {
101                    block_remaining
102                } else {
103                    remaining_bytes
104                };
105
106                buffer.extend_from_slice(
107                    &block_data[block_start_offset..block_start_offset + copy_size],
108                );
109
110                current_offset += copy_size;
111            } else if remaining_bytes < block_data.len() {
112                // If the block has more bytes than we need, it means we're on the last block
113                buffer.extend_from_slice(&block_data[..remaining_bytes]);
114                current_offset += remaining_bytes;
115            } else {
116                // If the previous 2 conditions failed, it means this whole block belongs to the file
117                buffer.extend_from_slice(&block_data[..]);
118                current_offset += block_data.len();
119            }
120
121            current_block += 1;
122        }
123
124        Ok(buffer)
125    }
126
127    /// Reads the entire specified entry's data
128    /// Tag needs to be in this package
129    fn read_tag(&self, tag: TagHash) -> anyhow::Result<Vec<u8>> {
130        ensure!(tag.pkg_id() == self.pkg_id());
131        self.read_entry(tag.entry_index() as _)
132    }
133
134    // /// Reads the entire specified entry's data
135    // /// Hash needs to be in this package
136    // fn read_hash64(&self, hash: u64) -> anyhow::Result<Vec<u8>> {
137    //     let tag = self.translate_hash64(hash).ok_or_else(|| {
138    //         anyhow::anyhow!(
139    //             "Could not find hash 0x{hash:016x} in this package ({:04x})",
140    //             self.pkg_id()
141    //         )
142    //     })?;
143    //     ensure!(tag.pkg_id() == self.pkg_id());
144    //     self.read_entry(tag.entry_index() as _)
145    // }
146
147    fn get_all_by_reference(&self, reference: u32) -> Vec<(usize, UEntryHeader)> {
148        self.entries()
149            .iter()
150            .enumerate()
151            .filter(|(_, e)| e.reference == reference)
152            .map(|(i, e)| (i, e.clone()))
153            .collect()
154    }
155
156    fn get_all_by_type(&self, etype: u8, esubtype: Option<u8>) -> Vec<(usize, UEntryHeader)> {
157        self.entries()
158            .iter()
159            .enumerate()
160            .filter(|(_, e)| {
161                e.file_type == etype && esubtype.map(|t| t == e.file_subtype).unwrap_or(true)
162            })
163            .map(|(i, e)| (i, e.clone()))
164            .collect()
165    }
166}
167
168/// ! Currently only works for Pre-BL Destiny 2
169pub fn classify_file_prebl(ftype: u8, fsubtype: u8) -> String {
170    match (ftype, fsubtype) {
171        // WWise audio bank
172        (26, 5) => "bnk".to_string(),
173        // WWise audio stream
174        (26, 6) => "wem".to_string(),
175        // Havok file
176        (26, 7) => "hkx".to_string(),
177        // CriWare USM video
178        (27, _) => "usm".to_string(),
179        (32, 1) => "texture.header".to_string(),
180        (32, 2) => "texture_cube.header".to_string(),
181        (32, 4) => "vertex.header".to_string(),
182        (32, 6) => "index.header".to_string(),
183        (40, 4) => "vertex.data".to_string(),
184        (40, 6) => "index.data".to_string(),
185        (48, 1) => "texture.data".to_string(),
186        (48, 2) => "texture_cube.data".to_string(),
187        // DXBC data
188        (41, shader_type) => {
189            let ty = match shader_type {
190                0 => "fragment".to_string(),
191                1 => "vertex".to_string(),
192                6 => "compute".to_string(),
193                u => format!("unk{u}"),
194            };
195
196            format!("cso.{ty}")
197        }
198        (8, _) => "8080".to_string(),
199        _ => "bin".to_string(),
200    }
201}
202
203#[derive(
204    serde::Serialize,
205    serde::Deserialize,
206    clap::ValueEnum,
207    PartialEq,
208    Eq,
209    Debug,
210    Clone,
211    Copy,
212    BinRead,
213)]
214#[br(repr = u16)]
215pub enum PackagePlatform {
216    Tool32,
217    Win32,
218    Win64,
219    X360,
220    PS3,
221    Tool64,
222    Win64v1,
223    PS4,
224    XboxOne,
225    Stadia,
226    PS5,
227    Scarlett,
228}
229
230impl PackagePlatform {
231    pub fn endianness(&self) -> Endian {
232        match self {
233            Self::PS3 | Self::X360 => Endian::Big,
234            Self::XboxOne | Self::PS4 | Self::Win64 => Endian::Little,
235            _ => Endian::Little,
236        }
237    }
238}
239
240impl FromStr for PackagePlatform {
241    type Err = anyhow::Error;
242
243    fn from_str(s: &str) -> Result<Self, Self::Err> {
244        Ok(match s {
245            "ps3" => Self::PS3,
246            "ps4" => Self::PS4,
247            "360" => Self::X360,
248            "w64" => Self::Win64,
249            "xboxone" => Self::XboxOne,
250            s => return Err(anyhow!("Invalid platform '{s}'")),
251        })
252    }
253}
254
255impl Display for PackagePlatform {
256    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
257        match self {
258            PackagePlatform::Tool32 => f.write_str("tool32"),
259            PackagePlatform::Win32 => f.write_str("w32"),
260            PackagePlatform::Win64 => f.write_str("w64"),
261            PackagePlatform::X360 => f.write_str("360"),
262            PackagePlatform::PS3 => f.write_str("ps3"),
263            PackagePlatform::Tool64 => f.write_str("tool64"),
264            PackagePlatform::Win64v1 => f.write_str("w64"),
265            PackagePlatform::PS4 => f.write_str("ps4"),
266            PackagePlatform::XboxOne => f.write_str("xboxone"),
267            PackagePlatform::Stadia => f.write_str("stadia"),
268            PackagePlatform::PS5 => f.write_str("ps5"),
269            PackagePlatform::Scarlett => f.write_str("scarlett"),
270        }
271    }
272}