Can anyone tell me why my projection perspective matrix isn't working?

221 Views Asked by At

I'm a beginner in WebGL and graphics programming in general. I'm trying to render procedurally generated terrain. My first stab at this seemed to work and I get the following result.

enter image description here

I want to add perspective projection to this, but I end up just getting a screen with only my clear color (green in this case). The code below was used to implement the perspective matrix in javascript with glmatrix:

const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.0;
const zFar = 1.0;
const projectionMatrix = mat4.create();
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);

const projectionMatrixLoc = gl.getUniformLocation(program, "uProjectionMatrix");
gl.uniformMatrix4fv(projectionMatrixLoc, false, projectionMatrix);

and this is the corresponding code in my vertex shader:

attribute vec4 vPosition;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying float v_color;

void main(){
  gl_Position = uProjectionMatrix * uModelViewMatrix * vPosition;
  v_color = (vPosition.z + 1.0) / 2.0;

}

I have zFar at 1.0 because my maximum Z value is 1.0. I know that I can place the points at arbitrary coordinates as long as those coordinates are within the frustum, but I wanted to render this with points that would render even if I had trouble with the perspective matrix.

The entire project can be found in a Codesandbox repository if you're interested in seeing the full project (shaders are in the html file).

Any help is greatly appreciated!

1

There are 1 best solutions below

1
On

The perspective projection matrix defines a Viewing frustum. Therefore zNear must be greater than 0. 0 leads to an undefined behavior, because a division by zero occurs during the internal calculation of the projection matrix (0 < zNear < zFar). e.g.:

const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.001;                       
const zFar = 1.0;
const projectionMatrix = mat4.create();
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);