summaryrefslogtreecommitdiff
path: root/mcmap/region.go
blob: 93c8693d2d281992cda7a0c95b8216de549cd8ae (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
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
package mcmap

import (
	"errors"
	"fmt"
	"math"
	"os"
	"regexp"
	"strconv"
)

var (
	NotAvailable = errors.New("Chunk or Superchunk not available")
	AlreadyThere = errors.New("Chunk is already there")
)

type superchunk struct {
	preChunks map[XZPos]*preChunk
	chunks    map[XZPos]*Chunk
	modified  bool
}

type Region struct {
	path             string
	autosave         bool
	superchunksAvail map[XZPos]bool
	superchunks      map[XZPos]*superchunk
}

var mcaRegex = regexp.MustCompile(`^r\.([0-9-]+)\.([0-9-]+)\.mca$`)

// OpenRegion opens a region directory. If autosave is true, mcmap will save modified and unloaded chunks automatically to reduce memory usage. You still have to call Save at the end.
//
// You can also use OpenRegion to create a new region. Yust make sure the path exists.
func OpenRegion(path string, autosave bool) (*Region, error) {
	rv := &Region{
		path:             path,
		superchunksAvail: make(map[XZPos]bool),
		superchunks:      make(map[XZPos]*superchunk),
	}

	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	fi, err := f.Stat()
	if err != nil {
		return nil, err
	}

	if !fi.IsDir() {
		return nil, fmt.Errorf("%s is not a directory", path)
	}

	names, err := f.Readdirnames(-1)
	if err != nil {
		return nil, err
	}
	for _, name := range names {
		match := mcaRegex.FindStringSubmatch(name)
		if len(match) == 3 {
			// We ignore the error here. The Regexp already ensures that the inputs are numbers.
			x, _ := strconv.ParseInt(match[1], 10, 32)
			z, _ := strconv.ParseInt(match[2], 10, 32)

			rv.superchunksAvail[XZPos{int(x), int(z)}] = true
		}
	}

	return rv, nil
}

// MaxDims calculates the approximate maximum x, z dimensions of this region in number of chunks. The actual maximum dimensions might be a bit smaller.
func (reg *Region) MaxDims() (xmin, xmax, zmin, zmax int) {
	if len(reg.superchunksAvail) == 0 {
		return 0, 0, 0, 0
	}

	xmin = math.MaxInt32
	zmin = math.MaxInt32
	xmax = math.MinInt32
	zmax = math.MinInt32

	for pos := range reg.superchunksAvail {
		if pos.X < xmin {
			xmin = pos.X
		}
		if pos.Z < zmin {
			zmin = pos.Z
		}
		if pos.X > xmax {
			xmax = pos.X
		}
		if pos.Z > zmax {
			zmax = pos.Z
		}
	}

	xmax++
	zmax++
	xmin *= superchunkSizeXZ
	xmax *= superchunkSizeXZ
	zmin *= superchunkSizeXZ
	zmax *= superchunkSizeXZ
	return
}

func chunkToSuperchunk(cx, cz int) (scx, scz, rx, rz int) {
	scx = cx >> 5
	scz = cz >> 5
	rx = ((cx % superchunkSizeXZ) + superchunkSizeXZ) % superchunkSizeXZ
	rz = ((cz % superchunkSizeXZ) + superchunkSizeXZ) % superchunkSizeXZ
	return
}

func superchunkToChunk(scx, scz, rx, rz int) (cx, cz int) {
	cx = scx*superchunkSizeXZ + rx
	cz = scz*superchunkSizeXZ + rz
	return
}

func (reg *Region) loadSuperchunk(pos XZPos) error {
	if !reg.superchunksAvail[pos] {
		return NotAvailable
	}
	fname := fmt.Sprintf("%s%cr.%d.%d.mca", reg.path, os.PathSeparator, pos.X, pos.Z)

	f, err := os.Open(fname)
	if err != nil {
		return err
	}
	defer f.Close()

	pcs, err := readRegionFile(f)
	if err != nil {
		return err
	}

	reg.superchunks[pos] = &superchunk{
		preChunks: pcs,
		chunks:    make(map[XZPos]*Chunk),
	}
	return nil
}

func (reg *Region) cleanSuperchunks(forceSave bool) error {
	del := make(map[XZPos]bool)

	for scPos, sc := range reg.superchunks {
		if len(sc.chunks) > 0 {
			continue
		}

		if sc.modified {
			if !(reg.autosave || forceSave) {
				continue
			}

			fn := fmt.Sprintf("%s%cr.%d.%d.mca", reg.path, os.PathSeparator, scPos.X, scPos.Z)

			if len(sc.preChunks) == 0 {
				if err := os.Remove(fn); err != nil {
					return err
				}
			} else {
				f, err := os.Create(fn)
				if err != nil {
					return err
				}
				defer f.Close()

				if err := writeRegionFile(f, sc.preChunks); err != nil {
					return err
				}
			}
		}

		del[scPos] = true
	}

	for scPos, _ := range del {
		delete(reg.superchunks, scPos)
	}

	return nil
}

func (sc *superchunk) loadChunk(reg *Region, rx, rz int) (*Chunk, error) {
	cPos := XZPos{rx, rz}

	if chunk, ok := sc.chunks[cPos]; ok {
		return chunk, nil
	}

	pc, ok := sc.preChunks[cPos]
	if !ok {
		return nil, NotAvailable
	}

	chunk, err := pc.toChunk(reg)
	if err != nil {
		return nil, err
	}
	sc.chunks[cPos] = chunk
	return chunk, nil
}

// Chunk returns the chunk at x, z. If no chunk could be found, the error NotAvailable will be returned. Other errors indicate an internal error (I/O error, file format violated, ...)
func (reg *Region) Chunk(x, z int) (*Chunk, error) {
	scx, scz, cx, cz := chunkToSuperchunk(x, z)
	scPos := XZPos{scx, scz}

	sc, ok := reg.superchunks[scPos]
	if !ok {
		if err := reg.loadSuperchunk(scPos); err != nil {
			return nil, err
		}
		sc = reg.superchunks[scPos]
	}

	chunk, err := sc.loadChunk(reg, cx, cz)
	if err != nil {
		return nil, err
	}

	if err := reg.cleanSuperchunks(false); err != nil {
		return nil, err
	}

	return chunk, nil
}

func (reg *Region) unloadChunk(x, z int) error {
	scx, scz, cx, cz := chunkToSuperchunk(x, z)
	scPos := XZPos{scx, scz}
	cPos := XZPos{cx, cz}

	sc, ok := reg.superchunks[scPos]
	if !ok {
		return nil
	}

	chunk, ok := sc.chunks[cPos]
	if !ok {
		return nil
	}

	if chunk.deleted {
		delete(sc.preChunks, cPos)
		sc.modified = true
	} else if chunk.modified {
		pc, err := chunk.toPreChunk()
		if err != nil {
			return err
		}
		sc.preChunks[cPos] = pc

		chunk.modified = false
		sc.modified = true
	}

	delete(sc.chunks, cPos)

	return nil
}

// AllChunks returns a channel that will give you the positions of all possibly available chunks in an efficient order.
//
// Note the "possibly available", you still have to check, if the chunk could actually be loaded.
func (reg *Region) AllChunks() <-chan XZPos {
	ch := make(chan XZPos)
	go func(ch chan<- XZPos) {
		for spos, _ := range reg.superchunksAvail {
			scx, scz := spos.X, spos.Z
			for rx := 0; rx < superchunkSizeXZ; rx++ {
				for rz := 0; rz < superchunkSizeXZ; rz++ {
					cx, cz := superchunkToChunk(scx, scz, rx, rz)
					ch <- XZPos{cx, cz}
				}
			}
		}
		close(ch)
	}(ch)

	return ch
}

// NewChunk adds a new, blank chunk. If the Chunk is already there, error AlreadyThere will be returned.
// Other errors indicate internal errors.
func (reg *Region) NewChunk(cx, cz int) (*Chunk, error) {
	scx, scz, rx, rz := chunkToSuperchunk(cx, cz)

	scPos := XZPos{scx, scz}

	var sc *superchunk
	if reg.superchunksAvail[scPos] {
		var ok bool
		if sc, ok = reg.superchunks[scPos]; !ok {
			if err := reg.loadSuperchunk(scPos); err != nil {
				return nil, err
			}
			sc = reg.superchunks[scPos]
		}
	} else {
		sc = &superchunk{
			chunks:    make(map[XZPos]*Chunk),
			preChunks: make(map[XZPos]*preChunk),
			modified:  true,
		}
		reg.superchunksAvail[scPos] = true
		reg.superchunks[scPos] = sc
	}

	switch chunk, err := sc.loadChunk(reg, rx, rz); err {
	case nil:
		chunk.MarkUnused()
		return nil, AlreadyThere
	case NotAvailable:
	default:
		return nil, err
	}

	cPos := XZPos{rx, rz}
	chunk := newChunk(reg, cx, cz)

	pc, err := chunk.toPreChunk()
	if err != nil {
		return nil, err
	}

	sc.preChunks[cPos] = pc
	sc.chunks[cPos] = chunk
	sc.modified = true

	return chunk, nil
}

// Save saves modified and unused chunks.
func (reg *Region) Save() error {
	return reg.cleanSuperchunks(true)
}