c# - 如何使用 GLFW.Net 初始化 OpenGL.NET?

标签 c# opengl openglcontext

我正在尝试在 C# 中使用 OpenGL 和 GLFW。我已经安装了 GLFW.Net 和 OpenGL.Net 的 NuGet 包。我一生无法弄清楚的是,如何使用 GLFW.Net 设置 OpenGL.Net 的上下文?当我尝试运行非常基本的测试 OpenGL 代码时,没有出现错误消息。即

    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();
        }
    }

但没有任何渲染。这是否意味着我的上下文不存在,或者我很愚蠢,留下了一些东西?

最佳答案

乍一看,我发现了一个明显的问题。缓冲区数据的大小必须以字节为单位指定(请参阅 glBufferData )。因此大小必须是 6*4 而不是 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);

事实证明OpenGL.NET在创建 OpenGL Context 之前必须初始化库当前(无论出于何种原因):

Gl.Initialize();
Glfw.MakeContextCurrent(window);

关于c# - 如何使用 GLFW.Net 初始化 OpenGL.NET?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61318104/

相关文章:

python - 在 Python 中创建向前兼容的 OpenGL 3.x 上下文

windows - 是否可以在上下文/线程之间共享 opengl 帧缓冲区对象?

python-2.7 - Ubuntu 上的 PyOpenGL for Python 2.7

c# - System.Runtime.Caching.MemoryCache 在被逐出时会处理 IDisposable 项目吗?

c# - TypedReference 的实际使用

c# - 通过 NetworkStream 从 ZlibStream 读取在 C# .Net 中出现阻塞问题

opengl - 这些矩阵模式有什么区别?

opengl - 我可以旋转 glOrtho() 的 View 吗?

opengl - 有没有办法运行 mesa 编译器来减少着色器文件的大小?

c# - 使用用户定义的类型对象创建 SafeArray