summaryrefslogtreecommitdiff
path: root/engine/Components/TextureManager.go
blob: eac1898182967c4d19573bb906c1b39c42e7f1b7 (plain)
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
package components

import (
	"encoding/json"
	"fmt"

	rl "github.com/gen2brain/raylib-go/raylib"
)

type TextrueManager struct {
	Textures []*rl.Texture2D
	NameToId map[string]uint64
}

// Loads the texture in the VRAM
func (base *TextrueManager) LoadTexture(path string, displayName string) {
	var image = rl.LoadImage(path)
	var texture = rl.LoadTextureFromImage(image)
	var id = len(base.Textures)
	base.Textures = append(base.Textures, &texture)
	base.NameToId[displayName] = uint64(id)
	rl.UnloadImage(image)
}

// Unloads all the textures from the VRAM
func (base *TextrueManager) UnloadAll() {
	for _, v := range base.Textures {
		rl.UnloadTexture(*v)
	}
}

func (base *TextrueManager) GetTexture(Id uint64) (*rl.Texture2D, error) {
	if Id >= uint64(len(base.Textures)) {
		return nil, fmt.Errorf("No texture loaded with that ID")
	}
	return base.Textures[Id], nil
}

func (base *TextrueManager) GetTextureByName(textureName string) (*rl.Texture2D, error) {
	var id, exists = base.NameToId[textureName]
	if !exists {
		return nil, fmt.Errorf("No such texture in the system")
	}
	return base.GetTexture(id)
}

func (base *TextrueManager) String() string {
	var outp, jsonErr = json.Marshal(base)
	if jsonErr != nil {
		return fmt.Sprintf("Failed to parse texture manager: %s", jsonErr.Error())
	}
	return string(outp)
}