nightshade 0.13.3

A cross-platform data-oriented game engine.
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
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Asynchronous texture loading with platform-specific implementations.
//!
//! Load textures in the background without blocking the main thread:
//!
//! - [`TextureLoadQueue`]: Queue for pending/in-flight/completed texture loads
//! - [`SharedTextureQueue`]: Thread-safe handle for async operations
//! - [`AssetLoadingState`]: Progress tracking for loading screens
//! - `process_texture_queue`: Process pending loads each frame
//! - `process_and_load_textures`: Combined process + upload to GPU
//!
//! # Platform Behavior
//!
//! | Platform | Loading Method |
//! |----------|----------------|
//! | Desktop | Synchronous file read from disk |
//! | WASM | Async HTTP fetch via ehttp |
//!
//! # Basic Usage
//!
//! ```ignore
//! // Create shared queue
//! let queue = create_shared_queue();
//!
//! // Queue textures for loading
//! queue_texture_from_path(&queue, "assets/textures/albedo.png");
//! queue_texture_from_path(&queue, "assets/textures/normal.png");
//!
//! // Track loading state
//! let mut loading_state = AssetLoadingState::new(2);  // 2 textures
//!
//! // Process each frame
//! fn run_systems(&mut self, world: &mut World) {
//!     let status = process_and_load_textures(
//!         &self.queue,
//!         world,
//!         &mut self.loading_state,
//!         4,  // Max concurrent loads
//!     );
//!
//!     if status == AssetLoadingStatus::Complete {
//!         println!("All textures loaded!");
//!     }
//! }
//! ```
//!
//! # Loading Screen Pattern
//!
//! ```ignore
//! struct LoadingScreen {
//!     queue: SharedTextureQueue,
//!     state: AssetLoadingState,
//! }
//!
//! impl LoadingScreen {
//!     fn new(texture_paths: &[&str]) -> Self {
//!         let queue = create_shared_queue();
//!         for path in texture_paths {
//!             queue_texture_from_path(&queue, path);
//!         }
//!         Self {
//!             queue,
//!             state: AssetLoadingState::new(texture_paths.len()),
//!         }
//!     }
//!
//!     fn update(&mut self, world: &mut World) -> bool {
//!         let status = process_and_load_textures(&self.queue, world, &mut self.state, 4);
//!         status == AssetLoadingStatus::Complete
//!     }
//!
//!     fn progress(&self) -> f32 {
//!         self.state.progress()  // 0.0 to 1.0
//!     }
//! }
//! ```
//!
//! # Asset Search Paths
//!
//! Configure where to search for texture files:
//!
//! ```ignore
//! // Set search paths at startup
//! set_asset_search_paths(vec![
//!     "assets/".to_string(),
//!     "content/textures/".to_string(),
//! ]);
//!
//! // Now queue_texture_from_path will search these directories
//! queue_texture_from_path(&queue, "player.png");
//! // Searches: assets/player.png, content/textures/player.png
//! ```
//!
//! # Manual Queue Control
//!
//! ```ignore
//! // Queue with explicit URL (WASM) or path (desktop)
//! if let Ok(mut q) = queue.lock() {
//!     q.queue_texture("my_texture".to_string(), "https://example.com/tex.png".to_string());
//! }
//!
//! // Process without auto-upload
//! process_texture_queue(&queue, 4);
//!
//! // Manually handle completed textures
//! if let Ok(mut q) = queue.lock() {
//!     for loaded in q.take_completed() {
//!         world.queue_command(WorldCommand::LoadTexture {
//!             name: loaded.name,
//!             rgba_data: loaded.rgba_data,
//!             width: loaded.width,
//!             height: loaded.height,
//!         });
//!     }
//! }
//! ```
//!
//! # AssetLoadingState
//!
//! | Method | Description |
//! |--------|-------------|
//! | `progress()` | Returns 0.0-1.0 completion ratio |
//! | `is_complete()` | True when all textures processed |
//! | `loaded_textures` | Count of successfully loaded |
//! | `failed_textures` | Count of failed loads |
//!
//! # Error Handling
//!
//! Failed loads are counted but don't block completion. Check `failed_textures`
//! after loading completes to detect missing assets.

use crate::ecs::world::World;
use crate::ecs::world::commands::WorldCommand;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, OnceLock};

static ASSET_SEARCH_PATHS: OnceLock<Vec<String>> = OnceLock::new();

pub fn set_asset_search_paths(paths: Vec<String>) {
    let _ = ASSET_SEARCH_PATHS.set(paths);
}

pub fn get_asset_search_paths() -> &'static [String] {
    ASSET_SEARCH_PATHS.get().map_or(&[], |v| v.as_slice())
}

#[derive(Default)]
pub struct TextureLoadQueue {
    pending: VecDeque<TextureLoadRequest>,
    in_flight: Vec<String>,
    completed: Vec<LoadedTexture>,
    failed: usize,
}

pub struct TextureLoadRequest {
    pub url: String,
    pub name: String,
}

pub struct LoadedTexture {
    pub name: String,
    pub rgba_data: Vec<u8>,
    pub width: u32,
    pub height: u32,
}

impl TextureLoadQueue {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn queue_texture(&mut self, name: String, url: String) {
        if !self.in_flight.contains(&name)
            && !self.pending.iter().any(|r| r.name == name)
            && !self.completed.iter().any(|t| t.name == name)
        {
            self.pending.push_back(TextureLoadRequest { url, name });
        }
    }

    pub fn take_completed(&mut self) -> Vec<LoadedTexture> {
        std::mem::take(&mut self.completed)
    }

    pub fn has_pending(&self) -> bool {
        !self.pending.is_empty() || !self.in_flight.is_empty()
    }

    pub fn pending_count(&self) -> usize {
        self.pending.len() + self.in_flight.len()
    }

    pub fn failed_count(&self) -> usize {
        self.failed
    }

    pub fn processed_count(&self) -> usize {
        self.completed.len() + self.failed
    }
}

pub type SharedTextureQueue = Arc<Mutex<TextureLoadQueue>>;

pub fn create_shared_queue() -> SharedTextureQueue {
    Arc::new(Mutex::new(TextureLoadQueue::new()))
}

#[cfg(target_arch = "wasm32")]
pub fn process_texture_queue(queue: &SharedTextureQueue, max_concurrent: usize) {
    let requests: Vec<TextureLoadRequest> = {
        let mut q = queue.lock().unwrap();
        let available_slots = max_concurrent.saturating_sub(q.in_flight.len());
        let mut requests = Vec::new();
        for _ in 0..available_slots {
            if let Some(req) = q.pending.pop_front() {
                q.in_flight.push(req.name.clone());
                requests.push(req);
            }
        }
        requests
    };

    for request in requests {
        let queue_clone = Arc::clone(queue);
        let name = request.name.clone();

        ehttp::fetch(
            ehttp::Request::get(&request.url),
            move |result: ehttp::Result<ehttp::Response>| {
                let mut q = queue_clone.lock().unwrap();
                q.in_flight.retain(|n| n != &name);

                match result {
                    Ok(response) => {
                        if response.ok {
                            if let Ok(img) = image::load_from_memory(&response.bytes) {
                                let rgba = img.to_rgba8();
                                let (width, height) = rgba.dimensions();
                                q.completed.push(LoadedTexture {
                                    name,
                                    rgba_data: rgba.into_raw(),
                                    width,
                                    height,
                                });
                            } else {
                                tracing::warn!("Failed to decode image: {}", name);
                                q.failed += 1;
                            }
                        } else {
                            tracing::warn!(
                                "HTTP error loading texture {}: {}",
                                name,
                                response.status
                            );
                            q.failed += 1;
                        }
                    }
                    Err(error) => {
                        tracing::warn!("Failed to fetch texture {}: {}", name, error);
                        q.failed += 1;
                    }
                }
            },
        );
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn process_texture_queue(queue: &SharedTextureQueue, _max_concurrent: usize) {
    use std::path::Path;

    let requests: Vec<TextureLoadRequest> = {
        let mut q = queue.lock().unwrap();
        std::mem::take(&mut q.pending).into()
    };

    for request in requests {
        let path = Path::new(&request.url);
        let bytes = if path.exists() {
            std::fs::read(path)
        } else {
            find_texture_file(&request.url)
        };

        match bytes {
            Ok(bytes) => {
                if let Ok(img) = image::load_from_memory(&bytes) {
                    let rgba = img.to_rgba8();
                    let (width, height) = rgba.dimensions();
                    let mut q = queue.lock().unwrap();
                    q.completed.push(LoadedTexture {
                        name: request.name,
                        rgba_data: rgba.into_raw(),
                        width,
                        height,
                    });
                } else {
                    tracing::warn!("Failed to decode image: {}", request.name);
                    let mut q = queue.lock().unwrap();
                    q.failed += 1;
                }
            }
            Err(error) => {
                tracing::warn!("Failed to read texture {}: {}", request.name, error);
                let mut q = queue.lock().unwrap();
                q.failed += 1;
            }
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn find_texture_file(url: &str) -> std::io::Result<Vec<u8>> {
    use std::path::Path;

    let candidate = Path::new(url);
    if candidate.exists() {
        return std::fs::read(candidate);
    }

    for prefix in get_asset_search_paths() {
        let candidate = Path::new(prefix).join(url);
        if candidate.exists() {
            return std::fs::read(&candidate);
        }
    }

    #[cfg(all(target_os = "android", feature = "android"))]
    if let Some(app) = crate::filesystem::get_android_app() {
        if let Some(bytes) = crate::filesystem::read_android_asset(app, url) {
            return Ok(bytes);
        }
        for prefix in get_asset_search_paths() {
            let prefixed = format!("{}/{}", prefix, url);
            if let Some(bytes) = crate::filesystem::read_android_asset(app, &prefixed) {
                return Ok(bytes);
            }
        }
    }

    Err(std::io::Error::new(
        std::io::ErrorKind::NotFound,
        format!("Texture not found: {}", url),
    ))
}

#[cfg(all(feature = "file_watcher", not(target_arch = "wasm32")))]
fn resolve_texture_path(name: &str) -> Option<std::path::PathBuf> {
    use std::path::Path;

    let candidate = Path::new(name);
    if candidate.exists() {
        return Some(candidate.to_path_buf());
    }
    for prefix in get_asset_search_paths() {
        let candidate = Path::new(prefix).join(name);
        if candidate.exists() {
            return Some(candidate);
        }
    }
    None
}

pub fn queue_texture_from_path(queue: &SharedTextureQueue, path: &str) {
    let normalized = path.replace('\\', "/");
    let name = normalized.clone();

    #[cfg(target_arch = "wasm32")]
    let url = {
        if let Some(stripped) = normalized.strip_prefix("assets/") {
            stripped.to_string()
        } else {
            normalized
        }
    };

    #[cfg(not(target_arch = "wasm32"))]
    let url = normalized;

    if let Ok(mut q) = queue.lock() {
        q.queue_texture(name, url);
    }
}

#[derive(Default, Clone, Copy)]
pub struct AssetLoadingState {
    pub total_textures: usize,
    pub loaded_textures: usize,
    pub failed_textures: usize,
}

impl AssetLoadingState {
    pub fn new(total_textures: usize) -> Self {
        Self {
            total_textures,
            loaded_textures: 0,
            failed_textures: 0,
        }
    }

    pub fn progress(&self) -> f32 {
        if self.total_textures == 0 {
            return 1.0;
        }
        (self.loaded_textures + self.failed_textures) as f32 / self.total_textures as f32
    }

    pub fn is_complete(&self) -> bool {
        self.total_textures > 0
            && (self.loaded_textures + self.failed_textures) >= self.total_textures
    }
}

#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub enum AssetLoadingStatus {
    #[default]
    Loading,
    Complete,
}

pub fn process_and_load_textures(
    queue: &SharedTextureQueue,
    world: &mut World,
    loading_state: &mut AssetLoadingState,
    max_concurrent: usize,
) -> AssetLoadingStatus {
    process_texture_queue(queue, max_concurrent);

    if let Ok(mut queue_guard) = queue.lock() {
        let completed = queue_guard.take_completed();
        let failed = queue_guard.failed_count();
        loading_state.loaded_textures += completed.len();
        loading_state.failed_textures = failed;

        for loaded in completed {
            #[cfg(all(feature = "file_watcher", not(target_arch = "wasm32")))]
            {
                let resolved_path = resolve_texture_path(&loaded.name);
                if let Some(path) = resolved_path {
                    world
                        .resources
                        .asset_watcher
                        .track_texture(loaded.name.clone(), path);
                }
            }
            world.queue_command(WorldCommand::LoadTexture {
                name: loaded.name,
                rgba_data: loaded.rgba_data,
                width: loaded.width,
                height: loaded.height,
            });
        }

        let pending = queue_guard.has_pending();
        let all_processed =
            (loading_state.loaded_textures + failed) >= loading_state.total_textures;

        if !pending && all_processed {
            if failed > 0 {
                tracing::warn!(
                    "Asset loading complete: {} textures loaded, {} failed",
                    loading_state.loaded_textures,
                    failed
                );
            } else if loading_state.loaded_textures > 0 {
                tracing::info!(
                    "Asset loading complete: {} textures loaded",
                    loading_state.loaded_textures
                );
            }
            return AssetLoadingStatus::Complete;
        }
    }

    AssetLoadingStatus::Loading
}