tiger_pkg/manager/
mod.rs

1pub mod lookup_cache;
2pub mod path_cache;
3
4use std::{
5    fmt::Display,
6    fs,
7    io::Cursor,
8    path::{Path, PathBuf},
9    str::FromStr,
10    sync::Arc,
11};
12
13use anyhow::Context;
14use binrw::{BinRead, BinReaderExt};
15use parking_lot::RwLock;
16use rayon::prelude::*;
17use rustc_hash::FxHashMap;
18use tracing::{debug_span, info, warn};
19
20use crate::{
21    d2_shared::PackageNamedTagEntry,
22    oodle,
23    package::{Package, PackagePlatform, UEntryHeader},
24    tag::TagHash64,
25    GameVersion, TagHash, Version,
26};
27
28#[derive(Clone, bincode::Decode, bincode::Encode)]
29pub struct HashTableEntryShort {
30    pub hash32: TagHash,
31    pub reference: TagHash,
32}
33
34#[derive(Default, bincode::Decode, bincode::Encode)]
35pub struct TagLookupIndex {
36    pub tag32_entries_by_pkg: FxHashMap<u16, Vec<UEntryHeader>>,
37    pub tag64_entries: FxHashMap<u64, HashTableEntryShort>,
38    pub named_tags: Vec<PackageNamedTagEntry>,
39}
40
41pub struct PackageManager {
42    pub package_dir: PathBuf,
43    pub package_paths: FxHashMap<u16, PackagePath>,
44    pub version: GameVersion,
45    pub platform: PackagePlatform,
46
47    /// Tag Lookup Index (TLI)
48    pub lookup: TagLookupIndex,
49
50    /// Packages that are currently open for reading
51    pkgs: RwLock<FxHashMap<u16, Arc<dyn Package>>>,
52}
53
54impl PackageManager {
55    pub fn new<P: AsRef<Path>>(
56        packages_dir: P,
57        version: GameVersion,
58        platform: Option<PackagePlatform>,
59    ) -> anyhow::Result<PackageManager> {
60        // All the latest packages
61        let mut packages: FxHashMap<u16, String> = Default::default();
62
63        let oo2core_3_path = packages_dir.as_ref().join("../bin/x64/oo2core_3_win64.dll");
64        let oo2core_9_path = packages_dir.as_ref().join("../bin/x64/oo2core_9_win64.dll");
65
66        if oo2core_3_path.exists() {
67            let mut o = oodle::OODLE_3.write();
68            if o.is_none() {
69                *o = oodle::Oodle::from_path(oo2core_3_path).ok();
70            }
71        }
72
73        if oo2core_9_path.exists() {
74            let mut o = oodle::OODLE_9.write();
75            if o.is_none() {
76                *o = oodle::Oodle::from_path(oo2core_9_path).ok();
77            }
78        }
79
80        let build_new_cache = match Self::validate_cache(version, platform, packages_dir.as_ref()) {
81            Ok(paths) => {
82                packages = paths;
83                false
84            }
85            Err(e) => {
86                warn!("Caches need to be rebuilt: {e}");
87                true
88            }
89        };
90
91        if build_new_cache {
92            info!("Creating new package cache for {}", version.id());
93            let path = packages_dir.as_ref();
94            // Every package in the given directory, including every patch
95            let mut packages_all = vec![];
96            debug_span!("Discover packages in directory").in_scope(|| -> anyhow::Result<()> {
97                for entry in fs::read_dir(path)? {
98                    let entry = entry?;
99                    let path = entry.path();
100                    if path.is_file() && path.to_string_lossy().to_lowercase().ends_with(".pkg") {
101                        packages_all.push(path.to_string_lossy().to_string());
102                    }
103                }
104
105                Ok(())
106            })?;
107
108            packages_all.sort();
109
110            debug_span!("Filter latest packages").in_scope(|| {
111                for p in packages_all {
112                    let parts: Vec<&str> = p.split('_').collect();
113                    if let Some(Ok(pkg_id)) = parts
114                        .get(parts.len() - 2)
115                        .map(|s| u16::from_str_radix(s, 16))
116                    {
117                        packages.insert(pkg_id, p);
118                    } else {
119                        let _span = debug_span!("Open package to find package ID").entered();
120                        // Take the long route and extract the package ID from the header
121                        if let Ok(pkg) = version.open(&p) {
122                            if pkg.language().english_or_none() {
123                                packages.insert(pkg.pkg_id(), p);
124                            }
125                        }
126                    }
127                }
128            });
129        }
130
131        let package_paths: FxHashMap<u16, PackagePath> = packages
132            .into_iter()
133            .map(|(id, p)| (id, PackagePath::parse_with_defaults(&p)))
134            .collect();
135
136        let first_path = package_paths.values().next().context("No packages found")?;
137
138        let platform = if let Ok(pkg) = version.open(&first_path.path) {
139            pkg.platform()
140        } else {
141            PackagePlatform::from_str(first_path.platform.as_str())?
142        };
143
144        let mut s = Self {
145            package_dir: packages_dir.as_ref().to_path_buf(),
146            platform,
147            package_paths,
148            version,
149            lookup: Default::default(),
150            pkgs: Default::default(),
151        };
152
153        if build_new_cache {
154            s.build_lookup_tables();
155            s.write_package_cache().ok();
156            s.write_lookup_cache().ok();
157        } else {
158            if let Some(lookup_cache) = s.read_lookup_cache() {
159                s.lookup = lookup_cache;
160            } else {
161                info!("No valid index cache found, rebuilding");
162                s.build_lookup_tables();
163                s.write_lookup_cache().ok();
164            }
165        }
166
167        Ok(s)
168    }
169}
170
171impl PackageManager {
172    pub fn get_all_by_reference(&self, reference: u32) -> Vec<(TagHash, UEntryHeader)> {
173        self.lookup
174            .tag32_entries_by_pkg
175            .par_iter()
176            .map(|(p, e)| {
177                e.iter()
178                    .enumerate()
179                    .filter(|(_, e)| e.reference == reference)
180                    .map(|(i, e)| (TagHash::new(*p, i as _), e.clone()))
181                    .collect::<Vec<(TagHash, UEntryHeader)>>()
182            })
183            .flatten()
184            .collect()
185    }
186
187    pub fn get_all_by_type(&self, etype: u8, esubtype: Option<u8>) -> Vec<(TagHash, UEntryHeader)> {
188        self.lookup
189            .tag32_entries_by_pkg
190            .par_iter()
191            .map(|(p, e)| {
192                e.iter()
193                    .enumerate()
194                    .filter(|(_, e)| {
195                        e.file_type == etype
196                            && esubtype.map(|t| t == e.file_subtype).unwrap_or(true)
197                    })
198                    .map(|(i, e)| (TagHash::new(*p, i as _), e.clone()))
199                    .collect::<Vec<(TagHash, UEntryHeader)>>()
200            })
201            .flatten()
202            .collect()
203    }
204
205    fn get_or_load_pkg(&self, pkg_id: u16) -> anyhow::Result<Arc<dyn Package>> {
206        let _span = tracing::debug_span!("PackageManager::get_or_Load_pkg", pkg_id).entered();
207        let v = self.pkgs.read();
208        if let Some(pkg) = v.get(&pkg_id) {
209            Ok(Arc::clone(pkg))
210        } else {
211            drop(v);
212            let package_path = self
213                .package_paths
214                .get(&pkg_id)
215                .with_context(|| format!("Couldn't get a path for package id {pkg_id:04x}"))?;
216
217            let package = self
218                .version
219                .open(&package_path.path)
220                .with_context(|| format!("Failed to open package '{}'", package_path.filename))?;
221
222            self.pkgs.write().insert(pkg_id, Arc::clone(&package));
223            Ok(package)
224        }
225    }
226
227    pub fn read_tag(&self, tag: impl Into<TagHash>) -> anyhow::Result<Vec<u8>> {
228        let _span = tracing::debug_span!("PackageManager::read_tag").entered();
229        let tag = tag.into();
230        self.get_or_load_pkg(tag.pkg_id())?
231            .read_entry(tag.entry_index() as _)
232    }
233
234    pub fn read_tag64(&self, hash: impl Into<TagHash64>) -> anyhow::Result<Vec<u8>> {
235        let hash = hash.into();
236        let tag = self
237            .lookup
238            .tag64_entries
239            .get(&hash.0)
240            .context("Hash not found")?
241            .hash32;
242        self.read_tag(tag)
243    }
244
245    pub fn get_entry(&self, tag: impl Into<TagHash>) -> Option<UEntryHeader> {
246        let tag: TagHash = tag.into();
247
248        self.lookup
249            .tag32_entries_by_pkg
250            .get(&tag.pkg_id())?
251            .get(tag.entry_index() as usize)
252            .cloned()
253    }
254
255    pub fn get_named_tag(&self, name: &str, class_hash: u32) -> Option<TagHash> {
256        self.lookup
257            .named_tags
258            .iter()
259            .find(|n| n.name == name && n.class_hash == class_hash)
260            .map(|n| n.hash)
261    }
262
263    pub fn get_named_tags_by_class(&self, class_hash: u32) -> Vec<(String, TagHash)> {
264        self.lookup
265            .named_tags
266            .iter()
267            .filter(|n| n.class_hash == class_hash)
268            .map(|n| (n.name.clone(), n.hash))
269            .collect()
270    }
271
272    /// Find the name of a tag by its hash, if it has one.
273    pub fn get_tag_name(&self, tag: impl Into<TagHash>) -> Option<String> {
274        let tag: TagHash = tag.into();
275        self.lookup
276            .named_tags
277            .iter()
278            .find(|n| n.hash == tag)
279            .map(|n| n.name.clone())
280    }
281
282    /// Read any BinRead type
283    pub fn read_tag_binrw<'a, T: BinRead>(&self, tag: impl Into<TagHash>) -> anyhow::Result<T>
284    where
285        T::Args<'a>: Default + Clone,
286    {
287        let tag = tag.into();
288        let data = self.read_tag(tag)?;
289        let mut cursor = Cursor::new(&data);
290        Ok(cursor.read_type(self.version.endian())?)
291    }
292
293    /// Read any BinRead type
294    pub fn read_tag64_binrw<'a, T: BinRead>(&self, hash: impl Into<TagHash64>) -> anyhow::Result<T>
295    where
296        T::Args<'a>: Default + Clone,
297    {
298        let data = self.read_tag64(hash)?;
299        let mut cursor = Cursor::new(&data);
300        Ok(cursor.read_type(self.version.endian())?)
301    }
302}
303
304#[derive(Debug, Clone)]
305pub struct PackagePath {
306    /// eg. ps3, w64
307    pub platform: String,
308    /// eg. arch_fallen, dungeon_prophecy, europa
309    pub name: String,
310
311    /// 2-letter language code (en, fr, de, etc.)
312    pub language: Option<String>,
313
314    /// eg. 0059, 043c, unp1, unp2
315    pub id: String,
316    pub patch: u8,
317
318    /// Full path to the package
319    pub path: String,
320    pub filename: String,
321}
322
323impl PackagePath {
324    /// Example path: ps3_arch_fallen_0059_0.pkg
325    pub fn parse(path: &str) -> Option<Self> {
326        let path_filename = Path::new(path).file_name()?.to_string_lossy();
327        let parts: Vec<&str> = path_filename.split('_').collect();
328        if parts.len() < 4 {
329            return None;
330        }
331
332        let platform = parts[0].to_string();
333        let mut name = parts[1..parts.len() - 2].join("_");
334        let mut id = parts[parts.len() - 2].to_string();
335        let mut language = None;
336        if id.len() == 2 {
337            // ID is actually language code
338            language = Some(id.clone());
339            name = parts[1..parts.len() - 3].join("_");
340            id = parts[parts.len() - 3].to_string();
341        }
342
343        let patch = parts[parts.len() - 1].split('.').next()?.parse().ok()?;
344
345        Some(Self {
346            platform,
347            name,
348            language,
349            id,
350            patch,
351            path: path.to_string(),
352            filename: path_filename.to_string(),
353        })
354    }
355
356    pub fn parse_with_defaults(path: &str) -> Self {
357        let path_filename = Path::new(path)
358            .file_name()
359            .map_or(path.to_string(), |p| p.to_string_lossy().to_string());
360        Self::parse(path).unwrap_or_else(|| Self {
361            platform: "unknown".to_string(),
362            name: "unknown".to_string(),
363            id: "unknown".to_string(),
364            language: None,
365            patch: 0,
366            path: path.to_string(),
367            filename: path_filename,
368        })
369    }
370}
371
372impl Display for PackagePath {
373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        write!(f, "{}", self.filename)
375    }
376}