Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenGL ES 2.0 for 2D, how to set origin to top-left

I think this has been discussed before, but I can't find an answer that works for me.

I'm developing a 2D "drawing" application for iPad with OpenGL ES 2.0.

I'm creating an Ortho Projection Matrix with a function described in the book "iPhone 3D Programming", and as far as I know that matrix is correct. The function call is something like this:

proj = identity.Ortho(-width/2, width/2, -height/2, height/2, -1.0f, 1.0f);

It works ok, but it's putting the origin in the center of the viewport. I'm gonna need to get touch information from the user to paint so I would like the origin to be at the top left corner.

I know I don't really need that, since I can just substract (width/2, height/2), but everything would be easier if the origin was at the TL.

So I tried this:

proj = identity.Ortho(0, width, 0, height, -1.0f, 1.0f);

But it doesn't work at all, if I draw a rectangle I just see some lines or triangles when I rotate the viewModel Matrix, it's like it getting distorted.

Thankyou.

like image 937
Odrakir Avatar asked Oct 20 '11 08:10

Odrakir


1 Answers

With identity.Ortho(0, width, 0, height, -1.0f, 1.0f) you were on the right track. But this will position the origin in the lower left corner (as it operates still in right-handed 3d space and not in screen space, so y goes up and x goes right). Instead, just swap top and bottom using

proj = identity.Ortho(0, width, height, 0, -1.0f, 1.0f);

But keep in mind, that since this mirrors the y-direction (like you want it), it will invert the orientation of any triangles you draw, turning counter-clockwise oriented triangles into clockwise ones. This is not really a problem, you just have to keep this in mind when you do things based on a triangle's orientation (e.g. back-face culling, two-sided materials, ...) and can be accounted for by using glFrontFace to switch the default front-side winding order. But since you want to do 2d, triangle orientation and back-face culling won't be that much of an issue for you, anyway.

like image 134
Christian Rau Avatar answered Nov 13 '22 10:11

Christian Rau