-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathmcdungeon.py
executable file
·2185 lines (2018 loc) · 87.7 KB
/
mcdungeon.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
#!/usr/bin/env python
import argparse
import copy
import logging
import numpy
import os
import platform
import re
import sys
import time
import traceback
if platform.system() != 'Windows':
import concurrent.futures as cf
# Version info
__version__ = '0.18.0'
__version_info__ = tuple([num for num in __version__.split('.')])
_vstring = '%%(prog)s %s' % (__version__)
# Globals
world = None
cache_path = None
def parseArgs():
# Argument parsers
parser = argparse.ArgumentParser(
description='Generate a tile-based dungeon in a Minecraft map.')
parser.add_argument('-v',
'--version',
action='version',
version=_vstring,
help='Print version and exit')
parser.add_argument('-q',
'--quiet',
action='store_true',
dest='quiet',
help='Suppress progress messages')
subparsers = parser.add_subparsers(
description='See "COMMAND --help" for additional help.',
title='Available commands')
# Interactive subcommand parser
parser_inter = subparsers.add_parser('interactive',
help='Interactive mode.')
parser_inter.set_defaults(command='interactive')
parser_inter.add_argument('--skip-relight',
action='store_true',
dest='skiprelight',
help='Skip relighting the level')
parser_inter.add_argument('-t',
'--term',
type=int,
dest='term',
metavar='FLOOR',
help='Print a text version of a given floor to the \
terminal')
parser_inter.add_argument('--html',
dest='html',
metavar='HTMLPATH',
help='Output html versions of the dungeon to the \
specified path. You can optionally include the keyword \
__DUNGEON__ which will be replaced with the dungeon \
name.')
parser_inter.add_argument('--debug',
action='store_true',
dest='debug',
help='Provide additional debug info')
parser_inter.add_argument('--force',
action='store_true',
dest='force',
help='Force overwriting of html output files')
parser_inter.add_argument('-s', '--seed',
dest='seed',
metavar='SEED',
help='Provide a seed for this dungeon. This can be \
anything')
parser_inter.add_argument('-o', '--offset',
dest='offset',
nargs=3,
type=int,
metavar=('X', 'Y', 'Z'),
help='Provide a location offset in blocks')
parser_inter.add_argument('--force-bury',
action='store_true',
dest='bury',
help='Attempt to calculate Y when using --offset')
parser_inter.add_argument('-e', '--entrance',
dest='entrance',
nargs=2,
type=int,
metavar=('X', 'Z'),
help='Provide an offset for the entrance in chunks')
parser_inter.add_argument('--spawn',
dest='spawn',
nargs=2,
type=int,
metavar=('X', 'Z'),
help='Override spawn point')
parser_inter.add_argument('--dir',
dest='dir',
metavar='SAVEDIR',
help='Override the default map directory.')
parser_inter.add_argument('--mapstore',
dest='mapstore',
metavar='PATH',
help='Provide an alternate world to store maps.')
parser_inter.add_argument('--outputdir',
dest='outputdir',
metavar='PATH',
help='Give the location for the OverViewer output path.')
parser_inter.add_argument('--regionfile',
dest='regionfile',
metavar='PATH',
help='Give the location for the regions.yml output path.\
This is usually located in plugins/WorldGuard/worlds/<name>/regions.yml \
Make sure you take a backup of this file first!')
parser_inter.add_argument('--workers',
dest='workers',
type=int,
metavar='WORKERS',
help='Number of child processes to use for the \
worker pool. Defaults to the number of reported \
cores on your machine.')
# AddTH subcommand parser
parser_addth = subparsers.add_parser('addth', help='Add new treasure hunts.')
parser_addth.set_defaults(command='addth')
parser_addth.add_argument('world',
metavar='SAVEDIR',
help='Target world (path to save directory)')
parser_addth.add_argument('distance',
help='Number of chunks per step, or provide a \
range.')
parser_addth.add_argument('steps',
metavar='STEPS',
help='Number of steps. Enter a positive value, or \
provide a range.')
parser_addth.add_argument('-c', '--config',
dest='config',
metavar='CFGFILE',
default='default.cfg',
help='Alternate config file. Default: default.cfg')
parser_addth.add_argument('--write',
action='store_true',
dest='write',
help='Write the treasure hunt to disk')
parser_addth.add_argument('--skip-relight',
action='store_true',
dest='skiprelight',
help='Skip relighting the level')
parser_addth.add_argument('--debug',
action='store_true',
dest='debug',
help='Provide additional debug info')
parser_addth.add_argument('-s', '--seed',
dest='seed',
metavar='SEED',
help='Provide a seed for this treasure hunt. This can be \
anything')
parser_addth.add_argument('-o', '--offset',
dest='offset',
nargs=3,
type=int,
metavar=('X', 'Y', 'Z'),
help='Provide a location offset in blocks for start')
parser_addth.add_argument('--spawn',
dest='spawn',
nargs=2,
type=int,
metavar=('X', 'Z'),
help='Override spawn point')
parser_addth.add_argument('-n',
'--number',
type=int,
dest='number',
metavar='NUM',
default=1,
help='Number of treasure hunts to generate. -1 will \
create as many as possible given X, Z, and STEPS \
settings.')
parser_addth.add_argument('--mapstore',
dest='mapstore',
metavar='PATH',
help='Provide an alternate world to store maps.')
parser_addth.add_argument('--workers',
dest='workers',
type=int,
metavar='WORKERS',
help='Number of child processes to use for the \
worker pool. Defaults to the number of reported \
cores on your machine.')
# Add subcommand parser
parser_add = subparsers.add_parser('add', help='Add new dungeons.')
parser_add.set_defaults(command='add')
parser_add.add_argument('world',
metavar='SAVEDIR',
help='Target world (path to save directory)')
parser_add.add_argument('x',
metavar='X',
help='Number of rooms West -> East, or provide a \
range.')
parser_add.add_argument('z',
metavar='Z',
help='Number of rooms North -> South, or provide a \
range. (ie: 4-7)')
parser_add.add_argument('levels',
metavar='LEVELS',
help='Number of levels. Enter a positive value, or \
provide a range.')
parser_add.add_argument('-c', '--config',
dest='config',
metavar='CFGFILE',
default='default.cfg',
help='Alternate config file. Default: default.cfg')
parser_add.add_argument('--write',
action='store_true',
dest='write',
help='Write the dungeon to disk')
parser_add.add_argument('--skip-relight',
action='store_true',
dest='skiprelight',
help='Skip relighting the level')
parser_add.add_argument('-t',
'--term',
type=int,
dest='term',
metavar='FLOOR',
help='Print a text version of a given floor to the \
terminal')
parser_add.add_argument('--html',
dest='html',
metavar='HTMLPATH',
help='Output html versions of the dungeon to the \
specified path. You can optionally include the keyword \
__DUNGEON__ which will be replaced with the dungeon \
name.')
parser_add.add_argument('--debug',
action='store_true',
dest='debug',
help='Provide additional debug info')
parser_add.add_argument('--force',
action='store_true',
dest='force',
help='Force overwriting of html output files')
parser_add.add_argument('-s', '--seed',
dest='seed',
metavar='SEED',
help='Provide a seed for this dungeon. This can be \
anything')
parser_add.add_argument('-o', '--offset',
dest='offset',
nargs=3,
type=int,
metavar=('X', 'Y', 'Z'),
help='Provide a location offset in blocks')
parser_add.add_argument('--force-bury',
action='store_true',
dest='bury',
help='Attempt to calculate Y when using --offset')
parser_add.add_argument('-e', '--entrance',
dest='entrance',
nargs=2,
type=int,
metavar=('X', 'Z'),
help='Provide an offset for the entrance in chunks')
parser_add.add_argument('--spawn',
dest='spawn',
nargs=2,
type=int,
metavar=('X', 'Z'),
help='Override spawn point')
parser_add.add_argument('-n',
'--number',
type=int,
dest='number',
metavar='NUM',
default=1,
help='Number of dungeons to generate. -1 will \
create as many as possible given X, Z, and LEVEL \
settings.')
parser_add.add_argument('--mapstore',
dest='mapstore',
metavar='PATH',
help='Provide an alternate world to store maps.')
parser_add.add_argument('--workers',
dest='workers',
type=int,
metavar='WORKERS',
help='Number of child processes to use for the \
worker pool. Defaults to the number of reported \
cores on your machine.')
# List subcommand parser
parser_list = subparsers.add_parser('list',
help='List known dungeons in a map.')
parser_list.set_defaults(command='list')
parser_list.add_argument('world',
metavar='SAVEDIR',
help='Target world (path to save directory)')
parser_list.add_argument('--debug',
action='store_true',
dest='debug',
help='Provide additional debug info')
parser_list.add_argument('--workers',
dest='workers',
type=int,
metavar='WORKERS',
help='Number of child processes to use for the \
worker pool. Defaults to the number of reported \
cores on your machine.')
# GenPOI subcommand parser
parser_genpoi = subparsers.add_parser('genpoi',
help='Create OverViewer POI configuration for known dungeons in a map.')
parser_genpoi.set_defaults(command='genpoi')
parser_genpoi.add_argument('--debug',
action='store_true',
dest='debug',
help='Provide additional debug info')
parser_genpoi.add_argument('world',
metavar='SAVEDIR',
help='Target world (path to save directory)')
parser_genpoi.add_argument('--outputdir',
dest='outputdir',
metavar='PATH',
help='Give the location for the OverViewer output path.')
parser_genpoi.add_argument('--workers',
dest='workers',
type=int,
metavar='WORKERS',
help='Number of child processes to use for the \
worker pool. Defaults to the number of reported \
cores on your machine.')
# GenRegions subcommand parser
parser_genreg = subparsers.add_parser('genregions',
help='Create WorldGuard regions.yml definitions for known dungeons in a map.')
parser_genreg.set_defaults(command='genreg')
parser_genreg.add_argument('--debug',
action='store_true',
dest='debug',
help='Provide additional debug info')
parser_genreg.add_argument('world',
metavar='SAVEDIR',
help='Target world (path to world directory)')
parser_genreg.add_argument('--regionfile',
dest='regionfile',
metavar='PATH',
help='Give the location for the regions.yml output path.\
This is usually located in plugins/WorldGuard/worlds/<name>/regions.yml \
Make sure you take a backup of this file first!')
parser_genreg.add_argument('--workers',
dest='workers',
type=int,
metavar='WORKERS',
help='Number of child processes to use for the \
worker pool. Defaults to the number of reported \
cores on your machine.')
# Delete subcommand parser
parser_del = subparsers.add_parser('delete',
help='Delete dungeons from a map.')
parser_del.set_defaults(command='delete')
parser_del.add_argument('--debug',
action='store_true',
dest='debug',
help='Provide additional debug info')
parser_del.add_argument('world',
metavar='SAVEDIR',
help='Target world (path to save directory)')
parser_del.add_argument('-d', '--dungeon',
metavar=('X', 'Z'),
nargs=2,
action='append',
dest='dungeons',
type=int,
help='The X Z coordinates of a dungeon or treasure \
hunt to delete. \
NOTE: These will be rounded to the nearest chunk. \
Multiple -d flags can be specified.')
parser_del.add_argument('-a', '--all',
dest='all',
action='store_true',
help='Delete all known dungeons. Overrides -d.')
parser_del.add_argument('--mapstore',
dest='mapstore',
metavar='PATH',
help='Provide an alternate world to store maps.')
parser_del.add_argument('--workers',
dest='workers',
type=int,
metavar='WORKERS',
help='Number of child processes to use for the \
worker pool. Defaults to the number of reported \
cores on your machine.')
# Regnerate subcommand parser
parser_regen = subparsers.add_parser('regenerate',
help='Regenerate dungeons in a map.')
parser_regen.set_defaults(command='regenerate')
parser_regen.add_argument('world',
metavar='SAVEDIR',
help='Target world (path to save directory)')
parser_regen.add_argument('-d', '--dungeon',
metavar=('X', 'Z'),
nargs=2,
action='append',
dest='dungeons',
type=int,
help='The X Z coordinates of a dungeon to \
regenerate. NOTE: These will be rounded to the \
nearest chunk. Multiple -d flags can be \
specified.')
parser_regen.add_argument('-c', '--config',
dest='config',
metavar='CFGFILE',
default='default.cfg',
help='Alternate config file. Default: default.cfg')
parser_regen.add_argument('--debug',
action='store_true',
dest='debug',
help='Provide additional debug info')
parser_regen.add_argument('--html',
dest='html',
metavar='HTMLPATH',
help='Output html versions of the dungeon to the \
specified path. You can optionally include the keyword \
__DUNGEON__ which will be replaced with the dungeon \
name.')
parser_regen.add_argument('--force',
action='store_true',
dest='force',
help='Force overwriting of html output files')
parser_regen.add_argument('-t',
'--term',
type=int,
dest='term',
metavar='FLOOR',
help='Print a text version of a given floor to the \
terminal')
parser_regen.add_argument('--skip-relight',
action='store_true',
dest='skiprelight',
help='Skip relighting the level')
parser_regen.add_argument('--mapstore',
dest='mapstore',
metavar='PATH',
help='Provide an alternate world to store maps.')
parser_regen.add_argument('-a', '--all',
dest='all',
action='store_true',
help='Regenerate all known dungeons. Overrides -d.')
parser_regen.add_argument('--workers',
dest='workers',
type=int,
metavar='WORKERS',
help='Number of child processes to use for the \
worker pool. Defaults to the number of reported \
cores on your machine.')
# Parse the args
args = parser.parse_args()
# On Windows, we can't yet use multiprocessing.
if platform.system() == 'Windows':
args.workers = 0
return args
def loadWorld(world_name):
'''Attempt to load a world file. Look in the literal path first, then look
in the typical save directory for the given platform. Check to see if the
mcdungeon cache directory exists, and create it if not.'''
# Attempt to open the world. Look in cwd first, then try to search the
# user's save directory.
global cfg
global cache_path
world = None
clean_name = world_name.encode('utf-8').strip()
try:
if args.quiet is False:
print "Trying to open:", clean_name
world = mclevel.fromFile(world_name)
except:
saveFileDir = mclevel.saveFileDir
world_name = os.path.join(saveFileDir, world_name)
if args.quiet is False:
print "Trying to open:", clean_name
try:
world = mclevel.fromFile(world_name)
except:
print "Failed to open world:", clean_name
sys.exit(1)
if args.quiet is False:
print 'Loaded world: %s (%d chunks, %d blocks high)' % (
clean_name,
world.chunkCount,
world.Height
)
# Create the mcdungeon cache dir if needed.
cache_path = os.path.join(world_name, cfg.cache_dir)
if os.path.exists(cache_path) is False:
os.makedirs(cache_path)
# Find the mapstore path
if args.quiet is False:
print 'Looking for data directory...'
if not os.path.exists(os.path.join(cfg.mapstore, 'data')):
cfg.mapstore = os.path.join(mclevel.saveFileDir, cfg.mapstore)
if args.quiet is False:
print 'Looking for data directory...'
if not os.path.exists(os.path.join(cfg.mapstore, 'data')):
print "Cannot find world data directory!"
sys.exit(1)
return world
def classifyChunk(c):
cx = c[0]
cz = c[1]
# Load the chunk
chunk = world.getChunk(cx, cz)
# Incomplete chunk
# These keys may be optional in older MC versions.
if (
cfg.use_incomplete_chunks != True and
'LightPopulated' in chunk.root_tag['Level'] and
'TerrainPopulated' in chunk.root_tag['Level']
):
if (
chunk.root_tag['Level']['LightPopulated'].value == 0 or
chunk.root_tag['Level']['TerrainPopulated'].value == 0
):
return cx, cz, 'I', None, 0
# Biomes
biomes = chunk.Biomes.flatten()
biome_type = numpy.argmax(numpy.bincount(biomes))
# Exclude chunks that are 20% river.
for river_biome in cfg.river_biomes:
if (biomes == river_biome).sum() > 50:
return cx, cz, 'R', river_biome, 0
# Exclude Oceans
if biome_type in cfg.ocean_biomes:
return cx, cz, 'O', biome_type, 0
# Structures
if (len(cfg.structure_values) > 0):
mats = cfg.structure_values
t = False
i = 0
while (t == False and i < len(mats)):
x = (chunk.Blocks[:] == mats[i])
t = x.any()
i += 1
if t:
return cx, cz, 'S', biome_type, 0
# Depths
min_depth = world.Height
max_depth = 0
for x in xrange(16):
for z in xrange(16):
y = chunk.HeightMap[x, z] - 1
while (y > 0 and
chunk.Blocks[x, z, y] not in
materials.heightmap_solids):
y = y - 1
min_depth = min(y, min_depth)
max_depth = max(y, max_depth)
# Surface too close to the max height
if max_depth > world.Height - 27:
return cx, cz, 'H', biome_type, min_depth
# Surface too close to the bottom of the world
if min_depth < 12:
return cx, cz, 'L', biome_type, min_depth
# Chunk is good
return cx, cz, 'G', biome_type, min_depth
def checkDInfo(c):
cx = c[0]
cz = c[1]
key = '%s,%s' % (cx * 16, cz * 16)
for tileEntity in world.getChunk(cx, cz).TileEntities:
if (
tileEntity['id'].value == 'Sign' and
'[MCD]' in tileEntity['Text1'].value
):
key = '%s,%s' % (
tileEntity["x"].value,
tileEntity["z"].value
)
return key, 'dungeon', tileEntity
if (
(tileEntity['id'].value == 'Chest' or tileEntity['id'].value == 'minecraft:chest') and
'CustomName' in tileEntity and
tileEntity['CustomName'].value == 'MCDungeon Data Library'
):
key = '%s,%s' % (
tileEntity["x"].value,
tileEntity["z"].value
)
return key, 'dungeon', tileEntity
if (
(tileEntity['id'].value == 'Chest' or tileEntity['id'].value == 'minecraft:chest') and
'CustomName' in tileEntity and
tileEntity['CustomName'].value == 'MCDungeon THunt Data Library'
):
key = '%s,%s' % (
tileEntity["x"].value,
tileEntity["z"].value
)
return key, 'thunt', tileEntity
return key, None, None
def loadCaches(expand_fill_caves=False, genpoi=False):
'''Scan a world for dungeons and treasure hunts. Try to cache
the results and only look at chunks that have changed since the
last run.'''
global world
global cache_path
pm = pmeter.ProgressMeter()
# Try to load the dungeon cache
dungeonCacheOld, mtime = utils.loadDungeonCache(cache_path)
dungeonCache = {}
# Try to load the treasure hunt cache
tHuntCacheOld, mtime = utils.loadTHuntCache(cache_path)
tHuntCache = {}
count = world.chunkCount
# Pass 1 will prefilter the chunks for ones that might be interesting.
if genpoi is False:
print 'Scanning world for existing dungeons and treasure hunts:'
pm.init(count, label='Pass 1:')
chunks = set()
for c in world.allChunks:
cx = c[0]
cz = c[1]
key = '%s,%s' % (cx * 16, cz * 16)
cmtime = world.worldFolder.getRegionForChunk(cx, cz).getTimestamp(cx, cz)
if (cmtime > mtime or key in dungeonCacheOld or key in tHuntCacheOld):
chunks.add(c)
count -= 1
if genpoi is False and count%200 == 0:
pm.update_left(count)
# Pass 2 will evaluate the interesting chunks.
count = world.chunkCount
if genpoi is False:
pm.set_complete()
pm.init(count, label='Pass 2:')
# Handle this in the main thread if we aren't multiprocessing.
if args.workers is not None and args.workers < 2:
if args.debug:
print 'Working with a single process.'
for c in chunks:
(key, d_type, entity) = checkDInfo(c)
if entity:
if d_type == 'dungeon':
dungeonCache[key] = entity
else:
tHuntCache[key] = entity
count -= 1
if genpoi is False and count%200 == 0:
pm.update_left(count)
# Process chunks in parallel.
else:
if args.debug:
print 'Working with multiple processes. workers =', args.workers
with cf.ProcessPoolExecutor(max_workers = args.workers) as executor:
chunk_scans = {executor.submit(checkDInfo, c): c for c in chunks}
for future in cf.as_completed(chunk_scans):
(key, d_type, entity) = future.result()
if entity:
if d_type == 'dungeon':
dungeonCache[key] = entity
else:
tHuntCache[key] = entity
count -= 1
if genpoi is False and count%200 == 0:
pm.update_left(count)
if genpoi is False:
pm.set_complete()
# Save the caches
utils.saveDungeonCache(cache_path, dungeonCache)
utils.saveTHuntCache(cache_path, tHuntCache)
output = ''
poiOutput = ''
# Process the dungeons
dungeons = []
output += "Known dungeons on this map:\n"
output += '+-----------+----------------+---------+-------+----+'\
'-------------------------+\n'
output += '| %9s | %14s | %7s | %5s | %2s | %23s |\n' % (
'Pos',
'Date/Time',
'Ver',
'Size',
'Lv',
'Name'
)
output += '+-----------+----------------+---------+-------+----+'\
'-------------------------+\n'
for tileEntity in dungeonCache.values():
info = utils.decodeDungeonInfo(tileEntity)
try:
(major, minor, patch) = info['version'].split('.')
except KeyError:
print 'Strange Dungeon Info cache found?'
continue
version = float(major + '.' + minor)
xsize = info['xsize']
zsize = info['zsize']
levels = info['levels']
offset = 0
if (
expand_fill_caves is True and
info['fill_caves'] is True
):
offset = 5
dungeons.append((info["position"].x - offset,
info["position"].z - offset,
xsize + offset,
zsize + offset,
info,
levels,
info["position"].x,
info["position"].y,
info["position"].z,
version))
if genpoi is True:
# If we have a 'new' format, with a defined portal_exit,
# then we use that. Otherwise, identify the top of the
# entrance stairway and use that instead.
if ((info["portal_exit"] is None) or (info["portal_exit"].x==0 and info["portal_exit"].y==0 and info["portal_exit"].z==0)):
# use <<4 instead of room_size because we can't get that
px = info["position"].x + ( info["entrance_pos"].x << 4 ) + 8
py = info["position"].y + info["entrance_height"]
pz = info["position"].z + ( info["entrance_pos"].z << 4 ) + 8
else:
px = info["position"].x + info["portal_exit"].x
py = info["position"].y - info["portal_exit"].y # reversed!
pz = info["position"].z + info["portal_exit"].z
# Output the POI format for OverViewer
fn = info.get('full_name', 'Dungeon')
fn = fn.replace("'","\\'")
poiOutput += '\t\t{\'id\':\'MCDungeon\',\n\t\t\'x\':%d,\n\t\t\'y\':%d,\n\t\t\'z\':%d,\n\t\t\'name\':\'%s\',\n\t\t\'description\':\'%s\\n%d Levels, Size %dx%d\'},\n' % (
px,py,pz,
fn,
fn,levels,xsize,zsize
)
else:
output += '| %9s | %14s | %7s | %5s | %2d | %23s |\n' % (
'%d %d' % (info["position"].x, info["position"].z),
time.strftime('%x %H:%M', time.localtime(info['timestamp'])),
info['version'],
'%dx%d' % (xsize, zsize),
levels,
info.get('full_name', 'Dungeon')[:23]
)
if genpoi is False:
output += '+-----------+----------------+---------+-------+----+'\
'-------------------------+\n'
# Process the treasure hunts
tHunts = []
output += '\n'
if genpoi is False:
output += "Known treasure hunts on this map:\n"
output += '+-----------+----------------+---------+-------+----+'\
'-------------------------+\n'
output += '| %9s | %14s | %7s | %5s | %2s | %23s |\n' % (
'Pos',
'Date/Time',
'Ver',
'Range',
'St',
'Name'
)
output += '+-----------+----------------+---------+-------+----+'\
'-------------------------+\n'
for tileEntity in tHuntCache.values():
info = utils.decodeTHuntInfo(tileEntity)
try:
(major, minor, patch) = info['version'].split('.')
except KeyError:
continue
version = float(major + '.' + minor)
try:
minrange = info['min_distance']
maxrange = info['max_distance']
except KeyError:
minrange = 1
maxrange = 20
steps = info['steps']
offset = 0
tHunts.append((
info["position"].x,
info["position"].z,
minrange,
maxrange,
info,
steps,
info["position"].x,
info["position"].y,
info["position"].z,
version))
if genpoi is True :
fn = info.get('full_name', 'Treasure Hunt')
fn = fn.replace("'","\\'")
poiOutput += '\t\t{\'id\':\'MCDungeonTH\',\n\t\t\'x\':%d,\n\t\t\'y\':%d,\n\t\t\'z\':%d,\n\t\t\'name\':"%s",\n\t\t\'description\':"%s\\n%d Steps, Range %d - %d"},\n' % (
info["landmarks"][0].x+8,
info["landmarks"][0].y,
info["landmarks"][0].z+8,
fn,
fn, steps-1, minrange, maxrange
)
# Here, we should also iterate through the waypoints
i = 0
for l in info["landmarks"]:
i = i + 1
if i == 1:
continue
if i == steps:
stepname = "Final location"
else:
stepname = "Waypoint %d" % (i-1)
poiOutput += '\t\t{\'id\':\'MCDungeonTHW\',\n\t\t\'x\':%d,\n\t\t\'y\':%d,\n\t\t\'z\':%d,\n\t\t\'name\':"%s (%s)",\n\t\t\'description\':"%s\\n%s\\n(%d steps)"},\n' % (
l.x+8,
l.y,
l.z+8,
fn, stepname,
fn, stepname, steps-1
)
else:
output += '| %9s | %14s | %7s | %5s | %2d | %23s |\n' % (
'%d %d' % (info["position"].x, info["position"].z),
time.strftime('%x %H:%M', time.localtime(info['timestamp'])),
info['version'],
'%d-%d' % (minrange,maxrange),
steps,
info.get('full_name', 'Treasure')[:23]
)
if genpoi is False:
output += '+-----------+----------------+---------+-------+----+'\
'-------------------------+\n'
if genpoi is True:
print poiOutput
elif len(tHunts) > 0 or len(dungeons) > 0:
print output
else:
print 'No dungeons or treasure hunts found!'
return dungeons, tHunts
def main():
'''
Main function.
'''
global world
global cache_path
dungeons = []
tHunts = []
dungeon_positions = {}
total_rooms = 0
chunk_cache = {}
good_chunks = {}
# Interactive mode
if (args.command == 'interactive'):
print 'Starting interactive mode!'
# Pick a map
if args.dir is not None:
mclevel.saveFileDir = args.dir
saveFileDir = mclevel.saveFileDir
print '\nYour save directory is:\n', saveFileDir
if (os.path.isdir(saveFileDir) is False):
sys.exit('\nI cannot find your save directory! Aborting!')
print '\nWorlds in your save directory:\n'
count = 0
worlds = []
for file in os.listdir(saveFileDir):
file_path = os.path.join(saveFileDir, file)
if (
os.path.isdir(file_path) and
os.path.isfile(file_path + '/level.dat')
):
print '\t[{}] {}'.format(count+1, file.encode('utf-8').strip())
count += 1
args.world = file_path
worlds.append(file)
if count == 0:
sys.exit('There do not appear to be any worlds in your save direcory. \
Aborting!')
if count > 1:
w = -1
while (w < 0 or w > len(worlds)-1):
w = raw_input(
'\nEnter the number for the world you wish to modify: '
)
try:
w = int(w)-1
except:
w = -1
args.world = os.path.join(saveFileDir, worlds[w])
else:
print '\nOnly one world available.'
# Pick a mode
print '\nChoose an action:\n-----------------\n'
print '\t[a] Add new dungeon(s) to this map.'
print '\t[t] Add new treasure hunt(s) to this map.'
print '\t[l] List dungeons and treasure hunts already in this map.'
print '\t[d] Delete dungeons or treasure hunts from this map.'
print '\t[r] Regenerate a dungeon or treasure hunt in this map.'
print '\t[p] Generate OverViewer POI file for dungeons and treasure hunts'
print '\t already in this map.'
print '\t[w] Generate a WorldGuard regions file for dungeons already in'
print '\t this map.'
command = raw_input('\nEnter choice or q to quit: ')
if command == 'a':
args.command = 'add'
# Pick a config
configDir = os.path.join(sys.path[0], 'configs')
if (os.path.isdir(configDir) is False):
configDir = 'configs'
if (os.path.isdir(configDir) is False):
sys.exit('\nI cannot find your configs directory! Aborting!')
choices = ['default']
for file in os.listdir(configDir):
file_path = os.path.join(configDir, file)
file = file.replace('.cfg', '')
if (
os.path.isfile(file_path) and
file_path.endswith('.cfg') and
file != 'default'):
choices.append(file)
print '\nConfigurations in your configs directory:\n'
count = 1
config = None
for file in choices:
print '\t[{}] {}'.format(count, file)
count += 1
while config is None:
config = raw_input('\nChoose a config (enter for default): ')
if config == '':
config = 'default'
else:
if config in [str(x+1) for x in xrange(len(choices))]:
config = choices[int(config)-1]
else:
config = None
args.config = str(config) + '.cfg'
cfg.Load(args.config)
# Prompt for a mapstore if we need to
if (cfg.mapstore == '' and args.mapstore is None):