How Do I Initialize OpenGL.NET with GLFW.Net?

2.2k Views Asked by At

I am trying to use OpenGL and GLFW in C#. I Have Installed NuGet Packages for GLFW.Net and OpenGL.Net. What I cannot for my life figure out, is how do I setup the context for OpenGL.Net with GLFW.Net?? No error messages appeared when I tried to run my very basic test OpenGL Code. i.e.

    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Glfw.Init();
            GLFWwindow window = Glfw.CreateWindow(1080, 720, "Yeet", null, null);
            Glfw.MakeContextCurrent(window);
            Gl.Initialize();

            uint vao = Gl.CreateVertexArray();
            Gl.BindVertexArray(vao);

            uint vbo = Gl.CreateBuffer();
            Gl.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            Gl.BufferData(BufferTarget.ArrayBuffer, 6, new float[] { -0.5f, -0.5f, 0.5f, -0.5f, 0.0f, 0.5f }, BufferUsage.StaticDraw);
            Gl.VertexAttribPointer(0, 2, VertexAttribType.Float, false, 0, null);

            while (Glfw.WindowShouldClose(window) != 1)
            {
                Glfw.PollEvents();

                Gl.ClearColor(0.0f, 1.0f, 1.0f, 1.0f);
                Gl.Clear(ClearBufferMask.ColorBufferBit);
                Gl.BindVertexArray(vao);
                Gl.EnableVertexAttribArray(0);
                Gl.DrawArrays(PrimitiveType.Triangles, 0, 3);
                Gl.DisableVertexAttribArray(0);
                Gl.BindVertexArray(0);

                Glfw.SwapBuffers(window);
            }

            Glfw.DestroyWindow(window);
            Glfw.Terminate();
        }
    }

But Nothing Renders. Does this mean my Context does not exist or that I have been stupid and left something?

2

There are 2 best solutions below

0
Rabbid76 On BEST ANSWER

On the first glace, I can see an obvious issue. The size of the buffer data has to be specified in bytes (see glBufferData). Hence the size has to be 6*4 rather than 6:

var vertices = new float[] { -0.5f, -0.5f, 0.5f, -0.5f, 0.0f, 0.5f };
Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(4 * vertices.Length),
    vertices, BufferUsage.StaticDraw);

It turns out that the OpenGL.NET library has to be initialized before making the OpenGL Context current (for whatever reason):

Gl.Initialize();
Glfw.MakeContextCurrent(window);
1
PixelRifts On

All I had to do was move Gl.Initialize() Above Glfw.MakeContextCurrent(window). I guess you have to create the OpenGL context first and then make the context current. This is unlike LWJGL in which one must call GLFW.glfwMakeContextCurrent() before calling GL.createCapabilities().

Hope this helped! :)