WGSL Editor
A simple online editor for the WebGPU Shading Language (WGSL).
untitled.wgsl — WGSL Editor
1
// A fragment shader which lights textured geometry with point lights.2
3
// Lights from a storage buffer binding.4
struct PointLight {5
position : vec3f,6
color : vec3f,7
}8
9
struct LightStorage {10
pointCount : u32,11
point : array<PointLight>,12
}13
@group(0) @binding(0) var<storage> lights : LightStorage;14
15
// Texture and sampler.16
@group(1) @binding(0) var baseColorSampler : sampler;17
@group(1) @binding(1) var baseColorTexture : texture_2d<f32>;18
19
// Function arguments are values from the vertex shader.20
@fragment21
fn fragmentMain(@location(0) worldPos : vec3f,22
@location(1) normal : vec3f,23
@location(2) uv : vec2f) -> @location(0) vec4f {24
// Sample the base color of the surface from a texture.25
let baseColor = textureSample(baseColorTexture, baseColorSampler, uv);26
27
let N = normalize(normal);28
var surfaceColor = vec3f(0);29
30
// Loop over the scene point lights.31
for (var i = 0u; i < lights.pointCount; i++) {32
let worldToLight = lights.point[i].position - worldPos;33
let dist = length(worldToLight);34
let dir = normalize(worldToLight);35
36
// Determine the contribution of this light to the surface color.37
let radiance = lights.point[i].color * (1 / pow(dist, 2));38
let nDotL = max(dot(N, dir), 0);39
40
// Accumulate light contribution to the surface color.41
surfaceColor += baseColor.rgb * radiance * nDotL;42
}43
44
// Return the accumulated surface color.45
return vec4(surfaceColor, baseColor.a);46
}