forked from orphu/mcdungeon
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
1570 lines (1349 loc) · 51.4 KB
/
utils.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
import code
import cPickle
import math
import os
import random
import re
import sys
import time
import uuid
import numpy
from materials import heightmap_solids
from pymclevel import mclevel, nbt
cache_version = '6'
def floor(n):
return int(n)
def ceil(n):
if int(n) == n:
return int(n)
return int(n) + 1
def clamp(n, a, b):
rmin = min(a, b)
rmax = max(a, b)
if(n < rmin):
return rmin
if(n > rmax):
return rmax
return n
class Vec(object):
def __init__(self, x, y, z):
self.x = int(x)
self.y = int(y)
self.z = int(z)
def __add__(self, b):
if isinstance(b, Vec):
return Vec(self.x + b.x, self.y + b.y, self.z + b.z)
else:
return Vec(self.x + b, self.y + b, self.z + b)
def __sub__(self, b):
if isinstance(b, Vec):
return Vec(self.x - b.x, self.y - b.y, self.z - b.z)
else:
return Vec(self.x - b, self.y - b, self.z - b)
def __mul__(self, b):
return Vec(self.x * b, self.y * b, self.z * b)
def __str__(self):
return "(%d,%d,%d)" % (self.x, self.y, self.z)
def __repr__(self):
return self.__str__()
def __eq__(self, b):
if not isinstance(b, Vec):
return False
return self.x == b.x and self.y == b.y and self.z == b.z
def __ne__(self, b):
if not isinstance(b, Vec):
return True
return self.x != b.x or self.y != b.y or self.z != b.z
def __hash__(self):
return self.x + (self.y << 4) + (self.z << 8)
def e(self, x):
return Vec(self.x + x, self.y, self.z)
def w(self, x):
return Vec(self.x - x, self.y, self.z)
def up(self, y):
return Vec(self.x, self.y - y, self.z)
def down(self, y):
return Vec(self.x, self.y + y, self.z)
def n(self, z):
return Vec(self.x, self.y, self.z - z)
def s(self, z):
return Vec(self.x, self.y, self.z + z)
def mag2d(self):
return math.sqrt(self.x * self.x + self.z * self.z)
def d(self, d):
if (d == 0):
return Vec(0, 0, -1)
if (d == 1):
return Vec(1, 0, 0)
if (d == 2):
return Vec(0, 0, 1)
if (d == 3):
return Vec(-1, 0, 0)
def rotate(self, r):
# rotate around xz plane
while r < 0:
r += 4
if r == 0:
return self
elif r == 1:
return Vec(-self.z, self.y, self.x)
elif r == 2:
return Vec(-self.x, self.y, -self.z)
elif r == 3:
return Vec(self.z, self.y, -self.x)
def ccw(self):
return self.rotate(-1)
def cw(self):
return self.rotate(1)
def trans(self, x, y, z):
return Vec(self.x + x, self.y + y, self.z + z)
# As of 1.9 pre 4:
# North = -Z
# South = +Z
# East = +X
# West = -X
NORTH = Vec(0, 0, -1)
SOUTH = Vec(0, 0, 1)
EAST = Vec(1, 0, 0)
WEST = Vec(-1, 0, 0)
UP = Vec(0, 1, 0)
DOWN = Vec(0, -1, 0)
class Vec2f(object):
def __init__(self, x, z):
self.x = float(x)
self.z = float(z)
@staticmethod
def fromVec(vec):
return Vec2f(vec.x, vec.z)
def rotate(self, r):
while r < 0:
r += 4
if r == 0:
return self
elif r == 1:
return Vec2f(-self.z, self.x)
elif r == 2:
return Vec2f(-self.x, -self.z)
elif r == 3:
return Vec2f(self.z, -self.x)
def det(self, b):
return self.x * b.z - self.z * b.x
def mag(self):
return math.sqrt(self.x * self.x + self.z * self.z)
def unit(self):
mag = math.sqrt(self.x * self.x + self.z * self.z)
return Vec2f(self.x / mag, self.z / mag)
def __str__(self):
return "(%f,%f)" % (self.x, self.z)
def __add__(self, b):
if isinstance(b, Vec2f):
return Vec2f(self.x + b.x, self.z + b.z)
else:
return Vec2f(self.x + b, self.z + b)
def __sub__(self, b):
if isinstance(b, Vec2f):
return Vec2f(self.x - b.x, self.z - b.z)
else:
return Vec2f(self.x - b, self.z - b)
def __mul__(self, b):
return Vec2f(self.x * b, self.z * b)
class Box(object):
def __init__(self, loc, w, h, d):
self.loc = loc
self.w = w
self.h = h
self.d = d
def x2(self):
return self.loc.x + self.w
def y2(self):
return self.loc.y + self.h
def z2(self):
return self.loc.z + self.d
def containsPoint(self, p):
x = p.x - self.loc.x
y = p.y - self.loc.y
z = p.z - self.loc.z
return ((x >= 0) and (x < self.w)
and (y >= 0) and (y < self.h)
and (z >= 0) and (z < self.d))
def intersects(self, b):
if ((self.loc.x > b.x2()) or (self.x2() <= b.loc.x)):
return False
if ((self.loc.y > b.y2()) or (self.y2() <= b.loc.y)):
return False
if ((self.loc.z > b.z2()) or (self.z2() <= b.loc.z)):
return False
return True
def __str__(self):
return '(%d, %d, %d) w: %d, h: %d, d: %d' % (
self.loc.x, self.loc.y, self.loc.z,
self.w, self.h, self.d)
def area(loc1, loc2):
return abs((loc1.x - loc2.x) * (loc1.z - loc2.z))
def iterate_plane(loc1, loc2):
for x in xrange(min(loc1.x, loc2.x), max(loc1.x, loc2.x) + 1):
for y in xrange(min(loc1.y, loc2.y), max(loc1.y, loc2.y) + 1):
for z in xrange(min(loc1.z, loc2.z), max(loc1.z, loc2.z) + 1):
yield Vec(x, y, z)
def iterate_cube(*points):
for x in xrange(min([p.x for p in points]),
max([p.x for p in points]) + 1):
for y in xrange(min([p.y for p in points]),
max([p.y for p in points]) + 1):
for z in xrange(min([p.z for p in points]),
max([p.z for p in points]) + 1):
yield Vec(x, y, z)
def iterate_hollow_cube(near, far):
for b in iterate_cube(near, Vec(near.x, far.y, far.z)):
yield b
for b in iterate_cube(near, Vec(far.x, near.y, far.z)):
yield b
for b in iterate_cube(near, Vec(far.x, far.y, near.z)):
yield b
for b in iterate_cube(Vec(near.x, near.y, far.z), far):
yield b
for b in iterate_cube(Vec(near.x, far.y, near.z), far):
yield b
for b in iterate_cube(Vec(far.x, near.y, near.z), far):
yield b
def iterate_four_walls(corner1, corner3, height):
corner2 = Vec(corner3.x, corner1.y, corner1.z)
corner4 = Vec(corner1.x, corner1.y, corner3.z)
for b in iterate_cube(corner1, corner2, corner1.up(height)):
yield b
for b in iterate_cube(corner2, corner3, corner2.up(height)):
yield b
for b in iterate_cube(corner3, corner4, corner3.up(height)):
yield b
for b in iterate_cube(corner4, corner1, corner4.up(height)):
yield b
def iterate_points_inside_flat_poly(*poly_points):
min_x = floor(min([p.x for p in poly_points]))
max_x = ceil(max([p.x for p in poly_points]))
min_z = floor(min([p.z for p in poly_points]))
max_z = ceil(max([p.z for p in poly_points]))
min_y = floor(min([p.y for p in poly_points]))
num_points = len(poly_points)
def point_inside(p):
if isinstance(p, Vec2f):
p = Vec(p.x, 0, p.z)
for i in xrange(num_points):
a = poly_points[i]
b = poly_points[(i + 1) % num_points]
if isinstance(a, Vec2f):
a = Vec(a.x, 0, a.z)
if isinstance(b, Vec2f):
b = Vec(b.x, 0, b.z)
b_to_a = Vec2f.fromVec(b - a)
p_to_a = Vec2f.fromVec(p - a)
det = b_to_a.det(p_to_a)
if det < 0:
return False
return True
for x in xrange(min_x, max_x + 1):
for z in xrange(min_z, max_z + 1):
p = Vec(x, min_y, z)
if point_inside(p):
yield p
def sum_points_inside_flat_poly(*poly_points):
return sum(1 for p in iterate_points_inside_flat_poly(*poly_points))
def random_point_inside_flat_poly(*poly_points):
points = {}
for p in iterate_points_inside_flat_poly(*poly_points):
points[p] = True
return random.choice(points.keys())
def iterate_points_surrounding_box(box):
near = box.loc.trans(-1, -1, -1)
far = box.loc.trans(box.w + 1, box.h + 1, box.d + 1)
return iterate_hollow_cube(near, far)
def iterate_spiral(p1, p2, height):
p = p1
box = Box(p1.trans(0, -height, 0), p2.x - p1.x, height, p2.z - p1.z)
step = Vec(1, -1, 0)
for y in xrange(int(height)):
yield p
if (box.containsPoint(p + step) is False):
if (step == Vec(1, -1, 0)):
step = Vec(0, -1, 1)
elif (step == Vec(0, -1, 1)):
step = Vec(-1, -1, 0)
elif (step == Vec(-1, -1, 0)):
step = Vec(0, -1, -1)
else:
step = Vec(1, -1, 0)
p += step
def weighted_choice(items):
"""items is a list of tuples in the form (item, weight)"""
weight_total = sum((int(item[1]) for item in items))
n = random.uniform(0, weight_total)
for item, weight in items:
if n < int(weight):
break
n = n - int(weight)
return item
def weighted_shuffle(master_list):
"""items is a list of tuples in the form (item, weight).
We return a new list with higher probability choices
listed toward the end. This let's us pop() item off the
stack."""
# Work on a copy so we don't destroy the original
results = []
items = []
# remove any prob 0 items... we don't want to get stuck
for item, weight in master_list:
if int(weight) >= 1:
items.append([item, int(weight)])
# Return the items in a weighted random order
while (len(items) > 0):
#item = weighted_choice(items)
weight_total = sum((item[1] for item in items))
n = random.uniform(0, weight_total)
for item, weight in items:
if n < weight:
break
n = n - weight
results.insert(0, item)
items.remove([item, weight])
return results
# Generate a number between min and max. Weighted towards higher numbers.
# (Beta distribution.)
def topheavy_random(min, max):
d = max - min + 1
return int(math.floor(math.sqrt(random.randrange(d * d))) + min)
def str2Vec(string):
m = re.search('(-{0,1}\d+)[\s,]*(-{0,1}\d+)[\s,]*(-{0,1}\d+)', string)
return Vec(m.group(1), m.group(2), m.group(3))
def iterate_tube(e0, e1, height):
for y in xrange(height + 1):
for p in iterate_ellipse(e0.up(y), e1.up(y)):
yield p
def iterate_cylinder(*points):
xmin = min([p.x for p in points])
xmax = max([p.x for p in points])
ymin = min([p.y for p in points])
ymax = max([p.y for p in points])
zmin = min([p.z for p in points])
zmax = max([p.z for p in points])
e0 = Vec(xmin, ymax, zmin)
e1 = Vec(xmax, ymax, zmax)
height = ymax - ymin
for y in xrange(0, height + 1):
for p in iterate_disc(e0.up(y), e1.up(y)):
yield p
def iterate_disc(e0, e1):
for (p0, p1) in zip(*[iter(iterate_ellipse(e0, e1))] * 2):
# A little wasteful. We get a few points more than once,
# but oh well.
for x in xrange(p0.x, p1.x + 1):
yield Vec(x, p0.y, p0.z)
def iterate_ellipse(p0, p1):
'''Ellipse function based on Bresenham's. This is ported from C and
probably horribly inefficient here in python, but we are dealing with
tiny spaces, so it probably won't matter much.'''
z = min(p0.y, p1.y)
x0 = p0.x
x1 = p1.x
y0 = p0.z
y1 = p1.z
a = abs(x1 - x0)
b = abs(y1 - y0)
b1 = b & 1
dx = 4 * (1 - a) * b * b
# 3.8 instead of 4 here makes the small circles look a little nicer.
dy = 3.8 * (b1 + 1) * a * a
err = dx + dy + b1 * a * a
e2 = 0
if (x0 > x1):
x0 = x1
x1 += a
if (y0 > y1):
y0 = y1
y0 += (b + 1) / 2
y1 = y0 - b1
a *= 8 * a
b1 = 8 * b * b
while True:
yield Vec(x0, z, y0)
yield Vec(x1, z, y0)
yield Vec(x0, z, y1)
yield Vec(x1, z, y1)
e2 = 2 * err
if (e2 >= dx):
x0 += 1
x1 -= 1
dx += b1
err += dx
if (e2 <= dy):
y0 += 1
y1 -= 1
dy += a
err += dy
if (x0 > x1):
break
# flat ellipses a=1
# Bug here... not sure what is going on, but
# this is only needed for ellipese with a
# horizontal radius of 1
# while (y0 - y1 < b):
# y0 += 1
# yield Vec(x0-1, z, y0)
# y1 -= 1
# yield Vec(x0-1, z, y1)
def drange(start, stop, step):
r = start
while r < stop:
yield r
r += step
def dumpEnts(world):
for i, cPos in enumerate(world.allChunks):
try:
chunk = world.getChunk(*cPos)
except mclevel.ChunkMalformed:
continue
for tileEntity in chunk.TileEntities:
pos = Vec(0, 0, 0)
if (tileEntity["id"].value == "Trap"):
for name, tag in tileEntity.items():
print ' ', name, tag.value
if (name == 'x'):
pos.x = tag.value & 0xf
if (name == 'y'):
pos.y = tag.value
if (name == 'z'):
pos.z = tag.value & 0xf
print pos
print 'Block Value:', chunk.Blocks[pos.x, pos.z, pos.y]
print 'Data Value:', chunk.Data[pos.x, pos.z, pos.y]
if i % 100 == 0:
print "Chunk {0}...".format(i)
def spin(c=''):
spinner = ['O o o', 'O O o', 'o O O', 'o o O', 'o O O', 'O O o']
if (c == ''):
c = spinner[random.randint(0, len(spinner) - 1)]
sys.stdout.write("\r" + str(c) + " \r")
sys.stdout.flush()
def findChunkDepth(p, world):
try:
chunk = world.getChunk(p.x, p.z)
except:
return 0
depth = world.Height
for x in xrange(16):
for z in xrange(16):
y = chunk.HeightMap[z, x] - 1
while (y > 0 and
chunk.Blocks[x, z, y] not in heightmap_solids):
y = y - 1
depth = min(y, depth)
return depth
def findChunkDepths(p, world):
try:
chunk = world.getChunk(p.x, p.z)
except:
return 0
min_depth = world.Height
max_depth = 0
for x in xrange(16):
for z in xrange(16):
y = chunk.HeightMap[z, x] - 1
while (y > 0 and
chunk.Blocks[x, z, y] not in heightmap_solids):
y = y - 1
min_depth = min(y, min_depth)
max_depth = max(y, max_depth)
return (min_depth, max_depth)
def enum(*sequential, **named):
'''Defines an object that can be used as an enum. Example:
> Numbers = enum('ZERO', 'ONE', 'TWO')
> Numbers.ZERO
0
> Numbers.ONE
1'''
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
def distribute(chunk, ymin, ymax, chance, material):
'''Ditributes a material through the strata of a given array'''
view = chunk.Blocks[:, :, ymin:ymax]
viewd = chunk.Data[:, :, ymin:ymax]
for i, v in numpy.ndenumerate(view):
if random.uniform(0.0, 100.0) <= chance:
view[i] = material.val
viewd[i] = 0
def loadDungeonCache(cache_path):
'''Load the dungeon cache given a path'''
global cache_version
dungeonCache = {}
mtime = 0
# Try some basic versioning.
if not os.path.exists(os.path.join(cache_path,
'dungeon_scan_version_' + cache_version)):
print 'Dungeon cache missing, or is an old verision. Resetting...'
return dungeonCache, mtime
# Try to load the cache
if os.path.exists(os.path.join(cache_path, 'dungeon_scan_cache')):
try:
FILE = open(os.path.join(cache_path, 'dungeon_scan_cache'), 'rb')
dungeonCache = cPickle.load(FILE)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to read the dungeon_scan_cache file. '
' Check permissions and try again.')
# Try to read the cache mtime
if os.path.exists(os.path.join(cache_path, 'dungeon_scan_mtime')):
try:
FILE = open(os.path.join(cache_path, 'dungeon_scan_mtime'), 'rb')
mtime = cPickle.load(FILE)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to read the dungeon_scan_mtime file. '
' Check permissions and try again.')
return dungeonCache, mtime
def loadTHuntCache(cache_path):
'''Load the treasure hunt cache given a path'''
global cache_version
tHuntCache = {}
mtime = 0
# Try some basic versioning.
if not os.path.exists(os.path.join(cache_path,
'thunt_scan_version_' + cache_version)):
print 'Treasure Hunt cache missing, or is an old verision. Resetting...'
return tHuntCache, mtime
# Try to load the cache
if os.path.exists(os.path.join(cache_path, 'thunt_scan_cache')):
try:
FILE = open(os.path.join(cache_path, 'thunt_scan_cache'), 'rb')
tHuntCache = cPickle.load(FILE)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to read the thunt_scan_cache file. '
' Check permissions and try again.')
# Try to read the cache mtime
if os.path.exists(os.path.join(cache_path, 'thunt_scan_mtime')):
try:
FILE = open(os.path.join(cache_path, 'thunt_scan_mtime'), 'rb')
mtime = cPickle.load(FILE)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to read the thunt_scan_mtime file. '
' Check permissions and try again.')
return tHuntCache, mtime
def saveDungeonCache(cache_path, dungeonCache):
''' save the dungeon cache given a path and array'''
global cache_version
try:
FILE = open(os.path.join(cache_path, 'dungeon_scan_cache'), 'wb')
cPickle.dump(dungeonCache, FILE, -1)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to write dungeon_scan_cache. '
' Check permissions and try again.')
mtime = int(time.time())
try:
FILE = open(os.path.join(cache_path, 'dungeon_scan_mtime'), 'wb')
cPickle.dump(mtime, FILE, -1)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to write dungeon_scan_mtime.'
'Check permissions and try again.')
try:
for f in os.listdir(cache_path):
if re.search('dungeon_scan_version_.*', f):
os.remove(os.path.join(cache_path, f))
FILE = open(
os.path.join(
cache_path,
'dungeon_scan_version_' +
cache_version),
'wb')
cPickle.dump('SSsssss....BOOM', FILE, -1)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to write dungeon_scan_version.'
'Check permissions and try again.')
def saveTHuntCache(cache_path, tHuntCache):
''' save the treasure hunt cache given a path and array'''
global cache_version
try:
FILE = open(os.path.join(cache_path, 'thunt_scan_cache'), 'wb')
cPickle.dump(tHuntCache, FILE, -1)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to write thunt_scan_cache. '
' Check permissions and try again.')
mtime = int(time.time())
try:
FILE = open(os.path.join(cache_path, 'thunt_scan_mtime'), 'wb')
cPickle.dump(mtime, FILE, -1)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to write thunt_scan_mtime.'
'Check permissions and try again.')
try:
for f in os.listdir(cache_path):
if re.search('thunt_scan_version_.*', f):
os.remove(os.path.join(cache_path, f))
FILE = open(
os.path.join(
cache_path,
'thunt_scan_version_' +
cache_version),
'wb')
cPickle.dump('SSsssss....BOOM', FILE, -1)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to write thunt_scan_version.'
'Check permissions and try again.')
def loadChunkCache(cache_path):
'''Load the chunk cache given a path'''
global cache_version
# Load the chunk cache
chunkCache = {}
chunkMTime = 0
# Try some basic versioning.
if not os.path.exists(os.path.join(cache_path,
'chunk_scan_version_' + cache_version)):
print 'Chunk cache missing, or is an old verision. Resetting...'
return chunkCache, chunkMTime
if os.path.exists(os.path.join(cache_path, 'chunk_scan_cache')):
try:
FILE = open(os.path.join(cache_path, 'chunk_scan_cache'), 'rb')
chunkCache = cPickle.load(FILE)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to read the chunk_scan_cache file.'
'Check permissions and try again.')
# Try to read the cache mtime
if os.path.exists(os.path.join(cache_path, 'chunk_scan_mtime')):
try:
FILE = open(os.path.join(cache_path, 'chunk_scan_mtime'), 'rb')
chunkMTime = cPickle.load(FILE)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to read the dungeon_scan_mtime file.'
'Check permissions and try again.')
return chunkCache, chunkMTime
def saveChunkCache(cache_path, chunkCache):
''' save the chunk cache given a path and array'''
global cache_version
try:
FILE = open(os.path.join(cache_path, 'chunk_scan_cache'), 'wb')
cPickle.dump(chunkCache, FILE, -1)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to write chunk_scan_cache.'
'Check permissions and try again.')
chunkMTime = int(time.time())
try:
FILE = open(os.path.join(cache_path, 'chunk_scan_mtime'), 'wb')
cPickle.dump(chunkMTime, FILE, -1)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to write chunk_scan_mtime.'
'Check permissions and try again.')
try:
for f in os.listdir(cache_path):
if re.search('chunk_scan_version_.*', f):
os.remove(os.path.join(cache_path, f))
FILE = open(os.path.join(cache_path,
'chunk_scan_version_' + cache_version), 'wb')
cPickle.dump('SSsssss....BOOM', FILE, -1)
FILE.close()
except Exception as e:
print e
sys.exit('Failed to write dungeon_scan_version.'
'Check permissions and try again.')
def encodeTHuntInfo(thunt, version):
'''Takes a dungeon object and Returns an NBT structure for a
chest+book encoding a lot of things to remember about this
dungeon.'''
# Some old things need to be added.
items = thunt.dinfo
items['version'] = version
items['steps'] = thunt.steps
items['timestamp'] = int(time.time())
items['landmarks'] = []
items['min_distance'] = thunt.min_distance
items['max_distance'] = thunt.max_distance
for l in thunt.landmarks:
items['landmarks'].append( l.pos )
# Create the base tags
root_tag = nbt.TAG_Compound()
root_tag['id'] = nbt.TAG_String('Chest')
root_tag['CustomName'] = nbt.TAG_String('MCDungeon THunt Data Library')
root_tag['x'] = nbt.TAG_Int(0)
root_tag['y'] = nbt.TAG_Int(0)
root_tag['z'] = nbt.TAG_Int(0)
inv_tag = nbt.TAG_List()
root_tag['Items'] = inv_tag
# Populate the pages
slot = 0
page = 0
newslot = True
for key in items:
# Make a new book
if newslot is True:
if slot >= 27:
sys.exit('Too many values to store, and not enough slots!')
item_tag = nbt.TAG_Compound()
inv_tag.append(item_tag)
item_tag['Slot'] = nbt.TAG_Byte(slot)
item_tag['Count'] = nbt.TAG_Byte(1)
item_tag['id'] = nbt.TAG_Short(387)
item_tag['Damage'] = nbt.TAG_Short(0)
tag_tag = nbt.TAG_Compound()
item_tag['tag'] = tag_tag
tag_tag['title'] = nbt.TAG_String(
'MCDungeon Data Volume %d' % (slot + 1)
)
tag_tag['author'] = nbt.TAG_String('Various')
tag_tag['pages'] = nbt.TAG_List()
newslot = False
page = 0
slot += 1
tag_tag['pages'].append(
nbt.TAG_String(cPickle.dumps({key: items[key]}))
)
page += 1
if page >= 50:
newslot = True
return root_tag
def encodeDungeonInfo(dungeon, version):
'''Takes a dungeon object and Returns an NBT structure for a
chest+book encoding a lot of things to remember about this
dungeon.'''
# Some old things need to be added.
items = dungeon.dinfo
items['entrance_pos'] = dungeon.entrance_pos
items['entrance_height'] = int(dungeon.entrance.height)
items['version'] = version
items['xsize'] = dungeon.xsize
items['zsize'] = dungeon.zsize
items['levels'] = dungeon.levels
items['timestamp'] = int(time.time())
# Create the base tags
root_tag = nbt.TAG_Compound()
root_tag['id'] = nbt.TAG_String('Chest')
root_tag['CustomName'] = nbt.TAG_String('MCDungeon Data Library')
root_tag['Lock'] = nbt.TAG_String(str(uuid.uuid4()))
root_tag['x'] = nbt.TAG_Int(0)
root_tag['y'] = nbt.TAG_Int(0)
root_tag['z'] = nbt.TAG_Int(0)
inv_tag = nbt.TAG_List()
root_tag['Items'] = inv_tag
# Populate the pages
slot = 0
page = 0
newslot = True
for key in items:
# Make a new book
if newslot is True:
if slot >= 27:
sys.exit('Too many values to store, and not enough slots!')
item_tag = nbt.TAG_Compound()
inv_tag.append(item_tag)
item_tag['Slot'] = nbt.TAG_Byte(slot)
item_tag['Count'] = nbt.TAG_Byte(1)
item_tag['id'] = nbt.TAG_Short(387)
item_tag['Damage'] = nbt.TAG_Short(0)
tag_tag = nbt.TAG_Compound()
item_tag['tag'] = tag_tag
tag_tag['title'] = nbt.TAG_String(
'MCDungeon Data Volume %d' % (slot + 1)
)
tag_tag['author'] = nbt.TAG_String('Various')
tag_tag['pages'] = nbt.TAG_List()
newslot = False
page = 0
slot += 1
tag_tag['pages'].append(
nbt.TAG_String(cPickle.dumps({key: items[key]}))
)
page += 1
if page >= 50:
newslot = True
return root_tag
def decodeDungeonInfo(lib):
'''Takes an NBT tag and tries to decode a Chest object containing
MCDungeon info. Returns a dictionary full of key=>value pairs'''
items = {}
# Position is always the x,y,z of the entity
items['position'] = Vec(int(lib['x']), int(lib['y']), int(lib['z']))
# Look for legacy sign-based entity.
if lib['id'] == "Sign":
m = re.search('E:(\d+),(\d+)', lib["Text4"])
items['entrance_pos'] = Vec(int(m.group(1)), 0, int(m.group(2)))
m = re.search('T:(..)', lib["Text4"])
items['entrance_height'] = int(m.group(1), 16)
items['version'] = lib["Text1"][5:]
(items['xsize'],
items['zsize'],
items['levels']) = [int(x) for x in lib["Text3"].split(',')]
items['timestamp'] = int(lib["Text2"])
m = re.search('H:(.)', lib["Text4"])
items['fill_caves'] = int(m.group(1))
return items
# Check the chest name
if (
'CustomName' not in lib or
lib['CustomName'] != 'MCDungeon Data Library'
):
sys.exit('Invalid data library NBT.')
# iterate through the objects in the chest
for book in lib['Items']:
if (
(book['id'] != 387 and book['id'] != 'minecraft:written_book') or
book['tag']['title'].startswith('MCDungeon Data Volume') is False
):
print 'Non-book or odd book found in chest!', items['position'], 'id:', book['id']
if 'tag' in book and 'title' in book['tag']:
print '\t', book['tag']['title']
continue
for page in book['tag']['pages']:
items.update(cPickle.loads(str(page)))
return items
def decodeTHuntInfo(lib):
'''Takes an NBT tag and tries to decode a Chest object containing
MCDungeon info. Returns a dictionary full of key=>value pairs'''
items = {}
# Position is always the x,y,z of the entity
items['position'] = Vec(int(lib['x']), int(lib['y']), int(lib['z']))
# Check the chest name
if (
'CustomName' not in lib or
lib['CustomName'] != 'MCDungeon THunt Data Library'
):
sys.exit('Invalid data library NBT.')
# iterate through the objects in the chest
for book in lib['Items']:
if (
(book['id'] != 387 and book['id'] != 'minecraft:written_book')
):
#print 'Non-book found in cache chest: %s' % ( book['id'] )
continue
if (
'title' not in book['tag']
):
print 'Strange book with no title found in cache chest'
continue
if (
book['tag']['title'].startswith('MCDungeon Data Volume') is False
):
print 'Strange book found in cache chest: %s' % ( book['tag']['title'] )
continue
for page in book['tag']['pages']:
items.update(cPickle.loads(str(page)))
return items
# Some entity helpers
def get_tile_entity_tags(
eid='Chest', Pos=Vec( 0, 0, 0),