/*
===========================================================================
Copyright (C) 2023-2024 Gian 'myT' Schellenbaum

This file is part of Challenge Quake 3 (CNQ3).

Challenge Quake 3 is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.

Challenge Quake 3 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Challenge Quake 3. If not, see <https://www.gnu.org/licenses/>.
===========================================================================
*/
// gather depth of field: near-field circle of confusion tile generation


#include "common.hlsli"
#include "gatherdof.hlsli"


cbuffer RootConstants : register(b0)
{
	uint inputTextureIndex;
	uint outputTextureIndex;
};

[numthreads(8, 8, 1)]
void cs(uint3 dtid : SV_DispatchThreadID, uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID)
{
	uint2 tcOut = dtid.xy;
	RWTexture2D<float> outputTexture = ResourceDescriptorHeap[outputTextureIndex];
	uint width, height;
	outputTexture.GetDimensions(width, height);
	if(any(dtid.xy >= uint2(width, height)))
	{
		return;
	}

	Texture2D<float> inputTexture = ResourceDescriptorHeap[inputTextureIndex];

	// This loop can read out of bounds in the inputTexture.
	// Each full-res pixel has a corresponding tile pixel, but the reverse isn't always true.
	// Texture.Load is specced to return 0 on OOB accesses.
	// Since we max() the values, zeroes have no effect on the final result.
	uint2 tcInCorner = tcOut * uint2(16, 16);
	float maxCoc = 0.0;
	for(uint y = 0; y < 16; y++)
	{
		for(uint x = 0; x < 16; x++)
		{
			uint2 tcIn = tcInCorner + uint2(x, y);
			float coc = inputTexture.Load(uint3(tcIn.x, tcIn.y, 0));
			maxCoc = max(maxCoc, coc);
		}
	}

	outputTexture[tcOut] = maxCoc;
}
