Galactica/src/render/shaders/starfield.wgsl

92 lines
2.2 KiB
WebGPU Shading Language
Raw Normal View History

2023-12-23 12:52:36 -08:00
// Vertex shader
2023-12-23 11:01:27 -08:00
struct InstanceInput {
2023-12-23 14:07:12 -08:00
@location(2) position: vec2<f32>,
2023-12-23 23:24:04 -08:00
@location(3) parallax: f32,
@location(4) height: f32,
2023-12-23 11:01:27 -08:00
};
2023-12-23 23:24:04 -08:00
struct VertexInput {
@location(0) position: vec3<f32>,
@location(1) texture_coords: vec2<f32>,
}
2023-12-23 11:01:27 -08:00
struct VertexOutput {
2023-12-23 23:24:04 -08:00
@builtin(position) position: vec4<f32>,
@location(0) texture_coords: vec2<f32>,
}
@group(1) @binding(0)
var<uniform> global: GlobalUniform;
struct GlobalUniform {
camera_position: vec2<f32>,
camera_zoom: f32,
window_aspect: f32,
starfield_texture: u32,
starfield_tile_size: f32
};
fn fmod(x: vec2<f32>, m: f32) -> vec2<f32> {
return x - floor(x * (1.0 / m)) * m;
2023-12-23 11:01:27 -08:00
}
@vertex
fn vertex_shader_main(
2023-12-23 23:24:04 -08:00
vertex: VertexInput,
2023-12-23 11:01:27 -08:00
instance: InstanceInput,
) -> VertexOutput {
2023-12-23 23:24:04 -08:00
// Center of the tile the camera is currently in, in game coordinates.
// x div y = x - (x mod y)
let tile_center = (
global.camera_position
- (
fmod(
2023-12-23 23:56:10 -08:00
global.camera_position + global.starfield_tile_size / 2.0,
2023-12-23 23:24:04 -08:00
global.starfield_tile_size
2023-12-23 23:56:10 -08:00
) - global.starfield_tile_size / 2.0
2023-12-23 23:24:04 -08:00
)
);
// Apply sprite aspect ratio & scale factor
// also applies screen aspect ratio
let scale = instance.height / global.camera_zoom;
var pos: vec2<f32> = vec2<f32>(
vertex.position.x * scale / global.window_aspect,
vertex.position.y * scale
);
// World position relative to camera
// (Note that instance position is in a different
// coordinate system than usual)
let camera_pos = (instance.position + tile_center) - global.camera_position;
// Translate
pos = pos + (
// Don't forget to correct distance for screen aspect ratio too!
2023-12-23 23:56:10 -08:00
(camera_pos / (global.camera_zoom * instance.parallax))
2023-12-23 23:24:04 -08:00
/ vec2<f32>(global.window_aspect, 1.0)
);
2023-12-23 11:01:27 -08:00
var out: VertexOutput;
2023-12-23 23:56:10 -08:00
out.position = vec4<f32>(pos, 0.0, 1.0) * instance.parallax;
2023-12-23 23:24:04 -08:00
out.texture_coords = vertex.texture_coords;
2023-12-23 11:01:27 -08:00
return out;
}
2023-12-23 23:24:04 -08:00
@group(0) @binding(0)
var texture_array: binding_array<texture_2d<f32>>;
@group(0) @binding(1)
var sampler_array: binding_array<sampler>;
2023-12-23 12:52:36 -08:00
// Fragment shader
2023-12-23 11:01:27 -08:00
@fragment
fn fragment_shader_main(in: VertexOutput) -> @location(0) vec4<f32> {
2023-12-23 23:24:04 -08:00
return textureSampleLevel(
texture_array[1],
sampler_array[1],
in.texture_coords,
0.0
).rgba * vec4<f32>(0.5, 0.5, 0.5, 1.0);
2023-12-23 11:01:27 -08:00
}