-
Notifications
You must be signed in to change notification settings - Fork 0
/
shader.go
97 lines (80 loc) · 2.16 KB
/
shader.go
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
package glutils
import (
"errors"
"github.com/pzsz/gl"
"io/ioutil"
"os"
"strings"
)
type Shader struct {
ShaderObject gl.Shader
Filename string
}
func newShader(filename string) (*Shader, error) {
var shaderType gl.GLenum
if strings.Index(filename, ".fragment") != -1 {
shaderType = gl.FRAGMENT_SHADER
} else {
shaderType = gl.VERTEX_SHADER
}
shader := &Shader{gl.CreateShader(shaderType), filename}
source, err := readShaderSource(filename)
if err != nil {
return nil, err
}
shader.ShaderObject.Source(source)
shader.ShaderObject.Compile()
if shader.ShaderObject.Get(gl.COMPILE_STATUS) == gl.FALSE {
info := shader.ShaderObject.GetInfoLog()
if info != "" {
return nil, errors.New("Error while compiling GLSL " + filename + ":\n" + info)
}
}
return shader, nil
}
func readShaderSource(filename string) (string, error) {
f, err := os.Open(filename)
if err != nil {
return "", err
}
defer f.Close()
ret, err := ioutil.ReadAll(f)
if err != nil {
return "", err
}
return string(ret), nil
}
type ShaderProgram struct {
Vertex *Shader
Fragment *Shader
ProgramObject gl.Program
}
func newShaderProgram(vertex, fragment *Shader) (*ShaderProgram, error) {
ret := &ShaderProgram{vertex, fragment, gl.CreateProgram()}
ret.ProgramObject.AttachShader(vertex.ShaderObject)
ret.ProgramObject.AttachShader(fragment.ShaderObject)
ret.ProgramObject.Link()
if ret.ProgramObject.Get(gl.LINK_STATUS) == gl.FALSE {
info := ret.ProgramObject.GetInfoLog()
if info != "" {
return nil, errors.New("Error while linking GLSL " + vertex.Filename + " with " + fragment.Filename + ": " + info)
}
}
ret.ProgramObject.Validate()
if ret.ProgramObject.Get(gl.VALIDATE_STATUS) == gl.FALSE {
info2 := ret.ProgramObject.GetInfoLog()
if info2 != "" {
return nil, errors.New("Error while linking GLSL " + vertex.Filename + " with " + fragment.Filename + ": " + info2)
}
}
return ret, nil
}
func (self *ShaderProgram) Use() {
self.ProgramObject.Use()
}
func (self *ShaderProgram) Unuse() {
gl.ProgramUnuse()
}
func (self *ShaderProgram) GetUniform(name string) gl.UniformLocation {
return self.ProgramObject.GetUniformLocation(name)
}