-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
555 lines (492 loc) · 13 KB
/
main.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
package gseprite
import (
"bufio"
"bytes"
"compress/zlib"
"encoding/hex"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
"image/gif"
"io"
"log"
"os"
"unsafe"
"github.com/mandykoh/prism/meta/icc"
)
func readString(file *io.Reader) string {
var Size uint16
if _, err := (*file).Read((*[2]byte)(unsafe.Pointer(&Size))[:]); err != nil {
log.Println(err)
}
buffer := make([]byte, Size)
if _, err := (*file).Read(buffer); err != nil {
log.Println(err)
}
return string(buffer)
}
type Header struct {
FileSize uint32
Magic uint16
Frames uint16
Width uint16
Height uint16
ColorDepth uint16 // Color depth (bits per pixel) 32 bpp = RGBA 16 bpp = Grayscale 8 bpp = Indexed
Flags uint32 // 1 = Layer opacity has valid value
Speed uint16 // DEPRECATED
reserved1 uint32
reserved2 uint32
Palette byte
ignore [3]byte
NumberOfColor uint16
PixelWidth byte // Pixel width (pixel ratio is "pixel width/pixel height"). If this or pixel height field is zero, pixel ratio is 1:1
PixelHeight byte // Pixel height
GridX int16 // X position of the grid
GridY int16 // Y position of the grid
GridWidth uint16 // Grid width (zero if there is no grid, grid size is 16x16 on Aseprite by default)
GridHeight uint16 // Grid height (zero if there is no grid)
reserved3 [84]byte
}
type Frame struct {
Size uint32
Magic uint16
NumberOfChunk uint16
Duration uint16
reserved [2]byte
NumberOfChunk2 uint32
// NonBytesFields
Chunks []Chunk
Gseprite *Gseprite
}
func readFrame(file io.Reader, g *Gseprite) (*Frame, error) {
var f Frame
f.Gseprite = g
file.Read((*[16]byte)(unsafe.Pointer(&f))[:])
if f.Magic != 0xF1FA {
return nil, errors.New("Magic code of frame checked failed")
}
var maxChunk int
if f.NumberOfChunk == 0xFFFF {
maxChunk = int(f.NumberOfChunk2)
} else {
maxChunk = int(f.NumberOfChunk)
}
for i := 0; i < maxChunk; i++ {
//log.Printf("chunk %d of %d", i, maxChunk)
f.Chunks = append(f.Chunks, readChunk(file, g))
}
return &f, nil
}
type ChunkType uint16
const (
ChunkTypeOldPalette4 ChunkType = 0x0004
ChunkTypeOldPalette11 ChunkType = 0x0011
ChunkTypeLayer ChunkType = 0x2004
ChunkTypeCel ChunkType = 0x2005
ChunkTypeCelExtra ChunkType = 0x2006
ChunkTypeColorProfile ChunkType = 0x2007
ChunkTypeMask ChunkType = 0x2016 // DEPRECATED
ChunkTypePath ChunkType = 0x2017 // Never used.
ChunkTypeFrameTags ChunkType = 0x2018
ChunkTypePalette ChunkType = 0x2019
ChunkTypeUserData ChunkType = 0x2020
ChunkTypeSlice ChunkType = 0x2022
ChunkTypeTileset ChunkType = 0x2023
)
func (e ChunkType) String() string {
switch e {
case ChunkTypeOldPalette4:
return "OldPalette4"
case ChunkTypeOldPalette11:
return "OldPalette11"
case ChunkTypeLayer:
return "Layer"
case ChunkTypeCel:
return "Cel"
case ChunkTypeCelExtra:
return "CelExtra"
case ChunkTypeColorProfile:
return "ColorProfile"
case ChunkTypeMask:
return "Mask"
case ChunkTypePath:
return "Path"
case ChunkTypeFrameTags:
return "FrameTags"
case ChunkTypePalette:
return "Palette"
case ChunkTypeUserData:
return "UserData"
case ChunkTypeSlice:
return "Slice"
case ChunkTypeTileset:
return "Tileset"
default:
return fmt.Sprintf("%d", int(e))
}
}
type Chunk interface {
ChunkType() ChunkType
}
type chunk struct {
Size uint32
Type ChunkType
Data []byte
}
func (c chunk) ChunkType() ChunkType {
return c.Type
}
func readChunk(file io.Reader, g *Gseprite) Chunk {
var c chunk
file.Read((*[6]byte)(unsafe.Pointer(&c))[:])
c.Data = make([]byte, c.Size-6)
file.Read(c.Data)
switch c.Type {
case ChunkTypePalette:
return readPalette(bytes.NewReader(c.Data), g)
case ChunkTypeLayer:
return readLayer(bytes.NewReader(c.Data), g)
case ChunkTypeCel:
return readCel(bytes.NewReader(c.Data), g)
case ChunkTypeColorProfile:
return readColorProfile(bytes.NewReader(c.Data), g)
case ChunkTypeOldPalette4:
return readOldPalette4(bytes.NewReader(c.Data), g)
case ChunkTypeFrameTags:
return readFrameTags(bytes.NewReader(c.Data), g)
default:
log.Panicln("Not support type: ", c.Type, "\n", hex.Dump(c.Data))
}
return c
}
type Gseprite struct {
Header Header
Frames []*Frame
Layers []*Layer
Palette *Palette
FrameTags *FrameTags
// For Sprites render
curtime float64
curframe int
// For Tag Render
prevTag string
tag_curtime float64
tag_curframe uint16
}
// Render current image, param is Duration, should be 1000/FPS
func (g *Gseprite) SpritesRender(Duration float64) image.Image {
g.curtime += Duration
if g.curtime > float64(g.Frames[g.curframe].Duration) {
g.curtime -= float64(g.Frames[g.curframe].Duration)
g.curframe++
g.curframe %= len(g.Frames)
}
return g.Frames[g.curframe].Render()
}
// Render current image by tag, param is Duration, should be 1000/FPS
func (g *Gseprite) SpritesTagRender(tagname string, Duration float64) (image.Image, error) {
tag, ok := g.FrameTags.M[tagname]
if !ok {
return nil, NoFound
}
if g.prevTag != tagname {
g.prevTag = tagname
g.tag_curframe = 0
g.tag_curtime = 0
}
g.curtime += Duration
if g.curtime > float64(g.Frames[int(tag.From+g.tag_curframe)].Duration) {
g.curtime -= float64(g.Frames[int(tag.From+g.tag_curframe)].Duration)
g.tag_curframe++
g.tag_curframe %= tag.To - tag.From + 1
}
log.Println("Render", g.tag_curframe)
return g.Frames[int(tag.From+g.tag_curframe)].Render(), nil
}
// Get this Aseprite image file Rectangle
func (g Gseprite) Rect() image.Rectangle {
return image.Rectangle{
Min: image.Point{X: 0, Y: 0},
Max: image.Point{X: int(g.Header.Width), Y: int(g.Header.Height)},
}
}
// Render frame to single image
func (f *Frame) Render() image.Image {
rect := f.Gseprite.Rect()
ret := image.NewNRGBA(rect)
NextChunk:
for _, c := range f.Chunks {
if c.ChunkType() == ChunkTypeCel {
var tmp interface{}
tmp = c
cel := tmp.(*Cel)
layer := f.Gseprite.Layers[cel.LayerIndex]
var lwalker *Layer = layer
for lwalker != nil {
if lwalker.Flags&LayerFlagsVisible == 0 {
continue NextChunk
}
lwalker = lwalker.parent
}
if cel.Image == nil {
continue
} // this cel do not contain image
// TODO: Should check Blend mode
//fmt.Println("話", cel.Opacity, cel.Y, cel.X, rect, layer.Name)
draw.Draw(ret, rect, cel, image.Point{X: int(-cel.X), Y: int(-cel.Y)}, draw.Over)
}
}
return ret
}
// Create GIF file
func (g Gseprite) GIF() gif.GIF {
var ret gif.GIF
for _, frame := range g.Frames {
img := frame.Render()
var palette color.Palette = color.Palette{
image.Transparent,
}
for _, v := range g.Palette.Colors {
palette = append(palette, v)
}
palettedImage := image.NewPaletted(g.Rect(), palette)
draw.Draw(palettedImage, palettedImage.Rect, img, g.Rect().Min, draw.Over)
ret.Image = append(ret.Image, palettedImage)
ret.Delay = append(ret.Delay, int(frame.Duration)/10)
ret.Disposal = append(ret.Disposal, gif.DisposalPrevious)
}
return ret
}
type LayerFlags uint16
const (
LayerFlagsVisible LayerFlags = 1
LayerFlagsEditable LayerFlags = 2
LayerFlagsLockMovement LayerFlags = 4
LayerFlagsBackground LayerFlags = 8
LayerFlagsPreferLinkedCels LayerFlags = 16
LayerFlagsCollapsedGroup LayerFlags = 32
LayerFlagsReference LayerFlags = 64
)
type LayerType uint16
const (
LayerTypeNormal LayerType = 0
LayerTypeGroup LayerType = 1
LayerTypeTilemap LayerType = 2
)
type Layer struct {
Flags LayerFlags
Type LayerType
ChildLevel uint16
width uint16 //Ignore
height uint16 //Ignore
Blend uint16 // always 0
Opacity uint8
reserved [3]byte
Name string
// This field is for fast to know which parent group set unvisable
parent *Layer
}
func (p *Layer) ChunkType() ChunkType {
return ChunkTypeLayer
}
func readLayer(file io.Reader, g *Gseprite) *Layer {
var p Layer
file.Read((*[16]byte)(unsafe.Pointer(&p))[:])
p.Name = readString(&file)
return &p
}
// Load Aseprite file
func LoadAseprite(filename string) (*Gseprite, error) {
var g Gseprite
if f, err := os.Open(filename); err != nil {
return nil, err
} else {
defer f.Close()
f.Read((*[128]byte)(unsafe.Pointer(&g.Header))[:])
if g.Header.Magic != 0xA5E0 {
return nil, errors.New("Magic code check failed")
}
for i := 0; i < int(g.Header.Frames); i++ {
if frame, err := readFrame(f, &g); err != nil {
return nil, err
} else {
g.Frames = append(g.Frames, frame)
}
}
for _, chunk := range g.Frames[0].Chunks {
var tmp interface{}
switch chunk.ChunkType() {
case ChunkTypePalette:
tmp = chunk
g.Palette = tmp.(*Palette)
case ChunkTypeLayer:
tmp = chunk
g.Layers = append(g.Layers, tmp.(*Layer))
}
}
// Create layer parent
var stack []*Layer = nil
var curgroup *Layer
for _, l := range g.Layers {
for curgroup != nil && l.ChildLevel <= curgroup.ChildLevel {
if len(stack) == 0 {
curgroup = nil
} else {
curgroup = stack[len(stack)-1]
stack = stack[:len(stack)-1]
}
}
if curgroup != nil && l.ChildLevel == curgroup.ChildLevel+1 {
l.parent = curgroup
}
if l.Type == LayerTypeGroup {
stack = append(stack, curgroup)
curgroup = l
}
if curgroup != nil && l.ChildLevel > curgroup.ChildLevel+1 {
l.parent = curgroup
}
}
}
return &g, nil
}
type CelType uint16
const (
CelTypeRaw CelType = 0
CelTypeLinked CelType = 1
CelTypeCompressed CelType = 2
CelTypeCompressedTilemap CelType = 3
)
// Cel determine where to put a cel in the specified layer/frame
type Cel struct {
LayerIndex uint16
X int16
Y int16
Opacity byte
Type CelType
reserved [7]byte
Image image.Image
// Non structlize field
ColorDepth uint16
}
func (c *Cel) ChunkType() ChunkType {
return ChunkTypeCel
}
func (c *Cel) ColorModel() color.Model {
switch c.ColorDepth {
case 8:
return color.AlphaModel
case 16:
return color.GrayModel
case 32:
return color.NRGBAModel
}
return color.NRGBAModel
}
func (c *Cel) Bounds() image.Rectangle {
return c.Image.Bounds()
}
func (c *Cel) At(x, y int) color.Color {
return c.Image.At(x, y)
}
func readCel(file io.Reader, g *Gseprite) *Cel {
var p Cel
file.Read((*[16]byte)(unsafe.Pointer(&p))[:])
p.ColorDepth = g.Header.ColorDepth
switch p.Type {
case CelTypeRaw, CelTypeCompressed:
var Height, Width uint16
file.Read((*[2]byte)(unsafe.Pointer(&Width))[:])
file.Read((*[2]byte)(unsafe.Pointer(&Height))[:])
if Height*Width == 0 {
return &p
}
img := image.NewRGBA(image.Rect(0, 0, int(Height), int(Width)))
p.Image = img
switch g.Header.ColorDepth {
case 8:
img.Pix = make([]byte, Height*Width*4)
buffer := make([]byte, Height*Width)
r, _ := zlib.NewReader(file)
r.Read(buffer)
r.Close()
img.Stride = int(Width) * 4
img.Rect = image.Rectangle{
Min: image.Point{X: 0, Y: 0},
Max: image.Point{X: int(Width), Y: int(Height)},
}
for y := 0; y < int(Height); y++ {
for x := 0; x < int(Width); x++ {
pindex := int(buffer[y*int(Width)+x])
if pindex == 0 {
continue
}
img.Set(x, y, g.Palette.Colors[pindex])
}
}
case 16:
img.Pix = make([]byte, Height*Width*4)
buffer := make([]byte, Height*Width*2)
r, _ := zlib.NewReader(file)
r.Read(buffer)
r.Close()
img.Stride = int(Width) * 4
img.Rect = image.Rectangle{
Min: image.Point{X: 0, Y: 0},
Max: image.Point{X: int(Width), Y: int(Height)},
}
for i := 0; i < int(Height*Width)*2; i += 2 {
img.Pix[i*4] = buffer[i*2]
img.Pix[i*4+1] = buffer[i*2]
img.Pix[i*4+2] = buffer[i*2]
img.Pix[i*4+3] = buffer[i*2+1]
}
case 32:
img.Pix = make([]byte, Height*Width*4)
r, _ := zlib.NewReader(file)
r.Read(img.Pix)
r.Close()
img.Stride = int(Width) * 4
img.Rect = image.Rectangle{
Min: image.Point{X: 0, Y: 0},
Max: image.Point{X: int(Width), Y: int(Height)},
}
}
case CelTypeLinked:
}
return &p
}
type fixed16_16 int32
func (i fixed16_16) Get() float64 {
return float64(i) / 65536.0
}
type ColorProfile struct {
Type uint16 //0 - no color profile (as in old .aseprite files) 1 - use sRGB 2 - use the embedded ICC profile
Flags uint16 // 1 - use special fixed gamma
/* FixedGamma: Fixed gamma (1.0 = linear)
Note: The gamma in sRGB is 2.2 in overall but it doesn''t use
this fixed gamma, because sRGB uses different gamma sections
(linear and non-linear). If sRGB is specified with a fixed
gamma = 1.0, it means that this is Linear sRGB.
*/
FixedGamma fixed16_16
reserved [8]byte
// If type = ICC:
iccprofile *icc.Profile
}
func (c ColorProfile) ChunkType() ChunkType {
return ChunkTypeColorProfile
}
func readColorProfile(file io.Reader, g *Gseprite) *ColorProfile {
var p ColorProfile
var err error
file.Read((*[16]byte)(unsafe.Pointer(&p))[:])
if p.Type == 2 {
pf := icc.NewProfileReader(bufio.NewReader(file))
p.iccprofile, err = pf.ReadProfile()
log.Panicln(err)
}
return &p
}