-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtiles.go
85 lines (62 loc) · 1.81 KB
/
tiles.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
package gfx
import "image"
// Tiles is a slice of paletted images.
type Tiles []PalettedImage
// Tileset is a paletted tileset.
type Tileset struct {
Palette Palette // Palette of the tileset.
Size image.Point // Size is the size of each tile.
Tiles Tiles // Images contains all of the images in the tileset.
}
// TilesetData is the raw data in a tileset
type TilesetData [][]uint8
// NewTileset creates a new paletted tileset.
func NewTileset(p Palette, s image.Point, td TilesetData) *Tileset {
ts := &Tileset{Palette: p, Size: s}
for i := 0; i < len(td); i++ {
ts.Tiles = append(ts.Tiles, NewTile(p, s.X, td[i]))
}
return ts
}
// NewTilesetFromImage creates a new paletted tileset based on the provided palette, tile size and image.
func NewTilesetFromImage(p Palette, tileSize image.Point, src image.Image) *Tileset {
cols := src.Bounds().Dx() / tileSize.X
rows := src.Bounds().Dy() / tileSize.Y
tiles := make(Tiles, cols*rows)
for row := 0; row < rows; row++ {
for col := 0; col < cols; col++ {
t := NewPaletted(tileSize.X, tileSize.Y, p)
DrawSrc(t, t.Bounds(), src, Pt(col*tileSize.X, row*tileSize.Y))
i := (row * cols) + col
tiles[i] = t
}
}
return &Tileset{Palette: p, Size: tileSize, Tiles: tiles}
}
// NewTile returns a new paletted image with the given pix, stride and palette.
func NewTile(p Palette, cols int, pix []uint8) *Paletted {
return &Paletted{
Palette: p,
Stride: cols,
Pix: pix,
Rect: calcRect(cols, pix),
}
}
func calcRect(cols int, pix []uint8) image.Rectangle {
s := calcSize(cols, pix)
return IR(0, 0, s.X, s.Y)
}
func calcSize(cols int, pix []uint8) image.Point {
l := len(pix)
if l < cols {
return Pt(cols, 1)
}
rows := l / cols
if rows*cols == l {
return Pt(cols, rows)
}
if rows%cols > 0 {
rows++
}
return Pt(cols, rows)
}