//#pragma enable_d3d11_debug_symbols

#pragma kernel BlendScenarios

#pragma multi_compile _ PROBE_VOLUMES_L2
#pragma multi_compile _ USE_APV_PROBE_OCCLUSION

#include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBlendStates.hlsl"

Texture3D<float4> _State0_L0_L1Rx;
Texture3D<float4> _State0_L1G_L1Ry;
Texture3D<float4> _State0_L1B_L1Rz;

Texture3D<float4> _State1_L0_L1Rx;
Texture3D<float4> _State1_L1G_L1Ry;
Texture3D<float4> _State1_L1B_L1Rz;

RWTexture3D<half4> _Out_L0_L1Rx;
RWTexture3D<unorm float4> _Out_L1G_L1Ry;
RWTexture3D<unorm float4> _Out_L1B_L1Rz;

#ifdef PROBE_VOLUMES_L2
Texture3D<float4> _State0_L2_0;
Texture3D<float4> _State0_L2_1;
Texture3D<float4> _State0_L2_2;
Texture3D<float4> _State0_L2_3;

Texture3D<float4> _State1_L2_0;
Texture3D<float4> _State1_L2_1;
Texture3D<float4> _State1_L2_2;
Texture3D<float4> _State1_L2_3;

RWTexture3D<unorm float4> _Out_L2_0;
RWTexture3D<unorm float4> _Out_L2_1;
RWTexture3D<unorm float4> _Out_L2_2;
RWTexture3D<unorm float4> _Out_L2_3;
#endif

#ifdef USE_APV_PROBE_OCCLUSION
Texture3D<float4> _State0_ProbeOcclusion;
Texture3D<float4> _State1_ProbeOcclusion;
RWTexture3D<unorm float4> _Out_ProbeOcclusion;
#endif

float4 _ChunkList[1000];

float4 _PoolDim_LerpFactor;
#define _DstPoolDim _PoolDim_LerpFactor.xy
#define _LerpFactor _PoolDim_LerpFactor.z

uint3 IndexToChunk(uint index, float2 poolSize)
{
    uint coordZ = index / (poolSize.x*poolSize.y);
    uint offsetXY = index - coordZ * (poolSize.x*poolSize.y);
    return uint3(offsetXY % poolSize.x, offsetXY / poolSize.x, coordZ);
}

[numthreads(4, 4, 4)]
void BlendScenarios(uint3 probe : SV_DispatchThreadID, uint3 brick : SV_GroupID)
{
    uint chunkIndex = brick.z;
    probe.z -= 4 * chunkIndex;

    // Load
    APVResources resources0, resources1;
    LOAD_APV_RES(resources0, _State0);
    LOAD_APV_RES(resources1, _State1);

    uint3 srcChunk = _ChunkList[chunkIndex].xyz;
    APVSample state0 = LoadAndDecodeAPV(resources0, probe + srcChunk);
    APVSample state1 = LoadAndDecodeAPV(resources1, probe + srcChunk);

    // Blend
    state0 = BlendAPVSamples(state0, state1, half(_LerpFactor));

    // Store
    APVResourcesRW output;
    LOAD_APV_RES(output, _Out);

    uint3 dstChunk = IndexToChunk(_ChunkList[chunkIndex].w, _DstPoolDim);
    EncodeAndStoreAPV(output, state0, probe + dstChunk);
}