/
uCarsListener.java
2181 lines (2028 loc) · 68.8 KB
/
uCarsListener.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 com.useful.ucars;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.regex.Pattern;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import org.bukkit.block.data.Lightable;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Damageable;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.vehicle.VehicleDamageEvent;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleEntityCollisionEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import org.bukkit.event.vehicle.VehicleUpdateEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.util.Vector;
import com.useful.uCarsAPI.CarRespawnReason;
import com.useful.uCarsAPI.uCarCrashEvent;
import com.useful.uCarsAPI.uCarRespawnEvent;
import com.useful.uCarsAPI.uCarsAPI;
import com.useful.ucars.controls.ControlSchemeManager;
import com.useful.ucars.util.UEntityMeta;
import com.useful.ucarsCommon.StatValue;
public class uCarsListener implements Listener {
private ucars plugin;
private List<String> ignoreJump = null;
private List<String> softBlocks = null;
private static double GRAVITY_Y_VELOCITY_MAGNITUDE = 0.04;
private static double SIMULATED_FRICTION_SPEED_MULTIPLIER = 0.55;
private Boolean carsEnabled = true;
private Boolean licenseEnabled = false;
private Boolean roadBlocksEnabled = false;
private Boolean multiverseEnabled = false;
private Boolean trafficLightsEnabled = true;
private Boolean effectBlocksEnabled = true;
private Boolean usePerms = false;
private Boolean fuelEnabled = false;
private Boolean fuelUseItems = false;
private Boolean disableFallDamage = false;
private Boolean pitchEnabled = true;
private double defaultSpeed = 30;
private static double defaultHealth = 10;
private double damage_water = 0;
private double damage_lava = 10;
private double damage_cactus = 5;
private double uCar_jump_amount = 5;
private double crash_damage = 0;
private double hitby_crash_damage = 0;
private String fuelBypassPerm = "ufuel.bypass";
private List<String> roadBlocks = new ArrayList<String>(); //Road blocks
private List<String> trafficLightRawIds = new ArrayList<String>(); //Traffic lights
private List<String> blockBoost = new ArrayList<String>(); //Gold booster blocks
private List<String> highBlockBoost = new ArrayList<String>(); //Diamond booster blocks
private List<String> resetBlockBoost = new ArrayList<String>(); //Emerald booster blocks
private List<String> jumpBlock = new ArrayList<String>(); //Jump blocks (Iron)
private List<String> teleportBlock = new ArrayList<String>(); //Teleport blocks (purple clay)
private List<String> barriers = new ArrayList<String>();
private List<String> ucarworlds = new ArrayList<String>();
private ConcurrentHashMap<String, Double> speedMods = new ConcurrentHashMap<String, Double>();
public uCarsListener(ucars plugin) {
this.plugin = ucars.plugin;
init();
}
/*
* Asks the API to calculate car stats (Such as velocity mods, etc...)
*/
public Vector calculateCarStats(Entity car, Player player,
Vector velocity, double currentMult) {
if (UEntityMeta.hasMetadata(car, "car.frozen") || car.hasMetadata("car.frozen")) {
if(car.hasMetadata("car.inertialYAxis")) {
velocity = new Vector(0, velocity.getY(), 0); // Don't freeze Y-velocity
return velocity;
}
if(car.getType() == EntityType.MINECART) {
velocity = new Vector(0, GRAVITY_Y_VELOCITY_MAGNITUDE, 0);
} else {
velocity = new Vector(0, 0, 0);
}
return velocity;
}
velocity = plugin.getAPI().getTravelVector(car, velocity, currentMult);
return velocity;
}
/*
* Checks if a trafficlight sign is attached to the given block
*/
public boolean trafficlightSignOn(Block block) {
if (block.getRelative(BlockFace.NORTH).getState() instanceof Sign) {
Sign sign = (Sign) block.getRelative(BlockFace.NORTH).getState();
if (ChatColor.stripColor(sign.getLine(1)).equalsIgnoreCase(
ChatColor.stripColor("[TrafficLight]"))) {
return true;
}
} else if (block.getRelative(BlockFace.EAST).getState() instanceof Sign) {
Sign sign = (Sign) block.getRelative(BlockFace.EAST).getState();
if (ChatColor.stripColor(sign.getLine(1)).equalsIgnoreCase(
ChatColor.stripColor("[TrafficLight]"))) {
return true;
}
} else if (block.getRelative(BlockFace.SOUTH).getState() instanceof Sign) {
Sign sign = (Sign) block.getRelative(BlockFace.SOUTH).getState();
if (ChatColor.stripColor(sign.getLine(1)).equalsIgnoreCase(
ChatColor.stripColor("[TrafficLight]"))) {
return true;
}
} else if (block.getRelative(BlockFace.WEST).getState() instanceof Sign) {
Sign sign = (Sign) block.getRelative(BlockFace.WEST).getState();
if (ChatColor.stripColor(sign.getLine(1)).equalsIgnoreCase(
ChatColor.stripColor("[TrafficLight]"))) {
return true;
}
} else if (block.getRelative(BlockFace.DOWN).getState() instanceof Sign) {
Sign sign = (Sign) block.getRelative(BlockFace.DOWN).getState();
if (ChatColor.stripColor(sign.getLine(1)).equalsIgnoreCase(
ChatColor.stripColor("[TrafficLight]"))) {
return true;
}
} else if (block.getRelative(BlockFace.UP).getState() instanceof Sign) {
Sign sign = (Sign) block.getRelative(BlockFace.UP).getState();
if (ChatColor.stripColor(sign.getLine(1)).equalsIgnoreCase(
ChatColor.stripColor("[TrafficLight]"))) {
return true;
}
}
return false;
}
/*
* Checks if the specified player is inside a ucar (public for traincarts
* support)
*/
public boolean inACar(String playername) {
try {
Player p = plugin.getServer().getPlayer(playername);
return inACar(p);
} catch (Exception e) {
// Server reloading
return false;
}
}
/*
* Checks if a minecart is a car (Public for traincarts support)
*/
public boolean isACar(Entity cart) {
if(cart.hasMetadata("ucars.ignore") || UEntityMeta.hasMetadata(cart, "ucars.ignore")){
return false; //Not a car
}
if(multiverseEnabled && !ucarworlds.contains(cart.getWorld().getName())) {
return false;
}
if((cart.getType().toString().toUpperCase().contains("MINECART") && cart.getType().toString().length() > 8) || cart.getType().toString().toUpperCase().contains("BOAT")) {
return false; //Not a car but a Minecart_Something (only useful when derailed)
}
if(cart instanceof Animals) {
return false; //Animals are not cars...
}
Location loc = cart.getLocation();
Block b = loc.getBlock();
loc.setY(loc.getY() - 1);
Block underblock = loc.getBlock();
String mat = b.getType().name().toUpperCase();
String underMat = b.getRelative(BlockFace.DOWN).getType().name().toUpperCase();
String underUnderMat = b.getRelative(BlockFace.DOWN, 2).getType().name().toUpperCase();
List<String> checks = new ArrayList<String>();
if(ucars.ignoreRails){
checks.add("POWERED_RAIL");
checks.add("RAIL");
checks.add("RAILS");
checks.add("DETECTOR_RAIL");
checks.add("ACTIVATOR_RAIL");
List<String> newRoadBlocks = new ArrayList<>(roadBlocks);
newRoadBlocks.remove("AIR"); //Keeping the metadata when falling off a cliff after rails
if(UEntityMeta.hasMetadata(cart,"car.wasOnRails") && cart.getVelocity().getY() == 0
&& (plugin.isBlockEqualToConfigIds(newRoadBlocks, underblock) ||
!ucars.config.getBoolean("general.cars.roadBlocks.enable") && cart.getVelocity().getX() == 0 && cart.getVelocity().getZ() == 0)
&& !checks.contains(mat) ) {
UEntityMeta.removeMetadata(cart,"car.wasOnRails");
}
if(UEntityMeta.hasMetadata(cart, "car.wasOnRails")) {
return false;
}
}
if(checks.contains(mat)
|| checks.contains(underMat)
|| checks.contains(underUnderMat)){
UEntityMeta.setMetadata(cart, "car.wasOnRails", new StatValue(true, ucars.plugin));
if(((Minecart)cart).getMaxSpeed() != 0.4 || ((Minecart)cart).getMaxSpeed() == 2.4) {
((Minecart)cart).setMaxSpeed(0.4);
}
return false;
}
if (!plugin.getAPI().runCarChecks(cart)) {
return false;
}
return true;
}
/*
* Resets any boosts the given car may have
*/
public void ResetCarBoost(String playername, Vehicle car,
double defaultSpeed) {
String p = playername;
World w = plugin.getServer().getPlayer(p).getLocation().getWorld();
w.playSound(plugin.getServer().getPlayer(p).getLocation(),
Sound.ENTITY_BAT_TAKEOFF, 1.5f, -2);
if (ucars.carBoosts.containsKey(p)) {
ucars.carBoosts.remove(p);
}
return;
}
/*
* Applies a boost to the car mentioned
*/
public boolean carBoost(String playerName, final double power,
final long lengthMillis, double defaultSpeed) {
final String p = playerName;
final double defMult = defaultSpeed;
double Cur = defMult;
if (ucars.carBoosts.containsKey(p)) {
Cur = ucars.carBoosts.get(p);
}
if (Cur > defMult) {
// Already boosting!
return false;
}
final double current = Cur;
if (plugin == null) {
plugin.getLogger().log(Level.SEVERE,
Lang.get("lang.error.pluginNull"));
}
plugin.getServer().getScheduler()
.runTaskAsynchronously(plugin, new Runnable() {
public void run() {
World w = plugin.getServer().getPlayer(p).getLocation()
.getWorld();
w.playSound(plugin.getServer().getPlayer(p)
.getLocation(), Sound.BLOCK_LAVA_EXTINGUISH, 1.5f, -2);
double speed = current + power;
ucars.carBoosts.put(p, speed);
// Boosting!
try {
Thread.sleep(lengthMillis);
} catch (InterruptedException e) {
ucars.carBoosts.remove(p);
return;
}
// paused for set time!
ucars.carBoosts.remove(p);
// resumed normal speed!
return;
}
});
return true;
}
/*
* Checks if the specified player is inside a ucars (public for traincarts
* support)
*/
public boolean inACar(Player p) {
try {
if (p == null) {
// Should NEVER happen(It means they r offline)
return false;
}
if (p.getVehicle() == null) {
return false;
}
Entity ent = p.getVehicle();
if (!(ent instanceof Vehicle)) {
while (!(ent instanceof Vehicle) && ent.getVehicle() != null) {
ent = ent.getVehicle();
}
if (!(ent instanceof Vehicle)) {
return false;
}
}
Vehicle cart = (Vehicle) ent;
return isACar(cart);
} catch (Exception e) {
// Server reloading
return false;
}
}
public Entity getDrivingPassengerOfCar(Vehicle vehicle){ //Get the PLAYER passenger of the car
if (vehicle.getPassengers().isEmpty() || !(vehicle instanceof Entity)) { //If it has nobody riding it, ignore it
return null;
}
Entity passenger = vehicle.getPassengers().get(0); //The vehicle's lowest passenger; may be a pig, etc... if pigucarting
if (!(passenger instanceof Player)) { //If not a player riding it; then keep looking until we find a player
while (!(passenger instanceof Player)
&& !passenger.getPassengers().isEmpty()) { //While there's more entities above this in the 'stack'
passenger = passenger.getPassengers().get(0); //Keep iterating
}
}
return passenger;
}
@EventHandler
void carExit(VehicleExitEvent event){
UEntityMeta.removeMetadata(event.getVehicle(), "car.vec");
UEntityMeta.removeMetadata(event.getExited(), "ucars.smooth");
event.getVehicle().removeMetadata("car.vec", ucars.plugin);
event.getExited().removeMetadata("ucars.smooth", ucars.plugin);
if(event.getVehicle().hasMetadata("safeExit.ignore")
|| UEntityMeta.hasMetadata(event.getVehicle(), "safeExit.ignore")){
return;
}
if(!(event.getVehicle() instanceof Vehicle) || !isACar((Vehicle) event.getVehicle())){
return;
}
}
@EventHandler(priority=EventPriority.MONITOR)
void carRemove(VehicleDestroyEvent event){
if(event.isCancelled()){
return;
}
UEntityMeta.removeMetadata(event.getVehicle(), "car.vec");
event.getVehicle().removeMetadata("car.vec", ucars.plugin);
final Vehicle v = event.getVehicle();
Bukkit.getScheduler().runTaskLaterAsynchronously(ucars.plugin, new Runnable(){
@Override
public void run() {
UEntityMeta.removeAllMeta(v);
return;
}}, 100l);
}
@EventHandler
void entityDeath(EntityDeathEvent event){
final Entity e = event.getEntity();
if(e instanceof Player){
return;
}
Bukkit.getScheduler().runTaskLaterAsynchronously(ucars.plugin, new Runnable(){
@Override
public void run() {
UEntityMeta.removeAllMeta(e);
return;
}}, 100l);
}
/*
* Standardises the text on some effect signs
*/
@EventHandler
public void signWriter(SignChangeEvent event) {
String[] lines = event.getLines();
if (ChatColor.stripColor(lines[1]).equalsIgnoreCase("[TrafficLight]")) {
lines[1] = "[TrafficLight]";
}
if (ChatColor.stripColor(lines[0]).equalsIgnoreCase("[uFuel]")) {
lines[0] = "[uFuel]";
}
if (ChatColor.stripColor(lines[0]).equalsIgnoreCase("[Teleport]")) {
lines[0] = "[Teleport]";
}
if(ChatColor.stripColor(lines[0]).equalsIgnoreCase("[wir]")){
if(!event.getPlayer().hasPermission("wirelessredstone")){
event.getPlayer().sendMessage(ChatColor.RED+"Sorry you need the permisson 'wirelessredstone' to do this!");
lines[0] = "";
}
}
return;
}
@EventHandler(priority = EventPriority.LOWEST) //Called first
public void playerJoinControlsUnlock(PlayerJoinEvent event){
ControlSchemeManager.setControlsLocked(event.getPlayer(), false);
}
/*
* Alert op's if no protocolLib found
*/
@EventHandler
public void playerJoin(PlayerJoinEvent event) {
if (event.getPlayer().isOp()) {
if (!plugin.protocolLib) {
event.getPlayer().sendMessage(
ucars.colors.getError()
+ Lang.get("lang.messages.noProtocolLib"));
}
}
}
/*
* Performs on-vehicle-tick calculations(even when stationary) and also
* allows for old versions of minecraft AND ucars to access the new features
* through this 'bridge' (in theory) But in practice they need protocol to
* get past the bukkit dependency exception so it uses that anyway! (Kept
* for old version hybrids, eg. tekkti)
*/
@EventHandler
public void tickCalcsAndLegacy(VehicleUpdateEvent event) {
// start vehicleupdate mechs
Vehicle vehicle = event.getVehicle();
if(!(vehicle instanceof Vehicle)){
return;
}
Entity passenger = getDrivingPassengerOfCar(vehicle); //Gets the entity highest in the passenger 'stack' (Allows for pigucart, etc...)
Boolean driven = passenger != null && passenger instanceof Player;
if(!driven){
return; //Forget extra car physics if minecart isn't manned, takes too much strain with extra entities
}
Vector travel = vehicle.getVelocity();
if(event instanceof ucarUpdateEvent){
travel = ((ucarUpdateEvent) event).getTravelVector().clone();
}
if(!(event instanceof ucarUpdateEvent)){ //If it's just the standard every tick vehicle update event...
if(UEntityMeta.hasMetadata(vehicle, "car.vec")){ //If it has the 'car.vec' meta, we need to use RACE CONTROLS on this vehicle
ucarUpdateEvent evt = (ucarUpdateEvent) UEntityMeta.getMetadata(vehicle, "car.vec").get(0).value(); //Handle the update event (Called here not directly because otherwise ppl with a better connection fire more control events and move marginally faster)
evt.player = ((Player)passenger); //Set the player (in the car) onto the event so it can be handled by uCarUpdate handlers
evt.incrementRead(); //Register that the control input update has been executed (So if no new control input event within 2 ticks; we know to stop the car)
UEntityMeta.removeMetadata(vehicle, "car.vec"); //Update the 'car.vec' metadata with an otherwise identical event; but without the player object attached
ucarUpdateEvent et = new ucarUpdateEvent(vehicle, evt.getTravelVector().clone(), null, evt.getDir()); //Clone of the other event, except no player object attached
et.setRead(evt.getReadCount()); //Make sure it IS a clone (With correct variable values)
UEntityMeta.setMetadata(vehicle, "car.vec", new StatValue(et, ucars.plugin)); //Update the meta on the car
/*ucars.plugin.getServer().getPluginManager().callEvent(evt); //Actually handle the uCarUpdateEvent
*/
if(!ucars.fireUpdateEvent){
onUcarUpdate(evt);
} else {
ucars.plugin.getServer().getPluginManager().callEvent(evt);
}
/*return;*/
}
}
//Everything below this (in this method) is executed EVERY MC vehicle update (every tick) and every ucar update
Block normalblock = vehicle.getLocation().getBlock();
Player player = null;
if (driven) {
player = (Player) passenger;
}
if (!carsEnabled) {
return;
}
Vehicle car = (Vehicle) vehicle;
if (!isACar(car)) {
return;
}
Vector vel = car.getVelocity();
if (vel.getY() > 0.1
&& !UEntityMeta.hasMetadata(car, "car.falling")
&& !UEntityMeta.hasMetadata(car, "car.ascending")) { // Fix jumping bug (Where car just flies up infinitely high when clipping a block)
// in most occasions
if (UEntityMeta.hasMetadata(car, "car.jumping")) {
/*vel.setY(2.5);*/
UEntityMeta.removeMetadata(car, "car.jumping");
} else if (UEntityMeta.hasMetadata(car, "car.jumpFull")) {
// Jumping a full block
if (vel.getY() > 10) {
vel.setY(5);
}
UEntityMeta.removeMetadata(car, "car.jumpFull");
} else if(car.hasMetadata("car.inertialYAxis")) {
//Do nothing
} else {
vel.setY(0);
}
car.setVelocity(vel);
}
// Make jumping work when not moving
// Calculate jumping gravity
if(UEntityMeta.hasMetadata(car, "car.jumpUp")){
double amt = (Double) UEntityMeta.getMetadata(car, "car.jumpUp").get(0).value();
UEntityMeta.removeMetadata(car, "car.jumpUp");
if(amt >= 1.5){
double y = amt * 0.1;
UEntityMeta.setMetadata(car, "car.jumpUp", new StatValue(amt-y, plugin));
vel.setY(y);
car.setVelocity(vel);
return; //We don't want any further calculations
}
else{ //At the peak of ascent
UEntityMeta.setMetadata(car, "car.falling", new StatValue(0.01, plugin));
//car.setMetadata("car.fallingPause", new StatValue(1, plugin));
}
}
if (UEntityMeta.hasMetadata(car, "car.falling")) {
double gravity = (Double) UEntityMeta.getMetadata(car, "car.falling").get(0).value();
double newGravity = gravity + (gravity * 0.6);
UEntityMeta.removeMetadata(car, "car.falling");
if ((gravity <= 0.6)) {
UEntityMeta.setMetadata(car, "car.falling", new StatValue(
newGravity, ucars.plugin));
vel.setY(-(gravity * 1.333 + 0.2d));
car.setVelocity(vel);
}
}
//Start health calculations
CarHealthData health = getCarHealthHandler(car);
Boolean recalculateHealth = false;
// Calculate health based on location
if (normalblock.getType().equals(Material.WATER)) {
double damage = damage_water;
if (damage > 0) {
if (driven) {
double max = defaultHealth;
double left = health.getHealth() - damage;
ChatColor color = ChatColor.YELLOW;
if (left > (max * 0.66)) {
color = ChatColor.GREEN;
}
if (left < (max * 0.33)) {
color = ChatColor.RED;
}
player.sendMessage(ChatColor.RED + "-" + damage + " ["
+ Material.WATER.name().toLowerCase() + "]"
+ color + " (" + left + ")");
}
health.damage(damage, car);
recalculateHealth = true;
}
}
if (normalblock.getType().equals(Material.LAVA)) {
double damage = damage_lava;
if (damage > 0) {
if (driven) {
double max = defaultHealth;
double left = health.getHealth() - damage;
ChatColor color = ChatColor.YELLOW;
if (left > (max * 0.66)) {
color = ChatColor.GREEN;
}
if (left < (max * 0.33)) {
color = ChatColor.RED;
}
player.sendMessage(ChatColor.RED + "-" + damage + " ["
+ Material.LAVA.name().toLowerCase() + "]"
+ color + " (" + left + ")");
}
health.damage(damage, car);
recalculateHealth = true;
}
}
if (recalculateHealth) {
updateCarHealthHandler(car, health);
}
float a = 1;
if(event instanceof ucarUpdateEvent && ucars.smoothDrive){ //If acceleration is enabled
a = ControlInput.getAccel(((ucarUpdateEvent)event).getPlayer(), ((ucarUpdateEvent)event).getDir()); //Find out the multiplier to use for accelerating the car 'naturally'
CarDirection driveDir = ControlInput.getCurrentDriveDir(player);
if(driveDir.equals(CarDirection.BACKWARDS)){
a *= 0.2; //0.2 speed backwards
}
travel.setX(travel.getX() * a); //Multiple only x
travel.setZ(travel.getZ() * a); //and z with it (No y acceleration)
}
Vector dirVec = travel.clone().setY(0).normalize();
if(dirVec.lengthSquared() > 0.01 /*dirVec.lengthSquared() > 0.1 && Math.abs(a) > 0.2 && *//*event.getDir() != null && !event.getDir().equals(CarDirection.NONE)*/){
Location dirLoc = new Location(car.getWorld(), 0, 0, 0); //Make sure car always faces the RIGHT "forwards"
if(event instanceof ucarUpdateEvent && ((ucarUpdateEvent) event).getDir().equals(CarDirection.BACKWARDS)){
dirVec = dirVec.multiply(-1);
}
CarDirection driveDir = ControlInput.getCurrentDriveDir(player);
if(driveDir.equals(CarDirection.BACKWARDS)){
dirVec = dirVec.multiply(-1);
}
dirLoc.setDirection(dirVec);
float yaw = dirLoc.getYaw()+90;
/*if(event.getDir().equals(CarDirection.BACKWARDS)){
yaw += 180;
}*/
if(a < 0){
yaw -= 180;
}
while(yaw < 0){
yaw = 360 + yaw;
}
while(yaw >= 360){
yaw = yaw - 360;
}
CartOrientationUtil.setYaw(car, yaw);
/*WrapperPlayServerEntityLook p = new WrapperPlayServerEntityLook();
p.setEntityID(car.getEntityId());
p.setYaw(yaw);
p.setPitch(car.getLocation().getPitch());
p.sendPacket(player);*/
}
// End health calculations
if (plugin.protocolLib) {
return;
}
/*// Attempt pre-protocollib controls (Broken in MC 1.6.0 and probably above)
Vector playerVelocity = car.getPassenger().getVelocity();
ucarUpdateEvent ucarupdate = new ucarUpdateEvent(car,
playerVelocity, player, CarDirection.NONE);
plugin.getServer().getPluginManager().callEvent(ucarupdate);
return;*/
}
/*
* Performs the actually mechanic for making the cars move
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onUcarUpdate(ucarUpdateEvent event) {
if (event.isCancelled()) {
return;
}
Boolean modY = true;
Vehicle vehicle = event.getVehicle();
if(event.getReadCount() > 2){
UEntityMeta.removeMetadata(vehicle, "car.vec");
vehicle.removeMetadata("car.vec", ucars.plugin);
}
Location under = vehicle.getLocation();
under.setY(vehicle.getLocation().getY() - 1);
Block underblock = under.getBlock();
Block underunderblock = underblock.getRelative(BlockFace.DOWN);
Block normalblock = vehicle.getLocation().getBlock();
// Block up = normalblock.getLocation().add(0, 1, 0).getBlock();
final Player player = event.getPlayer();
if (player == null) {
return;
}
if(!(vehicle instanceof Vehicle)){
return;
}
if (!carsEnabled) {
return;
}
try {
if (licenseEnabled
&& !plugin.licensedPlayers.contains(player.getName())) {
player.sendMessage(ucars.colors.getError()
+ Lang.get("lang.licenses.noLicense"));
return;
}
} catch (Exception e1) {
}
Vehicle car = (Vehicle) vehicle;
if(!isACar(car)){
return;
}
if (!(player.isInsideVehicle())) {
return;
}
//Valid vehicle!
/*Block next = car.getLocation().clone().add(event.getTravelVector().clone().setY(0)).getBlock();
Block underNext = next.getRelative(BlockFace.DOWN);
Block underunderNext = next.getRelative(BlockFace.DOWN, 2);*/
CarHealthData health = this.getCarHealthHandler(car);
Boolean recalculateHealth = false;
if (car.getVelocity().getY() > 0.01
&& !UEntityMeta.hasMetadata(car, "car.falling")
&& !UEntityMeta.hasMetadata(car, "car.ascending")) {
modY = false;
}
if (UEntityMeta.hasMetadata(car, "car.jumping")) {
if (!UEntityMeta.hasMetadata(car, "car.ascending")) {
modY = false;
}
UEntityMeta.removeMetadata(car, "car.jumping");
}
if(car instanceof Minecart && ((Minecart) car).getMaxSpeed() != 5) {
((Minecart)car).setMaxSpeed(5); // Don't allow game breaking speed - but faster than default
}
// Calculate road blocks
if (roadBlocksEnabled) {
/*Location loc = car.getLocation().getBlock()
.getRelative(BlockFace.DOWN).getLocation();*/
if(!plugin.isBlockEqualToConfigIds(roadBlocks, underblock)){
//Not a road block being driven on, so don't move
return;
}
}
Location loc = car.getLocation();
if (!ucars.playersIgnoreTrafficLights && atTrafficLight(car, underblock, underunderblock, loc)){
return; //Being told to wait at a traffic light, don't move
}
// Calculate default effect blocks
if (effectBlocksEnabled) {
if (plugin.isBlockEqualToConfigIds(blockBoost,
underblock)
|| plugin.isBlockEqualToConfigIds(
blockBoost, underunderblock)) {
carBoost(player.getName(), 20, 6000,
defaultSpeed);
}
if (plugin.isBlockEqualToConfigIds(
highBlockBoost, underblock)
|| plugin.isBlockEqualToConfigIds(
highBlockBoost, underunderblock)) {
carBoost(player.getName(), 50, 8000,
defaultSpeed);
}
if (plugin.isBlockEqualToConfigIds(
resetBlockBoost, underblock)
|| plugin
.isBlockEqualToConfigIds(
resetBlockBoost,
underunderblock)) {
ResetCarBoost(player.getName(), car,
defaultSpeed);
}
}
Vector travel = event.getTravelVector(); // Travel Vector,
// fixes
// controls for
// 1.6
if(car.hasMetadata("car.inertialYAxis")) {
travel.setY(event.getVehicle().getVelocity().getY());
}
float a = 1;
if(ucars.smoothDrive){ //If acceleration is enabled
a = ControlInput.getAccel(event.getPlayer(), event.getDir()); //Find out the multiplier to use for accelerating the car 'naturally'
CarDirection driveDir = ControlInput.getCurrentDriveDir(event.getPlayer());
if(driveDir.equals(CarDirection.BACKWARDS)){
a *= 0.2; //0.2 speed backwards
}
travel.setX(travel.getX() * a); //Multiple only x
travel.setZ(travel.getZ() * a); //and z with it (No y acceleration)
}
//Vector dirVec = travel.clone().setY(0).normalize();
/*try {
dirVec = (Vector) (car.hasMetadata("ucarsSteeringDir") ? car.getMetadata("ucarsSteeringDir").get(0).value() : travel.clone().normalize());
} catch (Exception e2) {
dirVec = travel.clone().normalize();
}*/
double multiplier = defaultSpeed;
try {
if (ucars.carBoosts.containsKey(player.getName())) { // Use the
// boost
// allocated
multiplier = ucars.carBoosts.get(player.getName());
}
} catch (Exception e1) {
return;
}
String underMat = under.getBlock().getType().name().toUpperCase();
String underunderMat = underunderblock.getType().name().toUpperCase();
// calculate speedmods
String key = underMat;
if(speedMods.containsKey(key)){
if(!ucars.carBoosts.containsKey(player.getName())){
multiplier = speedMods.get(key);
}
else{
multiplier = (speedMods.get(key)+multiplier)*0.5; //Mean Average of both
}
}
key = underunderMat;
if(speedMods.containsKey(key)){
if(!ucars.carBoosts.containsKey(player.getName())){
multiplier = speedMods.get(key);
}
else{
multiplier = (speedMods.get(key)+multiplier)*0.5; //Mean Average of both
}
}
if (event.getDoDivider()) { // Braking or going slower
multiplier = multiplier * event.getDivider();
}
travel = travel.setX(travel.getX()*multiplier);
travel = travel.setZ(travel.getZ()*multiplier);
if (usePerms) {
if (!player.hasPermission("ucars.cars")) {
player.sendMessage(ucars.colors.getInfo()
+ Lang.get("lang.messages.noDrivePerm"));
return;
}
}
/*if (normalblock.getType() != Material.AIR //Air
&& normalblock.getType() != Material.WATER //Water
&& normalblock.getType() != Material.STATIONARY_WATER //Water
&& normalblock.getType() != Material.STEP //Slab
&& normalblock.getType() != Material.DOUBLE_STEP //Double slab
&& normalblock.getType() != Material.LONG_GRASS //Long grass
&& !normalblock.getType().name().toLowerCase()
.contains("stairs")) {
// Stuck in a block
car.setVelocity(new Vector(0, 0.5, 0));
}*/
Location before = car.getLocation();
//float dir = player.getLocation().getYaw();
float dir = car.getLocation().clone().setDirection(travel).getYaw();
BlockFace faceDir = ClosestFace.getClosestFace(dir);
// before.add(faceDir.getModX(), faceDir.getModY(),
// faceDir.getModZ());
//Read the vehicle length if it exists
double length = car.getWidth();
double fx = travel.getX()*1;
if (Math.abs(fx) > 1) {
fx = faceDir.getModX();
}
double fz = travel.getZ()*1;
if (Math.abs(fz) > 1) {
fz = faceDir.getModZ();
}
//Compute unit vector in car direction of travel
Vector unitVec = new Vector(faceDir.getModX(),0,faceDir.getModZ());
if(unitVec.lengthSquared() > 1){
unitVec.multiply(1/(double)Math.sqrt(2));
}
Vector faceDirVec = new Vector(fx, faceDir.getModY(), fz);
before=before.add(faceDirVec);
//Add the length of the car in so that we are able to climb up blocks with an entity that has length
before=before.add(unitVec.clone().multiply(length*0.5));
Location frontRight = before.clone().add(unitVec.clone().multiply(length*0.5));
Location frontLeft = before.clone().add(unitVec.clone().multiply(length*-0.5));
Block block = before.getBlock(); //Block we're driving into
Block frontRightInFront = frontRight.getBlock();
Block frontLeftInFront = frontLeft.getBlock();
//Hackish way to make this able to jump for wider vehicles
boolean blockNoJump = noJump(block.getType().name());
if(blockNoJump){
if(!noJump(frontRightInFront.getType().name())){
block = frontRightInFront;
}
else if(!noJump(frontLeftInFront.getType().name())){
block = frontLeftInFront;
}
}
/*Block above = block.getRelative(BlockFace.UP);
if((!(block.isEmpty() || block.isLiquid())
&& !(above.isEmpty() || above.isLiquid())
&& !(block.getType().name().toLowerCase().contains("step"))
*//*&& !(above.getType().name().toLowerCase().contains("step"))*//*)
){
*//*ControlInput.setAccel(player, 0); //They hit a wall head on*//*
}*/
// Calculate collision health
if (block.getType().equals(Material.CACTUS)) {
double damage = damage_cactus;
if (damage > 0) {
double max = defaultHealth;
double left = health.getHealth() - damage;
ChatColor color = ChatColor.YELLOW;
if (left > (max * 0.66)) {
color = ChatColor.GREEN;
}
if (left < (max * 0.33)) {
color = ChatColor.RED;
}
player.sendMessage(ChatColor.RED + "-" + damage + " ["
+ Material.CACTUS.name().toLowerCase() + "]"
+ color + " (" + left + ")");
health.damage(damage, car);
recalculateHealth = true;
}
}
// End calculations for collision health
if (fuelEnabled
&& !fuelUseItems
&& !player.hasPermission(fuelBypassPerm)) {
double fuel = 0;
if (ucars.fuel.containsKey(player.getName())) {
fuel = ucars.fuel.get(player.getName());
}
if (fuel < 0.1) {
player.sendMessage(ucars.colors.getError()
+ Lang.get("lang.fuel.empty"));
return;
}
int amount = 0 + (int) (Math.random() * 250);
if (amount == 10) {
fuel = fuel - 0.1;
fuel = (double) Math.round(fuel * 10) / 10;
ucars.fuel.put(player.getName(), fuel);
}
}
else if (fuelEnabled
&& fuelUseItems
&& !player.hasPermission(fuelBypassPerm)) {
// item fuel - Not for laggy servers!!!
double fuel = 0;
ArrayList<ItemStack> items = plugin.ufuelitems;
Inventory inv = player.getInventory();
for (ItemStack item : items) {
if (inv.contains(item.getType(), 1)) {
fuel = fuel + 0.1;
}
}
if (fuel < 0.1) {
player.sendMessage(ucars.colors.getError()
+ Lang.get("lang.fuel.empty"));
return;
}
int amount = 0 + (int) (Math.random() * 150);
if (amount == 10) {
// remove item
Boolean taken = false;
Boolean last = false;
int toUse = 0;
for (int i = 0; i < inv.getContents().length; i++) {