Skip to main content

hello_client/
hello_client.rs

1use keket::{
2    database::{AssetDatabase, handle::AssetHandle, path::AssetPath},
3    fetch::{AssetAwaitsAsyncFetch, deferred::DeferredAssetFetch},
4    protocol::{bytes::BytesAssetProtocol, text::TextAssetProtocol},
5};
6use keket_client::{ClientAssetFetch, third_party::reqwest::Url};
7use std::error::Error;
8
9fn main() -> Result<(), Box<dyn Error>> {
10    /* ANCHOR: main */
11    let mut database = AssetDatabase::default()
12        .with_protocol(TextAssetProtocol)
13        .with_protocol(BytesAssetProtocol)
14        // Client asset fetch to request files from asset server.
15        .with_fetch(DeferredAssetFetch::new(ClientAssetFetch::new(
16            // IP address of asset server we connect to.
17            "127.0.0.1:8080",
18        )?));
19
20    // Ensure assets exists or start getting fetched.
21    let lorem = database.ensure("text://lorem.txt")?;
22    let trash = database.ensure("bytes://trash.bin")?;
23
24    // Wait till database is busy.
25    while database.is_busy() {
26        println!("Waiting for database to be free");
27        println!(
28            "Loading:\n- Lorem Ipsum: {}\n- Bytes: {}",
29            lorem.has::<AssetAwaitsAsyncFetch>(&database),
30            trash.has::<AssetAwaitsAsyncFetch>(&database)
31        );
32        database.maintain()?;
33    }
34
35    println!("Lorem Ipsum: {}", lorem.access::<&String>(&database));
36    println!("Bytes: {:?}", trash.access::<&Vec<u8>>(&database));
37
38    // List all assets from client.
39    for (asset_path, url) in database.storage.query::<true, (&AssetPath, &Url)>() {
40        println!("Asset: `{asset_path}` at url: `{url}`");
41    }
42
43    println!("Listening for file changes...");
44    loop {
45        database.maintain()?;
46
47        // With storage change detection we can ask for asset entities
48        // that their paths were updated (hot reloading updates them).
49        if let Some(changes) = database.storage.updated() {
50            for entity in changes.iter_of::<AssetPath>() {
51                println!(
52                    "Asset changed: `{}`",
53                    AssetHandle::new(entity).access::<&AssetPath>(&database)
54                );
55            }
56        }
57
58        // Simulate systems that detect particular asset type reload.
59        for entity in database.storage.added().iter_of::<String>() {
60            println!(
61                "Text asset changed: `{}`",
62                AssetHandle::new(entity).access::<&String>(&database)
63            );
64        }
65        for entity in database.storage.added().iter_of::<Vec<u8>>() {
66            println!(
67                "Bytes asset changed: `{:?}`",
68                AssetHandle::new(entity).access::<&Vec<u8>>(&database)
69            );
70        }
71    }
72    /* ANCHOR_END: main */
73}