gizmo-renderer 0.1.7

A custom ECS and physics engine aimed for realistic simulations.
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
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
//! Background-thread decoding for textures, OBJ, and GLTF **import** (disk + parse).
//! GPU upload and [`AssetManager`](crate::asset::AssetManager) updates must run on the main thread
//! — call [`AsyncAssetLoader::drain_completed`] each frame and then upload via `AssetManager`.

use crate::asset::{decode_obj_vertices_for_async, decode_rgba_image_file};
use std::collections::{HashMap, HashSet};
use std::sync::mpsc::{self, Receiver, Sender, SyncSender};
use std::sync::{Arc, Mutex};
use std::thread;

#[derive(Debug)]
pub struct TextureReloadCompletion {
    pub cache_key: String,
    pub rgba: Vec<u8>,
    pub width: u32,
    pub height: u32,
    pub entity_ids: Vec<usize>,
}

#[derive(Debug)]
pub struct ObjLoadCompletion {
    pub path: String,
    pub vertices: Vec<crate::gpu_types::Vertex>,
    pub aabb: gizmo_math::Aabb,
    pub handle_ids: Vec<usize>,
}

/// Successful GLTF parse on the worker; GPU upload via [`AssetManager::load_gltf_from_import`](crate::asset::AssetManager::load_gltf_from_import).
#[derive(Debug)]
pub struct GltfImportCompletion {
    pub path: String,
    pub document: gltf::Document,
    pub buffers: Vec<gltf::buffer::Data>,
    pub images: Vec<gltf::image::Data>,
}

#[derive(Debug)]
pub struct GltfImportError {
    pub path: String,
    pub message: String,
}

#[derive(Debug)]
pub struct CompletedAsyncLoads {
    pub textures: Vec<TextureReloadCompletion>,
    pub objs: Vec<ObjLoadCompletion>,
    pub gltfs: Vec<GltfImportCompletion>,
    pub gltf_errors: Vec<GltfImportError>,
}

enum Job {
    Texture { request_path: String },
    Obj { path: String },
    Gltf { path: String },
}

enum WorkerMsg {
    Texture {
        request_path: String,
        cache_key: String,
        result: Result<(Vec<u8>, u32, u32), String>,
    },
    Obj {
        path: String,
        result: Result<(Vec<crate::gpu_types::Vertex>, gizmo_math::Aabb), String>,
    },
    Gltf {
        path: String,
        result: Result<
            (
                gltf::Document,
                Vec<gltf::buffer::Data>,
                Vec<gltf::image::Data>,
            ),
            String,
        >,
    },
}

struct LoaderShared {
    job_tx: SyncSender<Job>,
    result_rx: Receiver<WorkerMsg>,
    /// Original request path (as passed to `request_texture_reload`) → entities
    texture_waiters: HashMap<String, Vec<usize>>,
    obj_waiters: HashMap<String, Vec<usize>>,
    texture_inflight: HashSet<String>,
    obj_inflight: HashSet<String>,
    gltf_inflight: HashSet<String>,
}

/// Thread-safe loader; safe to store as an ECS resource (`Send` + `Sync`).
pub struct AsyncAssetLoader {
    shared: Arc<Mutex<LoaderShared>>,
    _worker: Option<thread::JoinHandle<()>>,
    #[allow(dead_code)]
    result_tx: Sender<WorkerMsg>,
}

impl AsyncAssetLoader {
    pub fn new() -> Self {
        let (job_tx, job_rx) = mpsc::sync_channel::<Job>(64);
        let (result_tx, result_rx) = mpsc::channel::<WorkerMsg>();

        let worker_job_rx = job_rx;
        let worker_result_tx = result_tx.clone();
        #[cfg(not(target_arch = "wasm32"))]
        let _worker = Some(
            thread::Builder::new()
                .name("gizmo-async-assets".into())
                .spawn(move || {
                    for job in worker_job_rx {
                        match job {
                            Job::Texture { request_path } => {
                                let cache_key = std::path::Path::new(&request_path)
                                    .canonicalize()
                                    .map(|p| p.to_string_lossy().into_owned())
                                    .unwrap_or_else(|_| request_path.clone());
                                let result = decode_rgba_image_file(&request_path);
                                let _ = worker_result_tx.send(WorkerMsg::Texture {
                                    request_path,
                                    cache_key,
                                    result,
                                });
                            }
                            Job::Obj { path } => {
                                let result = decode_obj_vertices_for_async(&path);
                                let _ = worker_result_tx.send(WorkerMsg::Obj { path, result });
                            }
                            Job::Gltf { path } => {
                                let result = gltf::import(&path).map_err(|e| e.to_string());
                                let _ = worker_result_tx.send(WorkerMsg::Gltf { path, result });
                            }
                        }
                    }
                })
                .expect("spawn async asset worker"),
        );

        #[cfg(target_arch = "wasm32")]
        let _worker = None;

        Self {
            shared: Arc::new(Mutex::new(LoaderShared {
                job_tx,
                result_rx,
                texture_waiters: HashMap::new(),
                obj_waiters: HashMap::new(),
                texture_inflight: HashSet::new(),
                obj_inflight: HashSet::new(),
                gltf_inflight: HashSet::new(),
            })),
            _worker,
            result_tx,
        }
    }

    /// Queue a texture file decode; when done, [`drain_completed`] yields a row with `entity_ids`.
    /// Duplicate `request_path` while in-flight only adds more waiters (one disk read).
    pub fn request_texture_reload(&self, request_path: String, handle_id: usize) {
        let mut g = self.shared.lock().expect("async asset mutex");
        g.texture_waiters
            .entry(request_path.clone())
            .or_default()
            .push(handle_id);
        if g.texture_inflight.insert(request_path.clone()) {
            #[cfg(not(target_arch = "wasm32"))]
            {
                let _ = g.job_tx.send(Job::Texture { request_path });
            }
            #[cfg(target_arch = "wasm32")]
            {
                let result_tx = self.result_tx.clone();
                let path = request_path.clone();
                wasm_bindgen_futures::spawn_local(async move {
                    let result = fetch_and_decode_texture_wasm(&path).await;
                    let cache_key = path.clone();
                    let _ = result_tx.send(WorkerMsg::Texture {
                        request_path: path,
                        cache_key,
                        result,
                    });
                });
            }
        }
    }

    /// Queue an OBJ load (returns `ObjLoadCompletion` eventually).
    pub fn request_obj_load(&self, path: String, handle_id: usize) {
        let mut g = self.shared.lock().expect("async asset mutex");
        g.obj_waiters
            .entry(path.clone())
            .or_default()
            .push(handle_id);
        if g.obj_inflight.insert(path.clone()) {
            #[cfg(not(target_arch = "wasm32"))]
            {
                let _ = g.job_tx.send(Job::Obj { path });
            }
            #[cfg(target_arch = "wasm32")]
            {
                let result_tx = self.result_tx.clone();
                let path_clone = path.clone();
                wasm_bindgen_futures::spawn_local(async move {
                    let result = fetch_and_decode_obj_wasm(&path_clone).await;
                    let _ = result_tx.send(WorkerMsg::Obj {
                        path: path_clone,
                        result,
                    });
                });
            }
        }
    }

    /// Run `gltf::import` off the main thread; upload with `AssetManager::load_gltf_from_import`.
    pub fn request_gltf_import(&self, path: String) -> bool {
        tracing::info!(">>> request_gltf_import çağrıldı: {}", path);
        let mut g = self.shared.lock().expect("async asset mutex");
        if g.gltf_inflight.contains(&path) {
            tracing::info!(">>> request_gltf_import: Model zaten yükleniyor!");
            return false;
        }
        g.gltf_inflight.insert(path.clone());

        #[cfg(not(target_arch = "wasm32"))]
        {
            let ok = g.job_tx.send(Job::Gltf { path }).is_ok();
            tracing::info!(">>> request_gltf_import: İşlem gönderildi mi? {}", ok);
            ok
        }
        #[cfg(target_arch = "wasm32")]
        {
            let result_tx = self.result_tx.clone();
            let path_clone = path.clone();
            wasm_bindgen_futures::spawn_local(async move {
                let result = fetch_and_parse_gltf_wasm(&path_clone).await;
                let _ = result_tx.send(WorkerMsg::Gltf {
                    path: path_clone,
                    result,
                });
            });
            true
        }
    }

    /// Non-blocking: collect all finished jobs since the last call.
    pub fn drain_completed(&self) -> CompletedAsyncLoads {
        let mut out = CompletedAsyncLoads {
            textures: Vec::new(),
            objs: Vec::new(),
            gltfs: Vec::new(),
            gltf_errors: Vec::new(),
        };

        let mut g = self.shared.lock().expect("async asset mutex");
        while let Ok(msg) = g.result_rx.try_recv() {
            match msg {
                WorkerMsg::Texture {
                    request_path,
                    cache_key,
                    result,
                } => {
                    g.texture_inflight.remove(&request_path);
                    let entity_ids = g.texture_waiters.remove(&request_path).unwrap_or_default();
                    if entity_ids.is_empty() {
                        continue;
                    }
                    match result {
                        Ok((rgba, width, height)) => {
                            out.textures.push(TextureReloadCompletion {
                                cache_key,
                                rgba,
                                width,
                                height,
                                entity_ids,
                            });
                        }
                        Err(e) => {
                            tracing::error!(
                                "[AsyncAssetLoader] Texture decode failed ({request_path}): {e}"
                            );
                        }
                    }
                }
                WorkerMsg::Obj { path, result } => {
                    g.obj_inflight.remove(&path);
                    let handle_ids = g.obj_waiters.remove(&path).unwrap_or_default();
                    if handle_ids.is_empty() {
                        continue;
                    }
                    match result {
                        Ok((vertices, aabb)) => {
                            out.objs.push(ObjLoadCompletion {
                                path,
                                vertices,
                                aabb,
                                handle_ids,
                            });
                        }
                        Err(e) => {
                            tracing::error!("[AsyncAssetLoader] OBJ decode failed ({path}): {e}");
                        }
                    }
                }
                WorkerMsg::Gltf { path, result } => {
                    g.gltf_inflight.remove(&path);
                    match result {
                        Ok((document, buffers, images)) => {
                            out.gltfs.push(GltfImportCompletion {
                                path,
                                document,
                                buffers,
                                images,
                            });
                        }
                        Err(message) => {
                            out.gltf_errors.push(GltfImportError { path, message });
                        }
                    }
                }
            }
        }

        out
    }
}

impl Default for AsyncAssetLoader {
    fn default() -> Self {
        Self::new()
    }
}

// ── WASM Fetch & Parse Helpers ──────────────────────────────────────────────

#[cfg(target_arch = "wasm32")]
async fn native_fetch_bytes(url: &str) -> Result<Vec<u8>, String> {
    use wasm_bindgen::JsCast;
    use wasm_bindgen_futures::JsFuture;

    let window = web_sys::window().ok_or("No global window found")?;
    let resp_value = JsFuture::from(window.fetch_with_str(url))
        .await
        .map_err(|e| format!("Fetch failed for {url}: {e:?}"))?;
    let resp: web_sys::Response = resp_value.dyn_into().map_err(|_| "Failed to cast to Response")?;

    if !resp.ok() {
        return Err(format!("HTTP error status for {url}: {}", resp.status()));
    }

    let array_buffer_value = JsFuture::from(resp.array_buffer().map_err(|e| format!("Failed to get array buffer: {e:?}"))?)
        .await
        .map_err(|e| format!("Failed to resolve array buffer: {e:?}"))?;
    let array_buffer = js_sys::ArrayBuffer::from(array_buffer_value);
    let uint8_array = js_sys::Uint8Array::new(&array_buffer);
    let mut bytes = vec![0; uint8_array.length() as usize];
    uint8_array.copy_to(&mut bytes);
    Ok(bytes)
}

#[cfg(target_arch = "wasm32")]
async fn fetch_and_decode_texture_wasm(path: &str) -> Result<(Vec<u8>, u32, u32), String> {
    let bytes = native_fetch_bytes(path).await?;

    let img = image::load_from_memory(&bytes)
        .map_err(|e| format!("Cannot read texture ({path}) from memory: {e}"))?
        .to_rgba8();
    let (w, h) = img.dimensions();
    Ok((img.into_raw(), w, h))
}

#[cfg(target_arch = "wasm32")]
async fn fetch_and_parse_gltf_wasm(
    path: &str,
) -> Result<
    (
        gltf::Document,
        Vec<gltf::buffer::Data>,
        Vec<gltf::image::Data>,
    ),
    String,
> {
    let bytes = native_fetch_bytes(path).await?;

    gltf::import_slice(&bytes)
        .map_err(|e| format!("glTF parse slice failed ({path}): {e}"))
}

#[cfg(target_arch = "wasm32")]
async fn fetch_and_decode_obj_wasm(
    path: &str,
) -> Result<(Vec<crate::gpu_types::Vertex>, gizmo_math::Aabb), String> {
    let bytes = native_fetch_bytes(path).await?;

    let mut reader = std::io::Cursor::new(bytes);
    let (models, _) = tobj::load_obj_buf(
        &mut reader,
        &tobj::LoadOptions {
            single_index: true,
            triangulate: true,
            ignore_points: true,
            ignore_lines: true,
        },
        |_| Err(tobj::LoadError::OpenFileFailed),
    )
    .map_err(|e| format!("OBJ load from buffer failed ({path}): {e}"))?;

    if models.is_empty() {
        return Err(format!("OBJ file contains no models: {path}"));
    }

    let mut aabb = gizmo_math::Aabb::empty();
    let mut vertices = Vec::new();

    for model in &models {
        let m = &model.mesh;
        let has_normals = !m.normals.is_empty();
        let has_texcoords = !m.texcoords.is_empty();

        for &raw_idx in &m.indices {
            let idx = raw_idx as usize;
            let pos_base = idx * 3;
            if pos_base + 2 >= m.positions.len() {
                return Err(format!("OBJ ({path}): position index out of range"));
            }
            let position = [
                m.positions[pos_base],
                m.positions[pos_base + 1],
                m.positions[pos_base + 2],
            ];
            aabb.extend(gizmo_math::Vec3::new(position[0], position[1], position[2]));

            let normal = if has_normals {
                let n_base = idx * 3;
                [
                    m.normals[n_base],
                    m.normals[n_base + 1],
                    m.normals[n_base + 2],
                ]
            } else {
                [0.0, 1.0, 0.0]
            };

            let tex_coords = if has_texcoords {
                let uv_base = idx * 2;
                [m.texcoords[uv_base], 1.0 - m.texcoords[uv_base + 1]]
            } else {
                [0.0, 0.0]
            };

            vertices.push(crate::renderer::Vertex {
                position,
                normal,
                tex_coords,
                color: [1.0, 1.0, 1.0],
                joint_indices: [0; 4],
                joint_weights: [0.0; 4],
            });
        }
    }

    Ok((vertices, aabb))
}