-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathCraftWorld.java
More file actions
2023 lines (1693 loc) · 85.4 KB
/
CraftWorld.java
File metadata and controls
2023 lines (1693 loc) · 85.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.bukkit.craftbukkit;
import ca.spottedleaf.moonrise.common.list.ReferenceList;
import ca.spottedleaf.moonrise.common.util.CoordinateUtils;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.Lists;
import com.mojang.datafixers.util.Pair;
import io.papermc.paper.FeatureHooks;
import io.papermc.paper.raytracing.BlockCollisionMode;
import io.papermc.paper.raytracing.PositionedRayTraceConfigurationBuilder;
import io.papermc.paper.raytracing.PositionedRayTraceConfigurationBuilderImpl;
import io.papermc.paper.raytracing.RayTraceTarget;
import io.papermc.paper.registry.RegistryAccess;
import io.papermc.paper.registry.RegistryKey;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.PrimitiveIterator;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import net.kyori.adventure.pointer.PointersSupplier;
import net.minecraft.SharedConstants;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.HolderSet;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.protocol.game.ClientboundLevelEventPacket;
import net.minecraft.network.protocol.game.ClientboundSetTimePacket;
import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket;
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.DistanceManager;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.TicketType;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
import net.minecraft.util.NullOps;
import net.minecraft.world.attribute.BedRule;
import net.minecraft.world.attribute.EnvironmentAttributes;
import net.minecraft.world.entity.EntitySpawnReason;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LightningBolt;
import net.minecraft.world.entity.item.FallingBlockEntity;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.raid.Raids;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.Climate;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ImposterProtoChunk;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.status.ChunkStatus;
import net.minecraft.world.level.gamerules.GameRule;
import net.minecraft.world.level.gamerules.GameRules;
import net.minecraft.world.level.levelgen.structure.StructureStart;
import net.minecraft.world.level.storage.LevelData;
import net.minecraft.world.level.storage.LevelResource;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.CollisionContext;
import org.bukkit.BlockChangeDelegate;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.ChunkSnapshot;
import org.bukkit.Difficulty;
import org.bukkit.Effect;
import org.bukkit.FluidCollisionMode;
import org.bukkit.Location;
import org.bukkit.NamespacedKey;
import org.bukkit.Particle;
import org.bukkit.Raid;
import org.bukkit.Sound;
import org.bukkit.TreeType;
import org.bukkit.World;
import org.bukkit.WorldBorder;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.BlockData;
import org.bukkit.boss.DragonBattle;
import org.bukkit.craftbukkit.block.CraftBiome;
import org.bukkit.craftbukkit.block.CraftBlock;
import org.bukkit.craftbukkit.block.CraftBlockState;
import org.bukkit.craftbukkit.block.CraftBlockType;
import org.bukkit.craftbukkit.block.data.CraftBlockData;
import org.bukkit.craftbukkit.boss.CraftDragonBattle;
import org.bukkit.craftbukkit.entity.CraftEntity;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.craftbukkit.event.CraftEventFactory;
import org.bukkit.craftbukkit.generator.structure.CraftGeneratedStructure;
import org.bukkit.craftbukkit.generator.structure.CraftStructure;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
import org.bukkit.craftbukkit.metadata.BlockMetadataStore;
import org.bukkit.craftbukkit.persistence.CraftPersistentDataContainer;
import org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry;
import org.bukkit.craftbukkit.util.CraftBiomeSearchResult;
import org.bukkit.craftbukkit.util.CraftDifficulty;
import org.bukkit.craftbukkit.util.CraftLocation;
import org.bukkit.craftbukkit.util.CraftNamespacedKey;
import org.bukkit.craftbukkit.util.CraftRayTraceResult;
import org.bukkit.craftbukkit.util.CraftSpawnCategory;
import org.bukkit.craftbukkit.util.CraftStructureSearchResult;
import org.bukkit.entity.AbstractArrow;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.LightningStrike;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.SpawnCategory;
import org.bukkit.entity.SpectralArrow;
import org.bukkit.entity.TippedArrow;
import org.bukkit.entity.Trident;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.world.SpawnChangeEvent;
import org.bukkit.event.world.TimeSkipEvent;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.generator.structure.GeneratedStructure;
import org.bukkit.generator.structure.Structure;
import org.bukkit.generator.structure.StructureType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.messaging.StandardMessenger;
import org.bukkit.potion.PotionType;
import org.bukkit.util.BiomeSearchResult;
import org.bukkit.util.BoundingBox;
import org.bukkit.util.NumberConversions;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.StructureSearchResult;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class CraftWorld extends CraftRegionAccessor implements World {
private static final CraftPersistentDataTypeRegistry DATA_TYPE_REGISTRY = new CraftPersistentDataTypeRegistry();
private static final PointersSupplier<World> POINTERS_SUPPLIER = PointersSupplier.<World>builder()
.resolving(net.kyori.adventure.identity.Identity.NAME, World::getName)
.resolving(net.kyori.adventure.identity.Identity.UUID, World::getUID)
.build();
private final ServerLevel world;
private WorldBorder worldBorder;
private Environment environment;
private final CraftServer server = (CraftServer) Bukkit.getServer();
private final @Nullable ChunkGenerator generator;
private final @Nullable BiomeProvider biomeProvider;
private final List<BlockPopulator> populators = new ArrayList<>();
private final BlockMetadataStore blockMetadata = new BlockMetadataStore(this);
private final Object2IntOpenHashMap<SpawnCategory> spawnCategoryLimit = new Object2IntOpenHashMap<>();
private final CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(CraftWorld.DATA_TYPE_REGISTRY);
// Paper start - void damage configuration
private boolean voidDamageEnabled;
private float voidDamageAmount;
private double voidDamageMinBuildHeightOffset;
@Override
public boolean isVoidDamageEnabled() {
return this.voidDamageEnabled;
}
@Override
public void setVoidDamageEnabled(final boolean enabled) {
this.voidDamageEnabled = enabled;
}
@Override
public float getVoidDamageAmount() {
return this.voidDamageAmount;
}
@Override
public void setVoidDamageAmount(float voidDamageAmount) {
this.voidDamageAmount = voidDamageAmount;
}
@Override
public double getVoidDamageMinBuildHeightOffset() {
return this.voidDamageMinBuildHeightOffset;
}
@Override
public void setVoidDamageMinBuildHeightOffset(double minBuildHeightOffset) {
this.voidDamageMinBuildHeightOffset = minBuildHeightOffset;
}
// Paper end - void damage configuration
// Paper start - Provide fast information methods
@Override
public int getEntityCount() {
return this.world.getEntityCount();
}
@Override
public int getTileEntityCount() {
// We don't use the full world block entity list, so we must iterate chunks
int size = 0;
for (ChunkHolder playerchunk : ca.spottedleaf.moonrise.common.PlatformHooks.get().getVisibleChunkHolders(this.world)) {
net.minecraft.world.level.chunk.LevelChunk chunk = playerchunk.getTickingChunk();
if (chunk == null) {
continue;
}
size += chunk.blockEntities.size();
}
return size;
}
@Override
public int getTickableTileEntityCount() {
return world.blockEntityTickers.size();
}
@Override
public int getChunkCount() {
return this.world.getChunkSource().getFullChunksCount();
}
@Override
public int getPlayerCount() {
return world.players().size();
}
@Override
public BiomeProvider vanillaBiomeProvider() {
ServerChunkCache serverCache = this.getHandle().chunkSource;
final net.minecraft.world.level.chunk.ChunkGenerator gen = serverCache.getGenerator();
net.minecraft.world.level.biome.BiomeSource biomeSource;
if (gen instanceof org.bukkit.craftbukkit.generator.CustomChunkGenerator custom) {
biomeSource = custom.getDelegate().getBiomeSource();
} else {
biomeSource = gen.getBiomeSource();
}
if (biomeSource instanceof org.bukkit.craftbukkit.generator.CustomWorldChunkManager customBiomeSource) {
biomeSource = customBiomeSource.vanillaBiomeSource;
}
final net.minecraft.world.level.biome.BiomeSource finalBiomeSource = biomeSource;
final net.minecraft.world.level.biome.Climate.Sampler sampler = serverCache.randomState().sampler();
final List<Biome> possibleBiomes = finalBiomeSource.possibleBiomes().stream()
.map(CraftBiome::minecraftHolderToBukkit)
.toList();
return new BiomeProvider() {
@Override
public Biome getBiome(final org.bukkit.generator.WorldInfo worldInfo, final int x, final int y, final int z) {
return CraftBiome.minecraftHolderToBukkit(finalBiomeSource.getNoiseBiome(x >> 2, y >> 2, z >> 2, sampler));
}
@Override
public List<Biome> getBiomes(final org.bukkit.generator.WorldInfo worldInfo) {
return possibleBiomes;
}
};
}
// Paper end
// Paper start - structure check API
@Override
public boolean hasStructureAt(final io.papermc.paper.math.Position position, final Structure structure) {
return this.world.structureManager().getStructureWithPieceAt(
io.papermc.paper.util.MCUtil.toBlockPos(position),
CraftStructure.bukkitToMinecraft(structure)
).isValid();
}
// Paper end
private static final Random rand = new Random();
public CraftWorld(ServerLevel world, @Nullable ChunkGenerator generator, @Nullable BiomeProvider biomeProvider, Environment environment) {
this.world = world;
this.generator = generator;
this.biomeProvider = biomeProvider;
this.environment = environment;
// Paper start - per world spawn limits
for (SpawnCategory spawnCategory : SpawnCategory.values()) {
if (CraftSpawnCategory.isValidForLimits(spawnCategory)) {
setSpawnLimit(spawnCategory, this.world.paperConfig().entities.spawning.spawnLimits.getInt(CraftSpawnCategory.toNMS(spawnCategory)));
}
}
// Paper end - per world spawn limits
// Paper start - per world void damage height
this.voidDamageEnabled = this.world.paperConfig().environment.voidDamageAmount.enabled();
this.voidDamageMinBuildHeightOffset = this.world.paperConfig().environment.voidDamageMinBuildHeightOffset;
this.voidDamageAmount = (float) this.world.paperConfig().environment.voidDamageAmount.or(0);
// Paper end - per world void damage height
}
@Override
public Block getBlockAt(int x, int y, int z) {
return CraftBlock.at(this.world, new BlockPos(x, y, z));
}
@Override
public Location getSpawnLocation() {
final LevelData.RespawnData respawnData = this.world.serverLevelData.getRespawnData();
return CraftLocation.toBukkit(respawnData.pos(), this, respawnData.yaw(), respawnData.pitch());
}
@Override
public boolean setSpawnLocation(Location location) {
Preconditions.checkArgument(location != null, "location");
return this.equals(location.getWorld()) ? this.setSpawnLocation(location.getBlockX(), location.getBlockY(), location.getBlockZ(), location.getYaw(), location.getPitch()) : false;
}
private boolean setSpawnLocation(int x, int y, int z, float yaw, float pitch) {
try {
Location previousLocation = this.getSpawnLocation();
this.world.serverLevelData.setSpawn(LevelData.RespawnData.of(this.world.dimension(), new BlockPos(x, y, z), yaw, pitch));
this.server.getServer().updateEffectiveRespawnData();
new SpawnChangeEvent(this, previousLocation).callEvent();
return true;
} catch (Exception e) {
return false;
}
}
@Override
public boolean setSpawnLocation(int x, int y, int z, float yaw) {
return this.setSpawnLocation(x, y, z, yaw, 0);
}
// Paper start
private static void warnUnsafeChunk(String reason, int x, int z) {
// if any chunk coord is outside of 30 million blocks
int max = (Level.MAX_LEVEL_SIZE / 16) + 625;
if (x > max || z > max || x < -max || z < -max) {
Plugin plugin = io.papermc.paper.util.StackWalkerUtil.getFirstPluginCaller();
if (plugin != null) {
plugin.getLogger().warning("Plugin is %s at (%s, %s), this might cause issues.".formatted(reason, x, z));
}
if (net.minecraft.server.MinecraftServer.getServer().isDebugging()) {
io.papermc.paper.util.TraceUtil.dumpTraceForThread("Dangerous chunk retrieval");
}
}
}
// Paper end
@Override
public Chunk getChunkAt(int x, int z) {
warnUnsafeChunk("getting a faraway chunk", x, z); // Paper
net.minecraft.world.level.chunk.LevelChunk chunk = (net.minecraft.world.level.chunk.LevelChunk) this.world.getChunk(x, z, ChunkStatus.FULL, true);
return new CraftChunk(chunk);
}
@NotNull
@Override
public Chunk getChunkAt(int x, int z, boolean generate) {
if (generate) {
return this.getChunkAt(x, z);
}
return new CraftChunk(this.getHandle(), x, z);
}
@Override
public Chunk getChunkAt(Block block) {
Preconditions.checkArgument(block != null, "null block");
return this.getChunkAt(block.getX() >> 4, block.getZ() >> 4);
}
@Override
public boolean isChunkLoaded(int x, int z) {
return this.world.getChunkSource().isChunkLoaded(x, z);
}
@Override
public boolean isChunkGenerated(int x, int z) {
// Paper start - Fix this method
if (!Bukkit.isPrimaryThread()) {
return java.util.concurrent.CompletableFuture.supplyAsync(() -> {
return CraftWorld.this.isChunkGenerated(x, z);
}, world.getChunkSource().mainThreadProcessor).join();
}
ChunkAccess chunk = world.getChunkSource().getChunkAtImmediately(x, z);
if (chunk != null) {
return chunk instanceof ImposterProtoChunk || chunk instanceof net.minecraft.world.level.chunk.LevelChunk;
}
final java.util.concurrent.CompletableFuture<ChunkAccess> future = new java.util.concurrent.CompletableFuture<>();
ca.spottedleaf.moonrise.common.PlatformHooks.get().scheduleChunkLoad(
this.world, x, z, false, ChunkStatus.EMPTY, true, ca.spottedleaf.concurrentutil.util.Priority.NORMAL, future::complete
);
world.getChunkSource().mainThreadProcessor.managedBlock(future::isDone);
return future.thenApply(c -> {
if (c != null) {
return c.getPersistedStatus() == ChunkStatus.FULL;
}
return false;
}).join();
// Paper end - Fix this method
}
@Override
public Chunk[] getLoadedChunks() {
ServerChunkCache serverChunkCache = this.getHandle().chunkSource;
ReferenceList<Chunk> chunks = new ReferenceList<>(new Chunk[serverChunkCache.fullChunks.size()]);
for (PrimitiveIterator.OfLong iterator = serverChunkCache.fullChunks.keyIterator(); iterator.hasNext();) {
long chunk = iterator.nextLong();
chunks.add(new CraftChunk(this.world, CoordinateUtils.getChunkX(chunk), CoordinateUtils.getChunkZ(chunk)));
}
Chunk[] raw = chunks.getRawDataUnchecked();
int size = chunks.size();
if (raw.length == size) {
// always true when on main
return raw;
}
return Arrays.copyOf(raw, size);
}
@Override
public boolean unloadChunk(int x, int z, boolean save) {
return this.unloadChunk0(x, z, save);
}
@Override
public boolean unloadChunkRequest(int x, int z) {
org.spigotmc.AsyncCatcher.catchOp("chunk unload"); // Spigot
if (this.isChunkLoaded(x, z)) {
this.world.getChunkSource().removeTicketWithRadius(TicketType.PLUGIN, new ChunkPos(x, z), 1);
}
return true;
}
private boolean unloadChunk0(int x, int z, boolean save) {
org.spigotmc.AsyncCatcher.catchOp("chunk unload"); // Spigot
if (!this.isChunkLoaded(x, z)) {
return true;
}
net.minecraft.world.level.chunk.LevelChunk chunk = this.world.getChunk(x, z);
if (!save) {
chunk.tryMarkSaved(); // Use method call to account for persistentDataContainer
}
this.unloadChunkRequest(x, z);
this.world.getChunkSource().purgeUnload();
return !this.isChunkLoaded(x, z);
}
@Override
public boolean refreshChunk(int x, int z) {
ChunkHolder playerChunk = this.world.getChunkSource().chunkMap.getVisibleChunkIfPresent(ChunkPos.asLong(x, z));
if (playerChunk == null) return false;
// Paper start - chunk system
net.minecraft.world.level.chunk.LevelChunk chunk = playerChunk.getChunkToSend();
if (chunk == null) {
return false;
}
// Paper end - chunk system
List<ServerPlayer> playersInRange = playerChunk.playerProvider.getPlayers(playerChunk.getPos(), false);
if (playersInRange.isEmpty()) return true; // Paper - chunk system
FeatureHooks.sendChunkRefreshPackets(playersInRange, chunk);
// Paper - chunk system
return true;
}
@Override
public Collection<Player> getPlayersSeeingChunk(Chunk chunk) {
Preconditions.checkArgument(chunk != null, "chunk cannot be null");
return this.getPlayersSeeingChunk(chunk.getX(), chunk.getZ());
}
@Override
public Collection<Player> getPlayersSeeingChunk(int x, int z) {
if (!this.isChunkLoaded(x, z)) {
return Collections.emptySet();
}
List<ServerPlayer> players = this.world.getChunkSource().chunkMap.getPlayers(new ChunkPos(x, z), false);
if (players.isEmpty()) {
return Collections.emptySet();
}
return players.stream()
.filter(Objects::nonNull)
.map(ServerPlayer::getBukkitEntity)
.collect(Collectors.toUnmodifiableSet());
}
@Override
public boolean isChunkInUse(int x, int z) {
return this.isChunkLoaded(x, z);
}
@Override
public boolean loadChunk(int x, int z, boolean generate) {
org.spigotmc.AsyncCatcher.catchOp("chunk load"); // Spigot
warnUnsafeChunk("loading a faraway chunk", x, z); // Paper
ChunkAccess chunk = this.world.getChunkSource().getChunk(x, z, generate || isChunkGenerated(x, z) ? ChunkStatus.FULL : ChunkStatus.EMPTY, true); // Paper
// If generate = false, but the chunk already exists, we will get this back.
if (chunk instanceof ImposterProtoChunk) {
// We then cycle through again to get the full chunk immediately, rather than after the ticket addition
chunk = this.world.getChunkSource().getChunk(x, z, ChunkStatus.FULL, true);
}
if (chunk instanceof LevelChunk) {
this.world.getChunkSource().addTicketWithRadius(TicketType.PLUGIN, new ChunkPos(x, z), 1);
return true;
}
return false;
}
@Override
public boolean isChunkLoaded(Chunk chunk) {
Preconditions.checkArgument(chunk != null, "null chunk");
return this.isChunkLoaded(chunk.getX(), chunk.getZ());
}
@Override
public void loadChunk(Chunk chunk) {
Preconditions.checkArgument(chunk != null, "null chunk");
this.loadChunk(chunk.getX(), chunk.getZ());
}
@Override
public boolean addPluginChunkTicket(int x, int z, Plugin plugin) {
warnUnsafeChunk("adding a faraway chunk ticket", x, z); // Paper
Preconditions.checkArgument(plugin != null, "null plugin");
Preconditions.checkArgument(plugin.isEnabled(), "plugin is not enabled");
final DistanceManager distanceManager = this.world.getChunkSource().chunkMap.distanceManager;
if (distanceManager.ticketStorage.addPluginRegionTicket(new ChunkPos(x, z), plugin)) {
this.getChunkAt(x, z); // ensure it's loaded
return true;
}
return false;
}
@Override
public boolean removePluginChunkTicket(int x, int z, Plugin plugin) {
Preconditions.checkNotNull(plugin, "null plugin");
final DistanceManager distanceManager = this.world.getChunkSource().chunkMap.distanceManager;
return distanceManager.ticketStorage.removePluginRegionTicket(new ChunkPos(x, z), plugin);
}
@Override
public void removePluginChunkTickets(Plugin plugin) {
Preconditions.checkNotNull(plugin, "null plugin");
DistanceManager chunkDistanceManager = this.world.getChunkSource().chunkMap.distanceManager;
chunkDistanceManager.ticketStorage.removeAllPluginRegionTickets(TicketType.PLUGIN_TICKET, ChunkMap.FORCED_TICKET_LEVEL, plugin);
}
@Override
public Collection<Plugin> getPluginChunkTickets(int x, int z) {
return FeatureHooks.getPluginChunkTickets(this.world, x, z); // Paper - chunk system
}
@Override
public Map<Plugin, Collection<Chunk>> getPluginChunkTickets() {
return FeatureHooks.getPluginChunkTickets(this.world); // Paper - chunk system
}
@NotNull
@Override
public Collection<Chunk> getIntersectingChunks(@NotNull BoundingBox boundingBox) {
List<Chunk> chunks = new ArrayList<>();
int minX = NumberConversions.floor(boundingBox.getMinX()) >> 4;
int maxX = NumberConversions.floor(boundingBox.getMaxX()) >> 4;
int minZ = NumberConversions.floor(boundingBox.getMinZ()) >> 4;
int maxZ = NumberConversions.floor(boundingBox.getMaxZ()) >> 4;
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
chunks.add(this.getChunkAt(x, z, false));
}
}
return chunks;
}
@Override
public boolean isChunkForceLoaded(int x, int z) {
return this.getHandle().getForceLoadedChunks().contains(ChunkPos.asLong(x, z));
}
@Override
public void setChunkForceLoaded(int x, int z, boolean forced) {
warnUnsafeChunk("forceloading a faraway chunk", x, z); // Paper
this.getHandle().setChunkForced(x, z, forced);
}
@Override
public Collection<Chunk> getForceLoadedChunks() {
Set<Chunk> chunks = new HashSet<>();
for (long coord : this.getHandle().getForceLoadedChunks()) {
chunks.add(new CraftChunk(this.getHandle(), ChunkPos.getX(coord), ChunkPos.getZ(coord)));
}
return Collections.unmodifiableCollection(chunks);
}
public ServerLevel getHandle() {
return this.world;
}
@Override
public org.bukkit.entity.Item dropItem(Location location, ItemStack item, Consumer<? super org.bukkit.entity.Item> function) {
Preconditions.checkArgument(location != null, "Location cannot be null");
Preconditions.checkArgument(item != null, "ItemStack cannot be null");
ItemEntity entity = new ItemEntity(this.world, location.getX(), location.getY(), location.getZ(), CraftItemStack.asNMSCopy(item));
org.bukkit.entity.Item itemEntity = (org.bukkit.entity.Item) entity.getBukkitEntity();
entity.pickupDelay = 10;
if (function != null) {
function.accept(itemEntity);
}
this.world.addFreshEntity(entity, SpawnReason.CUSTOM);
return itemEntity;
}
@Override
public org.bukkit.entity.Item dropItemNaturally(Location location, ItemStack item, Consumer<? super org.bukkit.entity.Item> function) {
Preconditions.checkArgument(location != null, "Location cannot be null");
Preconditions.checkArgument(item != null, "ItemStack cannot be null");
double xs = Mth.nextDouble(this.world.random, -0.25D, 0.25D);
double ys = Mth.nextDouble(this.world.random, -0.25D, 0.25D) - ((double) EntityType.ITEM.getHeight() / 2.0D);
double zs = Mth.nextDouble(this.world.random, -0.25D, 0.25D);
location = location.clone().add(xs, ys, zs);
return this.dropItem(location, item, function);
}
@Override
public <T extends AbstractArrow> T spawnArrow(Location location, Vector direction, float speed, float spread, Class<T> clazz) {
Preconditions.checkArgument(location != null, "Location cannot be null");
Preconditions.checkArgument(direction != null, "Vector cannot be null");
Preconditions.checkArgument(clazz != null, "clazz Entity for the arrow cannot be null");
net.minecraft.world.entity.projectile.arrow.AbstractArrow arrow;
if (TippedArrow.class.isAssignableFrom(clazz)) {
arrow = EntityType.ARROW.create(this.world, EntitySpawnReason.COMMAND);
((Arrow) arrow.getBukkitEntity()).setBasePotionType(PotionType.WATER);
} else if (SpectralArrow.class.isAssignableFrom(clazz)) {
arrow = EntityType.SPECTRAL_ARROW.create(this.world, EntitySpawnReason.COMMAND);
} else if (Trident.class.isAssignableFrom(clazz)) {
arrow = EntityType.TRIDENT.create(this.world, EntitySpawnReason.COMMAND);
} else {
arrow = EntityType.ARROW.create(this.world, EntitySpawnReason.COMMAND);
}
arrow.snapTo(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
arrow.shoot(direction.getX(), direction.getY(), direction.getZ(), speed, spread);
this.world.addFreshEntity(arrow);
return (T) arrow.getBukkitEntity();
}
@Override
public LightningStrike strikeLightning(Location loc) {
return this.strikeLightning0(loc, false);
}
@Override
public LightningStrike strikeLightningEffect(Location loc) {
return this.strikeLightning0(loc, true);
}
private LightningStrike strikeLightning0(Location loc, boolean isVisual) {
Preconditions.checkArgument(loc != null, "Location cannot be null");
LightningBolt lightning = EntityType.LIGHTNING_BOLT.create(this.world, EntitySpawnReason.COMMAND);
lightning.snapTo(loc.getX(), loc.getY(), loc.getZ());
lightning.isEffect = isVisual; // Paper - Properly handle lightning effects api
this.world.strikeLightning(lightning, LightningStrikeEvent.Cause.CUSTOM);
return (LightningStrike) lightning.getBukkitEntity();
}
// Paper start - Add methods to find targets for lightning strikes
@Override
public Location findLightningRod(Location location) {
return this.world.findLightningRod(CraftLocation.toBlockPosition(location))
.map(blockPos -> CraftLocation.toBukkit(blockPos, this.world)
// get the actual rod pos
.subtract(0, 1, 0))
.orElse(null);
}
@Override
public Location findLightningTarget(Location location) {
final BlockPos pos = this.world.findLightningTargetAround(CraftLocation.toBlockPosition(location), true);
return pos == null ? null : CraftLocation.toBukkit(pos, this.world);
}
// Paper end - Add methods to find targets for lightning strikes
@Override
public boolean generateTree(Location loc, TreeType type) {
return this.generateTree(loc, CraftWorld.rand, type);
}
@Override
public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate) {
this.world.captureTreeGeneration = true;
this.world.captureBlockStates = true;
boolean grownTree = this.generateTree(loc, type);
this.world.captureBlockStates = false;
this.world.captureTreeGeneration = false;
if (grownTree) { // Copy block data to delegate
for (BlockState blockstate : this.world.capturedBlockStates.values()) {
BlockPos position = ((CraftBlockState) blockstate).getPosition();
net.minecraft.world.level.block.state.BlockState oldBlock = this.world.getBlockState(position);
int flags = ((CraftBlockState) blockstate).getFlags();
delegate.setBlockData(blockstate.getX(), blockstate.getY(), blockstate.getZ(), blockstate.getBlockData());
net.minecraft.world.level.block.state.BlockState newBlock = this.world.getBlockState(position);
this.world.notifyAndUpdatePhysics(position, null, oldBlock, newBlock, newBlock, flags, net.minecraft.world.level.block.Block.UPDATE_LIMIT);
}
this.world.capturedBlockStates.clear();
return true;
} else {
this.world.capturedBlockStates.clear();
return false;
}
}
@Override
public String getName() {
return this.world.serverLevelData.getLevelName();
}
@Override
public UUID getUID() {
return this.world.uuid;
}
@Override
public NamespacedKey getKey() {
return CraftNamespacedKey.fromMinecraft(this.world.dimension().identifier());
}
@Override
public String toString() {
return "CraftWorld{name=" + this.getName() + '}';
}
@Override
public long getTime() {
long time = this.getFullTime() % SharedConstants.TICKS_PER_GAME_DAY;
if (time < 0) time += SharedConstants.TICKS_PER_GAME_DAY;
return time;
}
@Override
public void setTime(long time) {
long margin = (time - this.getFullTime()) % SharedConstants.TICKS_PER_GAME_DAY;
if (margin < 0) margin += SharedConstants.TICKS_PER_GAME_DAY;
this.setFullTime(this.getFullTime() + margin);
}
@Override
public long getFullTime() {
return this.world.getDayTime();
}
@Override
public void setFullTime(long time) {
// Notify anyone who's listening
TimeSkipEvent event = new TimeSkipEvent(this, TimeSkipEvent.SkipReason.CUSTOM, time - this.world.getDayTime());
this.server.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
this.world.setDayTime(this.world.getDayTime() + event.getSkipAmount());
// Forces the client to update to the new time immediately
for (Player p : this.getPlayers()) {
CraftPlayer cp = (CraftPlayer) p;
if (cp.getHandle().connection == null) continue;
cp.getHandle().connection.send(new ClientboundSetTimePacket(cp.getHandle().level().getGameTime(), cp.getHandle().getPlayerTime(), cp.getHandle().relativeTime && cp.getHandle().level().getGameRules().get(GameRules.ADVANCE_TIME)));
}
}
// Paper start
@Override
public boolean isDayTime() {
return getHandle().isBrightOutside();
}
// Paper end
@Override
public long getGameTime() {
return this.world.levelData.getGameTime();
}
@Override
public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks, Entity source) {
// Paper start - expand explosion API
return this.createExplosion(x, y, z, power, setFire, breakBlocks, source, null);
}
private boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks, Entity source, Consumer<net.minecraft.world.level.ServerExplosion> configurator) {
// Paper end - expand explosion API
net.minecraft.world.level.Level.ExplosionInteraction explosionType;
if (!breakBlocks) {
explosionType = net.minecraft.world.level.Level.ExplosionInteraction.NONE; // Don't break blocks
} else if (source == null) {
explosionType = net.minecraft.world.level.Level.ExplosionInteraction.STANDARD; // Break blocks, don't decay drops
} else if (source instanceof org.bukkit.entity.minecart.ExplosiveMinecart || source instanceof org.bukkit.entity.TNTPrimed) {
explosionType = net.minecraft.world.level.Level.ExplosionInteraction.TNT;
} else {
explosionType = net.minecraft.world.level.Level.ExplosionInteraction.MOB; // Respect mobGriefing gamerule
}
net.minecraft.world.entity.Entity entity = (source == null) ? null : ((CraftEntity) source).getHandle();
return !this.world.explode0(entity, Explosion.getDefaultDamageSource(this.world, entity), null, x, y, z, power, setFire, explosionType, ParticleTypes.EXPLOSION, ParticleTypes.EXPLOSION_EMITTER, Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES, SoundEvents.GENERIC_EXPLODE, configurator).wasCanceled; // Paper - expand explosion API
}
// Paper start
@Override
public boolean createExplosion(Entity source, Location loc, float power, boolean setFire, boolean breakBlocks, boolean excludeSourceFromDamage) {
return this.createExplosion(loc.x(), loc.getY(), loc.getZ(), power, setFire, breakBlocks, source, e -> e.excludeSourceFromDamage = excludeSourceFromDamage);
}
// Paper end
@Override
public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks, Entity source) {
Preconditions.checkArgument(loc != null, "Location is null");
Preconditions.checkArgument(this.equals(loc.getWorld()), "Location not in world");
return this.createExplosion(loc.getX(), loc.getY(), loc.getZ(), power, setFire, breakBlocks, source);
}
@Override
public @NotNull Environment getEnvironment() {
return this.environment;
}
@Override
public @Nullable ChunkGenerator getGenerator() {
return this.generator;
}
@Override
public @Nullable BiomeProvider getBiomeProvider() {
return this.biomeProvider;
}
@Override
public List<BlockPopulator> getPopulators() {
return this.populators;
}
@NotNull
@Override
public <T extends LivingEntity> T spawn(@NotNull Location location, @NotNull Class<T> clazz, @NotNull SpawnReason spawnReason, boolean randomizeData, @Nullable Consumer<? super T> function) throws IllegalArgumentException {
Preconditions.checkArgument(spawnReason != null, "Spawn reason cannot be null");
return this.spawn(location, clazz, function, spawnReason, randomizeData);
}
@Override
public int getHighestBlockYAt(int x, int z, org.bukkit.HeightMap heightMap) {
warnUnsafeChunk("getting a faraway chunk", x >> 4, z >> 4); // Paper
// Transient load for this tick
return this.world.getChunk(x >> 4, z >> 4).getHeight(CraftHeightMap.toNMS(heightMap), x, z);
}
@Override
public void setBiome(int x, int z, Biome bio) {
for (int y = this.getMinHeight(); y < this.getMaxHeight(); y++) {
this.setBiome(x, y, z, bio);
}
}
@Override
public void setBiome(int x, int y, int z, Holder<net.minecraft.world.level.biome.Biome> bb) {
BlockPos pos = new BlockPos(x, 0, z);
if (this.world.hasChunkAt(pos)) {
net.minecraft.world.level.chunk.LevelChunk chunk = this.world.getChunkAt(pos);
chunk.setBiome(x >> 2, y >> 2, z >> 2, bb);
chunk.markUnsaved(); // SPIGOT-2890
}
}
@Override
public double getTemperature(int x, int y, int z) {
BlockPos pos = new BlockPos(x, y, z);
return this.world.getNoiseBiome(x >> 2, y >> 2, z >> 2).value().getTemperature(pos, this.world.getSeaLevel());
}
@Override
public double getHumidity(int x, int y, int z) {
return this.world.getNoiseBiome(x >> 2, y >> 2, z >> 2).value().climateSettings.downfall();
}
@Override
@SuppressWarnings("unchecked")
@Deprecated
public <T extends Entity> Collection<T> getEntitiesByClass(Class<T>... classes) {
return (Collection<T>) this.getEntitiesByClasses(classes);
}
@Override
public Iterable<net.minecraft.world.entity.Entity> getNMSEntities() {
return this.getHandle().getEntities().getAll();
}
@Override
public void addEntityToWorld(net.minecraft.world.entity.Entity entity, SpawnReason reason) {
this.getHandle().addFreshEntity(entity, reason);
}
@Override
public void addEntityWithPassengers(net.minecraft.world.entity.Entity entity, SpawnReason reason) {
this.getHandle().tryAddFreshEntityWithPassengers(entity, reason);
}
@Override
public Collection<Entity> getNearbyEntities(Location location, double x, double y, double z, Predicate<? super Entity> filter) {
Preconditions.checkArgument(location != null, "Location cannot be null");
Preconditions.checkArgument(this.equals(location.getWorld()), "Location cannot be in a different world");
BoundingBox aabb = BoundingBox.of(location, x, y, z);
return this.getNearbyEntities(aabb, filter);
}
@Override
public Collection<Entity> getNearbyEntities(BoundingBox boundingBox, Predicate<? super Entity> filter) {
org.spigotmc.AsyncCatcher.catchOp("getNearbyEntities"); // Spigot
Preconditions.checkArgument(boundingBox != null, "BoundingBox cannot be null");
AABB bb = new AABB(boundingBox.getMinX(), boundingBox.getMinY(), boundingBox.getMinZ(), boundingBox.getMaxX(), boundingBox.getMaxY(), boundingBox.getMaxZ());
List<net.minecraft.world.entity.Entity> entityList = this.getHandle().getEntities((net.minecraft.world.entity.Entity) null, bb, Predicates.alwaysTrue());
List<Entity> bukkitEntityList = new ArrayList<org.bukkit.entity.Entity>(entityList.size());
for (net.minecraft.world.entity.Entity entity : entityList) {
Entity bukkitEntity = entity.getBukkitEntity();
if (filter == null || filter.test(bukkitEntity)) {
bukkitEntityList.add(bukkitEntity);
}
}
return bukkitEntityList;
}
@Override
public RayTraceResult rayTraceEntities(io.papermc.paper.math.Position start, Vector direction, double maxDistance, double raySize, Predicate<? super Entity> filter) {
Preconditions.checkArgument(start != null, "Location start cannot be null");
Preconditions.checkArgument(!(start instanceof Location location) || this.equals(location.getWorld()), "Location start cannot be in a different world");
Preconditions.checkArgument(start.isFinite(), "Location start is not finite");
Preconditions.checkArgument(direction != null, "Vector direction cannot be null");
direction.checkFinite();
Preconditions.checkArgument(direction.lengthSquared() > 0, "Direction's magnitude (%s) need to be greater than 0", direction.lengthSquared());
if (maxDistance < 0.0D) {
return null;
}
Vector startPos = start.toVector();
Vector dir = direction.clone().normalize().multiply(maxDistance);