Subversion Repositories AndroidProjects

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1452 chris 1
#region --- License ---
2
/* Licensed under the MIT/X11 license.
3
 * Copyright (c) 2006-2008 the OpenTK Team.
4
 * This notice may not be removed from any source distribution.
5
 * See license.txt for licensing detailed licensing details.
6
 */
7
#endregion
8
 
9
#region --- Using Directives ---
10
 
11
using System;
12
using System.Collections.Generic;
13
using System.ComponentModel;
14
using System.Drawing;
15
using System.Text;
16
using System.Windows.Forms;
17
using System.Threading;
18
using System.Diagnostics;
19
using System.IO;
20
 
21
using OpenTK;
22
using OpenTK.Graphics;
23
using OpenTK.Graphics.OpenGL;
24
 
25
#endregion --- Using Directives ---
26
 
27
namespace Examples.Tutorial
28
{
29
    /// <summary>
30
    /// Demonstrates how to load and use a simple OpenGL shader program. Example is incomplete (documentation).
31
    /// </summary>
32
    [Example("First shader", ExampleCategory.OpenGL, "2.x", Documentation = "SimpleGLSL")]
33
    public class T10_GLSL_Cube : GameWindow
34
    {
35
        #region --- Fields ---
36
 
37
        static float angle = 0.0f, rotation_speed = 3.0f;
38
        int vertex_shader_object, fragment_shader_object, shader_program;
39
        int vertex_buffer_object, color_buffer_object, element_buffer_object;
40
 
41
        Shapes.Shape shape = new Examples.Shapes.Cube();
42
 
43
        #endregion
44
 
45
        #region --- Constructors ---
46
 
47
        public T10_GLSL_Cube()
48
            : base(800, 600, GraphicsMode.Default)
49
        { }
50
 
51
        #endregion
52
 
53
        #region OnLoad
54
 
55
        /// <summary>
56
        /// This is the place to load resources that change little
57
        /// during the lifetime of the GameWindow. In this case, we
58
        /// check for GLSL support, and load the shaders.
59
        /// </summary>
60
        /// <param name="e">Not used.</param>
61
        protected override void OnLoad(EventArgs e)
62
        {
63
            // Check for necessary capabilities:
64
            string version = GL.GetString(StringName.Version);
65
            int major = (int)version[0];
66
            int minor = (int)version[2];
67
            if (major < 2)
68
            {
69
                MessageBox.Show("You need at least OpenGL 2.0 to run this example. Aborting.", "GLSL not supported",
70
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
71
                this.Exit();
72
            }
73
 
74
            GL.ClearColor(Color.MidnightBlue);
75
            GL.Enable(EnableCap.DepthTest);
76
 
77
            CreateVBO();
78
 
79
            using (StreamReader vs = new StreamReader("Data/Shaders/Simple_VS.glsl"))
80
            using (StreamReader fs = new StreamReader("Data/Shaders/Simple_FS.glsl"))
81
                CreateShaders(vs.ReadToEnd(), fs.ReadToEnd(),
82
                    out vertex_shader_object, out fragment_shader_object,
83
                    out shader_program);
84
        }
85
 
86
        #endregion
87
 
88
        #region CreateShaders
89
 
90
        void CreateShaders(string vs, string fs,
91
            out int vertexObject, out int fragmentObject,
92
            out int program)
93
        {
94
            int status_code;
95
            string info;
96
 
97
            vertexObject = GL.CreateShader(ShaderType.VertexShader);
98
            fragmentObject = GL.CreateShader(ShaderType.FragmentShader);
99
 
100
            // Compile vertex shader
101
            GL.ShaderSource(vertexObject, vs);
102
            GL.CompileShader(vertexObject);
103
            GL.GetShaderInfoLog(vertexObject, out info);
104
            GL.GetShader(vertexObject, ShaderParameter.CompileStatus, out status_code);
105
 
106
            if (status_code != 1)
107
                throw new ApplicationException(info);
108
 
109
            // Compile vertex shader
110
            GL.ShaderSource(fragmentObject, fs);
111
            GL.CompileShader(fragmentObject);
112
            GL.GetShaderInfoLog(fragmentObject, out info);
113
            GL.GetShader(fragmentObject, ShaderParameter.CompileStatus, out status_code);
114
 
115
            if (status_code != 1)
116
                throw new ApplicationException(info);
117
 
118
            program = GL.CreateProgram();
119
            GL.AttachShader(program, fragmentObject);
120
            GL.AttachShader(program, vertexObject);
121
 
122
            GL.LinkProgram(program);
123
            GL.UseProgram(program);
124
        }
125
 
126
        #endregion
127
 
128
        #region private void CreateVBO()
129
 
130
        void CreateVBO()
131
        {
132
            int size;
133
 
134
            GL.GenBuffers(1, out vertex_buffer_object);
135
            GL.GenBuffers(1, out color_buffer_object);
136
            GL.GenBuffers(1, out element_buffer_object);
137
 
138
            // Upload the vertex buffer.
139
            GL.BindBuffer(BufferTarget.ArrayBuffer, vertex_buffer_object);
140
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(shape.Vertices.Length * 3 * sizeof(float)), shape.Vertices,
141
                BufferUsageHint.StaticDraw);
142
            GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out size);
143
            if (size != shape.Vertices.Length * 3 * sizeof(Single))
144
                throw new ApplicationException(String.Format(
145
                    "Problem uploading vertex buffer to VBO (vertices). Tried to upload {0} bytes, uploaded {1}.",
146
                    shape.Vertices.Length * 3 * sizeof(Single), size));
147
 
148
            // Upload the color buffer.
149
            GL.BindBuffer(BufferTarget.ArrayBuffer, color_buffer_object);
150
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(shape.Colors.Length * sizeof(int)), shape.Colors,
151
                BufferUsageHint.StaticDraw);
152
            GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out size);
153
            if (size != shape.Colors.Length * sizeof(int))
154
                throw new ApplicationException(String.Format(
155
                    "Problem uploading vertex buffer to VBO (colors). Tried to upload {0} bytes, uploaded {1}.",
156
                    shape.Colors.Length * sizeof(int), size));
157
 
158
            // Upload the index buffer (elements inside the vertex buffer, not color indices as per the IndexPointer function!)
159
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, element_buffer_object);
160
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(shape.Indices.Length * sizeof(Int32)), shape.Indices,
161
                BufferUsageHint.StaticDraw);
162
            GL.GetBufferParameter(BufferTarget.ElementArrayBuffer, BufferParameterName.BufferSize, out size);
163
            if (size != shape.Indices.Length * sizeof(int))
164
                throw new ApplicationException(String.Format(
165
                    "Problem uploading vertex buffer to VBO (offsets). Tried to upload {0} bytes, uploaded {1}.",
166
                    shape.Indices.Length * sizeof(int), size));
167
        }
168
 
169
        #endregion
170
 
171
        #region OnUnload
172
 
173
        protected override void OnUnload(EventArgs e)
174
        {
175
            if (shader_program != 0)
176
                GL.DeleteProgram(shader_program);
177
            if (fragment_shader_object != 0)
178
                GL.DeleteShader(fragment_shader_object);
179
            if (vertex_shader_object != 0)
180
                GL.DeleteShader(vertex_shader_object);
181
            if (vertex_buffer_object != 0)
182
                GL.DeleteBuffers(1, ref vertex_buffer_object);
183
            if (element_buffer_object != 0)
184
                GL.DeleteBuffers(1, ref element_buffer_object);
185
        }
186
 
187
        #endregion
188
 
189
        #region OnResize
190
 
191
        /// <summary>
192
        /// Called when the user resizes the window.
193
        /// </summary>
194
        /// <param name="e">Contains the new width/height of the window.</param>
195
        /// <remarks>
196
        /// You want the OpenGL viewport to match the window. This is the place to do it!
197
        /// </remarks>
198
        protected override void OnResize(EventArgs e)
199
        {
200
            GL.Viewport(0, 0, Width, Height);
201
 
202
            float aspect_ratio = Width / (float)Height;
203
            Matrix4 perpective = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect_ratio, 1, 64);
204
            GL.MatrixMode(MatrixMode.Projection);
205
            GL.LoadMatrix(ref perpective);
206
        }
207
 
208
        #endregion
209
 
210
        #region OnUpdateFrame
211
 
212
        /// <summary>
213
        /// Prepares the next frame for rendering.
214
        /// </summary>
215
        /// <remarks>
216
        /// Place your control logic here. This is the place to respond to user input,
217
        /// update object positions etc.
218
        /// </remarks>
219
        protected override void OnUpdateFrame(FrameEventArgs e)
220
        {
221
            if (Keyboard[OpenTK.Input.Key.Escape])
222
                this.Exit();
223
 
224
            if (Keyboard[OpenTK.Input.Key.F11])
225
                if (WindowState != WindowState.Fullscreen)
226
                    WindowState = WindowState.Fullscreen;
227
                else
228
                    WindowState = WindowState.Normal;
229
        }
230
 
231
        #endregion
232
 
233
        #region OnRenderFrame
234
 
235
        /// <summary>
236
        /// Place your rendering code here.
237
        /// </summary>
238
        protected override void OnRenderFrame(FrameEventArgs e)
239
        {
240
            GL.Clear(ClearBufferMask.ColorBufferBit |
241
                     ClearBufferMask.DepthBufferBit);
242
 
243
            Matrix4 lookat = Matrix4.LookAt(0, 5, 5, 0, 0, 0, 0, 1, 0);
244
            GL.MatrixMode(MatrixMode.Modelview);
245
            GL.LoadMatrix(ref lookat);
246
 
247
            angle += rotation_speed * (float)e.Time;
248
            GL.Rotate(angle, 0.0f, 1.0f, 0.0f);
249
 
250
            GL.EnableClientState(EnableCap.VertexArray);
251
            GL.EnableClientState(EnableCap.ColorArray);
252
 
253
            GL.BindBuffer(BufferTarget.ArrayBuffer, vertex_buffer_object);
254
            GL.VertexPointer(3, VertexPointerType.Float, 0, IntPtr.Zero);
255
            GL.BindBuffer(BufferTarget.ArrayBuffer, color_buffer_object);
256
            GL.ColorPointer(4, ColorPointerType.UnsignedByte, 0, IntPtr.Zero);
257
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, element_buffer_object);
258
 
259
            GL.DrawElements(BeginMode.Triangles, shape.Indices.Length,
260
                DrawElementsType.UnsignedInt, IntPtr.Zero);
261
 
262
            //GL.DrawArrays(GL.Enums.BeginMode.POINTS, 0, shape.Vertices.Length);
263
 
264
            GL.DisableClientState(EnableCap.VertexArray);
265
            GL.DisableClientState(EnableCap.ColorArray);
266
 
267
 
268
            //int error = GL.GetError();
269
            //if (error != 0)
270
            //    Debug.Print(Glu.ErrorString(Glu.Enums.ErrorCode.INVALID_OPERATION));
271
 
272
            SwapBuffers();
273
        }
274
 
275
        #endregion
276
 
277
        #region public static void Main()
278
 
279
        /// <summary>
280
        /// Entry point of this example.
281
        /// </summary>
282
        [STAThread]
283
        public static void Main()
284
        {
285
            using (T10_GLSL_Cube example = new T10_GLSL_Cube())
286
            {
287
                // Get the title and category  of this example using reflection.
288
                ExampleAttribute info = ((ExampleAttribute)example.GetType().GetCustomAttributes(false)[0]);
289
                example.Title = String.Format("OpenTK | {0} {1}: {2}", info.Category, info.Difficulty, info.Title);
290
                example.Run(30.0, 0.0);
291
            }
292
        }
293
 
294
        #endregion
295
    }
296
}