Paper/patches/server/0759-Optimise-general-POI-access.patch

993 lines
52 KiB
Diff
Raw Normal View History

Merge tuinity (#6413) This PR contains all of Tuinity's patches. Very notable ones are: - Highly optimised collisions - Optimised entity lookups by bounding box (Mojang made regressions in 1.17, this brings it back to 1.16) - Starlight https://github.com/PaperMC/Starlight - Rewritten dataconverter system https://github.com/PaperMC/DataConverter - Random block ticking optimisation (wrongly dropped from Paper 1.17) - Chunk ticking optimisations - Anything else I've forgotten in the 60 or so patches If you are a previous Tuinity user, your config will not migrate. You must do it yourself. The config options have simply been moved into paper.yml, so it will be an easy migration. However, please note that the chunk loading options in tuinity.yml are NOT compatible with the options in paper.yml. * Port tuinity, initial patchset * Update gradle to 7.2 jmp said it fixes rebuildpatches not working for me. it fucking better * Completely clean apply * Remove tuinity config, add per player api patch * Remove paper reobf mappings patch * Properly update gradlew * Force clean rebuild * Mark fixups Comments and ATs still need to be done * grep -r "Tuinity" * Fixup * Ensure gameprofile lastaccess is written only under the state lock * update URL for dataconverter * Only clean rebuild tuinity patches might fix merge conflicts * Use UTF-8 for gradlew * Clean rb patches again * Convert block ids used as item ids Neither the converters of pre 1.13 nor DFU handled these cases, as by the time they were written the game at the time didn't consider these ids valid - they would be air. Because of this, some worlds have logspam since only DataConverter (not DFU or legacy converters) will warn when an invalid id has been seen. While quite a few do need to now be considered as air, quite a lot do not. So it makes sense to add conversion for these items, instead of simply suppressing or ignoring the logs. I've now added id -> string conversion for all block ids that could be used as items that existed in the game before 1.7.10 (I have no interest in tracking down the exact version block ids stopped working) that were on https://minecraft-ids.grahamedgecombe.com/ Items that did not directly convert to new items will be instead converted to air: stems, wheat crops, piston head, tripwire wire block * Fix LightPopulated parsing in V1466 The DFU code was checking if the number existed, not if it didn't exist. I misread the original code. * Always parse protochunk light sources unless it is marked as non-lit Chunks not marked as lit will always go through the light engine, so they should always have their block sources parsed. * Update custom names to JSON for players Missed this fix from CB, as it was inside the DataFixers class. I decided to double check all of the CB changes again: DataFixers.java was the only area I missed, as I had inspected all datafixer diffs and implemented them all into DataConverter. I also checked Bootstrap.java again, and re-evaluated their changes. I had previously done this, but determined that they were all bad. The changes to make standing_sign block map to oak_sign block in V1450 is bad, because that's not the item id V1450 accepts. Only in 1.14 did oak_sign even exist, and as expected there is a converter to rename all existing sign items/blocks. The fix to register the portal block under id 1440 is useless, as the flattenning logic will default to the lowest registered id - which is the exact blockstate that CB registers into 1440. So it just doesn't do anything. The extra item ids in the id -> string converter are already added, but I found this from EMC originally. The change for the spawn egg id 23 -> Arrow is just wrong, that id DOES correspond to TippedArrow, NOT Arrow. As expected, the spawn egg already has a dedicated mapping for Arrow, which is id 10 - which was Arrow's entity id. I also ported a fix for the cooked_fished id update. This doesn't really matter since there is already a dataconverter to fix this, but the game didn't accept cooked_fished at the time. So I see no harm. * Review all converters and walkers - Refactor V99 to have helper methods for defining entity/tile entity types - Automatically namespace all ids that should be namespaced. While vanilla never saved non-namespaced data for things that are namespaced, plugins/users might have. - Synchronised the identity ensure map in HelperBlockFlatteningV1450 - Code style consistency - Add missing log warning in V102 for ITEM_NAME type conversion - Use getBoolean instead of getByte - Use ConverterAbstractEntityRename for V143 TippedArrow -> Arrow rename, as it will affect ENTITY_NAME type - Always set isVillager to false in V502 for Zombie - Register V808's converter under subversion 1 like DFU - Register a breakpoint for V1.17.1. In the future, all final versions of major releases will have a breakpoint so that the work required to determine if a converter needs a breakpoint is minimal - Validate that a dataconverter is only registered for a version that is registered - ConverterFlattenTileEntity is actually ConverterFlattenEntity It even registered the converters under TILE_ENTITY, instead of ENTITY. - Fix id comparison in V1492 STRUCTURE_FEATURE renamer - Use ConverterAbstractStatsRename for V1510 stats renamer At the time I had written that class, the abstract renamer didn't exist. - Ensure OwnerUUID is at least set to empty string in V1904 if the ocelot is converted to a cat (this is likely so that it retains a collar) - Use generic read/write for Records in V1946 Records is actually a list, not a map. So reading map was invalid. * Always set light to zero when propagating decrease This fixes an almost infinite loop where light values would be spam queued on a very small subset on blocks. This also likely fixes the memory issues people were seeing. * re-organize patches * Apply and fix conflicts * Revert some patches getChunkAt retains chunks so that plugins don't spam loads revert mc-4 fix will remain unless issues pop up * Shuffle iterated chunks if per player is not enabled Can help with some mob spawning stacking up at locations * Make per player default, migrate all configs * Adjust comments in fixups * Rework config for player chunk loader Old config is not compatible. Move all configs to be under `settings` in paper.yml The player chunk loader has been modified to less aggressively load chunks, but to send chunks at higher rates compared to tuinity. There are new config entries to tune this behavior. * Add back old constructor to CompressionEncoder/Decoder (fixes Tuinity #358) * Raise chunk loading default limits * Reduce worldgen thread workers for lower core count cpus * Raise limits for chunk loading config Also place it under `chunk-loading` * Disable max chunk send rate by default * Fix conflicts and rebuild patches * Drop default send rate again Appears to be still causing problems for no known reason * Raise chunk send limits to 100 per player While a low limit fixes ping issues for some people, most people do not suffer from this issue and thus should not suffer from an extremely slow load-in rate. * Rebase part 1 Autosquash the fixups * Move not implemented up * Fixup mc-dev fixes Missed this one * Rebase per player viewdistance api into the original api patch * Remove old light engine patch part 1 The prioritisation must be kept from it, so that part has been rebased into the priority patch. Part 2 will deal with rebasing all of the patches _after_ * Rebase remaining patches for old light patch removal * Remove other mid tick patch * Remove Optimize-PlayerChunkMap-memory-use-for-visibleChunks.patch Replaced by `Do not copy visible chunks` * Revert AT for Vec3i setX/Y/Z The class is immutable. set should not be exposed * Remove old IntegerUtil class * Replace old CraftChunk#getEntities patch * Remove import for SWMRNibbleArray in ChunkAccess * Finished merge checklist * Remove ensureTickThread impl in urgency patch Co-authored-by: Spottedleaf <Spottedleaf@users.noreply.github.com> Co-authored-by: Jason Penilla <11360596+jpenilla@users.noreply.github.com>
2021-08-31 11:02:11 +00:00
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Spottedleaf <Spottedleaf@users.noreply.github.com>
Date: Sun, 31 Jan 2021 02:29:24 -0800
Subject: [PATCH] Optimise general POI access
There are a couple of problems with mojang's POI code.
Firstly, it's all streams. Unsurprisingly, stacking
streams on top of each other is horrible for performance
and ultimately took up half of a villager's tick!
Secondly, sometime's the search radius is large and there are
a significant number of poi entries per chunk section. Even
removing streams at this point doesn't help much. The only solution
is to start at the search point and iterate outwards. This
type of approach shows massive gains for portals, simply because
we can avoid sync loading a large area of chunks. I also tested
a massive farm I found in JellySquid's discord, which showed
to benefit significantly simply because the farm had so many
portal blocks that searching through them all was very slow.
Great care has been taken so that behavior remains identical to
vanilla, however I cannot account for oddball Stream API
implementations, if they even exist (streams can technically
be loose with iteration order in a sorted stream given its
source stream is not tagged with ordered, and mojang does not
tag the source stream as ordered). However in my testing on openjdk
there showed no difference, as expected.
This patch also specifically optimises other areas of code to
use PoiAccess. For example, some villager AI and portaling code
had to be specifically modified.
diff --git a/src/main/java/io/papermc/paper/util/PoiAccess.java b/src/main/java/io/papermc/paper/util/PoiAccess.java
new file mode 100644
index 0000000000000000000000000000000000000000..0a88c60161b04a733151c15046358f4b3b8b3280
--- /dev/null
+++ b/src/main/java/io/papermc/paper/util/PoiAccess.java
@@ -0,0 +1,748 @@
+package io.papermc.paper.util;
+
+import it.unimi.dsi.fastutil.doubles.Double2ObjectMap;
+import it.unimi.dsi.fastutil.doubles.Double2ObjectRBTreeMap;
+import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue;
+import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
+import net.minecraft.core.BlockPos;
+import net.minecraft.util.Mth;
+import net.minecraft.world.entity.ai.village.poi.PoiManager;
+import net.minecraft.world.entity.ai.village.poi.PoiRecord;
+import net.minecraft.world.entity.ai.village.poi.PoiSection;
+import net.minecraft.world.entity.ai.village.poi.PoiType;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Predicate;
+
+/**
+ * Provides optimised access to POI data. All returned values will be identical to vanilla.
+ */
+public final class PoiAccess {
+
+ protected static double clamp(final double val, final double min, final double max) {
+ return (val < min ? min : (val > max ? max : val));
+ }
+
+ protected static double getSmallestDistanceSquared(final double boxMinX, final double boxMinY, final double boxMinZ,
+ final double boxMaxX, final double boxMaxY, final double boxMaxZ,
+
+ final double circleX, final double circleY, final double circleZ) {
+ // is the circle center inside the box?
+ if (circleX >= boxMinX && circleX <= boxMaxX && circleY >= boxMinY && circleY <= boxMaxY && circleZ >= boxMinZ && circleZ <= boxMaxZ) {
+ return 0.0;
+ }
+
+ final double boxWidthX = (boxMaxX - boxMinX) / 2.0;
+ final double boxWidthY = (boxMaxY - boxMinY) / 2.0;
+ final double boxWidthZ = (boxMaxZ - boxMinZ) / 2.0;
+
+ final double boxCenterX = (boxMinX + boxMaxX) / 2.0;
+ final double boxCenterY = (boxMinY + boxMaxY) / 2.0;
+ final double boxCenterZ = (boxMinZ + boxMaxZ) / 2.0;
+
+ double centerDiffX = circleX - boxCenterX;
+ double centerDiffY = circleY - boxCenterY;
+ double centerDiffZ = circleZ - boxCenterZ;
+
+ centerDiffX = circleX - (clamp(centerDiffX, -boxWidthX, boxWidthX) + boxCenterX);
+ centerDiffY = circleY - (clamp(centerDiffY, -boxWidthY, boxWidthY) + boxCenterY);
+ centerDiffZ = circleZ - (clamp(centerDiffZ, -boxWidthZ, boxWidthZ) + boxCenterZ);
+
+ return (centerDiffX * centerDiffX) + (centerDiffY * centerDiffY) + (centerDiffZ * centerDiffZ);
+ }
+
+
+ // key is:
+ // upper 32 bits:
+ // upper 16 bits: max y section
+ // lower 16 bits: min y section
+ // lower 32 bits:
+ // upper 16 bits: section
+ // lower 16 bits: radius
+ protected static long getKey(final int minSection, final int maxSection, final int section, final int radius) {
+ return (
+ (maxSection & 0xFFFFL) << (64 - 16)
+ | (minSection & 0xFFFFL) << (64 - 32)
+ | (section & 0xFFFFL) << (64 - 48)
+ | (radius & 0xFFFFL) << (64 - 64)
+ );
+ }
+
+ // only includes x/z axis
+ // finds the closest poi data by distance.
+ public static BlockPos findClosestPoiDataPosition(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ // position predicate must not modify chunk POI
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final double maxDistance,
+ final PoiManager.Occupancy occupancy,
+ final boolean load) {
+ final PoiRecord ret = findClosestPoiDataRecord(
+ poiStorage, villagePlaceType, positionPredicate, sourcePosition, range, maxDistance, occupancy, load
+ );
+
+ return ret == null ? null : ret.getPos();
+ }
+
+ // only includes x/z axis
+ // finds the closest poi data by distance. if multiple match the same distance, then they all are returned.
+ public static void findClosestPoiDataPositions(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ // position predicate must not modify chunk POI
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final double maxDistance,
+ final PoiManager.Occupancy occupancy,
+ final boolean load,
+ final Set<BlockPos> ret) {
+ final Set<BlockPos> positions = new HashSet<>();
+ // pos predicate is last thing that runs before adding to ret.
+ final Predicate<BlockPos> newPredicate = (final BlockPos pos) -> {
+ if (positionPredicate != null && !positionPredicate.test(pos)) {
+ return false;
+ }
+ return positions.add(pos.immutable());
+ };
+
+ final List<PoiRecord> toConvert = new ArrayList<>();
+ findClosestPoiDataRecords(
+ poiStorage, villagePlaceType, newPredicate, sourcePosition, range, maxDistance, occupancy, load, toConvert
+ );
+
+ for (final PoiRecord record : toConvert) {
+ ret.add(record.getPos());
+ }
+ }
+
+ // only includes x/z axis
+ // finds the closest poi data by distance.
+ public static PoiRecord findClosestPoiDataRecord(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ // position predicate must not modify chunk POI
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final double maxDistance,
+ final PoiManager.Occupancy occupancy,
+ final boolean load) {
+ final List<PoiRecord> ret = new ArrayList<>();
+ findClosestPoiDataRecords(
+ poiStorage, villagePlaceType, positionPredicate, sourcePosition, range, maxDistance, occupancy, load, ret
+ );
+ return ret.isEmpty() ? null : ret.get(0);
+ }
+
+ // only includes x/z axis
+ // finds the closest poi data by distance. if multiple match the same distance, then they all are returned.
+ public static void findClosestPoiDataRecords(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ // position predicate must not modify chunk POI
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final double maxDistance,
+ final PoiManager.Occupancy occupancy,
+ final boolean load,
+ final List<PoiRecord> ret) {
+ final Predicate<? super PoiRecord> occupancyFilter = occupancy.getTest();
+
+ final List<PoiRecord> closestRecords = new ArrayList<>();
+ double closestDistanceSquared = maxDistance * maxDistance;
+
+ final int lowerX = Mth.floor(sourcePosition.getX() - range) >> 4;
+ final int lowerY = WorldUtil.getMinSection(poiStorage.world);
+ final int lowerZ = Mth.floor(sourcePosition.getZ() - range) >> 4;
+ final int upperX = Mth.floor(sourcePosition.getX() + range) >> 4;
+ final int upperY = WorldUtil.getMaxSection(poiStorage.world);
+ final int upperZ = Mth.floor(sourcePosition.getZ() + range) >> 4;
+
+ final int centerX = sourcePosition.getX() >> 4;
+ final int centerY = Mth.clamp(sourcePosition.getY() >> 4, lowerY, upperY);
+ final int centerZ = sourcePosition.getZ() >> 4;
+
+ final LongArrayFIFOQueue queue = new LongArrayFIFOQueue();
+ queue.enqueue(CoordinateUtils.getChunkSectionKey(centerX, centerY, centerZ));
+ final LongOpenHashSet seen = new LongOpenHashSet();
+
+ while (!queue.isEmpty()) {
+ final long key = queue.dequeueLong();
+ final int sectionX = CoordinateUtils.getChunkSectionX(key);
+ final int sectionY = CoordinateUtils.getChunkSectionY(key);
+ final int sectionZ = CoordinateUtils.getChunkSectionZ(key);
+
+ if (sectionX < lowerX || sectionX > upperX || sectionY < lowerY || sectionY > upperY || sectionZ < lowerZ || sectionZ > upperZ) {
+ // out of bound chunk
+ continue;
+ }
+
+ final double sectionDistanceSquared = getSmallestDistanceSquared(
+ (sectionX << 4) + 0.5,
+ (sectionY << 4) + 0.5,
+ (sectionZ << 4) + 0.5,
+ (sectionX << 4) + 15.5,
+ (sectionY << 4) + 15.5,
+ (sectionZ << 4) + 15.5,
+ (double)sourcePosition.getX(), (double)sourcePosition.getY(), (double)sourcePosition.getZ()
+ );
+ if (sectionDistanceSquared > closestDistanceSquared) {
+ continue;
+ }
+
+ // queue all neighbours
+ for (int dz = -1; dz <= 1; ++dz) {
+ for (int dx = -1; dx <= 1; ++dx) {
+ for (int dy = -1; dy <= 1; ++dy) {
+ // -1 and 1 have the 1st bit set. so just add up the first bits, and it will tell us how many
+ // values are set. we only care about cardinal neighbours, so, we only care if one value is set
+ if ((dx & 1) + (dy & 1) + (dz & 1) != 1) {
+ continue;
+ }
+
+ final int neighbourX = sectionX + dx;
+ final int neighbourY = sectionY + dy;
+ final int neighbourZ = sectionZ + dz;
+
+ final long neighbourKey = CoordinateUtils.getChunkSectionKey(neighbourX, neighbourY, neighbourZ);
+ if (seen.add(neighbourKey)) {
+ queue.enqueue(neighbourKey);
+ }
+ }
+ }
+ }
+
+ final Optional<PoiSection> poiSectionOptional = load ? poiStorage.getOrLoad(key) : poiStorage.get(key);
+
+ if (poiSectionOptional == null || !poiSectionOptional.isPresent()) {
+ continue;
+ }
+
+ final PoiSection poiSection = poiSectionOptional.orElse(null);
+
+ final Map<PoiType, Set<PoiRecord>> sectionData = poiSection.getData();
+ if (sectionData.isEmpty()) {
+ continue;
+ }
+
+ // now we search the section data
+ for (final Map.Entry<PoiType, Set<PoiRecord>> entry : sectionData.entrySet()) {
+ if (!villagePlaceType.test(entry.getKey())) {
+ // filter out by poi type
+ continue;
+ }
+
+ // now we can look at the poi data
+ for (final PoiRecord poiData : entry.getValue()) {
+ if (!occupancyFilter.test(poiData)) {
+ // filter by occupancy
+ continue;
+ }
+
+ final BlockPos poiPosition = poiData.getPos();
+
+ if (Math.abs(poiPosition.getX() - sourcePosition.getX()) > range
+ || Math.abs(poiPosition.getZ() - sourcePosition.getZ()) > range) {
+ // out of range for square radius
+ continue;
+ }
+
+ // it's important that it's poiPosition.distSqr(source) : the value actually is different IF the values are swapped!
+ final double dataRange = poiPosition.distSqr(sourcePosition);
+
+ if (dataRange > closestDistanceSquared) {
+ // out of range for distance check
+ continue;
+ }
+
+ if (positionPredicate != null && !positionPredicate.test(poiPosition)) {
+ // filter by position
+ continue;
+ }
+
+ if (dataRange < closestDistanceSquared) {
+ closestRecords.clear();
+ closestDistanceSquared = dataRange;
+ }
+ closestRecords.add(poiData);
+ }
+ }
+ }
+
+ // uh oh! we might have multiple records that match the distance sorting!
+ // we need to re-order our results by the way vanilla would have iterated over them.
+ closestRecords.sort((record1, record2) -> {
+ // vanilla iterates the same way we do for data inside sections, so we know the ordering inside a section
+ // is fine and should be preserved (this sort is stable so we're good there)
+ // but they iterate sections by x then by z (like the following)
+ // for (int x = -dx; x <= dx; ++x)
+ // for (int z = -dz; z <= dz; ++z)
+ // ....
+ // so we need to reorder such that records with lower chunk z, then lower chunk x come first
+ final BlockPos pos1 = record1.getPos();
+ final BlockPos pos2 = record2.getPos();
+
+ final int cx1 = pos1.getX() >> 4;
+ final int cz1 = pos1.getZ() >> 4;
+
+ final int cx2 = pos2.getX() >> 4;
+ final int cz2 = pos2.getZ() >> 4;
+
+ if (cz2 != cz1) {
+ // want smaller z
+ return Integer.compare(cz1, cz2);
+ }
+
+ if (cx2 != cx1) {
+ // want smaller x
+ return Integer.compare(cx1, cx2);
+ }
+
+ // same chunk
+ // once vanilla has the chunk, it will iterate from all of the chunk sections starting from smaller y
+ // so now we just compare section y, wanting smaller y
+
+ return Integer.compare(pos1.getY() >> 4, pos2.getY() >> 4);
+ });
+
+ // now we match perfectly what vanilla would have outputted, without having to search the whole radius (hopefully).
+ ret.addAll(closestRecords);
+ }
+
+ // finds the closest poi entry pos.
+ public static BlockPos findNearestPoiPosition(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ // position predicate must not modify chunk POI
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final double maxDistance,
+ final PoiManager.Occupancy occupancy,
+ final boolean load) {
+ final PoiRecord ret = findNearestPoiRecord(
+ poiStorage, villagePlaceType, positionPredicate, sourcePosition, range, maxDistance, occupancy, load
+ );
+ return ret == null ? null : ret.getPos();
+ }
+
+ // finds the closest `max` poi entry positions.
+ public static void findNearestPoiPositions(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ // position predicate must not modify chunk POI
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final double maxDistance,
+ final PoiManager.Occupancy occupancy,
+ final boolean load,
+ final int max,
+ final List<BlockPos> ret) {
+ final Set<BlockPos> positions = new HashSet<>();
+ // pos predicate is last thing that runs before adding to ret.
+ final Predicate<BlockPos> newPredicate = (final BlockPos pos) -> {
+ if (positionPredicate != null && !positionPredicate.test(pos)) {
+ return false;
+ }
+ return positions.add(pos.immutable());
+ };
+
+ final List<PoiRecord> toConvert = new ArrayList<>();
+ findNearestPoiRecords(
+ poiStorage, villagePlaceType, newPredicate, sourcePosition, range, maxDistance, occupancy, load, max, toConvert
+ );
+
+ for (final PoiRecord record : toConvert) {
+ ret.add(record.getPos());
+ }
+ }
+
+ // finds the closest poi entry.
+ public static PoiRecord findNearestPoiRecord(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ // position predicate must not modify chunk POI
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final double maxDistance,
+ final PoiManager.Occupancy occupancy,
+ final boolean load) {
+ final List<PoiRecord> ret = new ArrayList<>();
+ findNearestPoiRecords(
+ poiStorage, villagePlaceType, positionPredicate, sourcePosition, range, maxDistance, occupancy, load,
+ 1, ret
+ );
+ return ret.isEmpty() ? null : ret.get(0);
+ }
+
+ // finds the closest `max` poi entries.
+ public static void findNearestPoiRecords(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ // position predicate must not modify chunk POI
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final double maxDistance,
+ final PoiManager.Occupancy occupancy,
+ final boolean load,
+ final int max,
+ final List<PoiRecord> ret) {
+ final Predicate<? super PoiRecord> occupancyFilter = occupancy.getTest();
+
+ final double maxDistanceSquared = maxDistance * maxDistance;
+ final Double2ObjectRBTreeMap<List<PoiRecord>> closestRecords = new Double2ObjectRBTreeMap<>();
+ int totalRecords = 0;
+ double furthestDistanceSquared = maxDistanceSquared;
+
+ final int lowerX = Mth.floor(sourcePosition.getX() - range) >> 4;
+ final int lowerY = WorldUtil.getMinSection(poiStorage.world);
+ final int lowerZ = Mth.floor(sourcePosition.getZ() - range) >> 4;
+ final int upperX = Mth.floor(sourcePosition.getX() + range) >> 4;
+ final int upperY = WorldUtil.getMaxSection(poiStorage.world);
+ final int upperZ = Mth.floor(sourcePosition.getZ() + range) >> 4;
+
+ final int centerX = sourcePosition.getX() >> 4;
+ final int centerY = Mth.clamp(sourcePosition.getY() >> 4, lowerY, upperY);
+ final int centerZ = sourcePosition.getZ() >> 4;
+
+ final LongArrayFIFOQueue queue = new LongArrayFIFOQueue();
+ queue.enqueue(CoordinateUtils.getChunkSectionKey(centerX, centerY, centerZ));
+ final LongOpenHashSet seen = new LongOpenHashSet();
+
+ while (!queue.isEmpty()) {
+ final long key = queue.dequeueLong();
+ final int sectionX = CoordinateUtils.getChunkSectionX(key);
+ final int sectionY = CoordinateUtils.getChunkSectionY(key);
+ final int sectionZ = CoordinateUtils.getChunkSectionZ(key);
+
+ if (sectionX < lowerX || sectionX > upperX || sectionY < lowerY || sectionY > upperY || sectionZ < lowerZ || sectionZ > upperZ) {
+ // out of bound chunk
+ continue;
+ }
+
+ final double sectionDistanceSquared = getSmallestDistanceSquared(
+ (sectionX << 4) + 0.5,
+ (sectionY << 4) + 0.5,
+ (sectionZ << 4) + 0.5,
+ (sectionX << 4) + 15.5,
+ (sectionY << 4) + 15.5,
+ (sectionZ << 4) + 15.5,
+ (double) sourcePosition.getX(), (double) sourcePosition.getY(), (double) sourcePosition.getZ()
+ );
+
+ if (sectionDistanceSquared > (totalRecords >= max ? furthestDistanceSquared : maxDistanceSquared)) {
+ continue;
+ }
+
+ // queue all neighbours
+ for (int dz = -1; dz <= 1; ++dz) {
+ for (int dx = -1; dx <= 1; ++dx) {
+ for (int dy = -1; dy <= 1; ++dy) {
+ // -1 and 1 have the 1st bit set. so just add up the first bits, and it will tell us how many
+ // values are set. we only care about cardinal neighbours, so, we only care if one value is set
+ if ((dx & 1) + (dy & 1) + (dz & 1) != 1) {
+ continue;
+ }
+
+ final int neighbourX = sectionX + dx;
+ final int neighbourY = sectionY + dy;
+ final int neighbourZ = sectionZ + dz;
+
+ final long neighbourKey = CoordinateUtils.getChunkSectionKey(neighbourX, neighbourY, neighbourZ);
+ if (seen.add(neighbourKey)) {
+ queue.enqueue(neighbourKey);
+ }
+ }
+ }
+ }
+
+ final Optional<PoiSection> poiSectionOptional = load ? poiStorage.getOrLoad(key) : poiStorage.get(key);
+
+ if (poiSectionOptional == null || !poiSectionOptional.isPresent()) {
+ continue;
+ }
+
+ final PoiSection poiSection = poiSectionOptional.orElse(null);
+
+ final Map<PoiType, Set<PoiRecord>> sectionData = poiSection.getData();
+ if (sectionData.isEmpty()) {
+ continue;
+ }
+
+ // now we search the section data
+ for (final Map.Entry<PoiType, Set<PoiRecord>> entry : sectionData.entrySet()) {
+ if (!villagePlaceType.test(entry.getKey())) {
+ // filter out by poi type
+ continue;
+ }
+
+ // now we can look at the poi data
+ for (final PoiRecord poiData : entry.getValue()) {
+ if (!occupancyFilter.test(poiData)) {
+ // filter by occupancy
+ continue;
+ }
+
+ final BlockPos poiPosition = poiData.getPos();
+
+ if (Math.abs(poiPosition.getX() - sourcePosition.getX()) > range
+ || Math.abs(poiPosition.getZ() - sourcePosition.getZ()) > range) {
+ // out of range for square radius
+ continue;
+ }
+
+ // it's important that it's poiPosition.distSqr(source) : the value actually is different IF the values are swapped!
+ final double dataRange = poiPosition.distSqr(sourcePosition);
+
+ if (dataRange > maxDistanceSquared) {
+ // out of range for distance check
+ continue;
+ }
+
+ if (dataRange > furthestDistanceSquared && totalRecords >= max) {
+ // out of range for distance check
+ continue;
+ }
+
+ if (positionPredicate != null && !positionPredicate.test(poiPosition)) {
+ // filter by position
+ continue;
+ }
+
+ if (dataRange > furthestDistanceSquared) {
+ // we know totalRecords < max, so this entry is now our furthest
+ furthestDistanceSquared = dataRange;
+ }
+
+ closestRecords.computeIfAbsent(dataRange, (final double unused) -> {
+ return new ArrayList<>();
+ }).add(poiData);
+
+ if (++totalRecords >= max) {
+ if (closestRecords.size() >= 2) {
+ int entriesInClosest = 0;
+ final Iterator<Double2ObjectMap.Entry<List<PoiRecord>>> iterator = closestRecords.double2ObjectEntrySet().iterator();
+ double nextFurthestDistanceSquared = 0.0;
+
+ for (int i = 0, len = closestRecords.size() - 1; i < len; ++i) {
+ final Double2ObjectMap.Entry<List<PoiRecord>> recordEntry = iterator.next();
+ entriesInClosest += recordEntry.getValue().size();
+ nextFurthestDistanceSquared = recordEntry.getDoubleKey();
+ }
+
+ if (entriesInClosest >= max) {
+ // the last set of entries at range wont even be considered for sure... nuke em
+ final Double2ObjectMap.Entry<List<PoiRecord>> recordEntry = iterator.next();
+ totalRecords -= recordEntry.getValue().size();
+ iterator.remove();
+
+ furthestDistanceSquared = nextFurthestDistanceSquared;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ final List<PoiRecord> closestRecordsUnsorted = new ArrayList<>();
+
+ // we're done here, so now just flatten the map and sort it.
+
+ for (final List<PoiRecord> records : closestRecords.values()) {
+ closestRecordsUnsorted.addAll(records);
+ }
+
+ // uh oh! we might have multiple records that match the distance sorting!
+ // we need to re-order our results by the way vanilla would have iterated over them.
+ closestRecordsUnsorted.sort((record1, record2) -> {
+ // vanilla iterates the same way we do for data inside sections, so we know the ordering inside a section
+ // is fine and should be preserved (this sort is stable so we're good there)
+ // but they iterate sections by x then by z (like the following)
+ // for (int x = -dx; x <= dx; ++x)
+ // for (int z = -dz; z <= dz; ++z)
+ // ....
+ // so we need to reorder such that records with lower chunk z, then lower chunk x come first
+ final BlockPos pos1 = record1.getPos();
+ final BlockPos pos2 = record2.getPos();
+
+ final int cx1 = pos1.getX() >> 4;
+ final int cz1 = pos1.getZ() >> 4;
+
+ final int cx2 = pos2.getX() >> 4;
+ final int cz2 = pos2.getZ() >> 4;
+
+ if (cz2 != cz1) {
+ // want smaller z
+ return Integer.compare(cz1, cz2);
+ }
+
+ if (cx2 != cx1) {
+ // want smaller x
+ return Integer.compare(cx1, cx2);
+ }
+
+ // same chunk
+ // once vanilla has the chunk, it will iterate from all of the chunk sections starting from smaller y
+ // so now we just compare section y, wanting smaller section y
+
+ return Integer.compare(pos1.getY() >> 4, pos2.getY() >> 4);
+ });
+
+ // trim out any entries exceeding our maximum
+ for (int i = closestRecordsUnsorted.size() - 1; i >= max; --i) {
+ closestRecordsUnsorted.remove(i);
+ }
+
+ // now we match perfectly what vanilla would have outputted, without having to search the whole radius (hopefully).
+ ret.addAll(closestRecordsUnsorted);
+ }
+
+ public static BlockPos findAnyPoiPosition(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final PoiManager.Occupancy occupancy,
+ final boolean load) {
+ final PoiRecord ret = findAnyPoiRecord(
+ poiStorage, villagePlaceType, positionPredicate, sourcePosition, range, occupancy, load
+ );
+
+ return ret == null ? null : ret.getPos();
+ }
+
+ public static void findAnyPoiPositions(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final PoiManager.Occupancy occupancy,
+ final boolean load,
+ final int max,
+ final List<BlockPos> ret) {
+ final Set<BlockPos> positions = new HashSet<>();
+ // pos predicate is last thing that runs before adding to ret.
+ final Predicate<BlockPos> newPredicate = (final BlockPos pos) -> {
+ if (positionPredicate != null && !positionPredicate.test(pos)) {
+ return false;
+ }
+ return positions.add(pos.immutable());
+ };
+
+ final List<PoiRecord> toConvert = new ArrayList<>();
+ findAnyPoiRecords(
+ poiStorage, villagePlaceType, newPredicate, sourcePosition, range, occupancy, load, max, toConvert
+ );
+
+ for (final PoiRecord record : toConvert) {
+ ret.add(record.getPos());
+ }
+ }
+
+ public static PoiRecord findAnyPoiRecord(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final PoiManager.Occupancy occupancy,
+ final boolean load) {
+ final List<PoiRecord> ret = new ArrayList<>();
+ findAnyPoiRecords(poiStorage, villagePlaceType, positionPredicate, sourcePosition, range, occupancy, load, 1, ret);
+ return ret.isEmpty() ? null : ret.get(0);
+ }
+
+ public static void findAnyPoiRecords(final PoiManager poiStorage,
+ final Predicate<PoiType> villagePlaceType,
+ final Predicate<BlockPos> positionPredicate,
+ final BlockPos sourcePosition,
+ final int range, // distance on x y z axis
+ final PoiManager.Occupancy occupancy,
+ final boolean load,
+ final int max,
+ final List<PoiRecord> ret) {
+ // the biggest issue with the original mojang implementation is that they chain so many streams together
+ // the amount of streams chained just rolls performance, even if nothing is iterated over
+ final Predicate<? super PoiRecord> occupancyFilter = occupancy.getTest();
+ final double rangeSquared = range * range;
+
+ int added = 0;
+
+ // First up, we need to iterate the chunks
+ // all the values here are in chunk sections
+ final int lowerX = Mth.floor(sourcePosition.getX() - range) >> 4;
+ final int lowerY = Math.max(WorldUtil.getMinSection(poiStorage.world), Mth.floor(sourcePosition.getY() - range) >> 4);
+ final int lowerZ = Mth.floor(sourcePosition.getZ() - range) >> 4;
+ final int upperX = Mth.floor(sourcePosition.getX() + range) >> 4;
+ final int upperY = Math.min(WorldUtil.getMaxSection(poiStorage.world), Mth.floor(sourcePosition.getY() + range) >> 4);
+ final int upperZ = Mth.floor(sourcePosition.getZ() + range) >> 4;
+
+ // Vanilla iterates by x until max is reached then increases z
+ // vanilla also searches by increasing Y section value
+ for (int currZ = lowerZ; currZ <= upperZ; ++currZ) {
+ for (int currX = lowerX; currX <= upperX; ++currX) {
+ for (int currY = lowerY; currY <= upperY; ++currY) { // vanilla searches the entire chunk because they're actually stupid. just search the sections we need
+ final Optional<PoiSection> poiSectionOptional = load ? poiStorage.getOrLoad(CoordinateUtils.getChunkSectionKey(currX, currY, currZ)) :
+ poiStorage.get(CoordinateUtils.getChunkSectionKey(currX, currY, currZ));
+ final PoiSection poiSection = poiSectionOptional == null ? null : poiSectionOptional.orElse(null);
+ if (poiSection == null) {
+ continue;
+ }
+
+ final Map<PoiType, Set<PoiRecord>> sectionData = poiSection.getData();
+ if (sectionData.isEmpty()) {
+ continue;
+ }
+
+ // now we search the section data
+ for (final Map.Entry<PoiType, Set<PoiRecord>> entry : sectionData.entrySet()) {
+ if (!villagePlaceType.test(entry.getKey())) {
+ // filter out by poi type
+ continue;
+ }
+
+ // now we can look at the poi data
+ for (final PoiRecord poiData : entry.getValue()) {
+ if (!occupancyFilter.test(poiData)) {
+ // filter by occupancy
+ continue;
+ }
+
+ final BlockPos poiPosition = poiData.getPos();
+
+ if (Math.abs(poiPosition.getX() - sourcePosition.getX()) > range
+ || Math.abs(poiPosition.getZ() - sourcePosition.getZ()) > range) {
+ // out of range for square radius
+ continue;
+ }
+
+ if (poiPosition.distSqr(sourcePosition) > rangeSquared) {
+ // out of range for distance check
+ continue;
+ }
+
+ if (positionPredicate != null && !positionPredicate.test(poiPosition)) {
+ // filter by position
+ continue;
+ }
+
+ // found one!
+ ret.add(poiData);
+ if (++added >= max) {
+ return;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private PoiAccess() {
+ throw new RuntimeException();
+ }
+}
diff --git a/src/main/java/net/minecraft/world/entity/ai/behavior/AcquirePoi.java b/src/main/java/net/minecraft/world/entity/ai/behavior/AcquirePoi.java
index 84a0ee595bebcc1947c602c4c06e7437706ce37c..afbb2acd27416c801af3d718850b82a170734cd3 100644
--- a/src/main/java/net/minecraft/world/entity/ai/behavior/AcquirePoi.java
+++ b/src/main/java/net/minecraft/world/entity/ai/behavior/AcquirePoi.java
@@ -83,7 +83,11 @@ public class AcquirePoi extends Behavior<PathfinderMob> {
return true;
}
};
- Set<BlockPos> set = poiManager.findAllClosestFirst(this.poiType.getPredicate(), predicate, entity.blockPosition(), 48, PoiManager.Occupancy.HAS_SPACE).limit(5L).collect(Collectors.toSet());
+ // Paper start - optimise POI access
+ java.util.List<BlockPos> poiposes = new java.util.ArrayList<>();
+ io.papermc.paper.util.PoiAccess.findNearestPoiPositions(poiManager, this.poiType.getPredicate(), predicate, entity.blockPosition(), 48, 48*48, PoiManager.Occupancy.HAS_SPACE, false, 5, poiposes);
+ Set<BlockPos> set = new java.util.HashSet<>(poiposes);
+ // Paper end - optimise POI access
Path path = entity.getNavigation().createPath(set, this.poiType.getValidRange());
if (path != null && path.canReach()) {
BlockPos blockPos = path.getTarget();
diff --git a/src/main/java/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java b/src/main/java/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java
index e41b2fa1db6fb77a26cdb498904021b430e35be0..488d1e24b3e8f0fd8dc973d450215e4216720db3 100644
--- a/src/main/java/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java
+++ b/src/main/java/net/minecraft/world/entity/ai/sensing/NearestBedSensor.java
@@ -49,8 +49,12 @@ public class NearestBedSensor extends Sensor<Mob> {
return true;
}
};
- Stream<BlockPos> stream = poiManager.findAll(PoiType.HOME.getPredicate(), predicate, entity.blockPosition(), 48, PoiManager.Occupancy.ANY);
- Path path = entity.getNavigation().createPath(stream, PoiType.HOME.getValidRange());
+ // Paper start - optimise POI access
+ java.util.List<BlockPos> poiposes = new java.util.ArrayList<>();
+ // don't ask me why it's unbounded. ask mojang.
+ io.papermc.paper.util.PoiAccess.findAnyPoiPositions(poiManager, PoiType.HOME.getPredicate(), predicate, entity.blockPosition(), 48, PoiManager.Occupancy.ANY, false, Integer.MAX_VALUE, poiposes);
+ Path path = entity.getNavigation().createPath(new java.util.HashSet<>(poiposes), PoiType.HOME.getValidRange());
+ // Paper end - optimise POI access
if (path != null && path.canReach()) {
BlockPos blockPos = path.getTarget();
Optional<PoiType> optional = poiManager.getType(blockPos);
diff --git a/src/main/java/net/minecraft/world/entity/ai/village/poi/PoiManager.java b/src/main/java/net/minecraft/world/entity/ai/village/poi/PoiManager.java
index 7b1d2748328ffc1447bcacd1316f2c6fdbaf92b0..2b79ace854461b216dc4970d1cc4a3953a51dd50 100644
--- a/src/main/java/net/minecraft/world/entity/ai/village/poi/PoiManager.java
+++ b/src/main/java/net/minecraft/world/entity/ai/village/poi/PoiManager.java
@@ -37,7 +37,7 @@ public class PoiManager extends SectionStorage<PoiSection> {
public static final int VILLAGE_SECTION_SIZE = 1;
private final PoiManager.DistanceTracker distanceTracker;
private final LongSet loadedChunks = new LongOpenHashSet();
- private final net.minecraft.server.level.ServerLevel world; // Paper
+ public final net.minecraft.server.level.ServerLevel world; // Paper // Paper public
public PoiManager(File directory, DataFixer dataFixer, boolean dsync, LevelHeightAccessor world) {
super(directory, PoiSection::codec, PoiSection::new, dataFixer, DataFixTypes.POI_CHUNK, dsync, world);
@@ -100,36 +100,55 @@ public class PoiManager extends SectionStorage<PoiSection> {
}
public Optional<BlockPos> find(Predicate<PoiType> typePredicate, Predicate<BlockPos> posPredicate, BlockPos pos, int radius, PoiManager.Occupancy occupationStatus) {
- return this.findAll(typePredicate, posPredicate, pos, radius, occupationStatus).findFirst();
+ // Paper start - re-route to faster logic
+ BlockPos ret = io.papermc.paper.util.PoiAccess.findAnyPoiPosition(this, typePredicate, posPredicate, pos, radius, occupationStatus, false);
+ return Optional.ofNullable(ret);
+ // Paper end - re-route to faster logic
}
public Optional<BlockPos> findClosest(Predicate<PoiType> typePredicate, BlockPos pos, int radius, PoiManager.Occupancy occupationStatus) {
- return this.getInRange(typePredicate, pos, radius, occupationStatus).map(PoiRecord::getPos).min(Comparator.comparingDouble((blockPos2) -> {
- return blockPos2.distSqr(pos);
- }));
+ // Paper start - re-route to faster logic
+ BlockPos ret = io.papermc.paper.util.PoiAccess.findClosestPoiDataPosition(this, typePredicate, null, pos, radius, radius*radius, occupationStatus, false);
+ return Optional.ofNullable(ret);
+ // Paper end - re-route to faster logic
}
public Optional<BlockPos> findClosest(Predicate<PoiType> predicate, Predicate<BlockPos> predicate2, BlockPos blockPos, int i, PoiManager.Occupancy occupancy) {
- return this.getInRange(predicate, blockPos, i, occupancy).map(PoiRecord::getPos).filter(predicate2).min(Comparator.comparingDouble((blockPos2) -> {
- return blockPos2.distSqr(blockPos);
- }));
+ // Paper start - re-route to faster logic
+ BlockPos ret = io.papermc.paper.util.PoiAccess.findClosestPoiDataPosition(this, predicate, predicate2, blockPos, i, i*i, occupancy, false);
+ return Optional.ofNullable(ret);
+ // Paper end - re-route to faster logic
}
public Optional<BlockPos> take(Predicate<PoiType> typePredicate, Predicate<BlockPos> positionPredicate, BlockPos pos, int radius) {
- return this.getInRange(typePredicate, pos, radius, PoiManager.Occupancy.HAS_SPACE).filter((poi) -> {
- return positionPredicate.test(poi.getPos());
- }).findFirst().map((poi) -> {
- poi.acquireTicket();
- return poi.getPos();
- });
+ // Paper start - re-route to faster logic
+ PoiRecord ret = io.papermc.paper.util.PoiAccess.findAnyPoiRecord(
+ this, typePredicate, positionPredicate, pos, radius, PoiManager.Occupancy.HAS_SPACE, false
+ );
+ if (ret == null) {
+ return Optional.empty();
+ }
+ ret.acquireTicket();
+ return Optional.of(ret.getPos());
+ // Paper end - re-route to faster logic
}
public Optional<BlockPos> getRandom(Predicate<PoiType> typePredicate, Predicate<BlockPos> positionPredicate, PoiManager.Occupancy occupationStatus, BlockPos pos, int radius, Random random) {
- List<PoiRecord> list = this.getInRange(typePredicate, pos, radius, occupationStatus).collect(Collectors.toList());
- Collections.shuffle(list, random);
- return list.stream().filter((poiRecord) -> {
- return positionPredicate.test(poiRecord.getPos());
- }).findFirst().map(PoiRecord::getPos);
+ // Paper start - re-route to faster logic
+ List<PoiRecord> list = new java.util.ArrayList<>();
+ io.papermc.paper.util.PoiAccess.findAnyPoiRecords(
+ this, typePredicate, positionPredicate, pos, radius, occupationStatus, false, Integer.MAX_VALUE, list
+ );
+
+ // the old method shuffled the list and then tried to find the first element in it that
+ // matched positionPredicate, however we moved positionPredicate into the poi search. This means we can avoid a
+ // shuffle entirely, and just pick a random element from list
+ if (list.isEmpty()) {
+ return Optional.empty();
+ }
+
+ return Optional.of(list.get(random.nextInt(list.size())).getPos());
+ // Paper end - re-route to faster logic
}
public boolean release(BlockPos pos) {
diff --git a/src/main/java/net/minecraft/world/entity/ai/village/poi/PoiSection.java b/src/main/java/net/minecraft/world/entity/ai/village/poi/PoiSection.java
index 5a86bc6f552913e2978c61233148db22e3a240f1..16f9796adcb83350e97220ba0e96bfee998f1ff4 100644
--- a/src/main/java/net/minecraft/world/entity/ai/village/poi/PoiSection.java
+++ b/src/main/java/net/minecraft/world/entity/ai/village/poi/PoiSection.java
@@ -25,7 +25,7 @@ import org.apache.logging.log4j.Logger;
public class PoiSection {
private static final Logger LOGGER = LogManager.getLogger();
private final Short2ObjectMap<PoiRecord> records = new Short2ObjectOpenHashMap<>();
- private final Map<PoiType, Set<PoiRecord>> byType = Maps.newHashMap();
+ private final Map<PoiType, Set<PoiRecord>> byType = Maps.newHashMap(); public final Map<PoiType, Set<PoiRecord>> getData() { return this.byType; } // Paper - public accessor
private final Runnable setDirty;
private boolean isValid;
diff --git a/src/main/java/net/minecraft/world/level/chunk/storage/SectionStorage.java b/src/main/java/net/minecraft/world/level/chunk/storage/SectionStorage.java
index 90f7b06bd2c558be35c4577044fa033e1fb5cc22..e2d1149cbe75b0689c9f816b87ebb7ba0d6f56c8 100644
--- a/src/main/java/net/minecraft/world/level/chunk/storage/SectionStorage.java
+++ b/src/main/java/net/minecraft/world/level/chunk/storage/SectionStorage.java
@@ -61,11 +61,11 @@ public class SectionStorage<R> extends RegionFileStorage implements AutoCloseabl
}
@Nullable
- protected Optional<R> get(long pos) {
+ public Optional<R> get(long pos) { // Paper - public
return this.storage.get(pos);
}
- protected Optional<R> getOrLoad(long pos) {
+ public Optional<R> getOrLoad(long pos) { // Paper - public
if (this.outsideStoredRange(pos)) {
return Optional.empty();
} else {
diff --git a/src/main/java/net/minecraft/world/level/portal/PortalForcer.java b/src/main/java/net/minecraft/world/level/portal/PortalForcer.java
index ca3e143e641933fa6b9499bbaaa1836877d90c52..4e3987e6233e84647d019e41ba6afe7c5d09ea80 100644
Merge tuinity (#6413) This PR contains all of Tuinity's patches. Very notable ones are: - Highly optimised collisions - Optimised entity lookups by bounding box (Mojang made regressions in 1.17, this brings it back to 1.16) - Starlight https://github.com/PaperMC/Starlight - Rewritten dataconverter system https://github.com/PaperMC/DataConverter - Random block ticking optimisation (wrongly dropped from Paper 1.17) - Chunk ticking optimisations - Anything else I've forgotten in the 60 or so patches If you are a previous Tuinity user, your config will not migrate. You must do it yourself. The config options have simply been moved into paper.yml, so it will be an easy migration. However, please note that the chunk loading options in tuinity.yml are NOT compatible with the options in paper.yml. * Port tuinity, initial patchset * Update gradle to 7.2 jmp said it fixes rebuildpatches not working for me. it fucking better * Completely clean apply * Remove tuinity config, add per player api patch * Remove paper reobf mappings patch * Properly update gradlew * Force clean rebuild * Mark fixups Comments and ATs still need to be done * grep -r "Tuinity" * Fixup * Ensure gameprofile lastaccess is written only under the state lock * update URL for dataconverter * Only clean rebuild tuinity patches might fix merge conflicts * Use UTF-8 for gradlew * Clean rb patches again * Convert block ids used as item ids Neither the converters of pre 1.13 nor DFU handled these cases, as by the time they were written the game at the time didn't consider these ids valid - they would be air. Because of this, some worlds have logspam since only DataConverter (not DFU or legacy converters) will warn when an invalid id has been seen. While quite a few do need to now be considered as air, quite a lot do not. So it makes sense to add conversion for these items, instead of simply suppressing or ignoring the logs. I've now added id -> string conversion for all block ids that could be used as items that existed in the game before 1.7.10 (I have no interest in tracking down the exact version block ids stopped working) that were on https://minecraft-ids.grahamedgecombe.com/ Items that did not directly convert to new items will be instead converted to air: stems, wheat crops, piston head, tripwire wire block * Fix LightPopulated parsing in V1466 The DFU code was checking if the number existed, not if it didn't exist. I misread the original code. * Always parse protochunk light sources unless it is marked as non-lit Chunks not marked as lit will always go through the light engine, so they should always have their block sources parsed. * Update custom names to JSON for players Missed this fix from CB, as it was inside the DataFixers class. I decided to double check all of the CB changes again: DataFixers.java was the only area I missed, as I had inspected all datafixer diffs and implemented them all into DataConverter. I also checked Bootstrap.java again, and re-evaluated their changes. I had previously done this, but determined that they were all bad. The changes to make standing_sign block map to oak_sign block in V1450 is bad, because that's not the item id V1450 accepts. Only in 1.14 did oak_sign even exist, and as expected there is a converter to rename all existing sign items/blocks. The fix to register the portal block under id 1440 is useless, as the flattenning logic will default to the lowest registered id - which is the exact blockstate that CB registers into 1440. So it just doesn't do anything. The extra item ids in the id -> string converter are already added, but I found this from EMC originally. The change for the spawn egg id 23 -> Arrow is just wrong, that id DOES correspond to TippedArrow, NOT Arrow. As expected, the spawn egg already has a dedicated mapping for Arrow, which is id 10 - which was Arrow's entity id. I also ported a fix for the cooked_fished id update. This doesn't really matter since there is already a dataconverter to fix this, but the game didn't accept cooked_fished at the time. So I see no harm. * Review all converters and walkers - Refactor V99 to have helper methods for defining entity/tile entity types - Automatically namespace all ids that should be namespaced. While vanilla never saved non-namespaced data for things that are namespaced, plugins/users might have. - Synchronised the identity ensure map in HelperBlockFlatteningV1450 - Code style consistency - Add missing log warning in V102 for ITEM_NAME type conversion - Use getBoolean instead of getByte - Use ConverterAbstractEntityRename for V143 TippedArrow -> Arrow rename, as it will affect ENTITY_NAME type - Always set isVillager to false in V502 for Zombie - Register V808's converter under subversion 1 like DFU - Register a breakpoint for V1.17.1. In the future, all final versions of major releases will have a breakpoint so that the work required to determine if a converter needs a breakpoint is minimal - Validate that a dataconverter is only registered for a version that is registered - ConverterFlattenTileEntity is actually ConverterFlattenEntity It even registered the converters under TILE_ENTITY, instead of ENTITY. - Fix id comparison in V1492 STRUCTURE_FEATURE renamer - Use ConverterAbstractStatsRename for V1510 stats renamer At the time I had written that class, the abstract renamer didn't exist. - Ensure OwnerUUID is at least set to empty string in V1904 if the ocelot is converted to a cat (this is likely so that it retains a collar) - Use generic read/write for Records in V1946 Records is actually a list, not a map. So reading map was invalid. * Always set light to zero when propagating decrease This fixes an almost infinite loop where light values would be spam queued on a very small subset on blocks. This also likely fixes the memory issues people were seeing. * re-organize patches * Apply and fix conflicts * Revert some patches getChunkAt retains chunks so that plugins don't spam loads revert mc-4 fix will remain unless issues pop up * Shuffle iterated chunks if per player is not enabled Can help with some mob spawning stacking up at locations * Make per player default, migrate all configs * Adjust comments in fixups * Rework config for player chunk loader Old config is not compatible. Move all configs to be under `settings` in paper.yml The player chunk loader has been modified to less aggressively load chunks, but to send chunks at higher rates compared to tuinity. There are new config entries to tune this behavior. * Add back old constructor to CompressionEncoder/Decoder (fixes Tuinity #358) * Raise chunk loading default limits * Reduce worldgen thread workers for lower core count cpus * Raise limits for chunk loading config Also place it under `chunk-loading` * Disable max chunk send rate by default * Fix conflicts and rebuild patches * Drop default send rate again Appears to be still causing problems for no known reason * Raise chunk send limits to 100 per player While a low limit fixes ping issues for some people, most people do not suffer from this issue and thus should not suffer from an extremely slow load-in rate. * Rebase part 1 Autosquash the fixups * Move not implemented up * Fixup mc-dev fixes Missed this one * Rebase per player viewdistance api into the original api patch * Remove old light engine patch part 1 The prioritisation must be kept from it, so that part has been rebased into the priority patch. Part 2 will deal with rebasing all of the patches _after_ * Rebase remaining patches for old light patch removal * Remove other mid tick patch * Remove Optimize-PlayerChunkMap-memory-use-for-visibleChunks.patch Replaced by `Do not copy visible chunks` * Revert AT for Vec3i setX/Y/Z The class is immutable. set should not be exposed * Remove old IntegerUtil class * Replace old CraftChunk#getEntities patch * Remove import for SWMRNibbleArray in ChunkAccess * Finished merge checklist * Remove ensureTickThread impl in urgency patch Co-authored-by: Spottedleaf <Spottedleaf@users.noreply.github.com> Co-authored-by: Jason Penilla <11360596+jpenilla@users.noreply.github.com>
2021-08-31 11:02:11 +00:00
--- a/src/main/java/net/minecraft/world/level/portal/PortalForcer.java
+++ b/src/main/java/net/minecraft/world/level/portal/PortalForcer.java
@@ -52,16 +52,37 @@ public class PortalForcer {
// int i = flag ? 16 : 128;
// CraftBukkit end
- villageplace.ensureLoadedAndValid(this.level, blockposition, i);
- Optional<PoiRecord> optional = villageplace.getInSquare((villageplacetype) -> {
- return villageplacetype == PoiType.NETHER_PORTAL;
- }, blockposition, i, PoiManager.Occupancy.ANY).sorted(Comparator.comparingDouble((PoiRecord villageplacerecord) -> { // CraftBukkit - decompile error
- return villageplacerecord.getPos().distSqr(blockposition);
- }).thenComparingInt((villageplacerecord) -> {
- return villageplacerecord.getPos().getY();
- })).filter((villageplacerecord) -> {
- return this.level.getBlockState(villageplacerecord.getPos()).hasProperty(BlockStateProperties.HORIZONTAL_AXIS);
- }).findFirst();
+ // Paper start - optimise portals
+ Optional<PoiRecord> optional;
+ java.util.List<PoiRecord> records = new java.util.ArrayList<>();
+ io.papermc.paper.util.PoiAccess.findClosestPoiDataRecords(
+ villageplace,
+ (PoiType type) -> {
+ return type == PoiType.NETHER_PORTAL;
+ },
+ (BlockPos pos) -> {
+ net.minecraft.world.level.chunk.ChunkAccess lowest = this.level.getChunk(pos.getX() >> 4, pos.getZ() >> 4, net.minecraft.world.level.chunk.ChunkStatus.EMPTY);
+ if (!lowest.getStatus().isOrAfter(net.minecraft.world.level.chunk.ChunkStatus.FULL)) {
+ // why would we generate the chunk?
+ return false;
+ }
+ return lowest.getBlockState(pos).hasProperty(BlockStateProperties.HORIZONTAL_AXIS);
+ },
+ blockposition, i, Double.MAX_VALUE, PoiManager.Occupancy.ANY, true, records
+ );
+
+ // this gets us most of the way there, but we bias towards lower y values.
+ PoiRecord lowestYRecord = null;
+ for (PoiRecord record : records) {
+ if (lowestYRecord == null) {
+ lowestYRecord = record;
+ } else if (lowestYRecord.getPos().getY() > record.getPos().getY()) {
+ lowestYRecord = record;
+ }
+ }
+ // now we're done
+ optional = Optional.ofNullable(lowestYRecord);
+ // Paper end - optimise portals
return optional.map((villageplacerecord) -> {
BlockPos blockposition1 = villageplacerecord.getPos();