我正在使用 SharpGL 示例作为指南在 WPF 中创建一个现代 OpenGL hello world 应用程序。
在 Draw 方法中调用 DrawArrays 时,我似乎遇到了 AccessViolation 异常。检查了互联网 - 他们都认为它可能是底层的 GC 重定位数组。但既然我使用的是 VBO,这不应该发生,对吧?
代码:
XAML:
<Window x:Class="FirstSharpGlAppWpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sgl="clr-namespace:SharpGL.WPF;assembly=SharpGL.WPF"
Title="MainWindow" Height="350" Width="525">
<Grid>
<sgl:OpenGLControl x:Name="openGLCtrl"
OpenGLDraw="openGLCtrl_OpenGLDraw"
OpenGLInitialized="openGLCtrl_OpenGLInitialized"
RenderContextType="FBO"
DrawFPS="True" />
</Grid>
</Window>
XAML.cs
using SharpGL;
using SharpGL.Shaders;
using SharpGL.VertexBuffers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace FirstSharpGlAppWpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
VertexBufferArray _vao;
VertexBuffer _vbo;
ShaderProgram _shaderProgram;
float[] _vertices;
public MainWindow()
{
InitializeComponent();
}
private void openGLCtrl_OpenGLDraw(object sender, SharpGL.SceneGraph.OpenGLEventArgs args)
{
// Get the OpenGL instance that's been passed to us.
OpenGL gl = args.OpenGL;
gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT);
_shaderProgram.Bind(gl);
_vao.Bind(gl);
gl.DrawArrays(OpenGL.GL_POINTS, 0, _vertices.Length);
_vao.Unbind(gl);
_shaderProgram.Unbind(gl);
}
private void openGLCtrl_OpenGLInitialized(object sender, SharpGL.SceneGraph.OpenGLEventArgs args)
{
var gl = args.OpenGL;
_vertices = new float[]{
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
ShaderCreator sc = new ShaderCreator();
_shaderProgram = new ShaderProgram();
sc.Create(gl, _shaderProgram);
_vao = new VertexBufferArray();
_vao.Create(gl);
_vao.Bind(gl);
_vbo = new VertexBuffer();
_vbo.Create(gl);
_vbo.Bind(gl);
_vbo.SetData(gl, 0, _vertices, false, 0);
_vbo.Unbind(gl);
_vao.Unbind(gl);
}
}
}