/*
===========================================================================
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: field split and CoC generation


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


cbuffer RootConstants : register(b0)
{
	uint depthTextureIndex;
	uint colorTextureIndex;
	uint nearColorTextureIndex;
	uint farColorTextureIndex;
	uint nearCocTextureIndex;
	uint farCocTextureIndex;
	float linearDepthA;
	float linearDepthB;
	float focusNearMin;
	float focusNearMax;
	float focusFarMin;
	float focusFarMax;
	float brightnessScale;
};

[numthreads(8, 8, 1)]
void cs(uint3 dtid : SV_DispatchThreadID)
{
	uint2 tc = dtid.xy;
	Texture2D colorTexture = ResourceDescriptorHeap[colorTextureIndex];
	uint width, height, levels;
	colorTexture.GetDimensions(0, width, height, levels);
	if(any(dtid.xy >= uint2(width, height)))
	{
		return;
	}

	Texture2D<float> depthTexture = ResourceDescriptorHeap[depthTextureIndex];
	RWTexture2D<float4> nearColorTexture = ResourceDescriptorHeap[nearColorTextureIndex];
	RWTexture2D<float4> farColorTexture = ResourceDescriptorHeap[farColorTextureIndex];
	RWTexture2D<float> nearCocTexture = ResourceDescriptorHeap[nearCocTextureIndex];
	RWTexture2D<float> farCocTexture = ResourceDescriptorHeap[farCocTextureIndex];

	float4 color = colorTexture[tc];
	float depthZW = depthTexture[tc];
	float depth = LinearDepth(depthZW, linearDepthA, linearDepthB);
	float coc = CircleOfConfusion(depth, focusNearMin, focusNearMax, focusFarMin, focusFarMax);
	float nearCoc = max(-coc, 0.0);
	float farCoc = max(coc, 0.0);
	float brightnessWeight = 1.0 + brightnessScale * Brightness(color.rgb);
	float farWeight = farCoc * brightnessWeight;
	float4 nearColor = float4(color.rgb, nearCoc);
	float4 farColor = float4(color.rgb * farWeight, farWeight);

	nearColorTexture[tc] = nearColor;
	farColorTexture[tc] = farColor;
	nearCocTexture[tc] = nearCoc;
	farCocTexture[tc] = farCoc;
}
