ConstantBuffer error

I just ran into the following issue; it took about an hour or two to work out a reasonable guess as to what was happening.

My shader code that caused the issue was (in part) as follows:

float4x4 InvWorld;
struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
};
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
	output.Position = input.Position;
	float4 screenPos = float4((input.TexCoord - .5) * float2(2, -2), 0, 1);
	output.TexCoord = mul(screenPos, InvWorld).xy * float2(.5, -.5) + .5;
	return output;
}

Upon passing in the InvWorld parameter via EffectPass.Apply(), it crashed and reported an array mismatch. Investigating the matter, I found that the matrix was trying to be stored into a 32 byte ConstantBuffer, although the correct storage should have been 64 bytes. Ultimately, I worked out that it’s because I’m only using two of the resulting coordinates of the matrix multiplication, but an XNA/Monogame Matrix inherently comes with 4x4 elements, all of which it is trying to store in the effect’s ConstantBuffer.

I was able to circumvent the issue by tricking it into storing all elements as follows:

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float4 TexCoord : TEXCOORD0;
};
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
	output.Position = input.Position;
	float4 screenPos = float4((input.TexCoord - .5) * float2(2, -2), 0, 1);
	output.TexCoord = mul(screenPos, InvWorld) * float4(.5, -.5, 1, 1) + .5;
	return output;
}

I then extracted just the two coordinates I needed in the pixel shader.

Possible fixes to this issue may include not optimizing out these fields, or checking the range of the array before copying paramater data to the buffers upon EffectPass.Apply().

Monogame ‘removes’ vars from the compiled shader when they are not used (many examples/questions on this forum) but i’ve never seen it removing parts of a matrix

Yeah, the last two rows are optimized out by the shader compiler :confused: This issue has been around forever. It’s logged on GitHub here: https://github.com/MonoGame/MonoGame/issues/911

Wooaaaa i’ll double check my code and matrices from now on