Skip to content

Commit dc78d42

Browse files
committed
preserve image aspect ratio
1 parent 6618306 commit dc78d42

File tree

2 files changed

+24
-12
lines changed

2 files changed

+24
-12
lines changed

shader.wgsl

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@ fn transform_coords2(coords: vec2<f32>) -> vec2<f32> {
2626
}
2727

2828
struct Data {
29-
@location(0) image_dim: vec2<f32>,
30-
@location(1) pos: vec2<f32>,
31-
@location(2) scale: f32,
32-
@location(3) padding: vec2<f32>,
29+
@location(0) img_dim: vec2<f32>,
30+
@location(1) win_dim: vec2<f32>,
31+
@location(2) pos: vec2<f32>,
32+
@location(3) scale: f32,
3333
}
3434

3535
struct VertexOutput {
@@ -42,8 +42,14 @@ fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> VertexOutput {
4242
let pos = vec2<f32>(f32((in_vertex_index & 2u) >> 1), f32(in_vertex_index & 1u));
4343
var out: VertexOutput;
4444
out.tex_coords = vec2<f32>(pos.x, 1 - pos.y);
45+
var scale: vec2<f32>;
46+
if (data.win_dim.y > data.win_dim.x) {
47+
scale = vec2<f32>(data.scale, data.scale * data.win_dim.x / data.win_dim.y * data.img_dim.y / data.img_dim.x);
48+
} else {
49+
scale = vec2<f32>(data.scale * data.win_dim.y / data.win_dim.x * data.img_dim.x / data.img_dim.y, data.scale);
50+
}
4551
out.pos = vec4<f32>(
46-
((pos + data.pos) * 2.0 - 1) * data.scale,
52+
((pos + data.pos) * 2.0 - 1) * scale,
4753
0.0, 1.0
4854
);
4955
return out;

src/lib.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ struct App {
3131
// stuff to load/reload later
3232
bind_group: Option<BindGroup>,
3333
data_buffer: wgpu::Buffer,
34-
dim: (f32, f32),
34+
img_dim: (f32, f32),
3535
pos: (f32, f32),
3636
scale: f32,
3737
}
@@ -40,10 +40,16 @@ impl App {
4040
// must be a multiple of 16 bytes
4141
fn buf_contents(&self) -> [u8; 32] {
4242
let mut ret = [0u8; 32];
43-
for (dst, src) in ret
44-
.chunks_exact_mut(4)
45-
.zip([self.dim.0, self.dim.1, self.pos.0, self.pos.1, self.scale])
46-
{
43+
let win_dim = self.window.inner_size();
44+
for (dst, src) in ret.chunks_exact_mut(4).zip([
45+
self.img_dim.0,
46+
self.img_dim.1,
47+
win_dim.width as f32,
48+
win_dim.height as f32,
49+
self.pos.0,
50+
self.pos.1,
51+
self.scale,
52+
]) {
4753
dst.copy_from_slice(&src.to_le_bytes());
4854
}
4955
ret
@@ -97,7 +103,7 @@ impl App {
97103
fn load_image(&mut self, img: image::DynamicImage) {
98104
let dimensions = img.dimensions();
99105
let rgba = img.into_rgba8();
100-
self.dim = (dimensions.0 as f32, dimensions.1 as f32);
106+
self.img_dim = (dimensions.0 as f32, dimensions.1 as f32);
101107

102108
let size = wgpu::Extent3d {
103109
width: dimensions.0,
@@ -286,7 +292,7 @@ impl App {
286292
bind_group: None,
287293
layout,
288294
data_buffer,
289-
dim: (0., 0.),
295+
img_dim: (0., 0.),
290296
pos: (0.0, 0.0),
291297
scale: 1.0,
292298
}

0 commit comments

Comments
 (0)