1

I'm trying to develop a deferred render on my own webGL engine. I have everything ready to calculate the lightning but I can't reconstruct the position from the depth buffer properly...

Right now, I'm trying to do the calculations out of the shader at the CPU with JS, and if I'm able to get the correct position then translate it to the shader. This is the JS code:

        var model = mat4.create();
        var view = mat4.create();
        var projection = mat4.perspective(mat4.create(), 45, gl.canvas.width/gl.canvas.height, 0.1, 100);

        var pos = [0,0,-1,1];
        var viewport = gl.getViewport();

        var modelview =         mat4.multiply(mat4.create(),    view,       model); 
        var viewprojection =    mat4.multiply(mat4.create(),    projection, view);
        var mvp =               mat4.multiply(mat4.create(),    projection, modelview); 

        var posScreenCoords =   vec4.transformMat4(vec4.create(),   pos,    mvp);
        var vec3unproj = vec3.create();
        vec3.unproject(vec3unproj, [posScreenCoords[0],posScreenCoords[1],posScreenCoords[2]], viewprojection, viewport);

I know there are some useless calculations, like multiplying model and view when they are at the identity, but I want them to be there just for showing the step by step.

At the identity, the camera is facing to the [0,0,-1] world coords, so when I transform this coords with the MVP matrix to get the screen coords, it should result a point at the center of the screen [0,0,Z], this is what I'm getting.

Everything OK at this point. Here is where I'm stuck. I have the same environment as if I am at the shader, I have an XY which are the screen coords, and a Z . I have to unproject this coords to the world coords. I'm using the gl-matrix library, but it hasn't the vec3.unproject and got it from external source, but I'm not getting the desired result [0,0,-1] from it:

var unprojectMat = mat4.create();
var unprojectVec = vec4.create();

vec3.unproject = function (out, vec, viewprojection, viewport) {

  var m = unprojectMat;
  var v = unprojectVec;

  v[0] = (vec[0] - viewport[0]) * 2.0 / viewport[2] - 1.0;
  v[1] = (vec[1] - viewport[1]) * 2.0 / viewport[3] - 1.0;
  v[2] = 2.0 * vec[2] - 1.0;
  v[3] = 1.0;

  if(!mat4.invert(m,viewprojection)) 
    return null;

  vec4.transformMat4(v, v, m);
  if(v[3] === 0.0) 
    return null;

  out[0] = v[0] / v[3];
  out[1] = v[1] / v[3];
  out[2] = v[2] / v[3];

  return out;
};

You can see the test here. Any ideas? Thanks

MaDowen
  • 115
  • 1
  • 1
  • 9

0 Answers0