-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtexture.go
More file actions
79 lines (65 loc) · 1.57 KB
/
texture.go
File metadata and controls
79 lines (65 loc) · 1.57 KB
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
package main
import (
"fmt"
"image"
"image/draw"
_ "image/png"
"os"
"github.com/go-gl/gl/v3.3-core/gl"
)
type Texture struct {
Path string
RGBA *image.RGBA
ID uint32
}
func LoadTexture(path string) (*Texture, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("texture %q not found on disk: %v", path, err)
}
m, _, err := image.Decode(file)
if err != nil {
return nil, fmt.Errorf("unable to decode texture %q: %v", path, err)
}
rgba := image.NewRGBA(m.Bounds())
if rgba.Stride != rgba.Rect.Size().X*4 {
return nil, fmt.Errorf("unsupported stride")
}
draw.Draw(rgba, rgba.Bounds(), m, image.Point{0, 0}, draw.Src)
texture := &Texture{}
texture.Path = path
texture.RGBA = rgba
texture.upload()
return texture, nil
}
func (texture *Texture) upload() {
if texture.ID != 0 {
texture.delete()
}
gl.GenTextures(1, &texture.ID)
gl.ActiveTexture(gl.TEXTURE0)
gl.BindTexture(gl.TEXTURE_2D, texture.ID)
gl.TexImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
int32(texture.RGBA.Rect.Dx()),
int32(texture.RGBA.Rect.Dy()),
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
gl.Ptr(texture.RGBA.Pix))
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
}
func (texture *Texture) delete() {
gl.DeleteTextures(1, &texture.ID)
texture.ID = 0
}
func (texture *Texture) Destroy() {
texture.delete()
texture.RGBA = nil
texture.Path = ""
}