-
Notifications
You must be signed in to change notification settings - Fork 0
/
sprite.go
113 lines (95 loc) · 1.96 KB
/
sprite.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 Andy Frank Schoknecht
//go:generate go ./geninfo.go
package main
import (
"fmt"
"path/filepath"
"github.com/veandco/go-sdl2/sdl"
"github.com/veandco/go-sdl2/img"
"github.com/veandco/go-sdl2/ttf"
)
type Sprite struct {
renderer *sdl.Renderer
surface *sdl.Surface
texture *sdl.Texture
Rect sdl.Rect
}
func newSprite(renderer *sdl.Renderer) Sprite {
var ret = Sprite {
renderer: renderer,
}
return ret
}
func (s *Sprite) InitFromAsset(appPath string, assetPath string) {
var (
err error
fullpath string
pathPrefixes = []string{
appPath,
filepath.Join(appPath, "images"),
filepath.Join(appPath, AppName + "_data", "images"),
}
)
fullpath = getFilepathFromPaths(pathPrefixes, assetPath)
if fullpath == "" {
panic(fmt.Sprintf("Image not found in asset paths: %v\n",
pathPrefixes))
}
s.surface, err = img.Load(fullpath)
if err != nil {
panic(err)
}
s.texture, err = s.renderer.CreateTextureFromSurface(s.surface)
if err != nil {
panic(err)
}
s.Rect.W = s.surface.W
s.Rect.H = s.surface.H
}
func (s *Sprite) InitFromText(
text string,
colors []sdl.Color,
fonts []*ttf.Font,
) {
var (
err error
allS []*sdl.Surface
)
for i := len(fonts) - 1; i >= 0; i-- {
temp, err := fonts[i].RenderUTF8Solid(text, colors[i])
if err != nil {
panic(err)
}
allS = append(allS, temp)
}
for i := len(allS) - 1; i >= 1; i-- {
rect := sdl.Rect{
X: gfxTextOutlineSize,
Y: gfxTextOutlineSize,
W: allS[0].W,
H: allS[0].H,
}
err = allS[i].Blit(nil, allS[0], &rect)
if err != nil {
panic(err)
}
}
s.surface = allS[0]
s.texture, err = s.renderer.CreateTextureFromSurface(s.surface)
if err != nil {
panic(err)
}
s.Rect.W = s.surface.W
s.Rect.H = s.surface.H
}
func (s *Sprite) Draw() {
err := s.renderer.Copy(s.texture, nil, &s.Rect)
if err != nil {
panic(err)
}
}
func (s *Sprite) Free() {
s.surface.Free()
s.texture.Destroy()
}