#version 450

// Particle structure (must match compute shader)
struct Particle {
    vec4 position;      // xyz = position, w = life
    vec4 velocity;      // xyz = velocity, w = size
    vec4 color;         // rgba = color with alpha
};

// Input from vertex buffer (particle instances)
layout(set = 0, binding = 0, std430) readonly buffer ParticleBuffer {
    Particle particles[];
};

// Quad vertices for billboard (sent per vertex)
layout(location = 0) in vec2 in_position; // Quad corner (-1,-1) to (1,1)
layout(location = 1) in vec2 in_texCoord; // Texture coordinates (0,0) to (1,1)

// Uniform buffer for view/projection matrices
layout(set = 0, binding = 1) uniform CameraUBO {
    mat4 viewMatrix;
    mat4 projMatrix;
    vec4 cameraPosition;    // xyz = position, w = time
} camera;

// Outputs to fragment shader
layout(location = 0) out vec2 out_texCoord;
layout(location = 1) out vec4 out_color;
layout(location = 2) out float out_life;

void main() {
    // Get particle index from instance
    uint particleIndex = gl_InstanceIndex;
    
    // Get particle data
    Particle particle = particles[particleIndex];
    
    if (particle.position.w <= 0.0) {
        gl_Position = vec4(-2.0, -2.0, -2.0, 1.0); // Move off-screen
        out_texCoord = in_texCoord;
        out_color = vec4(0.0);
        out_life = 0.0;
        return;
    }
    
    // Calculate particle size
    float size = particle.velocity.w;
    
    // Create billboard that faces the camera
    vec3 particlePos = particle.position.xyz;
    vec3 cameraPos = camera.cameraPosition.xyz;
    
    // Calculate camera-facing vectors
    vec3 forward = normalize(cameraPos - particlePos);
    vec3 up = vec3(0.0, 1.0, 0.0);
    vec3 right = normalize(cross(up, forward));
    up = cross(forward, right);
    
    // billboard corner
    vec3 worldPos = particlePos + (right * in_position.x + up * in_position.y) * size;
    
    // clip space
    vec4 viewPos = camera.viewMatrix * vec4(worldPos, 1.0);
    gl_Position = camera.projMatrix * viewPos;
    
    out_texCoord = in_texCoord;
    out_color = particle.color;
    out_life = particle.position.w;
} 