forked from Tnze/go-mc
/
chunk.go
439 lines (398 loc) · 10.5 KB
/
chunk.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
package level
import (
"bytes"
"errors"
"fmt"
"io"
"math/bits"
"strconv"
"strings"
"github.com/SkyVillageMC/go-mc/level/biome"
"github.com/SkyVillageMC/go-mc/level/block"
"github.com/SkyVillageMC/go-mc/nbt"
pk "github.com/SkyVillageMC/go-mc/net/packet"
"github.com/SkyVillageMC/go-mc/save"
)
type ChunkPos [2]int32
func (c ChunkPos) WriteTo(w io.Writer) (n int64, err error) {
n, err = pk.Int(c[0]).WriteTo(w)
if err != nil {
return
}
n1, err := pk.Int(c[1]).WriteTo(w)
return n + n1, err
}
func (c *ChunkPos) ReadFrom(r io.Reader) (n int64, err error) {
var x, z pk.Int
if n, err = x.ReadFrom(r); err != nil {
return n, err
}
var n1 int64
if n1, err = z.ReadFrom(r); err != nil {
return n + n1, err
}
*c = ChunkPos{int32(x), int32(z)}
return n + n1, nil
}
type Chunk struct {
Sections []Section
HeightMaps HeightMaps
BlockEntity []BlockEntity
Status ChunkStatus
}
func EmptyChunk(secs int) *Chunk {
sections := make([]Section, secs)
for i := range sections {
sections[i] = Section{
BlockCount: 0,
States: NewStatesPaletteContainer(16*16*16, 0),
Biomes: NewBiomesPaletteContainer(4*4*4, 0),
}
}
return &Chunk{
Sections: sections,
HeightMaps: HeightMaps{
MotionBlocking: NewBitStorage(bits.Len(uint(secs)*16), 16*16, nil),
},
Status: StatusEmpty,
}
}
// ChunkFromSave convert save.Chunk to level.Chunk.
func ChunkFromSave(c *save.Chunk) (*Chunk, error) {
secs := len(c.Sections)
sections := make([]Section, secs)
for _, v := range c.Sections {
i := int32(v.Y) - c.YPos
if i < 0 || i >= int32(secs) {
return nil, fmt.Errorf("section Y value %d out of bounds", v.Y)
}
var err error
sections[i].States, err = readStatesPalette(v.BlockStates.Palette, v.BlockStates.Data)
if err != nil {
return nil, err
}
sections[i].BlockCount = countNoneAirBlocks(§ions[i])
sections[i].Biomes, err = readBiomesPalette(v.Biomes.Palette, v.Biomes.Data)
if err != nil {
return nil, err
}
sections[i].SkyLight = v.SkyLight
sections[i].BlockLight = v.BlockLight
}
blockEntities := make([]BlockEntity, len(c.BlockEntities))
for i, v := range c.BlockEntities {
var tmp struct {
ID string `nbt:"id"`
X int32 `nbt:"x"`
Y int32 `nbt:"y"`
Z int32 `nbt:"z"`
}
if err := v.Unmarshal(&tmp); err != nil {
return nil, err
}
blockEntities[i].Data = v
if x, z := int(tmp.X-c.XPos<<4), int(tmp.Z-c.ZPos<<4); !blockEntities[i].PackXZ(x, z) {
return nil, errors.New("Packing a XZ(" + strconv.Itoa(x) + ", " + strconv.Itoa(z) + ") out of bound")
}
blockEntities[i].Y = int16(tmp.Y)
blockEntities[i].Type = block.EntityTypes[tmp.ID]
}
motionBlocking := c.Heightmaps.MotionBlocking
motionBlockingNoLeaves := c.Heightmaps.MotionBlockingNoLeaves
oceanFloor := c.Heightmaps.OceanFloor
worldSurface := c.Heightmaps.WorldSurface
bitsForHeight := bits.Len( /* chunk height in blocks */ uint(secs) * 16)
return &Chunk{
Sections: sections,
HeightMaps: HeightMaps{
MotionBlocking: NewBitStorage(bitsForHeight, 16*16, motionBlocking),
MotionBlockingNoLeaves: NewBitStorage(bitsForHeight, 16*16, motionBlockingNoLeaves),
OceanFloor: NewBitStorage(bitsForHeight, 16*16, oceanFloor),
WorldSurface: NewBitStorage(bitsForHeight, 16*16, worldSurface),
},
BlockEntity: blockEntities,
Status: ChunkStatus(c.Status),
}, nil
}
func readStatesPalette(palette []save.BlockState, data []uint64) (paletteData *PaletteContainer[BlocksState], err error) {
statePalette := make([]BlocksState, len(palette))
for i, v := range palette {
b, ok := block.FromID[v.Name]
if !ok {
return nil, fmt.Errorf("unknown block id: %v", v.Name)
}
if v.Properties.Data != nil {
if err := v.Properties.Unmarshal(&b); err != nil {
return nil, fmt.Errorf("unmarshal block properties fail: %v", err)
}
}
s, ok := block.ToStateID[b]
if !ok {
return nil, fmt.Errorf("unknown block: %v", b)
}
statePalette[i] = s
}
paletteData = NewStatesPaletteContainerWithData(16*16*16, data, statePalette)
return
}
func readBiomesPalette(palette []string, data []uint64) (*PaletteContainer[BiomesState], error) {
biomesRawPalette := make([]BiomesState, len(palette))
var ok bool
for i, v := range palette {
biomesRawPalette[i], ok = biome.BiomesIDs[strings.TrimPrefix(v, "minecraft:")]
if !ok {
return nil, fmt.Errorf("unknown biomes: %s", v)
}
}
return NewBiomesPaletteContainerWithData(4*4*4, data, biomesRawPalette), nil
}
func countNoneAirBlocks(sec *Section) (blockCount int16) {
for i := 0; i < 16*16*16; i++ {
b := sec.GetBlock(i)
if !block.IsAir(b) {
blockCount++
}
}
return
}
// ChunkToSave convert level.Chunk to save.Chunk
func ChunkToSave(c *Chunk, dst *save.Chunk) (err error) {
secs := len(c.Sections)
sections := make([]save.Section, secs)
for i, v := range c.Sections {
s := §ions[i]
states := &s.BlockStates
biomes := &s.Biomes
s.Y = int8(int32(i) + dst.YPos)
states.Palette, states.Data, err = writeStatesPalette(v.States)
if err != nil {
return
}
biomes.Palette, biomes.Data = writeBiomesPalette(v.Biomes)
s.SkyLight = v.SkyLight
s.BlockLight = v.BlockLight
}
dst.Sections = sections
dst.Heightmaps.MotionBlocking = c.HeightMaps.MotionBlocking.Raw()
dst.Status = string(c.Status)
return
}
func writeStatesPalette(paletteData *PaletteContainer[BlocksState]) (palette []save.BlockState, data []uint64, err error) {
rawPalette := paletteData.palette.export()
palette = make([]save.BlockState, len(rawPalette))
var buffer bytes.Buffer
for i, v := range rawPalette {
b := block.StateList[v]
palette[i].Name = b.ID()
buffer.Reset()
err = nbt.NewEncoder(&buffer).Encode(b, "")
if err != nil {
return
}
_, err = nbt.NewDecoder(&buffer).Decode(&palette[i].Properties)
if err != nil {
return
}
}
data = append(data, paletteData.data.Raw()...)
return
}
func writeBiomesPalette(paletteData *PaletteContainer[BiomesState]) (palette []string, data []uint64) {
rawPalette := paletteData.palette.export()
palette = make([]string, len(rawPalette))
for i, v := range rawPalette {
palette[i] = biome.BiomesNames[v]
}
data = append(data, paletteData.data.Raw()...)
return
}
func (c *Chunk) WriteTo(w io.Writer) (int64, error) {
data, err := c.Data()
if err != nil {
return 0, err
}
light := lightData{
SkyLightMask: make(pk.BitSet, (16*16*16-1)>>6+1),
BlockLightMask: make(pk.BitSet, (16*16*16-1)>>6+1),
SkyLight: []pk.ByteArray{},
BlockLight: []pk.ByteArray{},
}
for i, v := range c.Sections {
if v.SkyLight != nil {
light.SkyLightMask.Set(i, true)
light.SkyLight = append(light.SkyLight, v.SkyLight)
}
if v.BlockLight != nil {
light.BlockLightMask.Set(i, true)
light.BlockLight = append(light.BlockLight, v.BlockLight)
}
}
return pk.Tuple{
// Heightmaps
pk.NBT(struct {
MotionBlocking []uint64 `nbt:"MOTION_BLOCKING"`
WorldSurface []uint64 `nbt:"WORLD_SURFACE"`
}{
MotionBlocking: c.HeightMaps.MotionBlocking.Raw(),
WorldSurface: c.HeightMaps.MotionBlocking.Raw(),
}),
pk.ByteArray(data),
pk.Array(c.BlockEntity),
&light,
}.WriteTo(w)
}
func (c *Chunk) ReadFrom(r io.Reader) (int64, error) {
var (
heightmaps struct {
MotionBlocking []uint64 `nbt:"MOTION_BLOCKING"`
WorldSurface []uint64 `nbt:"WORLD_SURFACE"`
}
data pk.ByteArray
)
n, err := pk.Tuple{
pk.NBT(&heightmaps),
&data,
pk.Array(&c.BlockEntity),
&lightData{
SkyLightMask: make(pk.BitSet, (16*16*16-1)>>6+1),
BlockLightMask: make(pk.BitSet, (16*16*16-1)>>6+1),
SkyLight: []pk.ByteArray{},
BlockLight: []pk.ByteArray{},
},
}.ReadFrom(r)
if err != nil {
return n, err
}
err = c.PutData(data)
return n, err
}
func (c *Chunk) Data() ([]byte, error) {
var buff bytes.Buffer
for i := range c.Sections {
_, err := c.Sections[i].WriteTo(&buff)
if err != nil {
return nil, err
}
}
return buff.Bytes(), nil
}
func (c *Chunk) PutData(data []byte) error {
r := bytes.NewReader(data)
for i := range c.Sections {
_, err := c.Sections[i].ReadFrom(r)
if err != nil {
return err
}
}
return nil
}
type HeightMaps struct {
MotionBlocking *BitStorage
MotionBlockingNoLeaves *BitStorage
OceanFloor *BitStorage
WorldSurface *BitStorage
}
type BlockEntity struct {
XZ int8
Y int16
Type block.EntityType
Data nbt.RawMessage
}
func (b BlockEntity) UnpackXZ() (X, Z int) {
return int((uint8(b.XZ) >> 4) & 0xF), int(uint8(b.XZ) & 0xF)
}
func (b *BlockEntity) PackXZ(X, Z int) bool {
if X > 0xF || Z > 0xF || X < 0 || Z < 0 {
return false
}
b.XZ = int8(X<<4 | Z)
return true
}
func (b BlockEntity) WriteTo(w io.Writer) (n int64, err error) {
return pk.Tuple{
pk.Byte(b.XZ),
pk.Short(b.Y),
pk.VarInt(b.Type),
pk.NBT(b.Data),
}.WriteTo(w)
}
func (b *BlockEntity) ReadFrom(r io.Reader) (n int64, err error) {
return pk.Tuple{
(*pk.Byte)(&b.XZ),
(*pk.Short)(&b.Y),
(*pk.VarInt)(&b.Type),
pk.NBT(&b.Data),
}.ReadFrom(r)
}
type Section struct {
BlockCount int16
States *PaletteContainer[BlocksState]
Biomes *PaletteContainer[BiomesState]
// Half a byte per light value.
// Could be nil if not exist
SkyLight []byte // len() == 2048
BlockLight []byte // len() == 2048
}
func (s *Section) GetBlock(i int) BlocksState {
return s.States.Get(i)
}
func (s *Section) SetBlock(i int, v BlocksState) {
if !block.IsAir(s.States.Get(i)) {
s.BlockCount--
}
if !block.IsAir(v) {
s.BlockCount++
}
s.States.Set(i, v)
}
func (s *Section) WriteTo(w io.Writer) (int64, error) {
return pk.Tuple{
pk.Short(s.BlockCount),
s.States,
s.Biomes,
}.WriteTo(w)
}
func (s *Section) ReadFrom(r io.Reader) (int64, error) {
return pk.Tuple{
(*pk.Short)(&s.BlockCount),
s.States,
s.Biomes,
}.ReadFrom(r)
}
type lightData struct {
SkyLightMask pk.BitSet
BlockLightMask pk.BitSet
SkyLight []pk.ByteArray
BlockLight []pk.ByteArray
}
func bitSetRev(set pk.BitSet) pk.BitSet {
rev := make(pk.BitSet, len(set))
for i := range rev {
rev[i] = ^set[i]
}
return rev
}
func (l *lightData) WriteTo(w io.Writer) (int64, error) {
return pk.Tuple{
pk.Boolean(true), // Trust Edges
l.SkyLightMask,
l.BlockLightMask,
bitSetRev(l.SkyLightMask),
bitSetRev(l.BlockLightMask),
pk.Array(l.SkyLight),
pk.Array(l.BlockLight),
}.WriteTo(w)
}
func (l *lightData) ReadFrom(r io.Reader) (int64, error) {
var TrustEdges pk.Boolean
var RevSkyLightMask, RevBlockLightMask pk.BitSet
return pk.Tuple{
&TrustEdges, // Trust Edges
&l.SkyLightMask,
&l.BlockLightMask,
&RevSkyLightMask,
&RevBlockLightMask,
pk.Array(&l.SkyLight),
pk.Array(&l.BlockLight),
}.ReadFrom(r)
}