-
Notifications
You must be signed in to change notification settings - Fork 0
/
shader.go
61 lines (52 loc) · 1.45 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
package shader
import (
"bytes"
"embed"
"fmt"
"io/fs"
"text/template"
)
//go:embed common/*.glsl ui/*.glsl game/*.glsl
var sources embed.FS
func shaderDir(name string) fs.FS {
subDir, err := fs.Sub(sources, name)
if err != nil {
panic(fmt.Errorf("error opening %q shaders: %w", name, err))
}
return subDir
}
// Common returns a filesystem containing common shaders.
func Common() fs.FS {
return shaderDir("common")
}
// UI returns a filesystem containing UI shaders.
func UI() fs.FS {
return shaderDir("ui")
}
// Game returns a filesystem containing game shaders.
func Game() fs.FS {
return shaderDir("game")
}
// ConstructFunc creates a shader from a template with the given name and data.
type ConstructFunc func(name string, data any) string
// Load loads all shaders from the given filesystems and returns a
// ConstructFunc that can be used to construct shaders from the loaded
// templates.
func Load(sources ...fs.FS) ConstructFunc {
rootTemplate := template.New("root").Delims("/*", "*/")
for _, source := range sources {
rootTemplate = template.Must(rootTemplate.ParseFS(source, "*.glsl"))
}
buffer := new(bytes.Buffer)
return func(name string, data any) string {
tmpl := rootTemplate.Lookup(name)
if tmpl == nil {
panic(fmt.Errorf("template %q not found", name))
}
buffer.Reset()
if err := tmpl.Execute(buffer, data); err != nil {
panic(fmt.Errorf("template %q exec error: %w", name, err))
}
return buffer.String()
}
}