#include "RayTypes.h"

StructuredBuffer<SphereHit> Hits : register(t0, space0);
StructuredBuffer<SphereRay> Rays : register(t1, space0);
StructuredBuffer<Sphere> Spheres : register(t2, space0);
RWStructuredBuffer<PixelIdData> Pixels : register(u0, space1);

cbuffer UBO : register(b0, space2)
{
    int4 ubo_size : packoffset(c0);
    int spheresCount : packoffset(c1.x);
    int4 skybox_size: packoffset(c2);
};

[numthreads(64, 1, 1)]
void main(uint3 GlobalInvocationID : SV_DispatchThreadID)
{
    uint n = GlobalInvocationID.x;

    SphereRay ray = Rays[n];
    SphereHit hit = Hits[n];

    PixelIdData pixel;
    float3 heading = ray.Heading.xyz;

    if (hit.SphereId < spheresCount)
    {
        float3 spot = ray.Position.xyz + heading * hit.RayDistance;
        Sphere sphere = Spheres[hit.SphereId];
        float3 normal = normalize(spot - sphere.PositionAndRadius.xyz);
        pixel.id.xyz = abs(normal);
        pixel.id.w = 1;
    }
    else
    {
        pixel.id.xyz = float3(1.0, 1.0, 1.0);
    }
    Pixels[n] = pixel;
}
