Skip to main content

euv_core/game/engine3d/texture/
fn.rs

1use super::*;
2
3/// Converts an 8-bit sRGB channel `[0..255]` into linear light `[0.0..1.0]`.
4///
5/// # Arguments
6///
7/// - `u8` - sRGB channel byte.
8///
9/// # Returns
10///
11/// - `f32` - Linear-light scalar in `[0.0, 1.0]`.
12#[cfg_attr(not(target_arch = "wasm32"), inline)]
13#[must_use]
14pub fn srgb_u8_to_linear(channel: u8) -> f32 {
15    let norm: f32 = f32::from(channel) / 255.0;
16    if norm <= 0.040_45 {
17        norm / 12.92
18    } else {
19        ((norm + 0.055) / 1.055).powf(2.4)
20    }
21}
22
23/// Converts a linear-light scalar `[0.0..1.0]` into an 8-bit sRGB channel `[0..255]`.
24///
25/// # Arguments
26///
27/// - `f32` - Linear-light channel value.
28///
29/// # Returns
30///
31/// - `u8` - sRGB-encoded byte value.
32#[cfg_attr(not(target_arch = "wasm32"), inline)]
33#[must_use]
34pub fn linear_to_srgb_u8(linear: f32) -> u8 {
35    let clamped: f32 = linear.clamp(0.0, 1.0);
36    let encoded: f32 = if clamped <= 0.003_130_8 {
37        clamped * 12.92
38    } else {
39        1.055 * clamped.powf(1.0 / 2.4) - 0.055
40    };
41    (encoded * 255.0).round().clamp(0.0, 255.0) as u8
42}
43
44/// Applies `wrap_mode` to a normalized texture coordinate `coord` producing `[0.0, 1.0]`.
45///
46/// # Arguments
47///
48/// - `f32` - Unwrapped texture coordinate.
49/// - `TextureWrapMode` - Wrapping policy.
50///
51/// # Returns
52///
53/// - `f32` - Wrapped coordinate in `[0.0, 1.0]`.
54#[cfg_attr(not(target_arch = "wasm32"), inline)]
55#[must_use]
56pub fn wrap_texture_coord(coord: f32, wrap_mode: TextureWrapMode) -> f32 {
57    match wrap_mode {
58        TextureWrapMode::ClampToEdge => coord.clamp(0.0, 1.0),
59        TextureWrapMode::Repeat => coord - coord.floor(),
60        TextureWrapMode::MirroredRepeat => {
61            let tile: f32 = coord.floor();
62            let frac: f32 = coord - tile;
63            let odd: bool = (tile as i64).rem_euclid(2) == 1;
64            if odd { 1.0 - frac } else { frac }
65        }
66    }
67}
68
69/// Downsamples a single mip level by 2x respecting `color_space` (linear sRGB box filter or re-normalized normals).
70///
71/// # Arguments
72///
73/// - `&TextureMipLevel3D` - Source higher-resolution mip level.
74/// - `TextureColorSpace` - Color-space filtering policy.
75///
76/// # Returns
77///
78/// - `TextureMipLevel3D` - Half-resolution filtered child mip level.
79#[must_use]
80pub fn downsample_mip_level(
81    src: &TextureMipLevel3D,
82    color_space: TextureColorSpace,
83) -> TextureMipLevel3D {
84    let src_w: usize = src.get_width().max(1) as usize;
85    let src_h: usize = src.get_height().max(1) as usize;
86    let dst_w: usize = (src_w / 2).max(1);
87    let dst_h: usize = (src_h / 2).max(1);
88    let pixels: &[u8] = src.get_pixels().as_slice();
89    let mut out: Vec<u8> = vec![0u8; dst_w * dst_h * 4];
90    for dy in 0..dst_h {
91        let sy0: usize = (dy * 2).min(src_h - 1);
92        let sy1: usize = (dy * 2 + 1).min(src_h - 1);
93        for dx in 0..dst_w {
94            let sx0: usize = (dx * 2).min(src_w - 1);
95            let sx1: usize = (dx * 2 + 1).min(src_w - 1);
96            let coords: [(usize, usize); 4] = [(sx0, sy0), (sx1, sy0), (sx0, sy1), (sx1, sy1)];
97            let dst_off: usize = (dy * dst_w + dx) * 4;
98            match color_space {
99                TextureColorSpace::Srgb => {
100                    let mut sum_r: f32 = 0.0;
101                    let mut sum_g: f32 = 0.0;
102                    let mut sum_b: f32 = 0.0;
103                    let mut sum_a: f32 = 0.0;
104                    for &(cx, cy) in coords.iter() {
105                        let off: usize = (cy * src_w + cx) * 4;
106                        sum_r += srgb_u8_to_linear(pixels[off]);
107                        sum_g += srgb_u8_to_linear(pixels[off + 1]);
108                        sum_b += srgb_u8_to_linear(pixels[off + 2]);
109                        sum_a += f32::from(pixels[off + 3]) / 255.0;
110                    }
111                    out[dst_off] = linear_to_srgb_u8(sum_r * 0.25);
112                    out[dst_off + 1] = linear_to_srgb_u8(sum_g * 0.25);
113                    out[dst_off + 2] = linear_to_srgb_u8(sum_b * 0.25);
114                    out[dst_off + 3] = (sum_a * 0.25 * 255.0).round().clamp(0.0, 255.0) as u8;
115                }
116                TextureColorSpace::Linear => {
117                    let mut sums: [u32; 4] = [0u32; 4];
118                    for &(cx, cy) in coords.iter() {
119                        let off: usize = (cy * src_w + cx) * 4;
120                        sums[0] += u32::from(pixels[off]);
121                        sums[1] += u32::from(pixels[off + 1]);
122                        sums[2] += u32::from(pixels[off + 2]);
123                        sums[3] += u32::from(pixels[off + 3]);
124                    }
125                    out[dst_off] = ((sums[0] + 2) >> 2) as u8;
126                    out[dst_off + 1] = ((sums[1] + 2) >> 2) as u8;
127                    out[dst_off + 2] = ((sums[2] + 2) >> 2) as u8;
128                    out[dst_off + 3] = ((sums[3] + 2) >> 2) as u8;
129                }
130                TextureColorSpace::NormalTangent => {
131                    let mut nx: f32 = 0.0;
132                    let mut ny: f32 = 0.0;
133                    let mut nz: f32 = 0.0;
134                    for &(cx, cy) in coords.iter() {
135                        let off: usize = (cy * src_w + cx) * 4;
136                        nx += f32::from(pixels[off]) / 127.5 - 1.0;
137                        ny += f32::from(pixels[off + 1]) / 127.5 - 1.0;
138                        nz += f32::from(pixels[off + 2]) / 127.5 - 1.0;
139                    }
140                    let unit: Vec3 = Vec3::new(nx, ny, nz).normalize();
141                    out[dst_off] = ((unit.get_x() * 0.5 + 0.5) * 255.0)
142                        .round()
143                        .clamp(0.0, 255.0) as u8;
144                    out[dst_off + 1] = ((unit.get_y() * 0.5 + 0.5) * 255.0)
145                        .round()
146                        .clamp(0.0, 255.0) as u8;
147                    out[dst_off + 2] = ((unit.get_z() * 0.5 + 0.5) * 255.0)
148                        .round()
149                        .clamp(0.0, 255.0) as u8;
150                    out[dst_off + 3] = 255;
151                }
152            }
153        }
154    }
155    TextureMipLevel3D {
156        width: dst_w as u32,
157        height: dst_h as u32,
158        pixels: out,
159    }
160}