forked from orphu/mcdungeon
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdungeon.py
2392 lines (2264 loc) · 97.9 KB
/
dungeon.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 sys
import os
import operator
from pprint import pprint
import random
from random import *
import logging
import cfg
import loottable
import materials
import rooms
import halls
import hall_traps
import floors
import features
import ruins
import pmeter
import namegenerator
import inventory
from utils import *
from disjoint_set import DisjointSet
from pymclevel import nbt
from overviewer_core import cache
from overviewer_core import world as ov_world
class Block(object):
def __init__(self, loc):
self.loc = loc
self.material = None
self.data = 0
# Hidden blocks are not drawn on maps
self.hide = False
# Locked blocks cannot be overwritten later
self.lock = False
# Soft blocks are only rendered in the world block is air
self.soft = False
class MazeCell(object):
states = enum('BLANK', 'USED', 'CONNECTED', 'RESTRICTED')
def __init__(self, loc):
self.loc = loc
self.depth = 0
self.state = 0
class RelightHandler(object):
_curr = 28
_count = 0
def __init__(self):
self.pm = pmeter.ProgressMeter()
self.pm.init(self._curr, label='Relighting chunks:')
def write(self, buff=''):
if 'Pass' in buff:
self._curr -= 1
self.pm.update_left(self._curr)
def flush(self):
pass
def done(self):
self.pm.set_complete()
class Dungeon (object):
def __init__(self,
args,
world,
oworld,
chunk_cache,
dungeon_cache,
good_chunks,
mapstore):
self.caches = []
self.caches.append(cache.LRUCache(size=100))
self.world = world
self.oworld = oworld
self.chunk_cache = chunk_cache
self.dungeon_cache = dungeon_cache
self.good_chunks = good_chunks
self.mapstore = mapstore
self.inventory = inventory.new(mapstore)
self.pm = pmeter.ProgressMeter()
self.rooms = {}
self.halls = []
self.hall_traps = []
self.blocks = {}
self.tile_ents = {}
self.ents = []
self.placed_items = []
self.torches = {}
self.doors = {}
self.entrance = None
self.entrance_pos = Vec(0, 0, 0)
self.maze = {}
self.stairwells = []
self.room_size = 16
self.room_height = 6
self.position = Vec(0, 0, 0)
self.args = args
self.dinfo = {}
self.dinfo['fill_caves'] = cfg.fill_caves
self.dinfo['portal_exit'] = cfg.portal_exit
self.dinfo['dungeon_name'] = cfg.dungeon_name
def generate(self, cache_path, version):
'''Generate a dungeon'''
# Pick a starting size.
self.xsize = randint(cfg.min_x, cfg.max_x)
self.zsize = randint(cfg.min_z, cfg.max_z)
self.levels = randint(cfg.min_levels, cfg.max_levels)
located = False
result = False
# Find a location, if we can.
# Manual location
if cfg.offset is not '':
print 'Dungeon size: {0} x {1} x {2}'.format(self.xsize,
self.zsize,
self.levels)
self.position = str2Vec(cfg.offset)
self.position.x = self.position.x & ~15
self.position.z = self.position.z & ~15
# Bury it if we need to
located = self.bury(manual=bool(cfg.bury == False))
if (located == False):
print 'Unable to bury a dungeon of requested depth at', self.position
print 'Try fewer levels, or a smaller size, or another location.'
sys.exit(1)
print "Location set to: ", self.position
# Search for a location.
else:
print "Searching for a suitable location..."
while (located is False):
located = self.findlocation()
if (located is False):
# Scale. Start with the largest axis and work down.
adjusted = False
while (
self.xsize > cfg.min_x or
self.zsize > cfg.min_z or
self.levels > cfg.min_levels
):
# X Z L
if (
self.xsize >= self.zsize and
self.zsize >= self.levels
):
if self.xsize > cfg.min_x:
self.xsize -= 1
adjusted = True
elif self.zsize > cfg.min_z:
self.zsize -= 1
adjusted = True
elif self.levels > cfg.min_levels:
self.levels -= 1
adjusted = True
# X L Z
elif (
self.xsize >= self.levels and
self.levels >= self.zsize
):
if self.xsize > cfg.min_x:
self.xsize -= 1
adjusted = True
elif self.levels > cfg.min_levels:
self.levels -= 1
adjusted = True
elif self.zsize > cfg.min_z:
self.zsize -= 1
adjusted = True
# Z X L
elif (
self.zsize >= self.xsize and
self.xsize >= self.levels
):
if self.zsize > cfg.min_z:
self.zsize -= 1
adjusted = True
elif self.xsize > cfg.min_x:
self.xsize -= 1
adjusted = True
elif self.levels > cfg.min_levels:
self.levels -= 1
adjusted = True
# Z L X
elif (
self.zsize >= self.levels and
self.levels >= self.xsize
):
if self.zsize > cfg.min_z:
self.zsize -= 1
adjusted = True
elif self.levels > cfg.min_levels:
self.levels -= 1
adjusted = True
elif self.xsize > cfg.min_x:
self.xsize -= 1
adjusted = True
# L X Z
elif (
self.levels >= self.xsize and
self.xsize >= self.zsize
):
if self.levels > cfg.min_levels:
self.levels -= 1
adjusted = True
elif self.xsize > cfg.min_x:
self.xsize -= 1
adjusted = True
elif self.zsize > cfg.min_z:
self.zsize -= 1
adjusted = True
# L Z X
elif (
self.levels >= self.zsize and
self.zsize >= self.xsize
):
if self.levels > cfg.min_levels:
self.levels -= 1
adjusted = True
elif self.zsize > cfg.min_z:
self.zsize -= 1
adjusted = True
elif self.xsize > cfg.min_x:
self.xsize -= 1
adjusted = True
if (adjusted is False):
print 'Unable to place any more dungeons.'
break
else:
print 'Dungeon size: {0} x {1} x {2}'.format(self.xsize,
self.zsize,
self.levels)
print "Location: ", self.position
# Generate!
if (located is True):
# We have a final size, so let's initialize some things.
for x in xrange(self.xsize):
for y in xrange(self.levels):
for z in xrange(self.zsize):
self.maze[Vec(x, y, z)] = MazeCell(Vec(x, y, z))
self.halls = [[[[None, None, None, None] for z in
xrange(self.zsize)] for y in
xrange(self.levels)] for x in
xrange(self.xsize)]
self.heightmap = numpy.zeros((self.xsize * self.room_size,
self.zsize * self.room_size))
# Set the seed if requested.
if (self.args.seed is not None):
seed(self.args.seed)
print 'Seed:', self.args.seed
# Now we know the biome, we can setup a name generator
self.namegen = namegenerator.namegenerator(self.biome)
print 'Theme:', self.namegen.theme
self.owner = self.namegen.genroyalname()
print 'Owner:', self.owner
print "Generating rooms..."
self.genrooms()
print "Generating halls..."
self.genhalls()
print "Generating floors..."
self.genfloors()
print "Generating features..."
self.genfeatures()
if self.args.command != 'regenerate':
print "Generating ruins..."
self.genruins()
self.setentrance()
else:
self.entrance.height = self.args.entrance_height
# Name this place
if self.owner.endswith("s"):
owners = self.owner + "'"
else:
owners = self.owner + "'s"
self.dungeon_name = self.dinfo['dungeon_name'].format(
owner=self.owner,
owners=owners)
self.dinfo['full_name'] = self.dungeon_name
print "Dungeon name:", self.dungeon_name
print "Finding secret rooms..."
self.findsecretrooms()
self.renderruins()
self.renderrooms()
self.renderhalls()
self.renderfloors()
self.renderfeatures()
print "Generating hall traps..."
self.genhalltraps()
self.renderhalltraps()
self.processBiomes()
print "Placing doors..."
self.placedoors(cfg.doors)
print "Placing torches..."
self.placetorches()
print "Placing chests..."
self.placechests()
print "Placing spawners..."
self.placespawners()
# Signature
self.setblock(Vec(0, 0, 0), materials.Chest, 0, hide=True)
self.tile_ents[Vec(0, 0, 0)] = encodeDungeonInfo(self,
version)
# Add to the dungeon cache.
key = key = '%s,%s' % (
self.position.x,
self.position.z,
)
#self.dungeon_cache[key] = self.tile_ents[Vec(0,0,0)]
self.dungeon_cache[key] = 1
# Generate maps
if (self.args.write and cfg.maps > 0):
print "Generating maps..."
self.generatemaps()
print "Placing special items..."
self.placeitems()
# copy results to the world
self.applychanges()
# Relight these chunks.
if (self.args.write is True and self.args.skiprelight is False):
# Super ugly, but does progress bars for lighting.
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
h = RelightHandler()
logging.basicConfig(stream=h, level=logging.INFO)
self.world.generateLights()
h.done()
logging.getLogger().level = logging.CRITICAL
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
# Saving here allows us to pick up where we left off if we stop.
if (self.args.write is True):
print "Saving..."
self.world.saveInPlace()
saveDungeonCache(cache_path, self.dungeon_cache)
saveChunkCache(cache_path, self.chunk_cache)
# make sure commandBlockOutput is false.
root_tag = nbt.load(self.world.filename)
root_tag['Data']['GameRules'][
'commandBlockOutput'].value = 'false'
root_tag.save(self.world.filename)
else:
print "Skipping save! (--write disabled)"
if (self.args.html is not None):
self.outputhtml()
if (self.args.term is not None):
self.outputterminal()
result = True
return result
def printmaze(self, y, cursor=None):
for z in xrange(self.zsize):
line = u''
for x in xrange(self.xsize):
p = Vec(x, y, z)
if p in self.rooms:
if self.halls[x][y][z][0] == 1:
line += (u'\u2554\u2569\u2557')
else:
line += (u'\u2554\u2550\u2557')
else:
line += (u'\u2591\u2591\u2591')
print line
line = u''
for x in xrange(self.xsize):
p = Vec(x, y, z)
if p in self.rooms:
if self.halls[x][y][z][3] == 1:
line += (u'\u2563')
else:
line += (u'\u2551')
if (cursor == p):
line += (u'X')
elif self.maze[p].state == MazeCell.states.CONNECTED:
line += (u' ')
elif self.maze[p].state == MazeCell.states.USED:
line += (u'U')
else:
line += (u'R')
if self.halls[x][y][z][1] == 1:
line += (u'\u2560')
else:
line += (u'\u2551')
else:
line += (u'\u2591\u2591\u2591')
print line
line = u''
for x in xrange(self.xsize):
p = Vec(x, y, z)
if p in self.rooms:
if self.halls[x][y][z][2] == 1:
line += (u'\u255a\u2566\u255d')
else:
line += (u'\u255a\u2550\u255d')
else:
line += (u'\u2591\u2591\u2591')
print line
line = u''
raw_input('continue...')
def setblock(
self,
loc,
material,
data=0,
hide=False,
lock=False,
soft=False):
# If material is None, remove this block
if material is None:
if loc in self.blocks:
del(self.blocks[loc])
return
# Build a block if we need to
if loc not in self.blocks:
self.blocks[loc] = Block(loc)
if (loc.x >= 0 and
loc.z >= 0 and
loc.x < self.xsize * self.room_size and
loc.z < self.zsize * self.room_size):
self.heightmap[loc.x][loc.z] = min(loc.y,
self.heightmap[loc.x][loc.z])
# If the existing block is locked, abort
# Unless we are requesting a locked block
if self.blocks[loc].lock and lock == False:
return
# Setup the material
self.blocks[loc].material = material
# Set the data value
if (data == 0):
self.blocks[loc].data = material.data
else:
self.blocks[loc].data = data
# Hide this from the map generator if requested
self.blocks[loc].hide = hide
# Lock it
self.blocks[loc].lock = lock
# Soft blocks are only drawn when the world block is air
self.blocks[loc].soft = soft
def delblock(self, loc):
if loc in self.blocks:
del self.blocks[loc]
def getblock(self, loc):
if loc in self.blocks:
return self.blocks[loc].material
return False
def findlocation(self):
positions = {}
sorted_p = []
world = self.world
if self.args.debug:
print 'Filtering for depth...'
for key, value in self.good_chunks.iteritems():
if value >= (self.levels + 1) * self.room_height:
positions[key] = value
if (cfg.maximize_distance and len(self.dungeon_cache) > 0):
if self.args.debug:
print 'Marking distances...'
for key in positions.keys():
d = 2 ^ 64
chunk = Vec(key[0], 0, key[1])
for dungeon in self.dungeon_cache:
(x, z) = dungeon.split(",")
dpos = Vec(int(x) >> 4, 0, int(z) >> 4)
d = min(d, (dpos - chunk).mag2d())
positions[key] = d
sorted_p = sorted(positions.iteritems(),
reverse=True,
key=operator.itemgetter(1))
else:
sorted_p = positions.items()
random.shuffle(sorted_p)
if self.args.debug:
print 'Selecting a location...'
all_chunks = set(positions.keys())
# Offset is fill caves. Expand the size of the dungeon if fill_caves is
# set. When recording the position, we'll center the dungeon in this
# area.
offset = 0
if self.dinfo['fill_caves']:
offset = 10
for p, d in sorted_p:
d_chunks = set()
for x in xrange(self.xsize + offset):
for z in xrange(self.zsize + offset):
d_chunks.add((p[0] + x, p[1] + z))
if d_chunks.issubset(all_chunks):
if self.args.debug:
print 'Found: ', p
self.position = Vec((p[0] + (offset / 2)) * self.room_size,
0,
(p[1] + (offset / 2)) * self.room_size)
if self.args.debug:
print 'Final: ', self.position
if self.bury():
self.worldmap(world, positions)
return True
if self.args.debug:
print 'No positions', p
return False
def worldmap(self, world, positions, note=None):
#rows, columns = os.popen('stty size', 'r').read().split()
columns = 39
bounds = world.bounds
if self.args.spawn is None:
scx = world.playerSpawnPosition()[0] >> 4
scz = world.playerSpawnPosition()[2] >> 4
else:
scx = self.args.spawn[0]
scz = self.args.spawn[1]
spawn_chunk = Vec(scx, 0, scz)
if note is not None:
note_chunk = Vec( note.x >> 4, 0, note.z >> 4 )
else:
note_chunk = Vec(0,0,0)
# Draw a nice little map of the dungeon location
map_min_x = bounds.maxcx
map_max_x = bounds.mincx
map_min_z = bounds.maxcz
map_max_z = bounds.mincz
for p in self.good_chunks:
map_min_x = min(map_min_x, p[0] + 1)
map_max_x = max(map_max_x, p[0] - 1)
map_min_z = min(map_min_z, p[1] + 1)
map_max_z = max(map_max_z, p[1] - 1)
# Include spawn
map_min_x = min(map_min_x, spawn_chunk.x)
map_max_x = max(map_max_x, spawn_chunk.x)
map_min_z = min(map_min_z, spawn_chunk.z)
map_max_z = max(map_max_z, spawn_chunk.z)
if map_max_x - map_min_x + 1 >= int(columns):
print 'Map too wide for terminal:', map_max_x - map_min_x
return
sx = self.position.x / self.room_size
sz = self.position.z / self.room_size
if self.args.debug:
print 'spos:', Vec(sx, 0, sz)
d_box = Box(Vec(sx, 0, sz), self.xsize, world.Height, self.zsize)
for z in xrange(map_min_z - 1, map_max_z + 2):
for x in xrange(map_min_x - 1, map_max_x + 2):
if (Vec(x, 0, z) == spawn_chunk):
sys.stdout.write('SS')
elif (x == 0 and z == 0):
sys.stdout.write('00')
elif (Vec(x, 0, z) == Vec(sx, 0, sz)):
sys.stdout.write('XX')
elif (Vec(x, 0, z) == note_chunk):
sys.stdout.write('@@')
elif (d_box.containsPoint(Vec(x, 64, z))):
sys.stdout.write('##')
elif ((x, z) in positions.keys()):
sys.stdout.write('++')
elif ((x, z) in self.good_chunks.keys()):
sys.stdout.write('--')
else:
sys.stdout.write('``')
print
def bury(self, manual=False):
if self.args.debug:
print 'Burying dungeon...'
min_depth = (self.levels + 1) * self.room_height
d_chunks = set()
p = (self.position.x / self.room_size,
self.position.z / self.room_size)
for x in xrange(self.xsize):
for z in xrange(self.zsize):
d_chunks.add((p[0] + x, p[1] + z))
# Calaculate the biome
biomes = {}
rset = self.oworld.get_regionset(None)
for chunk in d_chunks:
cdata = rset.get_chunk(chunk[0], chunk[1])
key = numpy.argmax(numpy.bincount((cdata['Biomes'].flatten())))
if key in biomes:
biomes[key] += 1
else:
biomes[key] = 1
self.biome = max(biomes, key=lambda k: biomes[k])
if self.args.debug:
print 'Biome: ', self.biome
depth = self.world.Height
for chunk in d_chunks:
if (chunk not in self.good_chunks):
d1 = findChunkDepth(Vec(chunk[0], 0, chunk[1]), self.world)
self.good_chunks[chunk] = d1
else:
d1 = self.good_chunks[chunk]
d1 -= 2
if not manual:
# Too shallow
if (d1 < min_depth):
return False
# Too high
elif (d1 > self.world.Height - 27):
return False
depth = min(depth, d1)
if not manual:
self.position = Vec(self.position.x,
depth,
self.position.z)
return True
def snow(self, pos, limit=16):
b = self.getblock(pos)
if (b and b != materials.Air):
return
count = 1
b = self.getblock(pos.down(count))
while (count <= limit and (b == False or b == materials.Air)):
count += 1
b = self.getblock(pos.down(count))
if count > limit:
return
if not b:
soft = True
else:
soft = False
if self.getblock(pos.down(count)).val in materials.heightmap_solids:
self.setblock(pos.down(count - 1), materials.Snow, soft=soft)
# print 'snow placed: ',pos.down(count-1), soft
def vines(self, pos, grow=False):
# Data values (1.9p5)
# 1 - South
# 2 - West
# 4 - North
# 8 - East
b = self.getblock(pos)
# Something here already
if (b and b != materials.Air):
return
if not b:
soft = True
else:
soft = False
# Look around for something to attach to
data = 0
b = self.getblock(pos.s(1))
if (b and b.val in materials.vine_solids):
data += 1
b = self.getblock(pos.w(1))
if (b and b.val in materials.vine_solids):
data += 2
b = self.getblock(pos.n(1))
if (b and b.val in materials.vine_solids):
data += 4
b = self.getblock(pos.e(1))
if (b and b.val in materials.vine_solids):
data += 8
# Nothing to attach to
if data == 0:
return
self.setblock(pos, materials.Vines, data, soft=soft)
if not grow:
return
pos = pos.down(1)
b = self.getblock(pos)
while ((b == False or b == materials.Air) and random.randint(1, 100) < 75):
if not b:
soft = True
else:
soft = False
self.setblock(pos, materials.Vines, data, soft=soft)
pos = pos.down(1)
b = self.getblock(pos)
def cobwebs(self, c1, c3):
'''Grow cobwebs in a volume. They concentrate at the top, and are more
likely to appear in air blocks bound by multiple solid blocks.'''
webs = {}
top = min(c1.y, c3.y)
for p in iterate_cube(c1, c3):
if (p not in self.blocks or
self.blocks[p].material != materials.Air):
continue
count = 0
chance = 80 - (p.y - top) * 14
for q in (Vec(1, 0, 0), Vec(-1, 0, 0),
Vec(0, 1, 0), Vec(0, -1, 0),
Vec(0, 0, 1), Vec(0, 0, -1)):
if (p + q in self.blocks and
self.blocks[p + q].material != materials.Air and
random.randint(1, 100) <= chance):
count += 1
if count >= 3:
webs[p] = True
for p, q in webs.items():
self.setblock(p, materials.Cobweb)
def processBiomes(self):
'''Add vines and snow according to biomes.'''
rset = self.oworld.get_regionset(None)
r = ov_world.CachedRegionSet(rset, self.caches)
wp = Vec(self.position.x, 0, self.position.z)
count = self.xsize * 16 * self.zsize * 16
self.pm.init(count, label='Processing biomes:')
for p in iterate_cube(Vec(0, 0, 0),
Vec(self.xsize * 16 - 1, 0, self.zsize * 16 - 1)):
self.pm.update_left(count)
count -= 1
cx = (p.x + wp.x) // 16
cz = (p.z + wp.z) // 16
chunk = r.get_chunk(cx, cz)
biome = chunk['Biomes'][p.x % 16][p.z % 16]
# Vines
if biome in (6, # Swampland
134, # Swampland M
21, # Jungle
149, # Jungle M
22, # Jungle Hills
23, # Jungle Edge
151, # Jungle Edge M
):
h = 0
try:
h = min(self.heightmap[p.x - 1][p.z], h)
except IndexError:
pass
try:
h = min(self.heightmap[p.x + 1][p.z], h)
except IndexError:
pass
try:
h = min(self.heightmap[p.x][p.z - 1], h)
except IndexError:
pass
try:
h = min(self.heightmap[p.x][p.z + 1], h)
except IndexError:
pass
if h == 0:
continue
for q in iterate_cube(Vec(p.x, h, p.z),
Vec(p.x, 0, p.z)):
if random.randint(1, 100) < 20:
self.vines(q, grow=True)
# Snow
if biome in (10, # Frozen Ocean
11, # Frozen River
12, # Ice Plains
140, # Ice Plains Spikes
13, # Ice Mountains
26, # Cold Beach
30, # Cold Taiga
158, # Cold Taiga M
31, # Cold Taiga Hills
):
h = self.heightmap[p.x][p.z]
if (h < 0):
self.snow(Vec(p.x, h - 1, p.z), limit=abs(h - 1))
self.pm.set_complete()
def getspawnertags(self, entity):
# See if we have a custom spawner match
if entity.lower() in cfg.custom_spawners.keys():
filepath = cfg.custom_spawners[entity.lower()]
root_tag = nbt.load(filename=filepath)
return root_tag
else:
root_tag = nbt.TAG_Compound()
# Cases where the entity id doesn't match the config
entity = entity.capitalize()
if (entity == 'Pigzombie'):
root_tag['EntityId'] = nbt.TAG_String('PigZombie')
elif (entity == 'Cavespider'):
root_tag['EntityId'] = nbt.TAG_String('CaveSpider')
elif (entity == 'Lavaslime'):
root_tag['EntityId'] = nbt.TAG_String('LavaSlime')
elif (entity == 'Witherboss'):
root_tag['EntityId'] = nbt.TAG_String('WitherBoss')
# For everything else the input is the EntityId
else:
root_tag['EntityId'] = nbt.TAG_String(entity)
return root_tag
def addsign(self, loc, text1, text2, text3, text4):
root_tag = nbt.TAG_Compound()
root_tag['id'] = nbt.TAG_String('Sign')
root_tag['x'] = nbt.TAG_Int(loc.x)
root_tag['y'] = nbt.TAG_Int(loc.y)
root_tag['z'] = nbt.TAG_Int(loc.z)
root_tag['Text1'] = nbt.TAG_String(text1)
root_tag['Text2'] = nbt.TAG_String(text2)
root_tag['Text3'] = nbt.TAG_String(text3)
root_tag['Text4'] = nbt.TAG_String(text4)
self.tile_ents[loc] = root_tag
def addspawner(self, loc, entity='', tier=-1):
if (entity == ''):
level = loc.y / self.room_height
if (cfg.max_mob_tier == 0 or level < 0):
tier = 0
elif tier == -1:
if (self.levels > 1):
tier = (float(level) /
float(self.levels - 1) *
float(cfg.max_mob_tier - 2)) + 1.5
tier = int(min(cfg.max_mob_tier - 1, tier))
else:
tier = cfg.max_mob_tier - 1
entity = weighted_choice(cfg.master_mobs[tier])
# print 'Spawner: lev=%d, tier=%d, ent=%s' % (level, tier, entity)
root_tag = self.getspawnertags(entity)
# Do generic spawner setup
root_tag['id'] = nbt.TAG_String('MobSpawner')
root_tag['x'] = nbt.TAG_Int(loc.x)
root_tag['y'] = nbt.TAG_Int(loc.y)
root_tag['z'] = nbt.TAG_Int(loc.z)
try:
root_tag['Delay']
except:
root_tag['Delay'] = nbt.TAG_Short(0)
# Calculate spawner tags from config
if tier == cfg.max_mob_tier:
SpawnCount = cfg.treasure_SpawnCount
SpawnMaxNearbyEntities = cfg.treasure_SpawnMaxNearbyEntities
SpawnMinDelay = cfg.treasure_SpawnMinDelay
SpawnMaxDelay = cfg.treasure_SpawnMaxDelay
SpawnRequiredPlayerRange = cfg.treasure_SpawnRequiredPlayerRange
else:
SpawnCount = cfg.SpawnCount
SpawnMaxNearbyEntities = cfg.SpawnMaxNearbyEntities
SpawnMinDelay = cfg.SpawnMinDelay
SpawnMaxDelay = cfg.SpawnMaxDelay
SpawnRequiredPlayerRange = cfg.SpawnRequiredPlayerRange
# But don't overwrite tags from NBT files
if (SpawnCount != 0):
try:
root_tag['SpawnCount']
except:
root_tag['SpawnCount'] = nbt.TAG_Short(SpawnCount)
if (SpawnMaxNearbyEntities != 0):
try:
root_tag['MaxNearbyEntities']
except:
root_tag['MaxNearbyEntities'] = nbt.TAG_Short(
SpawnMaxNearbyEntities)
if (SpawnMinDelay != 0):
try:
root_tag['MinSpawnDelay']
except:
root_tag['MinSpawnDelay'] = nbt.TAG_Short(SpawnMinDelay)
if (SpawnMaxDelay != 0):
try:
root_tag['MaxSpawnDelay']
except:
root_tag['MaxSpawnDelay'] = nbt.TAG_Short(SpawnMaxDelay)
if (SpawnRequiredPlayerRange != 0):
try:
root_tag['RequiredPlayerRange']
except:
root_tag['RequiredPlayerRange'] = nbt.TAG_Short(
SpawnRequiredPlayerRange)
# Finally give the tag to the entity
self.tile_ents[loc] = root_tag
def addnoteblock(self, loc, clicks=0):
root_tag = nbt.TAG_Compound()
root_tag['id'] = nbt.TAG_String('Music')
root_tag['x'] = nbt.TAG_Int(loc.x)
root_tag['y'] = nbt.TAG_Int(loc.y)
root_tag['z'] = nbt.TAG_Int(loc.z)
root_tag['note'] = nbt.TAG_Byte(clicks)
self.tile_ents[loc] = root_tag
def addchest(self, loc, tier=-1, loot=[], name='', lock=None):
level = loc.y / self.room_height
if (tier < 0):
if (self.levels > 1):
tierf = (float(level) /
float(self.levels - 1) *
float(loottable._maxtier - 2)) + 1.5
tierf = min(loottable._maxtier - 1, tierf)
else:
tierf = loottable._maxtier - 1
tier = max(1, int(tierf))
elif tier >= loottable._maxtier:
tier = loottable._maxtier - 1
if self.args.debug:
print 'Adding chest: level',level+1,'tier',tier
root_tag = nbt.TAG_Compound()
root_tag['id'] = nbt.TAG_String('Chest')
root_tag['x'] = nbt.TAG_Int(loc.x)
root_tag['y'] = nbt.TAG_Int(loc.y)
root_tag['z'] = nbt.TAG_Int(loc.z)
if (name != ''):
root_tag['CustomName'] = nbt.TAG_String(name)
if (lock is not None and lock != ''):
root_tag['Lock'] = nbt.TAG_String(lock)
inv_tag = nbt.TAG_List()
root_tag['Items'] = inv_tag
if len(loot) == 0:
loot = list(loottable.rollLoot(tier, level + 1))
for i in loot:
item_tag = self.inventory.buildItemTag(i)
inv_tag.append(item_tag)
self.tile_ents[loc] = root_tag
def addchestitem_tag(self, loc, item_tag):
'''Add an item to an existing chest'''
# No chest here!
if (loc not in self.tile_ents or
self.tile_ents[loc]['id'].value != 'Chest'):
return False
root_tag = self.tile_ents[loc]
slot = len(root_tag['Items'])
# Chest is full
if slot > 26:
return False
item_tag['Slot'] = nbt.TAG_Byte(slot)
root_tag['Items'].append(item_tag)
return True
def addchesttrap(self, loc, name=None, count=None):
name = weighted_choice(cfg.master_chest_traps)
count = int(cfg.lookup_chest_traps[name][1])
self.addtrap(loc, name=name, count=count)
def addtrap(self, loc, name=None, count=None):
if name is None:
name = weighted_choice(cfg.master_chest_traps)
if count is None:
count = int(cfg.lookup_chest_traps[name][1])
# sanity check for count
if count > 9 * 64:
print '\nFATAL: Item count for dispenser trap too large! Max number of items is 9x64 = 576! Check config file.'
print 'Item name:', name
print 'Count:', count
sys.exit()
root_tag = nbt.TAG_Compound()
root_tag['id'] = nbt.TAG_String('Trap')
root_tag['x'] = nbt.TAG_Int(loc.x)
root_tag['y'] = nbt.TAG_Int(loc.y)
root_tag['z'] = nbt.TAG_Int(loc.z)
inv_tag = nbt.TAG_List()
root_tag['Items'] = inv_tag
# fill slots of dispenser trap
slot = 0
while count > 0:
item_tag = nbt.TAG_Compound()
item_tag['Slot'] = nbt.TAG_Byte(slot)
if count > 64:
item_tag['Count'] = nbt.TAG_Byte(64)