9
0
mirror of https://github.com/VolmitSoftware/Iris.git synced 2025-12-31 12:56:35 +00:00

Merge branch 'mca' of https://github.com/RePixelatedMC/Iris into PixelatedDev

This commit is contained in:
RePixelatedMC
2024-05-04 11:26:47 +02:00
15 changed files with 1367 additions and 1078 deletions

View File

@@ -69,7 +69,6 @@ IrisAccess access=IrisToolbelt.createWorld() // If you like builders...
.name("myWorld") // The world name
.dimension("terrifyinghands")
.seed(69133742) // The world seed
.headless(true) // Headless make gen go fast
.pregen(PregenTask // Define a pregen job to run
.builder()
.center(new Position2(0,0)) // REGION coords (1 region = 32x32 chunks)

View File

@@ -25,7 +25,7 @@ plugins {
id "de.undercouch.download" version "5.0.1"
}
version '3.2.4-1.19.2-1.20.4'
version '3.2.6-1.19.2-1.20.4'
def specialSourceVersion = '1.11.0' //[NMS]
// ADD YOURSELF AS A NEW LINE IF YOU WANT YOUR OWN BUILD TASK GENERATED

View File

@@ -728,6 +728,11 @@ public class Iris extends VolmitPlugin implements Listener {
Iris.info("Resolved missing dimension, proceeding with generation.");
}
}
File packFolder = new File(Bukkit.getWorldContainer(), worldName + "/iris/pack");
if (packFolder.exists()) {
IrisDimension worldDim = IrisData.get(packFolder).getDimensionLoader().load(id);
if (worldDim != null) dim = worldDim;
}
Iris.debug("Assuming IrisDimension: " + dim.getName());
@@ -747,6 +752,9 @@ public class Iris extends VolmitPlugin implements Listener {
ff.mkdirs();
service(StudioSVC.class).installIntoWorld(getSender(), dim.getLoadKey(), w.worldFolder());
}
if (!INMS.get().registerDimension(worldName, dim)) {
throw new IllegalStateException("Unable to register dimension " + dim.getName());
}
return new BukkitChunkGenerator(w, false, ff, dim.getLoadKey(), false);
}

View File

@@ -135,30 +135,6 @@ public class ServerConfigurator {
public static void installDataPacks(boolean fullInstall) {
Iris.info("Checking Data Packs...");
File packs = new File("plugins/Iris/packs");
double ultimateMaxHeight = 0;
double ultimateMinHeight = 0;
if (packs.exists() && packs.isDirectory()) {
for (File pack : packs.listFiles()) {
IrisData data = IrisData.get(pack);
if (pack.isDirectory()) {
File dimensionsFolder = new File(pack, "dimensions");
if (dimensionsFolder.exists() && dimensionsFolder.isDirectory()) {
for (File file : dimensionsFolder.listFiles()) {
if (file.isFile() && file.getName().endsWith(".json")) {
IrisDimension dim = data.getDimensionLoader().load(file.getName().split("\\Q.\\E")[0]);
if (ultimateMaxHeight < dim.getDimensionHeight().getMax()) {
ultimateMaxHeight = dim.getDimensionHeight().getMax();
}
if (ultimateMinHeight > dim.getDimensionHeight().getMin()) {
ultimateMinHeight = dim.getDimensionHeight().getMin();
}
}
}
}
}
}
}
if (packs.exists()) {
for (File i : packs.listFiles()) {
if (i.isDirectory()) {
@@ -177,7 +153,7 @@ public class ServerConfigurator {
Iris.verbose(" Checking Dimension " + dim.getLoadFile().getPath());
for (File dpack : getDatapacksFolder()) {
dim.installDataPack(() -> data, dpack, ultimateMaxHeight, ultimateMinHeight);
dim.installDataPack(() -> data, dpack);
}
}
}
@@ -228,7 +204,7 @@ public class ServerConfigurator {
Iris.info( "Hotloading all Datapacks!");
if (INMS.get().supportsDataPacks()) {
for (File folder : getDatapacksFolder()) {
INMS.get().loadDatapack(folder);
INMS.get().loadDatapack(folder, false);
}
Iris.info("Datapacks Hotloaded!");
Iris.info(C.YELLOW + "============================================================================");

View File

@@ -20,9 +20,11 @@ package com.volmit.iris.core.commands;
import com.volmit.iris.Iris;
import com.volmit.iris.core.IrisSettings;
import com.volmit.iris.core.ServerConfigurator;
import com.volmit.iris.core.gui.NoiseExplorerGUI;
import com.volmit.iris.core.gui.VisionGUI;
import com.volmit.iris.core.loader.IrisData;
import com.volmit.iris.core.nms.INMS;
import com.volmit.iris.core.project.IrisProject;
import com.volmit.iris.core.service.ConversionSVC;
import com.volmit.iris.core.service.StudioSVC;
@@ -279,13 +281,23 @@ public class CommandStudio implements DecreeExecutor {
}
@Decree(description = "Hotload a studio", aliases = {"reload", "h"})
public void hotload() {
public void hotload(@Param(defaultValue = "false") boolean reloadDataPack) {
if (!Iris.service(StudioSVC.class).isProjectOpen()) {
sender().sendMessage(C.RED + "No studio world open!");
return;
}
Iris.service(StudioSVC.class).getActiveProject().getActiveProvider().getEngine().hotload();
var provider = Iris.service(StudioSVC.class).getActiveProject().getActiveProvider();
provider.getEngine().hotload();
sender().sendMessage(C.GREEN + "Hotloaded");
if (reloadDataPack) {
var world = provider.getTarget().getWorld().realWorld();
if (world == null) {
sender().sendMessage(C.RED + "Failed to reload datapacks.");
return;
}
boolean success = INMS.get().loadDatapack(new File(world.getWorldFolder(), "datapacks"), true);
sender().sendMessage(success ? C.GREEN + "Reloaded datapacks." : C.RED + "Failed to reload datapacks.");
}
}
@Decree(description = "Show loot if a chest were right here", origin = DecreeOrigin.PLAYER, sync = true)

View File

@@ -19,6 +19,7 @@
package com.volmit.iris.core.nms;
import com.volmit.iris.engine.framework.Engine;
import com.volmit.iris.engine.object.IrisDimension;
import com.volmit.iris.util.collection.KList;
import com.volmit.iris.util.collection.KMap;
import com.volmit.iris.util.mantle.Mantle;
@@ -113,7 +114,9 @@ public interface INMSBinding {
Entity spawnEntity(Location location, EntityType type, CreatureSpawnEvent.SpawnReason reason);
boolean loadDatapack(File datapackFolder);
boolean loadDatapack(File datapackFolder, boolean replace);
boolean registerDimension(String name, IrisDimension dimension);
void injectBukkit();
}

View File

@@ -23,6 +23,7 @@ import com.volmit.iris.Iris;
import com.volmit.iris.core.nms.INMSBinding;
import com.volmit.iris.core.nms.container.BlockPos;
import com.volmit.iris.engine.framework.Engine;
import com.volmit.iris.engine.object.IrisDimension;
import com.volmit.iris.util.collection.KList;
import com.volmit.iris.util.collection.KMap;
import com.volmit.iris.util.format.C;
@@ -107,7 +108,12 @@ public class NMSBinding1X implements INMSBinding {
}
@Override
public boolean loadDatapack(File datapackFolder) {
public boolean loadDatapack(File datapackFolder, boolean replace) {
return false;
}
@Override
public boolean registerDimension(String name, IrisDimension dimension) {
return false;
}

View File

@@ -19,6 +19,7 @@
package com.volmit.iris.core.tools;
import com.volmit.iris.core.loader.IrisData;
import com.volmit.iris.core.nms.INMS;
import com.volmit.iris.engine.object.*;
import com.volmit.iris.engine.platform.BukkitChunkGenerator;
import org.bukkit.Bukkit;
@@ -84,6 +85,9 @@ public class IrisWorldCreator {
? dim.getLoader().getDataFolder() :
new File(w.worldFolder(), "iris/pack"), dimensionName, smartVanillaHeight);
if (!INMS.get().registerDimension(name, dim)) {
throw new IllegalStateException("Unable to register dimension " + dim.getName());
}
return new WorldCreator(name)
.environment(findEnvironment())

View File

@@ -6,6 +6,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
@@ -13,13 +14,19 @@ import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Vector;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.base.Preconditions;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.Lifecycle;
import com.volmit.iris.engine.object.IrisDimension;
import com.volmit.iris.util.format.C;
import com.volmit.iris.util.io.IO;
import it.unimi.dsi.fastutil.objects.Reference2IntMap;
@@ -29,9 +36,14 @@ import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.matcher.ElementMatchers;
import net.minecraft.core.MappedRegistry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.block.data.BlockData;
@@ -45,6 +57,7 @@ import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftItemStack;
import org.bukkit.entity.Dolphin;
import org.bukkit.entity.Entity;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
@@ -551,25 +564,34 @@ public class NMSBinding implements INMSBinding {
}
@Override
public boolean loadDatapack(File folder) {
public boolean registerDimension(String name, IrisDimension dimension) {
var registry = registry(Registry.DIMENSION_TYPE_REGISTRY);
var baseLocation = switch (dimension.getEnvironment()) {
case NORMAL -> new ResourceLocation("minecraft", "overworld");
case NETHER -> new ResourceLocation("minecraft", "the_nether");
case THE_END -> new ResourceLocation("minecraft", "the_end");
case CUSTOM -> throw new IllegalArgumentException("Cannot register custom dimension");
};
var base = registry.getHolder(ResourceKey.create(Registry.DIMENSION_TYPE_REGISTRY, baseLocation)).orElse(null);
if (base == null) return false;
var json = encode(DimensionType.CODEC, base).orElse(null);
if (json == null) return false;
var object = json.getAsJsonObject();
var height = dimension.getDimensionHeight();
object.addProperty("min_y", height.getMin());
object.addProperty("height", height.getMax() - height.getMin());
object.addProperty("logical_height", dimension.getLogicalHeight());
var value = decode(DimensionType.CODEC, object.toString()).map(Holder::value).orElse(null);
if (value == null) return false;
return register(Registry.DIMENSION_TYPE_REGISTRY, new ResourceLocation("iris", name), value, true);
}
@Override
public boolean loadDatapack(File folder, boolean replace) {
var data = new File(folder, "iris/data");
if (!data.exists() || !data.isDirectory()) return false;
FilenameFilter jsonFilter = (dir, name) -> new File(dir, name).isFile() && name.toLowerCase().endsWith(".json");
var dimensionFolder = new File(data, "minecraft/dimension_type");
if (dimensionFolder.exists()) {
var files = dimensionFolder.listFiles(jsonFilter);
if (files != null) {
for (File file : files) {
try {
modifyDimension(file);
} catch (Throwable e) {
Iris.error("Unable to modify dimension!");
e.printStackTrace();
}
}
}
}
var files = data.listFiles((dir, name) -> new File(dir, name).isDirectory());
if (files == null) return false;
for (File file : files) {
@@ -578,8 +600,26 @@ public class NMSBinding implements INMSBinding {
var biomeFiles = biome.listFiles(jsonFilter);
if (biomeFiles == null) continue;
for (File biomeFile : biomeFiles) {
String json = null;
int tries = 10;
while (json == null && tries-- > 0) {
try {
json = IO.readAll(biomeFile);
} catch (IOException e) {
Iris.error("Failed to read biome " + file.getName() + ":" + biomeFile.getName() + " tries left: " + tries);
if (tries == 0) {
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {}
}
}
if (json == null) continue;
try {
registerBiome(file.getName(), biomeFile);
var value = decode(net.minecraft.world.level.biome.Biome.CODEC, json).map(Holder::value).orElse(null);
register(Registry.BIOME_REGISTRY, from(file.getName(), biomeFile), value, replace);
} catch (Throwable e) {
Iris.error("Failed to register biome " + file.getName() + ":" + biomeFile.getName());
e.printStackTrace();
@@ -594,75 +634,82 @@ public class NMSBinding implements INMSBinding {
return new ResourceLocation(namespace, name.substring(0, name.lastIndexOf('.')));
}
private void registerBiome(String namespace, File file) throws Throwable {
var rawRegistry = registry().registry(Registry.BIOME_REGISTRY).orElse(null);
var key = ResourceKey.create(Registry.BIOME_REGISTRY, from(namespace, file));
if (!(rawRegistry instanceof MappedRegistry<net.minecraft.world.level.biome.Biome> registry))
throw new IllegalStateException("The Biome Registry is not a mapped Registry!");
if (registry.containsKey(key)) return;
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field holdersField = null;
boolean holders = false;
for (Field f : MappedRegistry.class.getDeclaredFields()) {
if (!f.getGenericType().getTypeName().startsWith("java.util.Map<T, "))
continue;
holdersField = f;
}
if (holdersField != null) {
holdersField.setAccessible(true);
holders = holdersField.get(registry) == null;
if (holders) holdersField.set(registry, new IdentityHashMap<>());
}
private <T> Optional<T> decode(Codec<T> codec, String json) {
return codec.decode(JsonOps.INSTANCE, GsonHelper.parse(json)).get().left().map(Pair::getFirst);
}
private <T> Optional<JsonElement> encode(Codec<T> codec, T value) {
return codec.encode(value, JsonOps.INSTANCE, new JsonObject()).result();
}
private <T> boolean register(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value, boolean replace) {
Preconditions.checkArgument(registryKey != null, "The registry cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var biome = net.minecraft.world.level.biome.Biome.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (biome == null)
throw new IllegalStateException("Failed to decode biome " + file.getName());
registry.createIntrusiveHolder(biome);
registry.register(key, biome, Lifecycle.stable());
} finally {
field.setBoolean(registry, frozen);
if (holders) {
holdersField.set(registry, null);
if (registry.containsKey(key)) {
if (!replace) return false;
return replace(registryKey, location, value);
}
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
try {
var holder = registry.register(key, value, Lifecycle.stable());
if (frozen) valueField.set(holder, value);
return true;
} finally {
field.setBoolean(registry, frozen);
}
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
@SuppressWarnings("unchecked")
private void modifyDimension(File file) throws Throwable {
var key = ResourceKey.create(Registry.DIMENSION_TYPE_REGISTRY, from("minecraft", file));
var rawRegistry = registry().registry(Registry.DIMENSION_TYPE_REGISTRY).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<DimensionType> registry))
throw new IllegalStateException("The Dimension Registry is not a mapped Registry!");
private <T> boolean replace(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value) {
Preconditions.checkArgument(registryKey != null, "The registryKey cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var holder = registry.getHolder(key).orElse(null);
if (holder == null) return false;
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<T>) toIdField.get(registry);
var byValue = (Map<T, Holder.Reference<T>>) byValueField.get(registry);
var lifecycles = (Map<T, Lifecycle>) lifecyclesField.get(registry);
var holder = registry.getHolder(key).orElseThrow(() -> new IllegalStateException("Unknown dimension type: " + key));
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<DimensionType>) toIdField.get(registry);
var byValue = (Map<DimensionType, Holder.Reference<DimensionType>>) byValueField.get(registry);
var lifecycles = (Map<DimensionType, Lifecycle>) lifecyclesField.get(registry);
valueField.set(holder, value);
toId.put(value, toId.removeInt(oldValue));
byValue.put(value, byValue.remove(oldValue));
lifecycles.put(value, lifecycles.remove(oldValue));
return true;
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
var newValue = DimensionType.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (newValue == null)
throw new IllegalArgumentException("Failed to parse dimension type " + key.location() + " from " + file);
valueField.set(holder, newValue);
toId.put(newValue, toId.removeInt(oldValue));
byValue.put(newValue, byValue.remove(oldValue));
lifecycles.put(newValue, lifecycles.remove(oldValue));
private <T> MappedRegistry<T> registry(ResourceKey<Registry<T>> registryKey) {
var rawRegistry = registry().registry(registryKey).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<T> registry))
throw new IllegalStateException("The Registry is not a mapped Registry!");
return registry;
}
private static String buildType(Class<?> clazz, String... parameterTypes) {
@@ -715,6 +762,13 @@ public class NMSBinding implements INMSBinding {
.visit(Advice.to(WorldCreatorAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(String.class))))
.make()
.load(WorldCreator.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
new ByteBuddy()
.redefine(ServerLevel.class)
.visit(Advice.to(ServerLevelAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(MinecraftServer.class, Executor.class, LevelStorageSource.LevelStorageAccess.class,
PrimaryLevelData.class, ResourceKey.class, LevelStem.class, ChunkProgressListener.class, boolean.class, long.class,
List.class, boolean.class, World.Environment.class, ChunkGenerator.class, BiomeProvider.class))))
.make()
.load(ServerLevel.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Iris.info("Injected Bukkit Successfully!");
} catch (Exception e) {
Iris.info(C.RED + "Failed to Inject Bukkit!");
@@ -724,6 +778,22 @@ public class NMSBinding implements INMSBinding {
}
private static class ServerLevelAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) MinecraftServer server, @Advice.Argument(2) LevelStorageSource.LevelStorageAccess access, @Advice.Argument(4) ResourceKey<Level> key, @Advice.Argument(value = 5, readOnly = false) LevelStem levelStem) {
File iris = new File(access.levelDirectory.path().toFile(), "iris");
if (!iris.exists() && !key.location().getPath().startsWith("iris/")) return;
var logger = MinecraftServer.LOGGER;
ResourceKey<DimensionType> typeKey = ResourceKey.create(Registry.DIMENSION_TYPE_REGISTRY, new ResourceLocation("iris", key.location().getPath()));
RegistryAccess registryAccess = server.registryAccess();
Registry<DimensionType> registry = registryAccess.registry(Registry.DIMENSION_TYPE_REGISTRY).orElse(null);
if (registry == null) throw new IllegalStateException("Unable to find registry for dimension type " + typeKey);
Holder<DimensionType> holder = registry.getHolder(typeKey).orElse(null);
if (holder == null) throw new IllegalStateException("Unable to find dimension type " + typeKey);
levelStem = new LevelStem(holder, levelStem.generator());
}
}
private static class WorldCreatorAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) String name) {
@@ -741,4 +811,4 @@ public class NMSBinding implements INMSBinding {
}
}
}
}
}

View File

@@ -6,6 +6,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
@@ -13,13 +14,19 @@ import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Vector;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.base.Preconditions;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.Lifecycle;
import com.volmit.iris.engine.object.IrisDimension;
import com.volmit.iris.util.format.C;
import com.volmit.iris.util.io.IO;
import it.unimi.dsi.fastutil.objects.Reference2IntMap;
@@ -29,9 +36,14 @@ import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.matcher.ElementMatchers;
import net.minecraft.core.MappedRegistry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.block.data.BlockData;
@@ -45,6 +57,7 @@ import org.bukkit.craftbukkit.v1_19_R2.inventory.CraftItemStack;
import org.bukkit.entity.Dolphin;
import org.bukkit.entity.Entity;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
@@ -553,25 +566,34 @@ public class NMSBinding implements INMSBinding {
}
@Override
public boolean loadDatapack(File folder) {
public boolean registerDimension(String name, IrisDimension dimension) {
var registry = registry(Registries.DIMENSION_TYPE);
var baseLocation = switch (dimension.getEnvironment()) {
case NORMAL -> new ResourceLocation("minecraft", "overworld");
case NETHER -> new ResourceLocation("minecraft", "the_nether");
case THE_END -> new ResourceLocation("minecraft", "the_end");
case CUSTOM -> throw new IllegalArgumentException("Cannot register custom dimension");
};
var base = registry.getHolder(ResourceKey.create(Registries.DIMENSION_TYPE, baseLocation)).orElse(null);
if (base == null) return false;
var json = encode(DimensionType.CODEC, base).orElse(null);
if (json == null) return false;
var object = json.getAsJsonObject();
var height = dimension.getDimensionHeight();
object.addProperty("min_y", height.getMin());
object.addProperty("height", height.getMax() - height.getMin());
object.addProperty("logical_height", dimension.getLogicalHeight());
var value = decode(DimensionType.CODEC, object.toString()).map(Holder::value).orElse(null);
if (value == null) return false;
return register(Registries.DIMENSION_TYPE, new ResourceLocation("iris", name), value, true);
}
@Override
public boolean loadDatapack(File folder, boolean replace) {
var data = new File(folder, "iris/data");
if (!data.exists() || !data.isDirectory()) return false;
FilenameFilter jsonFilter = (dir, name) -> new File(dir, name).isFile() && name.toLowerCase().endsWith(".json");
var dimensionFolder = new File(data, "minecraft/dimension_type");
if (dimensionFolder.exists()) {
var files = dimensionFolder.listFiles(jsonFilter);
if (files != null) {
for (File file : files) {
try {
modifyDimension(file);
} catch (Throwable e) {
Iris.error("Unable to modify dimension!");
e.printStackTrace();
}
}
}
}
var files = data.listFiles((dir, name) -> new File(dir, name).isDirectory());
if (files == null) return false;
for (File file : files) {
@@ -580,8 +602,26 @@ public class NMSBinding implements INMSBinding {
var biomeFiles = biome.listFiles(jsonFilter);
if (biomeFiles == null) continue;
for (File biomeFile : biomeFiles) {
String json = null;
int tries = 10;
while (json == null && tries-- > 0) {
try {
json = IO.readAll(biomeFile);
} catch (IOException e) {
Iris.error("Failed to read biome " + file.getName() + ":" + biomeFile.getName() + " tries left: " + tries);
if (tries == 0) {
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {}
}
}
if (json == null) continue;
try {
registerBiome(file.getName(), biomeFile);
var value = decode(net.minecraft.world.level.biome.Biome.CODEC, json).map(Holder::value).orElse(null);
register(Registries.BIOME, from(file.getName(), biomeFile), value, replace);
} catch (Throwable e) {
Iris.error("Failed to register biome " + file.getName() + ":" + biomeFile.getName());
e.printStackTrace();
@@ -596,75 +636,82 @@ public class NMSBinding implements INMSBinding {
return new ResourceLocation(namespace, name.substring(0, name.lastIndexOf('.')));
}
private void registerBiome(String namespace, File file) throws Throwable {
var rawRegistry = registry().registry(Registries.BIOME).orElse(null);
var key = ResourceKey.create(Registries.BIOME, from(namespace, file));
if (!(rawRegistry instanceof MappedRegistry<net.minecraft.world.level.biome.Biome> registry))
throw new IllegalStateException("The Biome Registry is not a mapped Registry!");
if (registry.containsKey(key)) return;
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field holdersField = null;
boolean holders = false;
for (Field f : MappedRegistry.class.getDeclaredFields()) {
if (!f.getGenericType().getTypeName().startsWith("java.util.Map<T, "))
continue;
holdersField = f;
}
if (holdersField != null) {
holdersField.setAccessible(true);
holders = holdersField.get(registry) == null;
if (holders) holdersField.set(registry, new IdentityHashMap<>());
}
private <T> Optional<T> decode(Codec<T> codec, String json) {
return codec.decode(JsonOps.INSTANCE, GsonHelper.parse(json)).get().left().map(Pair::getFirst);
}
private <T> Optional<JsonElement> encode(Codec<T> codec, T value) {
return codec.encode(value, JsonOps.INSTANCE, new JsonObject()).result();
}
private <T> boolean register(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value, boolean replace) {
Preconditions.checkArgument(registryKey != null, "The registry cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var biome = net.minecraft.world.level.biome.Biome.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (biome == null)
throw new IllegalStateException("Failed to decode biome " + file.getName());
registry.createIntrusiveHolder(biome);
registry.register(key, biome, Lifecycle.stable());
} finally {
field.setBoolean(registry, frozen);
if (holders) {
holdersField.set(registry, null);
if (registry.containsKey(key)) {
if (!replace) return false;
return replace(registryKey, location, value);
}
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
try {
var holder = registry.register(key, value, Lifecycle.stable());
if (frozen) valueField.set(holder, value);
return true;
} finally {
field.setBoolean(registry, frozen);
}
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
@SuppressWarnings("unchecked")
private void modifyDimension(File file) throws Throwable {
var key = ResourceKey.create(Registries.DIMENSION_TYPE, from("minecraft", file));
var rawRegistry = registry().registry(Registries.DIMENSION_TYPE).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<DimensionType> registry))
throw new IllegalStateException("The Dimension Registry is not a mapped Registry!");
private <T> boolean replace(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value) {
Preconditions.checkArgument(registryKey != null, "The registryKey cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var holder = registry.getHolder(key).orElse(null);
if (holder == null) return false;
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<T>) toIdField.get(registry);
var byValue = (Map<T, Holder.Reference<T>>) byValueField.get(registry);
var lifecycles = (Map<T, Lifecycle>) lifecyclesField.get(registry);
var holder = registry.getHolder(key).orElseThrow(() -> new IllegalStateException("Unknown dimension type: " + key));
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<DimensionType>) toIdField.get(registry);
var byValue = (Map<DimensionType, Holder.Reference<DimensionType>>) byValueField.get(registry);
var lifecycles = (Map<DimensionType, Lifecycle>) lifecyclesField.get(registry);
valueField.set(holder, value);
toId.put(value, toId.removeInt(oldValue));
byValue.put(value, byValue.remove(oldValue));
lifecycles.put(value, lifecycles.remove(oldValue));
return true;
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
var newValue = DimensionType.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (newValue == null)
throw new IllegalArgumentException("Failed to parse dimension type " + key.location() + " from " + file);
valueField.set(holder, newValue);
toId.put(newValue, toId.removeInt(oldValue));
byValue.put(newValue, byValue.remove(oldValue));
lifecycles.put(newValue, lifecycles.remove(oldValue));
private <T> MappedRegistry<T> registry(ResourceKey<Registry<T>> registryKey) {
var rawRegistry = registry().registry(registryKey).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<T> registry))
throw new IllegalStateException("The Registry is not a mapped Registry!");
return registry;
}
private static String buildType(Class<?> clazz, String... parameterTypes) {
@@ -716,6 +763,13 @@ public class NMSBinding implements INMSBinding {
.visit(Advice.to(WorldCreatorAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(String.class))))
.make()
.load(WorldCreator.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
new ByteBuddy()
.redefine(ServerLevel.class)
.visit(Advice.to(ServerLevelAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(MinecraftServer.class, Executor.class, LevelStorageSource.LevelStorageAccess.class,
PrimaryLevelData.class, ResourceKey.class, LevelStem.class, ChunkProgressListener.class, boolean.class, long.class,
List.class, boolean.class, World.Environment.class, ChunkGenerator.class, BiomeProvider.class))))
.make()
.load(ServerLevel.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Iris.info("Injected Bukkit Successfully!");
} catch (Exception e) {
Iris.info(C.RED + "Failed to Inject Bukkit!");
@@ -725,6 +779,21 @@ public class NMSBinding implements INMSBinding {
}
private static class ServerLevelAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) MinecraftServer server, @Advice.Argument(2) LevelStorageSource.LevelStorageAccess access, @Advice.Argument(4) ResourceKey<Level> key, @Advice.Argument(value = 5, readOnly = false) LevelStem levelStem) {
File iris = new File(access.levelDirectory.path().toFile(), "iris");
if (!iris.exists() && !key.location().getPath().startsWith("iris/")) return;
ResourceKey<DimensionType> typeKey = ResourceKey.create(Registries.DIMENSION_TYPE, new ResourceLocation("iris", key.location().getPath()));
RegistryAccess registryAccess = server.registryAccess();
Registry<DimensionType> registry = registryAccess.registry(Registries.DIMENSION_TYPE).orElse(null);
if (registry == null) throw new IllegalStateException("Unable to find registry for dimension type " + typeKey);
Holder<DimensionType> holder = registry.getHolder(typeKey).orElse(null);
if (holder == null) throw new IllegalStateException("Unable to find dimension type " + typeKey);
levelStem = new LevelStem(holder, levelStem.generator());
}
}
private static class WorldCreatorAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) String name) {
@@ -742,4 +811,4 @@ public class NMSBinding implements INMSBinding {
}
}
}
}
}

View File

@@ -6,6 +6,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
@@ -13,13 +14,19 @@ import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Vector;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.base.Preconditions;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.Lifecycle;
import com.volmit.iris.engine.object.IrisDimension;
import com.volmit.iris.util.format.C;
import com.volmit.iris.util.io.IO;
import it.unimi.dsi.fastutil.objects.Reference2IntMap;
@@ -29,9 +36,14 @@ import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.matcher.ElementMatchers;
import net.minecraft.core.MappedRegistry;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.block.data.BlockData;
@@ -45,6 +57,7 @@ import org.bukkit.craftbukkit.v1_19_R3.inventory.CraftItemStack;
import org.bukkit.entity.Dolphin;
import org.bukkit.entity.Entity;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
@@ -557,25 +570,34 @@ public class NMSBinding implements INMSBinding {
}
@Override
public boolean loadDatapack(File folder) {
public boolean registerDimension(String name, IrisDimension dimension) {
var registry = registry(Registries.DIMENSION_TYPE);
var baseLocation = switch (dimension.getEnvironment()) {
case NORMAL -> new ResourceLocation("minecraft", "overworld");
case NETHER -> new ResourceLocation("minecraft", "the_nether");
case THE_END -> new ResourceLocation("minecraft", "the_end");
case CUSTOM -> throw new IllegalArgumentException("Cannot register custom dimension");
};
var base = registry.getHolder(ResourceKey.create(Registries.DIMENSION_TYPE, baseLocation)).orElse(null);
if (base == null) return false;
var json = encode(DimensionType.CODEC, base).orElse(null);
if (json == null) return false;
var object = json.getAsJsonObject();
var height = dimension.getDimensionHeight();
object.addProperty("min_y", height.getMin());
object.addProperty("height", height.getMax() - height.getMin());
object.addProperty("logical_height", dimension.getLogicalHeight());
var value = decode(DimensionType.CODEC, object.toString()).map(Holder::value).orElse(null);
if (value == null) return false;
return register(Registries.DIMENSION_TYPE, new ResourceLocation("iris", name), value, true);
}
@Override
public boolean loadDatapack(File folder, boolean replace) {
var data = new File(folder, "iris/data");
if (!data.exists() || !data.isDirectory()) return false;
FilenameFilter jsonFilter = (dir, name) -> new File(dir, name).isFile() && name.toLowerCase().endsWith(".json");
var dimensionFolder = new File(data, "minecraft/dimension_type");
if (dimensionFolder.exists()) {
var files = dimensionFolder.listFiles(jsonFilter);
if (files != null) {
for (File file : files) {
try {
modifyDimension(file);
} catch (Throwable e) {
Iris.error("Unable to modify dimension!");
e.printStackTrace();
}
}
}
}
var files = data.listFiles((dir, name) -> new File(dir, name).isDirectory());
if (files == null) return false;
for (File file : files) {
@@ -584,8 +606,26 @@ public class NMSBinding implements INMSBinding {
var biomeFiles = biome.listFiles(jsonFilter);
if (biomeFiles == null) continue;
for (File biomeFile : biomeFiles) {
String json = null;
int tries = 10;
while (json == null && tries-- > 0) {
try {
json = IO.readAll(biomeFile);
} catch (IOException e) {
Iris.error("Failed to read biome " + file.getName() + ":" + biomeFile.getName() + " tries left: " + tries);
if (tries == 0) {
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {}
}
}
if (json == null) continue;
try {
registerBiome(file.getName(), biomeFile);
var value = decode(net.minecraft.world.level.biome.Biome.CODEC, json).map(Holder::value).orElse(null);
register(Registries.BIOME, from(file.getName(), biomeFile), value, replace);
} catch (Throwable e) {
Iris.error("Failed to register biome " + file.getName() + ":" + biomeFile.getName());
e.printStackTrace();
@@ -600,75 +640,82 @@ public class NMSBinding implements INMSBinding {
return new ResourceLocation(namespace, name.substring(0, name.lastIndexOf('.')));
}
private void registerBiome(String namespace, File file) throws Throwable {
var rawRegistry = registry().registry(Registries.BIOME).orElse(null);
var key = ResourceKey.create(Registries.BIOME, from(namespace, file));
if (!(rawRegistry instanceof MappedRegistry<net.minecraft.world.level.biome.Biome> registry))
throw new IllegalStateException("The Biome Registry is not a mapped Registry!");
if (registry.containsKey(key)) return;
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field holdersField = null;
boolean holders = false;
for (Field f : MappedRegistry.class.getDeclaredFields()) {
if (!f.getGenericType().getTypeName().startsWith("java.util.Map<T, "))
continue;
holdersField = f;
}
if (holdersField != null) {
holdersField.setAccessible(true);
holders = holdersField.get(registry) == null;
if (holders) holdersField.set(registry, new IdentityHashMap<>());
}
private <T> Optional<T> decode(Codec<T> codec, String json) {
return codec.decode(JsonOps.INSTANCE, GsonHelper.parse(json)).get().left().map(Pair::getFirst);
}
private <T> Optional<JsonElement> encode(Codec<T> codec, T value) {
return codec.encode(value, JsonOps.INSTANCE, new JsonObject()).result();
}
private <T> boolean register(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value, boolean replace) {
Preconditions.checkArgument(registryKey != null, "The registry cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var biome = net.minecraft.world.level.biome.Biome.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (biome == null)
throw new IllegalStateException("Failed to decode biome " + file.getName());
registry.createIntrusiveHolder(biome);
registry.register(key, biome, Lifecycle.stable());
} finally {
field.setBoolean(registry, frozen);
if (holders) {
holdersField.set(registry, null);
if (registry.containsKey(key)) {
if (!replace) return false;
return replace(registryKey, location, value);
}
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
try {
var holder = registry.register(key, value, Lifecycle.stable());
if (frozen) valueField.set(holder, value);
return true;
} finally {
field.setBoolean(registry, frozen);
}
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
@SuppressWarnings("unchecked")
private void modifyDimension(File file) throws Throwable {
var key = ResourceKey.create(Registries.DIMENSION_TYPE, from("minecraft", file));
var rawRegistry = registry().registry(Registries.DIMENSION_TYPE).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<DimensionType> registry))
throw new IllegalStateException("The Dimension Registry is not a mapped Registry!");
private <T> boolean replace(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value) {
Preconditions.checkArgument(registryKey != null, "The registryKey cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var holder = registry.getHolder(key).orElse(null);
if (holder == null) return false;
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<T>) toIdField.get(registry);
var byValue = (Map<T, Holder.Reference<T>>) byValueField.get(registry);
var lifecycles = (Map<T, Lifecycle>) lifecyclesField.get(registry);
var holder = registry.getHolder(key).orElseThrow(() -> new IllegalStateException("Unknown dimension type: " + key));
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<DimensionType>) toIdField.get(registry);
var byValue = (Map<DimensionType, Holder.Reference<DimensionType>>) byValueField.get(registry);
var lifecycles = (Map<DimensionType, Lifecycle>) lifecyclesField.get(registry);
valueField.set(holder, value);
toId.put(value, toId.removeInt(oldValue));
byValue.put(value, byValue.remove(oldValue));
lifecycles.put(value, lifecycles.remove(oldValue));
return true;
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
var newValue = DimensionType.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (newValue == null)
throw new IllegalArgumentException("Failed to parse dimension type " + key.location() + " from " + file);
valueField.set(holder, newValue);
toId.put(newValue, toId.removeInt(oldValue));
byValue.put(newValue, byValue.remove(oldValue));
lifecycles.put(newValue, lifecycles.remove(oldValue));
private <T> MappedRegistry<T> registry(ResourceKey<Registry<T>> registryKey) {
var rawRegistry = registry().registry(registryKey).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<T> registry))
throw new IllegalStateException("The Registry is not a mapped Registry!");
return registry;
}
private static String buildType(Class<?> clazz, String... parameterTypes) {
@@ -720,6 +767,13 @@ public class NMSBinding implements INMSBinding {
.visit(Advice.to(WorldCreatorAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(String.class))))
.make()
.load(WorldCreator.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
new ByteBuddy()
.redefine(ServerLevel.class)
.visit(Advice.to(ServerLevelAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(MinecraftServer.class, Executor.class, LevelStorageSource.LevelStorageAccess.class,
PrimaryLevelData.class, ResourceKey.class, LevelStem.class, ChunkProgressListener.class, boolean.class, long.class,
List.class, boolean.class, World.Environment.class, ChunkGenerator.class, BiomeProvider.class))))
.make()
.load(ServerLevel.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Iris.info("Injected Bukkit Successfully!");
} catch (Exception e) {
Iris.info(C.RED + "Failed to Inject Bukkit!");
@@ -729,6 +783,21 @@ public class NMSBinding implements INMSBinding {
}
private static class ServerLevelAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) MinecraftServer server, @Advice.Argument(2) LevelStorageSource.LevelStorageAccess access, @Advice.Argument(4) ResourceKey<Level> key, @Advice.Argument(value = 5, readOnly = false) LevelStem levelStem) {
File iris = new File(access.levelDirectory.path().toFile(), "iris");
if (!iris.exists() && !key.location().getPath().startsWith("iris/")) return;
ResourceKey<DimensionType> typeKey = ResourceKey.create(Registries.DIMENSION_TYPE, new ResourceLocation("iris", key.location().getPath()));
RegistryAccess registryAccess = server.registryAccess();
Registry<DimensionType> registry = registryAccess.registry(Registries.DIMENSION_TYPE).orElse(null);
if (registry == null) throw new IllegalStateException("Unable to find registry for dimension type " + typeKey);
Holder<DimensionType> holder = registry.getHolder(typeKey).orElse(null);
if (holder == null) throw new IllegalStateException("Unable to find dimension type " + typeKey);
levelStem = new LevelStem(holder, levelStem.generator());
}
}
private static class WorldCreatorAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) String name) {

View File

@@ -1,14 +1,18 @@
package com.volmit.iris.core.nms.v1_20_R1;
import com.google.common.base.Preconditions;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.Lifecycle;
import com.volmit.iris.Iris;
import com.volmit.iris.core.nms.INMSBinding;
import com.volmit.iris.engine.data.cache.AtomicCache;
import com.volmit.iris.engine.framework.Engine;
import com.volmit.iris.engine.object.IrisDimension;
import com.volmit.iris.util.collection.KList;
import com.volmit.iris.util.collection.KMap;
import com.volmit.iris.util.format.C;
@@ -38,8 +42,11 @@ import net.minecraft.nbt.NbtIo;
import net.minecraft.nbt.TagParser;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.RandomSequences;
import net.minecraft.world.entity.EntityDimensions;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.BiomeSource;
@@ -50,6 +57,9 @@ import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.block.data.BlockData;
@@ -66,6 +76,7 @@ import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.entity.EntityType;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
@@ -77,6 +88,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
@@ -84,7 +96,9 @@ import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Vector;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
public class NMSBinding implements INMSBinding {
@@ -543,25 +557,34 @@ public class NMSBinding implements INMSBinding {
}
@Override
public boolean loadDatapack(File folder) {
public boolean registerDimension(String name, IrisDimension dimension) {
var registry = registry(Registries.DIMENSION_TYPE);
var baseLocation = switch (dimension.getEnvironment()) {
case NORMAL -> new ResourceLocation("minecraft", "overworld");
case NETHER -> new ResourceLocation("minecraft", "the_nether");
case THE_END -> new ResourceLocation("minecraft", "the_end");
case CUSTOM -> throw new IllegalArgumentException("Cannot register custom dimension");
};
var base = registry.getHolder(ResourceKey.create(Registries.DIMENSION_TYPE, baseLocation)).orElse(null);
if (base == null) return false;
var json = encode(DimensionType.CODEC, base).orElse(null);
if (json == null) return false;
var object = json.getAsJsonObject();
var height = dimension.getDimensionHeight();
object.addProperty("min_y", height.getMin());
object.addProperty("height", height.getMax() - height.getMin());
object.addProperty("logical_height", dimension.getLogicalHeight());
var value = decode(DimensionType.CODEC, object.toString()).map(Holder::value).orElse(null);
if (value == null) return false;
return register(Registries.DIMENSION_TYPE, new ResourceLocation("iris", name), value, true);
}
@Override
public boolean loadDatapack(File folder, boolean replace) {
var data = new File(folder, "iris/data");
if (!data.exists() || !data.isDirectory()) return false;
FilenameFilter jsonFilter = (dir, name) -> new File(dir, name).isFile() && name.toLowerCase().endsWith(".json");
var dimensionFolder = new File(data, "minecraft/dimension_type");
if (dimensionFolder.exists()) {
var files = dimensionFolder.listFiles(jsonFilter);
if (files != null) {
for (File file : files) {
try {
modifyDimension(file);
} catch (Throwable e) {
Iris.error("Unable to modify dimension!");
e.printStackTrace();
}
}
}
}
var files = data.listFiles((dir, name) -> new File(dir, name).isDirectory());
if (files == null) return false;
for (File file : files) {
@@ -570,8 +593,26 @@ public class NMSBinding implements INMSBinding {
var biomeFiles = biome.listFiles(jsonFilter);
if (biomeFiles == null) continue;
for (File biomeFile : biomeFiles) {
String json = null;
int tries = 10;
while (json == null && tries-- > 0) {
try {
json = IO.readAll(biomeFile);
} catch (IOException e) {
Iris.error("Failed to read biome " + file.getName() + ":" + biomeFile.getName() + " tries left: " + tries);
if (tries == 0) {
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {}
}
}
if (json == null) continue;
try {
registerBiome(file.getName(), biomeFile);
var value = decode(net.minecraft.world.level.biome.Biome.CODEC, json).map(Holder::value).orElse(null);
register(Registries.BIOME, from(file.getName(), biomeFile), value, replace);
} catch (Throwable e) {
Iris.error("Failed to register biome " + file.getName() + ":" + biomeFile.getName());
e.printStackTrace();
@@ -586,75 +627,82 @@ public class NMSBinding implements INMSBinding {
return new ResourceLocation(namespace, name.substring(0, name.lastIndexOf('.')));
}
private void registerBiome(String namespace, File file) throws Throwable {
var rawRegistry = registry().registry(Registries.BIOME).orElse(null);
var key = ResourceKey.create(Registries.BIOME, from(namespace, file));
if (!(rawRegistry instanceof MappedRegistry<net.minecraft.world.level.biome.Biome> registry))
throw new IllegalStateException("The Biome Registry is not a mapped Registry!");
if (registry.containsKey(key)) return;
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field holdersField = null;
boolean holders = false;
for (Field f : MappedRegistry.class.getDeclaredFields()) {
if (!f.getGenericType().getTypeName().startsWith("java.util.Map<T, "))
continue;
holdersField = f;
}
if (holdersField != null) {
holdersField.setAccessible(true);
holders = holdersField.get(registry) == null;
if (holders) holdersField.set(registry, new IdentityHashMap<>());
}
private <T> Optional<T> decode(Codec<T> codec, String json) {
return codec.decode(JsonOps.INSTANCE, GsonHelper.parse(json)).get().left().map(Pair::getFirst);
}
private <T> Optional<JsonElement> encode(Codec<T> codec, T value) {
return codec.encode(value, JsonOps.INSTANCE, new JsonObject()).result();
}
private <T> boolean register(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value, boolean replace) {
Preconditions.checkArgument(registryKey != null, "The registry cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var biome = net.minecraft.world.level.biome.Biome.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (biome == null)
throw new IllegalStateException("Failed to decode biome " + file.getName());
registry.createIntrusiveHolder(biome);
registry.register(key, biome, Lifecycle.stable());
} finally {
field.setBoolean(registry, frozen);
if (holders) {
holdersField.set(registry, null);
if (registry.containsKey(key)) {
if (!replace) return false;
return replace(registryKey, location, value);
}
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
try {
var holder = registry.register(key, value, Lifecycle.stable());
if (frozen) valueField.set(holder, value);
return true;
} finally {
field.setBoolean(registry, frozen);
}
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
@SuppressWarnings("unchecked")
private void modifyDimension(File file) throws Throwable {
var key = ResourceKey.create(Registries.DIMENSION_TYPE, from("minecraft", file));
var rawRegistry = registry().registry(Registries.DIMENSION_TYPE).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<DimensionType> registry))
throw new IllegalStateException("The Dimension Registry is not a mapped Registry!");
private <T> boolean replace(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value) {
Preconditions.checkArgument(registryKey != null, "The registryKey cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var holder = registry.getHolder(key).orElse(null);
if (holder == null) return false;
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<T>) toIdField.get(registry);
var byValue = (Map<T, Holder.Reference<T>>) byValueField.get(registry);
var lifecycles = (Map<T, Lifecycle>) lifecyclesField.get(registry);
var holder = registry.getHolder(key).orElseThrow(() -> new IllegalStateException("Unknown dimension type: " + key));
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<DimensionType>) toIdField.get(registry);
var byValue = (Map<DimensionType, Holder.Reference<DimensionType>>) byValueField.get(registry);
var lifecycles = (Map<DimensionType, Lifecycle>) lifecyclesField.get(registry);
valueField.set(holder, value);
toId.put(value, toId.removeInt(oldValue));
byValue.put(value, byValue.remove(oldValue));
lifecycles.put(value, lifecycles.remove(oldValue));
return true;
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
var newValue = DimensionType.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (newValue == null)
throw new IllegalArgumentException("Failed to parse dimension type " + key.location() + " from " + file);
valueField.set(holder, newValue);
toId.put(newValue, toId.removeInt(oldValue));
byValue.put(newValue, byValue.remove(oldValue));
lifecycles.put(newValue, lifecycles.remove(oldValue));
private <T> MappedRegistry<T> registry(ResourceKey<Registry<T>> registryKey) {
var rawRegistry = registry().registry(registryKey).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<T> registry))
throw new IllegalStateException("The Registry is not a mapped Registry!");
return registry;
}
private static String buildType(Class<?> clazz, String... parameterTypes) {
@@ -719,6 +767,13 @@ public class NMSBinding implements INMSBinding {
.visit(Advice.to(WorldCreatorAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(String.class))))
.make()
.load(WorldCreator.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
new ByteBuddy()
.redefine(ServerLevel.class)
.visit(Advice.to(ServerLevelAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(MinecraftServer.class, Executor.class, LevelStorageSource.LevelStorageAccess.class,
PrimaryLevelData.class, ResourceKey.class, LevelStem.class, ChunkProgressListener.class, boolean.class, long.class,
List.class, boolean.class, RandomSequences.class, World.Environment.class, ChunkGenerator.class, BiomeProvider.class))))
.make()
.load(ServerLevel.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Iris.info("Injected Bukkit Successfully!");
} catch (Exception e) {
Iris.info(C.RED + "Failed to Inject Bukkit!");
@@ -728,6 +783,21 @@ public class NMSBinding implements INMSBinding {
}
private static class ServerLevelAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) MinecraftServer server, @Advice.Argument(2) LevelStorageSource.LevelStorageAccess access, @Advice.Argument(4) ResourceKey<Level> key, @Advice.Argument(value = 5, readOnly = false) LevelStem levelStem) {
File iris = new File(access.levelDirectory.path().toFile(), "iris");
if (!iris.exists() && !key.location().getPath().startsWith("iris/")) return;
ResourceKey<DimensionType> typeKey = ResourceKey.create(Registries.DIMENSION_TYPE, new ResourceLocation("iris", key.location().getPath()));
RegistryAccess registryAccess = server.registryAccess();
Registry<DimensionType> registry = registryAccess.registry(Registries.DIMENSION_TYPE).orElse(null);
if (registry == null) throw new IllegalStateException("Unable to find registry for dimension type " + typeKey);
Holder<DimensionType> holder = registry.getHolder(typeKey).orElse(null);
if (holder == null) throw new IllegalStateException("Unable to find dimension type " + typeKey);
levelStem = new LevelStem(holder, levelStem.generator());
}
}
private static class WorldCreatorAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) String name) {

View File

@@ -6,6 +6,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
@@ -13,13 +14,19 @@ import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Vector;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.base.Preconditions;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.Lifecycle;
import com.volmit.iris.engine.object.IrisDimension;
import com.volmit.iris.util.format.C;
import com.volmit.iris.util.io.IO;
import it.unimi.dsi.fastutil.objects.Reference2IntMap;
@@ -28,9 +35,15 @@ import net.bytebuddy.asm.Advice;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.matcher.ElementMatchers;
import net.minecraft.core.MappedRegistry;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.RandomSequences;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.block.data.BlockData;
@@ -44,6 +57,7 @@ import org.bukkit.craftbukkit.v1_20_R2.util.CraftNamespacedKey;
import org.bukkit.entity.Dolphin;
import org.bukkit.entity.Entity;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
@@ -553,25 +567,34 @@ public class NMSBinding implements INMSBinding {
}
@Override
public boolean loadDatapack(File folder) {
public boolean registerDimension(String name, IrisDimension dimension) {
var registry = registry(Registries.DIMENSION_TYPE);
var baseLocation = switch (dimension.getEnvironment()) {
case NORMAL -> new ResourceLocation("minecraft", "overworld");
case NETHER -> new ResourceLocation("minecraft", "the_nether");
case THE_END -> new ResourceLocation("minecraft", "the_end");
case CUSTOM -> throw new IllegalArgumentException("Cannot register custom dimension");
};
var base = registry.getHolder(ResourceKey.create(Registries.DIMENSION_TYPE, baseLocation)).orElse(null);
if (base == null) return false;
var json = encode(DimensionType.CODEC, base).orElse(null);
if (json == null) return false;
var object = json.getAsJsonObject();
var height = dimension.getDimensionHeight();
object.addProperty("min_y", height.getMin());
object.addProperty("height", height.getMax() - height.getMin());
object.addProperty("logical_height", dimension.getLogicalHeight());
var value = decode(DimensionType.CODEC, object.toString()).map(Holder::value).orElse(null);
if (value == null) return false;
return register(Registries.DIMENSION_TYPE, new ResourceLocation("iris", name), value, true);
}
@Override
public boolean loadDatapack(File folder, boolean replace) {
var data = new File(folder, "iris/data");
if (!data.exists() || !data.isDirectory()) return false;
FilenameFilter jsonFilter = (dir, name) -> new File(dir, name).isFile() && name.toLowerCase().endsWith(".json");
var dimensionFolder = new File(data, "minecraft/dimension_type");
if (dimensionFolder.exists()) {
var files = dimensionFolder.listFiles(jsonFilter);
if (files != null) {
for (File file : files) {
try {
modifyDimension(file);
} catch (Throwable e) {
Iris.error("Unable to modify dimension!");
e.printStackTrace();
}
}
}
}
var files = data.listFiles((dir, name) -> new File(dir, name).isDirectory());
if (files == null) return false;
for (File file : files) {
@@ -580,8 +603,26 @@ public class NMSBinding implements INMSBinding {
var biomeFiles = biome.listFiles(jsonFilter);
if (biomeFiles == null) continue;
for (File biomeFile : biomeFiles) {
String json = null;
int tries = 10;
while (json == null && tries-- > 0) {
try {
json = IO.readAll(biomeFile);
} catch (IOException e) {
Iris.error("Failed to read biome " + file.getName() + ":" + biomeFile.getName() + " tries left: " + tries);
if (tries == 0) {
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {}
}
}
if (json == null) continue;
try {
registerBiome(file.getName(), biomeFile);
var value = decode(net.minecraft.world.level.biome.Biome.CODEC, json).map(Holder::value).orElse(null);
register(Registries.BIOME, from(file.getName(), biomeFile), value, replace);
} catch (Throwable e) {
Iris.error("Failed to register biome " + file.getName() + ":" + biomeFile.getName());
e.printStackTrace();
@@ -596,75 +637,82 @@ public class NMSBinding implements INMSBinding {
return new ResourceLocation(namespace, name.substring(0, name.lastIndexOf('.')));
}
private void registerBiome(String namespace, File file) throws Throwable {
var rawRegistry = registry().registry(Registries.BIOME).orElse(null);
var key = ResourceKey.create(Registries.BIOME, from(namespace, file));
if (!(rawRegistry instanceof MappedRegistry<net.minecraft.world.level.biome.Biome> registry))
throw new IllegalStateException("The Biome Registry is not a mapped Registry!");
if (registry.containsKey(key)) return;
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field holdersField = null;
boolean holders = false;
for (Field f : MappedRegistry.class.getDeclaredFields()) {
if (!f.getGenericType().getTypeName().startsWith("java.util.Map<T, "))
continue;
holdersField = f;
}
if (holdersField != null) {
holdersField.setAccessible(true);
holders = holdersField.get(registry) == null;
if (holders) holdersField.set(registry, new IdentityHashMap<>());
}
private <T> Optional<T> decode(Codec<T> codec, String json) {
return codec.decode(JsonOps.INSTANCE, GsonHelper.parse(json)).get().left().map(Pair::getFirst);
}
private <T> Optional<JsonElement> encode(Codec<T> codec, T value) {
return codec.encode(value, JsonOps.INSTANCE, new JsonObject()).result();
}
private <T> boolean register(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value, boolean replace) {
Preconditions.checkArgument(registryKey != null, "The registry cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var biome = net.minecraft.world.level.biome.Biome.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (biome == null)
throw new IllegalStateException("Failed to decode biome " + file.getName());
registry.createIntrusiveHolder(biome);
registry.register(key, biome, Lifecycle.stable());
} finally {
field.setBoolean(registry, frozen);
if (holders) {
holdersField.set(registry, null);
if (registry.containsKey(key)) {
if (!replace) return false;
return replace(registryKey, location, value);
}
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
try {
var holder = registry.register(key, value, Lifecycle.stable());
if (frozen) valueField.set(holder, value);
return true;
} finally {
field.setBoolean(registry, frozen);
}
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
@SuppressWarnings("unchecked")
private void modifyDimension(File file) throws Throwable {
var key = ResourceKey.create(Registries.DIMENSION_TYPE, from("minecraft", file));
var rawRegistry = registry().registry(Registries.DIMENSION_TYPE).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<DimensionType> registry))
throw new IllegalStateException("The Dimension Registry is not a mapped Registry!");
private <T> boolean replace(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value) {
Preconditions.checkArgument(registryKey != null, "The registryKey cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var holder = registry.getHolder(key).orElse(null);
if (holder == null) return false;
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<T>) toIdField.get(registry);
var byValue = (Map<T, Holder.Reference<T>>) byValueField.get(registry);
var lifecycles = (Map<T, Lifecycle>) lifecyclesField.get(registry);
var holder = registry.getHolder(key).orElseThrow(() -> new IllegalStateException("Unknown dimension type: " + key));
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<DimensionType>) toIdField.get(registry);
var byValue = (Map<DimensionType, Holder.Reference<DimensionType>>) byValueField.get(registry);
var lifecycles = (Map<DimensionType, Lifecycle>) lifecyclesField.get(registry);
valueField.set(holder, value);
toId.put(value, toId.removeInt(oldValue));
byValue.put(value, byValue.remove(oldValue));
lifecycles.put(value, lifecycles.remove(oldValue));
return true;
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
var newValue = DimensionType.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (newValue == null)
throw new IllegalArgumentException("Failed to parse dimension type " + key.location() + " from " + file);
valueField.set(holder, newValue);
toId.put(newValue, toId.removeInt(oldValue));
byValue.put(newValue, byValue.remove(oldValue));
lifecycles.put(newValue, lifecycles.remove(oldValue));
private <T> MappedRegistry<T> registry(ResourceKey<Registry<T>> registryKey) {
var rawRegistry = registry().registry(registryKey).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<T> registry))
throw new IllegalStateException("The Registry is not a mapped Registry!");
return registry;
}
private static String buildType(Class<?> clazz, String... parameterTypes) {
@@ -721,6 +769,13 @@ public class NMSBinding implements INMSBinding {
.visit(Advice.to(WorldCreatorAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(String.class))))
.make()
.load(WorldCreator.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
new ByteBuddy()
.redefine(ServerLevel.class)
.visit(Advice.to(ServerLevelAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(MinecraftServer.class, Executor.class, LevelStorageSource.LevelStorageAccess.class,
PrimaryLevelData.class, ResourceKey.class, LevelStem.class, ChunkProgressListener.class, boolean.class, long.class,
List.class, boolean.class, RandomSequences.class, World.Environment.class, ChunkGenerator.class, BiomeProvider.class))))
.make()
.load(ServerLevel.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Iris.info("Injected Bukkit Successfully!");
} catch (Exception e) {
Iris.info(C.RED + "Failed to Inject Bukkit!");
@@ -730,6 +785,21 @@ public class NMSBinding implements INMSBinding {
}
private static class ServerLevelAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) MinecraftServer server, @Advice.Argument(2) LevelStorageSource.LevelStorageAccess access, @Advice.Argument(4) ResourceKey<Level> key, @Advice.Argument(value = 5, readOnly = false) LevelStem levelStem) {
File iris = new File(access.levelDirectory.path().toFile(), "iris");
if (!iris.exists() && !key.location().getPath().startsWith("iris/")) return;
ResourceKey<DimensionType> typeKey = ResourceKey.create(Registries.DIMENSION_TYPE, new ResourceLocation("iris", key.location().getPath()));
RegistryAccess registryAccess = server.registryAccess();
Registry<DimensionType> registry = registryAccess.registry(Registries.DIMENSION_TYPE).orElse(null);
if (registry == null) throw new IllegalStateException("Unable to find registry for dimension type " + typeKey);
Holder<DimensionType> holder = registry.getHolder(typeKey).orElse(null);
if (holder == null) throw new IllegalStateException("Unable to find dimension type " + typeKey);
levelStem = new LevelStem(holder, levelStem.generator());
}
}
private static class WorldCreatorAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) String name) {

View File

@@ -6,16 +6,22 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.base.Preconditions;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.Lifecycle;
import com.volmit.iris.engine.object.IrisDimension;
import com.volmit.iris.util.format.C;
import com.volmit.iris.util.io.IO;
import it.unimi.dsi.fastutil.objects.Reference2IntMap;
@@ -23,10 +29,17 @@ import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.matcher.ElementMatchers;
import net.minecraft.core.IdMapper;
import net.minecraft.core.MappedRegistry;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.RandomSequences;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData;
import org.bukkit.*;
import org.bukkit.block.Biome;
import org.bukkit.block.data.BlockData;
@@ -40,6 +53,7 @@ import org.bukkit.craftbukkit.v1_20_R3.util.CraftNamespacedKey;
import org.bukkit.entity.Dolphin;
import org.bukkit.entity.Entity;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
@@ -445,13 +459,13 @@ public class NMSBinding implements INMSBinding {
@Override
public MCAPaletteAccess createPalette() {
MCAIdMapper<BlockState> registry = registryCache.aquireNasty(() -> {
Field cf = net.minecraft.core.IdMapper.class.getDeclaredField("tToId");
Field df = net.minecraft.core.IdMapper.class.getDeclaredField("idToT");
Field bf = net.minecraft.core.IdMapper.class.getDeclaredField("nextId");
Field cf = IdMapper.class.getDeclaredField("tToId");
Field df = IdMapper.class.getDeclaredField("idToT");
Field bf = IdMapper.class.getDeclaredField("nextId");
cf.setAccessible(true);
df.setAccessible(true);
bf.setAccessible(true);
net.minecraft.core.IdMapper<BlockState> blockData = Block.BLOCK_STATE_REGISTRY;
IdMapper<BlockState> blockData = Block.BLOCK_STATE_REGISTRY;
int b = bf.getInt(blockData);
Object2IntMap<BlockState> c = (Object2IntMap<BlockState>) cf.get(blockData);
List<BlockState> d = (List<BlockState>) df.get(blockData);
@@ -551,25 +565,34 @@ public class NMSBinding implements INMSBinding {
}
@Override
public boolean loadDatapack(File folder) {
public boolean registerDimension(String name, IrisDimension dimension) {
var registry = registry(Registries.DIMENSION_TYPE);
var baseLocation = switch (dimension.getEnvironment()) {
case NORMAL -> new ResourceLocation("minecraft", "overworld");
case NETHER -> new ResourceLocation("minecraft", "the_nether");
case THE_END -> new ResourceLocation("minecraft", "the_end");
case CUSTOM -> throw new IllegalArgumentException("Cannot register custom dimension");
};
var base = registry.getHolder(ResourceKey.create(Registries.DIMENSION_TYPE, baseLocation)).orElse(null);
if (base == null) return false;
var json = encode(DimensionType.CODEC, base).orElse(null);
if (json == null) return false;
var object = json.getAsJsonObject();
var height = dimension.getDimensionHeight();
object.addProperty("min_y", height.getMin());
object.addProperty("height", height.getMax() - height.getMin());
object.addProperty("logical_height", dimension.getLogicalHeight());
var value = decode(DimensionType.CODEC, object.toString()).map(Holder::value).orElse(null);
if (value == null) return false;
return register(Registries.DIMENSION_TYPE, new ResourceLocation("iris", name), value, true);
}
@Override
public boolean loadDatapack(File folder, boolean replace) {
var data = new File(folder, "iris/data");
if (!data.exists() || !data.isDirectory()) return false;
FilenameFilter jsonFilter = (dir, name) -> new File(dir, name).isFile() && name.toLowerCase().endsWith(".json");
var dimensionFolder = new File(data, "minecraft/dimension_type");
if (dimensionFolder.exists()) {
var files = dimensionFolder.listFiles(jsonFilter);
if (files != null) {
for (File file : files) {
try {
modifyDimension(file);
} catch (Throwable e) {
Iris.error("Unable to modify dimension!");
e.printStackTrace();
}
}
}
}
var files = data.listFiles((dir, name) -> new File(dir, name).isDirectory());
if (files == null) return false;
for (File file : files) {
@@ -578,8 +601,26 @@ public class NMSBinding implements INMSBinding {
var biomeFiles = biome.listFiles(jsonFilter);
if (biomeFiles == null) continue;
for (File biomeFile : biomeFiles) {
String json = null;
int tries = 10;
while (json == null && tries-- > 0) {
try {
json = IO.readAll(biomeFile);
} catch (IOException e) {
Iris.error("Failed to read biome " + file.getName() + ":" + biomeFile.getName() + " tries left: " + tries);
if (tries == 0) {
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {}
}
}
if (json == null) continue;
try {
registerBiome(file.getName(), biomeFile);
var value = decode(net.minecraft.world.level.biome.Biome.CODEC, json).map(Holder::value).orElse(null);
register(Registries.BIOME, from(file.getName(), biomeFile), value, replace);
} catch (Throwable e) {
Iris.error("Failed to register biome " + file.getName() + ":" + biomeFile.getName());
e.printStackTrace();
@@ -594,75 +635,82 @@ public class NMSBinding implements INMSBinding {
return new ResourceLocation(namespace, name.substring(0, name.lastIndexOf('.')));
}
private void registerBiome(String namespace, File file) throws Throwable {
var rawRegistry = registry().registry(Registries.BIOME).orElse(null);
var key = ResourceKey.create(Registries.BIOME, from(namespace, file));
if (!(rawRegistry instanceof MappedRegistry<net.minecraft.world.level.biome.Biome> registry))
throw new IllegalStateException("The Biome Registry is not a mapped Registry!");
if (registry.containsKey(key)) return;
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field holdersField = null;
boolean holders = false;
for (Field f : MappedRegistry.class.getDeclaredFields()) {
if (!f.getGenericType().getTypeName().startsWith("java.util.Map<T, "))
continue;
holdersField = f;
}
if (holdersField != null) {
holdersField.setAccessible(true);
holders = holdersField.get(registry) == null;
if (holders) holdersField.set(registry, new IdentityHashMap<>());
}
private <T> Optional<T> decode(Codec<T> codec, String json) {
return codec.decode(JsonOps.INSTANCE, GsonHelper.parse(json)).get().left().map(Pair::getFirst);
}
private <T> Optional<JsonElement> encode(Codec<T> codec, T value) {
return codec.encode(value, JsonOps.INSTANCE, new JsonObject()).result();
}
private <T> boolean register(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value, boolean replace) {
Preconditions.checkArgument(registryKey != null, "The registry cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var biome = net.minecraft.world.level.biome.Biome.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (biome == null)
throw new IllegalStateException("Failed to decode biome " + file.getName());
registry.createIntrusiveHolder(biome);
registry.register(key, biome, Lifecycle.stable());
} finally {
field.setBoolean(registry, frozen);
if (holders) {
holdersField.set(registry, null);
if (registry.containsKey(key)) {
if (!replace) return false;
return replace(registryKey, location, value);
}
Field field = getField(MappedRegistry.class, boolean.class);
field.setAccessible(true);
boolean frozen = field.getBoolean(registry);
field.setBoolean(registry, false);
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
try {
var holder = registry.register(key, value, Lifecycle.stable());
if (frozen) valueField.set(holder, value);
return true;
} finally {
field.setBoolean(registry, frozen);
}
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
@SuppressWarnings("unchecked")
private void modifyDimension(File file) throws Throwable {
var key = ResourceKey.create(Registries.DIMENSION_TYPE, from("minecraft", file));
var rawRegistry = registry().registry(Registries.DIMENSION_TYPE).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<DimensionType> registry))
throw new IllegalStateException("The Dimension Registry is not a mapped Registry!");
private <T> boolean replace(ResourceKey<Registry<T>> registryKey, ResourceLocation location, T value) {
Preconditions.checkArgument(registryKey != null, "The registryKey cannot be null!");
Preconditions.checkArgument(location != null, "The location cannot be null!");
Preconditions.checkArgument(value != null, "The value cannot be null!");
var registry = registry(registryKey);
var key = ResourceKey.create(registryKey, location);
try {
var holder = registry.getHolder(key).orElse(null);
if (holder == null) return false;
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<T>) toIdField.get(registry);
var byValue = (Map<T, Holder.Reference<T>>) byValueField.get(registry);
var lifecycles = (Map<T, Lifecycle>) lifecyclesField.get(registry);
var holder = registry.getHolder(key).orElseThrow(() -> new IllegalStateException("Unknown dimension type: " + key));
var oldValue = holder.value();
Field valueField = getField(Holder.Reference.class, "T");
valueField.setAccessible(true);
Field toIdField = getField(MappedRegistry.class, buildType(Reference2IntMap.class, "T"));
toIdField.setAccessible(true);
Field byValueField = getField(MappedRegistry.class, buildType(Map.class, "T", buildType(Holder.Reference.class, "T")));
byValueField.setAccessible(true);
Field lifecyclesField = getField(MappedRegistry.class, buildType(Map.class, "T", Lifecycle.class.getName()));
lifecyclesField.setAccessible(true);
var toId = (Reference2IntMap<DimensionType>) toIdField.get(registry);
var byValue = (Map<DimensionType, Holder.Reference<DimensionType>>) byValueField.get(registry);
var lifecycles = (Map<DimensionType, Lifecycle>) lifecyclesField.get(registry);
valueField.set(holder, value);
toId.put(value, toId.removeInt(oldValue));
byValue.put(value, byValue.remove(oldValue));
lifecycles.put(value, lifecycles.remove(oldValue));
return true;
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
var newValue = DimensionType.CODEC.decode(JsonOps.INSTANCE, GsonHelper.parse(IO.readAll(file)))
.get().left().map(Pair::getFirst).map(Holder::value).orElse(null);
if (newValue == null)
throw new IllegalArgumentException("Failed to parse dimension type " + key.location() + " from " + file);
valueField.set(holder, newValue);
toId.put(newValue, toId.removeInt(oldValue));
byValue.put(newValue, byValue.remove(oldValue));
lifecycles.put(newValue, lifecycles.remove(oldValue));
private <T> MappedRegistry<T> registry(ResourceKey<Registry<T>> registryKey) {
var rawRegistry = registry().registry(registryKey).orElse(null);
if (!(rawRegistry instanceof MappedRegistry<T> registry))
throw new IllegalStateException("The Registry is not a mapped Registry!");
return registry;
}
private static String buildType(Class<?> clazz, String... parameterTypes) {
@@ -718,6 +766,13 @@ public class NMSBinding implements INMSBinding {
.visit(Advice.to(WorldCreatorAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(String.class))))
.make()
.load(WorldCreator.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
new ByteBuddy()
.redefine(ServerLevel.class)
.visit(Advice.to(ServerLevelAdvice.class).on(ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(MinecraftServer.class, Executor.class, LevelStorageSource.LevelStorageAccess.class,
PrimaryLevelData.class, ResourceKey.class, LevelStem.class, ChunkProgressListener.class, boolean.class, long.class,
List.class, boolean.class, RandomSequences.class, World.Environment.class, ChunkGenerator.class, BiomeProvider.class))))
.make()
.load(ServerLevel.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Iris.info("Injected Bukkit Successfully!");
} catch (Exception e) {
Iris.info(C.RED + "Failed to Inject Bukkit!");
@@ -727,6 +782,21 @@ public class NMSBinding implements INMSBinding {
}
private static class ServerLevelAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) MinecraftServer server, @Advice.Argument(2) LevelStorageSource.LevelStorageAccess access, @Advice.Argument(4) ResourceKey<Level> key, @Advice.Argument(value = 5, readOnly = false) LevelStem levelStem) {
File iris = new File(access.levelDirectory.path().toFile(), "iris");
if (!iris.exists() && !key.location().getPath().startsWith("iris/")) return;
ResourceKey<DimensionType> typeKey = ResourceKey.create(Registries.DIMENSION_TYPE, new ResourceLocation("iris", key.location().getPath()));
RegistryAccess registryAccess = server.registryAccess();
Registry<DimensionType> registry = registryAccess.registry(Registries.DIMENSION_TYPE).orElse(null);
if (registry == null) throw new IllegalStateException("Unable to find registry for dimension type " + typeKey);
Holder<DimensionType> holder = registry.getHolder(typeKey).orElse(null);
if (holder == null) throw new IllegalStateException("Unable to find dimension type " + typeKey);
levelStem = new LevelStem(holder, levelStem.generator());
}
}
private static class WorldCreatorAdvice {
@Advice.OnMethodEnter
static void enter(@Advice.Argument(0) String name) {