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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use crate::{
    assets::{
        asset::{Asset, AssetId},
        protocol::{AssetLoadResult, AssetProtocol, AssetVariant, Meta},
    },
    fetch::{FetchEngine, FetchProcessReader, FetchStatus},
};
use std::{any::TypeId, borrow::BorrowMut, collections::HashMap};

#[derive(Debug, Clone, PartialEq)]
pub enum LoadStatus {
    InvalidPath(String),
    UnknownProtocol(String),
    FetchError(FetchStatus),
}

pub trait AssetsDatabaseErrorReporter: Send + Sync {
    fn on_report(&mut self, protocol: &str, path: &str, message: &str);
}

#[derive(Debug, Default, Copy, Clone)]
pub struct LoggerAssetsDatabaseErrorReporter;

impl AssetsDatabaseErrorReporter for LoggerAssetsDatabaseErrorReporter {
    fn on_report(&mut self, protocol: &str, path: &str, message: &str) {
        error!(
            "Assets database loading `{}://{}` error: {}",
            protocol, path, message
        );
    }
}

pub struct AssetsDatabase {
    pub max_bytes_per_frame: Option<usize>,
    fetch_engines: Vec<Box<dyn FetchEngine>>,
    protocols: HashMap<String, Box<dyn AssetProtocol>>,
    assets: HashMap<AssetId, (String, Asset)>,
    table: HashMap<String, AssetId>,
    loading: HashMap<String, (String, Box<dyn FetchProcessReader>)>,
    #[allow(clippy::type_complexity)]
    yielded: HashMap<String, (String, Meta, Vec<(String, String)>)>,
    lately_loaded: Vec<(String, AssetId)>,
    lately_unloaded: Vec<(String, AssetId)>,
    error_reporters: HashMap<TypeId, Box<dyn AssetsDatabaseErrorReporter>>,
}

impl AssetsDatabase {
    pub fn new<FE>(fetch_engine: FE) -> Self
    where
        FE: FetchEngine + 'static,
    {
        Self {
            max_bytes_per_frame: None,
            fetch_engines: vec![Box::new(fetch_engine)],
            protocols: Default::default(),
            assets: Default::default(),
            table: Default::default(),
            loading: Default::default(),
            yielded: Default::default(),
            lately_loaded: vec![],
            lately_unloaded: vec![],
            error_reporters: Default::default(),
        }
    }

    pub fn register_error_reporter<T>(&mut self, reporter: T)
    where
        T: AssetsDatabaseErrorReporter + 'static,
    {
        self.error_reporters
            .insert(TypeId::of::<T>(), Box::new(reporter));
    }

    pub fn unregister_error_reporter<T>(&mut self)
    where
        T: AssetsDatabaseErrorReporter + 'static,
    {
        self.error_reporters.remove(&TypeId::of::<T>());
    }

    pub fn loaded_count(&self) -> usize {
        self.assets.len()
    }

    pub fn loaded_paths(&self) -> Vec<String> {
        self.assets
            .iter()
            .map(|(_, (_, a))| a.to_full_path())
            .collect()
    }

    pub fn loaded_ids(&self) -> Vec<AssetId> {
        self.assets.iter().map(|(id, _)| *id).collect()
    }

    pub fn loading_count(&self) -> usize {
        self.loading.len()
    }

    pub fn loading_paths(&self) -> Vec<String> {
        let mut result = self
            .loading
            .iter()
            .map(|(path, (prot, _))| format!("{}://{}", prot, path))
            .collect::<Vec<_>>();
        result.sort();
        result
    }

    pub fn yielded_count(&self) -> usize {
        self.yielded.len()
    }

    pub fn yielded_paths(&self) -> Vec<String> {
        let mut result = self
            .yielded
            .iter()
            .map(|(path, (prot, _, _))| format!("{}://{}", prot, path))
            .collect::<Vec<_>>();
        result.sort();
        result
    }

    pub fn yielded_deps_count(&self) -> usize {
        self.yielded
            .iter()
            .map(|(_, (_, _, list))| list.len())
            .sum()
    }

    pub fn yielded_deps_paths(&self) -> Vec<String> {
        let mut result = self
            .yielded
            .iter()
            .flat_map(|(_, (_, _, list))| {
                list.iter().map(|(p, _)| p.to_owned()).collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();
        result.sort();
        result.dedup();
        result
    }

    pub fn lately_loaded(&self) -> impl Iterator<Item = &AssetId> {
        self.lately_loaded.iter().map(|(_, id)| id)
    }

    pub fn lately_loaded_paths(&self) -> impl Iterator<Item = &str> {
        self.lately_loaded.iter().map(|(path, _)| path.as_str())
    }

    pub fn lately_loaded_protocol<'a>(
        &'a self,
        protocol: &'a str,
    ) -> impl Iterator<Item = &'a AssetId> {
        self.lately_loaded
            .iter()
            .filter_map(move |(prot, id)| if protocol == prot { Some(id) } else { None })
    }

    pub fn lately_unloaded(&self) -> impl Iterator<Item = &AssetId> {
        self.lately_unloaded.iter().map(|(_, id)| id)
    }

    pub fn lately_unloaded_paths(&self) -> impl Iterator<Item = &str> {
        self.lately_unloaded.iter().map(|(path, _)| path.as_str())
    }

    pub fn lately_unloaded_protocol<'a>(
        &'a self,
        protocol: &'a str,
    ) -> impl Iterator<Item = &'a AssetId> {
        self.lately_unloaded
            .iter()
            .filter_map(move |(prot, id)| if protocol == prot { Some(id) } else { None })
    }

    pub fn is_ready(&self) -> bool {
        self.loading.is_empty() && self.yielded.is_empty()
    }

    pub fn are_ready<I, S>(&self, iter: I) -> bool
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        !iter
            .into_iter()
            .any(|path| !self.table.contains_key(path.as_ref()))
    }

    pub fn push_fetch_engine(&mut self, fetch_engine: Box<dyn FetchEngine>) {
        self.fetch_engines.push(fetch_engine);
    }

    pub fn pop_fetch_engine(&mut self) -> Option<Box<dyn FetchEngine>> {
        if !self.fetch_engines.is_empty() {
            self.fetch_engines.pop()
        } else {
            None
        }
    }

    #[allow(clippy::borrowed_box)]
    pub fn fetch_engine(&self) -> &Box<dyn FetchEngine> {
        self.fetch_engines.last().unwrap()
    }

    #[allow(clippy::borrowed_box)]
    pub fn fetch_engine_mut(&mut self) -> &mut Box<dyn FetchEngine> {
        self.fetch_engines.last_mut().unwrap()
    }

    pub fn with_fetch_engine<F, R>(&mut self, mut action: F) -> R
    where
        F: FnMut(&mut dyn FetchEngine) -> R,
    {
        let fetch_engine: &mut dyn FetchEngine = self.fetch_engine_mut().borrow_mut();
        action(fetch_engine)
    }

    pub fn register<FE>(&mut self, mut protocol: FE)
    where
        FE: AssetProtocol + 'static,
    {
        protocol.on_register();
        let name = protocol.name().to_owned();
        self.protocols.insert(name, Box::new(protocol));
    }

    pub fn unregister(&mut self, protocol_name: &str) -> Option<Box<dyn AssetProtocol>> {
        if let Some(mut protocol) = self.protocols.remove(protocol_name) {
            protocol.on_unregister();
            Some(protocol)
        } else {
            None
        }
    }

    pub fn load(&mut self, path: &str) -> Result<(), LoadStatus> {
        if self.table.contains_key(path) {
            return Ok(());
        }
        let parts = path.split("://").take(2).collect::<Vec<_>>();
        if parts.len() == 2 {
            let prot = parts[0];
            let subpath = parts[1];
            if self.protocols.contains_key(prot) {
                let reader = self.fetch_engine_mut().fetch(subpath);
                match reader {
                    Ok(reader) => {
                        self.loading
                            .insert(subpath.to_owned(), (prot.to_owned(), reader));
                        Ok(())
                    }
                    Err(status) => Err(LoadStatus::FetchError(status)),
                }
            } else {
                Err(LoadStatus::UnknownProtocol(prot.to_owned()))
            }
        } else {
            Err(LoadStatus::InvalidPath(path.to_owned()))
        }
    }

    pub fn insert(&mut self, path: &str, asset: Asset) -> AssetId {
        let id = asset.id();
        self.lately_loaded.push((asset.protocol().to_owned(), id));
        self.assets.insert(id, (path.to_owned(), asset));
        self.table.insert(path.to_owned(), id);
        id
    }

    pub fn remove_by_id(&mut self, id: AssetId) -> Option<Asset> {
        if let Some((path, asset)) = self.assets.remove(&id) {
            self.table.remove(&path);
            self.lately_unloaded.push((asset.protocol().to_owned(), id));
            if let Some(protocol) = self.protocols.get_mut(asset.protocol()) {
                if let Some(list) = protocol.on_unload(&asset) {
                    self.remove_by_variants(&list);
                }
            }
            Some(asset)
        } else {
            None
        }
    }

    pub fn remove_by_path(&mut self, path: &str) -> Option<Asset> {
        if let Some(id) = self.table.remove(path) {
            if let Some((_, asset)) = self.assets.remove(&id) {
                self.lately_unloaded.push((asset.protocol().to_owned(), id));
                if let Some(protocol) = self.protocols.get_mut(asset.protocol()) {
                    if let Some(list) = protocol.on_unload(&asset) {
                        self.remove_by_variants(&list);
                    }
                }
                return Some(asset);
            }
        }
        None
    }

    pub fn remove_by_variants(&mut self, variants: &[AssetVariant]) {
        for v in variants {
            match v {
                AssetVariant::Id(id) => self.remove_by_id(*id),
                AssetVariant::Path(path) => self.remove_by_path(path),
            };
        }
    }

    pub fn id_by_path(&self, path: &str) -> Option<AssetId> {
        self.table.get(path).cloned()
    }

    pub fn path_by_id(&self, id: AssetId) -> Option<&str> {
        self.assets.get(&id).map(|(path, _)| path.as_str())
    }

    pub fn asset_by_id(&self, id: AssetId) -> Option<&Asset> {
        self.assets.get(&id).map(|(_, asset)| asset)
    }

    pub fn asset_by_path(&self, path: &str) -> Option<&Asset> {
        if let Some(id) = self.table.get(path) {
            if let Some((_, asset)) = self.assets.get(id) {
                return Some(asset);
            }
        }
        None
    }

    pub fn process(&mut self) {
        self.lately_loaded.clear();
        self.lately_unloaded.clear();
        let to_dispatch = {
            let mut bytes_read = 0;
            self.loading
                .iter()
                .filter_map(|(path, (prot, reader))| {
                    if bytes_read < self.max_bytes_per_frame.unwrap_or(std::usize::MAX) {
                        if let Some(data) = reader.read() {
                            bytes_read += data.len();
                            return Some((path.to_owned(), prot.to_owned(), data));
                        }
                    }
                    None
                })
                .collect::<Vec<_>>()
        };
        for (path, prot, data) in to_dispatch {
            if let Some(protocol) = self.protocols.get_mut(&prot) {
                match protocol.on_load_with_path(&path, data) {
                    AssetLoadResult::Data(data) => {
                        let asset = Asset::new(&prot, &path, data);
                        self.insert(&asset.to_full_path(), asset);
                    }
                    AssetLoadResult::Yield(meta, list) => {
                        let list = list
                            .into_iter()
                            .filter(|(_, path)| self.load(&path).is_ok())
                            .collect();
                        self.yielded.insert(path, (prot, meta, list));
                    }
                    AssetLoadResult::Error(message) => {
                        for reporter in self.error_reporters.values_mut() {
                            reporter.on_report(&prot, &path, &message);
                        }
                    }
                }
            }
        }
        self.loading.retain(|_, (_, reader)| {
            matches!(
                reader.status(),
                FetchStatus::InProgress(_) | FetchStatus::Done
            )
        });
        let yielded = std::mem::take(&mut self.yielded);
        for (path, (prot, meta, list)) in yielded {
            if list.iter().all(|(_, path)| self.table.contains_key(path)) {
                let ptr = self as *const Self;
                if let Some(protocol) = self.protocols.get_mut(&prot) {
                    let list = list
                        .iter()
                        .map(|(key, path)| unsafe {
                            let asset = &(*ptr).table[path];
                            let asset = &(*ptr).assets[asset].1;
                            (key.as_str(), asset)
                        })
                        .collect::<Vec<_>>();
                    match protocol.on_resume(meta, &list) {
                        AssetLoadResult::Data(data) => {
                            let asset = Asset::new(&prot, &path, data);
                            self.insert(&asset.to_full_path(), asset);
                        }
                        AssetLoadResult::Yield(meta, list) => {
                            let list = list
                                .into_iter()
                                .filter(|(_, path)| self.load(&path).is_ok())
                                .collect();
                            self.yielded.insert(path, (prot, meta, list));
                        }
                        AssetLoadResult::Error(message) => {
                            for reporter in self.error_reporters.values_mut() {
                                reporter.on_report(&prot, &path, &message);
                            }
                        }
                    }
                }
            } else {
                self.yielded.insert(path, (prot, meta, list));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assets::protocols::prelude::*;
    use crate::fetch::*;

    #[test]
    fn test_general() {
        let mut fetch_engine = engines::map::MapFetchEngine::default();
        fetch_engine.map.insert(
            "assets.txt".to_owned(),
            br#"
                txt://a.txt
                txt://b.txt
            "#
            .to_vec(),
        );
        fetch_engine.map.insert("a.txt".to_owned(), b"A".to_vec());
        fetch_engine.map.insert("b.txt".to_owned(), b"B".to_vec());

        let mut database = AssetsDatabase::new(fetch_engine);
        database.register(TextAssetProtocol);
        database.register(SetAssetProtocol);
        assert_eq!(database.load("set://assets.txt"), Ok(()));
        assert_eq!(database.loaded_count(), 0);
        assert_eq!(database.loading_count(), 1);
        assert_eq!(database.yielded_count(), 0);
        assert_eq!(database.yielded_deps_count(), 0);

        for _ in 0..2 {
            database.process();
        }
        assert_eq!(database.loaded_count(), 3);
        assert_eq!(database.loading_count(), 0);
        assert_eq!(database.yielded_count(), 0);
        assert_eq!(database.yielded_deps_count(), 0);

        assert!(database.asset_by_path("set://assets.txt").is_some());
        assert_eq!(
            &database
                .asset_by_path("set://assets.txt")
                .unwrap()
                .to_full_path(),
            "set://assets.txt"
        );
        assert!(database
            .asset_by_path("set://assets.txt")
            .unwrap()
            .is::<SetAsset>());
        assert_eq!(
            database
                .asset_by_path("set://assets.txt")
                .unwrap()
                .get::<SetAsset>()
                .unwrap()
                .paths()
                .to_vec(),
            vec!["txt://a.txt".to_owned(), "txt://b.txt".to_owned()],
        );

        assert!(database.asset_by_path("txt://a.txt").is_some());
        assert!(database
            .asset_by_path("txt://a.txt")
            .unwrap()
            .is::<TextAsset>());
        assert_eq!(
            database
                .asset_by_path("txt://a.txt")
                .unwrap()
                .get::<TextAsset>()
                .unwrap()
                .get(),
            "A"
        );

        assert!(database.asset_by_path("txt://b.txt").is_some());
        assert_eq!(
            database
                .asset_by_path("txt://b.txt")
                .unwrap()
                .get::<TextAsset>()
                .unwrap()
                .get(),
            "B"
        );

        assert!(database.remove_by_path("set://assets.txt").is_some());
        assert_eq!(database.loaded_count(), 0);
        assert_eq!(database.loading_count(), 0);
        assert_eq!(database.yielded_count(), 0);
        assert_eq!(database.yielded_deps_count(), 0);
    }
}