3
0
Mirror von https://github.com/IntellectualSites/FastAsyncWorldEdit.git synchronisiert 2024-11-03 01:50:07 +01:00

refactor: Address .editorconfig violations

Dieser Commit ist enthalten in:
NotMyFault 2021-10-18 23:09:21 +02:00
Ursprung 9a33789e41
Commit bd9476a175
Es konnte kein GPG-Schlüssel zu dieser Signatur gefunden werden
GPG-Schlüssel-ID: 158F5701A6AAD00C
53 geänderte Dateien mit 1415 neuen und 1127 gelöschten Zeilen

Datei anzeigen

@ -141,6 +141,7 @@ import org.bukkit.generator.ChunkGenerator;
import org.spigotmc.SpigotConfig; import org.spigotmc.SpigotConfig;
import org.spigotmc.WatchdogThread; import org.spigotmc.WatchdogThread;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
@ -162,7 +163,6 @@ import java.util.concurrent.ForkJoinPool;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
@ -193,7 +193,8 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
serverWorldsField.setAccessible(true); serverWorldsField.setAccessible(true);
getChunkFutureMethod = ServerChunkCache.class.getDeclaredMethod("getChunkFutureMainThread", getChunkFutureMethod = ServerChunkCache.class.getDeclaredMethod("getChunkFutureMainThread",
int.class, int.class, ChunkStatus.class, boolean.class); int.class, int.class, ChunkStatus.class, boolean.class
);
getChunkFutureMethod.setAccessible(true); getChunkFutureMethod.setAccessible(true);
chunkProviderExecutorField = ServerChunkCache.class.getDeclaredField( chunkProviderExecutorField = ServerChunkCache.class.getDeclaredField(
@ -232,7 +233,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
* Read the given NBT data into the given tile entity. * Read the given NBT data into the given tile entity.
* *
* @param tileEntity the tile entity * @param tileEntity the tile entity
* @param tag the tag * @param tag the tag
*/ */
static void readTagIntoTileEntity(net.minecraft.nbt.CompoundTag tag, BlockEntity tileEntity) { static void readTagIntoTileEntity(net.minecraft.nbt.CompoundTag tag, BlockEntity tileEntity) {
tileEntity.load(tag); tileEntity.load(tag);
@ -243,7 +244,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
* Write the tile entity's NBT data to the given tag. * Write the tile entity's NBT data to the given tag.
* *
* @param tileEntity the tile entity * @param tileEntity the tile entity
* @param tag the tag * @param tag the tag
*/ */
private static void readTileEntityIntoTag(BlockEntity tileEntity, net.minecraft.nbt.CompoundTag tag) { private static void readTileEntityIntoTag(BlockEntity tileEntity, net.minecraft.nbt.CompoundTag tag) {
tileEntity.save(tag); tileEntity.save(tag);
@ -262,7 +263,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
/** /**
* Create an entity using the given entity ID. * Create an entity using the given entity ID.
* *
* @param id the entity ID * @param id the entity ID
* @param world the world * @param world the world
* @return an entity or null * @return an entity or null
*/ */
@ -275,7 +276,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
* Write the given NBT data into the given entity. * Write the given NBT data into the given entity.
* *
* @param entity the entity * @param entity the entity
* @param tag the tag * @param tag the tag
*/ */
private static void readTagIntoEntity(net.minecraft.nbt.CompoundTag tag, Entity entity) { private static void readTagIntoEntity(net.minecraft.nbt.CompoundTag tag, Entity entity) {
entity.load(tag); entity.load(tag);
@ -285,7 +286,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
* Write the entity's NBT data to the given tag. * Write the entity's NBT data to the given tag.
* *
* @param entity the entity * @param entity the entity
* @param tag the tag * @param tag the tag
*/ */
private static void readEntityIntoTag(Entity entity, net.minecraft.nbt.CompoundTag tag) { private static void readEntityIntoTag(Entity entity, net.minecraft.nbt.CompoundTag tag) {
entity.save(tag); entity.save(tag);
@ -349,8 +350,10 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
@Override @Override
public WorldNativeAccess<?, ?, ?> createWorldNativeAccess(org.bukkit.World world) { public WorldNativeAccess<?, ?, ?> createWorldNativeAccess(org.bukkit.World world) {
return new PaperweightWorldNativeAccess(this, return new PaperweightWorldNativeAccess(
new WeakReference<>(((CraftWorld) world).getHandle())); this,
new WeakReference<>(((CraftWorld) world).getHandle())
);
} }
private static net.minecraft.core.Direction adapt(Direction face) { private static net.minecraft.core.Direction adapt(Direction face) {
@ -462,7 +465,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
return TranslatableComponent.of(CraftItemStack.asNMSCopy(BukkitAdapter.adapt(itemStack)).getDescriptionId()); return TranslatableComponent.of(CraftItemStack.asNMSCopy(BukkitAdapter.adapt(itemStack)).getDescriptionId());
} }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({"unchecked", "rawtypes"})
@Override @Override
public Map<String, ? extends Property<?>> getProperties(BlockType blockType) { public Map<String, ? extends Property<?>> getProperties(BlockType blockType) {
Map<String, Property<?>> properties = Maps.newTreeMap(String::compareTo); Map<String, Property<?>> properties = Maps.newTreeMap(String::compareTo);
@ -474,11 +477,25 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) { if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) {
property = new BooleanProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues())); property = new BooleanProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues()));
} else if (state instanceof DirectionProperty) { } else if (state instanceof DirectionProperty) {
property = new DirectionalProperty(state.getName(), property = new DirectionalProperty(
(List<Direction>) state.getPossibleValues().stream().map(e -> Direction.valueOf(((StringRepresentable) e).getSerializedName().toUpperCase(Locale.ROOT))).collect(Collectors.toList())); state.getName(),
(List<Direction>) state
.getPossibleValues()
.stream()
.map(e -> Direction.valueOf(((StringRepresentable) e)
.getSerializedName()
.toUpperCase(Locale.ROOT)))
.collect(Collectors.toList())
);
} else if (state instanceof net.minecraft.world.level.block.state.properties.EnumProperty) { } else if (state instanceof net.minecraft.world.level.block.state.properties.EnumProperty) {
property = new EnumProperty(state.getName(), property = new EnumProperty(
(List<String>) state.getPossibleValues().stream().map(e -> ((StringRepresentable) e).getSerializedName()).collect(Collectors.toList())); state.getName(),
(List<String>) state
.getPossibleValues()
.stream()
.map(e -> ((StringRepresentable) e).getSerializedName())
.collect(Collectors.toList())
);
} else if (state instanceof net.minecraft.world.level.block.state.properties.IntegerProperty) { } else if (state instanceof net.minecraft.world.level.block.state.properties.IntegerProperty) {
property = new IntegerProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues())); property = new IntegerProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues()));
} else { } else {
@ -536,7 +553,8 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
} }
fakePlayer.setItemInHand(InteractionHand.MAIN_HAND, stack); fakePlayer.setItemInHand(InteractionHand.MAIN_HAND, stack);
fakePlayer.absMoveTo(position.getBlockX(), position.getBlockY(), position.getBlockZ(), fakePlayer.absMoveTo(position.getBlockX(), position.getBlockY(), position.getBlockZ(),
(float) face.toVector().toYaw(), (float) face.toVector().toPitch()); (float) face.toVector().toYaw(), (float) face.toVector().toPitch()
);
final BlockPos blockPos = new BlockPos(position.getBlockX(), position.getBlockY(), position.getBlockZ()); final BlockPos blockPos = new BlockPos(position.getBlockX(), position.getBlockY(), position.getBlockZ());
final Vec3 blockVec = Vec3.atLowerCornerOf(blockPos); final Vec3 blockVec = Vec3.atLowerCornerOf(blockPos);
@ -545,7 +563,10 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
UseOnContext context = new UseOnContext(fakePlayer, InteractionHand.MAIN_HAND, rayTrace); UseOnContext context = new UseOnContext(fakePlayer, InteractionHand.MAIN_HAND, rayTrace);
InteractionResult result = stack.placeItem(context, InteractionHand.MAIN_HAND); InteractionResult result = stack.placeItem(context, InteractionHand.MAIN_HAND);
if (result != InteractionResult.SUCCESS) { if (result != InteractionResult.SUCCESS) {
if (worldServer.getBlockState(blockPos).use(worldServer, fakePlayer, InteractionHand.MAIN_HAND, rayTrace).consumesAction()) { if (worldServer
.getBlockState(blockPos)
.use(worldServer, fakePlayer, InteractionHand.MAIN_HAND, rayTrace)
.consumesAction()) {
result = InteractionResult.SUCCESS; result = InteractionResult.SUCCESS;
} else { } else {
result = stack.getItem().use(worldServer, fakePlayer, InteractionHand.MAIN_HAND).getResult(); result = stack.getItem().use(worldServer, fakePlayer, InteractionHand.MAIN_HAND).getResult();
@ -559,7 +580,10 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
public boolean canPlaceAt(org.bukkit.World world, BlockVector3 position, BlockState blockState) { public boolean canPlaceAt(org.bukkit.World world, BlockVector3 position, BlockState blockState) {
int internalId = BlockStateIdAccess.getBlockStateId(blockState); int internalId = BlockStateIdAccess.getBlockStateId(blockState);
net.minecraft.world.level.block.state.BlockState blockData = Block.stateById(internalId); net.minecraft.world.level.block.state.BlockState blockData = Block.stateById(internalId);
return blockData.canSurvive(((CraftWorld) world).getHandle(), new BlockPos(position.getX(), position.getY(), position.getZ())); return blockData.canSurvive(
((CraftWorld) world).getHandle(),
new BlockPos(position.getX(), position.getY(), position.getZ())
);
} }
@Override @Override
@ -661,7 +685,11 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Dynamic<net.minecraft.nbt.Tag> recursivelySetSeed(Dynamic<net.minecraft.nbt.Tag> dynamic, long seed, Set<Dynamic<net.minecraft.nbt.Tag>> seen) { private Dynamic<net.minecraft.nbt.Tag> recursivelySetSeed(
Dynamic<net.minecraft.nbt.Tag> dynamic,
long seed,
Set<Dynamic<net.minecraft.nbt.Tag>> seen
) {
if (!seen.add(dynamic)) { if (!seen.add(dynamic)) {
return dynamic; return dynamic;
} }
@ -685,7 +713,8 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void regenForWorld(Region region, Extent extent, ServerLevel serverWorld, RegenOptions options) throws WorldEditException { private void regenForWorld(Region region, Extent extent, ServerLevel serverWorld, RegenOptions options) throws
WorldEditException {
List<CompletableFuture<ChunkAccess>> chunkLoadings = submitChunkLoadTasks(region, serverWorld); List<CompletableFuture<ChunkAccess>> chunkLoadings = submitChunkLoadTasks(region, serverWorld);
BlockableEventLoop<Runnable> executor; BlockableEventLoop<Runnable> executor;
try { try {
@ -858,7 +887,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
* *
* @param foreign the foreign tag * @param foreign the foreign tag
* @return the converted tag * @return the converted tag
* @throws SecurityException on error * @throws SecurityException on error
* @throws IllegalArgumentException on error * @throws IllegalArgumentException on error
*/ */
private ListTag toNativeList(net.minecraft.nbt.ListTag foreign) throws SecurityException, IllegalArgumentException { private ListTag toNativeList(net.minecraft.nbt.ListTag foreign) throws SecurityException, IllegalArgumentException {
@ -935,6 +964,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
} }
private class SpigotWatchdog implements Watchdog { private class SpigotWatchdog implements Watchdog {
private final Field instanceField; private final Field instanceField;
private final Field lastTickField; private final Field lastTickField;
@ -959,9 +989,11 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
logger.log(Level.WARNING, "Failed to tick watchdog", e); logger.log(Level.WARNING, "Failed to tick watchdog", e);
} }
} }
} }
private static class MojangWatchdog implements Watchdog { private static class MojangWatchdog implements Watchdog {
private final DedicatedServer server; private final DedicatedServer server;
private final Field tickField; private final Field tickField;
@ -981,9 +1013,11 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
} catch (IllegalAccessException ignored) { } catch (IllegalAccessException ignored) {
} }
} }
} }
private static class NoOpWorldLoadListener implements ChunkProgressListener { private static class NoOpWorldLoadListener implements ChunkProgressListener {
@Override @Override
public void updateSpawnPos(ChunkPos spawnPos) { public void updateSpawnPos(ChunkPos spawnPos) {
} }
@ -1003,5 +1037,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter {
@Override @Override
public void setChunkRadius(int radius) { public void setChunkRadius(int radius) {
} }
} }
} }

Datei anzeigen

@ -49,6 +49,7 @@ import net.minecraft.world.item.DyeColor;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.EnumMap; import java.util.EnumMap;
@ -62,20 +63,19 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.annotation.Nullable;
/** /**
* Handles converting all Pre 1.13.2 data using the Legacy DataFix System (ported to 1.13.2) * Handles converting all Pre 1.13.2 data using the Legacy DataFix System (ported to 1.13.2)
* * <p>
* We register a DFU Fixer per Legacy Data Version and apply the fixes using legacy strategy * We register a DFU Fixer per Legacy Data Version and apply the fixes using legacy strategy
* which is safer, faster and cleaner code. * which is safer, faster and cleaner code.
* * <p>
* The pre DFU code did not fail when the Source version was unknown. * The pre DFU code did not fail when the Source version was unknown.
* * <p>
* This class also provides util methods for converting compounds to wrap the update call to * This class also provides util methods for converting compounds to wrap the update call to
* receive the source version in the compound * receive the source version in the compound
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.worldedit.world.DataFixer { class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.worldedit.world.DataFixer {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -118,7 +118,12 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
private String fixBlockState(String blockState, int srcVer) { private String fixBlockState(String blockState, int srcVer) {
net.minecraft.nbt.CompoundTag stateNBT = stateToNBT(blockState); net.minecraft.nbt.CompoundTag stateNBT = stateToNBT(blockState);
Dynamic<net.minecraft.nbt.Tag> dynamic = new Dynamic<>(OPS_NBT, stateNBT); Dynamic<net.minecraft.nbt.Tag> dynamic = new Dynamic<>(OPS_NBT, stateNBT);
net.minecraft.nbt.CompoundTag fixed = (net.minecraft.nbt.CompoundTag) INSTANCE.fixer.update(References.BLOCK_STATE, dynamic, srcVer, DATA_VERSION).getValue(); net.minecraft.nbt.CompoundTag fixed = (net.minecraft.nbt.CompoundTag) INSTANCE.fixer.update(
References.BLOCK_STATE,
dynamic,
srcVer,
DATA_VERSION
).getValue();
return nbtToState(fixed); return nbtToState(fixed);
} }
@ -128,7 +133,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
if (tagCompound.contains("Properties", 10)) { if (tagCompound.contains("Properties", 10)) {
sb.append('['); sb.append('[');
net.minecraft.nbt.CompoundTag props = tagCompound.getCompound("Properties"); net.minecraft.nbt.CompoundTag props = tagCompound.getCompound("Properties");
sb.append(props.getAllKeys().stream().map(k -> k + "=" + props.getString(k).replace("\"", "")).collect(Collectors.joining(","))); sb.append(props
.getAllKeys()
.stream()
.map(k -> k + "=" + props.getString(k).replace("\"", ""))
.collect(Collectors.joining(",")));
sb.append(']'); sb.append(']');
} }
return sb.toString(); return sb.toString();
@ -220,6 +229,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private class WrappedDataFixer implements DataFixer { private class WrappedDataFixer implements DataFixer {
private final DataFixer realFixer; private final DataFixer realFixer;
WrappedDataFixer(DataFixer realFixer) { WrappedDataFixer(DataFixer realFixer) {
@ -240,7 +250,12 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return realFixer.update(type, dynamic, sourceVer, targetVer); return realFixer.update(type, dynamic, sourceVer, targetVer);
} }
private net.minecraft.nbt.CompoundTag convert(LegacyType type, net.minecraft.nbt.CompoundTag cmp, int sourceVer, int desiredVersion) { private net.minecraft.nbt.CompoundTag convert(
LegacyType type,
net.minecraft.nbt.CompoundTag cmp,
int sourceVer,
int desiredVersion
) {
List<DataConverter> converters = PaperweightDataConverters.this.converters.get(type); List<DataConverter> converters = PaperweightDataConverters.this.converters.get(type);
if (converters != null && !converters.isEmpty()) { if (converters != null && !converters.isEmpty()) {
for (DataConverter converter : converters) { for (DataConverter converter : converters) {
@ -265,6 +280,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
public Schema getSchema(int i) { public Schema getSchema(int i) {
return realFixer.getSchema(i); return realFixer.getSchema(i);
} }
} }
public static net.minecraft.nbt.CompoundTag convert(LegacyType type, net.minecraft.nbt.CompoundTag cmp) { public static net.minecraft.nbt.CompoundTag convert(LegacyType type, net.minecraft.nbt.CompoundTag cmp) {
@ -275,7 +291,12 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return convert(type.getDFUType(), cmp, sourceVer); return convert(type.getDFUType(), cmp, sourceVer);
} }
public static net.minecraft.nbt.CompoundTag convert(LegacyType type, net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) { public static net.minecraft.nbt.CompoundTag convert(
LegacyType type,
net.minecraft.nbt.CompoundTag cmp,
int sourceVer,
int targetVer
) {
return convert(type.getDFUType(), cmp, sourceVer, targetVer); return convert(type.getDFUType(), cmp, sourceVer, targetVer);
} }
@ -288,16 +309,25 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return convert(type, cmp, sourceVer, DATA_VERSION); return convert(type, cmp, sourceVer, DATA_VERSION);
} }
public static net.minecraft.nbt.CompoundTag convert(TypeReference type, net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) { public static net.minecraft.nbt.CompoundTag convert(
TypeReference type,
net.minecraft.nbt.CompoundTag cmp,
int sourceVer,
int targetVer
) {
if (sourceVer >= targetVer) { if (sourceVer >= targetVer) {
return cmp; return cmp;
} }
return (net.minecraft.nbt.CompoundTag) INSTANCE.fixer.update(type, new Dynamic<>(OPS_NBT, cmp), sourceVer, targetVer).getValue(); return (net.minecraft.nbt.CompoundTag) INSTANCE.fixer
.update(type, new Dynamic<>(OPS_NBT, cmp), sourceVer, targetVer)
.getValue();
} }
public interface DataInspector { public interface DataInspector {
net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer); net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer);
} }
public interface DataConverter { public interface DataConverter {
@ -305,6 +335,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
int getDataVersion(); int getDataVersion();
net.minecraft.nbt.CompoundTag convert(net.minecraft.nbt.CompoundTag cmp); net.minecraft.nbt.CompoundTag convert(net.minecraft.nbt.CompoundTag cmp);
} }
@ -582,7 +613,13 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return key; return key;
} }
private static void convertCompound(LegacyType type, net.minecraft.nbt.CompoundTag cmp, String key, int sourceVer, int targetVer) { private static void convertCompound(
LegacyType type,
net.minecraft.nbt.CompoundTag cmp,
String key,
int sourceVer,
int targetVer
) {
cmp.put(key, convert(type, cmp.getCompound(key), sourceVer, targetVer)); cmp.put(key, convert(type, cmp.getCompound(key), sourceVer, targetVer));
} }
@ -658,6 +695,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataInspectorBlockEntity implements DataInspector { private static class DataInspectorBlockEntity implements DataInspector {
@ -840,6 +878,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
@ -859,7 +898,12 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
abstract net.minecraft.nbt.CompoundTag inspectChecked(net.minecraft.nbt.CompoundTag nbttagcompound, int sourceVer, int targetVer); abstract net.minecraft.nbt.CompoundTag inspectChecked(
net.minecraft.nbt.CompoundTag nbttagcompound,
int sourceVer,
int targetVer
);
} }
private static class DataInspectorItemList extends DataInspectorTagged { private static class DataInspectorItemList extends DataInspectorTagged {
@ -878,6 +922,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return nbttagcompound; return nbttagcompound;
} }
} }
private static class DataInspectorItem extends DataInspectorTagged { private static class DataInspectorItem extends DataInspectorTagged {
@ -896,6 +941,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return nbttagcompound; return nbttagcompound;
} }
} }
private static class DataConverterMaterialId implements DataConverter { private static class DataConverterMaterialId implements DataConverter {
@ -1296,6 +1342,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterBanner implements DataConverter { private static class DataConverterBanner implements DataConverter {
@ -1342,6 +1389,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterPotionId implements DataConverter { private static class DataConverterPotionId implements DataConverter {
@ -1619,7 +1667,15 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
private static class DataConverterMinecart implements DataConverter { private static class DataConverterMinecart implements DataConverter {
private static final List<String> a = Lists.newArrayList("MinecartRideable", "MinecartChest", "MinecartFurnace", "MinecartTNT", "MinecartSpawner", "MinecartHopper", "MinecartCommandBlock"); private static final List<String> a = Lists.newArrayList(
"MinecartRideable",
"MinecartChest",
"MinecartFurnace",
"MinecartTNT",
"MinecartSpawner",
"MinecartHopper",
"MinecartCommandBlock"
);
DataConverterMinecart() { DataConverterMinecart() {
} }
@ -1643,6 +1699,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterMobSpawner implements DataConverter { private static class DataConverterMobSpawner implements DataConverter {
@ -1687,6 +1744,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
} }
private static class DataConverterUUID implements DataConverter { private static class DataConverterUUID implements DataConverter {
@ -1705,11 +1763,47 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterHealth implements DataConverter { private static class DataConverterHealth implements DataConverter {
private static final Set<String> a = Sets.newHashSet("ArmorStand", "Bat", "Blaze", "CaveSpider", "Chicken", "Cow", "Creeper", "EnderDragon", "Enderman", "Endermite", "EntityHorse", "Ghast", "Giant", "Guardian", "LavaSlime", "MushroomCow", "Ozelot", "Pig", "PigZombie", "Rabbit", "Sheep", "Shulker", "Silverfish", "Skeleton", "Slime", "SnowMan", "Spider", "Squid", "Villager", "VillagerGolem", "Witch", "WitherBoss", "Wolf", "Zombie"); private static final Set<String> a = Sets.newHashSet(
"ArmorStand",
"Bat",
"Blaze",
"CaveSpider",
"Chicken",
"Cow",
"Creeper",
"EnderDragon",
"Enderman",
"Endermite",
"EntityHorse",
"Ghast",
"Giant",
"Guardian",
"LavaSlime",
"MushroomCow",
"Ozelot",
"Pig",
"PigZombie",
"Rabbit",
"Sheep",
"Shulker",
"Silverfish",
"Skeleton",
"Slime",
"SnowMan",
"Spider",
"Squid",
"Villager",
"VillagerGolem",
"Witch",
"WitherBoss",
"Wolf",
"Zombie"
);
DataConverterHealth() { DataConverterHealth() {
} }
@ -1738,6 +1832,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterSaddle implements DataConverter { private static class DataConverterSaddle implements DataConverter {
@ -1762,6 +1857,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterHanging implements DataConverter { private static class DataConverterHanging implements DataConverter {
@ -1800,6 +1896,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterDropChances implements DataConverter { private static class DataConverterDropChances implements DataConverter {
@ -1823,13 +1920,15 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
if (cmp.contains("ArmorDropChances", 9)) { if (cmp.contains("ArmorDropChances", 9)) {
nbttaglist = cmp.getList("ArmorDropChances", 5); nbttaglist = cmp.getList("ArmorDropChances", 5);
if (nbttaglist.size() == 4 && nbttaglist.getFloat(0) == 0.0F && nbttaglist.getFloat(1) == 0.0F && nbttaglist.getFloat(2) == 0.0F && nbttaglist.getFloat(3) == 0.0F) { if (nbttaglist.size() == 4 && nbttaglist.getFloat(0) == 0.0F && nbttaglist.getFloat(1) == 0.0F && nbttaglist.getFloat(
2) == 0.0F && nbttaglist.getFloat(3) == 0.0F) {
cmp.remove("ArmorDropChances"); cmp.remove("ArmorDropChances");
} }
} }
return cmp; return cmp;
} }
} }
private static class DataConverterRiding implements DataConverter { private static class DataConverterRiding implements DataConverter {
@ -1865,6 +1964,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
nbttagcompound.remove("Riding"); nbttagcompound.remove("Riding");
return nbttagcompound1; return nbttagcompound1;
} }
} }
private static class DataConverterBook implements DataConverter { private static class DataConverterBook implements DataConverter {
@ -1933,6 +2033,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterCookedFish implements DataConverter { private static class DataConverterCookedFish implements DataConverter {
@ -1953,6 +2054,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterZombie implements DataConverter { private static class DataConverterZombie implements DataConverter {
@ -1995,6 +2097,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
private int convert(int i) { private int convert(int i) {
return i >= 0 && i < 6 ? i : -1; return i >= 0 && i < 6 ? i : -1;
} }
} }
private static class DataConverterVBO implements DataConverter { private static class DataConverterVBO implements DataConverter {
@ -2010,6 +2113,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
cmp.putString("useVbo", "true"); cmp.putString("useVbo", "true");
return cmp; return cmp;
} }
} }
private static class DataConverterGuardian implements DataConverter { private static class DataConverterGuardian implements DataConverter {
@ -2032,6 +2136,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterSkeleton implements DataConverter { private static class DataConverterSkeleton implements DataConverter {
@ -2060,6 +2165,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterZombieType implements DataConverter { private static class DataConverterZombieType implements DataConverter {
@ -2098,6 +2204,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterHorse implements DataConverter { private static class DataConverterHorse implements DataConverter {
@ -2140,6 +2247,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterTileEntity implements DataConverter { private static class DataConverterTileEntity implements DataConverter {
@ -2302,7 +2410,8 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
public net.minecraft.nbt.CompoundTag convert(net.minecraft.nbt.CompoundTag cmp) { public net.minecraft.nbt.CompoundTag convert(net.minecraft.nbt.CompoundTag cmp) {
String s = cmp.getString("id"); String s = cmp.getString("id");
if ("minecraft:potion".equals(s) || "minecraft:splash_potion".equals(s) || "minecraft:lingering_potion".equals(s) || "minecraft:tipped_arrow".equals(s)) { if ("minecraft:potion".equals(s) || "minecraft:splash_potion".equals(s) || "minecraft:lingering_potion".equals(s) || "minecraft:tipped_arrow".equals(
s)) {
net.minecraft.nbt.CompoundTag nbttagcompound1 = cmp.getCompound("tag"); net.minecraft.nbt.CompoundTag nbttagcompound1 = cmp.getCompound("tag");
if (!nbttagcompound1.contains("Potion", 8)) { if (!nbttagcompound1.contains("Potion", 8)) {
@ -2316,6 +2425,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterShulker implements DataConverter { private static class DataConverterShulker implements DataConverter {
@ -2334,11 +2444,12 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterShulkerBoxItem implements DataConverter { private static class DataConverterShulkerBoxItem implements DataConverter {
public static final String[] a = new String[] { "minecraft:white_shulker_box", "minecraft:orange_shulker_box", "minecraft:magenta_shulker_box", "minecraft:light_blue_shulker_box", "minecraft:yellow_shulker_box", "minecraft:lime_shulker_box", "minecraft:pink_shulker_box", "minecraft:gray_shulker_box", "minecraft:silver_shulker_box", "minecraft:cyan_shulker_box", "minecraft:purple_shulker_box", "minecraft:blue_shulker_box", "minecraft:brown_shulker_box", "minecraft:green_shulker_box", "minecraft:red_shulker_box", "minecraft:black_shulker_box" }; public static final String[] a = new String[]{"minecraft:white_shulker_box", "minecraft:orange_shulker_box", "minecraft:magenta_shulker_box", "minecraft:light_blue_shulker_box", "minecraft:yellow_shulker_box", "minecraft:lime_shulker_box", "minecraft:pink_shulker_box", "minecraft:gray_shulker_box", "minecraft:silver_shulker_box", "minecraft:cyan_shulker_box", "minecraft:purple_shulker_box", "minecraft:blue_shulker_box", "minecraft:brown_shulker_box", "minecraft:green_shulker_box", "minecraft:red_shulker_box", "minecraft:black_shulker_box"};
DataConverterShulkerBoxItem() { DataConverterShulkerBoxItem() {
} }
@ -2375,6 +2486,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterShulkerBoxBlock implements DataConverter { private static class DataConverterShulkerBoxBlock implements DataConverter {
@ -2393,6 +2505,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterLang implements DataConverter { private static class DataConverterLang implements DataConverter {
@ -2411,6 +2524,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterTotem implements DataConverter { private static class DataConverterTotem implements DataConverter {
@ -2429,6 +2543,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterBedBlock implements DataConverter { private static class DataConverterBedBlock implements DataConverter {
@ -2476,6 +2591,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterBedItem implements DataConverter { private static class DataConverterBedItem implements DataConverter {
@ -2494,12 +2610,14 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataConverterSignText implements DataConverter { private static class DataConverterSignText implements DataConverter {
public static final Gson a = new GsonBuilder().registerTypeAdapter(Component.class, new JsonDeserializer() { public static final Gson a = new GsonBuilder().registerTypeAdapter(Component.class, new JsonDeserializer() {
MutableComponent a(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { MutableComponent a(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws
JsonParseException {
if (jsonelement.isJsonPrimitive()) { if (jsonelement.isJsonPrimitive()) {
return new TextComponent(jsonelement.getAsString()); return new TextComponent(jsonelement.getAsString());
} else if (jsonelement.isJsonArray()) { } else if (jsonelement.isJsonArray()) {
@ -2509,7 +2627,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
while (iterator.hasNext()) { while (iterator.hasNext()) {
JsonElement jsonelement1 = (JsonElement) iterator.next(); JsonElement jsonelement1 = (JsonElement) iterator.next();
MutableComponent ichatbasecomponent1 = this.a(jsonelement1, jsonelement1.getClass(), jsondeserializationcontext); MutableComponent ichatbasecomponent1 = this.a(
jsonelement1,
jsonelement1.getClass(),
jsondeserializationcontext
);
if (ichatbasecomponent == null) { if (ichatbasecomponent == null) {
ichatbasecomponent = ichatbasecomponent1; ichatbasecomponent = ichatbasecomponent1;
@ -2524,7 +2646,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
} }
} }
public Object deserialize(JsonElement jsonelement, Type type, JsonDeserializationContext jsondeserializationcontext) throws JsonParseException { public Object deserialize(
JsonElement jsonelement,
Type type,
JsonDeserializationContext jsondeserializationcontext
) throws JsonParseException {
return this.a(jsonelement, type, jsondeserializationcontext); return this.a(jsonelement, type, jsondeserializationcontext);
} }
}).create(); }).create();
@ -2590,9 +2716,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
nbttagcompound.putString(s, Component.Serializer.toJson(object)); nbttagcompound.putString(s, Component.Serializer.toJson(object));
} }
} }
private static class DataInspectorPlayerVehicle implements DataInspector { private static class DataInspectorPlayerVehicle implements DataInspector {
@Override @Override
public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) { public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) {
if (cmp.contains("RootVehicle", 10)) { if (cmp.contains("RootVehicle", 10)) {
@ -2605,9 +2733,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataInspectorLevelPlayer implements DataInspector { private static class DataInspectorLevelPlayer implements DataInspector {
@Override @Override
public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) { public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) {
if (cmp.contains("Player", 10)) { if (cmp.contains("Player", 10)) {
@ -2616,9 +2746,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataInspectorStructure implements DataInspector { private static class DataInspectorStructure implements DataInspector {
@Override @Override
public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) { public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) {
net.minecraft.nbt.ListTag nbttaglist; net.minecraft.nbt.ListTag nbttaglist;
@ -2649,9 +2781,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataInspectorChunks implements DataInspector { private static class DataInspectorChunks implements DataInspector {
@Override @Override
public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) { public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) {
if (cmp.contains("Level", 10)) { if (cmp.contains("Level", 10)) {
@ -2663,7 +2797,15 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
nbttaglist = nbttagcompound1.getList("Entities", 10); nbttaglist = nbttagcompound1.getList("Entities", 10);
for (j = 0; j < nbttaglist.size(); ++j) { for (j = 0; j < nbttaglist.size(); ++j) {
nbttaglist.set(j, convert(LegacyType.ENTITY, (net.minecraft.nbt.CompoundTag) nbttaglist.get(j), sourceVer, targetVer)); nbttaglist.set(
j,
convert(
LegacyType.ENTITY,
(net.minecraft.nbt.CompoundTag) nbttaglist.get(j),
sourceVer,
targetVer
)
);
} }
} }
@ -2671,16 +2813,26 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
nbttaglist = nbttagcompound1.getList("TileEntities", 10); nbttaglist = nbttagcompound1.getList("TileEntities", 10);
for (j = 0; j < nbttaglist.size(); ++j) { for (j = 0; j < nbttaglist.size(); ++j) {
nbttaglist.set(j, convert(LegacyType.BLOCK_ENTITY, (net.minecraft.nbt.CompoundTag) nbttaglist.get(j), sourceVer, targetVer)); nbttaglist.set(
j,
convert(
LegacyType.BLOCK_ENTITY,
(net.minecraft.nbt.CompoundTag) nbttaglist.get(j),
sourceVer,
targetVer
)
);
} }
} }
} }
return cmp; return cmp;
} }
} }
private static class DataInspectorEntityPassengers implements DataInspector { private static class DataInspectorEntityPassengers implements DataInspector {
@Override @Override
public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) { public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) {
if (cmp.contains("Passengers", 9)) { if (cmp.contains("Passengers", 9)) {
@ -2693,9 +2845,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataInspectorPlayer implements DataInspector { private static class DataInspectorPlayer implements DataInspector {
@Override @Override
public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) { public net.minecraft.nbt.CompoundTag inspect(net.minecraft.nbt.CompoundTag cmp, int sourceVer, int targetVer) {
convertItems(cmp, "Inventory", sourceVer, targetVer); convertItems(cmp, "Inventory", sourceVer, targetVer);
@ -2710,9 +2864,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataInspectorVillagers implements DataInspector { private static class DataInspectorVillagers implements DataInspector {
ResourceLocation entityVillager = getKey("EntityVillager"); ResourceLocation entityVillager = getKey("EntityVillager");
@Override @Override
@ -2736,9 +2892,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataInspectorMobSpawnerMinecart implements DataInspector { private static class DataInspectorMobSpawnerMinecart implements DataInspector {
ResourceLocation entityMinecartMobSpawner = getKey("EntityMinecartMobSpawner"); ResourceLocation entityMinecartMobSpawner = getKey("EntityMinecartMobSpawner");
ResourceLocation tileEntityMobSpawner = getKey("TileEntityMobSpawner"); ResourceLocation tileEntityMobSpawner = getKey("TileEntityMobSpawner");
@ -2753,9 +2911,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataInspectorMobSpawnerMobs implements DataInspector { private static class DataInspectorMobSpawnerMobs implements DataInspector {
ResourceLocation tileEntityMobSpawner = getKey("TileEntityMobSpawner"); ResourceLocation tileEntityMobSpawner = getKey("TileEntityMobSpawner");
@Override @Override
@ -2776,9 +2936,11 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
private static class DataInspectorCommandBlock implements DataInspector { private static class DataInspectorCommandBlock implements DataInspector {
ResourceLocation tileEntityCommand = getKey("TileEntityCommand"); ResourceLocation tileEntityCommand = getKey("TileEntityCommand");
@Override @Override
@ -2791,5 +2953,7 @@ class PaperweightDataConverters extends DataFixerBuilder implements com.sk89q.wo
return cmp; return cmp;
} }
} }
} }

Datei anzeigen

@ -37,7 +37,11 @@ import java.util.OptionalInt;
import java.util.UUID; import java.util.UUID;
class PaperweightFakePlayer extends ServerPlayer { class PaperweightFakePlayer extends ServerPlayer {
private static final GameProfile FAKE_WORLDEDIT_PROFILE = new GameProfile(UUID.nameUUIDFromBytes("worldedit".getBytes()), "[WorldEdit]");
private static final GameProfile FAKE_WORLDEDIT_PROFILE = new GameProfile(
UUID.nameUUIDFromBytes("worldedit".getBytes()),
"[WorldEdit]"
);
private static final Vec3 ORIGIN = new Vec3(0.0D, 0.0D, 0.0D); private static final Vec3 ORIGIN = new Vec3(0.0D, 0.0D, 0.0D);
PaperweightFakePlayer(ServerLevel world) { PaperweightFakePlayer(ServerLevel world) {
@ -95,4 +99,5 @@ class PaperweightFakePlayer extends ServerPlayer {
@Override @Override
public void openTextEdit(SignBlockEntity sign) { public void openTextEdit(SignBlockEntity sign) {
} }
} }

Datei anzeigen

@ -35,11 +35,13 @@ import org.bukkit.craftbukkit.v1_17_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_17_R1.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_17_R1.block.data.CraftBlockData;
import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPhysicsEvent;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.Objects; import java.util.Objects;
import javax.annotation.Nullable;
public class PaperweightWorldNativeAccess implements WorldNativeAccess<LevelChunk, net.minecraft.world.level.block.state.BlockState, BlockPos> { public class PaperweightWorldNativeAccess implements
WorldNativeAccess<LevelChunk, net.minecraft.world.level.block.state.BlockState, BlockPos> {
private static final int UPDATE = 1; private static final int UPDATE = 1;
private static final int NOTIFY = 2; private static final int NOTIFY = 2;
@ -81,12 +83,19 @@ public class PaperweightWorldNativeAccess implements WorldNativeAccess<LevelChun
@Nullable @Nullable
@Override @Override
public net.minecraft.world.level.block.state.BlockState setBlockState(LevelChunk chunk, BlockPos position, net.minecraft.world.level.block.state.BlockState state) { public net.minecraft.world.level.block.state.BlockState setBlockState(
LevelChunk chunk,
BlockPos position,
net.minecraft.world.level.block.state.BlockState state
) {
return chunk.setType(position, state, false, this.sideEffectSet.shouldApply(SideEffect.UPDATE)); return chunk.setType(position, state, false, this.sideEffectSet.shouldApply(SideEffect.UPDATE));
} }
@Override @Override
public net.minecraft.world.level.block.state.BlockState getValidBlockForPosition(net.minecraft.world.level.block.state.BlockState block, BlockPos position) { public net.minecraft.world.level.block.state.BlockState getValidBlockForPosition(
net.minecraft.world.level.block.state.BlockState block,
BlockPos position
) {
return Block.updateFromNeighbourShapes(block, getWorld(), position); return Block.updateFromNeighbourShapes(block, getWorld(), position);
} }
@ -106,7 +115,12 @@ public class PaperweightWorldNativeAccess implements WorldNativeAccess<LevelChun
} }
@Override @Override
public void notifyBlockUpdate(LevelChunk chunk, BlockPos position, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState) { public void notifyBlockUpdate(
LevelChunk chunk,
BlockPos position,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
if (chunk.getSections()[getWorld().getSectionIndex(position.getY())] != null) { if (chunk.getSections()[getWorld().getSectionIndex(position.getY())] != null) {
getWorld().sendBlockUpdated(position, oldState, newState, UPDATE | NOTIFY); getWorld().sendBlockUpdated(position, oldState, newState, UPDATE | NOTIFY);
} }
@ -125,7 +139,11 @@ public class PaperweightWorldNativeAccess implements WorldNativeAccess<LevelChun
} }
@Override @Override
public void notifyNeighbors(BlockPos pos, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState) { public void notifyNeighbors(
BlockPos pos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
ServerLevel world = getWorld(); ServerLevel world = getWorld();
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) { if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
world.updateNeighborsAt(pos, oldState.getBlock()); world.updateNeighborsAt(pos, oldState.getBlock());
@ -149,14 +167,22 @@ public class PaperweightWorldNativeAccess implements WorldNativeAccess<LevelChun
} }
@Override @Override
public void updateNeighbors(BlockPos pos, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState, int recursionLimit) { public void updateNeighbors(
BlockPos pos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState,
int recursionLimit
) {
ServerLevel world = getWorld(); ServerLevel world = getWorld();
// a == updateNeighbors // a == updateNeighbors
// b == updateDiagonalNeighbors // b == updateDiagonalNeighbors
oldState.updateIndirectNeighbourShapes(world, pos, NOTIFY, recursionLimit); oldState.updateIndirectNeighbourShapes(world, pos, NOTIFY, recursionLimit);
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) { if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
CraftWorld craftWorld = world.getWorld(); CraftWorld craftWorld = world.getWorld();
BlockPhysicsEvent event = new BlockPhysicsEvent(craftWorld.getBlockAt(pos.getX(), pos.getY(), pos.getZ()), CraftBlockData.fromData(newState)); BlockPhysicsEvent event = new BlockPhysicsEvent(
craftWorld.getBlockAt(pos.getX(), pos.getY(), pos.getZ()),
CraftBlockData.fromData(newState)
);
world.getCraftServer().getPluginManager().callEvent(event); world.getCraftServer().getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {
return; return;
@ -167,7 +193,11 @@ public class PaperweightWorldNativeAccess implements WorldNativeAccess<LevelChun
} }
@Override @Override
public void onBlockStateChange(BlockPos pos, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState) { public void onBlockStateChange(
BlockPos pos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
getWorld().onBlockStateChange(pos, oldState, newState); getWorld().onBlockStateChange(pos, oldState, newState);
} }

Datei anzeigen

@ -513,7 +513,10 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
@Override @Override
public org.bukkit.inventory.ItemStack adapt(BaseItemStack baseItemStack) { public org.bukkit.inventory.ItemStack adapt(BaseItemStack baseItemStack) {
ItemStack stack = new ItemStack(Registry.ITEM.get(ResourceLocation.tryParse(baseItemStack.getType().getId())), baseItemStack.getAmount()); ItemStack stack = new ItemStack(
Registry.ITEM.get(ResourceLocation.tryParse(baseItemStack.getType().getId())),
baseItemStack.getAmount()
);
stack.setTag(((net.minecraft.nbt.CompoundTag) fromNative(baseItemStack.getNbtData()))); stack.setTag(((net.minecraft.nbt.CompoundTag) fromNative(baseItemStack.getNbtData())));
return CraftItemStack.asCraftMirror(stack); return CraftItemStack.asCraftMirror(stack);
} }
@ -525,7 +528,11 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
) { ) {
TreeType bukkitType = BukkitWorld.toBukkitTreeType(treeType); TreeType bukkitType = BukkitWorld.toBukkitTreeType(treeType);
if (bukkitType == TreeType.CHORUS_PLANT) { if (bukkitType == TreeType.CHORUS_PLANT) {
blockVector3 = blockVector3.add(0, 1, 0); // bukkit skips the feature gen which does this offset normally, so we have to add it back blockVector3 = blockVector3.add(
0,
1,
0
); // bukkit skips the feature gen which does this offset normally, so we have to add it back
} }
ServerLevel serverLevel = ((CraftWorld) bukkitWorld).getHandle(); ServerLevel serverLevel = ((CraftWorld) bukkitWorld).getHandle();
serverLevel.captureTreeGeneration = true; serverLevel.captureTreeGeneration = true;

Datei anzeigen

@ -491,7 +491,8 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
existingSection = levelChunkSections[layer]; existingSection = levelChunkSections[layer];
if (existingSection == null) { if (existingSection == null) {
LOGGER.error("Skipping invalid null section. chunk: {}, {} layer: {}", chunkX, chunkZ, LOGGER.error("Skipping invalid null section. chunk: {}, {} layer: {}", chunkX, chunkZ,
+ layer); +layer
);
continue; continue;
} }
} }
@ -535,7 +536,8 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
layer layer
)) { )) {
LOGGER.error("Skipping invalid null section. chunk: {}, {} layer: {}", chunkX, chunkZ, LOGGER.error("Skipping invalid null section. chunk: {}, {} layer: {}", chunkX, chunkZ,
+ layer); +layer
);
} else { } else {
updateGet(nmsChunk, levelChunkSections, newSection, setArr, layer); updateGet(nmsChunk, levelChunkSections, newSection, setArr, layer);
} }

Datei anzeigen

@ -73,11 +73,8 @@ import org.bukkit.generator.BlockPopulator;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.io.IOException; import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;

Datei anzeigen

@ -61,7 +61,7 @@ public abstract class ChunkListener implements Listener {
TaskManager.IMP.repeat(() -> { TaskManager.IMP.repeat(() -> {
Location tmpLoc = lastCancelPos; Location tmpLoc = lastCancelPos;
if (tmpLoc != null) { if (tmpLoc != null) {
LOGGER.info("[FAWE Tick Limiter] Detected and cancelled physics lag source at {}", tmpLoc); LOGGER.info("[FAWE Tick Limiter] Detected and cancelled physics lag source at {}", tmpLoc);
} }
rateLimit--; rateLimit--;
physicsFreeze = false; physicsFreeze = false;

Datei anzeigen

@ -7,7 +7,6 @@ import com.fastasyncworldedit.core.regions.FaweMaskManager;
import com.fastasyncworldedit.core.regions.filter.RegionFilter; import com.fastasyncworldedit.core.regions.filter.RegionFilter;
import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler;
import com.plotsquared.core.PlotSquared; import com.plotsquared.core.PlotSquared;
import com.plotsquared.core.command.MainCommand;
import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.configuration.Settings;
import com.plotsquared.core.database.DBFunc; import com.plotsquared.core.database.DBFunc;
import com.plotsquared.core.player.PlotPlayer; import com.plotsquared.core.player.PlotPlayer;

Datei anzeigen

@ -16,7 +16,7 @@ import javax.xml.parsers.DocumentBuilderFactory;
import java.net.URL; import java.net.URL;
/** /**
* @hidden *
*/ */
public class UpdateNotification { public class UpdateNotification {

Datei anzeigen

@ -23,6 +23,7 @@ package com.sk89q.worldedit.bukkit.adapter;
* Reflection helper to deal with obfuscation. * Reflection helper to deal with obfuscation.
*/ */
public class Refraction { public class Refraction {
private static final String MOJANG_MAPPED_CLASS_NAME = "net.minecraft.nbt.ListTag"; private static final String MOJANG_MAPPED_CLASS_NAME = "net.minecraft.nbt.ListTag";
private static final boolean IS_MOJANG_MAPPED; private static final boolean IS_MOJANG_MAPPED;
@ -43,4 +44,5 @@ public class Refraction {
private Refraction() { private Refraction() {
} }
} }

Datei anzeigen

@ -911,8 +911,7 @@ public class StubServer implements Server {
} }
@Override @Override
public @NotNull public @NotNull <T extends Keyed> Iterable<Tag<T>> getTags(@NotNull String s, @NotNull Class<T> aClass) {
<T extends Keyed> Iterable<Tag<T>> getTags(@NotNull String s, @NotNull Class<T> aClass) {
return null; return null;
} }

Datei anzeigen

@ -2,8 +2,6 @@ package com.fastasyncworldedit.core;
/** /**
* An internal FAWE class not meant for public use. * An internal FAWE class not meant for public use.
*
* @hidden
**/ **/
public class FaweVersion { public class FaweVersion {

Datei anzeigen

@ -3,7 +3,6 @@ package com.fastasyncworldedit.core.command.tool.brush;
import com.fastasyncworldedit.core.FaweCache; import com.fastasyncworldedit.core.FaweCache;
import com.fastasyncworldedit.core.command.tool.ResettableTool; import com.fastasyncworldedit.core.command.tool.ResettableTool;
import com.fastasyncworldedit.core.configuration.Caption; import com.fastasyncworldedit.core.configuration.Caption;
import com.fastasyncworldedit.core.internal.exception.FaweException;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.MaxChangedBlocksException; import com.sk89q.worldedit.MaxChangedBlocksException;
import com.sk89q.worldedit.command.tool.brush.Brush; import com.sk89q.worldedit.command.tool.brush.Brush;

Datei anzeigen

@ -331,7 +331,7 @@ public class Config {
/** /**
* Get the field for a specific config node and instance. * Get the field for a specific config node and instance.
* * <p>
* As expiry can have multiple blocks there will be multiple instances * As expiry can have multiple blocks there will be multiple instances
* *
* @param split the node (split by period) * @param split the node (split by period)

Datei anzeigen

@ -228,6 +228,7 @@ public class Settings extends Config {
" - \"extended[true:false]\"" " - \"extended[true:false]\""
}) })
public List<String> REMAP_PROPERTIES = new ArrayList<>(); public List<String> REMAP_PROPERTIES = new ArrayList<>();
} }
public static class HISTORY { public static class HISTORY {

Datei anzeigen

@ -154,7 +154,7 @@ public class DisallowedBlocksExtent extends AbstractDelegateExtent implements IB
} }
} }
if (remaps == null || remaps.isEmpty()) { if (remaps == null || remaps.isEmpty()) {
blocks[i] = block; blocks[i] = block;
continue; continue;
} }
for (PropertyRemap<?> remap : remaps) { for (PropertyRemap<?> remap : remaps) {

Datei anzeigen

@ -5,7 +5,6 @@ import com.fastasyncworldedit.core.configuration.Caption;
import com.fastasyncworldedit.core.util.MemUtil; import com.fastasyncworldedit.core.util.MemUtil;
import com.fastasyncworldedit.core.util.Permission; import com.fastasyncworldedit.core.util.Permission;
import com.fastasyncworldedit.core.util.WEManager; import com.fastasyncworldedit.core.util.WEManager;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;

Datei anzeigen

@ -12,6 +12,7 @@ public abstract class SimpleClipboard implements Clipboard {
private final int volume; private final int volume;
private BlockVector3 offset; private BlockVector3 offset;
private BlockVector3 origin; private BlockVector3 origin;
SimpleClipboard(BlockVector3 dimensions, BlockVector3 offset) { SimpleClipboard(BlockVector3 dimensions, BlockVector3 offset) {
this.size = dimensions; this.size = dimensions;
this.offset = offset; this.offset = offset;

Datei anzeigen

@ -2,7 +2,6 @@ package com.fastasyncworldedit.core.history.changeset;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extent.inventory.BlockBag; import com.sk89q.worldedit.extent.inventory.BlockBag;
import com.sk89q.worldedit.history.change.BlockChange; import com.sk89q.worldedit.history.change.BlockChange;

Datei anzeigen

@ -6,7 +6,6 @@ import java.lang.reflect.Field;
/** /**
* This is an internal class not meant to be used outside the FAWE internals. * This is an internal class not meant to be used outside the FAWE internals.
* @hidden
*/ */
public class UnsafeUtility { public class UnsafeUtility {

Datei anzeigen

@ -45,12 +45,12 @@ import com.fastasyncworldedit.core.function.pattern.ExistingPattern;
import com.fastasyncworldedit.core.function.visitor.DirectionalVisitor; import com.fastasyncworldedit.core.function.visitor.DirectionalVisitor;
import com.fastasyncworldedit.core.history.changeset.AbstractChangeSet; import com.fastasyncworldedit.core.history.changeset.AbstractChangeSet;
import com.fastasyncworldedit.core.history.changeset.BlockBagChangeSet; import com.fastasyncworldedit.core.history.changeset.BlockBagChangeSet;
import com.fastasyncworldedit.core.limit.FaweLimit;
import com.fastasyncworldedit.core.math.LocalBlockVectorSet; import com.fastasyncworldedit.core.math.LocalBlockVectorSet;
import com.fastasyncworldedit.core.math.MutableBlockVector2; import com.fastasyncworldedit.core.math.MutableBlockVector2;
import com.fastasyncworldedit.core.math.MutableBlockVector3; import com.fastasyncworldedit.core.math.MutableBlockVector3;
import com.fastasyncworldedit.core.math.MutableVector3; import com.fastasyncworldedit.core.math.MutableVector3;
import com.fastasyncworldedit.core.math.random.SimplexNoise; import com.fastasyncworldedit.core.math.random.SimplexNoise;
import com.fastasyncworldedit.core.limit.FaweLimit;
import com.fastasyncworldedit.core.queue.implementation.preloader.Preloader; import com.fastasyncworldedit.core.queue.implementation.preloader.Preloader;
import com.fastasyncworldedit.core.regions.RegionWrapper; import com.fastasyncworldedit.core.regions.RegionWrapper;
import com.fastasyncworldedit.core.util.ExtentTraverser; import com.fastasyncworldedit.core.util.ExtentTraverser;

Datei anzeigen

@ -52,9 +52,9 @@ import com.fastasyncworldedit.core.configuration.Settings;
import com.fastasyncworldedit.core.extent.clipboard.MultiClipboardHolder; import com.fastasyncworldedit.core.extent.clipboard.MultiClipboardHolder;
import com.fastasyncworldedit.core.function.mask.IdMask; import com.fastasyncworldedit.core.function.mask.IdMask;
import com.fastasyncworldedit.core.function.mask.SingleBlockTypeMask; import com.fastasyncworldedit.core.function.mask.SingleBlockTypeMask;
import com.fastasyncworldedit.core.limit.FaweLimit;
import com.fastasyncworldedit.core.math.heightmap.ScalableHeightMap; import com.fastasyncworldedit.core.math.heightmap.ScalableHeightMap;
import com.fastasyncworldedit.core.math.heightmap.ScalableHeightMap.Shape; import com.fastasyncworldedit.core.math.heightmap.ScalableHeightMap.Shape;
import com.fastasyncworldedit.core.limit.FaweLimit;
import com.fastasyncworldedit.core.util.MainUtil; import com.fastasyncworldedit.core.util.MainUtil;
import com.fastasyncworldedit.core.util.MathMan; import com.fastasyncworldedit.core.util.MathMan;
import com.fastasyncworldedit.core.util.StringMan; import com.fastasyncworldedit.core.util.StringMan;

Datei anzeigen

@ -39,7 +39,6 @@ import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.formatting.component.PaginationBox; import com.sk89q.worldedit.util.formatting.component.PaginationBox;
import com.sk89q.worldedit.util.formatting.text.Component; import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TextComponent; import com.sk89q.worldedit.util.formatting.text.TextComponent;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import com.sk89q.worldedit.util.formatting.text.event.ClickEvent; import com.sk89q.worldedit.util.formatting.text.event.ClickEvent;
import com.sk89q.worldedit.util.formatting.text.format.TextColor; import com.sk89q.worldedit.util.formatting.text.format.TextColor;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;

Datei anzeigen

@ -36,7 +36,6 @@ import com.sk89q.worldedit.command.argument.Arguments;
import com.sk89q.worldedit.command.util.AsyncCommandBuilder; import com.sk89q.worldedit.command.util.AsyncCommandBuilder;
import com.sk89q.worldedit.command.util.CommandPermissions; import com.sk89q.worldedit.command.util.CommandPermissions;
import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator; import com.sk89q.worldedit.command.util.CommandPermissionsConditionGenerator;
import com.sk89q.worldedit.entity.Player;
import com.sk89q.worldedit.extension.platform.Actor; import com.sk89q.worldedit.extension.platform.Actor;
import com.sk89q.worldedit.extension.platform.Capability; import com.sk89q.worldedit.extension.platform.Capability;
import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard;

Datei anzeigen

@ -513,15 +513,20 @@ public class DefaultBlockParser extends InputParser<BaseBlock> {
if (actor != null) { if (actor != null) {
if (!actor.hasPermission("worldedit.anyblock") if (!actor.hasPermission("worldedit.anyblock")
&& worldEdit.getConfiguration().disallowedBlocks.contains(blockType.getId().toLowerCase(Locale.ROOT))) { && worldEdit.getConfiguration().disallowedBlocks.contains(blockType.getId().toLowerCase(Locale.ROOT))) {
throw new DisallowedUsageException(Caption.of("worldedit.error.disallowed-block", TextComponent.of(blockType.getId()))); throw new DisallowedUsageException(Caption.of(
"worldedit.error.disallowed-block",
TextComponent.of(blockType.getId())
));
} }
FaweLimit limit = actor.getLimit(); FaweLimit limit = actor.getLimit();
if (!limit.isUnlimited()) { if (!limit.isUnlimited()) {
// No need to account for blocked states/properties as it will simply return false in the equality check // No need to account for blocked states/properties as it will simply return false in the equality check
// during contains. // during contains.
if (limit.DISALLOWED_BLOCKS.contains(blockType.getId().toLowerCase(Locale.ROOT))) { if (limit.DISALLOWED_BLOCKS.contains(blockType.getId().toLowerCase(Locale.ROOT))) {
throw new DisallowedUsageException(Caption.of("fawe.error.limit.disallowed-block", throw new DisallowedUsageException(Caption.of(
TextComponent.of(blockType.getId()))); "fawe.error.limit.disallowed-block",
TextComponent.of(blockType.getId())
));
} }
} }
} }

Datei anzeigen

@ -159,9 +159,9 @@ public class CraftScriptContext extends CraftScriptEnvironment {
/** /**
* Immediately terminate execution of the script, but without a failure message. * Immediately terminate execution of the script, but without a failure message.
* * <p>
* This exits by throwing an exception, which if caught will prevent * This exits by throwing an exception, which if caught will prevent
* the script from exiting * the script from exiting
*/ */
public void exit() { public void exit() {
throw new ReturnException(null); throw new ReturnException(null);

Datei anzeigen

@ -344,7 +344,10 @@ public class BlockState implements BlockStateHolder<BlockState>, Pattern {
//FAWE end //FAWE end
BlockType type = this.getBlockType(); BlockType type = this.getBlockType();
// Lazily initialize the map // Lazily initialize the map
Map<? extends Property<?>, Object> map = Maps.asMap(type.getPropertiesSet(), (Function<Property<?>, Object>) this::getState); Map<? extends Property<?>, Object> map = Maps.asMap(
type.getPropertiesSet(),
(Function<Property<?>, Object>) this::getState
);
//noinspection RedundantCast - This is required for compilation, etc. //noinspection RedundantCast - This is required for compilation, etc.
return Collections.unmodifiableMap((Map<Property<?>, Object>) map); return Collections.unmodifiableMap((Map<Property<?>, Object>) map);
//FAWE end //FAWE end

Datei anzeigen

@ -166,8 +166,8 @@ public interface BlockStateHolder<B extends BlockStateHolder<B>> extends TileEnt
* *
* @param compoundTag The NBT Data to apply * @param compoundTag The NBT Data to apply
* @return The BaseBlock * @return The BaseBlock
* This must be overridden by new subclasses. See {@link NonAbstractForCompatibility} * This must be overridden by new subclasses. See {@link NonAbstractForCompatibility}
* for details * for details
*/ */
@NonAbstractForCompatibility( @NonAbstractForCompatibility(
delegateName = "toBaseBlock", delegateName = "toBaseBlock",

Datei anzeigen

@ -20,16 +20,13 @@
package com.sk89q.worldedit.world.chunk; package com.sk89q.worldedit.world.chunk;
import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.entity.Entity;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.world.DataException; import com.sk89q.worldedit.world.DataException;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* A 16 by 16 block chunk. * A 16 by 16 block chunk.
@ -46,6 +43,7 @@ public interface Chunk {
BaseBlock getBlock(BlockVector3 position) throws DataException; BaseBlock getBlock(BlockVector3 position) throws DataException;
//FAWE start - biome and entity restore //FAWE start - biome and entity restore
/** /**
* Get a biome. * Get a biome.
* *
@ -59,6 +57,7 @@ public interface Chunk {
/** /**
* Get the stored entities. * Get the stored entities.
*
* @return list of stored entities * @return list of stored entities
*/ */
default List<BaseEntity> getEntities() throws DataException { default List<BaseEntity> getEntities() throws DataException {

Datei anzeigen

@ -149,8 +149,10 @@ public final class LegacyMapper {
// if it's still null, both fixer and default failed // if it's still null, both fixer and default failed
if (state == null) { if (state == null) {
LOGGER.error("Unknown block: {}. Neither the DataFixer nor defaulting worked to recognize this block.", LOGGER.error(
value); "Unknown block: {}. Neither the DataFixer nor defaulting worked to recognize this block.",
value
);
} else { } else {
// it's not null so one of them succeeded, now use it // it's not null so one of them succeeded, now use it
blockToStringMap.put(state, id); blockToStringMap.put(state, id);

Datei anzeigen

@ -28,8 +28,6 @@ import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.Location; import com.sk89q.worldedit.util.Location;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.BinaryTagTypes;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag; import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.ListBinaryTag; import com.sk89q.worldedit.util.nbt.ListBinaryTag;
import com.sk89q.worldedit.world.DataException; import com.sk89q.worldedit.world.DataException;

Datei anzeigen

@ -87,6 +87,7 @@ public abstract class ChunkStore implements Closeable {
public abstract CompoundTag getChunkTag(BlockVector2 position, World world) throws DataException, IOException; public abstract CompoundTag getChunkTag(BlockVector2 position, World world) throws DataException, IOException;
//FAWE start - biome and entity restore //FAWE start - biome and entity restore
/** /**
* Get the tag for the entities stored in a chunk from the entities folder. 1.17+ use only. * Get the tag for the entities stored in a chunk from the entities folder. 1.17+ use only.
* If an error occurs, returns null. * If an error occurs, returns null.

Datei-Diff unterdrückt, da er zu groß ist Diff laden

Datei anzeigen

@ -147,7 +147,7 @@ public class CommandContextTest {
public void testSlice() { public void testSlice() {
try { try {
CommandContext context = new CommandContext("foo bar baz"); CommandContext context = new CommandContext("foo bar baz");
assertArrayEquals(new String[] { "foo", "bar", "baz" }, context.getSlice(0)); assertArrayEquals(new String[]{"foo", "bar", "baz"}, context.getSlice(0));
} catch (CommandException e) { } catch (CommandException e) {
LOGGER.warn("Error", e); LOGGER.warn("Error", e);
@ -165,4 +165,5 @@ public class CommandContextTest {
fail("Error creating CommandContext"); fail("Error creating CommandContext");
} }
} }
} }

Datei anzeigen

@ -37,22 +37,23 @@ class CommandArgParserTest {
@Test @Test
void testArgumentParsing() { void testArgumentParsing() {
assertEquals(ImmutableList.of( assertEquals(ImmutableList.of(
Substring.wrap("", 0, 0) Substring.wrap("", 0, 0)
), argParse("")); ), argParse(""));
assertEquals(ImmutableList.of( assertEquals(ImmutableList.of(
Substring.wrap("ab", 0, 2) Substring.wrap("ab", 0, 2)
), argParse("ab")); ), argParse("ab"));
assertEquals(ImmutableList.of( assertEquals(ImmutableList.of(
Substring.wrap("", 0, 0), Substring.wrap("", 0, 0),
Substring.wrap("", 1, 1) Substring.wrap("", 1, 1)
), argParse(" ")); ), argParse(" "));
assertEquals(ImmutableList.of( assertEquals(ImmutableList.of(
Substring.wrap("a", 0, 1), Substring.wrap("a", 0, 1),
Substring.wrap("", 2, 2) Substring.wrap("", 2, 2)
), argParse("a ")); ), argParse("a "));
assertEquals(ImmutableList.of( assertEquals(ImmutableList.of(
Substring.wrap("a", 0, 1), Substring.wrap("a", 0, 1),
Substring.wrap("b", 2, 3) Substring.wrap("b", 2, 3)
), argParse("a b")); ), argParse("a b"));
} }
} }

Datei anzeigen

@ -122,4 +122,5 @@ class BaseExpressionTest {
expression.optimize(); expression.optimize();
return expression; return expression;
} }
} }

Datei anzeigen

@ -42,39 +42,39 @@ class ExpressionTest extends BaseExpressionTest {
@TestFactory @TestFactory
public Stream<DynamicNode> testEvaluate() throws ExpressionException { public Stream<DynamicNode> testEvaluate() throws ExpressionException {
List<ExpressionTestCase> testCases = ImmutableList.of( List<ExpressionTestCase> testCases = ImmutableList.of(
// basic arithmetic // basic arithmetic
testCase("1 - 2 + 3", 2), testCase("1 - 2 + 3", 2),
// unary ops // unary ops
testCase("2 + +4", 6), testCase("2 + +4", 6),
testCase("2 - -4", 6), testCase("2 - -4", 6),
testCase("2 * -4", -8), testCase("2 * -4", -8),
// check functions // check functions
testCase("sin(5)", sin(5)), testCase("sin(5)", sin(5)),
testCase("atan2(3, 4)", atan2(3, 4)), testCase("atan2(3, 4)", atan2(3, 4)),
testCase("min(1, 2)", 1), testCase("min(1, 2)", 1),
testCase("max(1, 2)", 2), testCase("max(1, 2)", 2),
testCase("max(1, 2, 3, 4, 5)", 5), testCase("max(1, 2, 3, 4, 5)", 5),
// check conditionals // check conditionals
testCase("0 || 5", 5), testCase("0 || 5", 5),
testCase("2 || 5", 2), testCase("2 || 5", 2),
testCase("2 && 5", 5), testCase("2 && 5", 5),
testCase("5 && 0", 0), testCase("5 && 0", 0),
// check ternaries // check ternaries
testCase("false ? 1 : 2", 2), testCase("false ? 1 : 2", 2),
testCase("true ? 1 : 2", 1), testCase("true ? 1 : 2", 1),
// - ternary binds inside // - ternary binds inside
testCase("true ? true ? 1 : 2 : 3", 1), testCase("true ? true ? 1 : 2 : 3", 1),
testCase("true ? false ? 1 : 2 : 3", 2), testCase("true ? false ? 1 : 2 : 3", 2),
testCase("false ? true ? 1 : 2 : 3", 3), testCase("false ? true ? 1 : 2 : 3", 3),
testCase("false ? false ? 1 : 2 : 3", 3), testCase("false ? false ? 1 : 2 : 3", 3),
// check return // check return
testCase("return 1; 0", 1) testCase("return 1; 0", 1)
); );
return testCases.stream() return testCases.stream()
.map(testCase -> dynamicTest( .map(testCase -> dynamicTest(
testCase.getExpression(), testCase.getExpression(),
() -> checkTestCase(testCase) () -> checkTestCase(testCase)
)); ));
} }
@Test @Test
@ -82,8 +82,10 @@ class ExpressionTest extends BaseExpressionTest {
assertEquals(8, compile("foo+bar", "foo", "bar").evaluate(5D, 3D), 0); assertEquals(8, compile("foo+bar", "foo", "bar").evaluate(5D, 3D), 0);
// variables need to be assigned first // variables need to be assigned first
EvaluationException ex = assertThrows(EvaluationException.class, EvaluationException ex = assertThrows(
() -> simpleEval("a*=5")); EvaluationException.class,
() -> simpleEval("a*=5")
);
assertTrue(ex.getMessage().contains("not initialized yet")); assertTrue(ex.getMessage().contains("not initialized yet"));
// can't modify e, pi, true, false // can't modify e, pi, true, false
@ -93,11 +95,11 @@ class ExpressionTest extends BaseExpressionTest {
@TestFactory @TestFactory
Stream<DynamicNode> testModifyConstants() { Stream<DynamicNode> testModifyConstants() {
return Stream.of("e", "pi", "true", "false").map(constant -> return Stream.of("e", "pi", "true", "false").map(constant ->
dynamicTest(constant, () -> { dynamicTest(constant, () -> {
EvaluationException ex = assertThrows(EvaluationException.class, () -> EvaluationException ex = assertThrows(EvaluationException.class, () ->
simpleEval(constant + "++")); simpleEval(constant + "++"));
assertTrue(ex.getMessage().endsWith("'" + constant + "' is not a variable")); assertTrue(ex.getMessage().endsWith("'" + constant + "' is not a variable"));
})); }));
} }
@Test @Test
@ -214,45 +216,63 @@ class ExpressionTest extends BaseExpressionTest {
public void testErrors() { public void testErrors() {
// test lexer errors // test lexer errors
{ {
ExpressionException e = assertThrows(ExpressionException.class, ExpressionException e = assertThrows(
() -> compile("#")); ExpressionException.class,
() -> compile("#")
);
assertEquals(0, e.getPosition(), "Error position"); assertEquals(0, e.getPosition(), "Error position");
} }
// test parser errors // test parser errors
{ {
ExpressionException e = assertThrows(ExpressionException.class, ExpressionException e = assertThrows(
() -> compile("x")); ExpressionException.class,
() -> compile("x")
);
assertEquals(0, e.getPosition(), "Error position"); assertEquals(0, e.getPosition(), "Error position");
} }
{ {
ExpressionException e = assertThrows(ExpressionException.class, ExpressionException e = assertThrows(
() -> compile("x()")); ExpressionException.class,
() -> compile("x()")
);
assertEquals(0, e.getPosition(), "Error position"); assertEquals(0, e.getPosition(), "Error position");
} }
{ {
// verify that you must return a value // verify that you must return a value
ExpressionException e = assertThrows(ExpressionException.class, ExpressionException e = assertThrows(
() -> compile("return")); ExpressionException.class,
() -> compile("return")
);
assertEquals(6, e.getPosition(), "Error position"); assertEquals(6, e.getPosition(), "Error position");
} }
assertThrows(ExpressionException.class, assertThrows(
() -> compile("(")); ExpressionException.class,
assertThrows(ExpressionException.class, () -> compile("(")
() -> compile("x(")); );
assertThrows(
ExpressionException.class,
() -> compile("x(")
);
// test overloader errors // test overloader errors
{ {
ExpressionException e = assertThrows(ExpressionException.class, ExpressionException e = assertThrows(
() -> compile("atan2(1)")); ExpressionException.class,
() -> compile("atan2(1)")
);
assertEquals(0, e.getPosition(), "Error position"); assertEquals(0, e.getPosition(), "Error position");
} }
{ {
ExpressionException e = assertThrows(ExpressionException.class, ExpressionException e = assertThrows(
() -> compile("atan2(1, 2, 3)")); ExpressionException.class,
() -> compile("atan2(1, 2, 3)")
);
assertEquals(0, e.getPosition(), "Error position"); assertEquals(0, e.getPosition(), "Error position");
} }
{ {
ExpressionException e = assertThrows(ExpressionException.class, ExpressionException e = assertThrows(
() -> compile("rotate(1, 2, 3)")); ExpressionException.class,
() -> compile("rotate(1, 2, 3)")
);
assertEquals(7, e.getPosition(), "Error position"); assertEquals(7, e.getPosition(), "Error position");
} }
@ -289,41 +309,41 @@ class ExpressionTest extends BaseExpressionTest {
checkTestCase("c=5; a=0; while (c > 0) { ++a; --c; } a", 5); checkTestCase("c=5; a=0; while (c > 0) { ++a; --c; } a", 5);
checkTestCase("c=5; a=0; do { ++a; --c; } while (c > 0); a", 5); checkTestCase("c=5; a=0; do { ++a; --c; } while (c > 0); a", 5);
checkTestCase("" + checkTestCase("" +
"c=5;" + "c=5;" +
"a=0;" + "a=0;" +
"while (c > 0) {" + "while (c > 0) {" +
" ++a;" + " ++a;" +
" --c;" + " --c;" +
" if (c == 1) break;" + " if (c == 1) break;" +
"}" + "}" +
"a", 4); "a", 4);
checkTestCase("" + checkTestCase("" +
"c=5;" + "c=5;" +
"a=0;" + "a=0;" +
"while (c > 0) {" + "while (c > 0) {" +
" ++a;" + " ++a;" +
" if (a < 5) continue;" + " if (a < 5) continue;" +
" --c;" + " --c;" +
"}" + "}" +
"a", 9); "a", 9);
checkTestCase("" + checkTestCase("" +
"c=5;" + "c=5;" +
"a=0;" + "a=0;" +
"do {" + "do {" +
" ++a;" + " ++a;" +
" --c;" + " --c;" +
" if (c == 1) break;" + " if (c == 1) break;" +
"} while (c > 0);" + "} while (c > 0);" +
"a", 4); "a", 4);
checkTestCase("" + checkTestCase("" +
"c=5;" + "c=5;" +
"a=0;" + "a=0;" +
"do {" + "do {" +
" ++a;" + " ++a;" +
" if (a < 5) continue;" + " if (a < 5) continue;" +
" --c;" + " --c;" +
"} while (c > 0);" + "} while (c > 0);" +
"a", 9); "a", 9);
} }
@Test @Test
@ -331,33 +351,33 @@ class ExpressionTest extends BaseExpressionTest {
checkTestCase("a=0; for (i=0; i<5; ++i) { ++a; } a", 5); checkTestCase("a=0; for (i=0; i<5; ++i) { ++a; } a", 5);
checkTestCase("y=0; for (i=1,5) { y *= 10; y += i; } y", 12345); checkTestCase("y=0; for (i=1,5) { y *= 10; y += i; } y", 12345);
checkTestCase("" + checkTestCase("" +
"a=0;" + "a=0;" +
"for (c = 5; c > 0; c--) {" + "for (c = 5; c > 0; c--) {" +
" ++a;" + " ++a;" +
" if (c == 2) break;" + " if (c == 2) break;" +
"}" + "}" +
"a", 4); "a", 4);
checkTestCase("" + checkTestCase("" +
"a=0;" + "a=0;" +
"for (c = 5; c > 0; c--) {" + "for (c = 5; c > 0; c--) {" +
" if (a > 1) continue;" + " if (a > 1) continue;" +
" ++a;" + " ++a;" +
"}" + "}" +
"a", 2); "a", 2);
checkTestCase("" + checkTestCase("" +
"a=0;" + "a=0;" +
"for (c = 1,5) {" + "for (c = 1,5) {" +
" ++a;" + " ++a;" +
" if (c == 4) break;" + " if (c == 4) break;" +
"}" + "}" +
"a", 4); "a", 4);
checkTestCase("" + checkTestCase("" +
"a=0;" + "a=0;" +
"for (c = 1,5) {" + "for (c = 1,5) {" +
" if (a > 1) continue;" + " if (a > 1) continue;" +
" ++a;" + " ++a;" +
"}" + "}" +
"a", 2); "a", 2);
} }
@Test @Test
@ -375,33 +395,33 @@ class ExpressionTest extends BaseExpressionTest {
// try to continue in a switch :P // try to continue in a switch :P
{ {
EvaluationException ex = assertThrows(EvaluationException.class, () -> simpleEval("" + EvaluationException ex = assertThrows(EvaluationException.class, () -> simpleEval("" +
"switch(1) {" + "switch(1) {" +
" case 1: continue;" + " case 1: continue;" +
"}")); "}"));
assertTrue(ex.getMessage().contains("continue in a switch")); assertTrue(ex.getMessage().contains("continue in a switch"));
} }
{ {
EvaluationException ex = assertThrows(EvaluationException.class, () -> simpleEval("" + EvaluationException ex = assertThrows(EvaluationException.class, () -> simpleEval("" +
"switch(1) {" + "switch(1) {" +
" default: continue;" + " default: continue;" +
"}")); "}"));
assertTrue(ex.getMessage().contains("continue in a switch")); assertTrue(ex.getMessage().contains("continue in a switch"));
} }
// duplicate case checks // duplicate case checks
{ {
EvaluationException ex = assertThrows(EvaluationException.class, () -> simpleEval("" + EvaluationException ex = assertThrows(EvaluationException.class, () -> simpleEval("" +
"switch(1) {" + "switch(1) {" +
" case 1: 1;" + " case 1: 1;" +
" case 1: 1;" + " case 1: 1;" +
"}")); "}"));
assertTrue(ex.getMessage().contains("Duplicate cases")); assertTrue(ex.getMessage().contains("Duplicate cases"));
} }
{ {
EvaluationException ex = assertThrows(EvaluationException.class, () -> simpleEval("" + EvaluationException ex = assertThrows(EvaluationException.class, () -> simpleEval("" +
"switch(1) {" + "switch(1) {" +
" default: 1;" + " default: 1;" +
" default: 1;" + " default: 1;" +
"}")); "}"));
assertTrue(ex.getMessage().contains("Duplicate default cases")); assertTrue(ex.getMessage().contains("Duplicate default cases"));
} }
} }
@ -420,9 +440,11 @@ class ExpressionTest extends BaseExpressionTest {
@Test @Test
public void testTimeout() { public void testTimeout() {
ExpressionTimeoutException e = assertTimeoutPreemptively(Duration.ofSeconds(10), () -> ExpressionTimeoutException e = assertTimeoutPreemptively(Duration.ofSeconds(10), () ->
assertThrows(ExpressionTimeoutException.class, assertThrows(
() -> simpleEval("for(i=0;i<256;i++){for(j=0;j<256;j++){for(k=0;k<256;k++){for(l=0;l<256;l++){ln(pi)}}}}"), ExpressionTimeoutException.class,
"Loop was not stopped.") () -> simpleEval("for(i=0;i<256;i++){for(j=0;j<256;j++){for(k=0;k<256;k++){for(l=0;l<256;l++){ln(pi)}}}}"),
"Loop was not stopped."
)
); );
assertTrue(e.getMessage().contains("Calculations exceeded time limit")); assertTrue(e.getMessage().contains("Calculations exceeded time limit"));
} }

Datei anzeigen

@ -45,4 +45,5 @@ public class ExpressionTestCase {
public String toString() { public String toString() {
return expression + " -> " + result; return expression + " -> " + result;
} }
} }

Datei anzeigen

@ -49,7 +49,8 @@ class RealExpressionTest extends BaseExpressionTest {
postChecks.accept(expr); postChecks.accept(expr);
double data = readSlot(expr, "data"); double data = readSlot(expr, "data");
assertEquals(expectedData, (int) data, assertEquals(expectedData, (int) data,
"Test case " + this + " failed (data)"); "Test case " + this + " failed (data)"
);
}); });
} }
@ -57,6 +58,7 @@ class RealExpressionTest extends BaseExpressionTest {
public String toString() { public String toString() {
return loc + " -> " + result; return loc + " -> " + result;
} }
} }
private static TestCase testCase(Vector3 loc, double result) { private static TestCase testCase(Vector3 loc, double result) {
@ -73,44 +75,51 @@ class RealExpressionTest extends BaseExpressionTest {
for (TestCase aCase : cases) { for (TestCase aCase : cases) {
Vector3 loc = aCase.loc; Vector3 loc = aCase.loc;
assertEquals(aCase.result, compiled.evaluate(loc.getX(), loc.getY(), loc.getZ()), 0, assertEquals(aCase.result, compiled.evaluate(loc.getX(), loc.getY(), loc.getZ()), 0,
"Test case " + aCase + " failed (result)"); "Test case " + aCase + " failed (result)"
);
aCase.postChecks.accept(compiled); aCase.postChecks.accept(compiled);
} }
} }
@Test @Test
void torus() { void torus() {
checkExpression("(0.75-sqrt(x^2+y^2))^2+z^2 < 0.25^2", checkExpression(
testCase(Vector3.at(0, 0, 0), 0), "(0.75-sqrt(x^2+y^2))^2+z^2 < 0.25^2",
testCase(Vector3.at(0.5, 0.5, 0.5), 0), testCase(Vector3.at(0, 0, 0), 0),
testCase(Vector3.at(1, 0, 0), 0), testCase(Vector3.at(0.5, 0.5, 0.5), 0),
testCase(Vector3.at(0.5, 0.5, 0), 1), testCase(Vector3.at(1, 0, 0), 0),
testCase(Vector3.at(0.75, 0.5, 0), 1), testCase(Vector3.at(0.5, 0.5, 0), 1),
testCase(Vector3.at(0.75, 0, 0), 1)); testCase(Vector3.at(0.75, 0.5, 0), 1),
testCase(Vector3.at(0.75, 0, 0), 1)
);
} }
@Test @Test
void gnarledOakTree() { void gnarledOakTree() {
checkExpression("(0.5+sin(atan2(x,z)*8)*0.2)*(sqrt(x*x+z*z)/0.5)^(-2)-1.2 < y", checkExpression(
testCase(Vector3.at(-1, -1, -1), 1), "(0.5+sin(atan2(x,z)*8)*0.2)*(sqrt(x*x+z*z)/0.5)^(-2)-1.2 < y",
testCase(Vector3.at(-1, 0, 1), 1), testCase(Vector3.at(-1, -1, -1), 1),
testCase(Vector3.at(1, 1, 1), 1), testCase(Vector3.at(-1, 0, 1), 1),
testCase(Vector3.at(0, 0, -1), 1), testCase(Vector3.at(1, 1, 1), 1),
testCase(Vector3.at(0, 0, 0), 0), testCase(Vector3.at(0, 0, -1), 1),
testCase(Vector3.at(0, 1, 0), 0), testCase(Vector3.at(0, 0, 0), 0),
testCase(Vector3.at(0, 0, 0.32274), 0), testCase(Vector3.at(0, 1, 0), 0),
testCase(Vector3.at(0, 0, 0.32275), 1)); testCase(Vector3.at(0, 0, 0.32274), 0),
testCase(Vector3.at(0, 0, 0.32275), 1)
);
} }
@Test @Test
void rainbowTorus() { void rainbowTorus() {
checkExpression("data=(32+15/2/pi*atan2(x,y))%16; (0.75-sqrt(x^2+y^2))^2+z^2 < 0.25^2", checkExpression(
testCase(Vector3.at(0, 0, 0), 0), "data=(32+15/2/pi*atan2(x,y))%16; (0.75-sqrt(x^2+y^2))^2+z^2 < 0.25^2",
testCase(Vector3.at(0.5, 0.5, 0.5), 0), testCase(Vector3.at(0, 0, 0), 0),
testCase(Vector3.at(1, 0, 0), 0), testCase(Vector3.at(0.5, 0.5, 0.5), 0),
testCase(Vector3.at(0.5, 0.5, 0), 1).withData(1), testCase(Vector3.at(1, 0, 0), 0),
testCase(Vector3.at(0.75, 0.5, 0), 1).withData(2), testCase(Vector3.at(0.5, 0.5, 0), 1).withData(1),
testCase(Vector3.at(0.75, 0, 0), 1).withData(3)); testCase(Vector3.at(0.75, 0.5, 0), 1).withData(2),
testCase(Vector3.at(0.75, 0, 0), 1).withData(3)
);
} }
@Test @Test
@ -118,53 +127,64 @@ class RealExpressionTest extends BaseExpressionTest {
TestCase[] testCases = new TestCase[15]; TestCase[] testCases = new TestCase[15];
for (int i = 0; i < testCases.length; i++) { for (int i = 0; i < testCases.length; i++) {
testCases[i] = testCase(Vector3.at(0, i / 16.0 - 0.5, 0), 1) testCases[i] = testCase(Vector3.at(0, i / 16.0 - 0.5, 0), 1)
.withData((i + 9) % 16); .withData((i + 9) % 16);
} }
testCases = Stream.concat(Stream.of(testCases), Stream.of( testCases = Stream.concat(Stream.of(testCases), Stream.of(
testCase(Vector3.at(0, 1, 0), 0) testCase(Vector3.at(0, 1, 0), 0)
)).toArray(TestCase[]::new); )).toArray(TestCase[]::new);
checkExpression("data=(32+y*16+1)%16; y^2/9+x^2/6*(1/(1-0.4*y))+z^2/6*(1/(1-0.4*y))<0.08", checkExpression(
testCases); "data=(32+y*16+1)%16; y^2/9+x^2/6*(1/(1-0.4*y))+z^2/6*(1/(1-0.4*y))<0.08",
testCases
);
} }
@Test @Test
void heart() { void heart() {
checkExpression("(z/2)^2+x^2+(5*y/4-sqrt(abs(x)))^2<0.6", checkExpression(
testCase(Vector3.at(0, 0, -1), 1), "(z/2)^2+x^2+(5*y/4-sqrt(abs(x)))^2<0.6",
testCase(Vector3.at(0, 1, -1), 0), testCase(Vector3.at(0, 0, -1), 1),
testCase(Vector3.at(-0.5, 1, 0), 1)); testCase(Vector3.at(0, 1, -1), 0),
testCase(Vector3.at(-0.5, 1, 0), 1)
);
} }
@Test @Test
void sineWave() { void sineWave() {
checkExpression("sin(x*5)/2<y", checkExpression(
testCase(Vector3.at(1, -0.47947, 0), 0), "sin(x*5)/2<y",
testCase(Vector3.at(1, -0.47946, 0), 1), testCase(Vector3.at(1, -0.47947, 0), 0),
testCase(Vector3.at(2, -0.27202, 0), 0), testCase(Vector3.at(1, -0.47946, 0), 1),
testCase(Vector3.at(2, -0.27201, 0), 1), testCase(Vector3.at(2, -0.27202, 0), 0),
testCase(Vector3.at(3, 0.32513, 0), 0), testCase(Vector3.at(2, -0.27201, 0), 1),
testCase(Vector3.at(3, 0.32515, 0), 1)); testCase(Vector3.at(3, 0.32513, 0), 0),
testCase(Vector3.at(3, 0.32515, 0), 1)
);
} }
@Test @Test
void radialCosine() { void radialCosine() {
checkExpression("cos(sqrt(x^2+z^2)*5)/2<y", checkExpression(
testCase(Vector3.at(0, 0.5, 0), 0), "cos(sqrt(x^2+z^2)*5)/2<y",
testCase(Vector3.at(0, 0.51, 0), 1), testCase(Vector3.at(0, 0.5, 0), 0),
testCase(Vector3.at(Math.PI / 5, -0.5, 0), 0), testCase(Vector3.at(0, 0.51, 0), 1),
testCase(Vector3.at(Math.PI / 5, -0.49, 0), 1), testCase(Vector3.at(Math.PI / 5, -0.5, 0), 0),
testCase(Vector3.at(Math.PI / 10, 0, 0), 0), testCase(Vector3.at(Math.PI / 5, -0.49, 0), 1),
testCase(Vector3.at(Math.PI / 10, 0.1, 0), 1)); testCase(Vector3.at(Math.PI / 10, 0, 0), 0),
testCase(Vector3.at(Math.PI / 10, 0.1, 0), 1)
);
} }
@Test @Test
void circularHyperboloid() { void circularHyperboloid() {
checkExpression("-(z^2/12)+(y^2/4)-(x^2/12)>-0.03", checkExpression(
testCase(Vector3.at(0, 0, 0), 1), "-(z^2/12)+(y^2/4)-(x^2/12)>-0.03",
testCase(Vector3.at(0, 1, 0), 1), testCase(Vector3.at(0, 0, 0), 1),
testCase(Vector3.at(0, 1, 1), 1), testCase(Vector3.at(0, 1, 0), 1),
testCase(Vector3.at(1, 1, 1), 1), testCase(Vector3.at(0, 1, 1), 1),
testCase(Vector3.at(0, 0, 1), 0), testCase(Vector3.at(1, 1, 1), 1),
testCase(Vector3.at(1, 0, 1), 0)); testCase(Vector3.at(0, 0, 1), 0),
testCase(Vector3.at(1, 0, 1), 0)
);
} }
} }

Datei anzeigen

@ -28,37 +28,44 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class DeprecationUtilTest { public class DeprecationUtilTest {
public interface ModifiedApi { public interface ModifiedApi {
@Deprecated @Deprecated
default boolean oldApi() { default boolean oldApi() {
return newApi(); return newApi();
} }
@NonAbstractForCompatibility( @NonAbstractForCompatibility(
delegateName = "oldApi", delegateName = "oldApi",
delegateParams = {} delegateParams = {}
) )
default boolean newApi() { default boolean newApi() {
DeprecationUtil.checkDelegatingOverride(getClass()); DeprecationUtil.checkDelegatingOverride(getClass());
return oldApi(); return oldApi();
} }
} }
public static class OldImpl implements ModifiedApi { public static class OldImpl implements ModifiedApi {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Override @Override
public boolean oldApi() { public boolean oldApi() {
return false; return false;
} }
} }
public static class NewImpl implements ModifiedApi { public static class NewImpl implements ModifiedApi {
@Override @Override
public boolean newApi() { public boolean newApi() {
return true; return true;
} }
} }
public static class NewBadImpl implements ModifiedApi { public static class NewBadImpl implements ModifiedApi {
} }
@Test @Test

Datei anzeigen

@ -39,6 +39,7 @@ import static org.junit.jupiter.api.Assertions.fail;
* Verifies that {@link RegionOptimizedVectorSorter} sorts properly. * Verifies that {@link RegionOptimizedVectorSorter} sorts properly.
*/ */
public class RegionOptimizedVectorSorterTest { public class RegionOptimizedVectorSorterTest {
/** /**
* Find factors, smallest to biggest. * Find factors, smallest to biggest.
* *
@ -64,10 +65,10 @@ public class RegionOptimizedVectorSorterTest {
} }
@ParameterizedTest( @ParameterizedTest(
name = "size={0}" name = "size={0}"
) )
@ValueSource(ints = { @ValueSource(ints = {
0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000 0, 1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000
}) })
void checkSorted(int size) { void checkSorted(int size) {
Random rng = new Random(size); Random rng = new Random(size);
@ -84,7 +85,7 @@ public class RegionOptimizedVectorSorterTest {
int minZ = z / 2; int minZ = z / 2;
int maxZ = minZ + z % 2; int maxZ = minZ + z % 2;
toSort = Lists.newArrayList(new CuboidRegion( toSort = Lists.newArrayList(new CuboidRegion(
BlockVector3.at(-minX, 0, -minZ), BlockVector3.at(maxX - 1, 0, maxZ - 1) BlockVector3.at(-minX, 0, -minZ), BlockVector3.at(maxX - 1, 0, maxZ - 1)
)); ));
} }
assertEquals(size, toSort.size()); assertEquals(size, toSort.size());
@ -104,23 +105,23 @@ public class RegionOptimizedVectorSorterTest {
String spaceship = "(" + curr + " <=> " + next + ")"; String spaceship = "(" + curr + " <=> " + next + ")";
if (currRegionX > nextRegionX) { if (currRegionX > nextRegionX) {
fail(spaceship + " " fail(spaceship + " "
+ currRegionX + " region x should be less than or equal to " + nextRegionX); + currRegionX + " region x should be less than or equal to " + nextRegionX);
} else if (currRegionX == nextRegionX) { } else if (currRegionX == nextRegionX) {
if (currRegionZ > nextRegionZ) { if (currRegionZ > nextRegionZ) {
fail(spaceship + " " fail(spaceship + " "
+ currRegionZ + " region z should be less than or equal to " + nextRegionZ); + currRegionZ + " region z should be less than or equal to " + nextRegionZ);
} else if (currRegionZ == nextRegionZ) { } else if (currRegionZ == nextRegionZ) {
if (currChunkX > nextChunkX) { if (currChunkX > nextChunkX) {
fail(spaceship + " " fail(spaceship + " "
+ currChunkX + " chunk x should be less than or equal to " + nextChunkX); + currChunkX + " chunk x should be less than or equal to " + nextChunkX);
} else if (currChunkX == nextChunkX) { } else if (currChunkX == nextChunkX) {
if (currChunkZ > nextChunkZ) { if (currChunkZ > nextChunkZ) {
fail(spaceship + " " fail(spaceship + " "
+ currChunkZ + " chunk z should be less than or equal to " + nextChunkZ); + currChunkZ + " chunk z should be less than or equal to " + nextChunkZ);
} else if (currChunkZ == nextChunkZ) { } else if (currChunkZ == nextChunkZ) {
if (curr.getY() < next.getY()) { if (curr.getY() < next.getY()) {
fail(spaceship + " " fail(spaceship + " "
+ curr + " y should be greater than or equal to " + next); + curr + " y should be greater than or equal to " + next);
} }
} }
} }
@ -128,4 +129,5 @@ public class RegionOptimizedVectorSorterTest {
} }
} }
} }
} }

Datei anzeigen

@ -150,7 +150,7 @@ public class LocationTest {
World world = mock(World.class); World world = mock(World.class);
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
BlockVector3 location1 = BlockVector3.ZERO; BlockVector3 location1 = BlockVector3.ZERO;
location1.add(10,10,10); location1.add(10, 10, 10);
System.out.println(System.currentTimeMillis() - start + " ms"); System.out.println(System.currentTimeMillis() - start + " ms");
} }

Datei anzeigen

@ -29,17 +29,21 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
abstract class PositionListTest { abstract class PositionListTest {
static class Long extends PositionListTest { static class Long extends PositionListTest {
@Override @Override
protected PositionList createPositionList() { protected PositionList createPositionList() {
return new LongPositionList(); return new LongPositionList();
} }
} }
static class Vector extends PositionListTest { static class Vector extends PositionListTest {
@Override @Override
protected PositionList createPositionList() { protected PositionList createPositionList() {
return new VectorPositionList(); return new VectorPositionList();
} }
} }
private final VariedVectorGenerator generator = new VariedVectorGenerator(true); private final VariedVectorGenerator generator = new VariedVectorGenerator(true);
@ -116,4 +120,5 @@ abstract class PositionListTest {
assertEquals(0, positionList.size()); assertEquals(0, positionList.size());
}); });
} }
} }

Datei anzeigen

@ -69,4 +69,5 @@ public class EventBusTest {
eventBus.post(e2); eventBus.post(e2);
assertEquals(singletonList(e1), subscriber.events); assertEquals(singletonList(e1), subscriber.events);
} }
} }

Datei anzeigen

@ -38,32 +38,33 @@ class MorePathsTest {
@Test @Test
void testRelative() { void testRelative() {
assertEquals( assertEquals(
paths("a", "a/b", "a/b/c"), paths("a", "a/b", "a/b/c"),
MorePaths.iterPaths(Paths.get("a/b/c")).collect(toList()) MorePaths.iterPaths(Paths.get("a/b/c")).collect(toList())
); );
} }
@Test @Test
void testAbsolute() { void testAbsolute() {
assertEquals( assertEquals(
paths("/", "/a", "/a/b", "/a/b/c"), paths("/", "/a", "/a/b", "/a/b/c"),
MorePaths.iterPaths(Paths.get("/a/b/c")).collect(toList()) MorePaths.iterPaths(Paths.get("/a/b/c")).collect(toList())
); );
} }
@Test @Test
void testEmpty() { void testEmpty() {
assertEquals( assertEquals(
paths(""), paths(""),
MorePaths.iterPaths(Paths.get("")).collect(toList()) MorePaths.iterPaths(Paths.get("")).collect(toList())
); );
} }
@Test @Test
void testJustFile() { void testJustFile() {
assertEquals( assertEquals(
paths("a"), paths("a"),
MorePaths.iterPaths(Paths.get("a")).collect(toList()) MorePaths.iterPaths(Paths.get("a")).collect(toList())
); );
} }
} }

Datei anzeigen

@ -20,8 +20,10 @@
package com.sk89q.worldedit.util.test; package com.sk89q.worldedit.util.test;
public class ResourceLockKeys { public class ResourceLockKeys {
public static final String WORLDEDIT_PLATFORM = "WORLDEDIT_PLATFORM"; public static final String WORLDEDIT_PLATFORM = "WORLDEDIT_PLATFORM";
private ResourceLockKeys() { private ResourceLockKeys() {
} }
} }

Datei anzeigen

@ -63,7 +63,8 @@ public class VariedVectorGenerator {
BlockVector3.at(-maxXZ, -maxY - 1, -maxXZ), BlockVector3.at(-maxXZ, -maxY - 1, -maxXZ),
BlockVector3.at(maxXZ, -maxY - 1, maxXZ), BlockVector3.at(maxXZ, -maxY - 1, maxXZ),
BlockVector3.at(-maxXZ, maxY, -maxXZ), BlockVector3.at(-maxXZ, maxY, -maxXZ),
BlockVector3.at(maxXZ, maxY, maxXZ)); BlockVector3.at(maxXZ, maxY, maxXZ)
);
} }
public Stream<BlockVector3> makeVectorsStream() { public Stream<BlockVector3> makeVectorsStream() {
@ -108,4 +109,5 @@ public class VariedVectorGenerator {
} }
}; };
} }
} }

Datei anzeigen

@ -22,6 +22,7 @@ package com.sk89q.worldedit.util.test;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
public class VariedVectorPair { public class VariedVectorPair {
public final BlockVector3 first; public final BlockVector3 first;
public final BlockVector3 second; public final BlockVector3 second;
@ -29,4 +30,5 @@ public class VariedVectorPair {
this.first = first; this.first = first;
this.second = second; this.second = second;
} }
} }

Datei anzeigen

@ -36,6 +36,7 @@ import static com.sk89q.worldedit.world.snapshot.experimental.fs.FileSystemSnaps
import static com.sk89q.worldedit.world.snapshot.experimental.fs.FileSystemSnapshotDatabaseTest.REGION_DATA; import static com.sk89q.worldedit.world.snapshot.experimental.fs.FileSystemSnapshotDatabaseTest.REGION_DATA;
interface EntryMaker<T> { interface EntryMaker<T> {
EntryMaker<ZonedDateTime> TIMESTAMPED_DIR = (directory, time) -> { EntryMaker<ZonedDateTime> TIMESTAMPED_DIR = (directory, time) -> {
Path timestampedDir = directory.resolve(time.format(FORMATTER)); Path timestampedDir = directory.resolve(time.format(FORMATTER));
Files.createDirectories(timestampedDir); Files.createDirectories(timestampedDir);
@ -44,8 +45,8 @@ interface EntryMaker<T> {
EntryMaker<ZonedDateTime> TIMESTAMPED_ARCHIVE = (directory, time) -> { EntryMaker<ZonedDateTime> TIMESTAMPED_ARCHIVE = (directory, time) -> {
Path zipFile = directory.resolve(time.format(FORMATTER) + ".zip"); Path zipFile = directory.resolve(time.format(FORMATTER) + ".zip");
try (FileSystem zipFs = FileSystems.newFileSystem( try (FileSystem zipFs = FileSystems.newFileSystem(
URI.create("jar:" + zipFile.toUri() + "!/"), URI.create("jar:" + zipFile.toUri() + "!/"),
ImmutableMap.of("create", "true") ImmutableMap.of("create", "true")
)) { )) {
TIMESTAMPED_DIR.createEntry(zipFs.getPath("/"), time); TIMESTAMPED_DIR.createEntry(zipFs.getPath("/"), time);
} }
@ -63,6 +64,7 @@ interface EntryMaker<T> {
}; };
class DimInfo { class DimInfo {
final String worldName; final String worldName;
final int dim; final int dim;
@ -70,6 +72,7 @@ interface EntryMaker<T> {
this.worldName = worldName; this.worldName = worldName;
this.dim = dim; this.dim = dim;
} }
} }
EntryMaker<DimInfo> WORLD_DIM_DIR = (directory, dimInfo) -> { EntryMaker<DimInfo> WORLD_DIM_DIR = (directory, dimInfo) -> {
@ -95,12 +98,12 @@ interface EntryMaker<T> {
Files.createDirectories(worldDir); Files.createDirectories(worldDir);
Files.createFile(worldDir.resolve("level.dat")); Files.createFile(worldDir.resolve("level.dat"));
Path chunkFile = worldDir.resolve(LegacyChunkStore.getFilename( Path chunkFile = worldDir.resolve(LegacyChunkStore.getFilename(
CHUNK_POS.toBlockVector2(), "/" CHUNK_POS.toBlockVector2(), "/"
)); ));
Files.createDirectories(chunkFile.getParent()); Files.createDirectories(chunkFile.getParent());
Files.write(chunkFile, CHUNK_DATA); Files.write(chunkFile, CHUNK_DATA);
chunkFile = worldDir.resolve(LegacyChunkStore.getFilename( chunkFile = worldDir.resolve(LegacyChunkStore.getFilename(
CHUNK_POS.add(32, 0, 32).toBlockVector2(), "/" CHUNK_POS.add(32, 0, 32).toBlockVector2(), "/"
)); ));
Files.createDirectories(chunkFile.getParent()); Files.createDirectories(chunkFile.getParent());
Files.write(chunkFile, CHUNK_DATA); Files.write(chunkFile, CHUNK_DATA);
@ -112,8 +115,8 @@ interface EntryMaker<T> {
try { try {
Files.deleteIfExists(temp); Files.deleteIfExists(temp);
try (FileSystem zipFs = FileSystems.newFileSystem( try (FileSystem zipFs = FileSystems.newFileSystem(
URI.create("jar:" + temp.toUri() + "!/"), URI.create("jar:" + temp.toUri() + "!/"),
ImmutableMap.of("create", "true") ImmutableMap.of("create", "true")
)) { )) {
WORLD_DIR.createEntry(zipFs.getPath("/"), worldName); WORLD_DIR.createEntry(zipFs.getPath("/"), worldName);
} }

Datei anzeigen

@ -24,13 +24,13 @@ import com.sk89q.worldedit.util.io.file.ArchiveDir;
import com.sk89q.worldedit.util.io.file.ArchiveNioSupport; import com.sk89q.worldedit.util.io.file.ArchiveNioSupport;
import com.sk89q.worldedit.world.snapshot.experimental.Snapshot; import com.sk89q.worldedit.world.snapshot.experimental.Snapshot;
import javax.annotation.Nullable;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toList;
@ -75,8 +75,10 @@ class FSSDContext {
snapshots = snapshotStream.collect(toList()); snapshots = snapshotStream.collect(toList());
} }
try { try {
assertTrue(snapshots.size() <= 1, assertTrue(
"Too many snapshots matched for " + worldName); snapshots.size() <= 1,
"Too many snapshots matched for " + worldName
);
return requireSnapshot(name, snapshots.stream().findAny().orElse(null)); return requireSnapshot(name, snapshots.stream().findAny().orElse(null));
} catch (Throwable t) { } catch (Throwable t) {
Closer closer = Closer.create(); Closer closer = Closer.create();
@ -99,6 +101,7 @@ class FSSDContext {
ArchiveDir getRootOfArchive(Path archive) throws IOException { ArchiveDir getRootOfArchive(Path archive) throws IOException {
return archiveNioSupport.tryOpenAsDir(archive) return archiveNioSupport.tryOpenAsDir(archive)
.orElseThrow(() -> new AssertionError("No archive opener for " + archive)); .orElseThrow(() -> new AssertionError("No archive opener for " + archive));
} }
} }

Datei anzeigen

@ -54,10 +54,14 @@ enum FSSDTestType {
@Override @Override
List<DynamicTest> getTests(FSSDContext context) { List<DynamicTest> getTests(FSSDContext context) {
return ImmutableList.of( return ImmutableList.of(
dynamicTest("return an empty stream from getSnapshots(worldName)", dynamicTest(
() -> context.db.getSnapshots(WORLD_ALPHA)), "return an empty stream from getSnapshots(worldName)",
dynamicTest("return an empty optional from getSnapshot(name)", () -> context.db.getSnapshots(WORLD_ALPHA)
() -> context.db.getSnapshot(context.nameUri(WORLD_ALPHA))) ),
dynamicTest(
"return an empty optional from getSnapshot(name)",
() -> context.db.getSnapshot(context.nameUri(WORLD_ALPHA))
)
); );
} }
}, },
@ -74,7 +78,7 @@ enum FSSDTestType {
List<DynamicTest> getTests(FSSDContext context) throws IOException { List<DynamicTest> getTests(FSSDContext context) throws IOException {
int dim = ThreadLocalRandom.current().nextInt(); int dim = ThreadLocalRandom.current().nextInt();
Path worldFolder = EntryMaker.WORLD_DIM_DIR Path worldFolder = EntryMaker.WORLD_DIM_DIR
.createEntry(context.db.getRoot(), new EntryMaker.DimInfo(WORLD_ALPHA, dim)); .createEntry(context.db.getRoot(), new EntryMaker.DimInfo(WORLD_ALPHA, dim));
Files.setLastModifiedTime(worldFolder, FileTime.from(TIME_ONE.toInstant())); Files.setLastModifiedTime(worldFolder, FileTime.from(TIME_ONE.toInstant()));
return singleSnapTest(context, WORLD_ALPHA, TIME_ONE); return singleSnapTest(context, WORLD_ALPHA, TIME_ONE);
} }
@ -83,7 +87,7 @@ enum FSSDTestType {
@Override @Override
List<DynamicTest> getTests(FSSDContext context) throws IOException { List<DynamicTest> getTests(FSSDContext context) throws IOException {
Path worldFolder = EntryMaker.WORLD_NO_REGION_DIR Path worldFolder = EntryMaker.WORLD_NO_REGION_DIR
.createEntry(context.db.getRoot(), WORLD_ALPHA); .createEntry(context.db.getRoot(), WORLD_ALPHA);
Files.setLastModifiedTime(worldFolder, FileTime.from(TIME_ONE.toInstant())); Files.setLastModifiedTime(worldFolder, FileTime.from(TIME_ONE.toInstant()));
return singleSnapTest(context, WORLD_ALPHA, TIME_ONE); return singleSnapTest(context, WORLD_ALPHA, TIME_ONE);
} }
@ -92,7 +96,7 @@ enum FSSDTestType {
@Override @Override
List<DynamicTest> getTests(FSSDContext context) throws IOException { List<DynamicTest> getTests(FSSDContext context) throws IOException {
Path worldFolder = EntryMaker.WORLD_LEGACY_DIR Path worldFolder = EntryMaker.WORLD_LEGACY_DIR
.createEntry(context.db.getRoot(), WORLD_ALPHA); .createEntry(context.db.getRoot(), WORLD_ALPHA);
Files.setLastModifiedTime(worldFolder, FileTime.from(TIME_ONE.toInstant())); Files.setLastModifiedTime(worldFolder, FileTime.from(TIME_ONE.toInstant()));
return singleSnapTest(context, WORLD_ALPHA, TIME_ONE); return singleSnapTest(context, WORLD_ALPHA, TIME_ONE);
} }
@ -101,11 +105,11 @@ enum FSSDTestType {
@Override @Override
List<DynamicTest> getTests(FSSDContext context) throws IOException { List<DynamicTest> getTests(FSSDContext context) throws IOException {
Path worldArchive = EntryMaker.WORLD_ARCHIVE Path worldArchive = EntryMaker.WORLD_ARCHIVE
.createEntry(context.db.getRoot(), WORLD_ALPHA); .createEntry(context.db.getRoot(), WORLD_ALPHA);
try (ArchiveDir rootOfArchive = context.getRootOfArchive(worldArchive)) { try (ArchiveDir rootOfArchive = context.getRootOfArchive(worldArchive)) {
Files.setLastModifiedTime( Files.setLastModifiedTime(
rootOfArchive.getPath(), rootOfArchive.getPath(),
FileTime.from(TIME_ONE.toInstant()) FileTime.from(TIME_ONE.toInstant())
); );
} }
return singleSnapTest(context, WORLD_ALPHA + ".zip", TIME_ONE); return singleSnapTest(context, WORLD_ALPHA + ".zip", TIME_ONE);
@ -116,20 +120,26 @@ enum FSSDTestType {
List<? extends DynamicNode> getTests(FSSDContext context) throws IOException { List<? extends DynamicNode> getTests(FSSDContext context) throws IOException {
Path root = context.db.getRoot(); Path root = context.db.getRoot();
Path timestampedDir = EntryMaker.TIMESTAMPED_DIR Path timestampedDir = EntryMaker.TIMESTAMPED_DIR
.createEntry(root, TIME_ONE); .createEntry(root, TIME_ONE);
EntryMaker.WORLD_DIR.createEntry(timestampedDir, WORLD_ALPHA); EntryMaker.WORLD_DIR.createEntry(timestampedDir, WORLD_ALPHA);
EntryMaker.WORLD_ARCHIVE.createEntry(timestampedDir, WORLD_BETA); EntryMaker.WORLD_ARCHIVE.createEntry(timestampedDir, WORLD_BETA);
return ImmutableList.of( return ImmutableList.of(
dynamicContainer("world dir", dynamicContainer(
singleSnapTest(context, "world dir",
root.relativize(timestampedDir) + File.separator + WORLD_ALPHA, singleSnapTest(
TIME_ONE) context,
), root.relativize(timestampedDir) + File.separator + WORLD_ALPHA,
dynamicContainer("world archive", TIME_ONE
singleSnapTest(context, )
root.relativize(timestampedDir) + File.separator + WORLD_BETA + ".zip", ),
TIME_ONE) dynamicContainer(
) "world archive",
singleSnapTest(
context,
root.relativize(timestampedDir) + File.separator + WORLD_BETA + ".zip",
TIME_ONE
)
)
); );
} }
}, },
@ -138,17 +148,20 @@ enum FSSDTestType {
List<? extends DynamicNode> getTests(FSSDContext context) throws IOException { List<? extends DynamicNode> getTests(FSSDContext context) throws IOException {
Path root = context.db.getRoot(); Path root = context.db.getRoot();
Path timestampedArchive = EntryMaker.TIMESTAMPED_ARCHIVE Path timestampedArchive = EntryMaker.TIMESTAMPED_ARCHIVE
.createEntry(root, TIME_ONE); .createEntry(root, TIME_ONE);
try (ArchiveDir timestampedDir = context.getRootOfArchive(timestampedArchive)) { try (ArchiveDir timestampedDir = context.getRootOfArchive(timestampedArchive)) {
EntryMaker.WORLD_DIR.createEntry(timestampedDir.getPath(), WORLD_ALPHA); EntryMaker.WORLD_DIR.createEntry(timestampedDir.getPath(), WORLD_ALPHA);
EntryMaker.WORLD_ARCHIVE.createEntry(timestampedDir.getPath(), WORLD_BETA); EntryMaker.WORLD_ARCHIVE.createEntry(timestampedDir.getPath(), WORLD_BETA);
} }
return ImmutableList.of( return ImmutableList.of(
dynamicContainer("world dir", dynamicContainer(
singleSnapTest(context, "world dir",
root.relativize(timestampedArchive) + File.separator + WORLD_ALPHA, singleSnapTest(
TIME_ONE) context,
) root.relativize(timestampedArchive) + File.separator + WORLD_ALPHA,
TIME_ONE
)
)
); );
} }
}, },
@ -157,22 +170,28 @@ enum FSSDTestType {
List<? extends DynamicNode> getTests(FSSDContext context) throws IOException { List<? extends DynamicNode> getTests(FSSDContext context) throws IOException {
Path root = context.db.getRoot(); Path root = context.db.getRoot();
Path timestampedDirA = EntryMaker.TIMESTAMPED_DIR Path timestampedDirA = EntryMaker.TIMESTAMPED_DIR
.createEntry(root.resolve(WORLD_ALPHA), TIME_ONE); .createEntry(root.resolve(WORLD_ALPHA), TIME_ONE);
Path timestampedDirB = EntryMaker.TIMESTAMPED_DIR Path timestampedDirB = EntryMaker.TIMESTAMPED_DIR
.createEntry(root.resolve(WORLD_BETA), TIME_ONE); .createEntry(root.resolve(WORLD_BETA), TIME_ONE);
EntryMaker.WORLD_DIR.createEntry(timestampedDirA, WORLD_ALPHA); EntryMaker.WORLD_DIR.createEntry(timestampedDirA, WORLD_ALPHA);
EntryMaker.WORLD_ARCHIVE.createEntry(timestampedDirB, WORLD_BETA); EntryMaker.WORLD_ARCHIVE.createEntry(timestampedDirB, WORLD_BETA);
return ImmutableList.of( return ImmutableList.of(
dynamicContainer("world dir", dynamicContainer(
singleSnapTest(context, "world dir",
root.relativize(timestampedDirA) + File.separator + WORLD_ALPHA, singleSnapTest(
TIME_ONE) context,
), root.relativize(timestampedDirA) + File.separator + WORLD_ALPHA,
dynamicContainer("world archive", TIME_ONE
singleSnapTest(context, )
root.relativize(timestampedDirB) + File.separator + WORLD_BETA + ".zip", ),
TIME_ONE) dynamicContainer(
) "world archive",
singleSnapTest(
context,
root.relativize(timestampedDirB) + File.separator + WORLD_BETA + ".zip",
TIME_ONE
)
)
); );
} }
}, },
@ -181,57 +200,57 @@ enum FSSDTestType {
List<DynamicTest> getTests(FSSDContext context) throws IOException { List<DynamicTest> getTests(FSSDContext context) throws IOException {
Path root = context.db.getRoot(); Path root = context.db.getRoot();
Path timestampedDirA = EntryMaker.TIMESTAMPED_DIR Path timestampedDirA = EntryMaker.TIMESTAMPED_DIR
.createEntry(root, TIME_ONE); .createEntry(root, TIME_ONE);
EntryMaker.WORLD_DIR.createEntry(timestampedDirA, WORLD_ALPHA); EntryMaker.WORLD_DIR.createEntry(timestampedDirA, WORLD_ALPHA);
Path timestampedDirB = EntryMaker.TIMESTAMPED_DIR Path timestampedDirB = EntryMaker.TIMESTAMPED_DIR
.createEntry(root, TIME_TWO); .createEntry(root, TIME_TWO);
EntryMaker.WORLD_DIR.createEntry(timestampedDirB, WORLD_ALPHA); EntryMaker.WORLD_DIR.createEntry(timestampedDirB, WORLD_ALPHA);
return ImmutableList.of( return ImmutableList.of(
dynamicTest("list both snapshots in order (newest first)", () -> { dynamicTest("list both snapshots in order (newest first)", () -> {
List<Snapshot> snapshots = context.db
.getSnapshotsNewestFirst(WORLD_ALPHA).collect(toList());
assertEquals(2, snapshots.size());
assertValidSnapshot(TIME_ONE, snapshots.get(0));
assertValidSnapshot(TIME_TWO, snapshots.get(1));
}),
dynamicTest("list both snapshots in order (oldest first)", () -> {
List<Snapshot> snapshots = context.db
.getSnapshotsOldestFirst(WORLD_ALPHA).collect(toList());
assertEquals(2, snapshots.size());
assertValidSnapshot(TIME_TWO, snapshots.get(0));
assertValidSnapshot(TIME_ONE, snapshots.get(1));
}),
dynamicTest("list only 1 if getting AFTER 2", () -> {
List<Snapshot> snapshots = context.db
.getSnapshotsAfter(WORLD_ALPHA, TIME_TWO).collect(toList());
assertEquals(1, snapshots.size());
assertValidSnapshot(TIME_ONE, snapshots.get(0));
}),
dynamicTest("list only 2 if getting BEFORE 1", () -> {
List<Snapshot> snapshots = context.db
.getSnapshotsBefore(WORLD_ALPHA, TIME_ONE).collect(toList());
assertEquals(1, snapshots.size());
assertValidSnapshot(TIME_TWO, snapshots.get(0));
}),
dynamicTest("list both if AFTER time before 2", () -> {
List<Snapshot> snapshots = context.db
.getSnapshotsAfter(WORLD_ALPHA, TIME_TWO.minusSeconds(1))
.collect(toList());
assertEquals(2, snapshots.size());
// sorted newest first
assertValidSnapshot(TIME_ONE, snapshots.get(0));
assertValidSnapshot(TIME_TWO, snapshots.get(1));
}),
dynamicTest("list both if BEFORE time after 1", () -> {
List<Snapshot> snapshots = context.db List<Snapshot> snapshots = context.db
.getSnapshotsBefore(WORLD_ALPHA, TIME_ONE.plusSeconds(1)) .getSnapshotsNewestFirst(WORLD_ALPHA).collect(toList());
.collect(toList()); assertEquals(2, snapshots.size());
assertValidSnapshot(TIME_ONE, snapshots.get(0));
assertValidSnapshot(TIME_TWO, snapshots.get(1));
}),
dynamicTest("list both snapshots in order (oldest first)", () -> {
List<Snapshot> snapshots = context.db
.getSnapshotsOldestFirst(WORLD_ALPHA).collect(toList());
assertEquals(2, snapshots.size()); assertEquals(2, snapshots.size());
// sorted oldest first
assertValidSnapshot(TIME_TWO, snapshots.get(0)); assertValidSnapshot(TIME_TWO, snapshots.get(0));
assertValidSnapshot(TIME_ONE, snapshots.get(1)); assertValidSnapshot(TIME_ONE, snapshots.get(1));
} }),
) dynamicTest("list only 1 if getting AFTER 2", () -> {
List<Snapshot> snapshots = context.db
.getSnapshotsAfter(WORLD_ALPHA, TIME_TWO).collect(toList());
assertEquals(1, snapshots.size());
assertValidSnapshot(TIME_ONE, snapshots.get(0));
}),
dynamicTest("list only 2 if getting BEFORE 1", () -> {
List<Snapshot> snapshots = context.db
.getSnapshotsBefore(WORLD_ALPHA, TIME_ONE).collect(toList());
assertEquals(1, snapshots.size());
assertValidSnapshot(TIME_TWO, snapshots.get(0));
}),
dynamicTest("list both if AFTER time before 2", () -> {
List<Snapshot> snapshots = context.db
.getSnapshotsAfter(WORLD_ALPHA, TIME_TWO.minusSeconds(1))
.collect(toList());
assertEquals(2, snapshots.size());
// sorted newest first
assertValidSnapshot(TIME_ONE, snapshots.get(0));
assertValidSnapshot(TIME_TWO, snapshots.get(1));
}),
dynamicTest("list both if BEFORE time after 1", () -> {
List<Snapshot> snapshots = context.db
.getSnapshotsBefore(WORLD_ALPHA, TIME_ONE.plusSeconds(1))
.collect(toList());
assertEquals(2, snapshots.size());
// sorted oldest first
assertValidSnapshot(TIME_TWO, snapshots.get(0));
assertValidSnapshot(TIME_ONE, snapshots.get(1));
}
)
); );
} }
}, },
@ -239,36 +258,40 @@ enum FSSDTestType {
@Override @Override
List<? extends DynamicNode> getTests(FSSDContext context) throws IOException { List<? extends DynamicNode> getTests(FSSDContext context) throws IOException {
Path worldFolderA = EntryMaker.WORLD_DIR Path worldFolderA = EntryMaker.WORLD_DIR
.createEntry(context.db.getRoot(), WORLD_ALPHA); .createEntry(context.db.getRoot(), WORLD_ALPHA);
Files.setLastModifiedTime(worldFolderA, FileTime.from(TIME_ONE.toInstant())); Files.setLastModifiedTime(worldFolderA, FileTime.from(TIME_ONE.toInstant()));
Path worldFolderB = EntryMaker.WORLD_DIR Path worldFolderB = EntryMaker.WORLD_DIR
.createEntry(context.db.getRoot(), WORLD_BETA); .createEntry(context.db.getRoot(), WORLD_BETA);
Files.setLastModifiedTime(worldFolderB, FileTime.from(TIME_TWO.toInstant())); Files.setLastModifiedTime(worldFolderB, FileTime.from(TIME_TWO.toInstant()));
return Stream.of( return Stream.of(
singleSnapTest(context, WORLD_ALPHA, TIME_ONE), singleSnapTest(context, WORLD_ALPHA, TIME_ONE),
singleSnapTest(context, WORLD_BETA, TIME_TWO) singleSnapTest(context, WORLD_BETA, TIME_TWO)
).flatMap(List::stream).collect(toList()); ).flatMap(List::stream).collect(toList());
} }
}; };
List<DynamicTest> singleSnapTest(FSSDContext context, String name, List<DynamicTest> singleSnapTest(
ZonedDateTime time) { FSSDContext context, String name,
ZonedDateTime time
) {
return ImmutableList.of( return ImmutableList.of(
dynamicTest("return a valid snapshot for " + name, () -> { dynamicTest("return a valid snapshot for " + name, () -> {
try (Snapshot snapshot = context.requireSnapshot(name)) { try (Snapshot snapshot = context.requireSnapshot(name)) {
assertValidSnapshot(time, snapshot); assertValidSnapshot(time, snapshot);
} }
}), }),
dynamicTest("list a valid snapshot for " + name, () -> { dynamicTest("list a valid snapshot for " + name, () -> {
try (Snapshot snapshot = context.requireListsSnapshot(name)) { try (Snapshot snapshot = context.requireListsSnapshot(name)) {
assertValidSnapshot(time, snapshot); assertValidSnapshot(time, snapshot);
} }
}) })
); );
} }
private static void assertValidSnapshot(ZonedDateTime time, private static void assertValidSnapshot(
Snapshot snapshot) throws IOException, DataException { ZonedDateTime time,
Snapshot snapshot
) throws IOException, DataException {
assertEquals(time, snapshot.getInfo().getDateTime()); assertEquals(time, snapshot.getInfo().getDateTime());
// MCA file // MCA file
assertEquals(CHUNK_TAG.toString(), snapshot.getChunkTag(CHUNK_POS).toString()); assertEquals(CHUNK_TAG.toString(), snapshot.getChunkTag(CHUNK_POS).toString());
@ -281,10 +304,10 @@ enum FSSDTestType {
Stream<DynamicNode> getNamedTests(FSSDContext context) throws IOException { Stream<DynamicNode> getNamedTests(FSSDContext context) throws IOException {
return Stream.of(dynamicContainer( return Stream.of(dynamicContainer(
name(), name(),
URI.create("method:" + getClass().getName() + URI.create("method:" + getClass().getName() +
"#getTests(" + FSSDContext.class.getName() + ")"), "#getTests(" + FSSDContext.class.getName() + ")"),
getTests(context).stream() getTests(context).stream()
)); ));
} }

Datei anzeigen

@ -71,9 +71,9 @@ class FileSystemSnapshotDatabaseTest {
static final String WORLD_BETA = "World Beta"; static final String WORLD_BETA = "World Beta";
static final DateTimeFormatter FORMATTER = static final DateTimeFormatter FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH_mm_ss"); DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH_mm_ss");
static final ZonedDateTime TIME_ONE = Instant.parse("2018-01-01T12:00:00.00Z") static final ZonedDateTime TIME_ONE = Instant.parse("2018-01-01T12:00:00.00Z")
.atZone(ZoneId.systemDefault()); .atZone(ZoneId.systemDefault());
static final ZonedDateTime TIME_TWO = TIME_ONE.minusDays(1); static final ZonedDateTime TIME_TWO = TIME_ONE.minusDays(1);
private static Path TEMP_DIR; private static Path TEMP_DIR;
@ -88,11 +88,11 @@ class FileSystemSnapshotDatabaseTest {
try { try {
// Find the single chunk // Find the single chunk
BlockVector2 chunkPos = IntStream.range(0, 32).mapToObj( BlockVector2 chunkPos = IntStream.range(0, 32).mapToObj(
x -> IntStream.range(0, 32).filter(z -> reader.hasChunk(x, z)) x -> IntStream.range(0, 32).filter(z -> reader.hasChunk(x, z))
.mapToObj(z -> BlockVector2.at(x, z)) .mapToObj(z -> BlockVector2.at(x, z))
).flatMap(Function.identity()) ).flatMap(Function.identity())
.findAny() .findAny()
.orElseThrow(() -> new AssertionError("No chunk in region file.")); .orElseThrow(() -> new AssertionError("No chunk in region file."));
ByteArrayOutputStream cap = new ByteArrayOutputStream(); ByteArrayOutputStream cap = new ByteArrayOutputStream();
try (InputStream in = reader.getChunkInputStream(chunkPos); try (InputStream in = reader.getChunkInputStream(chunkPos);
GZIPOutputStream gzOut = new GZIPOutputStream(cap)) { GZIPOutputStream gzOut = new GZIPOutputStream(cap)) {
@ -100,7 +100,7 @@ class FileSystemSnapshotDatabaseTest {
} }
CHUNK_DATA = cap.toByteArray(); CHUNK_DATA = cap.toByteArray();
CHUNK_TAG = ChunkStoreHelper.readCompoundTag(() -> new GZIPInputStream( CHUNK_TAG = ChunkStoreHelper.readCompoundTag(() -> new GZIPInputStream(
new ByteArrayInputStream(CHUNK_DATA) new ByteArrayInputStream(CHUNK_DATA)
)); ));
CHUNK_POS = chunkPos.toBlockVector3(); CHUNK_POS = chunkPos.toBlockVector3();
} finally { } finally {
@ -142,14 +142,18 @@ class FileSystemSnapshotDatabaseTest {
try { try {
Path relative = root.getFileSystem().getPath("relative"); Path relative = root.getFileSystem().getPath("relative");
Files.createDirectories(relative); Files.createDirectories(relative);
FileSystemSnapshotDatabase db2 = new FileSystemSnapshotDatabase(relative, FileSystemSnapshotDatabase db2 = new FileSystemSnapshotDatabase(
ArchiveNioSupports.combined()); relative,
ArchiveNioSupports.combined()
);
assertEquals(root.getFileSystem().getPath(".").toRealPath() assertEquals(root.getFileSystem().getPath(".").toRealPath()
.resolve(relative), db2.getRoot()); .resolve(relative), db2.getRoot());
Path absolute = root.resolve("absolute"); Path absolute = root.resolve("absolute");
Files.createDirectories(absolute); Files.createDirectories(absolute);
FileSystemSnapshotDatabase db3 = new FileSystemSnapshotDatabase(absolute, FileSystemSnapshotDatabase db3 = new FileSystemSnapshotDatabase(
ArchiveNioSupports.combined()); absolute,
ArchiveNioSupports.combined()
);
assertEquals(absolute, db3.getRoot()); assertEquals(absolute, db3.getRoot());
} finally { } finally {
deleteTree(root); deleteTree(root);
@ -160,26 +164,28 @@ class FileSystemSnapshotDatabaseTest {
@TestFactory @TestFactory
Stream<DynamicNode> withSpecificNioSupport() { Stream<DynamicNode> withSpecificNioSupport() {
return Stream.of( return Stream.of(
ZipArchiveNioSupport.getInstance() ZipArchiveNioSupport.getInstance()
) )
.map(nioSupport -> { .map(nioSupport -> {
Stream<? extends DynamicNode> nodes = Stream.of(FSSDTestType.values()) Stream<? extends DynamicNode> nodes = Stream.of(FSSDTestType.values())
.flatMap(type -> { .flatMap(type -> {
try { try {
return getTests(nioSupport, type); return getTests(nioSupport, type);
} catch (IOException e) { } catch (IOException e) {
throw new UncheckedIOException(e); throw new UncheckedIOException(e);
} }
}); });
return dynamicContainer( return dynamicContainer(
nioSupport.getClass().getSimpleName() + ", can, for format:", nioSupport.getClass().getSimpleName() + ", can, for format:",
nodes nodes
); );
}); });
} }
private static Stream<? extends DynamicNode> getTests(ArchiveNioSupport nioSupport, private static Stream<? extends DynamicNode> getTests(
FSSDTestType type) throws IOException { ArchiveNioSupport nioSupport,
FSSDTestType type
) throws IOException {
Path root = newTempDb(); Path root = newTempDb();
try { try {
Path dbRoot = root.resolve("snapshots"); Path dbRoot = root.resolve("snapshots");