[1.21.1] ModLoading cleanup and optimisations (#10052)

This commit is contained in:
Paint_Ninja authored and GitHub committed 2024-08-16 22:49:11 +01:00
1 parent f106ff0c21
commit 9714512c31
101 files changed
+837 -841

No files matched your search

@@ -141,7 +141,6 @@ import net.minecraftforge.common.ForgeConfig;
import net.minecraftforge.common.ForgeI18n;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.Event;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.IExtensionPoint;
import net.minecraftforge.fml.ModList;
@@ -202,7 +201,7 @@ public class ForgeHooksClient {
}
public static void clearGuiLayers(Minecraft minecraft) {
while(guiLayers.size() > 0)
while (!guiLayers.isEmpty())
popGuiLayerInternal(minecraft);
}
@@ -221,7 +220,7 @@ public class ForgeHooksClient {
}
public static void popGuiLayer(Minecraft minecraft) {
if (guiLayers.size() == 0) {
if (guiLayers.isEmpty()) {
minecraft.setScreen(null);
return;
}
@@ -310,7 +309,7 @@ public class ForgeHooksClient {
if (idx == -1)
return base + complex;
String name = complex.substring(idx + 1, complex.length());
String name = complex.substring(idx + 1);
if (idx > 1) {
String domain = complex.substring(0, idx);
return domain + ':' + base + name;
@@ -320,9 +319,7 @@ public class ForgeHooksClient {
}
public static float getFieldOfViewModifier(Player entity, float fovModifier) {
ComputeFovModifierEvent fovModifierEvent = new ComputeFovModifierEvent(entity, fovModifier);
MinecraftForge.EVENT_BUS.post(fovModifierEvent);
return fovModifierEvent.getNewFovModifier();
return MinecraftForge.EVENT_BUS.fire(new ComputeFovModifierEvent(entity, fovModifier)).getNewFovModifier();
}
/**
@@ -333,41 +330,52 @@ public class ForgeHooksClient {
//RenderingRegistry.registerBlockHandler(RenderBlockFluid.instance);
}
private static VersionChecker.Status getForgeVersionStatus() {
final class LazyInit {
private static final VersionChecker.Status INSTANCE = ForgeVersion.getStatus();
static {
forgeStatusLine = switch (INSTANCE) {
// case FAILED -> " Version check failed";
// case UP_TO_DATE -> "Forge up to date";
// case AHEAD -> "Using non-recommended Forge build, issues may arise.";
case OUTDATED, BETA_OUTDATED -> I18n.get("forge.update.newversion", ForgeVersion.getTarget());
default -> null;
};
}
private LazyInit() {}
}
return LazyInit.INSTANCE;
}
public static void renderMainMenu(TitleScreen gui, GuiGraphics graphics, Font font, int width, int height, int alpha) {
VersionChecker.Status status = ForgeVersion.getStatus();
VersionChecker.Status status = getForgeVersionStatus();
if (status == VersionChecker.Status.BETA || status == VersionChecker.Status.BETA_OUTDATED) {
// Render a warning at the top of the screen
Component line = Component.translatable("forge.update.beta.1", ChatFormatting.RED, ChatFormatting.RESET).withStyle(ChatFormatting.RED);
graphics.drawCenteredString(font, line, width / 2, 4 + (0 * (font.lineHeight + 1)), 0xFFFFFF | alpha);
graphics.drawCenteredString(font, line, width / 2, 4, 0xFFFFFF | alpha);
line = Component.translatable("forge.update.beta.2");
graphics.drawCenteredString(font, line, width / 2, 4 + (1 * (font.lineHeight + 1)), 0xFFFFFF | alpha);
graphics.drawCenteredString(font, line, width / 2, 4 + (font.lineHeight + 1), 0xFFFFFF | alpha);
}
forgeStatusLine = switch(status) {
// case FAILED -> " Version check failed";
// case UP_TO_DATE -> "Forge up to date";
// case AHEAD -> "Using non-recommended Forge build, issues may arise.";
case OUTDATED, BETA_OUTDATED -> I18n.get("forge.update.newversion", ForgeVersion.getTarget());
default -> null;
};
}
public static String forgeStatusLine;
@Nullable
public static SoundInstance playSound(SoundEngine manager, SoundInstance sound) {
PlaySoundEvent e = new PlaySoundEvent(manager, sound);
MinecraftForge.EVENT_BUS.post(e);
return e.getSound();
return MinecraftForge.EVENT_BUS.fire(new PlaySoundEvent(manager, sound)).getSound();
}
public static void drawScreen(Screen screen, GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
guiGraphics.pose().pushPose();
guiLayers.forEach(layer -> {
for (Screen layer : guiLayers) {
// Prevent the background layers from thinking the mouse is over their controls and showing them as highlighted.
drawScreenInternal(layer, guiGraphics, Integer.MAX_VALUE, Integer.MAX_VALUE, partialTick);
guiGraphics.pose().translate(0, 0, 10000);
});
}
drawScreenInternal(screen, guiGraphics, mouseX, mouseY, partialTick);
guiGraphics.pose().popPose();
}
@@ -535,8 +543,7 @@ public class ForgeHooksClient {
public static void onClientChangeGameType(PlayerInfo info, GameType currentGameMode, GameType newGameMode) {
if (currentGameMode != newGameMode) {
ClientPlayerChangeGameTypeEvent evt = new ClientPlayerChangeGameTypeEvent(info, currentGameMode, newGameMode);
MinecraftForge.EVENT_BUS.post(evt);
MinecraftForge.EVENT_BUS.post(new ClientPlayerChangeGameTypeEvent(info, currentGameMode, newGameMode));
}
}
@@ -563,8 +570,7 @@ public class ForgeHooksClient {
}
public static void onRecipesUpdated(RecipeManager mgr) {
Event event = new RecipesUpdatedEvent(mgr);
MinecraftForge.EVENT_BUS.post(event);
MinecraftForge.EVENT_BUS.post(new RecipesUpdatedEvent(mgr));
}
public static void onKeyInput(int key, int scanCode, int action, int modifiers) {
@@ -589,7 +595,7 @@ public class ForgeHooksClient {
public static SpriteContents loadSpriteContents(ResourceLocation name, Resource resource, FrameSize frameSize, NativeImage image, ResourceMetadata animationMeta) {
try {
ForgeTextureMetadata forgeMeta = ForgeTextureMetadata.forResource(resource);
return forgeMeta.getLoader() == null ? null : forgeMeta.getLoader().loadContents(name, resource, frameSize, image, animationMeta, forgeMeta);
return forgeMeta.loader() == null ? null : forgeMeta.loader().loadContents(name, resource, frameSize, image, animationMeta, forgeMeta);
} catch (IOException e) {
LOGGER.error("Unable to get Forge metadata for {}, falling back to vanilla loading", name);
e.printStackTrace();
@@ -599,10 +605,10 @@ public class ForgeHooksClient {
@Nullable
public static TextureAtlasSprite loadTextureAtlasSprite(ResourceLocation atlasName, SpriteContents contents, int atlasWidth, int atlasHeight, int spriteX, int spriteY, int mipmapLevel) {
if (contents.forgeMeta == null || contents.forgeMeta.getLoader() == null)
if (contents.forgeMeta == null || contents.forgeMeta.loader() == null)
return null;
return contents.forgeMeta.getLoader().makeSprite(atlasName, contents, atlasWidth, atlasHeight, spriteX, spriteY, mipmapLevel);
return contents.forgeMeta.loader().makeSprite(atlasName, contents, atlasWidth, atlasHeight, spriteX, spriteY, mipmapLevel);
}
private static final Map<ModelLayerLocation, Supplier<LayerDefinition>> layerDefinitions = new HashMap<>();
@@ -612,7 +618,9 @@ public class ForgeHooksClient {
}
public static void loadLayerDefinitions(ImmutableMap.Builder<ModelLayerLocation, LayerDefinition> builder) {
layerDefinitions.forEach((k, v) -> builder.put(k, v.get()));
for (var entry : layerDefinitions.entrySet()) {
builder.put(entry.getKey(), entry.getValue().get());
}
}
public static void processForgeListPingData(ServerStatus packet, ServerData target) {
@@ -716,7 +724,7 @@ public class ForgeHooksClient {
}
private static Connection getClientConnection() {
return Minecraft.getInstance().getConnection()!=null ? Minecraft.getInstance().getConnection().getConnection() : null;
return Minecraft.getInstance().getConnection() != null ? Minecraft.getInstance().getConnection().getConnection() : null;
}
public static void handleClientLevelClosing(ClientLevel level) {
@@ -825,8 +833,7 @@ public class ForgeHooksClient {
Font font = getTooltipFont(stack, fallbackFont);
var event = new RenderTooltipEvent.GatherComponents(stack, screenWidth, screenHeight, elements, -1);
MinecraftForge.EVENT_BUS.post(event);
if (event.isCanceled()) return List.of();
if (MinecraftForge.EVENT_BUS.post(event)) return List.of();
// text wrapping
int tooltipTextWidth = event.getTooltipElements().stream()
@@ -891,9 +898,7 @@ public class ForgeHooksClient {
}
public static ScreenEvent.RenderInventoryMobEffects onScreenPotionSize(Screen screen, int availableSpace, boolean compact, int horizontalOffset) {
final ScreenEvent.RenderInventoryMobEffects event = new ScreenEvent.RenderInventoryMobEffects(screen, availableSpace, compact, horizontalOffset);
MinecraftForge.EVENT_BUS.post(event);
return event;
return MinecraftForge.EVENT_BUS.fire(new ScreenEvent.RenderInventoryMobEffects(screen, availableSpace, compact, horizontalOffset));
}
public static boolean onToastAdd(Toast toast) {
@@ -45,7 +45,10 @@ public final class ItemDecoratorHandler
var event = new RegisterItemDecorationsEvent(decorators);
ModLoader.get().postEventWrapContainerInModOrder(event);
var builder = new ImmutableMap.Builder<Item, ItemDecoratorHandler>();
decorators.forEach((item, itemDecorators) -> builder.put(item, new ItemDecoratorHandler(itemDecorators)));
for (var entry : decorators.entrySet()) {
Item item = entry.getKey();
builder.put(item, new ItemDecoratorHandler(entry.getValue()));
}
DECORATOR_LOOKUP = builder.build();
}
@@ -7,6 +7,7 @@ package net.minecraftforge.client;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
@@ -31,7 +32,12 @@ public final class PresetEditorManager
Map<ResourceKey<WorldPreset>, PresetEditor> gatheredEditors = new HashMap<>();
// Vanilla's map uses Optional<ResourceKey>s as its keys.
// As far as we can tell there's no good reason for this, so we'll just use regular keys.
PresetEditor.EDITORS.forEach((k, v) -> k.ifPresent(key -> gatheredEditors.put(key, v)));
for (var entry : PresetEditor.EDITORS.entrySet()) {
var key = entry.getKey().orElse(null);
if (key != null) {
gatheredEditors.put(key, entry.getValue());
}
}
// Gather mods' entries
RegisterPresetEditorsEvent event = new RegisterPresetEditorsEvent(gatheredEditors);
@@ -5,8 +5,6 @@
package net.minecraftforge.client;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import net.minecraft.client.RecipeBookCategories;
import net.minecraft.world.inventory.RecipeBookType;
import net.minecraft.world.item.crafting.Recipe;
@@ -57,14 +55,14 @@ public final class RecipeBookManager {
@ApiStatus.Internal
public static void init() {
// The ImmutableMap is the patched out value of AGGREGATE_CATEGORIES
var aggregateCategories = new HashMap<>(ImmutableMap.of(
RecipeBookCategories.CRAFTING_SEARCH, ImmutableList.of(RecipeBookCategories.CRAFTING_EQUIPMENT, RecipeBookCategories.CRAFTING_BUILDING_BLOCKS, RecipeBookCategories.CRAFTING_MISC, RecipeBookCategories.CRAFTING_REDSTONE),
RecipeBookCategories.FURNACE_SEARCH, ImmutableList.of(RecipeBookCategories.FURNACE_FOOD, RecipeBookCategories.FURNACE_BLOCKS, RecipeBookCategories.FURNACE_MISC),
RecipeBookCategories.BLAST_FURNACE_SEARCH, ImmutableList.of(RecipeBookCategories.BLAST_FURNACE_BLOCKS, RecipeBookCategories.BLAST_FURNACE_MISC),
RecipeBookCategories.SMOKER_SEARCH, ImmutableList.of(RecipeBookCategories.SMOKER_FOOD)
var aggregateCategories = new HashMap<>(Map.of(
RecipeBookCategories.CRAFTING_SEARCH, List.of(RecipeBookCategories.CRAFTING_EQUIPMENT, RecipeBookCategories.CRAFTING_BUILDING_BLOCKS, RecipeBookCategories.CRAFTING_MISC, RecipeBookCategories.CRAFTING_REDSTONE),
RecipeBookCategories.FURNACE_SEARCH, List.of(RecipeBookCategories.FURNACE_FOOD, RecipeBookCategories.FURNACE_BLOCKS, RecipeBookCategories.FURNACE_MISC),
RecipeBookCategories.BLAST_FURNACE_SEARCH, List.of(RecipeBookCategories.BLAST_FURNACE_BLOCKS, RecipeBookCategories.BLAST_FURNACE_MISC),
RecipeBookCategories.SMOKER_SEARCH, List.of(RecipeBookCategories.SMOKER_FOOD)
));
var typeCategories = new HashMap<RecipeBookType, ImmutableList<RecipeBookCategories>>();
var typeCategories = new HashMap<RecipeBookType, List<RecipeBookCategories>>();
var recipeCategoryLookups = new HashMap<RecipeType<?>, Function<Recipe<?>, RecipeBookCategories>>();
var event = new RegisterRecipeBookCategoriesEvent(aggregateCategories, typeCategories, recipeCategoryLookups);
ModLoader.get().postEventWrapContainerInModOrder(event);
@@ -78,8 +78,7 @@ public final class ForgeEventFactoryClient {
* @return the event object passed in and possibly modified by listeners
*/
private static <E extends Event> E fire(E e) {
post(e);
return e;
return MinecraftForge.EVENT_BUS.fire(e);
}
/**
@@ -5,7 +5,6 @@
package net.minecraftforge.client.event;
import com.google.common.collect.ImmutableList;
import net.minecraft.client.RecipeBookCategories;
import net.minecraft.world.inventory.RecipeBookType;
import net.minecraft.world.item.crafting.Recipe;
@@ -31,14 +30,14 @@ import java.util.function.Function;
*/
public class RegisterRecipeBookCategoriesEvent extends Event implements IModBusEvent
{
private final Map<RecipeBookCategories, ImmutableList<RecipeBookCategories>> aggregateCategories;
private final Map<RecipeBookType, ImmutableList<RecipeBookCategories>> typeCategories;
private final Map<RecipeBookCategories, List<RecipeBookCategories>> aggregateCategories;
private final Map<RecipeBookType, List<RecipeBookCategories>> typeCategories;
private final Map<RecipeType<?>, Function<Recipe<?>, RecipeBookCategories>> recipeCategoryLookups;
@ApiStatus.Internal
public RegisterRecipeBookCategoriesEvent(
Map<RecipeBookCategories, ImmutableList<RecipeBookCategories>> aggregateCategories,
Map<RecipeBookType, ImmutableList<RecipeBookCategories>> typeCategories,
Map<RecipeBookCategories, List<RecipeBookCategories>> aggregateCategories,
Map<RecipeBookType, List<RecipeBookCategories>> typeCategories,
Map<RecipeType<?>, Function<Recipe<?>, RecipeBookCategories>> recipeCategoryLookups)
{
this.aggregateCategories = aggregateCategories;
@@ -51,7 +50,7 @@ public class RegisterRecipeBookCategoriesEvent extends Event implements IModBusE
*/
public void registerAggregateCategory(RecipeBookCategories category, List<RecipeBookCategories> others)
{
aggregateCategories.put(category, ImmutableList.copyOf(others));
aggregateCategories.put(category, List.copyOf(others));
}
/**
@@ -59,7 +58,7 @@ public class RegisterRecipeBookCategoriesEvent extends Event implements IModBusE
*/
public void registerBookCategories(RecipeBookType type, List<RecipeBookCategories> categories)
{
typeCategories.put(type, ImmutableList.copyOf(categories));
typeCategories.put(type, List.copyOf(categories));
}
/**
@@ -21,60 +21,44 @@ import java.util.Optional;
/**
* The "forge" section of texture metadata files (.mcmeta). Currently used only to specify custom
* TextureAtlasSprite loaders.
*
* @see ITextureAtlasSpriteLoader
*/
public final class ForgeTextureMetadata
{
public record ForgeTextureMetadata(@Nullable ITextureAtlasSpriteLoader loader) {
public static final ForgeTextureMetadata EMPTY = new ForgeTextureMetadata(null);
public static final MetadataSectionSerializer<ForgeTextureMetadata> SERIALIZER = new Serializer();
public static ForgeTextureMetadata forResource(Resource resource) throws IOException {
Optional<ForgeTextureMetadata> metadata = resource.metadata().getSection(SERIALIZER);
return metadata.isEmpty() ? EMPTY : metadata.get();
return metadata.orElse(EMPTY);
}
@Nullable
private final ITextureAtlasSpriteLoader loader;
public ForgeTextureMetadata(@Nullable ITextureAtlasSpriteLoader loader)
{
this.loader = loader;
}
@Nullable
public ITextureAtlasSpriteLoader getLoader()
{
public ITextureAtlasSpriteLoader getLoader() {
return loader;
}
private static final class Serializer implements MetadataSectionSerializer<ForgeTextureMetadata>
{
private static final class Serializer implements MetadataSectionSerializer<ForgeTextureMetadata> {
@Override
@NotNull
public String getMetadataSectionName()
{
public String getMetadataSectionName() {
return "forge";
}
@Override
@NotNull
public ForgeTextureMetadata fromJson(JsonObject json)
{
public ForgeTextureMetadata fromJson(JsonObject json) {
@Nullable
ITextureAtlasSpriteLoader loader;
if (json.has("loader"))
{
if (json.has("loader")) {
ResourceLocation loaderName = ResourceLocation.parse(GsonHelper.getAsString(json, "loader"));
loader = TextureAtlasSpriteLoaderManager.get(loaderName);
if (loader == null)
{
if (loader == null) {
throw new JsonSyntaxException("Unknown TextureAtlasSpriteLoader " + loaderName);
}
}
else
{
} else {
loader = null;
}
return new ForgeTextureMetadata(loader);
@@ -13,35 +13,31 @@ import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
/**
* Manager for {@link ITextureAtlasSpriteLoader} instances.
* <p>
* Provides a lookup.
*/
public final class TextureAtlasSpriteLoaderManager
{
private static ImmutableMap<ResourceLocation, ITextureAtlasSpriteLoader> LOADERS;
public final class TextureAtlasSpriteLoaderManager {
private static Map<ResourceLocation, ITextureAtlasSpriteLoader> LOADERS;
/**
* Finds the loader with the given name, or null if none is registered.
*/
@Nullable
public static ITextureAtlasSpriteLoader get(ResourceLocation name)
{
public static ITextureAtlasSpriteLoader get(ResourceLocation name) {
return LOADERS.get(name);
}
@ApiStatus.Internal
public static void init()
{
public static void init() {
var loaders = new HashMap<ResourceLocation, ITextureAtlasSpriteLoader>();
var event = new RegisterTextureAtlasSpriteLoadersEvent(loaders);
ModLoader.get().postEventWrapContainerInModOrder(event);
LOADERS = ImmutableMap.copyOf(loaders);
}
private TextureAtlasSpriteLoaderManager()
{
}
private TextureAtlasSpriteLoaderManager() {}
}