Search code examples
matrixdirectx-11matrix-multiplicationhlslsharpdx

Matrix multiplication does not work in my vertex shader


Currently, I am calculating the World View Projection Matrix in my application instead of the GPU. I want to move this calculation to the GPU, but I am currently unable to do so.

Case 1 (see below) works very well, but case 2 doesn't and I have no idea what I've done wrong.

In my camera class, I calculate the View and the Projection matrices like this:

ViewMatrix = SharpDX.Matrix.LookAtLH(_cameraPosition, _lookAtPosition, SharpDX.Vector3.UnitY);
ProjectionMatrix = SharpDX.Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, renderForm.ClientSize.Width / (float)renderForm.ClientSize.Height, 0.1f, 500.0f);

Then, I calculate the World matrix for each of my models during the render process:

SharpDX.Matrix worldMatrix = SharpDX.Matrix.Translation(_position);

Case 1: Calculation of matrix in my application

When rendering a model, I calculate the World View Projection Matrix like this:

SharpDX.Matrix matrix = SharpDX.Matrix.Multiply(worldMatrix, camera.ViewMatrix);
matrix = SharpDX.Matrix.Multiply(matrix, camera.ProjectionMatrix);

matrix.Transpose();

And in my vertex shader, I calculate the final position of my vertices by calling:

output.pos = mul(input.pos, WVP);

And everything works fine!

Case 2: Calculation of matrix in HLSL

Instead of calculating anything in my application, I just write the three matrices World, View and Projection into my vertex shader's constant buffer and calculate everything in HLSL:

matrix mat = mul(World, View);
mat = mul(mat, Projection);

mat = transpose(mat);

output.pos = mul(input.pos, mat);

It does work. I don't see anything in my scene. So I assume some calculations were wrong. I checked my code several times.

Either, I am blind or stupid. What did I do wrong?


Solution

  • I used several days to experiment with the HLSL shaders and with my render functions. It turned out, that I transposed one matrix which I shouldn't have done. As a result, my whole scene was messed up. It was not much fun to debug, but it works now! :-)