gregtatum / mdn-webgl

Helper functions for Mozilla Developer Network WebGL documentation
MIT License
32 stars 7 forks source link

Model View Projection #6

Open gregtatum opened 9 years ago

gregtatum commented 9 years ago

@nickdesaulniers

So I'm trying to write this demo to explain clip space in WebGL, and I'm wondering if my understanding is wrong. I draw 3 boxes, a red, green, and blue one. For the Z coordinates of the 2d boxes I have the red one at 0, the green is at 0.5, and the blue is at 1.5. My thought would be that the green covers the red box, and the blue gets clipped. What happens is the opposite regardless of draw order, the red covers the green box. If I set the green to -0.5 then it is in front of the red box. I have gl.enable(gl.DEPTH_TEST) set.

I feel like every time I work with 3d space in WebGL positive Z heads towards the viewer. I'm a little confused as this is the opposite.

https://jsfiddle.net/tatumcreative/dzhL4zjg/

gregtatum commented 9 years ago

Frustum example

I guess the camera frustum flips it around.

gregtatum commented 9 years ago

Yup, got it figured out. Playing around with a perspective matrix makes it clear.

var near = 5
var far = 10
var cam = mat4.perspective([], 2, 1, near, far)

// A point at the near plane of the camera
vec4.transformMat4([], [0,0,-5,1], cam)
> [0, 0, -5, 5]
// Divide by W gets you -1 as the Z component

// A point at the far plane of the camera
vec4.transformMat4([], [0,0,-10,1], cam)
> [0, 0, 10, 10]
// Divide by W gets you 1 as the Z component
nickdesaulniers commented 9 years ago

in webgl, negative Z is out of the page, positive Z is into the page. some linear algebra libs like gl-matrix will flip this when doing a transform based on projection (orthographic or perspective). The book I had read on webgl was wrong, and our WebGL implementer pointed this out to me. This slide is wrong.

gregtatum commented 9 years ago

Cool, I put this graphic together last night

Writing this stuff up is really solidifying my understanding how this all works together.

nickdesaulniers commented 9 years ago

cool! what program did you use to create that?

gregtatum commented 9 years ago

Adobe Illustrator. They have a 3d extrude function for the basic box shape, then I just eyeballed the rest of it.

gregtatum commented 9 years ago

https://github.com/TatumCreative/mdn-model-view-projection/blob/master/lessons/02-homogeneous-coordinates/script.js

My first pass at explaining homogeneous coordinates in relation to clipspace.

gregtatum commented 9 years ago

https://github.com/TatumCreative/mdn-model-view-projection/tree/master/lessons/03-model-transform

Model transforms.

gregtatum commented 9 years ago

https://github.com/TatumCreative/mdn-model-view-projection

First pass done, still some work to do on it all.