/
textures.go
96 lines (82 loc) · 2.23 KB
/
textures.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
package gogl
import (
"image"
"image/png"
"os"
"github.com/go-gl/gl/v3.3-core/gl"
)
type TextureID uint32
func LoadTexture(filename string) TextureID {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
defer file.Close()
img, err := png.Decode(file)
if err != nil {
panic(err)
}
w := img.Bounds().Max.X
h := img.Bounds().Max.Y
pixels := make([]byte, w*h*4)
i := 0
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
r, g, b, a := img.At(x, y).RGBA()
pixels[i] = byte(r / 256)
i++
pixels[i] = byte(g / 256)
i++
pixels[i] = byte(b / 256)
i++
pixels[i] = byte(a / 256)
i++
}
}
texture := GenBindTexture()
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, int32(w), int32(h), 0, gl.RGBA, gl.UNSIGNED_BYTE, gl.Ptr(pixels))
gl.GenerateMipmap(gl.TEXTURE_2D)
return texture
}
func LoadTextureFromImage(img image.Image) TextureID {
w := img.Bounds().Max.X
h := img.Bounds().Max.Y
pixels := make([]byte, w*h*4)
i := 0
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
r, g, b, a := img.At(x, y).RGBA()
pixels[i] = byte(r / 256)
i++
pixels[i] = byte(g / 256)
i++
pixels[i] = byte(b / 256)
i++
pixels[i] = byte(a / 256)
i++
}
}
texture := GenBindTexture()
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, int32(w), int32(h), 0, gl.RGBA, gl.UNSIGNED_BYTE, gl.Ptr(pixels))
gl.GenerateMipmap(gl.TEXTURE_2D)
return texture
}
// generates a new nexture ID and binds it to gl.TEXTURE_2D
func GenBindTexture() TextureID {
var textureId uint32
gl.GenTextures(1, &textureId)
gl.BindTexture(gl.TEXTURE_2D, textureId)
return TextureID(textureId)
}
// binds a texture to gl.TEXTURE_2D from its texture id
func BindTexture(id TextureID) {
gl.BindTexture(gl.TEXTURE_2D, uint32(id))
}