summaryrefslogtreecommitdiffstats
path: root/nms-patches/EntityPlayer.patch
blob: 4f076c2a03971333215bbdda43d304bf1e9275b5 (plain)
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
--- a/net/minecraft/server/EntityPlayer.java
+++ b/net/minecraft/server/EntityPlayer.java
@@ -15,10 +15,28 @@
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 
+// CraftBukkit start
+import com.google.common.base.Preconditions;
+import org.bukkit.Bukkit;
+import org.bukkit.GameMode;
+import org.bukkit.Location;
+import org.bukkit.WeatherType;
+import org.bukkit.craftbukkit.CraftWorld;
+import org.bukkit.craftbukkit.entity.CraftPlayer;
+import org.bukkit.craftbukkit.event.CraftEventFactory;
+import org.bukkit.craftbukkit.inventory.CraftItemStack;
+import org.bukkit.event.inventory.InventoryType;
+import org.bukkit.event.player.PlayerChangedMainHandEvent;
+import org.bukkit.event.player.PlayerGameModeChangeEvent;
+import org.bukkit.event.player.PlayerLocaleChangeEvent;
+import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
+import org.bukkit.inventory.MainHand;
+// CraftBukkit end
+
 public class EntityPlayer extends EntityHuman implements ICrafting {
 
     private static final Logger cc = LogManager.getLogger();
-    public String locale = "en_US";
+    public String locale = "en_us"; // CraftBukkit - lowercase
     public PlayerConnection playerConnection;
     public final MinecraftServer server;
     public final PlayerInteractManager playerInteractManager;
@@ -54,6 +72,19 @@
     public int ping;
     public boolean viewingCredits;
 
+    // CraftBukkit start
+    public String displayName;
+    public IChatBaseComponent listName;
+    public org.bukkit.Location compassTarget;
+    public int newExp = 0;
+    public int newLevel = 0;
+    public int newTotalExp = 0;
+    public boolean keepLevel = false;
+    public double maxHealthCache;
+    public boolean joining = true;
+    public boolean sentListPacket = false;
+    // CraftBukkit end
+
     public EntityPlayer(MinecraftServer minecraftserver, WorldServer worldserver, GameProfile gameprofile, PlayerInteractManager playerinteractmanager) {
         super((World) worldserver, gameprofile);
         playerinteractmanager.player = this;
@@ -64,8 +95,50 @@
         this.cf = minecraftserver.getPlayerList().h(this);
         this.Q = 1.0F;
         this.a(worldserver);
+
+        // CraftBukkit start
+        this.displayName = this.getName();
+        this.canPickUpLoot = true;
+        this.maxHealthCache = this.getMaxHealth();
     }
 
+    // Yes, this doesn't match Vanilla, but it's the best we can do for now.
+    // If this is an issue, PRs are welcome
+    public final BlockPosition getSpawnPoint(WorldServer worldserver) {
+        BlockPosition blockposition = worldserver.getSpawn();
+
+        if (worldserver.worldProvider.g() && worldserver.getWorldData().getGameType() != EnumGamemode.ADVENTURE) {
+            int i = Math.max(0, this.server.a(worldserver));
+            int j = MathHelper.floor(worldserver.getWorldBorder().b((double) blockposition.getX(), (double) blockposition.getZ()));
+
+            if (j < i) {
+                i = j;
+            }
+
+            if (j <= 1) {
+                i = 1;
+            }
+
+            int k = (i * 2 + 1) * (i * 2 + 1);
+            int l = this.r(k);
+            int i1 = (new Random()).nextInt(k);
+
+            for (int j1 = 0; j1 < k; ++j1) {
+                int k1 = (i1 + l * j1) % k;
+                int l1 = k1 % (i * 2 + 1);
+                int i2 = k1 / (i * 2 + 1);
+                BlockPosition blockposition1 = worldserver.o().a(blockposition.getX() + l1 - i, blockposition.getZ() + i2 - i, false);
+
+                if (blockposition1 != null) {
+                    return blockposition1;
+                }
+            }
+        }
+
+        return blockposition;
+    }
+    // CraftBukkit end
+
     private void a(WorldServer worldserver) {
         BlockPosition blockposition = worldserver.getSpawn();
 
@@ -132,6 +205,7 @@
         if (nbttagcompound.hasKeyOfType("recipeBook", 10)) {
             this.cy.a(nbttagcompound.getCompound("recipeBook"));
         }
+        this.getBukkitEntity().readExtraData(nbttagcompound); // CraftBukkit
 
     }
 
@@ -151,7 +225,20 @@
         Entity entity = this.getRootVehicle();
         Entity entity1 = this.getVehicle();
 
-        if (entity1 != null && entity != this && entity.bR()) {
+        // CraftBukkit start - handle non-persistent vehicles
+        boolean persistVehicle = true;
+        if (entity1 != null) {
+            Entity vehicle;
+            for (vehicle = entity1; vehicle != null; vehicle = vehicle.getVehicle()) {
+                if (!vehicle.persist) {
+                    persistVehicle = false;
+                    break;
+                }
+            }
+        }
+
+        if (persistVehicle && entity1 != null && entity != this && entity.bR()) {
+            // CraftBukkit end
             NBTTagCompound nbttagcompound2 = new NBTTagCompound();
             NBTTagCompound nbttagcompound3 = new NBTTagCompound();
 
@@ -162,8 +249,34 @@
         }
 
         nbttagcompound.set("recipeBook", this.cy.e());
+        this.getBukkitEntity().setExtraData(nbttagcompound); // CraftBukkit
     }
 
+    // CraftBukkit start - World fallback code, either respawn location or global spawn
+    public void spawnIn(World world) {
+        super.spawnIn(world);
+        if (world == null) {
+            this.dead = false;
+            BlockPosition position = null;
+            if (this.spawnWorld != null && !this.spawnWorld.equals("")) {
+                CraftWorld cworld = (CraftWorld) Bukkit.getServer().getWorld(this.spawnWorld);
+                if (cworld != null && this.getBed() != null) {
+                    world = cworld.getHandle();
+                    position = EntityHuman.getBed(cworld.getHandle(), this.getBed(), false);
+                }
+            }
+            if (world == null || position == null) {
+                world = ((CraftWorld) Bukkit.getServer().getWorlds().get(0)).getHandle();
+                position = world.getSpawn();
+            }
+            this.world = world;
+            this.setPosition(position.getX() + 0.5, position.getY(), position.getZ() + 0.5);
+        }
+        this.dimension = ((WorldServer) this.world).dimension;
+        this.playerInteractManager.a((WorldServer) world);
+    }
+    // CraftBukkit end
+
     public void a(int i) {
         float f = (float) this.getExpToLevel();
         float f1 = (f - 1.0F) / f;
@@ -210,6 +323,11 @@
     }
 
     public void tick() {
+        // CraftBukkit start
+        if (this.joining) {
+            this.joining = false;
+        }
+        // CraftBukkit end
         this.playerInteractManager.a();
         --this.invulnerableTicks;
         if (this.noDamageTicks > 0) {
@@ -275,7 +393,7 @@
             }
 
             if (this.getHealth() != this.lastHealthSent || this.co != this.foodData.getFoodLevel() || this.foodData.getSaturationLevel() == 0.0F != this.cp) {
-                this.playerConnection.sendPacket(new PacketPlayOutUpdateHealth(this.getHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel()));
+                this.playerConnection.sendPacket(new PacketPlayOutUpdateHealth(this.getBukkitEntity().getScaledHealth(), this.foodData.getFoodLevel(), this.foodData.getSaturationLevel())); // CraftBukkit
                 this.lastHealthSent = this.getHealth();
                 this.co = this.foodData.getFoodLevel();
                 this.cp = this.foodData.getSaturationLevel() == 0.0F;
@@ -306,6 +424,12 @@
                 this.a(IScoreboardCriteria.k, MathHelper.f((float) this.cm));
             }
 
+            // CraftBukkit start - Force max health updates
+            if (this.maxHealthCache != this.getMaxHealth()) {
+                this.getBukkitEntity().updateScaledHealth();
+            }
+            // CraftBukkit end
+
             if (this.expLevel != this.cl) {
                 this.cl = this.expLevel;
                 this.a(IScoreboardCriteria.l, MathHelper.f((float) this.cl));
@@ -320,6 +444,16 @@
                 CriterionTriggers.p.a(this);
             }
 
+            // CraftBukkit start - initialize oldLevel and fire PlayerLevelChangeEvent
+            if (this.oldLevel == -1) {
+                this.oldLevel = this.expLevel;
+            }
+
+            if (this.oldLevel != this.expLevel) {
+                CraftEventFactory.callPlayerLevelChangeEvent(this.world.getServer().getPlayer((EntityPlayer) this), this.oldLevel, this.expLevel);
+                this.oldLevel = this.expLevel;
+            }
+            // CraftBukkit end
         } catch (Throwable throwable) {
             CrashReport crashreport = CrashReport.a(throwable, "Ticking player");
             CrashReportSystemDetails crashreportsystemdetails = crashreport.a("Player being ticked");
@@ -330,24 +464,50 @@
     }
 
     private void a(IScoreboardCriteria iscoreboardcriteria, int i) {
-        this.getScoreboard().getObjectivesForCriteria(iscoreboardcriteria, this.getName(), (scoreboardscore) -> {
+        // CraftBukkit - Use our scores instead
+        this.world.getServer().getScoreboardManager().getScoreboardScores(iscoreboardcriteria, this.getName(), (scoreboardscore) -> {
             scoreboardscore.setScore(i);
         });
     }
 
     public void die(DamageSource damagesource) {
         boolean flag = this.world.getGameRules().getBoolean("showDeathMessages");
+        // CraftBukkit start - fire PlayerDeathEvent
+        if (this.dead) {
+            return;
+        }
+        java.util.List<org.bukkit.inventory.ItemStack> loot = new java.util.ArrayList<org.bukkit.inventory.ItemStack>(this.inventory.getSize());
+        boolean keepInventory = this.world.getGameRules().getBoolean("keepInventory") || this.isSpectator();
+
+        if (!keepInventory) {
+            for (ItemStack item : this.inventory.getContents()) {
+                if (!item.isEmpty() && !EnchantmentManager.shouldNotDrop(item)) {
+                    loot.add(CraftItemStack.asCraftMirror(item));
+                }
+            }
+        }
 
-        if (flag) {
-            IChatBaseComponent ichatbasecomponent = this.getCombatTracker().getDeathMessage();
+        IChatBaseComponent defaultMessage = this.getCombatTracker().getDeathMessage();
+
+        String deathmessage = defaultMessage.getString();
+        org.bukkit.event.entity.PlayerDeathEvent event = CraftEventFactory.callPlayerDeathEvent(this, loot, deathmessage, keepInventory);
+
+        String deathMessage = event.getDeathMessage();
+
+        if (deathMessage != null && deathMessage.length() > 0 && flag) { // TODO: allow plugins to override?
+            IChatBaseComponent ichatbasecomponent;
+            if (deathMessage.equals(deathmessage)) {
+                ichatbasecomponent = this.getCombatTracker().getDeathMessage();
+            } else {
+                ichatbasecomponent = org.bukkit.craftbukkit.util.CraftChatMessage.fromStringOrNull(deathMessage);
+            }
 
             this.playerConnection.a((Packet) (new PacketPlayOutCombatEvent(this.getCombatTracker(), PacketPlayOutCombatEvent.EnumCombatEventType.ENTITY_DIED, ichatbasecomponent)), (future) -> {
                 if (!future.isSuccess()) {
-                    boolean flag = true;
                     String s = ichatbasecomponent.a(256);
                     ChatMessage chatmessage = new ChatMessage("death.attack.message_too_long", new Object[] { (new ChatComponentText(s)).a(EnumChatFormat.YELLOW)});
                     IChatBaseComponent ichatbasecomponent1 = (new ChatMessage("death.attack.even_more_magic", new Object[] { this.getScoreboardDisplayName()})).a((chatmodifier) -> {
-                        chatmodifier.setChatHoverable(new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_TEXT, ichatbasecomponent));
+                        chatmodifier.setChatHoverable(new ChatHoverable(ChatHoverable.EnumHoverAction.SHOW_TEXT, chatmessage));
                     });
 
                     this.playerConnection.sendPacket(new PacketPlayOutCombatEvent(this.getCombatTracker(), PacketPlayOutCombatEvent.EnumCombatEventType.ENTITY_DIED, ichatbasecomponent1));
@@ -370,12 +530,17 @@
         }
 
         this.releaseShoulderEntities();
-        if (!this.world.getGameRules().getBoolean("keepInventory") && !this.isSpectator()) {
-            this.dj();
-            this.inventory.q();
+        // we clean the player's inventory after the EntityDeathEvent is called so plugins can get the exact state of the inventory.
+        if (!event.getKeepInventory()) {
+            this.inventory.clear();
         }
 
-        this.getScoreboard().getObjectivesForCriteria(IScoreboardCriteria.d, this.getName(), ScoreboardScore::incrementScore);
+        this.closeInventory();
+        this.setSpectatorTarget(this); // Remove spectated target
+        // CraftBukkit end
+
+        // CraftBukkit - Get our scores instead
+        this.world.getServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.d, this.getName(), ScoreboardScore::incrementScore);
         EntityLiving entityliving = this.cv();
 
         if (entityliving != null) {
@@ -398,10 +563,12 @@
             String s = this.getName();
             String s1 = entity.getName();
 
-            this.getScoreboard().getObjectivesForCriteria(IScoreboardCriteria.f, s, ScoreboardScore::incrementScore);
+            // CraftBukkit - Get our scores instead
+            this.world.getServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.f, s, ScoreboardScore::incrementScore);
             if (entity instanceof EntityHuman) {
                 this.a(StatisticList.PLAYER_KILLS);
-                this.getScoreboard().getObjectivesForCriteria(IScoreboardCriteria.e, s, ScoreboardScore::incrementScore);
+                // CraftBukkit - Get our scores instead
+                this.world.getServer().getScoreboardManager().getScoreboardScores(IScoreboardCriteria.e, s, ScoreboardScore::incrementScore);
             } else {
                 this.a(StatisticList.MOB_KILLS);
             }
@@ -419,7 +586,8 @@
             int i = scoreboardteam.getColor().b();
 
             if (i >= 0 && i < aiscoreboardcriteria.length) {
-                this.getScoreboard().getObjectivesForCriteria(aiscoreboardcriteria[i], s, ScoreboardScore::incrementScore);
+                // CraftBukkit - Get our scores instead
+                this.world.getServer().getScoreboardManager().getScoreboardScores(aiscoreboardcriteria[i], s, ScoreboardScore::incrementScore);
             }
         }
 
@@ -461,12 +629,14 @@
     }
 
     private boolean canPvP() {
-        return this.server.getPVP();
+        // CraftBukkit - this.server.getPvP() -> this.world.pvpMode
+        return this.world.pvpMode;
     }
 
     @Nullable
     public Entity a(DimensionManager dimensionmanager) {
-        this.worldChangeInvuln = true;
+        if (this.isSleeping()) return this; // CraftBukkit - SPIGOT-3154
+        // this.worldChangeInvuln = true; // CraftBukkit - Moved down and into PlayerList#changeDimension
         if (this.dimension == DimensionManager.OVERWORLD && dimensionmanager == DimensionManager.NETHER) {
             this.cC = new Vec3D(this.locX, this.locY, this.locZ);
         } else if (this.dimension != DimensionManager.NETHER && dimensionmanager != DimensionManager.OVERWORLD) {
@@ -474,6 +644,7 @@
         }
 
         if (this.dimension == DimensionManager.THE_END && dimensionmanager == DimensionManager.THE_END) {
+            this.worldChangeInvuln = true; // CraftBukkit - Moved down from above
             this.world.kill(this);
             if (!this.viewingCredits) {
                 this.viewingCredits = true;
@@ -487,7 +658,10 @@
                 dimensionmanager = DimensionManager.THE_END;
             }
 
-            this.server.getPlayerList().a(this, dimensionmanager);
+            // CraftBukkit start
+            TeleportCause cause = (this.dimension == DimensionManager.THE_END || dimensionmanager == DimensionManager.THE_END) ? TeleportCause.END_PORTAL : TeleportCause.NETHER_PORTAL;
+            this.server.getPlayerList().changeDimension(this, dimensionmanager, cause); // PAIL: check all this
+            // CraftBukkit end
             this.playerConnection.sendPacket(new PacketPlayOutWorldEvent(1032, BlockPosition.ZERO, 0, false));
             this.lastSentExp = -1;
             this.lastHealthSent = -1.0F;
@@ -533,6 +707,7 @@
     }
 
     public void a(boolean flag, boolean flag1, boolean flag2) {
+        if (!this.sleeping) return; // CraftBukkit - Can't leave bed if not in one!
         if (this.isSleeping()) {
             this.getWorldServer().getTracker().sendPacketToEntity(this, new PacketPlayOutAnimation(this, 2));
         }
@@ -611,23 +786,55 @@
         this.playerConnection.sendPacket(new PacketPlayOutOpenSignEditor(tileentitysign.getPosition()));
     }
 
-    public void nextContainerCounter() {
+    public int nextContainerCounter() { // CraftBukkit - void -> int
         this.containerCounter = this.containerCounter % 100 + 1;
+        return containerCounter; // CraftBukkit
     }
 
     public void openTileEntity(ITileEntityContainer itileentitycontainer) {
-        if (itileentitycontainer instanceof ILootable && ((ILootable) itileentitycontainer).getLootTable() != null && this.isSpectator()) {
+        // CraftBukkit start - Inventory open hook
+        if (false && itileentitycontainer instanceof ILootable && ((ILootable) itileentitycontainer).getLootTable() != null && this.isSpectator()) {
             this.a((new ChatMessage("container.spectatorCantOpen", new Object[0])).a(EnumChatFormat.RED), true);
         } else {
+            boolean cancelled = itileentitycontainer instanceof ILootable && ((ILootable) itileentitycontainer).getLootTable()!= null && this.isSpectator();
+            Container container = CraftEventFactory.callInventoryOpenEvent(this, itileentitycontainer.createContainer(this.inventory, this), cancelled);
+            if (container == null) {
+                return;
+            }
             this.nextContainerCounter();
+            this.activeContainer = container;
             this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, itileentitycontainer.getContainerName(), itileentitycontainer.getScoreboardDisplayName()));
-            this.activeContainer = itileentitycontainer.createContainer(this.inventory, this);
+            // CraftBukkit end
             this.activeContainer.windowId = this.containerCounter;
             this.activeContainer.addSlotListener(this);
         }
     }
 
     public void openContainer(IInventory iinventory) {
+        // CraftBukkit start - Inventory open hook
+        // Copied from below
+        boolean cancelled = false;
+        if (iinventory instanceof ITileInventory) {
+            ITileInventory itileinventory = (ITileInventory) iinventory;
+            cancelled = itileinventory.isLocked() && !this.a(itileinventory.getLock()) && !this.isSpectator();
+        }
+
+        Container container;
+        if (iinventory instanceof ITileEntityContainer) {
+            if (iinventory instanceof TileEntity) {
+                Preconditions.checkArgument(((TileEntity) iinventory).getWorld() != null, "Container must have world to be opened");
+            }
+            container = ((ITileEntityContainer) iinventory).createContainer(this.inventory, this);
+        } else {
+            container = new ContainerChest(this.inventory, iinventory, this);
+        }
+        container = CraftEventFactory.callInventoryOpenEvent(this, container, cancelled);
+        if (container == null && !cancelled) { // Let pre-cancelled events fall through
+            iinventory.closeContainer(this);
+            return;
+        }
+        // CraftBukkit end
+
         if (iinventory instanceof ILootable && ((ILootable) iinventory).getLootTable() != null && this.isSpectator()) {
             this.a((new ChatMessage("container.spectatorCantOpen", new Object[0])).a(EnumChatFormat.RED), true);
         } else {
@@ -641,18 +848,21 @@
                 if (itileinventory.isLocked() && !this.a(itileinventory.getLock()) && !this.isSpectator()) {
                     this.playerConnection.sendPacket(new PacketPlayOutChat(new ChatMessage("container.isLocked", new Object[] { iinventory.getScoreboardDisplayName()}), ChatMessageType.GAME_INFO));
                     this.playerConnection.sendPacket(new PacketPlayOutNamedSoundEffect(SoundEffects.BLOCK_CHEST_LOCKED, SoundCategory.BLOCKS, this.locX, this.locY, this.locZ, 1.0F, 1.0F));
+                    iinventory.closeContainer(this); // CraftBukkit
                     return;
                 }
             }
 
             this.nextContainerCounter();
+            // CraftBukkit start
             if (iinventory instanceof ITileEntityContainer) {
+                this.activeContainer = container;
                 this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, ((ITileEntityContainer) iinventory).getContainerName(), iinventory.getScoreboardDisplayName(), iinventory.getSize()));
-                this.activeContainer = ((ITileEntityContainer) iinventory).createContainer(this.inventory, this);
             } else {
+                this.activeContainer = container;
                 this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, "minecraft:container", iinventory.getScoreboardDisplayName(), iinventory.getSize()));
-                this.activeContainer = new ContainerChest(this.inventory, iinventory, this);
             }
+            // CraftBukkit end
 
             this.activeContainer.windowId = this.containerCounter;
             this.activeContainer.addSlotListener(this);
@@ -660,8 +870,14 @@
     }
 
     public void openTrade(IMerchant imerchant) {
+        // CraftBukkit start - Inventory open hook
+        Container container = CraftEventFactory.callInventoryOpenEvent(this, new ContainerMerchant(this.inventory, imerchant, this.world));
+        if (container == null) {
+            return;
+        }
+        // CraftBukkit end
         this.nextContainerCounter();
-        this.activeContainer = new ContainerMerchant(this.inventory, imerchant, this.world);
+        this.activeContainer = container; // CraftBukkit
         this.activeContainer.windowId = this.containerCounter;
         this.activeContainer.addSlotListener(this);
         InventoryMerchant inventorymerchant = ((ContainerMerchant) this.activeContainer).d();
@@ -681,13 +897,20 @@
     }
 
     public void openHorseInventory(EntityHorseAbstract entityhorseabstract, IInventory iinventory) {
+        // CraftBukkit start - Inventory open hook
+        Container container = CraftEventFactory.callInventoryOpenEvent(this, new ContainerHorse(this.inventory, iinventory, entityhorseabstract, this));
+        if (container == null) {
+            iinventory.closeContainer(this);
+            return;
+        }
+        // CraftBukkit end
         if (this.activeContainer != this.defaultContainer) {
             this.closeInventory();
         }
 
         this.nextContainerCounter();
         this.playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.containerCounter, "EntityHorse", iinventory.getScoreboardDisplayName(), iinventory.getSize(), entityhorseabstract.getId()));
-        this.activeContainer = new ContainerHorse(this.inventory, iinventory, entityhorseabstract, this);
+        this.activeContainer = container; // CraftBukkit
         this.activeContainer.windowId = this.containerCounter;
         this.activeContainer.addSlotListener(this);
     }
@@ -728,6 +951,11 @@
     public void a(Container container, NonNullList<ItemStack> nonnulllist) {
         this.playerConnection.sendPacket(new PacketPlayOutWindowItems(container.windowId, nonnulllist));
         this.playerConnection.sendPacket(new PacketPlayOutSetSlot(-1, -1, this.inventory.getCarried()));
+        // CraftBukkit start - Send a Set Slot to update the crafting result slot
+        if (java.util.EnumSet.of(InventoryType.CRAFTING,InventoryType.WORKBENCH).contains(container.getBukkitView().getType())) {
+            this.playerConnection.sendPacket(new PacketPlayOutSetSlot(container.windowId, 0, container.getSlot(0).getItem()));
+        }
+        // CraftBukkit end
     }
 
     public void setContainerData(Container container, int i, int j) {
@@ -742,6 +970,7 @@
     }
 
     public void closeInventory() {
+        CraftEventFactory.handleInventoryCloseEvent(this); // CraftBukkit
         this.playerConnection.sendPacket(new PacketPlayOutCloseWindow(this.activeContainer.windowId));
         this.m();
     }
@@ -775,14 +1004,14 @@
 
     public void a(Statistic<?> statistic, int i) {
         this.cg.b(this, statistic, i);
-        this.getScoreboard().getObjectivesForCriteria(statistic, this.getName(), (scoreboardscore) -> {
+        this.world.getServer().getScoreboardManager().getScoreboardScores(statistic, this.getName(), (scoreboardscore) -> { // CraftBukkit - Get our scores instead
             scoreboardscore.addScore(i);
         });
     }
 
     public void a(Statistic<?> statistic) {
         this.cg.setStatistic(this, statistic, 0);
-        this.getScoreboard().getObjectivesForCriteria(statistic, this.getName(), ScoreboardScore::c);
+        this.world.getServer().getScoreboardManager().getScoreboardScores(statistic, this.getName(), ScoreboardScore::c); // CraftBukkit - Get our scores instead
     }
 
     public int discoverRecipes(Collection<IRecipe> collection) {
@@ -830,8 +1059,17 @@
 
     public void triggerHealthUpdate() {
         this.lastHealthSent = -1.0E8F;
+        this.lastSentExp = -1; // CraftBukkit - Added to reset
     }
 
+    // CraftBukkit start - Support multi-line messages
+    public void sendMessage(IChatBaseComponent[] ichatbasecomponent) {
+        for (IChatBaseComponent component : ichatbasecomponent) {
+            this.sendMessage(component);
+        }
+    }
+    // CraftBukkit end
+
     public void a(IChatBaseComponent ichatbasecomponent, boolean flag) {
         this.playerConnection.sendPacket(new PacketPlayOutChat(ichatbasecomponent, flag ? ChatMessageType.GAME_INFO : ChatMessageType.CHAT));
     }
@@ -882,7 +1120,7 @@
         this.lastSentExp = -1;
         this.lastHealthSent = -1.0F;
         this.co = -1;
-        this.cy.a((RecipeBook) entityplayer.cy);
+        // this.cy.a((RecipeBook) entityplayer.cy); // CraftBukkit
         this.removeQueue.addAll(entityplayer.removeQueue);
         this.cx = entityplayer.cx;
         this.cC = entityplayer.cC;
@@ -941,6 +1179,18 @@
     }
 
     public void a(EnumGamemode enumgamemode) {
+        // CraftBukkit start
+        if (enumgamemode == this.playerInteractManager.getGameMode()) {
+            return;
+        }
+
+        PlayerGameModeChangeEvent event = new PlayerGameModeChangeEvent(getBukkitEntity(), GameMode.getByValue(enumgamemode.getId()));
+        world.getServer().getPluginManager().callEvent(event);
+        if (event.isCancelled()) {
+            return;
+        }
+        // CraftBukkit end
+
         this.playerInteractManager.setGameMode(enumgamemode);
         this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(3, (float) enumgamemode.getId()));
         if (enumgamemode == EnumGamemode.SPECTATOR) {
@@ -988,6 +1238,16 @@
     }
 
     public void a(PacketPlayInSettings packetplayinsettings) {
+        // CraftBukkit start
+        if (getMainHand() != packetplayinsettings.getMainHand()) {
+            PlayerChangedMainHandEvent event = new PlayerChangedMainHandEvent(getBukkitEntity(), getMainHand() == EnumMainHand.LEFT ? MainHand.LEFT : MainHand.RIGHT);
+            this.server.server.getPluginManager().callEvent(event);
+        }
+        if (!this.locale.equals(packetplayinsettings.b())) {
+            PlayerLocaleChangeEvent event = new PlayerLocaleChangeEvent(getBukkitEntity(), packetplayinsettings.b());
+            this.server.server.getPluginManager().callEvent(event);
+        }
+        // CraftBukkit end
         this.locale = packetplayinsettings.b();
         this.cs = packetplayinsettings.d();
         this.ct = packetplayinsettings.e();
@@ -1053,7 +1313,7 @@
         this.cv = (Entity) (entity == null ? this : entity);
         if (entity1 != this.cv) {
             this.playerConnection.sendPacket(new PacketPlayOutCamera(this.cv));
-            this.enderTeleportTo(this.cv.locX, this.cv.locY, this.cv.locZ);
+            this.playerConnection.a(this.cv.locX, this.cv.locY, this.cv.locZ, this.yaw, this.pitch, TeleportCause.SPECTATE); // CraftBukkit
         }
 
     }
@@ -1080,7 +1340,7 @@
 
     @Nullable
     public IChatBaseComponent getPlayerListName() {
-        return null;
+        return listName; // CraftBukkit
     }
 
     public void a(EnumHand enumhand) {
@@ -1097,12 +1357,17 @@
     }
 
     public void J() {
+        if (!CraftEventFactory.callToggleGlideEvent(this, true).isCancelled()) // CraftBukkit
         this.setFlag(7, true);
     }
 
     public void K() {
+        // CraftBukkit start
+        if (!CraftEventFactory.callToggleGlideEvent(this, false).isCancelled()) {
         this.setFlag(7, true);
         this.setFlag(7, false);
+        }
+        // CraftBukkit end
     }
 
     public AdvancementDataPlayer getAdvancementData() {
@@ -1114,9 +1379,16 @@
         return this.cC;
     }
 
+    // CraftBukkit start
     public void a(WorldServer worldserver, double d0, double d1, double d2, float f, float f1) {
+        this.a(worldserver, d0, d1, d2, f, f1, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause.UNKNOWN);
+    }
+
+    public void a(WorldServer worldserver, double d0, double d1, double d2, float f, float f1, org.bukkit.event.player.PlayerTeleportEvent.TeleportCause cause) {
+        // CraftBukkit end
         this.setSpectatorTarget(this);
         this.stopRiding();
+        /* CraftBukkit start - replace with bukkit handling for multi-world
         if (worldserver == this.world) {
             this.playerConnection.a(d0, d1, d2, f, f1);
         } else {
@@ -1141,6 +1413,149 @@
             this.server.getPlayerList().b(this, worldserver);
             this.server.getPlayerList().updateClient(this);
         }
+        */
+        this.getBukkitEntity().teleport(new Location(worldserver.getWorld(), d0, d1, d2, f, f1), cause);
+        // CraftBukkit end
+
+    }
+
+    // CraftBukkit start - Add per-player time and weather.
+    public long timeOffset = 0;
+    public boolean relativeTime = true;
+
+    public long getPlayerTime() {
+        if (this.relativeTime) {
+            // Adds timeOffset to the current server time.
+            return this.world.getDayTime() + this.timeOffset;
+        } else {
+            // Adds timeOffset to the beginning of this day.
+            return this.world.getDayTime() - (this.world.getDayTime() % 24000) + this.timeOffset;
+        }
+    }
+
+    public WeatherType weather = null;
+
+    public WeatherType getPlayerWeather() {
+        return this.weather;
+    }
+
+    public void setPlayerWeather(WeatherType type, boolean plugin) {
+        if (!plugin && this.weather != null) {
+            return;
+        }
+
+        if (plugin) {
+            this.weather = type;
+        }
+
+        if (type == WeatherType.DOWNFALL) {
+            this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(2, 0));
+        } else {
+            this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(1, 0));
+        }
+    }
+
+    private float pluginRainPosition;
+    private float pluginRainPositionPrevious;
+
+    public void updateWeather(float oldRain, float newRain, float oldThunder, float newThunder) {
+        if (this.weather == null) {
+            // Vanilla
+            if (oldRain != newRain) {
+                this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(7, newRain));
+            }
+        } else {
+            // Plugin
+            if (pluginRainPositionPrevious != pluginRainPosition) {
+                this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(7, pluginRainPosition));
+            }
+        }
+
+        if (oldThunder != newThunder) {
+            if (weather == WeatherType.DOWNFALL || weather == null) {
+                this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(8, newThunder));
+            } else {
+                this.playerConnection.sendPacket(new PacketPlayOutGameStateChange(8, 0));
+            }
+        }
+    }
+
+    public void tickWeather() {
+        if (this.weather == null) return;
+
+        pluginRainPositionPrevious = pluginRainPosition;
+        if (weather == WeatherType.DOWNFALL) {
+            pluginRainPosition += 0.01;
+        } else {
+            pluginRainPosition -= 0.01;
+        }
+
+        pluginRainPosition = MathHelper.a(pluginRainPosition, 0.0F, 1.0F);
+    }
+
+    public void resetPlayerWeather() {
+        this.weather = null;
+        this.setPlayerWeather(this.world.getWorldData().hasStorm() ? WeatherType.DOWNFALL : WeatherType.CLEAR, false);
+    }
+
+    @Override
+    public String toString() {
+        return super.toString() + "(" + this.getName() + " at " + this.locX + "," + this.locY + "," + this.locZ + ")";
+    }
+
+    // SPIGOT-1903, MC-98153
+    public void forceSetPositionRotation(double x, double y, double z, float yaw, float pitch) {
+        this.setPositionRotation(x, y, z, yaw, pitch);
+        this.playerConnection.syncPosition();
+    }
+
+    @Override
+    protected boolean isFrozen() {
+        return super.isFrozen() || !getBukkitEntity().isOnline();
+    }
+
+    @Override
+    public Scoreboard getScoreboard() {
+        return getBukkitEntity().getScoreboard().getHandle();
+    }
+
+    public void reset() {
+        float exp = 0;
+        boolean keepInventory = this.world.getGameRules().getBoolean("keepInventory");
+
+        if (this.keepLevel || keepInventory) {
+            exp = this.exp;
+            this.newTotalExp = this.expTotal;
+            this.newLevel = this.expLevel;
+        }
+
+        this.setHealth(this.getMaxHealth());
+        this.fireTicks = 0;
+        this.fallDistance = 0;
+        this.foodData = new FoodMetaData(this);
+        this.expLevel = this.newLevel;
+        this.expTotal = this.newTotalExp;
+        this.exp = 0;
+        this.deathTicks = 0;
+        this.setArrowCount(0);
+        this.removeAllEffects(org.bukkit.event.entity.EntityPotionEffectEvent.Cause.DEATH);
+        this.updateEffects = true;
+        this.activeContainer = this.defaultContainer;
+        this.killer = null;
+        this.lastDamager = null;
+        this.combatTracker = new CombatTracker(this);
+        this.lastSentExp = -1;
+        if (this.keepLevel || keepInventory) {
+            this.exp = exp;
+        } else {
+            this.giveExp(this.newExp);
+        }
+        this.keepLevel = false;
+    }
 
+    @Override
+    public CraftPlayer getBukkitEntity() {
+        return (CraftPlayer) super.getBukkitEntity();
     }
+    // CraftBukkit end
 }