-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Laser.java
1207 lines (1039 loc) · 43.8 KB
/
Laser.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
package fr.skytasul.guardianbeam;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
/**
* A whole class to create Guardian Lasers and Ender Crystal Beams using packets and reflection.<br>
* Inspired by the API
* <a href="https://www.spigotmc.org/resources/guardianbeamapi.18329">GuardianBeamAPI</a><br>
* <b>1.9 -> 1.20.4</b>
*
* @see <a href="https://github.com/SkytAsul/GuardianBeam">GitHub repository</a>
* @version 2.3.6
* @author SkytAsul
*/
public abstract class Laser {
protected final int distanceSquared;
protected final int duration;
protected boolean durationInTicks = false;
protected Location start;
protected Location end;
protected Plugin plugin;
protected BukkitRunnable main;
protected BukkitTask startMove;
protected BukkitTask endMove;
protected Set<Player> show = ConcurrentHashMap.newKeySet();
private Set<Player> seen = new HashSet<>();
private List<Runnable> executeEnd = new ArrayList<>(1);
protected Laser(Location start, Location end, int duration, int distance) {
if (!Packets.enabled) throw new IllegalStateException("The Laser Beam API is disabled. An error has occured during initialization.");
if (start.getWorld() != end.getWorld()) throw new IllegalArgumentException("Locations do not belong to the same worlds.");
this.start = start.clone();
this.end = end.clone();
this.duration = duration;
distanceSquared = distance < 0 ? -1 : distance * distance;
}
/**
* Adds a runnable to execute when the laser reaches its final duration
* @param runnable action to execute
* @return this {@link Laser} instance
*/
public Laser executeEnd(Runnable runnable) {
executeEnd.add(runnable);
return this;
}
/**
* Makes the duration provided in the constructor passed as ticks and not seconds
* @return this {@link Laser} instance
*/
public Laser durationInTicks() {
durationInTicks = true;
return this;
}
/**
* Starts this laser.
* <p>
* It will make the laser visible for nearby players and start the countdown to the final duration.
* <p>
* Once finished, it will destroy the laser and execute all runnables passed with {@link Laser#executeEnd}.
* @param plugin plugin used to start the task
*/
public void start(Plugin plugin) {
if (main != null) throw new IllegalStateException("Task already started");
this.plugin = plugin;
main = new BukkitRunnable() {
int time = 0;
@Override
public void run() {
try {
if (time == duration) {
cancel();
return;
}
if (!durationInTicks || time % 20 == 0) {
for (Player p : start.getWorld().getPlayers()) {
if (isCloseEnough(p)) {
if (show.add(p)) {
sendStartPackets(p, !seen.add(p));
}
}else if (show.remove(p)) {
sendDestroyPackets(p);
}
}
}
time++;
}catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
@Override
public synchronized void cancel() throws IllegalStateException {
super.cancel();
main = null;
try {
for (Player p : show) {
sendDestroyPackets(p);
}
show.clear();
executeEnd.forEach(Runnable::run);
}catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
};
main.runTaskTimerAsynchronously(plugin, 0L, durationInTicks ? 1L : 20L);
}
/**
* Stops this laser.
* <p>
* This will destroy the laser for every player and start execute all runnables passed with {@link Laser#executeEnd}
*/
public void stop() {
if (main == null) throw new IllegalStateException("Task not started");
main.cancel();
}
/**
* Gets laser status.
* @return <code>true</code> if the laser is currently running
* (i.e. {@link #start} has been called and the duration is not over)
*/
public boolean isStarted() {
return main != null;
}
/**
* Gets laser type.
* @return LaserType enum constant of this laser
*/
public abstract LaserType getLaserType();
/**
* Instantly moves the start of the laser to the location provided.
* @param location New start location
* @throws ReflectiveOperationException if a reflection exception occurred during laser moving
*/
public abstract void moveStart(Location location) throws ReflectiveOperationException;
/**
* Instantly moves the end of the laser to the location provided.
* @param location New end location
* @throws ReflectiveOperationException if a reflection exception occurred during laser moving
*/
public abstract void moveEnd(Location location) throws ReflectiveOperationException;
/**
* Gets the start location of the laser.
* @return where exactly is the start position of the laser located
*/
public Location getStart() {
return start.clone();
}
/**
* Gets the end location of the laser.
* @return where exactly is the end position of the laser located
*/
public Location getEnd() {
return end.clone();
}
/**
* Moves the start of the laser smoothly to the new location, within a given time.
* @param location New start location to go to
* @param ticks Duration (in ticks) to make the move
* @param callback {@link Runnable} to execute at the end of the move (nullable)
*/
public void moveStart(Location location, int ticks, Runnable callback) {
startMove = moveInternal(location, ticks, startMove, getStart(), this::moveStart, callback);
}
/**
* Moves the end of the laser smoothly to the new location, within a given time.
* @param location New end location to go to
* @param ticks Duration (in ticks) to make the move
* @param callback {@link Runnable} to execute at the end of the move (nullable)
*/
public void moveEnd(Location location, int ticks, Runnable callback) {
endMove = moveInternal(location, ticks, endMove, getEnd(), this::moveEnd, callback);
}
private BukkitTask moveInternal(Location location, int ticks, BukkitTask oldTask, Location from,
ReflectiveConsumer<Location> moveConsumer, Runnable callback) {
if (ticks <= 0)
throw new IllegalArgumentException("Ticks must be a positive value");
if (plugin == null)
throw new IllegalStateException("The laser must have been started a least once");
if (oldTask != null && !oldTask.isCancelled())
oldTask.cancel();
return new BukkitRunnable() {
double xPerTick = (location.getX() - from.getX()) / ticks;
double yPerTick = (location.getY() - from.getY()) / ticks;
double zPerTick = (location.getZ() - from.getZ()) / ticks;
Location loc = from.clone();
int elapsed = 0;
@Override
public void run() {
try {
loc.add(xPerTick, yPerTick, zPerTick);
moveConsumer.accept(loc);
}catch (ReflectiveOperationException e) {
e.printStackTrace();
cancel();
return;
}
if (++elapsed == ticks) {
cancel();
if (callback != null) callback.run();
}
}
}.runTaskTimer(plugin, 0L, 1L);
}
protected void moveFakeEntity(Location location, int entityId, Object fakeEntity) throws ReflectiveOperationException {
if (fakeEntity != null) Packets.moveFakeEntity(fakeEntity, location);
if (main == null) return;
Object packet;
if (fakeEntity == null) {
packet = Packets.createPacketMoveEntity(location, entityId);
}else {
packet = Packets.createPacketMoveEntity(fakeEntity);
}
for (Player p : show) {
Packets.sendPackets(p, packet);
}
}
protected abstract void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException;
protected abstract void sendDestroyPackets(Player p) throws ReflectiveOperationException;
protected boolean isCloseEnough(Player player) {
if (distanceSquared == -1) return true;
Location location = player.getLocation();
return getStart().distanceSquared(location) <= distanceSquared ||
getEnd().distanceSquared(location) <= distanceSquared;
}
public static class GuardianLaser extends Laser {
private static AtomicInteger teamID = new AtomicInteger(ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE));
private Object createGuardianPacket;
private Object createSquidPacket;
private Object teamCreatePacket;
private Object[] destroyPackets;
private Object metadataPacketGuardian;
private Object metadataPacketSquid;
private Object fakeGuardianDataWatcher;
private final UUID squidUUID = UUID.randomUUID();
private final UUID guardianUUID = UUID.randomUUID();
private final int squidID = Packets.generateEID();
private final int guardianID = Packets.generateEID();
private Object squid;
private Object guardian;
private int targetID;
private UUID targetUUID;
protected LivingEntity endEntity;
private Location correctStart;
private Location correctEnd;
/**
* Creates a new Guardian Laser instance
* @param start Location where laser will starts
* @param end Location where laser will ends
* @param duration Duration of laser in seconds (<i>-1 if infinite</i>)
* @param distance Distance where laser will be visible (<i>-1 if infinite</i>)
* @throws ReflectiveOperationException if a reflection exception occurred during Laser creation
* @see Laser#start(Plugin) to start the laser
* @see #durationInTicks() to make the duration in ticks
* @see #executeEnd(Runnable) to add Runnable-s to execute when the laser will stop
* @see #GuardianLaser(Location, LivingEntity, int, int) to create a laser which follows an entity
*/
public GuardianLaser(Location start, Location end, int duration, int distance) throws ReflectiveOperationException {
super(start, end, duration, distance);
initSquid();
targetID = squidID;
targetUUID = squidUUID;
initLaser();
}
/**
* Creates a new Guardian Laser instance
* @param start Location where laser will starts
* @param endEntity Entity who the laser will follow
* @param duration Duration of laser in seconds (<i>-1 if infinite</i>)
* @param distance Distance where laser will be visible (<i>-1 if infinite</i>)
* @throws ReflectiveOperationException if a reflection exception occurred during Laser creation
* @see Laser#start(Plugin) to start the laser
* @see #durationInTicks() to make the duration in ticks
* @see #executeEnd(Runnable) to add Runnable-s to execute when the laser will stop
* @see #GuardianLaser(Location, Location, int, int) to create a laser with a specific end location
*/
public GuardianLaser(Location start, LivingEntity endEntity, int duration, int distance) throws ReflectiveOperationException {
super(start, endEntity.getLocation(), duration, distance);
targetID = endEntity.getEntityId();
targetUUID = endEntity.getUniqueId();
initLaser();
}
private void initLaser() throws ReflectiveOperationException {
fakeGuardianDataWatcher = Packets.createFakeDataWatcher();
Packets.initGuardianWatcher(fakeGuardianDataWatcher, targetID);
if (Packets.version >= 17) {
guardian = Packets.createGuardian(getCorrectStart(), guardianUUID, guardianID);
}
metadataPacketGuardian = Packets.createPacketMetadata(guardianID, fakeGuardianDataWatcher);
teamCreatePacket = Packets.createPacketTeamCreate("noclip" + teamID.getAndIncrement(), squidUUID, guardianUUID);
destroyPackets = Packets.createPacketsRemoveEntities(squidID, guardianID);
}
private void initSquid() throws ReflectiveOperationException {
if (Packets.version >= 17) {
squid = Packets.createSquid(getCorrectEnd(), squidUUID, squidID);
}
metadataPacketSquid = Packets.createPacketMetadata(squidID, Packets.fakeSquidWatcher);
Packets.setDirtyWatcher(Packets.fakeSquidWatcher);
}
private Object getGuardianSpawnPacket() throws ReflectiveOperationException {
if (createGuardianPacket == null) {
if (Packets.version < 17) {
createGuardianPacket = Packets.createPacketEntitySpawnLiving(getCorrectStart(), Packets.mappings.getGuardianID(), guardianUUID, guardianID);
}else {
createGuardianPacket = Packets.createPacketEntitySpawnLiving(guardian);
}
}
return createGuardianPacket;
}
private Object getSquidSpawnPacket() throws ReflectiveOperationException {
if (createSquidPacket == null) {
if (Packets.version < 17) {
createSquidPacket = Packets.createPacketEntitySpawnLiving(getCorrectEnd(), Packets.mappings.getSquidID(), squidUUID, squidID);
}else {
createSquidPacket = Packets.createPacketEntitySpawnLiving(squid);
}
}
return createSquidPacket;
}
@Override
public LaserType getLaserType() {
return LaserType.GUARDIAN;
}
/**
* Makes the laser follow an entity (moving end location).
*
* This is done client-side by making the fake guardian follow the existing entity.
* Hence, there is no consuming of server resources.
*
* @param entity living entity the laser will follow
* @throws ReflectiveOperationException if a reflection operation fails
*/
public void attachEndEntity(LivingEntity entity) throws ReflectiveOperationException {
if (entity.getWorld() != start.getWorld()) throw new IllegalArgumentException("Attached entity is not in the same world as the laser.");
this.endEntity = entity;
setTargetEntity(entity.getUniqueId(), entity.getEntityId());
}
public Entity getEndEntity() {
return endEntity;
}
private void setTargetEntity(UUID uuid, int id) throws ReflectiveOperationException {
targetUUID = uuid;
targetID = id;
fakeGuardianDataWatcher = Packets.createFakeDataWatcher();
Packets.initGuardianWatcher(fakeGuardianDataWatcher, targetID);
metadataPacketGuardian = Packets.createPacketMetadata(guardianID, fakeGuardianDataWatcher);
for (Player p : show) {
Packets.sendPackets(p, metadataPacketGuardian);
}
}
@Override
public Location getEnd() {
return endEntity == null ? end : endEntity.getLocation();
}
protected Location getCorrectStart() {
if (correctStart == null) {
correctStart = start.clone();
correctStart.subtract(0, 0.5, 0);
}
return correctStart;
}
protected Location getCorrectEnd() {
if (correctEnd == null) {
correctEnd = end.clone();
correctEnd.subtract(0, 0.5, 0);
Vector corrective = correctEnd.toVector().subtract(getCorrectStart().toVector()).normalize();
if (Double.isNaN(corrective.getX())) corrective.setX(0);
if (Double.isNaN(corrective.getY())) corrective.setY(0);
if (Double.isNaN(corrective.getZ())) corrective.setZ(0);
// coordinates can be NaN when start and end are stricly equals
correctEnd.subtract(corrective);
}
return correctEnd;
}
@Override
protected boolean isCloseEnough(Player player) {
return player == endEntity || super.isCloseEnough(player);
}
@Override
protected void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException {
if (squid == null) {
Packets.sendPackets(p,
getGuardianSpawnPacket(),
metadataPacketGuardian);
}else {
Packets.sendPackets(p,
getGuardianSpawnPacket(),
getSquidSpawnPacket(),
metadataPacketGuardian,
metadataPacketSquid);
}
if (!hasSeen) Packets.sendPackets(p, teamCreatePacket);
}
@Override
protected void sendDestroyPackets(Player p) throws ReflectiveOperationException {
Packets.sendPackets(p, destroyPackets);
}
@Override
public void moveStart(Location location) throws ReflectiveOperationException {
this.start = location.clone();
correctStart = null;
createGuardianPacket = null; // will force re-generation of spawn packet
moveFakeEntity(getCorrectStart(), guardianID, guardian);
if (squid != null) {
correctEnd = null;
createSquidPacket = null;
moveFakeEntity(getCorrectEnd(), squidID, squid);
}
}
@Override
public void moveEnd(Location location) throws ReflectiveOperationException {
this.end = location.clone();
createSquidPacket = null; // will force re-generation of spawn packet
correctEnd = null;
if (squid == null) {
initSquid();
for (Player p : show) {
Packets.sendPackets(p, getSquidSpawnPacket(), metadataPacketSquid);
}
}else {
moveFakeEntity(getCorrectEnd(), squidID, squid);
}
if (targetUUID != squidUUID) {
endEntity = null;
setTargetEntity(squidUUID, squidID);
}
}
/**
* Asks viewers' clients to change the color of this laser
* @throws ReflectiveOperationException
*/
public void callColorChange() throws ReflectiveOperationException {
for (Player p : show) {
Packets.sendPackets(p, metadataPacketGuardian);
}
}
}
public static class CrystalLaser extends Laser {
private Object createCrystalPacket;
private Object metadataPacketCrystal;
private Object[] destroyPackets;
private Object fakeCrystalDataWatcher;
private final Object crystal;
private final int crystalID = Packets.generateEID();
/**
* Creates a new Ender Crystal Laser instance
* @param start Location where laser will starts. The Crystal laser do not handle decimal number, it will be rounded to blocks.
* @param end Location where laser will ends. The Crystal laser do not handle decimal number, it will be rounded to blocks.
* @param duration Duration of laser in seconds (<i>-1 if infinite</i>)
* @param distance Distance where laser will be visible (<i>-1 if infinite</i>)
* @throws ReflectiveOperationException if a reflection exception occurred during Laser creation
* @see #start(Plugin) to start the laser
* @see #durationInTicks() to make the duration in ticks
* @see #executeEnd(Runnable) to add Runnable-s to execute when the laser will stop
*/
public CrystalLaser(Location start, Location end, int duration, int distance) throws ReflectiveOperationException {
super(start, new Location(end.getWorld(), end.getBlockX(), end.getBlockY(), end.getBlockZ()), duration,
distance);
fakeCrystalDataWatcher = Packets.createFakeDataWatcher();
Packets.setCrystalWatcher(fakeCrystalDataWatcher, end);
if (Packets.version < 17) {
crystal = null;
}else {
crystal = Packets.createCrystal(start, UUID.randomUUID(), crystalID);
}
metadataPacketCrystal = Packets.createPacketMetadata(crystalID, fakeCrystalDataWatcher);
destroyPackets = Packets.createPacketsRemoveEntities(crystalID);
}
private Object getCrystalSpawnPacket() throws ReflectiveOperationException {
if (createCrystalPacket == null) {
if (Packets.version < 17) {
createCrystalPacket = Packets.createPacketEntitySpawnNormal(start, Packets.crystalID, Packets.crystalType, crystalID);
}else {
createCrystalPacket = Packets.createPacketEntitySpawnNormal(crystal);
}
}
return createCrystalPacket;
}
@Override
public LaserType getLaserType() {
return LaserType.ENDER_CRYSTAL;
}
@Override
protected void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException {
Packets.sendPackets(p, getCrystalSpawnPacket());
Packets.sendPackets(p, metadataPacketCrystal);
}
@Override
protected void sendDestroyPackets(Player p) throws ReflectiveOperationException {
Packets.sendPackets(p, destroyPackets);
}
@Override
public void moveStart(Location location) throws ReflectiveOperationException {
this.start = location.clone();
createCrystalPacket = null; // will force re-generation of spawn packet
moveFakeEntity(start, crystalID, crystal);
}
@Override
public void moveEnd(Location location) throws ReflectiveOperationException {
location = new Location(location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ());
if (end.equals(location))
return;
this.end = location;
if (main != null) {
Packets.setCrystalWatcher(fakeCrystalDataWatcher, location);
metadataPacketCrystal = Packets.createPacketMetadata(crystalID, fakeCrystalDataWatcher);
for (Player p : show) {
Packets.sendPackets(p, metadataPacketCrystal);
}
}
}
}
public enum LaserType {
/**
* Represents a laser from a Guardian entity.
* <p>
* It can be pointed to precise locations and
* can track entities smoothly using {@link GuardianLaser#attachEndEntity(LivingEntity)}
*/
GUARDIAN,
/**
* Represents a laser from an Ender Crystal entity.
* <p>
* Start and end locations are automatically rounded to integers (block locations).
*/
ENDER_CRYSTAL;
/**
* Creates a new Laser instance, {@link GuardianLaser} or {@link CrystalLaser} depending on this enum value.
* @param start Location where laser will starts
* @param end Location where laser will ends
* @param duration Duration of laser in seconds (<i>-1 if infinite</i>)
* @param distance Distance where laser will be visible
* @throws ReflectiveOperationException if a reflection exception occurred during Laser creation
* @see Laser#start(Plugin) to start the laser
* @see Laser#durationInTicks() to make the duration in ticks
* @see Laser#executeEnd(Runnable) to add Runnable-s to execute when the laser will stop
*/
public Laser create(Location start, Location end, int duration, int distance) throws ReflectiveOperationException {
switch (this) {
case ENDER_CRYSTAL:
return new CrystalLaser(start, end, duration, distance);
case GUARDIAN:
return new GuardianLaser(start, end, duration, distance);
}
throw new IllegalStateException();
}
}
private static class Packets {
private static AtomicInteger lastIssuedEID = new AtomicInteger(2000000000);
static int generateEID() {
return lastIssuedEID.getAndIncrement();
}
private static Logger logger;
private static int version;
private static int versionMinor;
private static String npack = "net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
private static String cpack = Bukkit.getServer().getClass().getPackage().getName() + ".";
private static ProtocolMappings mappings;
private static int crystalID = 51; // pre-1.13
private static Object crystalType;
private static Object squidType;
private static Object guardianType;
private static Constructor<?> crystalConstructor;
private static Constructor<?> squidConstructor;
private static Constructor<?> guardianConstructor;
private static Object watcherObject1; // invisilibity
private static Object watcherObject2; // spikes
private static Object watcherObject3; // attack id
private static Object watcherObject4; // crystal target
private static Object watcherObject5; // crystal base plate
private static Constructor<?> watcherConstructor;
private static Method watcherSet;
private static Method watcherRegister;
private static Method watcherDirty;
private static Method watcherPack;
private static Constructor<?> blockPositionConstructor;
private static Constructor<?> packetSpawnLiving;
private static Constructor<?> packetSpawnNormal;
private static Constructor<?> packetRemove;
private static Constructor<?> packetTeleport;
private static Constructor<?> packetMetadata;
private static Class<?> packetTeam;
private static Method createTeamPacket;
private static Constructor<?> createTeam;
private static Constructor<?> createScoreboard;
private static Method setTeamPush;
private static Object pushNever;
private static Method getTeamPlayers;
private static Method getHandle;
private static Field playerConnection;
private static Method sendPacket;
private static Method setLocation;
private static Method setUUID;
private static Method setID;
private static Object fakeSquid;
private static Object fakeSquidWatcher;
private static Object nmsWorld;
public static boolean enabled = false;
static {
try {
logger = new Logger("GuardianBeam", null) {
@Override
public void log(LogRecord logRecord) {
logRecord.setMessage("[GuardianBeam] " + logRecord.getMessage());
super.log(logRecord);
}
};
logger.setParent(Bukkit.getServer().getLogger());
logger.setLevel(Level.ALL);
// e.g. Bukkit.getServer().getClass().getPackage().getName() -> org.bukkit.craftbukkit.v1_17_R1
String[] versions = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3].substring(1).split("_");
version = Integer.parseInt(versions[1]); // 1.X
if (version >= 17) {
// e.g. Bukkit.getBukkitVersion() -> 1.17.1-R0.1-SNAPSHOT
versions = Bukkit.getBukkitVersion().split("-R")[0].split("\\.");
versionMinor = versions.length <= 2 ? 0 : Integer.parseInt(versions[2]);
}else versionMinor = Integer.parseInt(versions[2].substring(1)); // 1.X.Y
logger.info("Found server version 1." + version + "." + versionMinor);
mappings = ProtocolMappings.getMappings(version);
if (mappings == null) {
mappings = ProtocolMappings.values()[ProtocolMappings.values().length - 1];
logger.warning("Loaded not matching version of the mappings for your server version (1." + version + "." + versionMinor + ")");
}
logger.info("Loaded mappings " + mappings.name());
Class<?> entityTypesClass = getNMSClass("world.entity", "EntityTypes");
Class<?> entityClass = getNMSClass("world.entity", "Entity");
Class<?> crystalClass = getNMSClass("world.entity.boss.enderdragon", "EntityEnderCrystal");
Class<?> squidClass = getNMSClass("world.entity.animal", "EntitySquid");
Class<?> guardianClass = getNMSClass("world.entity.monster", "EntityGuardian");
watcherObject1 = getField(entityClass, mappings.getWatcherFlags(), null);
watcherObject2 = getField(guardianClass, mappings.getWatcherSpikes(), null);
watcherObject3 = getField(guardianClass, mappings.getWatcherTargetEntity(), null);
watcherObject4 = getField(crystalClass, mappings.getWatcherTargetLocation(), null);
watcherObject5 = getField(crystalClass, mappings.getWatcherBasePlate(), null);
if (version >= 13) {
crystalType = entityTypesClass.getDeclaredField(mappings.getCrystalTypeName()).get(null);
if (version >= 17) {
squidType = entityTypesClass.getDeclaredField(mappings.getSquidTypeName()).get(null);
guardianType = entityTypesClass.getDeclaredField(mappings.getGuardianTypeName()).get(null);
}
}
Class<?> dataWatcherClass = getNMSClass("network.syncher", "DataWatcher");
watcherConstructor = dataWatcherClass.getDeclaredConstructor(entityClass);
if (version >= 18) {
watcherSet = dataWatcherClass.getDeclaredMethod("b", watcherObject1.getClass(), Object.class);
watcherRegister = dataWatcherClass.getDeclaredMethod("a", watcherObject1.getClass(), Object.class);
}else {
watcherSet = getMethod(dataWatcherClass, "set");
watcherRegister = getMethod(dataWatcherClass, "register");
}
if (version >= 15) watcherDirty = getMethod(dataWatcherClass, "markDirty");
if (version > 19 || (version == 19 && versionMinor >= 3))
watcherPack = dataWatcherClass.getDeclaredMethod("b");
packetSpawnNormal = getNMSClass("network.protocol.game", "PacketPlayOutSpawnEntity").getDeclaredConstructor(version < 17 ? new Class<?>[0] : new Class<?>[] { getNMSClass("world.entity", "Entity") });
packetSpawnLiving = version >= 19 ? packetSpawnNormal : getNMSClass("network.protocol.game", "PacketPlayOutSpawnEntityLiving").getDeclaredConstructor(version < 17 ? new Class<?>[0] : new Class<?>[] { getNMSClass("world.entity", "EntityLiving") });
packetRemove = getNMSClass("network.protocol.game", "PacketPlayOutEntityDestroy").getDeclaredConstructor(version == 17 && versionMinor == 0 ? int.class : int[].class);
packetMetadata = getNMSClass("network.protocol.game", "PacketPlayOutEntityMetadata")
.getDeclaredConstructor(version < 19 || (version == 19 && versionMinor < 3)
? new Class<?>[] {int.class, dataWatcherClass, boolean.class}
: new Class<?>[] {int.class, List.class});
packetTeleport = getNMSClass("network.protocol.game", "PacketPlayOutEntityTeleport").getDeclaredConstructor(version < 17 ? new Class<?>[0] : new Class<?>[] { entityClass });
packetTeam = getNMSClass("network.protocol.game", "PacketPlayOutScoreboardTeam");
blockPositionConstructor =
getNMSClass("core", "BlockPosition").getConstructor(int.class, int.class, int.class);
nmsWorld = Class.forName(cpack + "CraftWorld").getDeclaredMethod("getHandle").invoke(Bukkit.getWorlds().get(0));
squidConstructor = squidClass.getDeclaredConstructors()[0];
if (version >= 17) {
guardianConstructor = guardianClass.getDeclaredConstructors()[0];
crystalConstructor = crystalClass.getDeclaredConstructor(nmsWorld.getClass().getSuperclass(), double.class, double.class, double.class);
}
Object[] entityConstructorParams = version < 14 ? new Object[] { nmsWorld } : new Object[] { entityTypesClass.getDeclaredField(mappings.getSquidTypeName()).get(null), nmsWorld };
fakeSquid = squidConstructor.newInstance(entityConstructorParams);
fakeSquidWatcher = createFakeDataWatcher();
tryWatcherSet(fakeSquidWatcher, watcherObject1, (byte) 32);
getHandle = Class.forName(cpack + "entity.CraftPlayer").getDeclaredMethod("getHandle");
playerConnection = getNMSClass("server.level", "EntityPlayer")
.getDeclaredField(version < 17 ? "playerConnection" : (version < 20 ? "b" : "c"));
playerConnection.setAccessible(true);
sendPacket = getNMSClass("server.network", "PlayerConnection").getMethod(
version < 18 ? "sendPacket" : (version >= 20 && versionMinor >= 2 ? "b" : "a"),
getNMSClass("network.protocol", "Packet"));
if (version >= 17) {
setLocation = entityClass.getDeclaredMethod(version < 18 ? "setLocation" : "a", double.class, double.class, double.class, float.class, float.class);
setUUID = entityClass.getDeclaredMethod("a_", UUID.class);
setID = entityClass.getDeclaredMethod("e", int.class);
createTeamPacket = packetTeam.getMethod("a", getNMSClass("world.scores", "ScoreboardTeam"), boolean.class);
Class<?> scoreboardClass = getNMSClass("world.scores", "Scoreboard");
Class<?> teamClass = getNMSClass("world.scores", "ScoreboardTeam");
Class<?> pushClass = getNMSClass("world.scores", "ScoreboardTeamBase$EnumTeamPush");
createTeam = teamClass.getDeclaredConstructor(scoreboardClass, String.class);
createScoreboard = scoreboardClass.getDeclaredConstructor();
setTeamPush = teamClass.getDeclaredMethod(mappings.getTeamSetCollision(), pushClass);
pushNever = pushClass.getDeclaredField("b").get(null);
getTeamPlayers = teamClass.getDeclaredMethod(mappings.getTeamGetPlayers());
}
enabled = true;
}catch (Exception e) {
e.printStackTrace();
String errorMsg = "Laser Beam reflection failed to initialize. The util is disabled. Please ensure your version (" + Bukkit.getServer().getClass().getPackage().getName() + ") is supported.";
if (logger == null)
System.err.println(errorMsg);
else
logger.severe(errorMsg);
}
}
public static void sendPackets(Player p, Object... packets) throws ReflectiveOperationException {
Object connection = playerConnection.get(getHandle.invoke(p));
for (Object packet : packets) {
if (packet == null) continue;
sendPacket.invoke(connection, packet);
}
}
public static Object createFakeDataWatcher() throws ReflectiveOperationException {
Object watcher = watcherConstructor.newInstance(fakeSquid);
if (version > 13) setField(watcher, "registrationLocked", false);
return watcher;
}
public static void setDirtyWatcher(Object watcher) throws ReflectiveOperationException {
if (version >= 15) watcherDirty.invoke(watcher, watcherObject1);
}
public static Object createSquid(Location location, UUID uuid, int id) throws ReflectiveOperationException {
Object entity = squidConstructor.newInstance(squidType, nmsWorld);
setEntityIDs(entity, uuid, id);
moveFakeEntity(entity, location);
return entity;
}
public static Object createGuardian(Location location, UUID uuid, int id) throws ReflectiveOperationException {
Object entity = guardianConstructor.newInstance(guardianType, nmsWorld);
setEntityIDs(entity, uuid, id);
moveFakeEntity(entity, location);
return entity;
}
public static Object createCrystal(Location location, UUID uuid, int id) throws ReflectiveOperationException {
Object entity = crystalConstructor.newInstance(nmsWorld, location.getX(), location.getY(), location.getZ());
setEntityIDs(entity, uuid, id);
return entity;
}
public static Object createPacketEntitySpawnLiving(Location location, int typeID, UUID uuid, int id) throws ReflectiveOperationException {
Object packet = packetSpawnLiving.newInstance();
setField(packet, "a", id);
setField(packet, "b", uuid);
setField(packet, "c", typeID);
setField(packet, "d", location.getX());
setField(packet, "e", location.getY());
setField(packet, "f", location.getZ());
setField(packet, "j", (byte) (location.getYaw() * 256.0F / 360.0F));
setField(packet, "k", (byte) (location.getPitch() * 256.0F / 360.0F));
if (version <= 14) setField(packet, "m", fakeSquidWatcher);
return packet;
}
public static Object createPacketEntitySpawnNormal(Location location, int typeID, Object type, int id) throws ReflectiveOperationException {
Object packet = packetSpawnNormal.newInstance();
setField(packet, "a", id);
setField(packet, "b", UUID.randomUUID());
setField(packet, "c", location.getX());
setField(packet, "d", location.getY());
setField(packet, "e", location.getZ());
setField(packet, "i", (int) (location.getYaw() * 256.0F / 360.0F));
setField(packet, "j", (int) (location.getPitch() * 256.0F / 360.0F));
setField(packet, "k", version < 13 ? typeID : type);
return packet;
}
public static Object createPacketEntitySpawnLiving(Object entity) throws ReflectiveOperationException {
return packetSpawnLiving.newInstance(entity);
}
public static Object createPacketEntitySpawnNormal(Object entity) throws ReflectiveOperationException {
return packetSpawnNormal.newInstance(entity);
}
public static void initGuardianWatcher(Object watcher, int targetId) throws ReflectiveOperationException {
tryWatcherSet(watcher, watcherObject1, (byte) 32);
tryWatcherSet(watcher, watcherObject2, Boolean.FALSE);
tryWatcherSet(watcher, watcherObject3, targetId);
}
public static void setCrystalWatcher(Object watcher, Location target) throws ReflectiveOperationException {
Object blockPosition =
blockPositionConstructor.newInstance(target.getBlockX(), target.getBlockY(), target.getBlockZ());
tryWatcherSet(watcher, watcherObject4, version < 13 ? com.google.common.base.Optional.of(blockPosition) : Optional.of(blockPosition));
tryWatcherSet(watcher, watcherObject5, Boolean.FALSE);
}
public static Object[] createPacketsRemoveEntities(int... entitiesId) throws ReflectiveOperationException {
Object[] packets;
if (version == 17 && versionMinor == 0) {
packets = new Object[entitiesId.length];
for (int i = 0; i < entitiesId.length; i++) {
packets[i] = packetRemove.newInstance(entitiesId[i]);
}
}else {
packets = new Object[] { packetRemove.newInstance(entitiesId) };
}
return packets;
}
public static Object createPacketMoveEntity(Location location, int entityId) throws ReflectiveOperationException {
Object packet = packetTeleport.newInstance();
setField(packet, "a", entityId);
setField(packet, "b", location.getX());
setField(packet, "c", location.getY());
setField(packet, "d", location.getZ());
setField(packet, "e", (byte) (location.getYaw() * 256.0F / 360.0F));
setField(packet, "f", (byte) (location.getPitch() * 256.0F / 360.0F));
setField(packet, "g", true);
return packet;
}
public static void setEntityIDs(Object entity, UUID uuid, int id) throws ReflectiveOperationException {
setUUID.invoke(entity, uuid);
setID.invoke(entity, id);
}
public static void moveFakeEntity(Object entity, Location location) throws ReflectiveOperationException {
setLocation.invoke(entity, location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw());
}
public static Object createPacketMoveEntity(Object entity) throws ReflectiveOperationException {
return packetTeleport.newInstance(entity);
}
public static Object createPacketTeamCreate(String teamName, UUID... entities) throws ReflectiveOperationException {
Object packet;
if (version < 17) {
packet = packetTeam.newInstance();
setField(packet, "a", teamName);
setField(packet, "i", 0);
setField(packet, "f", "never");
Collection<String> players = (Collection<String>) getField(packetTeam, "h", packet);
for (UUID entity : entities) players.add(entity.toString());
}else {
Object team = createTeam.newInstance(createScoreboard.newInstance(), teamName);
setTeamPush.invoke(team, pushNever);
Collection<String> players = (Collection<String>) getTeamPlayers.invoke(team);
for (UUID entity : entities) players.add(entity.toString());
packet = createTeamPacket.invoke(null, team, true);
}
return packet;
}
private static Object createPacketMetadata(int entityId, Object watcher) throws ReflectiveOperationException {
if (version < 19 || (version == 19 && versionMinor < 3)) {
return packetMetadata.newInstance(entityId, watcher, false);
} else {
return packetMetadata.newInstance(entityId, watcherPack.invoke(watcher));
}
}
private static void tryWatcherSet(Object watcher, Object watcherObject, Object watcherData) throws ReflectiveOperationException {
try {
watcherSet.invoke(watcher, watcherObject, watcherData);
}catch (InvocationTargetException ex) {
watcherRegister.invoke(watcher, watcherObject, watcherData);
if (version >= 15) watcherDirty.invoke(watcher, watcherObject);
}
}
/* Reflection utils */
private static Method getMethod(Class<?> clazz, String name) throws NoSuchMethodException {