forked from mcedit/pymclevel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
infiniteworld.py
3345 lines (2570 loc) · 114 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
'''
# **FIXME** WindowsError is the name of a built-in Exception, but pyflakes doesn't seem to know that. -zothar
from collections import deque
from contextlib import closing
from cStringIO import StringIO
from datetime import datetime
from entity import Entity, TileEntity
from faces import FaceXDecreasing, FaceXIncreasing, FaceZDecreasing, FaceZIncreasing
import gzip
import itertools
from logging import getLogger
from materials import alphaMaterials, namedMaterials
from math import floor
from mclevelbase import appDataDir, Blocks, ChunkMalformed, ChunkNotPresent, decompress_first, Entities, exhaust, notclosing, PlayerNotFound, RegionMalformed, TileEntities, unpack_first
import nbt
from numpy import array, clip, fromstring, maximum, uint32, uint8, zeros
import os
from os.path import join, dirname, basename
import random
import time
import traceback
import zlib
import struct
import shutil
import subprocess
import sys
import tempfile
import urllib
log = getLogger(__name__)
warn, error, info, debug = log.warn, log.error, log.info, log.debug
import blockrotation
from box import BoundingBox
from level import LightedChunk, EntityLevel, computeChunkHeightMap
# infinite
Level = 'Level'
BlockData = 'BlockData'
BlockLight = 'BlockLight'
SkyLight = 'SkyLight'
HeightMap = 'HeightMap'
TerrainPopulated = 'TerrainPopulated'
LastUpdate = 'LastUpdate'
xPos = 'xPos'
zPos = 'zPos'
Data = 'Data'
SpawnX = 'SpawnX'
SpawnY = 'SpawnY'
SpawnZ = 'SpawnZ'
LastPlayed = 'LastPlayed'
RandomSeed = 'RandomSeed'
SizeOnDisk = 'SizeOnDisk' # maybe update this?
Time = 'Time'
Player = 'Player'
Sections = 'Sections'
DIM_NETHER = -1
DIM_END = 1
__all__ = ["ZeroChunk", "InfdevChunk", "ChunkedLevelMixin", "MCInfdevOldLevel", "MCAlphaDimension", "ZipSchematic"]
import re
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
def sort_nicely(l):
""" Sort the given list in the way that humans expect.
"""
l.sort(key=alphanum_key)
# Thank you, Stackoverflow
# http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
def which(program):
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, _fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
if sys.platform == "win32":
if "SYSTEMROOT" in os.environ:
root = os.environ["SYSTEMROOT"]
exe_file = os.path.join(root, program)
if is_exe(exe_file):
return exe_file
if "PATH" in os.environ:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
if sys.platform == "win32":
appSupportDir = os.path.join(appDataDir, u"pymclevel")
elif sys.platform == "darwin":
appSupportDir = os.path.expanduser(u"~/Library/Application Support/pymclevel/")
else:
appSupportDir = os.path.expanduser(u"~/.pymclevel")
class ServerJarStorage(object):
defaultCacheDir = os.path.join(appSupportDir, u"ServerJarStorage")
def __init__(self, cacheDir=None):
if cacheDir is None:
cacheDir = self.defaultCacheDir
self.cacheDir = cacheDir
if not os.path.exists(self.cacheDir):
os.makedirs(self.cacheDir)
readme = os.path.join(self.cacheDir, "README.TXT")
if not os.path.exists(readme):
with file(readme, "w") as f:
f.write("""
About this folder:
This folder is used by MCEdit and pymclevel to store different versions of the
Minecraft Server to use for terrain generation. It should have one or more
subfolders, one for each version of the server. Each subfolder must hold at
least one file named minecraft_server.jar, and the subfolder's name should
have the server's version plus the names of any installed mods.
There may already be a subfolder here (for example, "Beta 1.7.3") if you have
used the Chunk Create feature in MCEdit to create chunks using the server.
Version numbers can be automatically detected. If you place one or more
minecraft_server.jar files in this folder, they will be placed automatically
into well-named subfolders the next time you run MCEdit. If a file's name
begins with "minecraft_server" and ends with ".jar", it will be detected in
this way.
""")
self.reloadVersions()
def reloadVersions(self):
cacheDirList = os.listdir(self.cacheDir)
self.versions = list(reversed(sorted([v for v in cacheDirList if os.path.exists(self.jarfileForVersion(v))], key=alphanum_key)))
if MCServerChunkGenerator.javaExe:
for f in cacheDirList:
p = os.path.join(self.cacheDir, f)
if f.startswith("minecraft_server") and f.endswith(".jar") and os.path.isfile(p):
print "Unclassified minecraft_server.jar found in cache dir. Discovering version number..."
self.cacheNewVersion(p)
os.remove(p)
print "Minecraft_Server.jar storage initialized."
print u"Each server is stored in a subdirectory of {0} named with the server's version number".format(self.cacheDir)
print "Cached servers: ", self.versions
def downloadCurrentServer(self):
print "Downloading the latest Minecraft Server..."
try:
(filename, headers) = urllib.urlretrieve("http://www.minecraft.net/download/minecraft_server.jar")
except Exception, e:
print "Error downloading server: {0!r}".format(e)
return
self.cacheNewVersion(filename, allowDuplicate=False)
def cacheNewVersion(self, filename, allowDuplicate=True):
""" Finds the version number from the server jar at filename and copies
it into the proper subfolder of the server jar cache folder"""
version = MCServerChunkGenerator._serverVersionFromJarFile(filename)
print "Found version ", version
versionDir = os.path.join(self.cacheDir, version)
i = 1
newVersionDir = versionDir
while os.path.exists(newVersionDir):
if not allowDuplicate:
return
newVersionDir = versionDir + " (" + str(i) + ")"
i += 1
os.mkdir(newVersionDir)
shutil.copy2(filename, os.path.join(newVersionDir, "minecraft_server.jar"))
if version not in self.versions:
self.versions.append(version)
def jarfileForVersion(self, v):
return os.path.join(self.cacheDir, v, "minecraft_server.jar").encode(sys.getfilesystemencoding())
def checksumForVersion(self, v):
jf = self.jarfileForVersion(v)
with file(jf, "rb") as f:
import hashlib
return hashlib.md5(f.read()).hexdigest()
broken_versions = ["Beta 1.9 Prerelease {0}".format(i) for i in (1, 2, 3)]
@property
def latestVersion(self):
if len(self.versions) == 0:
return None
return max((v for v in self.versions if v not in self.broken_versions), key=alphanum_key)
def getJarfile(self, version=None):
if len(self.versions) == 0:
print "No servers found in cache."
self.downloadCurrentServer()
version = version or self.latestVersion
if version not in self.versions:
return None
return self.jarfileForVersion(version)
class JavaNotFound(RuntimeError):
pass
class VersionNotFound(RuntimeError):
pass
def readProperties(filename):
if not os.path.exists(filename):
return {}
with file(filename) as f:
properties = dict((line.split("=", 2) for line in (l.strip() for l in f) if not line.startswith("#")))
return properties
def saveProperties(filename, properties):
with file(filename, "w") as f:
for k, v in properties.iteritems():
f.write("{0}={1}\n".format(k, v))
def findJava():
if sys.platform == "win32":
javaExe = which("java.exe")
if javaExe is None:
KEY_NAME = "HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
try:
p = subprocess.Popen(["REG", "QUERY", KEY_NAME, "/v", "CurrentVersion"], stdout=subprocess.PIPE, universal_newlines=True)
o, e = p.communicate()
lines = o.split("\n")
for l in lines:
l = l.strip()
if l.startswith("CurrentVersion"):
words = l.split(None, 2)
version = words[-1]
p = subprocess.Popen(["REG", "QUERY", KEY_NAME + "\\" + version, "/v", "JavaHome"], stdout=subprocess.PIPE, universal_newlines=True)
o, e = p.communicate()
lines = o.split("\n")
for l in lines:
l = l.strip()
if l.startswith("JavaHome"):
w = l.split(None, 2)
javaHome = w[-1]
javaExe = os.path.join(javaHome, "bin", "java.exe")
print "RegQuery: java.exe found at ", javaExe
break
except Exception, e:
print "Error while locating java.exe using the Registry: ", repr(e)
else:
javaExe = which("java")
return javaExe
class MCServerChunkGenerator(object):
"""Generates chunks using minecraft_server.jar. Uses a ServerJarStorage to
store different versions of minecraft_server.jar in an application support
folder.
from pymclevel import *
Example usage:
gen = MCServerChunkGenerator() # with no arguments, use the newest
# server version in the cache, or download
# the newest one automatically
level = loadWorldNamed("MyWorld")
gen.generateChunkInLevel(level, 12, 24)
Using an older version:
gen = MCServerChunkGenerator("Beta 1.6.5")
"""
defaultJarStorage = None
javaExe = findJava()
jarStorage = None
tempWorldCache = {}
def __init__(self, version=None, jarfile=None, jarStorage=None):
self.jarStorage = jarStorage or self.getDefaultJarStorage()
if self.javaExe is None:
raise JavaNotFound("Could not find java. Please check that java is installed correctly. (Could not find java in your PATH environment variable.)")
if jarfile is None:
jarfile = self.jarStorage.getJarfile(version)
if jarfile is None:
raise VersionNotFound("Could not find minecraft_server.jar for version {0}. Please make sure that a minecraft_server.jar is placed under {1} in a subfolder named after the server's version number.".format(version or "(latest)", self.jarStorage.cacheDir))
self.serverJarFile = jarfile
self.serverVersion = version or self._serverVersion()
@classmethod
def getDefaultJarStorage(cls):
if cls.defaultJarStorage is None:
cls.defaultJarStorage = ServerJarStorage()
return cls.defaultJarStorage
@classmethod
def clearWorldCache(cls):
cls.tempWorldCache = {}
for tempDir in os.listdir(cls.worldCacheDir):
t = os.path.join(cls.worldCacheDir, tempDir)
if os.path.isdir(t):
shutil.rmtree(t)
def createReadme(self):
readme = os.path.join(self.worldCacheDir, "README.TXT")
if not os.path.exists(readme):
with file(readme, "w") as f:
f.write("""
About this folder:
This folder is used by MCEdit and pymclevel to cache levels during terrain
generation. Feel free to delete it for any reason.
""")
worldCacheDir = os.path.join(tempfile.gettempdir(), "pymclevel_MCServerChunkGenerator")
def tempWorldForLevel(self, level):
# tempDir = tempfile.mkdtemp("mclevel_servergen")
tempDir = os.path.join(self.worldCacheDir, self.jarStorage.checksumForVersion(self.serverVersion), str(level.RandomSeed))
propsFile = os.path.join(tempDir, "server.properties")
properties = readProperties(propsFile)
tempWorld = self.tempWorldCache.get((self.serverVersion, level.RandomSeed))
if tempWorld is None:
if not os.path.exists(tempDir):
os.makedirs(tempDir)
self.createReadme()
worldName = "world"
worldName = properties.setdefault("level-name", worldName)
tempWorldDir = os.path.join(tempDir, worldName)
tempWorld = MCInfdevOldLevel(tempWorldDir, create=True, random_seed=level.RandomSeed)
del tempWorld.version # for compatibility with older servers. newer ones will set it again without issue.
self.tempWorldCache[self.serverVersion, level.RandomSeed] = tempWorld
if level.dimNo == 0:
properties["allow-nether"] = "false"
else:
tempWorld = tempWorld.getDimension(level.dimNo)
properties["allow-nether"] = "true"
properties["server-port"] = int(32767 + random.random() * 32700)
saveProperties(propsFile, properties)
return tempWorld, tempDir
def generateAtPosition(self, tempWorld, tempDir, cx, cz):
return exhaust(self.generateAtPositionIter(tempWorld, tempDir, cx, cz))
def generateAtPositionIter(self, tempWorld, tempDir, cx, cz, simulate=False):
tempWorld.setPlayerSpawnPosition((cx * 16, 64, cz * 16))
tempWorld.saveInPlace()
tempWorld.unloadRegions()
startTime = time.time()
proc = self.runServer(tempDir)
while proc.poll() is None:
line = proc.stderr.readline().strip()
info(line)
yield line
if "[INFO] Done" in line:
if simulate:
duration = time.time() - startTime
simSeconds = int(duration) + 1
for i in range(simSeconds):
# process tile ticks
yield "%2d/%2d: Simulating the world for a little bit..." % (i, simSeconds)
time.sleep(1)
proc.stdin.write("stop\n")
proc.wait()
break
if "FAILED TO BIND" in line:
proc.kill()
proc.wait()
raise RuntimeError("Server failed to bind to port!")
stdout, _ = proc.communicate()
if "Could not reserve enough space" in stdout and not MCServerChunkGenerator.lowMemory:
MCServerChunkGenerator.lowMemory = True
for i in self.generateAtPositionIter(tempWorld, tempDir, cx, cz):
yield i
(tempWorld.parentWorld or tempWorld).loadLevelDat() # reload version number
def copyChunkAtPosition(self, tempWorld, level, cx, cz):
if level.containsChunk(cx, cz):
return
try:
tempChunk = tempWorld.getChunk(cx, cz)
except ChunkNotPresent, e:
raise ChunkNotPresent("While generating a world in {0} using server {1} ({2!r})".format(tempWorld, self.serverJarFile, e), sys.exc_traceback)
tempChunk.decompress()
tempChunk.unpackChunkData()
root_tag = tempChunk.root_tag
if not level.containsChunk(cx, cz):
level.createChunk(cx, cz)
chunk = level.getChunk(cx, cz)
chunk.decompress()
chunk.unpackChunkData()
chunk.root_tag = root_tag # xxx tag swap, could copy blocks and entities and chunk attrs instead?
chunk.dirty = True
chunk.compress()
chunk.save()
chunk.unload()
tempChunk.compress()
tempChunk.unload()
def generateChunkInLevel(self, level, cx, cz):
assert isinstance(level, MCInfdevOldLevel)
tempWorld, tempDir = self.tempWorldForLevel(level)
self.generateAtPosition(tempWorld, tempDir, cx, cz)
self.copyChunkAtPosition(tempWorld, level, cx, cz)
minRadius = 5
maxRadius = 20
def createLevel(self, level, box, simulate=False, **kw):
return exhaust(self.createLevelIter(level, box, simulate, **kw))
def createLevelIter(self, level, box, simulate=False, **kw):
if isinstance(level, basestring):
filename = level
level = MCInfdevOldLevel(filename, create=True, **kw)
assert isinstance(level, MCInfdevOldLevel)
minRadius = self.minRadius
genPositions = list(itertools.product(
xrange(box.mincx, box.maxcx, minRadius * 2),
xrange(box.mincz, box.maxcz, minRadius * 2)))
for i, (cx, cz) in enumerate(genPositions):
info("Generating at %s" % ((cx, cz),))
parentDir = dirname(level.worldDir)
propsFile = join(parentDir, "server.properties")
props = readProperties(join(dirname(self.serverJarFile), "server.properties"))
props["level-name"] = basename(level.worldDir)
props["server-port"] = int(32767 + random.random() * 32700)
saveProperties(propsFile, props)
for p in self.generateAtPositionIter(level, parentDir, cx, cz, simulate):
yield i, len(genPositions), p
level.unloadRegions()
def generateChunksInLevel(self, level, chunks):
return exhaust(self.generateChunksInLevelIter(level, chunks))
def generateChunksInLevelIter(self, level, chunks, simulate=False):
assert isinstance(level, MCInfdevOldLevel)
tempWorld, tempDir = self.tempWorldForLevel(level)
startLength = len(chunks)
minRadius = self.minRadius
maxRadius = self.maxRadius
chunks = set(chunks)
while len(chunks):
length = len(chunks)
centercx, centercz = chunks.pop()
chunks.add((centercx, centercz))
# assume the generator always generates at least an 11x11 chunk square.
centercx += minRadius
centercz += minRadius
# boxedChunks = [cPos for cPos in chunks if inBox(cPos)]
print "Generating {0} chunks out of {1} starting from {2}".format("XXX", len(chunks), (centercx, centercz))
yield startLength - len(chunks), startLength
# chunks = [c for c in chunks if not inBox(c)]
for p in self.generateAtPositionIter(tempWorld, tempDir, centercx, centercz, simulate):
yield startLength - len(chunks), startLength, p
i = 0
for cx, cz in itertools.product(
xrange(centercx - maxRadius, centercx + maxRadius),
xrange(centercz - maxRadius, centercz + maxRadius)):
if level.containsChunk(cx, cz):
chunks.discard((cx, cz))
elif ((cx, cz) in chunks
and tempWorld.containsChunk(cx, cz)
and tempWorld.getChunk(cx, cz).TerrainPopulated
):
self.copyChunkAtPosition(tempWorld, level, cx, cz)
i += 1
chunks.discard((cx, cz))
yield startLength - len(chunks), startLength
if length == len(chunks):
print "No chunks were generated. Aborting."
break
level.saveInPlace()
def runServer(self, startingDir):
if isinstance(startingDir, unicode):
startingDir = startingDir.encode(sys.getfilesystemencoding())
return self._runServer(startingDir, self.serverJarFile)
lowMemory = False
@classmethod
def _runServer(cls, startingDir, jarfile):
info("Starting server %s in %s", jarfile, startingDir)
if cls.lowMemory:
memflags = []
else:
memflags = ["-Xmx1024M", "-Xms1024M", ]
proc = subprocess.Popen([cls.javaExe, "-Djava.awt.headless=true"] + memflags + ["-jar", jarfile],
executable=cls.javaExe,
cwd=startingDir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
return proc
def _serverVersion(self):
return self._serverVersionFromJarFile(self.serverJarFile)
@classmethod
def _serverVersionFromJarFile(cls, jarfile):
tempdir = tempfile.mkdtemp("mclevel_servergen")
proc = cls._runServer(tempdir, jarfile)
version = "Unknown"
# out, err = proc.communicate()
# for line in err.split("\n"):
while proc.poll() is None:
line = proc.stderr.readline()
if "Preparing start region" in line:
break
if "Starting minecraft server version" in line:
version = line.split("Starting minecraft server version")[1].strip()
break
if proc.returncode is None:
try:
proc.kill()
except WindowsError:
pass # access denied, process already terminated
proc.wait()
shutil.rmtree(tempdir)
if ";)" in version:
version = version.replace(";)", "") # Damnit, Jeb!
# Versions like "0.2.1" are alphas, and versions like "1.0.0" without "Beta" are releases
if version[0] == "0":
version = "Alpha " + version
try:
if int(version[0]) > 0:
version = "Release " + version
except ValueError:
pass
return version
_zeros = {}
def ZeroChunk(height=512):
z = _zeros.get(height)
if z is None:
z = _zeros[height] = _ZeroChunk(height)
return z
from level import ChunkBase
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 = unpackedData.reshape(16, 16, unpackedData.shape[2] / 2, 2)
packedData[..., 1] <<= 4
packedData[..., 1] |= packedData[..., 0]
return array(packedData[:, :, :, 1])
class InfdevChunk(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.
"""
@property
def filename(self):
if self.world.version:
cx, cz = self.chunkPosition
rx, rz = cx >> 5, cz >> 5
rf = self.world.regionFiles[rx, rz]
offset = rf.getOffset(cx & 0x1f, cz & 0x1f)
return u"{region} index {index} sector {sector} length {length} format {format}".format(
region=os.path.basename(self.world.regionFilename(rx, rz)),
sector=offset >> 8,
length=offset & 0xff,
index=4 * ((cx & 0x1f) + ((cz & 0x1f) * 32)),
format=["???", "gzip", "deflate"][self.compressMode])
else:
return self.chunkFilename
compressedTag = None
root_tag = None
def __init__(self, world, chunkPosition, create=False):
self.world = world
self.chunkPosition = chunkPosition
self.chunkFilename = world.chunkFilename(*chunkPosition)
if self.world.version:
self.compressMode = MCRegionFile.VERSION_DEFLATE
else:
self.compressMode = MCRegionFile.VERSION_GZIP
if create:
self.create()
else:
if not world.containsChunk(*chunkPosition):
raise ChunkNotPresent("Chunk {0} not found", self.chunkPosition)
@property
def materials(self):
return self.world.materials
@classmethod
def compressTagGzip(cls, root_tag):
buf = StringIO()
with closing(gzip.GzipFile(fileobj=buf, mode='wb', compresslevel=2)) as gzipper:
root_tag.save(buf=gzipper)
return buf.getvalue()
@classmethod
def compressTagDeflate(cls, root_tag):
buf = StringIO()
root_tag.save(buf=buf)
return deflate(buf.getvalue())
def _compressChunk(self):
root_tag = self.root_tag
if root_tag is None:
return
if self.compressMode == MCRegionFile.VERSION_GZIP:
self.compressedTag = self.compressTagGzip(root_tag)
if self.compressMode == MCRegionFile.VERSION_DEFLATE:
self.compressedTag = self.compressTagDeflate(root_tag)
self.root_tag = None
def decompressTagGzip(self, data):
return nbt.load(buf=nbt.gunzip(data))
def decompressTagDeflate(self, data):
return nbt.load(buf=inflate(data))
def _decompressChunk(self):
data = self.compressedTag
if self.compressMode == MCRegionFile.VERSION_GZIP:
self.root_tag = self.decompressTagGzip(data)
if self.compressMode == MCRegionFile.VERSION_DEFLATE:
self.root_tag = self.decompressTagDeflate(data)
def compressedSize(self):
"return the size of the compressed data for this level, in bytes."
self.compress()
if self.compressedTag is None:
return 0
return len(self.compressedTag)
def sanitizeBlocks(self):
# change grass to dirt where needed so Minecraft doesn't flip out and die
grass = self.Blocks == self.materials.Grass.ID
grass |= self.Blocks == self.materials.Dirt.ID
badgrass = grass[:, :, 1:] & grass[:, :, :-1]
self.Blocks[:, :, :-1][badgrass] = self.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(self.materials, "SnowLayer"):
snowlayer = self.Blocks == self.materials.SnowLayer.ID
badsnow = snowlayer[:, :, 1:] & snowlayer[:, :, :-1]
self.Blocks[:, :, 1:][badsnow] = self.materials.Air.ID
def compress(self):
if not self.dirty:
# if we are not dirty, just throw the
# uncompressed tag structure away. rely on the OS disk cache.
self.root_tag = None
else:
if self.root_tag is not None:
self.sanitizeBlocks() # xxx
self.packChunkData()
self._compressChunk()
self.world.chunkDidCompress(self)
def decompress(self):
"""called when accessing attributes decorated with @decompress_first"""
if not self in self.world.decompressedChunkQueue:
if self.root_tag != None:
return
if self.compressedTag is None:
if self.root_tag is None:
self.load()
else:
return
try:
self._decompressChunk()
except Exception, e:
error(u"Malformed NBT data in file: {0} ({1})".format(self.filename, e))
if self.world:
self.world.malformedChunk(*self.chunkPosition)
raise ChunkMalformed((e,), sys.exc_info()[2])
try:
self.shapeChunkData()
except KeyError, e:
error(u"Incorrect chunk format in file: {0} ({1})".format(self.filename, e))
if self.world:
self.world.malformedChunk(*self.chunkPosition)
raise ChunkMalformed((e,), sys.exc_info()[2])
self.dataIsPacked = True
self.world.chunkDidDecompress(self)
def __str__(self):
return u"InfdevChunk, coords:{0}, world: {1}, D:{2}, L:{3}".format(self.chunkPosition, self.world.displayName, self.dirty, self.needsLighting)
def create(self):
(cx, cz) = self.chunkPosition
chunkTag = nbt.TAG_Compound()
chunkTag.name = ""
levelTag = nbt.TAG_Compound()
chunkTag[Level] = levelTag
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[BlockLight] = nbt.TAG_Byte_Array()
levelTag[BlockLight].value = zeros(16 * 16 * self.world.Height / 2, uint8)
levelTag[Blocks] = nbt.TAG_Byte_Array()
levelTag[Blocks].value = zeros(16 * 16 * self.world.Height, uint8)
levelTag[Data] = nbt.TAG_Byte_Array()
levelTag[Data].value = zeros(16 * 16 * self.world.Height / 2, uint8)
levelTag[SkyLight] = nbt.TAG_Byte_Array()
levelTag[SkyLight].value = zeros(16 * 16 * self.world.Height / 2, uint8)
levelTag[SkyLight].value[:] = 255
if self.world.Height <= 256:
levelTag[HeightMap] = nbt.TAG_Byte_Array()
levelTag[HeightMap].value = zeros(16 * 16, uint8)
else:
levelTag[HeightMap] = nbt.TAG_Int_Array()
levelTag[HeightMap].value = zeros(16 * 16, uint32).newbyteorder()
levelTag[Entities] = nbt.TAG_List()
levelTag[TileEntities] = nbt.TAG_List()
self.root_tag = chunkTag
self.shapeChunkData()
self.dataIsPacked = True
self.dirty = True
self.save()
def save(self):
""" does not recalculate any data or light """
self.compress()
if self.dirty:
debug(u"Saving chunk: {0}".format(self))
self.world._saveChunk(self)
debug(u"Saved chunk {0}".format(self))
self.dirty = False
def load(self):
""" If the chunk is unloaded, calls world._loadChunk to set root_tag and
compressedTag, then unpacks the chunk fully"""
if self.root_tag is None and self.compressedTag is None:
try:
self.world._loadChunk(self)
self.dataIsPacked = True
self.decompress()
except Exception, e:
error(u"Incorrect chunk format in file: {0} ({1})".format(self.filename, e))
if self.world:
self.world.malformedChunk(*self.chunkPosition)
raise ChunkMalformed((e,), sys.exc_info()[2])
self.world.chunkDidLoad(self)
self.world.chunkDidDecompress(self)
def unload(self):
""" Frees the chunk's memory. Will not save to disk. Unloads completely
if the chunk does not need to be saved."""
self.compress()
if not self.dirty:
self.compressedTag = None
self.world.chunkDidUnload(self)
def isLoaded(self):
# we're loaded if we have our tag data in ram
# and we don't have to go back to the disk for it.
return not (self.compressedTag is None and self.root_tag is None)
def isCompressed(self):
return self.isLoaded() and self.root_tag == None
def generateHeightMap(self):
if self.world.dimNo == DIM_NETHER:
self.HeightMap[:] = 0
else:
computeChunkHeightMap(self.materials, self.Blocks, self.HeightMap)
def unpackChunkData(self):
if not self.dataIsPacked:
return
""" for internal use. call getChunk and compressChunk to load, compress, and unpack chunks automatically """
for key in (SkyLight, BlockLight, Data):
dataArray = self.root_tag[Level][key].value
assert dataArray.shape[2] == self.world.Height / 2
self.root_tag[Level][key].value = unpackNibbleArray(dataArray)
self.dataIsPacked = False
def packChunkData(self):
if self.dataIsPacked:
return
if self.root_tag is None:
warn(u"packChunkData called on unloaded chunk: {0}".format(self.chunkPosition))
return
for key in (SkyLight, BlockLight, Data):
dataArray = self.root_tag[Level][key].value
assert dataArray.shape[2] == self.world.Height
self.root_tag[Level][key].value = packNibbleArray(self.root_tag[Level][key].value)
self.dataIsPacked = True
def shapeChunkData(self):
"""Applies the chunk shape to all of the data arrays
in the chunk tag. used by chunk creation and loading"""
chunkTag = self.root_tag
chunkSize = 16
if not hasattr(self.world, 'HeightOverride'):
length = chunkTag[Level][Blocks].value.ravel().shape[0]
height = length / (chunkSize * chunkSize)
self.world.Height = height
self.world.HeightOverride = True
self.world._bounds = None
chunkTag[Level][Blocks].value.shape = (chunkSize, chunkSize, self.world.Height)
chunkTag[Level][HeightMap].value.shape = (chunkSize, chunkSize)
chunkTag[Level][SkyLight].value.shape = (chunkSize, chunkSize, self.world.Height / 2)
chunkTag[Level][BlockLight].value.shape = (chunkSize, chunkSize, self.world.Height / 2)
chunkTag[Level]["Data"].value.shape = (chunkSize, chunkSize, self.world.Height / 2)
if TileEntities not in chunkTag[Level]:
chunkTag[Level][TileEntities] = nbt.TAG_List()
if Entities not in chunkTag[Level]:
chunkTag[Level][Entities] = nbt.TAG_List()
def addEntity(self, entityTag):
def doubleize(name):
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(InfdevChunk, self).addEntity(entityTag)
def removeEntitiesInBox(self, box):
self.dirty = True
return super(InfdevChunk, self).removeEntitiesInBox(box)
def removeTileEntitiesInBox(self, box):
self.dirty = True
return super(InfdevChunk, self).removeTileEntitiesInBox(box)
@property
@decompress_first
def Blocks(self):
return self.root_tag[Level][Blocks].value
@property
@decompress_first
@unpack_first
def Data(self):
return self.root_tag[Level][Data].value
@property