lixiaojun
2025-03-17 85fc43aa549bbe24c4d867a055c0d90d21deba8b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
using OpenTK.GLControl;
using OpenTK.Graphics.OpenGL;
using OpenTK.Mathematics;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
 
namespace Yw.WinFrmUI.HydroL3d
{
    public partial class OpenGLControl : UserControl
    {
        public OpenGLControl()
        {
            InitializeComponent();
            this.glControl1.Load += glControl_Load;
        }
 
        #region 着色器资源
 
        private const string VertexShaderSource = @"#version 330 core
 
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec4 aColor;
 
out vec4 fColor;
 
uniform mat4 MVP;
 
void main()
{
    gl_Position = vec4(aPos, 1) * MVP;
    fColor = aColor;
}
";
 
        private const string FragmentShaderSource = @"#version 330 core
 
in vec4 fColor;
 
out vec4 oColor;
 
void main()
{
    oColor = fColor;
}
";
 
        #endregion
 
        // 坐标轴顶点数据
        private static readonly Vector3[] AxisVertexData = new Vector3[]
        {
            new Vector3(0, 0, 0), new Vector3(2, 0, 0), // X 轴
            new Vector3(0, 0, 0), new Vector3(0, 2, 0), // Y 轴
            new Vector3(0, 0, 0), new Vector3(0, 0, 2)  // Z 轴
        };
 
        // 坐标轴颜色数据
        private static readonly Color4[] AxisColorData = new Color4[]
        {
            Color4.Red, Color4.Red,
            Color4.Green, Color4.Green,
            Color4.Blue, Color4.Blue
        };
 
        private static readonly int[] AxisIndexData = new int[] { 0, 1, 2, 3, 4, 5 };
 
        private Matrix4 _projection; // 投影
        private System.Windows.Forms.Timer _timer = null!;
 
        private int CubeShader;
 
        private int AxisVAO;
        private int AxisEBO;
        private int AxisPositionBuffer;
        private int AxisColorBuffer;
 
        private void glControl_Load(object sender, EventArgs e)
        {
            this.glControl1.Resize += glControl_Resize;
            this.glControl1.Paint += glControl_Paint;
            _timer = new System.Windows.Forms.Timer();
            _timer.Tick += (sender, e) =>
            {
                RenderGL();
            };
            _timer.Interval = 50;   // 1000 ms per sec / 50 ms per frame = 20 FPS
            _timer.Start();
 
            CubeShader = CompileProgram(VertexShaderSource, FragmentShaderSource);
 
            ResizeGL();
 
            // 初始化坐标轴的 VAO 和 VBO
            AxisVAO = GL.GenVertexArray();
            GL.BindVertexArray(AxisVAO);
 
            AxisEBO = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, AxisEBO);
            GL.BufferData(BufferTarget.ElementArrayBuffer, AxisIndexData.Length * sizeof(int), AxisIndexData, BufferUsageHint.StaticDraw);
 
            AxisPositionBuffer = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ArrayBuffer, AxisPositionBuffer);
            GL.BufferData(BufferTarget.ArrayBuffer, AxisVertexData.Length * sizeof(float) * 3, AxisVertexData, BufferUsageHint.StaticDraw);
 
            GL.EnableVertexAttribArray(0);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, sizeof(float) * 3, 0);
 
            AxisColorBuffer = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ArrayBuffer, AxisColorBuffer);
            GL.BufferData(BufferTarget.ArrayBuffer, AxisColorData.Length * sizeof(float) * 4, AxisColorData, BufferUsageHint.StaticDraw);
 
            GL.EnableVertexAttribArray(1);
            GL.VertexAttribPointer(1, 4, VertexAttribPointerType.Float, false, sizeof(float) * 4, 0);
        }
 
        private int CompileProgram(string vertexShader, string fragmentShader)
        {
            int program = GL.CreateProgram();
 
            int vert = CompileShader(ShaderType.VertexShader, vertexShader);
            int frag = CompileShader(ShaderType.FragmentShader, fragmentShader);
 
            GL.AttachShader(program, vert);
            GL.AttachShader(program, frag);
 
            GL.LinkProgram(program);
 
            GL.GetProgram(program, GetProgramParameterName.LinkStatus, out int success);
            if (success == 0)
            {
                string log = GL.GetProgramInfoLog(program);
                throw new Exception($"Could not link program: {log}");
            }
 
            GL.DetachShader(program, vert);
            GL.DetachShader(program, frag);
 
            GL.DeleteShader(vert);
            GL.DeleteShader(frag);
 
            return program;
 
            static int CompileShader(ShaderType type, string source)
            {
                int shader = GL.CreateShader(type);
 
                GL.ShaderSource(shader, source);
                GL.CompileShader(shader);
 
                GL.GetShader(shader, ShaderParameter.CompileStatus, out int status);
                if (status == 0)
                {
                    string log = GL.GetShaderInfoLog(shader);
                    throw new Exception($"Failed to compile {type}: {log}");
                }
 
                return shader;
            }
        }
 
        // 尺寸改变
        private void glControl_Resize(object sender, EventArgs e)
        {
            ResizeGL();
        }
 
        // 绘制
        private void glControl_Paint(object sender, PaintEventArgs e)
        {
            RenderGL();
        }
 
        // 渲染
        private void RenderGL()
        {
            this.glControl1.MakeCurrent();
 
            GL.ClearColor(Color4.Transparent);
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.Enable(EnableCap.DepthTest); // 开启深度测试
 
            Matrix4 lookat = Matrix4.LookAt(0, 5, 5, 0, 0, 0, 0, 1, 0);
            Matrix4 model = Matrix4.Identity;
 
            Matrix4 mvp = model * lookat * _projection;
 
            GL.UseProgram(CubeShader);
            GL.UniformMatrix4(GL.GetUniformLocation(CubeShader, "MVP"), true, ref mvp);
 
            // 绘制坐标轴
            GL.BindVertexArray(AxisVAO);
            GL.DrawElements(BeginMode.Lines, AxisIndexData.Length, DrawElementsType.UnsignedInt, 0);
 
            this.glControl1.SwapBuffers();
        }
 
        // 调整大小
        private void ResizeGL()
        {
            this.glControl1.MakeCurrent();
            if (this.glControl1.ClientSize.Height == 0)
            {
                this.glControl1.ClientSize = new Size(this.glControl1.ClientSize.Width, 1);
            }
            GL.Viewport(0, 0, this.glControl1.ClientSize.Width, this.glControl1.ClientSize.Height);
            float aspect = Math.Max(this.glControl1.ClientSize.Width, 1) / (float)Math.Max(this.glControl1.ClientSize.Height, 1);
            _projection = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect, 1, 64);
        }
 
    }
}