[solved] HLSL - Texture (s0)

Hi devs,
can’t figure out how to pass a Texture2D to a shader, read trough some materials but they are mostly obsolete, none of them worked for me (I might be doing something trivial in the wrong way). Trying to create a simple passtrough effect, using MonoGame 3.8 latest dev build, simple 2D stuff, DirectX. I’m able to get colors working in shader as:

float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    return float4(1, 0, 0, 1);
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_3 PixelShaderFunction();
    }
}

Tried to get my sampler as:

sampler MySampler : register(s0)

And obtaining color as float4 color = tex2D(s0, coords);

C# code:

sb.Begin(transformMatrix: m, effect: effect);
// tried effect.CurrentTechnique.Passes[0].Apply(); here as well
sb.Draw(sprite, position, FinalizeColor(DrawColor));
sb.End();

Image1 - Shader setting all pixels to a color (red here) is working fine

I have some experience with GLSL, totally new to HLSL if anyone could help me resolve this issue I would be grateful, sure this will help other passangers too.

If you’re using ps_4_0 then you probably should do this:

The repo has a number of approaches (I wanted to test those) for a number of compatibility levels.
Hope that helps a bit.
(haven’t updated that project in a while, sorry)

1 Like

I remember seeing this in the past as well with surprisingly little info in the forum.

I always wondered if it was related to this quirk, where shader variables are aggressively optimized in a way that can screw up integrated code, but I’m not sure if they’re related.

Resolved as suggested by Throbax:

Texture2D FirstTexture;

SamplerState FirstSampler
{
    Texture = <FirstTexture>;
	MinFilter = Linear;
	MagFilter = Linear;
	MipFilter = Linear;
	AddressU = Wrap;
	AddressV = Wrap;
};

float4 displace(float4 pos : SV_POSITION, float4 color : COLOR0, float2 texCoord : TEXCOORD0) : SV_TARGET0
{
	float4 c = FirstTexture.Sample(FirstSampler, texCoord);
	return c * color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_3 displace();
    }
}

Here is a example EDIT (a pair of examples) i made a while back, it may help.

1 Like