summaryrefslogtreecommitdiff
path: root/mcmap/regionfile.go
blob: 1be08ea198e8f5ae74fec81e0ef64894885fae4b (plain)
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
package mcmap

import (
	"bytes"
	"encoding/binary"
	"github.com/kch42/kagus"
	"io"
	"time"
)

const sectorSize = 4096

type chunkOffTs struct {
	offset, size int64
	ts           time.Time
}

func (cOff chunkOffTs) readPreChunk(r io.ReadSeeker) (*preChunk, error) {
	pc := preChunk{ts: cOff.ts}

	if _, err := r.Seek(cOff.offset, 0); err != nil {
		return nil, err
	}

	lr := io.LimitReader(r, cOff.size)

	var length uint32
	if err := binary.Read(lr, binary.BigEndian, &length); err != nil {
		return nil, err
	}
	lr = io.LimitReader(lr, int64(length))

	compType, err := kagus.ReadByte(lr)
	if err != nil {
		return nil, err
	}
	pc.compression = compType

	buf := new(bytes.Buffer)
	if _, err := io.Copy(buf, lr); err != nil {
		return nil, err
	}
	pc.data = buf.Bytes()

	return &pc, err

}

func readRegionFile(r io.ReadSeeker) (map[XZPos]*preChunk, error) {
	if _, err := r.Seek(0, 0); err != nil {
		return nil, err
	}

	offs := make(map[XZPos]*chunkOffTs)

	for z := 0; z < 32; z++ {
		for x := 0; x < 32; x++ {
			var location uint32
			if err := binary.Read(r, binary.BigEndian, &location); err != nil {
				return nil, err
			}

			if location == 0 {
				continue
			}

			offs[XZPos{x, z}] = &chunkOffTs{
				offset: int64((location >> 8) * sectorSize),
				size:   int64((location & 0xff) * sectorSize),
			}
		}
	}

	for z := 0; z < 32; z++ {
		for x := 0; x < 32; x++ {
			pos := XZPos{x, z}

			var ts int32
			if err := binary.Read(r, binary.BigEndian, &ts); err != nil {
				return nil, err
			}

			if _, ok := offs[pos]; !ok {
				continue
			}

			offs[pos].ts = time.Unix(int64(ts), 0)
		}
	}

	preChunks := make(map[XZPos]*preChunk)
	for pos, cOff := range offs {
		pc, err := cOff.readPreChunk(r)
		if err != nil {
			return nil, err
		}
		preChunks[pos] = pc
	}

	return preChunks, nil
}