Yaminichi's picture

Finding Top-Left of GameWindow

The title is exactly what it seems: I need to know how to find the top-left corner of the GameWindow given any aspect ratio, field of view, camera position, ect. The reason is that I want to implement a GUI in my game, and it seems impossible to find coordinates relative to screen size and camera location. If anyone can give me a formula, sample code, whatever you know: it would be greatly appreciated.


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
the Fiddler's picture

Can you describe the GUI you are trying to create? Is it a 2d overlay over the 3d scene or do you want it to be part of the 3d scene (i.e. have a depth, be affected by camera movement, etc)?

For a 2d overlay, the solution is pretty simple: render your scene as normal, then switch to an orthographic projection and render your GUI in 2d. This way, you can use the projection matrix to define the exact location of the top-left corner. For example:

// (top,left)-(bottom,right) = (0,0)-(width,height); +x goes right; +y goes down
var projection = Matrix4.CreateOrthographicOffCenter(0, Width, Height, 0, -1, 1);
// (top,left)-(bottom,right) = (-1,-1)-(+1,+1); +x goes right; +y goes up
var projection = Matrix4.CreateOrthographic(-1, 1, -1, 1, -1, 1);
// For OpenGL 1.x:
GL.LoadMatrix(ref project);
// For OpenGL 2.x+:
GL.UniformMatrix4(location, transpose, ref projection);
Yaminichi's picture

I am creating a 2D overlay on a 3D scene and it's not actually as simple as you would think. Firstly, Matrix4.CreateOrthographic takes 4 or 5 arguments: you have 6 for whatever reason. Secondly, using a modelview matrixmode, rendering, then switching to a projection matrixmode to render GUI stuff causes nothing to be displayed at all. Trust me, if it were simple, I would have figured it out considering I have an entire game, minus the GUI, programmed.

the Fiddler's picture

I have adapted the "Text Rendering" example to overlay a rudimentary GUI over a 3d scene. Take a look at the code here:


Take a look at the OnRenderFrame function (you can pretty much ignore the rest).

The CreateOrthographic mismatch is a typo. It should have been CreateOrthographicsOffCenter with 6 parameters or CreateOrthographic with 5 parameters. The difference between these two functions is that CreateOrthographic always places the origin (0,0) at the center of the viewport, whereas CreateOrthographicOffCenter can place the origin anywhere in the viewport.