/*
===========================================================================
Copyright (C) 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/>.
===========================================================================
*/
// Quake 3 blend equations


#if !defined(DISABLE_PRAGMA_ONCE)
#pragma once
#endif


float4 BlendSource(float4 src, float4 dst, uint stateBits)
{
	if(stateBits == GLS_SRCBLEND_ZERO)
		return float4(0.0, 0.0, 0.0, 0.0);
	else if(stateBits == GLS_SRCBLEND_ONE)
		return src;
	else if(stateBits == GLS_SRCBLEND_DST_COLOR)
		return src * dst;
	else if(stateBits == GLS_SRCBLEND_ONE_MINUS_DST_COLOR)
		return src * (float4(1.0, 1.0, 1.0, 1.0) - dst);
	else if(stateBits == GLS_SRCBLEND_SRC_ALPHA)
		return src * float4(src.a, src.a, src.a, 1.0);
	else if(stateBits == GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA)
		return src * float4(1.0 - src.a, 1.0 - src.a, 1.0 - src.a, 1.0);
	else if(stateBits == GLS_SRCBLEND_DST_ALPHA)
		return src * float4(dst.a, dst.a, dst.a, 1.0);
	else if(stateBits == GLS_SRCBLEND_ONE_MINUS_DST_ALPHA)
		return src * float4(1.0 - dst.a, 1.0 - dst.a, 1.0 - dst.a, 1.0);
	else if(stateBits == GLS_SRCBLEND_ALPHA_SATURATE)
		return src * float4(src.a, src.a, src.a, 1.0);
	else
		return src;
}

float4 BlendDest(float4 src, float4 dst, uint stateBits)
{
	if(stateBits == GLS_DSTBLEND_ZERO)
		return float4(0.0, 0.0, 0.0, 0.0);
	else if(stateBits == GLS_DSTBLEND_ONE)
		return dst;
	else if(stateBits == GLS_DSTBLEND_SRC_COLOR)
		return dst * src;
	else if(stateBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR)
		return dst * float4(1.0 - src.r, 1.0 - src.g, 1.0 - src.b, 1.0 - src.a);
	else if(stateBits == GLS_DSTBLEND_SRC_ALPHA)
		return dst * float4(src.a, src.a, src.a, 1.0);
	else if(stateBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA)
		return dst * float4(1.0 - src.a, 1.0 - src.a, 1.0 - src.a, 0.0);
	else if(stateBits == GLS_DSTBLEND_DST_ALPHA)
		return dst * float4(dst.a, dst.a, dst.a, 1.0);
	else if(stateBits == GLS_DSTBLEND_ONE_MINUS_DST_ALPHA)
		return dst * float4(1.0 - dst.a, 1.0 - dst.a, 1.0 - dst.a, 1.0);
	else
		return float4(0.0, 0.0, 0.0, 0.0);
}

float4 Blend(float4 src, float4 dst, uint stateBits)
{
	float4 srcOut = BlendSource(src, dst, stateBits & GLS_SRCBLEND_BITS);
	float4 dstOut = BlendDest(src, dst, stateBits & GLS_DSTBLEND_BITS);

	return srcOut + dstOut;
}
