Skip to content

Commit 05e5008

Browse files
superdumpcart
andcommitted
Support array / cubemap / cubemap array textures in KTX2 (#5325)
# Objective - Fix / support KTX2 array / cubemap / cubemap array textures - Fixes #4495 . Supersedes #4514 . ## Solution - Add `Option<TextureViewDescriptor>` to `Image` to enable configuration of the `TextureViewDimension` of a texture. - This allows users to set `D2Array`, `D3`, `Cube`, `CubeArray` or whatever they need - Automatically configure this when loading KTX2 - Transcode all layers and faces instead of just one - Use the UASTC block size of 128 bits, and the number of blocks in x/y for a given mip level in order to determine the offset of the layer and face within the KTX2 mip level data - `wgpu` wants data ordered as layer 0 mip 0..n, layer 1 mip 0..n, etc. See https://docs.rs/wgpu/latest/wgpu/util/trait.DeviceExt.html#tymethod.create_texture_with_data - Reorder the data KTX2 mip X layer Y face Z to `wgpu` layer Y face Z mip X order - Add a `skybox` example to demonstrate / test loading cubemaps from PNG and KTX2, including ASTC 4x4, BC7, and ETC2 compression for support everywhere. Note that you need to enable the `ktx2,zstd` features to be able to load the compressed textures. --- ## Changelog - Fixed: KTX2 array / cubemap / cubemap array textures - Fixes: Validation failure for compressed textures stored in KTX2 where the width/height are not a multiple of the block dimensions. - Added: `Image` now has an `Option<TextureViewDescriptor>` field to enable configuration of the texture view. This is useful for configuring the `TextureViewDimension` when it is not just a plain 2D texture and the loader could/did not identify what it should be. Co-authored-by: Carter Anderson <mcanders1@gmail.com>
1 parent 83a9e16 commit 05e5008

File tree

11 files changed

+615
-51
lines changed

11 files changed

+615
-51
lines changed

Cargo.toml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,17 @@ description = "Demonstrates how to prevent meshes from casting/receiving shadows
393393
category = "3D Rendering"
394394
wasm = true
395395

396+
[[example]]
397+
name = "skybox"
398+
path = "examples/3d/skybox.rs"
399+
required-features = ["ktx2", "zstd"]
400+
401+
[package.metadata.example.skybox]
402+
name = "Skybox"
403+
description = "Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats."
404+
category = "3D Rendering"
405+
wasm = false
406+
396407
[[example]]
397408
name = "spherical_area_lights"
398409
path = "examples/3d/spherical_area_lights.rs"

assets/shaders/cubemap_unlit.wgsl

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#import bevy_pbr::mesh_view_bindings
2+
3+
#ifdef CUBEMAP_ARRAY
4+
@group(1) @binding(0)
5+
var base_color_texture: texture_cube_array<f32>;
6+
#else
7+
@group(1) @binding(0)
8+
var base_color_texture: texture_cube<f32>;
9+
#endif
10+
11+
@group(1) @binding(1)
12+
var base_color_sampler: sampler;
13+
14+
@fragment
15+
fn fragment(
16+
#import bevy_pbr::mesh_vertex_output
17+
) -> @location(0) vec4<f32> {
18+
let fragment_position_view_lh = world_position.xyz * vec3<f32>(1.0, 1.0, -1.0);
19+
return textureSample(
20+
base_color_texture,
21+
base_color_sampler,
22+
fragment_position_view_lh
23+
);
24+
}

assets/textures/Ryfjallet_cubemap.png

654 KB
Loading
1.38 MB
Binary file not shown.
1.3 MB
Binary file not shown.
589 KB
Binary file not shown.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
Modifications
2+
=============
3+
4+
The original work, as attributed below, has been modified as follows using the ImageMagick tool:
5+
6+
mogrify -resize 256x256 -format png *.jpg
7+
convert posx.png negx.png posy.png negy.png posz.png negz.png -gravity center -append cubemap.png
8+
9+
Author
10+
======
11+
12+
This is the work of Emil Persson, aka Humus.
13+
http://www.humus.name
14+
15+
16+
17+
License
18+
=======
19+
20+
This work is licensed under a Creative Commons Attribution 3.0 Unported License.
21+
http://creativecommons.org/licenses/by/3.0/

crates/bevy_render/src/texture/image.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ pub struct Image {
110110
pub texture_descriptor: wgpu::TextureDescriptor<'static>,
111111
/// The [`ImageSampler`] to use during rendering.
112112
pub sampler_descriptor: ImageSampler,
113+
pub texture_view_descriptor: Option<wgpu::TextureViewDescriptor<'static>>,
113114
}
114115

115116
/// Used in [`Image`], this determines what image sampler to use when rendering. The default setting,
@@ -216,6 +217,7 @@ impl Default for Image {
216217
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
217218
},
218219
sampler_descriptor: ImageSampler::Default,
220+
texture_view_descriptor: None,
219221
}
220222
}
221223
}
@@ -684,7 +686,13 @@ impl RenderAsset for Image {
684686
texture
685687
};
686688

687-
let texture_view = texture.create_view(&TextureViewDescriptor::default());
689+
let texture_view = texture.create_view(
690+
image
691+
.texture_view_descriptor
692+
.or_else(|| Some(TextureViewDescriptor::default()))
693+
.as_ref()
694+
.unwrap(),
695+
);
688696
let size = Vec2::new(
689697
image.texture_descriptor.size.width as f32,
690698
image.texture_descriptor.size.height as f32,

crates/bevy_render/src/texture/ktx2.rs

Lines changed: 125 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,17 @@ use std::io::Read;
55
use basis_universal::{
66
DecodeFlags, LowLevelUastcTranscoder, SliceParametersUastc, TranscoderBlockFormat,
77
};
8+
use bevy_utils::default;
89
#[cfg(any(feature = "flate2", feature = "ruzstd"))]
910
use ktx2::SupercompressionScheme;
1011
use ktx2::{
1112
BasicDataFormatDescriptor, ChannelTypeQualifiers, ColorModel, DataFormatDescriptorHeader,
1213
Header, SampleInformation,
1314
};
14-
use wgpu::{AstcBlock, AstcChannel, Extent3d, TextureDimension, TextureFormat};
15+
use wgpu::{
16+
AstcBlock, AstcChannel, Extent3d, TextureDimension, TextureFormat, TextureViewDescriptor,
17+
TextureViewDimension,
18+
};
1519

1620
use super::{CompressedImageFormats, DataFormat, Image, TextureError, TranscodeFormat};
1721

@@ -28,10 +32,14 @@ pub fn ktx2_buffer_to_image(
2832
pixel_height: height,
2933
pixel_depth: depth,
3034
layer_count,
35+
face_count,
3136
level_count,
3237
supercompression_scheme,
3338
..
3439
} = ktx2.header();
40+
let layer_count = layer_count.max(1);
41+
let face_count = face_count.max(1);
42+
let depth = depth.max(1);
3543

3644
// Handle supercompression
3745
let mut levels = Vec::new();
@@ -80,25 +88,25 @@ pub fn ktx2_buffer_to_image(
8088
let texture_format = ktx2_get_texture_format(&ktx2, is_srgb).or_else(|error| match error {
8189
// Transcode if needed and supported
8290
TextureError::FormatRequiresTranscodingError(transcode_format) => {
83-
let mut transcoded = Vec::new();
91+
let mut transcoded = vec![Vec::default(); levels.len()];
8492
let texture_format = match transcode_format {
8593
TranscodeFormat::Rgb8 => {
86-
let (mut original_width, mut original_height) = (width, height);
87-
88-
for level_data in &levels {
89-
let n_pixels = (original_width * original_height) as usize;
94+
let mut rgba = vec![255u8; width as usize * height as usize * 4];
95+
for (level, level_data) in levels.iter().enumerate() {
96+
let n_pixels = (width as usize >> level).max(1) * (height as usize >> level).max(1);
9097

91-
let mut rgba = vec![255u8; n_pixels * 4];
92-
for i in 0..n_pixels {
93-
rgba[i * 4] = level_data[i * 3];
94-
rgba[i * 4 + 1] = level_data[i * 3 + 1];
95-
rgba[i * 4 + 2] = level_data[i * 3 + 2];
98+
let mut offset = 0;
99+
for _layer in 0..layer_count {
100+
for _face in 0..face_count {
101+
for i in 0..n_pixels {
102+
rgba[i * 4] = level_data[offset];
103+
rgba[i * 4 + 1] = level_data[offset + 1];
104+
rgba[i * 4 + 2] = level_data[offset + 2];
105+
offset += 3;
106+
}
107+
transcoded[level].extend_from_slice(&rgba[0..n_pixels]);
108+
}
96109
}
97-
transcoded.push(rgba);
98-
99-
// Next mip dimensions are half the current, minimum 1x1
100-
original_width = (original_width / 2).max(1);
101-
original_height = (original_height / 2).max(1);
102110
}
103111

104112
if is_srgb {
@@ -111,41 +119,54 @@ pub fn ktx2_buffer_to_image(
111119
TranscodeFormat::Uastc(data_format) => {
112120
let (transcode_block_format, texture_format) =
113121
get_transcoded_formats(supported_compressed_formats, data_format, is_srgb);
114-
let (mut original_width, mut original_height) = (width, height);
115-
let (block_width_pixels, block_height_pixels) = (4, 4);
122+
let texture_format_info = texture_format.describe();
123+
let (block_width_pixels, block_height_pixels) = (
124+
texture_format_info.block_dimensions.0 as u32,
125+
texture_format_info.block_dimensions.1 as u32,
126+
);
127+
let block_bytes = texture_format_info.block_size as u32;
116128

117129
let transcoder = LowLevelUastcTranscoder::new();
118130
for (level, level_data) in levels.iter().enumerate() {
119-
let slice_parameters = SliceParametersUastc {
120-
num_blocks_x: ((original_width + block_width_pixels - 1)
121-
/ block_width_pixels)
122-
.max(1),
123-
num_blocks_y: ((original_height + block_height_pixels - 1)
124-
/ block_height_pixels)
125-
.max(1),
126-
has_alpha: false,
127-
original_width,
128-
original_height,
129-
};
130-
131-
transcoder
132-
.transcode_slice(
133-
level_data,
134-
slice_parameters,
135-
DecodeFlags::HIGH_QUALITY,
136-
transcode_block_format,
137-
)
138-
.map(|transcoded_level| transcoded.push(transcoded_level))
139-
.map_err(|error| {
140-
TextureError::SuperDecompressionError(format!(
141-
"Failed to transcode mip level {} from UASTC to {:?}: {:?}",
142-
level, transcode_block_format, error
143-
))
144-
})?;
131+
let (level_width, level_height) = (
132+
(width >> level as u32).max(1),
133+
(height >> level as u32).max(1),
134+
);
135+
let (num_blocks_x, num_blocks_y) = (
136+
((level_width + block_width_pixels - 1) / block_width_pixels) .max(1),
137+
((level_height + block_height_pixels - 1) / block_height_pixels) .max(1),
138+
);
139+
let level_bytes = (num_blocks_x * num_blocks_y * block_bytes) as usize;
145140

146-
// Next mip dimensions are half the current, minimum 1x1
147-
original_width = (original_width / 2).max(1);
148-
original_height = (original_height / 2).max(1);
141+
let mut offset = 0;
142+
for _layer in 0..layer_count {
143+
for _face in 0..face_count {
144+
// NOTE: SliceParametersUastc does not implement Clone nor Copy so
145+
// it has to be created per use
146+
let slice_parameters = SliceParametersUastc {
147+
num_blocks_x,
148+
num_blocks_y,
149+
has_alpha: false,
150+
original_width: level_width,
151+
original_height: level_height,
152+
};
153+
transcoder
154+
.transcode_slice(
155+
&level_data[offset..(offset + level_bytes)],
156+
slice_parameters,
157+
DecodeFlags::HIGH_QUALITY,
158+
transcode_block_format,
159+
)
160+
.map(|mut transcoded_level| transcoded[level].append(&mut transcoded_level))
161+
.map_err(|error| {
162+
TextureError::SuperDecompressionError(format!(
163+
"Failed to transcode mip level {} from UASTC to {:?}: {:?}",
164+
level, transcode_block_format, error
165+
))
166+
})?;
167+
offset += level_bytes;
168+
}
169+
}
149170
}
150171
texture_format
151172
}
@@ -178,16 +199,52 @@ pub fn ktx2_buffer_to_image(
178199
)));
179200
}
180201

202+
// Reorder data from KTX2 MipXLayerYFaceZ to wgpu LayerYFaceZMipX
203+
let texture_format_info = texture_format.describe();
204+
let (block_width_pixels, block_height_pixels) = (
205+
texture_format_info.block_dimensions.0 as usize,
206+
texture_format_info.block_dimensions.1 as usize,
207+
);
208+
let block_bytes = texture_format_info.block_size as usize;
209+
210+
let mut wgpu_data = vec![Vec::default(); (layer_count * face_count) as usize];
211+
for (level, level_data) in levels.iter().enumerate() {
212+
let (level_width, level_height) = (
213+
(width as usize >> level).max(1),
214+
(height as usize >> level).max(1),
215+
);
216+
let (num_blocks_x, num_blocks_y) = (
217+
((level_width + block_width_pixels - 1) / block_width_pixels).max(1),
218+
((level_height + block_height_pixels - 1) / block_height_pixels).max(1),
219+
);
220+
let level_bytes = num_blocks_x * num_blocks_y * block_bytes;
221+
222+
let mut index = 0;
223+
for _layer in 0..layer_count {
224+
for _face in 0..face_count {
225+
let offset = index * level_bytes;
226+
wgpu_data[index].extend_from_slice(&level_data[offset..(offset + level_bytes)]);
227+
index += 1;
228+
}
229+
}
230+
}
231+
181232
// Assign the data and fill in the rest of the metadata now the possible
182233
// error cases have been handled
183234
let mut image = Image::default();
184235
image.texture_descriptor.format = texture_format;
185-
image.data = levels.into_iter().flatten().collect::<Vec<_>>();
236+
image.data = wgpu_data.into_iter().flatten().collect::<Vec<_>>();
186237
image.texture_descriptor.size = Extent3d {
187238
width,
188239
height,
189-
depth_or_array_layers: if layer_count > 1 { layer_count } else { depth }.max(1),
190-
};
240+
depth_or_array_layers: if layer_count > 1 || face_count > 1 {
241+
layer_count * face_count
242+
} else {
243+
depth
244+
}
245+
.max(1),
246+
}
247+
.physical_size(texture_format);
191248
image.texture_descriptor.mip_level_count = level_count;
192249
image.texture_descriptor.dimension = if depth > 1 {
193250
TextureDimension::D3
@@ -196,6 +253,24 @@ pub fn ktx2_buffer_to_image(
196253
} else {
197254
TextureDimension::D1
198255
};
256+
let mut dimension = None;
257+
if face_count == 6 {
258+
dimension = Some(if layer_count > 1 {
259+
TextureViewDimension::CubeArray
260+
} else {
261+
TextureViewDimension::Cube
262+
});
263+
} else if layer_count > 1 {
264+
dimension = Some(TextureViewDimension::D2Array);
265+
} else if depth > 1 {
266+
dimension = Some(TextureViewDimension::D3);
267+
}
268+
if dimension.is_some() {
269+
image.texture_view_descriptor = Some(TextureViewDescriptor {
270+
dimension,
271+
..default()
272+
});
273+
}
199274
Ok(image)
200275
}
201276

0 commit comments

Comments
 (0)