Skip to main content

sim_engine/renderer/
mesh3d_texture_creation.rs

1//! Complete-chain creation and physically isolated atlas snapshots.
2
3use super::*;
4
5impl WgpuRenderer {
6    /// Creates an independently filtered image with explicit alpha/mipmap policy.
7    /// ImageBudget covers the complete committed CPU/GPU chain, not only mip zero.
8    pub fn create_texture3d_rgba8_with_options(
9        &self,
10        width: u32,
11        height: u32,
12        pixels: Vec<u8>,
13        budget: ImageBudget,
14        options: Texture3dOptions,
15    ) -> Result<Texture3d, Texture3dError> {
16        create_texture_with_options(
17            &self.device,
18            &self.queue,
19            &self.renderer_identity,
20            &self.mesh3d_renderer.textures.layout,
21            width,
22            height,
23            pixels,
24            budget,
25            options,
26        )
27    }
28
29    /// Crops physical source mip-zero texels into an independent local texture.
30    /// Mip generation sees only the selected region. Later parent updates never
31    /// propagate. Use full-domain normalized UVs and material Repeat to repeat a
32    /// tile without sampling neighboring atlas entries at any mip level.
33    pub fn crop_texture3d_tile(
34        &self,
35        source: &Texture3d,
36        region: ImageTexelRect,
37        budget: ImageBudget,
38        options: Texture3dOptions,
39    ) -> Result<Texture3d, Texture3dError> {
40        crop_texture_tile(
41            &self.device,
42            &self.queue,
43            &self.renderer_identity,
44            &self.mesh3d_renderer.textures.layout,
45            source,
46            region,
47            budget,
48            options,
49        )
50    }
51}
52
53#[allow(clippy::too_many_arguments)]
54pub(in crate::renderer::mesh3d) fn create_texture_with_options(
55    device: &wgpu::Device,
56    queue: &wgpu::Queue,
57    identity: &Arc<()>,
58    layout: &wgpu::BindGroupLayout,
59    width: u32,
60    height: u32,
61    pixels: Vec<u8>,
62    budget: ImageBudget,
63    options: Texture3dOptions,
64) -> Result<Texture3d, Texture3dError> {
65    image::validate_image_shape(
66        width,
67        height,
68        pixels.len(),
69        budget,
70        device.limits().max_texture_dimension_2d,
71    )
72    .map_err(Texture3dError::Image)?;
73    if !options.preserves_alpha()
74        && let Some(texel) = pixels.chunks_exact(4).position(|pixel| pixel[3] != 255)
75    {
76        return Err(Texture3dError::NonOpaquePixel { texel });
77    }
78    let chain = CpuMipChain::new(
79        width,
80        height,
81        pixels,
82        budget,
83        device.limits().max_texture_dimension_2d,
84        options.mipmaps(),
85    )
86    .map_err(Texture3dError::Image)?;
87    Ok(upload_chain(
88        device,
89        queue,
90        identity,
91        layout,
92        chain,
93        options.preserves_alpha(),
94    ))
95}
96
97#[allow(clippy::too_many_arguments)]
98pub(in crate::renderer::mesh3d) fn crop_texture_tile(
99    device: &wgpu::Device,
100    queue: &wgpu::Queue,
101    identity: &Arc<()>,
102    layout: &wgpu::BindGroupLayout,
103    source: &Texture3d,
104    region: ImageTexelRect,
105    budget: ImageBudget,
106    options: Texture3dOptions,
107) -> Result<Texture3d, Texture3dError> {
108    if !source.belongs_to(identity) {
109        return Err(Texture3dError::RendererMismatch);
110    }
111    if !region.fits(source.size().0, source.size().1) {
112        return Err(Texture3dError::InvalidRegion);
113    }
114    let bytes = (region.width() as usize)
115        .checked_mul(region.height() as usize)
116        .and_then(|count| count.checked_mul(4))
117        .ok_or(Texture3dError::Image(ImageError::DimensionsTooLarge))?;
118    // Validate the whole chain before even allocating the cropped base image.
119    mips::validate_layout(
120        region.width(),
121        region.height(),
122        bytes,
123        budget,
124        device.limits().max_texture_dimension_2d,
125        options.mipmaps(),
126    )
127    .map_err(Texture3dError::Image)?;
128    if !options.preserves_alpha() {
129        for y in 0..region.height() as usize {
130            for x in 0..region.width() as usize {
131                let source_texel =
132                    (region.y() as usize + y) * source.size().0 as usize + region.x() as usize + x;
133                if source.pixels()[source_texel * 4 + 3] != 255 {
134                    return Err(Texture3dError::NonOpaquePixel {
135                        texel: y * region.width() as usize + x,
136                    });
137                }
138            }
139        }
140    }
141    let mut pixels = Vec::new();
142    pixels.try_reserve_exact(bytes).map_err(|_| {
143        Texture3dError::Image(ImageError::AllocationFailed {
144            requested_bytes: bytes,
145        })
146    })?;
147    if pixels.capacity() > budget.max_bytes() {
148        return Err(Texture3dError::Image(ImageError::BudgetExceeded {
149            limit: budget.max_bytes(),
150            actual: pixels.capacity(),
151        }));
152    }
153    let row_bytes = region.width() as usize * 4;
154    for y in 0..region.height() as usize {
155        let start =
156            ((region.y() as usize + y) * source.size().0 as usize + region.x() as usize) * 4;
157        pixels.extend_from_slice(&source.pixels()[start..start + row_bytes]);
158    }
159    create_texture_with_options(
160        device,
161        queue,
162        identity,
163        layout,
164        region.width(),
165        region.height(),
166        pixels,
167        budget,
168        options,
169    )
170}