matrix multiplication with vector in glsl
Asked Answered
S

2

5

Ref http://webglfundamentals.org/webgl/lessons/webgl-3d-orthographic.html In vector shader there is multiplication of mat4 and vec4.

attribute vec4 a_position;

uniform mat4 u_matrix;

void main() {

  // Multiply the position by the matrix.

  gl_Position = u_matrix * a_position;

}

How is it possible to multiply 4*4 matrix with 1*4 matrix? Shouldn't it be gl_Position = a_position * u_matrix;

Can anybody explain this?

Soapberry answered 6/7, 2014 at 8:11 Comment(1)
I am confused because it is the reverse of the mathematical formalist. It's impossible to multiply by a vector line on the right side. So v*m seen more consistent with the algebraic convention, no ?Togo
H
15

From the GLSL spec 1.017

5.11 Vector and Matrix Operations

With a few exceptions, operations are component-wise. When an operator operates on a vector or matrix, it is operating independently on each component of the vector or matrix, in a component-wise fashion.

...matrix multiplied by vector, vector multiplied by matrix, and matrix multiplied by matrix. These do not operate component-wise, but rather perform the correct linear algebraic multiply. They require the size of the operands match.

vec3 v, u;
mat3 m;

u = v * m;

is equivalent to

u.x = dot(v, m[0]); // m[0] is the left column of m
u.y = dot(v, m[1]); // dot(a,b) is the inner (dot) product of a and b
u.z = dot(v, m[2]);

And

u = m * v;

is equivalent to

u.x = m[0].x * v.x + m[1].x * v.y + m[2].x * v.z;
u.y = m[0].y * v.x + m[1].y * v.y + m[2].y * v.z;
u.z = m[0].z * v.x + m[1].z * v.y + m[2].z * v.z;

or also

u = v.x * m[0] + v.y * m[1] + v.z * m[2];
Hali answered 6/7, 2014 at 9:34 Comment(0)
L
2

http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf https://en.wikibooks.org/wiki/GLSL_Programming/Vector_and_Matrix_Operations#Operators

Assume 3x3 matrix:

m_of_math = 
    m11, m12, m13
    m21, m22, m23
    m31, m32, m33

and vector is column vector:

v = [x
     y
     z]

glsl store matrix as column major, so init as:

mat3 m = mat3(m11, m21, m31, 
              m12, m22, m32,
              m13, m23, m33)

access as column:

m[0] = (m11, m21, m31)
       //first column of matrix
       //first row of stored memory

when do operations, forget the store order, for example:

m * v:

m * v => matrix of math * vector

v * m:

v * m => v^T * m = (M^T * v)^T
      => transpose of matrix of math * vector

m1 * m2:

m1 * m2 = matrix 1 of math * matrix 2 of math
Living answered 4/7, 2021 at 3:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.