GLSLEffect.cs 6.34 KB
Newer Older
pcy's avatar
initial  
pcy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

/* TODO:
 * * apply
 *   * HOW????
 *   * OnApply: protecteed internal :(
 *   * INTERNAL_applyEffect: internal...
 *     + calls mojoshader! --> hijack?!!
 *       -> glEffect{Begin,End}: state mgmt | unbind shader!
 *       -> glEffect{Begin,End}Pass: bind shader! | state mgmt
 *   * GD draw calls: ok
 *     * EXCEPT mojoshader: glProgramReady, glProgramViewportInfo
18
19
20
 *       -> set up uniforms and vertex arrays!
 *       --> circumvent? --> HOW??
 *       --> just go with it?? --> glProgramReady ok, glProgramViewportInfo might segfault!
21
 *
pcy's avatar
initial  
pcy committed
22
23
 * * uniforms
 * * samplers, textures
24
25
26
 *   -> https://www.khronos.org/opengl/wiki/Program_Introspection
 *   -> https://stackoverflow.com/questions/440144/in-opengl-is-there-a-way-to-get-a-list-of-all-uniforms-attribs-used-by-a-shade#442819
 * * vertex format verification!
pcy's avatar
initial  
pcy committed
27
28
29
30
 */

namespace PoroCYon.FNAGLSL {
	public class GLSLEffect : Effect {
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
		public struct ActiveEffect : IDisposable {
			internal uint oldprgm;
			bool disposed;

			internal ActiveEffect(uint old) {
				oldprgm = old; disposed = false;
			}

			public void Dispose() {
				if (disposed) return;

				GL.UseProgram(oldprgm);
				oldprgm = 0;

				disposed = true;
			}
		}

pcy's avatar
initial  
pcy committed
49
50
51
		uint[] glshdrs;
		uint glprgm;

52
53
		EffectTechnique fakeTech;

pcy's avatar
pcy committed
54
		//readonly static List<EffectTechnique> emptyEffTechList = new List<EffectTechnique>();
pcy's avatar
initial  
pcy committed
55
56
57
		public unsafe GLSLEffect(GraphicsDevice gd,
					IDictionary<GLSLPurpose, string> shaders)
				: base(/*UGLY hack*/new BasicEffect(gd)) {
58
59
60
61
62
			fakeTech = Techniques[0];

			// cause NullRefExns when dumb code would try to access the techns
			this.SetTechniques(null/*ReflUtil.CreateTechColl(emptyEffTechList)*/);

pcy's avatar
initial  
pcy committed
63
			GL.Init(gd);
pcy's avatar
pcy committed
64
			GL.GetError(); // ignore errors from FNA/mojoshader
pcy's avatar
initial  
pcy committed
65

66
67
68
69
			// this basically makes FNA think this effect is a noop, so binding
			// this effect will do the same as binding the 0 program in OpenGL,
			// so the BasicEffect used won't do much anymore
			/*gd.DeleteEffect(this);
70
71
			this.SetGLEffectData(IntPtr.Zero);
			this.SetEffectData  (IntPtr.Zero);*/
72
73
74
75
76
77
			// turns out we can't do this, or libmojoshader will segfault
			// because it lacks some null checking in
			// glEffectEnd, glEffectBeginPass, glProgramViewportInfo :/ ...
			// so we basically have to make sure the usual route of Apply()ing
			// the shader happens (unless we can circumvent this *somehow*),
			// and then apply the shader manually.
pcy's avatar
initial  
pcy committed
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

			var shdrs = new uint[shaders.Count];
			bool ok = false;
			uint prgm = 0;

			try {
				prgm = GL.CreateProgram();
				if (prgm == 0) GL.Throw();

				int i = 0;
				foreach (var kvp in shaders) {
					uint sh = GL.CreateShader(kvp.Key);
					if (sh == 0) GL.Throw();

					byte[] utf8src = Encoding.UTF8.GetBytes(kvp.Value);
					fixed (byte* sbuf = utf8src) {
						sbyte** uurgh = stackalloc sbyte*[1];
						*uurgh = (sbyte*)sbuf;
						int* uurgh2 = stackalloc int[1];
						*uurgh2 = utf8src.Length;
						GL.ShaderSource(sh, 1, uurgh, uurgh2);
					}
					GL.Throw();

					GL.CompileShader(sh);

					if (GL.GetError() != 0 || GL.GetShaderiv(sh, GL.COMPILE_STATUS) == 0) {
						int len = GL.GetShaderiv(sh, GL.INFO_LOG_LENGTH);
pcy's avatar
pcy committed
106
107
108
						var msg = GL.GetShaderInfoLog(sh, len);
						throw new GLSLCompileException("Failed to compile "
								+ kvp.Key + ": " + msg);
pcy's avatar
initial  
pcy committed
109
110
111
112
113
114
115
116
117
118
119
					}

					GL.AttachShader(prgm, sh);
					GL.Throw();

					shdrs[i++] = sh;
				}

				GL.LinkProgram(prgm);
				if (GL.GetError() != 0 || GL.GetProgramiv(prgm, GL.LINK_STATUS) == 0) {
					int len = GL.GetProgramiv(prgm, GL.INFO_LOG_LENGTH);
pcy's avatar
pcy committed
120
121
					var msg = GL.GetProgramInfoLog(prgm, len);
					throw new GLSLLinkException("Failed to link shader: " + msg);
pcy's avatar
initial  
pcy committed
122
123
				}

pcy's avatar
pcy committed
124
125
126
127
128
				glshdrs = shdrs;
				glprgm  = prgm ;

				ParseAttribUnif();

pcy's avatar
initial  
pcy committed
129
130
131
132
133
134
135
136
137
138
139
140
				ok = true;
			}
			finally {
				if (!ok) {
					DelShdrPrgm();
				} else {
					glshdrs = shdrs;
					glprgm  = prgm ;
				}
			}
		}

pcy's avatar
pcy committed
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
		void ParseAttribUnif() {
			// TODO: build EffectParameter stuff
			int attrs = GL.GetProgramiv(glprgm, GL.ACTIVE_ATTRIBUTES);
			GL.Throw();
			Console.WriteLine("#attrs = " + attrs);
			for (int i = 0; i < attrs; ++i) {
				int size; GLSLType type; string name;
				GL.GetActiveAttrib(glprgm, unchecked((uint)i), out size,
						out type, out name);
				GL.Throw();
				int loc = GL.GetAttribLocation(glprgm, name);
				GL.Throw();

				Console.WriteLine("attrs["+i+"] = {size=" + size + ", type="
						+ type + ", name=" + name + ", loc="+loc+"}");
			}

			int unifs = GL.GetProgramiv(glprgm, GL.ACTIVE_UNIFORMS);
			GL.Throw();
			Console.WriteLine("#unifs = " + unifs);
			for (int i = 0; i < unifs; ++i) {
				int size; GLSLType type; string name;
				GL.GetActiveUniform(glprgm, unchecked((uint)i), out size,
						out type, out name);
				GL.Throw();
				int loc = GL.GetUniformLocation(glprgm, name);
				GL.Throw();

				Console.WriteLine("unifs["+i+"] = {size=" + size + ", type="
						+ type + ", name=" + name + ", loc="+loc+"}");
			}

			/* #attrs = 1
			 * attrs[0] = {size=1, type=FLOAT_VEC3, name=in_pos, loc=0}
			 * #unifs = 2
			 * unifs[0] = {size=1, type=FLOAT, name=fGlobalTime, loc=0}
			 * unifs[1] = {size=1, type=FLOAT_VEC2, name=v2Resolution, loc=1}
			 */
		}

181
182
183
184
		// TODO: find out a better (i.e. more API-conform) way to do this!
		///<summary>
		///USAGE: using (var eff &eq; glslEffect.Bind()) { ... gd.DrawPrimitives(...); ... }
		///</summary>
pcy's avatar
pcy committed
185
186
187
		public ActiveEffect Bind() { // TODO: how to warn on discarding the retval?
			GL.GetError(); // ignore errors from FNA/mojoshader

188
189
190
191
			// workaround FNA crap
			CurrentTechnique = fakeTech;
			fakeTech.Passes[0].Apply();

192
193
194
195
196
197
198
199
200
201
202
203
204
			uint oldprgm = unchecked((uint)GL.GetIntegerv(GL.CURRENT_PROGRAM));
			GL.Throw();

			GL.UseProgram(glprgm);
			GL.Throw();

			// TODO: apply uniforms and samplers! (XNA API -> OpenGL state)

			return new ActiveEffect(oldprgm);
		}
		[Obsolete("Please use Bind() instead")]
		public ActiveEffect Apply() { return Bind(); }

pcy's avatar
initial  
pcy committed
205
		void DelShdrPrgm() {
pcy's avatar
pcy committed
206
			for (int i = 0; glshdrs != null && i < glshdrs.Length; ++i)
207
208
				if (glshdrs[i] != 0)
					GL.DeleteShader(glshdrs[i]);
pcy's avatar
pcy committed
209
			glshdrs = null;
pcy's avatar
initial  
pcy committed
210

211
212
			if (glprgm != 0)
				GL.DeleteProgram(glprgm);
pcy's avatar
initial  
pcy committed
213
214
215
216
217
		}

		protected override void Dispose(bool disposing) {
			if (!IsDisposed) {
				DelShdrPrgm();
218
219
220

				this.SetTechniques(ReflUtil.CreateTechColl(new[]{fakeTech}.ToList()));
				fakeTech = null;
pcy's avatar
initial  
pcy committed
221
222
223
224
225
226
227
			}

			base.Dispose(disposing);
		}
	}
}