-
Notifications
You must be signed in to change notification settings - Fork 81
/
infiniteworld.py
1845 lines (1380 loc) · 60.9 KB
/
infiniteworld.py
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Created on Jul 22, 2011
@author: Rio
'''
import copy
from datetime import datetime
import itertools
from logging import getLogger
from math import floor
import os
import re
import random
import shutil
import struct
import time
import traceback
import weakref
import zlib
import sys
import blockrotation
from box import BoundingBox
from entity import Entity, TileEntity
from faces import FaceXDecreasing, FaceXIncreasing, FaceZDecreasing, FaceZIncreasing
from level import LightedChunk, EntityLevel, computeChunkHeightMap, MCLevel, ChunkBase
from materials import alphaMaterials
from mclevelbase import ChunkMalformed, ChunkNotPresent, exhaust, PlayerNotFound
import nbt
from numpy import array, clip, maximum, zeros
from regionfile import MCRegionFile
log = getLogger(__name__)
DIM_NETHER = -1
DIM_END = 1
__all__ = ["ZeroChunk", "AnvilChunk", "ChunkedLevelMixin", "MCInfdevOldLevel", "MCAlphaDimension", "ZipSchematic"]
_zeros = {}
class SessionLockLost(IOError):
pass
def ZeroChunk(height=512):
z = _zeros.get(height)
if z is None:
z = _zeros[height] = _ZeroChunk(height)
return z
class _ZeroChunk(ChunkBase):
" a placebo for neighboring-chunk routines "
def __init__(self, height=512):
zeroChunk = zeros((16, 16, height), 'uint8')
whiteLight = zeroChunk + 15
self.Blocks = zeroChunk
self.BlockLight = whiteLight
self.SkyLight = whiteLight
self.Data = zeroChunk
def unpackNibbleArray(dataArray):
s = dataArray.shape
unpackedData = zeros((s[0], s[1], s[2] * 2), dtype='uint8')
unpackedData[:, :, ::2] = dataArray
unpackedData[:, :, ::2] &= 0xf
unpackedData[:, :, 1::2] = dataArray
unpackedData[:, :, 1::2] >>= 4
return unpackedData
def packNibbleArray(unpackedData):
packedData = array(unpackedData.reshape(16, 16, unpackedData.shape[2] / 2, 2))
packedData[..., 1] <<= 4
packedData[..., 1] |= packedData[..., 0]
return array(packedData[:, :, :, 1])
def sanitizeBlocks(chunk):
# change grass to dirt where needed so Minecraft doesn't flip out and die
grass = chunk.Blocks == chunk.materials.Grass.ID
grass |= chunk.Blocks == chunk.materials.Dirt.ID
badgrass = grass[:, :, 1:] & grass[:, :, :-1]
chunk.Blocks[:, :, :-1][badgrass] = chunk.materials.Dirt.ID
# remove any thin snow layers immediately above other thin snow layers.
# minecraft doesn't flip out, but it's almost never intended
if hasattr(chunk.materials, "SnowLayer"):
snowlayer = chunk.Blocks == chunk.materials.SnowLayer.ID
badsnow = snowlayer[:, :, 1:] & snowlayer[:, :, :-1]
chunk.Blocks[:, :, 1:][badsnow] = chunk.materials.Air.ID
class AnvilChunkData(object):
""" This is the chunk data backing an AnvilChunk. Chunk data is retained by the MCInfdevOldLevel until its
AnvilChunk is no longer used, then it is either cached in memory, discarded, or written to disk according to
resource limits.
AnvilChunks are stored in a WeakValueDictionary so we can find out when they are no longer used by clients. The
AnvilChunkData for an unused chunk may safely be discarded or written out to disk. The client should probably
not keep references to a whole lot of chunks or else it will run out of memory.
"""
def __init__(self, world, chunkPosition, root_tag = None, create = False):
self.chunkPosition = chunkPosition
self.world = world
self.root_tag = root_tag
self.dirty = False
self.Blocks = zeros((16, 16, world.Height), 'uint16')
self.Data = zeros((16, 16, world.Height), 'uint8')
self.BlockLight = zeros((16, 16, world.Height), 'uint8')
self.SkyLight = zeros((16, 16, world.Height), 'uint8')
self.SkyLight[:] = 15
if create:
self._create()
else:
self._load(root_tag)
levelTag = self.root_tag["Level"]
if "Biomes" not in levelTag:
levelTag["Biomes"] = nbt.TAG_Byte_Array(zeros((16, 16), 'uint8'))
levelTag["Biomes"].value[:] = -1
def _create(self):
(cx, cz) = self.chunkPosition
chunkTag = nbt.TAG_Compound()
chunkTag.name = ""
levelTag = nbt.TAG_Compound()
chunkTag["Level"] = levelTag
levelTag["HeightMap"] = nbt.TAG_Int_Array(zeros((16, 16), 'uint32').newbyteorder())
levelTag["TerrainPopulated"] = nbt.TAG_Byte(1)
levelTag["xPos"] = nbt.TAG_Int(cx)
levelTag["zPos"] = nbt.TAG_Int(cz)
levelTag["LastUpdate"] = nbt.TAG_Long(0)
levelTag["Entities"] = nbt.TAG_List()
levelTag["TileEntities"] = nbt.TAG_List()
self.root_tag = chunkTag
self.dirty = True
def _load(self, root_tag):
self.root_tag = root_tag
for sec in self.root_tag["Level"].pop("Sections", []):
y = sec["Y"].value * 16
for name in "Blocks", "Data", "SkyLight", "BlockLight":
arr = getattr(self, name)
secarray = sec[name].value
if name == "Blocks":
secarray.shape = (16, 16, 16)
else:
secarray.shape = (16, 16, 8)
secarray = unpackNibbleArray(secarray)
arr[..., y:y + 16] = secarray.swapaxes(0, 2)
tag = sec.get("Add")
if tag is not None:
tag.value.shape = (16, 16, 8)
add = unpackNibbleArray(tag.value)
self.Blocks[...,y:y + 16] |= (array(add, 'uint16') << 8).swapaxes(0, 2)
def savedTagData(self):
""" does not recalculate any data or light """
log.debug(u"Saving chunk: {0}".format(self))
sanitizeBlocks(self)
sections = nbt.TAG_List()
for y in range(0, self.world.Height, 16):
section = nbt.TAG_Compound()
Blocks = self.Blocks[..., y:y + 16].swapaxes(0, 2)
Data = self.Data[..., y:y + 16].swapaxes(0, 2)
BlockLight = self.BlockLight[..., y:y + 16].swapaxes(0, 2)
SkyLight = self.SkyLight[..., y:y + 16].swapaxes(0, 2)
if (not Blocks.any() and
not BlockLight.any() and
(SkyLight == 15).all()):
continue
Data = packNibbleArray(Data)
BlockLight = packNibbleArray(BlockLight)
SkyLight = packNibbleArray(SkyLight)
add = Blocks >> 8
if add.any():
section["Add"] = nbt.TAG_Byte_Array(packNibbleArray(add).astype('uint8'))
section['Blocks'] = nbt.TAG_Byte_Array(array(Blocks, 'uint8'))
section['Data'] = nbt.TAG_Byte_Array(array(Data))
section['BlockLight'] = nbt.TAG_Byte_Array(array(BlockLight))
section['SkyLight'] = nbt.TAG_Byte_Array(array(SkyLight))
section["Y"] = nbt.TAG_Byte(y / 16)
sections.append(section)
self.root_tag["Level"]["Sections"] = sections
data = self.root_tag.save(compressed=False)
del self.root_tag["Level"]["Sections"]
log.debug(u"Saved chunk {0}".format(self))
return data
@property
def materials(self):
return self.world.materials
class AnvilChunk(LightedChunk):
""" This is a 16x16xH chunk in an (infinite) world.
The properties Blocks, Data, SkyLight, BlockLight, and Heightmap
are ndarrays containing the respective blocks in the chunk file.
Each array is indexed [x,z,y]. The Data, Skylight, and BlockLight
arrays are automatically unpacked from nibble arrays into byte arrays
for better handling.
"""
def __init__(self, chunkData):
self.world = chunkData.world
self.chunkPosition = chunkData.chunkPosition
self.chunkData = chunkData
def savedTagData(self):
return self.chunkData.savedTagData()
def __str__(self):
return u"AnvilChunk, coords:{0}, world: {1}, D:{2}, L:{3}".format(self.chunkPosition, self.world.displayName, self.dirty, self.needsLighting)
@property
def needsLighting(self):
return self.chunkPosition in self.world.chunksNeedingLighting
@needsLighting.setter
def needsLighting(self, value):
if value:
self.world.chunksNeedingLighting.add(self.chunkPosition)
else:
self.world.chunksNeedingLighting.discard(self.chunkPosition)
def generateHeightMap(self):
if self.world.dimNo == DIM_NETHER:
self.HeightMap[:] = 0
else:
computeChunkHeightMap(self.materials, self.Blocks, self.HeightMap)
def addEntity(self, entityTag):
def doubleize(name):
# This is needed for compatibility with Indev levels. Those levels use TAG_Float for entity motion and pos
if name in entityTag:
m = entityTag[name]
entityTag[name] = nbt.TAG_List([nbt.TAG_Double(i.value) for i in m])
doubleize("Motion")
doubleize("Position")
self.dirty = True
return super(AnvilChunk, self).addEntity(entityTag)
def removeEntitiesInBox(self, box):
self.dirty = True
return super(AnvilChunk, self).removeEntitiesInBox(box)
def removeTileEntitiesInBox(self, box):
self.dirty = True
return super(AnvilChunk, self).removeTileEntitiesInBox(box)
# --- AnvilChunkData accessors ---
@property
def root_tag(self):
return self.chunkData.root_tag
@property
def dirty(self):
return self.chunkData.dirty
@dirty.setter
def dirty(self, val):
self.chunkData.dirty = val
# --- Chunk attributes ---
@property
def materials(self):
return self.world.materials
@property
def Blocks(self):
return self.chunkData.Blocks
@property
def Data(self):
return self.chunkData.Data
@property
def SkyLight(self):
return self.chunkData.SkyLight
@property
def BlockLight(self):
return self.chunkData.BlockLight
@property
def Biomes(self):
return self.root_tag["Level"]["Biomes"].value.reshape((16, 16))
@property
def HeightMap(self):
return self.root_tag["Level"]["HeightMap"].value.reshape((16, 16))
@property
def Entities(self):
return self.root_tag["Level"]["Entities"]
@property
def TileEntities(self):
return self.root_tag["Level"]["TileEntities"]
@property
def TerrainPopulated(self):
return self.root_tag["Level"]["TerrainPopulated"].value
@TerrainPopulated.setter
def TerrainPopulated(self, val):
"""True or False. If False, the game will populate the chunk with
ores and vegetation on next load"""
self.root_tag["Level"]["TerrainPopulated"].value = val
self.dirty = True
base36alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
def decbase36(s):
return int(s, 36)
def base36(n):
global base36alphabet
n = int(n)
if 0 == n:
return '0'
neg = ""
if n < 0:
neg = "-"
n = -n
work = []
while n:
n, digit = divmod(n, 36)
work.append(base36alphabet[digit])
return neg + ''.join(reversed(work))
def deflate(data):
# zobj = zlib.compressobj(6,zlib.DEFLATED,-zlib.MAX_WBITS,zlib.DEF_MEM_LEVEL,0)
# zdata = zobj.compress(data)
# zdata += zobj.flush()
# return zdata
return zlib.compress(data)
def inflate(data):
return zlib.decompress(data)
class ChunkedLevelMixin(MCLevel):
def blockLightAt(self, x, y, z):
if y < 0 or y >= self.Height:
return 0
zc = z >> 4
xc = x >> 4
xInChunk = x & 0xf
zInChunk = z & 0xf
ch = self.getChunk(xc, zc)
return ch.BlockLight[xInChunk, zInChunk, y]
def setBlockLightAt(self, x, y, z, newLight):
if y < 0 or y >= self.Height:
return 0
zc = z >> 4
xc = x >> 4
xInChunk = x & 0xf
zInChunk = z & 0xf
ch = self.getChunk(xc, zc)
ch.BlockLight[xInChunk, zInChunk, y] = newLight
ch.chunkChanged(False)
def blockDataAt(self, x, y, z):
if y < 0 or y >= self.Height:
return 0
zc = z >> 4
xc = x >> 4
xInChunk = x & 0xf
zInChunk = z & 0xf
try:
ch = self.getChunk(xc, zc)
except ChunkNotPresent:
return 0
return ch.Data[xInChunk, zInChunk, y]
def setBlockDataAt(self, x, y, z, newdata):
if y < 0 or y >= self.Height:
return 0
zc = z >> 4
xc = x >> 4
xInChunk = x & 0xf
zInChunk = z & 0xf
try:
ch = self.getChunk(xc, zc)
except ChunkNotPresent:
return 0
ch.Data[xInChunk, zInChunk, y] = newdata
ch.dirty = True
ch.needsLighting = True
def blockAt(self, x, y, z):
"""returns 0 for blocks outside the loadable chunks. automatically loads chunks."""
if y < 0 or y >= self.Height:
return 0
zc = z >> 4
xc = x >> 4
xInChunk = x & 0xf
zInChunk = z & 0xf
try:
ch = self.getChunk(xc, zc)
except ChunkNotPresent:
return 0
return ch.Blocks[xInChunk, zInChunk, y]
def setBlockAt(self, x, y, z, blockID):
"""returns 0 for blocks outside the loadable chunks. automatically loads chunks."""
if y < 0 or y >= self.Height:
return 0
zc = z >> 4
xc = x >> 4
xInChunk = x & 0xf
zInChunk = z & 0xf
try:
ch = self.getChunk(xc, zc)
except ChunkNotPresent:
return 0
ch.Blocks[xInChunk, zInChunk, y] = blockID
ch.dirty = True
ch.needsLighting = True
def skylightAt(self, x, y, z):
if y < 0 or y >= self.Height:
return 0
zc = z >> 4
xc = x >> 4
xInChunk = x & 0xf
zInChunk = z & 0xf
ch = self.getChunk(xc, zc)
return ch.SkyLight[xInChunk, zInChunk, y]
def setSkylightAt(self, x, y, z, lightValue):
if y < 0 or y >= self.Height:
return 0
zc = z >> 4
xc = x >> 4
xInChunk = x & 0xf
zInChunk = z & 0xf
ch = self.getChunk(xc, zc)
skyLight = ch.SkyLight
oldValue = skyLight[xInChunk, zInChunk, y]
ch.chunkChanged(False)
if oldValue < lightValue:
skyLight[xInChunk, zInChunk, y] = lightValue
return oldValue < lightValue
createChunk = NotImplemented
def generateLights(self, dirtyChunkPositions=None):
return exhaust(self.generateLightsIter(dirtyChunkPositions))
def generateLightsIter(self, dirtyChunkPositions=None):
""" dirtyChunks may be an iterable yielding (xPos,zPos) tuples
if none, generate lights for all chunks that need lighting
"""
startTime = datetime.now()
if dirtyChunkPositions is None:
dirtyChunkPositions = self.chunksNeedingLighting
else:
dirtyChunkPositions = (c for c in dirtyChunkPositions if self.containsChunk(*c))
dirtyChunkPositions = sorted(dirtyChunkPositions)
maxLightingChunks = getattr(self, 'loadedChunkLimit', 400)
log.info(u"Asked to light {0} chunks".format(len(dirtyChunkPositions)))
chunkLists = [dirtyChunkPositions]
def reverseChunkPosition((cx, cz)):
return cz, cx
def splitChunkLists(chunkLists):
newChunkLists = []
for l in chunkLists:
# list is already sorted on x position, so this splits into left and right
smallX = l[:len(l) / 2]
bigX = l[len(l) / 2:]
# sort halves on z position
smallX = sorted(smallX, key=reverseChunkPosition)
bigX = sorted(bigX, key=reverseChunkPosition)
# add quarters to list
newChunkLists.append(smallX[:len(smallX) / 2])
newChunkLists.append(smallX[len(smallX) / 2:])
newChunkLists.append(bigX[:len(bigX) / 2])
newChunkLists.append(bigX[len(bigX) / 2:])
return newChunkLists
while len(chunkLists[0]) > maxLightingChunks:
chunkLists = splitChunkLists(chunkLists)
if len(chunkLists) > 1:
log.info(u"Using {0} batches to conserve memory.".format(len(chunkLists)))
# batchSize = min(len(a) for a in chunkLists)
estimatedTotals = [len(a) * 32 for a in chunkLists]
workDone = 0
for i, dc in enumerate(chunkLists):
log.info(u"Batch {0}/{1}".format(i, len(chunkLists)))
dc = sorted(dc)
workTotal = sum(estimatedTotals)
t = 0
for c, t, p in self._generateLightsIter(dc):
yield c + workDone, t + workTotal - estimatedTotals[i], p
estimatedTotals[i] = t
workDone += t
timeDelta = datetime.now() - startTime
if len(dirtyChunkPositions):
log.info(u"Completed in {0}, {1} per chunk".format(timeDelta, dirtyChunkPositions and timeDelta / len(dirtyChunkPositions) or 0))
return
def _generateLightsIter(self, dirtyChunkPositions):
la = array(self.materials.lightAbsorption)
clip(la, 1, 15, la)
dirtyChunks = set(self.getChunk(*cPos) for cPos in dirtyChunkPositions)
workDone = 0
workTotal = len(dirtyChunks) * 29
progressInfo = (u"Lighting {0} chunks".format(len(dirtyChunks)))
log.info(progressInfo)
for i, chunk in enumerate(dirtyChunks):
chunk.chunkChanged()
yield i, workTotal, progressInfo
assert chunk.dirty and chunk.needsLighting
workDone += len(dirtyChunks)
workTotal = len(dirtyChunks)
for ch in list(dirtyChunks):
# relight all blocks in neighboring chunks in case their light source disappeared.
cx, cz = ch.chunkPosition
for dx, dz in itertools.product((-1, 0, 1), (-1, 0, 1)):
try:
ch = self.getChunk(cx + dx, cz + dz)
except (ChunkNotPresent, ChunkMalformed):
continue
dirtyChunks.add(ch)
ch.dirty = True
dirtyChunks = sorted(dirtyChunks, key=lambda x: x.chunkPosition)
workTotal += len(dirtyChunks) * 28
for i, chunk in enumerate(dirtyChunks):
chunk.BlockLight[:] = self.materials.lightEmission[chunk.Blocks]
chunk.dirty = True
zeroChunk = ZeroChunk(self.Height)
zeroChunk.BlockLight[:] = 0
zeroChunk.SkyLight[:] = 0
startingDirtyChunks = dirtyChunks
oldLeftEdge = zeros((1, 16, self.Height), 'uint8')
oldBottomEdge = zeros((16, 1, self.Height), 'uint8')
oldChunk = zeros((16, 16, self.Height), 'uint8')
if self.dimNo in (-1, 1):
lights = ("BlockLight",)
else:
lights = ("BlockLight", "SkyLight")
log.info(u"Dispersing light...")
def clipLight(light):
# light arrays are all uint8 by default, so when results go negative
# they become large instead. reinterpret as signed int using view()
# and then clip to range
light.view('int8').clip(0, 15, light)
for j, light in enumerate(lights):
zerochunkLight = getattr(zeroChunk, light)
newDirtyChunks = list(startingDirtyChunks)
work = 0
for i in range(14):
if len(newDirtyChunks) == 0:
workTotal -= len(startingDirtyChunks) * (14 - i)
break
progressInfo = u"{0} Pass {1}: {2} chunks".format(light, i, len(newDirtyChunks))
log.info(progressInfo)
# propagate light!
# for each of the six cardinal directions, figure a new light value for
# adjoining blocks by reducing this chunk's light by light absorption and fall off.
# compare this new light value against the old light value and update with the maximum.
#
# we calculate all chunks one step before moving to the next step, to ensure all gaps at chunk edges are filled.
# we do an extra cycle because lights sent across edges may lag by one cycle.
#
# xxx this can be optimized by finding the highest and lowest blocks
# that changed after one pass, and only calculating changes for that
# vertical slice on the next pass. newDirtyChunks would have to be a
# list of (cPos, miny, maxy) tuples or a cPos : (miny, maxy) dict
newDirtyChunks = set(newDirtyChunks)
newDirtyChunks.discard(zeroChunk)
dirtyChunks = sorted(newDirtyChunks, key=lambda x: x.chunkPosition)
newDirtyChunks = list()
for chunk in dirtyChunks:
(cx, cz) = chunk.chunkPosition
neighboringChunks = {}
for dir, dx, dz in ((FaceXDecreasing, -1, 0),
(FaceXIncreasing, 1, 0),
(FaceZDecreasing, 0, -1),
(FaceZIncreasing, 0, 1)):
try:
neighboringChunks[dir] = self.getChunk(cx + dx, cz + dz)
except (ChunkNotPresent, ChunkMalformed):
neighboringChunks[dir] = zeroChunk
neighboringChunks[dir].dirty = True
chunkLa = la[chunk.Blocks]
chunkLight = getattr(chunk, light)
oldChunk[:] = chunkLight[:]
### Spread light toward -X
nc = neighboringChunks[FaceXDecreasing]
ncLight = getattr(nc, light)
oldLeftEdge[:] = ncLight[15:16, :, 0:self.Height] # save the old left edge
# left edge
newlight = (chunkLight[0:1, :, :self.Height] - la[nc.Blocks[15:16, :, 0:self.Height]])
clipLight(newlight)
maximum(ncLight[15:16, :, 0:self.Height], newlight, ncLight[15:16, :, 0:self.Height])
# chunk body
newlight = (chunkLight[1:16, :, 0:self.Height] - chunkLa[0:15, :, 0:self.Height])
clipLight(newlight)
maximum(chunkLight[0:15, :, 0:self.Height], newlight, chunkLight[0:15, :, 0:self.Height])
# right edge
nc = neighboringChunks[FaceXIncreasing]
ncLight = getattr(nc, light)
newlight = ncLight[0:1, :, :self.Height] - chunkLa[15:16, :, 0:self.Height]
clipLight(newlight)
maximum(chunkLight[15:16, :, 0:self.Height], newlight, chunkLight[15:16, :, 0:self.Height])
### Spread light toward +X
# right edge
nc = neighboringChunks[FaceXIncreasing]
ncLight = getattr(nc, light)
newlight = (chunkLight[15:16, :, 0:self.Height] - la[nc.Blocks[0:1, :, 0:self.Height]])
clipLight(newlight)
maximum(ncLight[0:1, :, 0:self.Height], newlight, ncLight[0:1, :, 0:self.Height])
# chunk body
newlight = (chunkLight[0:15, :, 0:self.Height] - chunkLa[1:16, :, 0:self.Height])
clipLight(newlight)
maximum(chunkLight[1:16, :, 0:self.Height], newlight, chunkLight[1:16, :, 0:self.Height])
# left edge
nc = neighboringChunks[FaceXDecreasing]
ncLight = getattr(nc, light)
newlight = ncLight[15:16, :, :self.Height] - chunkLa[0:1, :, 0:self.Height]
clipLight(newlight)
maximum(chunkLight[0:1, :, 0:self.Height], newlight, chunkLight[0:1, :, 0:self.Height])
zerochunkLight[:] = 0 # zero the zero chunk after each direction
# so the lights it absorbed don't affect the next pass
# check if the left edge changed and dirty or compress the chunk appropriately
if (oldLeftEdge != ncLight[15:16, :, :self.Height]).any():
# chunk is dirty
newDirtyChunks.append(nc)
### Spread light toward -Z
# bottom edge
nc = neighboringChunks[FaceZDecreasing]
ncLight = getattr(nc, light)
oldBottomEdge[:] = ncLight[:, 15:16, :self.Height] # save the old bottom edge
newlight = (chunkLight[:, 0:1, :self.Height] - la[nc.Blocks[:, 15:16, :self.Height]])
clipLight(newlight)
maximum(ncLight[:, 15:16, :self.Height], newlight, ncLight[:, 15:16, :self.Height])
# chunk body
newlight = (chunkLight[:, 1:16, :self.Height] - chunkLa[:, 0:15, :self.Height])
clipLight(newlight)
maximum(chunkLight[:, 0:15, :self.Height], newlight, chunkLight[:, 0:15, :self.Height])
# top edge
nc = neighboringChunks[FaceZIncreasing]
ncLight = getattr(nc, light)
newlight = ncLight[:, 0:1, :self.Height] - chunkLa[:, 15:16, 0:self.Height]
clipLight(newlight)
maximum(chunkLight[:, 15:16, 0:self.Height], newlight, chunkLight[:, 15:16, 0:self.Height])
### Spread light toward +Z
# top edge
nc = neighboringChunks[FaceZIncreasing]
ncLight = getattr(nc, light)
newlight = (chunkLight[:, 15:16, :self.Height] - la[nc.Blocks[:, 0:1, :self.Height]])
clipLight(newlight)
maximum(ncLight[:, 0:1, :self.Height], newlight, ncLight[:, 0:1, :self.Height])
# chunk body
newlight = (chunkLight[:, 0:15, :self.Height] - chunkLa[:, 1:16, :self.Height])
clipLight(newlight)
maximum(chunkLight[:, 1:16, :self.Height], newlight, chunkLight[:, 1:16, :self.Height])
# bottom edge
nc = neighboringChunks[FaceZDecreasing]
ncLight = getattr(nc, light)
newlight = ncLight[:, 15:16, :self.Height] - chunkLa[:, 0:1, 0:self.Height]
clipLight(newlight)
maximum(chunkLight[:, 0:1, 0:self.Height], newlight, chunkLight[:, 0:1, 0:self.Height])
zerochunkLight[:] = 0
if (oldBottomEdge != ncLight[:, 15:16, :self.Height]).any():
newDirtyChunks.append(nc)
newlight = (chunkLight[:, :, 0:self.Height - 1] - chunkLa[:, :, 1:self.Height])
clipLight(newlight)
maximum(chunkLight[:, :, 1:self.Height], newlight, chunkLight[:, :, 1:self.Height])
newlight = (chunkLight[:, :, 1:self.Height] - chunkLa[:, :, 0:self.Height - 1])
clipLight(newlight)
maximum(chunkLight[:, :, 0:self.Height - 1], newlight, chunkLight[:, :, 0:self.Height - 1])
if (oldChunk != chunkLight).any():
newDirtyChunks.append(chunk)
work += 1
yield workDone + work, workTotal, progressInfo
workDone += work
workTotal -= len(startingDirtyChunks)
workTotal += work
work = 0
for ch in startingDirtyChunks:
ch.needsLighting = False
def TagProperty(tagName, tagType, default_or_func=None):
def getter(self):
if tagName not in self.root_tag["Data"]:
if hasattr(default_or_func, "__call__"):
default = default_or_func(self)
else:
default = default_or_func
self.root_tag["Data"][tagName] = tagType(default)
return self.root_tag["Data"][tagName].value
def setter(self, val):
self.root_tag["Data"][tagName] = tagType(value=val)
return property(getter, setter)
class AnvilWorldFolder(object):
def __init__(self, filename):
if not os.path.exists(filename):
os.mkdir(filename)
elif not os.path.isdir(filename):
raise IOError, "AnvilWorldFolder: Not a folder: %s" % filename
self.filename = filename
self.regionFiles = {}
# --- File paths ---
def getFilePath(self, path):
path = path.replace("/", os.path.sep)
return os.path.join(self.filename, path)
def getFolderPath(self, path):
path = self.getFilePath(path)
if not os.path.exists(path):
os.makedirs(path)
return path
# --- Region files ---
def getRegionFilename(self, rx, rz):
return os.path.join(self.getFolderPath("region"), "r.%s.%s.%s" % (rx, rz, "mca"))
def getRegionFile(self, rx, rz):
regionFile = self.regionFiles.get((rx, rz))
if regionFile:
return regionFile
regionFile = MCRegionFile(self.getRegionFilename(rx, rz), (rx, rz))
self.regionFiles[rx, rz] = regionFile
return regionFile
def getRegionForChunk(self, cx, cz):
rx = cx >> 5
rz = cz >> 5
return self.getRegionFile(rx, rz)
def closeRegions(self):
for rf in self.regionFiles.values():
rf.close()
self.regionFiles = {}
# --- Chunks and chunk listing ---
def tryLoadRegionFile(self, filepath):
filename = os.path.basename(filepath)
bits = filename.split('.')
if len(bits) < 4 or bits[0] != 'r' or bits[3] != "mca":
return None
try:
rx, rz = map(int, bits[1:3])
except ValueError:
return None
return MCRegionFile(filepath, (rx, rz))
def findRegionFiles(self):
regionDir = self.getFolderPath("region")
regionFiles = os.listdir(regionDir)
for filename in regionFiles:
yield os.path.join(regionDir, filename)
def listChunks(self):
chunks = set()
for filepath in self.findRegionFiles():
regionFile = self.tryLoadRegionFile(filepath)
if regionFile is None:
continue
if regionFile.offsets.any():
rx, rz = regionFile.regionCoords
self.regionFiles[rx, rz] = regionFile
for index, offset in enumerate(regionFile.offsets):
if offset:
cx = index & 0x1f
cz = index >> 5
cx += rx << 5
cz += rz << 5
chunks.add((cx, cz))
else:
log.info(u"Removing empty region file {0}".format(filepath))
regionFile.close()
os.unlink(regionFile.path)
return chunks
def containsChunk(self, cx, cz):
rx = cx >> 5
rz = cz >> 5
if not os.path.exists(self.getRegionFilename(rx, rz)):
return False
return self.getRegionForChunk(cx, cz).containsChunk(cx, cz)
def deleteChunk(self, cx, cz):
r = cx >> 5, cz >> 5
rf = self.getRegionFile(*r)
if rf:
rf.setOffset(cx & 0x1f, cz & 0x1f, 0)
if (rf.offsets == 0).all():
rf.close()
os.unlink(rf.path)
del self.regionFiles[r]
def readChunk(self, cx, cz):
if not self.containsChunk(cx, cz):
raise ChunkNotPresent((cx, cz))
return self.getRegionForChunk(cx, cz).readChunk(cx, cz)
def saveChunk(self, cx, cz, data):
regionFile = self.getRegionForChunk(cx, cz)
regionFile.saveChunk(cx, cz, data)
def copyChunkFrom(self, worldFolder, cx, cz):
fromRF = worldFolder.getRegionForChunk(cx, cz)
rf = self.getRegionForChunk(cx, cz)
rf.copyChunkFrom(fromRF, cx, cz)