Skip to content

Commit 84991d3

Browse files
superdumpcart
andcommitted
Array texture example (#5077)
# Objective - Make the reusable PBR shading functionality a little more reusable - Add constructor functions for `StandardMaterial` and `PbrInput` structs to populate them with default values - Document unclear `PbrInput` members - Demonstrate how to reuse the bevy PBR shading functionality - The final important piece from #3969 as the initial shot at making the PBR shader code reusable in custom materials ## Solution - Add back and rework the 'old' `array_texture` example from pre-0.6. - Create a custom shader material - Use a single array texture binding and sampler for the material bind group - Use a shader that calls `pbr()` from the `bevy_pbr::pbr_functions` import - Spawn a row of cubes using the custom material - In the shader, select the array texture layer to sample by using the world position x coordinate modulo the number of array texture layers <img width="1392" alt="Screenshot 2022-06-23 at 12 28 05" src="https://user-images.githubusercontent.com/302146/175278593-2296f519-f577-4ece-81c0-d842283784a1.png"> Co-authored-by: Carter Anderson <mcanders1@gmail.com>
1 parent 9eb6928 commit 84991d3

File tree

7 files changed

+309
-3
lines changed

7 files changed

+309
-3
lines changed

Cargo.toml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1183,6 +1183,16 @@ description = "A compute shader that simulates Conway's Game of Life"
11831183
category = "Shaders"
11841184
wasm = false
11851185

1186+
[[example]]
1187+
name = "array_texture"
1188+
path = "examples/shader/array_texture.rs"
1189+
1190+
[package.metadata.example.array_texture]
1191+
name = "Array Texture"
1192+
description = "A shader that shows how to reuse the core bevy PBR shading functionality in a custom material that obtains the base color from an array texture."
1193+
category = "Shaders"
1194+
wasm = true
1195+
11861196
# Stress tests
11871197
[[package.metadata.category]]
11881198
name = "Stress Tests"

assets/shaders/array_texture.wgsl

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#import bevy_pbr::mesh_view_bindings
2+
#import bevy_pbr::mesh_bindings
3+
4+
#import bevy_pbr::pbr_types
5+
#import bevy_pbr::utils
6+
#import bevy_pbr::clustered_forward
7+
#import bevy_pbr::lighting
8+
#import bevy_pbr::shadows
9+
#import bevy_pbr::pbr_functions
10+
11+
[[group(1), binding(0)]]
12+
var my_array_texture: texture_2d_array<f32>;
13+
[[group(1), binding(1)]]
14+
var my_array_texture_sampler: sampler;
15+
16+
struct FragmentInput {
17+
[[builtin(front_facing)]] is_front: bool;
18+
[[builtin(position)]] frag_coord: vec4<f32>;
19+
[[location(0)]] world_position: vec4<f32>;
20+
[[location(1)]] world_normal: vec3<f32>;
21+
[[location(2)]] uv: vec2<f32>;
22+
#ifdef VERTEX_TANGENTS
23+
[[location(3)]] world_tangent: vec4<f32>;
24+
#endif
25+
#ifdef VERTEX_COLORS
26+
[[location(4)]] color: vec4<f32>;
27+
#endif
28+
};
29+
30+
[[stage(fragment)]]
31+
fn fragment(in: FragmentInput) -> [[location(0)]] vec4<f32> {
32+
let layer = i32(in.world_position.x) & 0x3;
33+
34+
// Prepare a 'processed' StandardMaterial by sampling all textures to resolve
35+
// the material members
36+
var pbr_input: PbrInput = pbr_input_new();
37+
38+
pbr_input.material.base_color = textureSample(my_array_texture, my_array_texture_sampler, in.uv, layer);
39+
#ifdef VERTEX_COLORS
40+
pbr_input.material.base_color = pbr_input.material.base_color * in.color;
41+
#endif
42+
43+
pbr_input.frag_coord = in.frag_coord;
44+
pbr_input.world_position = in.world_position;
45+
pbr_input.world_normal = in.world_normal;
46+
47+
pbr_input.is_orthographic = view.projection[3].w == 1.0;
48+
49+
pbr_input.N = prepare_normal(
50+
pbr_input.material.flags,
51+
in.world_normal,
52+
#ifdef VERTEX_TANGENTS
53+
#ifdef STANDARDMATERIAL_NORMAL_MAP
54+
in.world_tangent,
55+
#endif
56+
#endif
57+
in.uv,
58+
in.is_front,
59+
);
60+
pbr_input.V = calculate_view(in.world_position, pbr_input.is_orthographic);
61+
62+
return pbr(pbr_input);
63+
}

crates/bevy_pbr/src/render/pbr.wgsl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ fn fragment(in: FragmentInput) -> [[location(0)]] vec4<f32> {
7474
pbr_input.is_orthographic = view.projection[3].w == 1.0;
7575

7676
pbr_input.N = prepare_normal(
77+
material.flags,
7778
in.world_normal,
7879
#ifdef VERTEX_TANGENTS
7980
#ifdef STANDARDMATERIAL_NORMAL_MAP

crates/bevy_pbr/src/render/pbr_functions.wgsl

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// NOTE: This ensures that the world_normal is normalized and if
44
// vertex tangents and normal maps then normal mapping may be applied.
55
fn prepare_normal(
6+
standard_material_flags: u32,
67
world_normal: vec3<f32>,
78
#ifdef VERTEX_TANGENTS
89
#ifdef STANDARDMATERIAL_NORMAL_MAP
@@ -25,7 +26,7 @@ fn prepare_normal(
2526
#endif
2627
#endif
2728

28-
if ((material.flags & STANDARD_MATERIAL_FLAGS_DOUBLE_SIDED_BIT) != 0u) {
29+
if ((standard_material_flags & STANDARD_MATERIAL_FLAGS_DOUBLE_SIDED_BIT) != 0u) {
2930
if (!is_front) {
3031
N = -N;
3132
#ifdef VERTEX_TANGENTS
@@ -41,15 +42,15 @@ fn prepare_normal(
4142
#ifdef STANDARDMATERIAL_NORMAL_MAP
4243
// Nt is the tangent-space normal.
4344
var Nt: vec3<f32>;
44-
if ((material.flags & STANDARD_MATERIAL_FLAGS_TWO_COMPONENT_NORMAL_MAP) != 0u) {
45+
if ((standard_material_flags & STANDARD_MATERIAL_FLAGS_TWO_COMPONENT_NORMAL_MAP) != 0u) {
4546
// Only use the xy components and derive z for 2-component normal maps.
4647
Nt = vec3<f32>(textureSample(normal_map_texture, normal_map_sampler, uv).rg * 2.0 - 1.0, 0.0);
4748
Nt.z = sqrt(1.0 - Nt.x * Nt.x - Nt.y * Nt.y);
4849
} else {
4950
Nt = textureSample(normal_map_texture, normal_map_sampler, uv).rgb * 2.0 - 1.0;
5051
}
5152
// Normal maps authored for DirectX require flipping the y component
52-
if ((material.flags & STANDARD_MATERIAL_FLAGS_FLIP_NORMAL_MAP_Y) != 0u) {
53+
if ((standard_material_flags & STANDARD_MATERIAL_FLAGS_FLIP_NORMAL_MAP_Y) != 0u) {
5354
Nt.y = -Nt.y;
5455
}
5556
// NOTE: The mikktspace method of normal mapping applies maps the tangent-space normal from
@@ -86,12 +87,36 @@ struct PbrInput {
8687
occlusion: f32;
8788
frag_coord: vec4<f32>;
8889
world_position: vec4<f32>;
90+
// Normalized world normal used for shadow mapping as normal-mapping is not used for shadow
91+
// mapping
8992
world_normal: vec3<f32>;
93+
// Normalized normal-mapped world normal used for lighting
9094
N: vec3<f32>;
95+
// Normalized view vector in world space, pointing from the fragment world position toward the
96+
// view world position
9197
V: vec3<f32>;
9298
is_orthographic: bool;
9399
};
94100

101+
// Creates a PbrInput with default values
102+
fn pbr_input_new() -> PbrInput {
103+
var pbr_input: PbrInput;
104+
105+
pbr_input.material = standard_material_new();
106+
pbr_input.occlusion = 1.0;
107+
108+
pbr_input.frag_coord = vec4<f32>(0.0, 0.0, 0.0, 1.0);
109+
pbr_input.world_position = vec4<f32>(0.0, 0.0, 0.0, 1.0);
110+
pbr_input.world_normal = vec3<f32>(0.0, 0.0, 1.0);
111+
112+
pbr_input.is_orthographic = false;
113+
114+
pbr_input.N = vec3<f32>(0.0, 0.0, 1.0);
115+
pbr_input.V = vec3<f32>(1.0, 0.0, 0.0);
116+
117+
return pbr_input;
118+
}
119+
95120
fn pbr(
96121
in: PbrInput,
97122
) -> vec4<f32> {

crates/bevy_pbr/src/render/pbr_types.wgsl

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,19 @@ let STANDARD_MATERIAL_FLAGS_ALPHA_MODE_MASK: u32 = 128u;
2222
let STANDARD_MATERIAL_FLAGS_ALPHA_MODE_BLEND: u32 = 256u;
2323
let STANDARD_MATERIAL_FLAGS_TWO_COMPONENT_NORMAL_MAP: u32 = 512u;
2424
let STANDARD_MATERIAL_FLAGS_FLIP_NORMAL_MAP_Y: u32 = 1024u;
25+
26+
// Creates a StandardMaterial with default values
27+
fn standard_material_new() -> StandardMaterial {
28+
var material: StandardMaterial;
29+
30+
// NOTE: Keep in-sync with src/pbr_material.rs!
31+
material.base_color = vec4<f32>(1.0, 1.0, 1.0, 1.0);
32+
material.emissive = vec4<f32>(0.0, 0.0, 0.0, 1.0);
33+
material.perceptual_roughness = 0.089;
34+
material.metallic = 0.01;
35+
material.reflectance = 0.5;
36+
material.flags = STANDARD_MATERIAL_FLAGS_ALPHA_MODE_OPAQUE;
37+
material.alpha_cutoff = 0.5;
38+
39+
return material;
40+
}

examples/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ There are also compute shaders which are used for more general processing levera
253253
Example | Description
254254
--- | ---
255255
[Animated](../examples/shader/animate_shader.rs) | A shader that uses dynamic data like the time since startup
256+
[Array Texture](../examples/shader/array_texture.rs) | A shader that shows how to reuse the core bevy PBR shading functionality in a custom material that obtains the base color from an array texture.
256257
[Compute - Game of Life](../examples/shader/compute_shader_game_of_life.rs) | A compute shader that simulates Conway's Game of Life
257258
[Custom Vertex Attribute](../examples/shader/custom_vertex_attribute.rs) | A shader that reads a mesh's custom vertex attribute
258259
[Instancing](../examples/shader/shader_instancing.rs) | A shader that renders a mesh multiple times in one draw call

examples/shader/array_texture.rs

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
use bevy::{
2+
asset::LoadState,
3+
ecs::system::{lifetimeless::SRes, SystemParamItem},
4+
pbr::MaterialPipeline,
5+
prelude::*,
6+
reflect::TypeUuid,
7+
render::{
8+
render_asset::{PrepareAssetError, RenderAsset, RenderAssets},
9+
render_resource::{
10+
BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayout,
11+
BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingType,
12+
SamplerBindingType, ShaderStages, TextureSampleType, TextureViewDimension,
13+
},
14+
renderer::RenderDevice,
15+
},
16+
};
17+
18+
/// This example illustrates how to create a texture for use with a `texture_2d_array<f32>` shader
19+
/// uniform variable.
20+
fn main() {
21+
App::new()
22+
.add_plugins(DefaultPlugins)
23+
.add_plugin(MaterialPlugin::<ArrayTextureMaterial>::default())
24+
.add_startup_system(setup)
25+
.add_system(create_array_texture)
26+
.run();
27+
}
28+
29+
struct LoadingTexture {
30+
is_loaded: bool,
31+
handle: Handle<Image>,
32+
}
33+
34+
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
35+
// Start loading the texture.
36+
commands.insert_resource(LoadingTexture {
37+
is_loaded: false,
38+
handle: asset_server.load("textures/array_texture.png"),
39+
});
40+
41+
// light
42+
commands.spawn_bundle(PointLightBundle {
43+
point_light: PointLight {
44+
intensity: 3000.0,
45+
..Default::default()
46+
},
47+
transform: Transform::from_xyz(-3.0, 2.0, -1.0),
48+
..Default::default()
49+
});
50+
commands.spawn_bundle(PointLightBundle {
51+
point_light: PointLight {
52+
intensity: 3000.0,
53+
..Default::default()
54+
},
55+
transform: Transform::from_xyz(3.0, 2.0, 1.0),
56+
..Default::default()
57+
});
58+
59+
// camera
60+
commands.spawn_bundle(Camera3dBundle {
61+
transform: Transform::from_xyz(5.0, 5.0, 5.0).looking_at(Vec3::new(1.5, 0.0, 0.0), Vec3::Y),
62+
..Default::default()
63+
});
64+
}
65+
66+
fn create_array_texture(
67+
mut commands: Commands,
68+
asset_server: Res<AssetServer>,
69+
mut loading_texture: ResMut<LoadingTexture>,
70+
mut images: ResMut<Assets<Image>>,
71+
mut meshes: ResMut<Assets<Mesh>>,
72+
mut materials: ResMut<Assets<ArrayTextureMaterial>>,
73+
) {
74+
if loading_texture.is_loaded
75+
|| asset_server.get_load_state(loading_texture.handle.clone()) != LoadState::Loaded
76+
{
77+
return;
78+
}
79+
loading_texture.is_loaded = true;
80+
let image = images.get_mut(&loading_texture.handle).unwrap();
81+
82+
// Create a new array texture asset from the loaded texture.
83+
let array_layers = 4;
84+
image.reinterpret_stacked_2d_as_array(array_layers);
85+
86+
// Spawn some cubes using the array texture
87+
let mesh_handle = meshes.add(Mesh::from(shape::Cube { size: 1.0 }));
88+
let material_handle = materials.add(ArrayTextureMaterial {
89+
array_texture: loading_texture.handle.clone(),
90+
});
91+
for x in -5..=5 {
92+
commands.spawn_bundle(MaterialMeshBundle {
93+
mesh: mesh_handle.clone(),
94+
material: material_handle.clone(),
95+
transform: Transform::from_xyz(x as f32 + 0.5, 0.0, 0.0),
96+
..Default::default()
97+
});
98+
}
99+
}
100+
101+
#[derive(Debug, Clone, TypeUuid)]
102+
#[uuid = "9c5a0ddf-1eaf-41b4-9832-ed736fd26af3"]
103+
struct ArrayTextureMaterial {
104+
array_texture: Handle<Image>,
105+
}
106+
107+
#[derive(Clone)]
108+
pub struct GpuArrayTextureMaterial {
109+
bind_group: BindGroup,
110+
}
111+
112+
impl RenderAsset for ArrayTextureMaterial {
113+
type ExtractedAsset = ArrayTextureMaterial;
114+
type PreparedAsset = GpuArrayTextureMaterial;
115+
type Param = (
116+
SRes<RenderDevice>,
117+
SRes<MaterialPipeline<Self>>,
118+
SRes<RenderAssets<Image>>,
119+
);
120+
fn extract_asset(&self) -> Self::ExtractedAsset {
121+
self.clone()
122+
}
123+
124+
fn prepare_asset(
125+
extracted_asset: Self::ExtractedAsset,
126+
(render_device, material_pipeline, gpu_images): &mut SystemParamItem<Self::Param>,
127+
) -> Result<Self::PreparedAsset, PrepareAssetError<Self::ExtractedAsset>> {
128+
let (array_texture_texture_view, array_texture_sampler) = if let Some(result) =
129+
material_pipeline
130+
.mesh_pipeline
131+
.get_image_texture(gpu_images, &Some(extracted_asset.array_texture.clone()))
132+
{
133+
result
134+
} else {
135+
return Err(PrepareAssetError::RetryNextUpdate(extracted_asset));
136+
};
137+
let bind_group = render_device.create_bind_group(&BindGroupDescriptor {
138+
entries: &[
139+
BindGroupEntry {
140+
binding: 0,
141+
resource: BindingResource::TextureView(array_texture_texture_view),
142+
},
143+
BindGroupEntry {
144+
binding: 1,
145+
resource: BindingResource::Sampler(array_texture_sampler),
146+
},
147+
],
148+
label: Some("array_texture_material_bind_group"),
149+
layout: &material_pipeline.material_layout,
150+
});
151+
152+
Ok(GpuArrayTextureMaterial { bind_group })
153+
}
154+
}
155+
156+
impl Material for ArrayTextureMaterial {
157+
fn fragment_shader(asset_server: &AssetServer) -> Option<Handle<Shader>> {
158+
Some(asset_server.load("shaders/array_texture.wgsl"))
159+
}
160+
161+
fn bind_group(render_asset: &<Self as RenderAsset>::PreparedAsset) -> &BindGroup {
162+
&render_asset.bind_group
163+
}
164+
165+
fn bind_group_layout(render_device: &RenderDevice) -> BindGroupLayout {
166+
render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
167+
entries: &[
168+
// Array Texture
169+
BindGroupLayoutEntry {
170+
binding: 0,
171+
visibility: ShaderStages::FRAGMENT,
172+
ty: BindingType::Texture {
173+
multisampled: false,
174+
sample_type: TextureSampleType::Float { filterable: true },
175+
view_dimension: TextureViewDimension::D2Array,
176+
},
177+
count: None,
178+
},
179+
// Array Texture Sampler
180+
BindGroupLayoutEntry {
181+
binding: 1,
182+
visibility: ShaderStages::FRAGMENT,
183+
ty: BindingType::Sampler(SamplerBindingType::Filtering),
184+
count: None,
185+
},
186+
],
187+
label: None,
188+
})
189+
}
190+
}

0 commit comments

Comments
 (0)