/
packer.go
203 lines (162 loc) · 4.58 KB
/
packer.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package sxtp
import (
"fmt"
"github.com/disintegration/imaging"
"golang.org/x/sync/errgroup"
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
)
type FileFormat string
const (
FormatPNG FileFormat = "png"
FormatJPG FileFormat = "jpg"
)
var (
supportedFormats = [...]FileFormat{FormatPNG, FormatJPG}
)
// PackMasks packs a set of secondary textures using the atlas layouts passed in
func PackMasks(atlasPages []Atlas, format FileFormat, masksPath, outputPath, suffix string, hasAlpha bool, l *log.Logger) error {
maskImages, err := getImageNames(masksPath)
if err != nil {
return err
}
var wg errgroup.Group
for i, atlas := range atlasPages {
i, atlas := i, &atlas
wg.Go(func() error {
noExtName := strings.TrimSuffix(atlas.Name, filepath.Ext(atlas.Name))
maskFileName := fmt.Sprintf("%s_%s_%02d.%s", noExtName, suffix, i, format)
outFileName := filepath.Join(outputPath, maskFileName)
return packPage(atlas, maskImages, format, outFileName, hasAlpha, l)
})
}
return wg.Wait()
}
func packPage(atlas *Atlas, maskImages map[string]string, format FileFormat, outputPath string, hasAlpha bool, l *log.Logger) error {
outImage := image.NewNRGBA(image.Rectangle{Max: atlas.Size})
packedCount := 0
for _, sprite := range atlas.Sprites {
maskImagePath, ok := maskImages[sprite.Name]
if !ok {
l.Printf("Skipped %s since packed images path does not contain it", sprite.Name)
continue
}
maskImage, err := loadImage(maskImagePath, l)
if err != nil {
return err
}
maskImage = imaging.Rotate(maskImage, sprite.Rotate.Degrees(), color.NRGBA{})
maskImage = cropAndOffset(maskImage, sprite)
spriteRect := image.Rectangle{Min: sprite.Bounds.Position, Max: sprite.Bounds.Position.Add(maskImage.Bounds().Size())}
draw.Draw(outImage, spriteRect, maskImage, image.Point{}, draw.Over) // TODO might need to use DrawMask, and mask with color image alpha
if !hasAlpha {
stripAlpha(outImage)
}
packedCount++
}
if err := saveImage(outputPath, outImage, format, l); err != nil {
return err
}
l.Printf("Packed %d sprites to %s\n", packedCount, outputPath)
return nil
}
func rotateCoord(pt image.Point) image.Point {
return image.Pt(pt.Y, pt.X)
}
func cropAndOffset(img image.Image, sprite Sprite) image.Image {
if sprite.Offsets.Offset.Eq(image.Point{}) && sprite.Bounds.Size.Eq(sprite.Offsets.OriginalSize) {
return img
}
size := sprite.Bounds.Size
orig := sprite.Offsets.OriginalSize
offset := sprite.Offsets.Offset
var newRect image.Rectangle
var sp image.Point
if sprite.Rotate == 90 {
newRect = image.Rectangle{Max: rotateCoord(size)}
sp = rotateCoord(orig.Sub(size).Sub(offset))
} else {
newRect = image.Rectangle{Max: size}
sp = image.Pt(offset.X, orig.Y-size.Y-offset.Y)
}
cropped := image.NewNRGBA(newRect)
draw.Draw(cropped, cropped.Rect, img, sp, draw.Over)
return cropped
}
func stripAlpha(img *image.NRGBA) {
bounds := img.Bounds()
width, height := bounds.Max.X, bounds.Max.Y
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
c := img.NRGBAAt(x, y)
c.A = 0xff
img.SetNRGBA(x, y, c)
}
}
}
func getImageNames(path string) (map[string]string, error) {
images := make([]string, 0)
err := filepath.Walk(path, func(p string, info fs.FileInfo, err error) error {
ext := filepath.Ext(p)
for _, format := range supportedFormats {
if fmt.Sprintf(".%s", format) == ext {
images = append(images, p)
break
}
}
return nil
})
if err != nil {
return nil, err
}
mapping := make(map[string]string, len(images))
for _, img := range images {
name, err := filepath.Rel(path, img)
if err != nil {
return nil, err
}
name = strings.TrimSuffix(name, filepath.Ext(name))
mapping[name] = img
}
return mapping, nil
}
func loadImage(path string, l *log.Logger) (image.Image, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer closeWithLoggedError(f, l)
img, _, err := image.Decode(f)
return img, err
}
func saveImage(path string, img image.Image, format FileFormat, l *log.Logger) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer closeWithLoggedError(f, l)
switch format {
case FormatPNG:
encoder := png.Encoder{CompressionLevel: png.NoCompression}
return encoder.Encode(f, img)
case FormatJPG:
options := jpeg.Options{Quality: 100}
return jpeg.Encode(f, img, &options)
default:
return fmt.Errorf("invalid file format, got: %q expected: png or jpg", format)
}
}
func closeWithLoggedError(c io.Closer, l *log.Logger) {
if err := c.Close(); err != nil {
l.Println(err)
}
}