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 tag32_to_tag64: FxHashMap<TagHash, TagHash64>,
39
40    pub named_tags: Vec<PackageNamedTagEntry>,
41}
42
43pub struct PackageManager {
44    pub package_dir: PathBuf,
45    pub package_paths: FxHashMap<u16, PackagePath>,
46    pub version: GameVersion,
47    pub platform: PackagePlatform,
48
49    /// Tag Lookup Index (TLI)
50    pub lookup: TagLookupIndex,
51
52    /// Packages that are currently open for reading
53    pkgs: RwLock<FxHashMap<u16, Arc<dyn Package>>>,
54}
55
56impl PackageManager {
57    pub fn new<P: AsRef<Path>>(
58        packages_dir: P,
59        version: GameVersion,
60        platform: Option<PackagePlatform>,
61    ) -> anyhow::Result<PackageManager> {
62        // All the latest packages
63        let mut packages: FxHashMap<u16, String> = Default::default();
64
65        let oo2core_3_path = packages_dir.as_ref().join("../bin/x64/oo2core_3_win64.dll");
66        let oo2core_9_path = packages_dir.as_ref().join("../bin/x64/oo2core_9_win64.dll");
67
68        if oo2core_3_path.exists() {
69            let mut o = oodle::OODLE_3.write();
70            if o.is_none() {
71                *o = oodle::Oodle::from_path(oo2core_3_path).ok();
72            }
73        }
74
75        if oo2core_9_path.exists() {
76            let mut o = oodle::OODLE_9.write();
77            if o.is_none() {
78                *o = oodle::Oodle::from_path(oo2core_9_path).ok();
79            }
80        }
81
82        let build_new_cache = match Self::validate_cache(version, platform, packages_dir.as_ref()) {
83            Ok(paths) => {
84                packages = paths;
85                false
86            }
87            Err(e) => {
88                warn!("Caches need to be rebuilt: {e}");
89                true
90            }
91        };
92
93        if build_new_cache {
94            info!("Creating new package cache for {}", version.id());
95            let path = packages_dir.as_ref();
96            // Every package in the given directory, including every patch
97            let mut packages_all = vec![];
98            debug_span!("Discover packages in directory").in_scope(|| -> anyhow::Result<()> {
99                for entry in fs::read_dir(path)? {
100                    let entry = entry?;
101                    let path = entry.path();
102                    if path.is_file() && path.to_string_lossy().to_lowercase().ends_with(".pkg") {
103                        packages_all.push(path.to_string_lossy().to_string());
104                    }
105                }
106
107                Ok(())
108            })?;
109
110            packages_all.sort();
111
112            debug_span!("Filter latest packages").in_scope(|| {
113                for p in packages_all {
114                    let parts: Vec<&str> = p.split('_').collect();
115                    if let Some(Ok(pkg_id)) = parts
116                        .get(parts.len() - 2)
117                        .map(|s| u16::from_str_radix(s, 16))
118                    {
119                        packages.insert(pkg_id, p);
120                    } else {
121                        let _span = debug_span!("Open package to find package ID").entered();
122                        // Take the long route and extract the package ID from the header
123                        if let Ok(pkg) = version.open(&p) {
124                            if pkg.language().english_or_none() {
125                                packages.insert(pkg.pkg_id(), p);
126                            }
127                        }
128                    }
129                }
130            });
131        }
132
133        let package_paths: FxHashMap<u16, PackagePath> = packages
134            .into_iter()
135            .map(|(id, p)| (id, PackagePath::parse_with_defaults(&p)))
136            .collect();
137
138        let first_path = package_paths.values().next().context("No packages found")?;
139
140        let platform = if let Ok(pkg) = version.open(&first_path.path) {
141            pkg.platform()
142        } else {
143            PackagePlatform::from_str(first_path.platform.as_str())?
144        };
145
146        let mut s = Self {
147            package_dir: packages_dir.as_ref().to_path_buf(),
148            platform,
149            package_paths,
150            version,
151            lookup: Default::default(),
152            pkgs: Default::default(),
153        };
154
155        if build_new_cache {
156            s.build_lookup_tables();
157            s.write_package_cache().ok();
158            s.write_lookup_cache().ok();
159        } else if let Some(lookup_cache) = s.read_lookup_cache() {
160            s.lookup = lookup_cache;
161        } else {
162            info!("No valid index cache found, rebuilding");
163            s.build_lookup_tables();
164            s.write_lookup_cache().ok();
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    pub fn get_tag64_for_tag32(&self, tag: impl Into<TagHash>) -> Option<TagHash64> {
283        let tag: TagHash = tag.into();
284        self.lookup.tag32_to_tag64.get(&tag).copied()
285    }
286
287    /// Read any BinRead type
288    pub fn read_tag_binrw<'a, T: BinRead>(&self, tag: impl Into<TagHash>) -> anyhow::Result<T>
289    where
290        T::Args<'a>: Default + Clone,
291    {
292        let tag = tag.into();
293        let data = self.read_tag(tag)?;
294        let mut cursor = Cursor::new(&data);
295        Ok(cursor.read_type(self.version.endian())?)
296    }
297
298    /// Read any BinRead type
299    pub fn read_tag64_binrw<'a, T: BinRead>(&self, hash: impl Into<TagHash64>) -> anyhow::Result<T>
300    where
301        T::Args<'a>: Default + Clone,
302    {
303        let data = self.read_tag64(hash)?;
304        let mut cursor = Cursor::new(&data);
305        Ok(cursor.read_type(self.version.endian())?)
306    }
307}
308
309#[derive(Debug, Clone)]
310pub struct PackagePath {
311    /// eg. ps3, w64
312    pub platform: String,
313    /// eg. arch_fallen, dungeon_prophecy, europa
314    pub name: String,
315
316    /// 2-letter language code (en, fr, de, etc.)
317    pub language: Option<String>,
318
319    /// eg. 0059, 043c, unp1, unp2
320    pub id: String,
321    pub patch: u8,
322
323    /// Full path to the package
324    pub path: String,
325    pub filename: String,
326}
327
328impl PackagePath {
329    /// Example path: ps3_arch_fallen_0059_0.pkg
330    pub fn parse(path: &str) -> Option<Self> {
331        let path_filename = Path::new(path).file_name()?.to_string_lossy();
332        let parts: Vec<&str> = path_filename.split('_').collect();
333        if parts.len() < 4 {
334            return None;
335        }
336
337        let platform = parts[0].to_string();
338        let mut name = parts[1..parts.len() - 2].join("_");
339        let mut id = parts[parts.len() - 2].to_string();
340        let mut language = None;
341        if id.len() == 2 {
342            // ID is actually language code
343            language = Some(id.clone());
344            name = parts[1..parts.len() - 3].join("_");
345            id = parts[parts.len() - 3].to_string();
346        }
347
348        let patch = parts[parts.len() - 1].split('.').next()?.parse().ok()?;
349
350        Some(Self {
351            platform,
352            name,
353            language,
354            id,
355            patch,
356            path: path.to_string(),
357            filename: path_filename.to_string(),
358        })
359    }
360
361    pub fn parse_with_defaults(path: &str) -> Self {
362        let path_filename = Path::new(path)
363            .file_name()
364            .map_or(path.to_string(), |p| p.to_string_lossy().to_string());
365        Self::parse(path).unwrap_or_else(|| Self {
366            platform: "unknown".to_string(),
367            name: "unknown".to_string(),
368            id: "unknown".to_string(),
369            language: None,
370            patch: 0,
371            path: path.to_string(),
372            filename: path_filename,
373        })
374    }
375}
376
377impl Display for PackagePath {
378    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
379        write!(f, "{}", self.filename)
380    }
381}