learn-wgpu/docs/beginner/tutorial5-textures/README.md

595 lines
22 KiB
Markdown
Raw Normal View History

2019-11-05 08:02:41 +00:00
# Textures and bind groups
Up to this point we have been drawing super simple shapes. While we can make a game with just triangles, trying to draw highly detailed objects would massively limit what devices could even run our game. However, we can get around this problem with **textures**.
Textures are images overlayed on a triangle mesh to make it seem more detailed. There are multiple types of textures such as normal maps, bump maps, specular maps and diffuse maps. We're going to talk about diffuse maps, or more simply, the color texture.
2019-11-05 08:02:41 +00:00
## Loading an image from a file
If we want to map an image to our mesh, we first need an image. Let's use this happy little tree:
2019-11-05 08:02:41 +00:00
![a happy tree](./happy-tree.png)
We'll use the [image crate](https://crates.io/crates/image) to load our tree. We already added to our dependencies in the first section, so all we have to do is use it.
In `State`'s `new()` method add the following just after creating the `swap_chain`:
2019-11-05 08:02:41 +00:00
```rust
2021-08-28 22:11:33 +00:00
surface.configure(&device, &config);
// NEW!
2019-11-05 08:02:41 +00:00
let diffuse_bytes = include_bytes!("happy-tree.png");
let diffuse_image = image::load_from_memory(diffuse_bytes).unwrap();
let diffuse_rgba = diffuse_image.as_rgba8().unwrap();
use image::GenericImageView;
let dimensions = diffuse_image.dimensions();
```
Here we grab the bytes from our image file and load them into an image which is then converted into a `Vec` of rgba bytes. We also save the image's dimensions for when we create the actual `Texture`.
Now, let's create the `Texture`:
2019-11-05 08:02:41 +00:00
```rust
let texture_size = wgpu::Extent3d {
2019-11-05 08:02:41 +00:00
width: dimensions.0,
height: dimensions.1,
2021-05-01 21:55:26 +00:00
depth_or_array_layers: 1,
2019-11-05 08:02:41 +00:00
};
2020-09-05 19:46:15 +00:00
let diffuse_texture = device.create_texture(
&wgpu::TextureDescriptor {
// All textures are stored as 3D, we represent our 2D texture
2020-09-05 19:46:15 +00:00
// by setting depth to 1.
size: texture_size,
2020-09-05 19:46:15 +00:00
mip_level_count: 1, // We'll talk about this a little later
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
2021-07-20 23:25:36 +00:00
// Most images are stored using sRGB so we need to reflect that here.
2020-09-05 19:46:15 +00:00
format: wgpu::TextureFormat::Rgba8UnormSrgb,
// SAMPLED tells wgpu that we want to use this texture in shaders
// COPY_DST means that we want to copy data to this texture
2021-09-11 16:37:05 +00:00
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2020-09-05 19:46:15 +00:00
label: Some("diffuse_texture"),
}
);
2019-11-05 08:02:41 +00:00
```
## Getting data into a Texture
The `Texture` struct has no methods to interact with the data directly. However, we can use a method on the `queue` we created earlier called `write_texture` to load the texture in. Let's take a look at how we do that:
2019-11-05 08:02:41 +00:00
```rust
2020-09-05 19:46:15 +00:00
queue.write_texture(
// Tells wgpu where to copy the pixel data
2021-05-01 21:55:26 +00:00
wgpu::ImageCopyTexture {
2020-09-05 19:46:15 +00:00
texture: &diffuse_texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
},
// The actual pixel data
diffuse_rgba,
// The layout of the texture
2021-05-01 21:55:26 +00:00
wgpu::ImageDataLayout {
2020-09-05 19:46:15 +00:00
offset: 0,
2021-06-06 08:40:12 +00:00
bytes_per_row: std::num::NonZeroU32::new(4 * dimensions.0),
rows_per_image: std::num::NonZeroU32::new(dimensions.1),
2020-09-05 19:46:15 +00:00
},
texture_size,
2020-04-21 19:05:48 +00:00
);
2019-11-05 08:02:41 +00:00
```
2020-09-05 19:46:15 +00:00
<div class="note">
2019-11-05 08:02:41 +00:00
The old way of writing data to a texture was to copy the pixel data to a buffer and then copy it to the texture. Using `write_texture` is a bit more efficient as it uses one less buffer - I'll leave it here though in case you need it.
2019-11-05 08:02:41 +00:00
2020-09-05 19:46:15 +00:00
```rust
2020-09-28 04:52:35 +00:00
let buffer = device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
label: Some("Temp Buffer"),
2020-11-22 15:43:15 +00:00
contents: &diffuse_rgba,
2021-09-11 16:19:15 +00:00
usage: wgpu::BufferUsages::COPY_SRC,
2020-09-28 04:52:35 +00:00
}
2020-09-05 19:46:15 +00:00
);
2019-11-05 08:02:41 +00:00
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
2020-04-21 19:05:48 +00:00
label: Some("texture_buffer_copy_encoder"),
2019-11-05 08:02:41 +00:00
});
encoder.copy_buffer_to_texture(
2021-05-01 21:55:26 +00:00
wgpu::ImageCopyBuffer {
2020-04-21 19:05:48 +00:00
buffer: &buffer,
2019-11-05 08:02:41 +00:00
offset: 0,
2020-04-21 19:05:48 +00:00
bytes_per_row: 4 * dimensions.0,
rows_per_image: dimensions.1,
2020-05-11 16:24:44 +00:00
},
2021-05-01 21:55:26 +00:00
wgpu::ImageCopyTexture {
2020-05-11 16:24:44 +00:00
texture: &diffuse_texture,
2019-11-05 08:02:41 +00:00
mip_level: 0,
array_layer: 0,
origin: wgpu::Origin3d::ZERO,
2020-05-11 16:24:44 +00:00
},
2019-11-05 08:02:41 +00:00
size,
);
queue.submit(std::iter::once(encoder.finish()));
2019-11-05 08:02:41 +00:00
```
The `bytes_per_row` field needs some consideration. This value needs to be a multiple of 256. Check out [the gif tutorial](../../showcase/gifs/#how-do-we-make-the-frames) for more details.
2020-09-05 19:46:15 +00:00
</div>
2019-11-05 08:02:41 +00:00
## TextureViews and Samplers
Now that our texture has data in it, we need a way to use it. This is where a `TextureView` and a `Sampler` come in. A `TextureView` offers us a *view* into our texture. A `Sampler` controls how the `Texture` is *sampled*. Sampling works similar to the eyedropper tool in GIMP/Photoshop. Our program supplies a coordinate on the texture (known as a *texture coordinate*), and the sampler then returns the corresponding color based on the texture and some internal parameters.
2019-11-05 08:02:41 +00:00
Let's define our `diffuse_texture_view` and `diffuse_sampler` now:
2019-11-05 08:02:41 +00:00
```rust
// We don't need to configure the texture view much, so let's
// let wgpu define it.
2020-09-05 19:46:15 +00:00
let diffuse_texture_view = diffuse_texture.create_view(&wgpu::TextureViewDescriptor::default());
2019-11-05 08:02:41 +00:00
let diffuse_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
2020-09-05 19:46:15 +00:00
..Default::default()
2019-11-05 08:02:41 +00:00
});
```
The `address_mode_*` parameters determine what to do if the sampler gets a texture coordinate that's outside of the texture itself. We have a few options to choose from:
2019-11-05 08:02:41 +00:00
* `ClampToEdge`: Any texture coordinates outside the texture will return the color of the nearest pixel on the edges of the texture.
* `Repeat`: The texture will repeat as texture coordinates exceed the textures dimensions.
* `MirrorRepeat`: Similar to `Repeat`, but the image will flip when going over boundaries.
![address_mode.png](./address_mode.png)
The `mag_filter` and `min_filter` options describe what to do when a fragment covers multiple pixels, or there are multiple fragments for a single pixel. This often comes into play when viewing a surface from up close, or from far away.
2019-11-05 08:02:41 +00:00
There are 2 options:
* `Linear`: Attempt to blend the in-between fragments so that they seem to flow together.
* `Nearest`: In-between fragments will use the color of the nearest pixel. This creates an image that's crisper from far away, but pixelated up close. This can be desirable, however, if your textures are designed to be pixelated, like in pixel art games, or voxel games like Minecraft.
2019-11-05 08:02:41 +00:00
Mipmaps are a complex topic, and will require [their own section in the future](/todo). For now, we can say that `mipmap_filter` functions similar to `(mag/min)_filter` as it tells the sampler how to blend between mipmaps.
2019-11-05 08:02:41 +00:00
I'm using some defaults for the other fields. If you want to see what they are, check [the wgpu docs](https://docs.rs/wgpu/0.7.0/wgpu/struct.SamplerDescriptor.html).
All these different resources are nice and all, but they don't do us much good if we can't plug them in anywhere. This is where `BindGroup`s and `PipelineLayout`s come in.
2019-11-05 08:02:41 +00:00
## The BindGroup
A `BindGroup` describes a set of resources and how they can be accessed by a shader. We create a `BindGroup` using a `BindGroupLayout`. Let's make one of those first.
```rust
2020-09-05 19:46:15 +00:00
let texture_bind_group_layout = device.create_bind_group_layout(
&wgpu::BindGroupLayoutDescriptor {
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
2021-09-11 16:37:05 +00:00
visibility: wgpu::ShaderStages::FRAGMENT,
2021-02-19 04:30:18 +00:00
ty: wgpu::BindingType::Texture {
2020-09-05 19:46:15 +00:00
multisampled: false,
2021-02-19 04:30:18 +00:00
view_dimension: wgpu::TextureViewDimension::D2,
2021-05-18 03:15:25 +00:00
sample_type: wgpu::TextureSampleType::Float { filterable: true },
2020-09-05 19:46:15 +00:00
},
count: None,
2019-11-05 08:02:41 +00:00
},
2020-09-05 19:46:15 +00:00
wgpu::BindGroupLayoutEntry {
binding: 1,
2021-09-11 16:37:05 +00:00
visibility: wgpu::ShaderStages::FRAGMENT,
2020-09-05 19:46:15 +00:00
ty: wgpu::BindingType::Sampler {
2021-07-20 23:48:23 +00:00
// This is only for TextureSampleType::Depth
2020-09-05 19:46:15 +00:00
comparison: false,
2021-07-20 23:48:23 +00:00
// This should be true if the sample_type of the texture is:
// TextureSampleType::Float { filterable: true }
// Otherwise you'll get an error.
2021-02-19 04:30:18 +00:00
filtering: true,
2020-09-05 19:46:15 +00:00
},
count: None,
2020-04-21 19:05:48 +00:00
},
2020-09-05 19:46:15 +00:00
],
label: Some("texture_bind_group_layout"),
}
);
2019-11-05 08:02:41 +00:00
```
Our `texture_bind_group_layout` has two entries: one for a sampled texture at binding 0, and one for a sampler at binding 1. Both of these bindings are visible only to the fragment shader as specified by `FRAGMENT`. The possible values for this field are any bitwise combination of `NONE`, `VERTEX`, `FRAGMENT`, or `COMPUTE`. Most of the time we'll only use `FRAGMENT` for textures and samplers, but it's good to know what else is available.
2019-11-05 08:02:41 +00:00
With `texture_bind_group_layout`, we can now create our `BindGroup`:
2019-11-05 08:02:41 +00:00
```rust
2020-09-05 19:46:15 +00:00
let diffuse_bind_group = device.create_bind_group(
&wgpu::BindGroupDescriptor {
layout: &texture_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
2020-10-31 10:39:50 +00:00
resource: wgpu::BindingResource::TextureView(&diffuse_texture_view),
2020-09-05 19:46:15 +00:00
},
wgpu::BindGroupEntry {
binding: 1,
2020-10-31 10:39:50 +00:00
resource: wgpu::BindingResource::Sampler(&diffuse_sampler),
2020-09-05 19:46:15 +00:00
}
],
label: Some("diffuse_bind_group"),
}
);
2019-11-05 08:02:41 +00:00
```
2021-05-24 20:38:27 +00:00
Looking at this you might get a bit of déjà vu! That's because a `BindGroup` is a more specific declaration of the `BindGroupLayout`. The reason why they're separate is it allows us to swap out `BindGroup`s on the fly, so long as they all share the same `BindGroupLayout`. Each texture and sampler we create will need to be added to a `BindGroup`. For our purposes, we'll create a new bind group for each texture.
2019-11-05 08:02:41 +00:00
Now that we have our `diffuse_bind_group`, let's add it to our `State` struct:
2019-11-05 08:02:41 +00:00
```rust
struct State {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
2021-08-28 22:11:33 +00:00
config: wgpu::SurfaceConfiguration,
size: winit::dpi::PhysicalSize<u32>,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
num_indicies: u32,
diffuse_bind_group: wgpu::BindGroup, // NEW!
2019-11-05 08:02:41 +00:00
}
```
2019-11-05 08:02:41 +00:00
And make sure we return these fields in the `new` method:
```rust
2019-11-05 08:02:41 +00:00
impl State {
2020-04-21 19:05:48 +00:00
async fn new() -> Self {
2019-11-05 08:02:41 +00:00
// ...
Self {
surface,
device,
queue,
2021-08-28 22:11:33 +00:00
config,
size,
2019-11-05 08:02:41 +00:00
render_pipeline,
vertex_buffer,
index_buffer,
num_indices,
// NEW!
2019-11-05 08:02:41 +00:00
diffuse_bind_group,
}
}
}
```
Now that we've got our `BindGroup`, we can use it in our `render()` function.
2019-11-05 08:02:41 +00:00
```rust
// render()
// ...
2020-05-28 19:57:07 +00:00
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]); // NEW!
2021-03-21 14:01:00 +00:00
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
2021-02-19 04:30:18 +00:00
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
2020-05-28 19:57:07 +00:00
render_pass.draw_indexed(0..self.num_indices, 0, 0..1);
2019-11-05 08:02:41 +00:00
```
## PipelineLayout
Remember the `PipelineLayout` we created back in [the pipeline section](/beginner/tutorial3-pipeline#how-do-we-use-the-shaders)? Now we finally get to use it! The `PipelineLayout` contains a list of `BindGroupLayout`s that the pipeline can use. Modify `render_pipeline_layout` to use our `texture_bind_group_layout`.
2019-11-05 08:02:41 +00:00
```rust
2021-02-19 04:30:18 +00:00
async fn new(...) {
// ...
let render_pipeline_layout = device.create_pipeline_layout(
&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"), // NEW!
bind_group_layouts: &[&texture_bind_group_layout], // NEW!
push_constant_ranges: &[],
}
);
// ...
}
2019-11-05 08:02:41 +00:00
```
## A change to the VERTICES
There's a few things we need to change about our `Vertex` definition. Up to now we've been using a `color` attribute to set the color of our mesh. Now that we're using a texture, we want to replace our `color` with `tex_coords`. These coordinates will then be passed to the `Sampler` to retrieve the appropriate color.
Since our `tex_coords` are two dimensional, we'll change the field to take two floats instead of three.
First, we'll change the `Vertex` struct:
2019-11-05 08:02:41 +00:00
```rust
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
2019-11-05 08:02:41 +00:00
struct Vertex {
position: [f32; 3],
tex_coords: [f32; 2], // NEW!
2019-11-05 08:02:41 +00:00
}
```
2021-02-12 06:29:40 +00:00
And then reflect these changes in the `VertexBufferLayout`:
2019-11-05 08:02:41 +00:00
```rust
impl Vertex {
2021-02-12 06:29:40 +00:00
fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
2020-09-05 19:46:15 +00:00
use std::mem;
2021-02-12 06:29:40 +00:00
wgpu::VertexBufferLayout {
array_stride: mem::size_of::<Vertex>() as wgpu::BufferAddress,
2021-09-11 16:19:15 +00:00
step_mode: wgpu::VertexStepMode::Vertex,
2020-09-05 19:46:15 +00:00
attributes: &[
2021-02-12 06:29:40 +00:00
wgpu::VertexAttribute {
2020-09-05 19:46:15 +00:00
offset: 0,
shader_location: 0,
2021-05-01 21:55:26 +00:00
format: wgpu::VertexFormat::Float32x3,
2020-09-05 19:46:15 +00:00
},
2021-02-12 06:29:40 +00:00
wgpu::VertexAttribute {
2020-09-05 19:46:15 +00:00
offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
2021-05-01 21:55:26 +00:00
format: wgpu::VertexFormat::Float32x2, // NEW!
2020-09-05 19:46:15 +00:00
},
]
2019-11-05 08:02:41 +00:00
}
}
}
```
Lastly we need to change `VERTICES` itself. Replace the existing definition with the following:
2019-11-05 08:02:41 +00:00
```rust
// Changed
2019-11-05 08:02:41 +00:00
const VERTICES: &[Vertex] = &[
2020-04-21 19:05:48 +00:00
Vertex { position: [-0.0868241, 0.49240386, 0.0], tex_coords: [0.4131759, 0.99240386], }, // A
Vertex { position: [-0.49513406, 0.06958647, 0.0], tex_coords: [0.0048659444, 0.56958646], }, // B
Vertex { position: [-0.21918549, -0.44939706, 0.0], tex_coords: [0.28081453, 0.050602943], }, // C
Vertex { position: [0.35966998, -0.3473291, 0.0], tex_coords: [0.85967, 0.15267089], }, // D
Vertex { position: [0.44147372, 0.2347359, 0.0], tex_coords: [0.9414737, 0.7347359], }, // E
2019-11-05 08:02:41 +00:00
];
```
## Shader time
With our new `Vertex` structure in place it's time to update our shaders. We'll first need to pass our `tex_coords` into the vertex shader and then use them over to our fragment shader to get the final color from the `Sampler`. Let's start with the vertex shader:
2019-11-05 08:02:41 +00:00
2021-05-19 02:38:15 +00:00
```wgsl
// Vertex shader
2019-11-05 08:02:41 +00:00
2021-05-19 02:38:15 +00:00
struct VertexInput {
[[location(0)]] position: vec3<f32>;
[[location(1)]] tex_coords: vec2<f32>;
};
2019-11-05 08:02:41 +00:00
2021-05-19 02:38:15 +00:00
struct VertexOutput {
[[builtin(position)]] clip_position: vec4<f32>;
[[location(0)]] tex_coords: vec2<f32>;
};
2019-11-05 08:02:41 +00:00
2021-05-19 02:38:15 +00:00
[[stage(vertex)]]
fn main(
model: VertexInput,
) -> VertexOutput {
var out: VertexOutput;
out.tex_coords = model.tex_coords;
out.clip_position = vec4<f32>(model.position, 1.0);
return out;
2019-11-05 08:02:41 +00:00
}
```
2021-05-19 02:38:15 +00:00
Now that we have our vertex shader outputting our `tex_coords`, we need to change the fragment shader to take them in. With these coordinates, we'll finally be able to use our sampler to get a color from our texture.
2019-11-05 08:02:41 +00:00
```glsl
2021-05-19 02:38:15 +00:00
// Fragment shader
2019-11-05 08:02:41 +00:00
2021-05-19 02:38:15 +00:00
[[group(0), binding(0)]]
var t_diffuse: texture_2d<f32>;
[[group(0), binding(1)]]
var s_diffuse: sampler;
2019-11-05 08:02:41 +00:00
2021-05-19 02:38:15 +00:00
[[stage(fragment)]]
fn main(in: VertexOutput) -> [[location(0)]] vec4<f32> {
return textureSample(t_diffuse, s_diffuse, in.tex_coords);
2019-11-05 08:02:41 +00:00
}
```
2021-05-19 02:38:15 +00:00
The variables `t_diffuse` and `s_diffuse` are what's known as uniforms. We'll go over uniforms more in the [cameras section](/beginner/tutorial6-uniforms/). For now, all we need to know is that `group()` corresponds to the 1st parameter in `set_bind_group()` and `binding()` relates to the `binding` specified when we created the `BindGroupLayout` and `BindGroup`.
2019-11-05 08:02:41 +00:00
## The results
If we run our program now we should get the following result:
2019-11-05 08:02:41 +00:00
![an upside down tree on a hexagon](./upside-down.png)
2020-07-02 00:51:09 +00:00
That's weird, our tree is upside down! This is because wgpu's world coordinates have the y-axis pointing up, while texture coordinates have the y-axis pointing down. In other words, (0, 0) in texture coordinates coresponds to the top-left of the image, while (1, 1) is the bottom right.
![happy-tree-uv-coords.png](./happy-tree-uv-coords.png)
We can get our triangle right-side up by inverting the y coordinate of each texture coordinate:
```rust
const VERTICES: &[Vertex] = &[
// Changed
2020-04-21 19:05:48 +00:00
Vertex { position: [-0.0868241, 0.49240386, 0.0], tex_coords: [0.4131759, 0.00759614], }, // A
Vertex { position: [-0.49513406, 0.06958647, 0.0], tex_coords: [0.0048659444, 0.43041354], }, // B
2021-08-04 12:32:59 +00:00
Vertex { position: [-0.21918549, -0.44939706, 0.0], tex_coords: [0.28081453, 0.949397], }, // C
Vertex { position: [0.35966998, -0.3473291, 0.0], tex_coords: [0.85967, 0.84732914], }, // D
2020-04-21 19:05:48 +00:00
Vertex { position: [0.44147372, 0.2347359, 0.0], tex_coords: [0.9414737, 0.2652641], }, // E
];
```
With that in place, we now have our tree right-side up on our hexagon:
2019-11-05 08:02:41 +00:00
![our happy tree as it should be](./rightside-up.png)
2020-02-24 23:23:23 +00:00
## Cleaning things up
For convenience sake, let's pull our texture code into its module. We'll first need to add the [anyhow](https://docs.rs/anyhow/) crate to our `Cargo.toml` file to simplify error handling;
```toml
[dependencies]
image = "0.23"
2021-04-11 07:38:53 +00:00
cgmath = "0.18"
2021-06-19 22:31:49 +00:00
winit = "0.25"
env_logger = "0.9"
log = "0.4"
2021-07-14 12:26:05 +00:00
pollster = "0.2"
2021-08-28 22:11:33 +00:00
wgpu = "0.10"
bytemuck = { version = "1.4", features = [ "derive" ] }
anyhow = "1.0" // NEW!
```
Then, in a new file called `src/texture.rs`, add the following:
2020-02-24 23:23:23 +00:00
```rust
use image::GenericImageView;
2020-09-05 19:46:15 +00:00
use anyhow::*;
2020-02-24 23:23:23 +00:00
pub struct Texture {
pub texture: wgpu::Texture,
pub view: wgpu::TextureView,
pub sampler: wgpu::Sampler,
}
impl Texture {
2020-09-05 19:46:15 +00:00
pub fn from_bytes(
device: &wgpu::Device,
queue: &wgpu::Queue,
bytes: &[u8],
label: &str
) -> Result<Self> {
2020-02-24 23:23:23 +00:00
let img = image::load_from_memory(bytes)?;
2020-09-05 19:46:15 +00:00
Self::from_image(device, queue, &img, Some(label))
2020-02-24 23:23:23 +00:00
}
2020-09-05 19:46:15 +00:00
pub fn from_image(
device: &wgpu::Device,
queue: &wgpu::Queue,
img: &image::DynamicImage,
label: Option<&str>
) -> Result<Self> {
2020-02-24 23:23:23 +00:00
let rgba = img.as_rgba8().unwrap();
let dimensions = img.dimensions();
let size = wgpu::Extent3d {
width: dimensions.0,
height: dimensions.1,
2021-05-01 21:55:26 +00:00
depth_or_array_layers: 1,
2020-02-24 23:23:23 +00:00
};
2020-09-05 19:46:15 +00:00
let texture = device.create_texture(
&wgpu::TextureDescriptor {
label,
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
2021-09-11 16:37:05 +00:00
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2020-09-05 19:46:15 +00:00
}
2020-04-21 19:05:48 +00:00
);
2020-02-24 23:23:23 +00:00
2020-09-05 19:46:15 +00:00
queue.write_texture(
2021-05-01 21:55:26 +00:00
wgpu::ImageCopyTexture {
2021-09-11 16:37:05 +00:00
aspect: wgpu::TextureAspect::All,
2020-02-24 23:23:23 +00:00
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
2020-05-11 16:24:44 +00:00
},
2020-09-05 19:46:15 +00:00
rgba,
2021-05-01 21:55:26 +00:00
wgpu::ImageDataLayout {
2020-09-05 19:46:15 +00:00
offset: 0,
2021-06-06 17:32:38 +00:00
bytes_per_row: std::num::NonZeroU32::new(4 * dimensions.0),
rows_per_image: std::num::NonZeroU32::new(dimensions.1),
2020-09-05 19:46:15 +00:00
},
2020-02-24 23:23:23 +00:00
size,
);
2020-09-05 19:46:15 +00:00
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
let sampler = device.create_sampler(
&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Nearest,
mipmap_filter: wgpu::FilterMode::Nearest,
..Default::default()
}
);
Ok(Self { texture, view, sampler })
2020-02-24 23:23:23 +00:00
}
}
```
Note that we're returning a `CommandBuffer` with our texture. This means we can load multiple textures at the same time, and then submit all their command buffers at once.
2020-02-24 23:23:23 +00:00
We need to import `texture.rs` as a module, so somewhere at the top of `main.rs` add the following.
```rust
mod texture;
```
The texture creation code in `new()` now gets a lot simpler:
2020-02-24 23:23:23 +00:00
```rust
2021-08-28 22:11:33 +00:00
surface.configure(&device, &config);
let diffuse_bytes = include_bytes!("happy-tree.png"); // CHANGED!
let diffuse_texture = texture::Texture::from_bytes(&device, &queue, diffuse_bytes, "happy-tree.png").unwrap(); // CHANGED!
// Everything up until `let texture_bind_group_layout = ...` can now be removed.
2020-02-24 23:23:23 +00:00
```
We still need to store the bind group separately so that `Texture` doesn't need know how the `BindGroup` is laid out. Creating the `diffuse_bind_group` changes slightly to use the `view` and `sampler` fields of our `diffuse_texture`:
2020-02-24 23:23:23 +00:00
```rust
2020-09-05 19:46:15 +00:00
let diffuse_bind_group = device.create_bind_group(
&wgpu::BindGroupDescriptor {
layout: &texture_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&diffuse_texture.view), // CHANGED!
2020-09-05 19:46:15 +00:00
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&diffuse_texture.sampler), // CHANGED!
2020-09-05 19:46:15 +00:00
}
],
label: Some("diffuse_bind_group"),
}
);
2020-02-24 23:23:23 +00:00
```
Finally, let's update our `State` field to use our shiny new `Texture` struct, as we'll need it in future tutorials.
```rust
struct State {
// ...
diffuse_bind_group: wgpu::BindGroup,
diffuse_texture: texture::Texture, // NEW
}
```
```rust
impl State {
async fn new() -> Self {
// ...
Self {
// ...
num_indices,
diffuse_bind_group,
diffuse_texture, // NEW
}
}
}
```
Phew!
With these changes in place, the code should be working the same as it was before, but we now have a much easier way to create textures.
2020-02-24 23:23:23 +00:00
## Challenge
Create another texture and swap it out when you press the space key.
<AutoGithubLink/>