# Thread: Code for inverting a mat4

1. ## Code for inverting a mat4

In my shader i need an inverted matrix (4*4).
I had hoped that there was a built in function for inverting a matrix, but in all threads I found on this topic was said, that you have to write you're own.
Wouldn't it be nice, if some Guru could post his or her code for this task (in GLSL of course) because i guess many people have a problem with this, including me, and people need this quite often i think. I need it for doing shadow mapping, and im finnished with it exept with this function, this is so weird...
So can someone do that pleeeeaaaase?
(or maybe it is already there and i havn't found it, could you please give me a link in this case?)
Thanks a lot,
spl@t

2. ## Re: Code for inverting a mat4

In CG you rarely need to compute the inverse of an arbitrary 4x4 matrix. It is more likely that your 4x4 matrix was constructed by concatenating a number of transformation matrices alá M = Rx(a) * T(x,y,z), where Rx is a rotation matrix about the x-axis (say) and T is a translation matrix.

Computing M^{-1} is done by concatenating the inverses in the reverse order: M^{-1} = (Rx(a) * T(x,y,z))^{-1} = T(x,y,z)^{-1} * Rx(a)^{-1}.

Now all you need is to do is compute the inverses for each T, Rx, Ry, Rz etc, which is easy. E.g. T(x,y,z)^{-1} = T(-x,-y,-z)..

It has been a while since I did shadow mapping. However, I doubt the matrices changer per vertex, so computing them in the vertex shader is *not* a good idea..

3. ## Re: Code for inverting a mat4

Computing the inverse matrix in a shader is (quite) impossible, because it is not a trivial task. For a 4x4 matrix you need to calculate a few determinants, which is not that much work (for a CPU), but for a (vertex-) shader, this is very very much work, and it is done at every vertex, which is simply wasted power.

To compute your own inverse matrix, take a look at the matrix FAQ (http://skal.planet-d.net/demo/matrixfaq.htm#Q21), which explains how to do that. It is really easy to program.

Jan.

4. ## Re: Code for inverting a mat4

Thanks, what you said makes sense, and I tried both the easy but circumstantial way with reversing he transformations / rotations etc. and inverting the matrix with maths (i found a library which does that for me )
and i get the same result in both possibilities:
One side of the Utah-Teapot (which looks to the light) is in shadow, and the other side is lighten, and the worst is, that this doesen't change relativ to the teapot if it's rotating, so it's like this wrong shadow was painted on the teapot...
Seems like there are some other mistakes in my code

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•