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
use crate::{
    assets::{
        asset::Asset,
        protocol::{AssetLoadResult, AssetProtocol, AssetVariant, Meta},
    },
    prefab::{Prefab, PrefabScene},
};
use std::{any::Any, str::from_utf8};

pub struct PrefabAsset(PrefabScene);

impl PrefabAsset {
    pub fn get(&self) -> &PrefabScene {
        &self.0
    }
}

pub struct PrefabAssetProtocol;

impl AssetProtocol for PrefabAssetProtocol {
    fn name(&self) -> &str {
        "prefab"
    }

    fn on_load(&mut self, data: Vec<u8>) -> AssetLoadResult {
        match PrefabScene::from_prefab_str(from_utf8(&data).unwrap()) {
            Ok(data) => {
                if data.dependencies.is_empty() {
                    AssetLoadResult::Data(Box::new(PrefabAsset(data)))
                } else {
                    let list = data
                        .dependencies
                        .iter()
                        .enumerate()
                        .map(|(i, path)| (i.to_string(), path.to_owned()))
                        .collect::<Vec<_>>();
                    AssetLoadResult::Yield(Some(Box::new(data)), list)
                }
            }
            Err(error) => {
                AssetLoadResult::Error(format!("Error loading prefab asset: {:?}", error))
            }
        }
    }

    fn on_resume(&mut self, payload: Meta, _: &[(&str, &Asset)]) -> AssetLoadResult {
        let prefab = *(payload.unwrap() as Box<dyn Any + Send>)
            .downcast::<PrefabScene>()
            .unwrap();
        AssetLoadResult::Data(Box::new(PrefabAsset(prefab)))
    }

    fn on_unload(&mut self, asset: &Asset) -> Option<Vec<AssetVariant>> {
        if let Some(asset) = asset.get::<PrefabAsset>() {
            Some(
                asset
                    .get()
                    .dependencies
                    .iter()
                    .map(|path| AssetVariant::Path(path.to_owned()))
                    .collect(),
            )
        } else {
            None
        }
    }
}