GLSL反转矩阵inverse

低版本 vertex shader 可以使用,通常用来反转TBN矩阵,但是计算量很大。

代码来自 OpenGL Mathematics (GLM)

mat4 inverse_mat4(mat4 m)
{
float Coef00 = m[][] * m[][] - m[][] * m[][];
float Coef02 = m[][] * m[][] - m[][] * m[][];
float Coef03 = m[][] * m[][] - m[][] * m[][]; float Coef04 = m[][] * m[][] - m[][] * m[][];
float Coef06 = m[][] * m[][] - m[][] * m[][];
float Coef07 = m[][] * m[][] - m[][] * m[][]; float Coef08 = m[][] * m[][] - m[][] * m[][];
float Coef10 = m[][] * m[][] - m[][] * m[][];
float Coef11 = m[][] * m[][] - m[][] * m[][]; float Coef12 = m[][] * m[][] - m[][] * m[][];
float Coef14 = m[][] * m[][] - m[][] * m[][];
float Coef15 = m[][] * m[][] - m[][] * m[][]; float Coef16 = m[][] * m[][] - m[][] * m[][];
float Coef18 = m[][] * m[][] - m[][] * m[][];
float Coef19 = m[][] * m[][] - m[][] * m[][]; float Coef20 = m[][] * m[][] - m[][] * m[][];
float Coef22 = m[][] * m[][] - m[][] * m[][];
float Coef23 = m[][] * m[][] - m[][] * m[][]; const vec4 SignA = vec4( 1.0, -1.0, 1.0, -1.0);
const vec4 SignB = vec4(-1.0, 1.0, -1.0, 1.0); vec4 Fac0 = vec4(Coef00, Coef00, Coef02, Coef03);
vec4 Fac1 = vec4(Coef04, Coef04, Coef06, Coef07);
vec4 Fac2 = vec4(Coef08, Coef08, Coef10, Coef11);
vec4 Fac3 = vec4(Coef12, Coef12, Coef14, Coef15);
vec4 Fac4 = vec4(Coef16, Coef16, Coef18, Coef19);
vec4 Fac5 = vec4(Coef20, Coef20, Coef22, Coef23); vec4 Vec0 = vec4(m[][], m[][], m[][], m[][]);
vec4 Vec1 = vec4(m[][], m[][], m[][], m[][]);
vec4 Vec2 = vec4(m[][], m[][], m[][], m[][]);
vec4 Vec3 = vec4(m[][], m[][], m[][], m[][]); vec4 Inv0 = SignA * (Vec1 * Fac0 - Vec2 * Fac1 + Vec3 * Fac2);
vec4 Inv1 = SignB * (Vec0 * Fac0 - Vec2 * Fac3 + Vec3 * Fac4);
vec4 Inv2 = SignA * (Vec0 * Fac1 - Vec1 * Fac3 + Vec3 * Fac5);
vec4 Inv3 = SignB * (Vec0 * Fac2 - Vec1 * Fac4 + Vec2 * Fac5); mat4 Inverse = mat4(Inv0, Inv1, Inv2, Inv3); vec4 Row0 = vec4(Inverse[][], Inverse[][], Inverse[][], Inverse[][]); float Determinant = dot(m[], Row0); Inverse /= Determinant; return Inverse;
}
mat3 inverse_mat3(mat3 m)
{
float Determinant =
m[][] * (m[][] * m[][] - m[][] * m[][])
- m[][] * (m[][] * m[][] - m[][] * m[][])
+ m[][] * (m[][] * m[][] - m[][] * m[][]); mat3 Inverse;
Inverse[][] = + (m[][] * m[][] - m[][] * m[][]);
Inverse[][] = - (m[][] * m[][] - m[][] * m[][]);
Inverse[][] = + (m[][] * m[][] - m[][] * m[][]);
Inverse[][] = - (m[][] * m[][] - m[][] * m[][]);
Inverse[][] = + (m[][] * m[][] - m[][] * m[][]);
Inverse[][] = - (m[][] * m[][] - m[][] * m[][]);
Inverse[][] = + (m[][] * m[][] - m[][] * m[][]);
Inverse[][] = - (m[][] * m[][] - m[][] * m[][]);
Inverse[][] = + (m[][] * m[][] - m[][] * m[][]);
Inverse /= Determinant; return Inverse;
}
上一篇:数据库版本管理工具Flyway(4.0.3)---工作机制(译文)


下一篇:day39-异常处理