-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathRadioBeacon.java
More file actions
1467 lines (1182 loc) · 54.2 KB
/
Copy pathRadioBeacon.java
File metadata and controls
1467 lines (1182 loc) · 54.2 KB
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
/*
http://dev.bukkit.org/server-mods/radiobeacon/
Copyright (c) 2012, Mushroom Hostage
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package me.exphc.RadioBeacon;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.UUID;
import java.util.Iterator;
import java.util.logging.Logger;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.ConcurrentHashMap;
import java.io.*;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.*;
import org.bukkit.event.*;
import org.bukkit.event.block.*;
import org.bukkit.event.player.*;
import org.bukkit.event.weather.*;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.Material.*;
import org.bukkit.block.*;
import org.bukkit.entity.*;
import org.bukkit.command.*;
import org.bukkit.inventory.*;
import org.bukkit.configuration.*;
import org.bukkit.configuration.file.*;
import org.bukkit.*;
// 2D integral location (unlike Bukkit's location)
class AntennaXZ implements Comparable {
World world;
int x, z;
public AntennaXZ(World w, int x0, int z0) {
world = w;
x = x0;
z = z0;
}
public AntennaXZ(Location loc) {
world = loc.getWorld();
x = loc.getBlockX();
z = loc.getBlockZ();
}
public Location getLocation(double y) {
return new Location(world, x + 0.5, y, z + 0.5);
}
public String toString() {
return x + "," + z;
}
public int compareTo(Object obj) {
if (!(obj instanceof AntennaXZ)) {
return -1;
}
AntennaXZ rhs = (AntennaXZ)obj;
if (!world.equals(rhs.world)) {
return world.getName().compareTo(rhs.world.getName());
}
if (x - rhs.x != 0) {
return x - rhs.x;
} else if (z - rhs.z != 0) {
return z - rhs.z;
}
return 0;
}
public boolean equals(Object obj) {
return compareTo(obj) == 0; // why do I have to do this myself?
}
public int hashCode() {
// lame hashing TODO: improve?
return x * z;
}
}
// Compare antennas based on their distance from some fixed location
class AntennaDistanceComparator implements Comparator<Antenna> {
Location otherLoc;
public AntennaDistanceComparator(Location otherLoc) {
this.otherLoc = otherLoc;
}
public int compare(Antenna a, Antenna b) {
return a.getDistance(otherLoc) - b.getDistance(otherLoc);
}
}
class Antenna implements Comparable<Antenna> {
// TODO: map by world first? see discussion http://forums.bukkit.org/threads/performance-question-merge-world-with-chunk-coordinates-or-not.60160/#post-969934
static public ConcurrentHashMap<AntennaXZ, Antenna> xz2Ant = new ConcurrentHashMap<AntennaXZ, Antenna>();
final AntennaXZ xz;
final int baseY;
int tipY;
String message;
final boolean isRelay;
// Normal antenna creation method
public Antenna(Location loc) {
xz = new AntennaXZ(loc);
baseY = (int)loc.getY();
tipY = baseY;
xz2Ant.put(xz, this);
isRelay = loc.getBlock().getType() == AntennaConf.fixedBaseRelayMaterial;
RadioBeacon.log("New antenna " + this);
Bukkit.getServer().getPluginManager().callEvent(new AntennaChangeEvent(this, AntennaChangeEvent.Action.CREATE));
}
// Load from serialized format (from disk)
public Antenna(Map<?,?> d) {
World world;
if (d.get("world") != null) {
// Legacy world
world = Bukkit.getWorld(UUID.fromString((String)d.get("world")));
if (world == null) {
// TODO: gracefully handle, and skip this antenna (maybe its world was deleted, no big deal)
throw new RuntimeException("Antenna loading failed, no world with UUID: " + d.get("world"));
}
} else {
world = Bukkit.getWorld((String)d.get("W"));
if (world == null) {
throw new RuntimeException("Antenna loading failed, no world with name: "+ d.get("W"));
}
}
if (d.get("baseX") != null) {
// Legacy format, tipX and tipZ are redundant
xz = new AntennaXZ(world, (Integer)d.get("baseX"), (Integer)d.get("baseZ"));
} else {
xz = new AntennaXZ(world, (Integer)d.get("X"), (Integer)d.get("Z"));
}
baseY = (Integer)d.get("baseY");
tipY = (Integer)d.get("tipY");
if (d.get("relay") != null) {
isRelay = (Boolean)d.get("relay");
} else {
isRelay = false;
}
setMessage((String)d.get("message"));
xz2Ant.put(xz, this);
RadioBeacon.log("Loaded antenna " + this);
}
// Dump to serialized format (to disk)
public HashMap<String,Object> dump() {
HashMap<String,Object> d = new HashMap<String,Object>();
// For simplicity, dump as a flat data structure
//d.put("world", xz.world.getUID().toString());
d.put("W", xz.world.getName());
d.put("X", xz.x);
d.put("Z", xz.z);
d.put("baseY", baseY);
d.put("tipY", tipY);
d.put("message", message);
d.put("relay", isRelay);
// TODO: other user data?
return d;
}
public String toString() {
return "<Antenna r="+getBroadcastRadius()+" height="+getHeight()+" xz="+xz+" baseY="+baseY+" tipY="+tipY+" w="+xz.world.getName()+
" l="+getLightningAttractRadius()+" p="+getBlastPower()+
" r="+isRelay+" "+
" m="+message+">";
}
public static Antenna getAntenna(Location loc) {
return getAntenna(new AntennaXZ(loc));
}
public static Antenna getAntenna(AntennaXZ loc) {
Antenna a = xz2Ant.get(loc);
return a;
}
// Get an antenna by base directly adjacent to given location
public static Antenna getAntennaByAdjacent(Location loc) {
for (int x = -1; x <= 1; x += 1) {
for (int z = -1; z <= 1; z += 1) {
Antenna ant = getAntenna(loc.clone().add(x+0.5, 0, z+0.5));
if (ant != null) {
return ant;
}
}
}
return null;
}
public static void destroy(Antenna ant) {
if (xz2Ant.remove(ant.xz) == null) {
throw new RuntimeException("No antenna at "+ant.xz+" to destroy!");
}
RadioBeacon.log("Destroyed antenna " + ant);
Bukkit.getServer().getPluginManager().callEvent(new AntennaChangeEvent(ant, AntennaChangeEvent.Action.DESTROY));
}
// Set or get textual message being broadcasted (may be null for none)
public void setMessage(String m) {
message = m;
Bukkit.getServer().getPluginManager().callEvent(new AntennaChangeEvent(this, AntennaChangeEvent.Action.MESSAGE));
}
public String getMessage() {
return message;
}
// Extend or shrink size of the antenna, updating the new center location
public void setTipY(int newTipY) {
RadioBeacon.log("Move tip from "+tipY+" to + " +newTipY);
tipY = newTipY;
Bukkit.getServer().getPluginManager().callEvent(new AntennaChangeEvent(this, AntennaChangeEvent.Action.TIP_MOVE));
}
// Set new tip at highest Y with iron fences, starting at given Y
// Will set at or above placedY
public void setTipYAtHighest(int placedY) {
World world = xz.world;
int x = xz.x;
int z = xz.z;
// Starting at location, get the highest Y coordinate in the world that is part of the antenna material
// Look up until hit first non-antenna material
// If pillaring up, won't enter loop at all
// But we have to check, so antennas with gaps can be 'repaired' to extend their
// range to their full tip
int newTipY = placedY;
while(world.getBlockTypeIdAt(x, newTipY, z) == AntennaConf.fixedAntennaMaterial.getId()) {
newTipY += 1;
}
setTipY(newTipY);
}
public Location getTipLocation() {
return xz.getLocation(tipY);
}
public Location getSourceLocation() {
return AntennaConf.fixedRadiateFromTip ? getTipLocation() : getBaseLocation();
}
public Location getBaseLocation() {
return xz.getLocation(baseY);
}
public int getHeight() {
return tipY - baseY;
}
// Get radius of broadcasts for fixed antenna
public int getBroadcastRadius() {
int height = getHeight();
if (AntennaConf.fixedMaxHeight != 0 && height > AntennaConf.fixedMaxHeight) {
// Above max will not extend range
height = AntennaConf.fixedMaxHeight;
}
// TODO: exponential not multiplicative?
int radius = AntennaConf.fixedInitialRadius + height * AntennaConf.fixedRadiusIncreasePerBlock;
if (xz.world.hasStorm()) {
radius = (int)((double)radius * AntennaConf.fixedRadiusStormFactor);
}
if (xz.world.isThundering()) {
radius = (int)((double)radius * AntennaConf.fixedRadiusThunderFactor);
}
if (isRelay) {
radius = (int)((double)radius * AntennaConf.fixedRadiusRelayFactor);
}
return radius;
}
// Get radius of reception for fixed antenna
// This is normally same as broadcast, but can be changed
public int getReceptionRadius() {
if (AntennaConf.fixedReceptionRadiusDivisor == 0) {
// special meaning no reception radius (must directly overlap)
return 0;
}
int receptionRadius = getBroadcastRadius() / AntennaConf.fixedReceptionRadiusDivisor;
return receptionRadius;
}
// 2D radius within lightning strike will strike base
public int getLightningAttractRadius() {
int attractRadius = (int)(AntennaConf.fixedLightningAttractRadiusInitial + getHeight() * AntennaConf.fixedLightningAttractRadiusIncreasePerBlock);
return Math.min(attractRadius, AntennaConf.fixedLightningAttractRadiusMax);
}
// Explosive power on direct lightning strike
public float getBlastPower() {
float power = (float)(AntennaConf.fixedBlastPowerInitial + getHeight() * AntennaConf.fixedBlastPowerIncreasePerBlock);
return Math.min(power, (float)AntennaConf.fixedBlastPowerMax);
}
public boolean withinReceiveRange(Location receptionLoc, int receptionRadius) {
if (!xz.world.equals(receptionLoc.getWorld())) {
// No cross-world communication... yet! TODO: how?
return false;
}
// Sphere intersection of broadcast range from source
return getSourceLocation().distanceSquared(receptionLoc) < square(getBroadcastRadius() + receptionRadius);
}
// Square a number, returning a double as to not overflow if x>sqrt(2**31)
private static double square(int x) {
return (double)x * (double)x;
}
// Get 3D distance from tip
public int getDistance(Location receptionLoc) {
return (int)Math.sqrt(getSourceLocation().distanceSquared(receptionLoc));
}
// Get 2D distance from antenna xz
public double get2dDistance(Location otherLoc) {
Location otherLoc2d = otherLoc.clone();
Location baseLoc = getBaseLocation();
otherLoc2d.setY(baseLoc.getY());
return baseLoc.distance(otherLoc2d);
}
// Return whether antenna is in same world as other location
public boolean inSameWorld(Location otherLoc) {
return xz.world.equals(otherLoc.getWorld());
}
// Receive antenna signals (to this antenna) and show to player
public void receiveSignals(Player player) {
player.sendMessage("Antenna range: " + getBroadcastRadius() + " m"); //, lightning attraction: " + getLightningAttractRadius() + " m" + ", blast power: " + getBlastPower());
receiveSignals(player, getSourceLocation(), getReceptionRadius(), false);
}
// Update any nearby relay antennas with message from this antenna, informing the player
public void notifyRelays(Player player) {
List<Antenna> nearbyAnts = receiveSignals(player, getSourceLocation(), getReceptionRadius(), false);
// Update any relay antennas within range
for (Antenna ant: nearbyAnts) {
if (ant.isRelay) {
int distance = ant.getDistance(getSourceLocation());
ant.setMessage("[Relayed " + distance + " m] " + this.getMessage());
RadioBeacon.log("Notified relay: " + ant);
player.sendMessage("Notified relay " + distance + " m away");
}
}
}
// Receive signals from mobile radio held by player
static public void receiveSignalsAtPlayer(Player player) {
ItemStack item = player.getItemInHand();
if (item == null || item.getTypeId() != AntennaConf.mobileRadioItem && AntennaPlayerListener.playerRadioEnabled(player)) {
// Compass = mobile radio
return;
}
Location receptionLoc = player.getLocation();
int receptionRadius = getCompassRadius(item, player);
Antenna.receiveSignals(player, receptionLoc, receptionRadius, true);
}
// Get reception radius for a stack of compasses
// The default of one compass has a radius of 0, meaning you must be directly within range,
// but more compasses can increase the range further
static public int getCompassRadius(ItemStack item, Player player) {
World world = player.getWorld();
// Bigger stack of compasses = better reception!
int n = item.getAmount() - 1;
int receptionRadius = AntennaConf.mobileInitialRadius + n * AntennaConf.mobileIncreaseRadius;
// If scan bonus enabled, add
if (AntennaConf.mobileScanBonusRadius != 0) {
Integer bonusObject = AntennaPlayerListener.playerScanBonus.get(player.getUniqueId());
if (bonusObject != null) {
receptionRadius += bonusObject.intValue();
}
}
if (world.hasStorm()) {
receptionRadius = (int)((double)receptionRadius * AntennaConf.mobileRadiusStormFactor);
}
if (world.isThundering()) {
receptionRadius = (int)((double)receptionRadius * AntennaConf.mobileRadiusThunderFactor);
}
receptionRadius = Math.min(receptionRadius, AntennaConf.mobileMaxRadius);
return receptionRadius;
}
// Receive signals from standing at any location
static public List<Antenna> receiveSignals(Player player, Location receptionLoc, int receptionRadius, boolean signalLock) {
int count = 0;
List<Antenna> nearbyAnts = new ArrayList<Antenna>();
for (Map.Entry<AntennaXZ,Antenna> pair : Antenna.xz2Ant.entrySet()) {
Antenna otherAnt = pair.getValue();
if (otherAnt.withinReceiveRange(receptionLoc, receptionRadius)) {
//RadioBeacon.log("Received transmission from " + otherAnt);
int distance = otherAnt.getDistance(receptionLoc);
if (distance == 0) {
// Squelch self-transmissions to avoid interference
continue;
}
nearbyAnts.add(otherAnt);
}
}
// Sort so reception list is deterministic, for target index
Collections.sort(nearbyAnts, new AntennaDistanceComparator(receptionLoc));
for (Antenna otherAnt: nearbyAnts) {
notifySignal(player, receptionLoc, otherAnt, otherAnt.getDistance(receptionLoc));
}
count = nearbyAnts.size();
if (count == 0) {
if (AntennaConf.mobileNoSignalsMessage != null && !AntennaConf.mobileNoSignalsMessage.equals("")) {
player.sendMessage(AntennaConf.mobileNoSignalsMessage.replace("%d", ""+receptionRadius));
}
} else if (signalLock) {
if (AntennaConf.mobileSignalLock) {
// Player radio compass targetting
Integer targetInteger = AntennaPlayerListener.playerTargets.get(player.getUniqueId());
Location targetLoc;
int targetInt;
if (targetInteger == null) {
targetInt = 0;
} else {
targetInt = Math.abs(targetInteger.intValue()) % count;
}
Antenna antLoc = nearbyAnts.get(targetInt);
targetLoc = antLoc.getSourceLocation();
if (AntennaConf.mobileSetCompassTarget) {
player.setCompassTarget(targetLoc);
}
String message = antLoc.getMessage();
player.sendMessage("Locked onto signal at " + antLoc.getDistance(player.getLocation()) + " m" + (message == null ? "" : ": " + message));
//RadioBeacon.log("Targetting " + targetLoc);
}
}
return nearbyAnts;
}
// Tell player about an incoming signal from an antenna
static private void notifySignal(Player player, Location receptionLoc, Antenna ant, int distance) {
String message = "";
if (ant.message != null) {
message = ": " + ant.message;
}
player.sendMessage("Received transmission (" + distance + " m)" + message);
}
// Check if antenna is intact, what we know about it matching reality
// Returns whether had to fix it
public boolean checkIntact() {
World world = xz.world;
int x = xz.x;
int z = xz.z;
// Base
Location base = new Location(world, x, baseY, z);
if (base.getBlock() == null || !AntennaConf.isFixedBaseMaterial(base.getBlock().getType())) {
RadioBeacon.log("checkIntact: antenna is missing base!");
destroy(this);
return false;
}
// Antenna
for (int y = baseY + 1; y < tipY; y += 1) {
Location piece = new Location(world, x, y, z);
if (piece.getBlock() == null || piece.getBlock().getType() != AntennaConf.fixedAntennaMaterial) {
RadioBeacon.log("checkIntact: antenna is shorter than expected!");
setTipY(y);
return false;
}
}
return true;
}
public static void checkIntactAll(CommandSender sender) {
int count = 0, fixed = 0;
for (Map.Entry<AntennaXZ,Antenna> pair : Antenna.xz2Ant.entrySet()) {
Antenna ant = pair.getValue();
if (!ant.checkIntact()) {
fixed += 1;
}
count += 1;
}
sender.sendMessage("Updated "+fixed+" of "+count+" antennas");
}
// Delegate comparison to location
public int compareTo(Antenna otherAnt) {
return xz.compareTo(otherAnt.xz);
}
}
// Task to check affected antennas after nearby explosion
class AntennaExplosionReactionTask implements Runnable {
Set<AntennaXZ> affected;
RadioBeacon plugin;
public AntennaExplosionReactionTask(RadioBeacon pl, Set<AntennaXZ> a) {
plugin = pl;
affected = a;
}
public void run() {
for (AntennaXZ xz: affected) {
Antenna ant = Antenna.getAntenna(xz);
if (ant != null) {
RadioBeacon.log("Explosion affected "+ant);
ant.checkIntact();
}
}
}
}
class AntennaBlockListener implements Listener {
RadioBeacon plugin;
public AntennaBlockListener(RadioBeacon plugin) {
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(this, plugin);
}
// Building an antenna
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onBlockPlace(BlockPlaceEvent event) {
Block block = event.getBlock();
Player player = event.getPlayer();
if (AntennaConf.isFixedBaseMaterial(block.getType())) {
// Base material for antenna, if powered
if (block.isBlockPowered() || block.isBlockIndirectlyPowered()) {
if (!player.hasPermission("radiobeacon.create")) {
String message = AntennaConf.fixedDenyCreateMessage;
if (message != null && !message.equals("")) {
player.sendMessage(message);
}
return;
}
if (block.getY() < AntennaConf.fixedBaseMinY) {
player.sendMessage("Not creating antenna below depth of " + AntennaConf.fixedBaseMinY + " m");
} else {
Antenna ant = new Antenna(block.getLocation());
// Usually, will be placing a new antenna from scratch.. but if they are repairing
// look for the highest iron bars above it
Location above = block.getLocation().add(0, 1, 0);
if (above.getBlock().getType() == AntennaConf.fixedAntennaMaterial) {
ant.setTipYAtHighest(above.getBlockY());
}
if (ant.isRelay) {
player.sendMessage("New relay antenna created");
} else {
player.sendMessage("New antenna created"); //, with range "+ant.getBroadcastRadius()+" m");
}
}
} else {
if (AntennaConf.fixedUnpoweredNagMessage != null && !AntennaConf.fixedUnpoweredNagMessage.equals("")) {
player.sendMessage(AntennaConf.fixedUnpoweredNagMessage);
}
}
} else if (block.getType() == AntennaConf.fixedAntennaMaterial) {
Antenna ant = Antenna.getAntenna(block.getLocation());
if (ant == null) {
// No antenna at this xz column to extend
return;
}
int placedY = block.getLocation().getBlockY();
if (placedY < ant.baseY) {
// Coincidental placement below antenna
return;
}
if (placedY > ant.tipY + 1) {
// Might be trying to extend, but it is too far above the tip
// so is not (yet) contiguous
return;
}
int oldRadius = ant.getBroadcastRadius();
ant.setTipYAtHighest(placedY);
int newRadius = ant.getBroadcastRadius();
if (oldRadius == newRadius) {
player.sendMessage("Reached maximum " + newRadius + " m");
} else {
player.sendMessage("Extended antenna range to " + newRadius + " m");
}
}
}
// Destroying an antenna
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onBlockBreak(BlockBreakEvent event) {
Block block = event.getBlock();
World world = block.getWorld();
if (AntennaConf.isFixedBaseMaterial(block.getType())) {
Antenna ant = Antenna.getAntenna(block.getLocation());
if (ant == null) {
// No antenna at this xz column
return;
}
if (ant.baseY != block.getLocation().getBlockY()) {
// A coincidental iron block above or below the actual antenna base
return;
}
ant.destroy(ant);
event.getPlayer().sendMessage("Destroyed antenna");
} else if (block.getType() == AntennaConf.fixedAntennaMaterial) {
Antenna ant = Antenna.getAntenna(block.getLocation());
if (ant == null) {
return;
}
int destroyedY = block.getLocation().getBlockY();
if (destroyedY < ant.baseY || destroyedY > ant.tipY) {
// A coincidental antenna block below or above the antenna, ignore
return;
}
// Look down from the broken tip, to the first intact antenna/base piece
int newTipY = destroyedY;
int pieceType;
int x = block.getLocation().getBlockX();
int z = block.getLocation().getBlockZ();
// Nearly always, this will only execute once, but if the antenna changed
// without us knowing, just be sure, and check the block(s) below until
// we find valid antenna material. Note, this will only find the first
// gap--if somehow other blocks below get destroyed, we won't know.
do {
newTipY -= 1;
pieceType = world.getBlockTypeIdAt(x, newTipY, z);
} while(!AntennaConf.isFixedBaseMaterial(pieceType) &&
pieceType != AntennaConf.fixedAntennaMaterial.getId() &&
newTipY > 0);
ant.setTipY(newTipY);
event.getPlayer().sendMessage("Shrunk antenna range to " + ant.getBroadcastRadius() + " m");
} else if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) {
Antenna ant = Antenna.getAntennaByAdjacent(block.getLocation());
if (ant == null) {
return;
}
event.getPlayer().sendMessage("Cleared antenna message");
ant.setMessage(null);
// do not update relay
}
}
// Signs to set transmission message
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onSignChange(SignChangeEvent event) {
Block block = event.getBlock();
String[] text = event.getLines();
Antenna ant = Antenna.getAntennaByAdjacent(block.getLocation());
if (ant != null) {
Player player = event.getPlayer();
if (ant.isRelay) {
player.sendMessage("To set a relay message, build a normal antenna within range of this relay");
event.setCancelled(true);
block.breakNaturally();
return;
}
if (!player.hasPermission("radiobeacon.addmessage")) {
String message = AntennaConf.fixedDenyAddMessageMessage;
if (message != null && !message.equals("")) {
player.sendMessage(message);
}
event.setCancelled(true);
if (AntennaConf.fixedDenyAddMessageBreak) {
block.breakNaturally();
}
return;
}
ant.setMessage(joinString(text));
player.sendMessage("Set transmission message: " + ant.message);
// setting message is a signal to update relays
ant.notifyRelays(player);
}
}
public static String joinString(String[] a) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < a.length; i+= 1) {
buffer.append(a[i]);
buffer.append(" ");
}
return buffer.toString();
}
// Currently antennas retain their magnetized properties even when redstone current is removed
/*
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onBlockRedstoneChange(BlockRedstoneEvent event) {
// TODO: find out how to disable antennas, get when block becomes unpowered
World world = event.getBlock().getWorld();
if (event.getOldCurrent() == 0) {
// TODO: find antenna at location and disable
RadioBeacon.log("current turned off at "+event.getBlock());
for (Antenna ant: plugin.ants) {
// TODO: efficiency
Block block = world.getBlockAt(ant.location);
RadioBeacon.log("ant block:"+block);
}
}
}
*/
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onEntityExplode(EntityExplodeEvent event) {
if (event.isCancelled()) {
return;
}
Set<AntennaXZ> affected = new HashSet<AntennaXZ>();
for (Block block: event.blockList()) {
Antenna ant = Antenna.getAntenna(block.getLocation());
if (ant != null) {
affected.add(ant.xz);
RadioBeacon.log("Explosion affected "+ant);
ant.checkIntact();
}
}
if (affected.size() > 0) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new AntennaExplosionReactionTask(plugin, affected), AntennaConf.fixedExplosionReactionDelay);
}
}
}
class AntennaPlayerListener implements Listener {
RadioBeacon plugin;
// Note, using UUID instead of Player for HashMap for reasons on
// https://github.com/Bukkit/CraftBukkit/commit/2ae0b94ecf4f168a65f585b802b1f886a6cd7e32#-P0
// Compass targets index selection
static ConcurrentHashMap<UUID, Integer> playerTargets = new ConcurrentHashMap<UUID, Integer>();
// How many scan iterations the player has faithfully held onto their compass for
static ConcurrentHashMap<UUID, Integer> playerScanBonus = new ConcurrentHashMap<UUID, Integer>();
// Whether player portable radio has been disabled using /toggleradio
static ConcurrentHashMap<UUID, Boolean> playerDisabled = new ConcurrentHashMap<UUID, Boolean>();
static boolean playerRadioEnabled(Player player) {
Boolean disabledObject = AntennaPlayerListener.playerDisabled.get(player.getUniqueId());
boolean disabled = false;
if (disabledObject != null) {
disabled = disabledObject.booleanValue();
}
return !disabled;
}
public AntennaPlayerListener(RadioBeacon pl) {
plugin = pl;
Bukkit.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onPlayerInteract(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
ItemStack item = event.getItem();
Player player = event.getPlayer();
if (block != null && AntennaConf.isFixedBaseMaterial(block.getType())) {
Antenna ant = Antenna.getAntenna(block.getLocation());
if (ant == null) {
return;
}
ant.receiveSignals(player);
} else if (block != null && block.getType() == Material.WALL_SIGN) {
for (int dx = -1; dx <= 1; dx += 1) {
for (int dz = -1; dz <= 1; dz += 1) {
Antenna ant = Antenna.getAntenna(block.getLocation().add(dx, 0, dz));
if (ant != null) {
ant.receiveSignals(player);
}
}
}
// TODO: and if click anywhere within antenna? maybe not unless holding compass
} else if (item != null && item.getTypeId() == AntennaConf.mobileRadioItem && AntennaPlayerListener.playerRadioEnabled(player)) {
if (AntennaConf.mobileShiftTune) {
// hold Shift + click to tune
if (!player.isSneaking()) {
return;
}
}
// Increment target index
Integer targetInteger = playerTargets.get(player.getUniqueId());
int targetInt;
if (targetInteger == null) {
playerTargets.put(player.getUniqueId(), 0);
targetInt = 0;
} else {
// Tune up or down
int delta;
if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) {
delta = -1;
if (!AntennaConf.mobileRightClickTuneDown) {
return;
}
} else {
delta = 1;
if (!AntennaConf.mobileLeftClickTuneUp) {
return;
}
}
// TODO: show direction in message?
targetInt = targetInteger.intValue() + delta;
playerTargets.put(player.getUniqueId(), targetInt);
}
int receptionRadius = Antenna.getCompassRadius(item, player);
player.sendMessage("Tuned radio" + (receptionRadius == 0 ? "" : " (range " + receptionRadius + " m)"));
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onItemHeldChange(PlayerItemHeldEvent event) {
Player player = event.getPlayer();
ItemStack item = player.getInventory().getItem(event.getNewSlot());
if (item != null && item.getTypeId() == AntennaConf.mobileRadioItem && AntennaPlayerListener.playerRadioEnabled(player)) {
// TODO: this actually doesn't receive signals on change, since this method checks
// the player's items in hand, and the event is called before they actually change -
// but, I actually like this design better since the player has to wait to receive.
Antenna.receiveSignalsAtPlayer(player);
} else {
// if scan increase is enabled, changing items resets scan bonus
if (AntennaConf.mobileScanBonusRadius != 0) {
playerScanBonus.put(player.getUniqueId(), 0);
}
}
}
}
// Periodically check for nearby signals to receive at mobile compass radios
class ReceptionTask implements Runnable {
RadioBeacon plugin;
int taskId;
public ReceptionTask(RadioBeacon plugin) {
this.plugin = plugin;
}
public void run() {
for (Player player: Bukkit.getOnlinePlayers()) {
ItemStack item = player.getItemInHand();
if (item != null && item.getTypeId() == AntennaConf.mobileRadioItem && AntennaPlayerListener.playerRadioEnabled(player)) {
// if scan increase is enabled, increment scan # each scan
if (AntennaConf.mobileScanBonusRadius != 0) {
Integer scanBonusObject = AntennaPlayerListener.playerScanBonus.get(player.getUniqueId());
int scanBonus = scanBonusObject == null ? 0 : scanBonusObject.intValue();
int newScanBonus = scanBonus + AntennaConf.mobileScanBonusRadius;
newScanBonus = Math.min(newScanBonus, AntennaConf.mobileScanBonusMaxRadius);
AntennaPlayerListener.playerScanBonus.put(player.getUniqueId(), newScanBonus);
}
// Compass = mobile radio
Antenna.receiveSignalsAtPlayer(player);
}
}
AntennaConf.saveAntennas(plugin);
}
}
class AntennaConf {
// Configuration options
static int fixedInitialRadius;
static int fixedRadiusIncreasePerBlock;