I would like to draw 100 circles with 2D SDF and frag shader. What is the best way to pass per-instance data to the frag shader?
One method that might work: create a vertex buffer with wgpu::VertexStepMode::Instance and pass it to the vertex shader, and then pass it to the frag shader. Each circle has 4 vertices representing its bounding rect, and these 4 vertices receive the same instance data. The interpolation of 4 instance data (which is a waste of compute) is passed to the frag shader.
struct FragmentInput {
@builtin(position) position: vec4<f32>,
};
struct InstanceData {
@location(5) position: vec2<f32>, // the center of a circle
@location(6) size: f32,
}
@fragment
fn fs_main(args: FragmentInput, instance: InstanceData) -> @location(0) vec4<f32> {
let dx = args.position.x - instance.x;
let dy = args.position.y - instance.y;
let dist_sq = dx * dx + dy * dy;
// color the circle
if dist_sq > instance.size * instance.size {
return vec4<f32>(1.0, 1.0, 0.0, 1.0);
} else {
return vec4<f32>(0.0, 0.0, 0.0, 1.0);
}
}