#version 450
#pragma shader_stage(fragment)

#define FRAGMENT 1
#define MAX_TEXTURES textures.length()

layout (constant_id = 0) const uint TEXTURES = 1;

#include "../../common/macros.h"
#include "../../common/structs.h"

layout (binding = 6) uniform sampler2D samplerTextures[TEXTURES];
layout (std140, binding = 7) readonly buffer DrawCommands {
	DrawCommand drawCommands[];
};
layout (std140, binding = 8) readonly buffer Instances {
	Instance instances[];
};
layout (std140, binding = 9) readonly buffer InstanceAddresseses {
	InstanceAddresses addresses[];
};
layout (std140, binding = 10) readonly buffer Materials {
	Material materials[];
};
layout (std140, binding = 11) readonly buffer Textures {
	Texture textures[];
};
layout (std140, binding = 12) readonly buffer Lights {
	Light lights[];
};

#include "../../common/functions.h"

layout (location = 0) flat in uvec4 inId;
layout (location = 1) flat in vec4 inPOS0;
layout (location = 2) in vec4 inPOS1;
layout (location = 3) in vec3 inPosition;
layout (location = 4) in vec2 inUv;
layout (location = 5) in vec4 inColor;
layout (location = 6) in vec2 inSt;
layout (location = 7) in vec3 inNormal;
layout (location = 8) in vec3 inTangent;

void main() {
	const uint triangleID = uint(inId.x); // gl_PrimitiveID
	const uint drawID = uint(inId.y);
	const uint instanceID = uint(inId.z);
	
	const DrawCommand drawCommand = drawCommands[drawID];
	const Instance instance = instances[instanceID];
	const Material material = materials[instance.materialID];

	surface.uv.xy = wrap(inUv.xy);
	surface.uv.z = mipLevel(dFdx(inUv), dFdy(inUv));

	vec4 A = inColor * material.colorBase;	
	// sample albedo
	if ( validTextureIndex( material.indexAlbedo ) ) {
		A = sampleTexture( material.indexAlbedo );
	}
	// alpha mode OPAQUE
	if ( material.modeAlpha == 0 ) {
		A.a = 1;
	// alpha mode BLEND
	} else if ( material.modeAlpha == 1 ) {

	// alpha mode MASK
	} else if ( material.modeAlpha == 2 ) {
		if ( A.a < abs(material.factorAlphaCutoff) ) discard;
		A.a = 1;
	}
	if ( A.a < 1 ) discard;
}