Galactica/crates/render/shaders/include/anchor.wgsl

52 lines
1.8 KiB
Plaintext
Raw Normal View History

2024-01-08 17:57:49 -08:00
// Given an anchored position and sprite dimensions,
// return the translation that should be applied on
// vertex coordinates
fn anchor(
anchor: u32, // Anchor index
position: vec2<f32>, // Anchored position
dim: vec2<f32>, // Sprite dimensions (width, height)
) -> vec2<f32> {
2024-01-30 17:05:03 -08:00
// TODO: remove, do in ui rust lib
2024-01-08 17:57:49 -08:00
var trans: vec2<f32> = vec2(0.0, 0.0);
2024-01-27 14:49:34 -08:00
let window_dim = (
vec2(global_data.window_size_w, global_data.window_size_h) /
global_data.window_scale
);
2024-01-08 17:57:49 -08:00
if anchor == 0u { // NW C (screen anchor, sprite anchor)
trans += vec2(-window_dim.x, window_dim.y) / 2.0; // origin
trans += vec2(0.0, 0.0) / 2.0; // offset
} else if anchor == 1u { // NW NW
trans += vec2(-window_dim.x, window_dim.y) / 2.0;
trans += vec2(dim.x, -dim.y) / 2.0;
} else if anchor == 2u { // NW NE
trans += vec2(-window_dim.x, window_dim.y) / 2.0;
trans += vec2(-dim.x, -dim.y) / 2.0;
} else if anchor == 3u { // NW SW
trans += vec2(-window_dim.x, window_dim.y) / 2.0;
trans += vec2(dim.x, dim.y) / 2.0;
} else if anchor == 4u { // NW SE
trans += vec2(-window_dim.x, window_dim.y) / 2.0;
trans += vec2(-dim.x, dim.y) / 2.0;
} else if anchor == 5u { // NE NE
trans += vec2(window_dim.x, window_dim.y) / 2.0;
2024-01-08 18:12:13 -08:00
trans += vec2(-dim.x, -dim.y) / 2.0;
2024-01-17 10:17:18 -08:00
} else if anchor == 6u { // C C
trans += vec2(0.0, 0.0) / 2.0;
trans += vec2(0.0, 0.0) / 2.0;
} else if anchor == 7u { // C NW
trans += vec2(0.0, 0.0) / 2.0;
trans += vec2(dim.x, -dim.y) / 2.0;
2024-01-08 17:57:49 -08:00
} else { // center / center as default, since it's the most visible variant.
2024-01-08 18:12:13 -08:00
trans += vec2(0.0, 0.0) / 2.0;
2024-01-08 17:57:49 -08:00
trans += vec2(0.0, 0.0) / 2.0;
}
trans += position;
// This renders correctly, but the offsets here are off by a factor of two.
// I'm not sure why... might be because WGPU screen coordinates are -1 to 1.
return (trans / window_dim) * 2.0;
}