

#include "/Lib/UniformDeclare.glsl"
#include "/Lib/Utilities.glsl"


#if SR_ENABLE == 1
	const vec2 workGroupsRender = vec2(SR_RENDER_SCALE_FACTOR, SR_RENDER_SCALE_FACTOR);
#elif FSR2_SCALE >= 0
	#if FSR2_SCALE == 0
		const vec2 workGroupsRender = vec2(1.0, 1.0);
	#elif FSR2_SCALE == 1
		const vec2 workGroupsRender = vec2(0.6667, 0.6667);
	#elif FSR2_SCALE == 2
		const vec2 workGroupsRender = vec2(0.5882, 0.5882);
	#elif FSR2_SCALE == 3
		const vec2 workGroupsRender = vec2(0.5, 0.5);
	#elif FSR2_SCALE == 4
		const vec2 workGroupsRender = vec2(0.3333, 0.3333);
	#endif
#else
	const vec2 workGroupsRender = vec2(1.0, 1.0);
#endif
layout (local_size_x = 16, local_size_y = 8) in;


layout (rgba16) uniform image2D FBIMG_GSOLID_DATA;
layout (rgba16) uniform image2D FBIMG_GSOLID_NORMAL;
layout (rgba16) uniform image2D FBIMG_GTRANS_DATA;
layout (rgba16) uniform image2D FBIMG_GTRANS_NORMAL;
layout (r32f) uniform image2D img_depthtexS;

void main(){
	ivec2 drawTexel = ivec2(gl_GlobalInvocationID.xy);
	#ifdef SUPER_RESOLUTION
		if (any(greaterThanEqual(vec2(drawTexel), fsrScreenSize))) return;
	#endif

	float gtransDepth = texelFetch(depthtex0, drawTexel, 0).x;
	float solidDepth = gtransDepth;

	#ifdef LOD_RENDERING
		if (gtransDepth == 1.0) gtransDepth = texelFetch(LOD_DEPTH_TEX_0, drawTexel, 0).x;
	#endif

	if (gtransDepth < 1.0){
		vec4 gtransData = texelFetch(FBTEX_GTRANS_DATA, drawTexel, 0);

		vec2 gtransMaterialIDs = Unpack2xU8_ID_LOD_Y_from_U16(gtransData.z);
		bool copySolid = gtransMaterialIDs.x == MATID_SKY;

		float particleDepth = texelFetch(depthtexS, drawTexel, 0).x;
		copySolid = copySolid || (gtransMaterialIDs.x == MATID_PARTICLE && particleDepth > gtransDepth);

		#ifdef LOD_RENDERING
			vec4 gsolidData = texelFetch(FBTEX_GSOLID_DATA, drawTexel, 0);
			vec2 gsolidMaterialIDs = Unpack2xU8_ID_LOD_Y_from_U16(gsolidData.z);
			copySolid = copySolid || gtransMaterialIDs.y != 0.0 && gsolidMaterialIDs.y == 0.0 && gsolidMaterialIDs.x != MATID_SKY;
		#endif

		if (copySolid){
			#ifndef LOD_RENDERING
				vec4 gsolidData = texelFetch(FBTEX_GSOLID_DATA, drawTexel, 0);
			#endif
			imageStore(FBIMG_GTRANS_DATA, drawTexel, gsolidData);
			imageStore(FBIMG_GTRANS_NORMAL, drawTexel, texelFetch(FBTEX_GSOLID_NORMAL, drawTexel, 0));
		}else if (gtransMaterialIDs.x == MATID_SOLID_TRANS){
			imageStore(FBIMG_GSOLID_DATA, drawTexel, gtransData);
			imageStore(FBIMG_GSOLID_NORMAL, drawTexel, texelFetch(FBTEX_GTRANS_NORMAL, drawTexel, 0));
		}else{
			solidDepth = texelFetch(depthtex1, drawTexel, 0).x;
		}

		imageStore(img_depthtexS, drawTexel, vec4(solidDepth));
	}
}
