Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matrix multiplication with vector in glsl

Tags:

webgl

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?

like image 536
user2135533 Avatar asked Dec 11 '22 04:12

user2135533


2 Answers

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];
like image 139
gman Avatar answered Jan 18 '23 03:01

gman


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, m23,
              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
like image 31
lbsweek Avatar answered Jan 18 '23 03:01

lbsweek