float4x4 g_WorldMatrix : WorldMatrix;
float4x4 g_ViewMatrix : ViewMatrix;
float4x4 g_ProjectionMatrix : ProjectionMatrix;

texture g_StencilMask : StencilMask;
sampler2D g_StencilMaskSampler = 
sampler_state
{
    texture = g_StencilMask;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
    AddressU = WRAP;
    AddressV = WRAP;
};

texture g_Texture : Texture;
sampler2D g_StencilMaskSampler = 
sampler_state
{
    texture = g_StencilMask;
    MinFilter = LINEAR;
    MagFilter = LINEAR;
    AddressU = WRAP;
    AddressV = WRAP;
};

// Standard
struct StandardVSInput
{
    float3 Position : POSITION;
    float2 TextureCoordinates : TEXCOORD;
};

struct StandardVSOutput
{
    float4 Position : POSITION;
    float2 TextureCoordinates : TEXCOORD;
};

StandardVSOutput StandardVS(StandardVSInput Input)
{
    StandardVSOutput Output;

    float4x4 WorldViewProjectionMatrix = mul(mul(g_WorldMatrix, g_ViewMatrix), g_ProjectionMatrix);
    Output.Position = mul(float4(Input.Position, 1.0f), WorldViewProjectionMatrix);
    Output.TextureCoordinates = Input.TextureCoordinates;

    return Output;
}

struct StandardPSInput
{
    float2 TextureCoordinates : TEXCOORD;
};

struct StandardPSOutput
{
    float4 Color : COLOR;
};

StandardPSOutput StencilTextureWritePS(StandardPSInput Input) 
{
    StandardPSOutput Output;

	float4 StencilMask = tex2D(g_StencilMaskSampler, Input.TextureCoordinates);
	
	if(StencilMask.rgb == 0.0f)
	{
		discard;
	}
	else
	{
		Output.Color = StencilMask;
	}
	
    return Output;
}

technique StencilTextureWrite
{
    pass P0
    {
		ColorWriteEnable = FALSE;
		
		DepthTestEnable = FALSE;
		
		StencilEnable = TRUE;
		StencilFunc = ALWAYS;
		StencilRef = 1;
		StencilMask = 0xffffffff;
		StencilWriteMask = 0xffffffff;
		StencilPass = REPLACE;

        VertexShader = compile vs_2_0 StandardVS();
        PixelShader  = compile ps_2_0 StencilTextureWritePS();
    }
}

StandardPSOutput StencilMaskPS(StandardPSInput Input) 
{
    StandardPSOutput Output;

	float4 StencilMask = tex2D(g_StencilMaskSampler, Input.TextureCoordinates);
	
    return Output;
}

technique StencilMask
{
    pass P0
    {
		ColorWriteEnable = RED | GREEN | BLUE | ALPHA;
				
		StencilEnable = TRUE;
		StencilRef = 1;
		StencilFunc = GREATER;
		StencilMask = 0xffffffff;
		StencilWriteMask = 0x00000000;
		StencilZFail = KEEP;
		StencilFail = KEEP;
		StencilPass = KEEP;

        VertexShader = compile vs_2_0 StandardVS();
        PixelShader  = compile ps_2_0 StencilMaskPS();
    }
}