bevy_mod_pakfile 0.1.0

Load Bevy assets from Quake 1 .pak files, with support for loading multiple and overlaying them
Documentation
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! # `bevy_mod_pakfile`
//!
//! Enables using `.pak` files as asset sources. Currently quite limited in functionality,
//! based on the needs of the [`seismon`](https://github.com/eira-fransham/seismon) engine.
//!
//! See the documentation of [`PakfilePlugin`] for usage.

#![deny(missing_docs)]

use std::{
    path::{Path, PathBuf},
    sync::Arc,
};

use bevy_app::Plugin;
use bevy_asset::{
    AssetApp,
    io::{
        AssetReader, AssetReaderError, AssetSource, AssetSourceId, ErasedAssetReader, PathStream,
        Reader, file::FileAssetReader,
    },
};
use bevy_log as log;
use futures::StreamExt as _;
use hashbrown::HashSet;
use pak::Pak;
use tokio::sync::SetOnce;

mod pak;

enum PakSource {
    Any(Box<dyn ErasedAssetReader>),
    #[cfg(not(target_arch = "wasm32"))]
    File(FileAssetReader),
}

impl PakSource {
    async fn load_pak(&self, file: &Path) -> Result<Pak, AssetReaderError> {
        match self {
            Self::Any(reader) => {
                let mut reader = reader.read(file).await?;

                let mut out = Vec::new();

                reader.read_to_end(&mut out).await?;

                let bytes = out.into_boxed_slice();

                Ok(Pak::from_backing(file.display(), bytes)?)
            }

            Self::File(reader) => {
                let full_path = reader.root_path().join(file);

                // Safety: The file is only ever accessed as a blob of bytes, so the potential for unsoundness
                // is low, but since it means data can change behind a `&` reference it is technically
                // unsound to open a memmap for any purpose.
                //
                // TODO: Investigate the performance of copying and then unlinking the .pak in order to make
                // the data we access inaccessible to other processes.
                let mmap = unsafe { memmap2::Mmap::map(&std::fs::File::open(full_path)?)? };

                Ok(Pak::from_backing(file.display(), mmap)?)
            }
        }
    }
}

impl AssetReader for PakSource {
    fn read<'a>(
        &'a self,
        path: &'a Path,
    ) -> impl bevy_asset::io::AssetReaderFuture<Value: Reader + 'a> {
        match self {
            Self::Any(reader) => reader.read(path),
            Self::File(reader) => ErasedAssetReader::read(reader, path),
        }
    }

    fn read_meta<'a>(
        &'a self,
        path: &'a Path,
    ) -> impl bevy_asset::io::AssetReaderFuture<Value: Reader + 'a> {
        match self {
            Self::Any(reader) => reader.read_meta(path),
            Self::File(reader) => ErasedAssetReader::read_meta(reader, path),
        }
    }

    fn read_directory<'a>(
        &'a self,
        path: &'a Path,
    ) -> impl bevy_tasks::ConditionalSendFuture<Output = Result<Box<PathStream>, AssetReaderError>>
    {
        match self {
            Self::Any(reader) => reader.read_directory(path),
            Self::File(reader) => ErasedAssetReader::read_directory(reader, path),
        }
    }

    fn is_directory<'a>(
        &'a self,
        path: &'a Path,
    ) -> impl bevy_tasks::ConditionalSendFuture<Output = Result<bool, AssetReaderError>> {
        match self {
            Self::Any(reader) => reader.is_directory(path),
            Self::File(reader) => ErasedAssetReader::is_directory(reader, path),
        }
    }
}

impl From<PathBuf> for PakSource {
    #[cfg(not(target_arch = "wasm32"))]
    fn from(value: PathBuf) -> Self {
        Self::File(FileAssetReader::new(value))
    }

    #[cfg(target_arch = "wasm32")]
    fn from(value: PathBuf) -> Self {
        Self::Any(AssetSource::get_default_reader(value.to_string())())
    }
}

impl From<Box<dyn ErasedAssetReader>> for PakSource {
    fn from(value: Box<dyn ErasedAssetReader>) -> Self {
        Self::Any(value)
    }
}

type MakeSource = dyn Fn() -> PakSource + Send + Sync + 'static;

/// The core plugin to enable reading from pakfiles. Note that if you do not explicitly set a source ID using
/// [`PakfilePlugin::with_source_id`], this _must_ be added before Bevy's asset plugin.
///
/// Note that when using [`PakfilePlugin::push_reader`], the pak will be loaded into memory, but with
/// [`PakfilePlugin::push_path`], the files will be mapped using [`memmap2`](https://crates.io/crates/memmap2).
/// On platforms that do not support memory mapping, all pakfiles will be loaded into memory before they can
/// be used.
///
/// ```no_run
/// # use bevy::prelude::*;
/// # use bevy_mod_pakfile::PakfilePlugin;
///
/// let id1_path = std::env::current_dir().unwrap().join("id1");
/// let mut app = App::new();
/// app.add_plugins(PakfilePlugin::from_paths([id1_path.display()]))
///     .add_plugins(DefaultPlugins);
/// ```
pub struct PakfilePlugin {
    sources: Vec<Arc<MakeSource>>,
    source_id: AssetSourceId<'static>,
}

impl Default for PakfilePlugin {
    fn default() -> Self {
        Self::from_paths::<[&str; 0]>([])
    }
}

impl PakfilePlugin {
    /// Create a new empty [`PakfilePlugin`]. Note that if you add this to an app without adding any
    /// directories with [`PakfilePlugin::push_path`] or [`PakfilePlugin::push_reader`] then trying to
    /// read any asset will fail.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a game directory to search for pakfiles. Note that paths are evaluated in reverse order, so
    /// if you want to have a mod `foo` that depends on `id1`, you'd pass [`id1`, `foo`]. On platforms
    /// that support it, pakfiles in directories added using this method will be loaded using a memory
    /// map for maximum efficiency.
    pub fn push_path<P: Into<PathBuf>>(&mut self, path: P) -> &mut Self {
        let path = path.into();

        self.sources
            .push(Arc::new(move || PakSource::from(path.clone())) as Arc<MakeSource>);

        self
    }

    /// Add an arbitrary source to search for pakfiles. The returned reader must be able to list directories.
    /// If you want to use an [`AssetReader`] that is not able to do this, such as web sources, you should
    /// implement a wrapper that shims in this ability - e.g. by searching for `pak0.pak`, `pak1.pak`, etc and
    /// returning the paths that resolve.
    pub fn push_reader<MkReader>(&mut self, make_reader: MkReader) -> &mut Self
    where
        MkReader: Fn() -> Box<dyn ErasedAssetReader> + Send + Sync + 'static,
    {
        self.sources
            .push(Arc::new(move || PakSource::from(make_reader())) as Arc<MakeSource>);

        self
    }

    /// Create a `PakfilePlugin` from a list of game paths. Paths are evaluated in reverse order, so
    /// if you want to have a mod `foo` that depends on `id1`, you'd pass [`id1`, `foo`].
    pub fn from_paths<I>(paths: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<PathBuf>,
    {
        Self {
            sources: paths
                .into_iter()
                .map(|path| {
                    let path = path.into();
                    Arc::new(move || PakSource::from(path.clone())) as Arc<MakeSource>
                })
                .collect(),
            source_id: AssetSourceId::Default,
        }
    }

    /// Set the source ID that assets in the underlying pakfiles will be accessed using. By default,
    /// this will register to the default asset source.
    pub fn with_source_id(&mut self, source_id: AssetSourceId<'_>) -> &mut Self {
        self.source_id = source_id.into_owned();

        self
    }
}

struct PakCollection {
    readers: SetOnce<Box<[Box<dyn ErasedAssetReader>]>>,
    dir_reader: PakSource,
}

struct VfsCollection {
    inner: Box<[Box<dyn ErasedAssetReader>]>,
}

impl PakCollection {
    async fn readers<'a>(&'a self) -> impl DoubleEndedIterator<Item = &'a dyn ErasedAssetReader> {
        // We need this for the types of the returned iterators to be the same.
        #[allow(clippy::borrowed_box)]
        let deref_box = |r: &'a Box<dyn ErasedAssetReader>| -> &'a dyn ErasedAssetReader { &**r };
        if let Some(readers) = self.readers.get() {
            readers.iter().map(deref_box)
        } else {
            let mut dir = match AssetReader::read_directory(&self.dir_reader, Path::new("")).await {
                Ok(dir) => dir,
                Err(e) => {
                    log::error!("Could not read pakfile directory: {e}");
                    let _ = self.readers.set(Box::new([]));
                    return self.readers.wait().await.iter().map(deref_box);
                }
            };

            let mut pakfiles = Vec::new();

            while let Some(file) = dir.next().await {
                let file_extension_is_pak = file
                    .extension()
                    .map(|ext| ext.eq_ignore_ascii_case("pak"))
                    .unwrap_or(false);

                if !file_extension_is_pak {
                    continue;
                }

                let pakfile = match self.dir_reader.load_pak(&file).await {
                    Ok(pakfile) => pakfile,
                    Err(e) => {
                        let file = file.display();
                        log::warn!("Could not load pakfile {file}: {e}");
                        continue;
                    }
                };

                pakfiles.push(pakfile);
            }

            pakfiles.sort_unstable_by(|a, b| a.name().cmp(b.name()));

            let pakfiles = pakfiles
                .into_iter()
                .map(|pakfile| Box::new(pakfile) as Box<dyn ErasedAssetReader>)
                .collect::<Vec<_>>();

            let _ = self.readers.set(pakfiles.into_boxed_slice());

            self.readers.wait().await.iter().map(deref_box)
        }
    }
}

impl AssetReader for VfsCollection {
    async fn read<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
        let mut err = AssetReaderError::NotFound(path.to_owned());

        for reader in self.inner.iter().rev() {
            match reader.read(path).await {
                Ok(reader) => return Ok(reader),
                Err(e) => err = e,
            }
        }

        Err(err)
    }

    async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
        let mut err = AssetReaderError::NotFound(path.to_owned());

        for reader in self.inner.iter().rev() {
            match reader.read_meta(path).await {
                Ok(reader) => return Ok(reader),
                Err(e) => err = e,
            }
        }

        Err(err)
    }

    async fn read_directory<'a>(
        &'a self,
        path: &'a Path,
    ) -> Result<Box<PathStream>, AssetReaderError> {
        let path = path.to_owned();

        let out = futures::future::join_all(self.inner.iter().map(|reader| async {
            match reader.read_directory(&path).await {
                Ok(paths) => paths.collect::<Vec<_>>().await,
                Err(_) => Vec::new(),
            }
        }))
        .await;

        let out = out.into_iter().flatten().collect::<HashSet<_>>();

        Ok(Box::new(futures::stream::iter(out)))
    }

    async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
        let mut err = AssetReaderError::NotFound(path.to_owned());

        for reader in self.inner.iter().rev() {
            match reader.is_directory(path).await {
                Ok(is_directory) => return Ok(is_directory),
                Err(e) => err = e,
            }
        }

        Err(err)
    }
}

impl AssetReader for PakCollection {
    async fn read<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
        for reader in self.readers().await.rev() {
            if let Ok(reader) = reader.read(path).await {
                return Ok(reader);
            }
        }

        ErasedAssetReader::read(&self.dir_reader, path).await
    }

    async fn read_meta<'a>(&'a self, path: &'a Path) -> Result<impl Reader + 'a, AssetReaderError> {
        for reader in self.readers().await.rev() {
            if let Ok(reader) = reader.read_meta(path).await {
                return Ok(reader);
            }
        }

        ErasedAssetReader::read_meta(&self.dir_reader, path).await
    }

    async fn read_directory<'a>(
        &'a self,
        path: &'a Path,
    ) -> Result<Box<PathStream>, AssetReaderError> {
        let path = path.to_owned();

        let out = futures::future::join_all(
            self.readers()
                .await
                .rev()
                .chain(std::iter::once(&self.dir_reader as &dyn ErasedAssetReader))
                .map(|reader| async {
                    match reader.read_directory(&path).await {
                        Ok(paths) => paths.collect::<Vec<_>>().await,
                        Err(_) => Vec::new(),
                    }
                }),
        )
        .await;

        let out = out.into_iter().flatten().collect::<HashSet<_>>();

        Ok(Box::new(futures::stream::iter(out)))
    }

    async fn is_directory<'a>(&'a self, path: &'a Path) -> Result<bool, AssetReaderError> {
        for reader in self.readers().await.rev() {
            if let Ok(is_dir) = reader.is_directory(path).await {
                return Ok(is_dir);
            }
        }

        ErasedAssetReader::is_directory(&self.dir_reader, path).await
    }
}

impl Plugin for PakfilePlugin {
    fn build(&self, app: &mut bevy_app::App) {
        let sources = self.sources.clone();
        app.register_asset_source(
            AssetSourceId::Default,
            AssetSource::build().with_reader(move || {
                let asset_readers = sources
                    .iter()
                    .map(|reader| {
                        Box::new(PakCollection {
                            readers: SetOnce::new(),
                            dir_reader: reader(),
                        }) as Box<dyn ErasedAssetReader + 'static>
                    })
                    .collect::<Vec<_>>()
                    .into_boxed_slice();

                Box::new(VfsCollection {
                    inner: asset_readers,
                })
            }),
        );
    }
}