GLSLEffect.cs 5.21 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
54
		EffectTechnique fakeTech;

		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
106
107
108

			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);
						var msg = new sbyte[len];
						fixed (sbyte* buf = msg) {
							GL.GetShaderInfoLog(sh, len, null, buf);
pcy's avatar
pcy committed
109
110
							throw new GLSLCompileException("Failed to compile "
									+ kvp.Key + ": " + new String(buf, 0, len-1));
pcy's avatar
initial  
pcy committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
						}
					}

					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);
					var msg = new sbyte[len];
					fixed (sbyte* buf = msg) {
						GL.GetProgramInfoLog(prgm, len, null, buf);
pcy's avatar
pcy committed
126
127
						throw new GLSLLinkException("Failed to link shader: "
								+ new String(buf, 0, len-1));
pcy's avatar
initial  
pcy committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
					}
				}

				ok = true;
			}
			finally {
				if (!ok) {
					DelShdrPrgm();
				} else {
					glshdrs = shdrs;
					glprgm  = prgm ;
				}
			}
		}

143
144
145
146
		// 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
147
148
149
		public ActiveEffect Bind() { // TODO: how to warn on discarding the retval?
			GL.GetError(); // ignore errors from FNA/mojoshader

150
151
152
153
			// workaround FNA crap
			CurrentTechnique = fakeTech;
			fakeTech.Passes[0].Apply();

154
155
156
157
158
159
160
161
162
163
164
165
166
			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
167
		void DelShdrPrgm() {
pcy's avatar
pcy committed
168
			for (int i = 0; glshdrs != null && i < glshdrs.Length; ++i)
169
170
				if (glshdrs[i] != 0)
					GL.DeleteShader(glshdrs[i]);
pcy's avatar
pcy committed
171
			glshdrs = null;
pcy's avatar
initial  
pcy committed
172

173
174
			if (glprgm != 0)
				GL.DeleteProgram(glprgm);
pcy's avatar
initial  
pcy committed
175
176
177
178
179
		}

		protected override void Dispose(bool disposing) {
			if (!IsDisposed) {
				DelShdrPrgm();
180
181
182

				this.SetTechniques(ReflUtil.CreateTechColl(new[]{fakeTech}.ToList()));
				fakeTech = null;
pcy's avatar
initial  
pcy committed
183
184
185
186
187
188
189
			}

			base.Dispose(disposing);
		}
	}
}