unproject vec3 in gl-matrix library

i’m using gl-matrix for a webgl project and i was surprised to see that it has no unproject function. After searching i found this: https://github.com/toji/gl-matrix/issues/16

but it’s not up-to-date, so here’s my version:

vec3.unproject = function (vec, view, proj, viewport) {

var dest = vec3.create();//output
var m = mat4.create();//view * proj
var im = mat4.create();//inverse view proj
var v = vec4.create();//vector
var tv = vec4.create();//transformed vector

//apply viewport transform
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] = vec[2];
v[3] = 1.0;

//build and invert viewproj matrix
if(!mat4.invert(im,m)) { return null; }

if(v[3] === 0.0) { return null; }

dest[0] = tv[0] / tv[3];
dest[1] = tv[1] / tv[3];
dest[2] = tv[2] / tv[3];

return dest;

vec is a vec3 describing the screenspace x and y coordinates as well as the depth of the pixel. view and proj are mat4 that holds the view and projection matrices.viewport is a vec4 describing the dimensions of the viewport ( typically {0,0,viewport_width,viewport_height})


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s