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?
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);