Skip to content

Commit

Permalink
Port resourceloader to latest snapshot (FabricMC#6)
Browse files Browse the repository at this point in the history
* Port resourceloader to latest snapshot

* Port resourceloader to latest snapshot
  • Loading branch information
shartte authored Oct 20, 2022
1 parent 61a2483 commit fad617c
Show file tree
Hide file tree
Showing 27 changed files with 142 additions and 772 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import net.minecraft.network.packet.s2c.play.GameJoinS2CPacket;
import net.minecraft.network.packet.s2c.play.PlayerRespawnS2CPacket;
import net.minecraft.network.packet.s2c.play.SynchronizeTagsS2CPacket;
import net.minecraft.util.registry.DynamicRegistryManager;
import net.minecraft.world.chunk.WorldChunk;

import net.fabricmc.api.EnvType;
Expand All @@ -44,8 +43,6 @@
abstract class ClientPlayNetworkHandlerMixin {
@Shadow
private ClientWorld world;
@Shadow
private DynamicRegistryManager.Immutable registryManager;

@Inject(method = "onPlayerRespawn", at = @At(value = "NEW", target = "net/minecraft/client/world/ClientWorld"))
private void onPlayerRespawn(PlayerRespawnS2CPacket packet, CallbackInfo ci) {
Expand Down Expand Up @@ -102,6 +99,7 @@ private void onClearWorld(CallbackInfo ci) {
}
}

@SuppressWarnings("ConstantConditions")
@Inject(
method = "onSynchronizeTags",
at = @At(
Expand All @@ -111,6 +109,7 @@ private void onClearWorld(CallbackInfo ci) {
)
)
private void hookOnSynchronizeTags(SynchronizeTagsS2CPacket packet, CallbackInfo ci) {
CommonLifecycleEvents.TAGS_LOADED.invoker().onTagsLoaded(registryManager, true);
ClientPlayNetworkHandler self = (ClientPlayNetworkHandler) (Object) this;
CommonLifecycleEvents.TAGS_LOADED.invoker().onTagsLoaded(self.getRegistryManager(), true);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,53 +16,23 @@

package net.fabricmc.fabric.mixin.resource.loader.client;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import net.minecraft.resource.AbstractFileResourcePack;
import net.minecraft.resource.ResourcePack;
import net.minecraft.resource.ResourcePackProfile;
import net.minecraft.client.resource.ClientBuiltinResourcePackProvider;
import net.minecraft.resource.ResourceType;
import net.minecraft.resource.ResourcePackProfile;

import net.fabricmc.fabric.api.resource.ModResourcePack;
import net.fabricmc.fabric.impl.resource.loader.ModResourcePackCreator;
import net.fabricmc.fabric.impl.resource.loader.ModResourcePackUtil;
import net.fabricmc.fabric.impl.resource.loader.client.pack.ProgrammerArtResourcePack;

@Mixin(ClientBuiltinResourcePackProvider.class)
public class ClientBuiltinResourcePackProviderMixin {
@Inject(method = "register", at = @At("RETURN"))
private void addBuiltinResourcePacks(Consumer<ResourcePackProfile> consumer, ResourcePackProfile.Factory factory, CallbackInfo ci) {
private void addBuiltinResourcePacks(Consumer<ResourcePackProfile> consumer, CallbackInfo ci) {
// Register mod and built-in resource packs after the vanilla built-in resource packs are registered.
ModResourcePackCreator.CLIENT_RESOURCE_PACK_PROVIDER.register(consumer, factory);
}

// ClientBuiltinResourcePackProvider#method_25454 first lambda.
@Inject(method = "method_25457", at = @At("RETURN"), cancellable = true)
private static void onSupplyZipProgrammerArtPack(File file, CallbackInfoReturnable<ResourcePack> cir) {
AbstractFileResourcePack originalPack = (AbstractFileResourcePack) cir.getReturnValue();
cir.setReturnValue(new ProgrammerArtResourcePack(originalPack, getProgrammerArtModResourcePacks()));
}

// ClientBuiltinResourcePackProvider#method_25454 second lambda.
@Inject(method = "method_25456", at = @At("RETURN"), cancellable = true)
private static void onSupplyDirProgrammerArtPack(File file, CallbackInfoReturnable<ResourcePack> cir) {
AbstractFileResourcePack originalPack = (AbstractFileResourcePack) cir.getReturnValue();
cir.setReturnValue(new ProgrammerArtResourcePack(originalPack, getProgrammerArtModResourcePacks()));
}

private static List<ModResourcePack> getProgrammerArtModResourcePacks() {
List<ModResourcePack> packs = new ArrayList<>();
ModResourcePackUtil.appendModResourcePacks(packs, ResourceType.CLIENT_RESOURCES, "programmer_art");
return packs;
ModResourcePackCreator.CLIENT_RESOURCE_PACK_PROVIDER.register(consumer);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,8 @@
package net.fabricmc.fabric.mixin.resource.loader.client;

import java.io.File;
import java.util.concurrent.CompletableFuture;

import com.google.gson.JsonElement;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.DynamicOps;
import com.mojang.serialization.JsonOps;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
Expand All @@ -35,114 +27,51 @@
import org.spongepowered.asm.mixin.injection.ModifyArg;
import org.spongepowered.asm.mixin.injection.ModifyVariable;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

import net.minecraft.class_7712;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.world.CreateWorldScreen;
import net.minecraft.client.gui.screen.world.MoreOptionsDialog;
import net.minecraft.client.world.GeneratorOptionsHolder;
import net.minecraft.resource.DataPackSettings;
import net.minecraft.resource.ResourceManager;
import net.minecraft.resource.ResourcePackManager;
import net.minecraft.resource.ResourceType;
import net.minecraft.server.SaveLoading;
import net.minecraft.util.Util;
import net.minecraft.util.dynamic.RegistryOps;
import net.minecraft.util.registry.DynamicRegistryManager;
import net.minecraft.world.gen.GeneratorOptions;

import net.fabricmc.fabric.impl.resource.loader.ModResourcePackCreator;
import net.fabricmc.fabric.impl.resource.loader.ModResourcePackUtil;
import net.fabricmc.fabric.mixin.resource.loader.ResourcePackManagerAccessor;

@Mixin(CreateWorldScreen.class)
public abstract class CreateWorldScreenMixin extends Screen {
@Unique
private static DataPackSettings defaultDataPackSettings;
private static class_7712 defaultDataPackSettings;

@Shadow
private ResourcePackManager packManager;

@Shadow
@Final
private static Logger LOGGER;

@Shadow
@Final
public MoreOptionsDialog moreOptionsDialog;

@Shadow
protected DataPackSettings dataPackSettings;

@Shadow
private static SaveLoading.ServerConfig createServerConfig(ResourcePackManager resourcePackManager, DataPackSettings dataPackSettings) {
return null;
}

@Shadow
@Nullable
protected abstract Pair<File, ResourcePackManager> getScannedPack();

private CreateWorldScreenMixin() {
super(null);
}

@ModifyVariable(method = "create(Lnet/minecraft/client/MinecraftClient;Lnet/minecraft/client/gui/screen/Screen;)V",
at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screen/world/CreateWorldScreen;createServerConfig(Lnet/minecraft/resource/ResourcePackManager;Lnet/minecraft/resource/DataPackSettings;)Lnet/minecraft/server/SaveLoading$ServerConfig;"))
at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screen/world/CreateWorldScreen;createServerConfig(Lnet/minecraft/resource/ResourcePackManager;Lnet/minecraft/class_7712;)Lnet/minecraft/server/SaveLoading$ServerConfig;"))
private static ResourcePackManager onCreateResManagerInit(ResourcePackManager manager) {
// Add mod data packs to the initial res pack manager so they are active even if the user doesn't use custom data packs
((ResourcePackManagerAccessor) manager).getProviders().add(new ModResourcePackCreator(ResourceType.SERVER_DATA));
manager.providers.add(new ModResourcePackCreator(ResourceType.SERVER_DATA));
return manager;
}

@Redirect(method = "create(Lnet/minecraft/client/MinecraftClient;Lnet/minecraft/client/gui/screen/Screen;)V", at = @At(value = "FIELD", target = "Lnet/minecraft/resource/DataPackSettings;SAFE_MODE:Lnet/minecraft/resource/DataPackSettings;", ordinal = 0))
private static DataPackSettings replaceDefaultSettings() {
@Redirect(method = "create(Lnet/minecraft/client/MinecraftClient;Lnet/minecraft/client/gui/screen/Screen;)V", at = @At(value = "FIELD", target = "Lnet/minecraft/class_7712;field_40260:Lnet/minecraft/class_7712;", ordinal = 0))
private static class_7712 replaceDefaultSettings() {
return (defaultDataPackSettings = ModResourcePackUtil.createDefaultDataPackSettings());
}

@ModifyArg(method = "create(Lnet/minecraft/client/MinecraftClient;Lnet/minecraft/client/gui/screen/Screen;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screen/world/CreateWorldScreen;<init>(Lnet/minecraft/client/gui/screen/Screen;Lnet/minecraft/resource/DataPackSettings;Lnet/minecraft/client/gui/screen/world/MoreOptionsDialog;)V"), index = 1)
private static DataPackSettings useReplacedDefaultSettings(DataPackSettings dataPackSettings) {
@ModifyArg(method = "create(Lnet/minecraft/client/MinecraftClient;Lnet/minecraft/client/gui/screen/Screen;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screen/world/CreateWorldScreen;<init>(Lnet/minecraft/client/gui/screen/Screen;Lnet/minecraft/class_7712;Lnet/minecraft/client/gui/screen/world/MoreOptionsDialog;)V"), index = 1)
private static class_7712 useReplacedDefaultSettings(class_7712 dataPackSettings) {
return defaultDataPackSettings;
}

@Redirect(method = "method_41854", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/registry/DynamicRegistryManager$Mutable;toImmutable()Lnet/minecraft/util/registry/DynamicRegistryManager$Immutable;"))
private static DynamicRegistryManager.Immutable loadDynamicRegistry(DynamicRegistryManager.Mutable mutableRegistryManager, ResourceManager dataPackManager) {
// This loads the dynamic registry from the data pack
RegistryOps.ofLoaded(JsonOps.INSTANCE, mutableRegistryManager, dataPackManager);
return mutableRegistryManager.toImmutable();
}

/**
* Load the DynamicRegistryManager again to fix GeneratorOptions not having custom dimensions.
* Taken from {@link CreateWorldScreen#applyDataPacks(ResourcePackManager)}.
*/
@SuppressWarnings("JavadocReference")
@Inject(method = "startServer", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screen/world/CreateWorldScreen;clearDataPackTempDir()V"))
private void loadDatapackDimensions(CallbackInfo ci) {
CompletableFuture<Void> future = SaveLoading.load(createServerConfig(getScannedPack().getSecond(), dataPackSettings), (resourceManager, dataPackSettings1) -> {
GeneratorOptionsHolder holder = moreOptionsDialog.getGeneratorOptionsHolder();
DynamicRegistryManager.Mutable newDrm = DynamicRegistryManager.createAndLoad();
DynamicOps<JsonElement> heldOps = RegistryOps.of(JsonOps.INSTANCE, holder.dynamicRegistryManager());
DynamicOps<JsonElement> newOps = RegistryOps.ofLoaded(JsonOps.INSTANCE, newDrm, resourceManager);
DataResult<GeneratorOptions> result = GeneratorOptions.CODEC.encodeStart(heldOps, holder.generatorOptions())
.flatMap(json -> GeneratorOptions.CODEC.parse(newOps, json));
return Pair.of(result, newDrm.toImmutable());
}, (resourceManager, dataPackContents, drm, result) -> {
resourceManager.close();
GeneratorOptions options = result.getOrThrow(false, Util.addPrefix("Error parsing worldgen settings after loading data packs: ", LOGGER::error));
GeneratorOptionsHolder holder = new GeneratorOptionsHolder(options, result.lifecycle().add(drm.getRegistryLifecycle()), drm, dataPackContents);
((MoreOptionsDialogAccessor) moreOptionsDialog).callSetGeneratorOptionsHolder(holder);
return null;
}, Util.getMainWorkerExecutor(), client);

client.runTasks(future::isDone);
}

@Inject(method = "getScannedPack",
at = @At(value = "INVOKE", target = "Lnet/minecraft/resource/ResourcePackManager;scanPacks()V", shift = At.Shift.BEFORE))
private void onScanPacks(CallbackInfoReturnable<Pair<File, ResourcePackManager>> cir) {
// Allow to display built-in data packs in the data pack selection screen at world creation.
((ResourcePackManagerAccessor) this.packManager).getProviders().add(new ModResourcePackCreator(ResourceType.SERVER_DATA));
this.packManager.providers.add(new ModResourcePackCreator(ResourceType.SERVER_DATA));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ public BuiltinModResourcePackSource(String modId) {
this.modId = modId;
}

@Override
public boolean method_45279() {
return true;
}

@Override
public Text decorate(Text packName) {
return Text.translatable("pack.nameAndSource", packName, Text.translatable("pack.source.builtinMod", modId)).formatted(Formatting.GRAY);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

package net.fabricmc.fabric.impl.resource.loader;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
Expand All @@ -28,6 +27,7 @@

import net.minecraft.SharedConstants;
import net.minecraft.resource.AbstractFileResourcePack;
import net.minecraft.resource.InputSupplier;
import net.minecraft.resource.ResourceType;
import net.minecraft.resource.metadata.ResourceMetadataReader;

Expand All @@ -43,60 +43,33 @@ public FabricModResourcePack(ResourceType type, List<ModResourcePack> packs) {
}

@Override
public InputStream openRoot(String fileName) throws IOException {
public InputSupplier<InputStream> openRoot(String... pathSegments) {
String fileName = String.join("/", pathSegments);

if ("pack.mcmeta".equals(fileName)) {
String description = "Mod resources.";
String pack = String.format("{\"pack\":{\"pack_format\":" + type.getPackVersion(SharedConstants.getGameVersion()) + ",\"description\":\"%s\"}}", description);
return IOUtils.toInputStream(pack, Charsets.UTF_8);
return () -> IOUtils.toInputStream(pack, Charsets.UTF_8);
} else if ("pack.png".equals(fileName)) {
InputStream stream = FabricLoader.getInstance().getModContainer("fabric-resource-loader-v0")
return FabricLoader.getInstance().getModContainer("fabric-resource-loader-v0")
.flatMap(container -> container.getMetadata().getIconPath(512).map(container::getPath))
.filter(Files::exists)
.map(iconPath -> {
try {
return Files.newInputStream(iconPath);
} catch (IOException e) {
return null;
}
}).orElse(null);

if (stream != null) {
return stream;
}
.map(path -> (InputSupplier<InputStream>) (() -> Files.newInputStream(path)))
.orElse(null);
}

// ReloadableResourceManagerImpl gets away with FileNotFoundException.
throw new FileNotFoundException("\"" + fileName + "\" in Fabric mod resource pack");
return null;
}

@Override
public <T> @Nullable T parseMetadata(ResourceMetadataReader<T> metaReader) throws IOException {
try {
InputStream inputStream = this.openRoot("pack.mcmeta");
Throwable error = null;
T metadata;
InputSupplier<InputStream> inputSupplier = this.openRoot("pack.mcmeta");

try {
metadata = AbstractFileResourcePack.parseMetadata(metaReader, inputStream);
} catch (Throwable e) {
error = e;
throw e;
} finally {
if (inputStream != null) {
if (error != null) {
try {
inputStream.close();
} catch (Throwable e) {
error.addSuppressed(e);
}
} else {
inputStream.close();
}
}
if (inputSupplier != null) {
try (InputStream input = inputSupplier.get()) {
return AbstractFileResourcePack.parseMetadata(metaReader, input);
}

return metadata;
} catch (FileNotFoundException | RuntimeException e) {
} else {
return null;
}
}
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,4 @@ default ResourcePackSource getFabricPackSource() {
LoggerFactory.getLogger(FabricResource.class).error("Unknown Resource implementation {}, returning PACK_SOURCE_NONE as the source", getClass().getName());
return ResourcePackSource.PACK_SOURCE_NONE;
}

void setFabricPackSource(ResourcePackSource packSource);
}
Loading

0 comments on commit fad617c

Please sign in to comment.