using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Mathematics;
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Desktop;
using System;
using System.Drawing;
namespace OpenTKTriangleExample
{
class GameWindowMy : GameWindow
{
int Width;
int Height;
public GameWindowMy(int width, int height, string title)
: base(GameWindowSettings.Default, NativeWindowSettings.Default)
{
this.Width = width;
this.Height = height;
VSync = VSyncMode.On; // 启用垂直同步
}
protected override void OnLoad()
{
GL.ClearColor(Color4.CornflowerBlue); // 设置背景颜色
// 设置视口
GL.Viewport(0, 0, Width, Height);
// 初始化OpenGL
GL.Enable(EnableCap.DepthTest); // 启用深度测试
// 设置投影矩阵
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
//GLU.Perspective(45.0f, (float)Width / Height, 0.1f, 100.0f);
// 设置模型视图矩阵
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
// 清除屏幕
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
}
protected override void OnRenderFrame(FrameEventArgs e)
{
// 清除屏幕和深度缓冲区
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
// 绘制三角形
GL.Begin(PrimitiveType.Triangles); // 开始绘制三角形
// 设置三角形顶点的颜色(可选)
GL.Color3(1,0,0); // 红色
// 设置三角形顶点的坐标
GL.Vertex3(-0.5f, -0.5f, 0.0f); // 顶点1
GL.Vertex3(0.5f, -0.5f, 0.0f); // 顶点2
GL.Vertex3(0.0f, 0.5f, 0.0f); // 顶点3
GL.End(); // 结束绘制三角形
// 交换缓冲区以显示渲染结果
SwapBuffers();
// 处理标题栏的帧率显示
Title = $"{Width} x {Height} - {e.Time.ToString("F3")} ms/frame";
// 调用基类的RenderFrame方法,如果需要的话
base.OnRenderFrame(e);
}
[STAThread]
static void Main()
{
using (GameWindowMy game = new GameWindowMy(800, 600, "OpenTK Triangle Example"))
{
game.Run(); // 以60 FPS运行
}
}
}
}