/
PortalUtil.java
1161 lines (1001 loc) · 40.3 KB
/
PortalUtil.java
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
/*
* Copyright (C) 2011-present Andrew Krieger.
*/
package org.akrieger.Nethrar;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.World.Environment;
import org.bukkit.block.Block;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.Plugin;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.util.Vector;
import java.io.File;
import java.io.IOException;
import java.lang.IllegalArgumentException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
/**
* Utility class for interacting with and managing Portals in the world.
* This class represents the 'meta-logic' of portals, eg. the way portals are
* linked, created, etc. Whereas the Portal class manages teleporting players
* and the various conditions for doing so, this class manages the connections
* between portals that define where a Portal will teleport a player to. This
* class also manages creating and removing Portal objects, to properly
* maintain links. Currently, Portals decide where their counterparts 'should'
* be, whereas this class is in charge of creating them.
*
* @author Andrew Krieger
*/
public class PortalUtil {
private static Plugin plugin;
private static Map<Location, Portal> portals;
private static Map<World, World> worldLinks;
private static Map<World, World> respawnRedirects;
private static Map<World, Integer> worldScales;
private static Map<World, Integer> worldHeights;
private static Map<World, Integer> compressionMethods;
private static Map<BlockData, World> blocksToWorlds;
private static Map<World, BlockData> worldsToBlocks;
private static Set<World> restrictedWorlds;
private static Map<Entity, Long> entityLastTeleportedTime;
// Map of chunks, encoded in a Location object, and a list of portals
// keeping that chunk loaded.
private static Map<Location, List<Portal>> forceLoadedChunks;
private static int keepAliveRadius;
private static final Logger log = Logger.getLogger("Minecraft.Nethrar");
private static final long TELEPORT_TIMEOUT_NANOS = 500000000l;
private static final long CLEANUP_TIMEOUT_NANOS = 5000000000l;
private static long lastCleanup = 0;
public static final int COMPRESS_CLAMP = 0;
public static final int COMPRESS_SCALE = 1;
public static final int COMPRESS_WRAP = 2;
/**
* Initializes the utility class with the given worlds and relative spatial
* scales.
*
* This resets the Portals configuration to link between the two given
* worlds. One world should be made with Environment.NORMAL, the other with
* Environment.NETHER, otherwise things will break. Also sets the relative
* spatial scale, so that newNormalScale blocks distance in the first world
* correspond to newNetherScale blocks distance in the second world.
*
* @param newNormalWorld The normal world for nether portals to link to.
* @param newNetherWorld The nether world for normal portals to link to.
* @param newNormalScale The relative scale of the normal world to the
* nether world's scale.
* @param newNetherScale The relative scale of the nether world to the
* normal world's scale.
* @return true
*/
public static boolean initialize(Plugin pl, Configuration worldsConfig,
int newKeepAliveRadius) throws IOException {
plugin = pl;
keepAliveRadius = newKeepAliveRadius;
portals = new HashMap<Location, Portal>();
worldLinks = new HashMap<World, World>();
worldScales = new HashMap<World, Integer>();
worldHeights = new HashMap<World, Integer>();
compressionMethods = new HashMap<World, Integer>();
respawnRedirects = new HashMap<World, World>();
blocksToWorlds = new HashMap<BlockData, World>();
worldsToBlocks = new HashMap<World, BlockData>();
entityLastTeleportedTime = new ConcurrentHashMap<Entity, Long>();
forceLoadedChunks = new HashMap<Location, List<Portal>>();
restrictedWorlds = new HashSet<World>();
initializeWorlds(worldsConfig);
File portalsFile = new File(plugin.getDataFolder(), "portals.yml");
YamlConfiguration portalsConfig =
YamlConfiguration.loadConfiguration(portalsFile);
initializePortals(portalsConfig);
portalsConfig.save(portalsFile);
return true;
}
private static void initializeWorlds(Configuration worldsConfig) {
Map<World, String> tempWorldLinks = new HashMap<World, String>();
Set<String> worldNames = worldsConfig.getKeys(false);
if (worldNames == null || worldNames.size() == 0) {
// Generate defaults.
List<World> worlds = plugin.getServer().getWorlds();
World normalWorld = null;
for (World w : worlds) {
if (w.getEnvironment().equals(Environment.NORMAL)) {
normalWorld = w;
break;
}
}
if (normalWorld == null) {
// Ok, not getting more defensive than this. If they made
// 'world' be a non-normal world, sucks to be them.
WorldCreator wc = new WorldCreator("world");
wc.environment(Environment.NORMAL);
normalWorld = wc.createWorld();
}
worlds = plugin.getServer().getWorlds();
World netherWorld = null;
for (World w : worlds) {
if (w.getEnvironment().equals(Environment.NETHER)) {
netherWorld = w;
break;
}
}
if (netherWorld == null) {
// Ok, not getting more defensive than this. If they made
// $WORLD_nether' be a non-nether world, sucks to be them.
WorldCreator wc = new WorldCreator(
normalWorld.getName() + "_nether");
wc.environment(Environment.NETHER);
netherWorld = wc.createWorld();
}
worldLinks.put(normalWorld, netherWorld);
worldLinks.put(netherWorld, normalWorld);
respawnRedirects.put(netherWorld, normalWorld);
worldScales.put(normalWorld, 8);
worldScales.put(netherWorld, 1);
String normalName = normalWorld.getName();
String netherName = netherWorld.getName();
worldsConfig.set(normalName + ".environment", "normal");
worldsConfig.set(normalName + ".destination", netherName);
worldsConfig.set(normalName + ".scale", 8);
worldsConfig.set(netherName + ".environment", "nether");
worldsConfig.set(netherName + ".destination", normalName);
worldsConfig.set(netherName + ".scale", 1);
worldsConfig.set(netherName + ".peaceful", false);
worldsConfig.set(netherName + ".respawnTo", normalName);
return;
}
// Validate and generate worlds.
for (String worldName : worldNames) {
ConfigurationSection worldConfig =
worldsConfig.getConfigurationSection(worldName);
String envtype = worldConfig.getString("environment", "");
World world;
Environment env;
String cgPluginName;
String cgArgs;
Plugin cgPlugin;
ChunkGenerator cg;
if (envtype.equals("")) {
world = plugin.getServer().getWorld(worldName);
if (world == null) {
log.severe("[NETHRAR] World \"" + worldName + "\" " +
"does not exist, and does not have an environment " +
"set. Please set \"" + worldName + ".environment\" " +
"in worlds.yml.");
throw new IllegalArgumentException("Need to set an " +
"environment for world " + worldName + ", or create " +
"the world through some means.");
}
} else {
try {
env = Environment.valueOf(envtype.toUpperCase());
} catch (IllegalArgumentException e) {
log.severe("[NETHRAR] Illegal environment " + envtype +
" specified for world " + worldName + ".");
throw new IllegalArgumentException("Need to set a valid " +
"environment for world " + worldName);
}
world = plugin.getServer().getWorld(worldName);
if (world == null) {
WorldCreator wc = new WorldCreator(worldName);
wc.environment(env);
cgPluginName = worldConfig.getString(
"worldGenerator.name", "");
if (!cgPluginName.equals("")) {
cgPlugin = plugin.getServer().getPluginManager()
.getPlugin(cgPluginName);
if (cgPlugin == null) {
log.severe("[NETHRAR] World generator " +
cgPluginName + " does not exist. Cannot " +
"create world " + worldName + ".");
continue;
}
cgArgs =
worldConfig.getString("worldGenerator.args", "");
cg = cgPlugin.getDefaultWorldGenerator(
worldName, cgArgs);
wc.generator(cg);
}
world = wc.createWorld();
} else if(!world.getEnvironment().equals(env)) {
log.warning("[NETHRAR] World \"" + worldName + "\" " +
"already exists, but is the wrong enviroment. Either " +
"remove the world's directory, or change the " +
"environment in the configuration file.");
}
}
boolean peaceful = worldConfig.getBoolean("peaceful", false);
world.setSpawnFlags(!peaceful, true);
boolean restricted = worldConfig.getBoolean("restricted", false);
if (restricted) {
restrictedWorlds.add(world);
}
int scale = worldConfig.getInt("scale", 1);
worldScales.put(world, scale);
int height = worldConfig.getInt("height", world.getMaxHeight());
worldHeights.put(world, height);
String mode = worldConfig.getString("heightScaleMode", "");
if (mode.equals("clamp")) {
compressionMethods.put(world, COMPRESS_CLAMP);
} else if (mode.equals("scale")) {
compressionMethods.put(world, COMPRESS_SCALE);
} else if (mode.equals("wrap")) {
compressionMethods.put(world, COMPRESS_WRAP);
}
String destWorldName = worldConfig.getString("destination", "");
tempWorldLinks.put(world, destWorldName);
String blockString = worldConfig.getString("worldBlock", "-1");
int blockId = -1, sep = -1;
byte data = 0;
String infostr =
"[NETHRAR] World \"" + worldName + "\""
+ ", environment " + envtype
+ ", scale " + scale
+ ", height " + height;
if (!mode.equals("")) {
infostr = infostr + ", height method " + mode;
}
if ((sep = blockString.indexOf("/")) != -1 && sep > 0) {
blockId = Integer.parseInt(blockString.substring(0, sep));
data = (byte)Integer.parseInt(blockString.substring(sep + 1));
} else {
blockId = Integer.parseInt(blockString);
}
if (blockId != -1) {
BlockData bd =
new BlockData(Material.getMaterial(blockId), data);
blocksToWorlds.put(bd, world);
worldsToBlocks.put(world, bd);
infostr = infostr + ", world block ID " + blockId
+ ", block data " + data;
}
log.info(infostr + ".");
}
// Link worlds and set up metadata.
log.info("[NETHRAR] World graph:");
for (String worldName : worldNames) {
World world = plugin.getServer().getWorld(worldName);
World destWorld = plugin.getServer().getWorld(
tempWorldLinks.get(world));
if (destWorld == null) {
log.severe("World " + world.getName() + " does not have a " +
"valid destination set. Expected destination: " +
tempWorldLinks.get(world) + ".");
continue;
}
worldLinks.put(world, destWorld);
log.info(world.getName() + " --> " + destWorld.getName());
String respawnToName = worldsConfig.getString(
worldName + ".respawnTo", "");
if (!respawnToName.equals("")) {
World respawnTo = plugin.getServer().getWorld(respawnToName);
if (respawnTo != null) {
respawnRedirects.put(world, respawnTo);
}
}
}
log.info("[NETHRAR] World respawn redirects:");
for (Map.Entry<World, World> mapent : respawnRedirects.entrySet()) {
log.info(mapent.getKey().getName() + " respawns redirect to " +
mapent.getValue().getName());
}
log.info("[NETHRAR] Restricted worlds:");
for (World w : restrictedWorlds) {
log.info(w.getName());
}
}
private static void initializePortals(Configuration portalConfig) {
Map<String, Portal> namesToPortals = new HashMap<String, Portal>();
Set<String> portalKeys = portalConfig.getKeys(false);
if (portals == null) {
return;
}
for (String portalKey : portalKeys) {
String worldName =
portalKey.substring(0, portalKey.lastIndexOf(";"));
ConfigurationSection config =
portalConfig.getConfigurationSection(portalKey);
List<Integer> coords = config.getIntegerList("keyblock");
if (coords == null) {
continue;
}
World portalWorld = plugin.getServer().getWorld(worldName);
if (portalWorld == null) {
continue;
}
Block keyBlock = portalWorld.getBlockAt(
coords.get(0), coords.get(1), coords.get(2));
Portal p = getPortalAt(keyBlock);
if (p == null) {
continue;
}
addPortal(p);
namesToPortals.put(portalKey, p);
}
for (String portalKey : portalKeys) {
ConfigurationSection config =
portalConfig.getConfigurationSection(portalKey);
String destKey = config.getString("destination");
boolean prot = config.getBoolean("protected");
Portal source = namesToPortals.get(portalKey);
if (source == null) {
continue;
}
source.setCounterpart(namesToPortals.get(destKey));
Block keyBlock = source.getKeyBlock();
World world = keyBlock.getWorld();
int destX = keyBlock.getX(),
destY = keyBlock.getY(),
destZ = keyBlock.getZ();
if (prot) {
// Build portal block set.
Set<Block> pBlocks = new HashSet<Block>();
if (source.isFacingNorth()) {
for (int z = destZ; z <= destZ + 1; z++) {
pBlocks.add(world.getBlockAt(destX, destY + 0, z));
pBlocks.add(world.getBlockAt(destX, destY + 1, z));
pBlocks.add(world.getBlockAt(destX, destY + 2, z));
}
} else {
for (int x = destX; x <= destX + 1; x++) {
pBlocks.add(world.getBlockAt(x, destY + 0, destZ));
pBlocks.add(world.getBlockAt(x, destY + 1, destZ));
pBlocks.add(world.getBlockAt(x, destY + 2, destZ));
}
}
for (Block b : pBlocks) {
NethrarDefaultListener.protectPortalBlock(b);
}
}
}
}
public static boolean savePortals() throws IOException {
File portalsFile = new File(plugin.getDataFolder(), "portals.yml");
YamlConfiguration portalConfig = new YamlConfiguration();
savePortals(portalConfig);
portalConfig.save(portalsFile);
return true;
}
private static void savePortals(Configuration portalConfig) {
int nonce = 0;
Map<Portal, String> portalKeyMap = new HashMap<Portal, String>();
for (Map.Entry<Location, Portal> ent : portals.entrySet()) {
Portal p = ent.getValue();
World w = p.getKeyBlock().getWorld();
portalKeyMap.put(p, w.getName() + ";" + (nonce++));
}
for (Map.Entry<Location, Portal> ent : portals.entrySet()) {
Portal p = ent.getValue();
Location l = p.getKeyBlock().getLocation();
String portalKey = portalKeyMap.get(p);
String destKey = portalKeyMap.get(p.getCounterpart());
int x = l.getBlockX(), y = l.getBlockY(), z = l.getBlockZ();
List<Integer> locCoords = Arrays.asList(x, y, z);
portalConfig.set(portalKey + ".keyblock", locCoords);
portalConfig.set(portalKey + ".destination", destKey);
portalConfig.set(portalKey + ".protected",
p.getKeyBlock().getWorld().getEnvironment().equals(
Environment.THE_END));
}
}
public static Plugin getPlugin() {
return plugin;
}
/**
* "Registers" the Portal with the mod, and performs relevant global
* initialization based on the new Portal.
*
* Note that this does not add chunks to the keep-alive set.
*/
public static boolean addPortal(Portal p) {
if (keepAliveRadius > 0) {
World w = p.getKeyBlock().getWorld();
int chunkX = p.getKeyBlock().getChunk().getX();
int chunkZ = p.getKeyBlock().getChunk().getZ();
for (int x = chunkX - keepAliveRadius + 1,
endx = chunkX + keepAliveRadius - 1; x <= endx; x++) {
for (int z = chunkZ - keepAliveRadius + 1,
endz = chunkZ + keepAliveRadius - 1; z <= endz; z++) {
Location tempLoc = new Location(w, x, 0, z);
List<Portal> tempList = forceLoadedChunks.get(tempLoc);
if (tempList == null) {
tempList = new LinkedList<Portal>();
tempList.add(p);
forceLoadedChunks.put(tempLoc, tempList);
w.loadChunk(x, z);
} else {
tempList.add(p);
}
}
}
}
Portal oldPortal = portals.get(p.getKeyBlock().getLocation());
if (oldPortal != null) {
removePortal(oldPortal);
}
return portals.put(p.getKeyBlock().getLocation(), p) != null;
}
/**
* Removes the given Portal, and updates mappings accordingly.
*
* This will remove any necessary chunks from the keep-alive list.
*/
public static boolean removePortal(Portal p) {
Block b = p.getKeyBlock();
if (keepAliveRadius > 0) {
int chunkX = b.getChunk().getX();
int chunkZ = b.getChunk().getZ();
World bWorld = b.getWorld();
for (int x = chunkX - keepAliveRadius + 1,
endx = chunkX + keepAliveRadius - 1; x <= endx; x++) {
for (int z = chunkZ - keepAliveRadius + 1,
endz = chunkZ + keepAliveRadius - 1; z <= endz; z++) {
Location tempLoc = new Location(bWorld, x, 0, z);
List<Portal> tempList = forceLoadedChunks.get(tempLoc);
if (tempList != null) {
if (!tempList.remove(p)) {
log.warning("Chunk location " + tempLoc + " did " +
"not have the portal at " + b + " linked to " +
"it.");
}
if (tempList.isEmpty()) {
forceLoadedChunks.remove(tempLoc);
bWorld.unloadChunkRequest(x, z);
}
} else {
log.warning("Chunk location " + tempLoc + " was not " +
"kept loaded when it should have been.");
}
}
}
}
if (p.getCounterpart() != null) {
p.getCounterpart().setCounterpart(null);
}
return portals.remove(b.getLocation()) != null;
}
/** Attempts to remove a Portal whose keyBlock is at the given Block. */
public static boolean removePortalAt(Block b) {
Portal temp = getPortalAt(b);
return removePortal(temp);
}
public static int getScaleFor(World w) {
Integer scale = worldScales.get(w);
if (scale != null) {
return scale;
}
return 0;
}
public static int getHeightFor(World w) {
Integer height = worldHeights.get(w);
if (height != null) {
return height;
}
return w.getMaxHeight();
}
public static int getCompressionMethodBetween(World s, World d) {
Integer mode = compressionMethods.get(d);
if (mode != null) {
return mode;
}
mode = compressionMethods.get(s);
if (mode != null) {
return mode;
}
return 0;
}
public static World getRespawnWorldFor(World sourceWorld) {
return respawnRedirects.get(sourceWorld);
}
public static World getDestWorldFor(Portal p) {
BlockData bd = p.getWorldBlockType();
if (blocksToWorlds.get(bd) != null) {
return blocksToWorlds.get(bd);
}
return getDestWorldFor(p.getKeyBlock().getWorld());
}
public static World getDestWorldFor(World sourceWorld) {
return worldLinks.get(sourceWorld);
}
/**
* Gets the Portal at the given Location, or null if there is none.
* The Location need not be the keyBlock location, but it must be one of
* Material.PORTAL blocks in the portal.
*/
public static Portal getPortalAt(Location loc) {
return getPortalAt(loc.getBlock());
}
/**
* Returns the Portal object corresponding to the given Portal block. One
* will be created if there is not already a Portal object for the given
* portal. Returns null if the block is not a Portal block.
*/
public static Portal getPortalAt(Block b) {
int keyX = b.getX();
int keyY = b.getY();
int keyZ = b.getZ();
World bWorld = b.getWorld();
if (!b.getType().equals(Material.PORTAL)) {
return null;
}
// Get keyBlock.
// Look in -x direction
while (bWorld.getBlockAt(--keyX, keyY, keyZ)
.getType()
.equals(Material.PORTAL));
keyX++;
// Look in -z direction
while (bWorld.getBlockAt(keyX, keyY, --keyZ)
.getType()
.equals(Material.PORTAL));
keyZ++;
// Look in -y direction
while (bWorld.getBlockAt(keyX, --keyY, keyZ)
.getType()
.equals(Material.PORTAL));
keyY++;
Location portalLoc = new Location(b.getWorld(), keyX, keyY, keyZ);
Portal newPortal = portals.get(portalLoc);
if (newPortal == null) {
// Newly entered portal.
// This is the only place Portals are "new'd".
newPortal = new Portal(b.getWorld()
.getBlockAt(keyX, keyY, keyZ));
if (newPortal.isValid()) {
addPortal(newPortal);
} else {
newPortal = null;
}
}
return newPortal;
}
/**
* Finds or creates a portal at the destination, following Notchian-esque
* portal creation semantics.
*
* If there exist portal blocks immediately adjacent to where the new
* portal would be, choose one and link to that portal instead.
*/
public static Portal getOrCreatePortalAt(Portal sourcePortal, Block dest) {
World world = dest.getWorld();
int destX = dest.getX(), destY = dest.getY(), destZ = dest.getZ();
Set<Block> outerAirBlocks = new HashSet<Block>();
Set<Block> innerAirBlocks = new HashSet<Block>();
if (sourcePortal.isFacingNorth()) {
for (int z = destZ; z <= destZ + 1; z++) {
innerAirBlocks.add(world.getBlockAt(destX, destY + 0, z));
innerAirBlocks.add(world.getBlockAt(destX, destY + 1, z));
innerAirBlocks.add(world.getBlockAt(destX, destY + 2, z));
outerAirBlocks.add(world.getBlockAt(destX - 1, destY + 0, z));
outerAirBlocks.add(world.getBlockAt(destX - 1, destY + 1, z));
outerAirBlocks.add(world.getBlockAt(destX - 1, destY + 2, z));
outerAirBlocks.add(world.getBlockAt(destX + 1, destY + 0, z));
outerAirBlocks.add(world.getBlockAt(destX + 1, destY + 1, z));
outerAirBlocks.add(world.getBlockAt(destX + 1, destY + 2, z));
}
} else {
for (int x = destX; x <= destX + 1; x++) {
innerAirBlocks.add(world.getBlockAt(x, destY + 0, destZ));
innerAirBlocks.add(world.getBlockAt(x, destY + 1, destZ));
innerAirBlocks.add(world.getBlockAt(x, destY + 2, destZ));
outerAirBlocks.add(world.getBlockAt(x, destY + 0, destZ - 1));
outerAirBlocks.add(world.getBlockAt(x, destY + 1, destZ - 1));
outerAirBlocks.add(world.getBlockAt(x, destY + 2, destZ - 1));
outerAirBlocks.add(world.getBlockAt(x, destY + 0, destZ + 1));
outerAirBlocks.add(world.getBlockAt(x, destY + 1, destZ + 1));
outerAirBlocks.add(world.getBlockAt(x, destY + 2, destZ + 1));
}
}
Set<Block> frameBlocks = new HashSet<Block>();
if (sourcePortal.isFacingNorth()) {
// Top and bottom
for (int z = destZ - 1; z <= destZ + 2; z++) {
frameBlocks.add(world.getBlockAt(destX, destY - 1, z));
frameBlocks.add(world.getBlockAt(destX, destY + 3, z));
}
// Sides
for (int dy = 0; dy <= 2; dy++) {
frameBlocks.add(world.getBlockAt(destX, destY + dy, destZ - 1));
frameBlocks.add(world.getBlockAt(destX, destY + dy, destZ + 2));
}
} else {
// Top and bottom
for (int x = destX - 1; x <= destX + 2; x++) {
frameBlocks.add(world.getBlockAt(x, destY - 1, destZ));
frameBlocks.add(world.getBlockAt(x, destY + 3, destZ));
}
// Sides
for (int dy = 0; dy <= 2; dy++) {
frameBlocks.add(world.getBlockAt(destX - 1, destY + dy, destZ));
frameBlocks.add(world.getBlockAt(destX + 2, destY + dy, destZ));
}
}
Set<Block> platformBlocks = new HashSet<Block>();
if (sourcePortal.isFacingNorth()) {
platformBlocks.add(world.getBlockAt(
destX + 1, destY - 1, destZ));
platformBlocks.add(world.getBlockAt(
destX + 1, destY - 1, destZ + 1));
platformBlocks.add(world.getBlockAt(
destX - 1, destY - 1, destZ));
platformBlocks.add(world.getBlockAt(
destX - 1, destY - 1, destZ + 1));
} else {
platformBlocks.add(world.getBlockAt(
destX, destY - 1, destZ - 1));
platformBlocks.add(world.getBlockAt(
destX + 1, destY - 1, destZ - 1));
platformBlocks.add(world.getBlockAt(
destX, destY - 1, destZ + 1));
platformBlocks.add(world.getBlockAt(
destX + 1, destY - 1, destZ + 1));
}
// Look for existing portals that interest where this portal would go.
for (Block newAirBlock : outerAirBlocks) {
if (newAirBlock.getType().equals(Material.PORTAL)) {
return getPortalAt(newAirBlock);
}
}
for (Block newAirBlock : innerAirBlocks) {
if (newAirBlock.getType().equals(Material.PORTAL)) {
return getPortalAt(newAirBlock);
}
}
for (Block newFrameBlock : frameBlocks) {
if (newFrameBlock.getType().equals(Material.PORTAL)) {
return getPortalAt(newFrameBlock);
}
}
// No existing portal - try to place one.
// Do our darnest not to accidentally delete an existing lit portal.
// We don't need to test our air blocks, because if there was obsidian
// in the air blocks attacked to a portal, we would detect that portal.
// We just won't delete obsidian if it exists.
// Build and light the portal.
if (restrictedWorlds.contains(dest.getWorld())) {
// This is a restricted world, it is illegal to generate new portals
// in it except by hand.
return null;
}
for (Block newFrameBlock : frameBlocks) {
newFrameBlock.setType(Material.OBSIDIAN);
}
for (Block newAirBlock : innerAirBlocks) {
newAirBlock.setType(Material.AIR);
}
for (Block newAirBlock : outerAirBlocks) {
if (!newAirBlock.getType().equals(Material.OBSIDIAN)) {
newAirBlock.setType(Material.AIR);
}
}
for (Block newPlatformBlock : platformBlocks) {
if (!newPlatformBlock.getType().equals(Material.OBSIDIAN) &&
!newPlatformBlock.getType().equals(Material.PORTAL)) {
newPlatformBlock.setType(Material.STONE);
}
}
if (dest.getWorld().getEnvironment().equals(
Environment.THE_END)) {
// Manually set portal blocks - but if they go out, you're screwed!
// ... if the server restarts ...
for (Block newPortalBlock : innerAirBlocks) {
newPortalBlock.setType(Material.PORTAL);
NethrarDefaultListener.protectPortalBlock(newPortalBlock);
}
return getPortalAt(dest);
}
dest.setType(Material.FIRE);
if (dest.getType().equals(Material.PORTAL)) {
// Successful portal ignition.
return getPortalAt(dest);
}
// Nope!
return null;
}
public static Portal getCounterpartPortalFor(Portal source) {
return getCounterpartPortalFor(source, getDestWorldFor(source));
}
public static Portal getCounterpartPortalFor(
Portal source, World destWorld) {
if (destWorld == null) {
// No outbound edge defined.
return null;
}
// Calculate the counterpart portal's keyblock location.
double destX, destY, destZ;
Block sourceKeyBlock = source.getKeyBlock();
Block destBlock;
World sourceWorld = sourceKeyBlock.getWorld();
double scale = getScaleFor(destWorld) /
(double)getScaleFor(sourceWorld);
int destHeight = getHeightFor(destWorld);
int compressionMethod =
getCompressionMethodBetween(sourceWorld, destWorld);
destY = sourceKeyBlock.getY();
switch (compressionMethod) {
case COMPRESS_CLAMP:
destY = destY > destHeight ? destHeight : destY;
break;
case COMPRESS_SCALE:
double heightScale = destHeight /
(double)getHeightFor(sourceWorld);
destY = Math.floor(sourceKeyBlock.getY() * heightScale);
break;
case COMPRESS_WRAP:
destY = destY % destHeight;
break;
}
int heightCompressionMethod =
getCompressionMethodBetween(sourceWorld, destWorld);
destX = Math.floor(sourceKeyBlock.getX() * scale);
destZ = Math.floor(sourceKeyBlock.getZ() * scale);
// If the destination world is 'larger', then we need to 'look around'
// more to find potential portals to link to, based on collision
// detection rules. Heuristic is, essentially, "If I were to step into
// the other portal, and it would link to the one I am entering here,
// then link to that other portal."
// Generalize.
if (scale > 1) {
/*
* The following diagrams define the 'macrogrid' area to search for
* a portal to link to. A 'macrogrid' square is a scale x scale area
* on the ground, where any portal in that square would have it's
* keyblock map to the same location in the other, smaller, world.
* The diagrams are the result of exhaustive manual generation and
* collision detection, done with pencils, paper, and fingers.
*
* o refers to 'opposite' zones where only portals that are the
* opposite orientation would collide with the source portal. s is
* 'same', wherein only portals of the same orientation would
* collide with the source portal.
*
* For portals facing north, this is the detection macrogrid.
* Regions are defined by minimum, inclusive, and maximum,
* exclusive, deltas from the portal's macrogrid square.
* oo ominx: -2, omaxx: -1; ominz: 0, omaxz: +2
* oxxx ominx: -1, maxx: 0; ominz: +2, omaxz: +3;
* minx/maxx same; minz: -1, maxz: +2
* xxpxs minx: 0, maxx: +1; minz: -1, maxz: +3;
* sminx/smaxx same; sminz: -2, smaxz: -1
* xxx minx: +1, maxx: +2; minz: -1; maxz: +2
*
* West-facing portals have regions defined column-wise.
* s
* xxx
* xpxo p
* xxxo for portal p
* xo
* 1234
*
* 1: minx: -1, maxx: +2; minz: +1, maxz: +2;
* 2: sminx: -2, smaxx: -1; sminz: 0, smaxz: +1;
* minx: -1, maxx: +3; minz/maxz same
* 3: minx: -1, maxx: +2; minz: -1, maxz: 0;
* ominx: +2, omaxx: +3; ominz/omaxz same
* 4: ominx: 0, omaxx: +2; ominz: -2, omaxz: -1;
*/
// minx,maxx,minz,maxz, repeating
int[] ndeltas = {-1,0,-1,2, 0,1,-1,3, 1,2,-1,2};
int[] nsdeltas = {0,1,-2,-1};
int[] nodeltas = {-2,-1,0,2, -1,0,2,3};
int[] wdeltas = {-1,2,1,2, -1,3,0,1, -1,2,-1,0};
int[] wsdeltas = {-2,-1,0,1};
int[] wodeltas = {2,3,-1,0, 0,2,-2,-1};
int minX, minY, minZ, maxX, maxY, maxZ, sourceX, sourceY, sourceZ;
sourceX = sourceKeyBlock.getX();
sourceY = sourceKeyBlock.getY();
sourceZ = sourceKeyBlock.getZ();
minY = sourceY - 1;
maxY = sourceY + 3;
Set<Portal> potentialPortals = new HashSet<Portal>();
if (source.isFacingNorth()) {
potentialPortals.addAll(findPortalsInDeltaRegions(
ndeltas, scale, sourceKeyBlock, destWorld));
potentialPortals.addAll(findPortalsInDeltaRegions(
nsdeltas, scale, sourceKeyBlock, destWorld));
potentialPortals.addAll(findPortalsInDeltaRegions(
nodeltas, scale, sourceKeyBlock, destWorld));
} else {
potentialPortals.addAll(findPortalsInDeltaRegions(
wdeltas, scale, sourceKeyBlock, destWorld));
potentialPortals.addAll(findPortalsInDeltaRegions(
wsdeltas, scale, sourceKeyBlock, destWorld));
potentialPortals.addAll(findPortalsInDeltaRegions(
wodeltas, scale, sourceKeyBlock, destWorld));
}
Vector destVector = new Vector(destX, destY, destZ);
double minDistSquared = Double.MAX_VALUE;
Portal candidatePortal = null;
for (Portal pp : potentialPortals) {
Vector tempVec = new Vector(pp.getKeyBlock().getX(),
pp.getKeyBlock().getY(), pp.getKeyBlock().getZ());
double tempDist = tempVec.distanceSquared(destVector);
// Need to do add'l checks here.
if (tempDist < minDistSquared) {
minDistSquared = tempDist;
candidatePortal = pp;
}
}
if (candidatePortal != null) {
linkPortals(source, candidatePortal);
return candidatePortal;
}
}
// Don't let the portal go into bedrock.
// Layer 6 for the portal, layer 5 for the obsidian
// Bedrock at layer 4 and below.
// Alternatively, in the Nether, layer 119 is the highest safe point
// for a portal keyblock to exist without accidentally nuking bedrock.
if (destY < 6) {
destY = 6;
}
if (destWorld.getEnvironment().equals(Environment.NETHER) &&
destY > destHeight - 9) {
destY = destHeight - 9;
}
destBlock = destWorld.getBlockAt((int)destX, (int)destY, (int)destZ);
Portal dest = getOrCreatePortalAt(source, destBlock);
linkPortals(source, dest);
return dest;
}
/**
* Finds portals in the given delta regions, as defined by the code in
* getCounterpartPortalFor(Portal).
*
* @param deltas An array specifying the closed/open range to search for
* for portals. The first coordinate is an inclusive delta x, the next
* is an exclusive x delta, then an inclusive/exclusive z delta pair.