-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathShaderProgram.cs
More file actions
495 lines (410 loc) · 14.7 KB
/
Copy pathShaderProgram.cs
File metadata and controls
495 lines (410 loc) · 14.7 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
using System;
using System.Collections.Generic;
using OpenTK.Graphics.OpenGL;
using OpenTK;
using System.Linq;
namespace GLFrameworkEngine
{
/// <summary>
/// Represents a shader program that stores GL shader data.
/// </summary>
public class ShaderProgram : IDisposable
{
/// <summary>
/// The ID of the shader program.
/// </summary>
public int program;
//The input attributes in the shader
private Dictionary<string, int> attributes = new Dictionary<string, int>();
//The uniforms in the shader
private Dictionary<string, int> uniforms = new Dictionary<string, int>();
private int activeAttributeCount;
//The shader stages inn the program
private HashSet<Shader> shaders = new HashSet<Shader>();
//Feedback attribute varyings to store attribute data executed from shader code
public string[] FeedbackVaryings = new string[0];
//Check if the shader was linked
public bool LinkSucessful = false;
// This isn't in OpenTK's enums for some reason.
// https://www.khronos.org/registry/OpenGL/api/GL/glcorearb.h
private static readonly int GL_PROGRAM_BINARY_MAX_LENGTH = 0x8741;
public ShaderProgram(Shader[] shaders)
{
program = GL.CreateProgram();
LoadSource(shaders);
}
public ShaderProgram()
{
program = GL.CreateProgram();
}
public ShaderProgram(Shader vertexShader, Shader fragmentShader)
{
program = GL.CreateProgram();
LoadSource(vertexShader, fragmentShader);
}
public ShaderProgram(byte[] binaryData, BinaryFormat format)
{
program = GL.CreateProgram();
LoadBinary(binaryData, format);
}
/// <summary>
/// Loads the shader from shader stages.
/// </summary>
public void LoadSource(Shader[] shaders)
{
this.shaders.Clear();
foreach (Shader shader in shaders)
{
if (!this.shaders.Contains(shader))
this.shaders.Add(shader);
}
CompileShaders();
}
/// <summary>
/// Loads the shader from vertex and fragment shader stages.
/// </summary>
public void LoadAsBinary(Shader vertexShader, Shader fragmentShader)
{
if (!this.shaders.Contains(vertexShader))
this.shaders.Add(vertexShader);
if (!this.shaders.Contains(fragmentShader))
this.shaders.Add(fragmentShader);
GL.ProgramParameter(program, ProgramParameterName.ProgramBinaryRetrievableHint, 1);
foreach (Shader shader in shaders)
{
GL.AttachShader(program, shader.id);
}
GL.LinkProgram(program);
foreach (var shader in shaders)
{
Console.WriteLine($"{shader.type.ToString("g")}:");
string log = GL.GetShaderInfoLog(shader.id);
Console.WriteLine(log);
}
LinkSucessful = true;
}
/// <summary>
/// Loads the shader from vertex and fragment shader stages.
/// </summary>
public void LoadSource(Shader vertexShader, Shader fragmentShader)
{
foreach (Shader shader in shaders)
{
GL.DetachShader(program, shader.id);
}
this.shaders.Clear();
if (!this.shaders.Contains(vertexShader))
this.shaders.Add(vertexShader);
if (!this.shaders.Contains(fragmentShader))
this.shaders.Add(fragmentShader);
CompileShaders();
}
/// <summary>
/// Loads the shader from a dumped glsl binary.
/// </summary>
public void LoadBinary(byte[] binaryData, BinaryFormat format)
{
// Number of supported binary formats.
int binaryFormatCount;
GL.GetInteger(GetPName.NumProgramBinaryFormats, out binaryFormatCount);
// Get all supported formats.
int[] binaryFormats = new int[binaryFormatCount];
GL.GetInteger(GetPName.ProgramBinaryFormats, binaryFormats);
if (binaryFormats.Contains((int)format))
{
try
{
GL.ProgramBinary(program, format, binaryData, binaryData.Length);
}
catch (AccessViolationException)
{
// The binary is corrupt or the wrong format.
LinkSucessful = false;
return;
}
LoadAttributes(program);
LoadUniorms(program);
LinkSucessful = true;
}
}
/// <summary>
/// Links the shader program.
/// </summary>
public void Link()
{
GL.LinkProgram(program);
}
/// <summary>
/// Enables the shader program.
/// </summary>
public void Enable()
{
GL.UseProgram(program);
}
/// <summary>
/// Disables the shader program.
/// </summary>
public void Disable()
{
GL.UseProgram(0);
}
/// <summary>
/// Disposes the shader program.
/// </summary>
public void Dispose()
{
foreach (var shader in shaders)
shader.Dispose();
GL.DeleteProgram(program);
}
/// <summary>
/// Loads a 2D texture into the shader given a uniform name, texture ID, and slot number.
/// </summary>
public void SetTexture2D(string uniform, int id, int slot)
{
GL.ActiveTexture(TextureUnit.Texture0 + slot);
GL.BindTexture(TextureTarget.Texture2D, id);
this.SetInt(uniform, slot);
}
/// <summary>
/// Loads a 2D texture into the shader given a texture instance, uniform name, and slot number.
/// </summary>
public void SetTexture(GLTexture tex, string uniform, int slot)
{
GL.ActiveTexture(TextureUnit.Texture0 + slot);
tex.Bind();
this.SetInt(uniform, slot);
}
/// <summary>
/// Loads a transform into the shader given a uniform name and gl transform.
/// </summary>
public void SetTransform(string name, GLTransform transform) {
var matrix = transform.TransformMatrix;
SetMatrix4x4(name, ref matrix);
}
public void SetVector4(string name, Vector4 value)
{
if (uniforms.ContainsKey(name))
GL.Uniform4(uniforms[name], value);
}
public void SetVector3(string name, Vector3 value)
{
if (uniforms.ContainsKey(name))
GL.Uniform3(uniforms[name], value);
}
public void SetVector2(string name, Vector2 value)
{
if (uniforms.ContainsKey(name))
GL.Uniform2(uniforms[name], value);
}
public void SetFloat(string name, float value)
{
if (uniforms.ContainsKey(name))
GL.Uniform1(uniforms[name], value);
}
public void SetInt(string name, int value)
{
if (uniforms.ContainsKey(name))
GL.Uniform1(uniforms[name], value);
}
public void SetBool(string name, bool value)
{
int intValue = value == true ? 1 : 0;
if (uniforms.ContainsKey(name))
GL.Uniform1(uniforms[name], intValue);
}
public void SetBoolToInt(string name, bool value)
{
if (!uniforms.ContainsKey(name))
return;
if (value)
GL.Uniform1(uniforms[name], 1);
else
GL.Uniform1(this[name], 0);
}
public void SetColor(string name, System.Drawing.Color color)
{
if (uniforms.ContainsKey(name))
GL.Uniform4(uniforms[name], color.R, color.G, color.B, color.A);
}
public void SetMatrix4x4(string name, ref Matrix4 value, bool transpose = false)
{
if (uniforms.ContainsKey(name))
GL.UniformMatrix4(uniforms[name], transpose, ref value);
}
public int this[string name]
{
get { return uniforms[name]; }
}
private void LoadUniorms(int program)
{
uniforms.Clear();
GL.GetProgram(program, GetProgramParameterName.ActiveUniforms, out activeAttributeCount);
for (int i = 0; i < activeAttributeCount; i++)
{
string name = GL.GetActiveUniform(program, i, out int size, out ActiveUniformType type);
if (string.IsNullOrEmpty(name))
continue;
int location = GL.GetUniformLocation(program, name);
// Overwrite existing vertex attributes.
uniforms[name] = location;
}
}
private void LoadAttributes(int program)
{
attributes.Clear();
GL.GetProgram(program, GetProgramParameterName.ActiveAttributes, out activeAttributeCount);
for (int i = 0; i < activeAttributeCount; i++)
{
string name = GL.GetActiveAttrib(program, i, out int size, out ActiveAttribType type);
int location = GL.GetAttribLocation(program, name);
// Overwrite existing vertex attributes.
attributes[name] = location;
}
}
public int GetAttribute(string name)
{
if (string.IsNullOrEmpty(name) || !attributes.ContainsKey(name))
return -1;
else
return attributes[name];
}
public void EnableVertexAttributes()
{
foreach (KeyValuePair<string, int> attrib in attributes)
GL.EnableVertexAttribArray(attrib.Value);
}
public void DisableVertexAttributes()
{
foreach (KeyValuePair<string, int> attrib in attributes)
GL.DisableVertexAttribArray(attrib.Value);
}
public void SaveBinary(string fileName)
{
CreateBinary(out byte[] binaryData, out BinaryFormat format);
System.IO.File.WriteAllBytes(fileName + ".bin", binaryData);
System.IO.File.WriteAllBytes(fileName + ".format", BitConverter.GetBytes((int)format));
}
private void CreateBinary(out byte[] binaryData, out BinaryFormat format)
{
GL.GetProgram(program, (GetProgramParameterName)GL_PROGRAM_BINARY_MAX_LENGTH, out int size);
binaryData = new byte[size];
GL.GetProgramBinary(program, size, out _, out format, binaryData);
}
public virtual void OnCompiled() { }
private void CompileShaders()
{
foreach (Shader shader in shaders)
{
GL.AttachShader(program, shader.id);
}
//Before linking, attach feedback varyings
TransformFeedbackVaryings(program);
GL.LinkProgram(program);
foreach (var shader in shaders)
{
Console.WriteLine($"{shader.type.ToString("g")}:");
string log = GL.GetShaderInfoLog(shader.id);
Console.WriteLine(log);
}
LoadAttributes(program);
LoadUniorms(program);
LinkSucessful = true;
}
private void TransformFeedbackVaryings(int program)
{
if (FeedbackVaryings.Length == 0)
return;
string[] varyings = this.FeedbackVaryings;
GL.TransformFeedbackVaryings(program, varyings.Length, varyings, TransformFeedbackMode.SeparateAttribs);
}
}
public class Shader : IDisposable
{
public Shader(string src, ShaderType type)
{
id = GL.CreateShader(type);
GL.ShaderSource(id, src);
GL.CompileShader(id);
this.type = type;
}
public Shader(byte[] binary, ShaderType type)
{
id = GL.CreateShader(type);
GL.ShaderBinary(1, ref id, (BinaryFormat)All.ShaderBinaryFormatSpirVArb, binary, binary.Length);
GL.SpecializeShader(id, "main", 0, (int[])null, (int[])null);
this.type = type;
}
public Shader(string src, ShaderType type, Dictionary<string, string> macros)
{
id = GL.CreateShader(type);
GL.ShaderSource(id, CompileMacros(macros, src));
GL.CompileShader(id);
this.type = type;
}
private string CompileMacros(Dictionary<string, string> macros, string src)
{
var sb = new System.Text.StringBuilder();
using (var writer = new System.IO.StringWriter(sb))
{
foreach (var line in src.Split("\n")) {
string value = line;
if (line.StartsWith("#define")) {
var macroName = line.Split()[1];
if (macros.ContainsKey(macroName))
value = string.Format("#define {0} {1}", macroName, macros[macroName]);
}
writer.WriteLine(value);
}
}
return sb.ToString();
}
public string GetShaderSource()
{
string source = "";
GL.GetShader(id, ShaderParameter.ShaderSourceLength, out int length);
if (length != 0)
GL.GetShaderSource(id, length, out _, out source);
return source;
}
public string GetInfoLog()
{
return GL.GetShaderInfoLog(id);
}
public void Dispose()
{
GL.DeleteShader(id);
}
public ShaderType type;
public int id;
}
public class FragmentShader : Shader
{
public FragmentShader(string src)
: base(src, ShaderType.FragmentShader)
{
}
public FragmentShader(byte[] binary)
: base(binary, ShaderType.FragmentShader)
{
}
}
public class VertexShader : Shader
{
public VertexShader(string src)
: base(src, ShaderType.VertexShader)
{
}
public VertexShader(byte[] binary)
: base(binary, ShaderType.VertexShader)
{
}
}
public class GeomertyShader : Shader
{
public GeomertyShader(string src)
: base(src, ShaderType.GeometryShader)
{
}
}
}