nightshade 0.14.0

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
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
512
513
use crate::ecs::asset_id::TextureId;
use crate::ecs::generational_registry::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use wgpu::util::DeviceExt;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TextureUsage {
    Color,
    Linear,
}

impl TextureUsage {
    pub fn wgpu_format(self) -> wgpu::TextureFormat {
        match self {
            Self::Color => wgpu::TextureFormat::Rgba8UnormSrgb,
            Self::Linear => wgpu::TextureFormat::Rgba8Unorm,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SamplerWrap {
    Repeat,
    MirroredRepeat,
    ClampToEdge,
}

impl SamplerWrap {
    pub fn wgpu_address_mode(self) -> wgpu::AddressMode {
        match self {
            Self::Repeat => wgpu::AddressMode::Repeat,
            Self::MirroredRepeat => wgpu::AddressMode::MirrorRepeat,
            Self::ClampToEdge => wgpu::AddressMode::ClampToEdge,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SamplerFilter {
    Nearest,
    Linear,
}

impl SamplerFilter {
    pub fn wgpu_filter_mode(self) -> wgpu::FilterMode {
        match self {
            Self::Nearest => wgpu::FilterMode::Nearest,
            Self::Linear => wgpu::FilterMode::Linear,
        }
    }

    pub fn wgpu_mipmap_filter_mode(self) -> wgpu::MipmapFilterMode {
        match self {
            Self::Nearest => wgpu::MipmapFilterMode::Nearest,
            Self::Linear => wgpu::MipmapFilterMode::Linear,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SamplerSettings {
    pub wrap_u: SamplerWrap,
    pub wrap_v: SamplerWrap,
    pub mag_filter: SamplerFilter,
    pub min_filter: SamplerFilter,
    pub mipmap_filter: SamplerFilter,
}

impl SamplerSettings {
    pub const DEFAULT: Self = Self {
        wrap_u: SamplerWrap::Repeat,
        wrap_v: SamplerWrap::Repeat,
        mag_filter: SamplerFilter::Linear,
        min_filter: SamplerFilter::Linear,
        mipmap_filter: SamplerFilter::Linear,
    };

    pub fn signature(&self) -> String {
        let wrap_char = |w: SamplerWrap| match w {
            SamplerWrap::Repeat => 'r',
            SamplerWrap::MirroredRepeat => 'm',
            SamplerWrap::ClampToEdge => 'c',
        };
        let filter_char = |f: SamplerFilter| match f {
            SamplerFilter::Nearest => 'n',
            SamplerFilter::Linear => 'l',
        };
        format!(
            "{}{}{}{}{}",
            wrap_char(self.wrap_u),
            wrap_char(self.wrap_v),
            filter_char(self.mag_filter),
            filter_char(self.min_filter),
            filter_char(self.mipmap_filter),
        )
    }
}

impl Default for SamplerSettings {
    fn default() -> Self {
        Self::DEFAULT
    }
}

#[derive(Default)]
pub struct TextureCache {
    pub registry: GenerationalRegistry<TextureEntry>,
    pub pending_references: HashMap<String, usize>,
    pub protected_names: std::collections::HashSet<String>,
}

impl TextureCache {
    pub fn get(&self, name: &str) -> Option<&TextureEntry> {
        let index = self.registry.name_to_index.get(name)?;
        self.registry.entries[*index as usize].as_ref()
    }
}

pub struct TextureEntry {
    pub texture: wgpu::Texture,
    pub view: wgpu::TextureView,
    pub sampler: wgpu::Sampler,
}

#[derive(Debug, Clone, Copy)]
pub struct TextureUploadSpec {
    pub format: wgpu::TextureFormat,
    pub sampler: SamplerSettings,
}

pub struct TextureUploadRequest<'a> {
    pub name: String,
    pub rgba_data: &'a [u8],
    pub dimensions: (u32, u32),
    pub spec: TextureUploadSpec,
}

pub fn texture_cache_load_from_raw_rgba_with_format(
    cache: &mut TextureCache,
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    mip_generator: &super::mip_generator::MipGenerator,
    request: TextureUploadRequest<'_>,
) -> Result<TextureId, String> {
    let TextureUploadRequest {
        name,
        rgba_data,
        dimensions,
        spec,
    } = request;
    let format = spec.format;
    let sampler_settings = spec.sampler;
    if let Some((index, generation)) = registry_lookup_index(&cache.registry, &name)
        && registry_is_filled(&cache.registry, index)
    {
        return Ok(TextureId::new(index, generation));
    }

    let pending_refs = cache.pending_references.remove(&name).unwrap_or(0);

    let (width, height) = dimensions;
    let largest = width.max(height).max(1);
    let mip_level_count = (largest as f32).log2().floor() as u32 + 1;

    let size = wgpu::Extent3d {
        width,
        height,
        depth_or_array_layers: 1,
    };

    let supports_gpu_mips = matches!(
        format,
        wgpu::TextureFormat::Rgba8UnormSrgb | wgpu::TextureFormat::Rgba8Unorm
    ) && mip_level_count > 1;

    let mut usage = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST;
    if supports_gpu_mips {
        usage |= wgpu::TextureUsages::RENDER_ATTACHMENT;
    }

    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some(&name),
        size,
        mip_level_count,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format,
        usage,
        view_formats: &[],
    });

    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        rgba_data,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(4 * width),
            rows_per_image: Some(height),
        },
        size,
    );

    if supports_gpu_mips {
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("Texture Cache Mip Gen"),
        });
        mip_generator.generate_mips(device, &mut encoder, &texture, 0);
        queue.submit(std::iter::once(encoder.finish()));
    } else if mip_level_count > 1 {
        let is_srgb = matches!(
            format,
            wgpu::TextureFormat::Rgba8UnormSrgb | wgpu::TextureFormat::Bgra8UnormSrgb
        );
        let mut current = rgba_data.to_vec();
        let mut current_width = width;
        let mut current_height = height;
        for mip in 1..mip_level_count {
            let (downsampled, new_width, new_height) =
                downsample_rgba8_box(&current, current_width, current_height, is_srgb);
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &texture,
                    mip_level: mip,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                &downsampled,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(4 * new_width),
                    rows_per_image: Some(new_height),
                },
                wgpu::Extent3d {
                    width: new_width,
                    height: new_height,
                    depth_or_array_layers: 1,
                },
            );
            current = downsampled;
            current_width = new_width;
            current_height = new_height;
        }
    }

    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());

    let mipmap_filter = sampler_settings.mipmap_filter.wgpu_mipmap_filter_mode();
    let min_filter = sampler_settings.min_filter.wgpu_filter_mode();
    let mag_filter = sampler_settings.mag_filter.wgpu_filter_mode();
    let supports_anisotropy = matches!(min_filter, wgpu::FilterMode::Linear)
        && matches!(mag_filter, wgpu::FilterMode::Linear)
        && matches!(mipmap_filter, wgpu::MipmapFilterMode::Linear);

    let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
        label: Some(&format!("{} Sampler", name)),
        address_mode_u: sampler_settings.wrap_u.wgpu_address_mode(),
        address_mode_v: sampler_settings.wrap_v.wgpu_address_mode(),
        address_mode_w: wgpu::AddressMode::Repeat,
        mag_filter,
        min_filter,
        mipmap_filter,
        anisotropy_clamp: if supports_anisotropy { 16 } else { 1 },
        ..Default::default()
    });

    let entry = TextureEntry {
        texture,
        view,
        sampler,
    };

    let (index, generation) = registry_insert(&mut cache.registry, name, entry);
    cache.registry.reference_counts[index as usize] += pending_refs;

    Ok(TextureId::new(index, generation))
}

pub fn texture_cache_reserve_id(cache: &mut TextureCache, name: String) -> TextureId {
    let (index, generation) = registry_reserve_name(&mut cache.registry, name);
    TextureId::new(index, generation)
}

pub fn texture_cache_add_reference(cache: &mut TextureCache, name: &str) {
    if let Some(&index) = cache.registry.name_to_index.get(name) {
        registry_add_reference(&mut cache.registry, index);
    } else {
        *cache
            .pending_references
            .entry(name.to_string())
            .or_insert(0) += 1;
    }
}

pub fn texture_cache_remove_reference(cache: &mut TextureCache, name: &str) {
    if let Some(&index) = cache.registry.name_to_index.get(name) {
        registry_remove_reference(&mut cache.registry, index);
    } else if let Some(count) = cache.pending_references.get_mut(name) {
        *count = count.saturating_sub(1);
        if *count == 0 {
            cache.pending_references.remove(name);
        }
    }
}

pub fn texture_cache_remove_unused(cache: &mut TextureCache) -> Vec<String> {
    let mut removed = Vec::new();
    for index in 0..cache.registry.entries.len() {
        if cache.registry.reference_counts[index] == 0 && cache.registry.entries[index].is_some() {
            if let Some(name) = cache.registry.index_to_name[index].as_ref()
                && cache.protected_names.contains(name)
            {
                continue;
            }
            if let Some(name) = cache.registry.index_to_name[index].take() {
                cache.registry.name_to_index.remove(&name);
                removed.push(name);
            }
            cache.registry.entries[index] = None;
            cache.registry.free_indices.push(index as u32);
        }
    }
    removed
}

pub fn texture_cache_protect(cache: &mut TextureCache, name: String) {
    cache.protected_names.insert(name);
}

pub enum TextureReloadResult {
    UpdatedInPlace,
    Recreated,
    NotFound,
}

pub fn texture_cache_reload(
    cache: &mut TextureCache,
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    name: &str,
    rgba_data: &[u8],
    width: u32,
    height: u32,
) -> TextureReloadResult {
    let Some(&index) = cache.registry.name_to_index.get(name) else {
        tracing::warn!("Texture reload: '{}' not found in cache", name);
        return TextureReloadResult::NotFound;
    };
    let Some(entry) = cache.registry.entries[index as usize].as_ref() else {
        tracing::warn!("Texture reload: '{}' entry is empty", name);
        return TextureReloadResult::NotFound;
    };

    let existing_size = entry.texture.size();
    if existing_size.width == width && existing_size.height == height {
        tracing::info!(
            "Texture reload: '{}' updated in-place ({}x{})",
            name,
            width,
            height
        );
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &entry.texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            rgba_data,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(4 * width),
                rows_per_image: Some(height),
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        TextureReloadResult::UpdatedInPlace
    } else {
        let existing_format = entry.texture.format();
        let size = wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        };
        let texture = device.create_texture_with_data(
            queue,
            &wgpu::TextureDescriptor {
                label: Some(name),
                size,
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: existing_format,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            },
            wgpu::util::TextureDataOrder::LayerMajor,
            rgba_data,
        );
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some(&format!("{} Sampler", name)),
            address_mode_u: wgpu::AddressMode::Repeat,
            address_mode_v: wgpu::AddressMode::Repeat,
            address_mode_w: wgpu::AddressMode::Repeat,
            mag_filter: wgpu::FilterMode::Nearest,
            min_filter: wgpu::FilterMode::Nearest,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });
        if let Some(slot) = cache.registry.entries[index as usize].as_mut() {
            *slot = TextureEntry {
                texture,
                view,
                sampler,
            };
        }
        tracing::info!(
            "Texture reload: '{}' recreated ({}x{} -> {}x{})",
            name,
            existing_size.width,
            existing_size.height,
            width,
            height
        );
        TextureReloadResult::Recreated
    }
}

fn downsample_rgba8_box(
    src: &[u8],
    src_width: u32,
    src_height: u32,
    is_srgb: bool,
) -> (Vec<u8>, u32, u32) {
    let dst_width = (src_width / 2).max(1);
    let dst_height = (src_height / 2).max(1);
    let mut dst = vec![0u8; (dst_width * dst_height * 4) as usize];

    for y in 0..dst_height {
        for x in 0..dst_width {
            let dst_index = ((y * dst_width + x) * 4) as usize;
            let mut sum = [0.0_f32; 4];
            let mut count = 0.0_f32;

            for dy in 0..2 {
                for dx in 0..2 {
                    let sx = (x * 2 + dx).min(src_width.saturating_sub(1));
                    let sy = (y * 2 + dy).min(src_height.saturating_sub(1));
                    let src_index = ((sy * src_width + sx) * 4) as usize;

                    if is_srgb {
                        sum[0] += srgb_byte_to_linear(src[src_index]);
                        sum[1] += srgb_byte_to_linear(src[src_index + 1]);
                        sum[2] += srgb_byte_to_linear(src[src_index + 2]);
                    } else {
                        sum[0] += src[src_index] as f32 / 255.0;
                        sum[1] += src[src_index + 1] as f32 / 255.0;
                        sum[2] += src[src_index + 2] as f32 / 255.0;
                    }
                    sum[3] += src[src_index + 3] as f32 / 255.0;
                    count += 1.0;
                }
            }

            sum[0] /= count;
            sum[1] /= count;
            sum[2] /= count;
            sum[3] /= count;

            if is_srgb {
                dst[dst_index] = linear_to_srgb_byte(sum[0]);
                dst[dst_index + 1] = linear_to_srgb_byte(sum[1]);
                dst[dst_index + 2] = linear_to_srgb_byte(sum[2]);
            } else {
                dst[dst_index] = (sum[0] * 255.0).round().clamp(0.0, 255.0) as u8;
                dst[dst_index + 1] = (sum[1] * 255.0).round().clamp(0.0, 255.0) as u8;
                dst[dst_index + 2] = (sum[2] * 255.0).round().clamp(0.0, 255.0) as u8;
            }
            dst[dst_index + 3] = (sum[3] * 255.0).round().clamp(0.0, 255.0) as u8;
        }
    }

    (dst, dst_width, dst_height)
}

fn srgb_byte_to_linear(value: u8) -> f32 {
    let normalized = value as f32 / 255.0;
    if normalized <= 0.04045 {
        normalized / 12.92
    } else {
        ((normalized + 0.055) / 1.055).powf(2.4)
    }
}

fn linear_to_srgb_byte(value: f32) -> u8 {
    let clamped = value.clamp(0.0, 1.0);
    let encoded = if clamped <= 0.0031308 {
        clamped * 12.92
    } else {
        1.055 * clamped.powf(1.0 / 2.4) - 0.055
    };
    (encoded * 255.0).round().clamp(0.0, 255.0) as u8
}