Jump to content
  • Advertisement
Sign in to follow this  
detlion1643

OpenGL matrix/coordinates?

This topic is 1510 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

To preface, I am using OpenTK and C#. However, I don't think that deters the issue from being something simple to how I am calling OpenGL methods. I don't understand some of the setup stuff, it's mostly pieced together code from other examples until I found something that worked somewhat.

 

Here is my routine for setting up OpenGL:

public bool Initialize(IntPtr Handle, Size ScreenSize)
        {
            //stuff to set in case of GDI
            handle = Handle;
            screensize = ScreenSize;
            bmp = new System.Drawing.Bitmap (screensize.Width, screensize.Height);

            //setup the initial scales
            if ((screensize.Width != 1000) && (screensize.Height != 600))
            {
                scalewidth = 1000 / screensize.Width;
                scaleheight = 600 / screensize.Height;
            }

            if (OpenTK.Configuration.RunningOnAndroid) 
            {
                //
                return true;
            } 
            else 
            {
                //video card name
                glRenderer = GL.GetString (StringName.Renderer);
                //what version of OpenGL do we have?
                glVersionStr = GL.GetString (StringName.Version);
                if (glVersionStr.Length < 3)
                    return false;

                glVersion = new Version (int.Parse (GLVersionStr [0].ToString ()), int.Parse (GLVersionStr [2].ToString ()));
                //glVersion = new Version (int.Parse (glVersionStr [0].ToString()), int.Parse (glVersionStr [2]).ToString());
                // Set viewport
                if (GLFunctions.Viewport (glVersion))
                    GL.Viewport (0, 0, screensize.Width, screensize.Height);
                else
                    return false; //can't use a viewport, default to GDI

                //we now have successfull OpenGL window/context we can use
                // Set rendering options
                GL.MatrixMode (MatrixMode.Projection);

                    GL.Enable (EnableCap.LineSmooth);
                    GL.Enable (EnableCap.PointSmooth);

                    GL.Hint (HintTarget.LineSmoothHint, HintMode.Nicest);
                    GL.Hint (HintTarget.PointSmoothHint, HintMode.Nicest);
                    GL.Hint (HintTarget.PolygonSmoothHint, HintMode.Nicest);
                    GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

                // Shading
                    GL.ShadeModel(ShadingModel.Smooth);

                // 3D options
                GL.CullFace(CullFaceMode.Front);
                GL.Enable(EnableCap.Multisample);
                GL.Enable(EnableCap.CullFace);

                // Enable blending
                GL.Enable(EnableCap.Blend);
                GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
 
                //without the next two lines we can't see anything
                ProjectionSet(Vector3d.Zero);
                ModelView_Set(Vector3d.Zero, Vector3d.Zero, Vector3d.Zero, 0, true);

                return true;
            }
        }

        private void ProjectionSet(Vector3d renderLocation)
        {
            // Create a perspective frustrum
            Matrix4d projection = Matrix4d.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(45), 1000.0 / 600.0, 1.0, 2000.0);

            if (renderLocation != Vector3d.Zero)
            {
                // Move zero point for rendering to upper left corner
                projection *= Matrix4d.CreateTranslation(-1, 1, 0);

                // Translate rendering point to the specified location
                projection *= Matrix4d.CreateTranslation(_3D_ProjectionSpace_NormalizeVector(new Vector3d(renderLocation.X, renderLocation.Y, 0)));
            }

            // Load matrix
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadIdentity();
            GL.LoadMatrix(ref projection);
        }
        
        public void ModelView_Set(Vector3d cameraLocation, Vector3d cameraRotation, Vector3d cameraOffset, double zoom, bool activateMatrix)
        {
            // Rotate world to get the correct axes in 3D (X going right, Y going down)
            modelview = Matrix4d.CreateRotationZ(MathHelper.DegreesToRadians(180));

            // Rotate camera
            modelview *= Matrix4d.CreateRotationX(MathHelper.DegreesToRadians(cameraRotation.X));
            modelview *= Matrix4d.CreateRotationY(MathHelper.DegreesToRadians(cameraRotation.Y));
            modelview *= Matrix4d.CreateRotationZ(MathHelper.DegreesToRadians(cameraRotation.Z));

            // Offset camera
            modelview *= Matrix4d.CreateTranslation(cameraOffset);

            // Zoom 
            if (zoom != 0)
                modelview *= Matrix4d.Scale(zoom);

            // Set camera with fixed zoom to make the 1000x600 frame match the 1000x600 pixels
            modelview *= Matrix4d.LookAt(new Vector3d(-cameraLocation.X, -cameraLocation.Y, cameraLocation.Z + (-724)), Vector3d.UnitZ, Vector3d.UnitY);

            // Load matrix
            if (activateMatrix)
                ModelView_Activate();
        }

        /// <summary>
        /// Activates the model view
        /// </summary>
        public void ModelView_Activate()
        {
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();
            GL.LoadMatrix(ref modelview);
        }

Now, I create a bitmap with the text to be drawn to the screen. Then I create a texture and bind it OpenGL. I then go to display that texture which semi works:

private void DrawImage(Image image, int X, int Y, int Z, int Width, int Height)
        {

            GL.Enable(EnableCap.Texture2D);
            if (image.GenerateTexture)
            {
                if (!LoadTexture (image))
                {
                    GL.Disable (EnableCap.Texture2D);
                    return;
                }
            }

            // Save current matrix
            //GL.PushMatrix();
                      
            //forget the values I passed and use hardcoded for testing
            GL.Color4(1F, 1F, 1F, 1F);
            GL.BindTexture (TextureTarget.Texture2D, image.Texture);
            GL.Begin(PrimitiveType.Quads);
            GL.TexCoord2(0.0f, 0.0f); 
            GL.Vertex3(0, 0, 0); //TOP-LEFT
            GL.TexCoord2(1.0f, 0.0f); 
            GL.Vertex3(1000, 0, 0); //TOP-RIGHT
            GL.TexCoord2(1.0f, 1.0f); 
            GL.Vertex3(1000, 300, 0); //BOTTOM-RIGHT
            GL.TexCoord2(0.0f, 1.0f); 
            GL.Vertex3(0, 300, 0); //BOTTOM-LEFT
            GL.End();

            // Restore matrix
            //GL.PopMatrix();

        }

As you can see, the GL.Vertex3 calls are outside the range of -1 to 1. For some reason this is how I can display the texture. However it shows up in the bottom right quadrant of the screen. Changing the Vertex3's x axis to anything negative (thinking -1 would be left of screen/view) completely hides the texture. Subtle trials like -0.1 don't change the location either.

 

This should be at Top left, 1000 wide, 300 down. I can't seem to figure this out...

[attachment=23844:opengl.png]

Share this post


Link to post
Share on other sites
Advertisement


I don't understand some of the setup stuff, it's mostly pieced together code from other examples until I found something that worked somewhat.

Stop here, delete your project, look for tutorials and start over again. This time concentrate on understanding the stuff you are using and why it does/doesn't works this way. tongue.png

 

It is the most safe and eventually quickest way to get into something new. Building your project on something which magically works sometimes, without knowing why it works at all huh.png .. will often end at the point , where you can't figure out a show-stopper (a bug, which ruins your whole project).

 

My first really big project ended this way, it was a pretty cool learning experience, still it hurts a lot if you consider the progress made sad.png .

Share this post


Link to post
Share on other sites

I went ahead and stripped everything down. I then followed some examples and tutorials and have some triangles rendering to the screen.

 

I am calling this to Initialize OpenGL:

GL.Viewport (0, 0, screensize.Width, screensize.Height);
                GL.Enable(EnableCap.DepthTest);
                GL.Enable(EnableCap.Texture2D);

                Matrix4 modelview = Matrix4.LookAt(Vector3.Zero, Vector3.UnitZ, Vector3.UnitY);
                GL.MatrixMode(MatrixMode.Modelview);
                GL.LoadMatrix(ref modelview);

I am then testing this by drawing a large triangle, then a small one

//large
            GL.Color4 (System.Drawing.Color.Yellow);
            GL.Begin(PrimitiveType.Triangles);
            GL.Vertex3(-1.0f, -1.0f, 4.0f);
            GL.Vertex3(1.0f, -1.0f, 4.0f);
            GL.Vertex3(0.0f, 1.0f, 4.0f);
            GL.End();

            //small
            GL.Color4 (System.Drawing.Color.Blue);
            GL.Begin(PrimitiveType.Triangles);
            GL.Vertex3(0.5f, -0.5f, 4.0f); //bottom left
            GL.Vertex3(0.0f, 1.0f, 4.0f); //top
            GL.Vertex3(-0.5f, -0.5f, 4.0f); //bottom right
            GL.End();

but only the large one is drawn (the small should be drawn on top of the large). If I move the "small" triangle code above the large, I see both triangles. Is the rendering/drawing order reversed for OpenGL or is it something I did wrong?

 

EDIT: Turns out I was a little hasty with my clicking. This is because of the

GL.Enable(EnableCap.DepthTest);
I thought depth testing was needed in order to use the z-axis for when I need 3d? Edited by detlion1643

Share this post


Link to post
Share on other sites

I was merely talking about why the first triangle in code wasn't drawn first, then the second in code drawn on top of the first. Both use the same depth of 4.0.

 

In fact, it seems like the initial -1 -> 1 coordinate system isn't working how I thought it would. Here is code that I trialed and errored to get right:

//negative y = down
            //negative x = right
            //negative z = closer to camera, less than 1 is invisible
            //the following x, y, and z coordinates fill the screen on the initial screensize
            GL.Vertex3( -1.38f, -0.828f, 2.0f);    // bottom right
            GL.Color3 (System.Drawing.Color.Green);
            GL.Vertex3( 1.38f, -0.828f, 2.0f);    // bottom left
            GL.Color3 (System.Drawing.Color.Red);
            GL.Vertex3( 1.38f, 0.828, 2.0f);    // top left
            GL.Color3 (System.Drawing.Color.DarkOrange);
            GL.Vertex3( -1.38f, 0.828f, 2.0f);    // top right
            GL.End ();
I know the depth is 2.0f, but even at 1.0f using -1, 1 for x/y values fill more than the screen (as 0.8 values fill more than the screen, 0.5 fill less than the screen).

 

Here is my resize code:

GL.Viewport(Left, Top, Width, Height);
            //Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 0.5f, 64.0f);
            Matrix4d projection = Matrix4d.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(45), Width / (float)Height, 1.0, 1000.0);
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadMatrix(ref projection);

 

Should I  be concerned about my starting point. I am going to have to calculate pixel coordinates based on a 1000x600 initial screensize in order to render my controls. For example, a control placed X=0, Y=0, W=500, H=300 would be calculated based on the above starting point. So the left side would be at 1.38f, the right side at 0, the top at 0.828 and the bottom at 0.

 

Doesn't this sound overly complex?

Share this post


Link to post
Share on other sites

I skipped over your initial problem. If you are trying to render 2D with openGL  You dont want persepctive (which implies a 3D world) you want orthographic.

 

Matrix4.____Ortho____
Should be a function something like that. Depth will still matter but you can work in 2D. Ortho(0,screenwidth, 0, screenheight)  <-- allows you to call glVertex3f() with 2d pixel coordinates + some z-depth.

 

With Ortho there is no perspective division to warp stuff away from the camera. The z value doesnt effect perspective, the input x,y  will be the output x,y

Edited by dpadam450

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!