mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-08-29 05:20:40 +00:00
d
This commit is contained in:
+130
@@ -0,0 +1,130 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementSeed;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import io.papermc.paper.world.saveddata.PaperLevelOverrides;
|
||||
import io.papermc.paper.world.saveddata.PaperWorldMetadata;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.world.level.storage.PrimaryLevelData;
|
||||
import net.minecraft.world.level.storage.SavedDataStorage;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.craftbukkit.CraftServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
final class CurrentPaperWorldDataWriter {
|
||||
private static final long SNAPSHOT_TIMEOUT_SECONDS = 30L;
|
||||
|
||||
private CurrentPaperWorldDataWriter() {
|
||||
}
|
||||
|
||||
static void write(
|
||||
Path sourceWorldDirectory,
|
||||
Path targetWorldDirectory,
|
||||
long seed
|
||||
) throws IOException {
|
||||
CraftServer craftServer = (CraftServer) Bukkit.getServer();
|
||||
MinecraftServer server = craftServer.getHandle().getServer();
|
||||
PaperLevelOverrides levelOverrides = captureLevelOverrides(craftServer, server);
|
||||
|
||||
Path targetWorld = targetWorldDirectory.toAbsolutePath().normalize();
|
||||
UUID metadataUuid = UUID.randomUUID();
|
||||
WorldReplacementSeed.copyWithAuthoritativeSeed(sourceWorldDirectory, targetWorld, seed);
|
||||
try (SavedDataStorage savedDataStorage = new SavedDataStorage(
|
||||
targetWorld.resolve("data"),
|
||||
server.getFixerUpper(),
|
||||
server.registryAccess()
|
||||
)) {
|
||||
savedDataStorage.set(PaperWorldMetadata.TYPE, new PaperWorldMetadata(metadataUuid));
|
||||
savedDataStorage.set(PaperLevelOverrides.TYPE, levelOverrides);
|
||||
}
|
||||
|
||||
List<Path> requiredDataFiles = List.of(
|
||||
targetWorld.resolve("data/minecraft/world_gen_settings.dat"),
|
||||
targetWorld.resolve("data/paper/metadata.dat"),
|
||||
targetWorld.resolve("data/paper/level_overrides.dat")
|
||||
);
|
||||
for (Path requiredDataFile : requiredDataFiles) {
|
||||
if (!Files.isRegularFile(requiredDataFile, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Current Paper world data was not written: " + requiredDataFile);
|
||||
}
|
||||
}
|
||||
|
||||
long writtenSeed = WorldReplacementSeed.readAuthoritativeSeed(targetWorld);
|
||||
if (writtenSeed != seed) {
|
||||
throw new IOException("Current Paper world data did not retain the requested seed.");
|
||||
}
|
||||
|
||||
try (SavedDataStorage verificationStorage = new SavedDataStorage(
|
||||
targetWorld.resolve("data"),
|
||||
server.getFixerUpper(),
|
||||
server.registryAccess()
|
||||
)) {
|
||||
PaperWorldMetadata metadata = verificationStorage.get(PaperWorldMetadata.TYPE);
|
||||
if (metadata == null || !metadataUuid.equals(metadata.uuid())) {
|
||||
throw new IOException("Current Paper world metadata could not be verified.");
|
||||
}
|
||||
PaperLevelOverrides overrides = verificationStorage.get(PaperLevelOverrides.TYPE);
|
||||
if (overrides == null || overrides.isInitialized()) {
|
||||
throw new IOException("Current Paper level overrides could not be verified.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static PaperLevelOverrides captureLevelOverrides(
|
||||
CraftServer craftServer,
|
||||
MinecraftServer server
|
||||
) throws IOException {
|
||||
if (craftServer.isGlobalTickThread()) {
|
||||
return createLevelOverrides(craftServer, server);
|
||||
}
|
||||
if (J.isFolia() && J.isPrimaryThread()) {
|
||||
throw new IOException("Current Paper world data cannot be staged from a Folia region tick thread.");
|
||||
}
|
||||
|
||||
CompletableFuture<PaperLevelOverrides> captured = new CompletableFuture<>();
|
||||
boolean scheduled = J.runGlobal(() -> {
|
||||
try {
|
||||
captured.complete(createLevelOverrides(craftServer, server));
|
||||
} catch (Throwable failure) {
|
||||
captured.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
if (!scheduled) {
|
||||
throw new IOException("Could not schedule the current Paper level-data snapshot on the global thread.");
|
||||
}
|
||||
|
||||
try {
|
||||
return captured.get(SNAPSHOT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException failure) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted while capturing current Paper level data.", failure);
|
||||
} catch (ExecutionException failure) {
|
||||
throw new IOException("Could not capture current Paper level data.", failure.getCause());
|
||||
} catch (TimeoutException failure) {
|
||||
throw new IOException("Timed out while capturing current Paper level data.", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static PaperLevelOverrides createLevelOverrides(
|
||||
CraftServer craftServer,
|
||||
MinecraftServer server
|
||||
) throws IOException {
|
||||
if (!craftServer.isGlobalTickThread()) {
|
||||
throw new IOException("Current Paper level data must be captured on the global tick thread.");
|
||||
}
|
||||
if (!(server.getWorldData().overworldData() instanceof PrimaryLevelData primaryLevelData)) {
|
||||
throw new IOException("Paper primary level data is unavailable for current world data staging.");
|
||||
}
|
||||
return PaperLevelOverrides.createFromLiveLevelData(primaryLevelData);
|
||||
}
|
||||
}
|
||||
+122
-72
@@ -7,7 +7,6 @@ import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderOwner;
|
||||
import net.minecraft.core.Vec3i;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.level.chunk.ChunkGeneratorStructureState;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureSet;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
|
||||
import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement;
|
||||
@@ -41,16 +40,31 @@ final class DatapackStructureStateFilter {
|
||||
DatapackStructureScopeIndex scopeIndex,
|
||||
Set<String> declaredSources,
|
||||
IrisImportedStructureControl importedStructures
|
||||
) {
|
||||
return filter(
|
||||
structureSets,
|
||||
scopeIndex,
|
||||
declaredSources,
|
||||
importedStructures,
|
||||
keyIndex(structureSets));
|
||||
}
|
||||
|
||||
static Selection filter(
|
||||
List<Holder<StructureSet>> structureSets,
|
||||
DatapackStructureScopeIndex scopeIndex,
|
||||
Set<String> declaredSources,
|
||||
IrisImportedStructureControl importedStructures,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
if (scopeIndex.isEmpty()) {
|
||||
return new Selection(
|
||||
scaleFrequencyOverrides(structureSets, importedStructures),
|
||||
scaleFrequencyOverrides(structureSets, importedStructures, keyIndex),
|
||||
0,
|
||||
0);
|
||||
}
|
||||
Map<String, Holder<StructureSet>> holdersByKey = new HashMap<>();
|
||||
for (Holder<StructureSet> holder : structureSets) {
|
||||
String key = structureSetKey(holder);
|
||||
String key = structureSetKey(holder, keyIndex);
|
||||
if (key != null) {
|
||||
holdersByKey.putIfAbsent(key, holder);
|
||||
}
|
||||
@@ -61,7 +75,7 @@ final class DatapackStructureStateFilter {
|
||||
int retainedManagedSets = 0;
|
||||
int excludedManagedSets = 0;
|
||||
for (Holder<StructureSet> holder : structureSets) {
|
||||
String setKey = structureSetKey(holder);
|
||||
String setKey = structureSetKey(holder, keyIndex);
|
||||
boolean managedSet = setKey != null && scopeIndex.isManagedStructureSet(setKey);
|
||||
Holder<StructureSet> scopedHolder = scopeHolder(
|
||||
holder,
|
||||
@@ -69,7 +83,8 @@ final class DatapackStructureStateFilter {
|
||||
declaredSources,
|
||||
holdersByKey,
|
||||
scopedByIdentity,
|
||||
visiting);
|
||||
visiting,
|
||||
keyIndex);
|
||||
if (scopedHolder == null) {
|
||||
if (managedSet) {
|
||||
excludedManagedSets++;
|
||||
@@ -82,21 +97,29 @@ final class DatapackStructureStateFilter {
|
||||
filteredSets.add(scopedHolder);
|
||||
}
|
||||
return new Selection(
|
||||
scaleFrequencyOverrides(List.copyOf(filteredSets), importedStructures),
|
||||
scaleFrequencyOverrides(
|
||||
List.copyOf(filteredSets), importedStructures, keyIndex),
|
||||
retainedManagedSets,
|
||||
excludedManagedSets);
|
||||
}
|
||||
|
||||
static String structureSetKey(Holder<StructureSet> holder) {
|
||||
Optional<ResourceKey<StructureSet>> key = holder.unwrapKey();
|
||||
if (key.isPresent()) {
|
||||
return key.get().identifier().toString();
|
||||
}
|
||||
if (holder.value().placement()
|
||||
instanceof ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement keyedPlacement) {
|
||||
return keyedPlacement.key.identifier().toString();
|
||||
}
|
||||
return null;
|
||||
return structureSetKey(holder, keyIndex(List.of(holder)));
|
||||
}
|
||||
|
||||
static StructureSetKeyIndex keyIndex(
|
||||
Iterable<? extends Holder<StructureSet>> registeredStructureSets
|
||||
) {
|
||||
return StructureSetKeyIndex.create(registeredStructureSets);
|
||||
}
|
||||
|
||||
private static String structureSetKey(
|
||||
Holder<StructureSet> holder,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
return keyIndex.resolve(holder)
|
||||
.map(key -> key.identifier().toString())
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private static List<StructureSet.StructureSelectionEntry> filterEntries(
|
||||
@@ -122,7 +145,8 @@ final class DatapackStructureStateFilter {
|
||||
Set<String> declaredSources,
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
Map<Holder<StructureSet>, Holder<StructureSet>> scopedByIdentity,
|
||||
Set<Holder<StructureSet>> visiting
|
||||
Set<Holder<StructureSet>> visiting,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
if (scopedByIdentity.containsKey(holder)) {
|
||||
return scopedByIdentity.get(holder);
|
||||
@@ -131,7 +155,7 @@ final class DatapackStructureStateFilter {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String setKey = structureSetKey(holder);
|
||||
String setKey = structureSetKey(holder, keyIndex);
|
||||
if (setKey != null && scopeIndex.isManagedStructureSet(setKey)
|
||||
&& !scopeIndex.allowsStructureSet(setKey, declaredSources)) {
|
||||
scopedByIdentity.put(holder, null);
|
||||
@@ -150,14 +174,15 @@ final class DatapackStructureStateFilter {
|
||||
declaredSources,
|
||||
holdersByKey,
|
||||
scopedByIdentity,
|
||||
visiting);
|
||||
visiting,
|
||||
keyIndex);
|
||||
if (entries.size() == originalSet.structures().size()
|
||||
&& placement == originalSet.placement()) {
|
||||
scopedByIdentity.put(holder, holder);
|
||||
return holder;
|
||||
}
|
||||
Holder<StructureSet> scoped = replacementHolder(
|
||||
holder, new StructureSet(entries, placement));
|
||||
holder, new StructureSet(entries, placement), keyIndex);
|
||||
scopedByIdentity.put(holder, scoped);
|
||||
return scoped;
|
||||
} finally {
|
||||
@@ -184,7 +209,8 @@ final class DatapackStructureStateFilter {
|
||||
Set<String> declaredSources,
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
Map<Holder<StructureSet>, Holder<StructureSet>> scopedByIdentity,
|
||||
Set<Holder<StructureSet>> visiting
|
||||
Set<Holder<StructureSet>> visiting,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
Optional<StructurePlacement.ExclusionZone> currentZone = exclusionZone(placement);
|
||||
if (currentZone.isEmpty()) {
|
||||
@@ -192,7 +218,7 @@ final class DatapackStructureStateFilter {
|
||||
}
|
||||
|
||||
Holder<StructureSet> target = currentZone.get().otherSet();
|
||||
String targetKey = structureSetKey(target);
|
||||
String targetKey = structureSetKey(target, keyIndex);
|
||||
if (targetKey != null) {
|
||||
target = holdersByKey.getOrDefault(targetKey, target);
|
||||
}
|
||||
@@ -202,7 +228,8 @@ final class DatapackStructureStateFilter {
|
||||
declaredSources,
|
||||
holdersByKey,
|
||||
scopedByIdentity,
|
||||
visiting);
|
||||
visiting,
|
||||
keyIndex);
|
||||
Optional<StructurePlacement.ExclusionZone> scopedZone = Optional.empty();
|
||||
if (scopedTarget != null) {
|
||||
scopedZone = Optional.of(new StructurePlacement.ExclusionZone(
|
||||
@@ -217,14 +244,15 @@ final class DatapackStructureStateFilter {
|
||||
|
||||
private static List<Holder<StructureSet>> scaleFrequencyOverrides(
|
||||
List<Holder<StructureSet>> structureSets,
|
||||
IrisImportedStructureControl importedStructures
|
||||
IrisImportedStructureControl importedStructures,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
if (!importedStructures.hasFrequencyOverrides()) {
|
||||
return structureSets;
|
||||
}
|
||||
Map<String, Holder<StructureSet>> holdersByKey = new HashMap<>();
|
||||
for (Holder<StructureSet> holder : structureSets) {
|
||||
String key = structureSetKey(holder);
|
||||
String key = structureSetKey(holder, keyIndex);
|
||||
if (key != null) {
|
||||
holdersByKey.putIfAbsent(key, holder);
|
||||
}
|
||||
@@ -234,7 +262,11 @@ final class DatapackStructureStateFilter {
|
||||
boolean changed = false;
|
||||
for (Holder<StructureSet> holder : structureSets) {
|
||||
Holder<StructureSet> scaled = scaleFrequencyHolder(
|
||||
holder, importedStructures, holdersByKey, scaledByIdentity);
|
||||
holder,
|
||||
importedStructures,
|
||||
holdersByKey,
|
||||
scaledByIdentity,
|
||||
keyIndex);
|
||||
scaledSets.add(scaled);
|
||||
changed |= scaled != holder;
|
||||
}
|
||||
@@ -245,17 +277,19 @@ final class DatapackStructureStateFilter {
|
||||
Holder<StructureSet> holder,
|
||||
IrisImportedStructureControl importedStructures,
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
Map<Holder<StructureSet>, Holder<StructureSet>> scaledByIdentity
|
||||
Map<Holder<StructureSet>, Holder<StructureSet>> scaledByIdentity,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
if (scaledByIdentity.containsKey(holder)) {
|
||||
return scaledByIdentity.get(holder);
|
||||
}
|
||||
if (!dependsOnFrequencyOverride(holder, importedStructures, holdersByKey)) {
|
||||
if (!dependsOnFrequencyOverride(
|
||||
holder, importedStructures, holdersByKey, keyIndex)) {
|
||||
scaledByIdentity.put(holder, holder);
|
||||
return holder;
|
||||
}
|
||||
|
||||
ResourceKey<StructureSet> holderKey = structureSetResourceKey(holder).orElseThrow(() ->
|
||||
ResourceKey<StructureSet> holderKey = keyIndex.resolve(holder).orElseThrow(() ->
|
||||
new IllegalStateException(
|
||||
"An affected native structure-set exclusion graph has an unkeyed holder"));
|
||||
ReboundStructureSetHolder scaledHolder = new ReboundStructureSetHolder(holderKey);
|
||||
@@ -267,16 +301,21 @@ final class DatapackStructureStateFilter {
|
||||
Optional<StructurePlacement.ExclusionZone> scaledZone = originalZone;
|
||||
if (originalZone.isPresent()) {
|
||||
Holder<StructureSet> target = canonicalHolder(
|
||||
originalZone.get().otherSet(), holdersByKey);
|
||||
originalZone.get().otherSet(), holdersByKey, keyIndex);
|
||||
Holder<StructureSet> scaledTarget = scaleFrequencyHolder(
|
||||
target, importedStructures, holdersByKey, scaledByIdentity);
|
||||
target,
|
||||
importedStructures,
|
||||
holdersByKey,
|
||||
scaledByIdentity,
|
||||
keyIndex);
|
||||
if (scaledTarget != originalZone.get().otherSet()) {
|
||||
scaledZone = Optional.of(new StructurePlacement.ExclusionZone(
|
||||
scaledTarget, originalZone.get().chunkCount()));
|
||||
}
|
||||
}
|
||||
|
||||
double multiplier = importedStructures.frequencyMultiplier(structureSetKey(holder));
|
||||
double multiplier = importedStructures.frequencyMultiplier(
|
||||
structureSetKey(holder, keyIndex));
|
||||
StructurePlacement scaledPlacement = multiplier == 1D && scaledZone.equals(originalZone)
|
||||
? originalPlacement
|
||||
: copyPlacement(originalPlacement, scaledZone, multiplier);
|
||||
@@ -287,12 +326,14 @@ final class DatapackStructureStateFilter {
|
||||
private static boolean dependsOnFrequencyOverride(
|
||||
Holder<StructureSet> holder,
|
||||
IrisImportedStructureControl importedStructures,
|
||||
Map<String, Holder<StructureSet>> holdersByKey
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
Set<Holder<StructureSet>> visited = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
Holder<StructureSet> current = holder;
|
||||
while (visited.add(current)) {
|
||||
if (importedStructures.frequencyMultiplier(structureSetKey(current)) != 1D) {
|
||||
if (importedStructures.frequencyMultiplier(
|
||||
structureSetKey(current, keyIndex)) != 1D) {
|
||||
return true;
|
||||
}
|
||||
Optional<StructurePlacement.ExclusionZone> zone =
|
||||
@@ -300,24 +341,26 @@ final class DatapackStructureStateFilter {
|
||||
if (zone.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
current = canonicalHolder(zone.get().otherSet(), holdersByKey);
|
||||
current = canonicalHolder(zone.get().otherSet(), holdersByKey, keyIndex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Holder<StructureSet> canonicalHolder(
|
||||
Holder<StructureSet> holder,
|
||||
Map<String, Holder<StructureSet>> holdersByKey
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
String key = structureSetKey(holder);
|
||||
String key = structureSetKey(holder, keyIndex);
|
||||
return key == null ? holder : holdersByKey.getOrDefault(key, holder);
|
||||
}
|
||||
|
||||
private static Holder<StructureSet> replacementHolder(
|
||||
Holder<StructureSet> original,
|
||||
StructureSet replacement
|
||||
StructureSet replacement,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
Optional<ResourceKey<StructureSet>> key = structureSetResourceKey(original);
|
||||
Optional<ResourceKey<StructureSet>> key = keyIndex.resolve(original);
|
||||
if (key.isEmpty()) {
|
||||
return Holder.direct(replacement);
|
||||
}
|
||||
@@ -326,20 +369,6 @@ final class DatapackStructureStateFilter {
|
||||
return holder;
|
||||
}
|
||||
|
||||
private static Optional<ResourceKey<StructureSet>> structureSetResourceKey(
|
||||
Holder<StructureSet> holder
|
||||
) {
|
||||
Optional<ResourceKey<StructureSet>> key = holder.unwrapKey();
|
||||
if (key.isPresent()) {
|
||||
return key;
|
||||
}
|
||||
if (holder.value().placement()
|
||||
instanceof ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement keyedPlacement) {
|
||||
return Optional.of(keyedPlacement.key);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static StructurePlacement copyPlacement(
|
||||
StructurePlacement placement,
|
||||
Optional<StructurePlacement.ExclusionZone> exclusionZone,
|
||||
@@ -357,26 +386,7 @@ final class DatapackStructureStateFilter {
|
||||
int salt = (int) declaredFieldValue(
|
||||
StructurePlacement.class, placement, int.class);
|
||||
|
||||
if (placement.getClass()
|
||||
== ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement.class) {
|
||||
ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement keyedPlacement =
|
||||
(ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement) placement;
|
||||
NativeStructureFrequencyScale scale = NativeStructureFrequencyScale.randomSpread(
|
||||
frequency, keyedPlacement.spacing(), keyedPlacement.separation(), frequencyMultiplier);
|
||||
return new ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement(
|
||||
keyedPlacement.key,
|
||||
locateOffset,
|
||||
frequencyReductionMethod,
|
||||
scale.frequency(),
|
||||
salt,
|
||||
exclusionZone,
|
||||
scale.spacing(),
|
||||
keyedPlacement.separation(),
|
||||
keyedPlacement.spreadType());
|
||||
}
|
||||
if (placement.getClass() == RandomSpreadStructurePlacement.class) {
|
||||
RandomSpreadStructurePlacement randomSpread =
|
||||
(RandomSpreadStructurePlacement) placement;
|
||||
if (placement instanceof RandomSpreadStructurePlacement randomSpread) {
|
||||
NativeStructureFrequencyScale scale = NativeStructureFrequencyScale.randomSpread(
|
||||
frequency, randomSpread.spacing(), randomSpread.separation(), frequencyMultiplier);
|
||||
return new RandomSpreadStructurePlacement(
|
||||
@@ -439,6 +449,46 @@ final class DatapackStructureStateFilter {
|
||||
}
|
||||
}
|
||||
|
||||
static final class StructureSetKeyIndex {
|
||||
private final Map<List<StructureSet.StructureSelectionEntry>, ResourceKey<StructureSet>>
|
||||
keysByEntries;
|
||||
|
||||
private StructureSetKeyIndex(
|
||||
Map<List<StructureSet.StructureSelectionEntry>, ResourceKey<StructureSet>>
|
||||
keysByEntries
|
||||
) {
|
||||
this.keysByEntries = keysByEntries;
|
||||
}
|
||||
|
||||
private static StructureSetKeyIndex create(
|
||||
Iterable<? extends Holder<StructureSet>> registeredStructureSets
|
||||
) {
|
||||
Map<List<StructureSet.StructureSelectionEntry>, ResourceKey<StructureSet>> keys =
|
||||
new IdentityHashMap<>();
|
||||
for (Holder<StructureSet> holder : registeredStructureSets) {
|
||||
Optional<ResourceKey<StructureSet>> key = holder.unwrapKey();
|
||||
if (key.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
List<StructureSet.StructureSelectionEntry> entries = holder.value().structures();
|
||||
ResourceKey<StructureSet> previous = keys.put(entries, key.get());
|
||||
if (previous != null && !previous.equals(key.get())) {
|
||||
throw new IllegalStateException(
|
||||
"Multiple registered structure sets share the same entry list");
|
||||
}
|
||||
}
|
||||
return new StructureSetKeyIndex(keys);
|
||||
}
|
||||
|
||||
private Optional<ResourceKey<StructureSet>> resolve(Holder<StructureSet> holder) {
|
||||
Optional<ResourceKey<StructureSet>> key = holder.unwrapKey();
|
||||
if (key.isPresent()) {
|
||||
return key;
|
||||
}
|
||||
return Optional.ofNullable(keysByEntries.get(holder.value().structures()));
|
||||
}
|
||||
}
|
||||
|
||||
record Selection(
|
||||
List<Holder<StructureSet>> structureSets,
|
||||
int retainedManagedSets,
|
||||
|
||||
+146
-132
@@ -15,7 +15,6 @@ import art.arcane.iris.core.nms.container.BiomeColor;
|
||||
import art.arcane.iris.core.nms.container.Pair;
|
||||
import art.arcane.iris.core.nms.container.BlockProperty;
|
||||
import art.arcane.iris.core.nms.datapack.DataVersion;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementSeed;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.data.chunk.TerrainChunk;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
@@ -55,8 +54,6 @@ import art.arcane.volmlib.util.nbt.tag.CompoundTag;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
||||
import it.unimi.dsi.fastutil.shorts.ShortList;
|
||||
import io.papermc.paper.world.saveddata.PaperLevelOverrides;
|
||||
import io.papermc.paper.world.saveddata.PaperWorldMetadata;
|
||||
import net.bytebuddy.ByteBuddy;
|
||||
import net.bytebuddy.agent.builder.AgentBuilder;
|
||||
import net.bytebuddy.agent.builder.ResettableClassFileTransformer;
|
||||
@@ -119,14 +116,14 @@ import net.minecraft.world.level.levelgen.XoroshiroRandomSource;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureCheck;
|
||||
import net.minecraft.world.level.levelgen.structure.BoundingBox;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureSet;
|
||||
import net.minecraft.world.level.levelgen.structure.structures.JigsawStructure;
|
||||
import net.minecraft.world.level.storage.PrimaryLevelData;
|
||||
import net.minecraft.world.level.storage.SavedDataStorage;
|
||||
import net.minecraft.world.level.levelgen.feature.AbstractHugeMushroomFeature;
|
||||
import net.minecraft.world.level.levelgen.feature.ConfiguredFeature;
|
||||
import net.minecraft.world.level.levelgen.feature.FallenTreeFeature;
|
||||
import net.minecraft.world.level.levelgen.feature.Feature;
|
||||
import net.minecraft.world.level.levelgen.feature.TreeFeature;
|
||||
import net.minecraft.world.level.storage.LevelStorageSource;
|
||||
import net.minecraft.world.level.levelgen.flat.FlatLayerInfo;
|
||||
import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorSettings;
|
||||
import org.bukkit.Bukkit;
|
||||
@@ -162,8 +159,6 @@ import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -173,23 +168,18 @@ import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class NMSBinding implements INMSBinding {
|
||||
private static final long CURRENT_WORLD_DATA_SNAPSHOT_TIMEOUT_SECONDS = 30L;
|
||||
|
||||
private final KMap<Biome, Object> baseBiomeCache = new KMap<>();
|
||||
private volatile DataVersion dataVersion;
|
||||
private final BlockData AIR = Material.AIR.createBlockData();
|
||||
private final AtomicCache<MCAIdMap<net.minecraft.world.level.biome.Biome>> biomeMapCache = new AtomicCache<>();
|
||||
private final AtomicBoolean injected = new AtomicBoolean();
|
||||
private volatile ResettableClassFileTransformer levelStorageAccessTransformer;
|
||||
private volatile ResettableClassFileTransformer serverLevelTransformer;
|
||||
private final AtomicCache<MCAIdMapper<BlockState>> registryCache = new AtomicCache<>();
|
||||
private final AtomicCache<MCAPalette<BlockState>> globalCache = new AtomicCache<>();
|
||||
@@ -1249,8 +1239,15 @@ public class NMSBinding implements INMSBinding {
|
||||
ChunkGeneratorStructureState currentState = level.getChunkSource().getGeneratorState();
|
||||
net.minecraft.world.level.chunk.ChunkGenerator generator = level.getChunkSource().getGenerator();
|
||||
ChunkGeneratorStructureState scopedState = createStructureState(level, generator, currentState);
|
||||
Registry<StructureSet> structureSetRegistry =
|
||||
level.registryAccess().lookupOrThrow(Registries.STRUCTURE_SET);
|
||||
DatapackStructureStateFilter.Selection selection = DatapackStructureStateFilter.filter(
|
||||
scopedState.possibleStructureSets(), scopeIndex, declaredSources, importedStructures);
|
||||
scopedState.possibleStructureSets(),
|
||||
scopeIndex,
|
||||
declaredSources,
|
||||
importedStructures,
|
||||
DatapackStructureStateFilter.keyIndex(
|
||||
structureSetRegistry.listElements().toList()));
|
||||
|
||||
Field possibleSetsField = getField(scopedState.getClass(), List.class);
|
||||
possibleSetsField.setAccessible(true);
|
||||
@@ -1328,7 +1325,7 @@ public class NMSBinding implements INMSBinding {
|
||||
level.registryAccess().lookupOrThrow(Registries.STRUCTURE_SET),
|
||||
currentState.randomState(),
|
||||
currentState.getLevelSeed(),
|
||||
currentState.conf);
|
||||
level.spigotConfig);
|
||||
}
|
||||
|
||||
private void initializeAndPublishStructureState(
|
||||
@@ -1542,6 +1539,18 @@ public class NMSBinding implements INMSBinding {
|
||||
}
|
||||
try {
|
||||
IrisLogging.info("Injecting Bukkit");
|
||||
levelStorageAccessTransformer = new AgentBuilder.Default()
|
||||
.disableClassFormatChanges()
|
||||
.with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
|
||||
.type(ElementMatchers.is(LevelStorageSource.LevelStorageAccess.class))
|
||||
.transform((builder, typeDescription, classLoader, module, protectionDomain) ->
|
||||
builder.visit(Advice.to(LevelStorageAccessAdvice.class).on(ElementMatchers.isConstructor()
|
||||
.and(ElementMatchers.takesArguments(4))
|
||||
.and(ElementMatchers.takesArgument(0, LevelStorageSource.class))
|
||||
.and(ElementMatchers.takesArgument(1, String.class))
|
||||
.and(ElementMatchers.takesArgument(2, Path.class))
|
||||
.and(ElementMatchers.takesArgument(3, ResourceKey.class)))))
|
||||
.installOn(Agent.getInstrumentation());
|
||||
serverLevelTransformer = new AgentBuilder.Default()
|
||||
.disableClassFormatChanges()
|
||||
.with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
|
||||
@@ -1549,8 +1558,7 @@ public class NMSBinding implements INMSBinding {
|
||||
.transform((builder, typeDescription, classLoader, module, protectionDomain) ->
|
||||
builder.visit(Advice.to(ServerLevelAdvice.class).on(ElementMatchers.isConstructor()
|
||||
.and(ElementMatchers.takesArgument(0, MinecraftServer.class))
|
||||
.and(ElementMatchers.takesArgument(5, LevelStem.class))
|
||||
.and(ElementMatchers.takesArgument(12, ChunkGenerator.class)))))
|
||||
.and(ElementMatchers.takesArgument(5, LevelStem.class)))))
|
||||
.installOn(Agent.getInstrumentation());
|
||||
ByteBuddy buddy = new ByteBuddy();
|
||||
for (Class<?> clazz : List.of(ChunkAccess.class, ProtoChunk.class)) {
|
||||
@@ -1565,12 +1573,17 @@ public class NMSBinding implements INMSBinding {
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error(C.RED + "Failed to inject Bukkit");
|
||||
e.printStackTrace();
|
||||
// The ServerLevel transformer may already be installed when the ChunkAccess
|
||||
// redefine throws; remove it or a retry would stack a second one and orphan
|
||||
// this one permanently.
|
||||
ResettableClassFileTransformer partial = serverLevelTransformer;
|
||||
ResettableClassFileTransformer partialServerLevel = serverLevelTransformer;
|
||||
ResettableClassFileTransformer partialStorageAccess = levelStorageAccessTransformer;
|
||||
serverLevelTransformer = null;
|
||||
if (partial != null) {
|
||||
levelStorageAccessTransformer = null;
|
||||
for (ResettableClassFileTransformer partial : new ResettableClassFileTransformer[]{
|
||||
partialServerLevel,
|
||||
partialStorageAccess
|
||||
}) {
|
||||
if (partial == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
partial.reset(Agent.getInstrumentation(), AgentBuilder.RedefinitionStrategy.RETRANSFORMATION);
|
||||
} catch (Throwable ignored) {
|
||||
@@ -1586,26 +1599,36 @@ public class NMSBinding implements INMSBinding {
|
||||
if (!injected.get())
|
||||
return;
|
||||
try {
|
||||
Agent.getInstrumentation().retransformClasses(ServerLevel.class);
|
||||
Agent.getInstrumentation().retransformClasses(
|
||||
LevelStorageSource.LevelStorageAccess.class,
|
||||
ServerLevel.class
|
||||
);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error(C.RED + "Failed to re-apply ServerLevel injection");
|
||||
IrisLogging.error(C.RED + "Failed to re-apply Bukkit world lifecycle injection");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void uninjectBukkit() {
|
||||
synchronized (injected) {
|
||||
ResettableClassFileTransformer transformer = serverLevelTransformer;
|
||||
ResettableClassFileTransformer activeServerLevel = serverLevelTransformer;
|
||||
ResettableClassFileTransformer activeStorageAccess = levelStorageAccessTransformer;
|
||||
serverLevelTransformer = null;
|
||||
levelStorageAccessTransformer = null;
|
||||
injected.set(false);
|
||||
if (transformer == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
transformer.reset(Agent.getInstrumentation(), AgentBuilder.RedefinitionStrategy.RETRANSFORMATION);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error(C.RED + "Failed to remove ServerLevel injection");
|
||||
e.printStackTrace();
|
||||
for (ResettableClassFileTransformer transformer : new ResettableClassFileTransformer[]{
|
||||
activeServerLevel,
|
||||
activeStorageAccess
|
||||
}) {
|
||||
if (transformer == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
transformer.reset(Agent.getInstrumentation(), AgentBuilder.RedefinitionStrategy.RETRANSFORMATION);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error(C.RED + "Failed to remove Bukkit world lifecycle injection");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1616,103 +1639,7 @@ public class NMSBinding implements INMSBinding {
|
||||
Path targetWorldDirectory,
|
||||
long seed
|
||||
) throws IOException {
|
||||
CraftServer craftServer = (CraftServer) Bukkit.getServer();
|
||||
MinecraftServer server = craftServer.getHandle().getServer();
|
||||
PaperLevelOverrides levelOverrides = captureCurrentPaperLevelOverrides(craftServer, server);
|
||||
|
||||
Path targetWorld = targetWorldDirectory.toAbsolutePath().normalize();
|
||||
UUID metadataUuid = UUID.randomUUID();
|
||||
WorldReplacementSeed.copyWithAuthoritativeSeed(sourceWorldDirectory, targetWorld, seed);
|
||||
try (SavedDataStorage savedDataStorage = new SavedDataStorage(
|
||||
targetWorld.resolve("data"),
|
||||
server.getFixerUpper(),
|
||||
server.registryAccess()
|
||||
)) {
|
||||
savedDataStorage.set(PaperWorldMetadata.TYPE, new PaperWorldMetadata(metadataUuid));
|
||||
savedDataStorage.set(
|
||||
PaperLevelOverrides.TYPE,
|
||||
levelOverrides
|
||||
);
|
||||
}
|
||||
|
||||
List<Path> requiredDataFiles = List.of(
|
||||
targetWorld.resolve("data/minecraft/world_gen_settings.dat"),
|
||||
targetWorld.resolve("data/paper/metadata.dat"),
|
||||
targetWorld.resolve("data/paper/level_overrides.dat")
|
||||
);
|
||||
for (Path requiredDataFile : requiredDataFiles) {
|
||||
if (!Files.isRegularFile(requiredDataFile, LinkOption.NOFOLLOW_LINKS)) {
|
||||
throw new IOException("Current Paper world data was not written: " + requiredDataFile);
|
||||
}
|
||||
}
|
||||
|
||||
long writtenSeed = WorldReplacementSeed.readAuthoritativeSeed(targetWorld);
|
||||
if (writtenSeed != seed) {
|
||||
throw new IOException("Current Paper world data did not retain the requested seed.");
|
||||
}
|
||||
|
||||
try (SavedDataStorage verificationStorage = new SavedDataStorage(
|
||||
targetWorld.resolve("data"),
|
||||
server.getFixerUpper(),
|
||||
server.registryAccess()
|
||||
)) {
|
||||
PaperWorldMetadata metadata = verificationStorage.get(PaperWorldMetadata.TYPE);
|
||||
if (metadata == null || !metadataUuid.equals(metadata.uuid())) {
|
||||
throw new IOException("Current Paper world metadata could not be verified.");
|
||||
}
|
||||
PaperLevelOverrides overrides = verificationStorage.get(PaperLevelOverrides.TYPE);
|
||||
if (overrides == null || overrides.isInitialized()) {
|
||||
throw new IOException("Current Paper level overrides could not be verified.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PaperLevelOverrides captureCurrentPaperLevelOverrides(
|
||||
CraftServer craftServer,
|
||||
MinecraftServer server
|
||||
) throws IOException {
|
||||
if (craftServer.isGlobalTickThread()) {
|
||||
return createCurrentPaperLevelOverrides(craftServer, server);
|
||||
}
|
||||
if (J.isFolia() && J.isPrimaryThread()) {
|
||||
throw new IOException("Current Paper world data cannot be staged from a Folia region tick thread.");
|
||||
}
|
||||
|
||||
CompletableFuture<PaperLevelOverrides> captured = new CompletableFuture<>();
|
||||
boolean scheduled = J.runGlobal(() -> {
|
||||
try {
|
||||
captured.complete(createCurrentPaperLevelOverrides(craftServer, server));
|
||||
} catch (Throwable failure) {
|
||||
captured.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
if (!scheduled) {
|
||||
throw new IOException("Could not schedule the current Paper level-data snapshot on the global thread.");
|
||||
}
|
||||
|
||||
try {
|
||||
return captured.get(CURRENT_WORLD_DATA_SNAPSHOT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException failure) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted while capturing current Paper level data.", failure);
|
||||
} catch (ExecutionException failure) {
|
||||
throw new IOException("Could not capture current Paper level data.", failure.getCause());
|
||||
} catch (TimeoutException failure) {
|
||||
throw new IOException("Timed out while capturing current Paper level data.", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private PaperLevelOverrides createCurrentPaperLevelOverrides(
|
||||
CraftServer craftServer,
|
||||
MinecraftServer server
|
||||
) throws IOException {
|
||||
if (!craftServer.isGlobalTickThread()) {
|
||||
throw new IOException("Current Paper level data must be captured on the global tick thread.");
|
||||
}
|
||||
if (!(server.getWorldData().overworldData() instanceof PrimaryLevelData primaryLevelData)) {
|
||||
throw new IOException("Paper primary level data is unavailable for current world data staging.");
|
||||
}
|
||||
return PaperLevelOverrides.createFromLiveLevelData(primaryLevelData);
|
||||
CurrentPaperWorldDataWriter.write(sourceWorldDirectory, targetWorldDirectory, seed);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -1777,13 +1704,76 @@ public class NMSBinding implements INMSBinding {
|
||||
}
|
||||
}
|
||||
|
||||
private static class LevelStorageAccessAdvice {
|
||||
@Advice.OnMethodEnter
|
||||
static void enter(
|
||||
@Advice.Argument(1) String levelId,
|
||||
@Advice.Argument(value = 3, readOnly = false) ResourceKey<LevelStem> dimensionType
|
||||
) {
|
||||
if (levelId == null || levelId.isBlank()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ClassLoader pluginClassLoader;
|
||||
Class<?> generatorType;
|
||||
Class<?> stagingType;
|
||||
try {
|
||||
org.bukkit.plugin.Plugin irisPlugin = Bukkit.getPluginManager().getPlugin("Iris");
|
||||
if (irisPlugin == null) {
|
||||
return;
|
||||
}
|
||||
pluginClassLoader = irisPlugin.getClass().getClassLoader();
|
||||
generatorType = Class.forName("art.arcane.iris.engine.platform.PlatformChunkGenerator", true, pluginClassLoader);
|
||||
stagingType = Class.forName("art.arcane.iris.core.lifecycle.WorldLifecycleStaging", true, pluginClassLoader);
|
||||
} catch (Throwable ignored) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object generator;
|
||||
try {
|
||||
generator = stagingType
|
||||
.getDeclaredMethod("peekStemGenerator", String.class)
|
||||
.invoke(null, levelId);
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Iris failed to inspect the staged world generator",
|
||||
e instanceof InvocationTargetException ex ? ex.getCause() : e);
|
||||
}
|
||||
if (generator == null || !generatorType.isInstance(generator)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Object target = generatorType.getMethod("getTarget").invoke(generator);
|
||||
if (target == null) {
|
||||
throw new IllegalStateException("Iris generator has no engine target.");
|
||||
}
|
||||
Object world = target.getClass().getMethod("getWorld").invoke(target);
|
||||
if (world == null) {
|
||||
throw new IllegalStateException("Iris generator target has no world identity.");
|
||||
}
|
||||
Object rawIdentity = world.getClass().getMethod("identity").invoke(world);
|
||||
String worldIdentity = rawIdentity == null ? "" : rawIdentity.toString().trim();
|
||||
Identifier worldIdentifier = Identifier.parse(worldIdentity);
|
||||
if (!"iris".equals(worldIdentifier.getNamespace())
|
||||
&& !"minecraft".equals(worldIdentifier.getNamespace())) {
|
||||
throw new IllegalStateException(
|
||||
"Iris generator has an unmanaged world identity: " + worldIdentity);
|
||||
}
|
||||
dimensionType = ResourceKey.create(Registries.LEVEL_STEM, worldIdentifier);
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Iris failed to bind the staged world storage identity",
|
||||
e instanceof InvocationTargetException ex ? ex.getCause() : e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class ServerLevelAdvice {
|
||||
@Advice.OnMethodEnter
|
||||
static void enter(
|
||||
@Advice.Argument(0) MinecraftServer server,
|
||||
@Advice.Argument(4) ResourceKey<Level> dimensionKey,
|
||||
@Advice.Argument(value = 4, readOnly = false) ResourceKey<Level> dimensionKey,
|
||||
@Advice.Argument(value = 5, readOnly = false) LevelStem levelStem,
|
||||
@Advice.Argument(12) ChunkGenerator constructorGenerator
|
||||
@Advice.AllArguments Object[] constructorArguments
|
||||
) {
|
||||
if (dimensionKey == null)
|
||||
return;
|
||||
@@ -1818,6 +1808,13 @@ public class NMSBinding implements INMSBinding {
|
||||
// the vanilla stem corrupts generation.
|
||||
ChunkGenerator gen = null;
|
||||
try {
|
||||
ChunkGenerator constructorGenerator = null;
|
||||
for (Object argument : constructorArguments) {
|
||||
if (argument instanceof ChunkGenerator candidate) {
|
||||
constructorGenerator = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Object generator = generatorType.isInstance(constructorGenerator) ? constructorGenerator : null;
|
||||
if (generator == null) {
|
||||
generator = stagingType
|
||||
@@ -1855,10 +1852,27 @@ public class NMSBinding implements INMSBinding {
|
||||
if (stemMethod == null) {
|
||||
throw new IllegalStateException("Iris binding is missing createRuntimeLevelStem.");
|
||||
}
|
||||
Object target = generatorType.getMethod("getTarget").invoke(gen);
|
||||
if (target == null) {
|
||||
throw new IllegalStateException("Iris generator has no engine target.");
|
||||
}
|
||||
Object world = target.getClass().getMethod("getWorld").invoke(target);
|
||||
if (world == null) {
|
||||
throw new IllegalStateException("Iris generator target has no world identity.");
|
||||
}
|
||||
Object rawIdentity = world.getClass().getMethod("identity").invoke(world);
|
||||
String worldIdentity = rawIdentity == null ? "" : rawIdentity.toString().trim();
|
||||
Identifier worldIdentifier = Identifier.parse(worldIdentity);
|
||||
if (!"iris".equals(worldIdentifier.getNamespace())
|
||||
&& !"minecraft".equals(worldIdentifier.getNamespace())) {
|
||||
throw new IllegalStateException(
|
||||
"Iris generator has an unmanaged world identity: " + worldIdentity);
|
||||
}
|
||||
Object resolvedStem = stemMethod.invoke(bindings, server.registryAccess(), gen);
|
||||
if (!(resolvedStem instanceof LevelStem runtimeStem)) {
|
||||
throw new IllegalStateException("Iris runtime LevelStem binding returned " + (resolvedStem == null ? "null" : resolvedStem.getClass().getName()) + ".");
|
||||
}
|
||||
dimensionKey = ResourceKey.create(Registries.DIMENSION, worldIdentifier);
|
||||
levelStem = runtimeStem;
|
||||
} catch (Throwable e) {
|
||||
throw new RuntimeException("Iris failed to replace the levelStem", e instanceof InvocationTargetException ex ? ex.getCause() : e);
|
||||
|
||||
+8
@@ -215,6 +215,14 @@ final class NativeStructureWorldgenAccess implements WorldGenLevel {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkAccess getChunk(int chunkX, int chunkZ) {
|
||||
if (isInsideGenerationRegion(chunkX, chunkZ)) {
|
||||
return delegate.getChunk(chunkX, chunkZ);
|
||||
}
|
||||
return outsideChunk(chunkX, chunkZ);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChunkAccess getChunk(int chunkX, int chunkZ, ChunkStatus status, boolean create) {
|
||||
if (isInsideGenerationRegion(chunkX, chunkZ)) {
|
||||
|
||||
+45
-12
@@ -3,29 +3,54 @@ package art.arcane.iris.core.nms.v26_2_R1;
|
||||
import art.arcane.iris.core.nms.INMSBinding;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class NMSBindingCurrentPaperWorldDataContractTest {
|
||||
@Test
|
||||
public void stagesAllCurrentPaperWorldDataFromLiveServerState() throws Exception {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.nmsBindingSource")));
|
||||
public void bindingDelegatesWithoutLinkingPaperSavedDataClasses() throws Exception {
|
||||
String bindingSource = Files.readString(bindingSourcePath());
|
||||
String writer = section(
|
||||
source,
|
||||
bindingSource,
|
||||
"public void writeCurrentPaperWorldData(",
|
||||
"public KMap<Material, List<BlockProperty>> getBlockProperties()"
|
||||
"public boolean awaitServerShutdownBoundary("
|
||||
);
|
||||
|
||||
assertTrue(writer.contains("CurrentPaperWorldDataWriter.write("));
|
||||
assertFalse(bindingSource.contains("PaperWorldMetadata"));
|
||||
assertFalse(bindingSource.contains("PaperLevelOverrides"));
|
||||
assertFalse(bindingSource.contains("io.papermc.paper.world.saveddata"));
|
||||
|
||||
InputStream classResource = NMSBindingCurrentPaperWorldDataContractTest.class
|
||||
.getResourceAsStream("NMSBinding.class");
|
||||
assertNotNull(classResource);
|
||||
try (InputStream input = classResource) {
|
||||
String classFile = new String(input.readAllBytes(), StandardCharsets.ISO_8859_1);
|
||||
assertFalse(classFile.contains("PaperWorldMetadata"));
|
||||
assertFalse(classFile.contains("PaperLevelOverrides"));
|
||||
assertFalse(classFile.contains("io/papermc/paper/world/saveddata"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stagesAllCurrentPaperWorldDataFromLiveServerState() throws Exception {
|
||||
String writer = Files.readString(writerSourcePath());
|
||||
|
||||
assertTrue(writer.contains("WorldReplacementSeed.copyWithAuthoritativeSeed("));
|
||||
assertTrue(writer.contains("UUID metadataUuid = UUID.randomUUID()"));
|
||||
assertTrue(writer.contains("new PaperWorldMetadata(metadataUuid)"));
|
||||
assertTrue(writer.contains("captureCurrentPaperLevelOverrides(craftServer, server)"));
|
||||
assertTrue(writer.contains("captureLevelOverrides(craftServer, server)"));
|
||||
assertTrue(writer.indexOf("captureLevelOverrides(craftServer, server)")
|
||||
< writer.indexOf("WorldReplacementSeed.copyWithAuthoritativeSeed("));
|
||||
assertTrue(writer.contains("new SavedDataStorage("));
|
||||
assertTrue(writer.contains("server.getFixerUpper()"));
|
||||
assertTrue(writer.contains("server.registryAccess()"));
|
||||
@@ -44,23 +69,23 @@ public class NMSBindingCurrentPaperWorldDataContractTest {
|
||||
|
||||
@Test
|
||||
public void capturesOnlyLiveLevelOverridesOnTheGlobalThread() throws Exception {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.nmsBindingSource")));
|
||||
String source = Files.readString(writerSourcePath());
|
||||
String capture = section(
|
||||
source,
|
||||
"private PaperLevelOverrides captureCurrentPaperLevelOverrides(",
|
||||
"private PaperLevelOverrides createCurrentPaperLevelOverrides("
|
||||
"private static PaperLevelOverrides captureLevelOverrides(",
|
||||
"private static PaperLevelOverrides createLevelOverrides("
|
||||
);
|
||||
String create = section(
|
||||
source,
|
||||
"private PaperLevelOverrides createCurrentPaperLevelOverrides(",
|
||||
"public KMap<Material, List<BlockProperty>> getBlockProperties()"
|
||||
"private static PaperLevelOverrides createLevelOverrides(",
|
||||
"\n }\n}"
|
||||
);
|
||||
|
||||
assertTrue(capture.contains("craftServer.isGlobalTickThread()"));
|
||||
assertTrue(capture.contains("J.isFolia() && J.isPrimaryThread()"));
|
||||
assertTrue(capture.contains("J.runGlobal("));
|
||||
assertTrue(capture.contains("createCurrentPaperLevelOverrides(craftServer, server)"));
|
||||
assertTrue(capture.contains("captured.get(CURRENT_WORLD_DATA_SNAPSHOT_TIMEOUT_SECONDS"));
|
||||
assertTrue(capture.contains("createLevelOverrides(craftServer, server)"));
|
||||
assertTrue(capture.contains("captured.get(SNAPSHOT_TIMEOUT_SECONDS"));
|
||||
assertTrue(capture.contains("Thread.currentThread().interrupt()"));
|
||||
assertTrue(create.contains("if (!craftServer.isGlobalTickThread())"));
|
||||
assertTrue(create.indexOf("if (!craftServer.isGlobalTickThread())")
|
||||
@@ -89,6 +114,14 @@ public class NMSBindingCurrentPaperWorldDataContractTest {
|
||||
assertTrue(error.getMessage().contains("does not support current Paper world data staging"));
|
||||
}
|
||||
|
||||
private static Path bindingSourcePath() {
|
||||
return Path.of(System.getProperty("iris.nmsBindingSource"));
|
||||
}
|
||||
|
||||
private static Path writerSourcePath() {
|
||||
return bindingSourcePath().resolveSibling("CurrentPaperWorldDataWriter.java");
|
||||
}
|
||||
|
||||
private static String section(String source, String startMarker, String endMarker) {
|
||||
int start = source.indexOf(startMarker);
|
||||
int end = source.indexOf(endMarker, start);
|
||||
|
||||
+72
-23
@@ -27,6 +27,8 @@ import org.junit.Test;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
@@ -38,8 +40,8 @@ import java.util.stream.Stream;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotSame;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class NMSBindingDatapackStructureScopeTest {
|
||||
@@ -108,28 +110,56 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void spigotDirectHolderRetainsItsStructureSetKey() {
|
||||
public void spigotDirectHolderRecoversItsRegistryKeyFromSharedEntries() {
|
||||
ResourceKey<StructureSet> key = ResourceKey.create(
|
||||
Registries.STRUCTURE_SET,
|
||||
Identifier.parse("minecraft:villages"));
|
||||
ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement placement =
|
||||
new ChunkGeneratorStructureState.KeyedRandomSpreadStructurePlacement(
|
||||
key,
|
||||
Vec3i.ZERO,
|
||||
StructurePlacement.FrequencyReductionMethod.DEFAULT,
|
||||
1.0F,
|
||||
10387312,
|
||||
Optional.empty(),
|
||||
34,
|
||||
8,
|
||||
RandomSpreadType.LINEAR);
|
||||
StructureSet structureSet = new StructureSet(
|
||||
List.of(new StructureSet.StructureSelectionEntry(
|
||||
structureHolder("minecraft:village_plains"), 1)),
|
||||
placement);
|
||||
Identifier.parse("managed:illager_barracks"));
|
||||
List<StructureSet.StructureSelectionEntry> entries = List.of(
|
||||
new StructureSet.StructureSelectionEntry(
|
||||
structureHolder("minecraft:pillager_outpost"), 1));
|
||||
Holder<StructureSet> registered = new KeyedHolder<>(key, new StructureSet(
|
||||
entries,
|
||||
new RandomSpreadStructurePlacement(
|
||||
34, 8, RandomSpreadType.LINEAR, 10387312)));
|
||||
Holder<StructureSet> spigotDirect = Holder.direct(new StructureSet(
|
||||
entries,
|
||||
new RandomSpreadStructurePlacement(
|
||||
34, 8, RandomSpreadType.LINEAR, 14357620)));
|
||||
DatapackStructureScopeIndex scopeIndex = index(
|
||||
List.of(), List.of("managed:illager_barracks"));
|
||||
DatapackStructureStateFilter.StructureSetKeyIndex keyIndex =
|
||||
DatapackStructureStateFilter.keyIndex(List.of(registered));
|
||||
|
||||
assertEquals("minecraft:villages",
|
||||
DatapackStructureStateFilter.structureSetKey(Holder.direct(structureSet)));
|
||||
DatapackStructureStateFilter.Selection excluded =
|
||||
DatapackStructureStateFilter.filter(
|
||||
List.of(spigotDirect),
|
||||
scopeIndex,
|
||||
Set.of(),
|
||||
new IrisImportedStructureControl(),
|
||||
keyIndex);
|
||||
DatapackStructureStateFilter.Selection retained =
|
||||
DatapackStructureStateFilter.filter(
|
||||
List.of(spigotDirect),
|
||||
scopeIndex,
|
||||
scopeIndex.declaredSources(List.of(SOURCE)),
|
||||
new IrisImportedStructureControl(),
|
||||
keyIndex);
|
||||
|
||||
assertEquals(0, excluded.structureSets().size());
|
||||
assertEquals(1, excluded.excludedManagedSets());
|
||||
assertSame(spigotDirect, retained.structureSets().getFirst());
|
||||
assertEquals(1, retained.retainedManagedSets());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void structureScopeDoesNotLinkPaperOnlyPlacementClasses() throws IOException {
|
||||
InputStream classResource = NMSBindingDatapackStructureScopeTest.class
|
||||
.getResourceAsStream("DatapackStructureStateFilter.class");
|
||||
assertNotNull(classResource);
|
||||
try (InputStream input = classResource) {
|
||||
String classFile = new String(input.readAllBytes(), StandardCharsets.ISO_8859_1);
|
||||
assertFalse(classFile.contains("KeyedRandomSpreadStructurePlacement"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -271,7 +301,7 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void affectedRandomSpreadSubclassFailsInsteadOfLosingSubtypeBehavior() {
|
||||
public void randomSpreadSubtypeUsesTheCanonicalPlacementContract() {
|
||||
Holder<StructureSet> custom = structureSetHolder(
|
||||
"example:custom",
|
||||
new CustomRandomSpreadPlacement(),
|
||||
@@ -283,8 +313,12 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
IrisImportedStructureControl control = new IrisImportedStructureControl()
|
||||
.setFrequencyOverrides(overrides);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> DatapackStructureStateFilter.filter(
|
||||
List.of(custom), index(List.of(), List.of()), Set.of(), control));
|
||||
DatapackStructureStateFilter.Selection selection = DatapackStructureStateFilter.filter(
|
||||
List.of(custom), index(List.of(), List.of()), Set.of(), control);
|
||||
StructurePlacement placement = selection.structureSets().getFirst().value().placement();
|
||||
|
||||
assertEquals(RandomSpreadStructurePlacement.class, placement.getClass());
|
||||
assertEquals(26, ((RandomSpreadStructurePlacement) placement).spacing());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -395,6 +429,21 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
assertTrue(structureRetarget > identityGate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void structureStateRecreationUsesTheWorldOwnedSpigotConfiguration() throws IOException {
|
||||
Path chunkGeneratorSource = Path.of(System.getProperty("iris.nmsChunkGeneratorSource"));
|
||||
String source = Files.readString(chunkGeneratorSource.resolveSibling("NMSBinding.java"));
|
||||
int methodStart = source.indexOf("private ChunkGeneratorStructureState createStructureState(");
|
||||
int methodEnd = source.indexOf(
|
||||
"\n private void initializeAndPublishStructureState(", methodStart);
|
||||
|
||||
assertTrue(methodStart >= 0);
|
||||
assertTrue(methodEnd > methodStart);
|
||||
String method = source.substring(methodStart, methodEnd);
|
||||
assertTrue(method.contains("level.spigotConfig"));
|
||||
assertFalse(method.contains("currentState.conf"));
|
||||
}
|
||||
|
||||
private static DatapackStructureScopeIndex index(
|
||||
List<String> structureKeys,
|
||||
List<String> structureSetKeys
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class NMSBindingServerLevelAdviceContractTest {
|
||||
@Test
|
||||
public void serverLevelAdviceSupportsCurrentSpigotAndPaperConstructorLayouts() throws Exception {
|
||||
String source = Files.readString(
|
||||
Path.of(System.getProperty("iris.nmsBindingSource")));
|
||||
String transformer = section(
|
||||
source,
|
||||
"public boolean injectBukkit()",
|
||||
"public void ensureServerLevelInjection()");
|
||||
String advice = section(
|
||||
source,
|
||||
"private static class ServerLevelAdvice",
|
||||
"\n }\n}");
|
||||
|
||||
assertTrue(transformer.contains("takesArgument(0, MinecraftServer.class)"));
|
||||
assertTrue(transformer.contains("takesArgument(5, LevelStem.class)"));
|
||||
assertFalse(transformer.contains("takesArgument(12, ChunkGenerator.class)"));
|
||||
assertFalse(transformer.contains("takesArgument(13, ChunkGenerator.class)"));
|
||||
assertTrue(advice.contains("@Advice.AllArguments Object[] constructorArguments"));
|
||||
assertTrue(advice.contains("argument instanceof ChunkGenerator candidate"));
|
||||
assertFalse(advice.contains("@Advice.Argument(12)"));
|
||||
assertFalse(advice.contains("@Advice.Argument(13)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void currentSpigotStorageAccessReceivesManagedIdentityBeforeConstruction() throws Exception {
|
||||
String source = Files.readString(
|
||||
Path.of(System.getProperty("iris.nmsBindingSource")));
|
||||
String transformer = section(
|
||||
source,
|
||||
"public boolean injectBukkit()",
|
||||
"public void ensureServerLevelInjection()");
|
||||
String advice = section(
|
||||
source,
|
||||
"private static class LevelStorageAccessAdvice",
|
||||
"private static class ServerLevelAdvice");
|
||||
|
||||
assertTrue(transformer.contains(
|
||||
".type(ElementMatchers.is(LevelStorageSource.LevelStorageAccess.class))"));
|
||||
assertTrue(transformer.contains("Advice.to(LevelStorageAccessAdvice.class)"));
|
||||
assertTrue(transformer.contains("ElementMatchers.takesArguments(4)"));
|
||||
assertTrue(transformer.contains(
|
||||
"ElementMatchers.takesArgument(0, LevelStorageSource.class)"));
|
||||
assertTrue(transformer.contains("ElementMatchers.takesArgument(1, String.class)"));
|
||||
assertTrue(transformer.contains("ElementMatchers.takesArgument(2, Path.class)"));
|
||||
assertTrue(transformer.contains("ElementMatchers.takesArgument(3, ResourceKey.class)"));
|
||||
assertTrue(advice.contains("@Advice.Argument(1) String levelId"));
|
||||
assertTrue(advice.contains(
|
||||
"@Advice.Argument(value = 3, readOnly = false) ResourceKey<LevelStem> dimensionType"));
|
||||
assertTrue(advice.contains("getDeclaredMethod(\"peekStemGenerator\", String.class)"));
|
||||
assertTrue(advice.contains(".invoke(null, levelId)"));
|
||||
assertTrue(advice.contains(
|
||||
"dimensionType = ResourceKey.create(Registries.LEVEL_STEM, worldIdentifier);"));
|
||||
assertFalse(advice.contains("dimensionRoot("));
|
||||
assertFalse(advice.contains("Files.copy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ownedWorldPublishesItsManagedIdentityAndRuntimeStemTogether() throws Exception {
|
||||
String source = Files.readString(
|
||||
Path.of(System.getProperty("iris.nmsBindingSource")));
|
||||
String advice = section(
|
||||
source,
|
||||
"private static class ServerLevelAdvice",
|
||||
"\n }\n}");
|
||||
|
||||
assertTrue(advice.contains(
|
||||
"@Advice.Argument(value = 4, readOnly = false) ResourceKey<Level> dimensionKey"));
|
||||
assertTrue(advice.contains("getMethod(\"getTarget\")"));
|
||||
assertTrue(advice.contains("getMethod(\"getWorld\")"));
|
||||
assertTrue(advice.contains("getMethod(\"identity\")"));
|
||||
assertTrue(advice.contains("\"iris\".equals(worldIdentifier.getNamespace())"));
|
||||
assertTrue(advice.contains("\"minecraft\".equals(worldIdentifier.getNamespace())"));
|
||||
|
||||
int resolvedStem = advice.indexOf("Object resolvedStem = stemMethod.invoke(");
|
||||
int validatedStem = advice.indexOf("resolvedStem instanceof LevelStem runtimeStem");
|
||||
int identityPublication = advice.indexOf(
|
||||
"dimensionKey = ResourceKey.create(Registries.DIMENSION, worldIdentifier);");
|
||||
int stemPublication = advice.indexOf("levelStem = runtimeStem;");
|
||||
assertTrue(resolvedStem >= 0);
|
||||
assertTrue(validatedStem > resolvedStem);
|
||||
assertTrue(identityPublication > validatedStem);
|
||||
assertTrue(stemPublication > identityPublication);
|
||||
}
|
||||
|
||||
private static String section(String source, String startMarker, String endMarker) {
|
||||
int start = source.indexOf(startMarker);
|
||||
int end = source.indexOf(endMarker, start);
|
||||
assertTrue("Missing source section starting with " + startMarker, start >= 0);
|
||||
assertTrue("Missing source section ending with " + endMarker, end > start);
|
||||
return source.substring(start, end);
|
||||
}
|
||||
}
|
||||
+24
-1
@@ -135,6 +135,18 @@ public class NativeStructureWorldgenAccessTest {
|
||||
assertEquals(1, recording.blockTicks.count());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void statuslessChunkReadsPreserveWorldgenDelegateSemantics() {
|
||||
RecordingDelegate recording = new RecordingDelegate();
|
||||
NativeStructureWorldgenAccess access = access(recording);
|
||||
ChunkPos generationCenter = generationCenter();
|
||||
|
||||
assertNull(access.getChunk(generationCenter.getWorldPosition()));
|
||||
|
||||
assertEquals(1, recording.statuslessChunkReads);
|
||||
assertEquals(0, recording.statusChunkReads);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void entityQueriesRejectDisjointAreasAndClampOverlaps() {
|
||||
RecordingDelegate recording = new RecordingDelegate();
|
||||
@@ -187,6 +199,8 @@ public class NativeStructureWorldgenAccessTest {
|
||||
private int terrainReads;
|
||||
private int heightReads;
|
||||
private int chunkReads;
|
||||
private int statuslessChunkReads;
|
||||
private int statusChunkReads;
|
||||
private int mutations;
|
||||
private int events;
|
||||
|
||||
@@ -240,7 +254,16 @@ public class NativeStructureWorldgenAccessTest {
|
||||
terrainReads++;
|
||||
return Blocks.WATER.defaultBlockState().getFluidState();
|
||||
}
|
||||
if (name.equals("getChunk") || name.equals("getChunkIfLoadedImmediately")) {
|
||||
if (name.equals("getChunk")) {
|
||||
chunkReads++;
|
||||
if (arguments.length == 2) {
|
||||
statuslessChunkReads++;
|
||||
} else {
|
||||
statusChunkReads++;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (name.equals("getChunkIfLoadedImmediately")) {
|
||||
chunkReads++;
|
||||
return null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user