$
\begin{bmatrix}
x’ \\
y’ \\
z’
\end{bmatrix}
= $$
\begin{bmatrix}
a & b & c \\
d & e & f \\
g & h & i
\end{bmatrix}
$ * $
\begin{bmatrix}
x \\
y \\
z
\end{bmatrix}$
结果:
$ \begin{cases} x’ = ax + by + cz \\ y’ = dx + ey + fz \\ z’ = gx + hy + iz \end{cases} $
var u_xformMatrix = gl.getUniformLocation(gl.program, 'u_xformMatrix'); // 赋值 gl.uniformMatrix4fv(u_xformMatrix, false, xformMatrix);
三、变换矩阵:平移
对比一般平移计算公式:
$x’ = ax+by+cz$
$x’ = x + Tx$ (一般方法)
分析:这里的Tx是一个常量,但是第一个等式中没有常量,意味着3X3的矩阵无法表示平移,所有这里使用4X4矩阵,以及具有第4个分量的矢量(通常设为1.0),也就是说,假设要进行平移的点p(x, y, z, 1),平移后坐标为p'(x', y', z', 1),如下等式:
$
\begin{bmatrix}
x’ \\
y’ \\
z’ \\
1
\end{bmatrix}
= $$
\begin{bmatrix}
a & b & c & d \\
e & f & g & h \\
i & j & k & l \\
m & n & o & p
\end{bmatrix}
$ * $
\begin{bmatrix}
x \\
y \\
z \\
1
\end{bmatrix}$
结果如下:
$ \begin{cases} x’ = ax + by + cz + d \\ y’ = ex + fy + gz + h \\ z’ = ix + jy + kz + l \\ 1 = mx + ny + oz + p \end{cases} $
根据式子$1 = mx + ny + oz + p$,计算出$m=0,n=0,o=0,p=1$,其中d、h、lp均为常数,比较等式:
$ \begin{cases} x’ = x + Tx \\ y’ = y + Ty \\ z’ = z + Tz \end{cases} $
var a_Position = gl.getAttribLocation(gl.program, 'a_Position'); if(a_Position < 0){ console.log("Failed to get the storage location of a_Position"); return -1; }
var VSHADER_SOURCE = //x' = x cos b - y sin b //y' = x sin b + y cosb //z' = z 'attribute vec4 a_Position;\n' + 'uniform mat4 u_xformMatrix;\n' + 'void main() {\n' + 'gl_Position = u_xformMatrix * a_Position;\n' + '}\n';
var canvas = document.getElementById("webgl"); if(!canvas){ console.log("Failed to retrieve the <canvas> element"); return; }
var gl = getWebGLContext(canvas); if(!gl){ console.log("Failed to get the rendering context for WebGL"); return; }
if(!initShaders(gl,VSHADER_SOURCE,FSHADER_SOURCE)){ console.log("Failed to initialize shaders."); return; }
//设置顶点位置 var n = initVertexBuffers(gl); if (n < 0) { console.log('Failed to set the positions of the vertices'); return; } // 角度转弧度制 var radian = Math.PI * ANGLE / 180.0; var cosB = Math.cos(radian); var sinB = Math.sin(radian);
var VSHADER_SOURCE = //x' = x cos b - y sin b //y' = x sin b + y cosb //z' = z 'attribute vec4 a_Position;\n' + 'uniform mat4 u_xformMatrix;\n' + 'void main() {\n' + 'gl_Position = u_xformMatrix * a_Position;\n' + '}\n';
// 变换矩阵缩放 var VSHADER_SOURCE = //x' = x cos b - y sin b //y' = x sin b + y cosb //z' = z 'attribute vec4 a_Position;\n' + 'uniform mat4 u_xformMatrix;\n' + 'void main() {\n' + 'gl_Position = u_xformMatrix * a_Position;\n' + '}\n';
var u_xformMatrix = gl.getUniformLocation(gl.program, 'u_xformMatrix'); if(u_xformMatrix < 0){ console.log("Failed to get the storage location of u_xformMatrix"); return; }