Opentk 튜토리얼 2---셰이더
Opentk チュートリアル 2---シェーダー
Opentk教學2---shader
using OpenTK.Graphics.OpenGL4; using OpenTK.Mathematics; public class Shader { public int Handle; private readonly Dictionary<string, int> _uniformLocations; public Shader(string vert_src, string frag_src) { var shaderSource = vert_src; var vertexShader = GL.CreateShader(ShaderType.VertexShader); GL.ShaderSource(vertexShader, shaderSource); CompileShader(vertexShader); shaderSource = frag_src; var fragmentShader = GL.CreateShader(ShaderType.FragmentShader); GL.ShaderSource(fragmentShader, shaderSource); CompileShader(fragmentShader); Handle = GL.CreateProgram(); GL.AttachShader(Handle, vertexShader); GL.AttachShader(Handle, fragmentShader); LinkProgram(Handle); GL.DetachShader(Handle, vertexShader); GL.DetachShader(Handle, fragmentShader); GL.DeleteShader(fragmentShader); GL.DeleteShader(vertexShader); GL.GetProgram(Handle, GetProgramParameterName.ActiveUniforms, out var numberOfUniforms); _uniformLocations = new Dictionary<string, int>(); for (int i = 0; i < numberOfUniforms; i++) { var key = GL.GetActiveUniform(Handle, i, out _, out _); var location = GL.GetUniformLocation(Handle, key); _uniformLocations.Add(key, location); } } private static void CompileShader(int shader) { GL.CompileShader(shader); GL.GetShader(shader, ShaderParameter.CompileStatus, out var code); if (code != (int)All.True) { var infoLog = GL.GetShaderInfoLog(shader); throw new Exception($"Error occurred whilst compiling Shader({shader}).\n\n{infoLog}"); } } private static void LinkProgram(int program) { GL.LinkProgram(program); GL.GetProgram(program, GetProgramParameterName.LinkStatus, out var code); if (code != (int)All.True) { throw new Exception($"Error occurred whilst linking Program({program})"); } } public void Use() { GL.UseProgram(Handle); } public void UnUse() { GL.UseProgram(0); } public int GetAttribLocation(string attribName) { return GL.GetAttribLocation(Handle, attribName); } public int Get_index(string name) { return _uniformLocations[name]; } public void SetInt_index(int index, int value) { GL.UseProgram(Handle); GL.Uniform1(index, value); } public void SetInt(string name, int data) { GL.UseProgram(Handle); GL.Uniform1(_uniformLocations[name], data); } public void SetFloat(string name, float data) { GL.UseProgram(Handle); GL.Uniform1(_uniformLocations[name], data); } public void SetFloat_index(int index, float value) { GL.UseProgram(Handle); GL.Uniform1(index, value); } public void SetMatrix4(string name, Matrix4 data) { GL.UseProgram(Handle); GL.UniformMatrix4(_uniformLocations[name], true, ref data); } public void SetVector3(string name, Vector3 data) { GL.UseProgram(Handle); GL.Uniform3(_uniformLocations[name], data); } public void SetVector2(string name, Vector2 data) { GL.UseProgram(Handle); GL.Uniform2(_uniformLocations[name], data); } public bool is_contain(String key) { return _uniformLocations.ContainsKey(key); } public void Delete() { GL.DeleteProgram(Handle); } }
沒有留言:
張貼留言