// RTMultiShadow — multi-light shadowing through the wavefront RT pipeline
// (issue #30). Five pillars on a checkered ground, lit by four colored
// point lights; the closest-hit emits one shadow ray PER LIGHT from the
// same invocation, so up to four rays per pixel resolve in a single SHADE
// pass. That requires both halves of #30:
//   - atomic rtAccumulate — the concurrent per-pixel adds don't race;
//   - RTPass::raysPerPixel — the ray/hit/payload buffers hold 4·W·H rays
//     per bounce, so none of the per-light emits get capacity-dropped.
// Each pillar casting four differently-colored shadows is the visual
// proof; any lost accumulate (race) or dropped ray (capacity) shows up as
// flickering dark noise / a missing shadow color.
//
// WebGPU/DOM only — the wavefront tracer is the WebGPU software RT path.

#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
int main() { return 0; }   // native path is hardware RT; out of scope here
#else

import Crafter.Graphics;
import Crafter.Math;
import Crafter.Event;
import std;

using namespace Crafter;
namespace fs = std::filesystem;

namespace {
    // Must match LIGHT_COUNT in closesthit.wgsl — it is the raysPerPixel
    // budget the RTPass is configured with.
    constexpr std::uint32_t kLightCount = 4;

    struct CameraGPU {
        float origin[3];   float pad0;
        float right[3];    float tanHalf;
        float up[3];       float aspect;
        float forward[3];  float pad1;
    };
    static_assert(sizeof(CameraGPU) == 64);

    // Axis-aligned box: 8 corners between mn and mx, same winding as the
    // RTStress unit cube.
    std::array<Vector<float, 3, 3>, 8> BoxVerts(float mnx, float mny, float mnz,
                                                float mxx, float mxy, float mxz) {
        return {{
            {mnx, mny, mnz}, {mxx, mny, mnz}, {mxx, mxy, mnz}, {mnx, mxy, mnz},
            {mnx, mny, mxz}, {mxx, mny, mxz}, {mxx, mxy, mxz}, {mnx, mxy, mxz},
        }};
    }
    // Mesh::Build takes mutable spans, so this can't be constexpr.
    std::array<std::uint32_t, 36> kBoxIndices {{
        0,1,2, 0,2,3,   5,4,7, 5,7,6,   4,0,3, 4,3,7,
        1,5,6, 1,6,2,   4,5,1, 4,1,0,   3,2,6, 3,6,7,
    }};
}

int main() {
    std::println("[RTMultiShadow] {} lights, one shadow ray per light per pixel", kLightCount);

    Device::Initialize();
    static Window window(1280, 720, "RTMultiShadow");
    auto cmd = window.StartInit();

    DescriptorHeapWebGPU heap;
    heap.Initialize(/*images*/ 1, /*buffers*/ 2, /*samplers*/ 1);

    std::array<WebGPUShader, 4> shaders {{
        WebGPUShader(fs::path("raygen.wgsl"),     "raygen_main",     WebGPURTStage::Raygen),
        WebGPUShader(fs::path("miss.wgsl"),       "miss_main",       WebGPURTStage::Miss),
        WebGPUShader(fs::path("closesthit.wgsl"), "closesthit_main", WebGPURTStage::ClosestHit),
        WebGPUShader(fs::path("resolve.wgsl"),    "resolve_main",    WebGPURTStage::Resolve),
    }};
    ShaderBindingTableWebGPU sbt;
    sbt.Init(shaders);

    std::array<RTShaderGroup, 1> raygenGroups {{ { .type = RTShaderGroupType::General,           .generalShader = 0 } }};
    std::array<RTShaderGroup, 1> missGroups   {{ { .type = RTShaderGroupType::General,           .generalShader = 1 } }};
    std::array<RTShaderGroup, 1> hitGroups    {{ { .type = RTShaderGroupType::TrianglesHitGroup, .closestHitShader = 2 } }};

    // One user binding: the camera storage buffer at @group(3).
    std::array<UICustomBinding, 1> bindings {{
        { .group = 3, .binding = 0, .kind = UICustomBindingKind::Buffer, .pushOffset = 0 },
    }};

    PipelineRTWebGPU pipeline;
    pipeline.Init(cmd, raygenGroups, missGroups, hitGroups, sbt, bindings);

    // ── Meshes: a large ground slab and a pillar (origin at its base). ──
    static auto groundVerts = BoxVerts(-30.0f, -1.0f, -30.0f, 30.0f, 0.0f, 30.0f);
    static auto pillarVerts = BoxVerts(-0.8f,   0.0f,  -0.8f,  0.8f, 6.0f,  0.8f);
    static Mesh ground, pillar;
    ground.Build(groundVerts, kBoxIndices, cmd);
    pillar.Build(pillarVerts, kBoxIndices, cmd);

    // ── Camera buffer + handle array. ─────────────────────────────────
    WebGPUBuffer<CameraGPU, true> cameraBuf;
    cameraBuf.Create(1);
    static std::array<std::uint32_t, 1> userHandles { cameraBuf.handle };

    // ── Instances: ground (customIndex 0) + five pillars. ─────────────
    struct Placement { float x, z; };
    static constexpr std::array<Placement, 5> kPillars {{
        { 0.0f, 0.0f }, { 5.0f, 5.0f }, { -5.0f, 5.0f }, { 5.0f, -5.0f }, { -5.0f, -5.0f },
    }};
    static std::vector<RenderingElement3D> renderers;
    renderers.reserve(1 + kPillars.size());
    auto addInstance = [&](std::uint64_t blasAddr, float x, float z) {
        renderers.emplace_back();
        RenderingElement3D& r = renderers.back();
        auto& tx = r.instance.transform.matrix;
        tx[0][0] = 1; tx[0][1] = 0; tx[0][2] = 0; tx[0][3] = x;
        tx[1][0] = 0; tx[1][1] = 1; tx[1][2] = 0; tx[1][3] = 0;
        tx[2][0] = 0; tx[2][1] = 0; tx[2][2] = 1; tx[2][3] = z;
        r.instance.instanceCustomIndex                    = static_cast<std::uint32_t>(renderers.size() - 1);
        r.instance.mask                                   = 0xFF;
        r.instance.instanceShaderBindingTableRecordOffset = 0;
        r.instance.flags                                  = kRTGeometryInstanceForceOpaque;
        r.instance.accelerationStructureReference         = blasAddr;
        RenderingElement3D::Add(&r);
    };
    addInstance(ground.blasAddr, 0.0f, 0.0f);
    for (const auto& p : kPillars) addInstance(pillar.blasAddr, p.x, p.z);
    RenderingElement3D::BuildTLAS(cmd, 0);

    window.descriptorHeap = &heap;
    window.FinishInit();

    RTPass rtPass(&pipeline);
    rtPass.handlesPtr   = userHandles.data();
    rtPass.handlesCount = static_cast<std::uint32_t>(userHandles.size());
    rtPass.maxDepth     = 2;            // primary + shadow
    rtPass.raysPerPixel = kLightCount;  // one shadow ray per light per pixel
    window.passes.push_back(&rtPass);

    // ── Free camera framing the pillars from above one corner. ────────
    struct CamState {
        Vector<float, 3, 4> position;
        float yaw;
        float pitch;
    } cam {
        Vector<float, 3, 4>{ 16.0f, 13.0f, 16.0f },
        0.0f, 0.0f,
    };
    {
        // Aim at the scene centre, slightly above the ground.
        Vector<float, 3, 4> d { -cam.position.x, 2.0f - cam.position.y, -cam.position.z };
        const float len = std::sqrt(d.x*d.x + d.y*d.y + d.z*d.z);
        cam.yaw   = std::atan2(d.z, d.x);
        cam.pitch = std::asin(d.y / len);
    }

    Input::Map inputMap;
    Input::Action& moveAct = inputMap.AddAction("Move", Input::ActionType::Vector2);
    Input::Action& lookAct = inputMap.AddAction("Look", Input::ActionType::Vector2);
    moveAct.bindings = { Input::WASDBind{
        Key(CrafterKeys::W), Key(CrafterKeys::S), Key(CrafterKeys::A), Key(CrafterKeys::D) } };
    lookAct.bindings = { Input::MouseDeltaBind{ 1.0f } };
    inputMap.Attach(window);

    const float kMoveSpeed = 14.0f;
    const float kLookSens  = 0.05f;
    const float kDt        = 1.0f / 60.0f;

    static int frames = 0;
    EventListener<void> camTick(&window.onBeforeUpdate, [&]() {
        inputMap.Tick();
        cam.yaw   += lookAct.vector2.x * kLookSens;
        cam.pitch -= lookAct.vector2.y * kLookSens;
        cam.pitch  = std::clamp(cam.pitch, -1.55f, 1.55f);

        const float cp = std::cos(cam.pitch), sp = std::sin(cam.pitch);
        const float cy = std::cos(cam.yaw),   sy = std::sin(cam.yaw);
        Vector<float, 3, 4> forward { cp * cy, sp, cp * sy };
        Vector<float, 3, 4> worldUp { 0.0f, 1.0f, 0.0f };
        Vector<float, 3, 4> right { forward.y*worldUp.z - forward.z*worldUp.y,
                                    forward.z*worldUp.x - forward.x*worldUp.z,
                                    forward.x*worldUp.y - forward.y*worldUp.x };
        const float rLen = std::sqrt(right.x*right.x + right.y*right.y + right.z*right.z);
        right.x /= rLen; right.y /= rLen; right.z /= rLen;
        Vector<float, 3, 4> up { right.y*forward.z - right.z*forward.y,
                                 right.z*forward.x - right.x*forward.z,
                                 right.x*forward.y - right.y*forward.x };

        const float dx = moveAct.vector2.x * kMoveSpeed * kDt;
        const float dy = moveAct.vector2.y * kMoveSpeed * kDt;
        cam.position.x += right.x*dx + forward.x*dy;
        cam.position.y += right.y*dx + forward.y*dy;
        cam.position.z += right.z*dx + forward.z*dy;

        CameraGPU& g = cameraBuf.value[0];
        g.origin[0]=cam.position.x; g.origin[1]=cam.position.y; g.origin[2]=cam.position.z; g.pad0=0;
        g.right[0]=right.x;   g.right[1]=right.y;   g.right[2]=right.z;
        g.up[0]=up.x;         g.up[1]=up.y;         g.up[2]=up.z;
        g.forward[0]=forward.x; g.forward[1]=forward.y; g.forward[2]=forward.z;
        g.aspect  = float(window.width) / float(window.height);
        g.tanHalf = std::tan(70.0f * 3.14159265f / 360.0f);
        g.pad1    = 0;
        cameraBuf.FlushDevice();

        if (++frames >= 60) {
            std::println("[RTMultiShadow] {} lights x {} pillars rendering", kLightCount, kPillars.size());
            frames = 0;
        }
    });

    window.Render();
    window.StartUpdate();
    window.StartSync();
    return 0;
}
#endif
